code stringlengths 2 1.05M |
|---|
console.log("loaded");
var start1 = function() {
document.getElementById('spotify1').style.display = "block";
document.getElementById('whatis').style.display = "none"
}
var start2 = function() {
document.getElementById('spotify1').style.display = "none";
document.getElementById('googlemaps').style.display = "block"
}
var mainform = function() {
document.getElementById('googlemaps').style.display = "none";
document.getElementById('mainform').style.display = "block"
}
var submit = function() {
document.getElementById('mainform').style.display = "none";
document.getElementById('thanks').style.display = "block"
}
|
import React from 'react';
import {Link} from 'react-router';
const DeliveryOption = React.createClass({
render() {
const additionalCost = this.props.option.additional_price;
return (
<option value={this.props.option.id} className="deoptionvery-option">
{this.props.option.name }{additionalCost > 0 ? ' | + £'+ parseFloat(this.props.option.additional_price).toFixed(2) : ''}
</option>
);
}
});
export default DeliveryOption; |
import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducers'
import audioDecode from '../middlewares/audioDecode'
export default (initialState = {}) => {
// ======================================================
// Middleware Configuration
// ======================================================
const middleware = [thunk, audioDecode]
// ======================================================
// Store Enhancers
// ======================================================
const enhancers = []
let composeEnhancers = compose
if (__DEV__) {
const composeWithDevToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
if (typeof composeWithDevToolsExtension === 'function') {
composeEnhancers = composeWithDevToolsExtension
}
}
// ======================================================
// Store Instantiation and HMR Setup
// ======================================================
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware(...middleware),
...enhancers
)
)
store.asyncReducers = {}
if (module.hot) {
module.hot.accept('./reducers', () => {
const reducers = require('./reducers').default
store.replaceReducer(reducers(store.asyncReducers))
})
}
return store
}
|
let Connection = require('./Connection');
let Request = require('tedious').Request;
let Q = require('q');
let _ = require('lodash');
let TriggerUtil = require('./TriggerUtil');
function createQuery(dataplan) {
let query = '';
dataplan.reverse().forEach(table => {
if (_.contains(TriggerUtil.getTablesWithTriggers(), table.tableName)) {
query += `DISABLE TRIGGER ALL ON ${table.tableName};
DELETE FROM ${table.tableName};
ENABLE TRIGGER ALL ON ${table.tableName};\n`;
} else {
query += `DELETE FROM ${table.tableName};\n`;
}
});
return query;
}
function runQuery(client, query) {
let deferred = new Q.defer();
let request = new Request(query, (err, rowCount) => {
if (err) {
deferred.reject(err);
}
deferred.resolve('data removed');
});
client.execSqlBatch(request);
return deferred.promise;
}
class Deleter {
constructor(config) {
this.config = config;
}
deleteRecords() {
return TriggerUtil.loadTablesWithTriggers(this.config)
.then(() => {
let query = createQuery(this.config.dataplan);
let connection = new Connection(this.config);
return connection.getConnection()
.then(client => {
return runQuery(client, query);
});
});
}
}
module.exports = Deleter;
|
// @flow
import React from 'react'
import ImportShapefile from '../import-shapefile'
import {mockWithProvider} from '../../utils/mock-data'
describe('Component > ImportShapefile', () => {
it('renders correctly', () => {
const props = {
close: jest.fn(),
createModifications: jest.fn(),
variants: [],
projectId: '1'
}
// mount component
const {snapshot} = mockWithProvider(<ImportShapefile {...props} />)
expect(snapshot()).toMatchSnapshot()
const noCalls = ['close', 'createModifications']
noCalls.forEach(fn => {
expect(props[fn]).not.toBeCalled()
})
})
})
|
/**
* @jsx React.DOM
*/
/* not used but thats how you can use touch events
* */
//React.initializeTouchEvents(true);
/* not used but thats how you can use animation and other transition goodies
* */
//var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
/**
* we will use yes for true
* we will use no for false
*
* React has some built ins that rely on state being true/false like classSet()
* and these will not work with yes/no but can easily be modified / reproduced
*
* this single app uses the yes/no var so if you want you can switch back to true/false
*
* */
var yes = 'yes', no = 'no';
//var yes = true, no = false;
var Routes = ReactRouter.Routes,
Link = ReactRouter.Link,
Route = ReactRouter.Route,
NotFoundRoute = ReactRouter.NotFoundRoute,
DefaultRoute = ReactRouter.DefaultRoute;
/* bootstrap components
* */
var Flash = ReactBootstrap.Alert;
var Btn = ReactBootstrap.Button;
var Modal = ReactBootstrap.Modal;
/* create flash message
* */
var SnowpiFlash = React.createClass({displayName: 'SnowpiFlash',
getInitialState: function() {
return {
isVisible: true
};
},
getDefaultProps: function() {
return ({showclass:'info'});
},
render: function() {
if(!this.state.isVisible)
return null;
var message = this.props.children;
return (
Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash},
React.DOM.p(null, message)
)
);
},
dismissFlash: function() {
this.setState({isVisible: false});
}
});
/* my little man component
* simple example
* */
var SnowpiMan = React.createClass({displayName: 'SnowpiMan',
getDefaultProps: function() {
return ({divstyle:{float:'right',}});
},
render: function() {
return this.transferPropsTo(
React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}})
);
}
});
var UI = React.createClass({displayName: 'UI',
getInitialState: function() {
var now = new Date();
/**
* initialize the app
* the plan is to keep only active references in root state.
* we should use props for the fill outs
* */
return {};
},
componentWillReceiveProps: function() {
/**
* should be a mimic of initial
*
* */
//this.setState({response:no});
return false;
},
changeTheme: function() {
},
render: function() {
return (
React.DOM.div({id: "snowpi-wrapper"},
React.DOM.div({id: "snowpi-body"},
React.DOM.div({id: "walletbar", className: "affix"},
React.DOM.div({className: "wallet"},
React.DOM.div({className: "button-group"},
Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name),
React.DOM.ul({className: "dropdown-menu", role: "menu"},
React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a(null, React.DOM.link({to: ""}, snowtext.menu.plus.name))),
React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a(null, React.DOM.link({to: "overview"}, snowtext.menu.list.name))),
React.DOM.li({className: "nav-item-receive"}, React.DOM.a(null, React.DOM.link({to: "receive"}, snowtext.menu.receive.name))),
React.DOM.li({className: "divider"}),
React.DOM.li({className: "nav-item-snowcat"}, React.DOM.link({to: ""})),
React.DOM.li({className: "divider"}),
React.DOM.li(null,
React.DOM.div(null,
React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})),
React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.link({to: "inq"}, React.DOM.span({className: "nav-item-inq"}))),
React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))),
React.DOM.div({className: "clearfix"})
)
)
)
)
)
)
),
/* this is the important part */
this.props.activeRouteHandler(null)
)
);
}
});
var routes1 = (
Routes({location: "history"},
Route({path: "/react", handler: UI}
),
Route({path: "/", handler: UI}
),
Route({path: "", handler: UI}
),
NotFoundRoute({handler: UI})
)
);
//React.renderComponent(routes, document.getElementById('snowcoins-react'));
var App = React.createClass({displayName: 'App',
render: function() {
return (
React.DOM.div(null,
React.DOM.header(null,
React.DOM.ul(null,
React.DOM.li(null, Link({to: "app"}, "Dashboard")),
React.DOM.li(null, Link({to: "inbox"}, "Inbox")),
React.DOM.li(null, Link({to: "calendar"}, "Calendar"))
),
"Logged in as Joe"
),
/* this is the important part */
this.props.activeRouteHandler(null)
)
);
}
});
var routes = (
Routes({location: "history"},
Route({name: "app", path: "/react", handler: App}
)
)
);
React.renderComponent(routes, document.body);
|
// ----------------------------------------------------------
// ----- Site
// ----------------------------------------------------------
class C_Site {
constructor(json) {
this.id = -1;
this.Name = "";
this.Slug = "";
this.Street = "";
this.City = "";
this.State = "TX";
this.Zip = "";
this.Latitude = 29.4104978;
this.Longitude = -98.5011676;
this.SiteCoordinatorIds = [];
this.SiteCoordinatorNames = [];
this.SiteCalendar = [];
this.SiteType = "Fixed";
this._WorkItems = [];
this.SiteCapabilities = [];
if (json !== null) {
if ("id" in json)
this.id = parseInt(json.id);
if ("name" in json)
this.Name = json.name;
if ("slug" in json)
this.Slug = json.slug;
if ("street" in json)
this.Street = json.street;
if ("city" in json)
this.City = json.city;
if ("state" in json)
this.State = json.state;
if ("zip" in json)
this.Zip = json.zip;
if ("latitude" in json)
this.Latitude = json.latitude;
if ("longitude" in json)
this.Longitude = json.longitude;
if ("sitecoordinatorids" in json)
this.SiteCoordinatorIds = json.sitecoordinatorids;
if ("sitecoordinatornames" in json)
this.SiteCoordinatorNames = json.sitecoordinatornames;
if ("calendar_overrides" in json) {
let cals = json.calendar_overrides;
this.SiteCalendar = [];
for (let ix = 0; ix !== cals.length; ix++) {
let ce = new C_CalendarEntry(cals[ix]);
this.SiteCalendar.push(ce);
}
}
this.SiteType = "Fixed";
if ("site_features" in json) {
this.SiteCapabilities = [];
for(let ix = 0; ix !== json.site_features.length; ix++) {
let sf = json.site_features[ix];
if (sf.toLowerCase() === "mobile")
this.SiteType = "Mobile";
else
this.SiteCapabilities.push(sf);
}
}
// this.SiteCapabilities = json.site_features;
// if ("sitetype" in json)
// this.SiteType = json.sitetype;
if ("worklog" in json) {
let items = json.worklog;
this._WorkItems = [];
for (let ix = 0; ix !== items.length; ix++) {
let item = items[ix];
let nwi = new C_WorkLog(item);
this._WorkItems.push(nwi);
}
}
}
}
ToJson() {
return {
"id": this.id,
"name": this.Name,
"slug": this.Slug,
"street": this.Street,
"city": this.City,
"state": this.State,
"zip": this.Zip,
"latitude": this.Latitude,
"longitude": this.Longitude,
"sitecoordinatorids": this.SiteCoordinatorIds,
"sitecoordinatornames": this.SiteCoordinatorNames,
"calendar_overrides": this.SiteCalendar,
"site_features": this.SiteCapabilities,
"sitetype": this.SiteType,
"worklog": this._WorkItems
};
}
ToJsonForBackend() {
return {
"name": this.Name,
"street": this.Street,
"city": this.City,
"state": this.State,
"zip": this.Zip,
"latitude": this.Latitude,
"longitude": this.Longitude,
"site_features": this.SiteCapabilities,
"sitetype": this.SiteType,
};
}
SiteHasFeature(feature) {
let res = false;
for(let fix = 0; fix !== this.SiteCapabilities.length; fix++)
{
let siteCapability = this.SiteCapabilities[fix];
if (siteCapability.toLowerCase() === feature.toLowerCase())
{
res = true;
break;
}
}
return res;
}
FindCalendarEntryForDate(date) {
let res = null;
for(let ix = 0; ix !== this.SiteCalendar.length; ix++) {
let ce = this.SiteCalendar[ix];
if (date.CompareTo(ce.Date) === 0) {
res = ce;
break;
}
}
return res;
}
}
// ----------------------------------------------------------
// ----- User
// ----------------------------------------------------------
class C_User {
constructor(json) {
this.id = -1;
this.Name = "";
this.Password = null;
this.Email = "";
this.Phone = "";
this.Certification = "none";
this.Roles = [];
this.SitesCoordinated = [];
this._WorkItems = [];
this.PreferedSites = [];
this.SubscribeMobile = false;
this.SubscribePrefered = false;
this.SubscribeEmailFeedback = false;
this.SubscribeEmailNewUser = false;
//this.Token = null;
let isUndefined = typeof json !== 'undefined';
if ((json !== null) && isUndefined) {
if ("id" in json)
this.id = parseInt(json.id);
if ("name" in json)
this.Name = json.name;
if ("email" in json)
this.Email = json.email;
if ("phone" in json)
this.Phone = json.phone;
if ("certification" in json)
this.Certification = json.certification;
if ("roles" in json)
this.Roles = json.roles;
if ("sites_coordinated" in json) {
let items = json.sites_coordinated;
this.SitesCoordinated = [];
for (let ix = 0; ix !== items.length; ix++) {
let item = items[ix];
let nsc = new C_SiteCoordinated(item);
this.SitesCoordinated.push(nsc);
}
}
if ("workitems" in json) {
let items = json.workitems;
this._WorkItems = [];
for (let ix = 0; ix !== items.length; ix++) {
let item = items[ix];
let nwi = new C_WorkLog(item);
this._WorkItems.push(nwi);
}
}
if ("preferredsites" in json)
this.PreferedSites = json.preferredsites;
if ("subscribemobile" in json)
this.SubscribeMobile = json.subscribemobile;
if ("subscribepreferred" in json)
this.SubscribePrefered = json.subscribepreferred;
if ("subscribeemailfeedback" in json)
this.SubscribeEmailFeedback = json.subscribeemailfeedback;
if ("subscribenemailnewuser" in json)
this.SubscribeEmailNewUser = json.subscribenemailnewuser;
}
}
ToJson() {
return {
"id": this.id,
"name": this.Name,
"password": this.Password,
"email": this.Email,
"phone": this.Phone,
"certification": this.Certification,
"roles": this.Roles,
"sites_coordinated": this.SitesCoordinated, // ---------------- !!!!!!!
"workitems": this._WorkItems,
"preferredsites": this.PreferedSites,
"subscribemobile": this.SubscribeMobile,
"subscribepreferred": this.SubscribePrefered,
"subscribeemailfeedback": this.SubscribeEmailFeedback,
"subscribenemailnewuser": this.SubscribeEmailNewUser
};
}
ToJsonForHeader() {
return {
"id": this.id,
"name": this.Name,
"password": this.Password,
"password_confirm": this.Password,
"email": this.Email,
"phone": this.Phone,
"certification": this.Certification,
"roles": this.Roles,
"preferredsites": this.PreferedSites,
"subscribemobile": this.SubscribeMobile,
"subscribepreferred": this.SubscribePrefered,
"subscribeemailfeedback": this.SubscribeEmailFeedback,
"subscribenemailnewuser": this.SubscribeEmailNewUser
};
}
HasAdmin() {
return this.Roles.includes("Admin");
}
HasSiteCoordinator() {
return this.Roles.includes("SiteCoordinator");
}
HasVolunteer() {
return this.Roles.includes("Volunteer");
}
HasMobile() {
return this.Roles.includes("Mobile");
}
}
// ----------------------------------------------------------
// SiteCoordinated
// ----------------------------------------------------------
class C_SiteCoordinated {
constructor(json) {
this.SiteId = -1;
this.SiteName = null;
this.SiteSlug = null;
if (json != null) {
if ("siteid" in json)
this.SiteId = parseInt(json.siteid);
if ("SiteId" in json)
this.SiteId = parseInt(json.SiteId);
if ("name" in json)
this.SiteName = json.name;
if ("SiteName" in json)
this.SiteName = json.SiteName;
if ("slug" in json)
this.SiteSlug = json.slug;
if ("SiteSlug" in json)
this.SiteSlug = json.SiteSlug;
}
}
ToJson() {
return {
"siteid" : this.SiteId.toString(),
"slug" : this.SiteSlug
};
}
static Create(siteid, sitename, siteslug) {
let sc = new C_SiteCoordinated(null);
sc.SiteId = siteid;
sc.SiteName = sitename;
sc.SiteSlug = siteslug;
return sc;
}
}
// ----------------------------------------------------------
// UserCredential
// ----------------------------------------------------------
class C_UserCredential {
constructor(json) {
if (json !== null) {
this.Name = json.name;
this.Email = json.email;
this.Password = json.password;
this.Role = json.role;
this.Mobile = json.mobile;
}
else {
this.Name = "";
this.Email = "";
this.Password = "";
this.Role = "client";
this.Mobile = false;
}
}
ToJson() {
return {
"name": this.Name,
"email": this.Email,
"password": this.Password,
"role": this.Role,
"mobile": this.Mobile
};
}
ImportUser(user) {
if (!(user instanceof C_User))
throw "Input type must be a C_User";
this.Name = user.Name;
this.Email = user.Email;
this.Password = user.Password;
if (user.HasAdmin())
this.Role = "Admin";
else if (user.HasSiteCoordinator())
this.Role = "SiteCoordinator";
else if (user.HasVolunteer())
this.Role = "Volunteer";
else
this.Role = "Client";
this.Mobile = user.HasMobile();
}
IsValidCredential() {
return ((this.Email !== null) && (this.Email.length > 0))
&& ((this.Password !== null) && (this.Password.length > 0))
&& (this.Role !== "Client");
}
HasAdmin() {
return this.Role.toLowerCase() === "admin";
}
HasSiteCoordinator() {
return this.Role.toLowerCase() === "sitecoordinator";
}
HasVolunteer() {
return this.Role.toLowerCase() === "volunteer";
}
HasMobile() {
return this.Mobile;
}
}
// ----------------------------------------------------------
// WorkLog
// ----------------------------------------------------------
class C_WorkLog {
constructor(json) {
this.id = -1;
this.Date = new C_YMD(0, 0, 0);
this.SiteId = -1;
this.UserId = -1;
this.Hours = 0;
this.Approved = false;
if (json !== null) {
if ("id" in json)
this.id = parseInt(json.id);
if ("date" in json)
this.Date = C_YMD.FromString(json.date);
if ("Date" in json)
this.Date = C_YMD.FromObject(json.Date);
if ("siteid" in json)
this.SiteId = parseInt(json.siteid);
if ("SiteId" in json)
this.SiteId = parseInt(json.SiteId);
if ("userid" in json)
this.UserId = parseInt(json.userid);
if ("UserId" in json)
this.UserId = parseInt(json.UserId);
if ("hours" in json)
this.Hours = parseFloat(json.hours);
if ("Hours" in json)
this.Hours = parseFloat(json.Hours);
if ("approved" in json)
this.Approved = json.approved === "true";
if ("Approved" in json)
this.Approved = json.Approved;
}
}
ToJson() {
return {
"id" : this.id.toString(),
"date" : this.Date.toString(),
"siteid" : this.SiteId.toString(),
"userid" : this.UserId.toString(),
"hours" : this.Hours.toString(),
"approved" : this.Approved ? "true" : "false"
};
}
// static FromWorkItem(wi) {
// return new C_WorkLog(
// {
// "date" : wi.Date.toString(),
// "siteid" : wi.SiteId.toString(),
// "userid" : wi.UserId.toString(),
// "hours" : wi.Hours.toString(),
// "approved" : wi.Approved.toString()
// });
// }
}
// ----------------------------------------------------------
// CalendarEntry
// ----------------------------------------------------------
class C_CalendarEntry {
constructor (json) {
this.id = -1;
this.SiteId = -1;
this.Date = C_YMD.Now();
this.SiteIsOpen = false;
this.OpenTime = new C_HMS(0, 0, 0);
this.CloseTime = new C_HMS(0, 0, 0);
if (json !== null) {
if ("id" in json)
this.id = parseInt(json.id);
if ("siteid" in json)
this.SiteId = parseInt(json.siteid);
if ("SiteId" in json)
this.SiteId = parseInt(json.SiteId);
if ("date" in json)
this.Date = C_YMD.FromString(json.date);
if ("Date" in json)
this.Date = C_YMD.FromObject(json.Date);
if ("is_closed" in json)
this.SiteIsOpen = json.is_closed === "false";
if ("SiteIsOpen" in json)
this.SiteIsOpen = json.SiteIsOpen;
if ("opentime" in json)
this.OpenTime = C_HMS.FromString(json.opentime);
if ("OpenTime" in json)
this.OpenTime = C_HMS.FromObject(json.OpenTime);
if ("closetime" in json)
this.CloseTime = C_HMS.FromString(json.closetime);
if ("CloseTime" in json)
this.CloseTime = C_HMS.FromObject(json.CloseTime);
}
}
ToJson() {
return {
"id": this.id,
"siteid": this.SiteId,
"date": this.Date.toString(),
"is_closed": !this.SiteIsOpen,
"opentime": this.OpenTime.toString(),
"closetime": this.CloseTime.toString()
};
}
}
// ----------------------------------------------------------
// Filter
// ----------------------------------------------------------
class C_Filter {
constructor (json) {
this.Dates = "all";
this.Mobile = false;
this.MFT = false;
this.DropOff = false;
this.InPerson = false;
this.Express = false;
this.PreferedSiteSlugs = [];
this.SelectedSiteSlug = "";
this.CalendarDate = C_YMD.Now();
this.SeasonFirstDate = C_YMD.Now();
this.SeasonLastDate = C_YMD.Now();
if (json !== null) {
if ("dates" in json)
this.Dates = json.dates;
if ("mobile" in json)
this.Mobile = json.mobile;
if ("mft" in json)
this.MFT = json.mft;
if ("dropoff" in json)
this.DropOff = json.dropoff;
if ("inperson" in json)
this.InPerson = json.inperson;
if ("express" in json)
this.Express = json.express;
if ("preferedsiteslugs" in json)
this.PreferedSiteSlugs = json.preferedsiteslugs;
if ("selectedsiteslug" in json)
this.SelectedSiteSlug = json.selectedsiteslug;
if ("calendardate" in json)
this.CalendarDate = C_YMD.FromString(json.calendardate);
if ("seasonfirstdate" in json)
this.SeasonFirstDate = C_YMD.FromString(json.seasonfirstdate);
if ("seasonlastdate" in json)
this.SeasonLastDate = C_YMD.FromString(json.seasonlastdate);
}
}
ToJson() {
return {
"dates": this.Dates,
"mobile": this.Mobile,
"mft": this.MFT,
"dropoff": this.DropOff,
"inperson": this.InPerson,
"express": this.Express,
"preferedsiteslugs" : this.PreferedSiteSlugs,
"selectedsiteslug" : this.SelectedSiteSlug,
"calendardate" : this.CalendarDate.toString(),
"seasonfirstdate" : this.SeasonFirstDate.toString(),
"seasonlastdate" : this.SeasonLastDate.toString()
};
}
AddPreferedSiteSlug(slug) {
if (!this.PreferedSiteSlugs.includes(slug))
this.PreferedSiteSlugs.push(slug);
}
RemovePreferedSiteSlug(slug) {
if (this.PreferedSiteSlugs.includes(slug)) {
let ix = this.PreferedSiteSlugs.indexOf(slug);
if (ix !== -1)
this.PreferedSiteSlugs.splice(ix, 1);
}
}
SiteMatchesFilter(site, user) {
let isAMobileSite = (site.SiteType.toLowerCase() === "mobile") || ((user !== null) && user.HasMobile());
let ok = true;
if (this.Mobile || this.MFT || this.DropOff || this.InPerson || this.Express)
{
const mftok = (this.MFT && site.SiteHasFeature("mft"));
const dropoffok = (this.DropOff && site.SiteHasFeature("dropoff"));
const inpersonok = (this.InPerson && site.SiteHasFeature("inperson"));
const expressok = (this.Express && site.SiteHasFeature("express"));
const mobileok = (this.Mobile && isAMobileSite);
ok = mftok || dropoffok || inpersonok || expressok || mobileok;
}
if (isAMobileSite && ((user == null) || (!user.HasMobile())))
ok = false;
return ok;
}
}
// ----------------------------------------------------------
// Notification
// ----------------------------------------------------------
class C_Notification {
constructor(json) {
this.id = -1;
this.Message = "";
this.Audience = "Volunteers";
this.Created = C_YMDhms.Now();
this.Updated = C_YMDhms.Now();
this.Sent = C_YMDhms.Now();
if (json !== null) {
if ("id" in json)
this.id = parseInt(json.id);
if ("message" in json)
this.Message = json.message;
if ("audience" in json)
this.Audience = json.audience;
if ("created_at" in json)
this.Created = C_YMDhms.FromString(json.created_at);
if ("updated_at" in json)
this.Updated = C_YMDhms.FromString(json.updated_at);
if ("sent" in json)
this.Sent = C_YMDhms.FromString(json.sent);
}
}
ToJson() {
return {
"id" : this.id.toString(),
"message" : this.Message,
"audience" : this.Audience,
"created_at" : this.Created.toString(),
"updated_at" : this.Updated.toString(),
"sent" : this.Sent.toString()
};
}
ToJsonForHeader() {
return {
"id" : this.id.toString(),
"message" : this.Message,
"audience" : this.Audience,
};
}
}
// ----------------------------------------------------------
// Suggestion
// ----------------------------------------------------------
class C_Suggestion {
constructor(json) {
this.id = -1;
this.UserId = -1;
this.Subject = "";
this.Text = "";
this.Created = C_YMDhms.Now();
this.Updated = C_YMDhms.Now();
this.Status = "Open";
this.FromPublic = false;
if (json !== null) {
if ("id" in json)
this.id = parseInt(json.id);
if ("user_id" in json)
this.UserId = parseInt(json.user_id);
if ("subject" in json)
this.Subject = json.subject;
if ("details" in json)
this.Text = json.details;
if ("created_at" in json)
this.Created = C_YMDhms.FromString(json.created_at);
if ("updated_at" in json)
this.Updated = C_YMDhms.FromString(json.updated_at);
if ("status" in json)
this.Status = json.status;
if ("from_public" in json)
this.FromPublic = json.from_public === "true";
}
}
ToJson() {
return {
"id" : this.id.toString(),
"user_id" : this.UserId.toString(),
"subject" : this.Subject,
"details" : this.Text,
"created_at" : this.Created.toString(),
"updated_at" : this.Updated.toString(),
"status" : this.Status,
"from_public" : this.FromPublic ? "true" : "false"
};
}
ToJsonFromHeader() {
return {
"id" : this.id.toString(),
"user_id" : this.UserId.toString(),
"subject" : this.Subject,
"details" : this.Text,
"from_public" : this.FromPublic ? "true" : "false"
};
}
}
// -------------------------- drop down manager ------------------------
// Sample invocation:
// let sitesOptions = {
// "choices": choices,
// "selitem" : selitem,
// "dropdownid" : "vitasa_dropdown_site",
// "buttonid" : "vitasa_button_selectsite"
// };
// sitesDropDown = new C_DropdownHelper(sitesOptions);
// sitesDropDown.SetHelper("sitesDropDown");
// sitesDropDown.CreateDropdown();
//
// input is array of
// - choices: array of { "text" : "human name name for the item", "item" : "computer name for the item" }
// - selitem: the "item" that is the default selected item
// - dropdownid: the id="" that specifies where to put the dropdown items; assumed to be in a <div>
// - buttonid: the id="" for teh button that initiates the dropdown; we will change the title
// >>> be sure to create this class in the global space, ie, without var, or let, or... <<<
class C_DropdownHelper {
constructor(options) {
this.DropDownSelectedItem = null;
this.Options = options;
}
// This is the name of this class, as a string, as it would be seen in the global
// space; the value is used in the onclick event handler to find this object
// and invoke the appropriate methods.
SetHelper(help) {
this.Helper = help;
}
CreateDropdown() {
let options = this.Options;
let helper = this.Helper;
this.DropDownSelectedItem = this.Options.selitem;
// remove any previous items
$("div#" + options.dropdownid)[0].innerHTML = '';
// populate the dropdown
this.Options.choices.forEach(function (c) {
let seltext = "";
if ((options.selitem !== null) && (options.selitem === c.item)) {
seltext = "active";
document.getElementById(options.buttonid).innerText = c.text;
}
const newRow = $("<span>");
let cols = '<a class="dropdown-item" href="#" ' +
'onclick="' + helper + '.DropdownItemSelected_Click(\'' + c.item + '\');" ' + seltext + '>' + c.text + '</a>';
newRow.append(cols);
$("div#" + options.dropdownid).append(newRow);
});
}
DropdownItemSelected_Click(item) {
let itemx = null;
for (let ix = 0; ix !== this.Options.choices.length; ix++) {
let cx = this.Options.choices[ix];
if (cx.item === item) {
itemx = cx;
break;
}
}
if (itemx !== null) {
document.getElementById(this.Options.buttonid).innerText = itemx.text;
this.DropDownSelectedItem = itemx.item;
}
}
}
// ----------------------------------------------------------
// YMD
// ----------------------------------------------------------
/**
*
*/
class C_YMD {
constructor (year, month, day) {
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day))
throw new Error("values must be int's and non-null");
this.Year = year;
this.Month = month;
this.Day = day;
}
static Now() {
let dnow = new Date();
let y = dnow.getFullYear();
let m = dnow.getMonth() + 1;
let d = dnow.getDate();
return new C_YMD(y, m, d);
}
AddDays(num) {
for(let ix = 0; ix !== num; ix++) {
this.Day++;
let xd = new Date(this.Year, this.Month, 0);
let daysInMonth = xd.getDate();
if (this.Day > daysInMonth) {
this.Day = 1;
this.Month++;
if (this.Month > 12) {
this.Month = 1;
this.Year++;
}
}
}
}
toString() {
if (!Number.isInteger(this.Year) || !Number.isInteger(this.Month) || !Number.isInteger(this.Day))
throw new Error("must be ints");
let y_s = this.Year.toString();
let m_s = this.Month.toString();
if (m_s.length === 1)
m_s = "0" + m_s;
let d_s = this.Day.toString();
if (d_s.length === 1)
d_s = "0" + d_s;
return y_s + "-" + m_s + "-" + d_s;
}
// returns a formated time using the provided format
// "yyyy" is replaced with 4 digit year, "yy" is replaced with last two digits of year
// "mm" is replaced with month number (1..12); "mmm" is replaced with month short name
// "dd" is replaced with day number (1..31)
// "dow" is replaced with name for the day of the week
// all other characters in the string are unchanged
toStringFormat(fmt) {
let res = fmt.toLowerCase();
if (res.includes("yyyy"))
res = res.replace("yyyy", this.Year.toString());
else if (res.includes("yy")) {
let ys = this.Year.toString();
ys = ys.substr(2, 2);
res = res.replace("yy", ys);
}
if (res.includes("mmm")) {
res = res.replace("mmm", MonthNames[this.Month - 1]);
}
else if (res.includes("mm"))
res = res.replace("mm", this.Month.toString());
if (res.includes("dd"))
res = res.replace("dd", this.Day.toString());
if (res.includes("dow")) {
let dow = this.DayOfWeek();
let down = DayOfWeekNames[dow];
res = res.replace("dow", down);
}
return res;
}
DayOfWeek() {
let xd = new Date(this.Year, this.Month - 1, this.Day);
return xd.getDay();
}
DaysInMonth() {
let xd = new Date(this.Year, this.Month, 0);
return xd.getDate();
}
// format: yyyy-mm-dd
static FromString(ymd) {
let ymd_split = ymd.split("-");
if (ymd_split.length !== 3)
throw new Error("invalid format");
let y_s = ymd_split[0];
let y = parseInt(y_s);
let m_s = ymd_split[1];
let m = parseInt(m_s);
let d_s = ymd_split[2];
let d = parseInt(d_s);
return new C_YMD(y, m, d);
}
// with members: Year, Month, Day
static FromObject(ymd) {
let y = ymd.Year;
let m = ymd.Month;
let d = ymd.Day;
return new C_YMD(y, m, d);
}
static FromYMD(year, month, day) {
return new C_YMD(year, month, day);
}
CompareTo(v2) {
let res = 1;
if ((this.Year === v2.Year) && (this.Month === v2.Month) && (this.Day === v2.Day))
res = 0;
else if ((this.Year < v2.Year)
|| ((this.Year === v2.Year) && (this.Month < v2.Month))
|| ((this.Year === v2.Year) && (this.Month === v2.Month) && (this.Day < v2.Day)))
res = -1;
return res;
}
}
// ----------------------------------------------------------
// HMS
// ----------------------------------------------------------
class C_HMS {
constructor (hour, minute, second) {
this.Hour = hour;
this.Minute = minute;
this.Second = second;
}
toString() {
let h = this.Hour.toString();
if (h.length === 1)
h = "0" + h;
let m = this.Minute.toString();
if (m.length === 1)
m = "0" + m;
let s = this.Second.toString();
if (s.length === 1)
s = "0" + s;
return h + ":" + m + ":" + s;
}
toStringFormat(fmt) {
let res = fmt.toLowerCase();
let ampm = "";
let ampmHour = this.Hour;
if (res.includes("p"))
{
if (ampmHour > 12) {
ampmHour = ampmHour - 12;
ampm = "pm";
if (ampmHour === 0) {
ampmHour = 12;
ampm = "am";
}
}
else if (ampmHour === 12)
ampm = "pm";
else
ampm = "am";
}
let s_ampmHour = ampmHour.toString();
if (ampmHour < 10)
s_ampmHour = " " + s_ampmHour;
let min_s = this.Minute.toString();
if (this.Minute < 9)
min_s = "0" + min_s;
let sec_s = this.Second.toString();
if (this.Second < 9)
sec_s = "0" + sec_s;
if (res.includes("hh"))
res = res.replace("hh", s_ampmHour);
if (res.includes("mm"))
res = res.replace("mm", min_s);
if (res.includes("ss"))
res = res.replace("ss", sec_s);
if (res.includes("p"))
res = res.replace("p", ampm);
return res;
}
// assumed format is "hh:mm:ss"; each may be 1 or 2 digits, must have h and m
static FromString(hms) {
let s = 0;
let hms_split = hms.split(":");
if (hms_split.length < 2)
throw new Error("invalid HMS format");
let h_s = hms_split[0];
let h = parseInt(h_s);
let m_s = hms_split[1];
let m = parseInt(m_s);
if (hms_split.length > 2) {
let s_s = hms_split[2];
s = parseInt(s_s);
}
return new C_HMS(h, m, s);
}
static Now() {
let dnow = new Date();
let h = dnow.getHours();
let m = dnow.getMinutes();
let s = dnow.getSeconds();
return new C_HMS(h, m, s);
}
// contains: Hour, Minute, Second
static FromObject(hms) {
let h = hms.Hour;
let m = hms.Minute;
let s = hms.Second;
return new C_HMS(h, m, s);
}
Get12HourHour() {
let res = this.Hour;
if (res > 12)
res = res - 12;
if (res === 0)
res = 12;
return res;
}
IsAm() {
return this.Hour < 12;
}
Num() {
return this.Hour * 60 * 60 + this.Minute * 60 + this.Second;
}
static FromHoursMinutesAMPM(hour, minutes, ampm) {
let h = hour + (ampm.toLowerCase() === "am" ? 0 : 12);
if (h === 24)
h = 0;
if ((h < 0) || (h > 23))
throw new Error("Hours value is out of range");
if ((minutes < 0) || (minutes > 59))
throw new Error("Minutes value is out of range");
return new C_HMS(h, minutes, 0);
}
CompareTo(v2) {
let res = 1;
if ((this.Hour === v2.Hour) && (this.Minute === v2.Minute) && (this.Second === v2.Second))
res = 0;
else if ((this.Hour < v2.Hour)
|| ((this.Hour === v2.Hour) && (this.Minute < v2.Minute))
|| ((this.Hour === v2.Hour) && (this.Minute === v2.Minute) && (this.Second < v2.Second)))
res = -1;
return res;
}
}
class C_YMDhms {
constructor(ymd, hms) {
if (!(ymd instanceof C_YMD))
throw new Error("expecting C_YMD");
if (!(hms instanceof C_HMS))
throw new Error("expeting C_HMS");
this.YMD = new C_YMD(ymd.Year, ymd.Month, ymd.Day);
this.HMS = new C_HMS(hms.Hour, hms.Minute, hms.Second);
}
// 2009-06-15T13:45:30.0000000Z
static FromString(ymdhms) {
let res = null;
try {
let ymd_hms = ymdhms.split('T');
let ymd_s = ymd_hms[0];
let ymd_a = ymd_s.split('-');
let y = parseInt(ymd_a[0]);
let mo = parseInt(ymd_a[1]);
let d = parseInt(ymd_a[2]);
let hms_s = ymd_hms[1];
let hms_a1 = hms_s.split('.');
let hms_a = hms_a1[0].split(':');
let h = parseInt(hms_a[0]);
let mi = parseInt(hms_a[1]);
let s = parseInt(hms_a[2]);
let ymd = new C_YMD(y, mo, d);
let hms = new C_HMS(h, mi, s);
res = new C_YMDhms(ymd, hms);
}
catch {
res = new C_YMDhms(C_YMD.Now(), C_HMS.Now());
}
return res;
}
// 2009-06-15T13:45:30.0000000Z
toString() {
return this.YMD.Year.toString() + '-' + C_YMDhms.PadTo(this.YMD.Month, 2) + '-' + C_YMDhms.PadTo(this.YMD.Day, 2) + 'Z' +
C_YMDhms.PadTo(this.HMS.Hour) + ':' + C_YMDhms.PadTo(this.HMS.Minute) + ':' + C_YMDhms.PadTo(this.HMS.Second) + '.0000000Z';
}
CompareTo(ymdhms) {
let res = 1;
let ymdCompare = this.YMD.CompareTo(ymdhms.YMD);
let hmsCompare = this.HMS.CompareTo(ymdhms.HMS);
if ((ymdCompare === 0) && (hmsCompare === 0))
res = 0;
else if (ymdCompare < 0)
res = -1;
else if (hmsCompare < 0)
res = -1;
return res;
}
static Now() {
return new C_YMDhms(C_YMD.Now(), C_HMS.Now());
}
static PadTo(value, digits) {
let s = value.toString();
while (s.length < digits) {
s = '0' + s;
}
return s;
}
}
class C_EncryptDecryption {
static async encrypt(stringToEncrypt) {
if (!C_EncryptDecryption._supportsCrypto())
return stringToEncrypt;
const mode = 'AES-GCM',
length = 256,
ivLength = 12,
pw = 'now is the time for all good men';
const encrypted = await C_EncryptDecryption._encrypt(stringToEncrypt, pw, mode, length, ivLength);
const _iv_s = C_EncryptDecryption.toHexString(encrypted.iv);
const _ciphertext_s = C_EncryptDecryption.toHexString(encrypted.cipherText);
const _v = {part1: _iv_s, part2: _ciphertext_s};
return JSON.stringify(_v);
}
static async decrypt(stringToDecrypt) {
if (!C_EncryptDecryption._supportsCrypto())
return stringToDecrypt;
const _v1 = JSON.parse(stringToDecrypt);
const _iv1 = C_EncryptDecryption.fromHexString(_v1.part1);
const _ciphertext1 = C_EncryptDecryption.fromHexString(_v1.part2);
const r_encrypted = {iv: _iv1, cipherText: _ciphertext1};
const mode = 'AES-GCM',
length = 256,
//ivLength = 12,
pw = 'now is the time for all good men';
return await C_EncryptDecryption._decrypt(r_encrypted, pw, mode, length);
}
static _supportsCrypto () {
return window.crypto && crypto.subtle && window.TextEncoder;
}
static toHexString(byteArray)
{
let s = '';
const ba = new Uint8Array(byteArray);
ba.forEach(
function(byte)
{
s += ('0' + (byte & 0xFF).toString(16)).slice(-2);
});
return s;
}
static fromHexString(hexString)
{
const result = [];
while (hexString.length >= 2)
{
result.push(parseInt(hexString.substring(0, 2), 16));
hexString = hexString.substring(2, hexString.length);
}
return new Uint8Array(result);
}
static async genEncryptionKey (password, mode, length)
{
const algo =
{
name: 'PBKDF2',
hash: 'SHA-256',
salt: new TextEncoder().encode('a-unique-salt'),
iterations: 1000
};
const derived = {name: mode, length: length};
const encoded = new TextEncoder().encode(password);
const key = await crypto.subtle.importKey('raw', encoded, {name: 'PBKDF2'}, false, ['deriveKey']);
return crypto.subtle.deriveKey(algo, key, derived, false, ['encrypt', 'decrypt']);
}
static async _encrypt (text, password, mode, length, ivLength)
{
const algo =
{
name: mode,
length: length,
iv: crypto.getRandomValues(new Uint8Array(ivLength))
};
const key = await C_EncryptDecryption.genEncryptionKey(password, mode, length);
const encoded = new TextEncoder().encode(text);
return { cipherText: await crypto.subtle.encrypt(algo, key, encoded), iv: algo.iv };
}
static async _decrypt (encrypted, password, mode, length)
{
const algo =
{
name: mode,
length: length,
iv: encrypted.iv
};
const key = await C_EncryptDecryption.genEncryptionKey(password, mode, length);
const decrypted = await crypto.subtle.decrypt(algo, key, encrypted.cipherText);
return new TextDecoder().decode(decrypted);
}
}
|
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'node_modules/jquery/dist/jquery.js',
'node_modules/bootstrap/dist/js/bootstrap.js',
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-aria/angular-aria.js',
'node_modules/angular-cookies/angular-cookies.js',
'node_modules/angular-messages/angular-messages.js',
'node_modules/angular-material/angular-material.js',
'node_modules/angular-material-data-table/dist/md-data-table.js',
'node_modules/angular-sanitize/angular-sanitize.js',
'node_modules/angular-translate/dist/angular-translate.js',
'node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'node_modules/angular-route/angular-route.js',
'node_modules/mdPickers/dist/mdPickers.js',
'node_modules/moment/moment.js',
'app/app.js',
'app/app.config.js',
'app/app.filters.js',
'app/app.routes.js',
'app/authentication/*.js',
'app/authentication/services/*.js',
'app/authentication/controllers/*.js',
'app/navbar/*.js',
'app/navbar/services/*.js',
'app/navbar/controllers/*.js',
'app/runs/*.js',
'app/runs/services/*.js',
'app/runs/controllers/*.js',
'app/users/*.js',
'app/users/services/*.js',
'app/users/controllers/*.js',
'templates/**/*.html'
],
exclude: [],
preprocessors: {
'templates/**/*.html': ['ng-html2js'],
'templates/**/!(*.mock|*.spec).js': ['coverage']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'templates/',
// create a single module that contains templates from all the files
moduleName: 'templates'
},
reporters: ['spec', 'coverage'],
coverageReporter: {
type: 'html',
// output coverage reports
dir: 'coverage/'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
import React from 'react'
class GroupList extends React.Component{
constructor(props, context) {
super(props, context);
}
render () {
let groupList = this.props.groupMembers.map((member) => (
<li key={member.name} className="list-group-item">{member.name}</li>
));
return (
<ul className="list-group list-group-flush">
{groupList}
</ul>
)
}
}
export default GroupList; |
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('ean-crud generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ean-crud:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig',
'Gruntfile.coffee',
'config.yaml',
'app.coffee',
'src/client/modules',
'src/client/common/config',
'src/client/common/directives',
'src/client/common/filters',
'src/client/common/interceptors',
'src/client/public',
'src/server/api',
'src/server/routes',
'test/mocha.opts',
'test/client/karma.conf.js',
'src/server/routes/client.coffee',
'test/server/integration',
'test/server/unit',
'test/client/integration',
'test/client/unit',
'src/client/common/directives/Alphabetical.coffee',
'src/client/common/directives/Alphanumerical.coffee',
'src/client/common/directives/Back.coffee',
'src/client/common/directives/BarChart.coffee',
'src/client/common/directives/DateInput.coffee',
'src/client/common/directives/GroupedBarChart.coffee',
'src/client/common/directives/MaxLength.coffee',
'src/client/common/directives/NoSpaces.coffee',
'src/client/common/directives/Notification.coffee',
'src/client/common/directives/OnlyNumber.coffee',
'src/client/common/directives/PasswordCheck.coffee',
'src/client/common/directives/SqlDate.coffee',
'src/client/common/directives/Tooltip.coffee',
'src/client/common/directives/Typeahead.coffee',
'src/client/common/directives/UpperCase.coffee',
'src/client/common/filters/PhoneNumber.coffee',
'src/client/common/filters/Truncate.coffee',
'src/client/common/interceptors/AuthorizationInterceptor.coffee',
'src/client/common/interceptors/Reset.coffee',
'src/client/common/interceptors/SpinnerInterceptor.coffee',
'src/client/common/interceptors/SpinnerInterceptorPromise.coffee',
'src/client/common/alert.html',
'src/client/common/app.coffee',
'src/client/common/graph-container.html',
'src/client/common/message.html',
'src/client/common/messageBoxes.coffee'
];
helpers.mockPrompt(this.app, {
'appName': "appName"
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
"use strict";
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);
};
var core_1 = require("@angular/core");
var platform_browser_1 = require("@angular/platform-browser");
var app_component_1 = require("./app.component");
var hello_world_component_1 = require("./hello-world.component");
var AppModule = (function () {
function AppModule() {
}
AppModule = __decorate([
core_1.NgModule({
imports: [
platform_browser_1.BrowserModule
],
declarations: [
app_component_1.AppComponent,
hello_world_component_1.HelloWorldComponent
],
bootstrap: [app_component_1.AppComponent]
}),
__metadata('design:paramtypes', [])
], AppModule);
return AppModule;
}());
exports.AppModule = AppModule;
;
|
/**
* ===================================================================
* main js
*
* -------------------------------------------------------------------
*/
(function($) {
"use strict";
/*---------------------------------------------------- */
/* Preloader
------------------------------------------------------ */
$(window).load(function() {
// will first fade out the loading animation
$("#loader").fadeOut("slow", function(){
// will fade out the whole DIV that covers the website.
$("#preloader").delay(300).fadeOut("slow");
});
})
/*---------------------------------------------------- */
/* FitText Settings
------------------------------------------------------ */
setTimeout(function() {
$('#intro h1').fitText(1, { minFontSize: '42px', maxFontSize: '84px' });
}, 100);
/*---------------------------------------------------- */
/* FitVids
------------------------------------------------------ */
$(".fluid-video-wrapper").fitVids();
/*---------------------------------------------------- */
/* Owl Carousel
------------------------------------------------------ */
$("#owl-slider").owlCarousel({
navigation: false,
pagination: true,
itemsCustom : [
[0, 1],
[700, 2],
[960, 3]
],
navigationText: false
});
/*----------------------------------------------------- */
/* Alert Boxes
------------------------------------------------------- */
$('.alert-box').on('click', '.close', function() {
$(this).parent().fadeOut(500);
});
/*----------------------------------------------------- */
/* Stat Counter
------------------------------------------------------- */
var statSection = $("#stats"),
stats = $(".stat-count");
statSection.waypoint({
handler: function(direction) {
if (direction === "down") {
stats.each(function () {
var $this = $(this);
$({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 4000,
easing: 'swing',
step: function (curValue) {
$this.text(Math.ceil(curValue));
}
});
});
}
// trigger once only
this.destroy();
},
offset: "90%"
});
/*---------------------------------------------------- */
/* Masonry
------------------------------------------------------ */
var containerProjects = $('.folio-wrapper');
containerProjects.imagesLoaded( function() {
containerProjects.masonry( {
itemSelector: '.folio-item',
resize: true
});
});
/*----------------------------------------------------*/
/* Modal Popup
------------------------------------------------------*/
$('.item-wrap a').magnificPopup({
type:'inline',
fixedContentPos: false,
removalDelay: 300,
showCloseBtn: false,
mainClass: 'mfp-fade'
});
$(document).on('click', '.popup-modal-dismiss', function (e) {
e.preventDefault();
$.magnificPopup.close();
});
/*-----------------------------------------------------*/
/* Navigation Menu
------------------------------------------------------ */
var toggleButton = $('.menu-toggle'),
nav = $('.main-navigation');
// toggle button
toggleButton.on('click', function(e) {
e.preventDefault();
toggleButton.toggleClass('is-clicked');
nav.slideToggle();
});
// nav items
nav.find('li a').on("click", function() {
// update the toggle button
toggleButton.toggleClass('is-clicked');
// fadeout the navigation panel
nav.fadeOut();
});
/*---------------------------------------------------- */
/* Highlight the current section in the navigation bar
------------------------------------------------------ */
var sections = $("section"),
navigation_links = $("#main-nav-wrap li a");
sections.waypoint( {
handler: function(direction) {
var active_section;
active_section = $('section#' + this.element.id);
if (direction === "up") active_section = active_section.prev();
var active_link = $('#main-nav-wrap a[href="#' + active_section.attr("id") + '"]');
navigation_links.parent().removeClass("current");
active_link.parent().addClass("current");
},
offset: '25%'
});
/*---------------------------------------------------- */
/* Smooth Scrolling
------------------------------------------------------ */
$('.smoothscroll').on('click', function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 800, 'swing', function () {
window.location.hash = target;
});
});
/*---------------------------------------------------- */
/* Placeholder Plugin Settings
------------------------------------------------------ */
$('input, textarea, select').placeholder()
/*---------------------------------------------------- */
/* contact form
------------------------------------------------------ */
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
/*----------------------------------------------------- */
/* Back to top
------------------------------------------------------- */
var pxShow = 300; // height on which the button will show
var fadeInTime = 400; // how slow/fast you want the button to show
var fadeOutTime = 400; // how slow/fast you want the button to hide
var scrollSpeed = 300; // how slow/fast you want the button to scroll to top. can be a value, 'slow', 'normal' or 'fast'
// Show or hide the sticky footer button
jQuery(window).scroll(function() {
if (!( $("#header-search").hasClass('is-visible'))) {
if (jQuery(window).scrollTop() >= pxShow) {
jQuery("#go-top").fadeIn(fadeInTime);
} else {
jQuery("#go-top").fadeOut(fadeOutTime);
}
}
});
})(jQuery); |
import React from 'react';
import PropTypes from 'prop-types';
const Alert = props => (
<div className="react-caps__alert">
<p className="react-caps__alert__text">{props.text}</p>
<button className="react-caps__alert__ok" onClick={e => props.onOkClick(e)}>
Ok
</button>
<style jsx>
{`
.react-caps__alert {
font-size: 12px;
line-height: 16px;
}
.react-caps__alert__text {
margin: 0;
padding: 20px;
}
.react-caps__alert__btns {
}
.react-caps__alert__ok {
margin: 0;
padding: 10px 5px;
border: none;
background: transparent;
border: none;
background: transparent;
border-top: 1px solid #eee;
text-transform: uppercase;
cursor: pointer;
color: #34ab5a;
display: block;
width: 100%;
box-sizing: border-box;
outline: none;
}
.react-caps__alert__ok:active {
background-color: #f7f7f7;
}
`}
</style>
</div>
);
Alert.propTypes = {
text: PropTypes.string.isRequired,
onOkClick: PropTypes.func.isRequired,
};
export default Alert;
|
var m = require('mithril');
var chessground = require('chessground');
var classSet = chessground.util.classSet;
var partial = chessground.util.partial;
var game = require('game').game;
var status = require('game').status;
var opposite = chessground.util.opposite;
var socket = require('../socket');
var clockView = require('../clock/view');
var renderCorrespondenceClock = require('../correspondenceClock/view');
var renderReplay = require('./replay');
var renderStatus = require('./status');
var renderUser = require('game').view.user;
var button = require('./button');
var m = require('mithril');
function compact(x) {
if (Object.prototype.toString.call(x) === '[object Array]') {
var elems = x.filter(function(n) {
return n !== undefined
});
return elems.length > 0 ? elems : null;
}
return x;
}
function renderPlayer(ctrl, player) {
return player.ai ? m('div.username.on-game', [
ctrl.trans('aiNameLevelAiLevel', 'Stockfish', player.ai),
m('span.status.hint--top', {
'data-hint': 'Artificial intelligence is ready'
}, m('span', {
'data-icon': '3'
}))
]) : m('div', {
class: 'username ' + player.color + (player.onGame ? ' on-game' : '')
},
renderUser(ctrl, player)
);
}
function loader() {
return m('div.loader.fast');
}
function renderTableEnd(ctrl) {
var d = ctrl.data;
var buttons = compact(ctrl.vm.redirecting ? loader() : [
button.backToTournament(ctrl) || [
button.joinRematch(ctrl) ||
button.answerOpponentRematch(ctrl) ||
button.cancelRematch(ctrl) ||
button.rematch(ctrl)
],
button.newOpponent(ctrl),
button.analysis(ctrl)
]);
return [
renderReplay(ctrl),
buttons ? m('div.control.buttons', buttons) : null,
renderPlayer(ctrl, d.player)
];
}
function renderTableWatch(ctrl) {
var d = ctrl.data;
var buttons = compact(ctrl.vm.redirecting ? loader() : [
button.viewRematch(ctrl),
button.viewTournament(ctrl),
button.analysis(ctrl)
]);
return [
renderReplay(ctrl),
buttons ? m('div.control.buttons', buttons) : null,
renderPlayer(ctrl, d.player)
];
}
function renderTablePlay(ctrl) {
var d = ctrl.data;
var buttons = button.submitMove(ctrl) || compact([
button.forceResign(ctrl),
button.threefoldClaimDraw(ctrl),
button.cancelDrawOffer(ctrl),
button.answerOpponentDrawOffer(ctrl),
button.cancelTakebackProposition(ctrl),
button.answerOpponentTakebackProposition(ctrl), (d.tournament && game.nbMoves(d, d.player.color) === 0) ? m('div.text[data-icon=j]',
ctrl.trans('youHaveNbSecondsToMakeYourFirstMove', 15)
) : null
]);
return [
renderReplay(ctrl),
ctrl.vm.moveToSubmit ? null : (
button.feedback(ctrl) || m('div.control.icons', [
game.abortable(d) ? button.standard(ctrl, null, 'L', 'abortGame', 'abort') :
button.standard(ctrl, game.takebackable, 'i', 'proposeATakeback', 'takeback-yes', partial(ctrl.takebackYes)),
button.standard(ctrl, game.drawable, '2', 'offerDraw', 'draw-yes'),
button.standard(ctrl, game.resignable, 'b', 'resign', 'resign')
])
),
buttons ? m('div.control.buttons', buttons) : null,
renderPlayer(ctrl, d.player)
];
}
function whosTurn(ctrl, color) {
var d = ctrl.data;
if (status.finished(d) || status.aborted(d)) return;
return m('div.whos_turn',
d.game.player === color ? (
d.player.spectator ? ctrl.trans(d.game.player + 'Plays') : ctrl.trans(
d.game.player === d.player.color ? 'yourTurn' : 'waitingForOpponent'
)
) : ''
);
}
function goBerserk(ctrl) {
return m('button', {
class: 'button berserk hint--bottom-left',
'data-hint': "GO BERSERK! Half the time, bonus point",
onclick: ctrl.berserk
}, m('span', {
'data-icon': '`'
}));
}
function renderClock(ctrl, color, position) {
var time = ctrl.clock.data[color];
var running = ctrl.isClockRunning() && ctrl.data.game.player === color;
return [
m('div', {
class: 'clock clock_' + color + ' clock_' + position + ' ' + classSet({
'outoftime': !time,
'running': running,
'emerg': time < ctrl.clock.data.emerg
})
}, [
clockView.showBar(ctrl.clock, time),
m('div.time', m.trust(clockView.formatClockTime(ctrl.clock, time * 1000, running))),
ctrl.data.player.color === color && game.berserkableBy(ctrl.data) ? goBerserk(ctrl) : null
]),
position === 'bottom' ? button.moretime(ctrl) : null
];
}
function renderRelayClock(ctrl, color, position) {
var time = ctrl.relayClock.data[color];
var running = ctrl.isClockRunning() && ctrl.data.game.player === color;
return m('div', {
class: 'clock clock_' + color + ' clock_' + position + ' ' + classSet({
'outoftime': !time,
'running': running
})
}, m('div.time', m.trust(clockView.formatClockTime(ctrl.relayClock, time * 1000, running))));
}
function anyClock(ctrl, color, position) {
if (ctrl.clock && !ctrl.data.blind) return renderClock(ctrl, color, position);
else if (ctrl.relayClock) return renderRelayClock(ctrl, color, position);
else if (ctrl.data.correspondence && ctrl.data.game.turns > 1)
return renderCorrespondenceClock(
ctrl.correspondenceClock, ctrl.trans, color, position, ctrl.data.game.player
);
else return whosTurn(ctrl, color);
}
function videochat(ctrl) {
return m('div', {
id: 'videochat',
class: ctrl.vm.videochat ? '' : 'none'
}, [
m('video', {
class: 'their-video',
autoplay: true
}),
m('video', {
class: 'my-video',
autoplay: true,
muted: true
})
]);
}
module.exports = function(ctrl) {
var showCorrespondenceClock = ctrl.data.correspondence && ctrl.data.game.turns > 1;
return m('div.table_wrap', [
anyClock(ctrl, ctrl.data.opponent.color, 'top'),
videochat(ctrl),
m('div', {
class: 'table' + (status.finished(ctrl.data) ? ' finished' : '')
}, [
ctrl.vm.videochat ? null : renderPlayer(ctrl, ctrl.data.opponent),
m('div.table_inner',
ctrl.data.player.spectator ? renderTableWatch(ctrl) : (
game.playable(ctrl.data) ? renderTablePlay(ctrl) : renderTableEnd(ctrl)
)
)
]),
anyClock(ctrl, ctrl.data.player.color, 'bottom')
]);
}
|
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("zrf", "3.0");
design.checkVersion("animate-captures", "false");
design.checkVersion("smart-moves", "false");
design.checkVersion("show-hints", "false");
design.checkVersion("show-blink", "false");
design.checkVersion("ko", "true");
design.checkVersion("advisor-wait", "5");
design.checkVersion("dodgem-extension", "true");
design.addDirection("w");
design.addDirection("e");
design.addDirection("s");
design.addDirection("n");
design.addPlayer("Blue", [1, 0, 3, 2]);
design.addPlayer("Red", [3, 2, 0, 1]);
design.addPosition("a6", [0, 1, 6, 0]);
design.addPosition("b6", [-1, 1, 6, 0]);
design.addPosition("c6", [-1, 1, 6, 0]);
design.addPosition("d6", [-1, 1, 6, 0]);
design.addPosition("e6", [-1, 1, 6, 0]);
design.addPosition("f6", [-1, 0, 6, 0]);
design.addPosition("a5", [0, 1, 6, -6]);
design.addPosition("b5", [-1, 1, 6, -6]);
design.addPosition("c5", [-1, 1, 6, -6]);
design.addPosition("d5", [-1, 1, 6, -6]);
design.addPosition("e5", [-1, 1, 6, -6]);
design.addPosition("f5", [-1, 0, 6, -6]);
design.addPosition("a4", [0, 1, 6, -6]);
design.addPosition("b4", [-1, 1, 6, -6]);
design.addPosition("c4", [-1, 1, 6, -6]);
design.addPosition("d4", [-1, 1, 6, -6]);
design.addPosition("e4", [-1, 1, 6, -6]);
design.addPosition("f4", [-1, 0, 6, -6]);
design.addPosition("a3", [0, 1, 6, -6]);
design.addPosition("b3", [-1, 1, 6, -6]);
design.addPosition("c3", [-1, 1, 6, -6]);
design.addPosition("d3", [-1, 1, 6, -6]);
design.addPosition("e3", [-1, 1, 6, -6]);
design.addPosition("f3", [-1, 0, 6, -6]);
design.addPosition("a2", [0, 1, 6, -6]);
design.addPosition("b2", [-1, 1, 6, -6]);
design.addPosition("c2", [-1, 1, 6, -6]);
design.addPosition("d2", [-1, 1, 6, -6]);
design.addPosition("e2", [-1, 1, 6, -6]);
design.addPosition("f2", [-1, 0, 6, -6]);
design.addPosition("a1", [0, 1, 0, -6]);
design.addPosition("b1", [-1, 1, 0, -6]);
design.addPosition("c1", [-1, 1, 0, -6]);
design.addPosition("d1", [-1, 1, 0, -6]);
design.addPosition("e1", [-1, 1, 0, -6]);
design.addPosition("f1", [-1, 0, 0, -6]);
design.addZone("goal", 1, [0, 1, 2, 3, 4, 5]);
design.addZone("goal", 2, [35, 29, 23, 17, 11, 5]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addCommand(1, ZRF.FUNCTION, 24); // from
design.addCommand(1, ZRF.IN_ZONE, 0); // goal
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.FUNCTION, 26); // capture
design.addCommand(1, ZRF.FUNCTION, 25); // to
design.addCommand(1, ZRF.FUNCTION, 28); // end
design.addPiece("Car", 0);
design.addMove(0, 0, [3], 0);
design.addMove(0, 0, [0], 0);
design.addMove(0, 0, [1], 0);
design.addMove(0, 1, [], 0);
design.setup("Blue", "Car", 31);
design.setup("Blue", "Car", 32);
design.setup("Blue", "Car", 33);
design.setup("Blue", "Car", 34);
design.setup("Blue", "Car", 35);
design.setup("Red", "Car", 24);
design.setup("Red", "Car", 18);
design.setup("Red", "Car", 12);
design.setup("Red", "Car", 6);
design.setup("Red", "Car", 0);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("BlueCar", "Blue Car");
view.defPiece("RedCar", "Red Car");
view.defPosition("a6", 2, 2, 60, 60);
view.defPosition("b6", 64, 2, 60, 60);
view.defPosition("c6", 126, 2, 60, 60);
view.defPosition("d6", 188, 2, 60, 60);
view.defPosition("e6", 250, 2, 60, 60);
view.defPosition("f6", 312, 2, 60, 60);
view.defPosition("a5", 2, 64, 60, 60);
view.defPosition("b5", 64, 64, 60, 60);
view.defPosition("c5", 126, 64, 60, 60);
view.defPosition("d5", 188, 64, 60, 60);
view.defPosition("e5", 250, 64, 60, 60);
view.defPosition("f5", 312, 64, 60, 60);
view.defPosition("a4", 2, 126, 60, 60);
view.defPosition("b4", 64, 126, 60, 60);
view.defPosition("c4", 126, 126, 60, 60);
view.defPosition("d4", 188, 126, 60, 60);
view.defPosition("e4", 250, 126, 60, 60);
view.defPosition("f4", 312, 126, 60, 60);
view.defPosition("a3", 2, 188, 60, 60);
view.defPosition("b3", 64, 188, 60, 60);
view.defPosition("c3", 126, 188, 60, 60);
view.defPosition("d3", 188, 188, 60, 60);
view.defPosition("e3", 250, 188, 60, 60);
view.defPosition("f3", 312, 188, 60, 60);
view.defPosition("a2", 2, 250, 60, 60);
view.defPosition("b2", 64, 250, 60, 60);
view.defPosition("c2", 126, 250, 60, 60);
view.defPosition("d2", 188, 250, 60, 60);
view.defPosition("e2", 250, 250, 60, 60);
view.defPosition("f2", 312, 250, 60, 60);
view.defPosition("a1", 2, 312, 60, 60);
view.defPosition("b1", 64, 312, 60, 60);
view.defPosition("c1", 126, 312, 60, 60);
view.defPosition("d1", 188, 312, 60, 60);
view.defPosition("e1", 250, 312, 60, 60);
view.defPosition("f1", 312, 312, 60, 60);
}
|
module.exports = {
"commands": [
{
"name": "set",
"params": [
"$abc",
"This_is_abc"
]
}
],
"props": {
"$abc": "This_is_abc"
},
"domains": {
"api.example.com": {
"domain": "api.example.com",
"commands": [
{
"name": "proxy_pass",
"params": [
"http://$local/news/src/mock/list.json"
]
},
{
"name": "set_header",
"params": [
"Access-Control-Allow-Origin",
"*"
]
}
],
"location": [
{
"path": "/abc/",
"originPath": "/abc/",
"source": "api.example.com/abc/",
"commands": [
{
"name": "proxy_pass",
"params": [
"http://api.example.com/prd/This_is_abc"
]
},
{
"name": "set_header",
"params": [
"Proxy",
"prd"
]
}
],
"props": {
"proxy": "http://api.example.com/prd/This_is_abc"
},
"parent": "_domain_api.example.com",
"parentID": "_domain_api.example.com"
},
{
"path": "/def/",
"originPath": "/def/",
"source": "api.example.com/def/",
"commands": [
{
"name": "proxy_pass",
"params": [
"http://api.example.com/prd/def/f"
]
},
{
"name": "set_header",
"params": [
"Proxy",
"def"
]
}
],
"props": {
"proxy": "http://api.example.com/prd/def/f"
},
"parent": "_domain_api.example.com",
"parentID": "_domain_api.example.com"
}
],
"props": {},
"__id__": "_domain_api.example.com",
"parent": "global",
"parentID": "global"
}
},
"__id__": "global"
}; |
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import expect from 'expect';
import React from 'react';
import { shallow } from 'enzyme';
import DocumentCard from '../../components/document/DocumentCard';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const setup = () => {
const props = {
document: {
title: 'title',
content: 'content',
access: 'public',
owner: { firstName: 'oluwafemi', lastName: 'akinwa' } },
deleteDocument: () => {},
currentUser: {}
};
return shallow(
<DocumentCard {...props} />,
context: { store: mockStore }
);
};
describe('DocumentCard', () => {
it('renders a col div', () => {
const wrapper = setup();
expect(wrapper.find('.col')).toExist();
});
it('renders card', () => {
const wrapper = setup();
expect(wrapper.find('.card')).toExist();
});
it('should render DOM elements', () => {
const wrapper = setup();
expect(wrapper.find('.card-title').text()).toEqual('title');
expect(wrapper.find('.card-content').text()).toExist();
expect(wrapper.find('.right').text()).toExist();
});
it('should contain links', () => {
const wrapper = setup();
expect(wrapper.find('Link').length).toBe(3);
});
it('should contain props', () => {
const wrapper = setup();
expect(wrapper.props('document')).toExist();
expect(wrapper.props('deleteDocument')).toExist();
expect(wrapper.props('currentUser')).toExist();
expect(wrapper.find('onClick')).toExist();
});
});
|
var data = require('../models/dataman');
exports.create = function(req,res){
res.render('tree/create');
};
exports.index = function(req,res){
data.read(function(err, trees) {
res.render('tree', {trees: trees});
});
};
exports.createTree = function(req,res){
data.create(req.body, function(err) {
data.read(function(err, trees) {
res.render('tree', {trees: trees});
});
});
}; |
'use strict';
/**
*
*/
var navlist = angular.module('mainNavList', []);
navlist.controller('mainNavCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'data-replication';
if (currentRoute.match('data-replication')) {
currentRoute = 'data-replication';
} else if (currentRoute.match('data-migration')) {
currentRoute = 'data-migration';
}
return page === currentRoute ? 'active' : '';
};
}]); |
webpackJsonp(["app/js/pay/show-mobile-modal/index"],[function(e,n){"use strict";var i=$("#modal"),a=$("#unbind-form"),o=$("#unbind-btn"),s=a.validate({rules:{mobile:{required:!0,phone:!0}}});o.click(function(){if(s.form()){o.button("loading"),i.modal("hide");var e=$("input[name='payAgreementId']").val();$.post(a.attr("action"),a.serialize(),function(n){n.success?($("#unbind-bank-"+e).remove(),Notify.success(n.message)):Notify.danger(n.message)})}})}]); |
import React from 'react';
import { render } from 'react-dom';
import Demo from './demo';
render(
(
<Demo />
),
document.getElementById('root'),
);
|
import React from 'react';
import { mount } from 'enzyme';
import Card from '../src/Card';
describe('<Card>', () => {
it('should output a div', () => {
mount(<Card>Card</Card>).assertSingle('div');
});
it('should have additional classes', () => {
mount(<Card className="custom-class">Card</Card>).assertSingle(
'.card.custom-class',
);
});
it('accepts a bg prop', () => {
mount(<Card bg="primary">Card</Card>).assertSingle('.card.bg-primary');
});
it('accepts a text prop', () => {
mount(<Card text="success">Card</Card>).assertSingle('.card.text-success');
});
it('accepts a border prop', () => {
mount(<Card border="danger">Card</Card>).assertSingle(
'.card.border-danger',
);
});
it('should render children', () => {
mount(
<Card>
<p>hello</p>
</Card>,
).assertSingle('p');
});
it('accepts as prop', () => {
mount(<Card as="section">body</Card>).assertSingle('section');
});
it('allows for the body shorthand', () => {
mount(<Card body>test</Card>).assertSingle('.card-body');
});
});
|
describe('api', () => {
describe ('middleware', () => {
describe ('players', () => {
it('TODO', () => {
})
})
})
})
|
// TODO: make singleton instance for cache
|
'use strict';
(function() {
// Yarn descriptions Controller Spec
describe('Yarn descriptions Controller Tests', function() {
// Initialize global variables
var YarnDescriptionsController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Yarn descriptions controller.
YarnDescriptionsController = $controller('YarnDescriptionsController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Yarn description object fetched from XHR', inject(function(YarnDescriptions) {
// Create sample Yarn description using the Yarn descriptions service
var sampleYarnDescription = new YarnDescriptions({
name: 'New Yarn description'
});
// Create a sample Yarn descriptions array that includes the new Yarn description
var sampleYarnDescriptions = [sampleYarnDescription];
// Set GET response
$httpBackend.expectGET('yarn-descriptions').respond(sampleYarnDescriptions);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.yarnDescriptions).toEqualData(sampleYarnDescriptions);
}));
it('$scope.findOne() should create an array with one Yarn description object fetched from XHR using a yarnDescriptionId URL parameter', inject(function(YarnDescriptions) {
// Define a sample Yarn description object
var sampleYarnDescription = new YarnDescriptions({
name: 'New Yarn description'
});
// Set the URL parameter
$stateParams.yarnDescriptionId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/yarn-descriptions\/([0-9a-fA-F]{24})$/).respond(sampleYarnDescription);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.yarnDescription).toEqualData(sampleYarnDescription);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(YarnDescriptions) {
// Create a sample Yarn description object
var sampleYarnDescriptionPostData = new YarnDescriptions({
name: 'New Yarn description'
});
// Create a sample Yarn description response
var sampleYarnDescriptionResponse = new YarnDescriptions({
_id: '525cf20451979dea2c000001',
name: 'New Yarn description'
});
// Fixture mock form input values
scope.name = 'New Yarn description';
// Set POST response
$httpBackend.expectPOST('yarn-descriptions', sampleYarnDescriptionPostData).respond(sampleYarnDescriptionResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Yarn description was created
expect($location.path()).toBe('/yarn-descriptions/' + sampleYarnDescriptionResponse._id);
}));
it('$scope.update() should update a valid Yarn description', inject(function(YarnDescriptions) {
// Define a sample Yarn description put data
var sampleYarnDescriptionPutData = new YarnDescriptions({
_id: '525cf20451979dea2c000001',
name: 'New Yarn description'
});
// Mock Yarn description in scope
scope.yarnDescription = sampleYarnDescriptionPutData;
// Set PUT response
$httpBackend.expectPUT(/yarn-descriptions\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/yarn-descriptions/' + sampleYarnDescriptionPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid yarnDescriptionId and remove the Yarn description from the scope', inject(function(YarnDescriptions) {
// Create new Yarn description object
var sampleYarnDescription = new YarnDescriptions({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Yarn descriptions array and include the Yarn description
scope.yarnDescriptions = [sampleYarnDescription];
// Set expected DELETE response
$httpBackend.expectDELETE(/yarn-descriptions\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleYarnDescription);
$httpBackend.flush();
// Test array after successful delete
expect(scope.yarnDescriptions.length).toBe(0);
}));
});
}()); |
import {
divideSync,
meanSync,
subtractSync,
stdSync
} from '../utils/linearAlgebra'
export default (X) => {
const mu = meanSync(X)
const sigma = stdSync(X)
const normX = divideSync(subtractSync(X, mu), sigma)
return [normX, mu, sigma]
}
|
'use strict';
const test = require('tape').test
var dgram = require('dgram')
const persistents = require('../')
const provider = require('./util/get-provider')('UDPWRAP')
test('\nudpwrap: dgram.createSocket', function (t) {
const sock = dgram.createSocket('udp4')
const res = persistents.collect()[provider]
t.equal(res.length, 1, 'finds one udpwrap')
t.equal(res[0].owner.type, 'udp4', 'udp4 type')
sock.close(t.end)
})
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.10_A1.3_T1;
* @section: 12.10;
* @assertion: The with statement adds a computed object to the front of the
* scope chain of the current execution context;
* @description: Using "with" statement within function constructor, leading to normal completition;
*/
this.p1 = 1;
this.p2 = 2;
this.p3 = 3;
var result = "result";
var myObj = {p1: 'a',
p2: 'b',
p3: 'c',
value: 'myObj_value',
valueOf : function(){return 'obj_valueOf';},
parseInt : function(){return 'obj_parseInt';},
NaN : 'obj_NaN',
Infinity : 'obj_Infinity',
eval : function(){return 'obj_eval';},
parseFloat : function(){return 'obj_parseFloat';},
isNaN : function(){return 'obj_isNaN';},
isFinite : function(){return 'obj_isFinite';}
}
var del;
var st_p1 = "p1";
var st_p2 = "p2";
var st_p3 = "p3";
var st_parseInt = "parseInt";
var st_NaN = "NaN";
var st_Infinity = "Infinity";
var st_eval = "eval";
var st_parseFloat = "parseFloat";
var st_isNaN = "isNaN";
var st_isFinite = "isFinite";
var f = function(){
with(myObj){
st_p1 = p1;
st_p2 = p2;
st_p3 = p3;
st_parseInt = parseInt;
st_NaN = NaN;
st_Infinity = Infinity;
st_eval = eval;
st_parseFloat = parseFloat;
st_isNaN = isNaN;
st_isFinite = isFinite;
p1 = 'x1';
this.p2 = 'x2';
del = delete p3;
var p4 = 'x4';
p5 = 'x5';
var value = 'value';
}
}
var obj = new f();
if(!(p1 === 1)){
$ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 );
}
if(!(p2 === 2)){
$ERROR('#2: p2 === 2. Actual: p2 ==='+ p2 );
}
if(!(p3 === 3)){
$ERROR('#3: p3 === 3. Actual: p3 ==='+ p3 );
}
try {
p4;
$ERROR('#4: p4 is not defined');
} catch(e) {
}
if(!(p5 === "x5")){
$ERROR('#5: p5 === "x5". Actual: p5 ==='+ p5 );
}
if(!(myObj.p1 === "x1")){
$ERROR('#6: myObj.p1 === "x1". Actual: myObj.p1 ==='+ myObj.p1 );
}
if(!(myObj.p2 === "b")){
$ERROR('#7: myObj.p2 === "b". Actual: myObj.p2 ==='+ myObj.p2 );
}
if(!(myObj.p3 === undefined)){
$ERROR('#8: myObj.p3 === undefined. Actual: myObj.p3 ==='+ myObj.p3 );
}
if(!(myObj.p4 === undefined)){
$ERROR('#9: myObj.p4 === undefined. Actual: myObj.p4 ==='+ myObj.p4 );
}
if(!(myObj.p5 === undefined)){
$ERROR('#10: myObj.p5 === undefined. Actual: myObj.p5 ==='+ myObj.p5 );
}
if(!(st_parseInt !== parseInt)){
$ERROR('#11: myObj.parseInt !== parseInt');
}
if(!(st_NaN === "obj_NaN")){
$ERROR('#12: myObj.NaN !== NaN');
}
if(!(st_Infinity !== Infinity)){
$ERROR('#13: myObj.Infinity !== Infinity');
}
if(!(st_eval !== eval)){
$ERROR('#14: myObj.eval !== eval');
}
if(!(st_parseFloat !== parseFloat)){
$ERROR('#15: myObj.parseFloat !== parseFloat');
}
if(!(st_isNaN !== isNaN)){
$ERROR('#16: myObj.isNaN !== isNaN');
}
if(!(st_isFinite !== isFinite)){
$ERROR('#17: myObj.isFinite !== isFinite');
}
try{
value;
$ERROR('#18: value is not defined');
}
catch(e){
}
if(!(myObj.value === "value")){
$ERROR('#19: myObj.value === "value". Actual: myObj.value ==='+ myObj.value );
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:f09aa2eb775d6aeb124d3291cc63834c175eaed66927f5c0fffcbafdd2b8d2a7
size 6674
|
'use strict';
angular.module('myApp.login', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'login/login.html',
controller: 'LoginCtrl'
});
}])
/**
* @ngdoc object
* @name myApp.login:LoginCtrl
* @description
* # Controller
* Controller for login screen. contains all the behavioral functions for login screen
*/
.controller('LoginCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.checkCred = function () {
$location.path('/home');
};
}]); |
var loggedUser = checkCookie();
if(loggedUser.userRole != 'DEV' && loggedUser.userRole != 'super'){
redirectToPage(loggedUser.userRole);
}
$('#logged-id').html(loggedUser.userName);
// these three objects are used to store requested data from server so that the browser doesn't have to request the same page.
// init: this object holds code that executed during the first time client loads the script.
// what does it do? request data from the server, save them as global variables.
var init = {};
// populate: this object holds code that executed when the client changes page to the one that has been requested.
// what does it do? fill the forms, tables, graph etc with the data initialized before.
//The client can manually refresh the data.
var populate = {};
// view: this object holds HTML strings to be parsed when the client requested them.
var view = {};
//holds the local data
var localData = {};
// this function governs how a new "page" is requested. By page it means new content
var loadPage = function(pageName){
// the "a" element that the user clicked in the navigation
var a_element = $('.nav-list>a[href="'+pageName+'"]');
// assets directory
var viewDir = '/assets/views/admin/';
var scriptDir = '/assets/js/admin/';
// remove all "active" element so that no indicator of where the page the user currently at.
$(".nav-list").removeClass('active');
// title on the (typically) tab bar of a browser
document.title = a_element.children('span').html();
// this line of code checks the view global object
if(typeof view[window.location.hash.substr(1)] == 'undefined'){
// if not, then this page had never been requested before. Request from server.
$.get(viewDir + pageName + '.html', function(data) {
// hold the parsed HTML string to the "view" global object
view[window.location.hash.substr(1)] = data;
// render the HTML strings.
$("#page-content").html(view[window.location.hash.substr(1)]);
console.log(pageName + ' view loaded');
// load the script
loadScript(scriptDir+pageName+'.js', function(){
// run "populate" function from the loaded script
console.log(window.location.hash.substr(1));
populate[window.location.hash.substr(1)]();
});
}).fail(function(e) {
// error handling.
console.log(e);
var msg = "Sorry but there was an error: ";
toastr.options = {
closeButton: true,
progressBar: true,
showMethod: 'slideDown',
timeOut: 4000
};
toastr.error(e.status + " <b>" + pageName + "</b> page " + e.statusText, msg);
window.history.back();
});
} else {
// if the page is already saved before, just render it
$("#page-content").html(view[window.location.hash.substr(1)]);
// load the script
loadScript(scriptDir+pageName+'.js', function(){
// run "populate" function from the loaded script
populate[window.location.hash.substr(1)]();
});
}
// set "active" to the navigation list
a_element.parent().addClass('active');
}
// this function governs how a new script is requested. A script is loaded and executed only after views have already been loaded and rendered.
function loadScript(url, callback){
// first check if script is already loaded
var src = $('script[src="'+url+'"]').length;
if(src == 0){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
init[window.location.hash.substr(1)](function(status){
if(status.success){
callback();
}
});
}
};
} else { //Others
script.onload = function(){
init[window.location.hash.substr(1)](function(status){
if(status.success){
callback();
}
});
};
}
script.src = url;
document.getElementsByTagName("body")[0].appendChild(script);
} else {
console.log('script is already loaded. No need to reload.');
callback();
}
}
// for etc use
function etcConfigs(){
$('#page-content').on('click', '.dropdown-menu>li>a', function(e){
e.preventDefault();
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});
//logout button
$('#logout-btn').on('click', function(e){
e.preventDefault();
$(this).html('Logging out..');
document.cookie = 'token=; path=/';
location.reload();
/*$.ajax({
method: 'GET',
url: 'http://192.168.100.50:8000/logout',
success: function(data, status, xhr){
},
error: function(status, xhr, err){
}
});*/
});
}
$(document).ready(function(){
$(window).on('hashchange', function() {
loadPage(window.location.hash.substr(1));
});
$(".nav-list a").on("click", function(e) {
e.preventDefault();
window.location.hash = $(this).attr('href');
});
$(".btn-menu-toggle").on("click", function(e){
e.preventDefault();
$(".btn-menu-toggle").toggleClass("minimized");
$("#page-wrapper").toggleClass("maximized");
$(".navbar-static-side").toggleClass("minimized");
})
// default hash, a homepage. automatically redirected to the first navigation on the list
if(window.location.hash === ""){
var firstNavHref = $(".nav-list").eq(0).children('a').attr('href');
window.location.hash = firstNavHref;
} else {
loadPage(window.location.hash.substr(1));
}
etcConfigs();
}); |
System.register(["angular2/core"],function(e){var t,n,o=this&&this.__decorate||function(e,t,n,o){var r,c=arguments.length,f=3>c?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(e,t,n,o);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(f=(3>c?r(f):c>3?r(t,n,f):r(t,n))||f);return c>3&&f&&Object.defineProperty(t,n,f),f},r=this&&this.__metadata||function(e,t){return"object"==typeof Reflect&&"function"==typeof Reflect.metadata?Reflect.metadata(e,t):void 0};return{setters:[function(e){t=e}],execute:function(){n=function(){function e(){}return e=o([t.Component({selector:"my-form",template:"\n\n "}),r("design:paramtypes",[])],e)}(),e("MyFormComponent",n)}}}); |
/**
* @projectDescription SuiteScript JavaScript library summary.
*
* Note that there are some restrictions on API usage. Also note that the only 2 objects that can be
* contructed are nlobjSearchFilter and nlobjSearchColumn. All other objects can only be created via
* top-level function or method calls.
*
* The @governance tag refers to the usage governance for an API call
* The @restricted tag refers to any known restrictions with a particular API call
*
* All Object arguments are Javascript Objects used as hash tables for specifying key-value pairs
*
* @since 2005.0 Support scripting of current record in Client SuiteScript
* @version 2007.0 Support scripting of records in user events, portlets, and scheduled scripts
* @version 2008.1 Support scripting of web requests (Suitelets) and user interfaces (UI Object API)
* @version 2009.1 Support scripting of file objects
* @version 2009.2 Support scripting of setup records and assistant (multi-step) pages
* @version 2009.2 converted JS template to use eclipse code completion friendly format
* @version 2010.1 Suppport dynamic scripting
*/
/**
* Return a new record using values from an existing record.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @param {Object} initializeValues Contains an array of name/value pairs of defaults to be used during record initialization.
* @return {nlobjRecord} Returns an nlobjRecord object of a copied record.
*
* @since 2007.0
*/
function nlapiCopyRecord(type, id, initializeValues) { ; }
/**
* Load an existing record from the system.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @param {Object} initializeValues Contains an array of name/value pairs of defaults to be used during record initialization.
* @return {nlobjRecord} Returns an nlobjRecord object of an existing NetSuite record.
*
* @exception {SSS_INVALID_RECORD_TYPE}
* @exception {SSS_TYPE_ARG_REQD}
* @exception {SSS_INVALID_INTERNAL_ID}
* @exception {SSS_ID_ARG_REQD}
*
* @since 2007.0
*/
function nlapiLoadRecord(type, id, initializeValues) { ; }
/**
* Instantiate a new nlobjRecord object containing all the default field data for that record type.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
*
* @param {string} type record type ID.
* @param {Object} initializeValues Contains an array of name/value pairs of defaults to be used during record initialization.
* @return {nlobjRecord} Returns an nlobjRecord object of a new record from the system.
*
* @exception {SSS_INVALID_RECORD_TYPE}
* @exception {SSS_TYPE_ARG_REQD}
*
* @since 2007.0
*/
function nlapiCreateRecord(type, initializeValues) { ; }
/**
* Submit a record to the system for creation or update.
* @governance 20 units for transactions, 4 for custom records, 8 for all other records
*
* @param {nlobjRecord} record nlobjRecord object containing the data record.
* @param {boolean} [doSourcing] If not set, this argument defaults to false.
* @param {boolean} [ignoreMandatoryFields] Disables mandatory field validation for this submit operation.
* @return {string} internal ID for committed record.
*
* @exception {SSS_INVALID_RECORD_OBJ}
* @exception {SSS_RECORD_OBJ_REQD}
* @exception {SSS_INVALID_SOURCE_ARG}
*
* @since 2007.0
*/
function nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields) { ; }
/**
* Delete a record from the system.
* @governance 20 units for transactions, 4 for custom records, 8 for all other records
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @return {void}
*
* @exception {SSS_INVALID_RECORD_TYPE}
* @exception {SSS_TYPE_ARG_REQD}
* @exception {SSS_INVALID_INTERNAL_ID}
* @exception {SSS_ID_ARG_REQD}
*
* @since 2007.0
*/
function nlapiDeleteRecord(type, id) { ; }
/**
* Perform a record search using an existing search or filters and columns.
* @governance 10 units
* @restriction returns the first 1000 rows in the search
*
* @param {string} type record type ID.
* @param {int, string} [id] The internal ID or script ID for the saved search to use for search.
* @param {nlobjSearchFilter, nlobjSearchFilter[]} [filters] [optional] A single nlobjSearchFilter object - or - an array of nlobjSearchFilter objects.
* @param {nlobjSearchColumn, nlobjSearchColumn[]} [columns] [optional] A single nlobjSearchColumn object - or - an array of nlobjSearchColumn objects.
* @return {nlobjSearchResult[]} Returns an array of nlobjSearchResult objects corresponding to the searched records.
*
* @exception {SSS_INVALID_RECORD_TYPE}
* @exception {SSS_TYPE_ARG_REQD}
* @exception {SSS_INVALID_SRCH_ID}
* @exception {SSS_INVALID_SRCH_FILTER}
* @exception {SSS_INVALID_SRCH_FILTER_JOIN}
* @exception {SSS_INVALID_SRCH_OPERATOR}
* @exception {SSS_INVALID_SRCH_COL_NAME}
* @exception {SSS_INVALID_SRCH_COL_JOIN}
*
* @since 2007.0
*/
function nlapiSearchRecord(type, id, filters, columns) { ; }
/**
* Perform a global record search across the system.
* @governance 10 units
* @restriction returns the first 1000 rows in the search
*
* @param {string} keywords Global search keywords string or expression.
* @return {nlobjSearchResult[]} Returns an Array of nlobjSearchResult objects containing the following four columns: name, type (as shown in the UI), info1, and info2.
*
* @since 2008.1
*/
function nlapiSearchGlobal(keywords) { ; }
/**
* Perform a duplicate record search using Duplicate Detection criteria.
* @governance 10 units
* @restriction returns the first 1000 rows in the search
*
* @param {string} type The recordType you are checking duplicates for (for example, customer|lead|prospect|partner|vendor|contact).
* @param {string[]} [fields] array of field names used to detect duplicate (for example, companyname|email|name|phone|address1|city|state|zipcode).
* @param {int} [id] internal ID of existing record. Depending on the use case, id may or may not be a required argument.
* @return {nlobjSearchResult[]} Returns an Array of nlobjSearchResult objects corresponding to the duplicate records.
*
* @since 2008.1
*/
function nlapiSearchDuplicate(type, fields, id) { ; }
/**
* Create a new record using values from an existing record of a different type.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @param {string} transformType The recordType you are transforming the existing record into.
* @param {Object} [transformValues] An object containing transform default option/value pairs used to pre-configure transformed record
* @return {nlobjRecord}
*
* @exception {SSS_INVALID_URL_CATEGORY}
* @exception {SSS_CATEGORY_ARG_REQD}
* @exception {SSS_INVALID_TASK_ID}
* @exception {SSS_TASK_ID_REQD}
* @exception {SSS_INVALID_INTERNAL_ID}
* @exception {SSS_INVALID_EDITMODE_ARG}
*
* @since 2007.0
*/
function nlapiTransformRecord(type, id, transformType, transformValues) { ; }
/**
* Fetch the value of one or more fields on a record. This API uses search to look up the fields and is much
* faster than loading the record in order to get the field.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @param {string, string[]} fields - field or fields to look up.
* @param {boolean} [text] If set then the display value is returned instead for select fields.
* @return {string, Object} single value or an Object of field name/value pairs depending on the fields argument.
*
* @since 2008.1
*/
function nlapiLookupField(type,id,fields, text) { ; }
/**
* Submit the values of a field or set of fields for an existing record.
* @governance 10 units for transactions, 2 for custom records, 4 for all other records
* @restriction only supported for records and fields where DLE (Direct List Editing) is supported
*
* @param {string} type The record type name.
* @param {int} id The internal ID for the record.
* @param {string, string[]} fields field or fields being updated.
* @param {string, string[]} values field value or field values used for updating.
* @param {boolean} [doSourcing] If not set, this argument defaults to false and field sourcing does not occur.
* @return {void}
*
* @since 2008.1
*/
function nlapiSubmitField(type,id,fields,values,doSourcing) { ; }
/**
* Attach a single record to another with optional properties.
* @governance 10 units
*
* @param {string} type1 The record type name being attached
* @param {int} id1 The internal ID for the record being attached
* @param {string} type2 The record type name being attached to
* @param {int} id2 The internal ID for the record being attached to
* @param {Object} [properties] Object containing name/value pairs used to configure attach operation
* @return {void}
*
* @since 2008.2
*/
function nlapiAttachRecord(type1, id1, type2, id2, properties) { ; }
/**
* Detach a single record from another with optional properties.
* @governance 10 units
*
* @param {string} type1 The record type name being attached
* @param {int} id1 The internal ID for the record being attached
* @param {string} type2 The record type name being attached to
* @param {int} id2 The internal ID for the record being attached to
* @param {Object} [properties] Object containing name/value pairs used to configure detach operation
* @return {void}
*
* @since 2008.2
*/
function nlapiDetachRecord(type1, id1, type2, id2, properties) { ; }
/**
* Resolve a URL to a resource or object in the system.
*
* @param {string} type type specifier for URL: suitelet|tasklink|record|mediaitem
* @param {string} subtype subtype specifier for URL (corresponding to type): scriptid|taskid|recordtype|mediaid
* @param {string} [id] internal ID specifier (sub-subtype corresponding to type): deploymentid|n/a|recordid|n/a
* @param {string} [pagemode] string specifier used to configure page (suitelet: external|internal, tasklink|record: edit|view)
* @return {string}
*
* @since 2007.0
*/
function nlapiResolveURL(type, subtype, id, pagemode) { ; }
/**
* Redirect the user to a page. Only valid in the UI on Suitelets and User Events. In Client scripts this will initialize the redirect URL used upon submit.
*
* @param {string} type type specifier for URL: suitelet|tasklink|record|mediaitem
* @param {string} subtype subtype specifier for URL (corresponding to type): scriptid|taskid|recordtype|mediaid
* @param {string} [id] internal ID specifier (sub-subtype corresponding to type): deploymentid|n/a|recordid|n/a
* @param {string} [pagemode] string specifier used to configure page (suitelet: external|internal, tasklink|record: edit|view)
* @param {Object} [parameters] Object used to specify additional URL parameters as name/value pairs
* @return {void}
*
* @since 2007.0
*/
function nlapiSetRedirectURL(type, subtype, id, pagemode, parameters) { ; }
/**
* Request a URL to an external or internal resource.
* @restriction NetSuite maintains a white list of CAs that are allowed for https requests. Please see the online documentation for the complete list.
* @governance 10 units
*
* @param {string} url A fully qualified URL to an HTTP(s) resource
* @param {string, Object} [postdata] - string, document, or Object containing POST payload
* @param {Object} [headers] - Object containing request headers.
* @param {function} [callback] - available on the Client to support asynchronous requests. function is passed an nlobjServerResponse with the results.
* @return {nlobjServerResponse}
*
* @exception {SSS_UNKNOWN_HOST}
* @exception {SSS_INVALID_HOST_CERT}
* @exception {SSS_REQUEST_TIME_EXCEEDED}
*
* @since 2007.0
*/
function nlapiRequestURL(url, postdata, headers, callback, method) { ; }
/**
* Return context information about the current user/script.
*
* @return {nlobjContext}
*
* @since 2007.0
*/
function nlapiGetContext() { ; }
/**
* Return the internal ID for the currently logged in user. Returns -4 when called from online forms or "Available without Login" Suitelets.
*
* @return {int}
*
* @since 2005.0
*/
function nlapiGetUser() { ; }
/**
* Return the internal ID for the current user's role. Returns 31 (Online Form User) when called from online forms or "Available without Login" Suitelets.
*
* @return {int}
*
* @since 2005.0
*/
function nlapiGetRole() { ; }
/**
* Return the internal ID for the current user's department.
*
* @return {int}
*
* @since 2005.0
*/
function nlapiGetDepartment() { ; }
/**
* Return the internal ID for the current user's location.
*
* @return {int}
*
* @since 2005.0
*/
function nlapiGetLocation() { ; }
/**
* Return the internal ID for the current user's subsidiary.
*
* @return {int}
*
* @since 2008.1
*/
function nlapiGetSubsidiary() { ; }
/**
* Return the recordtype corresponding to the current page or userevent script.
*
* @return {string}
*
* @since 2007.0
*/
function nlapiGetRecordType() { ; }
/**
* Return the internal ID corresponding to the current page or userevent script.
*
* @return {int}
*
* @since 2007.0
*/
function nlapiGetRecordId() { ; }
/**
* Send out an email and associate it with records in the system.
* Supported base types are entity for entities, transaction for transactions, activity for activities and cases, record|recordtype for custom records
* @governance 10 units
* @restriction all outbound emails subject to email Anti-SPAM policies
*
* @param {int} from internal ID for employee user on behalf of whom this email is sent
* @param {string, int} to email address or internal ID of user that this email is being sent to
* @param {string} subject email subject
* @param {string} body email body
* @param {string, string[]} cc copy email address(es)
* @param {string, string[]} bcc blind copy email address(es)
* @param {Object} records Object of base types -> internal IDs used to associate email to records. i.e. {entity: 100, record: 23, recordtype: customrecord_surveys}
* @param {nlobjFile[]} files array of nlobjFile objects (files) to include as attachments
* @return {void}
*
* @since 2007.0
*/
function nlapiSendEmail(from, to, subject, body, cc, bcc, records, files) { ; }
/**
* Sends a single on-demand campaign email to a specified recipient and returns a campaign response ID to track the email.
* @governance 10 units
* @restriction works in conjunction with the Lead Nurturing (campaigndrip) sublist only
*
* @param {int} campaigneventid internal ID of the campaign event
* @param {int} recipientid internal ID of the recipient - the recipient must have an email
* @return {int}
*
* @since 2010.1
*/
function nlapiSendCampaignEmail(campaigneventid, recipientid) { ; }
/**
* Send out a fax and associate it with records in the system. This requires fax preferences to be configured.
* Supported base types are entity for entities, transaction for transactions, activity for activities and cases, record|recordtype for custom records
* @governance 10 units
*
* @param {int} from internal ID for employee user on behalf of whom this fax is sent
* @param {string, int} to fax address or internal ID of user that this fax is being sent to
* @param {string} subject fax subject
* @param {string} body fax body
* @param {Object} records Object of base types -> internal IDs used to associate fax to records. i.e. {entity: 100, record: 23, recordtype: customrecord_surveys}
* @param {nlobjFile[]} files array of nlobjFile objects (files) to include as attachments
* @return {void}
*
* @since 2008.2
*/
function nlapiSendFax(from, to, subject, body, records, files) { ; }
/**
* Return field definition for a field.
*
* @param {string} fldnam the name of the field
* @return {nlobjField}
*
* @since 2009.1
*/
function nlapiGetField(fldnam) { ; }
/**
* Return field definition for a matrix field.
*
* @param {string} type matrix sublist name
* @param {string} fldnam matrix field name
* @param {int} column matrix field column index (1-based)
* @return {nlobjField}
*
* @since 2009.2
*/
function nlapiGetMatrixField(type, fldnam, column) { ; }
/**
* Return field definition for a sublist field.
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} [linenum] line number for sublist field (1-based) and only valid for sublists of type staticlist and list
* @return {nlobjField}
*
* @since 2009.1
*/
function nlapiGetLineItemField(type, fldnam, linenum) { ; }
/**
* Return an nlobjField containing sublist field metadata.
*
* @param {string} type matrix sublist name
* @param {string} fldnam matrix field name
* @param {int} linenum line number (1-based)
* @param {int} column matrix column index (1-based)
* @return {nlobjField}
*
* @since 2009.2
*/
function nlapiGetLineItemMatrixField(type, fldnam, linenum, column) { ; }
/**
* Return the value of a field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam the field name
* @return {string}
*
* @since 2005.0
*/
function nlapiGetFieldValue(fldnam) { ; }
/**
* Set the value of a field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} fldnam the field name
* @param {string} value value used to set field
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2005.0
*/
function nlapiSetFieldValue(fldnam,value,firefieldchanged,synchronous) { ; }
/**
* Return the display value of a select field's current selection on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam the field name
* @return {string}
*
* @since 2005.0
*/
function nlapiGetFieldText(fldnam) { ; }
/**
* Set the value of a field on the current record on a page using it's label.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} fldnam the field name
* @param {string} txt display name used to lookup field value
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2005.0
*/
function nlapiSetFieldText(fldnam,txt,firefieldchanged,synchronous) { ; }
/**
* Return the values of a multiselect field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam the field name
* @return {string[]}
*
* @since 2005.0
*/
function nlapiGetFieldValues(fldnam) { ; }
/**
* Set the values of a multiselect field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} fldnam field name
* @param {string[]} values array of strings containing values for field
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2005.0
*/
function nlapiSetFieldValues(fldnam,values,firefieldchanged,synchronous) { ; }
/**
* Return the values (via display text) of a multiselect field on the current record.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam field name
* @return {string[]}
*
* @since 2009.1
*/
function nlapiGetFieldTexts(fldnam) { ; }
/**
* Set the values (via display text) of a multiselect field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} fldnam field name
* @param {string[]} texts array of strings containing display values for field
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2009.1
*/
function nlapiSetFieldTexts(fldnam,texts,firefieldchanged,synchronous) { ; }
/**
* Get the value of a matrix header field
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} column matrix column index (1-based)
* @return {string}
*
* @since 2009.2
*/
function nlapiGetMatrixValue(type, fldnam, column) { ; }
/**
* Set the value of a matrix header field
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} column matrix column index (1-based)
* @param {string} value field value for matrix field
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2009.2
*/
function nlapiSetMatrixValue(type, fldnam, column, value, firefieldchanged, synchronous) { ; }
/**
* Get the current value of a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} column matrix column index (1-based)
* @return {string} value
*
* @since 2009.2
*/
function nlapiGetCurrentLineItemMatrixValue(type, fldnam, column) { ; }
/**
* Set the current value of a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @restriction synchronous arg is only supported in Client SuiteScript
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} column matrix column index (1-based)
* @param {string} value matrix field value
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2009.2
*/
function nlapiSetCurrentLineItemMatrixValue(type, fldnam, column, value, firefieldchanged, synchronous) { ; }
/**
* Return the value of a sublist matrix field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} linenum line number (1-based)
* @param {int} column column index (1-based)
* @param {string} value
*
* @since 2009.2
*/
function nlapiGetLineItemMatrixValue(type, fldnam, linenum, column) { ; }
/**
* Return the value of a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} linenum line number (1-based)
* @return {string}
*
* @since 2005.0
*/
function nlapiGetLineItemValue(type,fldnam,linenum) { ; }
/**
* Set the value of a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} linenum line number (1-based)
* @param {string} value
* @retun {void}
*
* @since 2005.0
*/
function nlapiSetLineItemValue(type,fldnam,linenum,value) { ; }
/**
* Return the label of a select field's current selection for a particular line.
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} linenum line number (1-based)
* @return {string}
*
* @since 2005.0
*/
function nlapiGetLineItemText(type,fldnam,linenum) { ; }
/**
* Return the 1st line number that a sublist field value appears in
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {string} val the value being queried for in a sublist field
* @return {int}
*
* @since 2009.2
*/
function nlapiFindLineItemValue(type, fldnam, val) { ; }
/**
* Return the 1st line number that a matrix field value appears in
*
* @param {string} type sublist name
* @param {string} fldnam matrix field name
* @param {int} column matrix column index (1-based)
* @param {string} val the value being queried for in a matrix field
* @return {int}
*
* @since 2009.2
*/
function nlapiFindLineItemMatrixValue(type, fldnam, column, val) { ; }
/**
* Return the number of columns for a matrix field
*
* @param {string} type sublist name
* @param {string} fldnam matrix field name
* @return {int}
*
* @since 2009.2
*/
function nlapiGetMatrixCount(type, fldnam) { ; }
/**
* Return the number of sublists in a sublist on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @return {int}
*
* @since 2005.0
*/
function nlapiGetLineItemCount(type) { ; }
/**
* Insert and select a new line into the sublist on a page or userevent.
*
* @param {string} type sublist name
* @param {int} [line] line number at which to insert a new line.
* @return{void}
*
* @since 2005.0
*/
function nlapiInsertLineItem(type, line) { ; }
/**
* Remove the currently selected line from the sublist on a page or userevent.
*
* @param {string} type sublist name
* @param {int} [line] line number to remove.
* @return {void}
*
* @since 2005.0
*/
function nlapiRemoveLineItem(type, line) { ; }
/**
* Set the value of a field on the currently selected line.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {string} value field value
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2005.0
*/
function nlapiSetCurrentLineItemValue(type,fldnam,value,firefieldchanged,synchronous) { ; }
/**
* Set the value of a field on the currently selected line using it's label.
* @restriction synchronous arg is only supported in client SuiteScript
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {string} txt string containing display value or search text.
* @param {boolean} [firefieldchanged] if false then the field change event is suppressed (defaults to true)
* @param {boolean} [synchronous] if true then sourcing and field change execution happens synchronously (defaults to false).
* @return {void}
*
* @since 2005.0
*/
function nlapiSetCurrentLineItemText(type,fldnam,txt,firefieldchanged,synchronous) { ; }
/**
* Return the value of a field on the currently selected line.
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @return {string}
*
* @since 2005.0
*/
function nlapiGetCurrentLineItemValue(type,fldnam) { ; }
/**
* Return the label of a select field's current selection on the currently selected line.
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @return {string}
*
* @since 2005.0
*/
function nlapiGetCurrentLineItemText(type,fldnam) { ; }
/**
* Return the line number for the currently selected line.
*
* @param {string} type sublist name
* @return {int}
*
* @since 2005.0
*/
function nlapiGetCurrentLineItemIndex(type) { ; }
/**
* Disable a sublist field.
* @restriction Only supported on sublists of type inlineeditor, editor and list (current field only)
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {boolean} disable if true then field is disabled
* @param {int} linenum line number for sublist field (1-based) and only valid for sublists of type list
* @return {void}
*
* @since 2009.1
*/
function nlapiSetLineItemDisabled(type,fldnam,disable, linenum) { ; }
/**
* Return field mandatoriness.
*
* @param {string} fldnam field name
* @return {boolean}
*
* @since 2009.1
*/
function nlapiGetFieldMandatory(fldnam) { ; }
/**
* Return sublist field mandatoriness.
* @restriction Only supported on sublists of type inlineeditor or editor (current field only)
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @return {boolean}
*
* @since 2009.1
*/
function nlapiGetLineItemMandatory(type,fldnam) { ; }
/**
* Make a field mandatory.
*
* @param {string} fldnam field name
* @param {boolean} mandatory if true then field is made mandatory
* @return {void}
*
* @since 2009.1
*/
function nlapiSetFieldMandatory(fldnam,mandatory) { ; }
/**
* Make a sublist field mandatory.
* @restriction Only supported on sublists of type inlineeditor or editor (current field only)
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {boolean} mandatory if true then field is made mandatory
* @return {void}
*
* @since 2009.2
*/
function nlapiSetLineItemMandatory(type,fldnam,mandatory) { ; }
/**
* Select an existing line in a sublist.
*
* @param {string} type sublist name
* @param {int} linenum line number to select
* @return {void}
*
* @since 2005.0
*/
function nlapiSelectLineItem(type, linenum) { ; }
/**
* Save changes made on the currently selected line to the sublist.
*
* @param {string} type sublist name
* @return {void}
*
* @since 2005.0
*/
function nlapiCommitLineItem(type) { ; }
/**
* Cancel any changes made on the currently selected line.
* @restriction Only supported for sublists of type inlineeditor and editor
*
* @param {string} type sublist name
* @return {void}
*
* @since 2005.0
*/
function nlapiCancelLineItem(type) { ; }
/**
* Select a new line in a sublist.
* @restriction Only supported for sublists of type inlineeditor and editor
*
* @param {string} type sublist name
* @return {void}
*
* @since 2005.0
*/
function nlapiSelectNewLineItem(type) { ; }
/**
* Refresh the sublist table.
* @restriction Only supported for sublists of type inlineeditor, editor, and staticlist
* @restriction Client SuiteScript only.
*
* @param {string} type sublist name
* @return{void}
*
* @since 2005.0
*/
function nlapiRefreshLineItems(type) { ; }
/**
* Adds a select option to a scripted select or multiselect field.
* @restriction Client SuiteScript only
*
* @param {string} fldnam field name
* @param {string} value internal ID for select option
* @param {string} text display text for select option
* @param {boolean} [selected] if true then option will be selected by default
* @return {void}
*
* @since 2008.2
*/
function nlapiInsertSelectOption(fldnam, value, text, selected) { ; }
/**
* Removes a select option (or all if value is null) from a scripted select or multiselect field.
* @restriction Client SuiteScript only
*
* @param {string} fldnam field name
* @param {string} value internal ID of select option to remove
* @return {void}
*
* @since 2008.2
*/
function nlapiRemoveSelectOption(fldnam, value) { ; }
/**
* Adds a select option to a scripted select or multiselect sublist field.
* @restriction Client SuiteScript only
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {string} value internal ID for select option
* @param {string} text display text for select option
* @param {boolean} [selected] if true then option will be selected by default
* @return {void}
*
* @since 2008.2
*/
function nlapiInsertLineItemOption(type, fldnam, value, text, selected) { ; }
/**
* Removes a select option (or all if value is null) from a scripted select or multiselect sublist field.
* @restriction Client SuiteScript only
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {string} value internal ID for select option to remove
* @return {void}
*
* @since 2008.2
*/
function nlapiRemoveLineItemOption(type, fldnam, value) { ; }
/**
* Returns true if any changes have been made to a sublist.
* @restriction Client SuiteScript only
*
* @param {string} type sublist name
* @return {boolean}
*
* @since 2005.0
*/
function nlapiIsLineItemChanged(type) { ; }
/**
* Return an record object containing the data being submitted to the system for the currenr record.
* @restriction User Event scripts only
*
* @return {nlobjRecord}
*
* @since 2008.1
*/
function nlapiGetNewRecord() { ; }
/**
* Return an record object containing the current record's data prior to the write operation.
* @restriction beforeSubmit|afterSubmit User Event scripts only
*
* @return {nlobjRecord}
*
* @since 2008.1
*/
function nlapiGetOldRecord() { ; }
/**
* Create an nlobjError object that can be used to abort script execution and configure error notification
*
* @param {string} code error code
* @param {string} details error description
* @param {boolean} [suppressEmail] if true then suppress the error notification emails from being sent out (false by default).
* @return {nlobjError}
*
* @since 2008.2
*/
function nlapiCreateError(code,details,suppressEmail) { ; }
/**
* Return a new entry form page.
* @restriction Suitelets only
*
* @param {string} title page title
* @param {boolean} [hideHeader] true to hide the page header (false by default)
* @return {nlobjForm}
*
* @since 2008.2
*/
function nlapiCreateForm(title, hideHeader) { ; }
/**
* Return a new list page.
* @restriction Suitelets only
*
* @param {string} title page title
* @param {boolean} [hideHeader] true to hide the page header (false by default)
* @return {nlobjList}
*
* @since 2008.2
*/
function nlapiCreateList(title, hideHeader) { ; }
/**
* Return a new assistant page.
* @restriction Suitelets only
*
* @param {string} title page title
* @param {boolean} [hideHeader] true to hide the page header (false by default)
* @return {nlobjAssistant}
*
* @since 2009.2
*/
function nlapiCreateAssistant(title, hideHeader) { ; }
/**
* Load a file from the file cabinet (via its internal ID or path).
* @governance 10 units
* @restriction Server SuiteScript only
*
* @param {string, int} id internal ID or relative path to file in the file cabinet (i.e. /SuiteScript/foo.js)
* @return {nlobjFile}
*
* @since 2008.2
*/
function nlapiLoadFile(id) { ; }
/**
* Add/update a file in the file cabinet.
* @governance 20 units
* @restriction Server SuiteScript only
*
* @param {nlobjFile} file a file object to submit
* @return {int} return internal ID of file
*
* @since 2009.1
*/
function nlapiSubmitFile(file) { ; }
/**
* Delete a file from the file cabinet.
* @governance 20 units
* @restriction Server SuiteScript only
*
* @param {int} id internal ID of file to be deleted
* @return {id}
*
* @since 2009.1
*/
function nlapiDeleteFile(id) { ; }
/**
* Instantiate a file object (specifying the name, type, and contents which are base-64 encoded for binary types.)
* @restriction Server SuiteScript only
*
* @param {string} name file name
* @param {string} type file type i.e. plainText, htmlDoc, pdf, word (see documentation for the list of supported file types)
* @param {string} contents string containing file contents (must be base-64 encoded for binary types)
* @return {nlobjFile}
*
* @since 2009.1
*/
function nlapiCreateFile(name, type, contents) { ; }
/**
* Perform a mail merge operation using any template and up to 2 records and returns an nlobjFile with the results.
* @restriction only supported for record types that are available in mail merge: transactions, entities, custom records, and cases
* @restriction Server SuiteScript only
* @governance 10 units
*
* @param {int} id internal ID of template
* @param {string} baseType primary record type
* @param {int} baseId internal ID of primary record
* @param {string} [altType] secondary record type
* @param {int} [altId] internal ID of secondary record
* @param {Object} [fields] Object of merge field values to use in the mail merge (by default all field values are obtained from records) which overrides those from the record.
* @return {nlobjFile}
*
* @since 2008.2
*/
function nlapiMergeRecord(id, baseType, baseId, altType, altId, fields) { ; }
/**
* Print a record (transaction) gievn its type, id, and output format.
* @restriction Server SuiteScript only
* @governance 10 units
*
* @param {string} type print output type: transaction|statement|packingslip|pickingticket
* @param {int} id internal ID of record to print
* @param {string} [format] output format: html|pdf|default
* @param {Object} [properties] Object of properties used to configure print
* @return {nlobjFile}
*
* @since 2008.2
*/
function nlapiPrintRecord(type, id, format, properties) { ; }
/**
* Generate a PDF from XML using the BFO report writer (see http://big.faceless.org/products/report/).
* @restriction Server SuiteScript only
* @governance 10 units
*
* @param {string} input string containing BFO compliant XHTML
* @return {nlobjFile}
*
* @since 2009.1
*/
function nlapiXMLToPDF(input) { ; }
/**
* Create an entry in the script execution log (note that execution log entries are automatically purged after 30 days).
*
* @param {string} type log type: debug|audit|error|emergency
* @param {string} title log title (up to 90 characters supported)
* @param {string} [details] log details (up to 3000 characters supported)
* @return {void}
*
* @since 2008.1
*/
function nlapiLogExecution(type, title, details) { ; }
/**
* Queue a scheduled script for immediate execution and return the status QUEUED if successfull.
* @restriction Server SuiteScript only
* @governance 20 units
*
* @param {string, int} script script ID or internal ID of scheduled script
* @param {string, int} [deployment] script ID or internal ID of scheduled script deployment. If empty, the first "free" deployment (i.e. status = Not Scheduled or Completed) will be used
* @param {Object} parameters Object of parameter name->values used in this scheduled script instance
* @return {string} QUEUED or null if no available deployments were found or the current status of the deployment specified if it was not available.
*
* @since 2008.1
*/
function nlapiScheduleScript(script, deployment, parameters) { ; }
/**
* Return a URL with a generated OAuth token.
* @restriction Suitelets and Portlets only
* @governance 20 units
*
* @param {string} ssoAppKey
* @return {string}
*
* @since 2009.2
*/
function nlapiOutboundSSO(ssoAppKey) { ; }
/**
* Loads a configuration record
* @restriction Server SuiteScript only
* @governance 10 units
*
* @param {string} type
* @return {nlobjConfiguration}
*
* @since 2009.2
*/
function nlapiLoadConfiguration(type) { ; }
/**
* Commits all changes to a configuration record.
* @restriction Server SuiteScript only
* @governance 10 units
*
* @param {nlobjConfiguration} setup record
* @return (void)
*
* @since 2009.2
*/
function nlapiSubmitConfiguration(setup) { ; }
/**
* Convert a String into a Date object.
*
* @param {string} str date string in the user's date format, timeofday format, or datetime format
* @param {string} format format type to use: date|datetime|timeofday with date being the default
* @return {date}
*
* @since 2005.0
*/
function nlapiStringToDate(str, format) { ; }
/**
* Convert a Date object into a String
*
* @param {date} d date object being converted to a string
* @param {string} [formattype] format type to use: date|datetime|timeofday with date being the default
* @return {string}
*
* @since 2005.0
*/
function nlapiDateToString(d, formattype) { ; }
/**
* Add days to a Date object and returns a new Date
*
* @param {date} d date object used to calculate the new date
* @param {int} days the number of days to add to this date object.
* @return {date}
*
* @since 2008.1
*/
function nlapiAddDays(d, days) { ; }
/**
* Add months to a Date object and returns a new Date.
*
* @param {date} d date object used to calculate the new date
* @param {int} months the number of months to add to this date object.
* @return {date}
*
* @since 2008.1
*/
function nlapiAddMonths(d, months) { ; }
/**
* Format a number for data entry into a currency field.
*
* @param {string} str numeric string used to format for display as currency using user's locale
* @return {string}
*
* @since 2008.1
*/
function nlapiFormatCurrency(str) { ; }
/**
* Encrypt a String using a SHA-1 hash function
*
* @param {string} s string to encrypt
* @return {string}
*
* @since 2009.2
*/
function nlapiEncrypt(s) { ; }
/**
* Escape a String for use in an XML document.
*
* @param {string} text string to escape
* @return {string}
*
* @since 2008.1
*/
function nlapiEscapeXML(text) { ; }
/**
* Convert a String into an XML document. Note that in Server SuiteScript XML is supported natively by the JS runtime using the e4x standard (http://en.wikipedia.org/wiki/E4X)
* This makes scripting XML simpler and more efficient
*
* @param {string} str string being parsed into an XML document
* @return {document}
*
* @since 2008.1
*/
function nlapiStringToXML(str) { ; }
/**
* Convert an XML document into a String. Note that in Server SuiteScript XML is supported natively by the JS runtime using the e4x standard (http://en.wikipedia.org/wiki/E4X)
* This makes scripting XML data simpler and more efficient
*
* @param {document} xml document being serialized into a string
* @return {string}
*
* @since 2008.1
*/
function nlapiXMLToString(xml) { ; }
/**
* select a value from an XML node using XPath. Supports custom namespaces (nodes in default namespace can be referenced using "nlapi" as the prefix)
*
* @param {node} node node being queried
* @param {string} xpath string containing XPath expression.
* @return {string}
*
* @since 2008.2
*/
function nlapiSelectValue(node, xpath) { ; }
/**
* Select an array of values from an XML node using XPath. Supports custom namespaces (nodes in default namespace can be referenced using "nlapi" as the prefix)
*
* @param {node} node node being queried
* @param {string} xpath string containing XPath expression.
* @return {string[]}
*
* @since 2008.1
*/
function nlapiSelectValues(node, xpath) { ; }
/**
* Select a node from an XML node using XPath. Supports custom namespaces (nodes in default namespace can be referenced using "nlapi" as the prefix)
*
* @param {node} node node being queried
* @param {string} xpath string containing XPath expression.
* @return {node}
*
* @since 2008.1
*/
function nlapiSelectNode(node, xpath) { ; }
/**
* Select an array of nodes from an XML node using XPath. Supports custom namespaces (nodes in default namespace can be referenced using "nlapi" as the prefix)
*
* @param {node} node node being queried
* @param {string} xpath string containing XPath expression.
* @return {node[]}
*
* @since 2008.1
*/
function nlapiSelectNodes(node, xpath) { ; }
/**
* Calculate exchange rate between two currencies as of today or an optional effective date.
* @governance 10 units
*
* @param {string, int} fromCurrency internal ID or currency code of currency we are converting from
* @param {string, int} toCurrency internal ID or currency code of currency we are converting to
* @param {string} [date] string containing date of effective exchange rate. defaults to today
* @return {float}
*
* @since 2009.1
*/
function nlapiExchangeRate(fromCurrency, toCurrency, date) { ; }
/**
* Initiates a workflow on-demand and returns the workflow instance ID for the workflow-record combination.
* @governance 20 units
*
* @param {string} recordtype record type ID of the workflow base record
* @param {int} id internal ID of the base record
* @param {string, int} workflowid internal ID or script ID for the workflow definition
* @return {int}
*
* @since 2010.1
*/
function nlapiInitiateWorkflow(recordtype, id, workflowid) { ; }
/**
* Triggers a workflow on a record.
* @governance 20 units
*
* @param {string} recordtype record type ID of the workflow base record
* @param {int} id internal ID of the base record
* @param {string, int} workflowid internal ID or script ID for the workflow definition
* @param {string, int} actionid internal ID or script ID of the action script
* @return {int}
*
* @since 2010.1
*/
function nlapiTriggerWorkflow(recordtype, id, workflowid, actionid) { ; }
/**
* Create a subrecord on a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function nlapiCreateCurrentLineSubrecord(type,fldnam) { ; }
/**
* edit a subrecord on a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function nlapiEditCurrentLineItemSubrecord(type,fldnam) { ; }
/**
* remove a subrecord on a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @retun {void}
*
* @since 2011.2
*/
function nlapiRemoveCurrentLineItemSubrecord(type,fldnam) { ; }
/**
* view a subrecord on a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function nlapiViewCurrentLineItemSubrecord(type,fldnam) { ; }
/**
* view a subrecord on a sublist field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function nlapiViewLineItemSubrecord(type,fldnam,linenum) { ; }
/**
* create a subrecord on body field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam body field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function createSubrecord(fldnam) { ; }
/**
* edit a subrecord on body field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam body field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function editSubrecord(fldnam) { ; }
/**
* remove a subrecord on body field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam body field name
* @retun {void}
*
* @since 2011.2
*/
function removeSubrecord(fldnam) { ; }
/**
* view a subrecord on body field on the current record on a page.
* @restriction supported in client and user event scripts only.
* @param {string} fldnam body field name
* @retun {nlobjSubrecord}
*
* @since 2011.2
*/
function viewSubrecord(fldnam) { ; }
/**
* Commit the subrecord after you finish modifying it.
*
* @return {void}
*
* @method
* @memberOf nlobjSubrecord
*
* @since 2008.1
*/
nlobjSubrecord.prototype.commit = function() { ; }
/**
* Cancel the any modification on subrecord.
*
* @return {void}
*
* @method
* @memberOf nlobjSubrecord
*
* @since 2008.1
*/
nlobjSubrecord.prototype.cancel = function() { ; }
/**
* Return a new instance of nlobjRecord used for accessing and manipulating record objects.
*
* @classDescription Class definition for business records in the system.
* @return {nlobjRecord}
* @constructor
*
* @since 2008.2
*/
function nlobjRecord() { ; }
/**
* Return the internalId of the record or NULL for new records.
*
* @return {int} Return the integer value of the record ID.
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getId = function() { ; }
/**
* Return the recordType corresponding to this record.
*
* @return {string} The string value of the record name internal ID
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getRecordType = function( ) { ; }
/**
* Return field metadata for field.
*
* @param {string} fldnam field name
* @return {nlobjField}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.1
*/
nlobjRecord.prototype.getField = function(fldnam) { ; }
/**
* Return sublist metadata for sublist.
*
* @param {string} type sublist name
* @return {nlobjSubList}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getSubList = function(type) { ; }
/**
* Return field metadata for field.
*
* @param {string} type matrix sublist name
* @param {string} fldnam matrix field name
* @param {column} linenum matrix column (1-based)
* @return {nlobjField}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getMatrixField = function(type, fldnam, column) { ; }
/**
* Return metadata for sublist field.
*
* @param {string} type sublist name
* @param {string} fldnam sublist field name
* @param {int} [linenum] line number (1-based). If empty, the current sublist field is returned. only settable for sublists of type list
* @return {nlobjField}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getLineItemField = function(type, fldnam, linenum) { ; }
/**
* Return metadata for sublist field.
*
* @param {string} type matrix sublist name
* @param {string} fldnam matrix field name
* @param {int} linenum line number
* @param {column} linenum matrix column (1-based)
* @return {nlobjField}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getLineItemMatrixField = function(type, fldnam, linenum, column) { ; }
/**
* Set the value of a field.
*
* @param {string} name field name
* @param {string} value field value
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.setFieldValue = function( name, value ) { ; }
/**
* Set the values of a multi-select field.
*
* @param {string} name field name
* @param {string[]} values string array containing field values
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.setFieldValues = function( name, values ) { ; }
/**
* Return the value of a field.
*
* @param {string} name field name
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getFieldValue = function( name ) { ; }
/**
* Return the selected values of a multi-select field as an Array.
*
* @param {string} name field name
* @return {string[]}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getFieldValues = function( name ) { ; }
/**
* Set the value (via display value) of a select field.
* @restriction only supported for select fields
*
* @param {string} name field name
* @param {string} text field display value
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.setFieldText = function( name, text ) { ; }
/**
* Set the values (via display values) of a multi-select field.
* @restriction only supported for multi-select fields
*
* @param {string} name field name
* @param {string[]} texts array of field display values
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.setFieldTexts = function( name, texts ) { ; }
/**
* Return the display value for a select field.
* @restriction only supported for select fields
*
* @param {string} name field name
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.getFieldText = function( name ) { ; }
/**
* Return the selected display values of a multi-select field as an Array.
* @restriction only supported for multi-select fields
*
* @param {string} name field name
* @return {string[]}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.getFieldTexts = function( name ) { ; }
/**
* Get the value of a matrix header field.
*
* @param {string} type matrix sublist name
* @param {string} name matrix field name
* @param {int} column matrix column index (1-based)
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getMatrixValue = function( type, name, column ) { ; }
/**
* Set the value of a matrix header field.
*
* @param {string} type matrix sublist name
* @param {string} name matrix field name
* @param {int} column matrix column index (1-based)
* @param {string} value field value
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.setMatrixValue = function( type, name, column, value ) { ; }
/**
* Return an Array of all field names on the record.
*
* @return {string[]}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getAllFields = function( ) { ; }
/**
* Return an Array of all field names on a record for a particular sublist.
*
* @param {string} group sublist name
* @return {string[]}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.getAllLineItemFields = function( group ) { ; }
/**
* Set the value of a sublist field.
*
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {int} line line number (1-based)
* @param {string} value sublist field value
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.setLineItemValue = function( group, name, line, value ) { ; }
/**
* Return the value of a sublist field.
*
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {int} line line number (1-based)
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.1
*/
nlobjRecord.prototype.getLineItemValue = function( group, name, line ) { ; }
/**
* Return the text value of a sublist field.
*
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {int} line line number (1-based)
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2008.2
*/
nlobjRecord.prototype.getLineItemText = function( group, name, line ) { ; }
/**
* Set the current value of a sublist field.
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {string} value sublist field value
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.setCurrentLineItemValue = function( group, name, value ) { ; }
/**
* Return the current value of a sublist field.
*
* @param {string} group sublist name
* @param {string} name sublist field name
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getCurrentLineItemValue = function( group, name ) { ; }
/**
* Return the current display value of a sublist field.
*
* @param {string} group sublist name
* @param {string} name sublist field name
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getCurrentLineItemText = function( group, name ) { ; }
/**
* Set the current value of a sublist matrix field.
*
* @param {string} group matrix sublist name
* @param {string} name matrix field name
* @param {int} column matrix field column index (1-based)
* @param {string} value matrix field value
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.setCurrentLineItemMatrixValue = function( group, name, column, value ) { ; }
/**
* Return the current value of a sublist matrix field.
*
* @param {string} group matrix sublist name
* @param {string} name matrix field name
* @param {int} column matrix field column index (1-based)
* @return {string}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getCurrentLineItemMatrixValue = function( group, name, column ) { ; }
/**
* Return the number of columns for a matrix field.
*
* @param {string} group matrix sublist name
* @param {string} name matrix field name
* @return {int}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getMatrixCount = function( group, name ) { ; }
/**
* Return the number of lines in a sublist.
*
* @param {string} group sublist name
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.getLineItemCount = function( group ) { ; }
/**
* Return line number for 1st occurence of field value in a sublist column.
*
* @param {string} group sublist name
* @param {string} fldnam sublist field name
* @param {string} value sublist field value
* @return {int}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.findLineItemValue = function( group, fldnam, value ) { ; }
/**
* Return line number for 1st occurence of field value in a sublist column.
*
* @param {string} group sublist name
* @param {string} fldnam sublist field name
* @param {int} column matrix column index (1-based)
* @param {string} value matrix field value
* @return {int}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.findLineItemMatrixValue = function( group, fldnam, column, value ) { ; }
/**
* Insert a new line into a sublist.
*
* @param {string} group sublist name
* @param {int} [line] line index at which to insert line
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.insertLineItem = function( group, line ) { ; }
/**
* Remove an existing line from a sublist.
*
* @param {string} group sublist name
* @param {int} [line] line number to remove
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.removeLineItem = function( group, line ) { ; }
/**
* Insert and select a new line in a sublist.
*
* @param {string} group sublist name
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.selectNewLineItem = function( group ) { ; }
/**
* Select an existing line in a sublist.
*
* @param {string} group sublist name
* @param {int} line line number to select
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.selectLineItem = function( group, line ) { ; }
/**
* Commit the current line in a sublist.
*
* @param {string} group sublist name
* @return {void}
*
* @method
* @memberOf nlobjRecord
*
* @since 2009.2
*/
nlobjRecord.prototype.commitLineItem = function( group ) { ; }
/**
* Return a new instance of nlobjConfiguration..
*
* @classDescription Class definition for interacting with setup/configuration pages
* @return {nlobjConfiguration}
* @constructor
*
* @since 2009.2
*/
function nlobjConfiguration( ) { ; }
/**
* return the type corresponding to this setup record.
*
* @return {string}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getType = function( ) { ; }
/**
* return field metadata for field.
*
* @param {string} fldnam field name
* @return {nlobjField}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getField = function(fldnam) { ; }
/**
* set the value of a field.
*
* @param {string} name field name
* @param {string} value field value
* @return {void}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.setFieldValue = function( name, value ) { ; }
/**
* Set the values of a multi-select field.
* @restriction only supported for multi-select fields
*
* @param {string} name field name
* @param {string[]} value field values
* @return {void}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.setFieldValues = function( name, value ) { ; }
/**
* return the value of a field.
*
* @param {string} name field name
* @return {string}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getFieldValue = function( name ) { ; }
/**
* return the selected values of a multi-select field as an Array.
* @restriction only supported for multi-select fields
*
* @param {string} name field name
* @return {string[]}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getFieldValues = function( name ) { ; }
/**
* set the value (via display value) of a field.
* @restriction only supported for select fields
*
* @param {string} name field name
* @param {string} text field display text
* @return {void}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.setFieldText = function( name, text ) { ; }
/**
* set the values (via display values) of a multi-select field.
* @restriction only supported for multi-select fields
*
* @param {string} name field name
* @param {string[]} texts array of field display text values
* @return {void}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.setFieldTexts = function( name, texts ) { ; }
/**
* return the text value of a field.
* @restriction only supported for select fields
*
* @param {string} name field name
* @return {string}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getFieldText = function( name ) { ; }
/**
* return the selected text values of a multi-select field as an Array.
* @param {string} name field name
* @return {string[]}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getFieldTexts = function( name ) { ; }
/**
* return an Array of all field names on the record.
* @return {string[]}
*
* @method
* @memberOf nlobjConfiguration
*
* @since 2009.2
*/
nlobjConfiguration.prototype.getAllFields = function( ) { ; }
/**
* Return a new instance of nlobjFile used for accessing and manipulating files in the file cabinet.
*
* @classDescription Encapsulation of files (media items) in the file cabinet.
* @return {nlobjFile}
* @constructor
*
* @since 2009.1
*/
function nlobjFile( ) { ; }
/**
* Return the name of the file.
* @return {string}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getName = function( ) { ; }
/**
* Sets the name of a file.
* @param {string} name the name of the file
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.setName = function( name ) { ; }
/**
* return the internal ID of the folder that this file is in.
* @return {int}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getFolder = function( ) { ; }
/**
* sets the internal ID of the folder that this file is in.
* @param {int} folder
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.setFolder = function( folder ) { ; }
/**
* sets the character encoding for the file.
* @param {String} encoding
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2010.2
*/
nlobjFile.prototype.setEncoding = function( encoding ) { ; }
/**
* return true if the file is "Available without Login".
* @return {boolean}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.isOnline = function( ) { ; }
/**
* sets the file's "Available without Login" status.
* @param {boolean} online
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.setIsOnline = function( online ) { ; }
/**
* return true if the file is inactive.
* @return {boolean}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.isInactive = function( ) { ; }
/**
* sets the file's inactive status.
* @param {boolean} inactive
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.setIsInactive = function( inactive ) { ; }
/**
* return the file description.
* @return {string}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getDescription = function( ) { ; }
/**
* sets the file's description.
* @param {string} descr the file description
* @return {void}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.setDescription = function( descr ) { ; }
/**
* Return the id of the file (if stored in the FC).
* @return {int}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getId = function( ) { ; }
/**
* Return the size of the file in bytes.
* @return {int}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getSize = function( ) { ; }
/**
* Return the URL of the file (if stored in the FC).
* @return {string}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getURL = function( ) { ; }
/**
* Return the type of the file.
* @return {string}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getType = function( ) { ; }
/**
* Return the value (base64 encoded for binary types) of the file.
* @return {string}
*
* @method
* @memberOf nlobjFile
*
* @since 2009.1
*/
nlobjFile.prototype.getValue = function( ) { ; }
/**
* Return a new instance of nlobjSearchFilter filter objects used to define search criteria.
*
* @classDescription search filter
* @constructor
* @param {string} name filter name.
* @param {string} join internal ID for joined search where this filter is defined
* @param {string} operator operator name (i.e. anyOf, contains, lessThan, etc..)
* @param {string|string[]} value
* @param {string} value2
* @return {nlobjSearchFilter}
*
* @since 2007.0
*/
function nlobjSearchFilter( name, join, operator, value, value2 ) { ; }
/**
* Return the name of this search filter.
* @return {string}
*
* @method
* @memberOf nlobjSearchFilter
*
* @since 2007.0
*/
nlobjSearchFilter.prototype.getName = function( ) { ; }
/**
* Return the join id for this search filter.
* @return {string}
*
* @method
* @memberOf nlobjSearchFilter
*
* @since 2008.1
*/
nlobjSearchFilter.prototype.getJoin = function( ) { ; }
/**
* Return the filter operator used.
* @return {string}
*
* @method
* @memberOf nlobjSearchFilter
*
* @since 2008.2
*/
nlobjSearchFilter.prototype.getOperator = function( ) { ; }
/**
* Return a new instance of nlobjSearchColumn used for column objects used to define search return columns.
*
* @classDescription search column.
* @return {nlobjSearchColumn}
* @constructor
* @param {string} name column name.
* @param {string} join internal ID for joined search where this column is defined
* @param {string} summary
*
* @since 2007.0
*/
function nlobjSearchColumn( name, join, summary ) { ; }
/**
* return the name of this search column.
* @return {string}
*
* @method
* @memberOf nlobjSearchColumn
* @since 2008.1
*/
nlobjSearchColumn.prototype.getName = function( ) { ; }
/**
* return the join id for this search column.
* @return {string}
*
* @method
* @memberOf nlobjSearchColumn
* @since 2008.1
*/
nlobjSearchColumn.prototype.getJoin = function( ) { ; }
/**
* return the label of this search column.
* @return {string}
*
* @method
* @memberOf nlobjSearchColumn
*
* @since 2009.1
*/
nlobjSearchColumn.prototype.getLabel = function( ) { ; }
/**
* return the summary type (avg,group,sum,count) of this search column.
* @return {string}
*
* @method
* @memberOf nlobjSearchColumn
* @since 2008.1
*/
nlobjSearchColumn.prototype.getSummary = function( ) { ; }
/**
* return formula for this search column.
* @return {string}
*
* @method
* @memberOf nlobjSearchColumn
*
* @since 2009.2
*/
nlobjSearchColumn.prototype.getFormula = function( ) { ; }
/**
* return nlobjSearchColumn sorted in either ascending or descending order.
* @return {nlobjSearchColumn}
* @param {boolean} sort if not set, defaults to false, which returns column data in ascending order.
*
* @method
* @memberOf nlobjSearchColumn
*
* @since 2010.1
*/
nlobjSearchColumn.prototype.setSort = function( order ) { ; }
/**
* Return a new instance of nlobjSearchResult used for search result row object.
*
* @classDescription Class definition for interacting with the results of a search operation
* @return {nlobjSearchResult}
* @constructor
*/
function nlobjSearchResult( ) { ; }
/**
* return the internalId for the record returned in this row.
* @method
* @memberOf nlobjSearchResult
* @return {int}
*/
nlobjSearchResult.prototype.getId = function( ) { ; }
/**
* return the recordtype for the record returned in this row.
* @method
* @memberOf nlobjSearchResult
* @return {string}
*/
nlobjSearchResult.prototype.getRecordType = function( ) { ; }
/**
* return the value for this nlobjSearchColumn.
* @param {nlobjSearchColumn} column search result column
* @return {string}
*
* @method
* @memberOf nlobjSearchResult
*
* @since 2009.1
*/
nlobjSearchResult.prototype.getValue = function( column ) { ; }
/**
* return the value for a return column specified by name, join ID, and summary type.
* @param {string} name the name of the search column
* @param {string} join the join ID for the search column
* @param {string} summary summary type specified for this column
* @return {string}
*
* @method
* @memberOf nlobjSearchResult
*
* @since 2008.1
*/
nlobjSearchResult.prototype.getValue = function( name, join, summary ) { ; }
/**
* return the text value for this nlobjSearchColumn if it's a select field.
* @param {nlobjSearchColumn} column search result column
* @return {string}
*
* @method
* @memberOf nlobjSearchResult
*
* @since 2009.1
*/
nlobjSearchResult.prototype.getText = function( column ) { ; }
/**
* return the text value of this return column if it's a select field.
* @param {string} name the name of the search column
* @param {string} join the join ID for the search column
* @param {string} summary summary type specified for this column
* @return {string}
*
* @method
* @memberOf nlobjSearchResult
*
* @since 2008.1
*/
nlobjSearchResult.prototype.getText = function( name, join, summary ) { ; }
/**
* return an array of all nlobjSearchColumn objects returned in this search.
* @return {nlobjSearchColumn[]}
*
* @method
* @memberOf nlobjSearchResult
*
* @since 2009.2
*/
nlobjSearchResult.prototype.getAllColumns = function( ) { ; }
/**
* Return a new instance of nlobjContext used for user and script context information.
*
* @classDescription Utility class providing information about the current user and the script runtime.
* @return {nlobjContext}
* @constructor
*/
function nlobjContext( ) { ; }
/**
* return the name of the current user.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getName = function( ) { ; }
/**
* return the internalId of the current user.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getUser = function( ) { ; }
/**
* return the internalId of the current user's role.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getRole = function( ) { ; }
/**
* return the script ID of the current user's role.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2008.2
*/
nlobjContext.prototype.getRoleId = function( ) { ; }
/**
* return the internalId of the current user's center type.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2008.2
*/
nlobjContext.prototype.getRoleCenter = function( ) { ; }
/**
* return the email address of the current user.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getEmail = function( ) { ; }
/**
* return the internal ID of the contact logged in on behalf of a customer, vendor, or partner. It returns -1 for non-contact logins
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.1
*/
nlobjContext.prototype.getContact = function( ) { ; }
/**
* return the account ID of the current user.
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getCompany = function( ) { ; }
/**
* return the internalId of the current user's department.
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getDepartment = function( ) { ; }
/**
* return the internalId of the current user's location.
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getLocation = function( ) { ; }
/**
* return the internalId of the current user's subsidiary.
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getSubsidiary = function( ) { ; }
/**
* return the execution context for this script: webServices|csvImport|client|userInterface|scheduledScript|portlet|suitelet|debugger|custommassupdate
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getExecutionContext = function( ) { ; }
/**
* return the amount of usage units remaining for this script.
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2007.0
*/
nlobjContext.prototype.getRemainingUsage = function( ) { ; }
/**
* return true if feature is enabled, false otherwise
* @param {string} name
* @return {boolean}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getFeature = function( name ) { ; }
/**
* return current user's permission level (0-4) for this permission
* @param {string} name
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getPermission = function( name ) { ; }
/**
* return system or script preference selection for current user
* @param {string} name
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getPreference = function( name ) { ; }
/**
* return value of session object set by script
* @param {string} name
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getSessionObject = function( name ) { ; }
/**
* set the value of a session object using a key.
* @param {string} name
* @param {string} value
* @return {void}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.setSessionObject = function( name, value ) { ; }
/**
* return an array containing the names of all keys used to set session objects
* @return {string[]}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getAllSessionObjects = function() { ; }
/**
* return the NetSuite version for the current account
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getVersion = function( ) { ; }
/**
* return the environment that the script is executing in: SANDBOX, PRODUCTION, BETA, INTERNAL
* @since 2008.2
*/
nlobjContext.prototype.getEnvironment = function( ) { ; }
/**
* return the logging level for the current script execution. Not supported in CLIENT scripts
* @since 2008.2
*/
nlobjContext.prototype.getLogLevel = function( ) { ; }
/**
* return the script ID for the current script
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getScriptId = function( ) { ; }
/**
* return the deployment ID for the current script
* @return {string}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getDeploymentId = function( ) { ; }
/**
* return the % complete specified for the current scheduled script execution
* @return {int}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.getPercentComplete = function( ) { ; }
/**
* set the % complete for the current scheduled script execution
* @param {float} ct the percentage of records completed
* @return {void}
*
* @method
* @memberOf nlobjContext
*
* @since 2009.2
*/
nlobjContext.prototype.setPercentComplete = function( pct ) { ; }
/**
* return a system/script setting. Types are SCRIPT, SESSION, FEATURE, PERMISSION
*
* @param {string} type
* @param {string} name
* @since 2007.0
* @deprecated
*/
nlobjContext.prototype.getSetting = function( type, name ) { ; }
/**
* set a system/script setting. Only supported type is SESSION
*
* @param {string} type
* @param {string} name
* @param {string} value
* @since 2007.0
* @deprecated
*/
nlobjContext.prototype.setSetting = function( type, name, value ) { ; }
/**
* return an Object containing name/value pairs of color groups to their corresponding RGB hex color based on the currenly logged in user's color them preferences.
* @return {Object}
*
* @method
* @memberOf nlobjContext
*
* @since 2010.1
*/
nlobjContext.prototype.getColorPreferences = function() { ; }
/**
* Return a new instance of nlobjError used system or user-defined error object.
*
* @classDescription Encapsulation of errors thrown during script execution.
* @return {nlobjError}
* @constructor
*/
function nlobjError( ) { ; }
/**
* return the error db ID for this error (if it was an unhandled unexpected error).
* @return {string}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getId = function( ) { ; }
/**
* return the error code for this system or user-defined error.
* @return {string}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getCode = function( ) { ; }
/**
* return the error description for this error.
* @return {string}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getDetails = function( ) { ; }
/**
* return a stacktrace containing the location of the error.
* @return {string[]}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getStackTrace = function( ) { ; }
/**
* return the userevent script name where this error was thrown.
* @return {string}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getUserEvent = function( ) { ; }
/**
* return the internalid of the record if this error was thrown in an aftersubmit script.
* @return {int}
*
* @method
* @memberOf nlobjError
*
* @since 2008.2
*/
nlobjError.prototype.getInternalId = function( ) { ; }
/**
* Return a new instance of nlobjServerResponse..
*
* @classDescription Contains the results of a server response to an outbound Http(s) call.
* @return {nlobjServerResponse}
* @constructor
*
* @since 2008.1
*/
function nlobjServerResponse( ) { ; }
/**
* return the Content-Type header in response
* @return {string}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getContentType = function( ) { ; }
/**
* return the value of a header returned.
* @param {string} name the name of the header to return
* @return {string}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getHeader = function(name) { ; }
/**
* return all the values of a header returned.
* @param {string} name the name of the header to return
* @return {string[]}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getHeaders = function(name) { ; }
/**
* return an Array of all headers returned.
* @return {string[]}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getAllHeaders = function( ) { ; }
/**
* return the response code returned.
* @return {int}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getCode = function( ) { ; }
/**
* return the response body returned.
* @return {string}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getBody = function( ) { ; }
/**
* return the nlobjError thrown via a client call to nlapiRequestURL.
* @return {nlobjError}
*
* @method
* @memberOf nlobjServerResponse
*
* @since 2008.1
*/
nlobjServerResponse.prototype.getError = function( ) { ; }
/**
* Return a new instance of nlobjResponse used for scripting web responses in Suitelets
*
* @classDescription Accessor to Http response made available to Suitelets.
* @return {nlobjResponse}
* @constructor
*/
function nlobjResponse( ) { ; }
/**
* add a value for a response header.
* @param {string} name of header
* @param {string} value for header
* @return {void}
*
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.addHeader = function( name, value ) { ; }
/**
* set the value of a response header.
* @param {string} name of header
* @param {string} value for header
* @return {void}
*
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.setHeader = function( name, value ) { ; }
/**
* return the value of a response header.
* @param {string} name of header
* @return {string}
*
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.getHeader = function( ) { ; }
/**
* return an Array of all response header values for a header
* @param {string} name of header
* @return {string[]}
*
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.getHeaders = function( name ) { ; }
/**
* return an Array of all response headers
* @return {Object}
*
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.getAllHeaders = function( ) { ; }
/**
* suppress caching for this response.
* @return {void}
*
* @method
* @memberOf nlobjResponse
*
* @since 2009.1
*/
nlobjResponse.prototype.sendNoCache = function( ) { ; }
/**
* sets the content type for the response (and an optional filename for binary output).
*
* @param {string} type the file type i.e. plainText, word, pdf, htmldoc (see list of media item types)
* @param {string} filename the file name
* @param {string} disposition Content Disposition used for streaming attachments: inline|attachment
* @return {void}
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.setContentType = function( type, filename, disposition ) { ; }
/**
* sets the redirect URL for the response. all URLs must be internal unless the Suitelet is being executed in an "Available without Login" context
* at which point it can use type "external" to specify an external url via the subtype arg
*
* @param {string} type type specifier for URL: suitelet|tasklink|record|mediaitem|external
* @param {string} subtype subtype specifier for URL (corresponding to type): scriptid|taskid|recordtype|mediaid|url
* @param {string} [id] internal ID specifier (sub-subtype corresponding to type): deploymentid|n/a|recordid|n/a
* @param {string} [pagemode] string specifier used to configure page (suitelet: external|internal, tasklink|record: edit|view)
* @param {Object} [parameters] Object used to specify additional URL parameters as name/value pairs
* @return {void}
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.sendRedirect = function( type, subtype, id, pagemode, parameters ) { ; }
/**
* write information (text/xml/html) to the response.
*
* @param {string} output
* @return {void}
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.write = function( output ) { ; }
/**
* write line information (text/xml/html) to the response.
*
* @param {string} output
* @return {void}
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.writeLine = function( output ) { ; }
/**
* write a UI object page.
*
* @param {Object} pageobject page UI object: nlobjList|nlobjAssistant|nlobjForm|nlobjDashboard
* @return {void}
* @method
* @memberOf nlobjResponse
*
* @since 2008.2
*/
nlobjResponse.prototype.writePage = function( pageobject ) { ; }
/**
* Return a new instance of nlobjRequest used for scripting web requests in Suitelets
*
* @classDescription Accessor to Http request data made available to Suitelets
* @return {nlobjRequest}
* @constructor
*/
function nlobjRequest( ) { ; }
/**
* return the value of a request parameter.
*
* @param {string} name parameter name
* @return {string}
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getParameter = function( name ) { ; }
/**
* return the values of a request parameter as an Array.
*
* @param {string} name parameter name
* @return {string[]}
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getParameterValues = function( name ) { ; }
/**
* return an Object containing all the request parameters and their values.
* @return {Object}
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getAllParameters = function( ) { ; }
/**
* return the value of a sublist value.
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {int} line sublist line number
* @return {string}
*
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getLineItemValue = function( group, name, line ) { ; }
/**
* return the number of lines in a sublist.
* @param {string} group sublist name
* @return {int}
*
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getLineItemCount = function( group ) { ; }
/**
* return the value of a request header.
* @param {string} name
* @return {string}
*
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getHeader = function( name ) { ; }
/**
* return an Object containing all the request headers and their values.
* @return {Object}
*
* @method
* @memberOf nlobjRequest
*
* @since 2008.2
*/
nlobjRequest.prototype.getAllHeaders = function( ) { ; }
/**
* return the value of an uploaded file.
* @param {string} name file field name
* @return {nlobjFile}
*
* @method
* @memberOf nlobjRequest
*
* @since 2009.1
*/
nlobjRequest.prototype.getFile = function( name ) { ; }
/**
* return an Object containing field names to file objects for all uploaded files.
* @return {Object}
*
* @method
* @memberOf nlobjRequest
*
* @since 2009.1
*/
nlobjRequest.prototype.getAllFiles = function( ) { ; }
/**
* return the body of the POST request
* @return {string}
*
* @method
* @memberOf nlobjRequest
* @since 2008.1
*/
nlobjRequest.prototype.getBody = function( ) { ; }
/**
* return the URL of the request
* @return {string}
*
* @method
* @memberOf nlobjRequest
* @since 2008.1
*/
nlobjRequest.prototype.getURL = function( ) { ; }
/**
* return the METHOD of the request
* @return {string}
*
* @method
* @memberOf nlobjRequest
* @since 2008.1
*/
nlobjRequest.prototype.getMethod = function( ) { ; }
/**
* Return a new instance of nlobjPortlet used for scriptable dashboard portlet.
*
* @classDescription UI Object used for building portlets that are displayed on dashboard pages
* @return {nlobjPortlet}
* @constructor
*/
function nlobjPortlet( ) { ; }
/**
* set the portlet title.
*
* @param {string} title
* @since 2008.2
*/
nlobjPortlet.prototype.setTitle = function( title ) { ; }
/**
* set the entire contents of the HTML portlet (will be placed inside a <TD>...</TD>).
*
* @param {string} html
* @since 2008.2
*/
nlobjPortlet.prototype.setHtml = function( html ) { ; }
/**
* add a column (nlobjColumn) to this LIST portlet and return it.
*
* @param {string} name column name
* @param {string} type column type
* @param {string} label column label
* @param {string} [align] column alignment
* @since 2008.2
*/
nlobjPortlet.prototype.addColumn = function( name, type, label, align ) { ; }
/**
* add an Edit column (nlobjColumn) to the left of the column specified (supported on LIST portlets only).
*
* @param {nlobjColumn} column
* @param {boolean} showView should Edit|View instead of Edit link
* @param {string} [showHref] column that evaluates to T or F that determines whether to disable the edit|view link per-row.
* @return {nlobjColumn}
*
* @since 2008.2
*/
nlobjPortlet.prototype.addEditColumn = function( column, showView, showHref ) { ; }
/**
* add a row (nlobjSearchResult or Array of name-value pairs) to this LIST portlet.
*
* @param {string[]|nlobjSearchResult} row
* @since 2008.2
*/
nlobjPortlet.prototype.addRow = function( row ) { ; }
/**
* add multiple rows (Array of nlobjSearchResults or name-value pair Arrays) to this LIST portlet.
*
* @param {string[][]|nlobjSearchResult[]} rows
* @since 2008.2
*/
nlobjPortlet.prototype.addRows = function( rows ) { ; }
/**
* add a field (nlobjField) to this FORM portlet and return it.
*
* @param {string} name field name
* @param {string} type field type
* @param {string} [label] field label
* @param {string, int} [source] script ID or internal ID for source list (select and multiselects only) -or- radio value for radio fields
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjPortlet.prototype.addField = function( name,type,label,source ) { ; }
/**
* add a FORM submit button to this FORM portlet.
*
* @param {string} url URL that this form portlet will POST to
* @param {string} [label] label for submit button (defaults to Save)
* @since 2008.2
*/
nlobjPortlet.prototype.setSubmitButton = function( url, label ) { ; }
/**
* add a line (containing text or simple HTML) with optional indenting and URL to this LINKS portlet.
*
* @param {string} text data to output to line
* @param {string} [url] URL if this line should be clickable (if NULL then line will not be clickable)
* @param {int} indent # of indents to insert before text
* @since 2008.2
*/
nlobjPortlet.prototype.addLine = function( text, url, indent ) { ; }
/**
* Return a new instance of nlobjList used for scriptable list page.
*
* @classDescription UI Object page type used for building lists
* @return {nlobjList}
* @constructor
*/
function nlobjList( ) { ; }
/**
* set the page title.
*
* @param {string} title
* @since 2008.2
*/
nlobjList.prototype.setTitle = function( title ) { ; }
/**
* set the global style for this list: grid|report|plain|normal.
*
* @param {string} style overall style used to render list
* @since 2008.2
*/
nlobjList.prototype.setStyle = function( style ) { ; }
/**
* set the Client SuiteScript used for this page.
*
* @param {string, int} script script ID or internal ID for global client script used to enable Client SuiteScript on page
* @since 2008.2
*/
nlobjList.prototype.setScript = function( script ) { ; }
/**
* add a column (nlobjColumn) to this list and return it.
*
* @param {string} name column name
* @param {string} type column type
* @param {string} label column label
* @param {string} [align] column alignment
* @return {nlobjColumn}
*
* @since 2008.2
*/
nlobjList.prototype.addColumn = function( name, type, label, align ) { ; }
/**
* add an Edit column (nlobjColumn) to the left of the column specified.
*
* @param {nlobjColumn} column
* @param {boolean} showView should Edit|View instead of Edit link
* @param {string} [showHref] column that evaluates to T or F that determines whether to disable the edit|view link per-row.
* @return {nlobjColumn}
*
* @since 2008.2
*/
nlobjList.prototype.addEditColumn = function( column, showView, showHref ) { ; }
/**
* add a row (Array of name-value pairs or nlobjSearchResult) to this portlet.
*
* @param {string[], nlobjSearchResult} row data used to add a single row
* @since 2008.2
*/
nlobjList.prototype.addRow = function( row ) { ; }
/**
* add multiple rows (Array of nlobjSearchResults or name-value pair Arrays) to this portlet.
*
* @param {string[][], nlobjSearchResult[]} rows data used to add multiple rows
* @since 2008.2
*/
nlobjList.prototype.addRows = function( rows ) { ; }
/**
* add a button (nlobjButton) to the footer of this page.
*
* @param {string} name button name
* @param {string} label button label
* @param {string} script button script (function name)
* @since 2008.2
*/
nlobjList.prototype.addButton = function( name, label, script ) { ; }
/**
* add a navigation cross-link to the page.
*
* @param {string} type page link type: crosslink|breadcrumb
* @param {string} title page link title
* @param {string} url URL for page link
* @since 2008.2
*/
nlobjList.prototype.addPageLink = function( type, title, url ) { ; }
/**
* Return a new instance of nlobjForm used for scriptable form page.
*
* @classDescription UI Object page type used for building basic data entry forms.
* @return {nlobjForm}
* @constructor
*/
function nlobjForm( ) { ; }
/**
* set the page title.
*
* @param {string} title
* @since 2008.2
*/
nlobjForm.prototype.setTitle = function( title ) { ; }
/**
* set additional title Html. INTERNAL ONLY
*
* @param {string} title
* @since 2008.2
*/
nlobjForm.prototype.addTitleHtml = function( html ) { ; }
/**
* set the Client Script definition used for this page.
*
* @param {string, int} script script ID or internal ID for global client script used to enable Client SuiteScript on page
* @since 2008.2
*/
nlobjForm.prototype.setScript = function( script ) { ; }
/**
* set the values for all the fields on this form.
*
* @param {Object} values Object containing field name/value pairs
* @since 2008.2
*/
nlobjForm.prototype.setFieldValues = function( values ) { ; }
/**
* add a navigation cross-link to the page.
*
* @param {string} type page link type: crosslink|breadcrumb
* @param {string} title page link title
* @param {string} url URL for page link
* @since 2008.2
*/
nlobjForm.prototype.addPageLink = function( type, title, url ) { ; }
/**
* add a button to this form.
*
* @param {string} name button name
* @param {string} label button label
* @param {string} script button script (function name)
* @return {nlobjButton}
*
* @since 2008.2
*/
nlobjForm.prototype.addButton = function( name, label, script ) { ; }
/**
* get a button from this form by name.
* @param {string} name
* @return {nlobjButton}
*
* @method
* @memberOf nlobjForm
*
* @since 2009.2 add
*/
nlobjForm.prototype.getButton = function( name ) { ; }
/**
* add a reset button to this form.
*
* @param {string} [label] label for this button. defaults to "Reset"
* @return {nlobjButton}
*
* @since 2008.2
*/
nlobjForm.prototype.addResetButton = function( label ) { ; }
/**
* add a submit button to this form.
*
* @param {string} [label] label for this submit button. defaults to "Save"
* @return {nlobjButton}
*
* @since 2008.2
*/
nlobjForm.prototype.addSubmitButton = function( label ) { ; }
/**
* add a tab (nlobjTab) to this form and return it.
*
* @param {string} name tab name
* @param {string} label tab label
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.addTab = function( name, label ) { ; }
/**
* add a field (nlobjField) to this form and return it.
*
* @param {string} name field name
* @param {string} type field type
* @param {string} [label] field label
* @param {string, int} [source] script ID or internal ID for source list (select and multiselects only) -or- radio value for radio fields
* @param {string} [tab] tab name that this field will live on. If empty then the field is added to the main section of the form (immediately below the title bar)
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjForm.prototype.addField = function( name,type,label,sourceOrRadio,tab ) { ; }
/**
* add a subtab (nlobjTab) to this form and return it.
*
* @param {string} name subtab name
* @param {string} label subtab label
* @param {string} [tab] parent tab that this subtab lives on. If empty, it is added to the main tab.
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.addSubTab = function( name,label,tab ) { ; }
/**
* add a sublist (nlobjSubList) to this form and return it.
*
* @param {string} name sublist name
* @param {string} type sublist type: inlineeditor|editor|list|staticlist
* @param {string} label sublist label
* @param {string} [tab] parent tab that this sublist lives on. If empty, it is added to the main tab
* @return {nlobjSubList}
*
* @since 2008.2
*/
nlobjForm.prototype.addSubList = function( name,type,label,tab ) { ; }
/**
* insert a tab (nlobjTab) before another tab (name).
*
* @param {nlobjTab} tab the tab object to insert
* @param {string} nexttab the name of the tab before which to insert this tab
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.insertTab = function( tab, nexttab ) { ; }
/**
* insert a field (nlobjField) before another field (name).
*
* @param {nlobjField} field the field object to insert
* @param {string} nextfld the name of the field before which to insert this field
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjForm.prototype.insertField = function( field, nextfld ) { ; }
/**
* insert a subtab (nlobjTab) before another subtab or sublist (name).
*
* @param {nlobjTab} subtab the subtab object to insert
* @param {string} nextsubtab the name of the subtab before which to insert this subtab
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.insertSubTab = function( subtab, nextsubtab ) { ; }
/**
* insert a sublist (nlobjSubList) before another subtab or sublist (name).
*
* @param {nlobjSubList} sublist the sublist object to insert
* @param {string} nextsublist the name of the sublist before which to insert this sublist
* @return {nlobjSubList}
*
* @since 2008.2
*/
nlobjForm.prototype.insertSubList = function( sublist, nextsublist ) { ; }
/**
* return a tab (nlobjTab) on this form.
*
* @param {string} name tab name
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.getTab = function( name ) { ; }
/**
* return a field (nlobjField) on this form.
*
* @param {string} name field name
* @param {string} [radio] if this is a radio field, specify which radio field to return based on radio value
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjForm.prototype.getField = function( name, radio ) { ; }
/**
* return a subtab (nlobjTab) on this form.
*
* @param {string} name subtab name
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjForm.prototype.getSubTab = function( name ) { ; }
/**
* return a sublist (nlobjSubList) on this form.
*
* @param {string} name sublist name
* @return {nlobjSubList}
*
* @since 2008.2
*/
nlobjForm.prototype.getSubList = function( name ) { ; }
/**
* add a field group to the form.
* @param {string} name field group name
* @param {string} label field group label
* @param tab
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjForm
*
* @since 2011.1
*/
nlobjForm.prototype.addFieldGroup = function( name, label, tab ) { ; }
/**
* Return a new instance of nlobjAssistant.
*
* @classDescription UI Object page type used to build multi-step "assistant" pages to simplify complex workflows. All data and state for an assistant is tracked automatically
* throughout the user's session up until completion of the assistant.
*
* @return {nlobjAssistant}
* @constructor
*
* @since 2009.2
*/
function nlobjAssistant( ) { ; }
/**
* set the page title.
* @param {string} title
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setTitle = function( title ) { ; }
/**
* set the script ID for Client Script used for this form.
* @param {string, int} script script ID or internal ID for global client script used to enable Client SuiteScript on page
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setScript = function( script ) { ; }
/**
* set the splash screen used for this page.
* @param {string} title splash portlet title
* @param {string} text1 splash portlet content (left side)
* @param {string} [text2] splash portlet content (right side)
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setSplash = function( title, text1, text2 ) { ; }
/**
* show/hide shortcut link. Always hidden on external pages
* @param {boolean} show enable/disable "Add To Shortcut" link on this page
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setShortcut = function(show) { ; }
/**
* set the values for all the fields on this page.
* @param {Object} values Object of field name/value pairs used to set all fields on page
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setFieldValues = function( values ) { ; }
/**
* if ordered, steps are show on left and must be completed sequentially, otherwise steps are shown on top and can be done in any order
* @param {boolean} ordered If true (default assistant behavior) then a navigation order thru the steps/pages will be imposed on the user. Otherwise the user
* will be allowed to navigate across steps/pages in any order they choose.
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setOrdered = function(ordered) { ; }
/**
* if numbered, step numbers are displayed next to the step's label in the navigation area
* @param {boolean} numbered If true (default assistant behavior) step numbers will be displayed next to the step label
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setNumbered = function(numbered) { ; }
/**
* return true if all the steps have been completed.
* @return {boolean}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.isFinished = function( ) { ; }
/**
* mark assistant page as completed and optionally set the rich text to display on completed page.
* @param {string} html completion message (rich text) to display on the "Finish" page
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setFinished = function( html ) { ; }
/**
* return true if the assistant has an error message to display for the current step.
* @return {boolean}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.hasError = function( ) { ; }
/**
* set the error message for the currrent step.
* @param {string} html error message (rich text) to display on the page to the user
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setError = function( html ) { ; }
/**
* mark a step as current. It will be highlighted accordingly when the page is displayed
* @param {nlobjAssistantStep} step assistant step object representing the current step that the user is on.
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.setCurrentStep = function( step ) { ; }
/**
* add a step to the assistant.
* @param {string} name the name of the step
* @param {string} label label used for this step
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.addStep = function( name, label ) { ; }
/**
* add a field to this page and return it.
* @param {string} name field name
* @param {string} type field type
* @param {string} [label] field label
* @param {string, int} [source] script ID or internal ID for source list (select and multiselects only) -or- radio value for radio fields
* @param {string} [group] group name that this field will live on. If empty then the field is added to the main section of the page
* @return {nlobjField}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.addField = function( name,type,label,source, group ) { ; }
/**
* add a sublist to this page and return it. For now only sublists of type inlineeditor are supported
* @param {string} name sublist name
* @param {string} type sublist type (inlineeditor only for now)
* @param {string} label sublist label
* @return {nlobjSubList}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.addSubList = function( name,type,label ) { ; }
/**
* add a field group to the page.
* @param {string} name field group name
* @param {string} label field group label
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.addFieldGroup = function( name, label ) { ; }
/**
* return an assistant step on this page.
* @param {string} name step name
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getStep = function( name ) { ; }
/**
* return a field on this page.
* @param {string} name field name
* @return {nlobjField}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getField = function( name ) { ; }
/**
* return a sublist on this page.
* @param {string} name sublist name
* @return {nlobjSubList}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getSubList = function( name ) { ; }
/**
* return a field group on this page.
* @param {string} name field group name
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getFieldGroup = function( name ) { ; }
/**
* return an array of all the assistant steps for this assistant.
* @return {nlobjAssistantStep[]}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getAllSteps = function( ) { ; }
/**
* return an array of the names of all fields on this page.
* @return {string[]}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getAllFields = function( ) { ; }
/**
* return an array of the names of all sublists on this page .
* @return {string[]}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getAllSubLists = function( ) { ; }
/**
* return an array of the names of all field groups on this page.
* @return {string[]}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getAllFieldGroups = function( ) { ; }
/**
* return the last submitted action by the user: next|back|cancel|finish|jump
* @return {string}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getLastAction = function() { ; }
/**
* return step from which the last submitted action came from
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getLastStep = function() { ; }
/**
* return the next logical step corresponding to the user's last submitted action. You should only call this after
* you have successfully captured all the information from the last step and are ready to move on to the next step. You
* would use the return value to set the current step prior to continuing.
*
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getNextStep = function() { ; }
/**
* return current step set via nlobjAssistant.setCurrentStep(step)
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getCurrentStep = function() { ; }
/**
* return the total number of steps in the assistant
* @return {int}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.getStepCount = function() { ; }
/**
* redirect the user following a user submit operation. Use this to automatically redirect the user to the next logical step.
* @param {nlobjResponse} response the response object used to communicate back to the user's client
* @return {void}
*
* @method
* @memberOf nlobjAssistant
*
* @since 2009.2
*/
nlobjAssistant.prototype.sendRedirect = function(response) { ; }
/**
* Return a new instance of nlobjField used for scriptable form/sublist field.
* This object is READ-ONLY except for scripted fields created via the UI Object API using Suitelets or beforeLoad user events
*
* @classDescription Core descriptor for fields used to define records and also used to build pages and portlets.
* @return {nlobjField}
* @constructor
*/
function nlobjField( ) { ; }
/**
* return field name.
* @return {string}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.getName = function( ) { ; }
/**
* return field label.
* @return {string}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.getLabel = function( ) { ; }
/**
* return field type.
* @return {string}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.getType = function( ) { ; }
/**
* return true if field is hidden.
* @return {boolean}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.isHidden = function( ) { ; }
/**
* return true if field is mandatory.
* @return {boolean}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.isMandatory = function( ) { ; }
/**
* return true if field is disabled.
* @return {boolean}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.isDisabled = function( ) { ; }
/**
* set the label for this field.
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} label
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setLabel = function( label ) { ; }
/**
* set the alias used to set the value for this field. Defaults to field name.
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} alias column used to populate the field (mostly relevant when populating sublist fields)
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setAlias = function( alias ) { ; }
/**
* set the default value for this field.
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} value
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setDefaultValue = function( value ) { ; }
/**
* Disable field via field metadata.
* This method is only supported on scripted fields via the UI Object API
* @param {boolean} disabled if true then field should be disabled.
* @return {nlobjField}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.setDisabled = function( disabled ) { ; }
/**
* make this field mandatory.
* This method is only supported on scripted fields via the UI Object API
*
* @param {boolean} mandatory if true then field becomes mandatory
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setMandatory = function( mandatory ) { ; }
/**
* set the maxlength for this field (only valid for certain field types).
* This method is only supported on scripted fields via the UI Object API
*
* @param {int} maxlength maximum length for this field
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setMaxLength = function( maxlength ) { ; }
/**
* set the display type for this field.
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} type display type: inline|normal|hidden|disabled|readonly|entry
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setDisplayType = function( type ) { ; }
/**
* set the break type (startcol|startrow|none) for this field. startrow is only used for fields with a layout type of outside
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} breaktype break type used to add a break in flow layout for this field: startcol|startrow|none
* @return {nlobjField}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.setBreakType = function( breaktype ) { ; }
/**
* set the layout type and optionally the break type.
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} type layout type: outside|startrow|midrow|endrow|normal
* @param {string} [breaktype] break type: startcol|startrow|none
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setLayoutType = function( type, breaktype ) { ; }
/**
* set the text that gets displayed in lieu of the field value for URL fields.
*
* @param {string} text user-friendly display value in lieu of URL
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setLinkText = function( text ) { ; }
/**
* set the width and height for this field.
* This method is only supported on scripted fields via the UI Object API
*
* @param {int} width
* @param {int} height
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setDisplaySize = function( width, height ) { ; }
/**
* set the amount of emppty vertical space (rows) between this field and the previous field.
* This method is only supported on scripted fields via the UI Object API
*
* @param {int} padding # of empty rows to display above field
* @return {nlobjField}
*
* @since 2008.2
*/
nlobjField.prototype.setPadding = function( padding ) { ; }
/**
* set help text for this field. If inline is set on assistant pages, help is displayed inline below field
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} help field level help content (rich text) for field
* @param {string} [inline] if true then in addition to the popup field help, the help will also be displayed inline below field (supported on assistant pages only)
* @return {nlobjField}
*
* @method
* @memberOf nlobjField
*
* @since 2009.2
*/
nlobjField.prototype.setHelpText = function( help, inline ) { ; }
/**
* add a select option to this field (valid for select/multiselect fields).
* This method is only supported on scripted fields via the UI Object API
*
* @param {string} value internal ID for this select option
* @param {string} text display value for this select option
* @param {boolean} [selected] if true then this select option will be selected by default
* @since 2008.2
*/
nlobjField.prototype.addSelectOption = function( value, text, selected ) { ; }
/**
* Return a new instance of nlobjSubList used for scriptable sublist (sublist).
* This object is READ-ONLY except for instances created via the UI Object API using Suitelets or beforeLoad user events.
*
* @classDescription high level container for defining sublist (many to one) relationships on a record or multi-line data entry UIs on pages.
* @return {nlobjSubList}
* @constructor
*/
function nlobjSubList( ) { ; }
/**
* set the label for this sublist.
* This method is only supported on sublists via the UI Object API
*
* @param {string} label
* @since 2008.2
*/
nlobjSubList.prototype.setLabel = function( label ) { ; }
/**
* set helper text for this sublist.
* This method is only supported on sublists via the UI Object API
*
* @param {string} help
* @since 2008.2
*/
nlobjSubList.prototype.setHelpText = function( help ) { ; }
/**
* set the displaytype for this sublist: hidden|normal.
* This method is only supported on scripted or staticlist sublists via the UI Object API
*
* @param {string} type
* @since 2008.2
*/
nlobjSubList.prototype.setDisplayType = function( type ) { ; }
/**
* set the value of a cell in this sublist.
*
* @param {string} field sublist field name
* @param {int} line line number (1-based)
* @param {string} value sublist value
*
* @method
* @memberOf nlobjSubList
*
* @since 2008.2
*/
nlobjSubList.prototype.setLineItemValue = function( field, line, value ) { ; }
/**
* set the value of a matrix cell in this sublist.
* @param {string} field matrix field name
* @param {int} line line number (1-based)
* @param {int} column matrix column index (1-based)
* @param {string} value matrix field value
* @return {void}
*
* @method
* @memberOf nlobjSubList
*
* @since 2009.2
*/
nlobjSubList.prototype.setLineItemMatrixValue = function( field, line, column, value ) { ; }
/**
* set values for multiple lines (Array of nlobjSearchResults or name-value pair Arrays) in this sublist.
* Note that this method is only supported on scripted sublists via the UI Object API
*
* @param {string[][], nlobjSearchResult[]} values
* @since 2008.2
*/
nlobjSubList.prototype.setLineItemValues = function( values ) { ; }
/**
* Return the number of lines in a sublist.
*
* @param {string} group sublist name
*
* @method
* @memberOf nlobjSubList
* @since 2010.1
*/
nlobjSubList.prototype.getLineItemCount = function( group ) { ; }
/**
* add a field (column) to this sublist.
*
* @param {string} name field name
* @param {string} type field type
* @param {string} label field label
* @param {string, int} [source] script ID or internal ID for source list used for this select field
* @return {nlobjField}
*
* @method
* @memberOf nlobjSubList
*
* @since 2008.2
*/
nlobjSubList.prototype.addField = function( name,type,label,source ) { ; }
/**
* designate a field on sublist that must be unique across all lines (only supported on sublists of type inlineeditor, editor).
* @param {string} fldnam the name of a field on this sublist whose value must be unique across all lines
* @return {nlobjField}
*
* @method
* @memberOf nlobjSubList
*
* @since 2009.2
*/
nlobjSubList.prototype.setUniqueField = function( fldnam ) { ; }
/**
* add a button to this sublist.
*
* @param {string} name button name
* @param {string} label button label
* @param {string} script button script (function name)
* @return {nlobjButton}
*
* @method
* @memberOf nlobjSubList
*
* @since 2008.2
*/
nlobjSubList.prototype.addButton = function( name, label, script ) { ; }
/**
* add "Refresh" button to sublists of type "staticlist" to support manual refreshing of the sublist (without entire page reloads) if it's contents are very volatile
* @return {nlobjButton}
*
* @method
* @memberOf nlobjSubList
*
* @since 2009.2
*/
nlobjSubList.prototype.addRefreshButton = function( ) { ; }
/**
* add "Mark All" and "Unmark All" buttons to this sublist of type "list".
*
* @method
* @memberOf nlobjSubList
*
* @since 2008.2
*/
nlobjSubList.prototype.addMarkAllButtons = function( ) { ; }
/**
* Return a new instance of nlobjColumn used for scriptable list column.
*
* @classDescription Class definition for columns used on lists and list portlets.
* @return {nlobjColumn}
* @constructor
*/
function nlobjColumn( ) { ; }
/**
* set the header name for this column.
*
* @param {string} label the label for this column
*
* @method
* @memberOf nlobjColumn
*
* @since 2008.2
*/
nlobjColumn.prototype.setLabel = function( label ) { ; }
/**
* set the base URL (optionally defined per row) for this column.
*
* @param {string} value the base URL or a column in the datasource that returns the base URL for each row
* @param {boolean} perRow if true then the 1st arg is expected to be a column in the datasource
*
* @method
* @memberOf nlobjColumn
*
* @since 2008.2
*/
nlobjColumn.prototype.setURL = function( value, perRow ) { ; }
/**
* add a URL parameter (optionally defined per row) to this column's URL.
*
* @param {string} param the name of a parameter to add to URL
* @param {string} value the value of the parameter to add to URL -or- a column in the datasource that returns the parameter value for each row
* @param {boolean} [perRow] if true then the 2nd arg is expected to be a column in the datasource
*
* @method
* @memberOf nlobjColumn
*
* @since 2008.2
*/
nlobjColumn.prototype.addParamToURL = function( param, value, perRow ) { ; }
/**
* Return a new instance of nlobjTab used for scriptable tab or subtab.
*
* @classDescription high level grouping for fields on a data entry form (nlobjForm).
* @return {nlobjTab}
* @constructor
*/
function nlobjTab( ) { ; }
/**
* set the label for this tab or subtab.
*
* @param {string} label string used as label for this tab or subtab
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjTab.prototype.setLabel = function( label ) { ; }
/**
* set helper text for this tab or subtab.
*
* @param {string} help inline help text used for this tab or subtab
* @return {nlobjTab}
*
* @since 2008.2
*/
nlobjTab.prototype.setHelpText = function( help ) { ; }
/**
* Return a new instance of nlobjAssistantStep.
*
* @classDescription assistant step definition. Used to define individual steps/pages in multi-step workflows.
* @return {nlobjAssistantStep}
* @constructor
*
* @since 2009.2
*/
function nlobjAssistantStep( ) { ; }
/**
* set the label for this assistant step.
* @param {string} label display label used for this assistant step
* @return {void}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.setLabel = function( label ) { ; }
/**
* set helper text for this assistant step.
* @param {string} help inline help text to display on assistant page for this step
* @return {nlobjAssistantStep}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.setHelpText = function( help ) { ; }
/**
* return the index of this step in the assistant page (1-based)
* @return {int} the index of this step in the assistant (1-based) based on the order in which the steps were added.
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getStepNumber = function( ) { ; }
/**
* return the value of a field entered by the user during this step.
* @param {string} name field name
* @return {string}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getFieldValue = function( name ) { ; }
/**
* return the selected values of a multi-select field as an Array entered by the user during this step.
* @param {string} name multi-select field name
* @return {string[]}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getFieldValues = function( name ) { ; }
/**
* return the number of lines previously entered by the user in this step (or -1 if the sublist does not exist).
* @param {string} group sublist name
* @return {int}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getLineItemCount = function( group ) { ; }
/**
* return the value of a sublist field entered by the user during this step.
* @param {string} group sublist name
* @param {string} name sublist field name
* @param {int} line sublist (1-based)
* @return {string}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getLineItemValue = function(group, name, line) { ; }
/**
* return an array of the names of all fields entered by the user during this step.
* @return {string[]}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getAllFields = function( ) { ; }
/**
* return an array of the names of all sublists entered by the user during this step.
* @return {string[]}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getAllLineItems = function( ) { ; }
/**
* return an array of the names of all sublist fields entered by the user during this step
* @param {string} group sublist name
* @return {string[]}
*
* @method
* @memberOf nlobjAssistantStep
*
* @since 2009.2
*/
nlobjAssistantStep.prototype.getAllLineItemFields = function( group ) { ; }
/**
* Return a new instance of nlobjFieldGroup (currently only supported on nlobjAssistant pages)
*
* @classDescription object used for grouping fields on pages (currently only supported on assistant pages).
* @return {nlobjFieldGroup}
* @constructor
*
* @since 2009.2
*/
function nlobjFieldGroup( ) { ; }
/**
* set the label for this field group.
* @param {string} label display label for field group
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjFieldGroup
*
* @since 2009.2
*/
nlobjFieldGroup.prototype.setLabel = function( label ) { ; }
/**
* set collapsibility property for this field group.
*
* @param {boolean} collapsible if true then this field group is collapsible
* @param {boolean} [defaultcollapsed] if true and the field group is collapsible, collapse this field group by default
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjFieldGroup
*
* @since 2009.2
*/
nlobjFieldGroup.prototype.setCollapsible = function( collapsible, defaultcollapsed ) { ; }
/**
* set singleColumn property for this field group.
*
* @param {boolean} singleColumn if true then this field group is displayed in single column
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjFieldGroup
*
* @since 2011.1
*/
nlobjFieldGroup.prototype.setSingleColumn = function( singleColumn ) { ; }
/**
* set showBorder property for this field group.
*
* @param {boolean} showBorder if true then this field group shows border including label of group
* @return {nlobjFieldGroup}
*
* @method
* @memberOf nlobjFieldGroup
*
* @since 2011.1
*/
nlobjFieldGroup.prototype.setShowBorder = function( showBorder ) { ; }
/**
* Return a new instance of nlobjButton.
*
* @classDescription buttons used for triggering custom behaviors on pages.
* @return {nlobjButton}
* @constructor
*
* @since 2009.2
*/
function nlobjButton( ) { ; }
/**
* set the label for this button.
* @param {string} label display label for button
* @return {nlobjButton}
*
* @method
* @memberOf nlobjButton
*
* @since 2008.2
*/
nlobjButton.prototype.setLabel = function( label ) { ; }
/**
* disable or enable button.
* @param {boolean} disabled if true then this button should be disabled on the page
* @return {nlobjButton}
*
* @method
* @memberOf nlobjButton
*
* @since 2008.2
*/
nlobjButton.prototype.setDisabled = function( disabled ) { ; }
/**
* Return a new instance of nlobjSelectOption.
*
* @classDescription select|radio option used for building select fields via the UI Object API and for describing select|radio fields.
* @return {nlobjSelectOption}
* @constructor
*
* @since 2009.2
*/
function nlobjSelectOption( ) { ; }
/**
* return internal ID for select option
* @return {string}
*
* @method
* @memberOf nlobjSelectOption
*
* @since 2009.2
*/
nlobjSelectOption.prototype.getId = function( ) { ; }
/**
* return display value for select option.
* @return {string}
*
* @method
* @memberOf nlobjSelectOption
*
* @since 2009.2
*/
nlobjSelectOption.prototype.getText = function( ) { ; }
|
var terrace = require('../'),
crel = require('crel');
var styles = crel('style');
styles.innerHTML = [
'html{font-size:18px;font-family:Arial;}',
'footer{position:fixed;bottom:0;left:0;right:0;height:30px; background:rgba(0,0,0,0.5);border:solid 1px red;}',
'nav{display: none; position:fixed;bottom:0;top:0;right:0;width:30px; background:rgba(0,0,0,0.5);border:solid 1px red;}',
'button{position:fixed;bottom:10px;margin-right:10px;margin-bottom:10px;height:50px;width:150px;}',
'.menu{position:absolute;top:60%;margin:10px;min-height:100px;min-width:150px;background:green;overflow-y:auto;}',
'.menu .item{border: solid 1px black;}'
].join('');
var footer = crel('footer', 'A footer, perchance?'),
floatingButton = crel('button', 'Commence!'),
nav = crel('nav', 'Navigate laterally'),
menu = crel('div', { class: 'menu' },
crel('h3', 'Some menu that has items'),
Array.apply(null, { length: 10 }).map((item, index) =>
crel('div', { class: 'item' }, index)
)
);
function animate(){
footer.style.height = String(Math.sin(Date.now() / 1000) * 100 + 100) + 'px';
nav.style.width = String(Math.sin(Date.now() / 3000) * 50 + 50) + 'px';
nav.style.display = Math.sin(Date.now() / 1000) > 0 ? 'initial' : 'none';
menu.style.top = String(Math.sin(Date.now() / 3000) * 10 + 70) + '%';
menu.style.left = String(Math.sin(Date.now() / 3000) * 40 + 40) + '%';
requestAnimationFrame(animate);
}
animate();
terrace(footer, 0, {
attach: ['left', 'right', 'bottom'],
displace: ['above']
});
var navTerrace = terrace(nav, 1, {
attach: ['right', 'bottom', 'top'],
displace: ['left']
});
terrace(floatingButton, 2, {
attach: ['right', 'bottom'],
displace: ['left']
});
terrace(menu, 3, {
autoPosition: true,
retract: ['bottom', 'right']
});
window.addEventListener('load', function(){
crel(document.body,
styles,
menu,
floatingButton,
nav,
footer
);
}); |
'use strict';
var assert = require('assert');
var controller = require('./../component/controller');
describe('Controller', function() {
var ctrl;
beforeEach(function() {
ctrl = controller();
});
afterEach(function() {
ctrl = null;
});
it('can add', function() {
assert.equal(ctrl.add(2, 3), 5);
assert.equal(ctrl.add('2', '3'), 5);
});
it('can multiply', function() {
assert.equal(ctrl.multiply(2, 3), 6);
assert.equal(ctrl.multiply('2', '3'), 6);
});
it('can subtract', function() {
assert.equal(ctrl.subtract(3, 2), 1);
assert.equal(ctrl.subtract('3', '2'), 1);
});
// Todo: Write asserts for extreme cases such as:
// - missing argument
// - non numeric type
}); |
/**
* 后期再提供解析当前数据库结构,根据sql语句反解析
*/
var Vue = require('lib/vue');
module.exports = Vue.extend({
template: __inline('main.html'),
data: function() {
return {
stepItems: [{
target: '#tab1',
title: '基础配置'
}, {
target: '#tab2',
title: '数据库配置'
}, {
target: '#tab3',
title: '新增页'
}, {
target: '#tab4',
title: 'Confirm'
}],
rulesOptions: {
fieldName: {
required: true
},
dbName: {
required: true
},
type: {
required: true
}
},
fieldName: '', // 字段名称
cnName: '', // 中文名称
state: '1', // 字段状态
remark: '', // 备注
isDb: true, // 是否为数据库字段
dbName: '', // 数据库中字段名称
dbTemplate: '', // 数据库字段模版,用于快速设定常用的字段
type: 'varchar', // 类型
length: 0, // 长度,只有varchar、char、int类型时有必要设置 TODO 默认值待优化
defaultVal: '', // 默认值
property: '', // 属性,如果是id,需要定义为UNSIGNED
isNotNull: true, // 是否非空
isAutoIncrease: false, // 是否自增
isKey: false, // 是否主键
isUnique: false, // 是否唯一
isForeignKey: false, // 是否外键
comment: '', // 数据库注释
isInList: true, // 是否在列表页中出现
isInAdd: false, // 是否在新增页中出现
isInModify: false, // 是否在修改页中出现
isInDetail: false, // 是否在详情页中出现
isInDelete: false, // 是否在删除页中出现
};
},
props: {
'title': String,
'codingId': {
required: true,
type: Number
}
},
methods: {
/**
* 点击取消按钮后,触发的一个事件,用于通知父组件关闭本页面,恢复初始状态
*/
backToInit: function() {
this.$dispatch('backtoinit');
},
},
ready: function() {
console.log('save... ready!');
}
});
|
<r-stylesheet href="css/screen.css"></r-stylesheet>
<r-stylesheet href="css/retool.css"></r-stylesheet>
<div class="app-content">
<h1>Server Default</h1>
<r-body></r-body>
</div>
==
class Application extends Template {
btnHello_onclick(){
var msg = Controllers.Hello.sayHello("Retool Developer");
alert(msg);
}
}
==
{} |
var Slider = (function () {
var $container = $('#ps-container'),
// the items (description elements for the slides/products)
$items = $container.children('div.ps-slides'),
itemsCount = $items.length,
$slidewrapper = $container.children('div.ps-slidewrapper'),
// the slides (product images)
$slidescontainer = $slidewrapper.find('div.ps-slides'),
$slides = $slidescontainer.children('div'),
// navigation arrows
$navprev = $slidewrapper.find('nav > a.ps-prev'),
$navnext = $slidewrapper.find('nav > a.ps-next'),
// current index for items and slides
current = 0,
// checks if the transition is in progress
isAnimating = false,
// support for CSS transitions
support = Modernizr.csstransitions,
// transition end event
// https://github.com/twitter/bootstrap/issues/2870
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
// its name
transEndEventName = transEndEventNames[Modernizr.prefixed('transition')],
init = function () {
// show first item
var $currentItem = $items.eq(current),
$currentSlide = $slides.eq(current),
initCSS = {
top: 0,
zIndex: 999
};
$currentItem.css(initCSS);
$currentSlide.css(initCSS);
// update nav images
updateNavImages();
// initialize some events
initEvents();
},
updateNavImages = function () {
// updates the background image for the navigation arrows
var configPrev = (current < 0) ? $slides.eq(current - 1 ).css('background-image') : $slides.eq(itemsCount - 1).css('background-image'),
configNext = (current > itemsCount - 1 ) ? $slides.eq(current + 1 ).css('background-image') : $slides.eq(0).css('background-image');
$navprev.css('background-image', configPrev);
$navnext.css('background-image', configNext);
},
initEvents = function () {
$navprev.on('click', function (event) {
if (!isAnimating) {
slide('prev');
}
return false;
});
$navnext.on('click', function (event) {
if (!isAnimating) {
slide('next');
}
return false;
});
// transition end event
$items.on(transEndEventName, removeTransition);
$slides.on(transEndEventName, removeTransition);
},
removeTransition = function () {
isAnimating = false;
$(this).removeClass('ps-move');
},
slide = function (dir) {
isAnimating = true;
var $currentItem = $items.eq(current),
$currentSlide = $slides.eq(current);
// update current value
if (dir === 'next') {
(current < 0) ? ++current : --current ;
} else if (dir === 'prev') {
(current > 0) ? --current : current = itemsCount + 3;
}
// new item that will be shown
var $newItem = $items.eq(current),
// new slide that will be shown
$newSlide = $slides.eq(current);
// position the new item up or down the viewport depending on the direction
$newItem.css({
top: (dir === 'next') ? '-100%' : '100%',
zIndex: 999
});
$newSlide.css({
top: (dir === 'next') ? '100%' : '-100%',
zIndex: 999
});
setTimeout(function () {
// move the current item and slide to the top or bottom depending on the direction
$currentItem.addClass('ps-move').css({
top: (dir === 'next') ? '100%' : '-100%',
zIndex: 1
});
$currentSlide.addClass('ps-move').css({
top: (dir === 'next') ? '-100%' : '100%',
zIndex: 1
});
// move the new ones to the main viewport
$newItem.addClass('ps-move').css('top', 0);
$newSlide.addClass('ps-move').css('top', 0);
// if no CSS transitions set the isAnimating flag to false
if (!support) {
isAnimating = false;
}
}, 0);
// update nav images
updateNavImages();
};
return {
init: init
};
})(); |
$(document).ready(function()
{
$(".inputmask").maskMoney({prefix:'', allowNegative: false, thousands:',', affixesStay: false, precision:0});
$(".inputmask").change(function(){
var records = {
};
var ID = $(this).data('id');
records["nilai"] = $(this).val();
$.post(base_url + "/panggarankegiatan/update/" + ID, records, function(response){
if (response.status === 'success')
{
} else {
alert("Data gagal disimpan");
}
});
});
}) |
import App from './App';
import './App.css';
export default App; |
Ext.define("JS.numerojournal.AdvancedSearch", {
extend: "Xfr.Component",
requires: [],
config: {
slimscroll:false
},
initialize: function () {
console.log("initializing advanced search");
var me = this;
me.on({
afterrendertpl: {
scope: me,
fn: "onAfterRenderTpl"
}
});
this.callParent();
//$('#form_pme').select2({
// ajax: select2AjaxConfig('api_v1_get_pmes'),
// escapeMarkup: function (markup) {
// return markup;
// },
// placeholder: "Sélection PME",
// allowClear: true,
// minimumInputLength: 1,
// templateResult: function (data) {
// if (null != data && undefined != data) {
// if (data.rso) {
// return data.id + '-' + data.rso;
// }
// else {
// return data.text;
// }
// }
// return null;
// },
// templateSelection: function (data) {
// if (null != data && undefined != data) {
// if (data.rso) {
// return data.id + '-' + data.rso;
// }
// else {
// return data.text;
// }
// }
// return null;
// }
//});
},
onAfterRenderTpl: function (me) {
var me = this;
//console.log("after render tpl filter form");
$("#filter-all-date-debut").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
endDate: "+0d",
startView: 1,
maxViewMode: 0,
todayBtn: "linked",
todayHighlight: true
});
$("#filter-all-date-fin").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
endDate: "+0d",
startView: 1,
maxViewMode: 0,
todayBtn: "linked",
todayHighlight: true
});
}
});
|
var gulp = require('gulp');
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var externalLibs = [
"react",
"reflux"
];
var customOpts ={
entries: './src/App.jsx',
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
var b = watchify(browserify(opts));
//Transform
b.transform(babelify.configure({
compact: false,
only: '/src/',
plugins: ["object-assign"]
}));
//Remove external libraries from the build process
externalLibs.forEach(function(lib) {
b.external(lib);
});
gulp.task('browser-bundle',bundle);
b.on('update',bundle);
b.on('log', gutil.log);
function bundle() {
return b.transform(babelify.configure({
compact: false,
only: '/src/',
plugins: ["object-assign"]
}))
.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
// optional, remove if you dont want sourcemaps
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
// Add transformation tasks to the pipeline here.
.pipe(sourcemaps.write('./')) // writes .map file
.pipe(gulp.dest('./dist'));
}
gulp.task('browser-vendor',function () {
var browserifyVendor = browserify({
debug: true
});
externalLibs.forEach(function(lib) {
browserifyVendor.require(lib);
});
return browserifyVendor.bundle()
.pipe(source('vendor.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest("./dist"));
});
|
import {PolymerElement, html} from "@polymer/polymer"
import template from "./app-search-result.html"
export default class AppSearchResult extends PolymerElement {
static get template() {
return html([template]);
}
static get properties() {
return {
item : {
type : Object,
value : () => {},
observer : '_onItemUpdate'
},
latestRelease : {
type : String,
value : ''
}
}
}
/**
* @method _onItemUpdate
* @description called when item property updates
*/
_onItemUpdate() {
if( !this.item ) return;
if( this.item.releases.length === 0 ) {
return this.latestRelease = 'No releases';
}
this.latestRelease = this.item.releases[this.item.releases.length-1].name;
}
}
customElements.define('app-search-result', AppSearchResult); |
/**
* Created by DubenskiyAA on 29.07.2016.
*/
"use strict";
angular.module('asPkpApp.myResizer.directive', [])
.directive("myResizer", function ($window, $document, $log, $timeout) {
function linker($scope, $element, $attr) {
var timeoutId;
// вверх-вниз
if ($attr.orientation === 'vertical') {
timeoutId = $timeout(function () {
var sliderElemY = document.getElementById('slider-y'),
topContent = document.getElementById('' + $attr.topContent),
bottomContent = document.getElementById('' + $attr.bottomContent);
// устанавливаю первоначальный отступ полосы прокрутки
var topContentCoords = getCoords(topContent);
sliderElemY.style.top = topContent.clientHeight + +$attr.indent + 16 + 'px';
sliderElemY.style.left = topContentCoords.left + (topContent.clientWidth / 2) + 'px';
sliderElemY.onmousedown = function (event) {
// получаю координаты
var sliderElemCoords = getCoords(sliderElemY);
// https://learn.javascript.ru/article/drag-and-drop/ball_shift.png
var sliderShiftY = event.pageY - sliderElemCoords.top;
document.onmousemove = function (event) {
// $attr.indent - отступ от края экрана до родительского блока
var newSliderElemTop = event.pageY - sliderShiftY - $attr.indent;
// ограничители
if (newSliderElemTop > +$attr.max) {
newSliderElemTop = $attr.max;
// $log.warn('max');
}
if (newSliderElemTop < +$attr.min) {
newSliderElemTop = $attr.min;
// $log.warn('min');
}
sliderElemY.style.top = +newSliderElemTop + +$attr.indent + 'px';
topContent.style.height = +newSliderElemTop + 'px';
// bottomContent.style.top = +newBottomContentTop + 'px';
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
$element.on('$destroy', function () {
$timeout.cancel(timeoutId);
});
};
return false; // disable selection start (cursor change)
}
}, 100);
} else if ($attr.orientation === 'horizontal') {
var sliderElemX = document.getElementById('slider-x'),
leftContent = document.getElementById('' + $attr.leftContent),
rightContent = document.getElementById('' + $attr.rightContent),
parentDiv = document.getElementById('parentDiv');
sliderElemX.style.left = parseInt((leftContent.clientWidth * 100) / parentDiv.clientWidth) + '%';
rightContent.style.width = 99 - parseInt(sliderElemX.style.left) + '%';
sliderElemX.onmousedown = function (event) {
// получаю координаты
var sliderElemCoords = getCoords(sliderElemX);
var sliderShiftX = event.pageX - sliderElemCoords.left;
document.onmousemove = function (event) {
// $attr.indent - отступ от края экрана до родительского блока
var newSliderElemLeft = event.pageX - sliderShiftX;
// ограничители
if (newSliderElemLeft > +$attr.max) {
newSliderElemLeft = $attr.max;
}
if (newSliderElemLeft < +$attr.min) {
newSliderElemLeft = $attr.min;
}
sliderElemX.style.left = parseInt((newSliderElemLeft * 100) / parentDiv.clientWidth) + '%';
leftContent.style.width = parseInt((newSliderElemLeft * 100) / parentDiv.clientWidth) + '%';
rightContent.style.width = 99 - parseInt((newSliderElemLeft * 100) / parentDiv.clientWidth) + '%';
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
};
return false; // disable selection start (cursor change)
}
}
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
// $log.warn(box);
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset,
bottom: box.bottom + pageYOffset
};
}
}
return {
restrict: 'EA',
link: linker
};
}
);
|
goog.provide('gmfapp.objectediting');
goog.require('gmf.Themes');
goog.require('gmf.TreeManager');
/** @suppress {extraRequire} */
goog.require('gmf.layertreeComponent');
/** @suppress {extraRequire} */
goog.require('gmf.mapDirective');
/** @suppress {extraRequire} */
goog.require('gmf.objecteditingComponent');
goog.require('gmf.ObjectEditingManager');
goog.require('ngeo.ToolActivate');
/** @suppress {extraRequire} */
goog.require('ngeo.proj.EPSG21781');
goog.require('ol.Collection');
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.OSM');
goog.require('ol.source.Vector');
/** @type {!angular.Module} **/
gmfapp.module = angular.module('gmfapp', ['gmf']);
/**
* @param {gmf.ObjectEditingManager} gmfObjectEditingManager The gmf
* ObjectEditing manager service.
* @param {gmf.Themes} gmfThemes The gmf themes service.
* @param {gmf.TreeManager} gmfTreeManager gmf Tree Manager service.
* @param {ngeo.ToolActivate.Mgr} ngeoToolActivateMgr Ngeo ToolActivate manager
* service.
* @constructor
* @ngInject
*/
gmfapp.MainController = function(gmfObjectEditingManager, gmfThemes,
gmfTreeManager, ngeoToolActivateMgr) {
/**
* @type {gmf.TreeManager}
* @private
*/
this.gmfTreeManager_ = gmfTreeManager;
gmfThemes.loadThemes();
const projection = ol.proj.get('EPSG:21781');
projection.setExtent([485869.5728, 76443.1884, 837076.5648, 299941.7864]);
/**
* @type {ol.source.Vector}
* @private
*/
this.vectorSource_ = new ol.source.Vector({
wrapX: false
});
/**
* @type {ol.layer.Vector}
* @private
*/
this.vectorLayer_ = new ol.layer.Vector({
source: this.vectorSource_
});
/**
* @type {ol.Collection.<ol.Feature>}
* @export
*/
this.sketchFeatures = new ol.Collection();
/**
* @type {ol.layer.Vector}
* @private
*/
this.sketchLayer_ = new ol.layer.Vector({
source: new ol.source.Vector({
features: this.sketchFeatures,
wrapX: false
})
});
/**
* @type {ol.Map}
* @export
*/
this.map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: 'EPSG:21781',
resolutions: [200, 100, 50, 20, 10, 5, 2.5, 2, 1, 0.5],
center: [537635, 152640],
zoom: 2
})
});
gmfThemes.getThemesObject().then((themes) => {
if (themes) {
// Add layer vector after
this.map.addLayer(this.vectorLayer_);
this.map.addLayer(this.sketchLayer_);
}
});
/**
* @type {string|undefined}
* @export
*/
this.objectEditingGeomType = gmfObjectEditingManager.getGeomType();
/**
* @type {number|undefined}
* @export
*/
this.objectEditingLayerNodeId = gmfObjectEditingManager.getLayerNodeId();
/**
* @type {boolean}
* @export
*/
this.objectEditingActive = true;
const objectEditingToolActivate = new ngeo.ToolActivate(
this, 'objectEditingActive');
ngeoToolActivateMgr.registerTool(
'mapTools', objectEditingToolActivate, true);
/**
* @type {boolean}
* @export
*/
this.dummyActive = false;
const dummyToolActivate = new ngeo.ToolActivate(
this, 'dummyActive');
ngeoToolActivateMgr.registerTool(
'mapTools', dummyToolActivate, false);
/**
* @type {?ol.Feature}
* @export
*/
this.objectEditingFeature = null;
gmfObjectEditingManager.getFeature().then((feature) => {
this.objectEditingFeature = feature;
if (feature) {
this.vectorSource_.addFeature(feature);
}
});
};
gmfapp.module.controller('MainController', gmfapp.MainController);
|
// Copyright (C) 2012 Orange
//
// 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.
// animated3dobjectstest.js
(function(){
// Test for UIPerfTest
if(!window.UIPerfTest){
alert("Please include uiperftest.js before animated3dobjectstest.js");
return;
}
var self = window.Animated3dObjectsTest = {
frameWidth : 300,
frameHeight : 300,
frameNumber : 0,
constant : "",
objects3d : new Array(),
run : function (label,
prerequisites,
startCB,
stopCB) {
document.addEventListener('DOMContentLoaded',
function (evt) {
document.getElementById("container").style[Modernizr.prefixed('perspective')] = 500;
UIPerfTest.run(label,prerequisites,startCB,stopCB);
},
false);
},
randomPositionObject : function (object) {
object.style['left']= Math.round((Math.random()*(UIPerfTest.contWidth-self.frameWidth)*0.9) + ((UIPerfTest.contHeight-self.frameHeight)*0.05) )+"px";
object.style['top']= Math.round((Math.random()*(UIPerfTest.contHeight-self.frameHeight)*0.9) + ((UIPerfTest.contHeight-self.frameHeight)*0.05) )+"px";
},
add3dColoredFrame : function () {
//self.frameWidth = Math.round((UIPerfTest.contWidth)/5);
//self.frameHeight = Math.round((UIPerfTest.contWidth)/5);
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var frame= document.createElement("div");
frame.style['backgroundColor']= "rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")";
frame.style['width']= self.frameWidth + "px";
frame.style['height']= self.frameHeight + "px";
div.appendChild(frame);
self.randomPositionObject(div);
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
add3dImageFrame : function (url) {
self.frameWidth = Math.round((UIPerfTest.contWidth)/3);
self.frameHeight = Math.round((UIPerfTest.contWidth)/3);
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style[transformStyleProperty] = 'preserve-3d';
div.style['position'] = 'absolute';
var frame= document.createElement("div");
//frame.style['backgroundColor']= "rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")";
frame.style['backgroundImage']= "url("+url+")";
frame.style['backgroundSize']= self.frameWidth + "px " + self.frameHeight + "px";
frame.style['backgroundRepeat']= "no-repeat";
frame.style['width']= self.frameWidth + "px";
frame.style['height']= self.frameHeight + "px";
div.appendChild(frame);
self.randomPositionObject(div);
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
add3dTextFrame : function (text) {
self.frameNumber++;
text= text ? text : "Text " + self.frameNumber + " in CSS3";
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var frame= document.createElement("div");
frame.style['backgroundColor']= "rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")";
frame.style['color']= "rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")";
div.style['padding']= "5px";
div.style['fontSize']= "80px";
div.style['fontWeight']= "bolder";
div.style['verticalAlign']= "middle";
div.style['width']= self.frameWidth + "px";
div.style['height']= self.frameHeight + "px";
frame.innerHTML= text;
div.appendChild(frame);
self.randomPositionObject(div);
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
add3dCardFrame : function (big, number) {
big = big ? big : false;
number = number ? number : ((self.frameNumber++)%54) + 1;
if (big) {
url = '../images/cards_big/card_'+ number +'.png';
self.frameWidth = 388;
self.frameHeight = 560;
}
else {
url = '../images/cards_small/card_'+ number +'.png';
self.frameWidth = 194;
self.frameHeight = 280;
}
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var frame= document.createElement("div");
frame.style['backgroundImage']= "url("+url+")";
frame.style['backgroundRepeat']= "no-repeat";
frame.style['width']= self.frameWidth + "px";
frame.style['height']= self.frameHeight + "px";
div.appendChild(frame);
self.randomPositionObject(div);
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
addCardObject : function (big, number) {
big = big ? big : false;
number = number ? number : ((self.frameNumber++)%54) + 1;
if (big) {
self.frameWidth = 388;
self.frameHeight = 560;
urlFront = '../images/cards_big/card_'+ number +'.png';
urlBack = '../images/cards_big/card_0.png';
}
else {
self.frameWidth = 194;
self.frameHeight = 280;
urlFront = '../images/cards_small/card_'+ number +'.png';
urlBack = '../images/cards_small/card_0.png';
}
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
div.style['width']= self.frameWidth + "px";
div.style['height']= self.frameHeight + "px";
// front picture
var front= document.createElement("div");
front.style['backgroundImage']= "url("+urlFront+")";
front.style['backgroundRepeat']= "no-repeat";
front.style['width']= self.frameWidth + "px";
front.style['height']= self.frameHeight + "px";
front.style[Modernizr.prefixed('backfaceVisibility')] = 'hidden';
div.appendChild(front);
// back picture
var back= document.createElement("div");
back.style['backgroundImage']= "url("+urlBack+")";
back.style['backgroundRepeat']= "no-repeat";
back.style['width']= self.frameWidth + "px";
back.style['height']= self.frameHeight + "px";
back.style[Modernizr.prefixed('backfaceVisibility')] = 'hidden';
back.style[Modernizr.prefixed('transform')] = 'rotateY( 180deg ) translateY( -' + (self.frameHeight) + 'px )';
div.appendChild(back);
self.randomPositionObject(div);
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
moveObject : function (object, move) {
object.style[Modernizr.prefixed('transform')] = self.constant + ' ' + move;
},
makeCarouselObject : function (number, div, text, url, urlMax) {
var index = 0;
var radius = 0;
if (number>=4) {
radius = Math.round(self.frameWidth * number/(Math.PI*2));
for (var i=0;i<number;i++) {
var figure= document.createElement("div");
if (url) {
var urlTmp = url.replace(/#/g,((index++)%urlMax)+1);
figure.style['backgroundImage']= "url("+urlTmp+")";
figure.style['backgroundSize']= self.frameWidth + "px " + self.frameHeight + "px";
figure.style['backgroundRepeat']= "no-repeat";
}
else {
figure.style['backgroundColor']= "rgb("+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+","+Math.round(Math.random()*255)+")";
if (text==true) {
figure.style['lineHeight']= self.frameHeight + "px";
figure.style['verticalAlign']= "middle";
figure.style['fontSize']= "64px";
figure.style['fontWeight']= "bolder";
figure.style['height']= self.frameHeight + "px";
figure.innerHTML = ++index;
}
}
figure.style['width']= self.frameWidth + "px";
figure.style['height']= self.frameHeight + "px";
figure.style['position']= "absolute";
figure.style['background']= "hsla( " + Math.round((360/number)*i) + ", 100%, 50%, 0.8 );";
figure.style[Modernizr.prefixed('transform')]= "translateX( -" + (self.frameWidth/2) + "px ) rotateY( "+ Math.round((360/number)*i) +"deg ) translateZ( "+ radius +"px )";
div.appendChild(figure);
}
self.makeCarouselObject(Math.round(number/2), div, text, url, urlMax);
}
return radius;
},
addColoredCarouselObject : function (number, text) {
number = number ? number : 9;
text = text ? text : false;
self.frameWidth = 300;
self.frameHeight = 300;
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var radius = self.makeCarouselObject(number, div, text);
self.constant = " rotateX( -25deg ) translateZ( -" + radius + "px )";
div.style[Modernizr.prefixed('transform')]= self.constant;
div.style['top']= Math.round(UIPerfTest.contHeight/2 - self.frameHeight/2) + "px";
div.style['left']= Math.round(UIPerfTest.contWidth/2 ) + "px";
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
addCImageCarouselObject : function (number) {
number = number ? number : 9;
self.frameWidth = 194;
self.frameHeight = 280;
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var radius = self.makeCarouselObject(number, div, false, '../images/cards_small/card_#.png', 54);
self.constant = " rotateX( -25deg ) translateZ( -" + radius + "px )";
div.style[Modernizr.prefixed('transform')] = self.constant;
div.style['top']= Math.round(UIPerfTest.contHeight/2 - self.frameHeight/2) + "px";
div.style['left']= Math.round(UIPerfTest.contWidth/2 ) + "px";
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
makeSphereObject : function (number, div, square, text, url, urlMax) {
square = square ? square : false;
text = text ? text : false;
var index = 0;
var radius = 0;
if (number>=4) {
radius = Math.round(self.frameWidth * number/(Math.PI*2));
var maxRotateY = Math.round(number/2);
var maxRotateX = Math.round(number);
var interTop = Math.round(number/4);
var interBottom = Math.round(3*number/4);
for (var ry=0;ry<maxRotateY;ry++) {
var color = "";
for (var rx=0;rx<=maxRotateX;rx++) {
color = "rgb(" + Math.abs(Math.round(128-128*Math.sin(Math.PI*rx*2/number + Math.PI/2))) + "," + Math.abs(Math.round(128-128*Math.cos(Math.PI*rx*2/number - Math.PI))) + "," + Math.abs(Math.round(128-128*Math.sin(Math.PI*rx*2/number))) + ")";
if ((ry!=rx && rx==interTop) || (ry!=0 && rx==interBottom)) {
continue;
}
var figure= document.createElement("div");
if (url) {
var urlTmp = url.replace(/#/g,((index++)%urlMax)+1);
figure.style['backgroundImage']= "url("+urlTmp+")";
figure.style['backgroundSize']= self.frameWidth + "px " + self.frameHeight + "px";
figure.style['backgroundRepeat']= "no-repeat";
figure.style['height']= self.frameHeight + "px";
figure.style['width']= self.frameWidth + "px";
}
else {
figure.style['backgroundColor']= color;
figure.style['height']= self.frameHeight + "px";
figure.style['opacity']= "0.9";
if (text==true) {
figure.style['lineHeight']= self.frameHeight + "px";
figure.style['verticalAlign']= "middle";
figure.style['fontSize']= "64px";
figure.style['fontWeight']= "bolder";
figure.innerHTML = ++index;
}
if (square) {
figure.style['width']= self.frameWidth + "px";
}
else {
if (rx==interTop || rx==interBottom) {
figure.style['width']= self.frameWidth + "px";
figure.style['borderRadius'] = '50%';
}
else {
var width = Math.abs(self.frameWidth*Math.cos(rx*2*Math.PI/number));
figure.style['width']= width + "px";
figure.style['left']= Math.round((self.frameWidth - width) / 2) + "px";
}
}
}
figure.style['position']= "absolute";
figure.style['background']= "hsla( " + Math.round((360/number)*ry) + ", 100%, 50%, 0.8 );";
figure.style[Modernizr.prefixed('transform')] = "translateY( -" + (self.frameHeight/2) + "px ) translateX( -" + (self.frameWidth/2) + "px ) rotateY( "+ Math.round(ry*360/number) +"deg ) rotateX( "+ Math.round(rx*360/number) +"deg ) translateZ( "+ radius +"px )";
div.appendChild(figure);
}
}
}
return radius;
},
addColoredSphereObject : function (number, text) {
number = number ? number : 9;
text = text ? text : false;
self.frameWidth = 300;
self.frameHeight = 300;
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var radius = self.makeSphereObject(number, div, false, text);
self.constant = " rotateX( -45deg ) translateZ( -" + (2*radius) + "px ) translateY( " + (2*radius) + "px )";
div.style[Modernizr.prefixed('transform')]= self.constant;
div.style['top']= Math.round(UIPerfTest.contHeight/2 - self.frameHeight/2) + "px";
div.style['left']= Math.round(UIPerfTest.contWidth/2 ) + "px";
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
addImageSphereObject : function (number) {
number = number ? number : 9;
self.frameWidth = 194;
self.frameHeight = 280;
var div= document.createElement("div");
div.style[Modernizr.prefixed('transition')] = 'all 1s ease-in-out';
div.style[Modernizr.prefixed('transformStyle')] = 'preserve-3d';
div.style['position'] = 'absolute';
var radius = self.makeSphereObject(number, div, true, false, '../images/cards_small/card_#.png', 54);
self.constant = " rotateX( -45deg ) translateZ( -" + (2*radius) + "px ) translateY( " + (2*radius) + "px )";
div.style[Modernizr.prefixed('transform')]= self.constant;
div.style['top']= Math.round(UIPerfTest.contHeight/2 - self.frameHeight/2) + "px";
div.style['left']= Math.round(UIPerfTest.contWidth/2 ) + "px";
UIPerfTest.container.appendChild(div);
self.objects3d.push(div);
},
}
})();
|
Template.rentalProductsSettings.helpers({
packageData: function () {
return ReactionCore.Collections.Packages.findOne({
name: 'reaction-rental-products',
shopId: ReactionCore.getShopId()
});
}
});
AutoForm.hooks({
'rental-products-update-form': {
onSuccess: function (operation, result, template) {
Alerts.removeSeen();
return Alerts.add('Rental Products settings saved.', 'success', {
autoHide: true
});
},
onError: function (operation, error, template) {
Alerts.removeSeen();
return Alerts.add('Rental Products settings update failed. ' + error, 'danger');
}
}
});
|
exports.renderer = function(input, out) {
out.write('[imported-foo] Name: ' + input.name);
}; |
define([], function()
{
var MapManager = function()
{
}
MapManager.extend = bin.extend;
var Class = MapManager.prototype;
Class.init = function()
{
this.require(function(err)
{
if(err)
{
console.log("Initialize map fail");
}
else
{
console.log("Initialize map succeed");
}
});
console.info("Map module initialize");
}
Class.require = function(cb)
{
require(["map!"+bin.globalConfig.mapSDK], function()
{
cb(null);
}, function(err)
{
require.undef(err.requireModules[0]);
cb(err);
});
}
_.extend(Class, Backbone.Events);
return MapManager;
}); |
const db = require('./knex');
const getHappyHoursByLocation = (req, res) => {
const locationId = parseInt(req.params.id, 10);
db('happy_hours')
.where('location_id', locationId)
.select()
.then(happyhours => res.status(200).json({ data: happyhours }))
.catch(error => res.status(500).json({ error }));
};
const addHappyHours = (req, res) => {
const happyHour = req.body;
for (const requiredParameter of ['timeslot', 'location_id']) {
if (!happyHour[requiredParameter]) {
return res.status(422).json({
error: `Missing required parameter of (${requiredParameter}).`
});
}
}
db('happy_hours')
.insert(req.body, '*')
.then(happyHour => res.status(201).json({ data: happyHour }))
.catch(error => res.status(500).json({ error }));
};
const updateHappyHours = (req, res) => {
const id = parseInt(req.params.id, 10);
db('happy_hours')
.update(req.body, '*')
.where('id', id)
.returning('*')
.then(happyHour => {
if (happyHour.length) {
res.status(200).json({ data: happyHour });
} else {
res.status(404).send({
data: {
message: `HappyHour with id (${id}) not found.`
}
});
}
})
.catch(error => console.log(error));
};
const deleteHappyHours = (req, res) => {
const id = parseInt(req.params.id, 10);
db('happy_hours')
.del()
.where('id', id)
.returning('*')
.then(happyHour => {
if (happyHour.length) {
res.status(200).send({
data: {
message: `HappyHour with id (${happyHour[0].id}) was deleted.`
}
});
} else {
res.status(404).send({
data: {
message: `HappyHour with id (${id}) not found.`
}
});
}
})
.catch(error => res.status(500).json({ error }));
};
module.exports = {
getHappyHoursByLocation,
addHappyHours,
updateHappyHours,
deleteHappyHours
};
|
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
const UglifyWebpack = webpack.optimize.UglifyJsPlugin;
module.exports = {
entry: {
'app': './src/main.ts'
},
resolve: {
extensions: ['.js', '.ts'],
},
module: {
rules: [
{
test: /\.ts$/,
use: ['awesome-typescript-loader', 'angular2-template-loader']
},
{
test: /\.html$/,
use: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
use: 'file-loader?name=assets/[name].[hash].[ext]'
},
/*{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap'})
}*/
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
],
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
use: 'raw-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
|
frappe.email_alert = {
setup_fieldname_select: function(frm) {
// get the doctype to update fields
if(!frm.doc.document_type) {
return;
}
frappe.model.with_doctype(frm.doc.document_type, function() {
var get_select_options = function(df) {
return {value: df.fieldname, label: df.fieldname + " (" + __(df.label) + ")"};
}
var fields = frappe.get_doc("DocType", frm.doc.document_type).fields;
var options = $.map(fields,
function(d) { return in_list(frappe.model.no_value_type, d.fieldtype) ?
null : get_select_options(d); });
// set value changed options
frm.set_df_property("value_changed", "options", [""].concat(options));
// set date changed options
frm.set_df_property("date_changed", "options", $.map(fields,
function(d) { return (d.fieldtype=="Date" || d.fieldtype=="Datetime") ?
get_select_options(d) : null; }));
var email_fields = $.map(fields,
function(d) { return d.options == "Email" ?
get_select_options(d) : null; });
// set email recipient options
frappe.meta.get_docfield("Email Alert Recipient", "email_by_document_field",
frm.doc.name).options = ["owner"].concat(email_fields);
});
}
}
frappe.ui.form.on("Email Alert", {
onload: function(frm) {
frm.set_query("document_type", function() {
return {
"filters": {
"istable": 0
}
}
})
},
refresh: function(frm) {
frappe.email_alert.setup_fieldname_select(frm);
},
document_type: function(frm) {
frappe.email_alert.setup_fieldname_select(frm);
},
view_properties: function(frm) {
frappe.route_options = {doc_type:frm.doc.document_type};
frappe.set_route("Form", "Customize Form");
}
});
|
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);
};
import { bindable, containerless } from 'aurelia-framework';
var MdcToolbarRow = (function () {
function MdcToolbarRow() {
}
__decorate([
bindable(),
__metadata("design:type", String)
], MdcToolbarRow.prototype, "class", void 0);
MdcToolbarRow = __decorate([
containerless()
], MdcToolbarRow);
return MdcToolbarRow;
}());
export { MdcToolbarRow };
|
define('ace/mode/gherkin-sr_cyrl', function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var MatchingBraceOutdent = require("ace/mode/matching_brace_outdent").MatchingBraceOutdent;
var Range = require("ace/range").Range;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var GherkinHighlightRules = function()
{
this.$rules = {
"start" : [
{
token : "comment",
regex : "^\\s*#.*$"
},
{
token : "comment.doc.tag",
regex : "@[^@\\\r\\\n\\\t ]+"
},
{
token : "keyword.with_children",
regex : "^\\s*(?:Сценарији|Примери|Концепт|Скица|Структура сценарија|Пример|Сценарио|Позадина|Основа|Контекст|Особина|Могућност|Функционалност):",
},
{
token : "keyword",
regex : "^\\s*(?:Али |И |Онда |Кад |Када |Задати |Задате |Задато |\\* )"
},
{
token : "string", // multi line """ string start
regex : '^\\s*"{3}.*$',
next : "qqstring"
},
],
"qqstring" : [ {
token : "string", // multi line """ string end
regex : '(?:[^\\\\]|\\\\.)*?"{3}',
next : "start"
}, {
token : "string",
regex : '.+'
}
]
};
};
oop.inherits(GherkinHighlightRules, TextHighlightRules);
var Mode = function()
{
this.$tokenizer = new Tokenizer(new GherkinHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
};
oop.inherits(Mode, TextMode);
(function()
{
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[0].type == "keyword.with_children") {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
'use strict';
var assert = require('assert')
, shimmer = require('shimmer')
, util = require('util')
, Sequelize = require('sequelize')
, errors = require('./errors')
, paranoiaTypes = [
Sequelize.QueryTypes.SELECT,
//Sequelize.QueryTypes.INSERT,
Sequelize.QueryTypes.UPDATE,
Sequelize.QueryTypes.BULKUPDATE,
Sequelize.QueryTypes.BULKDELETE,
Sequelize.QueryTypes.DELETE,
Sequelize.QueryTypes.UPSERT
];
module.exports = function(sequelize, options) {
options = options || {};
if (options.paranoia === false) return;
if (!sequelize.$ssaclParanoia) {
shimmer.wrap(sequelize, 'query', function (original) {
return function (sql, callee, queryOptions, replacements) {
if (arguments.length === 2) {
if (callee instanceof Sequelize.Model) {
queryOptions = {};
} else {
queryOptions = callee;
callee = undefined;
}
}
queryOptions = queryOptions || {};
if (queryOptions.type && paranoiaTypes.indexOf(queryOptions.type) > -1 &&
queryOptions.actor === undefined && queryOptions.paranoia !== false) {
throw new errors.Paranoia();
}
return original.apply(this, arguments);
};
});
sequelize.$ssaclParanoia = true;
}
};
module.exports.Error = errors.Paranoia; |
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var path = require('path');
var fs = require("fs");
var request = require('request');
var ncp = require('ncp').ncp;
ncp.limit = 16;
module.exports = function () {
function transform (file, enc, next) {
var self = this;
var url = "https://raw.github.com/krasimir/absurd/master/client-side/build/absurd.js";
var urlMin = "https://raw.github.com/krasimir/absurd/master/client-side/build/absurd.min.js";
var organicurl = "https://raw.github.com/krasimir/absurd/master/client-side/build/absurd.organic.js";
var organicurlMin = "https://raw.github.com/krasimir/absurd/master/client-side/build/absurd.organic.min.js";
var getAbsurd = function(callback) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.writeFileSync(__dirname + "/../builds/absurd.js", body, {});
request.get(urlMin, function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.writeFileSync(__dirname + "/../builds/absurd.min.js", body, {});
if(callback) callback();
}
});
}
});
}
var getOrganic = function(callback) {
request.get(organicurl, function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.writeFileSync(__dirname + "/../builds/absurd.organic.js", body, {});
request.get(organicurlMin, function (error, response, body) {
if (!error && response.statusCode == 200) {
fs.writeFileSync(__dirname + "/../builds/absurd.organic.min.js", body, {});
if(callback) callback();
}
});
}
});
}
var getTests = function(callback) {
var source = __dirname + '/../node_modules/absurd/client-side/tests';
var destination = __dirname + '/../tests';
var testsIndex = __dirname + '/../tests/index.php';
ncp(source, destination, function (err) {
var indexContent = fs.readFileSync(testsIndex);
indexContent = indexContent.toString().replace(/\/build/g, '/builds');
fs.writeFileSync(testsIndex, indexContent);
callback();
});
}
getAbsurd(function() {
getOrganic(function() {
getTests(next);
});
})
}
return through2.obj(transform);
}; |
$ = require("jquery");
_ = require("underscore");
WT = {
path: document.location.pathname.split("/").pop(),
projectPath: "https://en.wikipedia.org",
api: function(endpoint, params, noPath) {
if(typeof params === "object") {
params = _.extend(params, { norecord: true });
} else {
params = (params + "&norecord=1").replace(/^&/, '');
}
return $.ajax({
url: "/musikanimal/api" + (noPath ? '' : '/' + WT.path) + (endpoint ? "/" + endpoint : ""),
method: "GET",
data: params,
dataType: "JSON"
});
},
replag: function(replag) {
if(!replag) return;
var minutes = Math.round(replag / 60);
if(minutes >= 60) {
var hours = Math.floor(minutes / 60),
leftover = minutes % 60;
return hours + " hour" + (hours > 1 ? "s" : "") +
(leftover > 0 ? " and " + leftover + " minute" + (leftover > 1 ? "s" : "") : "");
} else if(minutes > 2) {
return minutes + " minutes";
} else {
return replag + " seconds";
}
},
updateProgress: function(value, message) {
if(!$("progress")[0]) return;
if(value !== null) {
if(value >= 100) {
$("progress").val(100);
$(".progress-report").text("Complete!");
} else {
$("progress").val(value).show();
$(".progress-report").text(value + "%");
}
if(message) {
$(".loading-text").text(message);
}
} else {
$("progress").val(0).hide();
$(".progress-report").text("");
}
},
wikifyText: function(text, pageName) {
var sectionRegex = new RegExp(/^\/\* (.*?) \*\//),
sectionMatch = sectionRegex.exec(text);
if(sectionMatch) {
var sectionTitle = sectionMatch[1];
text = text.replace(sectionMatch[0],
"<a href='"+WT.projectPath+"/wiki/"+pageName+"#"+sectionTitle.replace(/ /g,"_")+"'>→</a><span class='gray'>"+sectionTitle+":</span> "
);
}
var linkRegex = new RegExp(/\[\[(.*?)\]\]/g), linkMatch;
while(linkMatch = linkRegex.exec(text)) {
var wikilink = linkMatch[1].split("|")[0],
wikitext = linkMatch[1].split("|")[1] || wikilink,
link = "<a href='"+WT.projectPath+"/wiki/"+wikilink+"' class='section-link'>"+wikitext+"</a>";
text = text.replace(linkMatch[0], link);
}
return text;
}
};
$(document).ready(function() {
$("a").on("click", function(e) {
if(e.target.href === "#") e.preventDefault();
});
if(document.location.search.indexOf("username=") !== -1) {
setTimeout(function() {
$("form").trigger("submit");
});
}
$(".about-link").attr("href", "/musikanimal/"+WT.path+"/about");
$(".dropdown-text").on("click", function(e) {
var $selector = $(this).siblings(".dropdown-options");
if($selector.hasClass("open")) {
return;
}
$selector.addClass("open");
e.stopPropagation();
setTimeout(function() {
$(document).one("click.dropdown", function(e) {
$selector.removeClass("open");
});
});
});
$(".dropdown-option").on("click", function() {
var $options = $(this).parents(".dropdown-options");
$("#"+$options.data("select")).val($(this).data("id"));
$options.siblings(".dropdown-text").text($(this).text());
});
$("form").on("submit", function(e) {
e.preventDefault();
$("button").blur();
$(".loading").show();
$(this).addClass("busy");
$(this).find("[type=text]").each(function() {
this.value = this.value.trim();
});
this.params = $(this).serialize();
$.ajax({
url: "/musikanimal/api/uses",
method: 'PATCH',
data : {
tool: WT.path,
type: 'form'
}
});
WT.formSubmit.call(this);
});
if(WT.listeners) WT.listeners();
});
|
// javascript code used with Epic Games HTML5 projects
//
// much of this is for UE4 development purposes.
//
// to create a custom JS file for your project:
// - make a copy of this file - or make one from scratch
// - and put it in: "your project folder"/Build/HTML/GameX.js.template
// ================================================================================
// ================================================================================
// stubbing in missing/un-supported functions
// .../Engine/Source/Runtime/Engine/Private/ActiveSound.cpp
// // for velocity-based effects like doppler
// ParseParams.Velocity = (ParseParams.Transform.GetTranslation() - LastLocation) / DeltaTime;
window.AudioContext = ( window.AudioContext || window.webkitAudioContext || null );
if ( AudioContext ) {
var ue4_hacks = {}; // making this obvious...
ue4_hacks.ctx = new AudioContext();
ue4_hacks.panner = ue4_hacks.ctx.createPanner();
ue4_hacks.panner.__proto__.setVelocity = ( ue4_hacks.panner.__proto__.setVelocity || function(){} );
}
// ================================================================================
// ================================================================================
// project configuration
// Minimum WebGL version that the page needs in order to run. UE4 will attempt to use WebGL 2 if available.
// Set this to 1 to run with a WebGL 1 fallback if the graphical features required by your UE4 project are
// low enough that they do not strictly require WebGL 2.
const requiredWebGLVersion = 1;
const targetOffscreenCanvas = false;
// Add ?webgl1 GET param to explicitly test the WebGL 1 fallback version even if browser does support WebGL 2.
const explicitlyUseWebGL1 = (location.search.indexOf('webgl1') != -1);
// "Project Settings" -> Platforms -> HTML5 -> Packaging -> "Compress files during shipping packaging"
// When hosting UE4 builds live on a production CDN, compression should always be enabled,
// since uncompressed files are too huge to be downloaded over the web.
// Please view tip in "Project Setting" for more information.
const serveCompressedAssets = false;
// "Project Settings" -> Project -> Packaging -> "Use Pak File"
// For the large .data file, there's two ways to manage compression: either UE4 UnrealPak tool can compress it in engine, or
// it can be gzip compressed on disk like other assets. Compressing via UnrealPak has the advantage of storing a smaller data
// file to IndexedDB, whereas gzip compressing to disk has the advantage of starting up the page slightly faster.
// If true, serve out 'UE4Game.data.gz', if false, serve out 'UE4Game.data'.
//const dataFileIsGzipCompressed = false;
console.log("Emscripten version: D:/Program Files/Epic Games/UE_4.23/Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.38.31");
console.log("Emscripten configuration: D:/Program Files/Epic Games/UE_4.23/Engine/Intermediate/Build/HTML5/.emscripten");
// ================================================================================
// *** HTML5 emscripten ***
var Module = {
// state management
infoPrinted: false,
lastcurrentDownloadedSize: 0,
totalDependencies: 0,
dataBytesStoredInIndexedDB: 0, // Track how much data is currently stored in IndexedDB.
assetDownloadProgress: {}, // Track how many bytes of each needed asset has been downloaded so far.
UE4_indexedDBName: 'UE4_assetDatabase_MovingBlocks', // this should be an ascii ID string without special characters that is unique to the project that is being packaged
UE4_indexedDBVersion: 202003281838, // Bump this number to invalidate existing IDB storages in browsers.
};
// ================================================================================
// *** HTML5 UE4 ***
Module.arguments = ['../../../MovingBlocks/MovingBlocks.uproject','-stdout',];
// UE4 Editor or UE4 Frontend with assets "cook on the fly"?
if (location.host != "" && (location.search.indexOf('cookonthefly') != -1)) {
Module.arguments.push("'-filehostIp=" + location.protocol + "//" + location.host + "'");
}
var UE4 = {
on_fatal: function() {
try {
UE4.on_fatal = Module.cwrap('on_fatal', null, ['string', 'string']);
} catch(e) {
UE4.on_fatal = function() {};
}
},
};
// ----------------------------------------
// UE4 error and logging
document.addEventListener('error', function(){document.getElementById('clear_indexeddb').style.display = 'inline-block';}, false);
function addLog(info, color) {
$("#logwindow").append("<h4><small>" + info + " </small></h4>");
}
Module.print = addLog;
Module.printErr = function(text) {
console.error(text);
};
window.onerror = function(e) {
e = e.toString();
if (e.toLowerCase().indexOf('memory') != -1) {
e += '<br>';
if (!heuristic64BitBrowser) e += ' Try running in a 64-bit browser to resolve.';
}
showErrorDialog(e);
}
// ----------------------------------------
// ----------------------------------------
// detect wasm-threads
function detectWasmThreads() {
return WebAssembly.validate(new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60,
0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x01, 0x03, 0x01, 0x01,
0x0a, 0x0b, 0x01, 0x09, 0x00, 0x41, 0x01, 0xfe, 0x10, 0x02, 0x00, 0x1a,
0x0b
]));
}
Module['UE4_MultiThreaded'] = false && detectWasmThreads();
// ================================================================================
// ================================================================================
// emscripten memory system
// Tests if type === 'browser' or type === 'os' is 64-bit or not.
function heuristicIs64Bit(type) {
function contains(str, substrList) { for(var i in substrList) if (str.indexOf(substrList[i]) != -1) return true; return false; }
var ua = (navigator.userAgent + ' ' + navigator.oscpu + ' ' + navigator.platform).toLowerCase();
if (contains(ua, ['wow64'])) return type === 'os'; // 32bit browser on 64bit OS
if (contains(ua, ['x86_64', 'amd64', 'ia64', 'win64', 'x64', 'arm64', 'irix64', 'mips64', 'ppc64', 'sparc64'])) return true;
if (contains(ua, ['i386', 'i486', 'i586', 'i686', 'x86', 'arm7', 'android', 'mobile', 'win32'])) return false;
if (contains(ua, ['intel mac os'])) return true;
return false;
}
var heuristic64BitBrowser = heuristicIs64Bit('browser');
// // For best stability on 32-bit browsers, allocate asm.js/WebAssembly heap up front before proceeding
// // to load any other page content. This mitigates the chances that loading up page assets first would
// // fragment the memory area of the browser process.
// var pageSize = 64 * 1024;
// function alignPageUp(size) { return pageSize * Math.ceil(size / pageSize); }
//
// // The absolute maximum that is possible is one memory page short of 2GB.
// var MAX_MEMORY = Module['UE4_MultiThreaded']
// ? 512 * 1024 * 1024 // multi threaded - non-growable
// : 2048 * 1024 * 1024 - pageSize; // single threaded - growable
//
// // note: 32-bit browsers (single threaded) needs to start at 32MB
// var MIN_MEMORY = Module['UE4_MultiThreaded']
// ? 512 * 1024 * 1024 // multi threaded - non-growable
// : 32 * 1024 * 1024; // single threaded - growable
//
// function allocateHeap() {
// Module['wasmMemory'] = new WebAssembly.Memory({ initial: MIN_MEMORY / pageSize, maximum: MAX_MEMORY / pageSize });
// if (!Module['wasmMemory']||!Module['wasmMemory'].buffer) {
// throw 'Out of memory';
// }
// Module['buffer'] = Module['wasmMemory'].buffer;
// if (Module['buffer'].byteLength < MIN_MEMORY) {
// delete Module['buffer'];
// throw 'Out of memory';
// }
// Module['TOTAL_MEMORY'] = Module['buffer'].byteLength;
// }
// allocateHeap();
// Module['MAX_MEMORY'] = MAX_MEMORY;
//
// function MB(x) { return (x/1024/1024) + 'MB'; }
// console.log('Initial memory size: ' + MB(Module['TOTAL_MEMORY']) + ' (MIN_MEMORY: ' + MB(MIN_MEMORY) + ', MAX_MEMORY: ' + MB(MAX_MEMORY) + ', heuristic64BitBrowser: ' + heuristic64BitBrowser + ', heuristic64BitOS: ' + heuristicIs64Bit('os') + ')');
// ================================================================================
// WebGL
Module['preinitializedWebGLContext'] = null;
Module['canvas'] = document.getElementById('canvas');
function getGpuInfo() {
var gl = Module['preinitializedWebGLContext'];
if (!gl) return '(no GL: ' + Module['webGLErrorReason'] + ')';
var glInfo = '';
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
if (debugInfo) glInfo += gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) + ' ' + gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) + '/';
glInfo += gl.getParameter(gl.VENDOR) + ' ' + gl.getParameter(gl.RENDERER);
glInfo += ' ' + gl.getParameter(gl.VERSION);
glInfo += ', ' + gl.getParameter(gl.SHADING_LANGUAGE_VERSION);
if (Module['softwareWebGL']) glInfo += ' (software)';
return glInfo;
}
function detectWebGL() {
var canvas = targetOffscreenCanvas ? document.createElement("canvas") : (Module['canvas'] || document.createElement("canvas"));
// If you run into problems with WebGL 2, or for quick testing purposes, you can disable UE4
// from using WebGL 2 and revert back to WebGL 1 by setting the following flag to true.
var disableWebGL2 = false;
if (explicitlyUseWebGL1) {
disableWebGL2 = true;
console.log('Disabled WebGL 2 as requested by ?webgl1 GET param.');
}
var names = ["webgl", "experimental-webgl"];
if (disableWebGL2) {
WebGL2RenderingContext = undefined;
} else {
names = ["webgl2"].concat(names);
}
function testError(e) { Module['webGLErrorReason'] = e.statusMessage; };
canvas.addEventListener("webglcontextcreationerror", testError, false);
try {
for(var failIfMajorPerformanceCaveat = 1; failIfMajorPerformanceCaveat >= 0; --failIfMajorPerformanceCaveat) {
for(var i in names) {
try {
var context = canvas.getContext(names[i], {antialias:false,alpha:false,depth:true,stencil:true,failIfMajorPerformanceCaveat:!!failIfMajorPerformanceCaveat});
Module['preinitializedWebGLContext'] = context;
Module['softwareWebGL'] = !failIfMajorPerformanceCaveat;
if (context && typeof context.getParameter == "function") {
if (typeof WebGL2RenderingContext !== 'undefined' && context instanceof WebGL2RenderingContext && names[i] == 'webgl2') {
return 2;
} else {
// We were able to precreate only a WebGL 1 context, remove support for WebGL 2 from the rest of the page execution.
WebGL2RenderingContext = undefined;
return 1;
}
}
} catch(e) { Module['webGLErrorReason'] = e.toString(); }
}
}
} finally {
canvas.removeEventListener("webglcontextcreationerror", testError, false);
if ( targetOffscreenCanvas ) {
delete canvas;
}
}
return 0;
}
// ----------------------------------------
// ----------------------------------------
// canvas - scaling
// Canvas scaling mode should be set to one of: 1=STRETCH, 2=ASPECT, or 3=FIXED.
// This dictates how the canvas size changes when the browser window is resized
// by dragging from the corner.
var canvasWindowedScaleMode = 2 /*ASPECT*/;
// High DPI setting configures whether to match the canvas size 1:1 with
// the physical pixels on the screen.
// For background, see https://www.khronos.org/webgl/wiki/HandlingHighDPI
var canvasWindowedUseHighDpi = true;
// Stores the initial size of the canvas in physical pixel units.
// If canvasWindowedScaleMode == 3 (FIXED), this size defines the fixed resolution
// that the app will render to.
// If canvasWindowedScaleMode == 2 (ASPECT), this size defines only the aspect ratio
// that the canvas will be constrained to.
// If canvasWindowedScaleMode == 1 (STRETCH), these size values are ignored.
var canvasAspectRatioWidth = 1366;
var canvasAspectRatioHeight = 768;
// The resizeCanvas() function recomputes the canvas size on the page as the user changes
// the browser window size.
function resizeCanvas(aboutToEnterFullscreen) {
// Configuration variables, feel free to play around with these to tweak.
var minimumCanvasHeightCssPixels = 480; // the visible size of the canvas should always be at least this high (in CSS pixels)
var minimumCanvasHeightFractionOfBrowserWindowHeight = 0.65; // and also vertically take up this much % of the total browser client area height.
if (aboutToEnterFullscreen && !aboutToEnterFullscreen.type) { // UE4 engine is calling this function right before entering fullscreen?
// If you want to perform specific resolution setup here, do so by setting Module['canvas'].width x Module['canvas'].height now,
// and configure Module['UE4_fullscreenXXX'] fields above. Most of the time, the defaults are good, so no need to resize here.
// Return true here if you want to abort entering fullscreen mode altogether.
return;
}
// The browser called resizeCanvas() to notify that we just entered fullscreen? In that case, we never react, since the strategy is
// to always set the canvas size right before entering fullscreen.
if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
return;
}
var mainArea = document.getElementById('mainarea');
var canvasRect = mainArea.getBoundingClientRect();
// Compute the unconstrained size for the div that encloses the canvas, in CSS pixel units.
var cssWidth = canvasRect.right - canvasRect.left;
var cssHeight = Math.max(minimumCanvasHeightCssPixels, canvasRect.bottom - canvasRect.top, window.innerHeight * minimumCanvasHeightFractionOfBrowserWindowHeight);
if (canvasWindowedScaleMode == 3/*NONE*/) {
// In fixed display mode, render to a statically determined WebGL render target size.
var newRenderTargetWidth = canvasAspectRatioWidth;
var newRenderTargetHeight = canvasAspectRatioHeight;
} else {
// Convert unconstrained render target size from CSS to physical pixel units.
var newRenderTargetWidth = canvasWindowedUseHighDpi ? (cssWidth * window.devicePixelRatio) : cssWidth;
var newRenderTargetHeight = canvasWindowedUseHighDpi ? (cssHeight * window.devicePixelRatio) : cssHeight;
// Apply aspect ratio constraints, if desired.
if (canvasWindowedScaleMode == 2/*ASPECT*/) {
if (cssWidth * canvasAspectRatioHeight > canvasAspectRatioWidth * cssHeight) {
newRenderTargetWidth = newRenderTargetHeight * canvasAspectRatioWidth / canvasAspectRatioHeight;
} else {
newRenderTargetHeight = newRenderTargetWidth * canvasAspectRatioHeight / canvasAspectRatioWidth;
}
}
// WebGL render target sizes are always full integer pixels in size, so rounding is critical for CSS size computations below.
newRenderTargetWidth = Math.round(newRenderTargetWidth);
newRenderTargetHeight = Math.round(newRenderTargetHeight);
}
// Very subtle but important behavior is that the size of a DOM element on a web page in CSS pixel units can be a fraction, e.g. on
// high DPI scaling displays (CSS pixel units are "virtual" pixels). If the CSS size and physical pixel size of the WebGL canvas do
// not correspond to each other 1:1 after window.devicePixelRatio scaling has been applied, the result can look blurry. Therefore always
// first compute the WebGL render target size first in physical pixels, and convert that back to CSS pixels so that the CSS pixel size
// will perfectly align up and the result look clear without scaling applied.
cssWidth = canvasWindowedUseHighDpi ? (newRenderTargetWidth / window.devicePixelRatio) : newRenderTargetWidth;
cssHeight = canvasWindowedUseHighDpi ? (newRenderTargetHeight / window.devicePixelRatio) : newRenderTargetHeight;
// Resize the actual Canvas element. Since this can either be a regular Canvas or an OffscreenCanvas, use an Emscripten API to
// do the resizing, since it needs to be multithreading aware if an OffscreenCanvas is being used. In the case of an OffscreenCanvas,
// the resizing may happen asynchronously.
_emscripten_set_canvas_element_size(Module['canvas'].id, newRenderTargetWidth, newRenderTargetHeight);
// emscripten_set_canvas_element_size_js(Module['canvas'].id, newRenderTargetWidth, newRenderTargetHeight);
Module['canvas'].style.width = cssWidth + 'px';
Module['canvas'].style.height = mainArea.style.height = cssHeight + 'px';
// Tell the engine that the web page has changed the size of the WebGL render target on the canvas (Module['canvas'].width/height).
// This will update the GL viewport and propagate the change throughout the engine.
// If the CSS style size is changed, this function doesn't need to be called.
if (UE_JSlib.UE_CanvasSizeChanged) UE_JSlib.UE_CanvasSizeChanged();
}
Module['UE4_resizeCanvas'] = resizeCanvas;
// Input event hooks: UE4 calls these functions for all input events it receives prior to handling the input event itself.
// Use these functions if you need to override or hook into input handling on JavaScript side.
// Possible return values from these functions:
// 0: UE4 should process this input event, and use the default choice whether to suppress browser default navigation for the event.
// 1: UE4 should process this input event, but not suppress browser default navigation for the event.
// 2: UE4 should process this input event, and suppress browser default navigation for the event.
// 3: UE4 should discard this input event, and use the default choice whether to suppress browser default navigation for the event.
// 4: UE4 should discard this input event, but not suppress browser default navigation for the event.
// 5: UE4 should discard this input event, and suppress browser default navigation for the event.
Module['UE4_keyEvent'] = function(eventType, key, virtualKeyCode, domPhysicalKeyCode, keyEventStruct) { return 0; }
Module['UE4_mouseEvent'] = function(eventType, x, y, button, buttons, mouseEventStruct) { return 0; }
Module['UE4_wheelEvent'] = function(eventType, x, y, button, buttons, deltaX, deltaY, wheelEventStruct) { return 0; }
// ----------------------------------------
// ----------------------------------------
// canvas - fullscreen
// Fullscreen scaling mode behavior (export these to Module object for the engine to read)
// This value is one of:
// 0=NONE: The same canvas size is kept when entering fullscreen without change.
// 1=STRETCH: The canvas is resized to the size of the whole screen, potentially changing aspect ratio.
// 2=ASPECT: The canvas is resized to the size of the whole screen, but retaining current aspect ratio.
// 3=FIXED: The canvas is centered on screen with a fixed resolution.
Module['UE4_fullscreenScaleMode'] = 1;//canvasWindowedScaleMode; // BUG: if using FIXED, fullscreen gets some strange padding on margin...
// When entering fullscreen mode, should UE4 engine resize the canvas?
// 0=No resizing (do it manually in resizeCanvas()), 1=Resize to standard DPI, 2=Resize to highDPI
Module['UE4_fullscreenCanvasResizeMode'] = canvasWindowedUseHighDpi ? 2/*HIDPI*/ : 1/*Standard DPI*/;
// Specifies how canvas is scaled to fullscreen, if not rendering in 1:1 pixel perfect mode.
// One of 0=Default, 1=Nearest, 2=Bilinear
Module['UE4_fullscreenFilteringMode'] = 0;
// ================================================================================
// ================================================================================
// IndexDB
// NOTE: in a future release of UE4 - this whole section WILL GO AWAY (i.e. handled internally)
var enableReadFromIndexedDB = (location.search.indexOf('noidbread') == -1);
var enableWriteToIndexedDB = enableReadFromIndexedDB && (location.search.indexOf('noidbwrite') == -1);
enableReadFromIndexedDB = false;
enableWriteToIndexedDB = false;
if (!enableReadFromIndexedDB) showWarningRibbon('Running with IndexedDB access disabled.');
else if (!enableWriteToIndexedDB) showWarningRibbon('Running in read-only IndexedDB access mode.');
function getIDBRequestErrorString(req) {
try { return req.error ? ('IndexedDB ' + req.error.name + ': ' + req.error.message) : req.result;
} catch(ex) { return null; }
}
function formatBytes(bytes) {
if (bytes >= 1024*1024*1024) return (bytes / (1024*1024*1024)).toFixed(1) + ' GB';
if (bytes >= 1024*1024) return (bytes / (1024*1024)).toFixed(0) + ' MB';
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
return bytes + ' B';
}
function reportDataBytesStoredInIndexedDB(deltaBytes) {
if (deltaBytes === null) Module['dataBytesStoredInIndexedDB'] = 0; // call with deltaBytes == null to report that DB was cleared.
else Module['dataBytesStoredInIndexedDB'] += deltaBytes;
document.getElementById('clear_indexeddb').innerText = 'Clear IndexedDB (' + formatBytes(Module['dataBytesStoredInIndexedDB']) + ')';
}
function deleteIndexedDBStorage(dbName, onsuccess, onerror, onblocked) {
var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (Module['dbInstance']) Module['dbInstance'].close();
if (!dbName) dbName = Module['UE4_indexedDBName'];
var req = idb.deleteDatabase(dbName);
req.onsuccess = function() { console.log('Deleted IndexedDB storage ' + dbName + '!'); reportDataBytesStoredInIndexedDB(null); if (onsuccess) onsuccess(); }
req.onerror = function(evt) {
var errorString = getIDBRequestErrorString(req);
console.error('Failed to delete IndexedDB storage ' + dbName + ', ' + errorString);
evt.preventDefault();
if (onerror) onerror(errorString);
};
req.onblocked = function(evt) {
var errorString = getIDBRequestErrorString(req);
console.error('Failed to delete IndexedDB storage ' + dbName + ', DB was blocked! ' + errorString);
evt.preventDefault();
if (onblocked) onblocked(errorString);
}
}
function storeToIndexedDB(db, key, value) {
return new Promise(function(resolve, reject) {
if (!enableWriteToIndexedDB) return reject('storeToIndexedDB: IndexedDB writes disabled by "?noidbwrite" option');
function fail(e) {
console.error('Failed to store file ' + key + ' to IndexedDB storage! error: ' + e);
if (!Module['idberrorShown']) {
showWarningRibbon('Failed to store file ' + key + ' to IndexedDB, error: ' + e);
Module['idberrorShown'] = true;
}
return reject(e);
}
if (!db) return fail('IndexedDB not available!');
if (location.protocol.indexOf('file') != -1) return reject('Loading via file://, skipping caching to IndexedDB');
try {
var transaction = db.transaction(['FILES'], 'readwrite');
var packages = transaction.objectStore('FILES');
var putRequest = packages.put(value, "file/" + Module.key + '/' + key);
putRequest.onsuccess = function(evt) {
if (value.byteLength || value.length) reportDataBytesStoredInIndexedDB(value.size || value.byteLength || value.length);
resolve(key);
};
putRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(putRequest) || ('IndexedDB request error: ' + evt);
evt.preventDefault();
fail(errorString);
};
} catch(e) {
fail(e);
}
});
}
function fetchFromIndexedDB(db, key) {
return new Promise(function(resolve, reject) {
if (!enableReadFromIndexedDB) return reject('fetchFromIndexedDB: IndexedDB reads disabled by "?noidbread" option');
function fail(e) {
console.error('Failed to read file ' + key + ' from IndexedDB storage! error:');
console.error(e);
if (!Module['idberrorShown']) {
showWarningRibbon('Failed to read file ' + key + ' from IndexedDB, error: ' + e);
Module['idberrorShown'] = true;
}
return reject(e);
}
if (!db) return fail('IndexedDB not available!');
try {
var transaction = db.transaction(['FILES'], 'readonly');
var packages = transaction.objectStore('FILES');
var getRequest = packages.get("file/" + Module.key + '/' + key);
getRequest.onsuccess = function(evt) {
if (evt.target.result) {
var len = evt.target.result.size || evt.target.result.byteLength || evt.target.result.length;
if (len) reportDataBytesStoredInIndexedDB(len);
resolve(evt.target.result);
} else {
// Succeeded to load, but the load came back with the value of undefined, treat that as an error since we never store undefined in db.
reject();
}
};
getRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(getRequest) || ('IndexedDB.get request error: ' + evt);
evt.preventDefault();
fail(errorString);
};
} catch(e) {
fail(e);
}
});
}
function fetchOrDownloadAndStore(db, url, responseType) {
return new Promise(function(resolve, reject) {
fetchFromIndexedDB(db, url)
.then(function(data) { return resolve(data); })
.catch(function(error) {
return download(url, responseType)
.then(function(data) {
// Treat IDB store as separate operation that's not part of the Promise chain.
/*return*/ storeToIndexedDB(db, url, data)
.then(function() { return resolve(data); })
.catch(function(error) {
if ( enableReadFromIndexedDB || enableWriteToIndexedDB ) {
console.error('Failed to store download to IndexedDB! ' + error);
}
return resolve(data); // succeeded download, but failed to store - ignore failure in that case and just proceed to run by calling the success handler.
})
})
.catch(function(error) { return reject(error); })
});
});
}
function openIndexedDB(dbName, dbVersion) {
return new Promise(function(resolve, reject) {
if (!enableReadFromIndexedDB) return reject('openIndexedDB: IndexedDB disabled by "?noidbread" option');
try {
var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var openRequest = idb.open(dbName, dbVersion);
} catch(e) { return reject(e); }
openRequest.onupgradeneeded = function(evt) {
var db = evt.target.result;
if (db.objectStoreNames.contains('FILES')) db.deleteObjectStore('FILES');
db.createObjectStore('FILES');
};
openRequest.onsuccess = function(evt) {
resolve(evt.target.result);
};
openRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(openRequest) || ('IndexedDB request error: ' + evt);
evt.preventDefault();
reject(errorString);
};
});
}
// Module.locateFile() routes asset downloads to either gzip compressed or uncompressed assets.
Module.locateFile = function(name) {
var serveGzipped = serveCompressedAssets;
// When serving from file:// URLs, don't read .gz compressed files, because these files can't be transparently uncompressed.
var isFileProtocol = name.indexOf('file://') != -1 || location.protocol.indexOf('file') != -1;
if (isFileProtocol) {
if (!Module['shownFileProtocolWarning']) {
showWarningRibbon('Attempting to load the page via the "file://" protocol. This only works in Firefox, and even there only when not using compression, so attempting to load uncompressed assets. Please host the page on a web server and visit it via a "http://" URL.');
Module['shownFileProtocolWarning'] = true;
}
serveGzipped = false;
}
// uncompressing very large gzip files may slow down startup times.
// if (!dataFileIsGzipCompressed && name.split('.').slice(-1)[0] == 'data') serveGzipped = false;
return serveGzipped ? (name + 'gz') : name;
};
// see site/source/docs/api_reference/module.rst for details
Module.getPreloadedPackage = function(remotePackageName, remotePackageSize) {
return Module['preloadedPackages'] ? Module['preloadedPackages'][remotePackageName] : null;
}
// ================================================================================
// COMPILER
// ----------------------------------------
// wasm
Module['instantiateWasm'] = function(info, receiveInstance) {
Module['wasmDownloadAction'].then(function(downloadResults) {
taskProgress(TASK_COMPILING);
var wasmInstantiate = WebAssembly.instantiate(downloadResults.wasmModule || new Uint8Array(downloadResults.wasmBytes), info);
return wasmInstantiate.then(function(output) {
var instance = output.instance || output;
var module = output.module;
taskFinished(TASK_COMPILING);
Module['wasmInstantiateActionResolve'](instance);
receiveInstance(instance, module);
// After a successful instantiation, attempt to save the compiled Wasm Module object to IndexedDB.
if (!downloadResults.fromIndexedDB) {
storeToIndexedDB(downloadResults.db, 'wasmModule', module).catch(function() {
// If the browser did not support storing Wasm Modules to IndexedDB, try to store the Wasm instance instead.
return storeToIndexedDB(downloadResults.db, 'wasmBytes', downloadResults.wasmBytes);
});
}
});
}).catch(function(error) {
$ ('#mainarea').empty();
$ ('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert">WebAssembly instantiation failed: <br> ' + error + '</div></div>');
});
return {};
}
// ----------------------------------------
// shaders
function compileShadersFromJson(jsonData) {
var shaderPrograms = [];
if (jsonData instanceof ArrayBuffer) jsonData = new TextDecoder('utf-8').decode(new DataView(jsonData));
var programsDict = JSON.parse(jsonData);
for(var i in programsDict) {
shaderPrograms.push(programsDict[i]);
}
var gl = Module['preinitializedWebGLContext'];
Module['precompiledShaders'] = [];
Module['precompiledPrograms'] = [];
Module['glIDCounter'] = 1;
Module['precompiledUniforms'] = [null];
var promise = new Promise(function(resolve, reject) {
var nextProgramToBuild = 0;
function buildProgram() {
if (nextProgramToBuild >= shaderPrograms.length) {
taskFinished(TASK_SHADERS);
return resolve();
}
var p = shaderPrograms[nextProgramToBuild++];
taskProgress(TASK_SHADERS, {current: nextProgramToBuild, total: shaderPrograms.length });
var program = gl.createProgram();
function lineNumberize(str) {
str = str.split('\n');
for(var i = 0; i < str.length; ++i) str[i] = (i<9?' ':'') + (i<99?' ':'') + (i+1) + ': ' + str[i];
return str.join('\n');
}
var vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, p.vs);
gl.compileShader(vs);
var success = gl.getShaderParameter(vs, gl.COMPILE_STATUS);
var compileLog = gl.getShaderInfoLog(vs);
if (compileLog) compileLog = compileLog.trim();
if (compileLog) console.error('Compiling vertex shader: ' + lineNumberize(p.vs));
if (!success) console.error('Vertex shader compilation failed!');
if (compileLog) console.error('Compilation log: ' + compileLog);
if (!success) return reject('Vertex shader compilation failed: ' + compileLog);
gl.attachShader(program, vs);
Module['precompiledShaders'].push({
vs: p.vs,
shader: vs,
program: program
});
var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, p.fs);
gl.compileShader(fs);
var success = gl.getShaderParameter(fs, gl.COMPILE_STATUS);
var compileLog = gl.getShaderInfoLog(fs);
if (compileLog) compileLog = compileLog.trim();
if (compileLog) console.error('Compiling fragment shader: ' + lineNumberize(p.fs));
if (!success) console.error('Fragment shader compilation failed!');
if (compileLog) console.error('Compilation log: ' + compileLog);
if (!success) return reject('Fragment shader compilation failed: ' + compileLog);
gl.attachShader(program, fs);
Module['precompiledShaders'].push({
fs: p.fs,
shader: fs,
program: program
});
for(var name in p.attribs) {
gl.bindAttribLocation(program, p.attribs[name], name);
}
gl.linkProgram(program);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
var linkLog = gl.getProgramInfoLog(program);
if (linkLog) linkLog = linkLog.trim();
if (linkLog) console.error('Linking shader program, vs: \n' + lineNumberize(p.vs) + ', \n fs:\n' + lineNumberize(p.fs));
if (!success) console.error('Shader program linking failed!');
if (linkLog) console.error('Link log: ' + linkLog);
if (!success) return reject('Shader linking failed: ' + linkLog);
var ptable = {
uniforms: {},
maxUniformLength: 0,
maxAttributeLength: -1,
maxUniformBlockNameLength: -1
};
var GLctx = gl;
var utable = ptable.uniforms;
var numUniforms = GLctx.getProgramParameter(program, GLctx.ACTIVE_UNIFORMS);
for (var i = 0; i < numUniforms; ++i) {
var u = GLctx.getActiveUniform(program, i);
var name = u.name;
ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1);
if (name.indexOf("]", name.length - 1) !== -1) {
var ls = name.lastIndexOf("[");
name = name.slice(0, ls);
}
var loc = GLctx.getUniformLocation(program, name);
var id = Module['glIDCounter']++;
utable[name] = [ u.size, id ];
Module['precompiledUniforms'].push(loc);
if (Module['precompiledUniforms'].length != Module['glIDCounter']) throw 'uniforms array not in sync! ' + Module['precompiledUniforms'].length + ', ' + Module['glIDCounter'];
for (var j = 1; j < u.size; ++j) {
var n = name + "[" + j + "]";
loc = GLctx.getUniformLocation(program, n);
id = Module['glIDCounter']++;
Module['precompiledUniforms'].push(loc);
if (Module['precompiledUniforms'].length != Module['glIDCounter']) throw 'uniforms array not in sync! ' + Module['precompiledUniforms'].length + ', ' + Module['glIDCounter'];
}
}
var e = gl.getError();
if (e) {
console.error('Precompiling shaders got GL error: ' + e);
return reject('Precompiling shaders got GL error: ' + e);
}
Module['precompiledPrograms'].push({
program: program,
programInfos: ptable,
vs: p.vs,
fs: p.fs
});
setTimeout(buildProgram, 0);
}
setTimeout(buildProgram, 0);
})
return promise;
}
// ================================================================================
// download project files and progress handlers
var TASK_DOWNLOADING = 0;
var TASK_COMPILING = 1;
var TASK_SHADERS = 2;
var TASK_MAIN = 3;
var loadTasks = [ 'Downloading', 'Compiling WebAssembly', 'Building shaders', 'Launching engine'];
function taskProgress(taskId, progress) {
var c = document.getElementById('compilingmessage');
if (c) c.style.display = 'block';
else return;
var l = document.getElementById('load_' + taskId);
if (!l) {
var tasks = document.getElementById('loadTasks');
if (!tasks) return;
l = document.createElement('div');
l.innerHTML = '<span id="icon_' + taskId + '" class="glyphicon glyphicon-refresh glyphicon-spin"></span> <span id="load_' + taskId + '"></span>';
tasks.appendChild(l);
l = document.getElementById('load_' + taskId);
}
if (!l.startTime) l.startTime = performance.now();
var text = loadTasks[taskId];
if (progress && progress.total) {
text += ': ' + (progress.currentShow || progress.current) + '/' + (progress.totalShow || progress.total) + ' (' + (progress.current * 100 / progress.total).toFixed(0) + '%)';
} else {
text += '...';
}
l.innerHTML = text;
}
function taskFinished(taskId, error) {
var l = document.getElementById('load_' + taskId);
var icon = document.getElementById('icon_' + taskId);
if (l && icon) {
var totalTime = performance.now() - l.startTime;
if (!error) {
l.innerHTML = loadTasks[taskId] + ' (' + (totalTime/1000).toFixed(2) + 's)';
icon.className = 'glyphicon glyphicon-ok';
}
else {
l.innerHTML = loadTasks[taskId] + ': FAILED! ' + error;
icon.className = 'glyphicon glyphicon-remove';
showErrorDialog(loadTasks[taskId] + ' failed: <br> ' + error);
}
}
}
function reportDownloadProgress(url, downloadedBytes, totalBytes, finished) {
Module['assetDownloadProgress'][url] = {
current: downloadedBytes,
total: totalBytes,
finished: finished
};
var aggregated = {
current: 0,
total: 0,
finished: true
};
for(var i in Module['assetDownloadProgress']) {
aggregated.current += Module['assetDownloadProgress'][i].current;
aggregated.total += Module['assetDownloadProgress'][i].total;
aggregated.finished = aggregated.finished && Module['assetDownloadProgress'][i].finished;
}
aggregated.currentShow = formatBytes(aggregated.current);
aggregated.totalShow = formatBytes(aggregated.total);
if (aggregated.finished) taskFinished(TASK_DOWNLOADING);
else taskProgress(TASK_DOWNLOADING, aggregated);
}
function download(url, responseType) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = responseType || 'blob';
reportDownloadProgress(url, 0, 1);
xhr.onload = function() {
if (xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300)) {
var len = xhr.response.size || xhr.response.byteLength;
reportDownloadProgress(url, len, len, true);
resolve(xhr.response);
} else {
taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onprogress = function(p) {
if (p.lengthComputable) reportDownloadProgress(url, p.loaded, p.total);
};
xhr.onerror = function(e) {
var isFileProtocol = url.indexOf('file://') == 0 || location.protocol.indexOf('file') != -1;
if (isFileProtocol) taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url +'<br>Try using a web server to avoid loading via a "file://" URL.'); // Convert the most common source of errors to a more friendly message format.
else taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
reject({
status: xhr.status || 404,
statusText: xhr.statusText
});
};
xhr.onreadystatechange = function() {
if (xhr.readyState >= xhr.HEADERS_RECEIVED) {
if (url.endsWith('gz') && (xhr.status == 0 || xhr.status == 200)) {
if (xhr.getResponseHeader('Content-Encoding') != 'gzip') {
// A fallback is to set serveCompressedAssets = false to serve uncompressed assets instead, but that is not really recommended for production use, since gzip compression shrinks
// download sizes so dramatically that omitting it for production is not a good idea.
taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' without the necessary HTTP response header "Content-Encoding: gzip" specified!<br>Please configure gzip compression on this asset on the web server to serve gzipped assets!');
xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
xhr.abort();
return reject({
status: 406,
statusText: 'Not Acceptable'
});
}
// After enabling Content-Encoding: gzip, make sure that the appropriate MIME type is being used for the asset, i.e. the MIME
// type should be that of the uncompressed asset, and not the MIME type of the compression method that was used.
if (xhr.getResponseHeader('Content-Type').toLowerCase().indexOf('zip') != -1) {
function expectedMimeType(url) {
if (url.indexOf('.wasm') != -1) return 'application/wasm';
if (url.indexOf('.js') != -1) return 'application/javascript';
return 'application/octet-stream';
}
taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' with incorrect HTTP response header "Content-Type: ' + xhr.getResponseHeader('Content-Type') + '"!<br>Please set the MIME type of the asset to "' + expectedMimeType(url) + '".');
xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
xhr.abort();
return reject({
status: 406,
statusText: 'Not Acceptable'
});
}
}
}
}
xhr.send(null);
});
}
// ================================================================================
// ================================================================================
// UE4 DEFAULT UX TEMPLATE
function showErrorDialog(errorText) {
if ( errorText.indexOf('SyntaxError: ') != -1 ) { // this may be due to caching issue -- otherwise, compile time would have caught this
errorText = "NOTE: attempting to flush cache and force reload...<br>Please standby...";
setTimeout(function() {
location.reload(true);
}, 2000); // 2 seconds
}
console.error('error: ' + errorText);
var existingErrorDialog = document.getElementById('errorDialog');
if (existingErrorDialog) {
existingErrorDialog.innerHTML += '<br>' + errorText;
} else {
$('#mainarea').empty();
$('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert" id="errorDialog">' + errorText + '</div></div>');
}
}
function showWarningRibbon(warningText) {
var existingWarningDialog = document.getElementById('warningDialog');
if (existingWarningDialog) {
existingWarningDialog.innerHTML += '<br>' + warningText;
} else {
$('#buttonrow').prepend('<div class="alert alert-warning centered-axis-x" role="warning" id="warningDialog" style="padding-top:5px; padding-bottom: 5px">' + warningText + '</div></div>');
}
}
// Given a blob, asynchronously reads the byte contents of that blob to an arraybuffer and returns it as a Promise.
function readBlobToArrayBuffer(blob) {
return new Promise(function(resolve, reject) {
var fileReader = new FileReader();
fileReader.onload = function() { resolve(this.result); }
fileReader.onerror = function(e) { reject(e); }
fileReader.readAsArrayBuffer(blob);
});
}
// Asynchronously appends the given script code to DOM. This is to ensure that
// browsers parse and compile the JS code parallel to all other execution.
function addScriptToDom(scriptCode) {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
var blob = (scriptCode instanceof Blob) ? scriptCode : new Blob([scriptCode], { type: 'text/javascript' });
var objectUrl = URL.createObjectURL(blob);
script.src = objectUrl;
script.onload = function() {
script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
URL.revokeObjectURL(objectUrl); // Free up the blob. Note that for debugging purposes, this can be useful to comment out to be able to read the sources in debugger.
resolve();
}
script.onerror = function(e) {
script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
URL.revokeObjectURL(objectUrl);
console.error('script failed to add to dom: ' + e);
console.error(scriptCode);
console.error(e);
// The onerror event sends a DOM Level 3 event error object, which does not seem to have any kind of human readable error reason (https://developer.mozilla.org/en-US/docs/Web/Events/error)
// There is another error event object at https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent, which would have an error reason. Perhaps that error event might sometimes be fired,
// but if not, guess that the error reason was an OOM, since we are dealing with large .js files.
reject(e.message || "(out of memory?)");
}
document.body.appendChild(script);
});
}
// ----------------------------------------
// ----------------------------------------
// Startup task which is run after UE4 engine has launched.
function postRunEmscripten() {
taskFinished(TASK_MAIN);
$("#compilingmessage").remove();
// The default Emscripten provided canvas resizing behavior is not needed,
// since we are controlling the canvas sizes here, so stub those functions out.
Browser.updateCanvasDimensions = function() {};
Browser.setCanvasSize = function() {};
// If you'd like to configure the initial canvas size to render using the resolution
// defined in UE4 DefaultEngine.ini [SystemSettings] r.setRes=WidthxHeight,
// uncomment the following two lines before calling resizeCanvas() below:
// canvasAspectRatioWidth = UE_JSlib.UE_GSystemResolution_ResX();
// canvasAspectRatioHeight = UE_JSlib.UE_GSystemResolution_ResY();
// Configure the size of the canvas and display it.
resizeCanvas();
Module['canvas'].style.display = 'block';
// Whenever the browser window size changes, relayout the canvas size on the page.
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
// The following is needed if game is within an iframe - main window already has focus...
window.focus();
}
Module.postRun = [postRunEmscripten];
// ----------------------------------------
// ----------------------------------------
// MAIN
$(document).ready(function() {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Deduce which version to load up.
var supportsWasm = (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function');
if (!supportsWasm) {
showErrorDialog('Your browser does not support WebAssembly. Please try updating to latest 64-bit browser that supports WebAssembly.<br>Current user agent: ' + navigator.userAgent);
return;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// memory heap
// if (!Module['buffer']) {
// showErrorDialog('Failed to allocate ' + MB(MIN_MEMORY) + ' of linear memory for the WebAssembly heap!');
// return;
// }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// check for webgl and cache it for later (UE_BrowserWebGLVersion() reads this)
Module['WEBGL_VERSION'] = detectWebGL();
console.log(getGpuInfo());
if (!Module['WEBGL_VERSION'] || Module['WEBGL_VERSION'] < requiredWebGLVersion) {
showErrorDialog('Your browser does not support WebGL ' + requiredWebGLVersion + '<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '. Try updating your browser and/or graphics card drivers.<br>Current renderer: ' + getGpuInfo());
return;
}
function shouldBrowserSupportWebGL2() {
var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
if (match) return parseInt(match[1]) >= 51;
}
if (Module['WEBGL_VERSION'] < 2 && !explicitlyUseWebGL1) {
if (shouldBrowserSupportWebGL2()) {
showWarningRibbon('Your GPU does not support WebGL 2. This affects graphics performance and quality. Please try updating your graphics driver and/or browser to latest version.<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '<br>Current renderer: ' + getGpuInfo());
} else {
showWarningRibbon('The current browser does not support WebGL 2. This affects graphics performance and quality.<br>Please try updating your browser (and/or video drivers). NOTE: old hardware might have been blacklisted by this browser -- you may need to use a different browser.<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '<br>Current renderer: ' + getGpuInfo());
}
}
if (typeof OffscreenCanvas === 'undefined' && targetOffscreenCanvas) {
showWarningRibbon('This is an experimental UE4 build that uses OffscreenCanvas, but your browser does not seem to support it. Try out Firefox Nightly or Chrome Canary, and in Firefox, set pref gfx.offscreencanvas.enabled;true in about:config, and on Chrome Canary, Enable "Experimental canvas features" in chrome://flags. Continuing without OffscreenCanvas, but performance can be severely affected, and rendering might not look correct.');
}
// The following WebGL 1.0 extensions are available in core WebGL 2.0 specification, so they are no longer shown in the extensions list.
var webGLExtensionsInCoreWebGL2 = ['ANGLE_instanced_arrays','EXT_blend_minmax','EXT_color_buffer_half_float','EXT_frag_depth','EXT_sRGB','EXT_shader_texture_lod','OES_element_index_uint','OES_standard_derivatives','OES_texture_float','OES_texture_half_float','OES_texture_half_float_linear','OES_vertex_array_object','WEBGL_color_buffer_float','WEBGL_depth_texture','WEBGL_draw_buffers'];
var supportedWebGLExtensions = Module['preinitializedWebGLContext'].getSupportedExtensions();
if (Module['WEBGL_VERSION'] >= 2) supportedWebGLExtensions = supportedWebGLExtensions.concat(webGLExtensionsInCoreWebGL2);
// The following WebGL extensions are required by UE4/this project, and it cannot run without.
var requiredWebGLExtensions = []; // TODO: List WebGL extensions here that the demo needs and can't run without.
for(var i in requiredWebGLExtensions) {
if (supportedWebGLExtensions.indexOf(requiredWebGLExtensions[i]) == -1) {
showErrorDialog('Your browser does not support WebGL extension ' + requiredWebGLExtensions[i] + ', which is required to run this page!');
}
}
// The following WebGL extensions would be preferred to exist for best features/performance, but are not strictly needed and UE4 can fall back if not available.
var preferredToHaveWebGLExtensions = [// The following are core in WebGL 2:
'ANGLE_instanced_arrays', // UE4 uses instanced rendering where possible, but can fallback to noninstanced.
'EXT_color_buffer_half_float',
'EXT_sRGB',
'EXT_shader_texture_lod', // textureLod() is needed for correct reflections, without this reflection shaders are missing and render out black.
'OES_standard_derivatives',
'OES_texture_half_float',
'OES_texture_half_float_linear',
'OES_vertex_array_object',
'WEBGL_color_buffer_float',
'WEBGL_depth_texture',
'WEBGL_draw_buffers',
// These are still extensions in WebGL 2:
'OES_texture_float',
'WEBGL_compressed_texture_s3tc',
'EXT_texture_filter_anisotropic'
];
var unsupportedWebGLExtensions = [];
for(var i in preferredToHaveWebGLExtensions) {
if (supportedWebGLExtensions.indexOf(preferredToHaveWebGLExtensions[i]) == -1) {
unsupportedWebGLExtensions.push(preferredToHaveWebGLExtensions[i]);
}
}
if (unsupportedWebGLExtensions.length > 1) {
showWarningRibbon('Your browser or graphics card does not support the following WebGL extensions: ' + unsupportedWebGLExtensions.join(', ') + '. This can impact UE4 graphics performance and quality.');
} else if (unsupportedWebGLExtensions.length == 1) {
showWarningRibbon('Your browser or graphics card does not support the WebGL extension ' + unsupportedWebGLExtensions[0] + '. This can impact UE4 graphics performance and quality.');
}
if (targetOffscreenCanvas) {
Module['preinitializedWebGLContext'] = null; // TODO: Currently can't preinitialize a context when OffscreenCanvas is used.
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// browser 64bit vs 32bit check
if (!heuristicIs64Bit('browser')) {
if (heuristicIs64Bit('os')) {
showWarningRibbon('It looks like you are running a 32-bit browser on a 64-bit operating system. This can dramatically affect performance and risk running out of memory on large applications. Try updating to a 64-bit browser for an optimized experience.');
} else {
showWarningRibbon('It looks like your computer hardware is 32-bit. This can dramatically affect performance.');
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// files to download/cache
function withIndexedDB(db) {
Module['dbInstance'] = db;
// ----------------------------------------
// WASM
var mainCompiledCode = fetchFromIndexedDB(db, 'wasmModule').then(function(wasmModule) {
return { db: db, wasmModule: wasmModule, fromIndexedDB: true };
}).catch(function() {
return fetchFromIndexedDB(db, 'wasmBytes').then(function(wasmBytes) {
return { db: db, wasmBytes: wasmBytes, fromIndexedDB: true };
});
}).catch(function() {
return download(Module.locateFile('UE4Game.wasm'), 'arraybuffer').then(function(wasmBytes) {
return { db: db, wasmBytes: wasmBytes, fromIndexedDB: false };
});
});
Module['wasmDownloadAction'] = mainCompiledCode;
var compiledCodeInstantiateAction = new Promise(function(resolve, reject) {
Module['wasmInstantiateActionResolve'] = resolve;
Module['wasmInstantiateActionReject'] = reject;
});
// ----------------------------------------
// MAIN JS
var mainJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('UE4Game.js'), 'blob').then(function(data) {
Module['mainScriptUrlOrBlob'] = data;
return addScriptToDom(data).then(function() {
addRunDependency('wait-for-compiled-code');
});
});
// ----------------------------------------
// MORE JS
var dataJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('MovingBlocks.data.js'));
var utilityJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('Utility.js')).then(addScriptToDom);
var dataDownload =
/* // The following code would download and store the .data file as a Blob, which should be more efficient than loading an ArrayBuffer. However that seems to be buggy, so avoid it for now.
fetchOrDownloadAndStore(db, Module.locateFile('MovingBlocks.data')).then(function(dataBlob) {
return readBlobToArrayBuffer(dataBlob).then(function(dataArrayBuffer) {
Module['preloadedPackages'] = {};
Module['preloadedPackages'][Module.locateFile('MovingBlocks.data')] = dataArrayBuffer;
return dataJsDownload.then(addScriptToDom);
})
});
*/
// Instead as a fallback, download as ArrayBuffer. (TODO: Figure out the bugs with the above, and switch to using that one instead)
fetchOrDownloadAndStore(db, Module.locateFile('MovingBlocks.data'), 'arraybuffer').then(function(dataArrayBuffer) {
Module['preloadedPackages'] = {};
Module['preloadedPackages'][Module.locateFile('MovingBlocks.data')] = dataArrayBuffer;
return dataJsDownload.then(addScriptToDom);
});
// ----------------------------------------
// SHADERS
const precompileShaders = false; // Currently not enabled.
if (precompileShaders) {
var compileShaders = fetchOrDownloadAndStore(db, Module.locateFile('shaders.json'), 'arraybuffer')
.then(function(json) {
return compileShadersFromJson(json)
.catch(function(error) {
taskFinished(TASK_SHADERS, error + '<br>Current renderer: ' + getGpuInfo());
throw 'Shader compilation failed';
});
});
} else {
var compileShaders = true; // Not precompiling shaders, no-op Promise action.
}
// ----------------------------------------
// WAIT FOR DOWNLOADS AND COMPILES
Promise.all([mainCompiledCode, mainJsDownload, dataJsDownload, utilityJsDownload, dataDownload, compiledCodeInstantiateAction, compileShaders]).then(function() {
if (!precompileShaders) {
Module['precompiledShaders'] = Module['precompiledPrograms'] = Module['preinitializedWebGLContext'] = Module['glIDCounter'] = Module['precompiledUniforms'] = null;
}
taskProgress(TASK_MAIN);
removeRunDependency('wait-for-compiled-code'); // Now we are ready to call main()
});
};
// ----------------------------------------
// GO !
openIndexedDB(Module['UE4_indexedDBName'], Module['UE4_indexedDBVersion'] || 1).then(withIndexedDB).catch(function(e) {
if ( enableReadFromIndexedDB || enableWriteToIndexedDB ) {
console.error('Failed to openIndexedDB, proceeding without reading or storing contents to IndexedDB! Error: ');
}
console.error(e);
withIndexedDB(null);
});
});
|
/* @flow */
import * as Decoder from "../"
import * as Result from "result.flow"
import test from "blue-tape"
import testDecode from "./Decoder/Decoder"
test("Decoder.index", async test => {
test.deepEqual(Decoder.index(0, Decoder.Integer), {
type: "Index",
index: 0,
member: Decoder.Integer
})
test.deepEqual(Decoder.index(0, Decoder.index(2, Decoder.String)), {
type: "Index",
index: 0,
member: {
type: "Index",
index: 2,
member: Decoder.String
}
})
})
testDecode(
{
"Decoder.index(0, Decoder.Integer)": Decoder.index(0, Decoder.Integer),
'{type:"Index",index:0,member:{type:"Integer"}}': ({
type: "Index",
index: 0,
member: { type: "Integer" }
}: any)
},
{
"[7]": Result.ok(7),
"[1.1,2,3,4]": Result.error(
"Expecting an Integer at input[0] but instead got: `1.1`"
),
"[]": Result.error("Expecting a longer (>=1) array but instead got: `[]`"),
'["foo"]': Result.error(
`Expecting an Integer at input[0] but instead got: \`"foo"\``
),
"[true]": Result.error(
`Expecting an Integer at input[0] but instead got: \`true\``
),
"[false]": Result.error(
`Expecting an Integer at input[0] but instead got: \`false\``
),
'[["a","b","c","d"]]': Result.error(
'Expecting an Integer at input[0] but instead got: `["a","b","c","d"]`'
)
},
key => Result.error(`Expecting an array but instead got: \`${key}\``)
)
testDecode(
{
"Decoder.index(3, Decoder.Float)": Decoder.index(3, Decoder.Float),
'{type:"Index",index:3,member:{type:"Float"}}': ({
type: "Index",
index: 3,
member: { type: "Float" }
}: any)
},
{
"[7]": Result.error(
"Expecting a longer (>=4) array but instead got: `[7]`"
),
"[1.1,2,3,4]": Result.ok(4),
"[]": Result.error("Expecting a longer (>=4) array but instead got: `[]`"),
'["foo"]': Result.error(
'Expecting a longer (>=4) array but instead got: `["foo"]`'
),
"[true]": Result.error(
"Expecting a longer (>=4) array but instead got: `[true]`"
),
"[false]": Result.error(
"Expecting a longer (>=4) array but instead got: `[false]`"
),
'[["a","b","c","d"]]': Result.error(
'Expecting a longer (>=4) array but instead got: `[["a","b","c","d"]]`'
)
},
key => Result.error(`Expecting an array but instead got: \`${key}\``)
)
testDecode(
{
"Decoder.index(0, Decoder.index(3, Decoder.String))": Decoder.index(
0,
Decoder.index(3, Decoder.String)
),
'{type:"Index",index:0,member:{type:"Index",index:3,member:{type:"String"}}}': ({
type: "Index",
index: 0,
member: { type: "Index", index: 3, member: { type: "String" } }
}: any)
},
{
"[]": Result.error("Expecting a longer (>=1) array but instead got: `[]`"),
"[7]": Result.error("Expecting an array at input[0] but instead got: `7`"),
"[1.1,2,3,4]": Result.error(
"Expecting an array at input[0] but instead got: `1.1`"
),
'["foo"]': Result.error(
'Expecting an array at input[0] but instead got: `"foo"`'
),
"[true]": Result.error(
"Expecting an array at input[0] but instead got: `true`"
),
"[false]": Result.error(
"Expecting an array at input[0] but instead got: `false`"
),
'[["a","b","c","d"]]': Result.ok("d")
},
key => Result.error(`Expecting an array but instead got: \`${key}\``)
)
|
// @flow
import path from 'path';
import chalk from 'chalk';
import npmRunPath from 'npm-run-path';
import supportsColor from 'supports-color';
import type { ModuleGraphNode } from 'mor-core';
import type { ProcessingError } from './types';
require('draftlog').into(console, supportsColor);
// $FlowIgnore
const logger = console.draft.bind(console);
export default (errors: Array<ProcessingError>, verbose: boolean) => async (
ws: ModuleGraphNode
) => {
const cwd = path.dirname(ws.path);
const name = ws.name || cwd;
let status;
if (verbose) {
status = console.log.bind(console);
} else {
status = logger();
}
if (!ws.pkg.scripts || !ws.pkg.scripts.test) {
status(
`${chalk.reset.inverse.green.bold(' SKIP ')} ${name} ${chalk.yellow(
'no test script'
)}`
);
return;
}
try {
status(`${chalk.reset.inverse.yellow.bold(' RUNS ')} ${name} $ yarn test`);
const result = await ws.run('test', {
silent: true,
preferLocal: true,
exitOnError: false,
env: Object.assign(
{},
process.env,
npmRunPath({ path: process.env.PATH || '', cwd }),
supportsColor ? { FORCE_COLOR: true } : {}
),
stdio: [],
});
if (verbose) {
status(
`${chalk.reset.inverse.green.bold(
' PASS '
)} ${name} $ yarn test \n ${result.stdout}`
);
} else {
status(`${chalk.reset.inverse.green.bold(' PASS ')} ${name} $ yarn test`);
}
} catch (err) {
status(`${chalk.reset.inverse.red.bold(' FAIL ')} ${name} $ yarn test`);
errors.push({ ws, err });
}
};
|
import React from 'react'
import PropTypes from 'prop-types'
const Box = ({children, title, padded, color}) => (
<div className='wrapper'>
{title && <h3 className={`header ${color}`}>{title}</h3>}
<div className={padded ? 'padded' : ''}>
{children}
</div>
<style jsx>{`
@import 'colors';
.wrapper {
background-color: $white;
box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3);
border-radius: 2px;
margin-bottom: 20px;
overflow: hidden;
}
.header {
padding: 0.6em 0.75em 0.55em;
}
h3 {
font-size: 1.1em;
margin: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
font-weight: normal;
}
.subtitle {
margin-top: 0.2em;
font-size: 0.9em;
}
.padded {
padding: 1.5em 1.7em;
@media (max-width: 551px) {
padding: 1em;
}
}
// Colors
.grey {
background-color: $lightgrey;
}
.blue {
background-color: $blue;
color: $white;
}
.yellow {
background-color: $yellow;
}
.green {
background-color: $green;
color: $white;
}
`}</style>
</div>
)
Box.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node
]),
padded: PropTypes.bool,
color: PropTypes.oneOf([
'grey',
'blue',
'yellow',
'green'
])
}
Box.defaultProps = {
color: 'grey',
title: null,
padded: true
}
export default Box
|
#!/usr/bin/env node
var util = require('util'),
http = require('http'),
fs = require('fs'),
url = require('url'),
events = require('events');
var DEFAULT_PORT = 8000;
function main(argv) {
new HttpServer({
'GET': createServlet(StaticServlet),
'HEAD': createServlet(StaticServlet)
}).start(Number(argv[2]) || DEFAULT_PORT);
}
function escapeHtml(value) {
return value.toString().
replace('<', '<').
replace('>', '>').
replace('"', '"');
}
function createServlet(Class) {
var servlet = new Class();
return servlet.handleRequest.bind(servlet);
}
/**
* An Http server implementation that uses a map of methods to decide
* action routing.
*
* @param {Object} Map of method => Handler function
*/
function HttpServer(handlers) {
this.handlers = handlers;
this.server = http.createServer(this.handleRequest_.bind(this));
}
HttpServer.prototype.start = function(port) {
this.port = port;
this.server.listen(port);
util.puts('Http Server running at http://localhost:' + port + '/');
};
HttpServer.prototype.parseUrl_ = function(urlString) {
var parsed = url.parse(urlString);
parsed.pathname = url.resolve('/', parsed.pathname);
return url.parse(url.format(parsed), true);
};
HttpServer.prototype.handleRequest_ = function(req, res) {
var logEntry = req.method + ' ' + req.url;
if (req.headers['user-agent']) {
logEntry += ' ' + req.headers['user-agent'];
}
util.puts(logEntry);
req.url = this.parseUrl_(req.url);
var handler = this.handlers[req.method];
if (!handler) {
res.writeHead(501);
res.end();
} else {
handler.call(this, req, res);
}
};
/**
* Handles static content.
*/
function StaticServlet() {}
StaticServlet.MimeMap = {
'txt': 'text/plain',
'html': 'text/html',
'css': 'text/css',
'xml': 'application/xml',
'json': 'application/resources',
'js': 'application/javascript',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'png': 'image/png',
'svg': 'image/svg+xml'
};
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
StaticServlet.prototype.sendError_ = function(req, res, error) {
res.writeHead(500, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>Internal Server Error</title>\n');
res.write('<h1>Internal Server Error</h1>');
res.write('<pre>' + escapeHtml(util.inspect(error)) + '</pre>');
util.puts('500 Internal Server Error');
util.puts(util.inspect(error));
};
StaticServlet.prototype.sendMissing_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>404 Not Found</title>\n');
res.write('<h1>Not Found</h1>');
res.write(
'<p>The requested URL ' +
escapeHtml(path) +
' was not found on this server.</p>'
);
res.end();
util.puts('404 Not Found: ' + path);
};
StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(403, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>403 Forbidden</title>\n');
res.write('<h1>Forbidden</h1>');
res.write(
'<p>You do not have permission to access ' +
escapeHtml(path) + ' on this server.</p>'
);
res.end();
util.puts('403 Forbidden: ' + path);
};
StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
res.writeHead(301, {
'Content-Type': 'text/html',
'Location': redirectUrl
});
res.write('<!doctype html>\n');
res.write('<title>301 Moved Permanently</title>\n');
res.write('<h1>Moved Permanently</h1>');
res.write(
'<p>The document has moved <a href="' +
redirectUrl +
'">here</a>.</p>'
);
res.end();
util.puts('301 Moved Permanently: ' + redirectUrl);
};
StaticServlet.prototype.sendFile_ = function(req, res, path) {
var self = this;
var file = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': StaticServlet.
MimeMap[path.split('.').pop()] || 'text/plain'
});
if (req.method === 'HEAD') {
res.end();
} else {
file.on('data', res.write.bind(res));
file.on('close', function() {
res.end();
});
file.on('error', function(error) {
self.sendError_(req, res, error);
});
}
};
StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
var self = this;
if (path.match(/[^\/]$/)) {
req.url.pathname += '/';
var redirectUrl = url.format(url.parse(url.format(req.url)));
return self.sendRedirect_(req, res, redirectUrl);
}
fs.readdir(path, function(err, files) {
if (err)
return self.sendError_(req, res, error);
if (!files.length)
return self.writeDirectoryIndex_(req, res, path, []);
var remaining = files.length;
files.forEach(function(fileName, index) {
fs.stat(path + '/' + fileName, function(err, stat) {
if (err)
return self.sendError_(req, res, err);
if (stat.isDirectory()) {
files[index] = fileName + '/';
}
if (!(--remaining))
return self.writeDirectoryIndex_(req, res, path, files);
});
});
});
};
StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
path = path.substring(1);
res.writeHead(200, {
'Content-Type': 'text/html'
});
if (req.method === 'HEAD') {
res.end();
return;
}
res.write('<!doctype html>\n');
res.write('<title>' + escapeHtml(path) + '</title>\n');
res.write('<style>\n');
res.write(' ol { list-style-type: none; font-size: 1.2em; }\n');
res.write('</style>\n');
res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>');
res.write('<ol>');
files.forEach(function(fileName) {
if (fileName.charAt(0) !== '.') {
res.write('<li><a href="' +
escapeHtml(fileName) + '">' +
escapeHtml(fileName) + '</a></li>');
}
});
res.write('</ol>');
res.end();
};
// Must be last,
main(process.argv);
|
import util from '../util/util'
import uuid from 'uuid'
export default class Ocurrence {
constructor(options) {
if (options) {
this.email = options.email;
this.code = options.code;
this.latitude = options.latitude;
this.longitude = options.longitude;
this.description = options.description;
}
}
updateCode() {
this.code = util.toMd5(uuid.v4().toString() + new Date().toJSON());
}
/**
* GETTERS AND SETTERS
*/
set email(email) {
this._email = String(email).toLowerCase();
}
get email() {
return this._email;
}
set code(code) {
this._code = String(code);
}
get code() {
return this._code;
}
set latitude(latitude) {
this._latitude = String(latitude)
}
get latitude() {
return this._latitude;
}
set longitude(longitude) {
this._longitude = String(longitude)
}
get longitude() {
return this._longitude;
}
set description(description){
this._description = description;
}
get description(){
return this._description;
}
}
|
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const _ = require('lodash');
const app = express(); // Create the application
// Add Middleware necessary for REST API's
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
// CORS Support
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// TEST
// app.use('/hello', function(req, res, next) {
// res.send('Hello World!');
// next();
// });
// Connect to MongoDB
mongoose.connect('mongodb://localhost/meanmovieapp'); // replace 'localhost' with url of server if
mongoose.connection.once('open', function() { // running on something other than this computer
// Load the models
app.models = require('./models/index'); // Declare the models.
// A great way to take all of the models and dependency-inject
// them into the controllers.
// Load the routes
const routes = require('./routes'); // requiring routes.js
_.each(routes, function(controller, route) { // Iterate over routes; assign controller's value to tne first
// callback ('controller') and assign the key 'movie' to 'route'
app.use(route, controller(app, route)); //
});
console.log('Listening on port 3000...'); // 'meanmovieapp' is name of database
app.listen(3000);
});
|
import React from 'react'
import styled from 'styled-components'
import * as styles from 'styles'
import ignoreList from 'utils/math/ignoreList'
import anvil from 'icons/anvil.svg'
import pickaxe from 'icons/pickaxe.svg'
// import sword from 'icons/swords.svg'
import crown from 'icons/crown.svg'
import easel from 'icons/easel.svg'
const StyledHelp = styled.div`
background: ${styles.extraLightGray};
width: 100%;
border-radius: 9px;
height: 100%;
`
const Body = styled.div`
padding: 20px;
overflow-y: auto;
height: calc(100% - 88px);
`
const Close = styled.div`
cursor: pointer;
color: black;
position: absolute;
right: 10px;
i {
margin-top: 5px;
font-size: 2rem;
border-radius: 20px;
:hover {
background: white;
}
}
`
const IgnoreList = styled.div`
width: 100%;
display: flex;
flex-wrap: wrap;
`
const Item = styled.div`
width: 100px;
padding: 4px;
`
const Text = styled.div`
padding: 6px;
`
const StyledLink = styled.div`
display: contents;
cursor: pointer;
`
const Section = styled.div`
display: flex;
padding-bottom: 24px;
`
const VerticalGroup = styled.div`
display: flex;
flex-direction: column;
`
const Title = styled.div`
font-size: 1.4rem;
padding-bottom: 8px;
`
const Line = styled.div`
font-size: 1rem;
padding-bottom: 8px;
`
export default function HelpSheet (props) {
const {
toggleHelp
} = props
return (
<StyledHelp>
<Close onClick={toggleHelp}>
<i className='material-icons'>close</i>
</Close>
<Title style={{ padding: 10 }}>
Help
</Title>
<Body>
<Text>
<Section>
<VerticalGroup>
<Line>{'Show the sections that best fit your needs throughout your workflow.'}</Line>
<Line>{'Easily share work with others by sending them the url for the current equation.'}</Line>
</VerticalGroup>
</Section>
<Section>
<img src={pickaxe} alt='Material' height={40} width={40} />
<VerticalGroup>
<Title>{'Define Variables'}</Title>
<Line>{'Dynamically generate values for all of the undefined variables in your equations to be used with the command module.'}</Line>
</VerticalGroup>
</Section>
<Section>
<img src={anvil} alt='Forge' height={40} width={40} />
<VerticalGroup>
<Title>{'Build Equation'}</Title>
<Line>{'Any textboxes in the first section (except Notes) will be used to create and solve a math problem.'}</Line>
<Line>{'Alphabetical characters will be used as variables, and will add more blank textboxes.'}</Line>
<Line>{'Variables can be defined as numbers, equations, more variables or any combination.'}</Line>
<Line>{'Numbers before words will be used to multiply the variable.'}</Line>
<Line>{'Numbers at the end of words will be used as part of the variable name as a subscript.'}</Line>
<Line>{'Operators (+-*/()) separate variables.'}</Line>
</VerticalGroup>
</Section>
<Section>
<img src={easel} alt='Review' height={40} width={40} />
<VerticalGroup>
<Title>{'Review'}</Title>
<Line>{'Visually validate your equation.'}</Line>
</VerticalGroup>
</Section>
<Section>
<img src={crown} alt='Command' height={40} width={40} />
<VerticalGroup>
<Title>{'Graph'}</Title>
<Line>{'Graph your equation using variables left unspecified in the Equation section.'}</Line>
<Line>{'Quickly see the changes that occur as you manipulate the Defined Variables (materials).'}</Line>
<Line>{'Click on the labels for different lines to show/hide.'}</Line>
</VerticalGroup>
</Section>
<Section>
<i style={{ fontSize: 40 }} className='material-icons'>search</i>
<VerticalGroup>
<Title>{'Search'}</Title>
<Line>{'Save functions on your device.'}</Line>
<Line>{"Be specific. It's easy to save a bunch of problems and then delete them later. But names must be unique."}</Line>
<Line>{'Search saved functions and review your notes.'}</Line>
<Line>{'Add the subject or other relevant tags to the beginning of notes to make them easier to find.'}</Line>
<Line>{'There are no predefined categories. You make the categories by the notes and variables you create.'}</Line>
<Line>{'Try typing "finance" into the search and see what premade functions are already there.'}</Line>
</VerticalGroup>
</Section>
<br />
<Line>{'Functions that cannot be used as variables:'}</Line>
</Text>
<IgnoreList>
{ignoreList.map(func => {
return <Item key={func}>{func}</Item>
})}
</IgnoreList>
<Text>
<br />
Checkout <StyledLink><a href='http://mathjs.org/docs/reference/functions.html' target='_blank' rel='noopener noreferrer'>http://mathjs.org/docs/reference/functions.html</a></StyledLink> for an explanation of what the builtin functions do.
</Text>
</Body>
</StyledHelp>
)
}
|
"use strict";
angular.module("sbAdminApp").controller('serverEditCtrl', ['$scope', 'serverFactory', 'Notification', 'ipAddressFactory', 'osFactory', 'serverTypeFactory', 'cpuTypeFactory', 'programFactory',
function ($scope, factory, Notification, ipAddressFactory, osFactory, serverTypeFactory, cpuTypeFactory, programFactory) {
$scope.status;
$scope.bean;
$scope.editMode;
$scope.listIpAddress;
$scope.listOs;
$scope.listServerType;
$scope.listCpuType;
$scope.listParentServer;
$scope.listProgram;
getIpAddressList();
getOsList();
getServerTypeList();
getCpuTypeList();
getParentServerList();
getProgramList();
function getProgramList() {
console.log('getProgramList is working!');
programFactory.getList()
.success(function (list) {
$scope.listProgram = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
function getOsList() {
console.log('getOsList is working!');
osFactory.getList()
.success(function (list) {
$scope.listOs = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
function getServerTypeList() {
console.log('getServerTypeList is working!');
serverTypeFactory.getList()
.success(function (list) {
$scope.listServerType = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
function getCpuTypeList() {
console.log('getCpuTypeList is working!');
cpuTypeFactory.getList()
.success(function (list) {
$scope.listCpuType = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
function getParentServerList() {
console.log('getParentServerList is working!');
factory.getList()
.success(function (list) {
$scope.listParentServer = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
function getIpAddressList() {
console.log('getIpAddressList is working!');
ipAddressFactory.getList()
.success(function (list) {
$scope.listIpAddress = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
if (angular.isObject(factory.tempBean) && angular.isNumber(factory.tempBean.id)) {
$scope.bean = factory.tempBean;
get(factory.tempBean.id);
$scope.editMode = true;
factory.tempBean = null;
} else {
$scope.editMode = false;
}
function get(id) {
console.log("get ->" + id);
factory.getBean(id)
.success(function (returnBean) {
$scope.bean = returnBean;
})
.error(function (error) {
$scope.status = 'Unable to load bean data: ' + error.message;
console.log($scope.status);
});
}
$scope.showCreatedDate = function (message) {
return message.hasOwnProperty('createdDate')
}
$scope.update = function () {
console.log("update ->" + $scope.bean.id);
factory.updateBean($scope.bean)
.success(function () {
$scope.status = 'Updated ! Refreshing list.';
Notification.success($scope.status);
})
.error(function (error) {
$scope.status = 'Unable to update : ' + error.message;
Notification.error($scope.status);
});
};
$scope.insert = function () {
console.log("insert ->");
var temp = $scope.bean;
factory.insertBean(temp)
.success(function (data) {
$scope.status = 'Inserted Bean! Refreshing list.';
$scope.editMode = true;
$scope.bean = data;
Notification.success($scope.status);
console.log($scope.status);
}).
error(function (error) {
$scope.status = 'Unable to insert : ' + error.message;
console.log($scope.status);
Notification.error($scope.status);
});
};
}]); |
/**
* angular-bluebird-promises - Replaces $q with bluebirds promise API
* @version v1.0.2
* @link https://github.com/mattlewis92/angular-bluebird-promises
* @license MIT
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("angular"), require("bluebird"));
else if(typeof define === 'function' && define.amd)
define(["angular", "bluebird"], factory);
else if(typeof exports === 'object')
exports["angularBluebirdPromisesModuleName"] = factory(require("angular"), require("bluebird"));
else
root["angularBluebirdPromisesModuleName"] = factory(root["angular"], root["Promise"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__) {
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 = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _angular = __webpack_require__(1);
var _angular2 = _interopRequireDefault(_angular);
var _bluebird = __webpack_require__(2);
var _bluebird2 = _interopRequireDefault(_bluebird);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// In regards to: https://github.com/petkaantonov/bluebird#for-library-authors
// My reasoning behind not doing this is to prevent bundling bluebird code with this library
function $qBluebird(resolve, reject) {
return new _bluebird2.default(resolve, reject);
}
$qBluebird.prototype = _bluebird2.default.prototype;
_angular2.default.extend($qBluebird, _bluebird2.default);
//Make bluebird API compatible with angular's subset of Q
//Adapted from: https://gist.github.com/petkaantonov/8363789 and https://github.com/petkaantonov/bluebird-q
$qBluebird.defer = function () {
var deferred = {};
deferred.promise = $qBluebird(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
deferred.promise.progressCallbacks = [];
deferred.notify = function (progressValue) {
deferred.promise.progressCallbacks.forEach(function (cb) {
return typeof cb === 'function' && cb(progressValue);
});
};
return deferred;
};
$qBluebird.reject = $qBluebird.rejected;
$qBluebird.when = $qBluebird.cast;
var originalAll = $qBluebird.all;
$qBluebird.all = function (promises) {
if ((typeof promises === 'undefined' ? 'undefined' : _typeof(promises)) === 'object' && !Array.isArray(promises)) {
return $qBluebird.props(promises);
} else {
return originalAll(promises);
}
};
var originalThen = $qBluebird.prototype.then;
$qBluebird.prototype.then = function (fulfilledHandler, rejectedHandler, progressHandler) {
if (this.progressCallbacks) {
this.progressCallbacks.push(progressHandler);
}
return originalThen.call(this, fulfilledHandler, rejectedHandler, progressHandler);
};
var originalFinally = $qBluebird.prototype.finally;
$qBluebird.prototype.finally = function (finallyHandler, progressHandler) {
if (this.progressCallbacks) {
this.progressCallbacks.push(progressHandler);
}
return originalFinally.call(this, finallyHandler);
};
// You should override this, see the readme
$qBluebird.onPossiblyUnhandledRejection(function () {});
var ngModule = _angular2.default.module('mwl.bluebird', []).constant('Bluebird', $qBluebird).config(["$provide", "Bluebird", function ($provide, Bluebird) {
$provide.decorator('$q', function () {
return Bluebird;
});
}]).run(["$rootScope", "Bluebird", function ($rootScope, Bluebird) {
Bluebird.setScheduler(function (cb) {
return $rootScope.$evalAsync(cb);
});
}]);
exports.default = ngModule.name;
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ }
/******/ ])
});
; |
'use strict';
const Entity = require('../entity');
const AddressSchema = require('../shared').AddressSchema;
const PhoneSchema = require('../shared').PhoneSchema;
const ExternalLinkSchema = require('../shared').ExternalLinkSchema;
const PaymentTermSchema = require('../shared').PaymentTermSchema;
const OrganisationSchema = Entity.SchemaObject({
APIKey: { type: String },
Name: { type: String },
LegalName: { type: String },
PaysTax: { type: Boolean },
Version: { type: String },
OrganisationType: { type: String },
BaseCurrency: { type: String },
CountryCode: { type: String },
IsDemoCompany: { type: Boolean },
OrganisationStatus: { type: String },
RegistrationNumber: { type: String },
TaxNumber: { type: String },
FinancialYearEndDay: { type: Number },
FinancialYearEndMonth: { type: Number },
SalesTaxBasis: { type: String },
SalesTaxPeriod: { type: String },
DefaultSalesTax: { type: String },
DefaultPurchasesTax: { type: String },
PeriodLockDate: { type: Date },
EndOfYearLockDate: { type: Date },
CreatedDateUTC: { type: Date },
Timezone: { type: String },
OrganisationEntityType: { type: String },
ShortCode: { type: String },
LineOfBusiness: { type: String },
Addresses: { type: Array, arrayType: AddressSchema, toObject: 'always' },
Phones: { type: Array, arrayType: PhoneSchema, toObject: 'always' },
ExternalLinks: {
type: Array,
arrayType: ExternalLinkSchema,
toObject: 'always',
},
PaymentTerms: {
Bills: PaymentTermSchema,
Sales: PaymentTermSchema,
},
});
const Organisation = Entity.extend(OrganisationSchema, {
constructor: function(...args) {
this.Entity.apply(this, args);
},
changes: function(options) {
return this._super(options);
},
_toObject: function(options) {
return this._super(options);
},
});
module.exports.Organisation = Organisation;
|
(function() {
'use strict';
const type = require('ee-types');
const Base = require('./Base');
const log = require('ee-log');
module.exports = class PDFReport extends Base {
};
})();
|
module.exports=function(t){"use strict";t.entries=["maillard","swan","bluethroat"]}; |
/**
* Created by jacky on 12/27/14.
* Main Scene File
* Depends on three leap controller and leap controller and all their dependencies
*/
//array of nodes that have already been constructed
var occupied = [],
constructed = [];
//world wide length dimension scale. used to easily control relative distances and size of 3D objects.
const scale = 0.7;
//maximum nodes that can be constructed
const constructed_limit = 15;
var changeLoadingMsg = function(msg){
$('.loading-msg').html(msg);
};
var resetLoadingMsg = function(){
changeLoadingMsg('');
};
var showLoadingScreen = function(message){
changeLoadingMsg(message);
$('.loading-screen').show();
};
var hideLoadingScreen = function(){
$('.loading-screen').hide();
resetLoadingMsg();
};
//Text Geometry Constructor
var geo_TextGeometry = function(text,size){
return new THREE.TextGeometry( text, {
size: size,
height: 0.05,
curveSegments: 6,
font: "helvetiker",
weight: "normal",
style: "normal" });
};
//Materials
var matte_browishgreen = new THREE.MeshPhongMaterial( { color: 0xD0D45D } );
function checkPosition(pos){
var hasRepeats = false;
for(var i = 0;i<occupied.length;i++)
if(occupied[i].equals(pos)){
hasRepeats = true;
break;
}
if(hasRepeats)
return checkPosition(pos.add(new THREE.Vector3(0,0,2)));
else{
occupied.push(pos);
return pos;
}
}
var constructWelcomeTexts = function(){
//Welcome Text
//title
var welcome_texts = [
'Wave is an interactive web app',
'that generates 3D visualizations',
'of relationships among',
'Wikipedia articles',
'(compatible with LeapMotion and ',
'Oculus Rift!!!)'
];
var init_pos = new THREE.Vector3(-2,1.0,0);
welcome_texts.forEach(function(text){
var text_geo = geo_TextGeometry(text,0.2);
text_geo.castShadow = true;
text_geo.receiveShadow = true;
var text_obj = new THREE.Mesh(text_geo,matte_browishgreen);
all_orientables.add(text_obj);
setPosition(text_obj,init_pos);
init_pos = init_pos.add(new THREE.Vector3(0,-0.4,0));
});
};
var initScene = function(){
showLoadingScreen('Scene');
constructWelcomeTexts();
// create the geometry sphere
var bg_geo = new THREE.SphereGeometry(200, 32, 32),
bg_mat = new THREE.MeshBasicMaterial();
bg_mat.map = THREE.ImageUtils.loadTexture('assets/space.jpg');
bg_mat.side = THREE.BackSide;
var bg = new THREE.Mesh(bg_geo, bg_mat);
scene.add(bg);
//Lighting
var amb_light = new THREE.AmbientLight( 0x404040 ); // soft white light
var dir_light_warm = new THREE.DirectionalLight( 0xFFECD1, 0.5 );
dir_light_warm.position.set( 5, 10, 5 );
dir_light_warm.castShadow = true;
dir_light_warm.receiveShadow = true;
var dir_light_cold = new THREE.DirectionalLight( 0xD1EAFF, 1.0 );
dir_light_cold.position.set( -5, -10, -5 );
dir_light_cold.castShadow = true;
dir_light_cold.receiveShadow = true;
scene.add( dir_light_warm );
scene.add( dir_light_cold );
scene.add( amb_light );
hideLoadingScreen();
};
//Helper functions to turn nodes into 3D objects
var placeNodeInScene = function(node,origin,angle,weight){
//places node in scene as object
//returns position of object
constructed.push(node);
//new position
var new_pos = new THREE.Vector3(
scale*(weight*Math.cos(angle) + origin.x),
scale*(weight*Math.sin(angle) + origin.y),
scale*(node.name.getDepth() + origin.z)
);
new_pos = checkPosition(new_pos);
changeLoadingMsg(node.name.title);
//title
var node_title_geo = geo_TextGeometry(node.name.title,scale*0.8);
node_title_geo.castShadow = true;
node_title_geo.receiveShadow = true;
var node_title_obj = new THREE.Mesh(node_title_geo,matte_browishgreen);
//add objects to scene
all_orientables.add(node_title_obj);
//set positions
setPosition(node_title_obj,new_pos);
return new_pos;
};
var construct_scene_children = function(node,origin,angle,weight){
var node_pos = placeNodeInScene(node,origin,angle,weight);
//add line to connect node to parent
all_connections.add(origin,node_pos);
var adj = [];
node.adjList.forEach(function(cur_node){
if(constructed.indexOf(cur_node) == -1)
adj.push(cur_node);
});
var num_adj = adj.length,
weights = node.weight,
angle_offset = 2*Math.PI/num_adj;
for (var i = 0; i<num_adj; i++)
construct_scene_children(adj[i],node_pos,angle_offset*i,weights[i]);
};
var construct_scene_parent = function(graph){
var nodes = graph.getAllNodes(),
pivot_node = nodes[0];
var pivot_pos = placeNodeInScene(pivot_node,new THREE.Vector3(0,0,0),0,0);
//call construct_scene_children on adjs
var adj = pivot_node.adjList,
num_adj = adj.length,
weights = pivot_node.weight,
angle_offset = 2*Math.PI/num_adj;
for (var j = 0; j<num_adj; j++)
construct_scene_children(adj[j],pivot_pos,angle_offset*j,weights[j]);
};
var resetScene = function(){
all_orientables.reset();
all_connections.reset();
};
var populateScene = function(items){
resetScene();
var graph = getSceneGraph(items);
construct_scene_parent(graph);
hideLoadingScreen();
};
//Getting desired title from user
var form = $('#generateTreeForm');
form.keypress(function(e){
e.stopPropagation();
if(e.which == 13){
var value = form.val();
if(value){
showLoadingScreen(value);
getWikiData(value,constructed_limit,populateScene);
form.focusout();
}
}
});
form.focus(function(){
allow_key_board = false;
});
form.focusout(function(){
allow_key_board = true;
});
initScene();
//Settings
var reset = function(){
console.log("resetting everything");
showLoadingScreen();
resetScene();
constructWelcomeTexts();
resetCamera();
hideLoadingScreen();
};
$("#reset").click(function(){
reset();
});
$("#origin").click(function(){
resetCamera();
});
$("#enableVR").click(function(){
enableVRMode();
});
$("#toggleOrient").click(function(){
toggleOrient();
});
|
var express = require('express');
var app = express();
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({extended: false}));
app.post('/form', function(req, res){
var text = req.body.str.split('').reverse().join('');
//console.log(text);
res.end(text);
});
app.listen(process.argv[2]); |
export { default as dateRanges } from './DateRangeStore';
export { default as currentMonth } from './CurrentMonthStore';
|
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _jsxFileName='src/CircleButton.js';exports.default=
CircleButton;var _react=require('react');var _react2=_interopRequireDefault(_react);var _propTypes=require('prop-types');var _propTypes2=_interopRequireDefault(_propTypes);var _ButtonComponent=require('./ButtonComponent');var _ButtonComponent2=_interopRequireDefault(_ButtonComponent);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function CircleButton(props){
var buttonSize=props.size;
var progressSize=buttonSize;
var textInsideProgress=props.states?
props.states[props.buttonState].progress:
null;
return(
_react2.default.createElement(_ButtonComponent2.default,_extends({},
props,{
shape:'circle',
width:buttonSize,
height:buttonSize,
progressSize:progressSize,
textInsideProgress:textInsideProgress,__source:{fileName:_jsxFileName,lineNumber:13}})));
}
CircleButton.propTypes=_extends({},
_ButtonComponent2.default.propTypes,{
size:_propTypes2.default.number});
CircleButton.defaultProps={
size:100,
progressBackgroundColor:'#F0F0F0',
progress:true,
progressWidth:3}; |
(function() {
var KT, global;
global = this;
KT = require('../lib/katy.coffee').KT;
require('UnderscoreMatchersForJasmine');
describe("Wrapping Katy", function() {
var khw;
khw = KT("Hello World");
describe('K', function() {
it("should provide K", function() {
return expect(khw).toRespondTo('K');
});
it('should execute the function', function() {
var called;
called = false;
khw.K(function() {
return called = true;
});
return expect(called).toBeTruthy();
});
return it('should return the receiver', function() {
return expect(khw.K(function(x) {
return 'XXX' + x + 'XXX';
})).toEqual("Hello World");
});
});
return describe('T', function() {
it("should provide T", function() {
return expect(khw).toRespondTo('T');
});
it('should execute the function', function() {
var called;
called = false;
khw.T(function() {
return called = true;
});
return expect(called).toBeTruthy();
});
return it('should return the result', function() {
return expect(khw.T(function(x) {
return 'XXX' + x + 'XXX';
})).toEqual("XXXHello WorldXXX");
});
});
});
describe('Installing Katy', function() {
var hw;
KT.mixInto(String);
hw = "Hello World";
describe('K', function() {
it("should provide K", function() {
return expect(hw).toRespondTo('K');
});
it('should execute the function', function() {
var called;
called = false;
hw.K(function() {
return called = true;
});
return expect(called).toBeTruthy();
});
return it('should return the receiver', function() {
return expect(hw.K(function(x) {
return 'XXX' + x + 'XXX';
})).toEqual("Hello World");
});
});
return describe('T', function() {
it("should provide T", function() {
return expect(hw).toRespondTo('T');
});
it('should execute the function', function() {
var called;
called = false;
hw.T(function() {
return called = true;
});
return expect(called).toBeTruthy();
});
return it('should return the result', function() {
return expect(hw.T(function(x) {
return 'XXX' + x + 'XXX';
})).toEqual("XXXHello WorldXXX");
});
});
});
describe("Functionalizing Strings", function() {
describe("lambdas", function() {
var k123;
k123 = KT([1, 2, 3]);
it('should accept a string lambda for K', function() {
return expect(k123.K('.concat([4, 5, 6])')).toEqual([1, 2, 3]);
});
it('should accept a string lambda for T', function() {
return expect(k123.T('.concat([4, 5, 6])')).toEqual([1, 2, 3, 4, 5, 6]);
});
it('should support ->', function() {
return expect(k123.T('a -> a.length')).toEqual(3);
});
return it('should support point-free expressions', function() {
expect(KT('Hello').T("+ ' World'")).toEqual('Hello World');
expect(KT('Hello').T("+", ' World')).toEqual('Hello World');
return expect(KT('Hello').T(".length")).toEqual(5);
});
});
return describe('messages', function() {
var k123;
k123 = KT([1, 2, 3]);
it('should accept a message and argument(s) for K', function() {
return expect(k123.K('concat', [4, 5, 6])).toEqual([1, 2, 3]);
});
return it('should accept a message and argument(s) for T', function() {
return expect(k123.T('concat', [4, 5, 6])).toEqual([1, 2, 3, 4, 5, 6]);
});
});
});
describe('chaining', function() {
it('should not be mixed into array', function() {
return expect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).not.toRespondToAny('K', 'T');
});
it('should chain', function() {
return expect(KT([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).chain().K('pop').K('pop').K('pop').T('pop').value()).toEqual(7);
});
return it('should chain 2', function() {
return expect(KT([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]).chain().K('pop').K('pop').K('pop').value().sort(function(a, b) {
return a - b;
})).toEqual([4, 5, 6, 7, 8, 9, 10]);
});
});
describe('miscellaneous', function() {
beforeEach(function() {
return KT.mixInto(Array);
});
it('should work like this', function() {
var pop_n;
pop_n = function(arr, n) {
var x, _results;
_results = [];
for (x = 1; 1 <= n ? x <= n : x >= n; 1 <= n ? x++ : x--) {
_results.push(arr.pop());
}
return _results;
};
expect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].T(pop_n, 3)).toEqual([10, 9, 8]);
return expect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].K(pop_n, 3)).toEqual([1, 2, 3, 4, 5, 6, 7]);
});
return it('should have docs that use built-in methods', function() {
var identifiers, result;
identifiers = function(arrOfSymbols) {
return arrOfSymbols.filter(function(str) {
return /^[_a-zA-Z]\w*$/.test(str);
});
};
result = ['sna', 10, 'fu', 'bar', '1wayticket'].sort().T(identifiers).map(function(i) {
return i.length;
});
return expect(result).toEqual([3, 2, 3]);
});
});
}).call(this);
|
/**
* CSSS javascript code
* @author Lea Verou (http://leaverou.me)
* @version 2.0
*/
/**
* Make the environment a bit friendlier
*/
function $(expr, con) { return (con || document).querySelector(expr); }
function $$(expr, con) { return [].slice.call((con || document).querySelectorAll(expr)); }
(function(head, body, html){
// Check for classList support and include the polyfill if it's not supported
if(!('classList' in body)) {
var thisScript = $('script[src$="slideshow.js"]'),
script = document.createElement('script');
script.src = thisScript.src.replace(/\bslideshow\.js/, 'classList.js');
thisScript.parentNode.insertBefore(script, thisScript);
}
// Cache <title> element, we may need it for slides that don't have titles
var documentTitle = document.title + '';
var self = window.SlideShow = function(container, slide) {
var me = this;
// Set instance
if(!window.slideshow) {
window.slideshow = this;
}
this.container = container = container || body;
// Current slide
this.index = this.slide = slide || 0;
// Current .delayed item in the slide
this.item = 0;
// Create timer, if needed
this.duration = container.getAttribute('data-duration');
if(this.duration > 0) {
var timer = document.createElement('div');
timer.id = 'timer';
timer.setAttribute('style', PrefixFree.prefixCSS('transition: ' + this.duration * 60 + 's linear;'));
container.appendChild(timer);
setTimeout(function() {
timer.className = 'end';
}, 1);
}
// Create slide indicator
this.indicator = document.createElement('div');
this.indicator.id = 'indicator';
container.appendChild(this.indicator);
// Get the slide elements into an array
this.slides = $$('.slide', container);
// Order of the slides
this.order = [];
for(var i=0; i<this.slides.length; i++) {
var slide = this.slides[i]; // to speed up references
// Asign ids to slides that don't have one
if(!slide.id) {
slide.id = 'slide' + (i+1);
}
// Set data-title attribute to the title of the slide
if(!slide.title) {
// no title attribute, fetch title from heading(s)
var heading = $('hgroup', slide) || $('h1,h2,h3,h4,h5,h6', slide);
if(heading && heading.textContent.trim()) {
slide.setAttribute('data-title', heading.textContent);
}
}
else {
// The title attribute is set, use that
slide.setAttribute('data-title', slide.title);
slide.removeAttribute('title');
}
slide.setAttribute('data-index', i);
var imp = slide.getAttribute('data-import'),
imported = imp? this.getSlideById(imp) : null;
this.order.push(imported? +imported.getAttribute('data-index') : i);
}
if(window.name === 'projector' && window.opener && opener.slideshow) {
document.body.classList.add('projector');
this.presenter = opener.slideshow;
this.presenter.projector = this;
}
// Adjust the font-size when the window is resized
addEventListener('resize', this, false);
// In some browsers DOMContentLoaded is too early, so try again onload
addEventListener('load', this, false);
addEventListener('hashchange', this, false);
// If there's already a hash, update current slide number...
this.handleEvent({type: 'hashchange'});
document.addEventListener('keyup', this, false);
document.addEventListener('keydown', this, false);
// Rudimentary style[scoped] polyfill
$$('style[scoped]', container).forEach(function(style) {
var rulez = style.sheet.cssRules,
parentid = style.parentNode.id || self.getSlide(style).id;
for(var j=rulez.length; j--;) {
var cssText = rulez[j].cssText.replace(/^|,/g, function($0) {
return '#' + parentid + ' ' + $0
});
style.sheet.deleteRule(0);
style.sheet.insertRule(cssText, 0);
}
});
// Process iframe slides
$$('.slide > iframe:only-child', container).forEach(function(iframe) {
var slide = iframe.parentNode,
h = document.createElement('h1'),
a = document.createElement('a'),
src = iframe.src || iframe.getAttribute('data-src');
slide.classList.add('iframe');
var title = iframe.title || src.replace(/\/#?$/, '')
.replace(/^\w+:\/\/w{0,3}\.?/, '');
a.href = src;
a.target = '_blank';
a.textContent = title;
h.appendChild(a);
slide.appendChild(h);
});
}
self.prototype = {
handleEvent: function(evt) {
switch(evt.type) {
/**
Keyboard navigation
Ctrl+G : Go to slide...
Ctrl+H : Show thumbnails and go to slide
Ctrl+P : Presenter view
(Shift instead of Ctrl works too)
*/
case 'keyup':
if(evt.ctrlKey || evt.shiftKey) {
switch(evt.keyCode) {
case 71: // G
var slide = prompt('Which slide?');
me.goto(+slide? slide - 1 : slide);
break;
case 72: // H
if(body.classList.contains('show-thumbnails')) {
body.classList.remove('show-thumbnails');
body.classList.remove('headers-only');
}
else {
body.classList.add('show-thumbnails');
if(!evt.shiftKey || !evt.ctrlKey) {
body.classList.add('headers-only');
}
body.addEventListener('click', function(evt) {
var slide = evt.target;
while(slide && !slide.classList.contains('slide')) {
slide = slide.parentNode;
}
if(slide) {
this.goto(slide.id);
setTimeout(function() { me.adjustFontSize(); }, 1000); // for Opera
}
body.classList.remove('show-thumbnails');
body.classList.remove('headers-only');
}, false);
}
break;
case 74: // J
if(body.classList.contains('hide-elements')) {
body.classList.remove('hide-elements');
}
else {
body.classList.add('hide-elements');
}
break;
case 80: // P
// Open new window for attendee view
this.projector = open(location, 'projector');
// Get the focus back
window.focus();
// Switch this one to presenter view
body.classList.add('presenter');
}
}
break;
case 'keydown':
/**
Keyboard navigation
Home : First slide
End : Last slide
Space/Up/Right arrow : Next item/slide
Ctrl + Space/Up/Right arrow : Next slide
Down/Left arrow : Previous item/slide
Ctrl + Down/Left arrow : Previous slide
(Shift instead of Ctrl works too)
*/
if(evt.target === body || evt.target === body.parentNode || evt.altKey) {
if(evt.keyCode >= 32 && evt.keyCode <= 40) {
evt.preventDefault();
}
switch(evt.keyCode) {
case 33: //page up
this.previous();
break;
case 34: //page down
this.next();
break;
case 35: // end
this.end();
break;
case 36: // home
this.start();
break;
case 37: // <-
case 38: // up arrow
this.previous(evt.ctrlKey || evt.shiftKey);
break;
case 32: // space
case 39: // ->
case 40: // down arrow
this.next(evt.ctrlKey || evt.shiftKey);
break;
}
}
break;
case 'load':
case 'resize':
this.adjustFontSize();
break;
case 'hashchange':
this.goto(location.hash.substr(1) || 0);
}
},
start: function() {
this.goto(0);
},
end: function() {
this.goto(this.slides.length - 1);
},
/**
@param hard {Boolean} Whether to advance to the next slide (true) or
just the next step (which could very well be showing a list item)
*/
next: function(hard) {
if(!hard && this.items.length) {
this.nextItem();
}
else {
this.goto(this.index + 1);
this.item = 0;
// Mark all items as not displayed, if there are any
if(this.items.length) {
for (var i=0; i<this.items.length; i++) {
if(this.items[i].classList) {
this.items[i].classList.remove('displayed');
this.items[i].classList.remove('current');
}
}
}
}
},
nextItem: function() {
if(this.item < this.items.length) {
this.gotoItem(++this.item);
}
else {
this.item = 0;
this.next(true);
}
},
previous: function(hard) {
if(!hard && this.item > 0) {
this.previousItem();
}
else {
this.goto(this.index - 1);
this.item = this.items.length;
// Mark all items as displayed, if there are any
if(this.items.length) {
for (var i=0; i<this.items.length; i++) {
if(this.items[i].classList) {
this.items[i].classList.add('displayed');
}
}
// Mark the last one as current
var lastItem = this.items[this.items.length - 1];
lastItem.classList.remove('displayed');
lastItem.classList.add('current');
}
}
},
previousItem: function() {
this.gotoItem(--this.item);
},
getSlideById: function(id) {
return $('.slide#' + id, this.container);
},
/**
Go to an aribtary slide
@param which {String|Integer} Which slide (identifier or slide number)
*/
goto: function(which) {
var slide;
// We have to remove it to prevent multiple calls to goto messing up
// our current item (and there's no point either, so we save on performance)
window.removeEventListener('hashchange', this, false);
var id;
if(which + 0 === which && which in this.slides) {
// Argument is a valid slide number
this.index = which;
this.slide = this.order[which]
slide = this.slides[this.slide];
location.hash = '#' + slide.id;
}
else if(which + '' === which) { // Argument is a slide id
slide = this.getSlideById(which);
if(slide) {
this.slide = this.index = +slide.getAttribute('data-index');
location.hash = '#' + which;
}
}
if(slide) { // Slide actually changed, perform any other tasks needed
document.title = slide.getAttribute('data-title') || documentTitle;
if(slide.classList.contains('iframe')) {
var iframe = $('iframe', slide), src;
if(!iframe.hasAttribute('src') && (src = iframe.getAttribute('data-src'))) {
iframe.src = src;
}
}
else {
this.adjustFontSize();
}
this.indicator.textContent = this.index + 1;
// Update items collection
this.items = $$('.delayed, .delayed-children > *', this.slides[this.slide]);
this.item = 0;
this.projector && this.projector.goto(which);
// Update next/previous
for (var i=this.slides.length; i--;) {
this.slides[i].classList.remove('previous');
this.slides[i].classList.remove('next');
}
this.slides.previous = this.slides[this.order[this.index - 1]];
this.slides.next = this.slides[this.order[this.index + 1]];
this.slides.previous && this.slides.previous.classList.add('previous');
this.slides.next && this.slides.next.classList.add('next');
}
// If you attach the listener immediately again then it will catch the event
// We have to do it asynchronously
var me = this;
setTimeout(function() {
addEventListener('hashchange', me, false);
}, 1000);
},
gotoItem: function(which) {
this.item = which;
var items = this.items, classes;
for(var i=items.length; i-- > 0;) {
classes = this.items[i].classList;
classes.remove('current');
classes.remove('displayed');
}
for(var i=this.item - 1; i-- > 0;) {
this.items[i].classList.add('displayed');
}
if(this.item > 0) {
this.items[this.item - 1].classList.add('current');
}
this.projector && this.projector.gotoItem(which);
},
adjustFontSize: function() {
// Cache long lookup chains, for performance
var htmlStyle = html.style,
scrollRoot = document[html.scrollHeight? 'documentElement' : 'body'],
innerHeight = window.innerHeight,
innerWidth = window.innerWidth,
slide = this.slides[this.slide];
// Clear previous styles
htmlStyle.fontSize = '';
if(body.classList.contains('show-thumbnails')
|| slide.classList.contains('dont-resize')) {
return;
}
for(
var percent = 100;
(scrollRoot.scrollHeight > innerHeight || scrollRoot.scrollWidth > innerWidth) && percent >= 35;
percent-=5
) {
htmlStyle.fontSize = percent + '%';
}
// Individual slide
if(slide.clientHeight && slide.clientWidth) {
// Strange FF bug: scrollHeight doesn't work properly with overflow:hidden
var previousStyle = slide.getAttribute('style');
slide.style.overflow = 'auto';
for(
;
(slide.scrollHeight > slide.clientHeight || slide.scrollWidth > slide.clientWidth) && percent >= 35;
percent--
) {
htmlStyle.fontSize = percent + '%';
}
slide.setAttribute('style', previousStyle);
}
},
// Is the element on the current slide?
onCurrent: function(element) {
var slide = self.getSlide(element);
if(slide) {
return '#' + slide.id === location.hash;
}
return false;
}
};
/**********************************************
* Static methods
**********************************************/
// Helper method for plugins
self.getSlide = function(element) {
var slide = element;
while (slide && slide.classList && !slide.classList.contains('slide')) {
slide = slide.parentNode;
}
return slide;
}
})(document.head || document.getElementsByTagName('head')[0], document.body, document.documentElement);
|
function Component() {}
Component.prototype.view = __dirname;
Component.prototype.init = function () {
// do nothing
};
Component.prototype.create = function (model, dom) {
var self = this;
dom.on('click', function (e) {
self.close(e);
});
dom.on('keydown', function (e) {
if (e.keyCode === 27) self.close(e);
});
};
Component.prototype.open = function (e) {
e.preventDefault();
e.stopPropagation();
var open = this.model.set('open', true);
if (!open) this.emit('open');
};
Component.prototype.close = function (e) {
e.preventDefault();
e.stopPropagation();
this.model.del('open');
this.emit('close');
};
module.exports = Component;
|
var xtea = require("../xtea");
var Buffer = require("buffer").Buffer;
var test = require("tape");
test('XTEA ECB encryption', function (t) {
var buf = new Buffer([1,2,3]);
var key = new Buffer([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
var enc = xtea.encrypt(buf, key);
var dec = xtea.decrypt(enc, key);
t.notDeepEqual(enc, buf, "ciphertext should not equal plaintext");
t.deepEqual(dec, buf, "decrypted text should equal plaintext");
enc = xtea.encrypt(new Buffer("test vector 1"), new Buffer("super secret key"));
t.deepEqual(enc, new Buffer([223,83,148,252,243,87,191,226,116,252,121,16,154,53,112,203]), "test vector 1");
enc = xtea.encrypt(new Buffer("00000000"), new Buffer("super secret key"));
t.deepEqual(enc, new Buffer([113,181,178,30,196,40,107,136,191,240,216,226,16,148,62,88]), "test vector 2");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"));
t.deepEqual(enc, new Buffer([113,181,178,30,196,40,107,136,113,181,178,30,196,40,107,136,191,240,216,226,16,148,62,88]), "test vector 3");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"), 'ecb', false, true);
t.deepEqual(enc, new Buffer([113,181,178,30,196,40,107,136,113,181,178,30,196,40,107,136]), "test vector 4 (skipped padding)");
t.end();
})
test('XTEA CBC encryption', function (t) {
var buf = new Buffer([1,2,3]);
var key = new Buffer([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]);
var iv = new Buffer([8,7,6,5,4,3,2,1]);
var enc = xtea.encrypt(buf, key, "cbc", iv);
var dec = xtea.decrypt(enc, key, "cbc", iv);
t.notDeepEqual(enc, buf, "ciphertext should not equal plaintext");
t.deepEqual(dec, buf, "decrypted text should equal plaintext");
enc = xtea.encrypt(new Buffer("test vector 1"), new Buffer("super secret key"), "cbc", new Buffer("iv_value"));
t.deepEqual(enc, new Buffer([125,198,23,180,230,255,169,214,221,5,37,102,118,82,92,220]), "test vector 1");
enc = xtea.encrypt(new Buffer("00000000"), new Buffer("super secret key"), "cbc", new Buffer("iv_value"));
t.deepEqual(enc, new Buffer([203,190,233,189,122,108,38,122,69,155,94,70,225,197,145,101]), "test vector 2");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"), "cbc", new Buffer("iv_value"));
t.deepEqual(enc, new Buffer("cbbee9bd7a6c267ad17f4720f3eb70f31707672103db54d5", "hex"), "test vector 3");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"), "cbc", new Buffer("iv_value"), true);
t.deepEqual(enc, new Buffer("cbbee9bd7a6c267ad17f4720f3eb70f3", "hex"), "test vector 4 (skipped padding)");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"), "cbc");
t.deepEqual(enc, new Buffer("71b5b21ec4286b88920efa7cefa8b058fd5975f97b442b69", "hex"), "test vector 5 (not specified iv)");
enc = xtea.encrypt(new Buffer("0000000000000000"), new Buffer("super secret key"), "cbc", false, true);
t.deepEqual(enc, new Buffer("71b5b21ec4286b88920efa7cefa8b058", "hex"), "test vector 6 (not specified iv, skipped padding)");
t.throws(function() {
xtea.encrypt(new Buffer("00000000000000"), new Buffer("super secret key"), "cbc", false, true);
}, "test vector 7 (skipped padding, invalid block length)");
t.end();
})
|
'use strict';
var fs = require('fs');
var path = require('path');
var readline = require('readline');
var RECORD_START = /^t=\s*(\d+)\s\[st=\s*(\d+)\]\s+(.+)$/;
var RECORD_KEY_VALUE = /^\s+-->\s(\S+)\s=\s\"?([^\"]+)\"?/;
var RECORD_HEADERS = /^\s+(--> )?(:?[^:]+):\s(.+)$/;
var records = [];
var currentRecord;
function parse (logfile, cb) {
let input = readline.createInterface({
input: fs.createReadStream(logfile, {
encoding: 'utf-8'
})
});
input.on('line', data => {
let recordStartMatch = data.match(RECORD_START);
if (recordStartMatch) {
if (currentRecord) {
records.push(currentRecord);
}
currentRecord = {
t : recordStartMatch[1],
st : recordStartMatch[2],
e : recordStartMatch[3]
};
return;
}
let recordKeyValueMatch = data.match(RECORD_KEY_VALUE);
if (recordKeyValueMatch) {
currentRecord[recordKeyValueMatch[1]] = recordKeyValueMatch[2];
return;
}
let recordHeadersMatch = data.match(RECORD_HEADERS);
if (recordHeadersMatch) {
currentRecord.headers = currentRecord.headers || {};
currentRecord.headers[recordHeadersMatch[2]] = recordHeadersMatch[3];
return;
}
cb(new Error(`Could not parse ${data}`));
});
input.on('close', () => {
let data = {
records: records,
streams: {}
};
records.forEach(r => {
let streamId = r.stream_id || r.promised_stream_id;
if (streamId) {
data.streams[streamId] = data.streams[streamId] || [];
data.streams[streamId].push(r);
}
});
cb(null, data);
});
}
module.exports = parse;
|
var receive = require("./serialize-incoming"),
concussion = require("concussion");
/**
* Create connect middleware using the Later configuration.
* @param {Later} later
* @returns {function}
*/
function later(later) {
var Later = require("./later");
if (!(later instanceof Later)) later = new Later(later);
return function(req, res) {
var headers = concussion(req.headers),
methods = {},
allRules = later.rules,
hostedRules, foundRules, acceptableRules,
rule;
function checkHost(rule) {return rule.checkHost(req);}
function checkPath(rule) {return rule.checkPath(req);}
function checkMethod(rule) {return rule.checkMethod(req);}
// filter out any rules which don't match the host
hostedRules = allRules.filter(checkHost);
// 404 on invalid path
foundRules = hostedRules.filter(checkPath);
if (foundRules.length === 0) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("Not Found");
later.emit("request", req, res);
return;
}
// 405 on invalid method
acceptableRules = foundRules.filter(checkMethod);
if (acceptableRules.length === 0) {
rules.filter(checkPath).forEach(function(rule) {
methods[rule.method] = true;
});
res.writeHead(405, {
"Content-Type": "text/plain",
"Accept": Object.keys(methods).join(",")
});
res.end("Method Not Allowed");
later.emit("request", req, res);
return;
}
// use first acceptable rule
rule = acceptableRules.shift();
// add forwarding rule request headers
if (rule.forward && !headers.read("X-Later-Host")) {
headers.write("X-Later-Host", rule.forward);
}
// accept the rest
receive(req, function(err, req) {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.end(err.message);
} else later.storage.queue(req, function(err, key) {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.end(err.message);
} else {
res.writeHead(202, {"X-Later-Key": key,"X-Later-Scheme": rule.tls || rule.httpsonly ? "https" : "http"});
res.end();
concussion.write(req.headers, "X-Later-Key", key);
later.emit("request", req, res);
}
});
});
}
}
/** export the middleware function */
module.exports = later;
|
/**
* IMGUR: Clase para subir imágenes a un album anónimo.
*/
function Imgur() {
this.params = {
album: {
hash: 'bBAqLK1G2OvMnmj',
id: 'zlvtg'
},
client_id: 'fc503a6be5a62df',
token: '6528448c258cff474ca9701c5bab6927',
url_upload: 'http://api.imgur.com/3/upload.json',
url_album: ''
};
this.on_upload = null;
this.on_error = null;
this.on_progress = null;
this.format_response = true;
this.sizes = {
small_square: 's',
big_square: 'b',
small_thumbnail: 't',
medium_thumbnail: 'm',
largue_thumbnail: 'l',
huge_thumbnail: 'h'
};
}
Imgur.prototype.resizeLink = function (size, link) {
if (link === undefined || link.indexOf("http") < 0)
return "INVALID URL";
var p = link.split(".");
return p[0] + "." + p[1] + "." + p[2] + size + "." + p[3];
}
Imgur.prototype.validateImage = function (img) {
//var type = "file";// file, base64 or URL
if (typeof (img) === "string") {
if (img.indexOf(":image") > -1) {
img = img.split(",");
if (img.length < 2) {
console.log("Formato base64 no válido.");
return null;
}
img = img[1];
//img = encodeURIComponent(img);
return {
type: "base64",
image: img
};
} else if (img.indexOf("http") > -1) {
return {
type: "url",
image: img
};
} else {
console.log("La imagen no es una URL valida.");
return null;
}
} else if (img.type === null || typeof(img.type) === "undefined" || !img || !img.type.match(/image.*/)) {
console.log("Objeto FILE no válido.");
return null;
}
return {
type: 'file',
image: img
};
}
Imgur.prototype.createAlbum = function (title) {
var fd = new FormData();
fd.append("title", title);
fd.append('layout', 'grid');
var xhr = new XMLHttpRequest();
xhr.open("POST", this.params.url_album);
xhr.setRequestHeader("Authorization", "Client-ID " + this.params.client_id);
xhr.onload = function () {
var values = JSON.parse(xhr.responseText);
console.log("Se ha creado el album:");
console.log(values);
};
xhr.send(fd);
}
Imgur.prototype.formatResponse = function (r) {
if (typeof (r.data) !== 'undefined') {
var link = r.data.link;
r["upload"] = {
links: {
n: link,
original: link,
small_square: this.resizeLink('s', link),
big_square: this.resizeLink('b', link),
small_thumbnail: this.resizeLink('t', link),
medium_thumbnail: this.resizeLink('m', link),
largue_thumbnail: this.resizeLink('l', link),
huge_thumbnail: this.resizeLink('h', link)
},
image: r.data
};
//Eliminar datos repetidos!
delete r.data;
}
return r;
};
Imgur.prototype.upload = function (image) {
var result = this.validateImage(image);
console.log(result);
if (result === null) {
return;
}
var context = this;
var fd = new FormData();
fd.append("key", this.params.token);
//fd.append("type", result.image);
fd.append("album", this.params.album.hash);
fd.append("image", result.image);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = this.on_progress;
xhr.open("POST", this.params.url_upload);
xhr.setRequestHeader("Authorization", "Client-ID " + this.params.client_id);
xhr.onload = function () {
var values = JSON.parse(xhr.responseText);
console.log(values);
if (context.format_response) {
values = context.formatResponse(values);
}
if (context.on_upload !== null) {
context.on_upload(values);
}
};
xhr.onerror = function (r) {
console.log(r);
if (context.on_error !== null) {
context.on_error(r);
}
};
xhr.send(fd);
};
function ImgurUpload(){
this.count = 0;
this.max = 0;
this.multiple = false;
this.progressBar = null;
this.labelDescription = null;
this.targetOnLoad = null;
}
ImgurUpload.prototype.set = function(progressBar, labelDescription, targetOnLoad, multiple) {
this.progressBar = document.getElementById(progressBar);
this.labelDescription = document.getElementById(labelDescription);
this.targetOnLoad = targetOnLoad;
this.multiple = multiple;
};
ImgurUpload.prototype.setAndUpload = function(progressBar, labelDescription, targetOnLoad, multiple) {
this.set(progressBar, labelDescription, targetOnLoad, multiple);
this.upload();
};
ImgurUpload.prototype.upload = function() {
var c = this;
var file = document.createElement("input");
$(file).css("display", "none");
$(file).attr("type", "file");
if (this.multiple) {
$(file).attr("multiple", "");
}
$(file).attr("name", "filesToUpload[]");
$(file).appendTo("body");
$(file).change(function(){
var files = $(this).prop("files");
c.uploadMulti(files);
//"ImgurUploader.uploadMulti(this.files)"
});
file.click();
};
ImgurUpload.prototype.uploadMulti = function(files) {
this.count = 0;
this.max = 0;
for (var count in files) {
this.uploadOne(files[count]);
}
};
ImgurUpload.prototype.uploadOne = function(file) {
++this.max;
var c = this;
var imgur = new Imgur();
if (imgur.validateImage(file) === null)
return;
imgur.on_progress = function (D) {
var porcentaje = D.loaded / D.total;
$(c.labelDescription).html("Subiendo imagen [" + c.count + "/" + c.max + "]: " + file.name + " (" + Math.round(porcentaje * 100) + "%)");
$(c.progressBar).val(porcentaje);
};
imgur.on_upload = function (values) {
console.log("Se ha subido una imagen.");
++c.count;
if (c.count >= c.max) {
if (c.count > 1) {
$(c.labelDescription).html("Se han subido " + c.count + " imagenes.");
} else {
$(c.labelDescription).html("Se ha subido la imagen.");
}
}
if(c.targetOnLoad !== null){
c.targetOnLoad(values);
}
};
imgur.upload(file);
};
ImgurUpload.prototype.createAlbum = function(title) {
var imgur = new Imgur();
imgur.createAlbum(title);
};
var ImgurUploader = new ImgurUpload();
/*
var ImgurUploader = {
count: 0,
max: 0,
multiple: false,
progressBar: null,
labelDescription: null,
targetOnLoad: null,
set: function (progressBar, labelDescription, targetOnLoad, multiple) {
this.labelDescription = document.getElementById(labelDescription);
this.progressBar = document.getElementById(progressBar);
this.targetOnLoad = targetOnLoad;
this.multiple = multiple;
},
setAndUpload: function (progressBar, labelDescription, targetOnLoad, multiple) {
this.set(progressBar, labelDescription, targetOnLoad, multiple);
this.upload();
},
upload: function () {
var file = document.createElement("input");
$(file).css("display", "none");
$(file).attr("type", "file");
if (this.multiple) {
$(file).attr("multiple", "");
}
$(file).attr("name", "filesToUpload[]");
$(file).appendTo("body");
$(file).attr("onchange", "ImgurUploader.uploadMulti(this.files)");
file.click();
},
uploadMulti: function (files) {
this.count = 0;
this.max = 0;
for (var count in files) {
this.uploadOne(files[count]);
}
},
uploadOne: function (file) {
++this.max;
var imgur = new Imgur();
if (imgur.validateImage(file) === null)
return;
imgur.on_progress = function (D) {
var porcentaje = D.loaded / D.total;
$(ImgurUploader.labelDescription).html("Subiendo imagen [" + ImgurUploader.count + "/" + ImgurUploader.max + "]: " + file.name + " (" + Math.round(porcentaje * 100) + "%)");
$(ImgurUploader.progressBar).val(porcentaje);
};
imgur.on_upload = function (values) {
console.log("Se ha subido una imagen.");
++ImgurUploader.count;
if (ImgurUploader.count >= ImgurUploader.max) {
if (ImgurUploader.count > 1) {
$(ImgurUploader.labelDescription).html("Se han subido " + ImgurUploader.count + " imagenes.");
} else {
$(ImgurUploader.labelDescription).html("Se ha subido la imagen.");
}
}
ImgurUploader.targetOnLoad(values);
};
imgur.upload(file);
},
createAlbum: function (title) {
var imgur = new Imgur();
imgur.createAlbum(title);
}
};*/
|
"use strict";
const {test} = require('../browser');
const Menu = require('../pages/Menu');
const HomePage = require('../pages/Home');
const LocationPage = require('../pages/Location');
const assert = require('assert');
var tab;
var menu;
var homePage;
var locationPage;
var contactPage;
describe('On the landing page', () => {
it('it shows me the title', test(async (browser, options) => {
tab = await browser.newPage();
await tab.goto(options.appUrl);
this.menu = new Menu(tab);
this.homePage = new HomePage(tab);
await this.homePage.common.awaitH1();
const innerText = await this.homePage.common.getH1Content();
assert.equal(innerText, this.homePage.pageH1Text);
}));
it('and it shows the same title after a menu click', test(async (browser, opts) => {
this.homePage = await this.menu.clickMenuHome();
await this.homePage.common.awaitFooter();
const innerText = await this.homePage.common.getH1Content();
assert.equal(innerText, this.homePage.pageH1Text);
}));
});
describe('On the location page', () => {
it('there is a map', test(async (browser, opts) => {
this.locationPage = await this.menu.clickMenuLocation();
const newLocal = this.locationPage.page;
// Check for content of Iframe contains "Womerton"
const frames = await newLocal.frames();
await newLocal.evaluate(async() => { setTimeout(function(){ console.log('waiting'); }, 4000);});
await newLocal.screenshot({path: './screenshot-full.png', fullPage: true});
const frame = await frames.find(f => f.name() === 'googlemap');
//assert.con
//mapFrame.page
}));
});
describe('On the contact page', () => {
it('it shows me the title', test(async (browser, opts) => {
this.contactPage = await this.menu.clickMenuContact();
await this.contactPage.common.awaitH1();
const innerText = await this.contactPage.common.getH1Content();
assert.equal(innerText, this.contactPage.pageH1Text);
}));
it('but when you submit empty fields it theres a no message error', test(async (browser, opts) => {
await this.contactPage.clearForm();
await this.contactPage.submitTheForm();
const messageErrorShown = await this.contactPage.isMessageErrorShown();
assert.ok(messageErrorShown);
}));
it('if the message is filled, theres an email message error', test(async (browser, opts) => {
await this.contactPage.clearForm();
await this.contactPage.fillMessage("Test Message");
await this.contactPage.submitTheForm();
const messageErrorShown = await this.contactPage.isMessageErrorShown();
assert.ok(!messageErrorShown);
const emailErrorShown = await this.contactPage.isEmailErrorShown();
assert.ok(emailErrorShown);
}));
it('if the message and email are filled the page submits', test(async (browser, opts) => {
await this.contactPage.clearForm();
await this.contactPage.fillMessage("Test Message");
await this.contactPage.fillEmail("a@b.com");
await this.contactPage.submitTheForm();
await this.contactPage.common.awaitH1();
const innerText = await this.contactPage.common.getH1Content();
assert.equal(innerText, 'Thank you');
}));
});
|
import { library } from '@fortawesome/fontawesome-svg-core';
import { faBook } from '@fortawesome/free-solid-svg-icons/faBook';
import { faCog } from '@fortawesome/free-solid-svg-icons/faCog';
import { faAngleLeft } from '@fortawesome/free-solid-svg-icons/faAngleLeft';
import { faAngleRight } from '@fortawesome/free-solid-svg-icons/faAngleRight';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons/faArrowLeft';
import { faArrowRight } from '@fortawesome/free-solid-svg-icons/faArrowRight';
import { faFlag } from '@fortawesome/free-solid-svg-icons/faFlag';
import { faWindowMaximize } from '@fortawesome/free-solid-svg-icons/faWindowMaximize';
import { faDatabase } from '@fortawesome/free-solid-svg-icons/faDatabase';
import { faDownload } from '@fortawesome/free-solid-svg-icons/faDownload';
import { faComments } from '@fortawesome/free-solid-svg-icons/faComments';
import { faHome } from '@fortawesome/free-solid-svg-icons/faHome';
import { faMoon } from '@fortawesome/free-solid-svg-icons/faMoon';
import { faEye } from '@fortawesome/free-solid-svg-icons/faEye';
import { faEyeSlash } from '@fortawesome/free-solid-svg-icons/faEyeSlash';
import { faExclamationCircle } from '@fortawesome/free-solid-svg-icons/faExclamationCircle';
import { faTasks } from '@fortawesome/free-solid-svg-icons/faTasks';
import { faTimes } from '@fortawesome/free-solid-svg-icons/faTimes';
import { faThList } from '@fortawesome/free-solid-svg-icons/faThList';
import { faPen } from '@fortawesome/free-solid-svg-icons/faPen';
import { faPlus } from '@fortawesome/free-solid-svg-icons/faPlus';
import { faRss } from '@fortawesome/free-solid-svg-icons/faRss';
import { faSave } from '@fortawesome/free-solid-svg-icons/faSave';
import { faSun } from '@fortawesome/free-solid-svg-icons/faSun';
import { faUser } from '@fortawesome/free-solid-svg-icons/faUser';
function setupIcons() {
library.add(
faBook,
faCog,
faAngleLeft,
faAngleRight,
faArrowLeft,
faArrowRight,
faFlag,
faWindowMaximize,
faDatabase,
faDownload,
faComments,
faHome,
faMoon,
faEye,
faEyeSlash,
faExclamationCircle,
faTasks,
faTimes,
faThList,
faPen,
faPlus,
faRss,
faSave,
faSun,
faUser
);
}
export default setupIcons;
|
/* eslint-env mocha */
'use strict';
var expect = require('expect.js');
var nj = require('../../src');
describe('exp', function () {
it('should work on scalars', function () {
expect(nj.exp(0).tolist())
.to.eql([1]);
});
it('should work on vectors', function () {
var x = nj.arange(3);
expect(nj.exp(x).tolist())
.to.eql([1, Math.exp(1), Math.exp(2)]);
});
});
|
'use strict';
const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const baseConfig = require('../../.electron-vue/webpack.renderer.config');
const projectRoot = path.resolve(__dirname, '../../src/renderer');
// Set BABEL_ENV to use proper preset config
process.env.BABEL_ENV = 'test';
let webpackConfig = merge(baseConfig, {
devtool: '#inline-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"testing"'
})
]
});
// don't treat dependencies as externals
delete webpackConfig.entry;
delete webpackConfig.externals;
delete webpackConfig.output.libraryTarget;
// apply vue option to apply isparta-loader on js
webpackConfig.module.rules.find(rule => rule.use.loader === 'vue-loader').use.options.loaders.js = 'babel-loader';
module.exports = config => {
config.set({
browsers: ['visibleElectron'],
client: {
useIframe: false
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
},
customLaunchers: {
'visibleElectron': {
base: 'Electron',
flags: [] // --show
}
},
frameworks: ['mocha', 'chai'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
reporters: ['spec', 'coverage'],
singleRun: true,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
}
});
};
|
$(document).ready(function() {
// inserts a project into the browse box
function insert_project(score,name,category,date,id) {
$('#project-panel').append(`
<div style='padding:0; margin:0; margin-bottom: 2px;' class='row'>
<div class='col-sm-1' style='text-align: center'>
<button class='btn btn-sandbox text-striking vote-count'>${score}</button>
</div>
<div class='col-sm-7' style='margin-bottom: 16px;'>
<a href='/projects/${id}'>
<h3 style='font-size: 12px; padding:0; padding-top: 2px; margin: 0;'> ${name} • ${category} • ${moment(date).format('DD/MM/YYYY')}</h3>
</a>
</div>
<div style='text-align: right' class='col-sm-4'>
<button style='height: 25px; font-size: 10px;' onclick='window.location=\'/projects/${id}\'' class='btn btn-sandbox bg-discover-minor'>
View
</button>
</div>
</div>`)
}
let category = 'All'
let sort = $('#sort-type').val()
let amount = 10
// GET request projects, and add them to the page
var update_projects = function(amount) {
$.ajax({
type: 'GET',
url: window.location + "/projects?sort=" + sort + "&amount=" + amount + "&category=" + category,
success: function(data)
{
var outdata = JSON.parse(data)
if(outdata)
{
var projects = outdata.projects
$("#project-panel").empty()
for(var n in projects)
{
var project = projects[n]
var num = (sort=="views" ? project.views : project.num_votes)
insert_project(num,project.name,project.category,project.created_at,project.project_id)
}
$("#project-panel").append(
"<div class='col-sm-12' style='text-align: center'>" +
"<button id='show-more' style='border: none; margin-left: 0 auto; margin-top: 8px; border-radius: 6px; margin-bottom: 2px; padding: 4px; border-bottom: 2px groove rgba(0,0,0,0.15); display:inline-block; width: 100%; background-color: rgba(0,0,0,0.05);'> Show More </a>"
)
$("#show-more").click(function()
{
console.log("showed more")
amount = amount+10
update_projects(amount)
})
}
//console.log(comments)
},
error: function(error)
{
console.log("error")
}
});
}
// setting categories
$(".category").click(function()
{
category = $(this).text()
$(".category").css("background-color","rgba(0,0,0,0.10)");
$(this).css("background-color","rgba(0,0,0,0.25)");
amount = 10
update_projects(amount);
})
// set default category
$($(".category")[0]).click()
$( "#sort-type" ).change(function() {
sort = $("#sort-type").val()
amount = 10
update_projects(amount)
});
})
|
const assert = require('chai').assert;
const path = require('path');
const fs = require('fs');
const valid_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'valid.apib'), 'utf8');
const warning_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'warning.apib'), 'utf8');
const error_fixture = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'error.apib'), 'utf8');
const valid_refract = require('../fixtures/valid.parse.json');
const valid_sourcemap_refract = require('../fixtures/valid.parse.sourcemap.json');
const warning_parse_refract = require('../fixtures/warning.parse.json');
const warning_validate_refract = require('../fixtures/warning.validate.json');
const error_refract = require('../fixtures/error.json');
module.exports = (parser) => {
describe('Parse sync', () => {
it('valid fixture without options should return parse result', () => {
const refract = parser.parseSync(valid_fixture);
assert.deepEqual(refract, valid_refract);
});
it('valid fixture with options should return parse result', () => {
const refract = parser.parseSync(valid_fixture, { generateSourceMap: true });
assert.deepEqual(refract, valid_sourcemap_refract);
});
it('error fixture without options should return parse result', () => {
const refract = parser.parseSync(error_fixture);
assert.deepEqual(refract, error_refract);
});
it('warning fixture without options should return parse result', () => {
const refract = parser.parseSync(warning_fixture);
assert.deepEqual(refract, warning_parse_refract);
});
});
describe('Validate sync', () => {
it('valid fixture without options should return null', () => {
const refract = parser.validateSync(valid_fixture);
assert.isNull(refract);
});
it('valid fixture with options should return null', () => {
const refract = parser.validateSync(valid_fixture, {});
assert.isNull(refract);
});
it('error fixture without options should return annotations', () => {
const refract = parser.validateSync(error_fixture);
assert.deepEqual(refract, error_refract);
});
it('warning fixture without options should return annotations', () => {
const refract = parser.validateSync(warning_fixture);
assert.deepEqual(refract, warning_validate_refract);
});
});
};
|
$(document).ready(function(){
var pessoa = [];
pessoa[0] = [];
pessoa[0]["nome"] = "Emilia";
pessoa[0]["secreto"] = "Odete";
pessoa[0]["senha"] = "812w";
pessoa[1] = [];
pessoa[1]["nome"] = "jose carlos";
pessoa[1]["secreto"] = "Eusterio";
pessoa[1]["senha"] = "a12b";
pessoa[2] = [];
pessoa[2]["nome"] = "lazaro";
pessoa[2]["secreto"] = "Carlos Eduardo(Márcia)";
pessoa[2]["senha"] = "v37z";
pessoa[3] = [];
pessoa[3]["nome"] = "suely";
pessoa[3]["secreto"] = "Flávinho";
pessoa[3]["senha"] = "afg9";
pessoa[4] = [];
pessoa[4]["nome"] = "bruno";
pessoa[4]["secreto"] = "Lucinha";
pessoa[4]["senha"] = "tu8z";
pessoa[5] = [];
pessoa[5]["nome"] = "carlos eduardo";
pessoa[5]["secreto"] = "Dinda";
pessoa[5]["senha"] = "72fw";
pessoa[6] = [];
pessoa[6]["nome"] = "miguel";
pessoa[6]["secreto"] = "Honofre";
pessoa[6]["senha"] = "c1h3";
pessoa[7] = [];
pessoa[7]["nome"] = "santinha";
pessoa[7]["secreto"] = "Miguel";
pessoa[7]["senha"] = "ade9";
pessoa[8] = [];
pessoa[8]["nome"] = "reginaldo";
pessoa[8]["secreto"] = "Jeferson(Celismar)";
pessoa[8]["senha"] = "a9g8";
pessoa[9] = [];
pessoa[9]["nome"] = "ze";
pessoa[9]["secreto"] = "Manoel(irmão suelene)";
pessoa[9]["senha"] = "c11d";
pessoa[10] = [];
pessoa[10]["nome"] = "yuiara";
pessoa[10]["secreto"] = "Zélia";
pessoa[10]["senha"] = "9w3y";
pessoa[11] = [];
pessoa[11]["nome"] = "honofre";
pessoa[11]["secreto"] = "Eraldinho";
pessoa[11]["senha"] = "379f";
pessoa[12] = [];
pessoa[12]["nome"] = "lainara";
pessoa[12]["secreto"] = "Daniela(Sueyller)";
pessoa[12]["senha"] = "e94w";
pessoa[13] = [];
pessoa[13]["nome"] = "suelene";
pessoa[13]["secreto"] = "Laisla";
pessoa[13]["senha"] = "a3z7";
pessoa[14] = [];
pessoa[14]["nome"] = "sueyller";
pessoa[14]["secreto"] = "Márcia(Celismar)";
pessoa[14]["senha"] = "y12y";
pessoa[15] = [];
pessoa[15]["nome"] = "moises";
pessoa[15]["secreto"] = "Yuiara";
pessoa[15]["senha"] = "27ew";
pessoa[16] = [];
pessoa[16]["nome"] = "laisla";
pessoa[16]["secreto"] = "Rose";
pessoa[16]["senha"] = "wy28";
pessoa[17] = [];
pessoa[17]["nome"] = "reinaldo";
pessoa[17]["secreto"] = "Everaldo";
pessoa[17]["senha"] = "82y9";
pessoa[18] = [];
pessoa[18]["nome"] = "silas";
pessoa[18]["secreto"] = "Suely";
pessoa[18]["senha"] = "45wy";
pessoa[19] = [];
pessoa[19]["nome"] = "marcia";
pessoa[19]["secreto"] = "Jeferson";
pessoa[19]["senha"] = "y98w";
pessoa[20] = [];
pessoa[20]["nome"] = "geisielma";
pessoa[20]["secreto"] = "zé(filho eusterio)";
pessoa[20]["senha"] = "vjc9";
pessoa[21] = [];
pessoa[21]["nome"] = "jeferson celismar";
pessoa[21]["secreto"] = "Lainara";
pessoa[21]["senha"] = "w279";
pessoa[22] = [];
pessoa[22]["nome"] = "celismar";
pessoa[22]["secreto"] = "Emília";
pessoa[22]["senha"] = "cw10";
pessoa[23] = [];
pessoa[23]["nome"] = "manoel";
pessoa[23]["secreto"] = "Miller";
pessoa[23]["senha"] = "j399";
pessoa[24] = [];
pessoa[24]["nome"] = "marcia do everaldo";
pessoa[24]["secreto"] = "José Carlos";
pessoa[24]["senha"] = "d4f6";
pessoa[25] = [];
pessoa[25]["nome"] = "morgana";
pessoa[25]["secreto"] = "Sueyller";
pessoa[25]["senha"] = "97wz";
pessoa[26] = [];
pessoa[26]["nome"] = "eusterio";
pessoa[26]["secreto"] = "Morgana";
pessoa[26]["senha"] = "12fj";
pessoa[27] = [];
pessoa[27]["nome"] = "eraldinho";
pessoa[27]["secreto"] = "Reinaldo";
pessoa[27]["senha"] = "t43w";
pessoa[28] = [];
pessoa[28]["nome"] = "everaldo";
pessoa[28]["secreto"] = "Marivaldo(sobrinho suelene)";
pessoa[28]["senha"] = "97wt";
pessoa[29] = [];
pessoa[29]["nome"] = "fagner";
pessoa[29]["secreto"] = "...";//------------------------
pessoa[29]["senha"] = "r7q1";
pessoa[30] = [];
pessoa[30]["nome"] = "dinda";
pessoa[30]["secreto"] = "Celismar(irmão suelene)";
pessoa[30]["senha"] = "93ty";
pessoa[31] = [];
pessoa[31]["nome"] = "marivaldo";
pessoa[31]["secreto"] = "Lazaro";
pessoa[31]["senha"] = "c3e4";
pessoa[32] = [];
pessoa[32]["nome"] = "zelia";
pessoa[32]["secreto"] = "Geisielma";
pessoa[32]["senha"] = "p3w9";
pessoa[33] = [];
pessoa[33]["nome"] = "isadora";
pessoa[33]["secreto"] = "Bruno";
pessoa[33]["senha"] = "ab9w";
pessoa[34] = [];
pessoa[34]["nome"] = "muller";
pessoa[34]["secreto"] = "Silas";
pessoa[34]["senha"] = "w8z9";
pessoa[35] = [];
pessoa[35]["nome"] = "daniela";
pessoa[35]["secreto"] = "Moises(filho Everaldo)";
pessoa[35]["senha"] = "r8w3";
pessoa[36] = [];
pessoa[36]["nome"] = "jeferson";
pessoa[36]["secreto"] = "Alicia";
pessoa[36]["senha"] = "7421";
pessoa[37] = [];
pessoa[37]["nome"] = "lucinha";
pessoa[37]["secreto"] = "Santinha";
pessoa[37]["senha"] = "y2vz";
pessoa[38] = [];
pessoa[38]["nome"] = "flavio";
pessoa[38]["secreto"] = "Márcia(Everaldo)";
pessoa[38]["senha"] = "73yj";
pessoa[39] = [];
pessoa[39]["nome"] = "rose";
pessoa[39]["secreto"] = "Reginaldo(sobrinho suelene)";
pessoa[39]["senha"] = "aazz";
pessoa[40] = [];
pessoa[40]["nome"] = "joao";
pessoa[40]["secreto"] = "...";
pessoa[40]["senha"] = "2f57";//---------------------------
pessoa[41] = [];
pessoa[41]["nome"] = "odete";
pessoa[41]["secreto"] = "Suelene";
pessoa[41]["senha"] = "d37b";
pessoa[42] = [];
pessoa[42]["nome"] = "alicia";
pessoa[42]["secreto"] = "Isadora";
pessoa[42]["senha"] = "d1v9";
var quantidade = 42;
$("#sortear").click(function(){
var nome;
var senha;
nome = $("#nome").val();
senha = $("#senha").val();
nome = nome.toLowerCase(); //ignorando maiuscula e minuscula
//senha = senha.toLowerCase();
var p = pessoa[0]["nome"];
p = p.toLowerCase();
pessoa[0]["nome"]= p;
var i = 0;
var teste = 0;
while(pessoa[i]["nome"] != nome){
p = pessoa[i]["nome"];
p = p.toLowerCase();
pessoa[i]["nome"]= p;
if(i>=quantidade){
alert("Nome Incorreto, Tente denovo");
teste = 1;
break;
}
i = i + 1;
}
if (teste == 0) {
/*var teste2 = pessoa[i]["senha"];
teste2.toLowerCase();
pessoa[i]["senha"]= teste2;*/
if(pessoa[i]["senha"] != senha){
alert("Senha Incorreta, Tente denovo");
}else{
var texto = nome + ", seu amigo secreto é:" + pessoa[i]["secreto"];
$("#painel2").html(texto);
$("#painel2").show();
$("#painel1").hide();
$("#painel3").show();
$("#limpar").click(function(){
$("#nome").val("");
$("#senha").val("");
$("#painel1").show();
$("#painel2").hide();
$("#painel3").hide();
});
$("#sair").click(function(){
window.close();
});
}
}
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = require("../../models/config");
const app_utils_1 = require("../../utilities/app-utils");
const dynamic_path_parser_1 = require("../../utilities/dynamic-path-parser");
const stringUtils = require('ember-cli-string-utils');
const Blueprint = require('../../ember-cli/lib/models/blueprint');
exports.default = Blueprint.extend({
description: '',
aliases: ['i'],
anonymousOptions: [
'<interface-type>'
],
availableOptions: [
{
name: 'app',
type: String,
aliases: ['a'],
description: 'Specifies app name to use.'
}
],
normalizeEntityName: function (entityName) {
const appConfig = app_utils_1.getAppFromConfig(this.options.app);
const parsedPath = dynamic_path_parser_1.dynamicPathParser(this.project, entityName, appConfig);
this.dynamicPath = parsedPath;
return parsedPath.name;
},
locals: function (options) {
const interfaceType = options.args[2];
this.fileName = stringUtils.dasherize(options.entity.name);
if (interfaceType) {
this.fileName += '.' + interfaceType;
}
const prefix = config_1.CliConfig.getValue('defaults.interface.prefix');
return {
dynamicPath: this.dynamicPath.dir,
flat: options.flat,
fileName: this.fileName,
prefix: prefix
};
},
fileMapTokens: function () {
// Return custom template variables here.
return {
__path__: () => {
this.generatePath = this.dynamicPath.dir;
return this.generatePath;
},
__name__: () => {
return this.fileName;
}
};
}
});
//# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/blueprints/interface/index.js.map |
/* globals $, _ */
/* globals QUnit, test, asyncTest, expect, start, stop, ok, equal, notEqual, deepEqual */
var sinon = require('sinon');
var Environment = require('test/environment');
var EventLog = require('test/EventLog');
var ExampleData = require('example/ExampleData');
var Post = require('example/model/Post');
var CommentWithPostCollection = require('example/collection/CommentWithPostCollection');
//use Environment to mock ajax
QUnit.module('Model', _.extend(new Environment(), {
setup: function() {
Environment.prototype.setup.apply(this, arguments);
},
afterEach: function() {
window.router = undefined;
}
}));
var PostRemote = Post.extend({relationships: _.clone(Post.prototype.relationships)});
PostRemote.prototype.relationships.comments = _.extend({}, PostRemote.prototype.relationships.comments, {remote: 'autoload'});
test('Can instantiate', function(){
var model = new Post();
model.set({id: 1, body: 'my body'});
equal(model.get('body'), 'my body');
});
//
// Url
//
test('uses href for url', function(){
var model = new Post({href: '/foo'});
equal(model.url(), '/foo');
});
test('return null if no href and no urlRoot', function(){
var model = new Post();
model.urlRoot = false;
equal(model.url(), null);
});
test('use urlIdAttribute to generate url when no href', function(){
var model = new Post({name: 'foo'});
model.urlIdAttribute = 'name';
equal(model.url(), model.urlRoot + '/foo');
});
test('can override getUrlId for more complex urlId', function(){
var model = new Post();
model.getUrlId = function() {return 'abc/123';};
equal(model.url(), model.urlRoot +'/abc/123');
});
test('combines query params from href and view state', function(){
var model = new Post({href: '/foo?a=1', bar: 'baz'});
model.viewAttrs = ['bar'];
equal(model.urlWithParams(), '/foo?a=1&bar=baz');
});
test('navigate and updateUrl use viewUrl', function() {
var PostWithViewUrl = Post.extend({
viewUrlWithParams: function() {return '/bar';}
});
var model = new PostWithViewUrl({
href: '/foo'
});
try {
window.router = {navigateWithQueryParams: sinon.spy()};
model.navigate();
equal(window.router.navigateWithQueryParams.getCall(0).args[0], '/bar');
model.updateUrl();
equal(window.router.navigateWithQueryParams.getCall(1).args[0], '/bar');
} finally {
window.router = undefined;
}
});
//
// isNew
//
test('model with new href is new', function() {
var model = new Post({href: '/foo'});
ok(!model.isNew());
model.set('href', '/foo/new');
ok(model.isNew());
});
//
// Relationships
//
test('Can instantiate related', function(){
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
//try both set and fetch
for (var i=0; i<2; i++) {
var model = new Post({id: 1});
var eventLog = new EventLog(model);
if (i===0) {
model.set(ExampleData.POST_DATA_WITH_RELATED);
model.onLoad();
} else {
model.load();
}
equal(eventLog.counts.load, 1, 'should fire load event');
var comments = model.getRelated('comments');
var comment1 = comments.at(0);
var user1 = comment1.getRelated('user');
equal(model.get('body'), 'my body');
equal(comments.size(), 2);
equal(comments.at(1).get('id'), 6);
equal(comments.getRelated('post'), model);
equal(comment1.get('body'), 'my comment');
equal(comment1.getRelated('post'), model);
equal(user1.get('username'), 'user1');
equal(comments.fetched, true, 'relations should be marked as fetched');
equal(comment1.fetched, true, 'relations should be marked as fetched');
}
});
test('Can instantiate related href', function(){
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED_HREFS};
var model = new Post();
model.set(ExampleData.POST_DATA_WITH_RELATED_HREFS);
equal(model.getRelated('author').url(), '/users/7');
equal(model.getRelated('comments').url(), '/comments');
});
test('Can instantiate related collection with attributes', function(){
var model = new Post();
model.set(ExampleData.POST_DATA_WITH_COMMENTS_WITH_ATTRIBTES);
equal(model.getRelated('comments').url(), '/comments');
equal(model.getRelated('comments').size(), 2);
});
test('Can instantiate remote related collection with href', function(){
var model = new PostRemote();
model.set(ExampleData.POST_DATA_WITH_RELATED_HREFS);
equal(model.getRelated('comments').url(), '/comments');
});
//
// Loading
//
test('Related collection fires load', function(){
var model = new Post({id: 1, comments: []});
var eventLog = new EventLog([model, model.getRelated('comments')]);
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
model.load();
equal(eventLog.counts.load, 2, 'both model and related collection should fire load');
equal(eventLog.log[0].emitter, model, 'model should fire load first');
equal(eventLog.log[1].emitter, model.getRelated('comments'), 'collection should fire load second');
});
test('Does not load again while already loading', function(assert){
var model = new Post({id: 1, comments: []});
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
this.ajaxAsync = true;
var done = assert.async();
model.load({success: function() {
equal(this.ajaxCount, 1, 'should not load while loading');
done();
}.bind(this)});
model.load({success: function() {
ok(false, 'should not load again');
}});
this.ajaxAsync = false;
});
test('setting other variables does not affect related models', function() {
var model = new Post({id: 1, comments: []});
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
model.load();
model.set('foo', 'bar');
equal(model.getRelated('comments').size(), ExampleData.POST_DATA_WITH_RELATED.comments.length);
// again with force create
var PostForce = Post.extend({relationships: _.clone(Post.prototype.relationships)});
PostForce.prototype.relationships.comments = _.extend({}, PostForce.prototype.relationships.comments, {
forceCreate: true
});
model = new PostForce(ExampleData.POST_DATA_WITH_RELATED);
model.load();
model.set('foo', 'bar');
equal(model.getRelated('comments').size(), ExampleData.POST_DATA_WITH_RELATED.comments.length);
});
test('load events happen in correct order', function() {
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
for (var i=0; i<2; i++) {
var model = new Post({id: 1, comments: []});
var eventLog = new EventLog([model, model.getRelated('comments')]);
if (i===0) {
model.set(ExampleData.POST_DATA_WITH_RELATED);
model.onLoad();
} else {
model.load();
}
equal(eventLog.counts.load, 2, 'both load');
var loadEvents = _.where(eventLog.log, {event: 'load'});
equal(loadEvents[0].emitter, model, 'root model fires load first');
equal(loadEvents[1].emitter, model.getRelated('comments'), 'children fire load after');
}
});
test('Loading', function(){
var post = new Post(ExampleData.POST_DATA);
equal(post.fetched, false);
var eventLog = new EventLog(post);
post.load();
equal(post.fetched, true);
equal(eventLog.counts.beginLoad, 1, 'beginLoad should have been triggered');
equal(eventLog.counts.load, 1, 'load should have been triggered');
equal(this.ajaxCount, 1, 'fetch should make an async call');
});
test('Load error', function(){
var post = new Post({id: 1});
var eventLog = new EventLog(post);
this.ajaxResponseStatus = 'error';
var errorHandler = sinon.spy();
post.load({error: errorHandler});
equal(post.fetched, false);
equal(eventLog.counts.error, 1, 'error should have been triggered');
ok(errorHandler.calledOnce, 'error handler should have been called');
});
test('Error on invalid remote param', function() {
PostRemote.prototype.relationships.comments.remote = 'foo';
try {
new PostRemote(ExampleData.POST_DATA_WITH_EMPTY_COMMENTS);
ok(false, 'should throw on unknown remote param');
} catch(e) {
ok(true);
}
});
test('Remote relationship', function(){
PostRemote.prototype.relationships.comments.remote = 'autoload';
var post = new PostRemote(ExampleData.POST_DATA_WITH_EMPTY_COMMENTS);
var comments = post.getRelated('comments');
sinon.spy(comments, 'resetInMemory');
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_EMPTY_COMMENTS};
post.load();
ok(!comments.resetInMemory.called, 'remote relationship should not be reset in memory');
equal(this.ajaxCount, 2, 'should fetch both parent and remote children');
post.load();
equal(this.ajaxCount, 4, 'should fetch again when root model loads');
});
test('do not autoload for remote = manual', function(){
PostRemote.prototype.relationships.comments.remote = 'manual';
var post = new PostRemote(ExampleData.POST_DATA_WITH_RELATED);
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
post.load();
equal(this.ajaxCount, 1, 'should not load related');
equal(post.getRelated('comments').loadOnShow, undefined, 'do not mark for load on show');
});
test('defer load when remote = loadOnShow', function(){
PostRemote.prototype.relationships.comments.remote = 'loadOnShow';
var post = new PostRemote(ExampleData.POST_DATA_WITH_EMPTY_COMMENTS);
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED_HREFS};
equal(post.getRelated('comments').loadOnShow, true, 'should flag model as defer load');
post.load();
equal(this.ajaxCount, 1, 'should fetch both parent and remote children');
var comments = post.getRelated('comments');
equal(comments.loadOnShow, true, 'should flag model as defer load');
ok(!comments.fetched, 'loadOnShow children should not be fetched');
comments.fetch();
delete comments.loadOnShow;
equal(this.ajaxCount, 2);
post.load();
equal(this.ajaxCount, 4);
});
test('Force create relationship', function(){
var post = new Post(ExampleData.POST_DATA);
equal(post.getRelated('comments'), undefined, 'should not created related comments unless forced');
var PostForce = Post.extend({relationships: _.clone(Post.prototype.relationships)});
PostForce.prototype.relationships.comments = _.extend({}, PostForce.prototype.relationships.comments, {
forceCreate: true
});
post = new PostForce(ExampleData.POST_DATA);
var comments = post.getRelated('comments');
var commentEventCount = this.countEvents(comments);
equal(comments.size(), 0, 'should have force created related comments');
equal(comments.fetched, false, 'force created model should not have fetched flag set');
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
post.load();
equal(commentEventCount.load, 1, 'original comments should fire load');
});
test('Circular Relationship', function() {
var PostCirc = Post.extend({relationships: _.clone(Post.prototype.relationships)});
PostCirc.prototype.relationships.comments = _.extend({}, PostCirc.prototype.relationships.comments, {
modelCls: CommentWithPostCollection
});
this.ajaxResponse = {results: ExampleData.POST_DATA_WITH_RELATED};
for (var i=0; i<2; i++) {
var model = new PostCirc({id: 1});
if (i===0) {
model.set(ExampleData.POST_DATA_WITH_RELATED);
model.onLoad();
} else {
model.load();
}
var comments = model.getRelated('comments');
var comment1 = comments.at(0);
equal(comment1.fetched, true);
}
});
test('Relationship with no data in response should be considered fetched', function() {
var post = new Post({id: 1, comments: []});
this.ajaxResponse = ExampleData.POST_DATA;
var eventCount = this.countEvents(post.getRelated('comments'));
equal(post.getRelated('comments').fetched, false);
post.load();
equal(post.getRelated('comments').fetched, true);
equal(eventCount.load, '1', 'Comments should fire load');
});
test('Query params included in load url', function() {
var PostWithQuery = Post.extend({getQueryParams: function() {
return {foo: '1'};
}});
var post = new PostWithQuery({id: 1, comments: []});
this.ajaxResponse = ExampleData.POST_DATA;
post.load();
equal(this.syncArgs.options.data.foo, post.getQueryParams().foo, 'request url should include query params');
post.load({data:{bar: '2'}});
deepEqual(this.syncArgs.options.data, {foo: '1', bar: '2'}, 'request url should include data option');
});
test('View state', function(){
var PostWithViewState = Post.extend({viewAttrs: ['tab', 'filter']});
var post = new PostWithViewState({id: 1});
this.ajaxResponse = ExampleData.POST_WITH_VIEW_STATE;
post.load();
var tab = ExampleData.POST_WITH_VIEW_STATE.tab;
var queryParams = post.getQueryParams();
equal(queryParams.tab, tab, 'query params should include view state');
var postJson = post.toJSON();
equal(postJson.tab, undefined, 'should not include view state in json to persist');
postJson = post.toViewJSON();
equal(postJson.tab, tab, 'should include view state in view json');
equal(post.get('tab'), tab);
var eventLog = new EventLog(post);
post.set('tab');
equal(eventLog.counts['change:tab'], 1, 'should fire change event');
});
test('urlWithParams accepts overrides', function() {
var PostWithViewState = Post.extend({viewAttrs: ['tab', 'filter']});
var post = new PostWithViewState(ExampleData.POST_WITH_VIEW_STATE);
equal(post.urlWithParams(), '/posts/1?tab=detail');
equal(post.urlWithParams({foo: 'bar', tab: 'foo'}), '/posts/1?tab=foo&foo=bar', 'should override view params');
});
test('display name', function() {
var post = new Post({name: 'foo'});
equal(post.getDisplayName(), undefined);
equal(post.toViewJSON().displayName, undefined);
var PostWithDisplayName = Post.extend({displayNameAttr: 'name'});
post = new PostWithDisplayName({name: 'foo'});
equal(post.getDisplayName(), 'foo');
equal(post.toViewJSON().displayName, 'foo', 'should include displayName in view json');
});
//
// Saving
//
test('saving', function() {
var post = new Post();
post.set(ExampleData.POST_DATA);
var eventLog = new EventLog(post);
this.ajaxResponse = {
meta: {success: true},
result: ExampleData.POST_DATA
};
post.save();
equal(eventLog.counts.load, 1, 'should fire load on save');
// save failed
this.ajaxResponse = {
meta: {success: false, message: 'oops', message_class: 'bad'}
};
post.save();
equal(eventLog.counts.load, 1, 'should not fire load again');
equal(eventLog.counts.invalid, 1, 'should fire invalid');
this.ajaxResponse = {
meta: {success: false, validationError: {'body':'too short'}}
};
post.save();
equal(eventLog.counts.load, 1, 'should not fire load again');
equal(eventLog.counts.invalid, 2, 'should fire invalid');
}); |
var companion = require('companion');
var sinon = require('sinon');
var expect = require("chai").expect;
var assert = require("chai").assert;
var Sequenx = require('../js/sequenx.js');
// Mock
var customLog = {
createChild: () => { },
info: () => { },
warning: () => { },
error: () => { },
name: "",
dispose: () => { }
}
// Test
describe("Lapse", function() {
before(function() {
Sequenx.Log.isEnabled = false;
})
it("should be able to create a lapse instance", function() {
var lapse = new Sequenx.Lapse("lapse");
expect(lapse).instanceof(Sequenx.Lapse);
});
it("should be able to create with custom log", function() {
var lapse = new Sequenx.Lapse(customLog);
expect(lapse).instanceof(Sequenx.Lapse);
});
it("should be able start empty lapse", function() {
var lapse = new Sequenx.Lapse(customLog);
lapse.start();
});
it("should be able to start empty Lapse and receive complete", function(done) {
var lapse = new Sequenx.Lapse(customLog);
lapse.start(done);
});
it("should be able to sustain Lapse and dispose it after start", function(done) {
var lapse = new Sequenx.Lapse(customLog);
var subLapse = lapse.sustain("sub lapse");
lapse.start(done);
subLapse.dispose();
});
it("should not complete if never start", function() {
var lapse = new Sequenx.Lapse(customLog);
var subLapse = lapse.sustain("sub lapse");
lapse.start(() => assert.fail("should be never call complete"));
});
it("should be able to sustain Lapse and dispose it before start", function(done) {
var lapse = new Sequenx.Lapse(customLog);
var subLapse = lapse.sustain("sub lapse");
subLapse.dispose();
lapse.start(done);
});
it("should be able to sustain Lapse 2 time and receive complete after dispose 2 lapse", function(done) {
var lapse = new Sequenx.Lapse(customLog);
var subLapse = lapse.sustain("sub lapse");
var sub2Lapse = lapse.sustain("sub2 lapse");
var lasDisposed;
lapse.start(function() {
expect(lasDisposed).to.equal(true);
done();
});
subLapse.dispose();
lasDisposed = true;
sub2Lapse.dispose();
});
it("should be able to create a sequence from lapse (sequence)", function(done) {
var lapse = new Sequenx.Lapse(customLog);
lapse.sequence(seq => {
expect(seq).instanceof(Sequenx.Sequence);
done();
});
lapse.start();
});
it("should be able to create a child lapse (child)", function(done) {
var lapse = new Sequenx.Lapse("main");
lapse.child(l => {
expect(l).instanceof(Sequenx.Lapse);
});
lapse.start(done);
});
describe("Log test", function() {
it("should be able to retrieve log name", function() {
var lapse = new Sequenx.Lapse("lapse");
expect(lapse.name).to.equal("lapse");
});
it("should be able log Lapse on substain", function() {
Sequenx.Log.isEnabled = true;
sinon.spy(customLog, "info");
var clog = console.log;
console.log = () => { }
var log = new Sequenx.Log();
var lapse = new Sequenx.Lapse(customLog);
lapse.sustain("sustain");
lapse.dispose();
lapse.start();
console.log = clog;
expect(customLog.info.callCount, "info not called").to.equal(2)
expect(customLog.info.getCall(0).args[0]).to.be.equal("Sustain sustain");
expect(customLog.info.getCall(1).args[0]).to.be.equal("Cancelling");
customLog.info = () => { };
});
});
describe("Sequence extension", function() {
it("should be able to create a sequence from lapse and wait sequence complete", function(done) {
var lapse = new Sequenx.Lapse(customLog);
var spy = "";
lapse.sequence(seq => {
expect(seq).instanceof(Sequenx.Sequence);
seq.do(done => {
spy += "A";
setTimeout(() => done(), 50);
});
});
lapse.start(function() {
expect(spy).to.equal("AB");
done();
});
spy += "B";
});
it("should be able to create a sequence from lapse and wait sequence complete", function(done) {
var seq = new Sequenx.Sequence(customLog);
seq.doLapse(lapse => {
var d = lapse.sustain()
expect(lapse).instanceof(Sequenx.Lapse);
setTimeout(() => d.dispose(), 50);
});
seq.start(() => done());
});
});
}); |
'use strict';
angular.module('weatherApp.version.version-directive', [])
.directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}]);
|
export { default } from 'ember-cli-chartnew/components/ember-chartnew'; |
var marked = require('marked');
module.exports = function () {
return function(input, strip) {
return marked(input).replace(/<[^>]+>/g, '');
};
}; |
import PropTypes from 'prop-types';
import React from 'react';
import previewStyle from './defaultPreviewStyle';
export default function DateTimePreview({ value }) {
return <div style={previewStyle}>{value ? value.toString() : null}</div>;
}
DateTimePreview.propTypes = {
value: PropTypes.object,
};
|
Accounts.onCreateUser(function(options, user) {
if (Meteor.users.find().count() >= App.maxUsers) throw new Meteor.Error("too_many_users");
if (options.profile) {
user.profile = options.profile;
}
user.profile.week_ends = Math.floor(Math.random()*7);
Schema.Users.clean(user);
return user;
}) |
#!/usr/bin/env node
'use strict';
const net = require('net');
const objectPath = require('object-path'); // replace with .jq receipt?
const notifier = require('node-notifier');
const { SOCKET_PATH, runGcmInquirer } = require('./shared');
const argv = require('minimist')(process.argv.slice(2));
if (argv['setup-gcm']) {
runGcmInquirer();
return;
}
const client = net.createConnection(SOCKET_PATH);
const cliLog = console.log.bind(console);
const notify = message => notifier.notify({ title: 'xavier', message });
const log = argv.notify ? notify : cliLog;
const args = { id: argv._[0], args: argv._.slice(1), argv };
client.on('error', err => {
log(`failed to connect to server: ${err}`);
});
client.on('connect', () => {
client.write(JSON.stringify(args));
});
client.on('data', input => {
let result;
try {
result = JSON.parse(input.toString());
} catch (e) {
log(`Can't parse:\n${input.toString()}`);
return;
}
if (argv.path) {
try {
log(objectPath.get(result, argv.path));
} catch (err) {
log(err);
}
return;
}
if (argv.verbose) {
log(JSON.stringify({ args, result }));
} else if (typeof result.message === 'string') {
log(`${args.id}: ${result.message}`);
} else {
log(JSON.stringify(result));
}
client.end();
});
|
/**
* View para
* @class
* @author
* @name ViewTemplate
*/
define(["jquery",
"underscore",
"backbone",
//el template del view.
"text!templates/common/navbar-tmpl.html"],
function($,_,Backbone,tmpl) {
return Backbone.View.extend({
/**
* Constructor de la clase
* @function
*
* @name #initialize
* @param options {Object}
*/
initialize : function(options) {
//si tiene permitido cargar este view
this.on('allowed', this.allowed, this);
this.setup(options);
},
/**
* Json que mapea los eventos a los handlers
* @field
* @type Object
* @name #events
*/
events:{},
/**
* Si posee los permisos para cargar el view, se configuran
* los eventos y se realizan las peticiones para obtener los
* datos.
* @function
*
* @name #allowed
* @param options {Object}
*/
allowed : function(options) {
this.render();
},
/**
* Este metodo se encarga de renderizar el view
* @function
*
* @public
* @name #render
* @author
*/
render: function () {
var compTmpl = _.template(tmpl,{});
this.$el.html(compTmpl);
return this;
}
});
}
);
|
/*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifes the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
app.import(app.bowerDirectory + "/js-cookie/src/js.cookie.js");
return app.toTree();
};
|
var uploadChunk;
uploadChunk = function(blob, url, method, filename, chunk, chunks) {
var formData, xhr;
xhr = new XMLHttpRequest;
xhr.open(method, url, false);
xhr.onerror = function() {
throw new Error('error while uploading');
};
formData = new FormData;
formData.append('name', filename);
formData.append('chunk', chunk);
formData.append('chunks', chunks);
formData.append('file', blob);
xhr.send(formData);
return xhr.responseText;
};
this.onmessage = function(e) {
var blob, blobs, bytes_per_chunk, data, end, file, i, j, len, method, name, response, size, start, url;
file = e.data.file;
url = e.data.url;
method = e.data.method || 'POST';
name = e.data.name;
blobs = [];
bytes_per_chunk = 1024 * 1024 * 10;
start = 0;
end = bytes_per_chunk;
size = file.size;
while (start < size) {
blobs.push(file.slice(start, end));
start = end;
end = start += bytes_per_chunk;
}
for (i = j = 0, len = blobs.length; j < len; i = ++j) {
blob = blobs[i];
response = uploadChunk(blob, url, method, name, i, blobs.length);
data = {
message: 'progress',
body: ((i + 1) * 100 / blobs.length).toFixed(0)
};
this.postMessage(data);
}
data = {
message: 'load',
body: response
};
return this.postMessage(data);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.