code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Home from '@/pages/home/home.vue'
import Category from '@/pages/category/category.vue'
import List from '@/pages/list/list.vue'
import Detail from '@/pages/detail/detail.vue'
import Cart from '@/pages/cart/cart.vue'
import My from '@/pages/my/my.vue'
import Login from '@/pages/login/login.vue'
import Error from '../components/404.vue'
Vue.use(Router)
export default new Router({
linkActiveClass: 'active',
routes: [
{
path: '/',
name: 'Home',
component: Home
},{
path:'/home',
component: Home
},{
path:'/category',
name:'Category',
component: Category
},{
path:'/list/:id',
name:'List',
component: List
},{
path:'/detail/:id',
name:'Detail',
component: Detail
},{
path:'/cart',
name:'Cart',
component: Cart
},{
path:'/my',
name:'My',
component: My
},
{
path:'/login',
name:'Login',
component: Login
},
{
path:'/404',
name:'Error',
component: Error
},
{
path: "*",
redirect: '/404'
}
]
})
| D-gitlong/vue-douban | src/router/index.js | JavaScript | gpl-3.0 | 1,220 |
'use strict';
// Production specific configuration
// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
8080,
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME ||
'mongodb://admin:admin@dogen.mongohq.com:10052/wisdimo-dev'
}
}; | vivanov1410/wisdimo-app | server/config/environment/production.js | JavaScript | gpl-3.0 | 624 |
$(function() {
$('#activities').dataTable({
'order': [[ 0, 'desc' ]]
});
});
| DigitalNZ/supplejack_manager | app/javascript/src/admin/activities.js | JavaScript | gpl-3.0 | 85 |
"use strict";
module.exports = function(sequelize, DataTypes) {
var Actor = sequelize.define("Actor", {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false},
en_us: DataTypes.STRING,
zh_cn: DataTypes.STRING,
zh_hk: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
Actor.belongsToMany(models.Movie, {through: 'movie_actors'})
}
},
tableName: 'actors',
createdAt: false,
deletedAt: false,
updatedAt: false,
underscored: true
});
return Actor;
}; | albertchan/buttery | server/models/actors.js | JavaScript | gpl-3.0 | 642 |
/*
From everpolate.js --> https://github.com/BorisChumichev/everpolate/tree/master/lib
The MIT License (MIT)
Copyright (c) 2015 Boris Chumichev
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.*/
/**
* constructor for Interpolator "class"
*
* @param xValues array of values representing existing x-values
* @param yValues array of values representing existing y-values
* @param xyValues 2-dimensional array representing known values of the function, so that f(xValues[i], yValues[j]) = xyValues[i][j]
* @constructor
*/
function Interpolator(xValues, yValues, xyValues) {
var thiz = this;
/**
* bilinear interpolates values using the arrays given with the constructor.
* uses bilinear interpolation algorithm described at https://en.wikipedia.org/wiki/Bilinear_interpolation
* (1) interpolate in x direction, (2) interpolate in y direction
*
* @param x
* @param y
* @return {Array}
*/
thiz.interpolateBilinear = function (x, y) {
var interpolX = [];
xyValues.forEach(function (values) {
interpolX.push(evaluatePolynomial(x, xValues, values));
});
return evaluatePolynomial(y, yValues, interpolX);
};
thiz.interpolateBilinearArray = function(xArray, yArray) {
var result = [];
yArray.forEach(function (yVal) {
var row = [];
xArray.forEach(function (xVal) {
row.push(thiz.interpolateBilinear(xVal, yVal))
});
result.push(row);
});
return result;
};
/**
* Evaluates interpolating polynomial at the set of numbers
* or at a single number for the function y=f(x)
*
* @param {Number|Array} pointsToEvaluate number or set of numbers
* for which polynomial is calculated
* @param {Array} functionValuesX set of distinct x values
* @param {Array} functionValuesY set of distinct y=f(x) values
* @returns {Array} interpolating polynomial
*/
function evaluatePolynomial(pointsToEvaluate, functionValuesX, functionValuesY) {
var results = []
pointsToEvaluate = makeItArrayIfItsNot(pointsToEvaluate)
// evaluate the interpolating polynomial for each point
pointsToEvaluate.forEach(function (point) {
results.push(nevillesIteratedInterpolation(point, functionValuesX, functionValuesY))
})
return results
};
/**
* Neville's Iterated Interpolation algorithm implementation
* http://en.wikipedia.org/wiki/Neville's_algorithm <- for reference
*
* @param {Number} x number for which polynomial is calculated
* @param {Array} X set of distinct x values
* @param {Array} Y set of distinct y=f(x) values
* @returns {number} interpolating polynomial
*/
function nevillesIteratedInterpolation(x, X, Y) {
var Q = [Y]
for (var i = 1; i < X.length; i++) {
Q.push([])
for (var j = 1; j <= i; j++) {
Q[j][i] = ((x - X[i - j]) * Q[j - 1][i] - (x - X[i]) * Q[j - 1][i - 1]) / ( X[i] - X[i - j] )
}
}
return Q[j - 1][i - 1]
}
function makeItArrayIfItsNot(input) {
return Object.prototype.toString.call(input) !== '[object Array]'
? [input]
: input
}
}
window.interpolator = new Interpolator(); | ProjectKitchen/RoboFriend | src/Pi/static/lib/everpolate.polynomial.js | JavaScript | gpl-3.0 | 4,097 |
'use strict'
const restify = require('restify')
const config = require('./config.js')
const PORT = config.port || 3000
const redis = require('redis')
const FwoReportApi = require('./models/FwoReportApi.js')
const request = require('request')
const JSONStream = require('JSONStream')
const es = require('event-stream')
let server = restify.createServer({})
server.use(restify.queryParser())
server.use(restify.plugins.bodyParser())
// building report list
let report_list = []
request(config.json_documents_url)
.pipe(JSONStream.parse())
.pipe(es.mapSync(data => {
report_list.push(data)
}))
.on('end', () => {
console.log('Report list loaded')
api.set_reports(report_list)
})
// connecting to redis
let redis_client = {}
if(config.redis.connect) {
redis_client = redis.createClient(config.redis.port, config.redis.host, {no_ready_check: true})
redis_client.on('connect', function() {
console.log('Connected to Redis')
})
}
let api = new FwoReportApi(server, redis_client)
server.pre((req, res, next) => {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate')
res.header('Expires', '-1')
res.header('Pragma', 'no-cache, no-store')
return next()
})
server.post('/:action', api.action)
server.get('/list', api.list)
server.get(/\/?.*/, restify.serveStatic({
directory: './public',
default: 'index.html'
}))
server.listen(PORT, () => {
console.log('Employer Watch Fwo Reports API is running on port', PORT)
})
| oventi/employer-watch | apps/fwo_reports_api/index.js | JavaScript | gpl-3.0 | 1,531 |
Espo.define('she:views/hi-email/record/edit-quick', 'views/record/edit', function (Dep, Detail) {
return Dep.extend({
fullFormDisabled: true,
isWide: true,
sideView: false,
bottomView: null,
dropdownItemList: []
});
});
| flashnot/espocrm-skyeng-tt | client/modules/SHE/src/views/hi-email/record/edit-quick.js | JavaScript | gpl-3.0 | 274 |
function has_changed(){
$j('#pencil_icon').show();
$j('#save_button').show();
changed_flag = true;
}
| mercadolibre/cacique | public/javascripts/editor_changes.js | JavaScript | gpl-3.0 | 113 |
define(['module', 'plugCubed/Class', 'plugCubed/Notifications', 'plugCubed/Version', 'plugCubed/StyleManager', 'plugCubed/Settings', 'plugCubed/Lang', 'plugCubed/Utils',
'plugCubed/RoomSettings', 'plugCubed/dialogs/Menu', 'plugCubed/CustomChatColors', 'plugCubed/handlers/ChatHandler', 'plugCubed/handlers/CommandHandler', 'plugCubed/handlers/DialogHandler', 'plugCubed/handlers/FullscreenHandler', 'plugCubed/handlers/HideVideoHandler', 'plugCubed/handlers/VolumeSliderHandler', 'plugCubed/Features', 'plugCubed/Tickers', 'plugCubed/dialogs/panels/Panels', 'plugCubed/overrides/RoomUserListRow', 'plugCubed/Overrides', 'plugCubed/Socket'
], function(module, Class, Notifications, Version, Styles, Settings, p3Lang, p3Utils, RoomSettings, Menu, CustomChatColors, ChatHandler, CommandHandler, DialogHandler, FullscreenHandler, HideVideoHandler, VolumeSliderHandler, Features, Tickers, Panels, p3RoomUserListRow, Overrides, Socket) {
var Loader;
var loaded = false;
var RoomUsersListView = window.plugCubedModules.RoomUsersListView;
var original = RoomUsersListView.prototype.RowClass;
function __init() {
p3Utils.chatLog(undefined, p3Lang.i18n('running', Version) + '</span><br><span class="chat-text" style="color:#66FFFF">' + p3Lang.i18n('commandsHelp'), Settings.colors.infoMessage1, -10);
$('head').append('<link rel="stylesheet" type="text/css" id="plugcubed-css" href="https://plugcubed.net/scripts/release/plugCubed.css?v=' + Version.getSemver() + '"/>');
var users = API.getUsers();
for (var i = 0; i < users.length; i++) {
if (p3Utils.getUserData(users[i].id, 'joinTime', -1) < 0) {
p3Utils.setUserData(users[i].id, 'inRoom', true);
p3Utils.setUserData(users[i].id, 'joinTime', Date.now());
}
}
RoomUsersListView.prototype.RowClass = p3RoomUserListRow;
Overrides.override();
initBody();
window.plugCubed.version = Version.getSemver();
window.plugCubed.chatHistory = [];
window.plugCubed.emotes = {
twitchEmotes: {},
twitchSubEmotes: {},
tastyEmotes: {},
bttvEmotes: {},
customEmotes: {},
emoteHash: {},
ffzEmotes: {},
rcsEmotes: {}
};
window.thedark1337 = window.plugCubed.thedark1337 =
'\nโโโโโโโโโ โโโ โโ โโโโโโ โโโโโโโ โโโ โโโโโโ โโ โโโ โโ โโโโโโโ โโโโโโโ โโโโโโโ' +
'\nโ โโโ โโโโโโ โโโโโ โ โโโโ โโโโโโโโโ โโโ โ โโโ โโโโโ โโ โ โโ โ โ โโ โ โโโโโ' +
'\nโ โโโโ โโโโโโโโโโโโโโ โโโ โโโโโ โโโ โโโ โโโ โโโโโโโ โโ โโโโ โโโโ โโ' +
'\nโ โโโโ โ โโโ โโโ โโโ โ โโโโ โโโโโโโโโโ โโโโโโโ โโโ โโ โโ โ โ โโ' +
'\n โโโโ โ โโโโโโโโโโโโโโโโโโโโโโ โโ โโโโโโโโ โโโโโโโโ โโ โโ โโโโโโ โโโโโโ โโ' +
'\n โ โโ โ โโโโโโโ โโ โ โโโ โ โโ โโโโโ โโ โโโโโ โโ โโ โโ โโ โ โโ โ โโ ' +
'\n โ โ โโโ โ โ โ โ โ โ โ โ โโ โ โโ โ โโโ โโ โโ โโ โโ โ โโ โ โ' +
'\n โ โ โโ โ โ โ โ โ โ โ โโ โ โ โโ โ โ โ โ โ โ' +
'\n โ โ โ โ โ โ โ โ โ โ โ โ โ ' +
'\n โ โ โ ' +
'\n ';
Features.register();
Notifications.register();
Tickers.register();
CommandHandler.register();
ChatHandler.register();
FullscreenHandler.create();
HideVideoHandler.create();
VolumeSliderHandler.register();
Settings.load();
RoomSettings.update();
Socket.connect();
if (p3Utils.getRoomID() === 'tastycat') RoomSettings.rules.allowShowingMehs = false;
Panels.register();
DialogHandler.register();
loaded = true;
if (typeof console.timeEnd === 'function') console.timeEnd('[plugยณ] Loaded');
}
function initBody() {
var rank = p3Utils.getRank();
if (rank === 'dj') rank = 'residentdj';
$('body').addClass('rank-' + rank + ' id-' + API.getUser().id);
}
Loader = Class.extend({
init: function() {
if (loaded) return;
// Define UserData in case it's not already defined (reloaded p3 without refresh)
if (typeof window.plugCubedUserData === 'undefined') {
window.plugCubedUserData = {};
}
// Load language and begin script after language loaded
p3Lang.load($.proxy(__init, this));
},
close: function() {
if (!loaded) return;
Menu.close();
RoomSettings.close();
Socket.disconnect();
Features.unregister();
Notifications.unregister();
Tickers.unregister();
Panels.unregister();
Styles.destroy();
ChatHandler.close();
FullscreenHandler.close();
HideVideoHandler.close();
CommandHandler.close();
DialogHandler.close();
VolumeSliderHandler.close();
RoomUsersListView.prototype.RowClass = original;
Overrides.revert();
var mainClass = module.id.split('/')[0];
var modules = Object.keys(require.s.contexts._.defined);
for (var i = 0, j = modules.length; i < j; i++) {
if (modules[i] && p3Utils.startsWith(modules[i], mainClass)) {
requirejs.undef(modules[i]);
}
}
$('#plugcubed-css,#p3-settings-wrapper').remove();
plugCubed = undefined;
}
});
return Loader;
});
| plugCubed/plugCubed | src/release/plugCubed/Loader.js | JavaScript | gpl-3.0 | 6,714 |
const env = require('env.json');
const mockDeckCards = require('mockData/deckCards').cards;
const mockDecks = require('mockData/decks').decks;
const mockUsers = require('mockData/users').users;
const mockNewUsers = require('mockData/newUsers').users;
const mockUserCards = require('mockData/userCards').cards;
const resCode = {
OK: 200,
SERVFAIL: 500,
NOTFOUND: 404,
CREATED: 201,
NOMOD: 304,
BADREQ: 400,
UNAUTH: 401,
FORBID: 403
};
const testDeckCard = 0;
const testDeck = 0;
const testUser = 0;
const testNewUser = 0;
const mongoIdRe = /^[0-9a-fA-F]{24}$/;
const userNameSettings = {
length: {
min: 2,
max: 21
}
};
const pswdSettings = {
length: {
min: 8,
max: 256
}
};
const invalidMongoId = 'a'.repeat(23);
const validMongoId = 'a'.repeat(24);
const validDate = new Date();
const invalidDate = new Date('invalid');
module.exports.config = () => {
var node_env = [process.env.NODE_ENV || 'dev'];
return env[node_env];
}
module.exports.mockUserCards = () => {
return mockUserCards;
}
module.exports.mockDeckCards = () => {
return mockDeckCards;
}
module.exports.mockDecks = () => {
return mockDecks;
}
module.exports.mockUsers = () => {
return mockUsers;
}
module.exports.mockNewUsers = () => {
return mockNewUsers;
}
module.exports.resCode = () => {
return resCode;
}
module.exports.testDeckCard = () => {
return testDeckCard;
}
module.exports.testDeck = () => {
return testDeck;
}
module.exports.testUser = () => {
return testUser;
}
module.exports.testNewUser = () => {
return testNewUser;
}
module.exports.mongoIdRe = () => {
return mongoIdRe;
}
module.exports.userNameSettings = () => {
return userNameSettings;
}
module.exports.pswdSettings = () => {
return pswdSettings;
}
module.exports.invalidMongoId = () => {
return invalidMongoId;
}
module.exports.validMongoId = () => {
return validMongoId;
}
module.exports.invalidDate = () => {
return invalidDate;
}
module.exports.validDate = () => {
return validDate;
} | nbuhay/flashCards | config.js | JavaScript | gpl-3.0 | 1,979 |
import React, {Component} from 'react';
export default class LinkPreview extends Component {
constructor(props) {
super(props);
}
static propTypes = {
title: React.PropTypes.string.isRequired,
description: React.PropTypes.string.isRequired,
url: React.PropTypes.string,
thumbnailUrl: React.PropTypes.string
};
render () {
var actionBlock;
let { embedUrl, title, url, thumbnailUrl, description } = this.props;
if (this.props.scraping) {
title="loading";
thumbnailUrl="/img/loading.gif";
description="Scraping......";
} else if (!title || !description) {
thumbnailUrl="/img/scrape-error-m.png";
description="Sorry, we are not able to process this url, please try again later or contact us if this persists."
title="Parse error :("
}
if (embedUrl) {
actionBlock = (
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={embedUrl} />
</div>
);
} else {
actionBlock = (
<div className="embed-responsive embed-responsive-16by9">
<a href={url}>
<img className="embed-responsive-item" src={thumbnailUrl ? thumbnailUrl : ''}/>
</a>
</div>
);
}
return (
<section className="link-preview" >
<header>
<h3>{title}</h3>
</header>
<div className="link-preview-body">
<div className="link-preview-action">
{actionBlock}
</div>
<div className="link-preview-description">
<p>{description}</p>
</div>
</div>
</section>
);
}
}
| MattMcFarland/tw-client | src/components/Common/FormFields/LinkPreview.js | JavaScript | gpl-3.0 | 1,695 |
var ivis_demo005__usinga_p_t_b_screen_8m =
[
[ "ivisDemo005_usingaPTBScreen", "ivis_demo005__usinga_p_t_b_screen_8m.html#aaf5367b43a15b2b4b86b17682f028dec", null ]
]; | petejonze/ivis | ivis/doc/API/src/ivis_demo005__usinga_p_t_b_screen_8m.js | JavaScript | gpl-3.0 | 170 |
var __v=[
{
"Id": 4244,
"Panel": 2063,
"Name": "่ชฟ็จๅ ๆฃง",
"Sort": 0,
"Str": ""
},
{
"Id": 4245,
"Panel": 2063,
"Name": "ๆณจๆ",
"Sort": 0,
"Str": ""
}
] | zuiwuchang/king-document | data/panels/2063.js | JavaScript | gpl-3.0 | 197 |
var AppCatalog, AppManifest, Directory, File, Fs, FsApp, Path, Project, Q, ServerError, Tar, Workspace,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Fs = require('fs');
Path = require('path');
Q = require('q');
Tar = require('tar-stream');
AppCatalog = require_harrogate_module('/shared/scripts/app-catalog.js');
Project = require('./project.js');
ServerError = require_harrogate_module('/shared/scripts/server-error.js');
FsApp = AppCatalog.catalog['Host Filesystem'].get_instance();
Directory = require(AppCatalog.catalog['Host Filesystem'].path + '/directory.js');
File = require(AppCatalog.catalog['Host Filesystem'].path + '/file.js');
AppManifest = require('./manifest.json');
Workspace = (function() {
function Workspace(ws_directory) {
this.ws_directory = ws_directory;
this.create_project = bind(this.create_project, this);
this.import_from_archive = bind(this.import_from_archive, this);
this.init = bind(this.init, this);
this.get_representation = bind(this.get_representation, this);
this.get_projects = bind(this.get_projects, this);
this.get_project = bind(this.get_project, this);
this.is_valid = bind(this.is_valid, this);
this.uri = AppManifest.web_api.projects.uri;
this.users = ['Default User'];
var users_path = Path.join(this.ws_directory.path, 'users.json');
try {
this.users = JSON.parse(Fs.readFileSync(users_path, 'utf8'));
} catch(e) {}
if(this.users.constructor === Array)
{
var new_users = {};
this.users.forEach(function(user) {
new_users[user] = {
mode: "Simple"
};
});
this.users = new_users;
}
}
Workspace.prototype.is_valid = function() {
return Q.all([this.ws_directory.is_valid()]).then(function(values) {
return values.reduce(function(previousValue, currentValue) {
return previousValue && currentValue;
});
});
};
Workspace.prototype.get_project = function(user, name) {
user = user || 'Default User';
return this.get_projects(user).then((function(_this) {
return function(projects) {
var project;
project = ((function() {
var i, len, results;
results = [];
for (i = 0, len = projects.length; i < len; i++) {
project = projects[i];
var user_valid = !user || user === project.user;
if (project.name === name && user_valid) {
results.push(project);
}
}
return results;
})())[0];
if (project == null) {
throw new ServerError(404, 'This workspace does not contain a project named ' + name);
}
return project;
};
})(this));
};
Workspace.prototype.sync_users = function() {
const file = Path.join(this.ws_directory.path, 'users.json');
Fs.writeFileSync(file, JSON.stringify(this.users));
}
Workspace.prototype.update_user = function(user, data) {
if(!(user in this.users)) return;
this.users[user] = data;
this.sync_users();
}
Workspace.prototype.add_user = function(user) {
if(user in this.users) return;
this.users[user] = {
mode: "Simple"
};
this.sync_users();
console.log("ADD USER!!!!!!!!!!!!");
}
Workspace.prototype.remove_user = function(user) {
if(user === 'Default User') return;
if(!(user in this.users)) return;
delete this.users[user];
var dir = Directory.create_from_path(Path.join(this.ws_directory.path, user));
this.sync_users();
return dir.remove();
}
Workspace.prototype.get_projects = function(user) {
user = user || 'Default User';
// a project has at least a project file *.project.json located in the workspace root
return this.ws_directory.get_children().then(function(children) {
// create the project resources (exclude non-folders)
return Q.all(children.filter(function (user_dir) {
return user_dir instanceof Directory;
}).map(function (user_dir) {
return user_dir.get_children().then(function (projects) {
var ret = {
user: user_dir.name,
projects: projects
};
return ret;
});
})).then(function (users) {
var user_projects = users.filter(function (o) {
return o.user === user;
})[0] || {projects: []};
return user_projects.projects.map(function (child) {
return new Project(child.name,
File.create_from_path(Path.join(child.path, 'project.manifest')),
Directory.create_from_path(Path.join(child.path, 'include')),
Directory.create_from_path(Path.join(child.path, 'src')),
Directory.create_from_path(Path.join(child.path, 'data')),
Directory.create_from_path(Path.join(child.path, 'bin')),
Directory.create_from_path(Path.join(child.path, 'lib')));
});
});
});
};
Workspace.prototype.get_representation = function(user) {
var representation;
representation = {
links: {
self: {
href: this.uri
},
ws_directory: {
href: this.ws_directory.uri
}
}
};
// get the projects
return this.get_projects(user).then(function(project_resources) {
// get the representation of all project resources
return Q.allSettled(project_resources.map(function(project_resource) {
return project_resource.get_representation(true);
}));
}).then(function(project_representation_promises) {
// add the projects (just the valid ones)
return project_representation_promises
.filter(function(promise) { return promise.state === 'fulfilled'; })
.map(function(promise) { return promise.value; });
}).then(function(values) {
representation.projects = values;
return representation;
});
};
Workspace.prototype.init = function() {};
Workspace.prototype.import_from_archive = function(pack) {
return Q.Promise((function(_this) {
return function(resolve, reject, notify) {
var extract;
extract = Tar.extract();
extract.on('entry', function(header, stream, callback) {
var file_name, project_name, ref, type, type_root_directory_resource;
ref = header.name.split('/'), project_name = ref[0], type = ref[1], file_name = ref[2];
// skip this file if any of project_name, type, file_name is not set
if ((project_name == null) || (type == null) || (file_name == null)) {
callback();
return;
}
type_root_directory_resource = (function() {
switch (type) {
case 'include':
return this.include_directory;
case 'src':
return this.src_directory;
case 'data':
return this.data_directory;
}
}).call(_this);
if (type_root_directory_resource == null) {
callback();
return;
}
return type_root_directory_resource.is_valid().then(function(valid) {
// create <ws>/<type> if it doesn't exist
if (!valid) {
return Q.nfcall(Fs.mkdir, type_root_directory_resource.path);
} else {
return Q(void 0);
}
}).then(function() {
// get the project resource
return _this.get_project(project_name);
}).then((function(project_resource) {
// the project already exist
return project_resource;
}), function(error) {
if (((error != null ? error.code : void 0) != null) && error.code === 404) {
// the project does not exist yet, create it
return _this.create_project('Default User', project_name, 'C');
} else {
// some other error happended, rethrow
throw error;
}
}).then(function(project_resource) {
var directory_resource;
// get the directory resource and check if it is valid (= existing)
directory_resource = (function() {
switch (type) {
case 'include':
return project_resource.include_directory;
case 'src':
return project_resource.src_directory;
case 'data':
return project_resource.data_directory;
}
})();
return [Q(directory_resource), directory_resource.is_valid()];
}).spread(function(directory_resource, valid) {
// create <ws>/<type> if it doesn't exist
return [Q(directory_resource), !valid ? Q.nfcall(Fs.mkdir, directory_resource.path) : Q(void 0)];
}).spread(function(directory_resource) {
var fs_write_stream;
// create the file
fs_write_stream = Fs.createWriteStream(Path.join(directory_resource.path, file_name));
stream.pipe(fs_write_stream);
return stream.on('end', function() {
return callback();
});
})["catch"](function(error) {
// an error happened, continue with the next file
console.log("Unexpected error while importing " + project_name + "/" + type + "/" + file_name);
console.log(error);
return callback();
}).done();
});
extract.on('error', function(error) {
return reject(error);
});
extract.on('finish', function() {
return resolve();
});
return pack.pipe(extract);
};
})(this));
};
Workspace.prototype.create_project = function(user, name, language, src_file_name) {
var content;
if (src_file_name == null) {
src_file_name = 'main.c';
}
// create the project file
content = JSON.stringify({
language: language,
user: user
});
var programContent;
if (language === 'Python')
{
programContent = '#!/usr/bin/python\n'
+ 'sys.path.append("/usr/lib")\n'
+ 'import os, sys\n'
+ 'import kipr as k\n'
+ '\n'
+ 'def main():\n'
+ ' print "Hello World"\n'
+ '\n'
+ 'if __name__== "__main__":\n'
+ ' sys.stdout = os.fdopen(sys.stdout.fileno(),"w",0)\n'
+ ' main();\n';
}
else
{
programContent = '#include <kipr/wombat.h>\n'
+ '\n'
+ 'int main()\n'
+ '{\n'
+ ' printf("Hello World\\n");\n'
+ ' return 0;\n'
+ '}\n';
}
return this.ws_directory.create_subdirectory(user, false).then((function (_root) {
return function (user_dir) {
return user_dir.create_subdirectory(name).then(function (project_dir) {
return project_dir.create_file('project.manifest', content, 'ascii').then(function(project_file) {
return new Project(name, project_file,
Directory.create_from_path(Path.join(project_dir.path, 'include')),
Directory.create_from_path(Path.join(project_dir.path, 'src')),
Directory.create_from_path(Path.join(project_dir.path, 'data')),
Directory.create_from_path(Path.join(project_dir.path, 'bin')),
Directory.create_from_path(Path.join(project_dir.path, 'lib')));
});
}).then(function(project_resource) {
return project_resource.include_directory.create().then(function() {
return project_resource.data_directory.create().then(function() {
return project_resource.src_directory.create().then(function() {
return project_resource.src_directory.create_file(src_file_name, programContent, 'ascii').then(function() {
return project_resource;
});
});
});
});
});
};
})(this));
};
return Workspace;
})();
module.exports = Workspace;
| kipr/harrogate | apps/programs/workspace.js | JavaScript | gpl-3.0 | 12,097 |
var searchData=
[
['has_5falignment',['has_alignment',['../othellier_8c.html#a9470b5f4c0cf9a638d84cdebef08a619',1,'has_alignment(Othellier *oth, short position, short color, short direction): othellier.c'],['../othellier_8h.html#aa51740d0e5c708bc4cc2c1dac1626618',1,'has_alignment(Othellier *oth, short pos, short color, short direction): othellier.c']]],
['has_5flegal_5fmove',['has_legal_move',['../game_8c.html#a9fdbfe69bd4f5da786d347b5466425a2',1,'has_legal_move(Game *game, int color): game.c'],['../game_8h.html#a9fdbfe69bd4f5da786d347b5466425a2',1,'has_legal_move(Game *game, int color): game.c']]]
];
| SunnyDjinn/GenOthello | doc/search/functions_6.js | JavaScript | gpl-3.0 | 633 |
// ==UserScript==
// @description Make VLC play youtube videos on another computer
// @include https://www.youtube.com/*
// @include https://youtu.be/*
// @include http://youtu.be/*
// @include http://youtube.com/*
// @include http://www.youtu.be/*
// @include https://www.youtu.be/*
// @include http://www.youtube.com/*
// @name YoutubeVLC
// @namespace ytvlc
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// ==/UserScript==
var url = encodeURIComponent(document.location.href);
var buttonParent = $("#watch7-secondary-actions");
buttonParent.append(function() {
return "<button class='addandplay yt-uix-button-epic-nav-item'>Play With VLC</button>";
});
$(".addandplay").click(
function () {
GM_xmlhttpRequest({
method: "GET",
url : "http://127.0.0.1:8080/addyoutube?url="+url+"&play=true",
onload : function(response) {
console.log(response.responseText);
}
});
});
buttonParent.append(function() {
return "<button class='vlcadd yt-uix-button-epic-nav-item'>Enqueue to VLC</button>";
});
$(".vlcadd").click(
function () {
GM_xmlhttpRequest({
method: "GET",
url : "http://127.0.0.1:8080/addyoutube?url="+url+"&play=false",
onload : function(response) {
console.log(response.responseText);
}
});
});
buttonParent.append(function() {
return "<button class='nextvideo yt-uix-button-epic-nav-item'>Next Video</button>";
});
$(".nextvideo").click(
function () {
GM_xmlhttpRequest({
method : "GET",
url : "http://127.0.0.1:8080/next",
onload : function(response) {
console.log(response);
}
});
});
| nisstyre56/youtubevlc | vlc.user.js | JavaScript | gpl-3.0 | 1,689 |
GNATdoc.SourceFile = {
"kind": "code",
"children": [
{
"kind": "line",
"number": 1,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Ada.Interrupts.Names"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 2,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "STM32.Timers"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 3,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "STM32.Device"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 4,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "STM32.GPIO"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 5,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 6,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Board"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 7,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Config"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 8,
"children": [
]
},
{
"kind": "line",
"number": 9,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "package"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Hall",
"href": "docs/amc_hall___spec.html#L9C9"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
}
]
},
{
"kind": "line",
"number": 10,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @summary"
}
]
},
{
"kind": "line",
"number": 11,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Hall Sensor"
}
]
},
{
"kind": "line",
"number": 12,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 13,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @description"
}
]
},
{
"kind": "line",
"number": 14,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Interfaces peripherals used for hall sensor handling using common AMC types."
}
]
},
{
"kind": "line",
"number": 15,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 16,
"children": [
]
},
{
"kind": "line",
"number": 17,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Nof_Valid_Hall_States",
"href": "docs/amc_hall___spec.html#L17C4"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "constant"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Positive"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "6"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 18,
"children": [
]
},
{
"kind": "line",
"number": 19,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "type"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "As_Pattern",
"href": "docs/amc_hall___spec.html#L19C23"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "True"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
}
]
},
{
"kind": "line",
"number": 20,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
}
]
},
{
"kind": "line",
"number": 21,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "case"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "As_Pattern"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
}
]
},
{
"kind": "line",
"number": 22,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "when"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "True"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
}
]
},
{
"kind": "line",
"number": 23,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Bits",
"href": "docs/amc_hall___spec.html#L23C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.Hall_Bits",
"href": "docs/amc_types___spec.html#L84C12"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 24,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "when"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "False"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
}
]
},
{
"kind": "line",
"number": 25,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H1_Pin",
"href": "docs/amc_hall___spec.html#L25C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 26,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H2_Pin",
"href": "docs/amc_hall___spec.html#L26C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 27,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H3_Pin",
"href": "docs/amc_hall___spec.html#L27C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 28,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "case"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 29,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
},
{
"kind": "span",
"cssClass": "text",
"text": " Unchecked_Union, Size => AMC_Types.Hall_Bits'Size"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 30,
"children": [
]
},
{
"kind": "line",
"number": 31,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "for"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "use"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
}
]
},
{
"kind": "line",
"number": 32,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Bits"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "at"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "range"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ".."
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "2"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 33,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H1_Pin"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "at"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "range"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ".."
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 34,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H2_Pin"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "at"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "range"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "1"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ".."
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "1"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 35,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "H3_Pin"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "at"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "range"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "2"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ".."
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "2"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 36,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 37,
"children": [
]
},
{
"kind": "line",
"number": 38,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "type"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State",
"href": "docs/amc_hall___spec.html#L38C9"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
}
]
},
{
"kind": "line",
"number": 39,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Current",
"href": "docs/amc_hall___spec.html#L39C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 40,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Previous",
"href": "docs/amc_hall___spec.html#L40C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 41,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "record"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";",
"href": "docs/amc_hall___spec.html#L38C9"
}
]
},
{
"kind": "line",
"number": 42,
"children": [
]
},
{
"kind": "line",
"number": 43,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "function"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Is_Initialized",
"href": "docs/amc_hall___spec.html#L43C13"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "return"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 44,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @return True if initialized."
}
]
},
{
"kind": "line",
"number": 45,
"children": [
]
},
{
"kind": "line",
"number": 46,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Initialize",
"href": "docs/amc_hall___spec.html#L46C14"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 47,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Initialize hall, i.e. timer peripheral."
}
]
},
{
"kind": "line",
"number": 48,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 49,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Initialize TIM4 peripheral as follows:"
}
]
},
{
"kind": "line",
"number": 50,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 51,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - Hall sensor inputs are connected to Ch1, Ch2, and Ch3."
}
]
},
{
"kind": "line",
"number": 52,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - TI1 is xor of all three channels."
}
]
},
{
"kind": "line",
"number": 53,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - Input capture IC1 is configured to capture at both edges of TI1."
}
]
},
{
"kind": "line",
"number": 54,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - TI1F_ED = TI1 is set to trigger a reset of the timer."
}
]
},
{
"kind": "line",
"number": 55,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - OC2 is configured to create a pulse delayed from the TRC = TI1F_ED event."
}
]
},
{
"kind": "line",
"number": 56,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - Interrupt at input capture and delayed pulse event."
}
]
},
{
"kind": "line",
"number": 57,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 58,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- This way it is possible to measure the time between two consecutive"
}
]
},
{
"kind": "line",
"number": 59,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- hall sensor changes and thus to estimate the speed of the motor."
}
]
},
{
"kind": "line",
"number": 60,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Also, it is possible to trigger the commutation of the BLDC based on"
}
]
},
{
"kind": "line",
"number": 61,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- the IC (or delayed pulse) interrupt."
}
]
},
{
"kind": "line",
"number": 62,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 63,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Configuration:"
}
]
},
{
"kind": "line",
"number": 64,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- APB1 is the clock source = 2*APB1 (2*45 MHz)"
}
]
},
{
"kind": "line",
"number": 65,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Using a prescaler of 225 and using all 16 bits yields:"
}
]
},
{
"kind": "line",
"number": 66,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - Resolution = 225 / 90 MHz = 2.5 us"
}
]
},
{
"kind": "line",
"number": 67,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- - Time until overflow = 2^16 * 225 / 90 MHz = 0.16384 s"
}
]
},
{
"kind": "line",
"number": 68,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- This allows for a speed down to 61 rpm before an overflow occurs."
}
]
},
{
"kind": "line",
"number": 69,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- At 10000 rpm, the resolution will be approx 2.5 us * (10000^2)/10 = 25 rpm"
}
]
},
{
"kind": "line",
"number": 70,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "--"
}
]
},
{
"kind": "line",
"number": 71,
"children": [
]
},
{
"kind": "line",
"number": 72,
"children": [
]
},
{
"kind": "line",
"number": 73,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "function"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Is_Standstill",
"href": "docs/amc_hall___spec.html#L73C13"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "return"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 74,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @return True if the hall sensor has not changed state for a while."
}
]
},
{
"kind": "line",
"number": 75,
"children": [
]
},
{
"kind": "line",
"number": 76,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "protected"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "State",
"href": "docs/amc_hall___state___spec.html#L76C14"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
}
]
},
{
"kind": "line",
"number": 77,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "pragma"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Interrupt_Priority"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Config.Hall_ISR_Prio"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 78,
"children": [
]
},
{
"kind": "line",
"number": 79,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "entry"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Await_New",
"href": "docs/amc_hall___state___spec.html#L79C13"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "New_State",
"href": "docs/amc_hall___state___spec.html#L79C24"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "out"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State",
"href": "docs/amc_hall___spec.html#L38C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 80,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Time_Delta_s",
"href": "docs/amc_hall___state___spec.html#L80C24"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "out"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.Seconds",
"href": "docs/amc_types___spec.html#L23C12"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 81,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Speed_Timer_Overflow",
"href": "docs/amc_hall___state___spec.html#L81C24"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "out"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 82,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Suspend the caller and wake it up again as soon as the hall sensor changes state."
}
]
},
{
"kind": "line",
"number": 83,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @param New_State New State."
}
]
},
{
"kind": "line",
"number": 84,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @param Time_Delta_s Time since previous state change."
}
]
},
{
"kind": "line",
"number": 85,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @param Speed_Timer_Overflow Indicates if the speed measurement has overflowed."
}
]
},
{
"kind": "line",
"number": 86,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- If true it means Time_Delta_s has reached its maximal possible value."
}
]
},
{
"kind": "line",
"number": 87,
"children": [
]
},
{
"kind": "line",
"number": 88,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "function"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Get",
"href": "docs/amc_hall___state___spec.html#L88C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "return"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State",
"href": "docs/amc_hall___spec.html#L38C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 89,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @return The current hall state."
}
]
},
{
"kind": "line",
"number": 90,
"children": [
]
},
{
"kind": "line",
"number": 91,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Update",
"href": "docs/amc_hall___state___spec.html#L91C17"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 92,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Reads the hall pins and updates the hall state."
}
]
},
{
"kind": "line",
"number": 93,
"children": [
]
},
{
"kind": "line",
"number": 94,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Set_Commutation_Delay_Factor",
"href": "docs/amc_hall___state___spec.html#L94C17"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Factor",
"href": "docs/amc_hall___state___spec.html#L94C47"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "in"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.Percent",
"href": "docs/amc_types___spec.html#L25C12"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 95,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Set a delay time from the hall state change occurs to the commutation event."
}
]
},
{
"kind": "line",
"number": 96,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @param Factor The delay as a factor of the time between the hall state changes."
}
]
},
{
"kind": "line",
"number": 97,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- E.g. Assume that the time between the hall changes state is 1 ms."
}
]
},
{
"kind": "line",
"number": 98,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Setting Factor=50% then means that the commutation event triggers 0.5 ms after the"
}
]
},
{
"kind": "line",
"number": 99,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- hall changes state."
}
]
},
{
"kind": "line",
"number": 100,
"children": [
]
},
{
"kind": "line",
"number": 101,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "function"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Overflow",
"href": "docs/amc_hall___state___spec.html#L101C16"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "return"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 102,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- @return True if the speed timer has overflowed."
}
]
},
{
"kind": "line",
"number": 103,
"children": [
]
},
{
"kind": "line",
"number": 104,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "private"
}
]
},
{
"kind": "line",
"number": 105,
"children": [
]
},
{
"kind": "line",
"number": 106,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "ISR",
"href": "docs/amc_hall___state___spec.html#L106C17"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
}
]
},
{
"kind": "line",
"number": 107,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " Attach_Handler => Ada.Interrupts.Names.TIM4_Interrupt"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 108,
"children": [
]
},
{
"kind": "line",
"number": 109,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State_Is_Updated",
"href": "docs/amc_hall___state___spec.html#L109C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "False"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 110,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- True when hall sensor has changed state"
}
]
},
{
"kind": "line",
"number": 111,
"children": [
]
},
{
"kind": "line",
"number": 112,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Capture_Overflow",
"href": "docs/amc_hall___state___spec.html#L112C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "True"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 113,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- True when speed timer has overflowed, i.e. very slow rotation"
}
]
},
{
"kind": "line",
"number": 114,
"children": [
]
},
{
"kind": "line",
"number": 115,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "State",
"href": "docs/amc_hall___state___spec.html#L115C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State",
"href": "docs/amc_hall___spec.html#L38C9"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
}
]
},
{
"kind": "line",
"number": 116,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Holds the state of the hall sensor"
}
]
},
{
"kind": "line",
"number": 117,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_State",
"href": "docs/amc_hall___spec.html#L38C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "'"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Current"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "'"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "As_Pattern"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "True"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ","
}
]
},
{
"kind": "line",
"number": 118,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Bits"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.Valid_Hall_Bits",
"href": "docs/amc_types___spec.html#L85C12"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "'"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "First"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ","
}
]
},
{
"kind": "line",
"number": 119,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Previous"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Hall_Pattern",
"href": "docs/amc_hall___spec.html#L19C9"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "'"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "As_Pattern"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "True"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ","
}
]
},
{
"kind": "line",
"number": 120,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Bits"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "=>"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.Valid_Hall_Bits",
"href": "docs/amc_types___spec.html#L85C12"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "'"
},
{
"kind": "span",
"cssClass": "identifier",
"text": "First"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 121,
"children": [
]
},
{
"kind": "line",
"number": 122,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Delay_Factor",
"href": "docs/amc_hall___state___spec.html#L122C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Float"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "range"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0.0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ".."
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "1.0"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0.0"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 123,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Time for commutation will be this Factor times the time since last state change"
}
]
},
{
"kind": "line",
"number": 124,
"children": [
]
},
{
"kind": "line",
"number": 125,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Speed_Timer_Counter",
"href": "docs/amc_hall___state___spec.html#L125C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Types.UInt32",
"href": "docs/amc_types___spec.html#L12C12"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "number",
"text": "0"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 126,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Timer counts since last hall state change"
}
]
},
{
"kind": "line",
"number": 127,
"children": [
]
},
{
"kind": "line",
"number": 128,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "State"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 129,
"children": [
]
},
{
"kind": "line",
"number": 130,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "protected"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Commutation",
"href": "docs/amc_hall___commutation___spec.html#L130C14"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "is"
}
]
},
{
"kind": "line",
"number": 131,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "pragma"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Interrupt_Priority"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "("
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Config.Hall_ISR_Prio"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ")"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 132,
"children": [
]
},
{
"kind": "line",
"number": 133,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "entry"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Await_Commutation",
"href": "docs/amc_hall___commutation___spec.html#L133C13"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 134,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Suspend the caller and wake it up again as soon as commutation shall occur."
}
]
},
{
"kind": "line",
"number": 135,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Nominally, the time for this commutation is the time since last hall state change plus"
}
]
},
{
"kind": "line",
"number": 136,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Time_Delta_s * Commutation_Delay_Factor,"
}
]
},
{
"kind": "line",
"number": 137,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- i.e. if factor is 0.5 then commutation is halfway between two hall state changes"
}
]
},
{
"kind": "line",
"number": 138,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- (assuming constant speed)."
}
]
},
{
"kind": "line",
"number": 139,
"children": [
]
},
{
"kind": "line",
"number": 140,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Manual_Trigger",
"href": "docs/amc_hall___commutation___spec.html#L140C17"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 141,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- Manually trigger a commutation event."
}
]
},
{
"kind": "line",
"number": 142,
"children": [
]
},
{
"kind": "line",
"number": 143,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "private"
}
]
},
{
"kind": "line",
"number": 144,
"children": [
]
},
{
"kind": "line",
"number": 145,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "procedure"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "ISR",
"href": "docs/amc_hall___commutation___spec.html#L145C17"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "with"
}
]
},
{
"kind": "line",
"number": 146,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " Attach_Handler => Ada.Interrupts.Names.TIM3_Interrupt"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 147,
"children": [
]
},
{
"kind": "line",
"number": 148,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Is_Commutation",
"href": "docs/amc_hall___commutation___spec.html#L148C7"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Boolean"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": ":="
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "False"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 149,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "comment",
"text": "-- True when commutation event occurs"
}
]
},
{
"kind": "line",
"number": 150,
"children": [
]
},
{
"kind": "line",
"number": 151,
"children": [
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "Commutation"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
},
{
"kind": "line",
"number": 152,
"children": [
]
},
{
"kind": "line",
"number": 153,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "private"
}
]
},
{
"kind": "line",
"number": 154,
"children": [
]
},
{
"kind": "line",
"number": 169,
"children": [
{
"kind": "span",
"cssClass": "keyword",
"text": "end"
},
{
"kind": "span",
"cssClass": "text",
"text": " "
},
{
"kind": "span",
"cssClass": "identifier",
"text": "AMC_Hall"
},
{
"kind": "span",
"cssClass": "identifier",
"text": ";"
}
]
}
],
"label": "amc_hall.ads"
}; | osannolik/ada-motorcontrol | doc/html/srcs/amc_hall.ads.js | JavaScript | gpl-3.0 | 84,938 |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Course index cm component.
*
* This component is used to control specific course modules interactions like drag and drop
* in both course index and course content.
*
* @module core_courseformat/local/courseeditor/dndcmitem
* @class core_courseformat/local/courseeditor/dndcmitem
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import {BaseComponent, DragDrop} from 'core/reactive';
export default class extends BaseComponent {
/**
* Configure the component drag and drop.
*
* @param {number} cmid course module id
*/
configDragDrop(cmid) {
this.id = cmid;
// Drag and drop is only available for components compatible course formats.
if (this.reactive.isEditing && this.reactive.supportComponents) {
// Init element drag and drop.
this.dragdrop = new DragDrop(this);
// Save dropzone classes.
this.classes = this.dragdrop.getClasses();
}
}
/**
* Remove all subcomponents dependencies.
*/
destroy() {
if (this.dragdrop !== undefined) {
this.dragdrop.unregister();
}
}
// Drag and drop methods.
/**
* Get the draggable data of this component.
*
* @returns {Object} exported course module drop data
*/
getDraggableData() {
const exporter = this.reactive.getExporter();
return exporter.cmDraggableData(this.reactive.state, this.id);
}
/**
* Validate if the drop data can be dropped over the component.
*
* @param {Object} dropdata the exported drop data.
* @returns {boolean}
*/
validateDropData(dropdata) {
return dropdata?.type === 'cm';
}
/**
* Display the component dropzone.
*
* @param {Object} dropdata the accepted drop data
*/
showDropZone(dropdata) {
// If we are the next cmid of the dragged element we accept the drop because otherwise it
// will get captured by the section. However, we won't trigger any mutation.
if (dropdata.nextcmid != this.id && dropdata.id != this.id) {
this.element.classList.add(this.classes.DROPUP);
}
}
/**
* Hide the component dropzone.
*/
hideDropZone() {
this.element.classList.remove(this.classes.DROPUP);
}
/**
* Drop event handler.
*
* @param {Object} dropdata the accepted drop data
*/
drop(dropdata) {
// Call the move mutation if necessary.
if (dropdata.id != this.id && dropdata.nextcmid != this.id) {
this.reactive.dispatch('cmMove', [dropdata.id], null, this.id);
}
}
}
| tonyjbutler/moodle | course/format/amd/src/local/courseeditor/dndcmitem.js | JavaScript | gpl-3.0 | 3,449 |
var vOrientationTolerance=20, hOrientationTolerance=10, angleTolerance=10, numFrames=10, sizeX=(window.innerHeight/3>window.innerWidth/4?window.innerWidth:window.innerHeight/3*4), sizeY=(window.innerHeight/3<window.innerWidth/4?window.innerHeight:window.innerHeight/4*3), initialCountDown=5, cursorW=40, cursorH=20;
var origGamma, origAlpha, origBeta, video, canvas, ctx, ecanvas, ectx, keepedAngle=0, keepedCountdown=initialCountDown, anglePace=Math.ceil(360/numFrames);
// Creating canvas for previsualization & exportation
ecanvas = document.createElement("canvas");
ecanvas.setAttribute('width',(sizeX*numFrames)+'px');
ecanvas.setAttribute('height',sizeY+'px');
document.body.appendChild(ecanvas);
ectx= ecanvas.getContext('2d');
ectx.fillStyle = "#CCC";
ectx.fillRect(0, 0, numFrames*sizeX, sizeY);
ectx.fillStyle = "#fffff0";
ecanvas.setAttribute('style','width:'+sizeX+'px;height:'+Math.round(sizeY/numFrames)+'px;position:absolute;z-index:3;bottom:0;left:0;');
// Creation a video element to display camera stream
video = document.createElement("video");
video.autoplay = true;
video.setAttribute('style','width:'+sizeX+'px;height:'+sizeY+'px;position:absolute;z-index:1;top:0;left:0;');
document.body.appendChild(video);
// Creating a canvas element to display orientation helpers
canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.setAttribute('width',sizeX+'px');
canvas.setAttribute('height',sizeY+'px');
canvas.setAttribute('style','width:'+sizeX+'px;height:'+sizeY+'px;position:absolute;z-index:2;top:0;left:0;');
ctx= canvas.getContext('2d');
// Getting cam stream
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;
if(navigator.getUserMedia)
{
navigator.getUserMedia({video: true}, function(localMediaStream)
{
video.src = window.URL.createObjectURL(localMediaStream);
}, function(error)
{
console.log(error);
});
}
// Getting device orientation
window.addEventListener('deviceorientation', function(e)
{
if(ctx)
{
ctx.clearRect(0,0,sizeX,sizeY);
var portrait=(window.matchMedia&&window.matchMedia('(orientation: portrait)').matches);
ctx.fillStyle = "#CCC";
ctx.globalAlpha=1;
ctx.fillRect((sizeX/2)-((cursorW+hOrientationTolerance)/2),(sizeY/2)-((cursorH+vOrientationTolerance)/2),cursorW+hOrientationTolerance,cursorH+vOrientationTolerance);
ctx.fillRect(0,(sizeY/2)-1,sizeX,2);
if(!origGamma)
{
origGamma=e.gamma;
origBeta=e.beta;
origAlpha=e.alpha;
}
/* Setting the cursor position */
//var pos=(sizeX*(e.alpha/360));
if(portrait)
{
var x=(sizeX/2)+((sizeX/2)*(e.gamma/90)); // crap
var y=(sizeY/2)+((sizeY/2)*((Math.abs(e.beta)-90)/90)); // crap
}
else
{
var x=(sizeX/2)+(Math.abs(e.beta)>90?((sizeX/2)*((180-Math.abs(e.beta))/180)):((sizeX/2)*((e.beta)/90))); // crap
var y=(sizeY/2)+((sizeY/2)*(1-(Math.abs(e.gamma)/90))); // crap
}
/* Debug : printing cursor positions *
ctx.fillStyle = '#000000';
ctx.font='15px Arial';
ctx.textBaseline='top';
ctx.textAlign='left';
ctx.fillText((portrait?'portrait':'landscape')+'('+Math.round(x)+','+Math.round(y)+':'+Math.round(e.beta)+','+Math.round(e.gamma)+')',10, 10,300);
/* Debug : printing angle */
ctx.fillStyle = '#000000';
ctx.textBaseline='top';
ctx.textAlign='center';
ctx.font='30px Arial';
ctx.fillText(Math.round(e.alpha),(sizeY/2), 0);
/* Setting the cursor look */
var angleOk=false, orientOk=false;
if(Math.round(e.alpha)%anglePace>=(anglePace-(angleTolerance/2))
||Math.round(e.alpha)%anglePace<=(angleTolerance/2)) // Angle is ok
angleOk=true;
if(
((!portrait)&&(Math.abs(Math.round(e.beta))>=180-(vOrientationTolerance/2)
||Math.abs(Math.round(e.beta))<=vOrientationTolerance/2)
&&(Math.abs(Math.round(e.gamma))>=90-(vOrientationTolerance/2)))
||(portrait&&(Math.abs(Math.round(e.beta))>=180-(vOrientationTolerance/2)
||Math.abs(Math.round(e.beta))<=vOrientationTolerance/2)
&&(Math.abs(Math.round(e.gamma))>=90-(vOrientationTolerance/2)))
) // Orientation is ok
orientOk=true;
if(angleOk&&orientOk)
{
ctx.fillStyle = '#00FF00';
if(keepedAngle==parseInt(Math.round(e.alpha)/anglePace))
{ keepedCountdown--; }
else
{ keepedAngle=parseInt(Math.round(e.alpha)/anglePace); keepedCountdown=initialCountDown; }
if(keepedCountdown<=0) // Keeped position enought times
{
keepedCountdown=initialCountDown;
ectx.drawImage(video, 0, 0, sizeX, sizeY, parseInt(Math.round(e.alpha)/anglePace)*sizeX, 0, sizeX, sizeY);
}
}
else
{
keepedCountdown=initialCountDown;
if(orientOk)
ctx.fillStyle = '#FFFF00';
else if(angleOk)
ctx.fillStyle = '#FF0000';
else
ctx.fillStyle = '#000000';
}
ctx.globalAlpha=0.8;
ctx.fillRect(Math.round(x)-(cursorW/2),Math.round(y)-(cursorH/2),cursorW,cursorH);
ctx.globalAlpha=1;
ctx.fillStyle = '#000';
ctx.font='30px Arial';
ctx.textBaseline='middle';
ctx.textAlign='center';
ctx.fillText((keepedCountdown<initialCountDown?keepedCountdown:'X'),sizeX/2, sizeY/2,200, 40);
}
}, true); | nfroidure/Panoramix | panoramix.js | JavaScript | gpl-3.0 | 5,338 |
'use strict'
var tap = require('tap')
var utils = require('@newrelic/test-utilities')
var methods = require('methods')
tap.test('koa-route', function(t) {
var helper = utils.TestAgent.makeInstrumented()
t.tearDown(function() {
helper.unload()
})
helper.registerInstrumentation({
type: 'web-framework',
moduleName: 'koa-route',
onRequire: require('../../lib/route-instrumentation.js')
})
t.test('methods', function(t) {
var route = require('koa-route')
methods.forEach(function checkWrapped(method) {
t.type(
route[method].__NR_original,
'function',
method + ' should be wrapped'
)
})
t.end()
})
t.autoend()
})
| ety04/birthday-bot | node_modules/@newrelic/koa/tests/unit/route.tap.js | JavaScript | gpl-3.0 | 700 |
/*! jQuery UI - v1.11.1 - 2014-08-14
* http://jqueryui.com
* Includes: widget.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function (factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery"], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
/*!
* jQuery UI Widget 1.11.1
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
var widget_uuid = 0,
widget_slice = Array.prototype.slice;
$.cleanData = (function (orig) {
return function (elems) {
var events, elem, i;
for (i = 0; (elem = elems[i]) != null; i++) {
try {
// Only trigger remove when necessary to save time
events = $._data(elem, "events");
if (events && events.remove) {
$(elem).triggerHandler("remove");
}
// http://bugs.jquery.com/ticket/8235
} catch (e) {
}
}
orig(elems);
};
})($.cleanData);
$.widget = function (name, base, prototype) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split(".")[0];
name = name.split(".")[1];
fullName = namespace + "-" + name;
if (!prototype) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[":"][fullName.toLowerCase()] = function (elem) {
return !!$.data(elem, fullName);
};
$[namespace] = $[namespace] || {};
existingConstructor = $[namespace][name];
constructor = $[namespace][name] = function (options, element) {
// allow instantiation without "new" keyword
if (!this._createWidget) {
return new constructor(options, element);
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if (arguments.length) {
this._createWidget(options, element);
}
};
// extend with the existing constructor to carry over any static properties
$.extend(constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend({}, prototype),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend({}, basePrototype.options);
$.each(prototype, function (prop, value) {
if (!$.isFunction(value)) {
proxiedPrototype[prop] = value;
return;
}
proxiedPrototype[prop] = (function () {
var _super = function () {
return base.prototype[prop].apply(this, arguments);
},
_superApply = function (args) {
return base.prototype[prop].apply(this, args);
};
return function () {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply(this, arguments);
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend(basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if (existingConstructor) {
$.each(existingConstructor._childConstructors, function (i, child) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto);
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push(constructor);
}
$.widget.bridge(name, constructor);
return constructor;
};
$.widget.extend = function (target) {
var input = widget_slice.call(arguments, 1),
inputIndex = 0,
inputLength = input.length,
key,
value;
for (; inputIndex < inputLength; inputIndex++) {
for (key in input[inputIndex]) {
value = input[inputIndex][key];
if (input[inputIndex].hasOwnProperty(key) && value !== undefined) {
// Clone objects
if ($.isPlainObject(value)) {
target[key] = $.isPlainObject(target[key]) ?
$.widget.extend({}, target[key], value) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend({}, value);
// Copy everything else by reference
} else {
target[key] = value;
}
}
}
}
return target;
};
$.widget.bridge = function (name, object) {
var fullName = object.prototype.widgetFullName || name;
$.fn[name] = function (options) {
var isMethodCall = typeof options === "string",
args = widget_slice.call(arguments, 1),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply(null, [options].concat(args)) :
options;
if (isMethodCall) {
this.each(function () {
var methodValue,
instance = $.data(this, fullName);
if (options === "instance") {
returnValue = instance;
return false;
}
if (!instance) {
return $.error("cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'");
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
return $.error("no such method '" + options + "' for " + name + " widget instance");
}
methodValue = instance[options].apply(instance, args);
if (methodValue !== instance && methodValue !== undefined) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack(methodValue.get()) :
methodValue;
return false;
}
});
} else {
this.each(function () {
var instance = $.data(this, fullName);
if (instance) {
instance.option(options || {});
if (instance._init) {
instance._init();
}
} else {
$.data(this, fullName, new object(options, this));
}
});
}
return returnValue;
};
};
$.Widget = function (/* options, element */) {
};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function (options, element) {
element = $(element || this.defaultElement || this)[0];
this.element = $(element);
this.uuid = widget_uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend({},
this.options,
this._getCreateOptions(),
options);
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if (element !== this) {
$.data(element, this.widgetFullName, this);
this._on(true, this.element, {
remove: function (event) {
if (event.target === element) {
this.destroy();
}
}
});
this.document = $(element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element);
this.window = $(this.document[0].defaultView || this.document[0].parentWindow);
}
this._create();
this._trigger("create", null, this._getCreateEventData());
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function () {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind(this.eventNamespace)
.removeData(this.widgetFullName)
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData($.camelCase(this.widgetFullName));
this.widget()
.unbind(this.eventNamespace)
.removeAttr("aria-disabled")
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled");
// clean up events and states
this.bindings.unbind(this.eventNamespace);
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
},
_destroy: $.noop,
widget: function () {
return this.element;
},
option: function (key, value) {
var options = key,
parts,
curOption,
i;
if (arguments.length === 0) {
// don't return a reference to the internal hash
return $.widget.extend({}, this.options);
}
if (typeof key === "string") {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split(".");
key = parts.shift();
if (parts.length) {
curOption = options[key] = $.widget.extend({}, this.options[key]);
for (i = 0; i < parts.length - 1; i++) {
curOption[parts[i]] = curOption[parts[i]] || {};
curOption = curOption[parts[i]];
}
key = parts.pop();
if (arguments.length === 1) {
return curOption[key] === undefined ? null : curOption[key];
}
curOption[key] = value;
} else {
if (arguments.length === 1) {
return this.options[key] === undefined ? null : this.options[key];
}
options[key] = value;
}
}
this._setOptions(options);
return this;
},
_setOptions: function (options) {
var key;
for (key in options) {
this._setOption(key, options[key]);
}
return this;
},
_setOption: function (key, value) {
this.options[key] = value;
if (key === "disabled") {
this.widget()
.toggleClass(this.widgetFullName + "-disabled", !!value);
// If the widget is becoming disabled, then nothing is interactive
if (value) {
this.hoverable.removeClass("ui-state-hover");
this.focusable.removeClass("ui-state-focus");
}
}
return this;
},
enable: function () {
return this._setOptions({disabled: false});
},
disable: function () {
return this._setOptions({disabled: true});
},
_on: function (suppressDisabledCheck, element, handlers) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if (typeof suppressDisabledCheck !== "boolean") {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if (!handlers) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $(element);
this.bindings = this.bindings.add(element);
}
$.each(handlers, function (event, handler) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if (!suppressDisabledCheck &&
( instance.options.disabled === true ||
$(this).hasClass("ui-state-disabled") )) {
return;
}
return ( typeof handler === "string" ? instance[handler] : handler )
.apply(instance, arguments);
}
// copy the guid so direct unbinding works
if (typeof handler !== "string") {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match(/^([\w:-]*)\s*(.*)$/),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if (selector) {
delegateElement.delegate(selector, eventName, handlerProxy);
} else {
element.bind(eventName, handlerProxy);
}
});
},
_off: function (element, eventName) {
eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace;
element.unbind(eventName).undelegate(eventName);
},
_delay: function (handler, delay) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[handler] : handler )
.apply(instance, arguments);
}
var instance = this;
return setTimeout(handlerProxy, delay || 0);
},
_hoverable: function (element) {
this.hoverable = this.hoverable.add(element);
this._on(element, {
mouseenter: function (event) {
$(event.currentTarget).addClass("ui-state-hover");
},
mouseleave: function (event) {
$(event.currentTarget).removeClass("ui-state-hover");
}
});
},
_focusable: function (element) {
this.focusable = this.focusable.add(element);
this._on(element, {
focusin: function (event) {
$(event.currentTarget).addClass("ui-state-focus");
},
focusout: function (event) {
$(event.currentTarget).removeClass("ui-state-focus");
}
});
},
_trigger: function (type, event, data) {
var prop, orig,
callback = this.options[type];
data = data || {};
event = $.Event(event);
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[0];
// copy original event properties over to the new event
orig = event.originalEvent;
if (orig) {
for (prop in orig) {
if (!( prop in event )) {
event[prop] = orig[prop];
}
}
}
this.element.trigger(event, data);
return !( $.isFunction(callback) &&
callback.apply(this.element[0], [event].concat(data)) === false ||
event.isDefaultPrevented() );
}
};
$.each({show: "fadeIn", hide: "fadeOut"}, function (method, defaultEffect) {
$.Widget.prototype["_" + method] = function (element, options, callback) {
if (typeof options === "string") {
options = {effect: options};
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if (typeof options === "number") {
options = {duration: options};
}
hasOptions = !$.isEmptyObject(options);
options.complete = callback;
if (options.delay) {
element.delay(options.delay);
}
if (hasOptions && $.effects && $.effects.effect[effectName]) {
element[method](options);
} else if (effectName !== method && element[effectName]) {
element[effectName](options.duration, options.easing, callback);
} else {
element.queue(function (next) {
$(this)[method]();
if (callback) {
callback.call(element[0]);
}
next();
});
}
};
});
var widget = $.widget;
})); | xiinite/cymeriad | public/js/jquery.widget.js | JavaScript | gpl-3.0 | 20,860 |
import { colorIcon } from '../utils';
function generateInputsHTML(inputsArray) {
return inputsArray
.map(({ name, maxValue, valueType, pattern = null }) => {
return `
<div class="input__parent input__parent--${name}">
<label name=${name}>${colorIcon[name]} ${name}</label>
<input class="input--color input--color--${name}" ${
pattern ? (pattern = pattern) : ''
} type=${valueType} name=${name}
value=''
required max=${maxValue}/>
<span id="message-input-${name}" class="message-input-to-display"></span>
</div>
`;
})
.join('');
}
function generateColorBlocksHTML() {
return `
<div class="colorBlocs">
<div class="blocColor blocColor--find js-blocColor-find findBlocColor">
<span>color to find</span>
</div>
<div class="blocColor blocColor--player js-blocColor-player playerBlocColor">
<span>your color</span>
</div>
</div>`;
}
export { generateInputsHTML, generateColorBlocksHTML };
| Yedrup/Color-Game | js/game/templates.js | JavaScript | gpl-3.0 | 1,007 |
Bxs.Response = {
success: function(action,status) {
switch(action) {
case "insert":
if (status === 201) {
return true;
}
break;
case "update":
if (status === 200 || status === 304) {
return true;
}
break;
case "delete":
if (status === 204) {
return true;
}
break;
}
return false;
}
}
| rdallasgray/bxs | js/Bxs.Response.js | JavaScript | gpl-3.0 | 353 |
var fene_8hpp =
[
[ "calc_fene_pair_force", "fene_8hpp.html#a17b0d5b7533cd6e8ca660755d88d2226", null ],
[ "fene_pair_energy", "fene_8hpp.html#a025b875b61d73ba10293a978a60d51f9", null ],
[ "fene_set_params", "fene_8hpp.html#a373e8a8ee847549ba006ee54dcac4982", null ]
]; | HaoZeke/espresso | doc/doxygen/html/fene_8hpp.js | JavaScript | gpl-3.0 | 280 |
var _teeny_vandle_processor_8cpp =
[
[ "D_TIMEDIFF", "dc/dbb/_teeny_vandle_processor_8cpp.html#a0a526d2d0b18e1096db2418ffedb1a62", null ],
[ "DD_MAX", "dc/dbb/_teeny_vandle_processor_8cpp.html#ae94f612905035dc6c9d03ec122b2416d", null ],
[ "DD_MAXLCORGATE", "dc/dbb/_teeny_vandle_processor_8cpp.html#a89ba08d3c50c367c6c07c7035401cd86", null ],
[ "DD_MAXLEFTVSTDIFF", "dc/dbb/_teeny_vandle_processor_8cpp.html#ad648eaff24a77e114cef19c7d5338a7d", null ],
[ "DD_MAXLVSTDIFFAMP", "dc/dbb/_teeny_vandle_processor_8cpp.html#aeca5279ef3a1e87dbca31949330d8f51", null ],
[ "DD_MAXLVSTDIFFGATE", "dc/dbb/_teeny_vandle_processor_8cpp.html#a9d10775e76eff7b14f3c42a239ebd883", null ],
[ "DD_MAXRIGHTVSTDIFF", "dc/dbb/_teeny_vandle_processor_8cpp.html#acc210ffaa9870b0c4dc7e39d04ad4c42", null ],
[ "DD_PVSP", "dc/dbb/_teeny_vandle_processor_8cpp.html#ab40bb76c1010f8a79d305c77a603db7c", null ],
[ "DD_QDCVSMAX", "dc/dbb/_teeny_vandle_processor_8cpp.html#a954b93a2c70d4e5f9b9990d151ba6573", null ],
[ "DD_SNRANDSDEV", "dc/dbb/_teeny_vandle_processor_8cpp.html#a16f28823bf43eee8b9e80f5c8214c004", null ],
[ "DD_TQDC", "dc/dbb/_teeny_vandle_processor_8cpp.html#ae181e1ae711a17abd6d187bc7d8b7918", null ]
]; | pixie16/paassdoc | dc/dbb/_teeny_vandle_processor_8cpp.js | JavaScript | gpl-3.0 | 1,232 |
"use strict";
const events = require("../events.js");
const views = require("../util/views.js");
const template = views.getTemplate("posts-page");
class PostsPageView extends events.EventTarget {
constructor(ctx) {
super();
this._ctx = ctx;
this._hostNode = ctx.hostNode;
views.replaceContent(this._hostNode, template(ctx));
this._postIdToPost = {};
for (let post of ctx.response.results) {
this._postIdToPost[post.id] = post;
post.addEventListener("change", (e) => this._evtPostChange(e));
}
this._postIdToListItemNode = {};
for (let listItemNode of this._listItemNodes) {
const postId = listItemNode.getAttribute("data-post-id");
const post = this._postIdToPost[postId];
this._postIdToListItemNode[postId] = listItemNode;
const tagFlipperNode = this._getTagFlipperNode(listItemNode);
if (tagFlipperNode) {
tagFlipperNode.addEventListener("click", (e) =>
this._evtBulkEditTagsClick(e, post)
);
}
const safetyFlipperNode = this._getSafetyFlipperNode(listItemNode);
if (safetyFlipperNode) {
for (let linkNode of safetyFlipperNode.querySelectorAll("a")) {
linkNode.addEventListener("click", (e) =>
this._evtBulkEditSafetyClick(e, post)
);
}
}
}
this._syncBulkEditorsHighlights();
}
get _listItemNodes() {
return this._hostNode.querySelectorAll("li");
}
_getTagFlipperNode(listItemNode) {
return listItemNode.querySelector(".tag-flipper");
}
_getSafetyFlipperNode(listItemNode) {
return listItemNode.querySelector(".safety-flipper");
}
_evtPostChange(e) {
const listItemNode = this._postIdToListItemNode[e.detail.post.id];
for (let node of listItemNode.querySelectorAll("[data-disabled]")) {
node.removeAttribute("data-disabled");
}
this._syncBulkEditorsHighlights();
}
_evtBulkEditTagsClick(e, post) {
e.preventDefault();
const linkNode = e.target;
if (linkNode.getAttribute("data-disabled")) {
return;
}
linkNode.setAttribute("data-disabled", true);
this.dispatchEvent(
new CustomEvent(
linkNode.classList.contains("tagged") ? "untag" : "tag",
{
detail: { post: post },
}
)
);
}
_evtBulkEditSafetyClick(e, post) {
e.preventDefault();
const linkNode = e.target;
if (linkNode.getAttribute("data-disabled")) {
return;
}
const newSafety = linkNode.getAttribute("data-safety");
if (post.safety === newSafety) {
return;
}
linkNode.setAttribute("data-disabled", true);
this.dispatchEvent(
new CustomEvent("changeSafety", {
detail: { post: post, safety: newSafety },
})
);
}
_syncBulkEditorsHighlights() {
for (let listItemNode of this._listItemNodes) {
const postId = listItemNode.getAttribute("data-post-id");
const post = this._postIdToPost[postId];
const tagFlipperNode = this._getTagFlipperNode(listItemNode);
if (tagFlipperNode) {
let tagged = true;
for (let tag of this._ctx.bulkEdit.tags) {
tagged &= post.tags.isTaggedWith(tag);
}
tagFlipperNode.classList.toggle("tagged", tagged);
}
const safetyFlipperNode = this._getSafetyFlipperNode(listItemNode);
if (safetyFlipperNode) {
for (let linkNode of safetyFlipperNode.querySelectorAll("a")) {
const safety = linkNode.getAttribute("data-safety");
linkNode.classList.toggle(
"active",
post.safety === safety
);
}
}
}
}
}
module.exports = PostsPageView;
| rr-/szurubooru | client/js/views/posts_page_view.js | JavaScript | gpl-3.0 | 4,257 |
/**
* Session Configuration
* (sails.config.session)
*
* Sails session integration leans heavily on the great work already done by
* Express, but also unifies Socket.io with the Connect session store. It uses
* Connect's cookie parser to normalize configuration differences between Express
* and Socket.io and hooks into Sails' middleware interpreter to allow you to access
* and auto-save to `req.session` with Socket.io the same way you would with Express.
*
* For more information on configuring the session, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.session.html
*/
module.exports.session = {
/***************************************************************************
* *
* Session secret is automatically generated when your new app is created *
* Replace at your own risk in production-- you will invalidate the cookies *
* of your users, forcing them to log in again. *
* *
***************************************************************************/
secret: '6c58e78aa24be110ce0369a6dfda7f49',
/***************************************************************************
* *
* Set the session cookie expire time The maxAge is set by milliseconds, *
* the example below is for 24 hours *
* *
***************************************************************************/
// cookie: {
// maxAge: 24 * 60 * 60 * 1000
// },
/***************************************************************************
* *
* Uncomment the following lines to set up a Redis session store that can *
* be shared across multiple Sails.js servers. *
* *
* Requires connect-redis (https://www.npmjs.com/package/connect-redis) *
* *
***************************************************************************/
// adapter: 'redis',
/***************************************************************************
* *
* The following values are optional, if no options are set a redis *
* instance running on localhost is expected. Read more about options at: *
* *
* https://github.com/visionmedia/connect-redis *
* *
***************************************************************************/
// host: 'localhost',
// port: 6379,
// ttl: <redis session TTL in seconds>,
// db: 0,
// pass: <redis auth password>,
// prefix: 'sess:',
/***************************************************************************
* *
* Uncomment the following lines to set up a MongoDB session store that can *
* be shared across multiple Sails.js servers. *
* *
* Requires connect-mongo (https://www.npmjs.com/package/connect-mongo) *
* Use version 0.8.2 with Node version <= 0.12 *
* Use the latest version with Node >= 4.0 *
* *
***************************************************************************/
// adapter: 'mongo',
// url: 'mongodb://user:password@localhost:27017/dbname', // user, password and port optional
/***************************************************************************
* *
* Optional Values: *
* *
* See https://github.com/kcbanner/connect-mongo for more *
* information about connect-mongo options. *
* *
* See http://bit.ly/mongooptions for more information about options *
* available in `mongoOptions` *
* *
***************************************************************************/
// collection: 'sessions',
// stringify: true,
// mongoOptions: {
// server: {
// ssl: true
// }
// }
};
| njung/thesail | config/session.js | JavaScript | gpl-3.0 | 5,141 |
define(
"dojo/cldr/nls/sk/indian", //begin v1.x content
{
"field-quarter-short-relative+0": "tento ลกtvrลฅr.",
"field-quarter-short-relative+1": "budรบci ลกtvrลฅr.",
"field-tue-relative+-1": "minulรฝ utorok",
"field-year": "rok",
"field-wed-relative+0": "tรบto stredu",
"field-wed-relative+1": "budรบcu stredu",
"field-minute": "minรบta",
"field-tue-narrow-relative+0": "tento ut.",
"field-tue-narrow-relative+1": "budรบci ut.",
"field-thu-short-relative+0": "tento ลกt.",
"field-day-short-relative+-1": "vฤera",
"field-thu-short-relative+1": "budรบci ลกt.",
"field-day-relative+0": "dnes",
"field-day-short-relative+-2": "predvฤerom",
"field-day-relative+1": "zajtra",
"field-day-relative+2": "pozajtra",
"field-wed-narrow-relative+-1": "minulรบ st.",
"field-year-narrow": "r.",
"field-era-short": "letop.",
"field-year-narrow-relative+0": "tento rok",
"field-tue-relative+0": "tento utorok",
"field-year-narrow-relative+1": "budรบci rok",
"field-tue-relative+1": "budรบci utorok",
"field-weekdayOfMonth": "deล tรฝลพdลa vย mesiaci",
"field-second-short": "s",
"field-weekdayOfMonth-narrow": "d. ย tรฝลพ. vย mes.",
"field-week-relative+0": "tento tรฝลพdeล",
"field-month-relative+0": "tento mesiac",
"field-week-relative+1": "budรบci tรฝลพdeล",
"field-month-relative+1": "budรบci mesiac",
"field-sun-narrow-relative+0": "tรบto ne.",
"field-mon-short-relative+0": "tento pond.",
"field-sun-narrow-relative+1": "budรบcu ne.",
"field-mon-short-relative+1": "budรบci pond.",
"field-second-relative+0": "teraz",
"eraNames": [
"ล aka"
],
"field-weekOfMonth": "tรฝลพdeล mesiaca",
"field-month-short": "mes.",
"field-day": "deล",
"field-dayOfYear-short": "deล r.",
"field-year-relative+-1": "minulรฝ rok",
"field-sat-short-relative+-1": "minulรบ so.",
"field-hour-relative+0": "v tejto hodine",
"field-wed-relative+-1": "minulรบ stredu",
"field-sat-narrow-relative+-1": "minulรบ so.",
"field-second": "sekunda",
"field-quarter": "ลกtvrลฅrok",
"field-week-short": "tรฝลพ.",
"field-day-narrow-relative+0": "dnes",
"field-day-narrow-relative+1": "zajtra",
"field-day-narrow-relative+2": "pozajtra",
"field-tue-short-relative+0": "tento utor.",
"field-tue-short-relative+1": "budรบci utor.",
"field-month-short-relative+-1": "minulรฝ mes.",
"field-mon-relative+-1": "minulรฝ pondelok",
"field-month": "mesiac",
"field-day-narrow": "d.",
"field-minute-short": "min",
"field-dayperiod": "AM/PM",
"field-sat-short-relative+0": "tรบto so.",
"field-sat-short-relative+1": "budรบcu so.",
"eraAbbr": [
"ล aka"
],
"field-second-narrow": "s",
"field-mon-relative+0": "tento pondelok",
"field-mon-relative+1": "budรบci pondelok",
"field-day-narrow-relative+-1": "vฤera",
"field-year-short": "r.",
"field-day-narrow-relative+-2": "predvฤerom",
"field-quarter-relative+-1": "minulรฝ ลกtvrลฅrok",
"field-dayperiod-narrow": "AM/PM",
"field-dayOfYear": "deล roka",
"field-sat-relative+-1": "minulรบ sobotu",
"field-hour": "hodina",
"months-format-wide": [
"ฤaitra",
"vaiลกรกkh",
"dลพjรฉลกth",
"รกลกรกdh",
"ลกrรกvana",
"bhรกdrapad",
"รกลกvin",
"kรกrtik",
"agrahajana",
"pauลก",
"mรกgh",
"phรกlgun"
],
"field-month-relative+-1": "minulรฝ mesiac",
"field-quarter-short": "Q",
"field-sat-narrow-relative+0": "tรบto so.",
"field-fri-relative+0": "tento piatok",
"field-sat-narrow-relative+1": "budรบcu so.",
"field-fri-relative+1": "budรบci piatok",
"field-sun-short-relative+0": "tรบto ned.",
"field-sun-short-relative+1": "budรบcu ned.",
"field-week-relative+-1": "minulรฝ tรฝลพdeล",
"field-quarter-short-relative+-1": "minulรฝ ลกtvrลฅr.",
"months-format-abbr": [
"ฤaitra",
"vaiลกรกkh",
"dลพjรฉลกth",
"รกลกรกdh",
"ลกrรกvana",
"bhรกdrapad",
"รกลกvin",
"kรกrtik",
"agrahajana",
"pauลก",
"mรกgh",
"phรกlgun"
],
"field-quarter-relative+0": "tento ลกtvrลฅrok",
"field-minute-relative+0": "v tejto minรบte",
"field-quarter-relative+1": "budรบci ลกtvrลฅrok",
"field-wed-short-relative+-1": "minulรบ str.",
"field-thu-short-relative+-1": "minulรฝ ลกt.",
"field-year-narrow-relative+-1": "minulรฝ rok",
"field-mon-narrow-relative+-1": "minulรฝ po.",
"field-thu-narrow-relative+-1": "minulรฝ ลกt.",
"field-tue-narrow-relative+-1": "minulรฝ ut.",
"field-weekOfMonth-short": "tรฝลพ. mes.",
"field-wed-short-relative+0": "tรบto str.",
"months-standAlone-wide": [
"ฤaitra",
"vaiลกรกkh",
"dลพjรฉลกth",
"รกลกรกdh",
"ลกrรกvana",
"bhรกdrapad",
"รกลกvin",
"kรกrtik",
"agrahajana",
"pauลก",
"mรกgh",
"phรกlgun"
],
"field-wed-short-relative+1": "budรบcu str.",
"field-sun-relative+-1": "minulรบ nedeฤพu",
"field-weekday": "deล tรฝลพdลa",
"field-day-short-relative+0": "dnes",
"field-quarter-narrow-relative+0": "tento ลกtvrลฅr.",
"field-sat-relative+0": "tรบto sobotu",
"field-day-short-relative+1": "zajtra",
"field-quarter-narrow-relative+1": "budรบci ลกtvrลฅr.",
"field-sat-relative+1": "budรบcu sobotu",
"field-day-short-relative+2": "pozajtra",
"field-week-short-relative+0": "tento tรฝลพ.",
"field-week-short-relative+1": "budรบci tรฝลพ.",
"months-standAlone-abbr": [
"ฤaitra",
"vaiลกรกkh",
"dลพjรฉลกth",
"รกลกรกdh",
"ลกrรกvana",
"bhรกdrapad",
"รกลกvin",
"kรกrtik",
"agrahajana",
"pauลก",
"mรกgh",
"phรกlgun"
],
"field-dayOfYear-narrow": "deล r.",
"field-month-short-relative+0": "tento mes.",
"field-month-short-relative+1": "budรบci mes.",
"field-weekdayOfMonth-short": "d. ย tรฝลพ. vย mes.",
"field-zone-narrow": "pรกsmo",
"field-thu-narrow-relative+0": "tento ลกt.",
"field-thu-narrow-relative+1": "budรบci ลกt.",
"field-sun-narrow-relative+-1": "minulรบ ne.",
"field-mon-short-relative+-1": "minulรฝ pond.",
"field-thu-relative+0": "tento ลกtvrtok",
"field-thu-relative+1": "budรบci ลกtvrtok",
"field-fri-short-relative+-1": "minulรฝ pi.",
"field-thu-relative+-1": "minulรฝ ลกtvrtok",
"field-week": "tรฝลพdeล",
"field-wed-narrow-relative+0": "tรบto st.",
"field-wed-narrow-relative+1": "budรบcu st.",
"field-quarter-narrow-relative+-1": "minulรฝ ลกtvrลฅr.",
"field-year-short-relative+0": "tento rok",
"field-dayperiod-short": "AM/PM",
"field-year-short-relative+1": "budรบci rok",
"field-fri-short-relative+0": "tento pi.",
"field-fri-short-relative+1": "budรบci pi.",
"field-week-short-relative+-1": "minulรฝ tรฝลพ.",
"field-hour-short": "h",
"field-zone-short": "pรกsmo",
"field-month-narrow": "mes.",
"field-hour-narrow": "h",
"field-fri-narrow-relative+-1": "minulรฝ pi.",
"field-year-relative+0": "tento rok",
"field-year-relative+1": "budรบci rok",
"field-era-narrow": "letop.",
"field-fri-relative+-1": "minulรฝ piatok",
"eraNarrow": "ล aka",
"field-tue-short-relative+-1": "minulรฝ utor.",
"field-minute-narrow": "min",
"field-mon-narrow-relative+0": "tento po.",
"field-mon-narrow-relative+1": "budรบci po.",
"field-year-short-relative+-1": "minulรฝ rok",
"field-zone": "ฤasovรฉ pรกsmo",
"field-weekOfMonth-narrow": "tรฝลพ. mes.",
"field-weekday-narrow": "deล tรฝลพ.",
"field-quarter-narrow": "Q",
"field-sun-short-relative+-1": "minulรบ ned.",
"field-day-relative+-1": "vฤera",
"field-day-relative+-2": "predvฤerom",
"field-weekday-short": "deล tรฝลพ.",
"field-sun-relative+0": "tรบto nedeฤพu",
"field-sun-relative+1": "budรบcu nedeฤพu",
"field-day-short": "d.",
"field-week-narrow": "tรฝลพ.",
"field-era": "letopoฤet",
"field-fri-narrow-relative+0": "tento pi.",
"field-fri-narrow-relative+1": "budรบci pi."
}
//end v1.x content
); | ustegrew/ustegrew.github.io | courses/it001/lib/dojo/dojo/cldr/nls/sk/indian.js.uncompressed.js | JavaScript | gpl-3.0 | 7,499 |
var shape = {
name:
} | itpop/comp4900 | test/script.js | JavaScript | gpl-3.0 | 25 |
const winston = require('winston')
const exec = require('child_process').execSync
const path = require('path')
const { LOG_DIR } = require('./constant')
const env = process.env['NODE_ENV']
const LOG_FILE = process.env['LOG_FILE']
console.log('LOG_FILE', LOG_FILE)
exec(`mkdir -p ${LOG_DIR}`, {})
let transports = []
if (env === 'production') {
transports.push(new (winston.transports.File)({
name: 'info',
filename: path.resolve(LOG_FILE, 'access.log'),
timestamp: Date.now(),
level: 'info'
}), new (winston.transports.File)({
name: 'error',
filename: path.resolve(LOG_FILE, 'error.log'),
timestamp: Date.now(),
level: 'error'
}))
} else {
transports.push(new (winston.transports.Console)({
timestamp: Date.now(),
colorize: true,
level: 'debug'
}))
}
const logger = new (winston.Logger)({ transports });
module.exports = logger
| mrcodehang/github-issues-rss | src/logger.js | JavaScript | gpl-3.0 | 887 |
var longest__common__subsequence_8h =
[
[ "longest_common_subsequence", "longest__common__subsequence_8h.html#a02edd40c3c2dd3ce1b514284dd42e99c", null ],
[ "make_LCS", "longest__common__subsequence_8h.html#a377ef4206d4814024272c15c51051f09", null ]
]; | huaxz1986/cplusplus-_Implementation_Of_Introduction_to_Algorithms | doc/html/longest__common__subsequence_8h.js | JavaScript | gpl-3.0 | 259 |
/**
* Track ViewModel
* @descrip This view model is used to represent a track.
* @author Benjamin Russell (benrr101+dolomite@outlook.com)
*/
function TrackViewModel() {
var self = this;
// NON-OBSERVABLE //////////////////////////////////////////////////////
self.Id = null; // The GUID of the track
self.Loaded = false; // Whether or not the track has been fetched from the server
self.LoadCheckIntervalId = null; // The interval ID of the load checking method
// OBSERVABLE //////////////////////////////////////////////////////////
self.ArtHref = ko.observable(null); // The URL for this track's art
// NOTE: This must be observable for album art editing to work
self.Metadata = ko.observableDictionary(); // The dictionary of metadata available for the track
self.Qualities = ko.observableArray(); // The list of qualities that are available for the track
// NOTE: This must be observable in order for download lists to work
self.Ready = ko.observable(true); // Whether or not the track is ready. They usually are.
self.UploadProgress = ko.observable(false); // The percent progress of any active upload on this track
}
// ACTIONS /////////////////////////////////////////////////////////////////
// AJAX ////////////////////////////////////////////////////////////////////
TrackViewModel.prototype.checkReady = function() {
var self = this;
// Fetch the track and see if it's successful
self.fetch(null, null);
};
TrackViewModel.prototype.delete = function(callback, errorCallback) {
var self = this;
// Set up the parameters to delete the track
var params = getBaseAjaxParams("DELETE", serverAddress + "/tracks/" + self.Id);
params.error = function(xhr) {
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to delete track for unknown reason.")
};
params.success = function(xhr) {
// That's it, we're done here. To make sure no one tries anything silly, unload the track
self.Loaded = false;
if(callback !== null) {
callback(self);
}
};
$.ajax(params);
};
TrackViewModel.prototype.deleteArt = function(errorCallback) {
var self = this;
// Show the spinner
$(".mdAlbumArtPreview").hide();
$("#aaSpinner").show();
// Setup the ajax parameters to delete the album art
// to delete, we just send a blank request to the part update href
var params = getBaseAjaxParams("POST", serverAddress + "/tracks/" + self.Id + "/art");
params.success = function() {
// Force a reload (the spinner will be hidden on when complete, and
// the ArtHref update will redisplay the new art
self.Loaded = false;
self.fetch(function() { $("#aaSpinner").hide(); }, errorCallback);
};
params.error = function() {
// Hide the spinner
$("#aaSpinner").hide();
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to delete track album art for unknown reason.");
};
$.ajax(params);
};
TrackViewModel.prototype.fetch = function(callback, errorCallback) {
var self = this;
// Check to see if the track is loaded, skip loading if it is
if(self.Loaded) {
if(callback !== null) {
callback(self);
}
return;
}
// Set up a ajax request for the track
var params = getBaseAjaxParams("GET", serverAddress + "/tracks/" + self.Id);
params.error = function(xhr) {
if(errorCallback != null) {
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to lookup track for unknown reason.");
}
};
params.success = function(xhr) {
// Restore the metadata to force a reload of correct data
self.Metadata.removeAll();
self.Metadata.pushAll(xhr.Metadata);
// Store the information we don't already have
self.Qualities(xhr.Qualities);
self.ArtHref(xhr.ArtHref != null ? serverAddress + '/' + xhr.ArtHref : null);
self.Ready(true);
self.Loaded = true;
// Clear any interval that is being used on this track
if(self.LoadCheckIntervalId != null) {
clearInterval(self.LoadCheckIntervalId);
self.LoadCheckIntervalId = null;
}
// Call the optional callback
if(callback !== null) {
callback(self);
}
};
$.ajax(params);
};
TrackViewModel.prototype.resetMetadata = function(callback, errorCallback){
var self = this;
// Force a reload of the track
self.Loaded = false;
self.fetch(callback, errorCallback);
};
TrackViewModel.prototype.replace = function(formId, successCallback, alertCallback, errorCallback) {
var self = this;
// Get the form element to submit
var formElement = $("#" + formId);
// Setup the parameters to upload the replacement track
formElement.ajaxSubmit({
url: serverAddress + "/tracks/" + self.Id,
type: "PUT",
dataType: "json",
xhrFields: { withCredentials: true},
beforeSubmit: function() {
// Set this track as not ready
self.Ready(false);
self.Loaded = false;
self.UploadProgress(0);
},
uploadProgress: function(progress) {
// Update the percentage completed
self.UploadProgress(Math.floor(progress.loaded * 100 / progress.total));
},
success: function() {
// Hide the spinner/percentage but keep the button disabled.
alertCallback("Your upload was successful! This track will be unavailable until the track is processed on the server.");
self.UploadProgress(false);
if(successCallback != null) {
successCallback();
}
// Set up the infinichecker to run every minute.
self.LoadCheckIntervalId = setInterval(function() { self.checkReady(); }, 60000);
},
error: function(xhr) {
self.Ready(true);
self.UploadProgress(false);
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to update track album art for unknown reason.");
}
});
};
TrackViewModel.prototype.submitMetadata = function(callback, errorCallback) {
var self = this;
// Set up the parameters to submit the metadata
var params = getBaseAjaxParams("POST", serverAddress + "/tracks/" + self.Id + "?clear");
params.data = JSON.stringify(self.Metadata.toJSON());
params.error = function(xhr) {
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to update track metadata for unknown reason.");
};
params.success = function(xhr) {
// Force reload the track
self.Loaded = false;
self.fetch(callback, errorCallback);
}
$.ajax(params);
};
TrackViewModel.prototype.uploadArt = function(formId, errorCallback) {
var self = this;
// Get the form element to submit
var formElement = $("#" + formId);
// Set up the parameters to upload the album art
formElement.ajaxSubmit({
url: serverAddress + "/tracks/" + self.Id + "/art",
type: "POST",
dataType: "json",
xhrFields: { withCredentials: true },
beforeSubmit: function () {
// Show the spinner
$(".mdAlbumArtPreview").hide();
$("#aaSpinner").show();
},
success: function () {
// Force a reload (the spinner will be hidden on when complete, and
// the ArtHref update will redisplay the new art
self.Loaded = false;
self.fetch(function() { $("#aaSpinner").hide(); }, errorCallback);
},
error: function (xhr) {
// Hide the spinner
$("#aaSpinner").hide();
errorCallback(xhr.status != 0 ? xhr.responseJSON.Message : "Failed to update track album art for unknown reason.");
}
});
}; | benrr101/cinnabar | scripts/track.js | JavaScript | gpl-3.0 | 8,139 |
class doublylinkedlist{
constructor(value)
{
this.head = {
value:value,
next:null,
prev:null // a new pointer is to be defined which points to previous node
}
this.tail=this.head;
this.length=1;
}
append(value) //for appending operation(this adds node to the end of the linked list)
{
const newNode={
value:value,
next:null,
prev:null
}
newNode.prev=this.tail;
this.tail.next=newNode;
this.tail=newNode;
this.length++;
return this;
}
prepend(value) //for prepending
{
const newNode={
value:value,
next:null,
prev:null
}
newNode.next=this.head;
this.head.prev=newNode;
this.head=newNode;
this.length++;
return this;
}
printList() //to print linked list in form of list(array)
{
const array=[];
let currentNode=this.head;
while(currentNode!==null)
{
array.push(currentNode.value);
currentNode=currentNode.next;
}
return array;
}
insert(index,value) //inserting an element to a specific position
{
if(index>=this.length){
return this.append(value); //check parameter and do the operation according to your wish
}
const newNode={
value:value,
next:null,
prev:null //new pointer
}
const leader=this.traverseToIndex(index-1);
const follower=leader.next; //node after leader
leader.next=newNode;
newNode.prev=leader; //newnode pointing to leader(previous node)
newNode.next=follower;
follower.prev=newNode; //follower pointing to newnode(previous)
this.length++;
return this.printList();
}
remove(index) //O(n) time as it involves traversing
{
//check parameters if you want
const leader=this.traverseToIndex(index-1);
const unwantedNode=leader.next;
leader.next=unwantedNode.next;
const nodeAfterDeletedNode=unwantedNode.next;
nodeAfterDeletedNode.prev=leader;
this.length--;
return this.printList();
}
traverseToIndex(index) //for traversing
{
let counter=0;
let currentNode=this.head;
while(counter!==index)
{
currentNode=currentNode.next;
counter++;
}
return currentNode;
}
}
const mydoublylinkedlist=new doublylinkedlist(10);
mydoublylinkedlist.append(20);
mydoublylinkedlist.append(30);
mydoublylinkedlist.prepend(5);
mydoublylinkedlist.insert(2,15);
mydoublylinkedlist.remove(2);
mydoublylinkedlist.printList();
//Output:- => [ 5, 10, 20, 30 ]
| jainaman224/Algo_Ds_Notes | Doubly_Linked_List/Doubly_Linked_List.js | JavaScript | gpl-3.0 | 2,543 |
import {calculRDU} from '../calculateur/calculRDUVD';
// REF http://www.guidesocial.ch/fr/fiche/960/
function nombreEnfants(sim) {
return sim.personnes.filter(personne => (!personne.estAdulte)).length;
}
function chargesNormalesBaseLookup(chargesNormalesBaseVD, nbAdultes = 1, nbEnfants = 0, zone = 2) {
return chargesNormalesBaseVD.find(x => {
return x.zone === zone &&
x.nbAdultes === nbAdultes &&
x.nbEnfants === nbEnfants;
}).chargesNormales;
}
function chargesNormalesIndependantLookup(chargesNormalesIndependantVD, nbAdultes = 1, nbEnfants = 0, zone = 2) {
return chargesNormalesIndependantVD.find(x => {
return x.zone === zone &&
x.nbAdultes === nbAdultes &&
x.nbEnfants === nbEnfants;
}).chargesNormales;
}
function chargesNormalesComplementairesLookup(chargesNormalesComplementairesVD, age) {
return chargesNormalesComplementairesVD.find(x => {
return x.ageMin <= age &&
x.ageMax >= age;
}).forfait;
}
function fraisEtudeLookup(fraisEtudeVD, mode, key) {
return fraisEtudeVD.find(x => {
return x.mode === mode &&
x.key === key;
}).fraisEtude;
}
export function bourseEtudeVD(sim, chargesNormalesBaseVD,
fraisEtudeVD, chargesNormalesIndependantVD,
fraisTransportVD, chargesNormalesComplementairesVD, bourseZonesVD) {
let boursesTotales = 0;
const rdu = calculRDU(sim);
const nbEtudiants = sim.etudiants.length;
for (let i = 0; i < nbEtudiants; i++) {
const etudiant = sim.etudiants[i];
const charges = [];
const revenus = [];
let montantBourse = 0;
const zone = bourseZonesVD.find(x => {
return x.district === sim.lieuLogement.district;
}).zone;
const nbAdultes = sim.personnes.filter(personne => (personne.estAdulte)).length;
const nbEnfants = nombreEnfants(sim);
let chargesNormalesBaseFoyer = 0;
if (etudiant.estIndependanceFinanciere) {
chargesNormalesBaseFoyer = chargesNormalesIndependantLookup(chargesNormalesIndependantVD, nbAdultes, nbEnfants, zone);
} else {
chargesNormalesBaseFoyer = chargesNormalesBaseLookup(chargesNormalesBaseVD, nbAdultes, nbEnfants, zone);
}
charges.push(["Charges normales de base", chargesNormalesBaseFoyer]);
const chargesNormalesComplementaires = chargesNormalesComplementairesLookup(chargesNormalesComplementairesVD, etudiant.age);
charges.push(["Charges normales complementaires", chargesNormalesComplementaires]);
const fraisRepasForfait = 1500;
charges.push(["Forfait pour frais de repas", fraisRepasForfait]);
if (etudiant.aLogementSepare) {
const fraisLogementSepareForfait = (500 + 280) * 10;
charges.push(["Forfait pour frais de logement sรฉparรฉ", fraisLogementSepareForfait]);
}
// TODO compute frais transports
const fraisTransportForfait = 1000;
charges.push(["Forfait pour frais de transport", fraisTransportForfait]);
let fraisEtude = 0;
const niveau = etudiant.niveauEtude;
const mode = etudiant.formationRedoublementOuTempsPartiel ? "tpr" : "pt";
fraisEtude = fraisEtudeLookup(fraisEtudeVD, mode, niveau.key);
charges.push(["Frais d'รฉtude", fraisEtude]);
// repartition du RDU de l'UER
revenus.push(["Rรฉpartition du revenu dรฉterminant unifiรฉ", Math.round(rdu / nbEtudiants)]);
if (etudiant.revenueAuxiliaireContributionsEntretien) {
revenus.push(["Contributions d'entretien", etudiant.revenueAuxiliaireContributionsEntretien]);
}
if (etudiant.revenueAuxiliairesAutresPrestationsFinancieres) {
revenus.push(["Autres prestations financiรจres", etudiant.revenueAuxiliairesAutresPrestationsFinancieres]);
}
if (etudiant.aParentLogementAutreFoyer) {
const etatCivilFoyer2 = etudiant.nbAdultesFoyer2 > 1 ? 'M' : 'C'; // FIXME etat civil 2e foyer
const rduData = {
revenuNetImposable: etudiant.revenuNetFoyer2,
fortuneImmobiliereLogement: etudiant.fortuneImmobiliereFoyer2,
fortuneImmobiliereAutre: etudiant.autresFortuneImmobiliereFoyer2,
fortuneMobiliere: etudiant.fortuneMobiliereFoyer2,
fraisAccessoiresLogement: etudiant.fraisAccessoiresFoyer2,
personnes: [{etatCivil: etatCivilFoyer2}]
// rentePrevoyancePrivee
};
const rduFoyer2 = calculRDU(rduData);
revenus.push(["Revenu dรฉterminant du foyer du 2e parent", rduFoyer2]);
const chargesNormalesBaseFoyer2 = chargesNormalesBaseLookup(etudiant.nbAdultesFoyer2, etudiant.nbEnfantsFoyer2);
// TODO faudrait-il prendre en compte le nombre d'รฉtudiants dans le 2e foyer pour calculer leurs charges?
charges.push(["Charges normales de bases du foyer du 2e parent", chargesNormalesBaseFoyer2]);
}
// TODO charges fiscales
const chargesTotales = charges.reduce((total, charge) => total + charge[1], 0);
const revenusTotaux = revenus.reduce((total, revenu) => total + revenu[1], 0);
montantBourse = Math.min(revenusTotaux - chargesTotales, 0);
montantBourse = Math.abs(montantBourse);
montantBourse = 10 * Math.round(montantBourse / 10); // arrondi dizaine
// TODO si le revenu est รฉgal ร l'ensemble des charges, l'OCBE octroie une aide pour les frais d'รฉtudes uniquement;
etudiant.bourseEtude = {charges, revenus, chargesTotales, revenusTotaux, montantBourse};
boursesTotales += montantBourse;
}
return boursesTotales;
}
| HEG-Arc/PrestaSoc | src/app/calculateur/bourseCalculVD.js | JavaScript | gpl-3.0 | 5,357 |
const Ava = require('ava')
const Sinon = require('sinon')
const { getCard } = require('../deck')
const Junkyard = require('../junkyard')
Ava.test('should be playable', (t) => {
const game = new Junkyard('player1', 'Jay')
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const aGun = getCard('a-gun')
player1.hand.push(aGun)
game.play(player1, aGun)
t.is(player2.hp, player2.maxHp - 2)
t.is(game.turns, 1)
t.is(game.discardPile.length, 1)
t.truthy(game.discardPile.find(card => card === aGun))
t.is(player1.hand.length, player1.maxHand)
})
Ava.test('should be able to kill a player', (t) => {
const game = new Junkyard('player1', 'Jay')
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const aGun = getCard('a-gun')
player1.hand.push(aGun)
player2.hp = 2
game.play(player1, aGun)
t.is(game.players.length, 1)
})
Ava.test('should be unblockable', (t) => {
const announceCallback = Sinon.spy()
const game = new Junkyard('player1', 'Jay', announceCallback)
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const grab = getCard('grab')
const aGun = getCard('a-gun')
const block = getCard('block')
player1.hand = [grab, aGun]
player2.hand = [block]
game.play(player1.id, player1.hand)
game.play(player2.id, player2.hand)
t.true(announceCallback.calledWith('player:counter-failed'))
t.is(player2.hp, player2.maxHp - 2)
t.is(game.turns, 1)
t.is(game.players[0], player2)
t.is(game.discardPile.length, 3)
t.is(player1.hand.length, 0)
t.is(player2.hand.length, player2.maxHand)
t.truthy(game.discardPile.find(card => card === grab))
t.truthy(game.discardPile.find(card => card === aGun))
t.truthy(game.discardPile.find(card => card === block))
})
Ava.test('should returns valid plays', (t) => {
const game = new Junkyard('player1', 'Jay')
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const aGun = getCard('a-gun')
player1.hand = [aGun]
const plays = aGun.validPlays(player1, player2, game)
t.true(Array.isArray(plays))
plays.forEach((play) => {
t.true(Array.isArray(play.cards))
t.truthy(play.cards.length)
t.truthy(play.target)
t.is(typeof play.weight, 'number')
t.true(play.weight > 1)
})
})
| gfax/junkyard-brawl | src/cards/a-gun.spec.js | JavaScript | gpl-3.0 | 2,378 |
/*
* Network Pong
* Copyright 2012 Oscar Key, Jack Yuan, Will Kochanski
*/
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function(pong, undefined) {
// create the menu namespace
pong.menu = {};
pong.menu.showPosition = function() {
var value = document.getElementById("screenNo").value;
document.getElementById("positionDisplay").innerHTML = value;
}
pong.menu.screenNum = function() {
var value = document.getElementById("totalScreens").value;
document.getElementById("numScreens").innerHTML = value;
}
pong.menu.onConnectClick = function() {
pong.connectAndStart(document.getElementById("addressInput").value,document.getElementById("screenNo").value,document.getElementById("totalScreens").value);
}
}(window.pong = window.pong || {})); | oscarkey/Network-Pong | menu.js | JavaScript | gpl-3.0 | 1,412 |
const rmdir = require("rimraf");
// rmdir("./build", function(error) {});
// rmdir("./public/css", function(error) {});
rmdir("./public/js", function(error) {});
rmdir("./public/img", function(error) {});
| xtreemze/Lemonade | rmDir.js | JavaScript | gpl-3.0 | 210 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'smiley', 'cy', {
options: 'Opsiynau Gwenogluniau',
title: 'Mewnosod Gwenoglun',
toolbar: 'Gwenoglun'
} );
| ernestbuffington/PHP-Nuke-Titanium | includes/wysiwyg/ckeditor/plugins/smiley/lang/cy.js | JavaScript | gpl-3.0 | 299 |
$(document).ready(function () {
init_validation();
});
function search() {
use = $("#use").val();
skin_type = $("#skin_types").val();
difficult_degree = $("#difficult_degree").val();
datas = {
use : use,
skin_type : skin_type,
difficult_degree : difficult_degree
}
$.get(http_path + "formula/index", datas)
}
function add_formula(){
window.location.href = http_path + "formula/new";
}
function init_validation() {
$("input,select,textarea").jqBootstrapValidation({
preventSubmit : true,
submitError : function($form, event, errors) {
},
submitSuccess : function($form, event) {
//TODO
event.preventDefault();
},
filter : function() {
return $(this).is(":visible");
}
});
}
| cuckoo5/soap | Soap_know/static/js/formula.js | JavaScript | gpl-3.0 | 718 |
//ะะตะท ะพะฟะตัะฐัะพัะฐ ัะฐะทะฒะพัะพัะฐ
let mas = ['q','w','e'];
let mas2 = ['a','s','d'];
let mas3 = [mas,'z',mas2,'x','c'];
console.log(mas3);
// ะก ะพะฟะตัะฐัะพัะพะผ ัะฐะทะฒะพัะพัะฐ
let mas4 = ['r','t','y'];
let mas5 = [...mas4,'f','g','h'];
console.log(mas5);
| vivanov1410/coder-school | js/ES6/src/spread.js | JavaScript | gpl-3.0 | 292 |
jQuery(document).ready(function (){
// Comienza la parte de Sockets
socket_cliente = io.connect('/principal') // unica variable global
socket_cliente.on('stockBids', function(top5Bids){
bidList.reset(top5Bids) // llenar la collection de models de ofertas
setTimeout(requerirActualizacion, 5000) // cada 5 segundos requerir actualizacion
})
socket_cliente.on('stockProd', function(topXProd){
if (productoList.length == 5)
productoList.reset([])
productoList.add(topXProd) // llenar la collection de models de ofertas
if (productoList.length == 5)
productoListView.render()
})
function requerirActualizacion(){
socket_cliente.emit('restock')
}
socket_cliente.on('disconnect', function () {
$(".alert-error").removeClass("hide") // desaparecio el servidor
})
})
var ver_input = $('input[type=number]')
ver_input.change(function(){
$('#ver-a').attr('href', '/producto/'+ ver_input.val())
})
var BidItem = Backbone.Model.extend({}),
ProductoItem = Backbone.Model.extend({})
var BidList = Backbone.Collection.extend({model: BidItem}),
ProductoList = Backbone.Collection.extend({model: ProductoItem})
var bidList = new BidList(),
productoList = new ProductoList()
var BidsView = Backbone.View.extend({
tagName: 'li',
template: _.template(
'<p class="text-success">Q.<%= bid%> <%= nombre%> '
),
render: function(){
this.$el.html(this.template(this.model.toJSON()))
return this
}
}), BidsListView = Backbone.View.extend({
el: $('#bids-view'),
initialize: function(){
this.collection.on('reset', this.render, this)
},
addOne: function(bidsItem){
var bidsView = new BidsView({model: bidsItem})
this.$el.append(bidsView.render().el)
},
render: function(){
this.$el.find('li').remove() // quitar los elementos html anteriores
this.collection.forEach(this.addOne, this)
}
}), ProductoView = Backbone.View.extend({
tagName: 'li',
className: 'span9',
template: _.template(
'<a href="/producto/<%= codprod%>" class="thumbnail" target="_blank" rel="tooltip" data-placement="top" title="<%= nombre%>">' +
'<img src="<%= foto%>"/>' +
'<p><%= nombre%></a>'
),
render: function(){
this.$el.html(this.template(this.model.toJSON()))
return this
}
}), ProductoListView = Backbone.View.extend({
el: $('#productos-view'),
addOne: function(productoItem){
var productoView = new ProductoView({model: productoItem})
this.$el.append(productoView.render().el)
},
render: function(){
this.$el.find('li').remove()
this.collection.forEach(this.addOne, this)
}
})
bidsListView = new BidsListView({collection: bidList}),
productoListView = new ProductoListView({collection: productoList})
| yzaguirre/ChapinSubastas | public_html/js/index.js | JavaScript | gpl-3.0 | 2,646 |
var searchData=
[
['parser',['Parser',['../classParser.html#a12234f6cd36b61af4b50c94a179422c1',1,'Parser']]],
['pause',['pause',['../classSound.html#a65b0f66e9123caed2809da366ac4d377',1,'Sound::pause()'],['../classRace.html#af44a886dc92b726224634fd124bd7ddb',1,'Race::pause()'],['../classPause.html#a000be3800357b261b2713439fee551e0',1,'Pause::Pause()']]],
['peeri',['PeerI',['../classTinman_1_1PeerI.html#a57e58a21026bb2d2161692143e4c22a0',1,'Tinman::PeerI']]],
['perform_5faction',['perform_action',['../classBotController.html#a3a22b8226a62462fe52094f7f2183921',1,'BotController']]],
['physics',['Physics',['../classPhysics.html#a4b2ebc0a344f04f48d227c72f0d0fbda',1,'Physics']]],
['physicsdebugdrawer',['PhysicsDebugDrawer',['../classPhysicsDebugDrawer.html#ae1bb27351d9a736ae7f86cf77f509124',1,'PhysicsDebugDrawer']]],
['pick_5fmoney',['pick_money',['../classPlayer.html#aa4ac3c21d5c2668fd3922eeedc66bf4d',1,'Player']]],
['pick_5fnitro',['pick_nitro',['../classPlayer.html#ab6e39fbd03b50c13b67f6fdd523bf1e7',1,'Player']]],
['pick_5fup',['pick_up',['../classPowerUp.html#a139888437577a75d2ac658bee6cc1e3e',1,'PowerUp']]],
['play',['play',['../classSound.html#a94686752a3ef4035d202ed093e35c911',1,'Sound::play()'],['../classPlay.html#a9313fb932111323084a3bd6f74d7b855',1,'Play::Play()']]],
['player',['Player',['../classPlayer.html#ab6d4c11889a757a30210f274df3c62fa',1,'Player']]],
['powerup',['PowerUp',['../classPowerUp.html#a8e3159226639da56072887193485084c',1,'PowerUp']]],
['preallocateindices',['preallocateIndices',['../classMeshStrider.html#a0e74ffdbb0b3ecd1f1168699460ae34d',1,'MeshStrider']]],
['preallocatevertices',['preallocateVertices',['../classMeshStrider.html#aba159643114e0598144c2f9dcdc421ca',1,'MeshStrider']]],
['preparehardwarebuffers',['prepareHardwareBuffers',['../classDynamicRenderable.html#aeedfa92e7cb15c9f7615f97e5aceb72a',1,'DynamicRenderable']]],
['print_5fhelp',['print_help',['../main_8cpp.html#a853216ac51aa181669ff4d3de74058a7',1,'main.cpp']]],
['print_5fvector',['print_vector',['../classPhysics.html#a8080a407553072699d744b82bea1bac5',1,'Physics']]],
['purchase',['purchase',['../classPlayer.html#a620624a42fee83d355051b786db7ef56',1,'Player']]]
];
| isaaclacoba/tinman | doxygen/search/functions_e.js | JavaScript | gpl-3.0 | 2,224 |
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// Test that makes sure web console eval works while the js debugger paused the
// page, and while the inspector is active. See bug 886137.
"use strict";
const TEST_URI = "http://example.com/browser/devtools/client/webconsole/" +
"test/test-eval-in-stackframe.html";
// Force the old debugger UI since it's directly used (see Bug 1301705)
Services.prefs.setBoolPref("devtools.debugger.new-debugger-frontend", false);
registerCleanupFunction(function* () {
Services.prefs.clearUserPref("devtools.debugger.new-debugger-frontend");
});
add_task(function* () {
yield loadTab(TEST_URI);
let hud = yield openConsole();
let dbgPanel = yield openDebugger();
yield openInspector();
yield waitForFrameAdded();
yield openConsole();
yield testVariablesView(hud);
});
function* waitForFrameAdded() {
let target = TargetFactory.forTab(gBrowser.selectedTab);
let toolbox = gDevTools.getToolbox(target);
let thread = toolbox.threadClient;
info("Waiting for framesadded");
yield new Promise(resolve => {
thread.addOneTimeListener("framesadded", resolve);
ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
content.wrappedJSObject.firstCall();
});
});
}
function* testVariablesView(hud) {
info("testVariablesView");
let jsterm = hud.jsterm;
let msg = yield jsterm.execute("fooObj");
ok(msg, "output message found");
ok(msg.textContent.includes('{ testProp2: "testValue2" }'),
"message text check");
let anchor = msg.querySelector("a");
ok(anchor, "object link found");
info("Waiting for variable view to appear");
let variable = yield new Promise(resolve => {
jsterm.once("variablesview-fetched", (e, variable) => {
resolve(variable);
});
executeSoon(() => EventUtils.synthesizeMouse(anchor, 2, 2, {},
hud.iframeWindow));
});
info("Waiting for findVariableViewProperties");
let results = yield findVariableViewProperties(variable, [
{ name: "testProp2", value: "testValue2" },
{ name: "testProp", value: "testValue", dontMatch: true },
], { webconsole: hud });
let prop = results[0].matchedProp;
ok(prop, "matched the |testProp2| property in the variables view");
// Check that property value updates work and that jsterm functions can be
// used.
variable = yield updateVariablesViewProperty({
property: prop,
field: "value",
string: "document.title + foo2 + $('p')",
webconsole: hud
});
info("onFooObjFetchAfterUpdate");
let expectedValue = yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
let para = content.wrappedJSObject.document.querySelector("p");
return content.document.title + "foo2SecondCall" + para;
});
results = yield findVariableViewProperties(variable, [
{ name: "testProp2", value: expectedValue },
], { webconsole: hud });
prop = results[0].matchedProp;
ok(prop, "matched the updated |testProp2| property value");
// Check that testProp2 was updated.
yield new Promise(resolve => {
executeSoon(() => {
jsterm.execute("fooObj.testProp2").then(resolve);
});
});
expectedValue = yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function* () {
let para = content.wrappedJSObject.document.querySelector("p");
return content.document.title + "foo2SecondCall" + para;
});
isnot(hud.outputNode.textContent.indexOf(expectedValue), -1,
"fooObj.testProp2 is correct");
}
| Yukarumya/Yukarum-Redfoxes | devtools/client/webconsole/test/browser_console_variables_view_while_debugging_and_inspecting.js | JavaScript | mpl-2.0 | 3,723 |
'use strict';
/* global SumoDB, Utils, nunjucksEnv */
(function(exports) {
var MSG_NO_QUESTIONS = 'No questions found';
var PROFILE_DETAILS_TMPL = 'helper_profile.html';
var QUESTION_LIST_TMPL = 'question_list_day.html';
var username;
var headline;
var profile_details_container;
var questions_container;
function load_profile() {
SumoDB.get_public_user(username, {avatar_size: 100}).then(function(user) {
headline.textContent = user.display_name || user.username;
var profile_html = nunjucksEnv.render(PROFILE_DETAILS_TMPL, {
user: user
});
profile_details_container.innerHTML = profile_html;
});
SumoDB.get_solved_questions(username).then(function(response) {
var results = response.results;
var html;
if (results.length) {
for (var i = 0, l = results.length; i < l; i++) {
var updated = results[i].updated;
results[i].updated_day = updated.split('T')[0];
results[i].updated = Utils.time_since(new Date(updated));
results[i].displayable_metadata =
Utils.convert_metadata_for_display(results[i].metadata);
}
html = nunjucksEnv.render(QUESTION_LIST_TMPL, {
next: response.next,
results: results
});
} else {
html = nunjucksEnv.render(QUESTION_LIST_TMPL, {
message: MSG_NO_QUESTIONS
});
}
questions_container.insertAdjacentHTML('beforeend', html);
questions_container.classList.remove('hide');
});
}
var HelperProfileController = {
init: function() {
headline = document.getElementById('headline');
profile_details_container = document.getElementById(
'profile-details');
questions_container = document.getElementById('questions');
var params = Utils.get_url_parameters(location);
if (params.username) {
username = params.username;
load_profile();
}
}
};
exports.HelperProfileController = HelperProfileController;
HelperProfileController.init();
})(window);
| zbraniecki/buddyup | app/js/helper_profile_controller.js | JavaScript | mpl-2.0 | 2,083 |
/*
* Copyright (c) 2017 Mattia Panzeri <mattia.panzeri93@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
export { NearItManager as default, constants as NearItConstants } from './lib/NearItManager'
| panz3r/react-native-nearit-sdk | index.js | JavaScript | mpl-2.0 | 372 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var { seq, iterate, filter, map, reductions, reduce, count,
isEmpty, every, isEvery, some, take, takeWhile, drop,
dropWhile, concat, first, rest, nth, last, dropLast,
distinct, remove, mapcat, fromEnumerator, string,
object, pairs, keys, values, each, names, symbols
} = require("sdk/util/sequence");
const boom = () => { throw new Error("Boom!"); };
const broken = seq(function*() {
yield 1;
throw new Error("Boom!");
});
exports["test seq"] = assert => {
let xs = seq(function*() {
yield 1;
yield 2;
yield 3;
});
assert.deepEqual([...seq(null)], [], "seq of null is empty");
assert.deepEqual([...seq(void(0))], [], "seq of void is empty");
assert.deepEqual([...xs], [1, 2, 3], "seq of 1 2 3");
assert.deepEqual([...seq(xs)], [1, 2, 3], "seq of seq is seq");
assert.deepEqual([...seq([])], [], "seq of emtpy array is empty");
assert.deepEqual([...seq([1])], [1], "seq of lonly array is single element");
assert.deepEqual([...seq([1, 2, 3])], [1, 2, 3], "seq of array is it's elements");
assert.deepEqual([...seq("")], [], "seq of emtpy string is empty");
assert.deepEqual([...seq("o")], ["o"], "seq of char is single char seq");
assert.deepEqual([...seq("hello")], ["h", "e", "l", "l", "o"],
"seq of string are chars");
assert.deepEqual([...seq(new Set())], [], "seq of emtpy set is empty");
assert.deepEqual([...seq(new Set([1]))], [1], "seq of lonely set is single");
assert.deepEqual([...seq(new Set([1, 2, 3]))], [1, 2, 3], "seq of lonely set is single");
assert.deepEqual([...seq(new Map())], [], "seq of emtpy map is empty");
assert.deepEqual([...seq(new Map([[1, 2]]))], [[1, 2]], "seq single mapping is that mapping");
assert.deepEqual([...seq(new Map([[1, 2], [3, 4], [5, 6]]))],
[[1, 2], [3, 4], [5, 6]],
"seq of map is key value mappings");
[function(){}, 1, /foo/, true].forEach(x => {
assert.throws(() => seq(x), "Type is not seq-able");
});
assert.throws(() => [...broken],
/Boom/,
"broken sequence errors propagate");
};
exports["test seq casting"] = assert => {
const xs = seq(function*() { yield 1; yield 2; yield 3; });
const ys = seq(function*() { yield 1; });
const zs = seq(function*() {});
const kvs = seq(function*() { yield ["a", 1]; yield ["b", 2]; });
const kv = seq(function*() { yield ["a", 1]; });
assert.deepEqual([...xs], [1, 2, 3], "cast to array");
assert.deepEqual([...ys], [1], "cast to of one element");
assert.deepEqual([...zs], [], "cast empty array");
assert.deepEqual(string(...xs), "123", "cast to string");
assert.deepEqual(string(...ys), "1", "cast to char");
assert.deepEqual(string(...zs), "", "cast to empty string");
assert.deepEqual(new Set(xs), new Set([1, 2, 3]),
"cast to set of items");
assert.deepEqual(new Set(ys), new Set([1]),
"cast to set of one item");
assert.deepEqual(new Set(zs), new Set(),
"cast to set of one item");
assert.deepEqual(new Map(kvs), new Map([["a", 1], ["b", 2]]),
"cast to map");
assert.deepEqual(new Map(kv), new Map([["a", 1]]),
"cast to single mapping");
assert.deepEqual(new Map(zs), new Map(),
"cast to empty map");
assert.deepEqual(object(...kvs), {a: 1, b: 2},
"cast to object");
assert.deepEqual(object(...kv), {a: 1},
"cast to single pair");
assert.deepEqual(object(...zs), {},
"cast to empty object");
};
exports["test pairs"] = assert => {
assert.deepEqual([...pairs(null)], [], "pairs on null is empty");
assert.deepEqual([...pairs(void(0))], [], "pairs on void is empty");
assert.deepEqual([...pairs({})], [], "empty sequence");
assert.deepEqual([...pairs({a: 1})], [["a", 1]], "single pair");
assert.deepEqual([...pairs({a: 1, b: 2, c: 3})].sort(),
[["a", 1], ["b", 2], ["c", 3]],
"creates pairs");
let items = [];
for (let [key, value] of pairs({a: 1, b: 2, c: 3}))
items.push([key, value]);
assert.deepEqual(items.sort(),
[["a", 1], ["b", 2], ["c", 3]],
"for of works on pairs");
assert.deepEqual([...pairs([])], [], "pairs on empty array is empty");
assert.deepEqual([...pairs([1])], [[0, 1]], "pairs on array is [index, element]");
assert.deepEqual([...pairs([1, 2, 3])],
[[0, 1], [1, 2], [2, 3]],
"for arrays it pair of [index, element]");
assert.deepEqual([...pairs("")], [], "pairs on empty string is empty");
assert.deepEqual([...pairs("a")], [[0, "a"]], "pairs on char is [0, char]");
assert.deepEqual([...pairs("hello")],
[[0, "h"], [1, "e"], [2, "l"], [3, "l"], [4, "o"]],
"for strings it's pair of [index, char]");
assert.deepEqual([...pairs(new Map())],
[],
"pairs on empty map is empty");
assert.deepEqual([...pairs(new Map([[1, 3]]))],
[[1, 3]],
"pairs on single mapping single mapping");
assert.deepEqual([...pairs(new Map([[1, 2], [3, 4]]))],
[[1, 2], [3, 4]],
"pairs on map returs key vaule pairs");
assert.throws(() => pairs(new Set()),
"can't pair set");
assert.throws(() => pairs(4),
"can't pair number");
assert.throws(() => pairs(true),
"can't pair boolean");
};
exports["test keys"] = assert => {
assert.deepEqual([...keys(null)], [], "keys on null is empty");
assert.deepEqual([...keys(void(0))], [], "keys on void is empty");
assert.deepEqual([...keys({})], [], "empty sequence");
assert.deepEqual([...keys({a: 1})], ["a"], "single key");
assert.deepEqual([...keys({a: 1, b: 2, c: 3})].sort(),
["a", "b", "c"],
"all keys");
assert.deepEqual([...keys(Object.create({}, {
a: {value: 1, enumerable: true},
b: {value: 2, enumerable: false},
c: {value: 3, enumerable: false}
}))].sort(),
["a"],
"only enumerable keys");
let items = [];
for (let key of keys({a: 1, b: 2, c: 3}))
items.push(key);
assert.deepEqual(items.sort(),
["a", "b", "c"],
"for of works on keys");
assert.deepEqual([...keys([])], [], "keys on empty array is empty");
assert.deepEqual([...keys([1])], [0], "keys on array is indexes");
assert.deepEqual([...keys([1, 2, 3])],
[0, 1, 2],
"keys on arrays returns indexes");
assert.deepEqual([...keys("")], [], "keys on empty string is empty");
assert.deepEqual([...keys("a")], [0], "keys on char is 0");
assert.deepEqual([...keys("hello")],
[0, 1, 2, 3, 4],
"keys on strings is char indexes");
assert.deepEqual([...keys(new Map())],
[],
"keys on empty map is empty");
assert.deepEqual([...keys(new Map([[1, 3]]))],
[1],
"keys on single mapping single mapping is single key");
assert.deepEqual([...keys(new Map([[1, 2], [3, 4]]))],
[1, 3],
"keys on map is keys from map");
assert.throws(() => keys(new Set()),
"can't keys set");
assert.throws(() => keys(4),
"can't keys number");
assert.throws(() => keys(true),
"can't keys boolean");
};
exports["test names"] = assert => {
assert.deepEqual([...names(null)], [], "names on null is empty");
assert.deepEqual([...names(void(0))], [], "names on void is empty");
assert.deepEqual([...names({})], [], "empty sequence");
assert.deepEqual([...names({a: 1})], ["a"], "single key");
assert.deepEqual([...names({a: 1, b: 2, c: 3})].sort(),
["a", "b", "c"],
"all keys");
assert.deepEqual([...names(Object.create({}, {
a: {value: 1, enumerable: true},
b: {value: 2, enumerable: false},
c: {value: 3, enumerable: false}
}))].sort(),
["a", "b", "c"],
"all enumerable & non-enumerable keys");
assert.throws(() => names([1, 2, 3]),
"can't names array");
assert.throws(() => names(""),
"can't names string");
assert.throws(() => names(new Map()),
"can't names map");
assert.throws(() => names(new Set()),
"can't names set");
assert.throws(() => names(4),
"can't names number");
assert.throws(() => names(true),
"can't names boolean");
};
exports["test symbols"] = assert => {
assert.deepEqual([...symbols(null)], [], "symbols on null is empty");
assert.deepEqual([...symbols(void(0))], [], "symbols on void is empty");
assert.deepEqual([...symbols({})], [], "symbols on empty is empty");
assert.deepEqual([...symbols({a: 1})], [], "symbols is empty if not owned");
const b = Symbol("b");
assert.deepEqual([...symbols({a: 1, [b]: 2, c: 3})].sort(),
[b],
"only symbols");
assert.deepEqual([...symbols(Object.create({}, {
a: {value: 1, enumerable: true},
[b]: {value: 2, enumerable: false},
c: {value: 3, enumerable: false}
}))].sort(),
[b],
"includes non-enumerable symbols");
assert.throws(() => symbols([1, 2, 3]),
"can't symbols array");
assert.throws(() => symbols(""),
"can't symbols string");
assert.throws(() => symbols(new Map()),
"can't symbols map");
assert.throws(() => symbols(new Set()),
"can't symbols set");
assert.throws(() => symbols(4),
"can't symbols number");
assert.throws(() => symbols(true),
"can't symbols boolean");
};
exports["test values"] = assert => {
assert.deepEqual([...values({})], [], "empty sequence");
assert.deepEqual([...values({a: 1})], [1], "single value");
assert.deepEqual([...values({a: 1, b: 2, c: 3})].sort(),
[1, 2, 3],
"all values");
let items = [];
for (let value of values({a: 1, b: 2, c: 3}))
items.push(value);
assert.deepEqual(items.sort(),
[1, 2, 3],
"for of works on values");
assert.deepEqual([...values([])], [], "values on empty array is empty");
assert.deepEqual([...values([1])], [1], "values on array elements");
assert.deepEqual([...values([1, 2, 3])],
[1, 2, 3],
"values on arrays returns elements");
assert.deepEqual([...values("")], [], "values on empty string is empty");
assert.deepEqual([...values("a")], ["a"], "values on char is char");
assert.deepEqual([...values("hello")],
["h", "e", "l", "l", "o"],
"values on strings is chars");
assert.deepEqual([...values(new Map())],
[],
"values on empty map is empty");
assert.deepEqual([...values(new Map([[1, 3]]))],
[3],
"keys on single mapping single mapping is single key");
assert.deepEqual([...values(new Map([[1, 2], [3, 4]]))],
[2, 4],
"values on map is values from map");
assert.deepEqual([...values(new Set())], [], "values on empty set is empty");
assert.deepEqual([...values(new Set([1]))], [1], "values on set is it's items");
assert.deepEqual([...values(new Set([1, 2, 3]))],
[1, 2, 3],
"values on set is it's items");
assert.throws(() => values(4),
"can't values number");
assert.throws(() => values(true),
"can't values boolean");
};
exports["test fromEnumerator"] = assert => {
const { Cc, Ci } = require("chrome");
const { enumerateObservers,
addObserver,
removeObserver } = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
const topic = "sec:" + Math.random().toString(32).substr(2);
const [a, b, c] = [{wrappedJSObject: {}},
{wrappedJSObject: {}},
{wrappedJSObject: {}}];
const unwrap = x => x.wrappedJSObject;
[a, b, c].forEach(x => addObserver(x, topic, false));
const xs = fromEnumerator(() => enumerateObservers(topic));
const ys = map(unwrap, xs);
assert.deepEqual([...ys], [a, b, c].map(unwrap),
"all observers are there");
removeObserver(b, topic);
assert.deepEqual([...ys], [a, c].map(unwrap),
"b was removed");
removeObserver(a, topic);
assert.deepEqual([...ys], [c].map(unwrap),
"a was removed");
removeObserver(c, topic);
assert.deepEqual([...ys], [],
"c was removed, now empty");
addObserver(a, topic, false);
assert.deepEqual([...ys], [a].map(unwrap),
"a was added");
removeObserver(a, topic);
assert.deepEqual([...ys], [].map(unwrap),
"a was removed, now empty");
};
exports["test filter"] = assert => {
const isOdd = x => x % 2;
const odds = seq(function*() { yield 1; yield 3; yield 5; });
const evens = seq(function*() { yield 2; yield 4; yield 6; });
const mixed = seq(function*() {
yield 1;
yield 2;
yield 3;
yield 4;
});
assert.deepEqual([...filter(isOdd, mixed)], [1, 3],
"filtered odds");
assert.deepEqual([...filter(isOdd, odds)], [1, 3, 5],
"kept all");
assert.deepEqual([...filter(isOdd, evens)], [],
"kept none");
let xs = filter(boom, mixed);
assert.throws(() => [...xs], /Boom/, "errors propagate");
assert.throws(() => [...filter(isOdd, broken)], /Boom/,
"sequence errors propagate");
};
exports["test filter array"] = assert => {
let isOdd = x => x % 2;
let xs = filter(isOdd, [1, 2, 3, 4]);
let ys = filter(isOdd, [1, 3, 5]);
let zs = filter(isOdd, [2, 4, 6]);
assert.deepEqual([...xs], [1, 3], "filteres odds");
assert.deepEqual([...ys], [1, 3, 5], "kept all");
assert.deepEqual([...zs], [], "kept none");
assert.ok(!Array.isArray(xs));
};
exports["test filter set"] = assert => {
let isOdd = x => x % 2;
let xs = filter(isOdd, new Set([1, 2, 3, 4]));
let ys = filter(isOdd, new Set([1, 3, 5]));
let zs = filter(isOdd, new Set([2, 4, 6]));
assert.deepEqual([...xs], [1, 3], "filteres odds");
assert.deepEqual([...ys], [1, 3, 5], "kept all");
assert.deepEqual([...zs], [], "kept none");
};
exports["test filter string"] = assert => {
let isUpperCase = x => x.toUpperCase() === x;
let xs = filter(isUpperCase, "aBcDe");
let ys = filter(isUpperCase, "ABC");
let zs = filter(isUpperCase, "abcd");
assert.deepEqual([...xs], ["B", "D"], "filteres odds");
assert.deepEqual([...ys], ["A", "B", "C"], "kept all");
assert.deepEqual([...zs], [], "kept none");
};
exports["test filter lazy"] = assert => {
const x = 1;
let y = 2;
const xy = seq(function*() { yield x; yield y; });
const isOdd = x => x % 2;
const actual = filter(isOdd, xy);
assert.deepEqual([...actual], [1], "only one odd number");
y = 3;
assert.deepEqual([...actual], [1, 3], "filter is lazy");
};
exports["test filter non sequences"] = assert => {
const False = _ => false;
assert.throws(() => [...filter(False, 1)],
"can't iterate number");
assert.throws(() => [...filter(False, {a: 1, b:2})],
"can't iterate object");
};
exports["test map"] = assert => {
let inc = x => x + 1;
let xs = seq(function*() { yield 1; yield 2; yield 3; });
let ys = map(inc, xs);
assert.deepEqual([...ys], [2, 3, 4], "incremented each item");
assert.deepEqual([...map(inc, null)], [], "mapping null is empty");
assert.deepEqual([...map(inc, void(0))], [], "mapping void is empty");
assert.deepEqual([...map(inc, new Set([1, 2, 3]))], [2, 3, 4], "maps set items");
};
exports["test map two inputs"] = assert => {
let sum = (x, y) => x + y;
let xs = seq(function*() { yield 1; yield 2; yield 3; });
let ys = seq(function*() { yield 4; yield 5; yield 6; });
let zs = map(sum, xs, ys);
assert.deepEqual([...zs], [5, 7, 9], "summed numbers");
};
exports["test map diff sized inputs"] = assert => {
let sum = (x, y) => x + y;
let xs = seq(function*() { yield 1; yield 2; yield 3; });
let ys = seq(function*() { yield 4; yield 5; yield 6; yield 7; yield 8; });
let zs = map(sum, xs, ys);
assert.deepEqual([...zs], [5, 7, 9], "summed numbers");
assert.deepEqual([...map(sum, ys, xs)], [5, 7, 9],
"index of exhasting input is irrelevant");
};
exports["test map multi"] = assert => {
let sum = (x, y, z, w) => x + y + z + w;
let xs = seq(function*() { yield 1; yield 2; yield 3; yield 4; });
let ys = seq(function*() { yield 4; yield 5; yield 6; yield 7; yield 8; });
let zs = seq(function*() { yield 10; yield 11; yield 12; });
let ws = seq(function*() { yield 0; yield 20; yield 40; yield 60; });
let actual = map(sum, xs, ys, zs, ws);
assert.deepEqual([...actual], [15, 38, 61], "summed numbers");
};
exports["test map errors"] = assert => {
assert.deepEqual([...map(boom, [])], [],
"won't throw if empty");
const xs = map(boom, [1, 2, 4]);
assert.throws(() => [...xs], /Boom/, "propagates errors");
assert.throws(() => [...map(x => x, broken)], /Boom/,
"sequence errors propagate");
};
exports["test reductions"] = assert => {
let sum = (...xs) => xs.reduce((x, y) => x + y, 0);
assert.deepEqual([...reductions(sum, [1, 1, 1, 1])],
[1, 2, 3, 4],
"works with arrays");
assert.deepEqual([...reductions(sum, 5, [1, 1, 1, 1])],
[5, 6, 7, 8, 9],
"array with initial");
assert.deepEqual([...reductions(sum, seq(function*() {
yield 1;
yield 2;
yield 3;
}))],
[1, 3, 6],
"works with sequences");
assert.deepEqual([...reductions(sum, 10, seq(function*() {
yield 1;
yield 2;
yield 3;
}))],
[10, 11, 13, 16],
"works with sequences");
assert.deepEqual([...reductions(sum, [])], [0],
"invokes accumulator with no args");
assert.throws(() => [...reductions(boom, 1, [1])],
/Boom/,
"arg errors errors propagate");
assert.throws(() => [...reductions(sum, 1, broken)],
/Boom/,
"sequence errors propagate");
};
exports["test reduce"] = assert => {
let sum = (...xs) => xs.reduce((x, y) => x + y, 0);
assert.deepEqual(reduce(sum, [1, 2, 3, 4, 5]),
15,
"works with arrays");
assert.deepEqual(reduce(sum, seq(function*() {
yield 1;
yield 2;
yield 3;
})),
6,
"works with sequences");
assert.deepEqual(reduce(sum, 10, [1, 2, 3, 4, 5]),
25,
"works with array & initial");
assert.deepEqual(reduce(sum, 5, seq(function*() {
yield 1;
yield 2;
yield 3;
})),
11,
"works with sequences & initial");
assert.deepEqual(reduce(sum, []), 0, "reduce with no args");
assert.deepEqual(reduce(sum, "a", []), "a", "reduce with initial");
assert.deepEqual(reduce(sum, 1, [1]), 2, "reduce with single & initial");
assert.throws(() => [...reduce(boom, 1, [1])],
/Boom/,
"arg errors errors propagate");
assert.throws(() => [...reduce(sum, 1, broken)],
/Boom/,
"sequence errors propagate");
};
exports["test each"] = assert => {
const collect = xs => {
let result = [];
each((...etc) => result.push(...etc), xs);
return result;
};
assert.deepEqual(collect(null), [], "each ignores null");
assert.deepEqual(collect(void(0)), [], "each ignores void");
assert.deepEqual(collect([]), [], "each ignores empty");
assert.deepEqual(collect([1]), [1], "each works on single item arrays");
assert.deepEqual(collect([1, 2, 3, 4, 5]),
[1, 2, 3, 4, 5],
"works with arrays");
assert.deepEqual(collect(seq(function*() {
yield 1;
yield 2;
yield 3;
})),
[1, 2, 3],
"works with sequences");
assert.deepEqual(collect(""), [], "ignores empty strings");
assert.deepEqual(collect("a"), ["a"], "works on chars");
assert.deepEqual(collect("hello"), ["h", "e", "l", "l", "o"],
"works on strings");
assert.deepEqual(collect(new Set()), [], "ignores empty sets");
assert.deepEqual(collect(new Set(["a"])), ["a"],
"works on single item sets");
assert.deepEqual(collect(new Set([1, 2, 3])), [1, 2, 3],
"works on muti item tests");
assert.deepEqual(collect(new Map()), [], "ignores empty maps");
assert.deepEqual(collect(new Map([["a", 1]])), [["a", 1]],
"works on single mapping maps");
assert.deepEqual(collect(new Map([[1, 2], [3, 4], [5, 6]])),
[[1, 2], [3, 4], [5, 6]],
"works on muti mapping maps");
assert.throws(() => collect({}), "objects arn't supported");
assert.throws(() => collect(1), "numbers arn't supported");
assert.throws(() => collect(true), "booleas arn't supported");
};
exports["test count"] = assert => {
assert.equal(count(null), 0, "null counts to 0");
assert.equal(count(), 0, "undefined counts to 0");
assert.equal(count([]), 0, "empty array");
assert.equal(count([1, 2, 3]), 3, "non-empty array");
assert.equal(count(""), 0, "empty string");
assert.equal(count("hello"), 5, "non-empty string");
assert.equal(count(new Map()), 0, "empty map");
assert.equal(count(new Map([[1, 2], [2, 3]])), 2, "non-empty map");
assert.equal(count(new Set()), 0, "empty set");
assert.equal(count(new Set([1, 2, 3, 4])), 4, "non-empty set");
assert.equal(count(seq(function*() {})), 0, "empty sequence");
assert.equal(count(seq(function*() { yield 1; yield 2; })), 2,
"non-empty sequence");
assert.throws(() => count(broken),
/Boom/,
"sequence errors propagate");
};
exports["test isEmpty"] = assert => {
assert.equal(isEmpty(null), true, "null is empty");
assert.equal(isEmpty(), true, "undefined is empty");
assert.equal(isEmpty([]), true, "array is array");
assert.equal(isEmpty([1, 2, 3]), false, "array isn't empty");
assert.equal(isEmpty(""), true, "string is empty");
assert.equal(isEmpty("hello"), false, "non-empty string");
assert.equal(isEmpty(new Map()), true, "empty map");
assert.equal(isEmpty(new Map([[1, 2], [2, 3]])), false, "non-empty map");
assert.equal(isEmpty(new Set()), true, "empty set");
assert.equal(isEmpty(new Set([1, 2, 3, 4])), false , "non-empty set");
assert.equal(isEmpty(seq(function*() {})), true, "empty sequence");
assert.equal(isEmpty(seq(function*() { yield 1; yield 2; })), false,
"non-empty sequence");
assert.equal(isEmpty(broken), false, "hasn't reached error");
};
exports["test isEvery"] = assert => {
let isOdd = x => x % 2;
let isTrue = x => x === true;
let isFalse = x => x === false;
assert.equal(isEvery(isOdd, seq(function*() {
yield 1;
yield 3;
yield 5;
})), true, "all are odds");
assert.equal(isEvery(isOdd, seq(function*() {
yield 1;
yield 2;
yield 3;
})), false, "contains even");
assert.equal(isEvery(isTrue, seq(function*() {})), true, "true if empty");
assert.equal(isEvery(isFalse, seq(function*() {})), true, "true if empty");
assert.equal(isEvery(isTrue, null), true, "true for null");
assert.equal(isEvery(isTrue, undefined), true, "true for undefined");
assert.throws(() => isEvery(boom, [1, 2]),
/Boom/,
"arg errors errors propagate");
assert.throws(() => isEvery(x => true, broken),
/Boom/,
"sequence errors propagate");
assert.equal(isEvery(x => false, broken), false,
"hasn't reached error");
};
exports["test some"] = assert => {
let isOdd = x => x % 2;
let isTrue = x => x === true;
let isFalse = x => x === false;
assert.equal(some(isOdd, seq(function*() {
yield 2;
yield 4;
yield 6;
})), null, "all are even");
assert.equal(some(isOdd, seq(function*() {
yield 2;
yield 3;
yield 4;
})), true, "contains odd");
assert.equal(some(isTrue, seq(function*() {})), null,
"null if empty")
assert.equal(some(isFalse, seq(function*() {})), null,
"null if empty")
assert.equal(some(isTrue, null), null, "null for null");
assert.equal(some(isTrue, undefined), null, "null for undefined");
assert.throws(() => some(boom, [1, 2]),
/Boom/,
"arg errors errors propagate");
assert.throws(() => some(x => false, broken),
/Boom/,
"sequence errors propagate");
assert.equal(some(x => true, broken), true,
"hasn't reached error");
};
exports["test take"] = assert => {
let xs = seq(function*() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
yield 6;
});
assert.deepEqual([...take(3, xs)], [1, 2, 3], "took 3 items");
assert.deepEqual([...take(3, [1, 2, 3, 4, 5])], [1, 2, 3],
"took 3 from array");
let ys = seq(function*() { yield 1; yield 2; });
assert.deepEqual([...take(3, ys)], [1, 2], "takes at max n");
assert.deepEqual([...take(3, [1, 2])], [1, 2],
"takes at max n from arary");
let empty = seq(function*() {});
assert.deepEqual([...take(5, empty)], [], "nothing to take");
assert.throws(() => [...take(3, broken)],
/Boom/,
"sequence errors propagate");
assert.deepEqual([...take(1, broken)], [1],
"hasn't reached error");
};
exports["test iterate"] = assert => {
let inc = x => x + 1;
let nums = iterate(inc, 0);
assert.deepEqual([...take(5, nums)], [0, 1, 2, 3, 4], "took 5");
assert.deepEqual([...take(10, nums)], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "took 10");
let xs = iterate(x => x * 3, 2);
assert.deepEqual([...take(4, xs)], [2, 6, 18, 54], "took 4");
assert.throws(() => [...iterate(boom, 0)],
/Boom/,
"function exceptions propagate");
};
exports["test takeWhile"] = assert => {
let isNegative = x => x < 0;
let xs = seq(function*() {
yield -2;
yield -1;
yield 0;
yield 1;
yield 2;
yield 3;
});
assert.deepEqual([...takeWhile(isNegative, xs)], [-2, -1],
"took until 0");
let ys = seq(function*() {});
assert.deepEqual([...takeWhile(isNegative, ys)], [],
"took none");
let zs = seq(function*() {
yield 0;
yield 1;
yield 2;
yield 3;
});
assert.deepEqual([...takeWhile(isNegative, zs)], [],
"took none");
assert.throws(() => [...takeWhile(boom, zs)],
/Boom/,
"function errors errors propagate");
assert.throws(() => [...takeWhile(x => true, broken)],
/Boom/,
"sequence errors propagate");
assert.deepEqual([...takeWhile(x => false, broken)],
[],
"hasn't reached error");
};
exports["test drop"] = assert => {
let testDrop = xs => {
assert.deepEqual([...drop(2, xs)],
[3, 4],
"dropped two elements");
assert.deepEqual([...drop(1, xs)],
[2, 3, 4],
"dropped one");
assert.deepEqual([...drop(0, xs)],
[1, 2, 3, 4],
"dropped 0");
assert.deepEqual([...drop(-2, xs)],
[1, 2, 3, 4],
"dropped 0 on negative `n`");
assert.deepEqual([...drop(5, xs)],
[],
"dropped all items");
};
testDrop([1, 2, 3, 4]);
testDrop(seq(function*() {
yield 1;
yield 2;
yield 3;
yield 4;
}));
assert.throws(() => [...drop(1, broken)],
/Boom/,
"sequence errors propagate");
};
exports["test dropWhile"] = assert => {
let isNegative = x => x < 0;
let True = _ => true;
let False = _ => false;
let test = xs => {
assert.deepEqual([...dropWhile(isNegative, xs)],
[0, 1, 2],
"dropped negative");
assert.deepEqual([...dropWhile(True, xs)],
[],
"drop all");
assert.deepEqual([...dropWhile(False, xs)],
[-2, -1, 0, 1, 2],
"keep all");
};
test([-2, -1, 0, 1, 2]);
test(seq(function*() {
yield -2;
yield -1;
yield 0;
yield 1;
yield 2;
}));
assert.throws(() => [...dropWhile(boom, [1, 2, 3])],
/Boom/,
"function errors errors propagate");
assert.throws(() => [...dropWhile(x => true, broken)],
/Boom/,
"sequence errors propagate");
};
exports["test concat"] = assert => {
let test = (a, b, c, d) => {
assert.deepEqual([...concat()],
[],
"nothing to concat");
assert.deepEqual([...concat(a)],
[1, 2, 3],
"concat with nothing returns same as first");
assert.deepEqual([...concat(a, b)],
[1, 2, 3, 4, 5],
"concat items from both");
assert.deepEqual([...concat(a, b, a)],
[1, 2, 3, 4, 5, 1, 2, 3],
"concat itself");
assert.deepEqual([...concat(c)],
[],
"concat of empty is empty");
assert.deepEqual([...concat(a, c)],
[1, 2, 3],
"concat with empty");
assert.deepEqual([...concat(c, c, c)],
[],
"concat of empties is empty");
assert.deepEqual([...concat(c, b)],
[4, 5],
"empty can be in front");
assert.deepEqual([...concat(d)],
[7],
"concat singular");
assert.deepEqual([...concat(d, d)],
[7, 7],
"concat singulars");
assert.deepEqual([...concat(a, a, b, c, d, c, d, d)],
[1, 2, 3, 1, 2, 3, 4, 5, 7, 7, 7],
"many concats");
let ab = concat(a, b);
let abcd = concat(ab, concat(c, d));
let cdabcd = concat(c, d, abcd);
assert.deepEqual([...cdabcd],
[7, 1, 2, 3, 4, 5, 7],
"nested concats");
};
test([1, 2, 3],
[4, 5],
[],
[7]);
test(seq(function*() { yield 1; yield 2; yield 3; }),
seq(function*() { yield 4; yield 5; }),
seq(function*() { }),
seq(function*() { yield 7; }));
assert.throws(() => [...concat(broken, [1, 2, 3])],
/Boom/,
"function errors errors propagate");
};
exports["test first"] = assert => {
let test = (xs, empty) => {
assert.equal(first(xs), 1, "returns first");
assert.equal(first(empty), null, "returns null empty");
};
test("1234", "");
test([1, 2, 3], []);
test([1, 2, 3], null);
test([1, 2, 3], undefined);
test(seq(function*() { yield 1; yield 2; yield 3; }),
seq(function*() { }));
assert.equal(first(broken), 1, "did not reached error");
};
exports["test rest"] = assert => {
let test = (xs, x, nil) => {
assert.deepEqual([...rest(xs)], ["b", "c"],
"rest items");
assert.deepEqual([...rest(x)], [],
"empty when singular");
assert.deepEqual([...rest(nil)], [],
"empty when empty");
};
test("abc", "a", "");
test(["a", "b", "c"], ["d"], []);
test(seq(function*() { yield "a"; yield "b"; yield "c"; }),
seq(function*() { yield "d"; }),
seq(function*() {}));
test(["a", "b", "c"], ["d"], null);
test(["a", "b", "c"], ["d"], undefined);
assert.throws(() => [...rest(broken)],
/Boom/,
"sequence errors propagate");
};
exports["test nth"] = assert => {
let notFound = {};
let test = xs => {
assert.equal(nth(xs, 0), "h", "first");
assert.equal(nth(xs, 1), "e", "second");
assert.equal(nth(xs, 5), void(0), "out of bound");
assert.equal(nth(xs, 5, notFound), notFound, "out of bound");
assert.equal(nth(xs, -1), void(0), "out of bound");
assert.equal(nth(xs, -1, notFound), notFound, "out of bound");
assert.equal(nth(xs, 4), "o", "5th");
};
let testEmpty = xs => {
assert.equal(nth(xs, 0), void(0), "no first in empty");
assert.equal(nth(xs, 5), void(0), "no 5th in empty");
assert.equal(nth(xs, 0, notFound), notFound, "notFound on out of bound");
};
test("hello");
test(["h", "e", "l", "l", "o"]);
test(seq(function*() {
yield "h";
yield "e";
yield "l";
yield "l";
yield "o";
}));
testEmpty(null);
testEmpty(undefined);
testEmpty([]);
testEmpty("");
testEmpty(seq(function*() {}));
assert.throws(() => nth(broken, 1),
/Boom/,
"sequence errors propagate");
assert.equal(nth(broken, 0), 1, "have not reached error");
};
exports["test last"] = assert => {
assert.equal(last(null), null, "no last in null");
assert.equal(last(void(0)), null, "no last in undefined");
assert.equal(last([]), null, "no last in []");
assert.equal(last(""), null, "no last in ''");
assert.equal(last(seq(function*() { })), null, "no last in empty");
assert.equal(last("hello"), "o", "last from string");
assert.equal(last([1, 2, 3]), 3, "last from array");
assert.equal(last([1]), 1, "last from singular");
assert.equal(last(seq(function*() {
yield 1;
yield 2;
yield 3;
})), 3, "last from sequence");
assert.throws(() => last(broken),
/Boom/,
"sequence errors propagate");
};
exports["test dropLast"] = assert => {
let test = xs => {
assert.deepEqual([...dropLast(xs)],
[1, 2, 3, 4],
"dropped last");
assert.deepEqual([...dropLast(0, xs)],
[1, 2, 3, 4, 5],
"dropped none on 0");
assert.deepEqual([...dropLast(-3, xs)],
[1, 2, 3, 4, 5],
"drop none on negative");
assert.deepEqual([...dropLast(3, xs)],
[1, 2],
"dropped given number");
assert.deepEqual([...dropLast(5, xs)],
[],
"dropped all");
};
let testEmpty = xs => {
assert.deepEqual([...dropLast(xs)],
[],
"nothing to drop");
assert.deepEqual([...dropLast(0, xs)],
[],
"dropped none on 0");
assert.deepEqual([...dropLast(-3, xs)],
[],
"drop none on negative");
assert.deepEqual([...dropLast(3, xs)],
[],
"nothing to drop");
};
test([1, 2, 3, 4, 5]);
test(seq(function*() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}));
testEmpty([]);
testEmpty("");
testEmpty(seq(function*() {}));
assert.throws(() => [...dropLast(broken)],
/Boom/,
"sequence errors propagate");
};
exports["test distinct"] = assert => {
let test = (xs, message) => {
assert.deepEqual([...distinct(xs)],
[1, 2, 3, 4, 5],
message);
};
test([1, 2, 1, 3, 1, 4, 1, 5], "works with arrays");
test(seq(function*() {
yield 1;
yield 2;
yield 1;
yield 3;
yield 1;
yield 4;
yield 1;
yield 5;
}), "works with sequences");
test(new Set([1, 2, 1, 3, 1, 4, 1, 5]),
"works with sets");
test(seq(function*() {
yield 1;
yield 2;
yield 2;
yield 2;
yield 1;
yield 3;
yield 1;
yield 4;
yield 4;
yield 4;
yield 1;
yield 5;
}), "works with multiple repeatitions");
test([1, 2, 3, 4, 5], "work with distinct arrays");
test(seq(function*() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}), "works with distinct seqs");
};
exports["test remove"] = assert => {
let isPositive = x => x > 0;
let test = xs => {
assert.deepEqual([...remove(isPositive, xs)],
[-2, -1, 0],
"removed positives");
};
test([1, -2, 2, -1, 3, 7, 0]);
test(seq(function*() {
yield 1;
yield -2;
yield 2;
yield -1;
yield 3;
yield 7;
yield 0;
}));
assert.throws(() => [...distinct(broken)],
/Boom/,
"sequence errors propagate");
};
exports["test mapcat"] = assert => {
let upto = n => seq(function* () {
let index = 0;
while (index < n) {
yield index;
index = index + 1;
}
});
assert.deepEqual([...mapcat(upto, [1, 2, 3, 4])],
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3],
"expands given sequence");
assert.deepEqual([...mapcat(upto, [0, 1, 2, 0])],
[0, 0, 1],
"expands given sequence");
assert.deepEqual([...mapcat(upto, [0, 0, 0])],
[],
"expands given sequence");
assert.deepEqual([...mapcat(upto, [])],
[],
"nothing to expand");
assert.deepEqual([...mapcat(upto, null)],
[],
"nothing to expand");
assert.deepEqual([...mapcat(upto, void(0))],
[],
"nothing to expand");
let xs = seq(function*() {
yield 0;
yield 1;
yield 0;
yield 2;
yield 0;
});
assert.deepEqual([...mapcat(upto, xs)],
[0, 0, 1],
"expands given sequence");
assert.throws(() => [...mapcat(boom, xs)],
/Boom/,
"function errors errors propagate");
assert.throws(() => [...mapcat(upto, broken)],
/Boom/,
"sequence errors propagate");
};
require("sdk/test").run(exports);
| Yukarumya/Yukarum-Redfoxes | addon-sdk/source/test/test-sequence.js | JavaScript | mpl-2.0 | 39,167 |
describe('skip-link test pass', function() {
'use strict';
var results;
before(function(done) {
axe.testUtils.awaitNestedLoad(function() {
axe.run({ runOnly: { type: 'rule', values: ['skip-link'] } }, function(
err,
r
) {
assert.isNull(err);
results = r;
done();
});
});
});
describe('violations', function() {
it('should find 0', function() {
assert.lengthOf(results.violations, 0);
});
});
describe('passes', function() {
it('should find 3', function() {
assert.lengthOf(results.passes[0].nodes, 3);
});
});
it('should find 0 inapplicable', function() {
assert.lengthOf(results.inapplicable, 0);
});
it('should find 1 incomplete', function() {
assert.lengthOf(results.incomplete, 1);
});
});
| dequelabs/axe-core | test/integration/full/skip-link/skip-link-pass.js | JavaScript | mpl-2.0 | 825 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var assert = require('assert');
var request = require('supertest');
var app = require('../lib/app')();
var mocks = require('./lib/mocks');
var UID = 'abcdef123456';
describe('/sms', function () {
it('forwards properly-authenticated requests through to basket', function (done) {
var PHONE_NUMBER = '15555551234';
var MSG_ID = 'SMS_Android';
var OPTIN = 'N';
mocks.mockOAuthResponse().reply(200, {
user: UID,
scope: ['basket']
});
mocks.mockProfileResponse().reply(200, {
email: 'dont@ca.re',
});
mocks.mockBasketResponse().post('/subscribe_sms/', function (body) {
assert.deepEqual(body, {
/*eslint-disable camelcase*/
mobile_number: PHONE_NUMBER,
msg_id: MSG_ID,
/*eslint-enable camelcase*/
optin: OPTIN
});
return true;
}).reply(200, {
status: 'ok',
});
request(app)
.post('/subscribe_sms')
.set('authorization', 'Bearer TOKEN')
.send({
/*eslint-disable camelcase*/
mobile_number: PHONE_NUMBER,
msg_id: MSG_ID,
/*eslint-enable camelcase*/
optin: OPTIN
})
.expect(200, {
status: 'ok',
})
.end(done);
});
it('returns an error if no credentials are provided', function (done) {
request(app)
.post('/subscribe_sms')
.expect('Content-Type', /json/)
.expect(400, {
status: 'error',
code: 5,
desc: 'missing authorization header'
})
.end(done);
});
it('returns an error if the basket server request errors out', function (done) {
var PHONE_NUMBER = '15555551234';
var MSG_ID = 'SMS_Android';
var OPTIN = 'N';
mocks.mockOAuthResponse().reply(200, {
user: UID,
scope: ['basket']
});
mocks.mockProfileResponse().reply(200, {
email: 'dont@ca.re',
});
mocks.mockBasketResponse().post('/subscribe_sms/', function (body) {
assert.deepEqual(body, {
/*eslint-disable camelcase*/
mobile_number: PHONE_NUMBER,
msg_id: MSG_ID,
/*eslint-enable camelcase*/
optin: OPTIN
});
return true;
}).replyWithError('ruh-roh!');
request(app)
.post('/subscribe_sms')
.set('authorization', 'Bearer TOKEN')
.send({
/*eslint-disable camelcase*/
mobile_number: PHONE_NUMBER,
msg_id: MSG_ID,
/*eslint-enable camelcase*/
optin: OPTIN
})
.expect(500, {
status: 'error',
code: 99,
desc: 'Error: ruh-roh!'
})
.end(done);
});
});
| mozilla/fxa-basket-proxy | test/sms.js | JavaScript | mpl-2.0 | 2,811 |
import React from 'react';
import { Subscriber } from 'joy-react-broadcast';
import PropTypes from 'prop-types';
import is from 'styled-is';
import styled from 'styled-components';
import Card, { BaseCard } from './card';
const BaseOutlet = styled(BaseCard)`
box-sizing: border-box;
display: inline-flex;
flex: 1 1 auto;
flex-direction: column;
border-width: 0;
background-color: transparent;
${is('collapsed')`
display: none;
`};
`;
export const Outlet = ({ children, ...rest }) => (
<Subscriber channel="card">
{({ secondary, tertiary, collapsed }) => (
<BaseOutlet
{...rest}
name="card-outlet"
secondary={secondary}
tertiary={tertiary}
collapsed={collapsed}
>
{children}
</BaseOutlet>
)}
</Subscriber>
);
Outlet.propTypes = {
...Card.propTypes,
children: PropTypes.node
};
Outlet.defaultProps = {
...Card.defaultProps,
children: null
};
export default Outlet;
| yldio/joyent-portal | packages/ui-toolkit/src/card/outlet.js | JavaScript | mpl-2.0 | 978 |
/* @flow */
import invariant from 'invariant';
import {
UNLOAD_ADDON_REVIEWS,
UPDATE_RATING_COUNTS,
} from 'amo/actions/reviews';
import { removeUndefinedProps } from 'core/utils/addons';
import { ADDON_TYPE_THEME } from 'core/constants';
import type {
UnloadAddonReviewsAction,
UpdateRatingCountsAction,
} from 'amo/actions/reviews';
import type { ExternalAddonInfoType } from 'amo/api/addonInfo';
import type { AppState } from 'amo/store';
import type { ErrorHandlerType } from 'core/errorHandler';
import type {
AddonType,
ExternalAddonType,
PartialExternalAddonType,
ThemeData,
} from 'core/types/addons';
import type { AppState as DiscoAppState } from 'disco/store';
export const FETCH_ADDON_INFO: 'FETCH_ADDON_INFO' = 'FETCH_ADDON_INFO';
export const LOAD_ADDON_INFO: 'LOAD_ADDON_INFO' = 'LOAD_ADDON_INFO';
export const FETCH_ADDON: 'FETCH_ADDON' = 'FETCH_ADDON';
export const LOAD_ADDON_RESULTS: 'LOAD_ADDON_RESULTS' = 'LOAD_ADDON_RESULTS';
type AddonID = number;
export type AddonInfoType = {
eula: string | null,
privacyPolicy: string | null,
};
export type AddonsState = {|
// Flow wants hash maps with string keys.
// See: https://zhenyong.github.io/flowtype/docs/objects.html#objects-as-maps
byID: { [addonId: string]: AddonType },
byGUID: { [addonGUID: string]: AddonID },
bySlug: { [addonSlug: string]: AddonID },
infoBySlug: {
[slug: string]: {| info: AddonInfoType, loading: boolean |},
},
loadingBySlug: { [addonSlug: string]: boolean },
|};
export const initialState: AddonsState = {
byID: {},
byGUID: {},
bySlug: {},
infoBySlug: {},
loadingBySlug: {},
};
type FetchAddonParams = {|
errorHandler: ErrorHandlerType,
slug: string,
|};
export type FetchAddonAction = {|
type: typeof FETCH_ADDON,
payload: {|
errorHandlerId: string,
slug: string,
|},
|};
export function fetchAddon({
errorHandler,
slug,
}: FetchAddonParams): FetchAddonAction {
if (!errorHandler) {
throw new Error('errorHandler cannot be empty');
}
if (!slug) {
throw new Error('slug cannot be empty');
}
return {
type: FETCH_ADDON,
payload: { errorHandlerId: errorHandler.id, slug },
};
}
type LoadAddonResultsParams = {|
addons: Array<ExternalAddonType>,
|};
export type LoadAddonResultsAction = {|
payload: LoadAddonResultsParams,
type: typeof LOAD_ADDON_RESULTS,
|};
export function loadAddonResults({
addons,
}: LoadAddonResultsParams = {}): LoadAddonResultsAction {
if (!addons) {
throw new Error('addons are required');
}
return {
type: LOAD_ADDON_RESULTS,
payload: { addons },
};
}
type FetchAddonInfoParams = {|
errorHandlerId: string,
slug: string,
|};
export type FetchAddonInfoAction = {|
type: typeof FETCH_ADDON_INFO,
payload: FetchAddonInfoParams,
|};
export const fetchAddonInfo = ({
errorHandlerId,
slug,
}: FetchAddonInfoParams): FetchAddonInfoAction => {
invariant(errorHandlerId, 'errorHandlerId is required');
invariant(slug, 'slug is required');
return {
type: FETCH_ADDON_INFO,
payload: { errorHandlerId, slug },
};
};
type LoadAddonInfoParams = {|
info: ExternalAddonInfoType,
slug: string,
|};
type LoadAddonInfoAction = {|
type: typeof LOAD_ADDON_INFO,
payload: LoadAddonInfoParams,
|};
export const loadAddonInfo = ({
info,
slug,
}: LoadAddonInfoParams = {}): LoadAddonInfoAction => {
invariant(info, 'info is required');
invariant(slug, 'slug is required');
return {
type: LOAD_ADDON_INFO,
payload: { info, slug },
};
};
export function getGuid(
addon: ExternalAddonType | PartialExternalAddonType,
): string {
if (addon.type === ADDON_TYPE_THEME) {
// This mimics how Firefox appends @personas.mozilla.org internally.
// It's needed to look up themes in mozAddonManager.
return `${addon.id}@personas.mozilla.org`;
}
return addon.guid;
}
export function createInternalThemeData(
apiAddon: ExternalAddonType | PartialExternalAddonType,
): ThemeData | null {
if (!apiAddon.theme_data) {
return null;
}
return {
accentcolor: apiAddon.theme_data.accentcolor,
author: apiAddon.theme_data.author,
category: apiAddon.theme_data.category,
description: apiAddon.theme_data.description,
detailURL: apiAddon.theme_data.detailURL,
footer: apiAddon.theme_data.footer,
footerURL: apiAddon.theme_data.footerURL,
header: apiAddon.theme_data.header,
headerURL: apiAddon.theme_data.headerURL,
iconURL: apiAddon.theme_data.iconURL,
id: apiAddon.theme_data.id,
name: apiAddon.theme_data.name,
previewURL: apiAddon.theme_data.previewURL,
textcolor: apiAddon.theme_data.textcolor,
updateURL: apiAddon.theme_data.updateURL,
version: apiAddon.theme_data.version,
};
}
export function createInternalAddon(
apiAddon: ExternalAddonType | PartialExternalAddonType,
): AddonType {
let addon: AddonType = {
authors: apiAddon.authors,
average_daily_users: apiAddon.average_daily_users,
categories: apiAddon.categories,
contributions_url: apiAddon.contributions_url,
created: apiAddon.created,
default_locale: apiAddon.default_locale,
description: apiAddon.description,
edit_url: apiAddon.edit_url,
guid: getGuid(apiAddon),
has_eula: apiAddon.has_eula,
has_privacy_policy: apiAddon.has_privacy_policy,
homepage: apiAddon.homepage,
icon_url: apiAddon.icon_url,
id: apiAddon.id,
is_disabled: apiAddon.is_disabled,
is_experimental: apiAddon.is_experimental,
is_featured: apiAddon.is_featured,
is_source_public: apiAddon.is_source_public,
last_updated: apiAddon.last_updated,
latest_unlisted_version: apiAddon.latest_unlisted_version,
locale_disambiguation: apiAddon.locale_disambiguation,
name: apiAddon.name,
previews: apiAddon.previews,
public_stats: apiAddon.public_stats,
ratings: apiAddon.ratings,
requires_payment: apiAddon.requires_payment,
review_url: apiAddon.review_url,
slug: apiAddon.slug,
status: apiAddon.status,
summary: apiAddon.summary,
support_email: apiAddon.support_email,
support_url: apiAddon.support_url,
tags: apiAddon.tags,
target_locale: apiAddon.target_locale,
type: apiAddon.type,
url: apiAddon.url,
weekly_downloads: apiAddon.weekly_downloads,
// These are custom properties not in the API response.
currentVersionId: apiAddon.current_version
? apiAddon.current_version.id
: null,
isRestartRequired: false,
isWebExtension: false,
isMozillaSignedExtension: false,
themeData: createInternalThemeData(apiAddon),
};
const currentVersion = apiAddon.current_version;
if (
currentVersion &&
currentVersion.files &&
currentVersion.files.length > 0
) {
addon.isRestartRequired = currentVersion.files.some(
(file) => !!file.is_restart_required,
);
// The following checks are a bit fragile since only one file needs
// to contain the flag. However, it is highly unlikely to create an
// add-on with mismatched file flags in the current DevHub.
addon.isWebExtension = currentVersion.files.some(
(file) => !!file.is_webextension,
);
addon.isMozillaSignedExtension = currentVersion.files.some(
(file) => !!file.is_mozilla_signed_extension,
);
}
// Remove undefined properties entirely. This is for some legacy code
// in Discopane that relies on spreads to combine a Discopane result
// (which has a header and description) with a minimal add-on object.
// For example, the minimal add-on object does not have a description
// property so the spread should not override `description`.
addon = removeUndefinedProps(addon);
return addon;
}
export const getAddonByID = (
state: AppState | DiscoAppState,
id: AddonID,
): AddonType | null => {
return state.addons.byID[`${id}`] || null;
};
export const getAddonBySlug = (
state: AppState,
slug: string,
): AddonType | null => {
if (typeof slug !== 'string') {
return null;
}
const addonId = state.addons.bySlug[slug.toLowerCase()];
return getAddonByID(state, addonId);
};
export const getAddonByGUID = (
state: AppState | DiscoAppState,
guid: string,
): AddonType | null => {
const addonId = state.addons.byGUID[guid];
return getAddonByID(state, addonId);
};
export const isAddonLoading = (state: AppState, slug: string): boolean => {
if (typeof slug !== 'string') {
return false;
}
return Boolean(state.addons.loadingBySlug[slug.toLowerCase()]);
};
export const getAllAddons = (state: AppState): Array<AddonType> => {
const addons = state.addons.byID;
// $FLOW_FIXME: see https://github.com/facebook/flow/issues/2221.
return Object.values(addons);
};
type GetBySlugParams = {|
slug: string,
state: AddonsState,
|};
export const getAddonInfoBySlug = ({
slug,
state,
}: GetBySlugParams): AddonInfoType | null => {
invariant(slug, 'slug is required');
invariant(state, 'state is required');
const infoForSlug = state.infoBySlug[slug];
return (infoForSlug && infoForSlug.info) || null;
};
export const isAddonInfoLoading = ({
slug,
state,
}: GetBySlugParams): boolean => {
invariant(slug, 'slug is required');
invariant(state, 'state is required');
const infoForSlug = state.infoBySlug[slug];
return Boolean(infoForSlug && infoForSlug.loading);
};
export const createInternalAddonInfo = (
addonInfo: ExternalAddonInfoType,
): AddonInfoType => {
return {
eula: addonInfo.eula,
privacyPolicy: addonInfo.privacy_policy,
};
};
type Action =
| FetchAddonAction
| FetchAddonInfoAction
| LoadAddonInfoAction
| LoadAddonResultsAction
| UnloadAddonReviewsAction
| UpdateRatingCountsAction;
export default function addonsReducer(
state: AddonsState = initialState,
action: Action,
) {
switch (action.type) {
case FETCH_ADDON: {
const { slug } = action.payload;
return {
...state,
loadingBySlug: {
...state.loadingBySlug,
[slug.toLowerCase()]: true,
},
};
}
case LOAD_ADDON_RESULTS: {
const { addons: loadedAddons } = action.payload;
const byID = { ...state.byID };
const byGUID = { ...state.byGUID };
const bySlug = { ...state.bySlug };
const loadingBySlug = { ...state.loadingBySlug };
loadedAddons.forEach((loadedAddon) => {
const addon = createInternalAddon(loadedAddon);
// Flow wants hash maps with string keys.
// See: https://zhenyong.github.io/flowtype/docs/objects.html#objects-as-maps
byID[`${addon.id}`] = addon;
if (addon.slug) {
bySlug[addon.slug.toLowerCase()] = addon.id;
loadingBySlug[addon.slug.toLowerCase()] = false;
}
if (addon.guid) {
// `guid` is already "normalized" with the `getGuid()` function in
// `createInternalAddon()`.
byGUID[addon.guid] = addon.id;
}
});
return {
...state,
byID,
byGUID,
bySlug,
loadingBySlug,
};
}
case UNLOAD_ADDON_REVIEWS: {
const { addonId } = action.payload;
const addon = state.byID[`${addonId}`];
if (addon) {
return {
...state,
byID: {
...state.byID,
[`${addonId}`]: undefined,
},
byGUID: {
...state.byGUID,
[addon.guid]: undefined,
},
bySlug: {
...state.bySlug,
[addon.slug.toLowerCase()]: undefined,
},
loadingBySlug: {
...state.loadingBySlug,
[addon.slug.toLowerCase()]: undefined,
},
};
}
return state;
}
case UPDATE_RATING_COUNTS: {
const { addonId, oldReview, newReview } = action.payload;
const addon = state.byID[`${addonId}`];
if (!addon) {
return state;
}
const { ratings } = addon;
let average = ratings ? ratings.average : 0;
let ratingCount = ratings ? ratings.count : 0;
let reviewCount = ratings ? ratings.text_count : 0;
let countForAverage = ratingCount;
if (average && countForAverage && oldReview && oldReview.score) {
// If average and countForAverage are defined and greater than 0,
// begin by subtracting the old rating to reset the baseline.
const countAfterRemoval = countForAverage - 1;
if (countAfterRemoval === 0) {
// There are no ratings left.
average = 0;
} else {
// Expand all existing rating scores, take away the old score,
// and recalculate the average.
average =
(average * countForAverage - oldReview.score) / countAfterRemoval;
}
countForAverage = countAfterRemoval;
}
// Expand all existing rating scores, add in the new score,
// and recalculate the average.
average =
(average * countForAverage + newReview.score) / (countForAverage + 1);
// Adjust rating / review counts.
if (!oldReview) {
// A new rating / review was added.
ratingCount += 1;
if (newReview.body) {
reviewCount += 1;
}
} else if (!oldReview.body && newReview.body) {
// A rating was converted into a review.
reviewCount += 1;
}
return {
...state,
byID: {
...state.byID,
[addonId]: {
...addon,
ratings: {
...ratings,
average,
// It's impossible to recalculate the bayesian_average
// (i.e. median) so we set it to the average as an
// approximation.
bayesian_average: average,
count: ratingCount,
text_count: reviewCount,
},
},
},
};
}
case FETCH_ADDON_INFO: {
const { slug } = action.payload;
return {
...state,
infoBySlug: {
...state.infoBySlug,
[slug]: {
info: undefined,
loading: true,
},
},
};
}
case LOAD_ADDON_INFO: {
const { slug, info } = action.payload;
return {
...state,
infoBySlug: {
...state.infoBySlug,
[slug]: {
info: createInternalAddonInfo(info),
loading: false,
},
},
};
}
default:
return state;
}
}
| tsl143/addons-frontend | src/core/reducers/addons.js | JavaScript | mpl-2.0 | 14,512 |
# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla Communicator client code, released
# March 31, 1998.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Alec Flett <alecf@netscape.com>
# Bill Law <law@netscape.com>
# Blake Ross <blakeross@telocity.com>
# Dean Tessman <dean_tessman@hotmail.com>
# Matt Fisher <matt@netscape.com>
# Simon Fraser <sfraser@netscape.com>
# Stuart Parmenter <pavlov@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
var dialog; // Quick access to document/form elements.
var gFindInst; // nsIWebBrowserFind that we're going to use
var gFindInstData; // use this to update the find inst data
function initDialogObject()
{
// Create dialog object and initialize.
dialog = new Object;
dialog.findKey = document.getElementById("dialog.findKey");
dialog.caseSensitive = document.getElementById("dialog.caseSensitive");
dialog.wrap = document.getElementById("dialog.wrap");
dialog.find = document.getElementById("btnFind");
dialog.up = document.getElementById("radioUp");
dialog.down = document.getElementById("radioDown");
dialog.rg = dialog.up.radioGroup;
dialog.bundle = null;
// Move dialog to center, if it not been shown before
var windowElement = document.getElementById("findDialog");
if (!windowElement.hasAttribute("screenX") || !windowElement.hasAttribute("screenY"))
{
sizeToContent();
moveToAlertPosition();
}
}
function fillDialog()
{
// get the find service, which stores global find state
var findService = Components.classes["@mozilla.org/find/find_service;1"]
.getService(Components.interfaces.nsIFindService);
// Set initial dialog field contents. Use the gFindInst attributes first,
// this is necessary for window.find()
dialog.findKey.value = gFindInst.searchString ? gFindInst.searchString : findService.searchString;
dialog.caseSensitive.checked = gFindInst.matchCase ? gFindInst.matchCase : findService.matchCase;
dialog.wrap.checked = gFindInst.wrapFind ? gFindInst.wrapFind : findService.wrapFind;
var findBackwards = gFindInst.findBackwards ? gFindInst.findBackwards : findService.findBackwards;
if (findBackwards)
dialog.rg.selectedItem = dialog.up;
else
dialog.rg.selectedItem = dialog.down;
}
function saveFindData()
{
// get the find service, which stores global find state
var findService = Components.classes["@mozilla.org/find/find_service;1"]
.getService(Components.interfaces.nsIFindService);
// Set data attributes per user input.
findService.searchString = dialog.findKey.value;
findService.matchCase = dialog.caseSensitive.checked;
findService.wrapFind = dialog.wrap.checked;
findService.findBackwards = dialog.up.selected;
}
function onLoad()
{
initDialogObject();
// get the find instance
var arg0 = window.arguments[0];
// If the dialog was opened from window.find(),
// arg0 will be an instance of nsIWebBrowserFind
if (arg0 instanceof Components.interfaces.nsIWebBrowserFind) {
gFindInst = arg0;
} else {
gFindInstData = arg0;
gFindInst = gFindInstData.webBrowserFind;
}
fillDialog();
doEnabling();
if (dialog.findKey.value)
dialog.findKey.select();
dialog.findKey.focus();
}
function onUnload()
{
window.opener.findDialog = 0;
}
function onAccept()
{
if (gFindInstData && gFindInst != gFindInstData.webBrowserFind) {
gFindInstData.init();
gFindInst = gFindInstData.webBrowserFind;
}
// Transfer dialog contents to the find service.
saveFindData();
// set up the find instance
gFindInst.searchString = dialog.findKey.value;
gFindInst.matchCase = dialog.caseSensitive.checked;
gFindInst.wrapFind = dialog.wrap.checked;
gFindInst.findBackwards = dialog.up.selected;
// Search.
var result = gFindInst.findNext();
if (!result)
{
if (!dialog.bundle)
dialog.bundle = document.getElementById("findBundle");
window.alert(dialog.bundle.getString("notFoundWarning"));
dialog.findKey.select();
dialog.findKey.focus();
}
return false;
}
function doEnabling()
{
dialog.find.disabled = !dialog.findKey.value;
}
| tmhorne/celtx | toolkit/content/finddialog.js | JavaScript | mpl-2.0 | 6,138 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/**
* The following functions are used in testing to control and inspect
* the nsIProfiler in child process content. These should be called from
* the parent process.
*/
const { Cc, Ci } = require("chrome");
const { Task } = require("devtools/shared/task");
const FRAME_SCRIPT_UTILS_URL = "chrome://devtools/content/shared/frame-script-utils.js";
let gMM = null;
/**
* Loads the relevant frame scripts into the provided browser's message manager.
*/
exports.pmmLoadFrameScripts = (gBrowser) => {
gMM = gBrowser.selectedBrowser.messageManager;
gMM.loadFrameScript(FRAME_SCRIPT_UTILS_URL, false);
};
/**
* Clears the cached message manager.
*/
exports.pmmClearFrameScripts = () => {
gMM = null;
};
/**
* Sends a message to the message listener, attaching an id to the payload data.
* Resolves a returned promise when the response is received from the message
* listener, with the same id as part of the response payload data.
*/
exports.pmmUniqueMessage = function (message, payload) {
if (!gMM) {
throw new Error("`pmmLoadFrameScripts()` must be called when using MessageManager.");
}
let { generateUUID } = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator);
payload.id = generateUUID().toString();
return new Promise(resolve => {
gMM.addMessageListener(message + ":response", function onHandler({ data }) {
if (payload.id == data.id) {
gMM.removeMessageListener(message + ":response", onHandler);
resolve(data.data);
}
});
gMM.sendAsyncMessage(message, payload);
});
};
/**
* Checks if the nsProfiler module is active.
*/
exports.pmmIsProfilerActive = () => {
return exports.pmmSendProfilerCommand("IsActive");
};
/**
* Starts the nsProfiler module.
*/
exports.pmmStartProfiler = Task.async(function* ({ entries, interval, features }) {
let isActive = (yield exports.pmmSendProfilerCommand("IsActive")).isActive;
if (!isActive) {
return exports.pmmSendProfilerCommand("StartProfiler", [entries, interval, features,
features.length]);
}
return null;
});
/**
* Stops the nsProfiler module.
*/
exports.pmmStopProfiler = Task.async(function* () {
let isActive = (yield exports.pmmSendProfilerCommand("IsActive")).isActive;
if (isActive) {
return exports.pmmSendProfilerCommand("StopProfiler");
}
return null;
});
/**
* Calls a method on the nsProfiler module.
*/
exports.pmmSendProfilerCommand = (method, args = []) => {
return exports.pmmUniqueMessage("devtools:test:profiler", { method, args });
};
/**
* Evaluates a script in content, returning a promise resolved with the
* returned result.
*/
exports.pmmEvalInDebuggee = (script) => {
return exports.pmmUniqueMessage("devtools:test:eval", { script });
};
/**
* Evaluates a console method in content.
*/
exports.pmmConsoleMethod = function (method, ...args) {
// Terrible ugly hack -- this gets stringified when it uses the
// message manager, so an undefined arg in `console.profileEnd()`
// turns into a stringified "null", which is terrible. This method
// is only used for test helpers, so swap out the argument if its undefined
// with an empty string. Differences between empty string and undefined are
// tested on the front itself.
if (args[0] == null) {
args[0] = "";
}
return exports.pmmUniqueMessage("devtools:test:console", { method, args });
};
| Yukarumya/Yukarum-Redfoxes | devtools/client/performance/test/helpers/profiler-mm-utils.js | JavaScript | mpl-2.0 | 3,663 |
/* jshint forin:true, noarg:false, noempty:true, eqeqeq:true, bitwise:true,
strict:true, undef:true, curly:false, browser:true,
unused:true,
indent:2, maxerr:50, devel:true, node:true, boss:true, white:true,
globalstrict:true, nomen:false, newcap:true, esnext: true, moz: true */
/*global exports, require, console, Cc, Ci */
/** usage
- on pages like the ui-debug page, use this to get current top bar notice
for styling and debugging
- must be used from a priv'd page, like about:addons
*/
let getnb = function () {
let BROWSER = 'navigator:browser';
let WM = Cc['@mozilla.org/appshell/window-mediator;1'].
getService(Ci.nsIWindowMediator);
function getMostRecentWindow(type) {
return WM.getMostRecentWindow(type);
}
function getMostRecentBrowserWindow() {
return getMostRecentWindow(BROWSER);
}
let win = getMostRecentBrowserWindow();
// noficication
let box = win.document.getElementById("high-priority-global-notificationbox");
let notice = box.currentNotification;
let messageImage = document.getAnonymousElementByAttribute(notice, "class", "messageImage");
let messageText = document.getAnonymousElementByAttribute(notice, "class", "messageText");
let closeButton = document.getAnonymousElementByAttribute(notice, "class", "messageCloseButton close-icon tabbable");
return {
win: win,
box: box,
//scoreEl: scoreEl,
notice: notice,
//which: which,
messageImage: messageImage,
messageText: messageText,
closeButton: closeButton
};
};
let loop = (thing, fn) => [].forEach.call(thing, fn);
| gregglind/firefox-pulse | heartbeat-telemetry-experiment-1/getnb-helper.js | JavaScript | mpl-2.0 | 1,604 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The initial developer of trinitymobile-main.js is Rob Gerns.
* Copyright 2012 Rob Gerns. All rights reserved.*/
/*
* Function: TrinityMobile
*
* Parameters: none
*
* Constructor function that holds all of the various methods that handle
* data that's passed in from called trinjal methods.
*
*/
function TrinityMobile() {
"use strict";
//newsResponse method handles the Trinity News XML data
this.newsResponse = function (args, trinityNewsXML) {
var i = 0,
//Get the currently used jQuery Mobile theme, defaults to a.
tcCurrentTheme = $("div").attr("data-theme") || "a",
//Used to create an LI element that will hold an item's date.
tcNewsDateLI = "",
//All of the RSS feed items.
tcNewsItems = trinityNewsXML.getElementsByTagName("item"),
tcNewsItemDate = "",
tcNewsItemDateOrig = "",
tcNewsItemLink = "",
tcNewsItemTitle = "",
tcNewsLength = tcNewsItems.length,
//Used to create an LI element that will hold the link to the item.
tcNewsLinkLI = "",
//The place in the HTML where new markup should be inserted.
tcNewsUL = document.getElementById("tcNews-ul");
//This method doesn't use any arguments so make it null to be safe.
args = null;
//Grab each news item's title, link, and date...description isn't needed.
for (i = 0; i < tcNewsLength; i++) {
tcNewsItemTitle = tcNewsItems[i].getElementsByTagName("title")[0].
firstChild.nodeValue;
tcNewsItemLink = tcNewsItems[i].getElementsByTagName("link")[0].
firstChild.nodeValue;
tcNewsItemDateOrig = tcNewsItems[i].getElementsByTagName("pubDate")[0].
firstChild.nodeValue;
//Remove the timestamp from the date, as that's not really relevant.
tcNewsItemDate = tcNewsItemDateOrig.replace(
/\s\d\d[:]\d\d[:]\d\d\s.+/,
""
);
//Create a new LI with the correct theme, write the item's date.
tcNewsDateLI = document.createElement("li");
tcNewsUL.appendChild(tcNewsDateLI);
tcNewsDateLI.setAttribute("data-role", "list-divider");
tcNewsDateLI.setAttribute("data-theme", tcCurrentTheme);
tcNewsDateLI.innerHTML = tcNewsItemDate;
//Create a new LI with the correct theme, write the item's title.
tcNewsLinkLI = document.createElement("li");
tcNewsUL.appendChild(tcNewsLinkLI);
tcNewsLinkLI.setAttribute("id", "news-item-link" + i);
tcNewsLinkLI.setAttribute("data-theme", tcCurrentTheme);
tcNewsLinkLI.setAttribute("style", "padding-left: 5px");
tcNewsLinkLI.innerHTML = "<p><a href=\"" +
tcNewsItemLink +
"\" style=\"white-space: normal; color: blue;" +
" text-decoration: none\">" +
tcNewsItemTitle +
"</a></p>";
}
//Done, so go back to the place where this method was called.
return true;
};
//blogResponse method handles the Trinity Blog XML data.
this.blogResponse = function (args, trinityBlogXML) {
var i = 0,
//tcBlogDescriptionContainer = "", - unused for now.
tcBlogItem = "",
tcBlogItems = trinityBlogXML.getElementsByTagName("item"),
tcBlogItemDate = "",
tcBlogItemDateOrig = "",
//tcBlogItemDescription = "", - unused for now.
//tcBlogItemDescriptionOrig = "", - unused for now.
tcBlogItemLink = "",
tcBlogItemTitle = "",
tcBlogItemTitleOrig = "",
//The place where new HTML should be inserted.
tcBlogUL = document.getElementById("tcBlog-ul");
//This method doesn't have any arguments, so set it to null to be safe.
args = null;
//Get each item's title, link, and date (description doesn't work for now).
for (i = 0; i < 10; i++) {
tcBlogItemTitleOrig = tcBlogItems[i].
getElementsByTagName("title")[0].
firstChild.nodeValue;
//remove any in-line styles from the title
tcBlogItemTitle =
tcBlogItemTitleOrig.
replace(/style=\"[a-zA-Z0-9\-\:\;\s]+\"/gi, "");
tcBlogItemLink = tcBlogItems[i].getElementsByTagName("link")[0].
firstChild.nodeValue;
/*tcBlogItemDescriptionOrig = tcBlogItems[i].
getElementsByTagName("description")[0].firstChild.nodeValue;
tcBlogItemDescription =
tcBlogItemDescriptionOrig.
replace(/style=\"[a-zA-Z0-9\-\:\;\s]+\"/gi, "");*/
tcBlogItemDateOrig = tcBlogItems[i].
getElementsByTagName("pubDate")[0].firstChild.nodeValue;
//Remove the timestamp from the date.
tcBlogItemDate =
tcBlogItemDateOrig.replace(/\s\d\d[:]\d\d[:]\d\d\s.+/, "");
//Create a new element for the item and write in the date and title.
tcBlogItem = document.createElement("h3");
tcBlogUL.appendChild(tcBlogItem);
tcBlogItem.innerHTML =
tcBlogItemDate +
//Make the title into a link to the full post.
"<br/><a href=\"" +
tcBlogItemLink +
"\" style=\"font-size: small; " +
"padding:0 0 0 2px; white-space: normal;\">" +
tcBlogItemTitle +
"</a>";
//Can't get this to work properly...so it's disabled for now
//
//tcBlogDescriptionContainer = document.createElement("div");
//tcBlogUL.appendChild(tcBlogDescriptionContainer);
//tcBlogDescriptionContainer.innerHTML = tcBlogItemDescription;
}
//Done, so go back to the place where this method was called.
return true;
};
//twitterResponse method handles the @trinityeastonpa XML data.
this.twitterResponse = function (args, trinityTwitterXML) {
var i = 0,
//Links that are in a tweet, not the URL to the tweet itself.
newStatusLinks = "",
statusLinks = "",
//Get the current jquery mobile theme, default to "a."
tcCurrentTheme = $("div").attr("data-theme") || "a",
//Used to reference a specific tweet the loop processes.
tcStatus = "",
tcStatusDate = "",
tcStatusDateOrig = "",
//All of the statuses found in the XML.
tcStatuses = trinityTwitterXML.getElementsByTagName("item"),
tcStatusLength = tcStatuses.length,
//URL to a specific tweet.
tcStatusURL = "",
//Not the location of the tweet but what app was used to tweet.
tcTweetFrom = "",
//Used to create an LI element to insert a given tweet's HTML.
tcTwitterLI = "",
//The tweet's description with all of the links reformatted.
tcTwitterStatus = "",
//The tweet's description prior to links being reformatted.
tcTwitterStatusOrig = "",
//The place in the document where the new markup should be inserted.
tcTwitterUL = document.getElementById("tcTwitter-ul");
//There are no parameters for this method, so make this null to be safe.
args = null;
//Loop to process every tweet in the feed, one at a time.
for (i = 0; i < tcStatusLength; i++) {
//The tweet (item) object currently being processed.
tcStatus = tcStatuses[i];
//The tweet itself, otherwise known as the status or description.
tcTwitterStatusOrig =
tcStatus.getElementsByTagName("description")[0].
firstChild.nodeValue;
//Get any links that are in the tweet.
statusLinks = tcTwitterStatusOrig.match(/http:\/\/\b.\S+/);
//And reformat them into working links.
newStatusLinks = "<a href=\"" + statusLinks +
"\" style=\"color: blue\">" + statusLinks + "</a>";
//Replace any links with the corresponding new working links.
tcTwitterStatus = tcTwitterStatusOrig.replace(statusLinks,
newStatusLinks);
//Get the date the tweet was posted.
tcStatusDateOrig = tcStatus.getElementsByTagName("pubDate")[0].
firstChild.nodeValue;
//Remove the +0000 from the datetime.
tcStatusDate = tcStatusDateOrig.replace(/[+]\d\d\d\d/, ' ');
//Get the URL to the tweet.
tcStatusURL = tcStatus.getElementsByTagName("link")[0].
firstChild.nodeValue;
//Get whatever was used to post the tweet (web, specific app, etc).
tcTweetFrom = tcStatus.getElementsByTagName("source")[0].
firstChild.nodeValue;
//Create a new element and write the markup to show the tweet.
tcTwitterLI = document.createElement("li");
tcTwitterUL.appendChild(tcTwitterLI);
tcTwitterLI.setAttribute("data-theme", tcCurrentTheme);
tcTwitterLI.setAttribute("data-icon", "false");
tcTwitterLI.innerHTML = "<p style=\"white-space: normal;\">" +
tcTwitterStatus;
tcTwitterLI.innerHTML += "</p><span style=\"font-size: x-small\">" +
tcStatusDate + " via " + tcTweetFrom + "</span>";
}
//Done, so go back to the place where this method was called.
return true;
};
//facebookResponse method handles the relevant Facebook XML data.
this.facebookResponse = function (args, trinityFacebookXML) {
var i = 0,
//The XML item containing the Facebook status/post info.
tcEntry = "",
//The author of the status.
tcFacebookBy = "",
tcFacebookByName = "",
//The actual post.
tcFacebookContent = "",
//When the status was posted.
tcFacebookDate = "",
tcFacebookDateOrig = "",
//These are used to do various regex operations to format the date.
tcFacebookDateMod = "",
tcFacebookDateMod2 = "",
tcFacebookDateMod3 = "",
tcFacebookDateMod4 = "",
tcFacebookDateMod5 = "",
tcFacebookDateMod6 = "",
tcFacebookDateMod7 = "",
//The time of the post was published in HH:MM:SS.
tcFacebookDateTime = "",
//Where to place the markup.
tcFacebookDiv = document.getElementById("tcFacebook"),
//All of the posts.
tcFacebookEntries =
trinityFacebookXML.getElementsByTagName("entry"),
tcFacebookLength = tcFacebookEntries.length,
//The URL to an individual post.
tcFacebookLink = "",
//The title of an individual post.
tcFacebookTitle = "";
//This method has no parameters, so set this to null to be safe.
args = null;
//A loop that processes each entry one at a time.
for (i = 0; i < tcFacebookLength; i++) {
//The object (entry/post) currently being processed
tcEntry = tcFacebookEntries[i];
//Get the post's title
tcFacebookTitle = tcEntry.getElementsByTagName("title")[0].
firstChild.nodeValue;
//Get the post's URL.
tcFacebookLink = tcEntry.getElementsByTagName("link")[0].
getAttribute("href");
//Get the datetime the post was published.
tcFacebookDateOrig = tcEntry.getElementsByTagName("published")[0].
firstChild.nodeValue;
//Date is originally formatted: YYYY-MM-DDTHH:MM:SS+00:00
tcFacebookDateMod =
//remove +00:00, date is now YYYY-MM-DDTHH:MM:SS
tcFacebookDateOrig.replace(/\+\d*\D\d*/, '');
tcFacebookDateMod2 =
//remove T, date is now YYYY-MM-DD HH:MM:SS
tcFacebookDateMod.replace(/T/, ' ');
tcFacebookDateMod3 =
//remove :SS, date is now YYYY-MM-DD HH:MM
tcFacebookDateMod2.replace(/:\d\d$/,'');
tcFacebookDateTime =
//get the hours and minutes
tcFacebookDateMod3.match(/\d\d:\d\d/);
tcFacebookDateMod4 =
//remove the time, date is now YYYY-MM-DD
tcFacebookDateMod3.replace(/\s\d\d:\d\d/,'');
tcFacebookDateYear =
//get the year and the following -
tcFacebookDateMod4.match(/^\d\d\d\d-/);
tcFacebookDateMod5 =
//remove the year and following dash, date is now MM-DD
tcFacebookDateMod4.replace(/\d\d\d\d-/, '');
tcFacebookDateMod6 =
//add year and time to end, date is now MM-DD-YYYY-
tcFacebookDateMod5 + '-' + tcFacebookDateYear;
tcFacebookDateMod7 =
//remove final dash, date is now MM-DD-YYYY
tcFacebookDateMod6.replace(/-$/,'');
tcFacebookDate =
//add the time back, date is now MM-DD-YYYY HH:MM
tcFacebookDateMod7 + ' ' + tcFacebookDateTime;
//Get the author of the post.
tcFacebookBy = tcEntry.getElementsByTagName("author")[0];
tcFacebookByName = tcFacebookBy.getElementsByTagName("name")[0].
firstChild.nodeValue;
//Get the actual post itself.
tcFacebookContent = tcEntry.getElementsByTagName("content")[0].
firstChild.nodeValue;
//Create the appropriate markup to display the Facebook post.
tcFacebookDiv.innerHTML += "<p style=\"font-size:large;" +
"font-weight:bold\">";
tcFacebookDiv.innerHTML += tcFacebookDate + "</p><br/>";
tcFacebookDiv.innerHTML += tcFacebookContent + "<br/>";
tcFacebookDiv.innerHTML += "<p style=\"font-size: x-small\">";
tcFacebookDiv.innerHTML += "Posted by " + tcFacebookByName +
"<br/><br/>";
tcFacebookDiv.innerHTML += "<a href='" + tcFacebookLink + "'>" +
tcFacebookLink + "</a>";
tcFacebookDiv.innerHTML += "</p><hr style=\"color: black;\"/>";
}
//Done, so go back to the place where this method was called.
return true;
};
//calendarResponse method handles any calendar XML data.
this.calendarResponse = function (args, trinityCalendarXML) {
var i = 0,
//Where to place the HTML markup.
tcCalendar = document.getElementById("tcCalendar");
//All of the events (actual events) defined in the calendar XML.
tcCalendarItems = trinityCalendarXML.getElementsByTagName("item"),
//The description of the event.
tcCalendarItemDesc = "",
//The link to the event on the calendar website.
tcCalendarItemLink = "",
tcCalendarLength = tcCalendarItems.length,
//Used for writing the events into the HTML.
tcCalendarLinkLI = "",
//The currently used jQuery mobile theme, defaults to "a."
tcCurrentTheme = $("div").attr("data-theme") || "a";
//This method doesn't use parameters, so set args to null to be safe.
args = null;
//Process each calendar event (item), one at a time.
for (i = 0; i < tcCalendarLength; i++) {
//Get the event's link
tcCalendarItemLink = tcCalendarItems[i].getElementsByTagName("link")[0].
firstChild.nodeValue;
//Get the event description, which also contains the date and time.
tcCalendarItemDesc = tcCalendarItems[i].getElementsByTagName("description")[0].
firstChild.nodeValue;
//Create the appropriate HTML markup and add it to the document.
tcCalendarP = document.createElement("p");
tcCalendar.appendChild(tcCalendarP);
tcCalendarP.setAttribute("id", "Calendar-item-link" + i);
tcCalendarP.setAttribute("data-theme", tcCurrentTheme);
tcCalendarP.setAttribute("style", "padding-left: 5px");
tcCalendarP.innerHTML = tcCalendarItemDesc +
"<a href=\"" +
tcCalendarItemLink +
"\" style=\"white-space: normal; color: blue;" +
" text-decoration: none\">" +
"More Information" +
"</a>" +
"<hr/>";
}
//Done, so go back to the place where this method was called.
return true;
};
//serviceTimesResponse method handles the relevant Service Times XML data.
this.serviceTimesResponse = function (args, serviceTimesXML) {
var i = 0,
j = 0,
//Get all the services that are defined in the XML.
tcAllServices = serviceTimesXML.getElementsByTagName("service"),
tcAllServicesLength = tcAllServices.length,
//Get any special services that are defined in the XML.
tcAllSpecial = serviceTimesXML.getElementsByTagName("special"),
//The location of the service (church, chapel, etc).
tcLocation = "",
//The service that's being processed by the loop.
tcService = "",
//The day of the service.
tcServiceDayOrig = "",
//The day of the service reformatted.
tcServiceDay = "",
//The place in the document to insert the markup for Service Times.
tcServiceTimesDiv = document.getElementById("tcServiceTimes"),
tcSpecialLength = tcAllSpecial.length,
//The place in the document to insert markup for Special Services.
tcSpecialServiceTimesDiv =
document.getElementById("tcSpecialServiceTimes"),
//Info about any special services.
tcSpecialLocation = "",
tcSpecialService = "",
tcSpecialServiceDay = "",
tcSpecialServiceDate = "",
tcSpecialTime = "",
tcSpecialType = "",
//The time of the service.
tcTime = "",
//What kind of service.
tcType = "";
//This method doesn't have any parameters, so make args null to be safe.
args = null;
//Process any special services first.
for (i = 0; i < tcSpecialLength; i++) {
//The current special service's object.
tcSpecialService = tcAllSpecial[i];
//Get the special service's day (Sunday, Monday, Tuesday, etc).
tcSpecialServiceDay =
tcSpecialService.getElementsByTagName("day")[0].
firstChild.nodeValue;
//Get the date of the special service.
tcSpecialServiceDate =
tcSpecialService.getElementsByTagName("date")[0].
firstChild.nodeValue;
//Get the special service's time.
tcSpecialTime =
tcSpecialService.getElementsByTagName("time")[0].
firstChild.nodeValue;
//Get the special service's type info (baptism, Christmas, etc).
tcSpecialType =
tcSpecialService.getElementsByTagName("servicetype")[0].
firstChild.nodeValue;
//Get the location of the special service (church, chapel, etc).
tcSpecialLocation =
tcSpecialService.getElementsByTagName("location")[0].
firstChild.nodeValue;
//Add the appropriate HTML markup to the document.
tcSpecialServiceTimesDiv.innerHTML +=
"<h3 style='color: #0000cf'>" +
tcSpecialServiceDay + " " + tcSpecialServiceDate + "</h3>";
tcSpecialServiceTimesDiv.innerHTML += "<p>" +
"<span style='font-weight: bold'>" + tcSpecialTime;
tcSpecialServiceTimesDiv.innerHTML += "</span><br/>" +
tcSpecialType +
"<br/><br/>";
tcSpecialServiceTimesDiv.innerHTML += "Location: " +
tcSpecialLocation +
"</p><hr/>";
}
//Process each "regular" service, one at time.
for (j = 0; j < tcAllServicesLength; j++) {
//The service object currently being processed.
tcService = tcAllServices[j];
//Get the day of the service (Sunday, Monday, etc).
tcServiceDayOrig = tcService.parentNode.nodeName;
//Make the day's first letter uppercase.
tcServiceDay = tcServiceDayOrig.substr(0, 1).toUpperCase() +
tcServiceDayOrig.substr(1);
//Get the time of the service.
tcTime = tcService.getElementsByTagName("time")[0].
firstChild.nodeValue;
//Get the type of service (Holy Eucharist, Noon Prayer, etc).
tcType = tcService.getElementsByTagName("servicetype")[0].
firstChild.nodeValue;
//Get the location of the service (church, chapel, etc).
tcLocation = tcService.getElementsByTagName("location")[0].
firstChild.nodeValue;
//Add the appropriate HTML to the document.
tcServiceTimesDiv.innerHTML += "<h3>" +
tcServiceDay + "</h3>";
tcServiceTimesDiv.innerHTML += "<p>" +
"<span style='font-weight: bold'>" + tcTime;
tcServiceTimesDiv.innerHTML += "</span><br/>" + tcType +
"<br/><br/>";
tcServiceTimesDiv.innerHTML += "Location: " + tcLocation +
"</p><hr/>";
}
//Done, so go back to the place where this method was called.
return true;
};
}
//Create a new global instance of the trinityMobile object
var trinityMobile = new TrinityMobile();
| trinityeaston/Trinity-Mobile | 0.1.1/www/scripts/trinitymobile-main.js | JavaScript | mpl-2.0 | 23,509 |
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
'use strict';
var webdriver = require('selenium-webdriver'),
assert = require('assert');
const makeSuite = require('./lib/make_suite');
makeSuite('Test set up UI', (setUpWebapp) => {
// TODO: Clean up this work around by not using the driver anywhere
// in this file
var driver = setUpWebapp.driver;
describe('sessions ui', function() {
var setUpPage;
var signedInPage;
var elements;
var shortPasswordErrorMessage
= 'Please use a password of at least 8 characters.';
var errorPasswordDoNotMatch = 'Passwords don\'t match! Please try again.';
describe('Foxbox index', function() {
it('should be titled FoxBox', function () {
return driver.wait(webdriver.until.titleIs('FoxBox'), 5000)
.then(function(value) {
assert.equal(value, true);
});
});
describe('signup', function() {
beforeEach(function() {
elements = {
pwd1: driver.findElement(webdriver.By.id('signup-pwd1')),
pwd2: driver.findElement(webdriver.By.id('signup-pwd2')),
set: driver.findElement(webdriver.By.id('signup-button'))
};
setUpPage = setUpWebapp.getSetUpView();
return setUpPage;
});
it('should show the signup screen by default', function() {
return setUpPage.isSetUpView();
});
it('should have the rights fields', function() {
var types = {
pwd1: 'password',
pwd2: 'password',
set: 'submit'
};
var promises = Object.keys(elements).map(function(key) {
return elements[key].getAttribute('type')
.then(function(value) {
assert.equal(value, types[key]);
});
});
return Promise.all(promises);
});
it('should reject non-matching passwords', function() {
return setUpPage.failureLogin(12345678, 1234)
.then(text => { assert.equal(text, errorPasswordDoNotMatch); })
.then(() => setUpPage.dismissAlert());
});
it('should reject short passwords', function () {
return setUpPage.failureLogin(1234, 1234)
.then(text => { assert.equal(text, shortPasswordErrorMessage); })
.then(() => setUpPage.dismissAlert());
});
it('should fail if password is not set', function() {
return setUpPage.failureLogin('', '')
.then(text => { assert.equal(text, shortPasswordErrorMessage); })
.then(() => setUpPage.dismissAlert());
});
it('should accept matching, long-enough passwords', function() {
return setUpPage.successLogin()
.then(successfulPageView => successfulPageView.loginMessage)
.then(text => { assert.equal(text, 'Thank you!'); });
});
});
});
describe('signedin page', function() {
var elements;
var screens;
before(function() {
driver.navigate().refresh();
});
beforeEach(function() {
return driver.wait(webdriver.until.titleIs('FoxBox'), 5000).then(
function() {
screens = {
signin: driver.findElement(webdriver.By.id('signin')),
signedin: driver.findElement(webdriver.By.id('signedin'))
};
elements = {
signoutButton: driver.findElement(webdriver.By.id('signout-button'))
};
});
});
it('should show the signedin screen', function() {
return driver.wait(webdriver.until.elementIsVisible(screens.signedin),
3000);
});
it('should not show the signin screen', function(done) {
screens.signin.isDisplayed().then(function(visible) {
assert.equal(visible, false);
done();
});
});
it('should show signin screen after signing out', function() {
return elements.signoutButton.click().then(function() {
return driver.wait(webdriver.until.elementIsVisible(screens.signin),
5000);
});
});
});
describe('signin page', function() {
var elements;
var screens;
before(function() {
driver.navigate().refresh();
});
beforeEach(function() {
return driver.wait(webdriver.until.titleIs('FoxBox'), 5000).then(
function() {
screens = {
signin: driver.findElement(webdriver.By.id('signin')),
signedin: driver.findElement(webdriver.By.id('signedin'))
};
elements = {
signinPwd: driver.findElement(webdriver.By.id('signin-pwd')),
signinButton: driver.findElement(webdriver.By.id('signin-button'))
};
});
});
it('should show the signin screen', function() {
return driver.wait(webdriver.until.elementIsVisible(screens.signin),
3000);
});
it('should not show the signedIn screen', function(done) {
screens.signedin.isDisplayed().then(function(visible) {
assert.equal(visible, false);
done();
});
});
[{
test: 'should reject short passwords',
pass: 'short',
error: 'Invalid password'
}, {
test: 'should reject not matching passwords',
pass: 'longEnoughButInvalid',
error: 'Signin error Unauthorized'
}].forEach(function(config) {
it(config.test, function () {
return elements.signinPwd.sendKeys(config.pass).then(function() {
return elements.signinButton.click();
}).then(function() {
return driver.wait(webdriver.until.alertIsPresent(), 5000);
}).then(function() {
return driver.switchTo().alert();
}).then(function(alert) {
return alert.getText().then(function(text) {
assert.equal(text, config.error);
}).then(function() {
alert.dismiss();
});
});
});
});
it('should fail if password is not typed', function() {
return elements.signinButton.click().then(function() {
return driver.wait(webdriver.until.alertIsPresent(), 5000);
}).then(function() {
return driver.switchTo().alert();
}).then(function(alert) {
return alert.getText().then(function(text) {
assert.equal(text,
'Invalid password');
}).then(function() {
alert.dismiss();
});
});
});
it('should accept matching, long-enough passwords', function () {
return elements.signinPwd.sendKeys('12345678').then(function() {
return elements.signinButton.click();
}).then(function() {
return driver.wait(webdriver.until.elementIsVisible(screens.signedin),
5000);
});
});
describe('tests changing views', function(){
before(function() {
driver.navigate().refresh();
});
beforeEach(function(){
return driver.wait(webdriver.until.titleIs('FoxBox'), 5000).then(
function() {
return setUpWebapp.getSignInPage();
}).then(function(signedInPageView) {
signedInPage = signedInPageView;
});
});
it('should go to sign out page' , function() {
return signedInPage.signOut();
});
});
});
});
});
| fabricedesre/foxbox | test/selenium/sessions_ui_test.js | JavaScript | mpl-2.0 | 7,396 |
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
gTestfile = 'number-001.js';
/**
* The Java language allows static methods to be invoked using either the
* class name or a reference to an instance of the class, but previous
* versions of liveocnnect only allowed the former.
*
* Verify that we can call static methods and get the value of static fields
* from an instance reference.
*
* author: christine@netscape.com
*
* date: 12/9/1998
*
*/
var SECTION = "Call static methods from an instance";
var VERSION = "1_4";
var TITLE = "LiveConnect 3.0 " +
SECTION;
startTest();
var DT = Packages.com.netscape.javascript.qa.liveconnect.DataTypeClass;
var dt = new DT();
var a = new Array;
var i = 0;
a[i++] = new TestObject(
"dt.staticSetByte( 99 )",
"dt.PUB_STATIC_BYTE",
"dt.staticGetByte()",
"typeof dt.staticGetByte()",
99,
"number" );
a[i++] = new TestObject(
"dt.staticSetChar( 45678 )",
"dt.PUB_STATIC_CHAR",
"dt.staticGetChar()",
"typeof dt.staticGetChar()",
45678,
"number" );
a[i++] = new TestObject(
"dt.staticSetShort( 32109 )",
"dt.PUB_STATIC_SHORT",
"dt.staticGetShort()",
"typeof dt.staticGetShort()",
32109,
"number" );
a[i++] = new TestObject(
"dt.staticSetInteger( 2109876543 )",
"dt.PUB_STATIC_INT",
"dt.staticGetInteger()",
"typeof dt.staticGetInteger()",
2109876543,
"number" );
a[i++] = new TestObject(
"dt.staticSetLong( 9012345678901234567 )",
"dt.PUB_STATIC_LONG",
"dt.staticGetLong()",
"typeof dt.staticGetLong()",
9012345678901234567,
"number" );
a[i++] = new TestObject(
"dt.staticSetDouble( java.lang.Double.MIN_VALUE )",
"dt.PUB_STATIC_DOUBLE",
"dt.staticGetDouble()",
"typeof dt.staticGetDouble()",
java.lang.Double.MIN_VALUE,
"number" );
a[i++] = new TestObject(
"dt.staticSetFloat( java.lang.Float.MIN_VALUE )",
"dt.PUB_STATIC_FLOAT",
"dt.staticGetFloat()",
"typeof dt.staticGetFloat()",
java.lang.Float.MIN_VALUE,
"number" );
for ( i = 0; i < a.length; i++ ) {
new TestCase(
a[i].description +"; "+ a[i].javaFieldName,
a[i].jsValue,
a[i].javaFieldValue );
new TestCase(
a[i].description +"; " + a[i].javaMethodName,
a[i].jsValue,
a[i].javaMethodValue );
new TestCase(
a[i].javaTypeName,
a[i].jsType,
a[i].javaTypeValue );
}
test();
function TestObject( description, javaField, javaMethod, javaType,
jsValue, jsType )
{
eval (description );
this.description = description;
this.javaFieldName = javaField;
this.javaFieldValue = eval( javaField );
this.javaMethodName = javaMethod;
this.javaMethodValue = eval( javaMethod );
this.javaTypeName = javaType,
this.javaTypeValue = eval( javaType );
this.jsValue = jsValue;
this.jsType = jsType;
}
| mozilla/rhino | testsrc/tests/lc3/CallStatic/number-001.js | JavaScript | mpl-2.0 | 3,017 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
const mapValuesByKeys = require('../lib/functional').mapValuesByKeys
const _ = null
const messages = {
// URL bar shortcuts
SHORTCUT_FOCUS_URL: _,
// Active frame shortcuts
SHORTCUT_ACTIVE_FRAME_STOP: _,
SHORTCUT_ACTIVE_FRAME_RELOAD: _,
SHORTCUT_ACTIVE_FRAME_CLEAN_RELOAD: _,
SHORTCUT_ACTIVE_FRAME_CLONE: _,
SHORTCUT_ACTIVE_FRAME_ZOOM_IN: _,
SHORTCUT_ACTIVE_FRAME_ZOOM_OUT: _,
SHORTCUT_ACTIVE_FRAME_ZOOM_RESET: _,
SHORTCUT_ACTIVE_FRAME_TOGGLE_DEV_TOOLS: _,
SHORTCUT_SET_ACTIVE_FRAME_BY_INDEX: _, /** @arg {number} index of frame */
SHORTCUT_ACTIVE_FRAME_VIEW_SOURCE: _,
SHORTCUT_SET_ACTIVE_FRAME_TO_LAST: _,
SHORTCUT_ACTIVE_FRAME_SAVE: _,
SHORTCUT_ACTIVE_FRAME_PRINT: _,
SHORTCUT_ACTIVE_FRAME_SHOW_FINDBAR: _,
SHORTCUT_ACTIVE_FRAME_BACK: _,
SHORTCUT_ACTIVE_FRAME_FORWARD: _,
SHORTCUT_ACTIVE_FRAME_BOOKMARK: _,
SHORTCUT_ACTIVE_FRAME_REMOVE_BOOKMARK: _,
SHORTCUT_ACTIVE_FRAME_LOAD_URL: _, /** @arg {string} url to load */
SHORTCUT_ACTIVE_FRAME_COPY: _,
SHORTCUT_ACTIVE_FRAME_FIND_NEXT: _,
SHORTCUT_ACTIVE_FRAME_FIND_PREV: _,
// Frame management shortcuts
SHORTCUT_NEW_FRAME: _, /** @arg {string} opt_url to load if any */
SHORTCUT_CLOSE_FRAME: _, /** @arg {number} opt_key of frame, defaults to active frame */
SHORTCUT_CLOSE_OTHER_FRAMES: _, /** @arg {boolean} close to the right, @arg {boolean} close to the left */
SHORTCUT_UNDO_CLOSED_FRAME: _,
SHORTCUT_FRAME_MUTE: _,
SHORTCUT_FRAME_RELOAD: _, /** @arg {number} key of frame */
SHORTCUT_FRAME_CLONE: _, /** @arg {number} key of frame, @arg {object} options such as openInForeground */
SHORTCUT_NEXT_TAB: _,
SHORTCUT_PREV_TAB: _,
SHORTCUT_OPEN_CLEAR_BROWSING_DATA_PANEL: _,
// Misc application events
QUIT_APPLICATION: _,
OPEN_BRAVERY_PANEL: _,
PREFS_RESTART: _,
CERT_ERROR: _, /** @arg {Object} details of certificate error */
NOTIFICATION_RESPONSE: _, /** @arg {string} message, @arg {number} buttonId, @arg {boolean} persist */
// Downloads
SHOW_DOWNLOADS_TOOLBAR: _, /** Ensures the downloads toolbar is visible */
HIDE_DOWNLOADS_TOOLBAR: _, /** Hides the downloads toolbar */
DOWNLOAD_ACTION: _, /** @arg {string} downloadId, @arg {string} action such as 'resume', 'pause', or 'cancel' */
// Updates
UPDATE_REQUESTED: _,
UPDATE_AVAILABLE: _,
UPDATE_NOT_AVAILABLE: _,
CHECK_FOR_UPDATE: _,
SHOW_ABOUT: _,
UPDATE_META_DATA_RETRIEVED: _,
// App state
APP_INITIALIZED: _,
// Web contents state
// Webview page messages
CONTEXT_MENU_OPENED: _, /** @arg {Object} nodeProps properties of node being clicked */
APP_STATE_CHANGE: _,
STOP_LOAD: _,
THEME_COLOR_COMPUTED: _,
HIDE_CONTEXT_MENU: _,
LEAVE_FULL_SCREEN: _,
ENTER_FULL_SCREEN: _,
SET_CLIPBOARD: _,
GOT_CANVAS_FINGERPRINTING: _,
GO_BACK: _,
GO_FORWARD: _,
RELOAD: _,
CAN_SWIPE_BACK: _,
CAN_SWIPE_FORWARD: _,
CHECK_SWIPE_BACK: _,
CHECK_SWIPE_FORWARD: _,
ENABLE_SWIPE_GESTURE: _,
DISABLE_SWIPE_GESTURE: _,
SHOW_FLASH_NOTIFICATION: _,
// Password manager
GET_PASSWORDS: _, /** @arg {string} formOrigin, @arg {string} action */
GOT_PASSWORD: _, /** @arg {string} username, @arg {string} password, @arg {string} origin, @arg {string} action, @arg {boolean} isUnique */
SAVE_PASSWORD: _, /** @arg {string} username, @arg {string} password, @arg {string} formOrigin, @arg {string} action */
IS_MISSPELLED: _, /** @arg {string} word, the word to check */
GET_MISSPELLING_INFO: _, /** @arg {string} word, the word to lookup */
SHOW_USERNAME_LIST: _, /** @arg {string} formOrigin, @arg {string} action, @arg {Object} boundingRect, @arg {string} usernameValue */
FILL_PASSWORD: _, /** @arg {string} username, @arg {string} password, @arg {string} origin, @arg {string} action */
PASSWORD_DETAILS_UPDATED: _, /** @arg {Object} passwords app state */
PASSWORD_SITE_DETAILS_UPDATED: _, /** @arg {Object} passwords app state */
DECRYPT_PASSWORD: _, /** @arg {string} encrypted pw, @arg {string} iv, @arg {string} authTag, @arg {number} id */
DECRYPTED_PASSWORD: _, /** @arg {number} decrypted pw, @arg {number} id */
// Init
INITIALIZE_WINDOW: _,
INITIALIZE_PARTITION: _, /** @arg {string} name of partition */
// Session restore
REQUEST_WINDOW_STATE: _,
RESPONSE_WINDOW_STATE: _,
LAST_WINDOW_STATE: _,
UNDO_CLOSED_WINDOW: _,
CLEAR_CLOSED_FRAMES: _,
// Ad block, safebrowsing, and tracking protection
BLOCKED_RESOURCE: _,
BLOCKED_PAGE: _,
// About pages to contentScripts
SETTINGS_UPDATED: _,
SITE_SETTINGS_UPDATED: _,
BRAVERY_DEFAULTS_UPDATED: _,
BOOKMARKS_UPDATED: _,
HISTORY_UPDATED: _,
EXTENSIONS_UPDATED: _,
ADBLOCK_UPDATED: _,
DOWNLOADS_UPDATED: _,
FLASH_UPDATED: _,
// About pages from contentScript
OPEN_DOWNLOAD_PATH: _,
RELOAD_URL: _,
DISPATCH_ACTION: _,
CHECK_FLASH_INSTALLED: _,
ABOUT_COMPONENT_INITIALIZED: _,
CLEAR_BROWSING_DATA_NOW: _,
// Autofill
AUTOFILL_ADDRESSES_UPDATED: _,
AUTOFILL_CREDIT_CARDS_UPDATED: _,
// HTTPS
CERT_ERROR_ACCEPTED: _, /** @arg {string} url where a cert error was accepted */
CHECK_CERT_ERROR_ACCEPTED: _, /** @arg {string} url to check cert error, @arg {number} key of frame */
GET_CERT_ERROR_DETAIL: _,
SET_CERT_ERROR_DETAIL: _,
SET_SECURITY_STATE: _, /** @arg {number} key of frame, @arg {Object} security state */
HTTPSE_RULE_APPLIED: _, /** @arg {string} name of ruleset file, @arg {Object} details of rewritten request */
// Bookmarks
IMPORT_BOOKMARKS: _,
// Extensions
NEW_POPUP_WINDOW: _,
// NoScript
TEMPORARY_ALLOW_SCRIPTS: _, /** @arg {string} origin to allow scripts on */
// Localization
LANGUAGE: _, /** @arg {string} langCode, @arg {Array} availableLanguages */
REQUEST_LANGUAGE: _,
STATE_UPDATED: _,
// Ads
GET_AD_DIV_CANDIDATES: _,
SET_AD_DIV_CANDIDATES: _,
// Debugging
DEBUG_REACT_PROFILE: _,
// Ledger
LEDGER_PUBLISHER: _,
LEDGER_UPDATED: _,
LEDGER_CREATE_WALLET: _,
CHECK_BITCOIN_HANDLER: _,
ADD_FUNDS_CLOSED: _
}
module.exports = mapValuesByKeys(messages)
| MKuenzi/browser-laptop | js/constants/messages.js | JavaScript | mpl-2.0 | 6,213 |
/* !Javascript */
var remote = require('remote'),
remoteIpc = remote.require('ipc');
angular
.module('MainView', ['Utils'])
.controller('MainCtrl', ['Storage', '$scope', function(Storage, scope) {
var vm = this;
vm.keychain = null;
Storage
.init()
.then(function(db) {
vm.keychain = db.getDocs();
remoteIpc.on('update-main-view', function() {
Storage
.reload()
.then(function() {
vm.keychain = db.getDocs();
});
});
});
}]);
| zeusintuivo/electron-password-saver | src/windows/main/main.view.js | JavaScript | mpl-2.0 | 673 |
/**
* Created by sunil on 1/1/2015.
*/
function getElementByXpath (path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
function closeTab() {
self.port.emit('closeTab');
}
function generateIdFromText(text) {
return text.replace(/[^\w]/gi, '');
} | sunilrebel/spann-jira | data/js/commons.js | JavaScript | mpl-2.0 | 326 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { stripIndent } from 'common-tags';
// This module is mocked.
import copy from 'copy-to-clipboard';
import { MarkerTable } from '../../components/marker-table';
import { MaybeMarkerContextMenu } from '../../components/shared/MarkerContextMenu';
import {
updatePreviewSelection,
changeMarkersSearchString,
} from '../../actions/profile-view';
import { ensureExists } from '../../utils/flow';
import { getEmptyThread } from 'firefox-profiler/profile-logic/data-structures';
import { storeWithProfile } from '../fixtures/stores';
import {
getProfileFromTextSamples,
getMarkerTableProfile,
addMarkersToThreadWithCorrespondingSamples,
} from '../fixtures/profiles/processed-profile';
import {
getBoundingBox,
fireFullClick,
fireFullContextMenu,
} from '../fixtures/utils';
import type { CauseBacktrace } from 'firefox-profiler/types';
describe('MarkerTable', function() {
function setup(profile = getMarkerTableProfile()) {
// Set an arbitrary size that will not kick in any virtualization behavior.
jest
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(() => getBoundingBox(2000, 1000));
const store = storeWithProfile(profile);
const renderResult = render(
<Provider store={store}>
<>
<MaybeMarkerContextMenu />
<MarkerTable />
</>
</Provider>
);
const { container, getByText } = renderResult;
const fixedRows = () =>
Array.from(container.querySelectorAll('.treeViewRowFixedColumns'));
const scrolledRows = () =>
Array.from(container.querySelectorAll('.treeViewRowScrolledColumns'));
const getRowElement = functionName =>
ensureExists(
getByText(functionName).closest('.treeViewRow'),
`Couldn't find the row for node ${String(functionName)}.`
);
const getContextMenu = () =>
ensureExists(
container.querySelector('.react-contextmenu'),
`Couldn't find the context menu.`
);
return {
...renderResult,
...store,
fixedRows,
scrolledRows,
getRowElement,
getContextMenu,
};
}
it('renders some basic markers and updates when needed', () => {
const { container, fixedRows, scrolledRows, dispatch } = setup();
expect(fixedRows()).toHaveLength(7);
expect(scrolledRows()).toHaveLength(7);
expect(container.firstChild).toMatchSnapshot();
/* Check that the table updates properly despite the memoisation. */
dispatch(
updatePreviewSelection({
hasSelection: true,
isModifying: false,
selectionStart: 10,
selectionEnd: 20,
})
);
expect(fixedRows()).toHaveLength(2);
expect(scrolledRows()).toHaveLength(2);
});
it('selects a row when left clicking', () => {
const { getByText, getRowElement } = setup();
fireFullClick(getByText(/setTimeout/));
expect(getRowElement(/setTimeout/)).toHaveClass('isSelected');
fireFullClick(getByText('foobar'));
expect(getRowElement(/setTimeout/)).not.toHaveClass('isSelected');
expect(getRowElement('foobar')).toHaveClass('isSelected');
});
it('displays a context menu when right clicking', () => {
jest.useFakeTimers();
const { getContextMenu, getRowElement, getByText } = setup();
function checkMenuIsDisplayedForNode(str) {
expect(getContextMenu()).toHaveClass('react-contextmenu--visible');
// Note that selecting a menu item will close the menu.
fireFullClick(getByText('Copy description'));
expect(copy).toHaveBeenLastCalledWith(expect.stringMatching(str));
}
fireFullContextMenu(getByText(/setTimeout/));
checkMenuIsDisplayedForNode(/setTimeout/);
expect(getRowElement(/setTimeout/)).toHaveClass('isRightClicked');
// Wait that all timers are done before trying again.
jest.runAllTimers();
// Now try it again by right clicking 2 nodes in sequence.
fireFullContextMenu(getByText(/setTimeout/));
fireFullContextMenu(getByText('foobar'));
checkMenuIsDisplayedForNode('foobar');
expect(getRowElement(/setTimeout/)).not.toHaveClass('isRightClicked');
expect(getRowElement('foobar')).toHaveClass('isRightClicked');
// Wait that all timers are done before trying again.
jest.runAllTimers();
// And now let's do it again, but this time waiting for timers before
// clicking, because the timer can impact the menu being displayed.
fireFullContextMenu(getByText('NotifyDidPaint'));
fireFullContextMenu(getByText('foobar'));
jest.runAllTimers();
checkMenuIsDisplayedForNode('foobar');
expect(getRowElement('foobar')).toHaveClass('isRightClicked');
});
it("can copy a marker's cause using the context menu", () => {
jest.useFakeTimers();
// This is a tid we'll reuse later.
const tid = 4444;
// Just a simple profile with 1 thread and a nice stack.
const {
profile,
funcNamesDictPerThread: [{ E }],
} = getProfileFromTextSamples(`
A[lib:libxul.so]
B[lib:libxul.so]
C[lib:libxul.so]
D[lib:libxul.so]
E[lib:libxul.so]
`);
profile.threads[0].name = 'Main Thread';
// Add another thread with a known tid that we'll reuse in the marker's cause.
profile.threads.push(getEmptyThread({ name: 'Another Thread', tid }));
// Add the reflow marker to the first thread.
addMarkersToThreadWithCorrespondingSamples(profile.threads[0], [
getReflowMarker(3, 100, {
tid: tid,
// We're cheating a bit here: E is a funcIndex, but because of how
// getProfileFromTextSamples works internally, this will be the right
// stackIndex too.
stack: E,
time: 1,
}),
]);
const { getByText } = setup(profile);
fireFullContextMenu(getByText(/Reflow/));
fireFullClick(getByText('Copy call stack'));
expect(copy).toHaveBeenLastCalledWith(stripIndent`
A [libxul.so]
B [libxul.so]
C [libxul.so]
D [libxul.so]
E [libxul.so]
`);
});
describe('EmptyReasons', () => {
it('shows reasons when a profile has no non-network markers', () => {
const { profile } = getProfileFromTextSamples('A'); // Just a simple profile without any marker.
const { container } = setup(profile);
expect(container.querySelector('.EmptyReasons')).toMatchSnapshot();
});
it('shows reasons when all non-network markers have been filtered out', function() {
const { dispatch, container } = setup();
dispatch(changeMarkersSearchString('MATCH_NOTHING'));
expect(container.querySelector('.EmptyReasons')).toMatchSnapshot();
});
});
});
function getReflowMarker(
startTime: number,
endTime: number,
cause?: CauseBacktrace
) {
return [
'Reflow',
startTime,
endTime,
{
type: 'tracing',
category: 'Paint',
cause,
},
];
}
| devtools-html/perf.html | src/test/components/MarkerTable.test.js | JavaScript | mpl-2.0 | 7,236 |
(function(){
'use strict';
angular
.module('PLMApp', ['ngAnimate', 'ngSanitize', 'gettext', 'ngCookies', 'ui.router', 'ui.codemirror', 'angular-locker', 'satellizer']);
})(); | BenjaminThirion/webPLM | public/app/app.js | JavaScript | agpl-3.0 | 180 |
import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { hydrateStore } from '../actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import PublicTimeline from '../features/standalone/public_timeline';
import UnionTimeline from '../features/standalone/union_timeline';
import HashtagTimeline from '../features/standalone/hashtag_timeline';
import ModalContainer from '../features/ui/containers/modal_container';
import initialState from '../initial_state';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
const store = configureStore();
if (initialState) {
store.dispatch(hydrateStore(initialState));
}
export default class TimelineContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
hashtag: PropTypes.string,
local: PropTypes.bool,
union: PropTypes.bool,
};
static defaultProps = {
local: !initialState.settings.known_fediverse,
union: initialState.settings.known_union,
};
render () {
const { locale, hashtag, local, union } = this.props;
let timeline;
if (hashtag) {
timeline = <HashtagTimeline hashtag={hashtag} />;
} else if (union) {
timeline = <UnionTimeline />;
} else {
timeline = <PublicTimeline local={local} />;
}
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<Fragment>
{timeline}
{ReactDOM.createPortal(
<ModalContainer />,
document.getElementById('modal-container'),
)}
</Fragment>
</Provider>
</IntlProvider>
);
}
}
| pso2club/mastodon | app/javascript/mastodon/containers/timeline_container.js | JavaScript | agpl-3.0 | 1,874 |
OC.L10N.register(
"drawio",
{
"Open in Draw.io" : "Abrir no Draw.io",
"Saving..." : "Salvando...",
"File saved!" : "Arquivo Salvo!",
"Draw.io URL" : "URL do Draw.io",
"Language" : "Idioma",
"Loading, please wait." : "Carregando, por favor aguarde.",
"File created" : "Arquivo criado",
"Diagram" : "Diagrama",
"New Diagram" : "Novo diagrama",
"Yes" : "Sim",
"No" : "Nรฃo",
"Associate XML files with Draw.io?" : "Associar arquivos XML com o Draw.io?",
"Kennedy" : "Kennedy",
"Minimal" : "Minimal",
"Atlas" : "Atlas",
"Dark" : "Dark",
"Theme:" : "Tema",
"auto or en,fr,de,es,ru,pl,zh,jp..." : "auto ou pt-br,en,fr,de,es,etc...",
"Save" : "Salvar",
"Error when trying to connect" : "Erro ao tentar conectar",
"Settings have been successfully saved" : "Configuraรงรตes salvas com sucesso",
"The required folder was not found" : "A pasta requerida nรฃo foi encontrada",
"You don't have enough permission to create file" : "Vocรช nรฃo tem permissรตes suficientes para criar o arquivo",
"Template not found" : "Modelo nรฃo encontrado",
"Can't create file" : "Nรฃo foi possรญvel criar o arquivo",
"File not found" : "Arquivo nรฃo encontrado",
"Draw.io app not configured! Please contact admin." : "O aplicativo Draw.io nรฃo estรก configurado! Favor contatar o administrador.",
"Format do not supported" : "Formato nรฃo suportado",
"The file has changed since opening" : "O arquivo foi modificado desde que foi aberto",
"User does not have permissions to write to the file:" : "Usuรกrio nรฃo tem permissรฃo para gravar o arquivo:",
"FileId is empty" : "FileId (ID do arquivo) estรก vazio",
"New Diagram.xml" : "Novo Diagrama.xml",
"You do not have enough permissions to view the file" : "Vocรช nรฃo tem permissรตes suficientes para ver o arquivo"
},
"nplurals=2; plural=(n != 1);");
| pawelrojek/nextcloud-drawio | drawio/l10n/pt_BR.js | JavaScript | agpl-3.0 | 1,839 |
function load_input_code_multiple_languages(submissionid, key, input) {
load_input_code(submissionid, key, input);
setDropDownWithTheRightLanguage(key, input[key + "/language"]);
changeSubmissionLanguage(key);
}
function onChangeLanguageDropdown(key, problem) {
changeSubmissionLanguage(key, problem);
}
function setDropDownWithTheRightLanguage(key, language) {
const dropDown = document.getElementById(key + '/language');
dropDown.value = language;
}
function changeSubmissionLanguage(key, problem_type) {
if (problem_type === 'code_file_multiple_languages') return;
const language = getLanguageForProblemId(key);
const mode = CodeMirror.findModeByName(language);
const editor = codeEditors[key];
const lintingOptions = {
async: true,
lintOnChange: getAutomaticLinterOption()
};
//This should be first because setOption("mode", ...) triggers callbacks that call the linter
editor.setOption("inginiousLanguage", getInginiousLanguageForProblemId(key));
editor.setOption("mode", mode.mime);
editor.setOption("gutters", ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"]);
editor.setOption("lint", lintingOptions);
CodeMirror.autoLoadMode(editor, mode["mode"]);
}
function getLanguageForProblemId(key) {
return convertInginiousLanguageToCodemirror(getInginiousLanguageForProblemId(key));
}
function getInginiousLanguageForProblemId(key) {
const dropDown = document.getElementById(key + '/language');
if (dropDown == null)
return "plain";
return dropDown.options[dropDown.selectedIndex].value;
}
function convertInginiousLanguageToCodemirror(inginiousLanguage) {
const languages = {
"java7": "java",
"java8": "java",
"cpp": "cpp",
"cpp11": "cpp",
"c": "c",
"c11": "c",
"python3": "python",
"vhdl": "vhdl",
"verilog": "verilog"
};
return languages[inginiousLanguage];
}
function studio_init_template_code_multiple_languages(well, pid, problem) {
if ("type" in problem)
$('#type-' + pid, well).val(problem["type"]);
if ("optional" in problem && problem["optional"])
$('#optional-' + pid, well).attr('checked', true);
if ("languages" in problem) {
jQuery.each(problem["languages"], function (language, allowed) {
if (allowed)
$("#" + language + "-" + pid, well).attr("checked", true);
});
}
}
function studio_init_template_notebook_file(well, pid, problem) {
if ("type" in problem)
$('#type-' + pid, well).val(problem["type"]);
}
function load_input_notebook_file(submissionid, key, input) {
load_input_file(submissionid, key, input);
const url = $('form#task').attr("action") + "?submissionid=" + submissionid + "&questionid=" + key;
$.ajax({
url: url,
method: "GET",
dataType: 'json',
success: function (data) {
render_notebook(data, $("#notebook-holder"))
}
});
highlight_code();
}
function studio_init_template_code_file_multiple_languages(well, pid, problem) {
if ("max_size" in problem)
$('#maxsize-' + pid, well).val(problem["max_size"]);
if ("allowed_exts" in problem)
$('#extensions-' + pid, well).val(problem["allowed_exts"].join());
if ("languages" in problem) {
jQuery.each(problem["languages"], function (language, allowed) {
if (allowed)
$("#" + language + "-" + pid, well).attr("checked", true);
});
}
}
function load_input_code_file_multiple_languages(submissionid, key, input) {
load_input_file(submissionid, key, input);
setDropDownWithTheRightLanguage(key, input[key + "/language"]);
}
let selected_all_languages = false;
function toggle_languages_checkboxes() {
const environmentSelectElement = $("#environment");
const problemId = getProblemIdEdit();
selected_all_languages = !selected_all_languages;
$(".checkbox_language").prop("checked", selected_all_languages);
let text_button = "Select all";
if (selected_all_languages) text_button = "Unselect All";
$("#toggle_select_languages_button").text(text_button);
if (!environmentSelectElement.length) return;
if (environmentSelectElement.val() === "HDL") {
$(".checkbox_language").prop("checked", false);
$(`#vhdl-${problemId}`).prop('checked', selected_all_languages);
$(`#verilog-${problemId}`).prop('checked', selected_all_languages);
} else if (environmentSelectElement.val() === "Data Science") {
$(".checkbox_language").prop("checked", false);
$(`#python3-${problemId}`).prop('checked', selected_all_languages);
} else {
$(`#vhdl-${problemId}`).prop('checked', false);
$(`#verilog-${problemId}`).prop('checked', false);
}
}
/**
* Monkey patch `studio_subproblem_delete` to detect when a subproblem is deleted, that way
* the options to create a new subproblem are displayed.
*/
const original_studio_subproblem_delete = this.studio_subproblem_delete;
this.studio_subproblem_delete = (pid) => {
original_studio_subproblem_delete(pid);
toggle_display_new_subproblem_option();
showCorrectLanguagesEnvironment();
};
/**
* Monkey patch `studio_create_new_subproblem` to detect when a subproblem is created, that way
* the options to create a new subproblem are hidden.
*/
const original_studio_create_new_subproblem = this.studio_create_new_subproblem;
this.studio_create_new_subproblem = () => {
original_studio_create_new_subproblem();
toggle_display_new_subproblem_option();
};
function toggle_display_new_subproblem_option() {
const container = $("#accordion");
const new_subproblem_element = $("#new_subproblem");
if (container.children().length) new_subproblem_element.hide();
else new_subproblem_element.show();
}
const render_notebook = function (ipynb, notebook_holder_element) {
const notebook_holder = notebook_holder_element[0];
notebook_holder_element.hide();
const notebook = this.notebook = nb.parse(ipynb);
while (notebook_holder.hasChildNodes()) {
notebook_holder.removeChild(notebook_holder.lastChild);
}
notebook_holder.appendChild(notebook.render());
highlight_code();
notebook_holder_element.show();
};
function notebook_start_renderer() {
const notebook_holder_html = '<div class="DivToScroll DivWithScroll" id="notebook-holder" hidden></div>'
let taskAlert = $("#task_alert");
taskAlert.after(notebook_holder_html);
const load_file = function (file) {
const reader = new FileReader();
reader.onload = function (e) {
const parsed = JSON.parse(this.result);
render_notebook(parsed, $("#notebook-holder"));
};
reader.readAsText(file);
};
try {
// Handle exception when getProblemId does not exists
const file_input = $("input[name=" + getProblemId() + "]")[0];
file_input.onchange = function (e) {
const file = this.files[0];
if (file === undefined || file.name.split('.')[1] !== 'ipynb') {
$("#notebook-holder").html("");
$("#notebook-holder").hide();
return;
}
load_file(file);
};
file_input.onclick = function () {
this.value = null;
$("#notebook-holder").html("");
$("#notebook-holder").hide();
};
} catch (e) {
}
}
function sendSubmissionAnalytics() {
$('#task-submit').on('click', function () {
if (loadingSomething)
return;
if (!taskFormValid())
return;
// The button related to late submissions has the attribute `late-submission`. In case it is a late
// submission, modify the key and name for the service adding at the end `late`.
const lateSubmission = $(this).attr("late-submission");
let lateSubmissionData = {key: "", name: ""};
if (typeof lateSubmission !== "undefined" && lateSubmission !== false) {
lateSubmissionData["key"] = "_late";
lateSubmissionData["name"] = " - Late";
}
const environments = new Set(['multiple_languages', 'Data Science', 'Notebook', 'HDL']);
if (!environments.has(getTaskEnvironment()))
return;
const services = {
'Notebook_notebook_file': [`${getTaskEnvironment()}_submission`, `${getTaskEnvironment()} submission`],
'multiple_languages_code_multiple_languages': [`multiple_languages_code_multiple_languages`, `Multiple languages - Code submission`],
'multiple_languages_code_file_multiple_languages': [`multiple_languages_code_file_multiple_languages`, `Multiple languages - File submission`],
'Data Science_code_multiple_languages': [`data_science_code_multiple_languages`, `Data Science - Code submission`],
'Data Science_code_file_multiple_languages': [`data_science_code_file_multiple_languages`, `Data Science - File submission`],
'HDL_code_multiple_languages': [`HDL_code_multiple_languages`, `HDL - Code submission`],
'HDL_code_file_multiple_languages': [`HDL_code_file_multiple_languages`, `HDL - File submission`],
};
let url = '/api/analytics/';
//Verify if is a lti task, and set the actual session id from task page (Do that for all analytics calls in task view)
if(is_lti()){
url = '/' + ($("form#task").attr("action").split('/')[1]) + url;
}
$.post(url, {
service: {
key: services[`${getTaskEnvironment()}_${getProblemType()}`][0] + lateSubmissionData["key"],
name: services[`${getTaskEnvironment()}_${getProblemType()}`][1] + lateSubmissionData["name"]
}, course_id: getCourseId(),
});
});
}
function highlight_code() {
Prism.highlightAll();
}
// These functions are intended to show the correct languages for multilang when the environment is HDL
// or multilang.
function getProblemIdEdit() {
const problemId = $("#problem_id")[0];
if (!problemId) return;
return problemId.value;
}
function hideLanguages() {
const problemId = getProblemIdEdit();
$(`.checkbox_language_${problemId}`).prop("hidden", true);
}
function showLanguages() {
const problemId = getProblemIdEdit();
$(`.checkbox_language_${problemId}`).prop("hidden", false);
}
function showCorrectLanguagesEnvironment(uncheckBoxes = true) {
const problemId = getProblemIdEdit();
const environmentSelectElement = $("#environment");
if (!environmentSelectElement.length) return;
if (uncheckBoxes) $(".checkbox_language").prop("checked", false);
if (environmentSelectElement.val() === "HDL") {
hideLanguages();
$(`.checkbox_${problemId}_vhdl`).prop('hidden', false);
$(`.checkbox_${problemId}_verilog`).prop('hidden', false);
} else if (environmentSelectElement.val() === "Data Science") {
hideLanguages();
$(`.checkbox_${problemId}_python3`).prop('hidden', false);
} else {
showLanguages();
$(`.checkbox_${problemId}_vhdl`).prop('hidden', true);
$(`.checkbox_${problemId}_verilog`).prop('hidden', true);
}
}
function setupGradingEnvironmentView() {
const environmentSelectElement = $("#environment");
let environmentValue = environmentSelectElement.val();
if (environmentSelectElement.length) {
environmentSelectElement.on('change', function () {
if (taskAlreadyHasASubproblem()){
$('#change_grading_environment').modal('show');
}else{
configEnvironmentView();
}
});
}
$('#change_environment').on('click', function () {
environmentValue = environmentSelectElement.val();
deleteProblem();
configEnvironmentView();
});
$('#change_grading_environment').on('hidden.bs.modal', function(){
environmentSelectElement.val(environmentValue);
});
configEnvironmentView(false);
}
function taskAlreadyHasASubproblem(){
const subproblemContainer = $("#accordion");
const subproblemList = subproblemContainer.children();
if (subproblemList.length > 0){
return true;
}
return false;
}
function deleteProblem(){
/*
Delete the task problem as studio function, but do not show the confirm alert.
This function is used when a course admin change the grading environment for a task
that already has a subproblem.
*/
const subproblemContainerElements = $("#accordion").children();
subproblemContainerElements.remove();
toggle_display_new_subproblem_option();
}
function configEnvironmentView(uncheckBoxes = true) {
showCorrectLanguagesEnvironment(uncheckBoxes);
blockUnusedLimitInputs();
showCorrectSubProblemsTypes();
}
function blockUnusedLimitInputs() {
const selectedEnvironmentVal = $("#environment").val();
const limitsToBlockIds = ["limit-time", "limit-hard-time", "limit-memory", "limit-output"];
const environmentWhichUsesLimits = "HDL";
const isUsingLimits = selectedEnvironmentVal === environmentWhichUsesLimits;
$.each(limitsToBlockIds, (_, id) => {
$(`#${id}`).prop('readonly', !isUsingLimits);
});
}
function showCorrectSubProblemsTypes() {
const selectedEnvironmentVal = $("#environment").val();
const notebookTypeValue = ["subproblem_notebook_file"];
const multipleLangTypeValue = ["subproblem_code_multiple_languages", "subproblem_code_file_multiple_languages"];
function blockOrUnlockOptions(types, block = false) {
$.each(types, (_, type) => {
$(`#new_subproblem_type option[value=${type}]`).enable(block);
});
}
function selectOption(selection) {
$(`#new_subproblem_type option`).each(function (index, element) {
element.selected = false;
});
$(`#new_subproblem_type option[value=${selection}]`).attr("selected", true);
}
if (selectedEnvironmentVal === "Notebook") {
blockOrUnlockOptions(notebookTypeValue, true);
blockOrUnlockOptions(multipleLangTypeValue);
selectOption(notebookTypeValue[0]);
} else {
blockOrUnlockOptions(multipleLangTypeValue, true);
blockOrUnlockOptions(notebookTypeValue);
selectOption(multipleLangTypeValue[0]);
}
}
function hideRandomInputForm() {
$("#randomInputForm").hide();
$("#accessibleDivForm").css({"padding-bottom": "1rem"});
}
jQuery(document).ready(function () {
hideRandomInputForm();
setupGradingEnvironmentView();
toggle_display_new_subproblem_option();
notebook_start_renderer();
sendSubmissionAnalytics();
});
| JuezUN/INGInious | inginious/frontend/plugins/multilang/static/multilang.js | JavaScript | agpl-3.0 | 14,892 |
mercury.view = mercury.view || {};
// Object cache
mercury.c.$calendar_container = $("#calendar_container");
mercury.c.$calevent_text = $("#calevent_text");
mercury.c.$select_container = $("#cal_select_container");
mercury.c.$select_year = $("#select_year");
mercury.c.$select_tripos = $("#select_tripos");
mercury.c.$select_part = $("#select_part");
mercury.c.$select_course = $("#select_course");
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
})(jQuery);
mercury.view.cleantext = function(name,text) {
return name+text;
};
mercury.view.clear_basic = function() {
$('.head').html('');
$('#hideshowlinks').css('display','none');
};
mercury.view.load_basics = function(ids) {
var any = false;
if(ids.length) {
mercury.view.load_basic(ids[0],function(text_here) {
any |= text_here;
if(ids.length>1) {
mercury.view.load_basics(ids.splice(1));
} else {
if(any) {
$('#hideshowlinks').css('display','block');
}
}
});
}
}
mercury.view.load_basic = function(id,cont) {
$.ajax({
type: "GET",
url: mercury.config.urlDetails,
data: {
"courseid": id
},
dataType: "json",
success: function(data, textStatus, jqXHR) {
all = data.metadata.head + " " + data.metadata.foot;
if(!$.trim(all)) {
cont(false);
return;
}
name = "<b>"+data.name+":</b> ";
if (data !== null) {
$('.head').append(mercury.view.cleantext(name,all));
} else {
alert("The following data feed did not produce any data: "+mercury.config.urlDetails);
mercury.data.top = {};
}
cont(true);
},
error: function(jqXHR, textStatus, errorThrown) {
var error_msg = "Could not load data from the feed!";
ajaxError.apply(this, [null, jqXHR, $.ajaxSettings, errorThrown, error_msg]);
mercury.data.details = {};
}
});
};
mercury.view.feed_success = function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = $.fullCalendar.parseISO8601(startStr, true);
var end = $.fullCalendar.parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = $.fullCalendar.applyAll(true, this, args);
if ($.isArray(res)) {
return res;
}
return events;
};
mercury.view.colour = function(id) {
// We build indexes out of the last three digits as a number and a hash of the rest in the MSB.
// That means in typical views, where it's the last three digits that vary, we guarantee
// different colours.
var suffix = parseInt(id.substr(id.length-3),10);
var prefix = id.substr(0,id.length-3);
// Simple hash function. We need not be the CIA here in our colour choices!
var h = 0;
for(var j=0;j<prefix.length;j++) {
h = ((h * 40503) + prefix.charAt(j).charCodeAt()) % 65535;
}
h += suffix;
return mercury.config.calendarColors[h%mercury.config.calendarColors.length];
};
mercury.view.calendar_data = function(id,cont) {
$.ajax({
type: "GET",
url: mercury.config.urlCalendar,
data: {
"tripospartid": id
},
dataType: "json",
success: function(data, textStatus, jqXHR) {
if (data !== null) {
cont(true,data);
} else {
cont(false,[]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
var error_msg = "Could not load data from the feed!";
ajaxError.apply(this, [null, jqXHR, $.ajaxSettings, errorThrown, error_msg]);
cont(false,[]);
}
});
};
mercury.view.convert_id_to_path = function(id,cont) {
// XXX cache
try {
var cid = id.substr(0,14);
var reversed = mercury.data.reverse_top[cid];
mercury.view.calendar_data(cid,function(success,data) {
if(success && data !== null) {
var subj = false;
if(id.length>14)
subj = data.courses[id].name;
cont(true,[reversed[0],reversed[1],reversed[2],cid,subj],data);
} else {
cont(false,[]);
}
});
} catch(err) {
cont(false,[]);
}
};
mercury.view.dropdown_update = function($selector,source,sel_in,data_cb,sel_cb) {
if(typeof data_cb !== 'function') {
data_cb = function(data,text) { return text; };
}
if(typeof sel_cb !== 'function') {
sel_cb = function(value) { return value == sel_in; };
}
var options = {};
_.each(source, function(data, text){
var selected = sel_cb(text) ? 'selected="true"' : "";
var display = data_cb(data,text);
options[display] = '<option value="'+text+'" '+selected+'>'+display+'</option>';
});
var keys = _.keys(options);
keys.sort();
var html = '';
_.each(keys,function(x) {
html += options[x];
});
$selector.html(html);
};
mercury.view.setup_multi = function($selector,what,minwidth,min_to_summary) {
// Initialise multiselect for subjects
$selector.multiselect({
selectedText: "# of # "+what+" selected",
noneSelectedText: "Select "+what,
selectedList: min_to_summary,
minWidth: minwidth
});
};
mercury.view.multi_change = function($what,callback) {
$what.bind("multiselectclick multiselectcheckall multiselectuncheckall", function(e, ui){
callback();
});
};
mercury.view.single_change = function($what,callback) {
$what.bind("change",function(e,ui) {
callback();
});
};
mercury.view.update_hash_from_course = function() {
var selected = mercury.c.$select_course.multiselect("getChecked").map(function(){ return this.value; }).get();
if(selected.length==0) {
$.bbq.pushState({
'part': mercury.c.$select_part.val()
},2);
} else {
var courses = selected.join(',');
$.bbq.pushState({
'course': courses
},2);
}
mercury.view.recompute();
};
mercury.view.render_path = function(sel_year,sel_tripos,sel_part,courses,ids) {
mercury.view.dropdown_update(mercury.c.$select_year,mercury.data.selector,sel_year);
mercury.view.dropdown_update(mercury.c.$select_tripos,mercury.data.selector[sel_year],sel_tripos);
mercury.view.dropdown_update(mercury.c.$select_part,mercury.data.selector[sel_year][sel_tripos],sel_part,function(data,text) { return data.name; });
mercury.view.dropdown_update(mercury.c.$select_course,courses,ids,function(data,text) { return data.name; },function(val) { return _.indexOf(ids,val) !== -1; });
mercury.c.$select_course.multiselect("refresh");
};
mercury.view.choose_part = function(year,tripos) {
var data = mercury.data.selector[year][tripos];
for(var id in data)
return id;
return undefined;
};
mercury.view.update_dropdowns = function() {
// We might need to choose another part if it doesn't match our dropdowns (eg change year)
var part_sel = mercury.c.$select_part.val();
mercury.view.convert_id_to_path(part_sel,function(success,data,cal) {
if(!success)
return;
var sel_year = mercury.c.$select_year.val();
var sel_tripos = mercury.c.$select_tripos.val();
if(sel_year != data[0] || sel_tripos != data[1]) {
part_sel = mercury.view.choose_part(sel_year,sel_tripos);
}
//
$.bbq.pushState({
'part': part_sel
},2);
mercury.view.render_selectors_and_update();
});
};
mercury.view.render_selectors_and_update = function() {
var tc = mercury.view.cur_part_and_subjects();
mercury.view.setup_multi(mercury.c.$select_course,'subjects',$(window).width()/2 - 100,4);
var src = tc[0];
if(tc[1].length) {
src = tc[1][0];
}
mercury.view.convert_id_to_path(src,function(success,data,cal) {
if(!success)
return;
tc = mercury.view.cur_part_and_subjects();
mercury.view.render_path(data[0],data[1],data[3],cal.courses,tc[1]);
mercury.view.recompute();
});
};
mercury.view.cur_part_and_subjects = function() {
var hash = $.deparam.fragment();
if(hash.course) {
var courses = hash.course.split(/,/);
var tripos = courses[0].substr(0,14);
return [tripos,courses];
} else {
var tripos = hash.part;
return [tripos,[]];
}
}
mercury.view.init = function() {
var hash = $.deparam.fragment();
var right = 'month,agendaWeek,agendaDay';
var weekends = true;
if(hash.embed) {
right = '';
if(hash.nowe)
weekends = false;
$("html,body").css('overflow','auto');
}
$('#view_popup').dialog({
'autoOpen': false
});
$('#embed_popup').dialog({
'autoOpen': false,
'width': '90%'
});
$('#embed_out a').click(function() {
try {
if (self.parent.frames.length != 0) {
var here = document.location.href;
here = here.replace('embed.html','view.html');
self.parent.location=here;
}
}
catch (Exception) {}
});
$('#embed').click(function() { $('#embed_popup').dialog('open'); return false; });
// Init calendar
mercury.data.calendarInstance = mercury.c.$calendar_container.fullCalendar({
theme: false,
aspectRatio: 1.4,
firstDay: 1,
minTime: 8,
maxTime: 18,
firstHour: 8,
defaultView: 'agendaWeek',
weekends: weekends,
header: {
left: 'prev,next today',
center: 'title',
right: right
},
firstHour: 8,
allDaySlot: false,
titleFormat: {
month: 'MMMM yyyy',
week: "d MMM [ yyyy]{ '—'d MMM yyyy}",
day: 'dddd, d MMM, yyyy'
},
columnFormat: {
month: 'ddd', // Mon
week: 'ddd d/M', // Mon 9/7
day: 'dddd d/M' // Monday 9/7
},
eventClick: function(calEvent, jsEvent, view) {
$('#view_popup').dialog('open');
$('#view_details').html(calEvent.description);
return false;
},
// Callback when hovering over an element
eventMouseover: function(event, jsEvent, view) {
mercury.c.$calevent_text.text(event.title);
},
eventMouseout: function(event, jsEvent, view) {
mercury.c.$calevent_text.text("");
},
loading: function(isLoading,view) {
if(isLoading)
mercury.common.pause_on();
else
mercury.common.pause_off();
}
});
$.ajax({
type: "GET",
url: mercury.config.urlTop,
dataType: "json",
success: function(data, textStatus, jqXHR) {
if (data !== null) {
// Save top data locally
mercury.data.top = data;
// Transform top data into a form which is easier to drive selectors from
mercury.data.selector = mercury.processTopData(mercury.data.top);
mercury.data.reverse_top = mercury.reverseTopData(mercury.data.top);
mercury.c.$select_container.hide(); // Prevent flash
mercury.view.render_selectors_and_update();
mercury.c.$select_container.show();
mercury.view.single_change(mercury.c.$select_year,mercury.view.update_dropdowns);
mercury.view.single_change(mercury.c.$select_tripos,mercury.view.update_dropdowns);
mercury.view.single_change(mercury.c.$select_part,mercury.view.update_dropdowns);
mercury.view.multi_change(mercury.c.$select_course,mercury.view.update_hash_from_course);
} else {
alert("The following data feed did not produce any data: "+mercury.config.urlTop);
mercury.data.top = {};
}
},
error: function(jqXHR, textStatus, errorThrown) {
var error_msg = "Could not load data from the feed!";
ajaxError.apply(this, [null, jqXHR, $.ajaxSettings, errorThrown, error_msg]);
mercury.data.top = {};
}
});
mercury.common.login_link();
$(window).bind("hashchange", function(event) {
mercury.view.render_selectors_and_update();
});
$('#headfoothide').click(function() {
$('#headfoothide').css('display','none');
$('#headfootshow').css('display','block');
$('#headfootshy').css('display','none');
return false;
});
$('#headfootshow').click(function() {
$('#headfootshow').css('display','none');
$('#headfoothide').css('display','block');
$('#headfootshy').css('display','block');
return false;
});
};
mercury.view.current_sources = [];
mercury.view.recompute = function() {
mercury.view.recompute_calendar();
mercury.view.recompute_embed();
};
mercury.view.recompute_embed = function() {
var tc = mercury.view.cur_part_and_subjects();
var ids = tc[1].join(',');
var root = mercury.data.top.root;
var rnd = Math.floor(Math.random()*100000000);
var gcal = root + "php/gcal.php?rnd="+rnd+"&course="+ids;
$('#embed_ical').attr('href',gcal+"&type=ical");
$('#embed_ical').html(gcal+"&type=ical");
$('#embed_gcal').attr('href',gcal);
$('#embed_gcal').html(gcal);
var frame = '<iframe src="'+root+'embed.html#course='+ids+'&embed=1" style="min-width: 600px; border: 0" width="100%" height="570"></iframe>';
$('#embed_embed').text(frame);
};
mercury.view.recompute_calendar = function() {
var tc = mercury.view.cur_part_and_subjects();
var courses = tc[1];
toadd = {};
togo = {};
old = [];
for(var i=0;i<mercury.view.current_sources.length;i++) {
togo[mercury.view.current_sources[i].url] = 1;
old.push(mercury.view.current_sources[i]);
}
mercury.view.clear_basic();
mercury.view.current_sources = [];
mercury.view.load_basics(courses);
for(var i=0;i<courses.length;i++) {
var colours = mercury.view.colour(courses[i]);
url = mercury.config.wcalFeedURL+"?course="+courses[i];
mercury.view.current_sources.push({
url: url,
success: mercury.view.feed_success,
backgroundColor: colours.backgroundColour,
borderColor: '#BDB219',
textColor: '#222'
});
if(!togo[mercury.view.current_sources[i].url]) {
toadd[mercury.view.current_sources[i].url] = 1;
}
togo[mercury.view.current_sources[i].url] = 0;
}
for(var i=0;i<old.length;i++) {
if(togo[old[i].url]) {
mercury.data.calendarInstance.fullCalendar('removeEventSource',old[i]);
}
}
for(var i=0;i<mercury.view.current_sources.length;i++) {
if(toadd[mercury.view.current_sources[i].url]) {
mercury.data.calendarInstance.fullCalendar('addEventSource',mercury.view.current_sources[i]);
}
}
mercury.data.calendarInstance.fullCalendar('refetchEvents');
};
// Start with calling page init function
$(document).ready(function() {
mercury.view.init();
}); | ieb/timetables | htdocs/js/view.js | JavaScript | agpl-3.0 | 15,404 |
import { Template } from 'meteor/templating';
import { GoogleMaps } from 'meteor/dburles:google-maps';
import { ReactiveVar } from 'meteor/reactive-var';
import { Meteor } from 'meteor/meteor';
import _ from 'underscore';
import './nodeMap.html';
Template.nodeMap.helpers({
mapOptions() {
let result;
if (GoogleMaps.loaded()) {
// TODO: find how to fix google lib undef
/* eslint-disable no-undef */
result = {
zoom: 12,
center: new google.maps.LatLng(38.95, -123.65),
mapTypeId: google.maps.MapTypeId.HYBRID
};
/* eslint-enable no-undef */
}
return result;
},
recenterMapStyle() {
let result;
if (Template.instance().recenterMap.get()) {
result = 'btn-success';
} else {
result = 'btn-default';
}
return result;
},
locationText() {
return Template.instance().locationText.get();
}
});
Template.nodeMap.events({
'click #button-recenter-map' () {
Template.instance().recenterMap.set(Template.instance().recenterMap.get() === false);
}
});
Template.nodeMap.onCreated(function () {
const instance = this;
const initialData = Template.currentData();
instance.markers = {};
instance.recenterMap = new ReactiveVar(true);
instance.locationText = new ReactiveVar('');
// We can use the `ready` callback to interact with the map API once the map is ready.
GoogleMaps.ready('nodeMap', function (map) {
/* eslint-disable no-undef */
google.maps.event.addListener(map.instance, 'rightclick', function (event) {
const lat = event.latLng.lat();
const lng = event.latLng.lng();
// populate yor box/field with lat, lng
instance.locationText.set('Coordinates: ' + lat + ', ' + lng);
});
google.maps.event.addListener(map.instance, 'click', function () {
initialData.onNodeSelected(null);
});
instance.autorun(() => {
const currentData = Template.currentData();
const nodes = currentData.nodes.fetch();
Object.keys(instance.markers).forEach((_id) => {
if (!_.findWhere(nodes, { _id })) {
instance.markers[_id].setMap(null);
}
});
const bounds = new google.maps.LatLngBounds();
nodes.forEach((node) => {
let latlng;
if (instance.markers[node._id]) {
if (instance.markers[node._id].map === null) {
instance.markers[node._id].setMap(map.instance);
}
latlng = new google.maps.LatLng(node.lat, node.lng);
bounds.extend(latlng);
} else if (node.lat && node.lat !== 0 && node.lng && node.lng !== 0) {
const name = node.name;
latlng = new google.maps.LatLng(node.lat, node.lng);
bounds.extend(latlng);
let icon;
switch (node.type) {
case 'cpe':
case 'wifi-ap':
icon = '/images/marker_green.png';
break;
case 'bts':
case 'relay-client':
icon = '/images/marker_yellow.png';
break;
default:
icon = '/images/marker_red.png';
break;
}
instance.markers[node._id] = new google.maps.Marker({
position: latlng,
title: name,
icon,
map: map.instance
});
}
if (instance.markers[node._id]) {
google.maps.event.clearListeners(instance.markers[node._id], 'click');
if (currentData.selectedNodeId && currentData.selectedNodeId === node._id) {
google.maps.event.addListener(instance.markers[node._id], 'click', function () {
currentData.onNodeSecondClick();
});
} else {
google.maps.event.addListener(instance.markers[node._id], 'click', function () {
currentData.onNodeSelected(node._id);
});
}
}
});
if (instance.recenterMap.get()) {
map.instance.fitBounds(bounds);
}
if (Template.currentData().selectedNodeId) {
const m = instance.markers[Template.currentData().selectedNodeId];
if (m != null) {
if (instance.recenterMap.get()) {
map.instance.setCenter(m.position);
map.instance.setZoom(16);
}
m.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
m.setAnimation(null);
}, 1400);
}
}
});
/* eslint-enable no-undef */
});
});
Template.nodeMap.onRendered(function () {
GoogleMaps.load({ v: '3', key: Meteor.settings.public.google.mapsApiKey, libraries: 'geometry,places' });
});
| Celerate/celerate-controller | external-controller/imports/ui/components/nodes/nodeMap.js | JavaScript | agpl-3.0 | 4,671 |
/*
* eyeos - The Open Source Cloud's Web Desktop
* Version 2.0
* Copyright (C) 2007 - 2010 eyeos Team
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* version 3 along with this program in the file "LICENSE". If not, see
* <http://www.gnu.org/licenses/agpl-3.0.txt>.
*
* See www.eyeos.org for more details. All requests should be sent to licensing@eyeos.org
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* eyeos" logo and retain the original copyright notice. If the display of the
* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
* must display the words "Powered by eyeos" and retain the original copyright notice.
*/
/**
* Implementing {@see eyeos.ui.menubar.IActions}.
*/
qx.Class.define("genericbar.both.Actions", {
extend: qx.core.Object,
implement : [eyeos.ui.genericbar.IActions],
construct: function(window, checknum, pid, application) {
arguments.callee.base.call(this);
this.setWindow(window);
this.setChecknum(checknum);
this.setApplication(application);
this.setPid(pid);
},
properties: {
mathProcessor: {
init: null,
check: 'Object'
},
window: {
init: null,
check: 'eyeos.ui.Window'
},
checknum: {
init: null
},
pid: {
init: null
},
application: {
init: null
}
},
members: {
dynamicsActions: function (e) {
// console.log(e.getTarget().getLabel());
},
fileNew: function (e) {
this.getApplication().newFile();
// console.log(e.getTarget().getLabel());
},
fileOpen: function (e) {
this.getApplication().open();
},
fileSave: function (e) {
this.getApplication().save();
},
chartDialog: function (e) {
this.getApplication()._buildChartWindow();
},
formula_sum: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstCell = sps.getLetters()[selection[2]] + (selection[0] + 1);
var lastCell = sps.getLetters()[selection[3]] + (selection[1] + 1);
this.getApplication().getUndoRedoStack().push([sps.getActiveSheet(), {row: selection[1] + 1, col: selection[3], oldValue: model.getValue(selection[3], selection[1] + 1), value: '=SUM('+firstCell+':'+lastCell+')'}]);
model.setValue(selection[3], selection[1] + 1, '=SUM('+firstCell+':'+lastCell+')');
table.setFocusedCell(selection[3], selection[1] + 1);
this.updateUndoRedoStack(sps);
},
formula_avg: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstCell = sps.getLetters()[selection[2]] + (selection[0] + 1);
var lastCell = sps.getLetters()[selection[3]] + (selection[1] + 1);
this.getApplication().getUndoRedoStack().push([sps.getActiveSheet(), {row: selection[1] + 1, col: selection[3], oldValue: model.getValue(selection[3], selection[1] + 1), value: '=AVG('+firstCell+':'+lastCell+')'}]);
model.setValue(selection[3], selection[1] + 1, '=AVG('+firstCell+':'+lastCell+')');
table.setFocusedCell(selection[3], selection[1] + 1);
this.updateUndoRedoStack(sps);
},
formula_prod: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstCell = sps.getLetters()[selection[2]] + (selection[0] + 1);
var lastCell = sps.getLetters()[selection[3]] + (selection[1] + 1);
this.getApplication().getUndoRedoStack().push([sps.getActiveSheet(), {row: selection[1] + 1, col: selection[3], oldValue: model.getValue(selection[3], selection[1] + 1), value: '=PROD('+firstCell+':'+lastCell+')'}]);
model.setValue(selection[3], selection[1] + 1, '=PROD('+firstCell+':'+lastCell+')');
table.setFocusedCell(selection[3], selection[1] + 1);
this.updateUndoRedoStack(sps);
},
formula_min: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstCell = sps.getLetters()[selection[2]] + (selection[0] + 1);
var lastCell = sps.getLetters()[selection[3]] + (selection[1] + 1);
this.getApplication().getUndoRedoStack().push([sps.getActiveSheet(), {row: selection[1] + 1, col: selection[3], oldValue: model.getValue(selection[3], selection[1] + 1), value: '=MIN('+firstCell+':'+lastCell+')'}]);
model.setValue(selection[3], selection[1] + 1, '=MIN('+firstCell+':'+lastCell+')');
table.setFocusedCell(selection[3], selection[1] + 1);
this.updateUndoRedoStack(sps);
},
formula_max: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstCell = sps.getLetters()[selection[2]] + (selection[0] + 1);
var lastCell = sps.getLetters()[selection[3]] + (selection[1] + 1);
this.getApplication().getUndoRedoStack().push([sps.getActiveSheet(), {row: selection[1] + 1, col: selection[3], oldValue: model.getValue(selection[3], selection[1] + 1), value: '=MAX('+firstCell+':'+lastCell+')'}]);
model.setValue(selection[3], selection[1] + 1, '=MAX('+firstCell+':'+lastCell+')');
table.setFocusedCell(selection[3], selection[1] + 1);
this.updateUndoRedoStack(sps);
},
updateUndoRedoStack: function (sps) {
if (sps.getUndoRedoStackIndex() > 0) {
sps.getUndoRedoStack().splice(parseInt(sps.getUndoRedoStackIndex() + 1), parseInt(sps.getUndoRedoStack().length - parseInt(sps.getUndoRedoStackIndex() + 1)));
}
sps.setUndoRedoStackIndex(sps.getUndoRedoStackIndex() + 1);
},
selectAll: function (e) {
var model = this.getApplication().getModels()[this.getApplication().getActiveSheet() - 1];
var table = this.getApplication().getTables()[this.getApplication().getActiveSheet() - 1];
model.setFirstSelectedCell({row: 0, col: 1});
model.setCurrentSelectedCell({row: model.getRowCount(), col: model.getColumnCount() });
table.customUpdate();
},
clearAll: function (e) {
var model = this.getApplication().getModels()[this.getApplication().getActiveSheet() - 1];
var table = this.getApplication().getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstRow = selection[0];
var lastRow = selection[1];
var firstCol = selection[2];
var lastCol = selection[3];
for (var i = firstRow; i <= lastRow; ++i) {
for (var f = firstCol; f <= lastCol; ++f) {
model.setValue(f, i, undefined);
}
}
table.customUpdate();
},
insertRowAbove: function (e) {
var sps = this.getApplication();
var tableModel = this.getApplication().getModels()[this.getApplication().getActiveSheet() - 1];
var table = this.getApplication().getTables()[this.getApplication().getActiveSheet() - 1];
var focusedRow = table.getFocusedRow();
if (focusedRow != null) {
tableModel.addRowsAsMapArray([[]], focusedRow);
} else {
tableModel.addRowsAsMapArray([[]], 0);
}
this.reDrawRows(tableModel)
},
insertRowBelow: function (e) {
var sps = this.getApplication();
var tableModel = this.getApplication().getModels()[this.getApplication().getActiveSheet() - 1];
var table = this.getApplication().getTables()[this.getApplication().getActiveSheet() - 1];
var focusedRow = table.getFocusedRow();
if (focusedRow != null) {
tableModel.addRowsAsMapArray([[]], focusedRow + 1);
} else {
tableModel.addRowsAsMapArray([[]], tableModel.getRowCount());
}
this.reDrawRows(tableModel)
},
reDrawRows: function (model) {
var rowCount = model.getRowCount();
for (var i = 0; i < rowCount; ++i) {
model.setValue(0, i, i + 1);
}
},
editCopy: function (e) {
var sps = this.getApplication();
sps.setCopyStack(new Array());
var tableModel = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var currentSelection = tableModel.getCurrentSelection();
var stack = new Array();
var limitRows = currentSelection[1] - currentSelection[0];
var limitCols = currentSelection[3] - currentSelection[2];
for (var i = 0; i <= limitRows; ++i) {
stack[i] = new Array();
for (var f = 0; f <= limitCols; ++f) {
stack[i][f] = tableModel.getValue(currentSelection[2]+f, currentSelection[0]+i);
//tableModel.setValue(currentSelection[2]+f, currentSelection[0]+i, '');
}
sps.getCopyStack().push(stack[i]);
}
},
editCut: function (e) {
var sps = this.getApplication();
sps.setCopyStack(new Array());
var tableModel = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var currentSelection = tableModel.getCurrentSelection();
var stack = new Array();
var limitRows = currentSelection[1] - currentSelection[0];
var limitCols = currentSelection[3] - currentSelection[2];
for (var i = 0; i <= limitRows; ++i) {
stack[i] = new Array();
for (var f = 0; f <= limitCols; ++f) {
stack[i][f] = tableModel.getValue(currentSelection[2]+f, currentSelection[0]+i);
tableModel.setValue(currentSelection[2]+f, currentSelection[0]+i, undefined);
}
sps.getCopyStack().push(stack[i]);
}
},
editPaste: function (e) {
var sps = this.getApplication();
var stack = sps.getCopyStack();
var tableModel = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var row = table.getFocusedRow();
var col = table.getFocusedColumn();
for (var i = 0; i < stack.length; ++i) {
var item = stack[i];
for (var f = 0; f < item.length; ++f) {
tableModel.setValue(col+f, row+i, item[f]);
}
}
table.customUpdate();
},
editUndo: function (e) {
var sps = this.getApplication();
var stack = sps.getUndoRedoStack();
var ind = sps.getUndoRedoStackIndex();
if (ind < 0) {
return;
} else {
if (ind != 0) {
var values = stack[ind - 1];
} else {
values = stack[0];
}
}
var model = sps.getModels()[values[0] - 1];
for (var i = 1; i < values.length; ++i) {
var item = values[i];
model.setValue(item.col, item.row, item.oldValue);
}
sps.getTables()[values[0] - 1].customUpdate();
if (ind > 0) {
sps.setUndoRedoStackIndex(ind - 1);
} else {
sps.setUndoRedoStackIndex(0);
}
},
editRedo: function (e) {
var sps = this.getApplication();
var stack = sps.getUndoRedoStack();
var ind = sps.getUndoRedoStackIndex();
if ((ind + 1) > stack.length) {
return;
} else {
var values = stack[ind];
}
var model = sps.getModels()[values[0] - 1];
for (var i = 1; i < values.length; ++i) {
var item = values[i];
model.setValue(item.col, item.row, item.value);
}
sps.getTables()[values[0] - 1].customUpdate();
if (ind < stack.length) {
sps.setUndoRedoStackIndex(ind + 1);
} else {
sps.setUndoRedoStackIndex(stack.length);
}
},
isValueNumeric: function (sText) {
var validChars = "0123456789.,";
var isNumber = true;
for (var i = 0; i < sText.length && isNumber == true; ++i) {
var character = sText.charAt(i);
if (validChars.indexOf(character) == -1) {
isNumber = false;
}
}
return isNumber;
},
sortPrepareUndoRedoStack: function (sps, valuesUndoRedo) {
// We prepare the stack for undo/redo values
var temp = new Array();
for (var i = 0; i < valuesUndoRedo.length; ++i) {
if (valuesUndoRedo[i] != undefined) {
for (var f = 0; f < valuesUndoRedo[i].length; ++f) {
if (valuesUndoRedo[i][f] != undefined) {
temp.push(valuesUndoRedo[i][f]);
}
}
}
}
// Store the active sheet for undo/redo
// Add one for the stack
temp.unshift(sps.getActiveSheet());
sps.getUndoRedoStack().push(temp);
if (sps.getUndoRedoStackIndex() > 0) {
sps.getUndoRedoStack().splice(parseInt(sps.getUndoRedoStackIndex() + 1), parseInt(sps.getUndoRedoStack().length - parseInt(sps.getUndoRedoStackIndex() + 1)));
}
sps.setUndoRedoStackIndex(sps.getUndoRedoStackIndex() + 1);
},
sortAscendant: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstRow = selection[0];
var lastRow = selection[1];
var firstCol = selection[2];
var lastCol = selection[3];
var letterFound = this.sortDetectLetter(sps, model, table, firstRow, lastRow, firstCol, lastCol);
var valuesUndoRedo = new Array();
if (letterFound) {
valuesUndoRedo = this.sortByLetters('ascendant', model, firstRow, lastRow, firstCol, lastCol);
} else {
valuesUndoRedo = this.sortNumeric('ascendant', sps, model, table, firstRow, lastRow, firstCol, lastCol);
}
this.sortPrepareUndoRedoStack(sps, valuesUndoRedo);
table.customUpdate();
},
sortDescendant: function (e) {
var sps = this.getApplication();
var model = sps.getModels()[this.getApplication().getActiveSheet() - 1];
var table = sps.getTables()[this.getApplication().getActiveSheet() - 1];
var selection = model.getCurrentSelection();
var firstRow = selection[0];
var lastRow = selection[1];
var firstCol = selection[2];
var lastCol = selection[3];
var letterFound = this.sortDetectLetter(sps, model, table, firstRow, lastRow, firstCol, lastCol);
var valuesUndoRedo = new Array();
if (letterFound) {
valuesUndoRedo = this.sortByLetters('descendant', model, firstRow, lastRow, firstCol, lastCol);
} else {
valuesUndoRedo = this.sortNumeric('descendant', sps, model, table, firstRow, lastRow, firstCol, lastCol);
}
this.sortPrepareUndoRedoStack(sps, valuesUndoRedo);
table.customUpdate();
},
sortDetectLetter: function (sps, model, table, firstRow, lastRow, firstCol, lastCol) {
var letterFound = false;
for (var i = firstCol; i <= lastCol; ++i) {
for (var f = firstRow; f <= lastRow; ++f) {
var tempValue = model.getValue(i, f);
if (typeof(tempValue) == "string") {
if (tempValue.substr(0,1) != "=" && !this.isValueNumeric(tempValue)) {
letterFound = true;
}
}
}
}
return letterFound;
},
sortByLetters: function (flag, model, firstRow, lastRow, firstCol, lastCol) {
var tempArray = new Array();
var sortArray = new Array();
var refArray = new Array();
var row = 0;
for (var i = firstRow; i <= lastRow; ++i) {
refArray[row] = new Array();
var col = 0;
for (var f = firstCol; f <= lastCol; ++f) {
if (f == firstCol) {
tempArray[row] = model.getValue(f, i);
sortArray[row] = model.getValue(f, i);
} else {
refArray[row][col] = model.getValue(f, i);
col++;
}
}
row++;
}
if (flag == 'ascendant') {
sortArray.sort();
} else {
sortArray.sort().reverse();
}
var sortedArray = new Array();
for (var i = 0; i < sortArray.length; i++) {
sortedArray[i] = new Array();
sortedArray[i][0] = sortArray[i];
for (var k = 1; k < (refArray[0].length + 1); ++k) {
sortedArray[i][k] = refArray[tempArray.indexOf(sortArray[i])][k - 1];
}
}
var valuesUndoRedo = new Array();
var x = 0;
for (var i = firstCol; i <= lastCol; ++i) {
var z = 0;
valuesUndoRedo[i] = new Array();
for (var f = firstRow; f <= lastRow; ++f) {
valuesUndoRedo[i][f] = {
oldValue: model.getValue(i, f),
value: sortedArray[z][x],
row: f,
col: i
};
model.setValue(i, f, sortedArray[z][x]);
z++;
}
x++;
}
return valuesUndoRedo;
},
sortNumeric: function (flag, sps, model, table, firstRow, lastRow, firstCol, lastCol) {
if (!(this.getMathProcessor() instanceof MathProcessor)) {
this.setMathProcessor(new MathProcessor(this.getApplication().getTables()[this.getApplication().getActiveSheet() - 1]));
}
var numOrdA = function (a, b){ return (a.value-b.value); };
var numOrdD = function (a, b){ return (a.value+b.value); };
var order;
if (flag == 'ascendant') {
order = numOrdA;
} else {
order = numOrdD;
}
var values = new Array();
var valuesUndoRedo = new Array();
/*
* We run from the first to the last column (and row) of our selection
*
* - We parse if there's any formula
* - Then we save the values for the undoRedo (it should do it just once)
*/
for (var i = firstCol; i <= lastCol; ++i) {
values[i] = new Array();
valuesUndoRedo[i] = new Array();
for (var f = firstRow; f <= lastRow; ++f) {
var tempValue = model.getValue(i, f);
if (typeof(tempValue) == "string") {
if (tempValue.substr(0,1) == "=") {
tempValue = this.getMathProcessor().parse(tempValue.substr(1));
}
}
valuesUndoRedo[i][f] = {oldValue: model.getValue(i, f), col: i, row: f};
values[i].push({value: tempValue, realValue: model.getValue(i, f), row: f});
}
}
// Then we sort every column
for (var i = firstCol; i <= lastCol; ++i) {
values[i].sort(order);
for (var f = 0; f < values[i].length; ++f) {
model.setValue(i, firstRow + f, values[i][f].realValue);
// Due to our array is sorted we add the value to valuesUndoRedo
valuesUndoRedo[i][firstRow + f].value = values[i][f].realValue;
}
}
return valuesUndoRedo;
},
basename: function(path, suffix) {
var b = path.replace(/^.*[\/\\]/g, '');
if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
b = b.substr(0, b.length-suffix.length);
}
return b;
}
}
}); | FireWalkerX/eyeOS-FOSS-V.2.0 | eyeos/apps/spreadsheets/bars/genericbar.both.Actions.js | JavaScript | agpl-3.0 | 19,195 |
import {posDirToText} from './utils.js'
import {move, initPlayerPos} from './movement.js'
import {hideLoadingScreen, openPage} from './interface.js'
import {initKeyboardInput, initMouseInput} from './input.js'
import {createCommonAudios} from './createAudios.js'
import {shrines, state} from './store.js'
import {interact, playButtonSound, onSetVision} from './game.js'
import {resize} from './vision.js'
import {pickLevel, startLevel} from './levels.js'
import {closeTutMsg} from './tutorial.js'
export function mainLoad() {
state.game.load.onLoadStart.add(function () {
console.log('Loading...')
}, this)
state.game.load.onLoadComplete.add(function () {
console.log('Done loading')
state.game.load.onLoadStart.removeAll()
state.game.load.onLoadComplete.removeAll()
mainInit()
}, this)
var firstImg = posDirToText(state.position, state.direction)
state.game.load.image(firstImg, `assets/map/${firstImg}.jpg`)
state.game.load.audio('button', ['assets/audio/button.ogg'])
state.game.load.audio('stream', ['assets/audio/stream_cold.ogg'])
state.game.load.audio('wind', ['assets/audio/wind.ogg'])
state.game.load.audio('fire', ['assets/audio/fire.ogg'])
state.game.load.audio('earth', ['assets/audio/earth.ogg'])
state.game.load.audio('magic', ['assets/audio/magic_slow.ogg'])
state.game.load.audio('magic_request', ['assets/audio/magic_request.ogg'])
state.game.load.audio('magic_arrived', ['assets/audio/magic_arrived.ogg'])
state.game.load.audio('magic_no', ['assets/audio/magic_no.ogg'])
state.game.load.audio('harp', ['assets/audio/harp.ogg'])
state.game.load.audio('harp_start', ['assets/audio/harp_start.ogg'])
state.game.load.audio('steps', ['assets/audio/steps.ogg'])
state.game.load.audio('dark_spell', ['assets/audio/dark_spell.ogg'])
state.game.load.audio('dark_presence', ['assets/audio/dark_presence.ogg'])
state.game.load.audio('dark_song', ['assets/audio/dark_song.ogg'])
state.game.load.audio('rarr', ['assets/audio/rarr.ogg'])
state.game.load.audio('end2', ['assets/audio/end2.ogg'])
state.game.load.script('gray', 'vendor/Gray.js')
state.game.load.start()
}
// First init called. Should be called only once, and before any level.
function mainInit() {
hideLoadingScreen()
state.game.stage.backgroundColor = '#000000'
// Used to render some things always in front of others
state.layers = {
back: state.game.add.group(),
front: state.game.add.group(),
}
state.onSetVision = onSetVision
resize()
// initialize state presences (needed to later randomize them)
for (let k in shrines) {
state.presences[k] = {}
}
state.game.createdFilters = {gray: state.game.add.filter('Gray')}
createCommonAudios()
initKeyboardInput(move, interact)
initMouseInput(move, interact)
if (!localStorage.getItem('lastLevel')) {
// No level unlocked
pickLevel(1, false)
} else {
// Level 2 unlocked
openPage('mainmenu', false)
}
}
// Exported functions, so interface can call them
window.openPage = openPage
window.pickLevel = pickLevel
window.startLevel = startLevel
window.closeTutMsg = closeTutMsg
window.playButtonSound = playButtonSound
| andresmrm/labyrimental | src/loader.js | JavaScript | agpl-3.0 | 3,308 |
MWF.xApplication.portal.PageDesigner.Module = MWF.xApplication.portal.PageDesigner.Module || {};
MWF.xDesktop.requireApp("process.FormDesigner", "Module.$Element", null, false);
MWF.xApplication.portal.PageDesigner.Module.Widget = MWF.PCWidget = new Class({
Extends: MWF.FC$Element,
Implements: [Options, Events],
options: {
"style": "default",
"propertyPath": "../x_component_portal_PageDesigner/Module/Widget/widget.html",
"actions": [
{
"name": "move",
"icon": "move1.png",
"event": "mousedown",
"action": "move",
"title": MWF.APPPOD.LP.formAction.move
},
{
"name": "delete",
"icon": "delete1.png",
"event": "click",
"action": "delete",
"title": MWF.APPPOD.LP.formAction["delete"]
}
// {
// "name": "styleBrush",
// "icon": "styleBrush.png",
// "event": "click",
// "action": "styleBrush",
// "title": MWF.APPPOD.LP.formAction["styleBrush"]
// }
]
},
initialize: function(page, options){
this.setOptions(options);
this.path = "../x_component_portal_PageDesigner/Module/Widget/";
this.cssPath = "../x_component_portal_PageDesigner/Module/Widget/"+this.options.style+"/css.wcss";
this._loadCss();
this.moduleType = "element";
this.moduleName = "widget";
this.page = page;
this.form = page;
this.container = null;
this.containerNode = null;
},
load : function(json, node, parent){
this.json = json;
this.node= node;
this.node.store("module", this);
//this.node.empty();
this.node.setStyles(this.css.moduleNode);
//this._loadNodeStyles();
this._initModule();
if (this.json.widgetSelected && this.json.widgetSelected!=="none" && this.json.widgetType!=="script"){
this.redoSelectedWidget(this.json.widgetSelected, null, "");
}else{
this.node.empty();
this.loadIcon();
}
this._loadTreeNode(parent);
this.setCustomStyles();
this.parentContainer = this.treeNode.parentNode.module;
this._setEditStyle_custom("id");
this.parseModules();
this.json.moduleName = this.moduleName;
this.node.addEvent("click", function(){
this.refreshWidget();
}.bind(this));
this.node.addEvent("dblclick", function(e){
this.openWidget(e);
}.bind(this));
},
_initModule: function(){
if (!this.json.isSaved) this.setStyleTemplate();
this.setPropertiesOrStyles("styles");
this.setPropertiesOrStyles("inputStyles");
this.setPropertiesOrStyles("properties");
this._setNodeProperty();
if (!this.page.isWidget) this._createIconAction();
this._setNodeEvent();
this.json.isSaved = true;
this.queryGetPageDataFun = this.queryGetPageData.bind(this);
this.postGetPageDataFun = this.postGetPageData.bind(this);
this.page.addEvent("queryGetPageData", this.queryGetPageDataFun);
this.page.addEvent("postGetPageData", this.postGetPageDataFun);
},
openWidget: function(e){
if (this.json.widgetSelected && this.json.widgetSelected!=="none" && this.json.widgetType!=="script"){
layout.desktop.openApplication(e, "portal.WidgetDesigner", {"id": this.json.widgetSelected, "appId": "WidgetDesigner"+this.json.widgetSelected});
}
},
_createMoveNode: function(){
this.moveNode = new Element("div", {
"MWFType": "widget",
"id": this.json.id,
"styles": this.css.moduleNodeMove,
"events": {
"selectstart": function(){
return false;
}
}
}).inject(this.page.container);
},
_getDroppableNodes: function(){
var nodes = [this.form.node].concat(this.form.moduleElementNodeList, this.form.moduleContainerNodeList, this.form.moduleComponentNodeList);
this.form.moduleList.each( function(module){
//้จไปถไธ่ฝๅพๆฐๆฎๆจกๆฟ้ๆ
if( module.moduleName === "datatemplate" ){
var subDoms = this.form.getModuleNodes(module.node);
nodes.erase( module.node );
subDoms.each(function (dom) {
nodes.erase( dom );
})
}
}.bind(this));
return nodes;
},
_createNode: function(){
this.node = this.moveNode.clone(true, true);
this.node.setStyles(this.css.moduleNode);
this.node.set("id", this.json.id);
this.node.addEvent("selectstart", function(){
return false;
});
// debugger;
// if (this.json.widgetSelected && this.json.widgetSelected!="none" && this.json.widgetType!=="script"){
// this.redoSelectedWidget(this.json.widgetSelected, $(this.property.data.pid+"selectWidget").getElement("select"), "");
// }else{
this.loadIcon();
// }
this.node.addEvent("click", function(){
this.refreshWidget();
}.bind(this));
debugger;
this.node.addEvent("dblclick", function(e){
this.openWidget(e);
}.bind(this));
},
postGetPageData: function(node){
if (!node || node.contains(this.node)) this.show();
},
queryGetPageData: function(node){
if (!node || node.contains(this.node)) this.hide();
},
hide: function(){
this.node.empty();
},
show: function(){
if (this.widgetData ){
this.widgetModule = new MWF.PCWidget.Page(this.page, this.node, {
parentpageIdList : this.getParentpageIdList(),
level : this.getLevel()
});
this.widgetModule.widgetSelector = this.getWidgetSelector();
this.widgetModule.widgetSelectedValue = this.getWidgetSelectedValue();
this.widgetModule.level1Widget = this.getLevel1Widget();
this.widgetModule.load(this.widgetData);
}else{
this.node.empty();
this.loadIcon();
}
},
"delete": function(e){
var module = this;
this.page.designer.shortcut = false;
this.page.designer.confirm("warn", module.node, MWF.APPPOD.LP.notice.deleteElementTitle, MWF.APPPOD.LP.notice.deleteElement, 300, 120, function(){
if (this.queryGetPageDataFun) module.page.removeEvent("queryGetPageData", this.queryGetPageDataFun);
if (this.postGetPageDataFun) module.page.removeEvent("postGetPageData", this.postGetPageDataFun);
module.destroy();
module.page.selected();
module.page.designer.shortcut = true;
this.close();
}, function(){
module.page.designer.shortcut = true;
this.close();
}, null);
},
getLevel : function(){
return ( this.page.options.level1 || 0 ) + 1;
},
getLevel1Widget : function(){
return this.page.level1Widget || this;
},
getWidgetSelector : function(){
return this.widgetSelector || this.page.widgetSelector;
},
getWidgetSelectedValue : function(){
return this.widgetSelectedValue || this.page.widgetSelectedValue;
},
checkWidgetNested : function( id ){
if( this.page.options.parentpageIdList ){
return !this.page.options.parentpageIdList.contains( id );
}
return true;
},
getParentpageIdList : function(){
var parentpageIdList;
if( this.page.options.parentpageIdList ){
parentpageIdList = Array.clone( this.page.options.parentpageIdList );
parentpageIdList.push( this.page.json.id )
}else{
parentpageIdList = [ this.page.json.id ];
}
return parentpageIdList;
},
refreshWidget: function(){
if (this.json.widgetSelected && this.json.widgetSelected!=="none" && this.json.widgetType!=="script"){
MWF.Actions.get("x_portal_assemble_designer").getWidget(this.json.widgetSelected, function(json){
if (this.widgetData.updateTime!==json.data.updateTime){
var select = null;
if (this.property){
select = $(this.property.data.pid+"selectWidget").getElement("select");
}
this.clearWidgetList(this.json.widgetSelected);
this.reloadWidget(json.data, select, "");
}
}.bind(this));
}
},
loadIcon: function(){
this.iconNode = new Element("div", {
"styles": this.css.iconNode
}).inject(this.node);
new Element("div", {
"styles": this.css.iconNodeIcon
}).inject(this.iconNode);
new Element("div", {
"styles": this.css.iconNodeText,
"text": "Widget"
}).inject(this.iconNode);
},
_loadNodeStyles: function(){
this.iconNode = this.node.getElement("div").setStyles(this.css.iconNode);
this.iconNode.getFirst("div").setStyles(this.css.iconNodeIcon);
this.iconNode.getLast("div").setStyles(this.css.iconNodeText);
},
_setEditStyle_custom: function(name, input, oldValue){
if (name==="widgetSelected"){
if (this.json.widgetSelected!==oldValue){
this.redoSelectedWidget(name, input, oldValue);
}
}
if (name==="widgetType"){
if (this.json.widgetType!==oldValue){
if (this.json.widgetType !== "script"){
this.redoSelectedWidget(name, $(this.property.data.pid+"selectWidget").getElement("select"), "");
}
if (this.json.widgetType === "script"){
this.widgetData = null;
this.clearWidgetList(this.json.widgetSelected);
this.node.empty();
this.loadIcon();
}
}
}
},
redoSelectedWidget: function(name, input, oldValue){
if (this.json.widgetSelected==="none") this.json.widgetSelected="";
if (this.json.widgetSelected && this.json.widgetSelected!=="none"){
if(input)this.widgetSelector = input;
if( !input )input = this.getWidgetSelector();
if( oldValue )this.widgetSelectedValue = oldValue;
if( !oldValue )oldValue = this.getWidgetSelectedValue() || "";
var level1Widget = this.getLevel1Widget();
if( !this.checkWidgetNested(this.json.widgetSelected) ){
//var p = this.node.getPosition(document.body);
//this.page.designer.alert("error", {
// "event": {
// "x": p.x + 150,
// "y": p.y + 80
// }
//}, this.page.designer.lp.widgetNestedTitle, this.page.designer.lp.widgetNestedInfor, 400, 120);
this.page.designer.notice( this.page.designer.lp.widgetNestedInfor, "error", level1Widget.node );
level1Widget.json.widgetSelected = oldValue;
if (input) {
for (var i = 0; i < input.options.length; i++) {
if (input.options[i].value === oldValue || (input.options[i].value==="none" && !oldValue ) ) {
input.options[i].set("selected", true);
break;
}
}
}
if( !oldValue ){
level1Widget.node.empty();
level1Widget.loadIcon();
}else{
level1Widget.refreshWidget();
}
}else{
MWF.Actions.get("x_portal_assemble_designer").getWidget(this.json.widgetSelected, function(json){
this.reloadWidget(json.data, input, oldValue);
}.bind(this));
}
}else{
this.widgetData = null;
this.clearWidgetList(oldValue);
this.node.empty();
this.loadIcon();
}
},
clearWidgetList: function(pageName){
if (!this.page.widgetList) this.page.widgetList = {};
if (pageName) if (this.page.widgetList[pageName]) delete this.page.widgetList[pageName];
},
addWidgetList: function(){
if (!this.page.widgetList) this.page.widgetList = {};
this.page.widgetList[this.json.widgetSelected] = Object.clone(this.widgetData.json);
},
getWidgetData: function(data){
var widgetDataStr = null;
if (this.page.options.mode !== "Mobile"){
widgetDataStr = data.data;
}else{
widgetDataStr = data.mobileData;
}
this.widgetData = null;
if (widgetDataStr){
this.widgetData = JSON.decode(MWF.decodeJsonString(widgetDataStr));
this.widgetData.updateTime = data.updateTime;
}
},
reloadWidget: function(data, input, oldValue){
this.getWidgetData(data);
if (this.widgetData){
var oldWidgetData = (this.page.widgetList && oldValue) ? this.page.widgetList[oldValue] : null;
this.clearWidgetList(oldValue);
if (this.checkWidget(data, input)){
this.node.empty();
this.loadWidget();
this.addWidgetList();
}else{
if (oldWidgetData){
if (!this.page.widgetList) this.page.widgetList = {};
this.page.widgetList[oldValue] = oldWidgetData;
}else{
this.clearWidgetList(oldValue);
this.node.empty();
this.loadIcon();
}
this.json.widgetSelected = oldValue;
if (!oldValue){
if (input) input.options[0].set("selected", true);
}else{
if (input){
for (var i=0; i<input.options.length; i++){
if (input.options[i].value===oldValue){
input.options[i].set("selected", true);
break;
}
}
}
}
}
}else{
this.json.widgetSelected = oldValue;
if (input){
if (!oldValue){
input.options[0].set("selected", true);
}else{
for (var i=0; i<input.options.length; i++){
if (input.options[i].value===oldValue){
input.options[i].set("selected", true);
break;
}
}
}
}
}
},
regetWidgetData: function(){
var flag = false;
if (this.json.widgetSelected && this.json.widgetSelected!=="none" && this.json.widgetType!=="script"){
MWF.Actions.get("x_portal_assemble_designer").getWidget(this.json.widgetSelected, function(json){
if (!this.widgetData || this.widgetData.updateTime!==json.data.updateTime){
this.getWidgetData(json.data);
flag = true;
}
}.bind(this), null, false);
}
return flag;
},
getConflictFields: function(){
var moduleNames = [];
if (this.widgetData){
Object.each(this.widgetData.json.moduleList, function(o, key){
var check = this.page.checkModuleId(key, o.type, this.widgetData.json.id);
if (check.fieldConflict){
moduleNames.push(key)
}else if (check.elementConflict){
o.changeId = this.json.id+"_"+key;
}
}.bind(this));
}
return moduleNames;
},
checkWidget: function(data, input){
return true;
var moduleNames = this.getConflictFields();
// Object.each(this.widgetData.json.moduleList, function(o, key){
// var check = this.page.checkModuleId(key, o.type, this.widgetData.json.id);
// if (check.fieldConflict){
// moduleNames.push(key)
// }else if (check.elementConflict){
// o.changeId = this.json.id+"_"+key;
// }
// }.bind(this));
if (moduleNames.length){
var txt = this.page.designer.lp.widgetNameConflictInfor;
txt = txt.replace("{name}", moduleNames.join(", "));
//var p = (input) ? input.getPosition() : this.node.getPosition();
// var p = this.node.getPosition(document.body);
// this.page.designer.alert("error", {
// "event": {
// "x": p.x+150,
// "y": p.y+80
// }
// }, this.page.designer.lp.widgetNameConflictTitle, txt, 400, 200);
this.page.designer.notice(txt, "error", this.node);
return false;
}
return true;
},
loadWidget: function(data) {
this.widgetData.json.style = this.page.json.style;
this.widgetData.json.properties = this.page.json.properties;
this.widgetData.json.jsheader = {"code": "", "html": ""};
this.widgetData.json.events = {};
this.widgetData.json.pageStyleType = this.page.json.pageStyleType;
//this.widgetData.json.id = this.json.id;
this.widgetModule = new MWF.PCWidget.Page(this.page, this.node,{
parentpageIdList : this.getParentpageIdList(),
level : this.getLevel()
});
this.widgetModule.widgetSelector = this.getWidgetSelector();
this.widgetModule.widgetSelectedValue = this.getWidgetSelectedValue();
this.widgetModule.level1Widget = this.getLevel1Widget();
this.widgetModule.load(this.widgetData);
//this.createRefreshNode();
},
destroy: function(){
this.page.moduleList.erase(this);
this.page.moduleNodeList.erase(this.node);
this.page.moduleElementNodeList.erase(this.node);
this.clearWidgetList(this.json.widgetSelected);
this.node.destroy();
this.actionArea.destroy();
delete this.page.json.moduleList[this.json.id];
this.json = null;
delete this.json;
this.treeNode.destroy();
}
});
MWF.xApplication.portal.PageDesigner.Module.Widget.Page = new Class({
Extends: MWF.PCPage,
initialize: function(page, container, options){
this.setOptions(options);
this.toppage = page.toppage || page;
this.parentpage = page;
this.parentform = page;
this.css = this.parentpage.css;
this.container = container;
this.form = this;
this.page = this;
this.isWidget = true;
this.isSubform = true;
this.moduleType = "widget";
this.moduleList = [];
this.moduleNodeList = [];
this.moduleContainerNodeList = [];
this.moduleElementNodeList = [];
this.moduleComponentNodeList = [];
// this.moduleContainerList = [];
this.dataTemplate = {};
this.designer = this.parentpage.designer;
this.selectedModules = [];
},
load : function(data){
this.data = data;
this.json = data.json;
this.html = data.html;
this.json.mode = this.options.mode;
this.container.set("html", this.html);
this.loadDomModules();
//this.setCustomStyles();
//this.node.setProperties(this.json.properties);
//this.setNodeEvents();
if (this.options.mode==="Mobile"){
if (oldStyleValue) this._setEditStyle("pageStyleType", null, oldStyleValue);
}
},
loadDomModules: function(){
this.node = this.container.getFirst();
this.node.set("id", this.json.id);
this.node.setStyles((this.options.mode==="Mobile") ? this.css.pageMobileNode : this.css.pageNode);
this.node.store("module", this);
this.loadDomTree();
},
loadDomTree: function(){
this.createPageTreeNode();
this.parseModules(this, this.node);
},
createPageTreeNode: function(){
this.treeNode = {
"insertChild": function(){return this;},
"appendChild": function(){return this;},
"selectNode": function(){},
"node": null,
"parentNode": {}
};
this.treeNode.module = this;
}
}); | o2oa/o2oa | o2web/source/x_component_portal_PageDesigner/Module/Widget.js | JavaScript | agpl-3.0 | 20,545 |
// @TODO, pull from config
export const DAYS_TO_REPLY = 14;
| Trustroots/trustroots | modules/experiences/client/utils/constants.js | JavaScript | agpl-3.0 | 60 |
define([
"pedigree/pedigreeDate",
"pedigree/model/baseGraph",
"pedigree/model/helpers"
], function(
PedigreeDate,
BaseGraph,
Helpers
){
PedigreeImport = function () {
};
PedigreeImport.prototype = {
};
/*PedigreeImport.SUPORTED_FORMATS = {
PED: 1, // standard .PED format. Can only import family structure, gender and the affected status
PHENOTIPS_GRAPH: 2, // Phenotips pedigree format, whithout positioning information (needs to be laid out automaticaly)
PHENOTIPS_INTERNAL_OLD: 3 // Phenotips internal format used during development and in test cases (to be replaced)
};
PedigreeImport.autodetectFormat = function(input) {
}*/
PedigreeImport.initFromPhenotipsInternal = function(inputG)
{
// note: serialize() produces the correct input for this function
var newG = new BaseGraph();
var nameToId = {};
var relationshipHasExplicitChHub = {};
// first pass: add all vertices and assign vertex IDs
for (var v = 0; v < inputG.length; v++) {
if (!inputG[v].hasOwnProperty("name") && !inputG[v].hasOwnProperty("id"))
throw "Invalid inpiut: a node without id and without name";
var type = BaseGraph.TYPE.PERSON;
if ( inputG[v].hasOwnProperty('relationship') || inputG[v].hasOwnProperty('rel') ) {
type = BaseGraph.TYPE.RELATIONSHIP;
// normally users wont specify childhubs explicitly - but save via JSON does
if (inputG[v].hasOwnProperty('hub') || inputG[v].hasOwnProperty('haschhub'))
relationshipHasExplicitChHub[v] = true;
}
else if ( inputG[v].hasOwnProperty('chhub') ) {
type = BaseGraph.TYPE.CHILDHUB;
}
else if ( inputG[v].hasOwnProperty('virtual') || inputG[v].hasOwnProperty('virt')) {
type = BaseGraph.TYPE.VIRTUALEDGE;
}
var properties = {};
if (inputG[v].hasOwnProperty('properties') || inputG[v].hasOwnProperty('prop'))
properties = inputG[v].hasOwnProperty('properties') ? inputG[v]["properties"] : inputG[v]["prop"];
if ( type == BaseGraph.TYPE.PERSON ) {
if (properties.hasOwnProperty("sex") && !properties.hasOwnProperty("gender")) {
properties["gender"] = properties["sex"];
}
if (!properties.hasOwnProperty("gender"))
properties["gender"] = "U";
if (inputG[v].hasOwnProperty("gender")) {
var genderString = inputG[v]["gender"].toLowerCase();
if( genderString == "female" || genderString == "f")
properties["gender"] = "F";
if( genderString == "other" || genderString == "o")
properties["gender"] = "O";
else if( genderString == "male" || genderString == "m")
properties["gender"] = "M";
}
}
var width = inputG[v].hasOwnProperty('width') ?
inputG[v].width :
(type == BaseGraph.TYPE.PERSON ? newG.defaultPersonNodeWidth : newG.defaultNonPersonNodeWidth);
var newID = newG._addVertex( null, type, properties, width ); // "null" since id is not known yet
if (inputG[v].hasOwnProperty("name")) { // note: this means using user input (not produced by this.serialize)
if (nameToId[inputG[v].name])
throw "Invalid user input: multiple nodes with the same name";
if (type == BaseGraph.TYPE.PERSON)
newG.properties[newID]["fName"] = inputG[v].name;
nameToId[inputG[v].name] = newID;
}
// when entered by user manually allow users to skip childhub nodes (and create them automatically)
// (but when saving/restoring from a JSON need to save/restore childhub nodes as they
// may have some properties assigned by the user which we need to save/restore)
if ( type == BaseGraph.TYPE.RELATIONSHIP && !relationshipHasExplicitChHub.hasOwnProperty(v) ) {
var chHubId = newG._addVertex(null, BaseGraph.TYPE.CHILDHUB, null, width );
nameToId["_chhub_" + newID] = chHubId;
}
}
// second pass (once all vertex IDs are known): process edges
for (var v = 0; v < inputG.length; v++) {
var nextV = inputG[v];
var vID = nextV.hasOwnProperty("id") ? nextV.id : nameToId[nextV.name];
var origID = vID;
var substitutedID = false;
if (newG.type[vID] == BaseGraph.TYPE.RELATIONSHIP && !relationshipHasExplicitChHub.hasOwnProperty(vID)) {
// replace edges from rel node by edges from childhub node
var childhubID = nameToId["_chhub_" + vID];
vID = childhubID;
substitutedID = true;
}
var maxChildEdgeWeight = 0;
if (nextV.outedges) {
for (var outE = 0; outE < nextV.outedges.length; outE++) {
var target = nextV.outedges[outE].to;
var targetID = nameToId[target] ? nameToId[target] : target; // can specify target either by name or ID
if (!newG.isValidId(targetID))
throw "Invalid input: invalid edge target (" + target + ")";
var weight = 1;
if (nextV.outedges[outE].hasOwnProperty('weight'))
weight = nextV.outedges[outE].weight;
if ( weight > maxChildEdgeWeight )
maxChildEdgeWeight = weight;
newG.addEdge( vID, targetID, weight );
}
}
if (substitutedID) {
newG.addEdge( origID, vID, maxChildEdgeWeight );
}
}
newG.validate();
return newG;
}
/* ===============================================================================================
*
* Creates and returns a BaseGraph from a text string in the PED/LINKAGE format.
*
* PED format:
* (from http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped)
* Family ID
* Individual ID
* Paternal ID
* Maternal ID
* Sex (1=male; 2=female; other=unknown)
* Phenotype
*
* Phenotype, by default, should be coded as:
* -9 missing
* 0 missing
* 1 unaffected
* 2 affected
*
* =================
*
* LINKAGE format:
* (from http://www.helsinki.fi/~tsjuntun/autogscan/pedigreefile.html)
*
* Column 1: Pedigree number
* Column 2: Individual ID number
* Column 3: ID of father
* Column 4: ID of mother
* Column 5: First offspring ID
* Column 6: Next paternal sibling ID
* Column 7: Next maternal sibling ID
* Column 8: Sex
* Column 9: Proband status (1=proband, higher numbers indicate doubled individuals formed
* in breaking loops. All other individuals have a 0 in this field.)
* Column 10+: Disease and marker phenotypes (as in the original pedigree file)
* ===============================================================================================
*/
PedigreeImport.initFromPED = function(inputText, acceptOtherPhenotypes, markEvaluated, saveIDAsExternalID, affectedCodeOne, disorderNames)
{
var inputLines = inputText.match(/[^\r\n]+/g);
if (inputLines.length == 0) throw "Unable to import: no data";
// autodetect if data is in pre-makeped or post-makeped format
var postMakeped = false;
if (inputLines[0].indexOf("Ped:") > 0 && inputLines[0].indexOf("Per:") > 0)
postMakeped = true;
var familyPrefix = "";
var newG = new BaseGraph();
var nameToId = {};
var phenotypeValues = {}; // set of all posible valuesin the phenotype column
var extendedPhenotypesFound = false;
// support both automatic and user-defined assignment of proband
var nextID = postMakeped ? 1 : 0;
// first pass: add all vertices and assign vertex IDs
for (var i = 0; i < inputLines.length; i++) {
inputLines[i] = inputLines[i].replace(/[^a-zA-Z0-9_.\-\s*]/g, ' ');
inputLines[i] = inputLines[i].replace(/^\s+|\s+$/g, ''); // trim()
var parts = inputLines[i].split(/\s+/);
//console.log("Parts: " + Helpers.stringifyObject(parts));
if (parts.length < 6 || (postMakeped && parts.length < 10)) {
throw "Input line has not enough columns: [" + inputLines[i] + "]";
}
if (familyPrefix == "") {
familyPrefix = parts[0];
} else {
if (parts[0] != familyPrefix) {
throw "Unsupported feature: multiple families detected within the same pedigree";
}
}
var pedID = parts[1];
if (nameToId.hasOwnProperty(pedID))
throw "Multiple persons with the same ID [" + pedID + "]";
var genderValue = postMakeped ? parts[7] : parts[4];
var gender = "U";
if (genderValue == 1)
gender = "M";
else if (genderValue == 2)
gender = "F";
var properties = {"gender": gender};
if (saveIDAsExternalID)
properties["externalID"] = pedID;
var useID = (postMakeped && parts[8] == 1) ? 0 : nextID++;
if (i == inputLines.length-1 && newG.v[0] === undefined) {
// last node and no node with id 0 yet
useID = 0;
}
var pedigreeID = newG._addVertex( useID, BaseGraph.TYPE.PERSON, properties, newG.defaultPersonNodeWidth );
nameToId[pedID] = pedigreeID;
var phenotype = postMakeped ? parts[9] : parts[5];
phenotypeValues[phenotype] = true;
if (acceptOtherPhenotypes && phenotype != "-9" && phenotype != "0" && phenotype != "1" && phenotype != "2") {
extendedPhenotypesFound = true;
}
}
// There are two popular schemes for the phenotype column (-9/0/1/2 or -9/0/1).
// Use the "standard" by default, unless directed to use the other one by the user
if (affectedCodeOne) {
if (extendedPhenotypesFound || phenotypeValues.hasOwnProperty("2")) {
throw "Phenotypes with codes other than 0 or 1 were found";
}
var affectedValues = { "1": true };
var missingValues = { "-9": true };
var unaffectedValues = { "0": true };
} else {
var affectedValues = { "2": true };
var missingValues = { "0": true, "-9": true };
var unaffectedValues = { "1": true };
}
if (!disorderNames) {
disorderNames = {};
if (extendedPhenotypesFound) {
for (var phenotype in phenotypeValues)
if (phenotypeValues.hasOwnProperty(phenotype)) {
if (phenotype != "-9" && phenotype != "0" && phenotype != "1") {
disorderNames[phenotype] = "affected (phenotype " + phenotype + ")";
affectedValues[phenotype] = true;
}
}
}
}
var defaultEdgeWeight = 1;
var relationshipTracker = new RelationshipTracker(newG, defaultEdgeWeight);
// second pass (once all vertex IDs are known): process edges
for (var i = 0; i < inputLines.length; i++) {
var parts = inputLines[i].split(/\s+/);
var thisPersonName = parts[1];
var id = nameToId[thisPersonName];
var phenotype = postMakeped ? parts[9] : parts[5];
if (affectedValues.hasOwnProperty(phenotype)) {
var disorder = disorderNames.hasOwnProperty(phenotype) ? disorderNames[phenotype] : "affected";
newG.properties[id]["carrierStatus"] = 'affected';
newG.properties[id]["disorders"] = [disorder];
if (markEvaluated)
newG.properties[id]["evaluated"] = true;
} else if (unaffectedValues.hasOwnProperty(phenotype)) {
newG.properties[id]["carrierStatus"] = '';
if (markEvaluated)
newG.properties[id]["evaluated"] = true;
} else if (!missingValues.hasOwnProperty(phenotype)) {
//treat all unsupported values as "unknown/no evaluation"
//throw "Individual with ID [" + thisPersonName + "] has unsupported phenotype value [" + phenotype + "]";
}
// check if parents are given for this individual; if at least one parent is given,
// check if the corresponding relationship has already been created. If not, create it. If yes,
// add an edge from childhub to this person
var fatherID = parts[2];
var motherID = parts[3];
if (fatherID == 0 && motherID == 0) continue;
// .PED supports specifying only mohter of father. Pedigree editor requires both (for now).
// So create a virtual parent in case one of the parents is missing
if (fatherID == 0) {
fatherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "M", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
fatherID = nameToId[fatherID];
if (newG.properties[fatherID].gender == "F")
throw "Unable to import pedigree: a person declared as female [id: " + fatherID + "] is also declared as being a father for [id: "+thisPersonName+"]";
}
if (motherID == 0) {
motherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "F", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
motherID = nameToId[motherID];
if (newG.properties[motherID].gender == "M")
throw "Unable to import pedigree: a person declared as male [id: " + motherID + "] is also declared as being a mother for [id: "+thisPersonName+"]";
}
// both motherID and fatherID are now given and represent valid existing nodes in the pedigree
// if there is a relationship between motherID and fatherID the corresponding childhub is returned
// if there is no relationship, a new one is created together with the chldhub
var chhubID = relationshipTracker.createOrGetChildhub(motherID, fatherID);
newG.addEdge( chhubID, id, defaultEdgeWeight );
}
PedigreeImport.validateBaseGraph(newG);
return newG;
}
/* ===============================================================================================
*
* Creates and returns a BaseGraph from a text string in the BOADICEA format.
*
* BOADICEA format:
* (from https://pluto.srl.cam.ac.uk/bd3/v3/docs/BWA_v3_user_guide.pdf)
*
* line1: BOADICEA import pedigree file format 2.0
* line2: column titles
* line3+: one patient per line, with values separated by spaces or tabs, as follows:
*
* FamID: Family/pedigree ID, character string (maximum 13 characters)
* Name: First name/ID of the family member, character string (maximum 8 characters)
* Target: The family member for whom the BOADICEA risk calculation is made, 1 = target for BOADICEA risk calculation, 0 = other family members. There must only be one BOADICEA target individual.
* IndivID: Unique ID of the family member, character string (maximum 7 characters)
* FathID: Unique ID of their father, 0 = no father, or character string (maximum 7 characters)
* MothID: Unique ID of their mother, 0 = unspecified, or character string (maximum 7 characters)
* Sex: M or F
* Twin: Identical twins, 0 = no identical twin, any non-zero character = twin.
* Dead: The current status of the family member, 0 = alive, 1 = dead
* Age: Age at last follow up, 0 = unspecified, integer = age at last follow up
* Yob: Year of birth, 0 = unspecified, or integer (consistent with Age if the person is alive)
* 1BrCa: Age at first breast cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected, age unknown)
* 2BrCa: Age at contralateral breast cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected, age unknown)
* OvCa: Age at ovarian cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected, age unknown)
* ProCa: Age at prostate cancer diagnosis 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected, age unknown)
* PanCa: Age at pancreatic cancer diagnosis 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected, age unknown)
* Gtest: Genetic test status, 0 = untested, S = mutation search, T = direct gene test
* Mutn: 0 = untested, N = no mutation, 1 = BRCA1 positive, 2 = BRCA2 positive, 3 = BRCA1 and BRCA2 positive
* Ashkn: 0 = not Ashkenazi, 1 = Ashkenazi
* ER: Estrogen receptor status, 0 = unspecified, N = negative, P = positive
* PR: Progestrogen receptor status, 0 = unspecified, N = negative, P = positive
* HER2: Human epidermal growth factor receptor 2 status, 0 = unspecified, N = negative, P = positive
* CK14: Cytokeratin 14 status, 0 = unspecified, N = negative, P = positive
* CK56: Cytokeratin 56 status, 0 = unspecified, N = negative, P = positive
* ===============================================================================================
*/
PedigreeImport.initFromBOADICEA = function(inputText, saveIDAsExternalID)
{
var inputLines = inputText.match(/[^\r\n]+/g);
if (inputLines.length <= 2) {
throw "Unable to import: no data";
}
if (inputLines[0].match(/^BOADICEA import pedigree file format 2/i) === null) {
throw "Unable to import: unsupported version of the BOADICEA format";
}
inputLines.splice(0,2); // remove 2 header lines
var familyPrefix = "";
var newG = new BaseGraph();
var nameToId = {};
var nextID = 1;
// first pass: add all vertices and assign vertex IDs
for (var i = 0; i < inputLines.length; i++) {
inputLines[i] = inputLines[i].replace(/[^a-zA-Z0-9_.\-\s*]/g, ' ');
inputLines[i] = inputLines[i].replace(/^\s+|\s+$/g, ''); // trim()
var parts = inputLines[i].split(/\s+/);
//console.log("Parts: " + Helpers.stringifyObject(parts));
if (parts.length < 24) {
throw "Input line has not enough columns: [" + inputLines[i] + "]";
}
if (familyPrefix == "") {
familyPrefix = parts[0];
} else {
if (parts[0] != familyPrefix) {
throw "Unsupported feature: multiple families detected within the same pedigree";
}
}
var extID = parts[3];
if (nameToId.hasOwnProperty(extID))
throw "Multiple persons with the same ID [" + extID + "]";
var genderValue = parts[6];
var gender = "M";
if (genderValue == "F") {
gender = "F";
}
var name = parts[1];
//if (Helpers.isInt(name)) {
// name = "";
//}
var properties = {"gender": gender, "fName": name};
if (saveIDAsExternalID) {
properties["externalID"] = extID;
}
var deadStatus = parts[8];
if (deadStatus == "1") {
properties["lifeStatus"] = "deceased";
}
var yob = parts[10];
if (yob != "0" && Helpers.isInt(yob)) {
properties["dob"] = {"decade": yob + "s", "year": parseInt(yob)};
}
var addCommentToProperties = function(properties, line) {
if (!line || line == "") return;
if (!properties.hasOwnProperty("comments")) {
properties["comments"] = line;
} else {
properties["comments"] += "\n" + line;
}
}
// TODO: handle all the columns and proper cancer handling
//
// 11: 1BrCa: Age at first breast cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected unknown)
// 12: 2BrCa: Age at contralateral breast cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected unknown)
// 13: OvCa: Age at ovarian cancer diagnosis, 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected unknown)
// 14: ProCa: Age at prostate cancer diagnosis 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected unknown)
// 15: PanCa: Age at pancreatic cancer diagnosis 0 = unaffected, integer = age at diagnosis, AU = unknown age at diagnosis (affected unknown)
var cancers = [ { "column": 11, "label": "Breast", "comment": ""},
{ "column": 12, "label": "Breast", "comment": "Contralateral breast cancer", "onlySetComment": true},
{ "column": 13, "label": "Ovarian", "comment": ""},
{ "column": 14, "label": "Prostate", "comment": ""},
{ "column": 15, "label": "Pancreatic", "comment": ""} ];
for (var c = 0; c < cancers.length; c++) {
var cancer = cancers[c];
if (!properties.hasOwnProperty("cancers")) {
properties["cancers"] = {};
}
var cancerData = {};
if (parts[cancer["column"]] == "0") {
if (!cancer.hasOwnProperty("onlySetComment") || !cancer.onlySetComment) {
cancerData["affected"] = false;
}
} else {
cancerData["affected"] = true;
var age = parts[cancer["column"]];
if (Helpers.isInt(age)) {
var numericAge = parseInt(age);
cancerData["numericAgeAtDiagnosis"] = numericAge;
if (numericAge > 100) {
age = "after_100";
}
cancerData["ageAtDiagnosis"] = age;
}
addCommentToProperties(properties, cancer["comment"]);
}
if (!cancer.onlySetComment) {
properties["cancers"][cancer.label] = cancerData;
}
}
// Mutn: 0 = untested, N = no mutation, 1 = BRCA1 positive, 2 = BRCA2 positive, 3 = BRCA1 and BRCA2 positive
var mutations = parts[17];
if (mutations == "1" || mutations == "2" || mutations == "3") {
properties["candidateGenes"] = [];
if (mutations == 1 || mutations == 3) {
properties["candidateGenes"].push("BRCA1");
}
if (mutations == 2 || mutations == 3) {
properties["candidateGenes"].push("BRCA2");
}
} else if (mutations == "N") {
addCommentToProperties(properties, "BRCA tested: no mutations");
}
var ashkenazi = parts[18];
if (ashkenazi != "0") {
properties["ethnicities"] = ["Ashkenazi Jews"];
}
var proband = (parts[2] == 1);
var useID = proband ? 0 : nextID++;
if (i == inputLines.length-1 && newG.v[0] === undefined) {
// last node and no proband yet
useID = 0;
}
var pedigreeID = newG._addVertex( useID, BaseGraph.TYPE.PERSON, properties, newG.defaultPersonNodeWidth );
nameToId[extID] = pedigreeID;
}
var defaultEdgeWeight = 1;
var relationshipTracker = new RelationshipTracker(newG, defaultEdgeWeight);
// second pass (once all vertex IDs are known): process edges
for (var i = 0; i < inputLines.length; i++) {
var parts = inputLines[i].split(/\s+/);
var extID = parts[3];
var id = nameToId[extID];
// check if parents are given for this individual; if at least one parent is given,
// check if the corresponding relationship has already been created. If not, create it. If yes,
// add an edge from childhub to this person
var fatherID = parts[4];
var motherID = parts[5];
if (fatherID == 0 && motherID == 0) {
continue;
}
// .PED supports specifying only mother or father. Pedigree editor requires both (for now).
// So create a virtual parent in case one of the parents is missing
if (fatherID == 0) {
fatherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "M", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
fatherID = nameToId[fatherID];
if (newG.properties[fatherID].gender == "F") {
throw "Unable to import pedigree: a person declared as female [id: " + fatherID + "] is also declared as being a father for [id: "+extID+"]";
}
}
if (motherID == 0) {
motherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "F", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
motherID = nameToId[motherID];
if (newG.properties[motherID].gender == "M") {
throw "Unable to import pedigree: a person declared as male [id: " + motherID + "] is also declared as being a mother for [id: "+extID+"]";
}
}
// both motherID and fatherID are now given and represent valid existing nodes in the pedigree
// if there is a relationship between motherID and fatherID the corresponding childhub is returned
// if there is no relationship, a new one is created together with the childhub
var chhubID = relationshipTracker.createOrGetChildhub(motherID, fatherID);
newG.addEdge( chhubID, id, defaultEdgeWeight );
}
PedigreeImport.validateBaseGraph(newG);
return newG;
}
/* ===============================================================================================
*
* Validates the generated basegraph and throws one of the following exceptions:
*
* 1) "Unsupported pedigree: some components of the imported pedigree are disconnected from each other"
* 2) "Unable to import pedigree"
*
* The method is a wrapper around the internal vlaidate method, which may throw many exceptions
* which change form version to version
*
* ===============================================================================================
*/
PedigreeImport.validateBaseGraph = function(newG)
{
try {
newG.validate();
} catch( err) {
if (err.indexOf("disconnected component")) {
throw "Unsupported pedigree: some components of the imported pedigree are disconnected from each other";
} else {
throw "Unable to import pedigree";
}
}
}
/* ===============================================================================================
*
* Creates and returns a BaseGraph from a text string in the "simple JSON" format.
*
* Simple JSON format: an array of objects, each object representing one person, e.g.:
*
* [ { "name": "f11", "sex": "female", "lifeStatus": "deceased" },
* { "name": "m11", "sex": "male" },
* { "name": "f12", "sex": "female", "disorders": [603235, "142763", "custom disorder"] },
* { "name": "m12", "sex": "male" },
* { "name": "m21", "sex": "male", "mother": "f11", "father": "m11" },
* { "name": "f21", "sex": "female", "mother": "f12", "father": "m12" },
* { "name": "ch1", "sex": "female", "mother": "f21", "father": "m21", "disorders": [603235], "proband": true } ]
*
* Supported properties:
* - "id": string or number (default: none). If two nodes with the same ID are found an error is reported.
* If present, this id is used only for the purpose of linking nodes to each other and is not recorded
* in the imported pedigree. Use "externalId" if an ID should be stored
* - "proband": boolean (default: true for the first object, false for all other objects. If another object
* is explicitly indicated as a proband, the firs tobject also defaults to false.
* If more than one node is indicated as a proband only the first one is considered ot be one)
* - "name" or "firstName": string (default: none). if both are defined "firstName" is used as "first name" and name is used for mother/father reference checks only
* - "lastName": string (default: none)
* - "lastNameAtBirth": string (default: none)
* - "comments": string (default: none)
* - "externalId": string (default: none)
* - "sex": one of "male" or "m", "female" or "f", "other" or "o", "unknown" or "u" (default: "unknown")
* - "twinGroup": integer. All children of the sam eparents with the same twin group are considered twins. (fefault: none)
* - "monozygotic": boolean. (only applicable for twins)
* - "adoptedIn": boolean (default: false)
* - "evaluated": boolean (default: false)
* - "birthDate": string (default: none)
* - "deathDate": string (default: none)
* - "nodeNumber": string (default: none) pedigree node number as of last renumbering
* - "lostContact": boolean (default: false) "false" if proband lost contact with the given individual
* - "numPersons": integer. When present and not 0 this individual is treated as a "person group"
* - "lifeStatus": one of {"alive", "deceased", "aborted", "miscarriage", "stillborn", "unborn"}.
* (default: "alive". If death date is given status defaults to "deceased" and overwrites
* the explicitly given status if it were "alive")
* - "disorders": array of strings or integers (a string representing an integer is considered to be an integer), integers treated as OMIM IDs. (default: none)
* - "carrierStatus": one of {'', 'carrier', 'affected', 'presymptomatic'}
* (default: if a disorder is given, default is 'affected', otherwise: none.
* also, if a disorder is given and status is explicitly '', it is automatically changed to 'affected')
* - "mother" and "father": string, a reference to another node given in the JSON.
* First a match versus an existing ID is checked, if not found a check against "externalId",
* if not found a check against "name" and finally "firstName".
* If one of the parents is given and the other one is not a virtual new node is created
*
* Each node should have at least one of {"id", "externalId", "name", "firstName"} defined.
* ===============================================================================================
*/
PedigreeImport.initFromSimpleJSON = function(inputText)
{
try {
var inputArray = JSON.parse(inputText);
} catch( err) {
throw "Unable to import pedigree: input is not a valid JSON string " + err;
}
if (typeof inputArray != 'object' || Object.prototype.toString.call(inputArray) !== '[object Array]') {
throw "Unable to import pedigree: JSON does not represent an array of objects";
}
if (inputArray.length == 0) {
throw "Unable to import pedigree: input is empty";
}
var newG = new BaseGraph();
var nameToID = {};
var externalIDToID = {};
var ambiguousReferences = {};
var hasID = {}
// first pass: add all vertices and assign vertex IDs
for (var i = 0; i < inputArray.length; i++) {
var nextPerson = inputArray[i];
if (typeof nextPerson != 'object') {
throw "Unable to import pedigree: JSON does not represent an array of objects";
}
if ( !nextPerson.hasOwnProperty("id") && !nextPerson.hasOwnProperty("name") &&
!nextPerson.hasOwnProperty("firstName") && !nextPerson.hasOwnProperty("externalId") ) {
throw "Unable to import pedigree: a node with no ID or name is found";
}
var pedigreeID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {}, newG.defaultPersonNodeWidth );
var properties = {};
properties["gender"] = "U"; // each person should have some gender set
for (var property in nextPerson) {
if (nextPerson.hasOwnProperty(property)) {
var value = nextPerson[property];
var property = property.toLowerCase();
if (property == "mother" || property == "father") // those are processed on the second pass
continue;
if (property == "sex") {
var genderString = value.toLowerCase();
if( genderString == "female" || genderString == "f")
properties["gender"] = "F";
else if( genderString == "male" || genderString == "m")
properties["gender"] = "M";
else if( genderString == "other" || genderString == "o")
properties["gender"] = "O";
} else if (property == "id") {
if (externalIDToID.hasOwnProperty(value)) {
throw "Unable to import pedigree: multiple persons with the same ID [" + value + "]";
}
if (nameToID.hasOwnProperty(value) && nameToID[value] != pedigreeID) {
delete nameToID[value];
ambiguousReferences[value] = true;
} else {
externalIDToID[value] = pedigreeID;
hasID[pedigreeID] = true;
}
} else if (property == "name" || property == "firstname" ) {
properties["fName"] = value;
if (nameToID.hasOwnProperty(value) && nameToID[value] != pedigreeID) {
// multiple nodes have this first name
delete nameToID[value];
ambiguousReferences[value] = true;
} else if (externalIDToID.hasOwnProperty(value) && externalIDToID[value] != pedigreeID) {
// some other node has this name as an ID
delete externalIDToID[value];
ambiguousReferences[value] = true;
} else {
nameToID[value] = pedigreeID;
}
} else {
var processed = PedigreeImport.convertProperty(property, value);
if (processed !== null) {
// supported property
properties[processed.propertyName] = processed.value;
}
}
}
}
// only use externalID if id is not present
if (nextPerson.hasOwnProperty("externalId") && !hasID.hasOwnProperty(pedigreeID)) {
externalIDToID[nextPerson.externalId] = pedigreeID;
hasID[pedigreeID] = true;
}
newG.properties[pedigreeID] = properties;
}
var getPersonID = function(person) {
if (person.hasOwnProperty("id"))
return externalIDToID[person.id];
if (person.hasOwnProperty("firstName"))
return nameToID[person.firstName];
if (person.hasOwnProperty("name"))
return nameToID[person.name];
};
var findReferencedPerson = function(reference, refType) {
if (ambiguousReferences.hasOwnProperty(reference))
throw "Unable to import pedigree: ambiguous reference to [" + reference + "]";
if (externalIDToID.hasOwnProperty(reference))
return externalIDToID[reference];
if (nameToID.hasOwnProperty(reference))
return nameToID[reference];
throw "Unable to import pedigree: [" + reference + "] is not a valid " + refType + " reference (does not correspond to a name or an ID of another person)";
};
var defaultEdgeWeight = 1;
var relationshipTracker = new RelationshipTracker(newG, defaultEdgeWeight);
// second pass (once all vertex IDs are known): process parents/children & add edges
for (var i = 0; i < inputArray.length; i++) {
var nextPerson = inputArray[i];
var personID = getPersonID(nextPerson);
var motherLink = nextPerson.hasOwnProperty("mother") ? nextPerson["mother"] : null;
var fatherLink = nextPerson.hasOwnProperty("father") ? nextPerson["father"] : null;
if (motherLink == null && fatherLink == null)
continue;
// create a virtual parent in case one of the parents is missing
if (fatherLink == null) {
var fatherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "M", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
var fatherID = findReferencedPerson(fatherLink, "father");
if (newG.properties[fatherID].gender == "F")
throw "Unable to import pedigree: a person declared as female is also declared as being a father ("+fatherLink+")";
}
if (motherLink == null) {
var motherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "F", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
var motherID = findReferencedPerson(motherLink, "mother");
if (newG.properties[motherID].gender == "M")
throw "Unable to import pedigree: a person declared as male is also declared as being a mother ("+motherLink+")";
}
if (fatherID == personID || motherID == personID)
throw "Unable to import pedigree: a person is declared to be his or hew own parent";
// both motherID and fatherID are now given and represent valid existing nodes in the pedigree
// if there is a relationship between motherID and fatherID the corresponding childhub is returned
// if there is no relationship, a new one is created together with the chldhub
var chhubID = relationshipTracker.createOrGetChildhub(motherID, fatherID);
newG.addEdge( chhubID, personID, defaultEdgeWeight );
}
PedigreeImport.validateBaseGraph(newG);
return newG;
}
/* ===============================================================================================
*
* GEDCOM file format: http://en.wikipedia.org/wiki/GEDCOM
*
* Supported individual (INDI) properties: NAME, SEX, NOTE, ADOP, BIRT, DEAT and DATE
* - Non-standard "_GENSTAT" is partially supported (for compatibility with Cyrillic v3)
* - Non-standard "_MAIDEN", "_INFO" and "_COMMENT" are supported (for compatibility with Cyrillic v3)
* - FAMS is ignored, instead 0-level FAM families are parsed/processed
* - only the first instance is used if the same property is given multiple times (e.g. multiple BIRT records)
*
* Suported family (FAM) properties: HUSB, WIFE, CHIL
*
* Note: reverse-engineered _GENSTAT values: the following symbols, in any position, mean:
* Disorder status:
* AFFECTED: "O"
* HEARSAY: "ยฌ" (hearsay graphic == pre-symptomatic graphic)
* UNTESTED: "E"
* "carrier" and "examined" does not seem to be exported to GEDCOM or CSV
* Other:
* PROBAND: "C" (may be more than one)
* STILLBORN: "K"
* INFERTILE: "M"
* ===============================================================================================
*/
PedigreeImport.initFromGEDCOM = function(inputText, markEvaluated, saveIDAsExternalID)
{
var inputLines = inputText.match(/[^\r\n]+/g);
if (inputLines.length == 0) throw "Unable to import: no data";
var convertToObject = function(inputLines) {
/* converts GEDCOM text into an object, where 0-level items are stored as "header", "individuals" and "families"
* properties, and all items below are arrays of objects, e.g. an array of objects representing each individual.
*
* Each next-level keyword is a key in the object, and the associated value is an array of objects, each
* object representing one encountered instance of the keyword (designed this way as ther emay be more than one
* keyword with the same nem, e.g. multiple alternative DATEs for an event, or multiple CHILdren in a family)
*
* The value of the keyword itself (if any) is stored under the "value" key. In the example below the
* all "DATA" keywords have no values, while all TEXT and DATE have some values assigned, and only some
* EVEN keywords have a value.
*
* 0 @I1@ INDI
* 1 EVEN AAA
* 2 DATE 10 JAN 1800
* 2 SOUR @S1@
* 3 DATA
* 4 TEXT ABC
* 3 DATA
* 4 TEXT DEF
* 3 NOTE DEF
* 3 ZZZZ 2
* 3 ZZZZ 3
* 1 EVEN
* 2 DATE 1800
* 2 SOUR @S2@
* 1 EVEN BBB
* 2 DATE 1900
* 0 @I2@ INDI
* 1 ...
*
* is stranslated to:
* // level
* // 1 2 3 4
* [{id: '@I1@'
* EVEN: [
* {value: 'AAA',
* DATE: [{value: '10 JAN 1800'}],
* SOUR: [{value: '@S1@',
* DATA: [{TEXT: [{value: 'ABC'}]}, {TEXT: [{value: 'DEF'}]}],
* NOTE: [{value: 'DEF'}],
* ZZZZ: [{value: '2'}, {value: '3'}]
* }
* ]
* },
* {DATE: [{value: '1800'}],
* SOUR: [{value: '@S2@'}]
* },
* {value: 'BBB',
* DATE: [{value: '1900'}]
* }
* ]
* },
* {id: '@I2@' ...}
* ]
*/
var obj = { "header": {}, "individuals": [], "families": [] };
var currentObject = [];
for (var i = 0; i < inputLines.length; i++) {
var nextLine = inputLines[i].replace(/[^a-zA-Z0-9.\@\/\-\s*]/g, ' ').replace(/^\s+|\s+$/g, ''); // sanitize + trim
var words = inputLines[i].split(/\s+/);
var parts = words.splice(0,2);
parts.push(words.join(' '));
// now parts[0] = level, parts[1] = record type, parts[2] = value, if any
var level = parseInt(parts[0]);
currentObject.splice(level);
if (level == 0) {
if (parts[1] == "HEAD") {
currentObject[0] = obj.header;
} else if (parts[1][0] == '@' && parts[2] == "INDI") {
obj.individuals.push({});
currentObject[0] = obj.individuals[obj.individuals.length - 1];
currentObject[0]["id"] = parts[1];
} else if (parts[1][0] == '@' && parts[2] == "FAM") {
obj.families.push({});
currentObject[0] = obj.families[obj.families.length - 1];
currentObject[0]["id"] = parts[1];
} else {
currentObject[0] = {};
}
} else {
if (currentObject.length < level - 1) {
throw "Unable to import GEDCOM: a multi-level jump detected in line: [" + inputLines[i] + "]";
}
if (!currentObject[level-1].hasOwnProperty(parts[1]))
currentObject[level-1][parts[1]] = []; // array of values
if (currentObject.length < level + 1) {
currentObject[level] = {};
currentObject[level - 1][parts[1]].push(currentObject[level]);
}
if (parts[2] != "") {
currentObject[level]["value"] = parts[2];
}
}
currentLevel = parts[0];
}
return obj;
};
var gedcom = convertToObject(inputLines);
console.log("GEDCOM object: " + Helpers.stringifyObject(gedcom));
if (gedcom.header.hasOwnProperty("GEDC")) {
if (gedcom.header.GEDC.hasOwnProperty("VERS")) {
if (gedcom.header.GEDC.VERS != "5.5" && gedcom.header.GEDC.VERS != "5.5.1") {
alert("Unsupported GEDCOM version detected: [" + gedcom.header.GEDC.VERS + "]. "+
"Import will continue but the correctness is not guaranteed. Supportede versions are 5.5 and 5.5.1");
}
}
}
if (gedcom.individuals.length == 0) {
throw "Unable to create a pedigree from GEDCOM: no individuals are defined in the import data";
}
var newG = new BaseGraph();
var externalIDToID = {};
// first pass: add all vertices and assign vertex IDs
for (var i = 0; i < gedcom.individuals.length; i++) {
var nextPerson = gedcom.individuals[i];
var pedigreeID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {}, newG.defaultPersonNodeWidth );
externalIDToID[nextPerson.id] = pedigreeID;
var cleanedID = nextPerson.id.replace(/@/g, '')
var properties = saveIDAsExternalID ? {"externalID": cleanedID} : {};
properties["gender"] = "U"; // each person should have some gender set
var getFirstValue = function(obj) {
//if (Object.prototype.toString.call(obj) === '[object Array]')
return obj[0].value;
}
var parseDate = function(gedcomDate) {
gedcomDate = gedcomDate[0].value;
// treat possible date modifiers
// "ABT" - "about"
// "EST" - "estimated"
// "BEF" - "before"
// "AFT" - "after"
// "BET ... AND ..." = "between ... and ..."
// for all of the above the date itself is used as the date; for the "between" the first date is used.
// TODO: add support for importing approximate dates, since those are now supported by PedigreeDate object
gedcomDate = gedcomDate.replace(/^(\s*)ABT(\s*)/,"");
gedcomDate = gedcomDate.replace(/^(\s*)EST(\s*)/,"");
gedcomDate = gedcomDate.replace(/^(\s*)BEF(\s*)/,"");
gedcomDate = gedcomDate.replace(/^(\s*)AFT(\s*)/,"");
var getBetweenDate = /^\s*BET\s+(.+)\s+AND.*/;
var match = getBetweenDate.exec(gedcomDate);
if (match != null) {
gedcomDate = match[1];
}
if (gedcomDate == "?") return null;
// TODO: can handle approx. dates (i.e. "ABT" and "EST") better using new Pedigree fuzzy dates
// conversion below would convert "ABT JAN 1999" to "JAN 1 1999" instead of fuzzy date "Jan 1999"
var timestamp=Date.parse(gedcomDate)
if (isNaN(timestamp)==false) {
return new PedigreeDate(new Date(timestamp));
}
return null;
};
for (var property in nextPerson) {
if (nextPerson.hasOwnProperty(property)) {
if (property == "SEX") {
var genderString = getFirstValue(nextPerson[property])[0].toLowerCase(); // use first character only
if( genderString == "female" || genderString == "f")
properties["gender"] = "F";
else if( genderString == "male" || genderString == "m")
properties["gender"] = "M";
} else if (property == "BIRT") {
if (nextPerson[property][0].hasOwnProperty("DATE")) {
var date = parseDate(nextPerson[property][0]["DATE"]);
if (date !== null) {
properties["dob"] = new PedigreeDate(date).getSimpleObject()
}
}
} else if (property == "DEAT") {
if (properties.hasOwnProperty("lifeStatus") && properties["lifeStatus"] == "stillborn")
continue;
properties["lifeStatus"] = "deceased";
if (nextPerson[property][0].hasOwnProperty("DATE")) {
var date = parseDate(nextPerson[property][0]["DATE"]);
if (date !== null) {
properties["dod"] = new PedigreeDate(date).getSimpleObject();
}
}
} else if (property == "ADOP") {
properties["adoptedStatus"] = "adoptedIn";
} else if (property == "_INFO") {
if (!properties.hasOwnProperty("comments"))
properties["comments"] = "";
properties["comments"] += "(Info: " + getFirstValue(nextPerson[property]) + ")\n";
} else if (property == "NOTE" || property == "_COMMENT") {
if (!properties.hasOwnProperty("comments"))
properties["comments"] = "";
properties["comments"] += getFirstValue(nextPerson[property]) + "\n";
if (nextPerson[property][0].hasOwnProperty("CONT")) {
var more = nextPerson[property][0]["CONT"];
for (var cc = 0; cc < more.length; cc++) {
properties["comments"] += more[cc].value + "\n";
}
}
} else if (property == "NAME") {
var nameParts = getFirstValue(nextPerson[property]).split('/');
var firstName = nameParts[0].replace(/^\s+|\s+$/g, '');
var lastName = nameParts.length > 1 ? nameParts[1].replace(/^\s+|\s+$/g, '') : "";
properties["fName"] = firstName;
if (lastName != "")
properties["lName"] = lastName;
} else if (property == "_MAIDEN") {
var nameParts = getFirstValue(nextPerson[property]).split('/');
var firstName = nameParts[0].replace(/^\s+|\s+$/g, '');
var lastName = nameParts.length > 1 ? nameParts[1].replace(/^\s+|\s+$/g, '') : "";
properties["lNameAtB"] = firstName;
if (lastName != "")
properties["lNameAtB"] += " " + lastName;
} else if (property == "_GENSTAT") {
var props = getFirstValue(nextPerson[property]).split('');
for (var p = 0; p < props.length; p++) {
var value = props[p];
if (value.charCodeAt(0) == 65533 || value.charCodeAt(0) == 172) {
// one value is obtained via copy-paste, another via file upload
value = "HEARSAY";
}
switch(value) {
case "O":
properties["carrierStatus"] = 'affected';
properties["disorders"] = ['affected'];
if (markEvaluated)
properties["evaluated"] = true;
break;
case "HEARSAY":
properties["carrierStatus"] = 'presymptomatic'; // the closest graphic to cyrillic's "hearsay"
if (markEvaluated)
properties["evaluated"] = true;
break;
case "K":
properties["lifeStatus"] = "stillborn";
break;
case "M":
properties["childlessStatus"] = "infertile";
break;
case "E":
if (!properties.hasOwnProperty("comments")) {
properties["comments"] = "(untested)";
}
else {
properties["comments"] = "(untested)\n" + properties["comments"];
}
break;
case "O":
// TODO: proband
break;
}
}
}
}
}
if (properties.hasOwnProperty("comments")) {
// remove trailing newlines and/or empty comments
properties.comments = properties.comments.replace(/^\s+|\s+$/g, '');
if (properties.comments == "")
delete properties.comments;
}
newG.properties[pedigreeID] = properties;
}
var defaultEdgeWeight = 1;
var relationshipTracker = new RelationshipTracker(newG, defaultEdgeWeight);
// second pass (once all vertex IDs are known): process families & add edges
for (var i = 0; i < gedcom.families.length; i++) {
var nextFamily = gedcom.families[i];
var motherLink = nextFamily.hasOwnProperty("WIFE") ? getFirstValue(nextFamily["WIFE"]) : null;
var fatherLink = nextFamily.hasOwnProperty("HUSB") ? getFirstValue(nextFamily["HUSB"]) : null;
// create a virtual parent in case one of the parents is missing
if (fatherLink == null) {
var fatherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "M", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
var fatherID = externalIDToID[fatherLink];
if (newG.properties[fatherID].gender == "F")
throw "Unable to import pedigree: a person declared as female is also declared as being a father ("+fatherLink+")";
}
if (motherLink == null) {
var motherID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "F", "comments": "unknown"}, newG.defaultPersonNodeWidth );
} else {
var motherID = externalIDToID[motherLink];
if (newG.properties[motherID].gender == "M")
throw "Unable to import pedigree: a person declared as male is also declared as being a mother ("+motherLink+")";
}
// both motherID and fatherID are now given and represent valid existing nodes in the pedigree
// if there is a relationship between motherID and fatherID the corresponding childhub is returned
// if there is no relationship, a new one is created together with the chldhub
var chhubID = relationshipTracker.createOrGetChildhub(motherID, fatherID);
var children = nextFamily.hasOwnProperty("CHIL") ? nextFamily["CHIL"] : null;
if (children == null) {
// create a virtual child
var childID = newG._addVertex( null, BaseGraph.TYPE.PERSON, {"gender": "U", "placeholder": true}, newG.defaultPersonNodeWidth );
externalIDToID[childID] = childID;
children = [{"value": childID}];
// TODO: add "infertile by choice" property to the relationship
}
for (var j = 0; j < children.length; j++) {
var externalID = children[j].value;
var childID = externalIDToID.hasOwnProperty(externalID) ? externalIDToID[externalID] : null;
if (childID == null) {
throw "Unable to import pedigree: child link does not point to an existing individual: [" + externalID + "]";
}
newG.addEdge( chhubID, childID, defaultEdgeWeight );
}
}
PedigreeImport.validateBaseGraph(newG);
return newG;
}
// ===============================================================================================
// TODO: convert internal properties to match public names and rename this to "supportedProperties"
PedigreeImport.JSONToInternalPropertyMapping = {
"proband": "proband",
"lastname": "lName",
"lastnameatbirth": "lNameAtB",
"comments": "comments",
"twingroup": "twinGroup",
"monozygotic": "monozygotic",
"adoptedstatus": "adoptedStatus",
"evaluated": "evaluated",
"birthdate": "dob",
"deathdate": "dod",
"gestationage": "gestationAge",
"lifestatus": "lifeStatus",
"disorders": "disorders",
"hpoterms": "hpoTerms",
"candidategenes": "candidateGenes",
"ethnicities": "ethnicities",
"carrierstatus": "carrierStatus",
"externalid": "externalID",
"numpersons": "numPersons",
"lostcontact": "lostContact",
"nodenumber": "nodeNumber",
"cancers": "cancers"
};
/*
* Converts property name from external JSON format to internal - also helps to
* support aliases for some terms and weed out unsupported terms.
*/
PedigreeImport.convertProperty = function(externalPropertyName, value) {
if (!PedigreeImport.JSONToInternalPropertyMapping.hasOwnProperty(externalPropertyName))
return null;
var internalPropertyName = PedigreeImport.JSONToInternalPropertyMapping[externalPropertyName];
return {"propertyName": internalPropertyName, "value": value };
}
//===============================================================================================
/*
* Helper class which keeps track of relationships already seen in pedigree being imported
*/
RelationshipTracker = function (newG, defaultEdgeWeight) {
this.newG = newG;
this.defaultEdgeWeight = defaultEdgeWeight;
this.relationships = {};
this.relChildHubs = {};
};
RelationshipTracker.prototype = {
// if there is a relationship between motherID and fatherID the corresponding childhub is returned
// if there is no relationship, a new one is created together with the chldhub
createOrGetChildhub: function (motherID, fatherID)
{
// both motherID and fatherID are now given. Check if there is a relationship between the two of them
if (this.relationships.hasOwnProperty(motherID) && this.relationships[motherID].hasOwnProperty(fatherID)) {
var relID = this.relationships[motherID][fatherID];
var chhubID = this.relChildHubs[relID];
} else {
if (this.relationships[motherID] === undefined) this.relationships[motherID] = {};
if (this.relationships[fatherID] === undefined) this.relationships[fatherID] = {};
var relID = this.newG._addVertex( null, BaseGraph.TYPE.RELATIONSHIP, {}, this.newG.defaultNonPersonNodeWidth );
var chhubID = this.newG._addVertex( null, BaseGraph.TYPE.CHILDHUB, {}, this.newG.defaultNonPersonNodeWidth );
this.newG.addEdge( relID, chhubID, this.defaultEdgeWeight );
this.newG.addEdge( motherID, relID, this.defaultEdgeWeight );
this.newG.addEdge( fatherID, relID, this.defaultEdgeWeight );
this.relationships[motherID][fatherID] = relID;
this.relationships[fatherID][motherID] = relID;
this.relChildHubs[relID] = chhubID;
}
return chhubID;
}
};
return PedigreeImport;
}); | danielpgross/phenotips | components/pedigree/resources/src/main/resources/pedigree/model/import.js | JavaScript | agpl-3.0 | 62,837 |
var img = document.getElementById("slice");
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.height = img.height * Math.sqrt(2);
canvas.width = img.width * Math.sqrt(2);
var cutCanvas = document.getElementById("cut");
var cutContext = cutCanvas.getContext("2d");
cutCanvas.height = 1;
cutCanvas.width = img.width * Math.sqrt(2);
context.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var cutImageData = cutContext.getImageData(0, 0, cutCanvas.width, cutCanvas.height);
var angle = 0;
var rayLength = img.width * Math.sqrt(2);
var samplingRate = 1;
var sampleCount = samplingRate*rayLength;
var sampleDistance = rayLength/sampleCount;
context.fillStyle = "#00FF00";
context.strokeStyle = "#FF0000";
console.log(imageData);
draw();
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2);
var increment = [Math.sin(angle)*sampleDistance, Math.cos(angle)*sampleDistance];
context.beginPath();
context.moveTo(
Math.sin(angle)*rayLength/2-Math.cos(angle)*rayLength/2 + rayLength/2,
Math.cos(angle)*rayLength/2+Math.sin(angle)*rayLength/2 + rayLength/2
);
context.lineTo(
Math.sin(angle)*rayLength/2+Math.cos(angle)*rayLength/2 + rayLength/2,
Math.cos(angle)*rayLength/2-Math.sin(angle)*rayLength/2 + rayLength/2
);
context.stroke();
for(var s = 0; s < sampleCount; s++){
var xPos = s;
var pos = [
Math.sin(angle)*rayLength/2 + Math.cos(angle)*((xPos-rayLength/2)/rayLength)*rayLength + rayLength/2,
Math.cos(angle)*rayLength/2 - Math.sin(angle)*((xPos-rayLength/2)/rayLength)*rayLength + rayLength/2
];
var max = 0;
for(var i = 0; i < sampleCount; i++){
//context.fillRect(Math.round(pos[0]), Math.round(pos[1]), 1, 1);
var value = getColorAtCoord(Math.round(pos[0]), Math.round(pos[1]), imageData);
max = Math.max(max, value[0]);
pos[0] -= increment[0];
pos[1] -= increment[1];
}
cutImageData.data[s*4+0] = max;
cutImageData.data[s*4+1] = max;
cutImageData.data[s*4+2] = max;
cutImageData.data[s*4+3] = 255;
}
cutContext.putImageData(cutImageData, 0, 0);
angle += 0.01;
setTimeout(draw, 16);
}
function getColorAtCoord(x, y, imageData){
if(x<0 || x>=imageData.width || y<0 || y>=imageData.height){
return [0, 0, 0, 0];
}
var pos = (x + y*imageData.width)*4;
return [
imageData.data[pos+0]
,imageData.data[pos+1]
,imageData.data[pos+2]
,imageData.data[pos+3]
];
}
| RolandR/VolumeRayCasting | planeDemo/lazyRaycasting.js | JavaScript | agpl-3.0 | 2,632 |
/* eslint-disable no-invalid-this */
import toggleNav from "src/decidim/admin/toggle_nav"
import createSortList from "src/decidim/admin/sort_list.component"
import createQuillEditor from "src/decidim/editor"
import formDatePicker from "src/decidim/form_datepicker"
import DataPicker from "src/decidim/data_picker"
import FormFilterComponent from "src/decidim/form_filter"
import Configuration from "src/decidim/configuration"
import InputCharacterCounter from "src/decidim/input_character_counter"
import managedUsersForm from "src/decidim/admin/managed_users"
window.Decidim = window.Decidim || {};
window.Decidim.managedUsersForm = managedUsersForm
window.Decidim.config = new Configuration()
window.Decidim.InputCharacterCounter = InputCharacterCounter;
$(() => {
window.theDataPicker = new DataPicker($(".data-picker"));
$(document).foundation();
toggleNav();
createSortList("#steps tbody", {
placeholder: $('<tr style="border-style: dashed; border-color: #000"><td colspan="4"> </td></tr>')[0],
onSortUpdate: ($children) => {
const sortUrl = $("#steps tbody").data("sort-url")
const order = $children.map((index, child) => $(child).data("id")).toArray();
$.ajax({
method: "POST",
url: sortUrl,
contentType: "application/json",
data: JSON.stringify({ items_ids: order }) }, // eslint-disable-line camelcase
);
}
})
formDatePicker();
$(".editor-container").each((_idx, container) => {
createQuillEditor(container);
});
$("form.new_filter").each(function () {
const formFilter = new FormFilterComponent($(this));
formFilter.mountComponent();
})
});
| decidim/decidim | decidim-admin/app/packs/src/decidim/admin/application.js | JavaScript | agpl-3.0 | 1,668 |
(function() {
this.Blazon.index.login = {
init: function() {
$('a.login').click(function() {
var params;
params = $('form[name=login]').serializeObject();
Blazon.post('/user/auth/', params, function(response) {
if (response.status === 'OK') {
window.location.href = '/';
} else {
if (response.message != null) {
alert(response.message);
}
console.log(response.message);
}
});
});
}
};
this.Blazon.index.login.init();
}).call(this);
| evanhuang8/Blazon | sponsorship/static/js/index/login.js | JavaScript | agpl-3.0 | 584 |
/**
* Copyright 2014, 2015 Netsend.
*
* This file is part of Mastersync.
*
* Mastersync is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* Mastersync is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along
* with Mastersync. If not, see <https://www.gnu.org/licenses/>.
*/
'use strict';
var EE = require('events').EventEmitter;
var util = require('util');
var crc32 = require('crc-32');
/**
* ConcatMongoStream
*
* Concatenate two mongodb collection streams.
*
* @param {Array} colls array of mongodb collections
* @param {Object} [opts] object containing configurable parameters
* @param {Array} [args] object containing arguments for mongodb.Cursor
*
* opts:
* log {Object, default console} log object that contains debug2, debug, info,
* notice, warning, err, crit and emerg functions. Uses console.log and
* console.error by default.
*
* args:
* all mongodb.Collection.find arguments
* args[1].sortIndex {column name} whether to sort on a specific column for the
* collection part (to support using an index).
*/
function ConcatMongoStream(colls, opts, args) {
if (!Array.isArray(colls)) { throw new TypeError('colls must be an array'); }
if (colls.length < 1) { throw new TypeError('colls must contain at least one element'); }
opts = opts || {};
if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
if (typeof opts.log !== 'undefined' && typeof opts.log !== 'object') { throw new TypeError('opts.log must be an object'); }
this._log = opts.log || {
emerg: console.error,
alert: console.error,
crit: console.error,
err: console.error,
warning: console.log,
notice: console.log,
info: console.log,
debug: console.log,
debug2: console.log
};
this._opts = opts;
var that = this;
if (!colls.every(function(item, i) {
if (typeof item === 'object') {
return true;
}
that._log.err('cms item %d is not an object: "%s"', i, item);
return false;
})) {
throw new TypeError('colls must only contain objects');
}
EE.call(this);
this._colls = colls;
this._args = args || [];
// remove last parameter from arguments if it is a callback
if (typeof this._args[this._args.length - 1] === 'function') {
this._args = Array.prototype.slice.call(this._args, 0, this._args.length - 1);
}
// try to get a sort from opts.args
this._sortDsc = ConcatMongoStream._sortDesc(this._args[1] && this._args[1].sort);
// init current coll
this._currentColl = 0;
this._sort = 1;
if (this._sortDsc) {
this._sort = -1;
}
var sum = crc32.str('' + Math.random());
sum = sum < 0 ? 4294967296 + sum : sum;
this._id = sum.toString(36);
this._log.info('cms %s constructor opts: %j, args: %j', this._id, opts, args);
}
util.inherits(ConcatMongoStream, EE);
module.exports = ConcatMongoStream;
/**
* Proxy pause.
*/
ConcatMongoStream.prototype.pause = function pause() {
this._log.debug2('cms %s pause', this._id);
if (this._stream) {
this._stream.pause();
}
};
/**
* Proxy resume.
*/
ConcatMongoStream.prototype.resume = function resume() {
this._log.debug2('cms %s resume', this._id);
if (this._stream) {
this._stream.resume();
}
};
/**
* Proxy destroy.
*/
ConcatMongoStream.prototype.destroy = function destroy() {
this._log.debug2('cms %s destroy', this._id);
if (this._destroyed) { return; }
this._destroyed = true;
if (this._stream && this._stream.readable) {
this._stream.destroy();
}
this._log.info('cms %s destroyed, emit close', this._id);
this.emit('close');
};
/**
* Start streaming.
*/
ConcatMongoStream.prototype.stream = function stream() {
this._log.debug2('cms %s stream arguments %j', this._id, arguments);
if (this._streaming) { return false; }
this._streaming = true;
var that = this;
if (this._sortDsc) {
this._log.info('cms %s stream reverse', this._id);
// precompute reverse order
this._reverseColls = [];
this._colls.forEach(function(coll) {
that._reverseColls.unshift(coll);
});
}
if (this._args[1]) {
// set a comment if none is given
if (!this._args[1].comment) {
this._args[1].comment = 'ConcatMongoStream.stream';
}
// determine which sort to use (if any), natural or other..
if (this._args[1].sortIndex) {
this._args[1].sort = {};
this._args[1].sort[this._args[1].sortIndex] = this._sort;
}
}
this._log.info('cms %s stream args %j', this._id, this._args);
process.nextTick(function() {
that._runner(arguments, function() {});
});
return this;
};
/**
* Stream collections.
*
* @param {Function} cb called when closed (either last collection or destroyed).
*/
ConcatMongoStream.prototype._runner = function _runner(args, cb) {
this._log.debug2('cms %s _runner', this._id);
var that = this;
var coll = this._sortDsc ? this._reverseColls[this._currentColl] : this._colls[this._currentColl];
var c = coll.find.apply(coll, this._args);
this._stream = c.stream.apply(c, args);
// proxy
this._stream.on('data', function(item) {
that._log.info('cms %s data %j', that._id, item);
that.emit('data', item);
});
// proxy
this._stream.on('error', function(err) {
that._log.crit('cms %s cursor stream error %s', that._id, err);
that.emit('error', err);
});
// either proceed to next collection or destroy
this._stream.on('close', function() {
if (that._destroyed) { cb(); return; }
if (that._currentColl < that._colls.length - 1) {
that._currentColl++;
that._runner(args, cb);
} else {
that.destroy();
cb();
}
});
};
/* use the order of the first sort key, if any */
ConcatMongoStream._sortDesc = function _sortDesc(opts) {
var sortDesc = false;
if (opts) {
// get the first sort key
var keys = Object.keys(opts);
if (typeof keys[0] !== 'undefined') {
if (opts[keys[0]] === -1) {
sortDesc = true;
}
}
}
return sortDesc;
};
| Netsend/mastersync | lib/concat_mongo_stream.js | JavaScript | agpl-3.0 | 6,534 |
/*
* Copyright 2010, Wen Pu (dexterpu at gmail dot com)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Check out http://www.cs.illinois.edu/homes/wenpu1/chatbox.html for document
*
* Depends on jquery.ui.core, jquery.ui.widiget, jquery.ui.effect
*
* Also uses some styles for jquery.ui.dialog
*
*/
// TODO: implement destroy()
(function($) {
$.widget("ui.chatbox", {
options: {
id: null, //id for the DOM element
title: null, // title of the chatbox
user: null, // can be anything associated with this chatbox
hidden: false,
offset: 0, // relative to right edge of the browser window
width: 300, // width of the chatbox
messageSent: function(id, user, msg) {
// override this
this.boxManager.addMsg(user.first_name, msg);
},
boxClosed: function(id) {
}, // called when the close icon is clicked
boxManager: {
// thanks to the widget factory facility
// similar to http://alexsexton.com/?p=51
init: function(elem) {
this.elem = elem;
},
addMsg: function(peer, msg) {
var self = this;
var box = self.elem.uiChatboxLog;
var e = document.createElement('div');
box.append(e);
$(e).hide();
var systemMessage = false;
if (peer) {
var peerName = document.createElement("b");
$(peerName).text(peer + ": ");
e.appendChild(peerName);
} else {
systemMessage = true;
}
var msgElement = document.createElement(
systemMessage ? "i" : "span");
$(msgElement).text(msg);
e.appendChild(msgElement);
$(e).addClass("ui-chatbox-msg");
$(e).css("maxWidth", $(box).width());
$(e).fadeIn();
self._scrollToBottom();
if (!self.elem.uiChatboxTitlebar.hasClass("ui-state-focus")
&& !self.highlightLock) {
self.highlightLock = true;
self.highlightBox();
}
},
highlightBox: function() {
var self = this;
self.elem.uiChatboxTitlebar.effect("highlight", {}, 300);
self.elem.uiChatbox.effect("bounce", {times: 1}, 300, function() {
self.highlightLock = false;
self._scrollToBottom();
});
},
toggleBox: function() {
this.elem.uiChatbox.toggle();
},
_scrollToBottom: function() {
var box = this.elem.uiChatboxLog;
box.scrollTop(box.get(0).scrollHeight);
}
}
},
toggleContent: function(event) {
this.uiChatboxContent.toggle();
if (this.uiChatboxContent.is(":visible")) {
this.uiChatboxInputBox.focus();
}
},
widget: function() {
return this.uiChatbox
},
_create: function() {
var self = this,
options = self.options,
title = options.title || "No Title",
// chatbox
uiChatbox = (self.uiChatbox = $('<div></div>'))
.appendTo(document.body)
.addClass('ui-widget ' +
'ui-corner-top ' +
'ui-chatbox'
)
.attr('outline', 0)
.focusin(function() {
// ui-state-highlight is not really helpful here
//self.uiChatbox.removeClass('ui-state-highlight');
self.uiChatboxTitlebar.addClass('ui-state-focus');
})
.focusout(function() {
self.uiChatboxTitlebar.removeClass('ui-state-focus');
}),
// titlebar
uiChatboxTitlebar = (self.uiChatboxTitlebar = $('<div></div>'))
.addClass('ui-widget-header ' +
'ui-corner-top ' +
'ui-chatbox-titlebar ' +
'ui-dialog-header' // take advantage of dialog header style
)
.click(function(event) {
self.toggleContent(event);
})
.appendTo(uiChatbox),
uiChatboxTitle = (self.uiChatboxTitle = $('<span></span>'))
.html(title)
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarClose = (self.uiChatboxTitlebarClose = $('<a href="#"></a>'))
.addClass('ui-corner-all ' +
'ui-chatbox-icon '
)
.attr('role', 'button')
.hover(function() { uiChatboxTitlebarClose.addClass('ui-state-hover'); },
function() { uiChatboxTitlebarClose.removeClass('ui-state-hover'); })
.click(function(event) {
uiChatbox.hide();
self.options.boxClosed(self.options.id);
return false;
})
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarCloseText = $('<span></span>')
.addClass('ui-icon ' +
'ui-icon-closethick')
.text('close')
.appendTo(uiChatboxTitlebarClose),
uiChatboxTitlebarMinimize = (self.uiChatboxTitlebarMinimize = $('<a href="#"></a>'))
.addClass('ui-corner-all ' +
'ui-chatbox-icon'
)
.attr('role', 'button')
.hover(function() { uiChatboxTitlebarMinimize.addClass('ui-state-hover'); },
function() { uiChatboxTitlebarMinimize.removeClass('ui-state-hover'); })
.click(function(event) {
self.toggleContent(event);
return false;
})
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarMinimizeText = $('<span></span>')
.addClass('ui-icon ' +
'ui-icon-minusthick')
.text('minimize')
.appendTo(uiChatboxTitlebarMinimize),
// content
uiChatboxContent = (self.uiChatboxContent = $('<div></div>'))
.addClass('ui-widget-content ' +
'ui-chatbox-content '
)
.appendTo(uiChatbox),
uiChatboxLog = (self.uiChatboxLog = self.element)
.addClass('ui-widget-content ' +
'ui-chatbox-log'
)
.appendTo(uiChatboxContent),
uiChatboxInput = (self.uiChatboxInput = $('<div>Chat<br></div>'))
.addClass('ui-widget-content ' +
'ui-chatbox-input'
)
.click(function(event) {
// anything?
})
.appendTo(uiChatboxContent),
// Aqui se le agregan cosas al menu
uiChatboxRest = (self.uiChatboxRest = $('<div><ul> <li> <a href="#"><i></i>Preguntas relacionadas</a> <ul id="respuestarel"> </ul> </li> <li> <a href="#"><i></i>Contacto</a> <ul class="closedt"> <li>Phone: Name 888-888888</li> <li>Email: email@email.com</li></ul></li> </ul></div>'))
.addClass('ui-widget-content ' +
'ui-chatbox-rest '
)
.appendTo(uiChatboxContent),
//apend al mas grande o general.
uiChatboxInputBox = (self.uiChatboxInputBox = $('<textarea></textarea>'))
.addClass('ui-widget-content ' +
'ui-chatbox-input-box ' +
'ui-corner-all'
)
.appendTo(uiChatboxInput)
.keydown(function(event) {
if (event.keyCode && event.keyCode == $.ui.keyCode.ENTER) {
msg = $.trim($(this).val());
if (msg.length > 0) {
self.options.messageSent(self.options.id, self.options.user, msg);
}
$(this).val('');
return false;
}
})
.focusin(function() {
uiChatboxInputBox.addClass('ui-chatbox-input-focus');
var box = $(this).parent().prev();
box.scrollTop(box.get(0).scrollHeight);
})
.focusout(function() {
uiChatboxInputBox.removeClass('ui-chatbox-input-focus');
});
// disable selection
uiChatboxTitlebar.find('*').add(uiChatboxTitlebar).disableSelection();
// switch focus to input box when whatever clicked
uiChatboxContent.children().click(function() {
// click on any children, set focus on input box
self.uiChatboxInputBox.focus();
});
self._setWidth(self.options.width);
self._position(self.options.offset);
self.options.boxManager.init(self);
if (!self.options.hidden) {
uiChatbox.show();
}
},
_setOption: function(option, value) {
if (value != null) {
switch (option) {
case "hidden":
if (value)
this.uiChatbox.hide();
else
this.uiChatbox.show();
break;
case "offset":
this._position(value);
break;
case "width":
this._setWidth(value);
break;
}
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_setWidth: function(width) {
this.uiChatboxTitlebar.width(width + "px");
this.uiChatboxLog.width(width + "px");
this.uiChatboxInput.css("maxWidth", width + "px");
this.uiChatboxRest.css("width", width + "px");
// padding:2, boarder:2, margin:5
this.uiChatboxInputBox.css("width", (width - 18) + "px");
},
_position: function(offset) {
this.uiChatbox.css("right", offset);
}
});
}(jQuery)); | allendecid/AIchat | ES/jquery.ui.chatboxmod.js | JavaScript | agpl-3.0 | 11,110 |
define(function(require) {
'use strict';
var _ = require('underscore');
var Vector2 = require('common/math/vector2');
var VerletAlgorithm = require('../verlet-algorithm');
var DiatomicAtomPositionUpdater = require('models/atom-position-updater/diatomic');
/**
* Implementation of the Verlet algorithm for simulating molecular interaction
* based on the Lennard-Jones potential - diatomic (i.e. two atoms per
* molecule) version.
*/
var DiatomicVerletAlgorithm = function(simulation) {
VerletAlgorithm.apply(this, [simulation]);
this.positionUpdater = DiatomicAtomPositionUpdater;
};
_.extend(DiatomicVerletAlgorithm.prototype, VerletAlgorithm.prototype, {
/**
* Update the motion of the particles and the forces that are acting upon
* them. This is the heart of this class, and it is here that the actual
* Verlet algorithm is contained.
*/
updateForcesAndMotion: function() {
// Obtain references to the model data and parameters so that we can
// perform fast manipulations.
var simulation = this.simulation;
var moleculeDataSet = simulation.moleculeDataSet;
var numberOfMolecules = moleculeDataSet.getNumberOfMolecules();
var moleculeCenterOfMassPositions = moleculeDataSet.moleculeCenterOfMassPositions;
var atomPositions = moleculeDataSet.atomPositions;
var moleculeVelocities = moleculeDataSet.moleculeVelocities;
var moleculeForces = moleculeDataSet.moleculeForces;
var nextMoleculeForces = moleculeDataSet.nextMoleculeForces;
var moleculeRotationAngles = moleculeDataSet.moleculeRotationAngles;
var moleculeRotationRates = moleculeDataSet.moleculeRotationRates;
var moleculeTorques = moleculeDataSet.moleculeTorques;
var nextMoleculeTorques = moleculeDataSet.nextMoleculeTorques;
// Initialize other values that will be needed for the calculation.
var massInverse = 1 / moleculeDataSet.moleculeMass;
var inertiaInverse = 1 / moleculeDataSet.moleculeRotationalInertia;
var normalizedContainerHeight = simulation.getNormalizedContainerHeight();
var normalizedContainerWidth = simulation.getNormalizedContainerWidth();
var gravitationalAcceleration = simulation.getGravitationalAcceleration();
var temperatureSetPoint = simulation.get('temperatureSetPoint');
// Update center of mass positions and angles for the molecules.
this._updateCenterOfMassPositions(
moleculeCenterOfMassPositions,
numberOfMolecules,
moleculeVelocities,
moleculeForces,
moleculeTorques,
moleculeRotationRates,
moleculeRotationAngles,
massInverse,
inertiaInverse
);
this.positionUpdater.updateAtomPositions(moleculeDataSet);
// Calculate the force from the walls. This force is assumed to act
// on the center of mass, so there is no torque.
// Calculate the forces exerted on the particles by the container
// walls and by gravity.
var pressureZoneWallForce = this._calculateWallAndGravityForces(
nextMoleculeForces,
nextMoleculeTorques,
numberOfMolecules,
moleculeCenterOfMassPositions,
normalizedContainerWidth,
normalizedContainerHeight,
gravitationalAcceleration,
temperatureSetPoint
);
// Update the pressure calculation.
this.updatePressure(pressureZoneWallForce);
// If there are any atoms that are currently designated as "unsafe",
// check them to see if they can be moved into the "safe" category.
if (moleculeDataSet.numberOfSafeMolecules < numberOfMolecules)
this.updateMoleculeSafety();
// Calculate the force and torque due to inter-particle interactions.
this._calculateInteractionForces(
nextMoleculeForces,
nextMoleculeTorques,
moleculeDataSet.numberOfSafeMolecules,
atomPositions,
moleculeCenterOfMassPositions
);
// Update center of mass velocities and angles and calculate kinetic
// energy.
this._calculateVelocities(
moleculeVelocities,
numberOfMolecules,
moleculeRotationRates,
moleculeForces,
moleculeTorques,
nextMoleculeForces,
nextMoleculeTorques,
moleculeDataSet.moleculeMass,
moleculeDataSet.moleculeRotationalInertia,
massInverse,
inertiaInverse
);
},
/**
* Updates the positions of all particles based on their current
* velocities and the forces acting on them.
*/
_updateCenterOfMassPositions: function(moleculeCenterOfMassPositions, numberOfMolecules, moleculeVelocities, moleculeForces, moleculeTorques, moleculeRotationRates, moleculeRotationAngles, massInverse, inertiaInverse) {
for (var i = 0; i < numberOfMolecules; i++) {
var xPos = moleculeCenterOfMassPositions[i].x +
(VerletAlgorithm.TIME_STEP * moleculeVelocities[i].x) +
(VerletAlgorithm.TIME_STEP_SQR_HALF * moleculeForces[i].x * massInverse);
var yPos = moleculeCenterOfMassPositions[i].y +
(VerletAlgorithm.TIME_STEP * moleculeVelocities[i].y) +
(VerletAlgorithm.TIME_STEP_SQR_HALF * moleculeForces[i].y * massInverse);
moleculeCenterOfMassPositions[i].set(xPos, yPos);
moleculeRotationAngles[i] += (VerletAlgorithm.TIME_STEP * moleculeRotationRates[i]) +
(VerletAlgorithm.TIME_STEP_SQR_HALF * moleculeTorques[i] * inertiaInverse);
}
},
/**
* Calculate the forces exerted on the particles by the container
* walls and by gravity.
*/
_calculateWallAndGravityForces: function(nextMoleculeForces, nextMoleculeTorques, numberOfMolecules, moleculeCenterOfMassPositions, normalizedContainerWidth, normalizedContainerHeight, gravitationalAcceleration, temperatureSetPoint) {
var pressureZoneWallForce = 0;
for (var i = 0; i < numberOfMolecules; i++) {
// Clear the previous calculation's particle forces and torques.
nextMoleculeForces[i].set(0, 0);
nextMoleculeTorques[i] = 0;
// Get the force values caused by the container walls.
this.calculateWallForce(
moleculeCenterOfMassPositions[i],
normalizedContainerWidth,
normalizedContainerHeight,
nextMoleculeForces[i]
);
// Accumulate this force value as part of the pressure being
// exerted on the walls of the container.
if (nextMoleculeForces[i].y < 0) {
pressureZoneWallForce += -nextMoleculeForces[i].y;
}
else if (moleculeCenterOfMassPositions[i].y > normalizedContainerHeight / 2) {
// If the particle bounced on one of the walls above the midpoint, add
// in that value to the pressure.
pressureZoneWallForce += Math.abs(nextMoleculeForces[i].x);
}
// Add in the effect of gravity.
var _gravitationalAcceleration = gravitationalAcceleration;
if (temperatureSetPoint < VerletAlgorithm.TEMPERATURE_BELOW_WHICH_GRAVITY_INCREASES) {
// Below a certain temperature, gravity is increased to counteract some
// odd-looking behaviorcaused by the thermostat.
_gravitationalAcceleration = gravitationalAcceleration * (
(VerletAlgorithm.TEMPERATURE_BELOW_WHICH_GRAVITY_INCREASES - temperatureSetPoint) *
VerletAlgorithm.LOW_TEMPERATURE_GRAVITY_INCREASE_RATE + 1
);
}
nextMoleculeForces[i].y = nextMoleculeForces[i].y - _gravitationalAcceleration;
}
return pressureZoneWallForce;
},
/**
* Calculate the forces created through interactions with other
* particles.
*/
_calculateInteractionForces: function(nextMoleculeForces, nextMoleculeTorques, numberOfSafeMolecules, atomPositions, moleculeCenterOfMassPositions) {
var force = new Vector2();
for (var i = 0; i < numberOfSafeMolecules; i++) {
for (var j = i + 1; j < numberOfSafeMolecules; j++) {
for (var ii = 0; ii < 2; ii++) {
for (var jj = 0; jj < 2; jj++) {
// Calculate the distance between the potentially
// interacting atoms.
var dx = atomPositions[2 * i + ii].x - atomPositions[2 * j + jj].x;
var dy = atomPositions[2 * i + ii].y - atomPositions[2 * j + jj].y;
var distanceSquared = dx * dx + dy * dy;
if (distanceSquared < VerletAlgorithm.PARTICLE_INTERACTION_DISTANCE_THRESH_SQRD) {
if (distanceSquared < VerletAlgorithm.MIN_DISTANCE_SQUARED)
distanceSquared = VerletAlgorithm.MIN_DISTANCE_SQUARED;
// Calculate the Lennard-Jones interaction forces.
var r2inv = 1 / distanceSquared;
var r6inv = r2inv * r2inv * r2inv;
var forceScalar = 48 * r2inv * r6inv * (r6inv - 0.5);
var fx = dx * forceScalar;
var fy = dy * forceScalar;
force.set(fx, fy);
nextMoleculeForces[i].add(force);
nextMoleculeForces[j].sub(force);
nextMoleculeTorques[i] +=
(atomPositions[2 * i + ii].x - moleculeCenterOfMassPositions[i].x) * fy -
(atomPositions[2 * i + ii].y - moleculeCenterOfMassPositions[i].y) * fx;
nextMoleculeTorques[j] -=
(atomPositions[2 * j + jj].x - moleculeCenterOfMassPositions[j].x) * fy -
(atomPositions[2 * j + jj].y - moleculeCenterOfMassPositions[j].y) * fx;
this.potentialEnergy += 4 * r6inv * (r6inv - 1) + 0.016316891136;
}
}
}
}
}
return this.potentialEnergy;
},
/**
* Calculate the new velocities based on the old ones and the forces
* that are acting on the particle.
*/
_calculateVelocities: function(moleculeVelocities, numberOfMolecules, moleculeRotationRates, moleculeForces, moleculeTorques, nextMoleculeForces, nextMoleculeTorques, moleculeMass, moleculeRotationalInertia, massInverse, inertiaInverse) {
var centersOfMassKineticEnergy = 0;
var rotationalKineticEnergy = 0;
for (var i = 0; i < numberOfMolecules; i++) {
var xVel = moleculeVelocities[i].x +
VerletAlgorithm.TIME_STEP_HALF * (moleculeForces[i].x + nextMoleculeForces[i].x) * massInverse;
var yVel = moleculeVelocities[i].y +
VerletAlgorithm.TIME_STEP_HALF * (moleculeForces[i].y + nextMoleculeForces[i].y) * massInverse;
moleculeVelocities[i].set(xVel, yVel);
moleculeRotationRates[i] += VerletAlgorithm.TIME_STEP_HALF * (moleculeTorques[i] + nextMoleculeTorques[i]) * inertiaInverse;
centersOfMassKineticEnergy += 0.5 *
moleculeMass *
(Math.pow(moleculeVelocities[i].x, 2) + Math.pow(moleculeVelocities[i].y, 2));
rotationalKineticEnergy += 0.5 *
moleculeRotationalInertia *
Math.pow(moleculeRotationRates[i], 2);
// Move the newly calculated forces and torques into the current spots.
moleculeForces[i].set(nextMoleculeForces[i].x, nextMoleculeForces[i].y);
moleculeTorques[i] = nextMoleculeTorques[i];
}
// Record the calculated temperature.
this.temperature = (centersOfMassKineticEnergy + rotationalKineticEnergy) / numberOfMolecules / 1.5;
}
});
return DiatomicVerletAlgorithm;
}); | Connexions/simulations | states-of-matter/src/js/models/verlet-algorithm/diatomic.js | JavaScript | agpl-3.0 | 13,520 |
import { env } from './env';
export const MIN_ID = 2147483648;
/**
* Equals to true in any browser.
*/
export const isBrowser = typeof window === 'undefined' ? false : true;
export function isOnline() {
return isBrowser ? navigator.onLine : true;
}
export function isVisible() {
return isBrowser ? document.visibilityState === 'visible' : true;
}
/**
* Check whether the string is a valid URL.
*/
export function validateWebSocketURL(url) {
const regex = /^(wss|ws):\/\/((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]))(:[0-9]{1,5})?(\/.*)?$/;
if (!new RegExp(regex, 'i').test(url)) {
throw new Error(`Invalid URL: ${url}`);
}
}
/**
* Generate random key which will be used to join the network.
*/
export function generateKey() {
const mask = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const length = 42; // Should be less then MAX_KEY_LENGTH value
const values = randNumbers(length);
let result = '';
for (let i = 0; i < length; i++) {
result += mask[values[i] % mask.length];
}
return result;
}
export function generateId(exclude = []) {
let id = randNumbers()[0];
if (id < MIN_ID) {
id += MIN_ID;
}
if (exclude.includes(id)) {
return generateId(exclude);
}
return id;
}
const MAX_KEY_LENGTH = 512;
export function validateKey(key) {
if (typeof key !== 'string') {
throw new Error(`The key type "${typeof key}" is not a "string"`);
}
else if (key === '') {
throw new Error('The key is an empty string');
}
else if (key.length > MAX_KEY_LENGTH) {
throw new Error(`The key length of ${key.length} exceeds the maximum of ${MAX_KEY_LENGTH} characters`);
}
return true;
}
export function extractHostnameAndPort(url) {
return url.split('/')[2];
}
function randNumbers(length = 1) {
let res;
if (isBrowser) {
res = new Uint32Array(length);
env.crypto.getRandomValues(res);
}
else {
res = [];
const bytes = env.cryptoNode.randomBytes(4 * length);
for (let i = 0; i < bytes.length; i += 4) {
res[res.length] = bytes.readUInt32BE(i, true);
}
}
return res;
}
export function equal(array1, array2) {
return (array1 !== undefined &&
array2 !== undefined &&
array1.length === array2.length &&
array1.every((v) => array2.includes(v)));
}
/**
* Indicates whether WebSocket is supported by the environment.
*/
export function isWebSocketSupported() {
return !!env.WebSocket;
}
/**
* Indicates whether WebRTC & RTCDataChannel is supported by the environment.
*/
export function isWebRTCSupported() {
return !!env.RTCPeerConnection && 'createDataChannel' in env.RTCPeerConnection.prototype;
}
export * from './util.log';
| coast-team/netflux | docs/jsFromTs/src/misc/util.js | JavaScript | agpl-3.0 | 2,979 |
// @flow
// This module exposes the api for internal usage, so that we don't have to
// deal with versioning, creation and waiting of/for the api.
import Model from "oxalis/model";
import createApi from "oxalis/api/api_latest";
const api = createApi(Model);
export default api;
| scalableminds/webknossos | frontend/javascripts/oxalis/api/internal_api.js | JavaScript | agpl-3.0 | 281 |
/*
* elRTE - WSWING editor for web
*
* Usage:
* var opts = {
* .... // see elRTE.options.js
* }
* var editor = new elRTE($('#my-id').get(0), opts)
* or
* $('#my-id').elrte(opts)
*
* $('#my-id) may be textarea or any DOM Element with text
*
* @author: Dmitry Levashov (dio) dio@std42.ru
* Copyright: Studio 42, http://www.std42.ru
*/
(function($) {
elRTE = function(target, opts) {
if (!target || !target.nodeName) {
return alert('elRTE: argument "target" is not DOM Element');
}
var self = this, html;
this.version = '1.3';
this.build = '2011-06-23';
this.options = $.extend(true, {}, this.options, opts);
this.browser = $.browser;
this.target = $(target);
this.lang = (''+this.options.lang);
this._i18n = new eli18n({textdomain : 'rte', messages : { rte : this.i18Messages[this.lang] || {}} });
this.rtl = !!(/^(ar|fa|he)$/.test(this.lang) && this.i18Messages[this.lang]);
if (this.rtl) {
this.options.cssClass += ' el-rte-rtl';
}
this.toolbar = $('<div class="toolbar"/>');
this.iframe = document.createElement('iframe');
this.iframe.setAttribute('frameborder', 0); // fixes IE border
// this.source = $('<textarea />').hide();
this.workzone = $('<div class="workzone"/>').append(this.iframe).append(this.source);
this.statusbar = $('<div class="statusbar"/>');
this.tabsbar = $('<div class="tabsbar"/>');
this.editor = $('<div class="'+this.options.cssClass+'" />').append(this.toolbar).append(this.workzone).append(this.statusbar).append(this.tabsbar);
this.doc = null;
this.$doc = null;
this.window = null;
this.utils = new this.utils(this);
this.dom = new this.dom(this);
this.filter = new this.filter(this)
/**
* Sync iframes/textareas height with workzone height
*
* @return void
*/
this.updateHeight = function() {
self.workzone.add(self.iframe).add(self.source).height(self.workzone.height());
}
/**
* Turn editor resizable on/off if allowed
*
* @param Boolean
* @return void
**/
this.resizable = function(r) {
var self = this;
if (this.options.resizable && $.fn.resizable) {
if (r) {
this.editor.resizable({handles : 'se', alsoResize : this.workzone, minWidth :300, minHeight : 200 }).bind('resize', self.updateHeight);
} else {
this.editor.resizable('destroy').unbind('resize', self.updateHeight);
}
}
}
/* attach editor to document */
this.editor.insertAfter(target);
/* init editor textarea */
var content = '';
if (target.nodeName == 'TEXTAREA') {
this.source = this.target;
this.source.insertAfter(this.iframe).hide();
content = this.target.val();
} else {
this.source = $('<textarea />').insertAfter(this.iframe).hide();
content = this.target.hide().html();
}
this.source.attr('name', this.target.attr('name')||this.target.attr('id'));
content = $.trim(content);
if (!content) {
content = ' ';
}
/* add tabs */
if (this.options.allowSource) {
this.tabsbar.append('<div class="tab editor rounded-bottom-7 active">'+self.i18n('Editor')+'</div><div class="tab source rounded-bottom-7">'+self.i18n('Source')+'</div><div class="clearfix" style="clear:both"/>')
.children('.tab').click(function(e) {
if (!$(this).hasClass('active')) {
self.tabsbar.children('.tab').toggleClass('active');
self.workzone.children().toggle();
if ($(this).hasClass('editor')) {
self.updateEditor();
self.window.focus();
self.ui.update(true);
} else {
self.updateSource();
self.source.focus();
if ($.browser.msie) {
// @todo
} else {
self.source[0].setSelectionRange(0, 0);
}
self.ui.disable();
self.statusbar.empty();
}
}
});
}
this.window = this.iframe.contentWindow;
this.doc = this.iframe.contentWindow.document;
this.$doc = $(this.doc);
/* put content into iframe */
html = '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
$.each(self.options.cssfiles, function() {
html += '<link rel="stylesheet" type="text/css" href="'+this+'" />';
});
this.doc.open();
var s = this.filter.wysiwyg(content),
cl = this.rtl ? ' class="el-rte-rtl"' : '';
this.doc.write(self.options.doctype+html+'</head><body'+cl+'>'+(s)+'</body></html>');
this.doc.close();
/* make iframe editable */
if ($.browser.msie) {
this.doc.body.contentEditable = true;
} else {
try { this.doc.designMode = "on"; }
catch(e) { }
this.doc.execCommand('styleWithCSS', false, this.options.styleWithCSS);
}
if (this.options.height>0) {
this.workzone.height(this.options.height);
}
if (this.options.width>0) {
this.editor.width(this.options.width);
}
this.updateHeight();
this.resizable(true);
this.window.focus();
this.history = new this.history(this);
/* init selection object */
this.selection = new this.selection(this);
/* init buttons */
this.ui = new this.ui(this);
/* bind updateSource to parent form submit */
this.target.parents('form').bind('submit.elfinder', function(e) {
self.source.parents('form').find('[name="el-select"]').remove()
self.beforeSave();
});
// on tab press - insert \t and prevent move focus
this.source.bind('keydown', function(e) {
if (e.keyCode == 9) {
e.preventDefault();
if ($.browser.msie) {
var r = document.selection.createRange();
r.text = "\t"+r.text;
this.focus();
} else {
var before = this.value.substr(0, this.selectionStart),
after = this.value.substr(this.selectionEnd);
this.value = before+"\t"+after;
this.setSelectionRange(before.length+1, before.length+1);
}
}
});
$(this.doc.body).bind('dragend', function(e) {
setTimeout(function() {
try {
self.window.focus();
var bm = self.selection.getBookmark();
self.selection.moveToBookmark(bm);
self.ui.update();
} catch(e) { }
}, 200);
});
this.typing = false;
this.lastKey = null;
/* update buttons on click and keyup */
this.$doc.bind('mouseup', function() {
self.typing = false;
self.lastKey = null;
self.ui.update();
})
.bind('keyup', function(e) {
if ((e.keyCode >= 8 && e.keyCode <= 13) || (e.keyCode>=32 && e.keyCode<= 40) || e.keyCode == 46 || (e.keyCode >=96 && e.keyCode <= 111)) {
self.ui.update();
}
})
.bind('keydown', function(e) {
if ((e.metaKey || e.ctrlKey) && e.keyCode == 65) {
self.ui.update();
} else if (e.keyCode == 13) {
var n = self.selection.getNode();
// self.log(n)
if (self.dom.selfOrParent(n, /^PRE$/)) {
self.selection.insertNode(self.doc.createTextNode("\r\n"));
return false;
} else if ($.browser.safari && e.shiftKey) {
self.selection.insertNode(self.doc.createElement('br'))
return false;
}
}
if ((e.keyCode>=48 && e.keyCode <=57) || e.keyCode==61 || e.keyCode == 109 || (e.keyCode>=65 && e.keyCode<=90) || e.keyCode==188 ||e.keyCode==190 || e.keyCode==191 || (e.keyCode>=219 && e.keyCode<=222)) {
if (!self.typing) {
self.history.add(true);
}
self.typing = true;
self.lastKey = null;
} else if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 32 || e.keyCode == 13) {
if (e.keyCode != self.lastKey) {
self.history.add(true);
}
self.lastKey = e.keyCode;
self.typing = false;
}
})
.bind('paste', function(e) {
if (!self.options.allowPaste) {
// paste denied
e.stopPropagation();
e.preventDefault();
} else {
var n = $(self.dom.create('div'))[0],
r = self.doc.createTextNode('_');
self.history.add(true);
self.typing = true;
self.lastKey = null;
n.appendChild(r);
self.selection.deleteContents().insertNode(n);
self.selection.select(r);
setTimeout(function() {
if (n.parentNode) {
// clean sandbox content
$(n).html(self.filter.proccess('paste', $(n).html()));
r = n.lastChild;
self.dom.unwrap(n);
if (r) {
self.selection.select(r);
self.selection.collapse(false);
}
} else {
// smth wrong - clean all doc
n.parentNode && n.parentNode.removeChild(n);
self.val(self.filter.proccess('paste', self.filter.wysiwyg2wysiwyg($(self.doc.body).html())));
self.selection.select(self.doc.body.firstChild);
self.selection.collapse(true);
}
$(self.doc.body).mouseup(); // to activate history buutons
}, 15);
}
});
if ($.browser.msie) {
this.$doc.bind('keyup', function(e) {
if (e.keyCode == 86 && (e.metaKey||e.ctrlKey)) {
self.history.add(true);
self.typing = true;
self.lastKey = null;
self.selection.saveIERange();
self.val(self.filter.proccess('paste', self.filter.wysiwyg2wysiwyg($(self.doc.body).html())));
self.selection.restoreIERange();
$(self.doc.body).mouseup();
this.ui.update();
}
});
}
if ($.browser.safari) {
this.$doc.bind('click', function(e) {
$(self.doc.body).find('.elrte-webkit-hl').removeClass('elrte-webkit-hl');
if (e.target.nodeName == 'IMG') {
$(e.target).addClass('elrte-webkit-hl');
}
}).bind('keyup', function(e) {
$(self.doc.body).find('.elrte-webkit-hl').removeClass('elrte-webkit-hl');
})
}
this.window.focus();
this.destroy = function() {
this.updateSource();
this.target.is('textarea')
? this.target.val($.trim(this.source.val()))
: this.target.html($.trim(this.source.val()));
this.editor.remove();
this.target.show().parents('form').unbind('submit.elfinder');
}
}
/**
* Return message translated to selected language
*
* @param string msg message text in english
* @return string
**/
elRTE.prototype.i18n = function(msg) {
return this._i18n.translate(msg);
}
/**
* Display editor
*
* @return void
**/
elRTE.prototype.open = function() {
this.editor.show();
}
/**
* Hide editor and display elements on wich editor was created
*
* @return void
**/
elRTE.prototype.close = function() {
this.editor.hide();
}
elRTE.prototype.updateEditor = function() {
this.val(this.source.val());
}
elRTE.prototype.updateSource = function() {
this.source.val(this.filter.source($(this.doc.body).html()));
}
/**
* Return edited text
*
* @return String
**/
elRTE.prototype.val = function(v) {
if (typeof(v) == 'string') {
v = ''+v;
if (this.source.is(':visible')) {
this.source.val(this.filter.source2source(v));
} else {
if ($.browser.msie) {
this.doc.body.innerHTML = '<br />'+this.filter.wysiwyg(v);
this.doc.body.removeChild(this.doc.body.firstChild);
} else {
this.doc.body.innerHTML = this.filter.wysiwyg(v);
}
}
} else {
if (this.source.is(':visible')) {
return $.trim(this.filter.source2source(this.source.val()));
} else {
return $.trim(this.filter.source($(this.doc.body).html()));
}
}
}
elRTE.prototype.beforeSave = function() {
this.source.val($.trim(this.val())||'');
}
/**
* Submit form
*
* @return void
**/
elRTE.prototype.save = function() {
this.beforeSave();
this.editor.parents('form').submit();
}
elRTE.prototype.log = function(msg) {
if (window.console && window.console.log) {
window.console.log(msg);
}
}
elRTE.prototype.i18Messages = {};
$.fn.elrte = function(o, v) {
var cmd = typeof(o) == 'string' ? o : '', ret;
this.each(function() {
if (!this.elrte) {
this.elrte = new elRTE(this, typeof(o) == 'object' ? o : {});
}
switch (cmd) {
case 'open':
case 'show':
this.elrte.open();
break;
case 'close':
case 'hide':
this.elrte.close();
break;
case 'updateSource':
this.elrte.updateSource();
break;
case 'destroy':
this.elrte.destroy();
}
});
if (cmd == 'val') {
if (!this.length) {
return '';
} else if (this.length == 1) {
return v || v === '' ? this[0].elrte.val(v) : this[0].elrte.val();
} else {
ret = {}
this.each(function() {
ret[this.elrte.source.attr('name')] = this.elrte.val();
});
return ret;
}
}
return this;
}
})(jQuery);
| xavoctechnocratspvtltd/property | public/js/elrte/js/elRTE.js | JavaScript | agpl-3.0 | 11,965 |
/**
* UStSvzA (sales tax prepayment) module for Geierlein.
*
* @author Stefan Siegl
*
* Copyright (c) 2013,2017,2018 Stefan Siegl <stesie@brokenpipe.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function() {
var geierlein = {};
if(typeof(window) !== 'undefined') {
geierlein = window.geierlein = window.geierlein || {};
}
else if(typeof(module) !== 'undefined' && module.exports) {
geierlein = {
Datenlieferant: require('./datenlieferant.js'),
Steuerfall: require('./steuerfall.js'),
util: require('./util.js'),
validation: require('./validation.js')
};
}
var rules = geierlein.validation.rules;
/**
* Create new UStSvzA instance.
*
* @param datenlieferant A Datenlieferant instance to use.
* @param jahr The year of the declaration.
* @param type The type of declaration
*/
geierlein.UStSvzA = function(datenlieferant, jahr, type) {
this.datenlieferant = datenlieferant || new geierlein.Datenlieferant();
this.jahr = jahr;
this.type = type;
};
geierlein.UStSvzA.prototype = new geierlein.Steuerfall();
geierlein.UStSvzA.prototype.constructor = geierlein.UStSvzA;
var validationRules = {
land: [
rules.required,
rules.range(1, 16)
],
jahr: [
rules.required,
rules.range(2010, 2018)
],
type: [
rules.required,
function(val) {
return this.type === 'Umsatzsteuersondervorauszahlung'
|| this.type === 'Dauerfristverlaengerung';
}
],
steuernummer: [rules.required, rules.taxNumber],
kz10: [rules.option],
kz26: [rules.option],
kz29: [rules.option],
kz38: [
function(val) {
if(this.type === 'Umsatzsteuersondervorauszahlung') {
return val !== undefined && rules.unsignedInt(val);
} else {
return val === undefined;
}
}
]
};
function writeOption(val) {
return val ? '1' : false;
}
function writeOptionalInt(val) {
return val === undefined ? false : (+val).toString();
}
var xmlWritingRules = {
kz10: writeOption,
kz26: writeOption,
kz29: writeOption,
kz38: writeOptionalInt
};
geierlein.util.extend(geierlein.UStSvzA.prototype, {
datenart: 'UStVA',
validate: function(field) {
var i = geierlein.validation.validate.call(this, validationRules, field);
/* If field is not set, i.e. we should check the whole form, call
validate on datenlieferant sub-model as well. */
if(field === undefined) {
var j = this.datenlieferant.validate();
if(j !== true) {
if(i === true) {
return j;
}
i = i.concat(j);
}
}
return i;
},
/**
* Get Elster XML representation of the Nutzdaten part.
*
* @return XML representation of the Nutzdaten part as a string.
*/
getNutzdatenXml: function(testcase) {
var nutzdaten = new geierlein.util.Xml();
var d = new Date();
var erstellDatum = this.erstellungsdatum || d.getFullYear() +
('0' + (d.getMonth() + 1)).substr(-2) +
('0' + d.getDate()).substr(-2);
nutzdaten.writeStartDocument();
nutzdaten.writeStartElement('Nutzdaten');
nutzdaten.writeStartElement('Anmeldungssteuern');
nutzdaten.writeAttributeString('art', 'UStVA');
nutzdaten.writeAttributeString('version', this.jahr + '01');
nutzdaten.writeStartElement('DatenLieferant')
nutzdaten.writeXml(this.datenlieferant.toXml());
nutzdaten.writeEndElement();
nutzdaten.writeElementString('Erstellungsdatum', erstellDatum);
nutzdaten.writeStartElement('Steuerfall');
nutzdaten.writeStartElement(this.type);
nutzdaten.writeElementString('Jahr', this.jahr);
nutzdaten.writeElementString('Steuernummer',
this.getFormattedTaxNumber());
nutzdaten.writeElementString('Kz09',
testcase ? '74931' : this.herstellerID);
for(var key in xmlWritingRules) {
var fmtValue = xmlWritingRules[key](this[key]);
if(fmtValue === false) {
continue;
}
nutzdaten.writeElementString('Kz' + key.substr(2),
fmtValue);
}
return nutzdaten.flush(true);
}
});
if(typeof(module) !== 'undefined' && module.exports) {
module.exports = geierlein.UStSvzA;
}
})();
| stesie/geierlein | chrome/content/lib/geierlein/ustsvza.js | JavaScript | agpl-3.0 | 5,349 |
import { contains } from 'mout/array';
const matchExtension = (fileName) => {
return fileName.match(/\.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$/);
};
const getExtensionFromFileName = (fileName) => {
var match = matchExtension(fileName);
if (match) {
return match[0];
}
// if file.name does not have .[ext] return a default doc
return _.sample(Partup.helpers.fileUploader.fallbackFileExtensions);
};
const imageExtensions = ['.gif', '.jpg', '.jpeg', '.png', '.GIF', '.JPG', '.JPEG', '.PNG'];
const docExtensions = ['.doc', '.docx', '.rtf', '.pages', '.txt', '.DOC', '.DOCX', '.RTF', '.PAGES', '.TXT'];
const pdfExtensions = ['.pdf', '.PDF'];
const presentationExtensions = ['.pps', '.ppsx', '.ppt', '.pptx', '.PPS', '.PPSX', '.PPT', '.PPTX'];
const fallbackFileExtensions = ['.ai', '.bmp', '.eps', '.psd', '.tiff', '.tif', '.svg', '.key', '.keynote', '.AI', '.BMP', '.EPS', '.PSD', '.TIFF', '.TIF', '.SVG', '.KEY', '.KEYNOTE'];
const spreadSheetExtensions = ['.xls', '.xlsx', '.numbers', '.csv', '.XLS', '.XLSX', '.NUMBERS', '.CSV'];
allowedExtensions = {
images: imageExtensions,
docs: _.flatten([
pdfExtensions,
docExtensions,
presentationExtensions,
fallbackFileExtensions,
spreadSheetExtensions
])
};
/**
* @param {object} doc - DocumentSchema in /packages/partup-lib/schemas/update.js
* @returns {string} filename - The svg icon [file.svg | ppt.svg | doc.svg | pdf.svg | xls.svg]
*/
export default function getSvgForDocument(doc) {
var svgFileName = 'file.svg';
// if there's extension in the file name
if (matchExtension(doc.name)) {
var extension = getExtensionFromFileName(doc.name);
if (contains(fallbackFileExtensions, extension)) {
svgFileName = 'file.svg';
} else if (contains(presentationExtensions, extension)) {
svgFileName = 'ppt.svg';
} else if (contains(docExtensions, extension)) {
svgFileName = 'doc.svg';
} else if (contains(pdfExtensions, extension)) {
svgFileName = 'pdf.svg';
} else if (contains(spreadSheetExtensions, extension)) {
svgFileName = 'xls.svg';
}
// otherwise fallback to file.svg
} else {
// if there's no extension in the file name,
// for example google sheet, google docs or google slide
// check the mimeType
if (doc.mimeType) {
if (doc.mimeType.indexOf('presentation') > -1) {
svgFileName = 'ppt.svg';
} else if (doc.mimeType.indexOf('document') > -1) {
svgFileName = 'doc.svg';
} else if (doc.mimeType.indexOf('spreadsheet') > -1) {
svgFileName = 'xls.svg';
}
}
}
return `/images/documents/${svgFileName}`;
};
| part-up/app | app/imports/client/services/getSvgForDocument.js | JavaScript | agpl-3.0 | 2,826 |
/*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2016 - 2019 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author: Ronan
* @event: Chapel Wedding
*/
var entryMap = 680000100;
var exitMap = 680000500;
var recruitMap = 680000000;
var clearMap = 680000500;
var minMapId = 680000100;
var maxMapId = 680000401;
var startMsgTime = 4;
var blessMsgTime = 5;
var eventTime = 10; // 10 minutes gathering
var ceremonyTime = 20; // 20 minutes ceremony
var blessingsTime = 15;// blessings are held until the 15th minute from the ceremony start
var partyTime = 45; // 45 minutes party
var forceHideMsgTime = 10; // unfortunately, EIM weddings don't send wedding talk packets to the server... this will need to suffice
var eventBoss = true; // spawns a Cake boss at the hunting ground
var isCathedral = false;
var lobbyRange = [0, 0];
function init() {}
function setLobbyRange() {
return lobbyRange;
}
function setEventExclusives(eim) {
var itemSet = [4031217, 4000313]; // golden key, golden maple leaf
eim.setExclusiveItems(itemSet);
}
function setEventRewards(eim) {
var itemSet, itemQty, evLevel, expStages;
evLevel = 1; //Rewards at clear PQ
itemSet = [];
itemQty = [];
eim.setEventRewards(evLevel, itemSet, itemQty);
expStages = []; //bonus exp given on CLEAR stage signal
eim.setEventClearStageExp(expStages);
}
function spawnCakeBoss(eim) {
var mapObj = eim.getMapInstance(680000400);
var mobObj = Packages.server.life.MapleLifeFactory.getMonster(9400606);
mapObj.spawnMonsterOnGroundBelow(mobObj, new Packages.java.awt.Point(777, -177));
}
function setup(level, lobbyid) {
var eim = em.newMarriage("Wedding" + lobbyid);
eim.setProperty("weddingId", "0");
eim.setProperty("weddingStage", "0"); // 0: gathering time, 1: wedding time, 2: ready to fulfill the wedding, 3: just married
eim.setProperty("guestBlessings", "0");
eim.setProperty("isPremium", "1");
eim.setProperty("canJoin", "1");
eim.setProperty("groomId", "0");
eim.setProperty("brideId", "0");
eim.setProperty("confirmedVows", "-1");
eim.setProperty("groomWishlist", "");
eim.setProperty("brideWishlist", "");
eim.initializeGiftItems();
eim.getInstanceMap(680000400).resetPQ(level);
if(eventBoss) spawnCakeBoss(eim);
respawnStages(eim);
eim.startEventTimer(eventTime * 60000);
setEventRewards(eim);
setEventExclusives(eim);
return eim;
}
function afterSetup(eim) {}
function respawnStages(eim) {
eim.getMapInstance(680000400).instanceMapRespawn();
eim.schedule("respawnStages", 15 * 1000);
}
function playerEntry(eim, player) {
eim.setProperty("giftedItemG" + player.getId(), "0");
eim.setProperty("giftedItemB" + player.getId(), "0");
player.getAbstractPlayerInteraction().gainItem(4000313, 1);
var map = eim.getMapInstance(entryMap);
player.changeMap(map, map.getPortal(0));
}
function stopBlessings(eim) {
var mapobj = eim.getMapInstance(entryMap + 10);
mapobj.dropMessage(6, "Wedding Assistant: Alright people, our couple are preparing their vows to each other right now.");
eim.setIntProperty("weddingStage", 2);
}
function sendWeddingAction(eim, type) {
var chr = eim.getLeader();
if(chr.getGender() == 0) {
chr.getMap().broadcastMessage(Packages.tools.packets.Wedding.OnWeddingProgress(type == 2, eim.getIntProperty("groomId"), eim.getIntProperty("brideId"), type + 1));
} else {
chr.getMap().broadcastMessage(Packages.tools.packets.Wedding.OnWeddingProgress(type == 2, eim.getIntProperty("brideId"), eim.getIntProperty("groomId"), type + 1));
}
}
function hidePriestMsg(eim) {
sendWeddingAction(eim, 2);
}
function showStartMsg(eim) {
eim.getMapInstance(entryMap + 10).broadcastMessage(Packages.tools.packets.Wedding.OnWeddingProgress(false, 0, 0, 0));
eim.schedule("hidePriestMsg", forceHideMsgTime * 1000);
}
function showBlessMsg(eim) {
eim.getMapInstance(entryMap + 10).broadcastMessage(Packages.tools.packets.Wedding.OnWeddingProgress(false, 0, 0, 1));
eim.setIntProperty("guestBlessings", 1);
eim.schedule("hidePriestMsg", forceHideMsgTime * 1000);
}
function showMarriedMsg(eim) {
sendWeddingAction(eim, 1);
eim.schedule("hidePriestMsg", 10 * 1000);
eim.restartEventTimer(partyTime * 60000);
}
function scheduledTimeout(eim) {
if(eim.getIntProperty("canJoin") == 1) {
em.getChannelServer().closeOngoingWedding(isCathedral);
eim.setIntProperty("canJoin", 0);
var mapobj = eim.getMapInstance(entryMap);
var chr = mapobj.getCharacterById(eim.getIntProperty("groomId"));
if(chr != null) {
chr.changeMap(entryMap + 10, "we00");
}
chr = mapobj.getCharacterById(eim.getIntProperty("brideId"));
if(chr != null) {
chr.changeMap(entryMap + 10, "we00");
}
mapobj.dropMessage(6, "Wedding Assistant: The couple are heading to the altar, hurry hurry talk to me to arrange your seat.");
eim.setIntProperty("weddingStage", 1);
eim.schedule("showStartMsg", startMsgTime * 60 * 1000);
eim.schedule("showBlessMsg", blessMsgTime * 60 * 1000);
eim.schedule("stopBlessings", blessingsTime * 60 * 1000);
eim.startEventTimer(ceremonyTime * 60000);
} else {
end(eim);
}
}
function playerUnregistered(eim, player) {}
function playerExit(eim, player) {
eim.unregisterPlayer(player);
player.changeMap(exitMap, 0);
}
function playerLeft(eim, player) {
if(!eim.isEventCleared()) {
playerExit(eim, player);
}
}
function isMarrying(eim, player) {
var playerid = player.getId();
return playerid == eim.getIntProperty("groomId") || playerid == eim.getIntProperty("brideId");
}
function changedMap(eim, player, mapid) {
if (mapid < minMapId || mapid > maxMapId) {
if (isMarrying(eim, player)) {
eim.unregisterPlayer(player);
end(eim);
}
else
eim.unregisterPlayer(player);
}
}
function changedLeader(eim, leader) {}
function playerDead(eim, player) {}
function playerRevive(eim, player) { // player presses ok on the death pop up.
if (isMarrying(eim, player)) {
eim.unregisterPlayer(player);
end(eim);
}
else
eim.unregisterPlayer(player);
}
function playerDisconnected(eim, player) {
if (isMarrying(eim, player)) {
eim.unregisterPlayer(player);
end(eim);
}
else
eim.unregisterPlayer(player);
}
function leftParty(eim, player) {}
function disbandParty(eim) {}
function monsterValue(eim, mobId) {
return 1;
}
function end(eim) {
var party = eim.getPlayers();
for (var i = 0; i < party.size(); i++) {
playerExit(eim, party.get(i));
}
eim.dispose();
}
function giveRandomEventReward(eim, player) {
eim.giveEventReward(player);
}
function clearPQ(eim) {
eim.stopEventTimer();
eim.setEventCleared();
}
function isCakeBoss(mob) {
return mob.getId() == 9400606;
}
function monsterKilled(mob, eim) {
if(isCakeBoss(mob)) {
eim.showClearEffect();
eim.clearPQ();
}
}
function allMonstersDead(eim) {}
function cancelSchedule() {}
function dispose(eim) {}
| ronancpl/MapleSolaxiaV2 | scripts/event/WeddingChapel.js | JavaScript | agpl-3.0 | 8,827 |
๏ปฟ// store: hempazonia
// Establish primary function wrapper
(function () {
'use strict';
var app = angular.module('app.avengers');
app.run(['routehelper', function (routehelper) {
routehelper.configureRoutes(getRoutes());
}]);
function getRoutes() {
return [
{
url: '/avengers',
config: {
templateUrl: 'app/avengers/avengers.html',
title: 'avengers',
settings: {
nav: 2,
content: '<i class="fa fa-lock"></i> Avengers'
}
}
}
];
}
// End primary function wrapper
})(); | rwebaz/Simple-Angular-js | JohnPappa0js/JohnPappa0js/app/avengers/config.route.js | JavaScript | agpl-3.0 | 721 |
OC.L10N.register(
"files_external",
{
"Please provide a valid app key and secret." : "่ฏทๆไพๆๆ็ๅบ็จkeyๅsecret",
"Step 1 failed. Exception: %s" : "ๆญฅ้ชค 1 ๅคฑ่ดฅใๅผๅธธ๏ผ%s",
"Step 2 failed. Exception: %s" : "ๆญฅ้ชค 2 ๅคฑ่ดฅใๅผๅธธ๏ผ%s",
"External storage" : "ๅค้จๅญๅจ",
"Dropbox App Configuration" : "Dropbox ๅบ็จ้
็ฝฎ",
"Google Drive App Configuration" : "Google Drive ๅบ็จ้
็ฝฎ",
"Personal" : "ไธชไบบ",
"System" : "็ณป็ป",
"Grant access" : "ๆๆ",
"Error configuring OAuth1" : "้
็ฝฎOAuth1ๆถๅบ้",
"Error configuring OAuth2" : "้
็ฝฎOAuth2ๆถๅบ้",
"Generate keys" : "็ๆๅฏ้ฅ",
"Error generating key pair" : "็ๆๅฏ้ฅๆถๅบ้",
"Saved" : "ๅทฒไฟๅญ",
"There was an error with message: " : "ๅ็้่ฏฏ๏ผ",
"External mount error" : "ๅค้จๆ่ฝฝ้่ฏฏ",
"external-storage" : "ๅค้จๅญๅจ",
"Username" : "็จๆทๅ",
"Password" : "ๅฏ็ ",
"Credentials saved" : "ๅญ่ฏๅทฒไฟๅญ",
"Credentials saving failed" : "ๅญ่ฏไฟๅญๅคฑ่ดฅ",
"Save" : "ไฟๅญ",
"Invalid mount point" : "ๆ ๆ็ๆ่ฝฝ็น",
"%s" : "%s",
"Access key" : "Access key",
"Secret key" : "Secret key",
"API key" : "APIๅฏๅ",
"RSA public key" : "RSA ๅ
ฌ้ฅ",
"Public key" : "ๅ
ฌ้ฅ",
"Amazon S3" : "Amazon S3",
"Hostname" : "ไธปๆบๅ",
"Port" : "็ซฏๅฃ",
"Region" : "ๅฐๅบ",
"Enable SSL" : "ๅฏ็จ SSL",
"Enable Path Style" : "ๅฏ็จ Path Style",
"WebDAV" : "WebDAV",
"URL" : "URL",
"Remote subfolder" : "่ฟ็จๅญๆไปถๅคน",
"Secure https://" : "ๅฎๅ
จ https://",
"Dropbox" : "Dropbox",
"Google Drive" : "Google Drive",
"Local" : "ๆฌๅฐ",
"Location" : "ๅฐ็น",
"ownCloud" : "ownCloud",
"SFTP" : "SFTP",
"Host" : "ไธปๆบ",
"Root" : "ๆ น่ทฏๅพ",
"SFTP with secret key login" : "ๅ
ๅซsecret key็SFTP",
"SMB / CIFS" : "SMB / CIFS",
"Share" : "ๅ
ฑไบซ",
"Domain" : "ๅๅ",
"SMB / CIFS using OC login" : "SMB / CIFS ไฝฟ็จ OC ็ปๅฝไฟกๆฏ",
"OpenStack Object Storage" : "OpenStack ๅฏน่ฑกๅญๅจ",
"Service name" : "ๆๅกๅ็งฐ",
"<b>Note:</b> " : "<b>ๆณจๆ๏ผ</b>",
"<b>Note:</b> The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>ๆณจๆ๏ผ</b> PHP ไธญ็ cURL ๆฏๆๆชๅฏ็จๆๆชๅฎ่ฃ
ใๅฏน %s ็ๆ่ฝฝๆ ๆณ่ฟ่กใ่ฏท่็ณป็ณป็ป็ฎก็ๅ่ฟ่กๅฎ่ฃ
ใ",
"<b>Note:</b> \"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>ๆณจๆ๏ผ</b>โ%sโๅฐๆชๅฎ่ฃ
ใๅฏน %s ็ๆ่ฝฝๆ ๆณ่ฟ่กใ่ฏท่็ณป็ณป็ป็ฎก็ๅ่ฟ่กๅฎ่ฃ
ใ",
"No external storage configured" : "ๆช้
็ฝฎๅค้จๅญๅจ",
"You can add external storages in the personal settings" : "ๆจๅฏไปฅๅจไธชไบบ่ฎพ็ฝฎไธญๆทปๅ ๅค้จๅญๅจ",
"Name" : "ๅ็งฐ",
"Storage type" : "ๅญๅจ็ฑปๅ",
"Scope" : "้็จ่ๅด",
"Enable encryption" : "ๅฏ็จๅ ๅฏ",
"Enable previews" : "ๅฏ็จ้ข่ง",
"Enable sharing" : "ๅฏ็จๅไบซ",
"Check for changes" : "ๆฃๆฅๆดๆน",
"Never" : "ไปไธ",
"External Storage" : "ๅค้จๅญๅจ",
"Folder name" : "็ฎๅฝๅ็งฐ",
"Authentication" : "่ฎค่ฏ",
"Configuration" : "้
็ฝฎ",
"Available for" : "ๅฏ็จไบ",
"Add storage" : "ๅขๅ ๅญๅจ",
"Advanced settings" : "้ซ็บง้้กน",
"Delete" : "ๅ ้ค",
"Allow users to mount external storage" : "ๅ
่ฎธ็จๆทๆ่ฝฝๅค้จๅญๅจ",
"Allow users to mount the following external storage" : "ๅ
่ฎธ็จๆทๆ่ฝฝไปฅไธๅค้จๅญๅจ"
},
"nplurals=1; plural=0;");
| IljaN/core | apps/files_external/l10n/zh_CN.js | JavaScript | agpl-3.0 | 3,698 |
'use strict';
/*ยฉagpl*************************************************************************
* *
* This file is part of FRIEND UNIFYING PLATFORM. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
*****************************************************************************ยฉ*/
var log = require('./Log')('DbAccount');
var events = require('events');
var uuid = require( './UuidPrefix' )( 'account' );
var conf = require( './Config' );
var accountDefaults = global.config.server.defaults.account;
var nativeKeys = {
'name' : true,
};
this.DbAccount = function( pool, friendId, accountId ) {
if ( !pool )
throw new Error( 'missing params' );
const self = this;
self.pool = pool;
self.friendId = String( friendId ) || null;
self.accountId = accountId;
}
this.DbAccount.prototype.close = function() {
const self = this;
delete self.pool;
delete self.friendId;
}
this.DbAccount.prototype.get = async function( clientId ) {
const self = this;
if ( !self.friendId )
throw new Error( 'account.get - self.friendId not set' );
const values = [ self.friendId ];
if ( clientId )
values.push( clientId );
else
values.push( null );
const query = self.buildCall( 'account_get', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'get - query ex', ex );
return false;
}
let accounts = res[ 0 ];
accounts = accounts.map( parseSettings );
accounts = accounts.map( setDefaults );
if ( clientId )
return accounts[ 0 ];
else
return accounts;
function parseSettings( account ) {
const settingsObj = parse( account.settings ) || {};
account.settings = settingsObj;
return account;
}
function setDefaults( account ) {
account = global.config.setMissing( account, accountDefaults );
return account;
}
}
this.DbAccount.prototype.set = async function( account ) {
const self = this;
const fields = [
'clientId',
'userId',
'name',
'settings',
];
account.clientId = uuid.v4();
account.settings = stringify( accountDefaults.settings );
const values = [];
fields.forEach( add );
function add( field, index ) {
values[ index ] = account[ field ];
}
const query = self.buildCall( 'account_set', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'set - query ex', ex );
return false;
}
return account.clientId;
}
this.DbAccount.prototype.touch = async function( clientId ) {
const self = this;
const values = [ clientId ];
const query = self.buildCall( 'account_touch', values.length );
try {
await self.pool.query( query, values );
} catch( ex ) {
log( 'touch - query ex', ex );
return false;
}
return true;
}
this.DbAccount.prototype.getAccountId = async function( name ) {
const self = this;
const values = [
self.friendId,
name,
];
const query = self.buildCall( 'account_get_id', values.length );
let res;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'getAccountId - query ex', ex );
return false;
}
const account = res[ 0 ][ 0 ];
if ( !account ) {
log( 'getAccountId - no account', {
values : values,
res : res,
});
return false;
}
return account.clientId;
}
this.DbAccount.prototype.update = async function( account ) {
const self = this;
if ( !account.clientId )
throw new Error( 'dbAccount.update - clientId required' );
const keys = [
'clientId',
'settings',
];
const values = keys.map( add );
const query = self.buildCall( 'account_update', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'update - query ex', ex );
return false;
}
return true;
function add( key ) {
var value = account[ key ];
if ( typeof value === 'undefined' )
value = null;
return value;
}
}
this.DbAccount.prototype.updateSetting = async function( data ) {
const self = this;
const clientId = data.clientId
const account = {
clientId : clientId,
};
if ( isNative( data.setting )) {
account[ data.setting ] = data.value;
return await self.update( account );
}
let row = null;
row = await self.get( clientId );
if ( !row )
return false;
const settings = row.settings || {};
settings[ data.setting ] = data.value;
account.settings = stringify( settings );
return await self.update( account );
function isNative( key ) { return !!nativeKeys[ key ]; }
}
this.DbAccount.prototype.updatePass = async function( currentPass, newPass ) {
const self = this;
throw new Error( 'DbAccount.updatePass - not yet implemented' );
}
this.DbAccount.prototype.remove = async function( clientId ) {
const self = this;
const values = [ clientId ];
const query = self.buildCall( 'account_remove', values.length );
let res = null;
try {
res = await self.pool.query( query, values, removeBack );
} catch( ex ) {
log( 'remove - query ex', ex );
return false;
}
return clientId;
}
// activuty
this.DbAccount.prototype.setActivity = async function( activityId, timestamp, event ) {
const self = this;
if ( !activityId || !timestamp ) {
log( 'setActivity - invalid things', [ activityId, timestamp ]);
resolve( false );
return;
}
const eventStr = stringify( event );
if ( !eventStr || !eventStr.length ) {
log( 'setActivity - invalid event', event );
resolve( false );
return;
}
const values = [
activityId,
timestamp,
eventStr,
self.accountId,
];
const query = self.buildCall( 'activity_set', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'setActivity - query ex', ex );
return false;
}
return eventStr;
}
this.DbAccount.prototype.getActivity = async function() {
const self = this;
const values = [ self.accountId ];
const query = self.buildCall( 'activity_get', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'getActivity - query ex', ex );
return null;
}
const rows = res[ 0 ];
const items = {};
rows.map( row => {
const id = row.clientId;
const eventStr = row.event;
const event = parse( eventStr );
items[ id ] = event;
});
return items;
}
this.DbAccount.prototype.removeActivity = async function( activityId ) {
const self = this;
if ( null == activityId )
throw new Error( '' );
const values = [
activityId,
];
const query = self.buildCall( 'activity_remove_item', values.length );
let res = null;
try {
res = await self.pool.query( query, values );
} catch( ex ) {
log( 'removeActivity - query ex', ex );
return false;
}
return true;
}
this.DbAccount.prototype.clearActivities = async function( accountId ) {
const self = this;
log( 'clearActivities - NYI', accountId );
}
// things
this.DbAccount.prototype.buildCall = function( procName, paramsLength ) {
const self = this;
const phStr = self.getPlaceholderString( paramsLength );
const call = "CALL " + procName + "(" + phStr + ")";
return call;
}
this.DbAccount.prototype.getPlaceholderString = function( length ) {
const arr = new Array( length );
let str = arr.join( '?,' );
str += '?';
return str;
}
module.exports = this.DbAccount;
// Helpers
function parse( string ) {
try {
return JSON.parse( string );
} catch ( e ) {
return null;
}
}
function stringify( obj ) {
try {
return JSON.stringify( obj );
} catch( e ) {
return '';
}
}
| FriendSoftwareLabs/friendchat | server/component/DbAccount.js | JavaScript | agpl-3.0 | 8,629 |
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
queryInterface.addColumn(
'Users',
'receiveNotifications',
Sequelize.BOOLEAN
);
},
down: (queryInterface, Sequelize) => {
queryInterface.removeColumn(
'Users',
'receiveNotifications'
);
}
};
| worknenjoy/gitpay | migration/migrations/20190118000232-add-receive-notifications-to-user.js | JavaScript | agpl-3.0 | 317 |
/*
* This file is part of FacturaSctipts
* Copyright (C) 2014-2015 Carlos Garcia Gomez neorazorx@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var numlineas = 0;
var fs_nf0 = 2;
var all_impuestos = [];
var all_series = [];
var proveedor = false;
var nueva_compra_url = '';
var kiwimaru_url = '';
var precio_compra = 'coste';
var fin_busqueda1 = true;
var fin_busqueda2 = true;
var siniva = false;
var irpf = 0;
var tiene_recargo = false;
function usar_proveedor(codproveedor)
{
if(nueva_compra_url !== '')
{
$.getJSON(nueva_compra_url, 'datosproveedor='+codproveedor, function(json) {
proveedor = json;
document.f_buscar_articulos.codproveedor.value = proveedor.codproveedor;
if(proveedor.regimeniva == 'Exento')
{
irpf = 0;
for(var j=0; j<numlineas; j++)
{
if($("#linea_"+j).length > 0)
{
$("#iva_"+j).val(0);
$("#recargo_"+j).val(0);
}
}
}
recalcular();
});
}
}
function usar_serie()
{
for(var i=0; i<all_series.length; i++)
{
if(all_series[i].codserie == $("#codserie").val())
{
siniva = all_series[i].siniva;
irpf = all_series[i].irpf;
for(var j=0; j<numlineas; j++)
{
if($("#linea_"+j).length > 0)
{
if(siniva)
{
$("#iva_"+j).val(0);
$("#recargo_"+j).val(0);
}
}
}
break;
}
}
}
function recalcular()
{
var l_uds = 0;
var l_pvp = 0;
var l_dto = 0;
var l_neto = 0;
var l_iva = 0;
var l_irpf = 0;
var l_recargo = 0;
var neto = 0;
var total_iva = 0;
var total_irpf = 0;
var total_recargo = 0;
for(var i=0; i<numlineas; i++)
{
if($("#linea_"+i).length > 0)
{
l_uds = parseFloat( $("#cantidad_"+i).val() );
l_pvp = parseFloat( $("#pvp_"+i).val() );
l_dto = parseFloat( $("#dto_"+i).val() );
l_neto = l_uds*l_pvp*(100-l_dto)/100;
l_iva = parseFloat( $("#iva_"+i).val() );
l_irpf = parseFloat( $("#irpf_"+i).val() );
if(tiene_recargo)
{
l_recargo = parseFloat( $("#recargo_"+i).val() );
}
else
{
l_recargo = 0;
$("#recargo_"+i).val(0);
}
$("#neto_"+i).val( l_neto );
if(numlineas == 1)
{
$("#total_"+i).val( fs_round(l_neto, fs_nf0) + fs_round(l_neto*(l_iva-l_irpf+l_recargo)/100, fs_nf0) );
}
else
{
$("#total_"+i).val( number_format(l_neto + (l_neto*(l_iva-l_irpf+l_recargo)/100), fs_nf0, '.', '') );
}
neto += l_neto;
total_iva += l_neto * l_iva/100;
total_irpf += l_neto * l_irpf/100;
total_recargo += l_neto * l_recargo/100;
}
}
neto = fs_round(neto, fs_nf0);
total_iva = fs_round(total_iva, fs_nf0);
total_irpf = fs_round(total_irpf, fs_nf0);
total_recargo = fs_round(total_recargo, fs_nf0);
$("#aneto").html( show_numero(neto) );
$("#aiva").html( show_numero(total_iva) );
$("#are").html( show_numero(total_recargo) );
$("#airpf").html( '-'+show_numero(total_irpf) );
$("#atotal").val( neto + total_iva - total_irpf + total_recargo );
if(total_recargo == 0 && !tiene_recargo)
{
$(".recargo").hide();
}
else
{
$(".recargo").show();
}
if(total_irpf == 0 && irpf == 0)
{
$(".irpf").hide();
}
else
{
$(".irpf").show();
}
}
function ajustar_neto()
{
var l_uds = 0;
var l_pvp = 0;
var l_dto = 0;
var l_neto = 0;
for(var i=0; i<numlineas; i++)
{
if($("#linea_"+i).length > 0)
{
l_uds = parseFloat( $("#cantidad_"+i).val() );
l_pvp = parseFloat( $("#pvp_"+i).val() );
l_dto = parseFloat( $("#dto_"+i).val() );
l_neto = parseFloat( $("#neto_"+i).val() );
if( isNaN(l_neto) )
l_neto = 0;
if( l_neto <= l_pvp*l_uds )
{
l_dto = 100 - 100*l_neto/(l_pvp*l_uds);
if( isNaN(l_dto) )
l_dto = 0;
}
else
{
l_dto = 0;
l_pvp = 100*l_neto/(l_uds*(100-l_dto));
if( isNaN(l_pvp) )
l_pvp = 0;
}
$("#pvp_"+i).val(l_pvp);
$("#dto_"+i).val(l_dto);
}
}
recalcular();
}
function ajustar_total()
{
var l_uds = 0;
var l_pvp = 0;
var l_dto = 0;
var l_iva = 0;
var l_irpf = 0;
var l_recargo = 0;
var l_neto = 0;
var l_total = 0;
for(var i=0; i<numlineas; i++)
{
if($("#linea_"+i).length > 0)
{
l_uds = parseFloat( $("#cantidad_"+i).val() );
l_pvp = parseFloat( $("#pvp_"+i).val() );
l_dto = parseFloat( $("#dto_"+i).val() );
l_iva = parseFloat( $("#iva_"+i).val() );
l_recargo = parseFloat( $("#recargo_"+i).val() );
l_irpf = irpf;
if(l_iva <= 0)
l_irpf = 0;
l_total = parseFloat( $("#total_"+i).val() );
if( isNaN(l_total) )
l_total = 0;
if( l_total <= l_pvp*l_uds + (l_pvp*l_uds*(l_iva-l_irpf+l_recargo)/100) )
{
l_neto = 100*l_total/(100+l_iva-l_irpf+l_recargo);
l_dto = 100 - 100*l_neto/(l_pvp*l_uds);
if( isNaN(l_dto) )
l_dto = 0;
}
else
{
l_dto = 0;
l_neto = 100*l_total/(100+l_iva-l_irpf+l_recargo);
l_pvp = l_neto/l_uds;
}
$("#pvp_"+i).val(l_pvp);
$("#dto_"+i).val(l_dto);
}
}
recalcular();
}
function ajustar_iva(num)
{
if($("#linea_"+num).length > 0)
{
if(siniva && $("#iva_"+num).val() != 0)
{
$("#iva_"+num).val(0);
$("#recargo_"+num).val(0);
alert('La serie selecciona es sin IVA.');
}
else if(tiene_recargo)
{
for(var i=0; i<all_impuestos.length; i++)
{
if($("#iva_"+num).val() == all_impuestos[i].iva)
{
$("#recargo_"+num).val(all_impuestos[i].recargo);
}
}
}
}
recalcular();
}
function aux_all_impuestos(num,codimpuesto)
{
var iva = 0;
var recargo = 0;
if(proveedor.regimeniva != 'Exento' && !siniva)
{
for(var i=0; i<all_impuestos.length; i++)
{
if(all_impuestos[i].codimpuesto == codimpuesto)
{
iva = all_impuestos[i].iva;
if(tiene_recargo)
{
recargo = all_impuestos[i].recargo;
}
break;
}
}
}
var html = "<td><select id=\"iva_"+num+"\" class=\"form-control\" name=\"iva_"+num+"\" onchange=\"ajustar_iva('"+num+"')\">";
for(var i=0; i<all_impuestos.length; i++)
{
if(iva == all_impuestos[i].iva)
{
html += "<option value=\""+all_impuestos[i].iva+"\" selected=\"selected\">"+all_impuestos[i].descripcion+"</option>";
}
else
html += "<option value=\""+all_impuestos[i].iva+"\">"+all_impuestos[i].descripcion+"</option>";
}
html += "</select></td>";
html += "<td class=\"recargo\"><input type=\"text\" class=\"form-control text-right\" id=\"recargo_"+num+"\" name=\"recargo_"+num+
"\" value=\""+recargo+"\" onclick=\"this.select()\" onkeyup=\"recalcular()\" autocomplete=\"off\"/></td>";
html += "<td class=\"irpf\"><input type=\"text\" class=\"form-control text-right\" id=\"irpf_"+num+"\" name=\"irpf_"+num+
"\" value=\""+irpf+"\" onclick=\"this.select()\" onkeyup=\"recalcular()\" autocomplete=\"off\"/></td>";
return html;
}
function add_articulo(ref,desc,pvp,dto,codimpuesto)
{
desc = Base64.decode(desc);
$("#lineas_albaran").append("<tr id=\"linea_"+numlineas+"\">\n\
<td><input type=\"hidden\" name=\"idlinea_"+numlineas+"\" value=\"-1\"/>\n\
<input type=\"hidden\" name=\"referencia_"+numlineas+"\" value=\""+ref+"\"/>\n\
<div class=\"form-control\"><a target=\"_blank\" href=\"index.php?page=ventas_articulo&ref="+ref+"\">"+ref+"</a></div></td>\n\
<td><textarea class=\"form-control\" id=\"desc_"+numlineas+"\" name=\"desc_"+numlineas+"\" rows=\"1\" onclick=\"this.select()\">"+desc+"</textarea></td>\n\
<td><input type=\"number\" step=\"any\" id=\"cantidad_"+numlineas+"\" class=\"form-control text-right\" name=\"cantidad_"+numlineas+
"\" onchange=\"recalcular()\" onkeyup=\"recalcular()\" autocomplete=\"off\" value=\"1\"/></td>\n\
<td><button class=\"btn btn-sm btn-danger\" type=\"button\" onclick=\"$('#linea_"+numlineas+"').remove();recalcular();\">\n\
<span class=\"glyphicon glyphicon-trash\"></span></button></td>\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"pvp_"+numlineas+"\" name=\"pvp_"+numlineas+"\" value=\""+pvp+
"\" onkeyup=\"recalcular()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
<td><input type=\"text\" id=\"dto_"+numlineas+"\" name=\"dto_"+numlineas+"\" value=\""+dto+
"\" class=\"form-control text-right\" onkeyup=\"recalcular()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"neto_"+numlineas+"\" name=\"neto_"+numlineas+
"\" onchange=\"ajustar_neto()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
"+aux_all_impuestos(numlineas,codimpuesto)+"\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"total_"+numlineas+"\" name=\"total_"+numlineas+
"\" onchange=\"ajustar_total()\" onclick=\"this.select()\" autocomplete=\"off\"/></td></tr>");
numlineas += 1;
$("#numlineas").val(numlineas);
recalcular();
$("#nav_articulos").hide();
$("#search_results").html('');
$("#kiwimaru_results").html('');
$("#nuevo_articulo").hide();
$("#modal_articulos").modal('hide');
$("#desc_"+(numlineas-1)).select();
return false;
}
function add_linea_libre()
{
codimpuesto = false;
for(var i=0; i<all_impuestos.length; i++)
{
codimpuesto = all_impuestos[i].codimpuesto;
break;
}
$("#lineas_albaran").append("<tr id=\"linea_"+numlineas+"\">\n\
<td><input type=\"hidden\" name=\"idlinea_"+numlineas+"\" value=\"-1\"/>\n\
<input type=\"hidden\" name=\"referencia_"+numlineas+"\"/>\n\
<div class=\"form-control\"></div></td>\n\
<td><textarea class=\"form-control\" id=\"desc_"+numlineas+"\" name=\"desc_"+numlineas+"\" rows=\"1\" onclick=\"this.select()\"></textarea></td>\n\
<td><input type=\"number\" step=\"any\" id=\"cantidad_"+numlineas+"\" class=\"form-control text-right\" name=\"cantidad_"+numlineas+
"\" onchange=\"recalcular()\" onkeyup=\"recalcular()\" autocomplete=\"off\" value=\"1\"/></td>\n\
<td><button class=\"btn btn-sm btn-danger\" type=\"button\" onclick=\"$('#linea_"+numlineas+"').remove();recalcular();\">\n\
<span class=\"glyphicon glyphicon-trash\"></span></button></td>\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"pvp_"+numlineas+"\" name=\"pvp_"+numlineas+"\" value=\"0\"\n\
onkeyup=\"recalcular()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
<td><input type=\"text\" id=\"dto_"+numlineas+"\" name=\"dto_"+numlineas+"\" value=\"0\" class=\"form-control text-right\"\n\
onkeyup=\"recalcular()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"neto_"+numlineas+"\" name=\"neto_"+numlineas+
"\" onchange=\"ajustar_neto()\" onclick=\"this.select()\" autocomplete=\"off\"/></td>\n\
"+aux_all_impuestos(numlineas,codimpuesto)+"\n\
<td><input type=\"text\" class=\"form-control text-right\" id=\"total_"+numlineas+"\" name=\"total_"+numlineas+
"\" onchange=\"ajustar_total()\" onclick=\"this.select()\" autocomplete=\"off\"/></td></tr>");
numlineas += 1;
$("#numlineas").val(numlineas);
recalcular();
$("#desc_"+(numlineas-1)).select();
return false;
}
function get_precios(ref)
{
if(nueva_compra_url !== '')
{
$.ajax({
type: 'POST',
url: nueva_compra_url,
dataType: 'html',
data: "referencia4precios="+ref+"&codproveedor="+proveedor.codproveedor,
success: function(datos) {
$("#nav_articulos").hide();
$("#search_results").html(datos);
}
});
}
}
function new_articulo()
{
if(nueva_compra_url !== '')
{
$.ajax({
type: 'POST',
url: nueva_compra_url+'&new_articulo=TRUE',
dataType: 'json',
data: $("form[name=f_nuevo_articulo]").serialize(),
success: function(datos) {
document.f_buscar_articulos.query.value = document.f_nuevo_articulo.referencia.value;
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_mis_articulos").addClass('active');
$("#search_results").html('');
$("#search_results").show('');
$("#kiwimaru_results").hide();
$("#nuevo_articulo").hide();
if(precio_compra == 'coste')
{
add_articulo(datos[0].referencia, Base64.encode(datos[0].descripcion), datos[0].coste, 0, datos[0].codimpuesto);
}
else
{
add_articulo(datos[0].referencia, Base64.encode(datos[0].descripcion), datos[0].pvp, 0, datos[0].codimpuesto);
}
}
});
}
}
function buscar_articulos()
{
document.f_nuevo_articulo.referencia.value = document.f_buscar_articulos.query.value;
document.f_nuevo_articulo.refproveedor.value = document.f_buscar_articulos.query.value;
if(document.f_buscar_articulos.query.value == '')
{
$("#nav_articulos").hide();
$("#search_results").html('');
$("#kiwimaru_results").html('');
$("#nuevo_articulo").hide();
fin_busqueda1 = true;
fin_busqueda2 = true;
}
else
{
$("#nav_articulos").show();
if(nueva_compra_url !== '')
{
fin_busqueda1 = false;
$.getJSON(nueva_compra_url, $("form[name=f_buscar_articulos]").serialize(), function(json) {
var items = [];
var insertar = false;
$.each(json, function(key, val) {
var descripcion = Base64.encode(val.descripcion);
var precio = val.coste;
if(precio_compra == 'pvp')
{
precio = val.pvp;
}
var tr_aux = '<tr>';
if(val.bloqueado)
{
tr_aux = "<tr class=\"bg-danger\">";
}
else if(val.stockfis < val.stockmin)
{
tr_aux = "<tr class=\"bg-warning\">";
}
else if(val.stockfis > val.stockmax)
{
tr_aux = "<tr class=\"bg-success\">";
}
if(val.secompra)
{
items.push(tr_aux+"<td><a href=\"#\" onclick=\"get_precios('"+val.referencia+"')\" title=\"mรกs detalles\">\n\
<span class=\"glyphicon glyphicon-eye-open\"></span></a>\n\
<a href=\"#\" onclick=\"return add_articulo('"
+val.referencia+"','"+descripcion+"','"+precio+"','"+val.dtopor+"','"+val.codimpuesto+"')\">"
+val.referencia+'</a> '+val.descripcion+"</td>\n\
<td class=\"text-right\"><a href=\"#\" onclick=\"return add_articulo('"
+val.referencia+"','"+descripcion+"','"+val.coste+"','"+val.dtopor+"','"+val.codimpuesto+"')\">"
+show_precio(val.coste)+"</a></td>\n\
<td class=\"text-right\"><a href=\"#\" onclick=\"return add_articulo('"
+val.referencia+"','"+descripcion+"','"+val.pvp+"','0','"+val.codimpuesto+"')\">"
+show_precio(val.pvp)+"</a></td>\n\
<td class=\"text-right\">"+val.stockfis+"</td></tr>");
}
if(val.query == document.f_buscar_articulos.query.value)
{
insertar = true;
fin_busqueda1 = true;
}
});
if(items.length == 0 && !fin_busqueda1)
{
items.push("<tr><td colspan=\"4\" class=\"bg-warning\">Sin resultados. Usa la pestaรฑa\n\
<b>Nuevo</b> para crear uno.</td></tr>");
document.f_nuevo_articulo.referencia.value = document.f_buscar_articulos.query.value;
insertar = true;
}
if(insertar)
{
$("#search_results").html("<div class=\"table-responsive\"><table class=\"table table-hover\"><thead><tr>\n\
<th class=\"text-left\">Referencia + descripciรณn</th><th class=\"text-right\">Coste</th>\n\
<th class=\"text-right\">Precio</th><th class=\"text-right\">Stock</th></tr></thead>"
+items.join('')+"</table></div>");
}
});
}
if(kiwimaru_url !== '')
{
fin_busqueda2 = false;
$.getJSON(kiwimaru_url, $("form[name=f_buscar_articulos]").serialize(), function(json) {
var items = [];
var insertar = false;
$.each(json, function(key, val) {
items.push( "<tr><td>"+val.sector+" / <a href=\""+val.link+"\" target=\"_blank\">"
+val.tienda+"</a> / "+val.familia+"</td>\n\
<td><a href=\""+val.link+"\" target=\"_blank\"><span class=\"glyphicon glyphicon-eye-open\"></span></a>\n\
<a href=\"#\" onclick=\"kiwi_import('"+val.referencia+"','"+val.descripcion+"','"+val.precio+"')\">"
+val.referencia+'</a> '+val.descripcion+"</td>\n\
<td class=\"text-right\"><a href=\"#\" onclick=\"kiwi_import('"
+val.referencia+"','"+val.descripcion+"','"+val.precio+"')\">"+show_precio(val.precio)+"</a></td></tr>" );
if(val.query == document.f_buscar_articulos.query.value)
{
insertar = true;
fin_busqueda2 = true;
}
});
if(items.length == 0 && !fin_busqueda2)
{
items.push("<tr><td colspan=\"3\" class=\"bg-warning\">Sin resultados.</td></tr>");
insertar = true;
}
if(insertar)
{
$("#kiwimaru_results").html("<p class=\"help-block\" style=\"padding: 5px;\">Estos son\n\
los resultados de <b>kiwimaru</b>, el potente buscador de tiendas online integrado en\n\
FacturaScripts, para que puedas buscar nuevos proveedores o simplemente comparar precios.\n\
Si deseas aรฑadir tus artรญculos a este buscador y ganar nuevos clientes fรกcilmente,\n\
<a href=\"https://www.facturascripts.com/comm3/index.php?page=community_feedback&feedback_privado=TRUE\" target=\"_blank\">\n\
contacta con nosotros</a>.</p>\n\
<div class=\"table-responsive\"><table class=\"table table-hover\"><thead><tr>\n\
<th class=\"text-left\">Sector / Tienda / Familia</th><th class=\"text-left\">Referencia + descripciรณn</th>\n\
<th class=\"text-right\">Precio+IVA</th></tr></thead>"+items.join('')+"</table></div>");
}
});
}
}
}
function kiwi_import(ref,desc,pvp)
{
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_nuevo_articulo").addClass('active');
$("#search_results").hide();
$("#kiwimaru_results").hide();
$("#nuevo_articulo").show();
document.f_nuevo_articulo.referencia.value = ref;
document.f_nuevo_articulo.refproveedor.value = ref;
document.f_nuevo_articulo.descripcion.value = desc;
document.f_nuevo_articulo.coste.value = pvp;
document.f_nuevo_articulo.pvp.value = pvp;
document.f_nuevo_articulo.referencia.select();
}
$(document).ready(function() {
$("#i_new_line").click(function() {
$("#i_new_line").val("");
document.f_buscar_articulos.query.value = "";
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_mis_articulos").addClass('active');
$("#nav_articulos").hide();
$("#search_results").html('');
$("#search_results").show('');
$("#kiwimaru_results").html('');
$("#kiwimaru_results").hide();
$("#nuevo_articulo").hide();
$("#modal_articulos").modal('show');
document.f_buscar_articulos.query.focus();
});
$("#i_new_line").keyup(function() {
document.f_buscar_articulos.query.value = $("#i_new_line").val();
$("#i_new_line").val('');
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_mis_articulos").addClass('active');
$("#nav_articulos").hide();
$("#search_results").html('');
$("#search_results").show('');
$("#kiwimaru_results").html('');
$("#kiwimaru_results").hide();
$("#nuevo_articulo").hide();
$("#modal_articulos").modal('show');
document.f_buscar_articulos.query.focus();
buscar_articulos();
});
$("#f_buscar_articulos").keyup(function() {
buscar_articulos();
});
$("#f_buscar_articulos").submit(function(event) {
event.preventDefault();
buscar_articulos();
});
$("#b_mis_articulos").click(function(event) {
event.preventDefault();
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_mis_articulos").addClass('active');
$("#kiwimaru_results").hide();
$("#nuevo_articulo").hide();
$("#search_results").show();
document.f_buscar_articulos.query.focus();
});
$("#b_kiwimaru").click(function(event) {
event.preventDefault();
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_kiwimaru").addClass('active');
$("#nuevo_articulo").hide();
$("#search_results").hide();
$("#kiwimaru_results").show();
document.f_buscar_articulos.query.focus();
});
$("#b_nuevo_articulo").click(function(event) {
event.preventDefault();
$("#nav_articulos li").each(function() {
$(this).removeClass("active");
});
$("#li_nuevo_articulo").addClass('active');
$("#search_results").hide();
$("#kiwimaru_results").hide();
$("#nuevo_articulo").show();
document.f_nuevo_articulo.referencia.select();
});
}); | Juanicos/facturacion_base | view/js/nueva_compra.js | JavaScript | agpl-3.0 | 24,045 |
import $ from 'jquery';
import {Example} from './modules/example';
new Example;
| RecaMedia/Backdoor | _development/js/init.js | JavaScript | agpl-3.0 | 81 |
/*
* app/src/BaseSource.js
*
*
* Copyright (C) 2015 Pierre Marchand <pierremarc07@gmail.com>
*
* License in LICENSE file at the root of the repository.
*
*/
'use strict';
var _ = require('underscore'),
rbush = require('rbush'),
O = require('../../lib/object'),
Geometry = require('../lib/Geometry');
var BaseSource = O.Object.extend({
constructor: function () {
this.tree = rbush();
this.index = {};
this.features = [];
O.Object.apply(this, arguments);
},
clear: function () {
this.index = {};
this.features = [];
this.tree.clear();
},
addFeature: function (f, skipSpatialIndex) {
this.features.push(f);
this.index[f.id] = this.features.length - 1;
if (!skipSpatialIndex) {
var geom = f.getGeometry(),
extent = _.assign({id: f.id}, geom.getExtent().getDictionary());
this.tree.insert(extent);
}
this.emit('add', f);
},
removeFeature: function (id) {
this.features.splice(this.index[id], 1);
delete this.index[id];
this.buildTree();
},
buildTree: function () {
var _ts = _.now(), _ts2;
var features = this.features,
flen = features.length,
items = [],
feature, geom, extent;
this.tree.clear();
for (var i = 0; i < flen; i++) {
feature = features[i];
extent = _.assign({id: feature.id},
feature.getExtent().getDictionary());
items.push(extent);
}
_ts2 = _.now() - _ts;
this.tree.load(items);
console.log('buildTree', flen, _ts2, _.now() - (_ts + _ts2));
},
getLength: function () {
return this.features.length;
},
getFeature: function (id) {
return this.features[this.index[id]];
},
getFeatures: function (opt_extent) {
var features = [], items, i;
if (opt_extent) {
if (opt_extent instanceof Geometry.Extent) {
items = this.tree.search(opt_extent.getDictionary());
}
else if (_.isArray(opt_extent)) { // we assume [minx, miny, maxx, maxy]
items = this.tree.search(
(new Geometry.Extent(opt_extent)).getDictionary());
}
else { // proper rbush dictionary?
items = this.tree.search(opt_extent);
}
for (i = 0; i < items.length; i++) {
var item = items[i];
features.push(
this.features[this.index[item.id]]
);
}
}
else {
return this.features;
}
return features;
},
});
//
// function str2ab(str) {
// var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
// var bufView = new Uint16Array(buf);
// for (var i=0, strLen=str.length; i < strLen; i++) {
// bufView[i] = str.charCodeAt(i);
// }
// return buf;
// }
module.exports = exports = BaseSource;
| atelier-cartographique/waend | app/src/BaseSource.js | JavaScript | agpl-3.0 | 3,108 |
var me = {
url: "/primarycontact.json",
params: {},
fields: {
email: function(me) {
return me.EmailAddress;
}
}
};
module.exports = me;
| saltt/oauthd | providers/campaign_monitor/me.js | JavaScript | agpl-3.0 | 181 |
/*
* Spreed Speak Freely.
* Copyright (C) 2013-2014 struktur AG
*
* This file is part of Spreed Speak Freely.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
define(['underscore', 'text!partials/roombar.html'], function(_, template) {
// roomBar
return ["$window", "$rootScope", "$location", function($window, $rootScope, $location) {
var link = function($scope) {
//console.log("roomBar directive link", arguments);
$scope.newroomid = $rootScope.roomid;
$scope.hideRoomBar = true;
$scope.save = function() {
var roomid = $scope.changeRoomToId($scope.newroomid);
if (roomid !== $rootScope.roomid) {
$scope.roombarform.$setPristine();
}
$scope.hideRoomBar = true;
};
$scope.hitEnter = function(evt){
if(angular.equals(evt.keyCode, 13)) {
$scope.save();
}
};
$scope.exit = function() {
$scope.newroomid = "";
$scope.save();
};
$rootScope.$watch("roomid", function(newroomid, roomid) {
if (!newroomid) {
newroomid = "";
}
$scope.newroomid = newroomid;
});
$scope.$watch("newroomid", function(newroomid) {
if (newroomid === $rootScope.roomid) {
$scope.roombarform.$setPristine();
}
});
};
return {
restrict: 'E',
replace: true,
scope: true,
template: template,
controller: "RoomchangeController",
link: link
}
}];
});
| cfrisemo/spreed-speakfreely | static/js/directives/roombar.js | JavaScript | agpl-3.0 | 2,419 |
import * as d3 from 'd3';
const GENEPANEL_ICON_WIDTH = 1.25;
const GENEPANEL_ICON_HEIGHT = 1.1;
const AlleleFreqPlotUtils = (function() {
var NO_DATA = undefined; // this was set by the patient view
// params: alt_counts (array of numbers), ref_counts (array of numbers)
// returns array of numbers
//
// returns an array of alt_count / (alt_count + ref_count). If either
// alt_count or ref_count equal NO_DATA, then returns 0 in that entry
//
// or, if there is no valid data, returns `undefined`
var process_data = function(alt_counts, ref_counts, caseId) {
// validate:
// * that data exists
var validated = _.find(alt_counts, function(data) {
return data[caseId] !== NO_DATA;
});
if (!validated) {
return undefined;
}
return d3.zip(alt_counts, ref_counts).map(function(pair) {
return (pair[0][caseId] === NO_DATA) === pair[1][caseId]
? 0
: pair[0][caseId] / (pair[0][caseId] + pair[1][caseId]);
});
};
// params: instance of GenomicEventObserver, from the patient view
//
// extracts the relevant data from the GenomicEventObserver and runs
// process_data
var extract_and_process = function(genomicEventObs, caseId) {
var alt_counts = genomicEventObs.mutations.data['alt-count'];
var ref_counts = genomicEventObs.mutations.data['ref-count'];
return process_data(alt_counts, ref_counts, caseId);
};
// params: variance, basically a smoothing parameter for this situation
//
// returns the gaussian function, aka kernel
var gaussianKernel = function(variance) {
var mean = 0;
return function(x) {
return (
(1 / (variance * Math.sqrt(2 * Math.PI))) *
Math.exp(
(-1 * Math.pow(x - mean, 2)) / (2 * Math.pow(variance, 2))
)
);
};
};
// params: kernel, list of points
//
// returns a function, call it kde, that takes a list of sample points, samples, and
// returns a list of pairs [x, y] where y is the average of
// kernel(sample - x)
// for all sample in samples
var kernelDensityEstimator = function(kernel, x) {
return function(sample) {
return x.map(function(z) {
return [
z,
d3.mean(sample, function(v) {
return kernel(z - v);
}),
];
});
};
};
// params: u, some number
// uniform kernel
var uniform = function(u) {
return Math.abs(u) <= 1 ? 0.5 * u : 0;
};
// Silverman's rule of thumb for calculating the bandwith parameter for
// kde with Gaussian kernel. Turns out that one can calculate the optimal
// bandwidth when using the Gaussian kernel (not a surprise). It turns out
// to basically be, a function of the variance of the data and the number
// of data points.
//
// http://en.wikipedia.org/wiki/Kernel_density_estimation#Practical_estimation_of_the_bandwidth
var calculate_bandwidth = function(data) {
var mean = d3.mean(data);
var variance = d3.mean(
data.map(function(d) {
return Math.pow(d - mean, 2);
})
);
var standard_deviation = Math.pow(variance, 0.5);
var bandwidth =
1.06 * standard_deviation * Math.pow(data.length, -1 / 5);
return bandwidth;
};
return {
process_data: process_data,
extract_and_process: extract_and_process,
kernelDensityEstimator: kernelDensityEstimator,
gaussianKernel: gaussianKernel,
calculate_bandwidth: calculate_bandwidth,
};
})();
export const AlleleFreqPlotMulti = function(
component,
data,
options,
order,
colors,
labels,
genepanel_icon_data
) {
// If nolegend is false, the div this is called on must be attached and
// rendered at call time or else Firefox will throw an error on the call
// to getBBox
var div = component.div;
//var fillcolors = d3.scale.category10();
// construct colors, if a duplicate found replace it with 'darker'
var colorhist = {};
if (!order) {
order = {};
}
if (Object.keys(order).length === 0) {
var order_ctr = 0;
for (var k in data) {
if (data.hasOwnProperty(k)) {
order[k] = order_ctr;
order_ctr += 1;
}
}
}
colors = $.extend(true, {}, colors);
for (var k in data) {
if (data.hasOwnProperty(k)) {
/*var ind = Object.keys(colors).length;
colors[k] = {stroke:fillcolors(ind), fill:fillcolors(ind)};*/
var col = d3.rgb(colors[k] || 'rgb(0,0,0)');
while (
col.toString() in colorhist &&
!(col.r === 0 && col.g === 0 && col.b === 0)
) {
col = col.darker(0.4);
}
var col_string = col.toString();
colorhist[col_string] = true;
colors[k] = { stroke: col_string, fill: col_string };
}
}
// data is a map of sample id to list of data
var options = options || {
label_font_size: '11.5px',
xticks: 3,
yticks: 8,
nolegend: false,
}; // init
var label_dist_to_axis = options.xticks === 0 ? 13 : 30;
options.margin = options.margin || {};
var margin = $.extend(
{ top: 20, right: 30, bottom: 30 + label_dist_to_axis / 2, left: 50 },
options.margin
);
var width = options.width || 200;
var height =
options.height ||
(500 + label_dist_to_axis) / 2 - margin.top - margin.bottom;
// x scale and axis
var x = d3.scale
.linear()
.domain([-0.1, 1])
.range([0, width]);
var xAxis = d3.svg
.axis()
.scale(x)
.orient('bottom')
.ticks(options.xticks);
var utils = AlleleFreqPlotUtils; // alias
// make kde's
var bandwidth = {};
var kde = {};
var plot_data = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
bandwidth[k] = Math.max(utils.calculate_bandwidth(data[k]), 0.01);
kde[k] = utils.kernelDensityEstimator(
utils.gaussianKernel(bandwidth[k]),
x.ticks(100)
);
plot_data[k] = kde[k](data[k]);
}
}
// make histograms
var histogram = d3.layout
.histogram()
.frequency(false)
.bins(x.ticks(30));
var binned_data = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
binned_data[k] = histogram(data[k]);
}
}
// calculate range of values that y takes
var all_plot_data = [];
for (var k in plot_data) {
if (plot_data.hasOwnProperty(k)) {
all_plot_data = all_plot_data.concat(plot_data[k]);
}
}
var ycoords = all_plot_data.map(function(d) {
return d[1];
});
var ydomain = [d3.min(ycoords), d3.max(ycoords)];
var y = d3.scale
.linear()
.domain(ydomain)
.range([height, 0]);
var line = d3.svg
.line()
.x(function(d) {
return x(d[0]);
})
.y(function(d) {
return y(d[1]);
});
var svg = d3
.select(div)
.append('svg')
.attr(
'width',
width +
margin.left +
(options.yticks === 0 ? 0 : margin.right) +
(options.nolegend ? 0 : 100)
)
.attr('height', height + margin.top + margin.bottom)
.attr('data-test', 'vaf-plot')
.append('g')
.attr(
'transform',
'translate(' +
(options.yticks === 0 ? margin.left / 2 : margin.left) +
',' +
margin.top +
')'
);
// x axis
var x_axis = svg
.append('g')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
// applies some common line and path css attributes to the selection. The
// only reason this isn't getting put into its own css file is due to the
// spectre of pdf export
var applyCss = function(selection) {
return selection
.attr('fill', 'none')
.attr('stroke', '#000')
.attr('shape-rendering', 'crispEdges');
};
applyCss(x_axis.selectAll('path'));
applyCss(x_axis.selectAll('line'));
// x-axis label
x_axis
.append('text')
//.attr("class", "label")
.attr('x', width / 2)
.attr('y', label_dist_to_axis)
.attr('font-size', options.label_font_size)
.style('text-anchor', 'middle')
.style('font-style', 'italic')
.text('variant allele frequency');
// make the y-axis mutation count
var all_binned_data = [];
for (var k in binned_data) {
if (binned_data.hasOwnProperty(k)) {
all_binned_data = all_binned_data.concat(binned_data[k]);
}
}
var mutation_counts = all_binned_data.map(function(d) {
return d.length;
});
var mutation_count_range = [0, d3.max(mutation_counts)];
// create y axis
var yAxis = d3.svg
.axis()
.scale(y.copy().domain(mutation_count_range))
.orient('left')
.ticks(options.yticks);
// render axis
var y_axis = svg.append('g').call(yAxis);
// takes a number and returns a displacement length for the
// yaxis label
//
// *signature:* `number -> number`
var displace_by_digits = function(n) {
var stringified = '' + n;
var no_digits = stringified.split('').length;
// there will be a comma in the string, i.e. 1,000 not 1000
if (no_digits >= 4) {
no_digits += 1.5;
}
return (no_digits * 7) / 3;
};
var ylabel_dist_to_axis = label_dist_to_axis;
ylabel_dist_to_axis +=
options.yticks === 0 ? 0 : displace_by_digits(mutation_count_range[1]);
// y axis label
y_axis
.append('text')
//.attr("class","label")
.attr('transform', 'rotate(-90)')
.attr('x', -height / 2)
.attr('y', -ylabel_dist_to_axis)
.attr('font-size', options.label_font_size)
.style('text-anchor', 'middle')
.style('font-style', 'italic')
.text('mutation count');
applyCss(y_axis.selectAll('path')).attr(
'display',
options.yticks === 0 ? '' : 'none'
);
applyCss(y_axis.selectAll('line'));
// calculate new domain for the binned data
var binned_yvalues = all_binned_data.map(function(d) {
return d.y;
});
var binned_ydomain = [d3.min(binned_yvalues), d3.max(binned_yvalues)];
var binned_yscale = y.copy();
binned_yscale.domain(binned_ydomain);
// make bar charts
for (var k in binned_data) {
if (binned_data.hasOwnProperty(k)) {
svg.selectAll('.bar')
.data(binned_data[k])
.enter()
.insert('rect')
.attr('x', function(d) {
return x(d.x) + 1;
})
.attr('y', function(d) {
return binned_yscale(d.y);
})
.attr('class', order[k] + '_viz_hist viz_hist')
.attr(
'width',
x(binned_data[k][0].dx + binned_data[k][0].x) -
x(binned_data[k][0].x) -
1
)
.attr('height', function(d) {
return height - binned_yscale(d.y);
})
.attr('fill', colors[k].fill)
.attr('opacity', Object.keys(data).length > 1 ? '0.1' : '0.3');
}
}
// make kde plots
for (var k in plot_data) {
if (plot_data.hasOwnProperty(k)) {
svg.append('path')
.datum(plot_data[k])
.attr('d', line)
.attr('class', 'curve ' + order[k] + '_viz_curve viz_curve')
.attr('fill', 'none')
.attr('stroke', colors[k].stroke)
.attr('stroke-width', '1.5px')
.attr('opacity', '0.9')
.attr('data-legend', function() {
return k;
})
.attr('data-legend-pos', function() {
return order[k];
});
}
}
// make legend
if (!options.nolegend && Object.keys(data).length > 1) {
var legend_font_size = 13;
var legend = svg
.append('g')
.attr('class', 'legend')
.attr('transform', 'translate(' + (width + 25) + ',0)')
.style('font-size', legend_font_size + 'px');
d3.legend(
component,
legend,
legend_font_size,
labels,
order,
genepanel_icon_data
);
}
return div;
};
// d3.legend.js
// (C) 2012 ziggy.jonsson.nyc@gmail.com
// Modifications by Adam Abeshouse adama@cbio.mskcc.org
// MIT licence
var highlightSample = function(div, k, order, show_histogram, show_curve) {
$(div)
.find('.viz_hist')
.hide();
$(div)
.find('.viz_curve')
.hide();
if (show_histogram) {
$(div)
.find('.' + order[k] + '_viz_hist')
.show();
$(div)
.find('.' + order[k] + '_viz_hist')
.attr('opacity', '0.5');
}
if (show_curve) {
$(div)
.find('.' + order[k] + '_viz_curve')
.show();
}
};
var showSamples = function(div, show_histogram, show_curve) {
if (show_histogram) {
$(div)
.find('.viz_hist')
.show();
$(div)
.find('.viz_hist')
.attr('opacity', '0.1');
}
if (show_curve) {
$(div)
.find('.viz_curve')
.show();
}
};
d3.legend = function(
component,
g,
font_size,
labels,
order,
genepanel_icon_data
) {
g.each(function() {
var g = d3.select(this),
items = {},
svg = d3.select(g.property('nearestViewportElement')),
legendPadding = g.attr('data-style-padding') || 5,
lb = g.selectAll('.legend-box').data([true]),
li = g.selectAll('.legend-items').data([true]);
li.enter()
.append('g')
.classed('legend-items', true);
svg.selectAll('[data-legend]').each(function() {
var self = d3.select(this);
items[self.attr('data-legend')] = {
pos: self.attr('data-legend-pos') || this.getBBox().y,
color:
self.attr('data-legend-color') != undefined
? self.attr('data-legend-color')
: self.style('fill') != 'none'
? self.style('fill')
: self.style('stroke'),
};
});
items = d3.entries(items).sort(function(a, b) {
return a.value.pos - b.value.pos;
});
var maxLabelLength = 10;
var spacing = 0.4;
// sample name text
li.selectAll('text')
.data(items, function(d) {
return d.key;
})
.call(function(d) {
d.enter().append('text');
})
.call(function(d) {
d.exit().remove();
})
.attr('y', function(d, i) {
return i - 0.2 + i * spacing + 'em';
})
.attr('x', 0.75 + GENEPANEL_ICON_WIDTH + 'em')
.text(function(d) {
var key = d.key;
var label =
key.length > maxLabelLength
? key.substring(0, 4) + '...' + key.slice(-3)
: key;
return label;
});
li.selectAll('circle')
.data(items, function(d) {
return d.key;
})
.call(function(d) {
d.enter().append('circle');
})
.call(function(d) {
d.exit().remove();
})
.attr('cy', function(d, i) {
return i - 0.5 + i * spacing + 'em';
})
.attr('cx', GENEPANEL_ICON_WIDTH + 'em')
.attr('r', '0.5em')
.style('fill', function(d) {
return d.value.color;
});
// sample index icon text
for (var i = 0, keys = Object.keys(items); i < keys.length; i++) {
li.append('text')
.attr('x', 0.4 + GENEPANEL_ICON_WIDTH + 'em')
.attr('y', (i - 0.5 + i * spacing) * font_size)
.attr('fill', 'white')
.attr('font-size', '10')
.attr('dy', '0.34em')
.attr('text-anchor', 'middle')
.text(labels[items[keys[i]].key])
.attr('class', 'sample-icon-text');
}
// gene panel icon
for (var i = 0, keys = Object.keys(items); i < keys.length; i++) {
var sample_id = items[i].key;
if (Object.keys(genepanel_icon_data).includes(sample_id)) {
var label = genepanel_icon_data[sample_id].label;
var color = genepanel_icon_data[sample_id].color;
li.append('rect')
.attr('x', '-0.75em')
.attr('y', i - 1.06 + i * spacing + 'em')
.attr('width', function(d) {
return GENEPANEL_ICON_WIDTH + 'em';
})
.attr('height', function(d) {
return GENEPANEL_ICON_HEIGHT + 'em';
})
.attr('rx', 4)
.attr('ry', 4)
.attr('fill', function(d) {
return color;
})
.attr('class', 'genepanel-icon');
li.append('text')
.attr('x', '-0.15em')
.attr('y', (i - 0.5 + i * spacing) * font_size)
.attr('fill', 'white')
.attr('font-size', '10')
.attr('dy', '0.34em')
.attr('text-anchor', 'middle')
.text(label)
.attr('class', 'genepanel-icon-text');
}
}
li.selectAll('rect:not(.genepanel-icon)')
.data(items, function(d) {
return d.key;
})
.call(function(d) {
d.enter().append('rect');
})
.call(function(d) {
d.exit().remove();
})
.attr('id', function(d) {
return d.key + 'legend_hover_rect';
})
.attr('y', function(d, i) {
return i - 1 + i * spacing - spacing / 2 + 'em';
})
.attr('x', '-1em')
.attr('width', function(d) {
return '117px';
})
.attr('height', 1 + spacing + 'em')
.style('fill', function(d) {
return d.value.color;
})
.attr('opacity', '0')
.on(
'mouseover',
Object.keys(items).length > 1
? function(d) {
$(this).attr('opacity', '0.2');
highlightSample(
component.div,
d.key,
order,
component.state.show_histogram,
component.state.show_curve
);
}
: function(d) {}
)
.on('mouseout', function(d) {
$(this).attr('opacity', '0');
});
for (var i = 0; i < items.length; i++) {
var k = items[i].key;
if (k.length > maxLabelLength) {
$('#' + k + 'legend_hover_rect').attr('title', k);
$('#' + k + 'legend_hover_rect').qtip({
content: { attr: 'title' },
style: { classes: 'qtip-light qtip-rounded' },
position: {
my: 'center left',
at: 'center right',
viewport: $(window),
},
});
}
}
li.on(
'mouseout',
Object.keys(items).length > 1
? function() {
showSamples(
component.div,
component.state.show_histogram,
component.state.show_curve
);
}
: function() {}
);
// Reposition and resize the box
var lbbox = li[0][0].getBBox();
lb.attr('x', lbbox.x - legendPadding)
.attr('y', lbbox.y - legendPadding)
.attr('height', lbbox.height + 2 * legendPadding)
.attr('width', lbbox.width + 2 * legendPadding);
});
return g;
};
| alisman/cbioportal-frontend | src/pages/patientView/vafPlot/legacyVAFCode.js | JavaScript | agpl-3.0 | 21,602 |
/*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
require('./angular-locale_fy-nl');
module.exports = 'ngLocale';
| Cineca/OrcidHub | src/main/webapp/bower_components/angular-i18n/fy-nl.js | JavaScript | agpl-3.0 | 763 |
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
define(['i18next', 'cs!app/views/base'], function(_arg, _arg1) {
var SMItemView, ServiceMapDisclaimersOverlayView, ServiceMapDisclaimersView, t;
t = _arg.t;
SMItemView = _arg1.SMItemView;
return {
ServiceMapDisclaimersView: ServiceMapDisclaimersView = (function(_super) {
__extends(ServiceMapDisclaimersView, _super);
function ServiceMapDisclaimersView() {
return ServiceMapDisclaimersView.__super__.constructor.apply(this, arguments);
}
ServiceMapDisclaimersView.prototype.template = 'description-of-service';
ServiceMapDisclaimersView.prototype.className = 'content modal-dialog about';
ServiceMapDisclaimersView.prototype.serializeData = function() {
return {
lang: p13n.getLanguage()
};
};
return ServiceMapDisclaimersView;
})(SMItemView),
ServiceMapDisclaimersOverlayView: ServiceMapDisclaimersOverlayView = (function(_super) {
__extends(ServiceMapDisclaimersOverlayView, _super);
function ServiceMapDisclaimersOverlayView() {
return ServiceMapDisclaimersOverlayView.__super__.constructor.apply(this, arguments);
}
ServiceMapDisclaimersOverlayView.prototype.template = 'disclaimers-overlay';
ServiceMapDisclaimersOverlayView.prototype.serializeData = function() {
var copyrightLink, layer;
layer = p13n.get('map_background_layer');
if (layer === 'servicemap' || layer === 'accessible_map') {
copyrightLink = "https://www.openstreetmap.org/copyright";
}
return {
copyright: t("disclaimer.copyright." + layer),
copyrightLink: copyrightLink
};
};
ServiceMapDisclaimersOverlayView.prototype.events = {
'click #about-the-service': 'onAboutClick'
};
ServiceMapDisclaimersOverlayView.prototype.onAboutClick = function(ev) {
return app.commands.execute('showServiceMapDescription');
};
return ServiceMapDisclaimersOverlayView;
})(SMItemView)
};
});
}).call(this);
//# sourceMappingURL=service-map-disclaimers.js.map
| vaaralav/servicemap | assets/js/views/service-map-disclaimers.js | JavaScript | agpl-3.0 | 2,541 |
(function() {
var Q, asserters, baseUrl, browseButtonSelector, browser, chai, chaiAsPromised, delay, errorDelay, pageTitle, pollFreq, searchButton, searchFieldPath, searchResultPath, serviceTreeItemSelector, should, typeaheadResultPath, wd;
Q = require('q');
chai = require('chai');
chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
should = chai.should();
wd = void 0;
browser = void 0;
asserters = void 0;
delay = 20000;
errorDelay = 1000;
pollFreq = 100;
baseUrl = 'http://localhost:9001';
pageTitle = 'Pรครคkaupunkiseudun palvelukartta';
serviceTreeItemSelector = '#service-tree-container > ul > li';
browseButtonSelector = '#browse-region';
searchResultPath = '#navigation-contents li';
searchButton = '#search-region > div > form > span.action-button.search-button > span';
searchFieldPath = '#search-region > div > form > span:nth-of-type(1) > input';
typeaheadResultPath = '#search-region span.twitter-typeahead span.tt-suggestions';
describe('Browser test', function() {
before(function() {
wd = this.wd;
chaiAsPromised.transferPromiseness = wd.transferPromiseness;
browser = this.browser;
return asserters = wd.asserters;
});
describe('Test navigation widget', function() {
it('Title should become "Pรครคkaupunkiseudun palvelukartta"', function(done) {
return browser.get(baseUrl).title().should.become(pageTitle).should.notify(done);
});
it('Should contain button "Selaa palveluita"', function(done) {
return browser.waitForElementByCss(browseButtonSelector, delay, pollFreq).click().should.be.fulfilled.should.notify(done);
});
it('Should contain list item "Terveys"', function(done) {
return browser.waitForElementByCss(serviceTreeItemSelector, asserters.textInclude('Terveys'), delay, pollFreq).should.be.fulfilled.should.notify(done);
});
return it('Should not contain list item "Sairaus"', function(done) {
return browser.waitForElementByCss(serviceTreeItemSelector, asserters.textInclude('Sairaus'), errorDelay, pollFreq).should.be.rejected.should.notify(done);
});
});
describe('Test look ahead', function() {
it('Title should become "Pรครคkaupunkiseudun palvelukartta"', function(done) {
return browser.get(baseUrl).title().should.become(pageTitle).should.notify(done);
});
return it('Should find item "Kallion kirjasto"', function(done) {
var searchText;
searchText = 'kallion kirjasto';
return browser.waitForElementByCss(searchFieldPath, delay, pollFreq).click().type(searchText).waitForElementByCss(typeaheadResultPath, asserters.textInclude("Kallion kirjasto"), delay, pollFreq).should.be.fulfilled.should.notify(done);
});
});
return describe('Test search', function() {
it('Title should become "Pรครคkaupunkiseudun palvelukartta"', function(done) {
return browser.get(baseUrl).title().should.become(pageTitle).should.notify(done);
});
it('Should manage to input search text', function(done) {
var searchText;
searchText = 'kallion kirjasto';
return browser.waitForElementByCss(searchFieldPath, delay, pollFreq).click().type(searchText).should.be.fulfilled.should.notify(done);
});
it('Should manage to click search button', function(done) {
return browser.waitForElementByCss(searchButton, delay, pollFreq).click().should.be.fulfilled.should.notify(done);
});
it('Should find item "Kallion kirjasto"', function(done) {
return browser.waitForElementByCss(searchResultPath, asserters.textInclude("Kallion kirjasto"), delay, pollFreq).should.be.fulfilled.should.notify(done);
});
return it('Should not find item "Kallio2n kirjasto"', function(done) {
return browser.waitForElementByCss(searchResultPath, asserters.textInclude("Kallio2n kirjasto"), errorDelay, pollFreq).should.be.rejected.should.notify(done);
});
});
});
}).call(this);
//# sourceMappingURL=promises-test.js.map
| vaaralav/servicemap | assets/test/promises-test.js | JavaScript | agpl-3.0 | 4,098 |
(function () {
"use strict"
angular.module("timesheetModule").controller("projectSearchOptionsFormController", ["$scope", "resource", function ($scope, resource) {
$scope.filterTasks = function (task) {
if ($scope.filteringTasks && $scope.taskNameSubstring) {
return task.name.toLowerCase().indexOf($scope.taskNameSubstring.toLowerCase()) >= 0
}
return true
}
$scope.resource = resource
resource.$get("tasks").then(function (tasks) {
$scope.tasks = tasks
})
}])
})() | saulo2/timesheet-java | src/main/webapp/js/projectSearchOptionsFormController.js | JavaScript | agpl-3.0 | 502 |
'use strict';
var should = require('should');
describe('COB', function ( ) {
var cob = require('../lib/plugins/cob')();
var profile = {
sens: 95
, carbratio: 18
, carbs_hr: 30
};
it('should calculate IOB, multiple treatments', function() {
var treatments = [
{
"carbs": "100",
"created_at": new Date("2015-05-29T02:03:48.827Z")
},
{
"carbs": "10",
"created_at": new Date("2015-05-29T03:45:10.670Z")
}
];
var after100 = cob.cobTotal(treatments, profile, new Date("2015-05-29T02:03:49.827Z"));
var before10 = cob.cobTotal(treatments, profile, new Date("2015-05-29T03:45:10.670Z"));
var after10 = cob.cobTotal(treatments, profile, new Date("2015-05-29T03:45:11.670Z"));
console.info('>>>>after100:', after100);
console.info('>>>>before10:', before10);
console.info('>>>>after2nd:', after10);
after100.cob.should.equal(100);
Math.round(before10.cob).should.equal(59);
Math.round(after10.cob).should.equal(69); //WTF == 128
});
it('should calculate IOB, single treatment', function() {
var treatments = [
{
"carbs": "8",
"created_at": new Date("2015-05-29T04:40:40.174Z")
}
];
var rightAfterCorrection = new Date("2015-05-29T04:41:40.174Z");
var later1 = new Date("2015-05-29T05:04:40.174Z");
var later2 = new Date("2015-05-29T05:20:00.174Z");
var later3 = new Date("2015-05-29T05:50:00.174Z");
var later4 = new Date("2015-05-29T06:50:00.174Z");
var result1 = cob.cobTotal(treatments, profile, rightAfterCorrection);
var result2 = cob.cobTotal(treatments, profile, later1);
var result3 = cob.cobTotal(treatments, profile, later2);
var result4 = cob.cobTotal(treatments, profile, later3);
var result5 = cob.cobTotal(treatments, profile, later4);
result1.cob.should.equal(8);
result2.cob.should.equal(6);
result3.cob.should.equal(0);
result4.cob.should.equal(0);
result5.cob.should.equal(0);
});
}); | sulkaharo/nightscout2 | tests/cob.test.js | JavaScript | agpl-3.0 | 2,029 |
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Soundscape = function () {
function Soundscape(scene) {
_classCallCheck(this, Soundscape);
this.listener = new THREE.AudioListener();
this.touchSound = new THREE.PositionalAudio(this.listener);
var audioLoader = new THREE.AudioLoader();
var me = this;
audioLoader.load('sounds/click.wav', function (buffer) {
me.touchSound.setBuffer(buffer);
me.touchSound.setRefDistance(20);
});
}
_createClass(Soundscape, [{
key: 'playTouchSound',
value: function playTouchSound(position) {
this.touchSound.position.copy(position);
this.touchSound.play();
}
}]);
return Soundscape;
}(); | marciot/html2three | js/dist-ecma5/Soundscape.js | JavaScript | agpl-3.0 | 1,450 |
define(["i18nObj","jquery"],function(a,b){b.extend(!0,a,{translations:{ar:{create_users_view:{required:"ุงูุฑุฌุงุก ุฅุฏุฎุงู ุจุนุถ ุนูุงููู ุงูุจุฑูุฏ ุงูุฅููุชุฑููู"}},es:{create_users_view:{required:"Introduzca algunas direcciones de correo electrรณnico"}},fr:{create_users_view:{required:"Veuillez indiquer des adresses e-mail"}},ja:{create_users_view:{required:"้ปๅญใกใผใซ ใขใใฌในใๅ
ฅๅใใฆใใ ใใ:"}},ko:{create_users_view:{required:"์ด๋ฉ์ผ ์ฃผ์ ์
๋ ฅ"}},nl:{create_users_view:{required:"Vul een aantal e-mailadressen in"}},pt:{create_users_view:{required:"Introduza alguns endereรงos de e-mail"}},ru:{create_users_view:{required:"ะะฒะตะดะธัะต ะฝะตัะบะพะปัะบะพ ะฐะดัะตัะพะฒ ัะปะตะบััะพะฝะฝะพะน ะฟะพััั"}},zh:{create_users_view:{required:"่ฏท่พๅ
ฅไธไบ็ตๅญ้ฎไปถๅฐๅ"}}}})}) | owly/canvassy | public/optimized/translations/create_users_view.js | JavaScript | agpl-3.0 | 838 |