code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
'use strict';
describe('Controller: GeneralCtrl', function () {
// load the controller's module
beforeEach(module('golfAdminApp'));
var GeneralCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
GeneralCtrl = $controller('GeneralCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(GeneralCtrl.awesomeThings.length).toBe(3);
});
});
| SinfoProject/golfAdmin | test/spec/controllers/general.js | JavaScript | gpl-3.0 | 566 |
(function(mod) {
if (typeof exports == "object" && typeof module == "object")
// CommonJS
mod(require("codemirror/lib/codemirror"));
else mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
const comment = { regex: /\(\*/, push: "comment", token: "comment" };
const base = [
{ regex: /"(?:[^\\]|\\.)*?(?:"|$)/, token: "string" },
{ regex: /`\(/, sol: true, token: "builtin strong", next: "staging" },
{ regex: /`/, token: "string", push: "expansion" },
{ regex: /[1-9][0-9]*/, token: "number" },
{ regex: /\{[a-z]+\|/, token: "string strong", push: "freequote_brpp" },
{ regex: /\{\{/, token: "string strong", push: "freequote_brbr" },
{ regex: /\<\</, token: "string strong", push: "freequote_abab" },
{ regex: /\{/, token: "string strong", push: "freequote_br" },
{ regex: /\%[a-z]+/, token: "builtin" },
comment,
{
regex: /(Yes(:|\.)|Impossible\.)/
},
{
regex: /\>\>/,
sol: true,
token: "builtin"
},
{ regex: /[A-Z_][A-Za-z_\\'0-9]*/, token: "variable-2" }, //metavars
{
regex: /(if|then|else|when|fun|pfun)\b/,
token: "keyword"
},
{
regex: /[a-z][a-zA-Z0-9_\']*/,
sol: true,
token: "def",
push: "definition"
},
{
regex: /[a-z][a-zA-Z0-9_\']*/
},
{ regex: /(\<-|:-)/, token: "builtin", indent: true },
{ regex: /(:=|-\>)/, token: "builtin" },
{ regex: /=\>/, token: "keyword" },
{
regex: /(\.|\?)(\s|$)/,
dedent: true,
dedentIfLineStart: true
}
];
CodeMirror.defineSimpleMode("makam", {
start: base,
staging: [].concat(
[{ regex: /\)\./, token: "builtin strong", next: "start" }],
base
),
const_definition: [
{
regex: /[a-z][a-zA-Z0-9_\']*/,
token: "def"
},
{ regex: /:/, next: "type_in_definition" }
],
definition: [
{ regex: /\s*,\s*/, next: "const_definition" },
{ regex: /\s*:\s*/, next: "type_in_definition" },
{ regex: /\s/, pop: true }
],
type_in_definition: [
{ regex: /(type|prop)\b/, token: "keyword" },
{ regex: /[a-z][a-zA-Z0-9_\']*/, token: "type" },
{ regex: /-\>/, token: "meta" },
{ regex: /[A-Z_][A-Za-z_\\'0-9]*/, token: "variable-2" }, //metavars
{ regex: /\./, pop: true }
],
expansion: [
{ regex: /\$\{/, push: "expansion_quote", token: "meta" },
{ regex: /\$\`/, pop: true, token: "string" },
{ regex: /\$[^\{]/, token: "string" },
{ regex: /(?:[^\\`\$]|\\.)+/, token: "string" },
{ regex: /\`/, pop: true, token: "string" }
],
expansion_quote: [].concat(
[{ regex: /\}/, pop: true, token: "meta" }],
base
),
freequote_brpp: [
{ regex: /\|\}/, token: "string strong", pop: true },
{ regex: /[^\|]+/, token: "string" },
{ regex: /\|/, token: "string" },
],
freequote_brbr: [
{ regex: /\}\}/, token: "string strong", pop: true },
{ regex: /[^\}]+/, token: "string" },
{ regex: /\}/, token: "string" }
],
freequote_abab: [
{ regex: /\>\>/, token: "string strong", pop: true },
{ regex: /[^\>]+/, token: "string" },
{ regex: /\>/, token: "string" }
],
freequote_br: [
{ regex: /\}/, token: "string strong", pop: true },
{ regex: /[^\}]+/, token: "string" }
],
comment: [
// { regex: /\(\*/, token: "comment", push: "comment" },
{ regex: /.*\*\)/, token: "comment", pop: true },
{ regex: /.*/, token: "comment" }
]
});
CodeMirror.defineSimpleMode("makam-query-results", {
start: [
{ regex: /^(Yes(:|\.)|Impossible\.)/, mode: { spec: "makam" } }
]
});
});
| astampoulis/makam | webui/makam-codemirror.js | JavaScript | gpl-3.0 | 3,725 |
var a00099 =
[
[ "enc_info", "a00099.html#ad111ceb6802da6301dbe73a73b35a4a1", null ],
[ "id_info", "a00099.html#a301c28abac3bf1f2f38d2b95854695cd", null ],
[ "master_id", "a00099.html#ad0cc95342832dacb99b8b0daede5856c", null ],
[ "peer_addr", "a00099.html#a2c9e328ee5b20afe64224e8d807e0015", null ],
[ "sign_info", "a00099.html#ad6b652026333405eba289d528d220638", null ]
]; | DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware | nrf51_sdk/Documentation/s120/html/a00099.js | JavaScript | gpl-3.0 | 393 |
const corenlp = require("corenlp");
const CoreNLP = corenlp.default; // convenient when not using `import`
/**
* IMPORTANT
* The server http://corenlp.run is used here just for demo purposes.
* It is not set up to handle a large volume of requests. Instructions for
* setting up your own server can be found in the Dedicated Server section (link below).
* @see {@lik https://stanfordnlp.github.io/CoreNLP/corenlp-server.html}
* @see {@link http://corenlp.run}
*/
const connector = new corenlp.ConnectorServer({
dsn: 'http://corenlp.run',
});
// initialize the pipeline and document to annotate
const props = new corenlp.Properties({
annotators: 'tokenize,ssplit,pos,ner,parse',
});
const pipeline = new corenlp.Pipeline(props, 'Spanish', connector);
const sent = new CoreNLP.simple.Sentence(
'Jorge quiere cinco empanadas de queso y carne.'
);
// performs the call to corenlp (in this case via http)
await pipeline.annotate(sent);
// constituency parse string representation
console.log('parse', sent.parse());
// constituency parse tree representation
const tree = CoreNLP.util.Tree.fromSentence(sent);
// traverse the tree leaves and print some props
tree.visitLeaves(node =>
console.log(node.word(), node.pos(), node.token().ner()));
// dump the tree for debugging
console.log(JSON.stringify(tree.dump(), null, 2));
| gerardobort/node-corenlp | examples/runkit.js | JavaScript | gpl-3.0 | 1,350 |
/*
* 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/.
*/
/**
* @module twitter-account
* @license MPL-2.0
*/
"use strict";
const twitter = require("twitter-text");
const fetch = require("fetch-base64");
const pagination = require("./pagination");
const Twitter = require("twitter");
const self = require("../self");
const ContentAccount = require("./content-account");
const TwitterFormatter = require("../formatters/twitter");
/**
* @fires module:twitter-account.TwitterAccount#mention
* @this module:twitter-account.TwitterAccount
* @param {string?} lastMention - ID of the latest mention.
* @returns {string} ID of the latest mention.
*/
async function getMentions(lastMention) {
await this.ready;
const args = {
count: 200,
tweet_mode: "extended"
};
if(lastMention !== undefined) {
args.since_id = lastMention;
}
const tweets = await this.tweets;
const res = await pagination.twitter((params) => this._twitterClient.get('statuses/mentions_timeline', params), args);
if(res.length > 0) {
const oldestTweet = Date.parse(tweets.length ? tweets.slice().pop().created_at : Date.now());
for(const tweet of res) {
//TODO filter replies in a thread from the same side, so you only get one issue for longer replies.
if(Date.parse(tweet.created_at) > oldestTweet && tweets.every((t) => t.in_reply_to_status_id_str !== tweet.id_str)) {
this.emit("mention", tweet);
}
}
return res[0].id_str;
}
return lastMention;
}
getMentions.emitsEvents = true;
/**
* @this module:twitter-account.TwitterAccount
* @param {[Object]} [tweets=[]] - Previous tweets.
* @returns {[Object]} Updated list of tweets.
*/
async function getTweets(tweets = []) {
await this.ready;
const args = {
user_id: await this.getID(),
exclude_replies: false,
include_rts: true,
count: 200,
tweet_mode: "extended"
};
if(tweets.length) {
args.since_id = tweets[0].id_str;
}
const result = await pagination.twitter((params) => this._twitterClient.get('statuses/user_timeline', params), args);
if(result.length) {
return result.concat(tweets);
}
return tweets;
}
/**
* A new mention of the twitter account was found. Holds the raw tweet from the API.
*
* @event module:twitter-account.TwitterAccount#mention
* @type {Object}
*/
/**
* @alias module:twitter-account.TwitterAccount
* @extends module:accounts/content-account.ContentAccount
*/
class TwitterAccount extends ContentAccount {
static get Formatter() {
return TwitterFormatter;
}
/**
* @param {Object} config - Twitter client config.
* @param {Twitter} [client] - Twitter client to use for testing.
*/
constructor(config, client) {
super({
lastMention: getMentions,
tweets: getTweets
});
/**
* @type {external:Twitter}
* @private
*/
this._twitterClient = client ? client : new Twitter(config);
/**
* @type {Promise}
*/
this.ready = this.checkLogin().catch((e) => {
console.error("TwitterAccount checkLogin", e);
throw e;
});
}
/**
* Extract the Tweet id from the url if it's a valid tweet URL.
*
* @param {string} tweetUrl - URL to the tweet.
* @returns {string?} If possible the ID of the tweet is returned.
*/
static getTweetIDFromURL(tweetUrl) {
const matches = tweetUrl.match(/^https?:\/\/(?:www\.)?twitter.com\/[^/]+\/status\/([0-9]+)\/?$/);
return (matches && matches.length > 1) ? matches[1] : null;
}
static getUserFromURL(tweetUrl) {
const matches = tweetUrl.match(/^https?:\/\/(?:www\.)?twitter.com\/([^/]+)\/status\/[0-9]+\/?$/);
return (matches && matches.length > 1) ? matches[1] : null;
}
/**
* @param {string} content - Content of the tweet to get the count for.
* @returns {number} Estimated amount of remaining characters for the tweet.
* @throws {Error} When the tweet contains too many images.
* @todo Convert to percentage/permill based indication
*/
static getRemainingChars(content) {
const [ pureTweet ] = this.getMediaAndContent(content);
const parsedTweet = twitter.parseTweet(pureTweet);
return 280 - parsedTweet.weightedLength;
}
/**
* Checks if the content of a tweet is too long.
*
* @param {string} content - Content of the tweet to check.
* @returns {boolean} Whether the tweet content is too long.
* @throws {Error} When the tweet contains too many images.
*/
static tweetTooLong(content) {
const charCount = this.getRemainingChars(content);
return charCount < 0;
}
/**
* Checks if the tweet content is valid.
*
* @param {string} content - Content of the tweet to check.
* @returns {boolean} Wether the tweet is valid.
* @throws {Error} When the tweet contains too many images.
*/
static tweetValid(content) {
const [ pureTweet ] = this.getMediaAndContent(content);
const parsedTweet = twitter.parseTweet(pureTweet);
return parsedTweet.valid;
}
/**
* Separate media and text content of a tweet authored in GitHub Flavoured
* Markdown.
*
* @param {string} tweet - Content of the tweet.
* @returns {[string, [string]]} An array with the first item being the
* cleaned up text content and the second item being an array of
* media item URLs.
* @throws {Error} When more than 4 images are given, as Twitter only
* supports up to 4 images.
*/
static getMediaAndContent(tweet) {
if(tweet.search(/!\[[^\]]*\]\([^)]+\)/) !== -1) {
const media = [];
const pureTweet = tweet.replace(/!\[[^\]]*\]\(([^)]+)\)/g, (match, url) => {
media.push(url);
return '';
});
if(media.length > 4) {
throw new Error("Can not upload more than 4 images per tweet");
}
return [ pureTweet.trim(), media ];
}
return [ tweet.trim(), [] ];
}
static makeTweetPermalink(username, id) {
return `https://twitter.com/${username}/status/${id}`;
}
async getAccountLink() {
const username = await this.getUsername();
return `[@${username}](https://twitter.com/${username})`;
}
/**
* Upload an image to Twitter and get its media id.
*
* @param {string} mediaUrl - URL of the image to upload.
* @returns {string} Media ID of the image on Twitter.
*/
async uploadMedia(mediaUrl) {
const [ media_data ] = await fetch.remote(mediaUrl);
const args = {
media_data
};
const response = await this._twitterClient.post('media/upload', args);
return response.media_id_string;
}
/**
* Sends a tweet with the given content to the authenticated account.
*
* @param {string} content - Tweet content. Should not be over 140 chars.
* @param {string} [media=''] - List of media ids to associate with the tweet.
* @param {string} [inReplyTo] - Tweet this is a reply to.
* @returns {string} URL of the tweet.
*/
async tweet(content, media = '', inReplyTo = null) {
if(self(this).tweetTooLong(content)) {
return Promise.reject(new Error("Tweet content too long"));
}
const args = {
status: content
};
if(inReplyTo) {
const tweetId = self(this).getTweetIDFromURL(inReplyTo);
if(tweetId) {
args.in_reply_to_status_id = tweetId;
const recipient = self(this).getUserFromURL(inReplyTo);
const mentions = twitter.extractMentions(content).map((m) => m.toLowerCase());
if(!mentions.length || !mentions.includes(recipient.toLowerCase())) {
args.auto_populate_reply_metadata = "true";
}
}
}
if(media.length) {
args.media_ids = media;
}
await this.ready;
const [
res,
username
] = await Promise.all([
this._twitterClient.post('statuses/update', args),
this.getUsername()
]);
return self(this).makeTweetPermalink(username, res.id_str);
}
/**
* Retweet a tweet based on its URL.
*
* @async
* @param {string} url - URL to the tweet to retweet.
* @returns {string} URL to the retweet.
*/
async retweet(url) {
const tweetId = self(this).getTweetIDFromURL(url);
await this.ready;
return this._twitterClient.post(`statuses/retweet/${tweetId}`, {})
.then(() => url);
}
/**
* Verifies the login credentials and stores the screenname if successful.
*
* @async
* @returns {undefined}
*/
checkLogin() {
return this._twitterClient.get('account/verify_credentials', {}).then((res) => {
this.username = res.screen_name;
this.id = res.id_str;
});
}
/**
* Returns the username when available.
*
* @returns {string} Authenticated username.
*/
async getUsername() {
await this.ready;
return this.username;
}
/**
* Returns the Twitter ID of the current account when available.
*
* @returns {string} Authenticated user ID.
*/
async getID() {
await this.ready;
return this.id;
}
async separateContentAndMedia(card) {
const staticRef = self(this);
const contentSection = staticRef.GetContentSection(card);
const [ content, media ] = staticRef.getMediaAndContent(contentSection);
const mediaIds = await Promise.all(media.map((m) => this.uploadMedia(m)));
return [ content, mediaIds.join(",") ];
}
async checkPosts(column, markPublished) {
const tweets = await this.tweets;
const cards = await column.cards;
for(const card of Object.values(cards)) {
if(!card.content.hasSection(TwitterFormatter.RETWEET)) {
const [ content ] = self(this).getMediaAndContent(self(this).GetContentSection(card));
const tweet = tweets.find((t) => 'full_text' in t ? t.full_text.includes(content) : t.text.includes(content));
if(tweet) {
await markPublished(card, self(this).makeTweetPermalink(tweet.user.screen_name, tweet.id_str));
}
}
else {
const retweetID = self(this).getTweetIDFromURL(card.content.getSection(TwitterFormatter.RETWEET));
const didRetweet = tweets.some((t) => t.retweeted_status && t.retweeted_status.id_str === retweetID);
if(didRetweet) {
await markPublished(card, 'Already retweeted.');
}
}
}
}
isCardHighPrio(card) {
return card.content.hasSection(TwitterFormatter.REPLY_TO);
}
async publish(card) {
let url;
if(card.content.hasSection(TwitterFormatter.RETWEET)) {
url = await this.retweet(card.content.getSection(TwitterFormatter.RETWEET));
}
else {
let replyTo = null;
if(card.content.hasSection(TwitterFormatter.REPLY_TO)) {
replyTo = card.content.getSection(TwitterFormatter.REPLY_TO);
}
const [ content, media ] = await this.separateContentAndMedia(card);
url = await this.tweet(content, media, replyTo);
}
let successMsg = "Successfully tweeted. See " + url;
if(card.content.hasSection(TwitterFormatter.RETWEET)) {
successMsg = "Successfully retweeted.";
}
return successMsg;
}
}
module.exports = TwitterAccount;
| mozillach/gh-projects-content-queue | lib/accounts/twitter.js | JavaScript | mpl-2.0 | 12,246 |
"use strict";
const React = require('react');
const _ = require('lodash');
const TabActions = require('../../actions/tabActions');
const TabList = React.createClass({
propTypes: {
openTabs: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
activeTabIndex: React.PropTypes.number.isRequired
},
onTabClick: function(tabIndex, clickEvent) {
clickEvent.preventDefault();
TabActions.switchToTab(tabIndex);
},
createTabElement: function(tabData, index) {
const elementKey = `tab${index}`;
const elementClass = index === this.props.activeTabIndex ? 'active' : null;
const onClickFunc = _.partial(this.onTabClick, index);
return (
<li key={elementKey} role="presentation" className={elementClass}>
<a href="#" onClick={onClickFunc}>{tabData.title}</a>
</li>
);
},
render: function() {
const tabs = _.map(this.props.openTabs, this.createTabElement);
return (
<ul className="nav nav-pills">
{tabs}
</ul>
);
}
});
module.exports = TabList;
| amgaera/azure-storage-navigator | src/components/tabs/tabList.js | JavaScript | mpl-2.0 | 1,052 |
angular.module("app").factory('Helpers', function() {
var service = {
replaceEmptyStrings: function(object) {
for (var i in object) {
if (object.hasOwnProperty(i)) {
if ((typeof object[i] === 'string' || object[i] instanceof String) && object[i] === "") {
object[i] = null;
}
}
}
return object;
},
};
return service;
});
| aksareen/balrog | ui/app/js/services/helper_service.js | JavaScript | mpl-2.0 | 403 |
defineComponent('login', {
prototype: {
data() {
return {
password: '',
username: '',
errors: [],
}
},
computed: {
is_not_clickable() {
if (!this.username) return true;
if (!this.password) return true;
return false;
}
},
methods: {
getBody() {
return {
login: this.username,
password: this.password,
};
},
logIn() {
if (this.is_not_clickable) return;
this.errors = [];
axios.post('/furetui/login', this.getBody())
.then((res) => {
if (res.data.global !== undefined) this.$store.commit('UPDATE_GLOBAL', res.data.global);
if (res.data.menus !== undefined) this.$store.commit('UPDATE_MENUS', res.data.menus);
if (res.data.lang !== undefined) updateLang(res.data.lang);
if (res.data.langs !== undefined) updateLocales(res.data.langs);
const userName = this.$store.state.global.userName;
this.$notify({
title: `Welcome ${userName}`,
text: 'Your are logged',
duration: 5000,
});
this.$store.commit('LOGIN')
if (this.$route.query.redirect !== undefined) this.$router.push(this.$route.query.redirect);
else this.$router.push('/');
})
.catch((error) => {
error.response.data.errors.forEach((error) => {
this.errors.push(this.$t('components.login.errors.' + error.name));
});
})
},
},
},
});
| AnyBlok/anyblok_furetui | anyblok_furetui/auth/components/login.js | JavaScript | mpl-2.0 | 1,656 |
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
var gTestfile = 'ownkeys-trap-duplicates.js';
var BUGNUMBER = 1293995;
var summary =
"Scripted proxies' [[OwnPropertyKeys]] should not throw if the trap " +
"implementation returns duplicate properties and the object is " +
"non-extensible or has non-configurable properties";
print(BUGNUMBER + ": " + summary);
/**************
* BEGIN TEST *
**************/
var target = Object.preventExtensions({ a: 1 });
var proxy = new Proxy(target, { ownKeys(t) { return ["a", "a"]; } });
assertDeepEq(Object.getOwnPropertyNames(proxy), ["a", "a"]);
target = Object.freeze({ a: 1 });
proxy = new Proxy(target, { ownKeys(t) { return ["a", "a"]; } });
assertDeepEq(Object.getOwnPropertyNames(proxy), ["a", "a"]);
/******************************************************************************/
if (typeof reportCompare === "function")
reportCompare(true, true);
print("Tests complete");
| Yukarumya/Yukarum-Redfoxes | js/src/tests/ecma_6/Proxy/ownkeys-trap-duplicates.js | JavaScript | mpl-2.0 | 1,004 |
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
var isOSX = Services.appinfo.OS === "Darwin";
add_task(function* () {
let shortcuts = new KeyShortcuts({
window
});
yield testSimple(shortcuts);
yield testNonLetterCharacter(shortcuts);
yield testPlusCharacter(shortcuts);
yield testFunctionKey(shortcuts);
yield testMixup(shortcuts);
yield testLooseDigits(shortcuts);
yield testExactModifiers(shortcuts);
yield testLooseShiftModifier(shortcuts);
yield testStrictLetterShiftModifier(shortcuts);
yield testAltModifier(shortcuts);
yield testCommandOrControlModifier(shortcuts);
yield testCtrlModifier(shortcuts);
yield testInvalidShortcutString(shortcuts);
yield testCmdShiftShortcut(shortcuts);
shortcuts.destroy();
yield testTarget();
});
// Test helper to listen to the next key press for a given key,
// returning a promise to help using Tasks.
function once(shortcuts, key, listener) {
let called = false;
return new Promise(done => {
let onShortcut = (key2, event) => {
shortcuts.off(key, onShortcut);
ok(!called, "once listener called only once (i.e. off() works)");
is(key, key2, "listener first argument match the key we listen");
called = true;
listener(key2, event);
done();
};
shortcuts.on(key, onShortcut);
});
}
function* testSimple(shortcuts) {
info("Test simple key shortcuts");
let onKey = once(shortcuts, "0", (key, event) => {
is(event.key, "0");
// Display another key press to ensure that once() correctly stop listening
EventUtils.synthesizeKey("0", {}, window);
});
EventUtils.synthesizeKey("0", {}, window);
yield onKey;
}
function* testNonLetterCharacter(shortcuts) {
info("Test non-naive character key shortcuts");
let onKey = once(shortcuts, "[", (key, event) => {
is(event.key, "[");
});
EventUtils.synthesizeKey("[", {}, window);
yield onKey;
}
function* testFunctionKey(shortcuts) {
info("Test function key shortcuts");
let onKey = once(shortcuts, "F12", (key, event) => {
is(event.key, "F12");
});
EventUtils.synthesizeKey("F12", { keyCode: 123 }, window);
yield onKey;
}
// Plus is special. It's keycode is the one for "=". That's because it requires
// shift to be pressed and is behind "=" key. So it should be considered as a
// character key
function* testPlusCharacter(shortcuts) {
info("Test 'Plus' key shortcuts");
let onKey = once(shortcuts, "Plus", (key, event) => {
is(event.key, "+");
});
EventUtils.synthesizeKey("+", { keyCode: 61, shiftKey: true }, window);
yield onKey;
}
// Test they listeners are not mixed up between shortcuts
function* testMixup(shortcuts) {
info("Test possible listener mixup");
let hitFirst = false, hitSecond = false;
let onFirstKey = once(shortcuts, "0", (key, event) => {
is(event.key, "0");
hitFirst = true;
});
let onSecondKey = once(shortcuts, "Alt+A", (key, event) => {
is(event.key, "a");
ok(event.altKey);
hitSecond = true;
});
// Dispatch the first shortcut and expect only this one to be notified
ok(!hitFirst, "First shortcut isn't notified before firing the key event");
EventUtils.synthesizeKey("0", {}, window);
yield onFirstKey;
ok(hitFirst, "Got the first shortcut notified");
ok(!hitSecond, "No mixup, second shortcut is still not notified (1/2)");
// Wait an extra time, just to be sure this isn't racy
yield new Promise(done => {
window.setTimeout(done, 0);
});
ok(!hitSecond, "No mixup, second shortcut is still not notified (2/2)");
// Finally dispatch the second shortcut
EventUtils.synthesizeKey("a", { altKey: true }, window);
yield onSecondKey;
ok(hitSecond, "Got the second shortcut notified once it is actually fired");
}
// On azerty keyboard, digits are only available by pressing Shift/Capslock,
// but we accept them even if we omit doing that.
function* testLooseDigits(shortcuts) {
info("Test Loose digits");
let onKey = once(shortcuts, "0", (key, event) => {
is(event.key, "à");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
});
// Simulate a press on the "0" key, without shift pressed on a french
// keyboard
EventUtils.synthesizeKey(
"à",
{ keyCode: 48 },
window);
yield onKey;
onKey = once(shortcuts, "0", (key, event) => {
is(event.key, "0");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(event.shiftKey);
});
// Simulate the same press with shift pressed
EventUtils.synthesizeKey(
"0",
{ keyCode: 48, shiftKey: true },
window);
yield onKey;
}
// Test that shortcuts is notified only when the modifiers match exactly
function* testExactModifiers(shortcuts) {
info("Test exact modifiers match");
let hit = false;
let onKey = once(shortcuts, "Alt+A", (key, event) => {
is(event.key, "a");
ok(event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
hit = true;
});
// Dispatch with unexpected set of modifiers
ok(!hit, "Shortcut isn't notified before firing the key event");
EventUtils.synthesizeKey("a",
{ accelKey: true, altKey: true, shiftKey: true },
window);
EventUtils.synthesizeKey(
"a",
{ accelKey: true, altKey: false, shiftKey: false },
window);
EventUtils.synthesizeKey(
"a",
{ accelKey: false, altKey: false, shiftKey: true },
window);
EventUtils.synthesizeKey(
"a",
{ accelKey: false, altKey: false, shiftKey: false },
window);
// Wait an extra time to let a chance to call the listener
yield new Promise(done => {
window.setTimeout(done, 0);
});
ok(!hit, "Listener isn't called when modifiers aren't exactly matching");
// Dispatch the expected modifiers
EventUtils.synthesizeKey("a", { accelKey: false, altKey: true, shiftKey: false},
window);
yield onKey;
ok(hit, "Got shortcut notified once it is actually fired");
}
// Some keys are only accessible via shift and listener should also be called
// even if the key didn't explicitely requested Shift modifier.
// For example, `%` on french keyboards is only accessible via Shift.
// Same thing for `@` on US keybords.
function* testLooseShiftModifier(shortcuts) {
info("Test Loose shift modifier");
let onKey = once(shortcuts, "%", (key, event) => {
is(event.key, "%");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(event.shiftKey);
});
EventUtils.synthesizeKey(
"%",
{ accelKey: false, altKey: false, ctrlKey: false, shiftKey: true},
window);
yield onKey;
onKey = once(shortcuts, "@", (key, event) => {
is(event.key, "@");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(event.shiftKey);
});
EventUtils.synthesizeKey(
"@",
{ accelKey: false, altKey: false, ctrlKey: false, shiftKey: true},
window);
yield onKey;
}
// But Shift modifier is strict on all letter characters (a to Z)
function* testStrictLetterShiftModifier(shortcuts) {
info("Test strict shift modifier on letters");
let hitFirst = false;
let onKey = once(shortcuts, "a", (key, event) => {
is(event.key, "a");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
hitFirst = true;
});
let onShiftKey = once(shortcuts, "Shift+a", (key, event) => {
is(event.key, "a");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(event.shiftKey);
});
EventUtils.synthesizeKey(
"a",
{ shiftKey: true},
window);
yield onShiftKey;
ok(!hitFirst, "Didn't fire the explicit shift+a");
EventUtils.synthesizeKey(
"a",
{ shiftKey: false},
window);
yield onKey;
}
function* testAltModifier(shortcuts) {
info("Test Alt modifier");
let onKey = once(shortcuts, "Alt+F1", (key, event) => {
is(event.keyCode, window.KeyboardEvent.DOM_VK_F1);
ok(event.altKey);
ok(!event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
});
EventUtils.synthesizeKey(
"VK_F1",
{ altKey: true },
window);
yield onKey;
}
function* testCommandOrControlModifier(shortcuts) {
info("Test CommandOrControl modifier");
let onKey = once(shortcuts, "CommandOrControl+F1", (key, event) => {
is(event.keyCode, window.KeyboardEvent.DOM_VK_F1);
ok(!event.altKey);
if (isOSX) {
ok(!event.ctrlKey);
ok(event.metaKey);
} else {
ok(event.ctrlKey);
ok(!event.metaKey);
}
ok(!event.shiftKey);
});
let onKeyAlias = once(shortcuts, "CmdOrCtrl+F1", (key, event) => {
is(event.keyCode, window.KeyboardEvent.DOM_VK_F1);
ok(!event.altKey);
if (isOSX) {
ok(!event.ctrlKey);
ok(event.metaKey);
} else {
ok(event.ctrlKey);
ok(!event.metaKey);
}
ok(!event.shiftKey);
});
if (isOSX) {
EventUtils.synthesizeKey(
"VK_F1",
{ metaKey: true },
window);
} else {
EventUtils.synthesizeKey(
"VK_F1",
{ ctrlKey: true },
window);
}
yield onKey;
yield onKeyAlias;
}
function* testCtrlModifier(shortcuts) {
info("Test Ctrl modifier");
let onKey = once(shortcuts, "Ctrl+F1", (key, event) => {
is(event.keyCode, window.KeyboardEvent.DOM_VK_F1);
ok(!event.altKey);
ok(event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
});
let onKeyAlias = once(shortcuts, "Control+F1", (key, event) => {
is(event.keyCode, window.KeyboardEvent.DOM_VK_F1);
ok(!event.altKey);
ok(event.ctrlKey);
ok(!event.metaKey);
ok(!event.shiftKey);
});
EventUtils.synthesizeKey(
"VK_F1",
{ ctrlKey: true },
window);
yield onKey;
yield onKeyAlias;
}
function* testCmdShiftShortcut(shortcuts) {
if (!isOSX) {
// This test is OSX only (Bug 1300458).
return;
}
let onCmdKey = once(shortcuts, "CmdOrCtrl+[", (key, event) => {
is(event.key, "[");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(event.metaKey);
ok(!event.shiftKey);
});
let onCmdShiftKey = once(shortcuts, "CmdOrCtrl+Shift+[", (key, event) => {
is(event.key, "[");
ok(!event.altKey);
ok(!event.ctrlKey);
ok(event.metaKey);
ok(event.shiftKey);
});
EventUtils.synthesizeKey(
"[",
{ metaKey: true, shiftKey: true },
window);
EventUtils.synthesizeKey(
"[",
{ metaKey: true },
window);
yield onCmdKey;
yield onCmdShiftKey;
}
function* testTarget() {
info("Test KeyShortcuts with target argument");
let target = document.createElementNS("http://www.w3.org/1999/xhtml",
"input");
document.documentElement.appendChild(target);
target.focus();
let shortcuts = new KeyShortcuts({
window,
target
});
let onKey = once(shortcuts, "0", (key, event) => {
is(event.key, "0");
is(event.target, target);
});
EventUtils.synthesizeKey("0", {}, window);
yield onKey;
target.remove();
shortcuts.destroy();
}
function testInvalidShortcutString(shortcuts) {
info("Test wrong shortcut string");
let shortcut = KeyShortcuts.parseElectronKey(window, "Cmmd+F");
ok(!shortcut, "Passing a invalid shortcut string should return a null object");
shortcuts.on("Cmmd+F", function () {});
ok(true, "on() shouldn't throw when passing invalid shortcut string");
}
| Yukarumya/Yukarum-Redfoxes | devtools/client/shared/test/browser_key_shortcuts.js | JavaScript | mpl-2.0 | 11,394 |
/*
Battleship browser client
version 0.1.2
required
battleshipclient.js >=0.1.2
battleshipgraphics.js >=0.1.2
*/
function battleshipSession(){
this.isMatchBeginning = false;
this.isPlayerMoved = false;
this.playerIndex = -1;
this.Grid = {
Self: [],
Enemy: [],
};
this.Ships = {
Self:[],
Enemy:[]
};
this.initialize();
}
battleshipSession.prototype.initialize = function (){
var column = 1;
var row = 1;
for (var i=0;i<100;i++){
var key = column + "" + row;
this.Grid.Self[key] = { ship: null, isTurned: false };
this.Grid.Enemy[key] = { ship: null, isTurned: false };
if (++row > 10){
column++;
row = 1;
}
}
var maximum = 4;
var minimum = 1;
do{
for (var i=0;i<minimum;i++){
this.Ships.Self.push ({ count: maximum , column: null, row: null , isVertical: true , isDie: false });
}
maximum--;
minimum++;
} while (maximum > 0);
}
battleshipSession.prototype.sendMessage = function (event,obj){
if (!obj) throw 'Sending object must defined!';
obj.event = event;
obj.playerIndex = this.playerIndex;
sendMessageToSession(obj);
}
battleshipSession.prototype.checkBlockedCells = function (ship,column,row){
var blockedCells = [];
for (var i=0;i<ship.length;i++){
var column = ship.isVertical ? (column+i) : column;
var row = !ship.isVertical ? (row+i) : row;
var key = column + "" + row;
if (this.Grid.Self[key].ship != null) blockedCells.push({column:column,row:row});
}
return blockedCells;
}
battleshipSession.prototype.checkFreeCells = function (ship,column,row){
for (var i=0;i<ship.length;i++){
var column = ship.isVertical ? (column+i) : column;
var row = !ship.isVertical ? (row+i) : row;
var key = column + "" + row;
if (this.Grid.Self[key].ship != null) return false;
}
return true;
}
battleshipSession.prototype.setShipToGrid = function (ship,column,row){
if (!this.checkFreeCells(ship,column,row)) return;//TODO:handle error
for (var i=0;i<ship.length;i++){
var column = ship.isVertical ? (column+i) : column;
var row = !ship.isVertical ? (row+i) : row;
var key = column + "" + row;
this.Grid.Self[key].ship = ship;
}
ship.column = column;
ship.row = row;
}
battleshipSession.prototype.changeEnemyGridStatus = function (column,row,status){
switch (status){
case "empty":
var cell = this.Grid.Enemy[column + "" + row];
cell.isTurned = true;
cell.ship = null;
break;
case "dead":
case "hit":
var cell = this.Grid.Enemy[column + "" + row];
cell.isTurned = true;
if (cell.ship == null) cell.ship = { count: 0 , coordinates:[] };
cell.ship.count += 1;
cell.ship.coordinates.push({column:column,row:row});
if (status == "dead") this.Ships.Enemy.push (cell.ship);
break;
default:
if (status.indexOf("error") > -1){
//TODO:handling error
}
break;
}
}
battleshipSession.prototype.changeSelfGridStatus = function (column,row,status){
switch (status){
case "empty":
var cell = this.Grid.Self[column + "" + row];
cell.isTurned = true;
break;
case "dead":
case "hit":
var cell = this.Grid.Self[column + "" + row];
cell.isTurned = true;
if (status == "dead") cell.ship.isDie = true;
break;
default:
if (status.indexOf("error") > -1){
//TODO:handling error
}
break;
}
}
function matchTime ( layer , x , y , viewer ){
this.x = x;
this.y = y;
this.layer = layer;
this.currentTime = 0;
this.spriteName;
this.viewer = viewer;
this.needIterate = false;
this.timeoutId;
this.text = new battleshipText(
{
characters: "0123456789:",
textAtlas: "images/Numbers_title.png",
width:8,
height:19,
viewer:viewer,
name:"matchTime"
}
);
}
matchTime.prototype.start = function (){
this.needIterate = true;
var self = this;
function iterator(){
self.currentTime+=1;
if (self.needIterate){
self.timeoutId = setTimeout(
iterator,
1000
);
}
}
iterator();
}
matchTime.prototype.stop = function(){
this.needIterate = false;
clearTimeout( this.timeoutId );
}
matchTime.prototype.showTwoDigit = function (digit){
return digit < 10 ? "0" + digit : "" + digit;
}
matchTime.prototype.showTime = function (){
var hours = Math.round(this.currentTime / 3600);
var minutes = Math.round(this.currentTime % 3600 / 60);
var time = this.showTwoDigit(hours) + ":" + this.showTwoDigit(minutes);
this.text.drawText ( this.layer , this.x , this.y , time );
}
var
CELL_STATE_EMPTY = 1,
CELL_STATE_CLEAR = 2,
CELL_STATE_SHIP = 3,
CELL_STATE_INJURED = 4,
CELL_STATE_DEAD = 5
;
function miniMap(options){
this.x = options.x;
this.y = options.y;
this.size = options.size;
this.count = options.size*options.size;
this.borderWidth = options.borderWidth;
this.stateWidth = options.stateWidth;
this.viewer = options.viewer;
this.layer = options.layer;
this.atlas = options.atlas;
this.atlasCell = options.atlasCell;
this.name = options.name;
this.cellCreated = false;
}
miniMap.prototype.getName = function (column,row){
return this.name + "minimap" + column + "" + row;
}
miniMap.prototype.getCellName = function (column,row){
return this.name + "minimapcell" + column + "" + row;
}
miniMap.prototype.createCells = function(){
for (var i=0;i<this.size;i++){
for (var l=0;l<this.size;l++){
this.viewer.addSprite ( this.layer , this.getName ( i , l ) , this.atlas );
this.viewer.addSprite ( this.layer , this.getCellName ( i , l ) , this.atlasCell );
}
}
this.cellCreated = true;
}
miniMap.prototype.changeCellTileOnCoordinates = function ( column , row , state ){
var sprite = this.viewer.getSprite ( this.getCellName ( column , row ) );
this.changeCellTileOnSprite ( sprite , state );
}
miniMap.prototype.changeCellTileOnSprite = function ( sprite , state ){
switch (state){//it need for control of state variable
case CELL_STATE_EMPTY:
case CELL_STATE_CLEAR:
case CELL_STATE_SHIP:
case CELL_STATE_INJURED:
case CELL_STATE_DEAD:
sprite.setSpriteTile(state,this.stateWidth,this.stateWidth);
break;
default: throw 'Incorrect state.';
}
}
miniMap.prototype.show = function (){
if (!this.cellCreated) this.createCells();
var columnPosition;
var rowPosition = this.y;
for ( var i=0 ; i < this.size ; i++ ){
columnPosition = this.x;
for ( var l=0 ; l< this.size ; l++ ){
var sprite = this.viewer.getSprite ( this.getName ( i , l ) );
var spriteCell = this.viewer.getSprite ( this.getCellName ( i , l ) );
sprite.position ( columnPosition , rowPosition );
spriteCell.position( columnPosition + 1 , rowPosition + 1 );
columnPosition += this.borderWidth-1;
}
rowPosition += this.borderWidth-1;
}
}
$(
function (){
var isGameStarted = $('#room').size() > 0;
if (!isGameStarted) return;
var session = new battleshipSession( );
var time;
var userMinimap;
var viewer = new battleshipViewer(
{
onStartLoadImages: function () {
},
onEndLoadImages: function () {
viewer.addLayer( "background" );
viewer.addSprite( "background" , "mainbackground" , "images/background.png" );
viewer.addLayer( "grids" );
viewer.addLayer( "hud" );
time = new matchTime ( "hud" , 379 , 4 , viewer );
time.start();
viewer.StartTimer( );
userMinimap = new miniMap(
{
x:39,
y:230,
size:10,
borderWidth:15,
stateWidth:13,
viewer:viewer,
layer:"grids",
atlas:"images/minimap_square.png",
atlasCell:"images/minimap_title.png",
name:"userMinimap"
}
);
userMinimap.show();
},
onDraw: function () {
var sprite = this.sprites["test"];
time.showTime();
},
images: [ "images/minimap_square.png", "images/minimap_title.png" , "images/background.png" , "images/Numbers_title.png" ]
}
);
var room = parseInt($('#room').val(),10);
$('#sendToChat').click(
function (){
session.sendMessage(
"chat",
{
message:$('#messageText').val()
}
);
}
);
$('#sendShips').click(
function (){
session.setShipToGrid(session.Ships.Self[0],1,1);//4
session.setShipToGrid(session.Ships.Self[1],3,1);//3
session.setShipToGrid(session.Ships.Self[2],5,1);//3
session.setShipToGrid(session.Ships.Self[3],7,1);//2
session.setShipToGrid(session.Ships.Self[4],1,8);//2
session.setShipToGrid(session.Ships.Self[5],3,5);//2
session.setShipToGrid(session.Ships.Self[6],4,9);//1
session.setShipToGrid(session.Ships.Self[7],6,9);//1
session.setShipToGrid(session.Ships.Self[8],8,9);//1
session.setShipToGrid(session.Ships.Self[9],10,9);//1
session.sendMessage(
"createField",
{
ships:session.Ships.Self
}
);
}
);
$('#turn').click(
function (){
if (!session.isMatchBeginning) return;
session.sendMessage(
"move",
{
column: $('#column').val(),
row: $('#row').val()
}
);
}
);
startSession(
room,
'Test',
function (event,data){
switch (event){
case introduceHandler:
session.playerIndex = data.playerIndex;
break;
case chatHandler:
$('#messageLog').val($('#messageLog').val() + data.message);
break;
case whoMoveHandler:
session.isPlayerMoved = data.isYouTurn;
$('#WhoTurn').val( session.isPlayerMoved ? "You turn" : "Not you turn" );
break;
case matchSuccessHandler:
session.isMatchBeginning = data.isSuccess;
$('#GameStatus').val( session.isMatchBeginning ? "game started" : "arrangement of ships" );
break;
}
}
);
}
); | trueromanus/battleship | src/battleship/public/javascripts/battleshiplogic.js | JavaScript | mpl-2.0 | 9,958 |
CoSeMe.namespace('protocol', (function(){
'use strict';
var k = CoSeMe.protocol.dictionary; // protocol constants
var token2Code = k.token2Code;
var ByteArray = CoSeMe.utils.ByteArrayWA;
var logger = new CoSeMe.common.Logger('BinaryWriter');
var IS_COUNTING = true;
var IS_RAW = true;
/**
* The binary writer sends via TCPSocket the required data avoiding
* unnecessary copies. To accomplish this purpose, as the size is not known
* before codifying the tree, the algorithm preprocess the tree by calculating
* the necessary space only, then repeat the processing to effectively write
* the data.
*/
function BinaryWriter(connection) {
this._socket = connection.socket; // an opened socket in binary mode
this.outputKey = undefined;
}
var STREAM_START = k.STREAM_START;
/**
* Sends the start of the protocol.
*/
BinaryWriter.prototype.streamStart = function(domain, resource, callback) {
var writerTask = this.newWriteTask(callback);
writerTask._sendProtocol(IS_COUNTING);
writerTask._sendProtocol();
writerTask._streamStart(domain, resource, IS_COUNTING);
writerTask._streamStart(domain, resource);
};
BinaryWriter.prototype._sendProtocol = function(counting) {
var dictionaryVersion = 5; // my guess: the dictionary version
this.resetBuffer(counting, IS_RAW);
this.writeASCII('WA', counting);
this.writeByte(STREAM_START, counting);
this.writeByte(dictionaryVersion, counting);
this.flushBuffer(counting);
}
BinaryWriter.prototype._streamStart = function(domain, resource, counting) {
var attributes = {to: domain, resource: resource};
this.resetBuffer(counting);
this.writeListStart(1 + 2 * CoSeMe.utils.len(attributes), counting);
this.writeInt8(1, counting);
this.writeAttributes(attributes, undefined, counting);
this.sendMessage(counting);
}
/**
* Spawn a new BinaryWriter in charge of sending the tree via socket.
*/
BinaryWriter.prototype.write = function(tree, callback) {
var writerTask = this.newWriteTask(callback);
writerTask._write(tree, IS_COUNTING);
writerTask._write(tree);
};
/*
* Creates a new BinaryWriter object proxying the current one. This new
* object can not spawn new write tasks.
*/
BinaryWriter.prototype.newWriteTask = function(callback) {
var task = Object.create(this);
task.newWriteTask = undefined;
task._callback = callback;
task._socket = this._socket; // Copy the current socket to the task to
// ensure this task put its data on the current
// socket and not in a future one (i.e a new
// one as a result of a reconnection).
return task;
};
BinaryWriter.prototype._write = function(tree, counting) {
this.resetBuffer(counting);
if (!tree) {
this.writeInt8(0, counting);
}
else {
this.writeTree(tree, counting);
!counting && logger.log(tree.toString());
}
this.sendMessage(counting);
}
/**
* Encode the tree in binary format and put it in the output buffer.
*/
BinaryWriter.prototype.writeTree = function(tree, counting) {
var length = 1 + (2 * CoSeMe.utils.len(tree.attributes));
if (tree.children.length > 0) length++;
if (tree.data !== null) length++;
// Tree header and tag
this.writeListStart(length, counting);
this.writeString(tree.tag, counting);
// Attributes
this.writeAttributes(tree.attributes, tree, counting);
// Data
if (tree.data) {
this.writeBytes(tree.data, counting);
}
// Children
var childrenCount = tree.children.length;
if (childrenCount !== 0) {
this.writeListStart(childrenCount, counting);
for (var i = 0; i < childrenCount; i++) {
this.writeTree(tree.children[i], counting);
}
}
};
var SHORT_LIST_MARK = k.SHORT_LIST_MARK;
var LONG_LIST_MARK = k.LONG_LIST_MARK;
var EMPTY_LIST_MARK = k.EMPTY_LIST_MARK;
/**
* Writes an attributes header in the output buffer.
*/
BinaryWriter.prototype.writeListStart = function(length, counting) {
if (length === 0) {
counting ? this.messageLength++ : this.message.write(EMPTY_LIST_MARK);
}
else if (length < 256) {
counting ? this.messageLength++ : this.message.write(SHORT_LIST_MARK);
this.writeInt8(length, counting);
}
else {
counting ? this.messageLength++ : this.message.write(LONG_LIST_MARK);
this.writeInt16(length, counting);
}
return this;
};
/**
* Writes an attribute object in the output buffer.
*/
BinaryWriter.prototype.writeAttributes = function(attrs, tree, counting) {
var attributes = attrs || {};
var value;
for (var attrName in attributes) if (attributes.hasOwnProperty(attrName)) {
value = tree ? tree.getAttributeValue(attrName) : attributes[attrName];
this.writeString(attrName, counting);
this.writeString(value, counting);
}
return this;
};
/**
* Wrapper to encode both tokens and JID (Jabber ID).
*/
BinaryWriter.prototype.writeString = function(string, counting) {
if (typeof string !== 'string') {
logger.warn('Expecting a string!', typeof string, 'given instead.');
if (string === null || string === undefined) {
string = '';
} else {
string = string.toString();
}
}
var result = token2Code(string);
if (result.code !== null) {
if (result.submap !== null) {
this.writeToken(result.submap, counting);
}
this.writeToken(result.code, counting);
} else {
if (string.indexOf('@') < 1) {
this.writeBytes(string, counting);
}
else {
var userAndServer = string.split('@');
var user = userAndServer[0];
var server = userAndServer[1];
this.writeJid(user, server, counting);
}
}
return this;
};
var SURROGATE_MARK = k.SURROGATE_MARK;
/**
* Writes a string token in an efficent encoding derived from a dictionary.
*/
BinaryWriter.prototype.writeToken = function(code, counting) {
if (code < 245) {
counting ? this.messageLength++ : this.message.write(code);
}
else if (code <= 500) {
counting ? this.messageLength++ : this.message.write(SURROGATE_MARK);
counting ? this.messageLength++ : this.message.write(code - 245);
}
return this;
};
var SHORT_STRING_MARK = k.SHORT_STRING_MARK;
var LONG_STRING_MARK = k.LONG_STRING_MARK;
/**
* Writes bytes from a JavaScript (latin1) string, an ArrayBuffer or any
* type with a buffer property of type ArrayBuffer like ArrayBufferView
* instances.
*/
BinaryWriter.prototype.writeBytes = function(data, counting) {
var bytes;
if (typeof data === 'string') {
bytes = CoSeMe.utils.bytesFromLatin1(data);
} else if (data instanceof ArrayBuffer) {
bytes = new Uint8Array(data);
} else if (data && data.buffer instanceof ArrayBuffer) {
bytes = new Uint8Array(data.buffer);
} else {
var fallback = data === null || data === undefined ? '' : data.toString();
logger.error('Expecting string, ArrayBuffer or ArrayBufferView-like' +
'object. A', data.constructor.name, 'received instead.');
bytes = CoSeMe.utils.bytesFromLatin1(fallback);
}
var l = bytes.length;
if (l < 256) {
counting ? this.messageLength++ : this.message.write(SHORT_STRING_MARK);
this.writeInt8(l, counting);
}
else {
counting ? this.messageLength++ : this.message.write(LONG_STRING_MARK);
this.writeInt24(l, counting);
}
for (var i = 0; i < l; i++) {
counting ? this.messageLength++ : this.message.write(bytes[i]);
}
return this;
};
var JID_MARK = k.JID_MARK;
/**
* Writes the JID in the output buffer.
*/
BinaryWriter.prototype.writeJid = function(user, server, counting) {
counting ? this.messageLength++ : this.message.write(JID_MARK);
if (user) {
this.writeString(user, counting);
} else {
this.writeToken(0, counting);
}
this.writeString(server, counting);
return this;
};
/**
* Writes the ASCII values for each character of the given input.
*/
BinaryWriter.prototype.writeASCII = function(input, counting) {
var character;
for (var i = 0, l = input.length; i < l; i++) {
character = input.charCodeAt(i);
this.writeByte(character, counting);
}
return this;
};
/**
* An alias for writeInt8.
*/
BinaryWriter.prototype.writeByte = function(i, counting) {
this.writeInt8(i, counting)
return this;
};
/**
* Writes a 8-bit integer into the output buffer.
*/
BinaryWriter.prototype.writeInt8 = function(i, counting) {
counting ? this.messageLength++ : this.message.write(i & 0xFF);
return this;
};
/**
* Writes a 16-bit integer into the output buffer.
*/
BinaryWriter.prototype.writeInt16 = function(i, counting) {
counting ? this.messageLength++ : this.message.write((i & 0xFF00) >>> 8);
counting ? this.messageLength++ : this.message.write((i & 0x00FF));
return this;
};
/**
* Writes a 24-bit integer into the output buffer.
*/
BinaryWriter.prototype.writeInt24 = function(i, counting) {
counting ? this.messageLength++ : this.message.write((i & 0xFF0000) >>> 16);
counting ? this.messageLength++ : this.message.write((i & 0x00FF00) >>> 8);
counting ? this.messageLength++ : this.message.write((i & 0x0000FF));
return this;
};
/**
* Sends the message in the output buffer.
*/
BinaryWriter.prototype.sendMessage = function(counting) {
if (counting) { return; }
if (this.isEncrypted()) {
this.cipherMessage();
}
this.addMessageHeader();
this.flushBuffer(counting);
};
/**
* Consumes all the data in the output buffer sending them via the socket.
*/
BinaryWriter.prototype.flushBuffer = function(counting) {
if (counting) { return; }
try {
// This includes the header and trailing paddings.
var out, offset, realOutLength;
if (this.isRaw) {
out = this.message.finish().buffer;
offset = 0;
realOutLength = this.messageLength;
}
else {
var completeView = new Uint32Array(this.outBuffer);
var completeViewLength = completeView.buffer.byteLength;
out = new ByteArray(completeView, completeViewLength).finish().buffer;
offset = HEADER_PADDING;
realOutLength = HEADER_LENGTH + this.messageLength;
}
var error = null, socketState = this._socket.readyState;
if (socketState === 'open') {
// With these offset and length we omit the header and trailing
// paddings.
this._socket.send(out.buffer, offset, realOutLength);
} else {
logger.warn('Can not write. Socket state:', socketState);
error = 'socket-non-ready';
}
(typeof this._callback === 'function') && this._callback(error);
} catch (x) {
var socketState = this._socket.readyState;
if (typeof this._callback === 'function') {
this._callback(socketState === 'closed' ? 'disconnected' : x);
}
}
};
var HEADER_LENGTH = k.HEADER_LENGTH;
var HEADER_PADDING = 4 - (HEADER_LENGTH % 4);
var COMPLETE_HEADER_LENGTH = HEADER_LENGTH + HEADER_PADDING;
var MAC_LENGTH = k.MAC_LENGTH;
/**
* If not counting, allocate an outgoing buffer for the message.
* If only counting, reset the outgoing length to 0.
*
* If isRaw parameter is set to true, no header, mac nor cyphering size
* considerations will be taken into account. Now is used to send the
* `streamStart`.
*/
BinaryWriter.prototype.resetBuffer = function(counting, isRaw) {
if (counting) {
this.messageLength = 0;
}
else {
// If encrypted, it is needed to allocate extra space for the mac.
this.isRaw = isRaw;
// No headers, no mac, no cyphering
if (isRaw) {
this.message = new ByteArray(this.messageLength);
}
// Headers + mac + cyphering
else {
var macLength = this.isEncrypted() ? MAC_LENGTH : 0;
this.messageLength += macLength;
this.messagePadding = 4 - (this.messageLength % 4);
this.completeMessageLength = this.messageLength + this.messagePadding;
var totalSize = COMPLETE_HEADER_LENGTH + this.completeMessageLength;
this.outBuffer = new Uint8Array(totalSize).buffer;
var headerView =
new Uint32Array(this.outBuffer, 0, COMPLETE_HEADER_LENGTH >>> 2);
var messageView =
new Uint32Array(this.outBuffer, COMPLETE_HEADER_LENGTH);
this.header = new ByteArray(headerView);
this.message = new ByteArray(messageView);
}
}
};
/**
* Ciphers the message and signs it. Ciphering occurs IN-PLACE.
*/
BinaryWriter.prototype.cipherMessage = function() {
var textAndMac = this.outputKey.encodeMessage(this.message);
for (var i = 0; i < MAC_LENGTH; i++) {
this.message.write(textAndMac.hmacSHA1.get(i));
}
};
/**
* Adds the header of the message and encrypt the output buffer.
*/
BinaryWriter.prototype.addMessageHeader = function() {
// Write padding
for (var i = 0; i < HEADER_PADDING; i++) {
this.header.write(0);
}
var messageLength = this.messageLength;
var encryptedFlag = this.isEncrypted() ? 0x80 : 0x00;
var b2 = encryptedFlag | ((messageLength & 0xFF0000) >>> 16);
var b1 = (messageLength & 0xFF00) >>> 8;
var b0 = (messageLength & 0x00FF);
this.header.write(b2);
this.header.write(b1);
this.header.write(b0);
};
/**
* Returns true if the RC4 key is set.
*/
BinaryWriter.prototype.isEncrypted = function() {
return !!this.outputKey;
};
return BinaryWriter;
}()));
| mozillahispano/coseme | src/protocol/binary_writer.js | JavaScript | mpl-2.0 | 13,957 |
highlightNavButton('#payments');
/*************** Cached Selectors ***************/
/* Tables / Charts / Tooltips */
var $transactionHistoryTable = $('#transaction-history-table');
var $transactionBarGraphContainer = $('#transaction-history-highchart');
var $payoutToolTips = $(".payout-tooltip");
var $transactionHistoryTableTimes = $transactionHistoryTable.find(".transaction-payout-time");
/* Panel Stuff */
var $loadingPanel = $('.panel-loading');
/* Off Canvas Stuff */
var $offCanvasRow = $('.row-offcanvas');
var $offConvasButton = $(".btn-offcanvas");
var $offCanvasArrowSymbol = $offConvasButton.find(".fa-offcanvas-arrow");
var $colClanInfo = $('.col-clan-info');
/* Payout Stuff */
var $payoutButton = $(".btn-payout");
var $payoutGroupsModal = $("#payout-groups-modal");
var $payoutSuccessModal = $("#payout-success-modal");
var $unpaidSharesSpan = $(".unpaid-shares-span");
/* Caller Bonus Stuff*/
var $callerBonusBattleAmount = $("#caller-bonus-battle-amount");
var $callerBonusUnpaidBattlesBadge = $("#caller-bonus-unpaid-battles");
var $callerBonusTotalAmountBadge = $("#caller-bonus-total-amount");
/* Tank Incentive Stuff */
var $tankIncentivePanel = $('.panel-tank-incentive');
var $usePresetValuesCheckbox = $tankIncentivePanel.find('.checkbox input[type="checkbox"]');
var $filterIncentiveTiersDropdown = $tankIncentivePanel.find('.input-group-tier-filter > select');
var $filterIncentiveTiersBtn = $tankIncentivePanel.find('.btn-filter-incentive-tiers');
var $incentiveTankDropdown = $('#incentive-tank');
var $incentiveAmountInput = $('#incentive-amount');
/* Datepicker Stuff */
var $inputDateRange = $(".input-daterange");
/*************** Initializers ***************/
formatMilisToLocalizedtime($transactionHistoryTableTimes);
initializeTransactionDataTable($transactionHistoryTable);
initializeTransactionBarGraphChart($transactionBarGraphContainer);
updateBarGraph($transactionBarGraphContainer);
var jsonOptions = {weekStart: 0, format: "mm/dd/yyyy", autoclose: true}
$inputDateRange = initializeDateRange($inputDateRange, jsonOptions);
colorizeUnpaidShareCountLabel($unpaidSharesSpan);
$payoutToolTips.tooltip();
$callerBonusBattleAmount.trigger("change"); //Updates the caller bonus total if there is any
/*************** Listeners ***************/
$offConvasButton.on("click", function() {
$colClanInfo.toggleClass("active");
// var colClanInfoHasActive = $colClanInfo.hasClass('active');
// var isNotAffixTopOrBottom = !$colClanInfo.hasClass('affix-top') && !$colClanInfo.hasClass('affix-bottom');
//
// if(isNotAffixTopOrBottom) {
// if(colClanInfoHasActive) {
// $colClanInfo.animate({
// right: '15%'
// }, 250);
// } else {
// $colClanInfo.animate({
// right: '-35%'
// }, 250);
// }
// }
$offCanvasRow.toggleClass("active");
$offCanvasArrowSymbol.toggleClass("fa-arrow-right");
});
$payoutButton.on("click", function(){
var $closestForm = $(this).closest('form');
var formSubmitURL = $closestForm.data("form-submit-url");
var notValidForm = !validateInputs($closestForm);
if(notValidForm) return;
var $formSubmitPromise = $.post(formSubmitURL, $closestForm.serialize());
var isStandardPayout = $(this).hasClass("btn-payout-standard");
$formSubmitPromise.done(function(data){
if(isStandardPayout){
$payoutSuccessModal.modal('show');
}else{
$payoutGroupsModal.find(".modal-body").empty().html(data);
$payoutGroupsModal.modal('show')
}
});
});
$payoutGroupsModal.on("click", "#btn-group-payout-finalize", function(){
var $newCalculatedPayoutGroupTotalForm = $payoutGroupsModal.find("#new-calculated-payout-group-total-form");
var formSubmitURL = $newCalculatedPayoutGroupTotalForm.data("form-submit-url");
$payoutGroupsModal.modal('hide');
var $payoutGroupFormSubmitPromise = $.post(formSubmitURL, $newCalculatedPayoutGroupTotalForm.serialize());
$payoutGroupFormSubmitPromise.done(function(){
$payoutSuccessModal.modal('show');
});
});
$payoutGroupsModal.on("click", ".btn-script-generation", function(){
var $this = $(this);
var $payoutGroupPlayerNicknameH4s = $this.closest(".panel").find(".panel-body .player-nickname");
var payoutAmount = $this.data("gold-amount");
var playerNicknames = [];
$payoutGroupPlayerNicknameH4s.each(function(){
playerNicknames.push($(this).text())
});
var locationUrl = "../app/payouts/get-payout-script.user.js?payoutAmount=" + payoutAmount;
$.each(playerNicknames, function(){
locationUrl += "&playerNicknames=" + this;
});
window.location = locationUrl;
});
$inputDateRange.datepicker().on("changeDate", function(e){
var startDate = $("#campaign-start-date").datepicker("getDate");
var endDate = $("#campaign-end-date").datepicker("getDate");
var startDateInSec = startDate.getTime();
var endDateInSec = endDate.getTime();
$("#hidden-campaign-start-date").val(startDateInSec);
$("#hidden-campaign-end-date").val(endDateInSec);
});
$callerBonusBattleAmount.on("keyup change", function(){
var amountEntered = $(this).val();
var unpaidBattles = $callerBonusUnpaidBattlesBadge.text();
var callerBonusTotalAmount = (Number(amountEntered) * Number(unpaidBattles));
//TODO think if we want to actually show NaN or not
$callerBonusTotalAmountBadge.text(callerBonusTotalAmount);
});$callerBonusBattleAmount.trigger('change');
$usePresetValuesCheckbox.on('change', function () {
var isNotChecked = !$(this).is(':checked');
if(isNotChecked) {
$filterIncentiveTiersDropdown.prop("disabled", false);
$filterIncentiveTiersBtn.removeAttr("disabled");
return false;
}else {
$filterIncentiveTiersDropdown.prop("disabled", true);
$filterIncentiveTiersBtn.attr("disabled", "disabled");
}
var dropdownAlreadyHasPresetValues = $incentiveTankDropdown.data('is-preset-values') == true;
if(dropdownAlreadyHasPresetValues) return false;
$loadingPanel.addClass('loading');
var $getTankIncentivePresetValuesPromise = $.get('payouts/get-tank-incentive-preset-values');
$getTankIncentivePresetValuesPromise.always(function() {
$loadingPanel.removeClass('loading');
}).done(function(data) {
$incentiveTankDropdown.empty();
var incentivePayoutAmountsTableRows = data;
$.each(incentivePayoutAmountsTableRows, function() {
var incentivePayoutAmountsTableRow = this;
var tankId = incentivePayoutAmountsTableRow.tankInformation.tankId;
var tankName = incentivePayoutAmountsTableRow.tankInformation.nameI18n;
var tankIncentiveAmount = incentivePayoutAmountsTableRow.tankIncentiveDefaultPayout.amount;
var dropdownOption = '<option value="' + tankId + '"' + ' data-tank-incentive-amount="' + tankIncentiveAmount + '" >' + tankName + '</option>';
$incentiveTankDropdown.append(dropdownOption).data('is-preset-values', 'true');
});
$incentiveTankDropdown.trigger('change');
});
});
$filterIncentiveTiersBtn.on('click', function () {
var tierSelected = $filterIncentiveTiersDropdown.val();
$loadingPanel.addClass('loading');
var $getTankInformationByTierPromise = $.get('payouts/get-tank-information-by-tier', {tankTiers : tierSelected});
$getTankInformationByTierPromise.always(function(){
$loadingPanel.removeClass('loading');
}).done(function(data) {
$incentiveTankDropdown.empty();
var tankInformationList = data;
$.each(tankInformationList, function() {
var tankInformation = this;
var tankId = tankInformation.tankId;
var tankName = tankInformation.nameI18n;
var dropdownOption = '<option value="' + tankId + '">' + tankName + '</option>';
$incentiveTankDropdown.append(dropdownOption).data('is-preset-values', 'false');;
});
$incentiveAmountInput.val('');
});
});
$incentiveTankDropdown.on('change', function() {
var isNotChecked = !$usePresetValuesCheckbox.is(':checked');
if(isNotChecked) return false;
var incentiveTankAmount = $incentiveTankDropdown.find('option:selected').data('tank-incentive-amount');
$incentiveAmountInput.val(incentiveTankAmount);
});$incentiveTankDropdown.trigger('change');
/************* Functions *************/
function updateBarGraph($transactionBarGraphContainer){
var $getTransactionBarGraphDataPromise = $.get("payouts/get-transaction-pie");
$getTransactionBarGraphDataPromise.done(function(data){
var barData = data;
var seriesData = [];
var categoryNames = [];
$.each(barData, function(){
var name = this.type;
var amount = this.amount;
seriesData.push(amount);
categoryNames.push(name);
});
var chart = $transactionBarGraphContainer.highcharts();
chart.xAxis[0].setCategories(categoryNames);
chart.series[0].setData(seriesData);
});
}
function colorizeUnpaidShareCountLabel($unpaidSharesSpan){
var unpaidShareAmount = parseInt($unpaidSharesSpan.html());
var isNaN = unpaidShareAmount == NaN;
if(isNaN) return;
switch (true){
case unpaidShareAmount < 100:
removeClassByWildCard($unpaidSharesSpan, "label-");
$unpaidSharesSpan.addClass("label-success");
break;
case unpaidShareAmount < 300:
removeClassByWildCard($unpaidSharesSpan, "label-");
$unpaidSharesSpan.addClass("label-warning");
break;
default:
removeClassByWildCard($unpaidSharesSpan, "label-");
$unpaidSharesSpan.addClass("label-danger");
}
}
function initializeTransactionBarGraphChart($barGraphContainer){
$barGraphContainer.highcharts({
chart: {
type: 'bar'
},
title: {
text: null
},
colors: ['#FFCC00'],
yAxis: {
min: 0,
title: {
text: 'Total Gold Amount',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
xAxis:{
labels: {
style: {
fontSize:'14px',
fontWeight: 'bold'
}
}
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b><br/>',
valueSuffix: ' gold'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
credits: {
enabled: false
},
series: [{
name: 'Gold Amount',
data: []
}]
});
}
function initializeTransactionDataTable($dataTable){
$dataTable.dataTable({
"paging": true,
"pageLength": 10,
"pagingType": "simple",
"order": [[ 1, "desc" ]],
"searching": true,
"columnDefs": [ {
"targets": [0],
"orderable": false
}
],
"drawCallback": function (oSettings) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
}
});
} | NYPD/pms | WebContent/js/payouts.js | JavaScript | mpl-2.0 | 11,044 |
/*
* 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/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
var clone = require('clone');
var tape = require('tape');
var uuid = require('libuuid').create;
var helper = require('./helper.js');
///--- Globals
var FULL_CFG = {
index: {
str: {
type: 'string'
},
str_u: {
type: 'string',
unique: true
},
num: {
type: 'number'
},
num_u: {
type: 'number',
unique: true
},
bool: {
type: 'boolean'
},
bool_u: {
type: 'boolean',
unique: true
}
},
pre: [function onePre(req, cb) { cb(); }],
post: [function onePost(req, cb) { cb(); }],
options: {}
};
var c; // client
var server;
var b; // bucket
function test(name, setup) {
tape.test(name + ' - setup', function (t) {
b = 'moray_unit_test_' + uuid().substr(0, 7);
helper.createServer(function (s) {
server = s;
c = helper.createClient();
c.on('connect', t.end.bind(t));
});
});
tape.test(name + ' - main', function (t) {
setup(t);
});
tape.test(name + ' - teardown', function (t) {
// May or may not exist, just blindly ignore
c.delBucket(b, function () {
c.once('close', function () {
helper.cleanupServer(server, function () {
t.pass('closed');
t.end();
});
});
c.close();
});
});
}
///--- Helpers
function assertBucket(t, bucket, cfg) {
t.ok(bucket);
if (!bucket)
return (undefined);
t.equal(bucket.name, b);
t.ok(bucket.mtime instanceof Date);
t.deepEqual(bucket.index, (cfg.index || {}));
t.ok(Array.isArray(bucket.pre));
t.ok(Array.isArray(bucket.post));
t.equal(bucket.pre.length, (cfg.pre || []).length);
t.equal(bucket.post.length, (cfg.post || []).length);
if (bucket.pre.length !== (cfg.pre || []).length ||
bucket.post.length !== (cfg.post || []).length)
return (undefined);
var i;
for (i = 0; i < bucket.pre.length; i++)
t.equal(bucket.pre[i].toString(), cfg.pre[i].toString());
for (i = 0; i < bucket.post.length; i++)
t.equal(bucket.post[i].toString(), cfg.post[i].toString());
return (undefined);
}
///--- tests
test('create bucket stock config', function (t) {
c.createBucket(b, {}, function (err) {
t.ifError(err);
c.getBucket(b, function (err2, bucket) {
t.ifError(err2);
assertBucket(t, bucket, {});
c.listBuckets(function (err3, buckets) {
t.ifError(err3);
t.ok(buckets);
t.ok(buckets.length);
t.end();
});
});
});
});
test('create bucket loaded', function (t) {
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
c.getBucket(b, function (err2, bucket) {
t.ifError(err2);
assertBucket(t, bucket, FULL_CFG);
t.end();
});
});
});
test('update bucket', function (t) {
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
var cfg = clone(FULL_CFG);
cfg.index.foo = {
type: 'string',
unique: false
};
cfg.post.push(function two(req, cb) {
cb();
});
c.updateBucket(b, cfg, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.end();
});
});
});
});
test('update bucket (versioned ok 0->1)', function (t) {
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
var cfg = clone(FULL_CFG);
cfg.options.version = 1;
cfg.index.foo = {
type: 'string',
unique: false
};
cfg.post.push(function two(req, cb) {
cb();
});
c.updateBucket(b, cfg, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.end();
});
});
});
});
test('update bucket (versioned ok 1->2)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 1;
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 2;
cfg.index.foo = {
type: 'string',
unique: false
};
cfg.post.push(function two(req, cb) {
cb();
});
c.updateBucket(b, cfg, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.end();
});
});
});
});
test('update bucket (reindex tracked)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 1;
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 2;
cfg.index.foo = {
type: 'string',
unique: false
};
c.updateBucket(b, cfg, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.ok(bucket.reindex_active);
t.ok(bucket.reindex_active['2']);
t.end();
});
});
});
});
test('update bucket (reindex disabled)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 1;
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 2;
cfg.index.foo = {
type: 'string',
unique: false
};
var opts = {
no_reindex: true
};
c.updateBucket(b, cfg, opts, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.notOk(bucket.reindex_active);
t.end();
});
});
});
});
test('update bucket (null version, reindex disabled)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 0;
c.createBucket(b, FULL_CFG, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 0;
cfg.index.foo = {
type: 'string',
unique: false
};
c.updateBucket(b, cfg, function (err2) {
t.ifError(err2);
c.getBucket(b, function (err3, bucket) {
t.ifError(err3);
assertBucket(t, bucket, cfg);
t.notOk(bucket.reindex_active);
t.end();
});
});
});
});
test('update bucket (versioned not ok 1 -> 0)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 1;
c.createBucket(b, cfg, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 0;
cfg.index.foo = {
type: 'string',
unique: false
};
cfg.post.push(function two(req, cb) {
cb();
});
c.updateBucket(b, cfg, function (err2) {
t.ok(err2);
if (err2) {
t.equal(err2.name, 'BucketVersionError');
t.ok(err2.message);
}
t.end();
});
});
});
test('update bucket (versioned not ok 2 -> 1)', function (t) {
var cfg = clone(FULL_CFG);
cfg.options.version = 2;
c.createBucket(b, cfg, function (err) {
t.ifError(err);
cfg = clone(FULL_CFG);
cfg.options.version = 1;
cfg.index.foo = {
type: 'string',
unique: false
};
cfg.post.push(function two(req, cb) {
cb();
});
c.updateBucket(b, cfg, function (err2) {
t.ok(err2);
if (err2) {
t.equal(err2.name, 'BucketVersionError');
t.ok(err2.message);
}
t.end();
});
});
});
test('create bucket bad index type', function (t) {
c.createBucket(b, {index: {foo: 'foo'}}, function (err) {
t.ok(err);
t.equal(err.name, 'InvalidBucketConfigError');
t.ok(err.message);
t.end();
});
});
test('create bucket triggers not function', function (t) {
c.createBucket(b, {pre: ['foo']}, function (err) {
t.ok(err);
t.equal(err.name, 'NotFunctionError');
t.ok(err.message);
t.end();
});
});
test('get bucket 404', function (t) {
c.getBucket(uuid().substr(0, 7), function (err) {
t.ok(err);
t.equal(err.name, 'BucketNotFoundError');
t.ok(err.message);
t.end();
});
});
test('delete missing bucket', function (t) {
c.delBucket(uuid().substr(0, 7), function (err) {
t.ok(err);
t.equal(err.name, 'BucketNotFoundError');
t.ok(err.message);
t.end();
});
});
| pfmooney/moray | test/buckets.test.js | JavaScript | mpl-2.0 | 9,723 |
/* -*- 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/. */
/*
* Date: 14 April 2001
*
* SUMMARY: Testing obj.prop getter/setter
* Note: this is a non-ECMA extension to the language.
*/
//-----------------------------------------------------------------------------
var gTestfile = 'getset-003.js';
var UBound = 0;
var BUGNUMBER = '(none)';
var summary = 'Testing obj.prop getter/setter';
var statprefix = 'Status: ';
var status = '';
var statusitems = [ ];
var actual = '';
var actualvalues = [ ];
var expect= '';
var expectedvalues = [ ];
var cnDEFAULT = 'default name';
var cnFRED = 'Fred';
var obj = {};
var obj2 = {};
var s = '';
// SECTION1: define getter/setter directly on an object (not its prototype)
obj = new Object();
obj.nameSETS = 0;
obj.nameGETS = 0;
obj.name setter = function(newValue) {this._name=newValue; this.nameSETS++;}
obj.name getter = function() {this.nameGETS++; return this._name;}
status = 'In SECTION1 of test after 0 sets, 0 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [0,0];
addThis();
s = obj.name;
status = 'In SECTION1 of test after 0 sets, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [0,1];
addThis();
obj.name = cnFRED;
status = 'In SECTION1 of test after 1 set, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [1,1];
addThis();
obj.name = obj.name;
status = 'In SECTION1 of test after 2 sets, 2 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [2,2];
addThis();
// SECTION2: define getter/setter in Object.prototype
Object.prototype.nameSETS = 0;
Object.prototype.nameGETS = 0;
Object.prototype.name setter = function(newValue) {this._name=newValue; this.nameSETS++;}
Object.prototype.name getter = function() {this.nameGETS++; return this._name;}
obj = new Object();
status = 'In SECTION2 of test after 0 sets, 0 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [0,0];
addThis();
s = obj.name;
status = 'In SECTION2 of test after 0 sets, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [0,1];
addThis();
obj.name = cnFRED;
status = 'In SECTION2 of test after 1 set, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [1,1];
addThis();
obj.name = obj.name;
status = 'In SECTION2 of test after 2 sets, 2 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [2,2];
addThis();
// SECTION 3: define getter/setter in prototype of user-defined constructor
function TestObject()
{
}
TestObject.prototype.nameSETS = 0;
TestObject.prototype.nameGETS = 0;
TestObject.prototype.name setter = function(newValue) {this._name=newValue; this.nameSETS++;}
TestObject.prototype.name getter = function() {this.nameGETS++; return this._name;}
TestObject.prototype.name = cnDEFAULT;
obj = new TestObject();
status = 'In SECTION3 of test after 1 set, 0 gets'; // (we set a default value in the prototype)
actual = [obj.nameSETS,obj.nameGETS];
expect = [1,0];
addThis();
s = obj.name;
status = 'In SECTION3 of test after 1 set, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [1,1];
addThis();
obj.name = cnFRED;
status = 'In SECTION3 of test after 2 sets, 1 get';
actual = [obj.nameSETS,obj.nameGETS];
expect = [2,1];
addThis();
obj.name = obj.name;
status = 'In SECTION3 of test after 3 sets, 2 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [3,2];
addThis();
obj2 = new TestObject();
status = 'obj2 = new TestObject() after 1 set, 0 gets';
actual = [obj2.nameSETS,obj2.nameGETS];
expect = [1,0]; // we set a default value in the prototype -
addThis();
// Use both obj and obj2 -
obj2.name = obj.name + obj2.name;
status = 'obj2 = new TestObject() after 2 sets, 1 get';
actual = [obj2.nameSETS,obj2.nameGETS];
expect = [2,1];
addThis();
status = 'In SECTION3 of test after 3 sets, 3 gets';
actual = [obj.nameSETS,obj.nameGETS];
expect = [3,3]; // we left off at [3,2] above -
addThis();
//---------------------------------------------------------------------------------
test();
//---------------------------------------------------------------------------------
function addThis()
{
statusitems[UBound] = status;
actualvalues[UBound] = actual.toString();
expectedvalues[UBound] = expect.toString();
UBound++;
}
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
for (var i = 0; i < UBound; i++)
{
reportCompare(expectedvalues[i], actualvalues[i], getStatus(i));
}
exitFunc ('test');
}
function getStatus(i)
{
return statprefix + statusitems[i];
}
| mozilla/rhino | testsrc/tests/js1_5/extensions/getset-003.js | JavaScript | mpl-2.0 | 4,686 |
(function (module) {
mifosX.controllers = _.extend(module, {
ViewSavingDetailsController: function (scope, routeParams, resourceFactory, paginatorService, location, $uibModal, route, dateFilter, $sce, $rootScope, API_VERSION) {
scope.report = false;
scope.hidePentahoReport = true;
scope.showActiveCharges = true;
scope.formData = {};
scope.date = {};
scope.staffData = {};
scope.fieldOfficers = [];
scope.savingaccountdetails = [];
scope.isDebit = function (savingsTransactionType) {
return savingsTransactionType.withdrawal == true || savingsTransactionType.feeDeduction == true
|| savingsTransactionType.overdraftInterest == true || savingsTransactionType.withholdTax == true;
};
scope.routeTo = function (savingsAccountId, transactionId, accountTransfer, transferId) {
if (accountTransfer) {
location.path('/viewaccounttransfers/' + transferId);
} else {
location.path('/viewsavingtrxn/' + savingsAccountId + '/trxnId/' + transactionId);
}
};
/***
* we are using orderBy(https://docs.angularjs.org/api/ng/filter/orderBy) filter to sort fields in ui
* api returns dates in array format[yyyy, mm, dd], converting the array of dates to date object
* @param dateFieldName
*/
scope.convertDateArrayToObject = function(dateFieldName){
for(var i in scope.savingaccountdetails.transactions){
scope.savingaccountdetails.transactions[i][dateFieldName] = new Date(scope.savingaccountdetails.transactions[i].date);
}
};
scope.isRecurringCharge = function (charge) {
return charge.chargeTimeType.value == 'Monthly Fee' || charge.chargeTimeType.value == 'Annual Fee' || charge.chargeTimeType.value == 'Weekly Fee';
}
scope.viewCharge = function (id){
location.path('/savings/'+scope.savingaccountdetails.id+'/viewcharge/'+id).search({'status':scope.savingaccountdetails.status.value});
}
scope.clickEvent = function (eventName, accountId) {
eventName = eventName || "";
switch (eventName) {
case "modifyapplication":
location.path('/editsavingaccount/' + accountId);
break;
case "approve":
location.path('/savingaccount/' + accountId + '/approve');
break;
case "reject":
location.path('/savingaccount/' + accountId + '/reject');
break;
case "withdrawnbyclient":
location.path('/savingaccount/' + accountId + '/withdrawnByApplicant');
break;
case "delete":
resourceFactory.savingsResource.delete({accountId: accountId}, {}, function (data) {
var destination = '/viewgroup/' + data.groupId;
if (data.clientId) destination = '/viewclient/' + data.clientId;
location.path(destination);
});
break;
case "undoapproval":
location.path('/savingaccount/' + accountId + '/undoapproval');
break;
case "activate":
location.path('/savingaccount/' + accountId + '/activate');
break;
case "deposit":
location.path('/savingaccount/' + accountId + '/deposit');
break;
case "withdraw":
location.path('/savingaccount/' + accountId + '/withdrawal');
break;
case "addcharge":
location.path('/savingaccounts/' + accountId + '/charges');
break;
case "calculateInterest":
resourceFactory.savingsResource.save({accountId: accountId, command: 'calculateInterest'}, {}, function (data) {
route.reload();
});
break;
case "postInterest":
resourceFactory.savingsResource.save({accountId: accountId, command: 'postInterest'}, {}, function (data) {
route.reload();
});
break;
case "applyAnnualFees":
location.path('/savingaccountcharge/' + accountId + '/applyAnnualFees/' + scope.annualChargeId);
break;
case "transferFunds":
if (scope.savingaccountdetails.clientId) {
location.path('/accounttransfers/fromsavings/' + accountId);
}
break;
case "close":
location.path('/savingaccount/' + accountId + '/close');
break;
case "assignSavingsOfficer":
location.path('/assignsavingsofficer/' + accountId);
break;
case "unAssignSavingsOfficer":
location.path('/unassignsavingsofficer/' + accountId);
break;
case "enableWithHoldTax":
var changes = {
withHoldTax:true
};
resourceFactory.savingsResource.update({accountId: accountId, command: 'updateWithHoldTax'}, changes, function (data) {
route.reload();
});
break;
case "disableWithHoldTax":
var changes = {
withHoldTax:false
};
resourceFactory.savingsResource.update({accountId: accountId, command: 'updateWithHoldTax'}, changes, function (data) {
route.reload();
});
break;
case "postInterestAsOn":
location.path('/savingaccount/' + accountId + '/postInterestAsOn');
break;
}
};
resourceFactory.savingsResource.get({accountId: routeParams.id, associations: 'all'}, function (data) {
scope.savingaccountdetails = data;
scope.savingaccountdetails.availableBalance = scope.savingaccountdetails.enforceMinRequiredBalance?(scope.savingaccountdetails.summary.accountBalance - scope.savingaccountdetails.minRequiredOpeningBalance):scope.savingaccountdetails.summary.accountBalance;
scope.convertDateArrayToObject('date');
if(scope.savingaccountdetails.groupId) {
resourceFactory.groupResource.get({groupId: scope.savingaccountdetails.groupId}, function (data) {
scope.groupLevel = data.groupLevel;
});
}
scope.showonhold = true;
if(angular.isUndefined(data.onHoldFunds)){
scope.showonhold = false;
}
scope.staffData.staffId = data.staffId;
scope.date.toDate = new Date();
scope.date.fromDate = new Date(data.timeline.activatedOnDate);
scope.status = data.status.value;
if (scope.status == "Submitted and pending approval" || scope.status == "Active" || scope.status == "Approved") {
scope.choice = true;
}
scope.chargeAction = data.status.value == "Submitted and pending approval" ? true : false;
scope.chargePayAction = data.status.value == "Active" ? true : false;
if (scope.savingaccountdetails.charges) {
scope.charges = scope.savingaccountdetails.charges;
scope.chargeTableShow = true;
} else {
scope.chargeTableShow = false;
}
if (data.status.value == "Submitted and pending approval") {
scope.buttons = { singlebuttons: [
{
name: "button.modifyapplication",
icon: "fa fa-pencil ",
taskPermissionName:"UPDATE_SAVINGSACCOUNT"
},
{
name: "button.approve",
icon: "fa fa-check",
taskPermissionName:"APPROVE_SAVINGSACCOUNT"
}
],
options: [
{
name: "button.reject",
taskPermissionName:"REJECT_SAVINGSACCOUNT"
},
{
name: "button.withdrawnbyclient",
taskPermissionName:"WITHDRAW_SAVINGSACCOUNT"
},
{
name: "button.addcharge",
taskPermissionName:"CREATE_SAVINGSACCOUNTCHARGE"
},
{
name: "button.delete",
taskPermissionName:"DELETE_SAVINGSACCOUNT"
}
]
};
}
if (data.status.value == "Approved") {
scope.buttons = { singlebuttons: [
{
name: "button.undoapproval",
icon: "fa faf-undo",
taskPermissionName:"APPROVALUNDO_SAVINGSACCOUNT"
},
{
name: "button.activate",
icon: "fa fa-check",
taskPermissionName:"ACTIVATE_SAVINGSACCOUNT"
},
{
name: "button.addcharge",
icon: "fa fa-plus",
taskPermissionName:"CREATE_SAVINGSACCOUNTCHARGE"
}
]
};
}
if (data.status.value == "Active") {
scope.buttons = { singlebuttons: [
{
name: "button.postInterestAsOn",
icon: "icon-arrow-right",
taskPermissionName:"POSTINTERESTASON_SAVINGSACCOUNT"
},
{
name: "button.deposit",
icon: "fa fa-arrow-up",
taskPermissionName:"DEPOSIT_SAVINGSACCOUNT"
},
{
name: "button.withdraw",
icon: "fa fa-arrow-down",
taskPermissionName:"WITHDRAW_SAVINGSACCOUNT"
},
{
name: "button.calculateInterest",
icon: "fa fa-table",
taskPermissionName:"CALCULATEINTEREST_SAVINGSACCOUNT"
}
],
options: [
{
name: "button.postInterest",
taskPermissionName:"POSTINTEREST_SAVINGSACCOUNT"
},
{
name: "button.addcharge",
taskPermissionName:"CREATE_SAVINGSACCOUNTCHARGE"
},
{
name: "button.close",
taskPermissionName:"CLOSE_SAVINGSACCOUNT"
}
]
};
if (data.clientId) {
scope.buttons.options.push({
name: "button.transferFunds",
taskPermissionName:"CREATE_ACCOUNTTRANSFER"
});
}
if (data.charges) {
for (var i in scope.charges) {
if (scope.charges[i].name == "Annual fee - INR") {
scope.buttons.options.push({
name: "button.applyAnnualFees",
taskPermissionName:"APPLYANNUALFEE_SAVINGSACCOUNT"
});
scope.annualChargeId = scope.charges[i].id;
}
}
}
if(data.taxGroup){
if(data.withHoldTax){
scope.buttons.options.push({
name: "button.disableWithHoldTax",
taskPermissionName:"UPDATEWITHHOLDTAX_SAVINGSACCOUNT"
});
}else{
scope.buttons.options.push({
name: "button.enableWithHoldTax",
taskPermissionName:"UPDATEWITHHOLDTAX_SAVINGSACCOUNT"
});
}
}
}
if (data.annualFee) {
var annualdueDate = [];
annualdueDate = data.annualFee.feeOnMonthDay;
annualdueDate.push(new Date().getFullYear());
scope.annualdueDate = new Date(annualdueDate);
};
resourceFactory.standingInstructionTemplateResource.get({fromClientId: scope.savingaccountdetails.clientId,fromAccountType: 2,fromAccountId: routeParams.id},function (response) {
scope.standinginstruction = response;
scope.searchTransaction();
});
});
var fetchFunction = function (offset, limit, callback) {
var params = {};
params.offset = offset;
params.limit = limit;
params.locale = scope.optlang.code;
params.fromAccountId = routeParams.id;
params.fromAccountType = 2;
params.clientId = scope.savingaccountdetails.clientId;
params.clientName = scope.savingaccountdetails.clientName;
params.dateFormat = scope.df;
resourceFactory.standingInstructionResource.search(params, callback);
};
scope.searchTransaction = function () {
scope.displayResults = true;
scope.instructions = paginatorService.paginate(fetchFunction, 14);
scope.isCollapsed = false;
};
resourceFactory.DataTablesResource.getAllDataTables({apptable: 'm_savings_account'}, function (data) {
scope.savingdatatables = data;
});
/*// Saving notes not yet implemented
resourceFactory.savingsResource.getAllNotes({accountId: routeParams.id,resourceType:'notes'}, function (data) {
scope.savingNotes = data;
});
scope.saveNote = function () {
resourceFactory.savingsResource.save({accountId: routeParams.id, resourceType: 'notes'}, this.formData, function (data) {
var today = new Date();
temp = { id: data.resourceId, note: scope.formData.note, createdByUsername: "test", createdOn: today };
scope.savingNotes.push(temp);
scope.formData.note = "";
scope.predicate = '-id';
});
};*/
scope.dataTableChange = function (datatable) {
resourceFactory.DataTablesResource.getTableDetails({datatablename: datatable.registeredTableName,
entityId: routeParams.id, genericResultSet: 'true'}, function (data) {
scope.datatabledetails = data;
scope.datatabledetails.isData = data.data.length > 0 ? true : false;
scope.datatabledetails.isMultirow = data.columnHeaders[0].columnName == "id" ? true : false;
scope.showDataTableAddButton = !scope.datatabledetails.isData || scope.datatabledetails.isMultirow;
scope.showDataTableEditButton = scope.datatabledetails.isData && !scope.datatabledetails.isMultirow;
scope.singleRow = [];
for (var i in data.columnHeaders) {
if (scope.datatabledetails.columnHeaders[i].columnCode) {
for (var j in scope.datatabledetails.columnHeaders[i].columnValues) {
for (var k in data.data) {
if (data.data[k].row[i] == scope.datatabledetails.columnHeaders[i].columnValues[j].id) {
data.data[k].row[i] = scope.datatabledetails.columnHeaders[i].columnValues[j].value;
}
}
}
}
}
if (scope.datatabledetails.isData) {
for (var i in data.columnHeaders) {
if (!scope.datatabledetails.isMultirow) {
var row = {};
row.key = data.columnHeaders[i].columnName;
row.value = data.data[0].row[i];
scope.singleRow.push(row);
}
}
}
});
};
scope.export = function () {
scope.report = true;
scope.printbtn = false;
scope.viewReport = false;
scope.viewSavingReport = true;
scope.viewTransactionReport = false;
};
scope.viewJournalEntries = function(){
location.path("/searchtransaction/").search({savingsId: scope.savingaccountdetails.id});
};
scope.viewDataTable = function (registeredTableName,data){
if (scope.datatabledetails.isMultirow) {
location.path("/viewdatatableentry/"+registeredTableName+"/"+scope.savingaccountdetails.id+"/"+data.row[0]);
}else{
location.path("/viewsingledatatableentry/"+registeredTableName+"/"+scope.savingaccountdetails.id);
}
};
scope.viewSavingDetails = function () {
scope.report = false;
scope.hidePentahoReport = true;
scope.viewReport = false;
};
scope.viewPrintDetails = function () {
//scope.printbtn = true;
scope.report = true;
scope.viewTransactionReport = false;
scope.viewReport = true;
scope.hidePentahoReport = true;
scope.formData.outputType = 'PDF';
scope.baseURL = $rootScope.hostUrl + API_VERSION + "/runreports/" + encodeURIComponent("Client Saving Transactions");
scope.baseURL += "?output-type=" + encodeURIComponent(scope.formData.outputType) + "&tenantIdentifier=" + $rootScope.tenantIdentifier+"&locale="+scope.optlang.code;
var reportParams = "";
scope.startDate = dateFilter(scope.date.fromDate, 'yyyy-MM-dd');
scope.endDate = dateFilter(scope.date.toDate, 'yyyy-MM-dd');
var paramName = "R_startDate";
reportParams += encodeURIComponent(paramName) + "=" + encodeURIComponent(scope.startDate)+ "&";
paramName = "R_endDate";
reportParams += encodeURIComponent(paramName) + "=" + encodeURIComponent(scope.endDate)+ "&";
paramName = "R_savingsAccountId";
reportParams += encodeURIComponent(paramName) + "=" + encodeURIComponent(scope.savingaccountdetails.accountNo);
if (reportParams > "") {
scope.baseURL += "&" + reportParams;
}
// allow untrusted urls for iframe http://docs.angularjs.org/error/$sce/insecurl
scope.viewReportDetails = $sce.trustAsResourceUrl(scope.baseURL);
};
scope.viewSavingsTransactionReceipts = function (transactionId) {
scope.report = true;
scope.viewTransactionReport = true;
scope.viewSavingReport = false;
scope.printbtn = false;
scope.viewReport = true;
scope.hidePentahoReport = true;
scope.formData.outputType = 'PDF';
scope.baseURL = $rootScope.hostUrl + API_VERSION + "/runreports/" + encodeURIComponent("Savings Transaction Receipt");
scope.baseURL += "?output-type=" + encodeURIComponent(scope.formData.outputType) + "&tenantIdentifier=" + $rootScope.tenantIdentifier+"&locale="+scope.optlang.code;
var reportParams = "";
var paramName = "R_transactionId";
reportParams += encodeURIComponent(paramName) + "=" + encodeURIComponent(transactionId);
if (reportParams > "") {
scope.baseURL += "&" + reportParams;
}
// allow untrusted urls for iframe http://docs.angularjs.org/error/$sce/insecurl
scope.viewReportDetails = $sce.trustAsResourceUrl(scope.baseURL);
};
scope.deletestandinginstruction = function (id) {
$uibModal.open({
templateUrl: 'delInstruction.html',
controller: DelInstructionCtrl,
resolve: {
ids: function () {
return id;
}
}
});
};
var DelInstructionCtrl = function ($scope, $uibModalInstance, ids) {
$scope.delete = function () {
resourceFactory.standingInstructionResource.cancel({standingInstructionId: ids}, function (data) {
scope.searchTransaction();
$uibModalInstance.close('delete');
});
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
};
scope.printReport = function () {
window.print();
window.close();
};
scope.deleteAll = function (apptableName, entityId) {
resourceFactory.DataTablesResource.delete({datatablename: apptableName, entityId: entityId, genericResultSet: 'true'}, {}, function (data) {
route.reload();
});
};
scope.modifyTransaction = function (accountId, transactionId) {
location.path('/savingaccount/' + accountId + '/modifytransaction?transactionId=' + transactionId);
};
scope.transactionSort = {
column: 'date',
descending: true
};
scope.changeTransactionSort = function(column) {
var sort = scope.transactionSort;
if (sort.column == column) {
sort.descending = !sort.descending;
} else {
sort.column = column;
sort.descending = true;
}
};
scope.checkStatus = function(){
if(scope.status == 'Active' || scope.status == 'Closed' || scope.status == 'Transfer in progress' ||
scope.status == 'Transfer on hold' || scope.status == 'Premature Closed' || scope.status == 'Matured'){
return true;
}
return false;
};
}
});
mifosX.ng.application.controller('ViewSavingDetailsController', ['$scope', '$routeParams', 'ResourceFactory','PaginatorService' , '$location','$uibModal', '$route', 'dateFilter', '$sce', '$rootScope', 'API_VERSION', mifosX.controllers.ViewSavingDetailsController]).run(function ($log) {
$log.info("ViewSavingDetailsController initialized");
});
}(mifosX.controllers || {}));
| gkrishnan724/community-app | app/scripts/controllers/savings/ViewSavingDetailsController.js | JavaScript | mpl-2.0 | 25,472 |
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { csetWithCcovData } from '../utils/data';
import hash from '../utils/hash';
import * as FetchAPI from '../utils/fetch_data';
const parse = require('parse-diff');
/* DiffViewer loads a raw diff from Mozilla's hg-web and code coverage from
* shiptit-uplift to show a diff with code coverage information for added
* lines.
*/
export default class DiffViewerContainer extends Component {
constructor(props) {
super(props);
this.state = {
appError: undefined,
csetMeta: {
coverage: undefined,
},
parsedDiff: [],
};
}
componentDidMount() {
const { changeset } = this.props;
Promise.all([this.fetchSetCoverageData(changeset), this.fetchSetDiff(changeset)]);
}
async fetchSetCoverageData(changeset) {
try {
this.setState({ csetMeta: await csetWithCcovData({ node: changeset }) });
} catch (error) {
console.error(error);
this.setState({
appError: 'There was an error fetching the code coverage data.',
});
}
}
async fetchSetDiff(changeset) {
try {
const text = await (await FetchAPI.getDiff(changeset)).text();
this.setState({ parsedDiff: parse(text) });
} catch (error) {
console.error(error);
this.setState({
appError: 'We did not manage to parse the diff correctly.',
});
}
}
render() {
const { appError, csetMeta, parsedDiff } = this.state;
return (
<DiffViewer
{...csetMeta}
appError={appError}
parsedDiff={parsedDiff}
/>
);
}
}
const DiffViewer = ({ appError, coverage, node, parsedDiff, summary }) => (
<div className="codecoverage-diffviewer">
<div className="return-home"><Link to="/">Return to main page</Link></div>
{(coverage) &&
<CoverageMeta
{...coverage.parentMeta(coverage)}
{...coverage.diffMeta(node)}
coverage={coverage}
node={node}
summary={summary}
/>}
<span className="error_message">{appError}</span>
{parsedDiff.map(diffBlock =>
// We only push down the subset of code coverage data
// applicable to a file
(
<DiffFile
key={diffBlock.from}
diffBlock={diffBlock}
fileCoverageDiffs={(coverage) ?
coverage.diffs[diffBlock.from] : undefined}
/>
))}
</div>
);
const CoverageMeta = ({ ccovBackend, codecov, coverage, gh, hgRev, pushlog, summary }) => (
<div className="coverage-meta">
<div className="coverage-meta-row">
<span className="meta parent-meta-subtitle">Parent meta</span>
<span className="meta">
{`Current coverage: ${coverage.overall_cur.substring(0, 4)}%`}
</span>
<span className="meta meta-right">
<a href={pushlog} target="_blank">Push log</a>
<a href={gh} target="_blank">GitHub</a>
<a href={codecov} target="_blank">Codecov</a>
</span>
</div>
<div className="coverage-meta-row">
<span className="meta parent-meta-subtitle">Changeset meta</span>
<span className="meta">{summary}</span>
<span className="meta meta-right">
<a href={hgRev} target="_blank">Hg diff</a>
<a href={ccovBackend} target="_blank">Coverage backend</a>
</span>
</div>
</div>
);
/* A DiffLine contains all diff changes for a specific file */
const DiffFile = ({ fileCoverageDiffs, diffBlock }) => (
<div className="diff-file">
<div className="file-summary">
<div className="file-path">{diffBlock.from}</div>
</div>
{diffBlock.chunks.map(block => (
<DiffBlock
key={block.content}
filePath={diffBlock.from}
block={block}
fileDiffs={fileCoverageDiffs}
/>
))}
</div>
);
const uniqueLineId = (filePath, change) => {
let lineNumber;
if (change.ln) {
lineNumber = change.ln;
} else if (change.ln2) {
lineNumber = change.ln2;
} else {
lineNumber = change.ln1;
}
return `${hash(filePath)}-${change.type}-${lineNumber}`;
};
/* A DiffBlock is *one* of the blocks changed for a specific file */
const DiffBlock = ({ filePath, block, fileDiffs }) => (
<div>
<div className="diff-line-at">{block.content}</div>
<div className="diff-block">
<table className="diff-block-table">
<tbody>
{block.changes.map((change) => {
const uid = uniqueLineId(filePath, change);
return (<DiffLine
key={uid}
id={uid}
change={change}
fileDiffs={fileDiffs}
/>);
})}
</tbody>
</table>
</div>
</div>
);
/* A DiffLine contains metadata about a line in a DiffBlock */
const DiffLine = ({ change, fileDiffs, id }) => {
const c = change; // Information about the line itself
const changeType = change.type; // Added, deleted or unchanged line
let rowClass = 'nolinechange'; // CSS tr and td classes
const rowId = id;
let [oldLineNumber, newLineNumber] = ['', '']; // Cell contents
if (changeType === 'add') {
// Added line - <blank> | <new line number>
if (fileDiffs) {
try {
const coverage = fileDiffs[c.ln];
if (coverage === 'Y') {
rowClass = 'hit';
} else if (coverage === '?') {
rowClass = 'nolinechange';
} else {
rowClass = 'miss';
}
} catch (e) {
console.log(e);
rowClass = 'miss';
}
}
newLineNumber = c.ln;
} else if (changeType === 'del') {
// Removed line - <old line number> | <blank>
oldLineNumber = c.ln;
} else {
// Unchanged line - <old line number> | <blank>
oldLineNumber = c.ln1;
if (oldLineNumber !== c.ln2) {
newLineNumber = c.ln2;
}
}
return (
<tr id={rowId} className={`${rowClass} diff-row`}>
<td className="old-line-number diff-cell">{oldLineNumber}</td>
<td className="new-line-number diff-cell">{newLineNumber}</td>
<td className="line-content diff-cell">
<pre>{c.content}</pre>
</td>
</tr>
);
};
| LinkaiQi/firefox-code-coverage-frontend | src/components/diffviewer.js | JavaScript | mpl-2.0 | 6,160 |
(function(global, _) {
var Dataset = global.Miso.Dataset;
Dataset.typeOf = function(value, options) {
var types = _.keys(Dataset.types),
chosenType;
//move string and mixed to the end
types.push(types.splice(_.indexOf(types, 'string'), 1)[0]);
types.push(types.splice(_.indexOf(types, 'mixed'), 1)[0]);
chosenType = _.find(types, function(type) {
return Dataset.types[type].test(value, options);
});
chosenType = _.isUndefined(chosenType) ? 'string' : chosenType;
return chosenType;
};
Dataset.types = {
mixed : {
name : 'mixed',
coerce : function(v) {
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(v)) {
return null;
}
return v;
},
test : function() {
return true;
},
compare : function(s1, s2) {
if ( _.isEqual(s1, s2) ) { return 0; }
if (s1 < s2) { return -1;}
if (s1 > s2) { return 1; }
},
numeric : function(v) {
return v === null || _.isNaN(+v) ? null : +v;
}
},
string : {
name : "string",
coerce : function(v) {
if (_.isNaN(v) || v === null || typeof v === "undefined") {
return null;
}
return v.toString();
},
test : function(v) {
return (v === null || typeof v === "undefined" || typeof v === 'string');
},
compare : function(s1, s2) {
if (s1 == null && s2 != null) { return -1; }
if (s1 != null && s2 == null) { return 1; }
if (s1 < s2) { return -1; }
if (s1 > s2) { return 1; }
return 0;
},
numeric : function(value) {
if (_.isNaN(+value) || value === null) {
return null;
} else if (_.isNumber(+value)) {
return +value;
} else {
return null;
}
}
},
"boolean" : {
name : "boolean",
regexp : /^(true|false)$/,
coerce : function(v) {
if (_.isNaN(v) || v === null || typeof v === "undefined") {
return null;
}
if (v === 'false') { return false; }
return Boolean(v);
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'boolean' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
if (value === null || _.isNaN(value)) {
return null;
} else {
return (value) ? 1 : 0;
}
}
},
number : {
name : "number",
regexp : /^\s*[\-\.]?[0-9]+([\.][0-9]+)?\s*$/,
coerce : function(v) {
var cv = +v;
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(cv)) {
return null;
}
return cv;
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'number' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
if (_.isNaN(value) || value === null) {
return null;
}
return value;
}
},
time : {
name : "time",
format : "DD/MM/YYYY",
_formatLookup : [
['DD', "\\d{2}"],
['D' , "\\d{1}|\\d{2}"],
['MM', "\\d{2}"],
['M' , "\\d{1}|\\d{2}"],
['YYYY', "\\d{4}"],
['YY', "\\d{2}"],
['A', "[AM|PM]"],
['hh', "\\d{2}"],
['h', "\\d{1}|\\d{2}"],
['mm', "\\d{2}"],
['m', "\\d{1}|\\d{2}"],
['ss', "\\d{2}"],
['s', "\\d{1}|\\d{2}"],
['ZZ',"[-|+]\\d{4}"],
['Z', "[-|+]\\d{2}:\\d{2}"]
],
_regexpTable : {},
_regexp: function(format) {
//memoise
if (this._regexpTable[format]) {
return new RegExp(this._regexpTable[format], 'g');
}
//build the regexp for substitutions
var regexp = format;
_.each(this._formatLookup, function(pair) {
regexp = regexp.replace(pair[0], pair[1]);
}, this);
// escape all forward slashes
regexp = regexp.split("/").join("\\/");
// save the string of the regexp, NOT the regexp itself.
// For some reason, this resulted in inconsistant behavior
this._regexpTable[format] = regexp;
return new RegExp(this._regexpTable[format], 'g');
},
coerce : function(v, options) {
options = options || {};
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(v)) {
return null;
}
// if string, then parse as a time
if (_.isString(v)) {
var format = options.format || this.format;
return moment(v, format);
} else if (_.isNumber(v)) {
return moment(v);
} else {
return v;
}
},
test : function(v, options) {
options = options || {};
if (v === null || typeof v === "undefined") {
return true;
}
if (_.isString(v) ) {
var format = options.format || this.format,
regex = this._regexp(format);
return regex.test(v);
} else {
//any number or moment obj basically
return true;
}
},
compare : function(d1, d2) {
if (d1 < d2) {return -1;}
if (d1 > d2) {return 1;}
return 0;
},
numeric : function( value ) {
if (_.isNaN(value) || value === null) {
return null;
}
return value.valueOf();
}
}
};
}(this, _));
| bwinton/d3Experiments | bower_components/miso.dataset/src/types.js | JavaScript | mpl-2.0 | 6,215 |
angular.module('app.preferences.email.directives').directive('sharedWith', sharedWith);
function sharedWith() {
return {
restrict: 'E',
replace: true,
templateUrl: 'preferences/email/directives/shared_with.html',
};
}
| HelloLily/hellolily | frontend/app/preferences/email/controllers/shared_with.js | JavaScript | agpl-3.0 | 251 |
/* eslint "import/prefer-default-export": 0 */
/* eslint "new-cap": 0 */
import { toGlobalId } from "graphql-relay";
import icalendar from "icalendar";
import moment from "moment";
import Event from "./models/Event";
export function icalEvents(req, res, next) {
let query = Event.find({ "permissions.public": true });
query = query
.where({
start: {
$gte: moment()
.subtract(1, "years")
.startOf("day"),
},
})
.sort("start")
.populate("creator", "username name");
query.exec((err, events) => {
if (err) {
return next(err);
}
const ical = new icalendar.iCalendar("2.0");
ical.addProperty("VERSION", "2.0");
ical.addProperty("PRODID", "-//Nidarholm//Aktivitetskalender//");
ical.addProperty("X-WR-CALNAME", "Nidarholmkalenderen");
ical.addProperty("METHOD", "PUBLISH");
ical.addProperty("CALSCALE", "GREGORIAN");
ical.addProperty("X-ORIGINAL", "https://nidarholm.no/events/");
events.forEach((e) => {
const event = new icalendar.VEvent();
event.addProperty("UID", e.id);
if (e.modified) {
event.addProperty("DTSTAMP", e.modified);
} else {
event.addProperty("DTSTAMP", e.created);
}
event.setSummary(e.title);
event.setDate(e.start, e.end);
event.setDescription(
e.mdtext.replace(/\r/g, "").replace(/(<([^>]+)>)/gi, ""),
);
event.setLocation(e.location);
event.addProperty(
"URL",
`https://nidarholm.no/events/${toGlobalId("event", e.id)}`,
);
ical.addComponent(event);
});
res.setHeader("Filename", "nidarholm.ics");
res.setHeader("Content-Disposition", "attachment; filename=nidarholm.ics");
res.setHeader("Content-Type", "text/calendar; charset=utf-8");
res.setHeader("Cache-Control", "max-age=7200, private, must-revalidate");
res.send(ical.toString());
return res;
});
}
| strekmann/nidarholmjs | src/server/icalRoutes.js | JavaScript | agpl-3.0 | 1,934 |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-10-13 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| Bluelytics/bluelytics_frontend | test/karma.conf.js | JavaScript | agpl-3.0 | 2,084 |
import React from 'react';
import StatisticBox from 'interface/others/StatisticBox';
import { formatNumber, formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
const MS_BUFFER=200;
const ABUNDANCE_MANA_REDUCTION = 0.06;
const ABUNDANCE_INCREASED_CRIT = 0.06;
/*
For each Rejuvenation you have active, Regrowth's cost is reduced by 6% and critical effect chance is increased by 6%.
*/
class Abundance extends Analyzer {
manaSavings = [];
critGains = [];
stacks = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.ABUNDANCE_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if(spellId !== SPELLS.REGROWTH.id) {
return;
}
const abundanceBuff = this.selectedCombatant.getBuff(SPELLS.ABUNDANCE_BUFF.id, event.timestamp, MS_BUFFER);
if(abundanceBuff == null) {
return;
}
if (!this.selectedCombatant.hasBuff(SPELLS.CLEARCASTING_BUFF.id) && !this.selectedCombatant.hasBuff(SPELLS.INNERVATE.id)) {
this.manaSavings.push(abundanceBuff.stacks * ABUNDANCE_MANA_REDUCTION > 1 ? 1 : abundanceBuff.stacks * ABUNDANCE_MANA_REDUCTION);
this.manaCasts++;
}
this.critGains.push((abundanceBuff.stacks * ABUNDANCE_INCREASED_CRIT) > 1 ? 1 : abundanceBuff.stacks * ABUNDANCE_INCREASED_CRIT);
this.stacks.push(abundanceBuff.stacks);
}
statistic() {
const avgManaSavingsPercent = (this.manaSavings.reduce(function(a, b) { return a + b; }, 0) / this.manaSavings.length) || 0;
const avgCritGains = (this.critGains.reduce(function(a, b) { return a + b; }, 0) / this.critGains.length) || 0;
const avgStacks = (this.stacks.reduce(function(a, b) { return a + b; }, 0) / this.stacks.length) || 0;
const avgManaSaings = SPELLS.REGROWTH.manaCost * avgManaSavingsPercent;
// TODO translate these values into healing/throughput.
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.ABUNDANCE_TALENT.id} />}
value={(
<>
{avgStacks.toFixed(2)} Avg. stacks<br />
</>
)}
label={'Abundance'}
tooltip={`Average mana reductions gained was ${formatPercentage(avgManaSavingsPercent)}% or ${formatNumber(avgManaSaings)} mana per cast.<br />
Maximum mana saved was ${avgManaSaings * this.manaSavings.length} <br />
Average crit gain was ${formatPercentage(avgCritGains)}%.
`}
/>
);
}
}
export default Abundance;
| FaideWW/WoWAnalyzer | src/parser/druid/restoration/modules/talents/Abundance.js | JavaScript | agpl-3.0 | 2,620 |
/* © 2016 Jairo Llopis <[email protected]>
* License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). */
(function ($) {
"use strict";
$('.oe_website_sale').each(function () {
var $this = $(this),
$country_selector = $this.find("select[name=country_id]"),
$no_country_field = $this.find("#no_country_field");
// Change VAT flag when address country changes
$country_selector.on("change", function (event) {
if ($country_selector.val() && !$no_country_field.val()) {
$this.find(".js_select_country_code[data-country_id="
+ $country_selector.val() + "]")
.click();
}
});
});
$('form[action="/shop/confirm_order"]').on('submit', function(){
if(!this.no_country_field.value){
this.vat.value = "";
}
});
})(jQuery);
| brain-tec/e-commerce | website_sale_checkout_country_vat/static/src/js/change_country.js | JavaScript | agpl-3.0 | 921 |
/*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-iotagent-lib
*
* fiware-iotagent-lib 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.
*
* fiware-iotagent-lib 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 fiware-iotagent-lib.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[email protected]
*/
const logger = require('logops');
const dbService = require('../../model/dbConn');
const config = require('../../commonConfig');
const fillService = require('./../common/domain').fillService;
const alarmsInt = require('../common/alarmManagement').intercept;
const errors = require('../../errors');
const constants = require('../../constants');
const Device = require('../../model/Device');
const async = require('async');
let context = {
op: 'IoTAgentNGSI.MongoDBDeviceRegister'
};
const attributeList = [
'id',
'type',
'name',
'service',
'subservice',
'lazy',
'commands',
'staticAttributes',
'active',
'registrationId',
'internalId',
'internalAttributes',
'resource',
'apikey',
'protocol',
'endpoint',
'transport',
'polling',
'timestamp',
'explicitAttrs',
'expressionLanguage',
'ngsiVersion'
];
/**
* Generates a handler for the save device operations. The handler will take the customary error and the saved device
* as the parameters (and pass the serialized DAO as the callback value).
*
* @return {Function} The generated handler.
*/
function saveDeviceHandler(callback) {
return function saveHandler(error, deviceDAO) {
if (error) {
logger.debug(fillService(context, deviceDAO), 'Error storing device information: %s', error);
callback(new errors.InternalDbError(error));
} else {
callback(null, deviceDAO.toObject());
}
};
}
/**
* Create a new register for a device. The device object should contain the id, type and registrationId
*
* @param {Object} newDevice Device object to be stored
*/
function storeDevice(newDevice, callback) {
/* eslint-disable-next-line new-cap */
const deviceObj = new Device.model();
attributeList.forEach((key) => {
deviceObj[key] = newDevice[key];
});
// Ensure protocol is in newDevice
if (!newDevice.protocol && config.getConfig().iotManager && config.getConfig().iotManager.protocol) {
deviceObj.protocol = config.getConfig().iotManager.protocol;
}
logger.debug(context, 'Storing device with id [%s] and type [%s]', newDevice.id, newDevice.type);
deviceObj.save(function saveHandler(error, deviceDAO) {
if (error) {
if (error.code === 11000) {
logger.debug(context, 'Tried to insert a device with duplicate ID in the database: %s', error);
callback(new errors.DuplicateDeviceId(newDevice.id));
} else {
logger.debug(context, 'Error storing device information: %s', error);
callback(new errors.InternalDbError(error));
}
} else {
callback(null, deviceDAO.toObject());
}
});
}
/**
* Remove the device identified by its id and service.
*
* @param {String} id Device ID of the device to remove.
* @param {String} service Service of the device to remove.
* @param {String} subservice Subservice inside the service for the removed device.
*/
function removeDevice(id, service, subservice, callback) {
const condition = {
id,
service,
subservice
};
logger.debug(context, 'Removing device with id [%s]', id);
Device.model.deleteOne(condition, function (error) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else {
logger.debug(context, 'Device [%s] successfully removed.', id);
callback(null);
}
});
}
/**
* Return the list of currently registered devices (via callback).
*
* @param {String} tyoe Type for which the devices are requested.
* @param {String} service Service for which the devices are requested.
* @param {String} subservice Subservice inside the service for which the devices are requested.
* @param {Number} limit Maximum number of entries to return.
* @param {Number} offset Number of entries to skip for pagination.
*/
function listDevices(type, service, subservice, limit, offset, callback) {
const condition = {};
if (type) {
condition.type = type;
}
if (service) {
condition.service = service;
}
if (subservice) {
condition.subservice = subservice;
}
const query = Device.model.find(condition).sort();
if (limit) {
query.limit(parseInt(limit, 10));
}
if (offset) {
query.skip(parseInt(offset, 10));
}
async.series([query.exec.bind(query), Device.model.countDocuments.bind(Device.model, condition)], function (
error,
results
) {
callback(error, {
count: results[1],
devices: results[0]
});
});
}
function findOneInMongoDB(queryParams, id, callback) {
const query = Device.model.findOne(queryParams);
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
logger.debug(context, 'Device data found: %j', data);
callback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', id);
callback(new errors.DeviceNotFound(id));
}
});
}
/**
* Internal function used to find a device in the DB.
*
* @param {String} id ID of the Device to find.
* @param {String} service Service the device belongs to (optional).
* @param {String} subservice Division inside the service (optional).
*/
function getDeviceById(id, service, subservice, callback) {
const queryParams = {
id,
service,
subservice
};
context = fillService(context, queryParams);
logger.debug(context, 'Looking for device with id [%s].', id);
findOneInMongoDB(queryParams, id, callback);
}
/**
* Retrieves a device using it ID, converting it to a plain Object before calling the callback.
*
* @param {String} id ID of the Device to find.
* @param {String} service Service the device belongs to.
* @param {String} subservice Division inside the service.
*/
function getDevice(id, service, subservice, callback) {
getDeviceById(id, service, subservice, function (error, data) {
if (error) {
callback(error);
} else {
callback(null, data);
}
});
}
function getByName(name, service, servicepath, callback) {
context = fillService(context, { service, subservice: servicepath });
logger.debug(context, 'Looking for device with name [%s].', name);
const query = Device.model.findOne({
name,
service,
subservice: servicepath
});
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
callback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', name);
callback(new errors.DeviceNotFound(name));
}
});
}
/**
* Updates the given device into the database.
* updated.
*
* @param {Object} device Device object with the new values to write.
*/
function update(device, callback) {
logger.debug(context, 'Storing updated values for device [%s]:\n%s', device.id, JSON.stringify(device, null, 4));
getDeviceById(device.id, device.service, device.subservice, function (error, data) {
if (error) {
callback(error);
} else {
data.lazy = device.lazy;
data.active = device.active;
data.internalId = device.internalId;
data.staticAttributes = device.staticAttributes;
data.internalAttributes = device.internalAttributes;
data.commands = device.commands;
data.endpoint = device.endpoint;
data.polling = device.polling;
data.name = device.name;
data.type = device.type;
data.apikey = device.apikey;
data.registrationId = device.registrationId;
data.explicitAttrs = device.explicitAttrs;
data.ngsiVersion = device.ngsiVersion;
/* eslint-disable-next-line new-cap */
const deviceObj = new Device.model(data);
deviceObj.isNew = false;
deviceObj.save(saveDeviceHandler(callback));
}
});
}
/**
* Cleans all the information in the database, leaving it in a clean state.
*/
function clear(callback) {
dbService.db.db.dropDatabase(callback);
}
function itemToObject(i) {
if (i.toObject) {
return i.toObject();
} else {
return i;
}
}
function getDevicesByAttribute(name, value, service, subservice, callback) {
const filter = {};
if (service) {
filter.service = service;
}
if (subservice) {
filter.subservice = subservice;
}
filter[name] = value;
context = fillService(context, filter);
logger.debug(context, 'Looking for device with filter [%j].', filter);
const query = Device.model.find(filter);
query.select({ __v: 0 });
query.exec(function handleGet(error, devices) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (devices) {
callback(null, devices.map(itemToObject));
} else {
logger.debug(context, 'Device [%s] not found.', name);
callback(new errors.DeviceNotFound(name));
}
});
}
exports.getDevicesByAttribute = alarmsInt(constants.MONGO_ALARM, getDevicesByAttribute);
exports.store = alarmsInt(constants.MONGO_ALARM, storeDevice);
exports.update = alarmsInt(constants.MONGO_ALARM, update);
exports.remove = alarmsInt(constants.MONGO_ALARM, removeDevice);
exports.list = alarmsInt(constants.MONGO_ALARM, listDevices);
exports.get = alarmsInt(constants.MONGO_ALARM, getDevice);
exports.getSilently = getDevice;
exports.getByName = alarmsInt(constants.MONGO_ALARM, getByName);
exports.clear = alarmsInt(constants.MONGO_ALARM, clear);
| telefonicaid/iotagent-node-lib | lib/services/devices/deviceRegistryMongoDB.js | JavaScript | agpl-3.0 | 11,503 |
class PandaseqModule extends Module {
constructor (params) {
super ("pandaseq", "https://github.com/yoann-dufresne/amplicon_pipeline/wiki/Pandaseq-module");
this.params = params;
}
onLoad () {
super.onLoad();
var that = this;
// --- Inputs ---
var inputs = this.dom.getElementsByClassName('input_file');
this.fwd = inputs[0]; this.rev = inputs[1];
this.fwd.onchange = this.rev.onchange = () => {that.input_change()};
}
input_change () {
// If the names are standards
if (this.fwd.value.includes('_fwd.fastq') && this.rev.value.includes('_rev.fastq')) {
// Get the main name
var i1 = this.fwd.value.indexOf('_fwd.fastq');
var sub1 = this.fwd.value.substring(0, i1);
var i2 = this.rev.value.indexOf('_rev.fastq');
var sub2 = this.rev.value.substring(0, i2);
if (sub2 == sub1) {
let output_file = this.dom.getElementsByClassName('output_zone')[0];
output_file = output_file.getElementsByTagName('input')[0];
output_file.value = sub1 + '_panda.fasta';
output_file.onchange();
}
}
}
};
module_manager.moduleCreators.pandaseq = (params) => {
return new PandaseqModule(params);
};
| yoann-dufresne/amplicon_pipeline | www/modules/pandaseq.js | JavaScript | agpl-3.0 | 1,149 |
const patron = require('patron.js');
class Remove extends patron.Command {
constructor() {
super({
names: ['remove', 'r'],
groupName: 'fun',
description: 'Deletes the command',
guildOnly: false,
args: [
new patron.Argument({
name: 'text',
key: 'text',
type: 'string',
example: 'No way hoe zay',
remainder: true
})
]
});
}
async run(msg, args) {
//Left blank, the message is deleted by the Command service
}
}
module.exports = new Remove();
| VapidSlay/selfbot | src/commands/Fun/remove.js | JavaScript | agpl-3.0 | 565 |
import {
event as currentEvent,
selectAll as d3SelectAll,
select as d3Select,
mouse as currentMouse,
} from 'd3-selection'
import { NODE_RADIUS } from '../constants'
const nodeRe = /node(\d*)_(.*)/
const getNodeIdFromElementId = (elementId) => (
[
elementId.replace(nodeRe, "$1"),
elementId.replace(nodeRe, "$2")
]
)
export const createOuterDrag = (simulation) => (actions) => {
return {
dragstart: function() {
const mouseXy = currentMouse(this.container.node())
this.graph.dragLine
.classed("hidden", false)
.attr("d", `M ${d.x} ${d.y} L ${mouseXy[0]} ${mouseXy[1]}`);
},
drag: function() {
const mouseXy = currentMouse(this.container.node())
this.graph.dragLine
.attr("d", `M ${d.x} ${d.y} L ${mouseXy[0]} ${mouseXy[1]}`);
const nodeSelection = d3SelectAll('.node')
const prevHoveredNodes = d3SelectAll('.node-hovered')
// back to their default color again
prevHoveredNodes.select('circle')
prevHoveredNodes.classed('node-hovered', false)
nodeSelection.each(node => {
if (node === d) return
const distanceToNode = Math.sqrt((node.x - mouseXy[0])**2 + (node.y - mouseXy[1])**2)
if (distanceToNode < node.radius) {
// change background color
d3Select(`#node-${node.id}`)
.classed('node-hovered', true)
.select('circle')
}
})
},
dragend: function() {
const mouseXy = currentMouse(this.container.node())
const nodeSelection = d3SelectAll('.node')
const { nodes } = this.props
this.graph.dragLine.classed("hidden", true)
const prevHoveredNodes = d3SelectAll('.node-hovered')
// back to their default color again
prevHoveredNodes.select('circle')
prevHoveredNodes.classed('node-hovered', false)
nodeSelection.each(node => {
if (node.id === d.id) return
const distanceToNode = Math.sqrt((node.x - mouseXy[0])**2 + (node.y - mouseXy[1])**2)
if (distanceToNode < node.radius) {
// create an edge from this node to otherNode
return actions.connect(d.id, node.id)
}
})
}
}
}
export const createInnerDrag = (self) => (actions) => {
let startX = null
let startY = null;
let dragStarted = false;
let nodes = null;
return {
dragstart: function() {
/*
* Freeze the graph
*/
const [ index, id ] = getNodeIdFromElementId(d3Select(this).attr('id'))
if (id === self.props.focusNodeId) {
return;
}
dragStarted = true;
startX = currentEvent.x
startY = currentEvent.y
// nodes = self.tree.nodes(d)
},
drag: function(d) {
if (!dragStarted) {
return;
}
const nodeElement = d3Select(this)
const [ index, id ] = getNodeIdFromElementId(nodeElement.attr('id'))
const node = self.nodesById[id]
// nodeElement.attr('transform', `translate(${currentEvent.x}, ${currentEvent.y})`)
self.props.dragElement(
id,
index,
currentEvent.y,
currentEvent.x,
currentEvent.y - startY, // dy from dragStart
currentEvent.x - startX, // dx from dragStart
)
// // TODO: panning (move with screen when dragging to edges - 2018-02-02
// const nodeSelection = d3SelectAll('.node')
// const prevHoveredNodes = d3SelectAll('.node-hovered')
// // back to their default color again
// prevHoveredNodes.select('circle')
// prevHoveredNodes.classed('node-hovered', false)
// nodeSelection.each(node => {
// if (node === d) return
// const distanceToNode = Math.sqrt((node.x - d.x)**2 + (node.y - d.y)**2)
// if (distanceToNode < node.radius) {
// // change background color
// d3Select(`#node-${node.id}`)
// .classed('node-hovered', true)
// .select('circle')
// }
// })
},
dragend: function() {
/*
* Create an edge to all nodes which are being hovered over
*/
if (!dragStarted) {
return;
}
dragStarted = false
const nodeElement = d3Select(this)
const [ index, id ] = getNodeIdFromElementId(nodeElement.attr('id'))
const node = self.nodesById[id]
const nodeSelection = d3SelectAll('.node-below')
self.props.dragElement()
console.log(index, id)
nodeSelection.each(function() {
// undo fixed state as set in dragstart
const currentNodeElement = d3Select(this)
const [ currentIndex, currentId ] = getNodeIdFromElementId(currentNodeElement.attr('id'))
const currentNode = self.nodesById[currentId]
if (id === currentId) {
return;
}
// TODO: x and y are switched here for currentNode - 2018-02-02
const distanceToNode = Math.sqrt((currentNode.y - currentEvent.x)**2 + (currentNode.x - currentEvent.y)**2)
if (distanceToNode < NODE_RADIUS) {
if (node.parent && node.parent.data.id === currentNode.data.id) {
// dragged over the already existing parent
return;
}
// move this node to the abstraction that is hovered over
// TODO: need a method for getting the currently visible abstraction chain
return actions.moveToAbstraction(
node.parent && node.parent.data.id,
node.data.id,
currentNode.data.id, //TODO: here it is data and before not, do something about this...
)
}
})
}
}
}
| bryanph/Geist | client/app/components/graphs/ExploreGraph/drag.js | JavaScript | agpl-3.0 | 6,601 |
(function(C2C, $) {
// area selector size
C2C.changeSelectSize = function(id, up_down) {
var select = $('#' + id);
var height = select.height();
if (up_down) {
height += 150;
} else {
height = Math.max(100, height - 150);
}
select.height(height);
};
// for some search inputs like date selection, we hide some parts
// depending on the first field value
// e.g. only display one input for selecting summits higher than 4000m,
// two inputs for selecting summits between 2000m and 3000m
C2C.update_on_select_change = function(field, optionIndex) {
var index = $('#' + field + '_sel').val();
if (index == '0' || index === ' ' || index == '-' || index >= 4) {
$('#' + field + '_span1').hide();
$('#' + field + '_span2').hide();
if (optionIndex >= 4) {
if (index == 4) {
$('#' + field + '_span3').show();
} else {
$('#' + field + '_span3').hide();
}
}
} else {
$('#' + field + '_span1').show();
if (index == '~' || index == 3) {
$('#' + field + '_span2').show();
} else {
$('#' + field + '_span2').hide();
}
if (optionIndex >= 4) {
$('#' + field + '_span3').hide();
}
}
};
// hide some fields depending onf the activity selected
function hide_unrelated_filter_fields() {
var activities = [];
$.each($("input[name='act[]']:checked"), function() {
activities.push($(this).val());
});
// show/hide data-act-filter tags depending on selected activities
$('[data-act-filter]').hide();
$('[data-act-filter="none"]').toggle(!!activities);
if (!!activities) $.each(activities, function (i, activity) {
$('[data-act-filter~='+ activity +']').show();
});
// some configuration should only be available if
// activity 2 (snow, ice, mixed) is selected
// not that not all browser allow to hide option tags, so we also
// disable them
var select = $('#conf'), select_size;
var options = select.find('option:eq(4), option:eq(5)');
if (activities && $.inArray("2", activities) !== -1) {
select_size = 6;
options.prop('disabled', false).show();
} else {
select_size = 4;
options.prop('disabled', true).hide();
}
select.attr('size', select_size);
}
$('#actform').on('click', "input[name='act[]']", function() {
hide_unrelated_filter_fields();
});
// run it once
hide_unrelated_filter_fields();
})(window.C2C = window.C2C || {}, jQuery);
| c2corg/camptocamp.org | web/static/js/filter.js | JavaScript | agpl-3.0 | 2,561 |
'use strict';
var Tokenizer = require('../tokenization/tokenizer'),
HTML = require('./html');
//Aliases
var $ = HTML.TAG_NAMES,
NS = HTML.NAMESPACES,
ATTRS = HTML.ATTRS;
//MIME types
var MIME_TYPES = {
TEXT_HTML: 'text/html',
APPLICATION_XML: 'application/xhtml+xml'
};
//Attributes
var DEFINITION_URL_ATTR = 'definitionurl',
ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL',
SVG_ATTRS_ADJUSTMENT_MAP = {
'attributename': 'attributeName',
'attributetype': 'attributeType',
'basefrequency': 'baseFrequency',
'baseprofile': 'baseProfile',
'calcmode': 'calcMode',
'clippathunits': 'clipPathUnits',
'contentscripttype': 'contentScriptType',
'contentstyletype': 'contentStyleType',
'diffuseconstant': 'diffuseConstant',
'edgemode': 'edgeMode',
'externalresourcesrequired': 'externalResourcesRequired',
'filterres': 'filterRes',
'filterunits': 'filterUnits',
'glyphref': 'glyphRef',
'gradienttransform': 'gradientTransform',
'gradientunits': 'gradientUnits',
'kernelmatrix': 'kernelMatrix',
'kernelunitlength': 'kernelUnitLength',
'keypoints': 'keyPoints',
'keysplines': 'keySplines',
'keytimes': 'keyTimes',
'lengthadjust': 'lengthAdjust',
'limitingconeangle': 'limitingConeAngle',
'markerheight': 'markerHeight',
'markerunits': 'markerUnits',
'markerwidth': 'markerWidth',
'maskcontentunits': 'maskContentUnits',
'maskunits': 'maskUnits',
'numoctaves': 'numOctaves',
'pathlength': 'pathLength',
'patterncontentunits': 'patternContentUnits',
'patterntransform': 'patternTransform',
'patternunits': 'patternUnits',
'pointsatx': 'pointsAtX',
'pointsaty': 'pointsAtY',
'pointsatz': 'pointsAtZ',
'preservealpha': 'preserveAlpha',
'preserveaspectratio': 'preserveAspectRatio',
'primitiveunits': 'primitiveUnits',
'refx': 'refX',
'refy': 'refY',
'repeatcount': 'repeatCount',
'repeatdur': 'repeatDur',
'requiredextensions': 'requiredExtensions',
'requiredfeatures': 'requiredFeatures',
'specularconstant': 'specularConstant',
'specularexponent': 'specularExponent',
'spreadmethod': 'spreadMethod',
'startoffset': 'startOffset',
'stddeviation': 'stdDeviation',
'stitchtiles': 'stitchTiles',
'surfacescale': 'surfaceScale',
'systemlanguage': 'systemLanguage',
'tablevalues': 'tableValues',
'targetx': 'targetX',
'targety': 'targetY',
'textlength': 'textLength',
'viewbox': 'viewBox',
'viewtarget': 'viewTarget',
'xchannelselector': 'xChannelSelector',
'ychannelselector': 'yChannelSelector',
'zoomandpan': 'zoomAndPan'
},
XML_ATTRS_ADJUSTMENT_MAP = {
'xlink:actuate': {prefix: 'xlink', name: 'actuate', namespace: NS.XLINK},
'xlink:arcrole': {prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK},
'xlink:href': {prefix: 'xlink', name: 'href', namespace: NS.XLINK},
'xlink:role': {prefix: 'xlink', name: 'role', namespace: NS.XLINK},
'xlink:show': {prefix: 'xlink', name: 'show', namespace: NS.XLINK},
'xlink:title': {prefix: 'xlink', name: 'title', namespace: NS.XLINK},
'xlink:type': {prefix: 'xlink', name: 'type', namespace: NS.XLINK},
'xml:base': {prefix: 'xml', name: 'base', namespace: NS.XML},
'xml:lang': {prefix: 'xml', name: 'lang', namespace: NS.XML},
'xml:space': {prefix: 'xml', name: 'space', namespace: NS.XML},
'xmlns': {prefix: '', name: 'xmlns', namespace: NS.XMLNS},
'xmlns:xlink': {prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS}
};
//SVG tag names adjustment map
var SVG_TAG_NAMES_ADJUSTMENT_MAP = {
'altglyph': 'altGlyph',
'altglyphdef': 'altGlyphDef',
'altglyphitem': 'altGlyphItem',
'animatecolor': 'animateColor',
'animatemotion': 'animateMotion',
'animatetransform': 'animateTransform',
'clippath': 'clipPath',
'feblend': 'feBlend',
'fecolormatrix': 'feColorMatrix',
'fecomponenttransfer': 'feComponentTransfer',
'fecomposite': 'feComposite',
'feconvolvematrix': 'feConvolveMatrix',
'fediffuselighting': 'feDiffuseLighting',
'fedisplacementmap': 'feDisplacementMap',
'fedistantlight': 'feDistantLight',
'feflood': 'feFlood',
'fefunca': 'feFuncA',
'fefuncb': 'feFuncB',
'fefuncg': 'feFuncG',
'fefuncr': 'feFuncR',
'fegaussianblur': 'feGaussianBlur',
'feimage': 'feImage',
'femerge': 'feMerge',
'femergenode': 'feMergeNode',
'femorphology': 'feMorphology',
'feoffset': 'feOffset',
'fepointlight': 'fePointLight',
'fespecularlighting': 'feSpecularLighting',
'fespotlight': 'feSpotLight',
'fetile': 'feTile',
'feturbulence': 'feTurbulence',
'foreignobject': 'foreignObject',
'glyphref': 'glyphRef',
'lineargradient': 'linearGradient',
'radialgradient': 'radialGradient',
'textpath': 'textPath'
};
//Tags that causes exit from foreign content
var EXITS_FOREIGN_CONTENT = {};
EXITS_FOREIGN_CONTENT[$.B] = true;
EXITS_FOREIGN_CONTENT[$.BIG] = true;
EXITS_FOREIGN_CONTENT[$.BLOCKQUOTE] = true;
EXITS_FOREIGN_CONTENT[$.BODY] = true;
EXITS_FOREIGN_CONTENT[$.BR] = true;
EXITS_FOREIGN_CONTENT[$.CENTER] = true;
EXITS_FOREIGN_CONTENT[$.CODE] = true;
EXITS_FOREIGN_CONTENT[$.DD] = true;
EXITS_FOREIGN_CONTENT[$.DIV] = true;
EXITS_FOREIGN_CONTENT[$.DL] = true;
EXITS_FOREIGN_CONTENT[$.DT] = true;
EXITS_FOREIGN_CONTENT[$.EM] = true;
EXITS_FOREIGN_CONTENT[$.EMBED] = true;
EXITS_FOREIGN_CONTENT[$.H1] = true;
EXITS_FOREIGN_CONTENT[$.H2] = true;
EXITS_FOREIGN_CONTENT[$.H3] = true;
EXITS_FOREIGN_CONTENT[$.H4] = true;
EXITS_FOREIGN_CONTENT[$.H5] = true;
EXITS_FOREIGN_CONTENT[$.H6] = true;
EXITS_FOREIGN_CONTENT[$.HEAD] = true;
EXITS_FOREIGN_CONTENT[$.HR] = true;
EXITS_FOREIGN_CONTENT[$.I] = true;
EXITS_FOREIGN_CONTENT[$.IMG] = true;
EXITS_FOREIGN_CONTENT[$.LI] = true;
EXITS_FOREIGN_CONTENT[$.LISTING] = true;
EXITS_FOREIGN_CONTENT[$.MENU] = true;
EXITS_FOREIGN_CONTENT[$.META] = true;
EXITS_FOREIGN_CONTENT[$.NOBR] = true;
EXITS_FOREIGN_CONTENT[$.OL] = true;
EXITS_FOREIGN_CONTENT[$.P] = true;
EXITS_FOREIGN_CONTENT[$.PRE] = true;
EXITS_FOREIGN_CONTENT[$.RUBY] = true;
EXITS_FOREIGN_CONTENT[$.s] = true;
EXITS_FOREIGN_CONTENT[$.SMALL] = true;
EXITS_FOREIGN_CONTENT[$.SPAN] = true;
EXITS_FOREIGN_CONTENT[$.STRONG] = true;
EXITS_FOREIGN_CONTENT[$.STRIKE] = true;
EXITS_FOREIGN_CONTENT[$.SUB] = true;
EXITS_FOREIGN_CONTENT[$.SUP] = true;
EXITS_FOREIGN_CONTENT[$.TABLE] = true;
EXITS_FOREIGN_CONTENT[$.TT] = true;
EXITS_FOREIGN_CONTENT[$.U] = true;
EXITS_FOREIGN_CONTENT[$.UL] = true;
EXITS_FOREIGN_CONTENT[$.VAR] = true;
//Check exit from foreign content
exports.causesExit = function (startTagToken) {
var tn = startTagToken.tagName;
if (tn === $.FONT && (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null ||
Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null ||
Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null)) {
return true;
}
return EXITS_FOREIGN_CONTENT[tn];
};
//Token adjustments
exports.adjustTokenMathMLAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
if (token.attrs[i].name === DEFINITION_URL_ATTR) {
token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
break;
}
}
};
exports.adjustTokenSVGAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
var adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];
if (adjustedAttrName)
token.attrs[i].name = adjustedAttrName;
}
};
exports.adjustTokenXMLAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
var adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];
if (adjustedAttrEntry) {
token.attrs[i].prefix = adjustedAttrEntry.prefix;
token.attrs[i].name = adjustedAttrEntry.name;
token.attrs[i].namespace = adjustedAttrEntry.namespace;
}
}
};
exports.adjustTokenSVGTagName = function (token) {
var adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName];
if (adjustedTagName)
token.tagName = adjustedTagName;
};
//Integration points
exports.isMathMLTextIntegrationPoint = function (tn, ns) {
return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT);
};
exports.isHtmlIntegrationPoint = function (tn, ns, attrs) {
if (ns === NS.MATHML && tn === $.ANNOTATION_XML) {
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].name === ATTRS.ENCODING) {
var value = attrs[i].value.toLowerCase();
return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
}
}
}
return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE);
};
| Adimpression/NewsMute | service/lambda/counsellor/node_modules/cheerio/node_modules/jsdom/node_modules/parse5/lib/common/foreign_content.js | JavaScript | agpl-3.0 | 9,186 |
var map;
var maps = [];
var thisLayer;
var proj_4326 = new OpenLayers.Projection('EPSG:4326');
var proj_900913 = new OpenLayers.Projection('EPSG:900913');
var vlayer;
var vlayers = [];
var highlightCtrl;
var selectCtrl;
var selectedFeatures = [];
function initEditMap(settings){
var defaultSettings = {
mapContainer:"mapContainer",
editContainer:"editContainer",
fieldName:"location"
};
settings = jQuery.extend(defaultSettings, settings);
var options = {
units: "dd",
numZoomLevels: 18,
controls:[],
theme: false,
projection: proj_900913,
'displayProjection': proj_4326,
/* eventListeners: {
"zoomend": incidentZoom
},*/
maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
maxResolution: 156543.0339
};
// Now initialise the map
map = new OpenLayers.Map(settings.mapContainer, options);
maps[settings.fieldName] = map;
var google_satellite = new OpenLayers.Layer.Google("Google Maps Satellite", {
type: google.maps.MapTypeId.SATELLITE,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_hybrid = new OpenLayers.Layer.Google("Google Maps Hybrid", {
type: google.maps.MapTypeId.HYBRID,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_normal = new OpenLayers.Layer.Google("Google Maps Normal", {
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_physical = new OpenLayers.Layer.Google("Google Maps Physical", {
type: google.maps.MapTypeId.TERRAIN,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
maps[settings.fieldName].addLayers([google_normal,google_satellite,google_hybrid,google_physical]);
maps[settings.fieldName].addControl(new OpenLayers.Control.Navigation());
maps[settings.fieldName].addControl(new OpenLayers.Control.Zoom());
maps[settings.fieldName].addControl(new OpenLayers.Control.MousePosition());
maps[settings.fieldName].addControl(new OpenLayers.Control.ScaleLine());
maps[settings.fieldName].addControl(new OpenLayers.Control.Scale('mapScale'));
maps[settings.fieldName].addControl(new OpenLayers.Control.LayerSwitcher());
// Vector/Drawing Layer Styles
style1 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#ffcc66",
fillOpacity: "0.7",
strokeColor: "#CC0000",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style2 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker-green.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style3 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1
});
var vlayerStyles = new OpenLayers.StyleMap({
"default": style1,
"select": style2,
"temporary": style3
});
vlayer = new OpenLayers.Layer.Vector( "Editable", {
styleMap: vlayerStyles,
rendererOptions: {
zIndexing: true
}
});
vlayers[settings.fieldName] = vlayer;
maps[settings.fieldName].addLayer(vlayers[settings.fieldName]);
var endDragfname = settings.fieldName+"_endDrag"
var code = ""
//code += "function "+endDragfname+"(feature, pixel) {";
code +="for (f in selectedFeatures) {";
code +=" f.state = OpenLayers.State.UPDATE;";
code +="}";
code +="refreshFeatures(\""+settings.fieldName+"\");";
code +="var latitude = parseFloat(jQuery('input[name=\""+settings.fieldName+"_latitude\"]').val());"
code +="var longitude = parseFloat(jQuery('input[name=\""+settings.fieldName+"_longitude\"]').val());"
code +="reverseGeocode(latitude, longitude,\""+settings.fieldName+"\");"
//code +="}";
var endDragf = new Function(code);
// Drag Control
var drag = new OpenLayers.Control.DragFeature(vlayers[settings.fieldName], {
onStart: startDrag,
onDrag: doDrag,
onComplete: endDragf
});
maps[settings.fieldName].addControl(drag);
// Vector Layer Events
vlayers[settings.fieldName].events.on({
beforefeaturesadded: function(event) {
//for(i=0; i < vlayer.features.length; i++) {
// if (vlayer.features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// vlayer.removeFeatures(vlayer.features);
// }
//}
// Disable this to add multiple points
// vlayer.removeFeatures(vlayer.features);
},
featuresadded: function(event) {
refreshFeatures(event,settings.fieldName);
},
featuremodified: function(event) {
refreshFeatures(event,settings.fieldName);
},
featuresremoved: function(event) {
refreshFeatures(event,settings.fieldName);
}
});
// Vector Layer Highlight Features
highlightCtrl = new OpenLayers.Control.SelectFeature(vlayers[settings.fieldName], {
hover: true,
highlightOnly: true,
renderIntent: "temporary"
});
selectCtrl = new OpenLayers.Control.SelectFeature(vlayers[settings.fieldName], {
clickout: true,
toggle: false,
multiple: false,
hover: false,
renderIntent: "select",
onSelect: addSelected,
onUnselect: clearSelected
});
maps[settings.fieldName].addControl(highlightCtrl);
maps[settings.fieldName].addControl(selectCtrl);
// Insert Saved Geometries
wkt = new OpenLayers.Format.WKT();
if(settings.geometries){
for(i in settings.geometries){
wktFeature = wkt.read(settings.geometries[i]);
wktFeature.geometry.transform(proj_4326,proj_900913);
vlayers[settings.fieldName].addFeatures(wktFeature);
}
}else{
// Default Point
point = new OpenLayers.Geometry.Point(settings.longitude, settings.latitude);
OpenLayers.Projection.transform(point, proj_4326, maps[settings.fieldName].getProjectionObject());
var origFeature = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(origFeature);
}
// Create a lat/lon object
var startPoint = new OpenLayers.LonLat(settings.longitude, settings.latitude);
startPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// Display the map centered on a latitude and longitude (Google zoom levels)
maps[settings.fieldName].setCenter(startPoint, 8);
// Create the Editing Toolbar
var container = document.getElementById(settings.editContainer);
var panel = new OpenLayers.Control.EditingToolbar(
vlayers[settings.fieldName], {
div: container
}
);
maps[settings.fieldName].addControl(panel);
panel.activateControl(panel.controls[0]);
drag.activate();
highlightCtrl.activate();
selectCtrl.activate();
jQuery('.'+settings.fieldName+'_locationButtonsLast').on('click', function () {
if (vlayers[settings.fieldName].features.length > 0) {
x = vlayers[settings.fieldName].features.length - 1;
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features[x]);
}
/*jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// Delete Selected Features
jQuery('.'+settings.fieldName+'_locationButtonsDelete').on('click', function () {
for(var y=0; y < selectedFeatures.length; y++) {
vlayers[settings.fieldName].removeFeatures(selectedFeatures);
}
/*jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// Clear Map
jQuery('.'+settings.fieldName+'_locationButtonsClear').on('click', function () {
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features);
jQuery('input[name="'+settings.fieldName+'_geometry[]"]').remove();
jQuery('input[name="'+settings.fieldName+'_latitude"]').val("");
jQuery('input[name="'+settings.fieldName+'_longitude"]').val("");
/*jQuery('#geometry_label').val("");
jQuery('#geometry_comment').val("");
jQuery('#geometry_color').val("");
jQuery('#geometry_lat').val("");
jQuery('#geometry_lon').val("");
jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// GeoCode
jQuery('.'+settings.fieldName+'_buttonFind').on('click', function () {
geoCode(settings.fieldName);
});
jQuery('#'+settings.fieldName+'_locationFind').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
geoCode(settings.fieldName);
return false;
}
});
// Event on Latitude/Longitude Typing Change
jQuery('#'+settings.fieldName+'_latitude, #'+settings.fieldName+'_longitude').bind("focusout keyup", function() {
var newlat = jQuery('input[name="'+settings.fieldName+'_latitude"]').val();
var newlon = jQuery('input[name="'+settings.fieldName+'_longitude"]').val();
if (!isNaN(newlat) && !isNaN(newlon))
{
// Clear the map first
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features);
jQuery('input[name="'+settings.fieldName+'_geometry[]"]').remove();
point = new OpenLayers.Geometry.Point(newlon, newlat);
OpenLayers.Projection.transform(point, proj_4326,proj_900913);
f = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(f);
// create a new lat/lon object
myPoint = new OpenLayers.LonLat(newlon, newlat);
myPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// display the map centered on a latitude and longitude
maps[settings.fieldName].panTo(myPoint);
}
else
{
// Commenting this out as its horribly annoying
//alert('Invalid value!');
}
});
}
function initViewMap(settings){
var defaultSettings = {
mapContainer:"mapContainer",
editContainer:"editContainer",
fieldName:"location"
};
settings = jQuery.extend(defaultSettings, settings);
var options = {
units: "dd",
numZoomLevels: 18,
controls:[],
theme: false,
projection: proj_900913,
'displayProjection': proj_4326,
/* eventListeners: {
"zoomend": incidentZoom
},*/
maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
maxResolution: 156543.0339
};
// Now initialise the map
map = new OpenLayers.Map(settings.mapContainer, options);
maps[settings.fieldName] = map
var google_satellite = new OpenLayers.Layer.Google("Google Maps Satellite", {
type: google.maps.MapTypeId.SATELLITE,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_hybrid = new OpenLayers.Layer.Google("Google Maps Hybrid", {
type: google.maps.MapTypeId.HYBRID,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_normal = new OpenLayers.Layer.Google("Google Maps Normal", {
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_physical = new OpenLayers.Layer.Google("Google Maps Physical", {
type: google.maps.MapTypeId.TERRAIN,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
maps[settings.fieldName].addLayers([google_normal,google_satellite,google_hybrid,google_physical]);
maps[settings.fieldName].addControl(new OpenLayers.Control.Navigation());
maps[settings.fieldName].addControl(new OpenLayers.Control.Zoom());
maps[settings.fieldName].addControl(new OpenLayers.Control.MousePosition());
maps[settings.fieldName].addControl(new OpenLayers.Control.ScaleLine());
maps[settings.fieldName].addControl(new OpenLayers.Control.Scale('mapScale'));
maps[settings.fieldName].addControl(new OpenLayers.Control.LayerSwitcher());
// Vector/Drawing Layer Styles
style1 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#ffcc66",
fillOpacity: "0.7",
strokeColor: "#CC0000",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style2 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker-green.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style3 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1
});
var vlayerStyles = new OpenLayers.StyleMap({
"default": style1,
"select": style2,
"temporary": style3
});
vlayer = new OpenLayers.Layer.Vector( "Editable", {
styleMap: vlayerStyles,
rendererOptions: {
zIndexing: true
}
});
vlayers[settings.fieldName] = vlayer
maps[settings.fieldName].addLayer(vlayers[settings.fieldName]);
// Insert Saved Geometries
wkt = new OpenLayers.Format.WKT();
if(settings.geometries){
for(i in settings.geometries){
wktFeature = wkt.read(settings.geometries[i]);
wktFeature.geometry.transform(proj_4326,proj_900913);
vlayers[settings.fieldName].addFeatures(wktFeature);
}
}else{
// Default Point
point = new OpenLayers.Geometry.Point(settings.longitude, settings.latitude);
OpenLayers.Projection.transform(point, proj_4326, maps[settings.fieldName].getProjectionObject());
var origFeature = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(origFeature);
}
// Create a lat/lon object
var startPoint = new OpenLayers.LonLat(settings.longitude, settings.latitude);
startPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// Display the map centered on a latitude and longitude (Google zoom levels)
maps[settings.fieldName].setCenter(startPoint, 8);
// Create the Editing Toolbar
//var container = document.getElementById(settings.editContainer);
//refreshFeatures(settings.fieldName);
}
function geoCode(fieldName)
{
jQuery('#'+fieldName+'_findLoading').html('<img src="res/openlayers/img/loading_g.gif">');
address = jQuery("#"+fieldName+"_locationFind").val();
jQuery.post("index.php?mod=events&act=geocode", {
address: address
},
function(data){
if (data.status == 'success'){
// Clear the map first
vlayers[fieldName].removeFeatures(vlayers[fieldName].features);
jQuery('input[name="'+fieldName+'_geometry[]"]').remove();
point = new OpenLayers.Geometry.Point(data.longitude, data.latitude);
OpenLayers.Projection.transform(point, proj_4326,proj_900913);
f = new OpenLayers.Feature.Vector(point);
vlayers[fieldName].addFeatures(f);
// create a new lat/lon object
myPoint = new OpenLayers.LonLat(data.longitude, data.latitude);
myPoint.transform(proj_4326, maps[fieldName].getProjectionObject());
// display the map centered on a latitude and longitude
maps[fieldName].panTo(myPoint);
// Update form values
jQuery("#"+fieldName+"_country_name").val(data.country);
jQuery('input[name="'+fieldName+'_latitude"]').val(data.latitude);
jQuery('input[name="'+fieldName+'_longitude"]').val(data.longitude);
jQuery("#"+fieldName+"_location_name").val(data.location_name);
} else {
// Alert message to be displayed
var alertMessage = address + " not found!\n\n***************************\n" +
"Enter more details like city, town, country\nor find a city or town " +
"close by and zoom in\nto find your precise location";
alert(alertMessage)
}
jQuery('div#'+fieldName+'_findLoading').html('');
}, "json");
return false;
}
/* Keep track of the selected features */
function addSelected(feature) {
selectedFeatures.push(feature);
selectCtrl.activate();
if (vlayer.features.length == 1 && feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// This is a single point, no need for geometry metadata
} else {
//jQuery('#geometryLabelerHolder').show(400);
if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
/*jQuery('#geometryLat').show();
jQuery('#geometryLon').show();
jQuery('#geometryColor').hide();
jQuery('#geometryStrokewidth').hide();*/
thisPoint = feature.clone();
thisPoint.geometry.transform(proj_900913,proj_4326);
/*jQuery('#geometry_lat').val(thisPoint.geometry.y);
jQuery('#geometry_lon').val(thisPoint.geometry.x);*/
} else {
/*jQuery('#geometryLat').hide();
jQuery('#geometryLon').hide();
jQuery('#geometryColor').show();
jQuery('#geometryStrokewidth').show();*/
}
/*if ( typeof(feature.label) != 'undefined') {
jQuery('#geometry_label').val(feature.label);
}
if ( typeof(feature.comment) != 'undefined') {
jQuery('#geometry_comment').val(feature.comment);
}
if ( typeof(feature.lon) != 'undefined') {
jQuery('#geometry_lon').val(feature.lon);
}
if ( typeof(feature.lat) != 'undefined') {
jQuery('#geometry_lat').val(feature.lat);
}
if ( typeof(feature.color) != 'undefined') {
jQuery('#geometry_color').val(feature.color);
}
if ( typeof(feature.strokewidth) != 'undefined' && feature.strokewidth != '') {
jQuery('#geometry_strokewidth').val(feature.strokewidth);
} else {
jQuery('#geometry_strokewidth').val("2.5");
}*/
}
}
/* Clear the list of selected features */
function clearSelected(feature) {
selectedFeatures = [];
/*jQuery('#geometryLabelerHolder').hide(400);
jQuery('#geometry_label').val("");
jQuery('#geometry_comment').val("");
jQuery('#geometry_color').val("");
jQuery('#geometry_lat').val("");
jQuery('#geometry_lon').val("");*/
selectCtrl.deactivate();
selectCtrl.activate();
//jQuery('#geometry_color').ColorPickerHide();
}
/* Feature starting to move */
function startDrag(feature, pixel) {
lastPixel = pixel;
}
/* Feature moving */
function doDrag(feature, pixel) {
for (f in selectedFeatures) {
if (feature != selectedFeatures[f]) {
var res = maps[settings.fieldName].getResolution();
selectedFeatures[f].geometry.move(res * (pixel.x - lastPixel.x), res * (lastPixel.y - pixel.y));
vlayer.drawFeature(selectedFeatures[f]);
}
}
lastPixel = pixel;
}
/* Featrue stopped moving */
/*function endDrag(feature, pixel) {
for (f in selectedFeatures) {
f.state = OpenLayers.State.UPDATE;
}
refreshFeatures(fieldName);
// Fetching Lat Lon Values
var latitude = parseFloat(jQuery('input[name="latitude"]').val());
var longitude = parseFloat(jQuery('input[name="longitude"]').val());
// Looking up country name using reverse geocoding
reverseGeocode(latitude, longitude);
}*/
function refreshFeatures(event,fieldName) {
var geoCollection = new OpenLayers.Geometry.Collection;
jQuery('input[name="'+fieldName+'_geometry[]"]').remove();
for(i=0; i < vlayers[fieldName].features.length; i++) {
newFeature = vlayers[fieldName].features[i].clone();
newFeature.geometry.transform(proj_900913,proj_4326);
geoCollection.addComponents(newFeature.geometry);
if (vlayers[fieldName].features.length == 1 && vlayers[fieldName].features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// If feature is a Single Point - save as lat/lon
} else {
// Otherwise, save geometry values
// Convert to Well Known Text
var format = new OpenLayers.Format.WKT();
var geometry = format.write(newFeature);
var label = '';
var comment = '';
var lon = '';
var lat = '';
var color = '';
var strokewidth = '';
if ( typeof(vlayers[fieldName].features[i].label) != 'undefined') {
label = vlayers[fieldName].features[i].label;
}
if ( typeof(vlayers[fieldName].features[i].comment) != 'undefined') {
comment = vlayers[fieldName].features[i].comment;
}
if ( typeof(vlayers[fieldName].features[i].lon) != 'undefined') {
lon = vlayers[fieldName].features[i].lon;
}
if ( typeof(vlayers[fieldName].features[i].lat) != 'undefined') {
lat = vlayers[fieldName].features[i].lat;
}
if ( typeof(vlayers[fieldName].features[i].color) != 'undefined') {
color = vlayers[fieldName].features[i].color;
}
if ( typeof(vlayers[fieldName].features[i].strokewidth) != 'undefined') {
strokewidth = vlayers[fieldName].features[i].strokewidth;
}
geometryAttributes = JSON.stringify({
geometry: geometry,
label: label,
comment: comment,
lat: lat,
lon: lon,
color: color,
strokewidth: strokewidth
});
jQuery('form').append(jQuery('<input></input>').attr('name',fieldName+'_geometry[]').attr('type','hidden').attr('value',geometryAttributes));
}
}
// Centroid of location will constitute the Location
// if its not a point
centroid = geoCollection.getCentroid(true);
jQuery('input[name="'+fieldName+'_latitude"]').val(centroid.y);
jQuery('input[name="'+fieldName+'_longitude"]').val(centroid.x);
}
function incidentZoom(event) {
jQuery("#incident_zoom").val(maps[settings.fieldName].getZoom());
}
function updateFeature(feature, color, strokeWidth){
// Create a symbolizer from exiting stylemap
var symbolizer = feature.layer.styleMap.createSymbolizer(feature);
// Color available?
if (color) {
symbolizer['fillColor'] = "#"+color;
symbolizer['strokeColor'] = "#"+color;
symbolizer['fillOpacity'] = "0.7";
} else {
if ( typeof(feature.color) != 'undefined' && feature.color != '' ) {
symbolizer['fillColor'] = "#"+feature.color;
symbolizer['strokeColor'] = "#"+feature.color;
symbolizer['fillOpacity'] = "0.7";
}
}
// Stroke available?
if (parseFloat(strokeWidth)) {
symbolizer['strokeWidth'] = parseFloat(strokeWidth);
} else if ( typeof(feature.strokewidth) != 'undefined' && feature.strokewidth !='' ) {
symbolizer['strokeWidth'] = feature.strokewidth;
} else {
symbolizer['strokeWidth'] = "2.5";
}
// Set the unique style to the feature
feature.style = symbolizer;
// Redraw the feature with its new style
feature.layer.drawFeature(feature);
}
// Reverse GeoCoder
function reverseGeocode(latitude, longitude,fieldName) {
var latlng = new google.maps.LatLng(latitude, longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var country = results[results.length - 1].formatted_address;
jQuery("#"+fieldName+"_country_name").val(country);
} else {
console.log("Geocoder failed due to: " + status);
}
});
} | txau/OpenEvSys | www/res/openlayers/map.js | JavaScript | agpl-3.0 | 26,354 |
// installed by cozy-scripts
require('babel-polyfill')
// polyfill for requestAnimationFrame
/* istanbul ignore next */
global.requestAnimationFrame = cb => {
setTimeout(cb, 0)
}
| gregorylegarec/cozy-collect | test/jestLib/setup.js | JavaScript | agpl-3.0 | 182 |
'use strict';
angular.module('malariaplantdbApp')
.config(function ($stateProvider) {
$stateProvider
.state('admin', {
abstract: true,
parent: 'site'
});
});
| acheype/malaria-plant-db | src/main/webapp/scripts/app/admin/admin.js | JavaScript | agpl-3.0 | 231 |
OC.L10N.register(
"external",
{
"Please enter valid urls - they have to start with either http://, https:// or /" : "Ju lutemi, jepni URL të vlefshme - duhet të fillojnë http://, https:// ose /",
"External sites saved." : "Sajtet e jashtëm u ruajtën.",
"External Sites" : "Sajte të Jashtëm",
"Please note that some browsers will block displaying of sites via http if you are running https." : "Ju lutemi, kini parasysh që disa shfletues do të bllokojnë shfaqjen e sajteve përmes http-je, nëse xhironi https.",
"Furthermore please note that many sites these days disallow iframing due to security reasons." : "Për më tepër, ju lutemi, kini parasysh që mjaft sajte në këto kohë s’lejojnë iframing, për arsye sigurie.",
"We highly recommend to test the configured sites below properly." : "Këshillojmë me forcë të testoni si duhet më poshtë sajtet e formësuar.",
"Name" : "Emër",
"URL" : "URL",
"Select an icon" : "Përzgjidhni një ikonë",
"Remove site" : "Hiqe sajtin",
"Add" : "Shtoje"
},
"nplurals=2; plural=(n != 1);");
| jacklicn/owncloud | apps/external/l10n/sq.js | JavaScript | agpl-3.0 | 1,106 |
/* Copyright 2012 Canonical Ltd. This software is licensed under the
* GNU Affero General Public License version 3 (see the file LICENSE). */
YUI.add('lp.registry.team.mailinglists.test', function (Y) {
// Local aliases.
var Assert = Y.Assert,
ArrayAssert = Y.ArrayAssert;
var team_mailinglists = Y.lp.registry.team.mailinglists;
var tests = Y.namespace('lp.registry.team.mailinglists.test');
tests.suite = new Y.Test.Suite('lp.registry.team.mailinglists Tests');
tests.suite.add(new Y.Test.Case({
name: 'Team Mailinglists',
setUp: function() {
window.LP = {
links: {},
cache: {}
};
},
tearDown: function() {
},
test_render_message: function () {
var config = {
messages: [
{
'message_id': 3,
'headers': {
'Subject': 'Please stop breaking things',
'To': '[email protected]',
'From': '[email protected]',
'Date': '2011-10-13'
},
'nested_messages': [],
'attachments': []
}
],
container: Y.one('#messagelist'),
forwards_navigation: Y.all('.last,.next'),
backwards_navigation: Y.all('.first,.previous')
};
var message_list = new Y.lp.registry.team.mailinglists.MessageList(
config);
message_list.display_messages();
var message = Y.one("#message-3");
Assert.areEqual(message.get('text'), 'Please stop breaking things');
},
test_nav: function () {
var config = {
messages: [],
container: Y.one('#messagelist'),
forwards_navigation: Y.all('.last,.next'),
backwards_navigation: Y.all('.first,.previous')
};
var message_list = new Y.lp.registry.team.mailinglists.MessageList(
config);
var fired = false;
Y.on('messageList:backwards', function () {
fired = true;
});
var nav_link = Y.one('.first');
nav_link.simulate('click');
Assert.isTrue(fired);
}
}));
}, '0.1', {
requires: ['test', 'lp.testing.helpers', 'test-console',
'lp.registry.team.mailinglists', 'lp.mustache',
'node-event-simulate', 'widget-stack', 'event']
});
| abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/registry/javascript/tests/test_team_mailinglists.js | JavaScript | agpl-3.0 | 2,657 |
/*
* 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/>.
*/
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u044f\u043a\u0448\u0430\u043d\u0431\u0430",
"\u0434\u0443\u0448\u0430\u043d\u0431\u0430",
"\u0441\u0435\u0448\u0430\u043d\u0431\u0430",
"\u0447\u043e\u0440\u0448\u0430\u043d\u0431\u0430",
"\u043f\u0430\u0439\u0448\u0430\u043d\u0431\u0430",
"\u0436\u0443\u043c\u0430",
"\u0448\u0430\u043d\u0431\u0430"
],
"ERANAMES": [
"\u041c.\u0410.",
"\u042d"
],
"ERAS": [
"\u041c.\u0410.",
"\u042d"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u042f\u043d\u0432\u0430\u0440",
"\u0424\u0435\u0432\u0440\u0430\u043b",
"\u041c\u0430\u0440\u0442",
"\u0410\u043f\u0440\u0435\u043b",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433\u0443\u0441\u0442",
"\u0421\u0435\u043d\u0442\u044f\u0431\u0440",
"\u041e\u043a\u0442\u044f\u0431\u0440",
"\u041d\u043e\u044f\u0431\u0440",
"\u0414\u0435\u043a\u0430\u0431\u0440"
],
"SHORTDAY": [
"\u042f\u043a\u0448",
"\u0414\u0443\u0448",
"\u0421\u0435\u0448",
"\u0427\u043e\u0440",
"\u041f\u0430\u0439",
"\u0416\u0443\u043c",
"\u0428\u0430\u043d"
],
"SHORTMONTH": [
"\u042f\u043d\u0432",
"\u0424\u0435\u0432",
"\u041c\u0430\u0440",
"\u0410\u043f\u0440",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433",
"\u0421\u0435\u043d",
"\u041e\u043a\u0442",
"\u041d\u043e\u044f",
"\u0414\u0435\u043a"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, y MMMM dd",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "yy/MM/dd HH:mm",
"shortDate": "yy/MM/dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "uz-cyrl",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| Cineca/OrcidHub | src/main/webapp/bower_components/angular-i18n/angular-locale_uz-cyrl.js | JavaScript | agpl-3.0 | 3,592 |
MWF.xApplication.Selector = MWF.xApplication.Selector || {};
MWF.xDesktop.requireApp("Selector", "Identity", null, false);
MWF.xApplication.Selector.IdentityWidthDuty = new Class({
Extends: MWF.xApplication.Selector.Identity,
options: {
"style": "default",
"count": 0,
"title": "",
"dutys": [],
"units": [],
"values": [],
"zIndex": 1000,
"expand": false,
"noUnit" : false,
"include" : [], //增加的可选项
"resultType" : "", //可以设置成个人,那么结果返回个人
"expandSubEnable": true,
"selectAllEnable" : true, //分类是否允许全选下一层
"exclude" : [],
"selectType" : "identity"
},
setInitTitle: function(){
this.setOptions({"title": MWF.xApplication.Selector.LP.selectIdentity});
},
_init : function(){
this.selectType = "identity";
this.className = "IdentityWidthDuty"
},
loadSelectItems: function(addToNext){
this.loadingCountDuty = "wait";
this.allUnitObjectWithDuty = {};
var afterLoadSelectItemFun = this.afterLoadSelectItem.bind(this);
if( this.options.disabled ){
this.afterLoadSelectItem();
return;
}
if( this.options.resultType === "person" ){
if( this.titleTextNode ){
this.titleTextNode.set("text", MWF.xApplication.Selector.LP.selectPerson );
}else{
this.options.title = MWF.xApplication.Selector.LP.selectPerson;
}
}
if (this.options.dutys.length){
var dutyLoaded = 0;
var loadDutySuccess = function () {
dutyLoaded++;
if( dutyLoaded === this.options.dutys.length ){
this.dutyLoaded = true;
if( this.includeLoaded ){
afterLoadSelectItemFun();
}
}
}.bind(this);
this.loadInclude( function () {
this.includeLoaded = true;
if( this.dutyLoaded ){
afterLoadSelectItemFun();
}
}.bind(this));
var loadDuty = function () {
if( this.isCheckStatusOrCount() ){
this.loadingCountDuty = "ready";
this.checkLoadingCount();
}
this.options.dutys.each(function(duty){
var data = {"name": duty, "id":duty};
var category = this._newItemCategory("ItemCategory",data, this, this.itemAreaNode);
this.subCategorys.push(category);
this.allUnitObjectWithDuty[data.name] = category;
loadDutySuccess();
}.bind(this));
}.bind(this);
if( this.options.units.length === 0 ){
loadDuty();
}else{
var unitList = [];
this.options.units.each(function(u) {
var unitName = typeOf(u) === "string" ? u : (u.distinguishedName || u.unique || u.levelName || u.id);
if (unitName)unitList.push( unitName )
});
debugger;
if( !this.options.expandSubEnable ){
this.allUnitNames = unitList;
loadDuty();
}else{
var unitObjectList = [];
var loadNestedUnit = function(){
MWF.Actions.get("x_organization_assemble_express").listUnitSubNested({"unitList": unitList }, function(json1){
var unitNames = [];
//排序
if( this.options.units.length === 1 ){
// unitNames = unitList.concat( json1.data );
unitNames = Array.clone(unitList);
for( var i=0; i<json1.data.length; i++ ){
if( !unitNames.contains(json1.data[i].distinguishedName) ){
unitNames.push( json1.data[i].distinguishedName );
}
}
}else{
unitObjectList.each( function ( u ) {
unitNames.push( u.distinguishedName || u.unique || u.levelName || u.id );
for( var i=0; i<json1.data.length; i++ ){
if( json1.data[i].levelName.indexOf(u.levelName) > -1 ){
unitNames.push( json1.data[i].distinguishedName );
}
}
})
}
this.allUnitNames = unitNames;
loadDuty();
}.bind(this), null);
}.bind(this);
var flag = false; //需要获取层次名用于排序
if( this.options.units.length === 1 ){
loadNestedUnit();
}else{
this.options.units.each(function(u) {
if (typeOf(u) === "string" ) {
u.indexOf("/") === -1 ? (flag = true) : unitObjectList.push( { levelName : u } );
} else {
u.levelName ? unitObjectList.push( u ) : (flag = true);
}
});
if( flag ){ //需要获取层次名来排序
o2.Actions.load("x_organization_assemble_express").UnitActions.listObject( function (json) {
unitObjectList = json.data || [];
loadNestedUnit();
}.bind(this) )
}else{
loadNestedUnit();
}
}
}
}
}
if( this.isCheckStatusOrCount() ) {
this.loadingCountInclude = "wait";
this.loadIncludeCount();
}
},
search: function(){
var key = this.searchInput.get("value");
if (key){
this.initSearchArea(true);
var createdId = this.searchInItems(key) || [];
if( this.options.include && this.options.include.length ){
this.includeObject.listByFilter( "key", key, function( array ){
array.each( function(d){
if( !createdId.contains( d.distinguishedName ) ){
if( !this.isExcluded( d ) ) {
this._newItem( d, this, this.itemSearchAreaNode);
}
}
}.bind(this))
}.bind(this))
}
}else{
this.initSearchArea(false);
}
},
listPersonByPinyin: function(node){
this.searchInput.focus();
var pinyin = this.searchInput.get("value");
pinyin = pinyin+node.get("text");
this.searchInput.set("value", pinyin);
this.search();
},
checkLoadSelectItems: function(){
if (!this.options.units.length){
this.loadSelectItems();
}else{
this.loadSelectItems();
}
},
_scrollEvent: function(y){
return true;
},
_getChildrenItemIds: function(){
return null;
},
_newItemCategory: function(type, data, selector, item, level, category, delay){
return new MWF.xApplication.Selector.IdentityWidthDuty[type](data, selector, item, level, category, delay)
},
_listItemByKey: function(callback, failure, key){
if (this.options.units.length) key = {"key": key, "unitList": this.options.units};
this.orgAction.listIdentityByKey(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, key);
},
_getItem: function(callback, failure, id, async){
this.orgAction.getIdentity(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, ((typeOf(id)==="string") ? id : id.distinguishedName), async);
},
_newItemSelected: function(data, selector, item, selectedNode){
return new MWF.xApplication.Selector.IdentityWidthDuty.ItemSelected(data, selector, item, selectedNode)
},
_listItemByPinyin: function(callback, failure, key){
if (this.options.units.length) key = {"key": key, "unitList": this.options.units};
this.orgAction.listIdentityByPinyin(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, key);
},
_newItem: function(data, selector, container, level, category, delay){
return new MWF.xApplication.Selector.IdentityWidthDuty.Item(data, selector, container, level, category, delay);
},
_newItemSearch: function(data, selector, container, level){
return new MWF.xApplication.Selector.IdentityWidthDuty.SearchItem(data, selector, container, level);
},
uniqueIdentityList: function(list){
var items = [], map = {};
(list||[]).each(function(d) {
if (d.distinguishedName || d.unique) {
if ((!d.distinguishedName || !map[d.distinguishedName]) && (!d.unique || !map[d.unique])) {
items.push(d);
map[d.distinguishedName] = true;
map[d.unique] = true;
}
} else {
items.push(d);
}
})
return items;
},
loadIncludeCount: function(){
var unitList = [];
var groupList = [];
if (this.options.include.length > 0) {
this.options.include.each(function (d) {
var dn = typeOf(d) === "string" ? d : d.distinguishedName;
var flag = dn.split("@").getLast().toLowerCase();
if (flag === "u") {
unitList.push(dn);
} else if (flag === "g") {
groupList.push(dn)
}
})
}
if(unitList.length || groupList.length){
this._loadUnitAndGroupCount(unitList, groupList, function () {
this.loadingCountInclude = "ready";
this.checkLoadingCount();
}.bind(this));
}else{
this.loadingCountInclude = "ignore";
this.checkLoadingCount();
}
},
checkLoadingCount: function(){
if(this.loadingCountDuty === "ready" && this.loadingCountInclude === "ready"){
this.checkCountAndStatus();
this.loadingCount = "done";
}else if(this.loadingCountDuty === "ready" && this.loadingCountInclude === "ignore"){
this.loadingCount = "done";
}
},
addSelectedCount: function( itemOrItemSelected, count, items ){
if( this.loadingCountInclude === "ignore" ){
this._addSelectedCountWithDuty(itemOrItemSelected, count, items);
}else{
this._addSelectedCountWithDuty(itemOrItemSelected, count, items);
this._addSelectedCount(itemOrItemSelected, count);
}
},
_addSelectedCountWithDuty: function( itemOrItemSelected, count, items ){
var itemData = itemOrItemSelected.data;
debugger;
items.each(function(item){
if(item.category && item.category._addSelectedCount && item.category.className === "ItemCategory"){
item.category._addSelectedCount( count );
}
}.bind(this));
},
//_listItemNext: function(last, count, callback){
// this.action.listRoleNext(last, count, function(json){
// if (callback) callback.apply(this, [json]);
// }.bind(this));
//}
});
MWF.xApplication.Selector.IdentityWidthDuty.Item = new Class({
Extends: MWF.xApplication.Selector.Identity.Item,
_getShowName: function(){
return this.data.name;
},
_getTtiteText: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/personicon.png)");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.SearchItem = new Class({
Extends: MWF.xApplication.Selector.Identity.Item,
_getShowName: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemSelected = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemSelected,
_getShowName: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_getTtiteText: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/personicon.png)");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemCategory,
createNode: function(){
this.className = "ItemCategory";
this.node = new Element("div", {
"styles": this.selector.css.selectorItemCategory_department,
"title" : this._getTtiteText()
}).inject(this.container);
},
_getShowName: function(){
return this.data.name;
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/companyicon.png)");
},
_addSelectAllSelectedCount: function(){
var count = this._getSelectedCount();
this._checkCountAndStatus(count);
},
_addSelectedCount : function(){
if( this.selector.loadingCount === "done" ){
var count = this._getSelectedCount();
this._checkCountAndStatus(count);
}
},
_getTotalCount : function(){
return this.subItems.length;
},
_getSelectedCount : function(){
var list = this.subItems.filter( function (item) { return item.isSelected; });
return list.length;
},
loadSub : function(callback){
this._loadSub( function( firstLoad ) {
if(firstLoad){
if( this.selector.isCheckStatusOrCount() ){
// var count = this._getSelectedCount();
// this.checkCountAndStatus(count);
if( this.selector.loadingCount === "done" ){
this.checkCountAndStatus();
}
}
}
if(callback)callback();
}.bind(this))
},
_loadSub: function(callback){
if (!this.loaded && !this.loadingsub){
this.loadingsub = true;
if (this.selector.options.units.length){
var data = {
"name":this.data.name,
"unit":"",
"unitList" : this.selector.allUnitNames
};
MWF.Actions.get("x_organization_assemble_express").getDuty(data, function(json){
var list = this.selector.uniqueIdentityList(json.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
if (!this.loaded) {
this.loaded = true;
this.loadingsub = false;
this.itemLoaded = true;
if (callback) callback( true );
}
}.bind(this), null, false);
// if (this.selector.options.units.length){
// var action = MWF.Actions.get("x_organization_assemble_express");
// var data = {"name":this.data.name, "unit":""};
// var count = this.selector.options.units.length;
// var i = 0;
//
// if (this.selector.options.expandSubEnable) {
// this.selector.options.units.each(function(u){
// var unitName = "";
// if (typeOf(u)==="string"){
// unitName = u;
// }else{
// unitName = u.distinguishedName || u.unique || u.id || u.levelName
// }
// if (unitName){
// var unitNames;
// action.listUnitNameSubNested({"unitList": [unitName]}, function(json){
// unitNames = json.data.unitList;
// }.bind(this), null, false);
//
// unitNames.push(unitName);
// if (unitNames && unitNames.length){
// data.unitList = unitNames;
// action.getDuty(data, function(json){
// json.data.each(function(idSubData){
// if( !this.selector.isExcluded( idSubData ) ) {
// var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
// this.selector.items.push(item);
// if(this.subItems)this.subItems.push( item );
// }
// }.bind(this));
// }.bind(this), null, false);
// }
// }
//
// i++;
// if (i>=count){
// if (!this.loaded) {
// this.loaded = true;
// this.loadingsub = false;
// this.itemLoaded = true;
// if (callback) callback();
// }
// }
// }.bind(this));
// }else{
// this.selector.options.units.each(function(u){
// if (typeOf(u)==="string"){
// data.unit = u;
// }else{
// data.unit = u.distinguishedName || u.unique || u.id || u.levelName
// }
// action.getDuty(data, function(json){
// json.data.each(function(idSubData){
// if( !this.selector.isExcluded( idSubData ) ) {
// var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
// this.selector.items.push(item);
// if(this.subItems)this.subItems.push( item );
// }
// }.bind(this));
// i++;
// if (i>=count){
// if (!this.loaded) {
// this.loaded = true;
// this.loadingsub = false;
// this.itemLoaded = true;
// if (callback) callback();
// }
// }
// }.bind(this));
// }.bind(this));
// }
}else{
this.selector.orgAction.listIdentityWithDuty(function(json){
var list = this.selector.uniqueIdentityList(json.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
this.loaded = true;
this.loadingsub = false;
if (callback) callback( true );
}.bind(this), null, this.data.name);
}
}else{
if (callback) callback( );
}
},
loadCategoryChildren: function(callback){
this.loadSub(callback);
this.categoryLoaded = true;
//if (callback) callback();
},
loadItemChildren: function(callback){
this.loadSub(callback);
},
_hasChild: function(){
return true;
},
_hasChildCategory: function(){
return true;
},
_hasChildItem: function(){
return true;
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemUnitCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemUnitCategory,
loadSub: function(callback){
if (!this.loaded){
this.selector.orgAction.listIdentityWithUnit(function(idJson){
if( !this.itemLoaded ){
var list = this.selector.uniqueIdentityList(idJson.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
this.itemLoaded = true;
}
if( !this.selector.options.expandSubEnable ){
this.loaded = true;
if (callback) callback();
}
if( this.selector.options.expandSubEnable ){
this.selector.orgAction.listSubUnitDirect(function(json){
json.data.each(function(subData){
if( !this.selector.isExcluded( subData ) ) {
if( subData && this.data.parentLevelName)subData.parentLevelName = this.data.parentLevelName +"/" + subData.name;
var category = this.selector._newItemCategory("ItemUnitCategory", subData, this.selector, this.children, this.level + 1, this);
this.subCategorys.push( category );
this.subCategoryMap[subData.parentLevelName || subData.levelName] = category;
}
}.bind(this));
this.loaded = true;
if (callback) callback();
}.bind(this), null, this.data.distinguishedName);
}
}.bind(this), null, this.data.distinguishedName);
}else{
if (callback) callback( );
}
},
loadCategoryChildren: function(callback){
if (!this.categoryLoaded){
this.loadSub(callback);
this.categoryLoaded = true;
this.itemLoaded = true;
//if( this.selector.options.expandSubEnable ){
// this.selector.orgAction.listSubUnitDirect(function(json){
// json.data.each(function(subData){
// if( !this.selector.isExcluded( subData ) ) {
// var category = this.selector._newItemCategory("ItemUnitCategory", subData, this.selector, this.children, this.level + 1, this);
// this.subCategorys.push( category );
// }
// }.bind(this));
// this.categoryLoaded = true;
// if (callback) callback();
// }.bind(this), null, this.data.distinguishedName);
//}else{
// if (callback) callback();
//}
}else{
if (callback) callback( );
}
},
loadItemChildren: function(callback){
if (!this.itemLoaded){
this.selector.orgAction.listIdentityWithUnit(function(idJson){
var list = this.selector.uniqueIdentityList(idJson.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
if (callback) callback();
}.bind(this), null, this.data.distinguishedName);
this.itemLoaded = true;
}else{
if (callback) callback( );
}
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemGroupCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemGroupCategory
});
MWF.xApplication.Selector.IdentityWidthDuty.Filter = new Class({
Implements: [Options, Events],
options: {
"style": "default",
"units": [],
"dutys": []
},
initialize: function(value, options){
this.setOptions(options);
this.value = value;
this.orgAction = MWF.Actions.get("x_organization_assemble_control");
},
getList: function(callback){
if (false && this.list){
if (callback) callback();
}else{
this.list = [];
MWF.require("MWF.widget.PinYin", function(){
this.options.dutys.each(function(duty){
if (this.options.units.length){
var action = MWF.Actions.get("x_organization_assemble_express");
var data = {"name":duty, "unit":""};
this.options.units.each(function(u){
if (typeOf(u)==="string"){
data.unit = u;
}else{
data.unit = u.distinguishedName || u.unique || u.levelName || u.id
}
action.getDuty(data, function(json){
json.data.each(function(d){
d.pinyin = d.name.toPY().toLowerCase();
d.firstPY = d.name.toPYFirst().toLowerCase();
this.list.push(d);
}.bind(this));
}.bind(this), null, false);
}.bind(this));
}else{
this.orgAction.listIdentityWithDuty(function(json){
json.data.each(function(d){
d.pinyin = d.name.toPY().toLowerCase();
d.firstPY = d.name.toPYFirst().toLowerCase();
this.list.push(d);
}.bind(this));
}.bind(this), null, duty, false);
}
}.bind(this));
if (callback) callback();
}.bind(this));
}
},
filter: function(value, callback){
this.value = value;
this.getList(function(){
var data = this.list.filter(function(d){
var text = d.name+"#"+d.pinyin+"#"+d.firstPY;
return (text.indexOf(this.value)!=-1);
}.bind(this));
if (callback) callback(data);
}.bind(this));
}
});
| o2oa/o2oa | o2web/source/x_component_Selector/IdentityWidthDuty.js | JavaScript | agpl-3.0 | 29,141 |
/**
*
* @param viewMode
* @constructor
*/
function ComboBoxControl( viewMode ) {
_.superClass( ListBoxControl, this, viewMode );
}
_.inherit( ComboBoxControl, ListEditorBaseControl );
_.extend( ComboBoxControl.prototype, {
/**
*
* @returns {ComboBoxModel}
*/
createControlModel: function() {
return new ComboBoxModel();
},
/**
*
* @param model
* @returns {ComboBoxView}
*/
createControlView: function( model ) {
return new ComboBoxView( { model: model } );
},
/**
*
* @param message
*/
setNoItemsMessage: function( message ) {
this.controlModel.setNoItemsMessage( message );
}
} );
InfinniUI.ComboBoxControl = ComboBoxControl;
| InfinniPlatform/InfinniUI | app/controls/comboBox/comboBoxControl.js | JavaScript | agpl-3.0 | 752 |
/**
* The tab view stacks several pages above each other and allows to switch
* between them by using a list of buttons.
*
* The buttons are positioned on one of the tab view's edges.
*
* *Example*
*
* Here is a little example of how to use the widget.
*
* <pre class='javascript'>
* var tabView = new qx.ui.tabview.TabView();
*
* var page1 = new qx.ui.tabview.Page("Layout", "icon/16/apps/utilities-terminal.png");
* page1.setLayout(new qx.ui.layout.VBox());
* page1.add(new qx.ui.basic.Label("Page Content"));
* tabView.add(page1);
*
* var page2 = new qx.ui.tabview.Page("Notes", "icon/16/apps/utilities-notes.png");
* tabView.add(page2);
*
* this.getRoot().add(tabView);
* </pre>
*
* This example builds a tab view with two pages called "Layout" and "Notes".
* Each page is a container widget, which can contain any other widget. Note
* that the pages need layout to render their children.
*
* *External Documentation*
*
* <a href='http://manual.qooxdoo.org/1.4/pages/widget/tabview.html' target='_blank'>
* Documentation of this widget in the qooxdoo manual.</a>
*/
| Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/framework/source/class/qx/ui/tabview/__init__.js | JavaScript | agpl-3.0 | 1,118 |
load('nashorn:mozilla_compat.js');
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
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. 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/>.
*/
/* J.J.
NLC VIP Eye Color Change.
*/
var status = 0;
var price = 1000000;
var colors = Array();
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (mode == 0 && status == 0) {
cm.dispose();
return;
}
if (mode == 1)
status++;
else
status--;
if (status == 0) {
cm.sendSimple("Hey, there~! I'm J.J.! I'm in charge of the cosmetic lenses here at NLC Shop! If you have a #b#t5152036##k, I can get you the best cosmetic lenses you have ever had! Now, what would you like to do?\r\n#L1#I would like to buy a #b#t5152036##k for " + price + " mesos, please!#l\r\n\#L2#I already have a Coupon!#l");
} else if (status == 1) {
if (selection == 1) {
if(cm.getMeso() >= price) {
cm.gainMeso(-price);
cm.gainItem(5152036, 1);
cm.sendOk("Enjoy!");
} else {
cm.sendOk("You don't have enough mesos to buy a coupon!");
}
cm.dispose();
} else if (selection == 2) {
if (cm.getChar().getGender() == 0) {
var current = cm.getChar().getFace()
% 100 + 20000;
}
if (cm.getChar().getGender() == 1) {
var current = cm.getChar().getFace()
% 100 + 21000;
}
colors = Array();
colors = Array(current , current + 100, current + 200, current + 300, current +400, current + 500, current + 600, current + 700);
cm.sendStyle("With our specialized machine, you can see yourself after the treatment in advance. What kind of lens would you like to wear? Choose the style of your liking.", colors);
}
}
else if (status == 2){
cm.dispose();
if (cm.haveItem(5152036) == true){
cm.gainItem(5152036, -1);
cm.setFace(colors[selection]);
cm.sendOk("Enjoy your new and improved cosmetic lenses!");
} else {
cm.sendOk("I'm sorry, but I don't think you have our cosmetic lens coupon with you right now. Without the coupon, I'm afraid I can't do it for you..");
}
}
}
}
| NoetherEmmy/intransigentms-scripts | npc/9201062.js | JavaScript | agpl-3.0 | 2,969 |
import {EditorState} from 'draft-js';
import {repositionHighlights, redrawHighlights} from '.';
/**
* @typedef StateWithComment
* @property {ContentState} editorState
* @property {Comment} activeHighlight
*/
/**
* @name updateHighlights
* @description Updates highlight information after every content change. It
* recalculates offsets (start and end points) and reapplies the inline styling to
* match these.
* @param {EditorState} oldState
* @param {EditorState} newState
* @returns {StateWithComment}
*/
export function updateHighlights(oldState, newState) {
let updatedState = repositionHighlights(oldState, newState);
let {editorState, activeHighlight} = redrawHighlights(updatedState);
let contentChanged = oldState.getCurrentContent() !== newState.getCurrentContent();
if (contentChanged) {
editorState = preserveSelection(editorState, newState.getCurrentContent());
}
return {editorState, activeHighlight};
}
// Preserve before & after selection when content was changed. This helps
// with keeping the cursor more or less in the same position when undo-ing
// and redo-ing. Without this, all of the recalculating of offsets and styles
// will misplace the cursor position when the user performs an Undo operation.
function preserveSelection(es, content) {
let editorState = es;
let selectionBefore = content.getSelectionBefore();
let selectionAfter = content.getSelectionAfter();
editorState = EditorState.set(editorState, {allowUndo: false});
editorState = EditorState.push(editorState, editorState.getCurrentContent()
.set('selectionBefore', selectionBefore)
.set('selectionAfter', selectionAfter)
);
return EditorState.set(editorState, {allowUndo: true});
}
| Aca-jov/superdesk-client-core | scripts/core/editor3/reducers/highlights/highlights.js | JavaScript | agpl-3.0 | 1,765 |
define([
"breakeven/config"
], function (
config
) {
return {
input: {
verkaufspreis: 75000,
absatzmenge: 200,
variable_kosten: 2500,
fixkosten: 8000,
fixkosten_in_prozent: 22.4,
stueckkosten: 150,
deckungsbeitrag: 50,
gewinnschwelle: 1250,
umsatzerloese: 250000,
gesamtkosten: 28000,
ergebnis: 10000,
berechnungsart: 5,
veraenderliche_groese: 4,
config: config
},
expectedOutput: {
verkaufspreis: 0,
absatzmenge: 200,
variable_kosten: 2500,
fixkosten: 8000,
fixkosten_in_prozent: 76.19047619047619,
stueckkosten: 12.5,
deckungsbeitrag: -12.5,
gewinnschwelle: -640,
umsatzerloese: 0,
gesamtkosten: 10500,
ergebnis: -10500,
error: false
}
}
});
| ohaz/amos-ss15-proj1 | FlaskWebProject/static/scripts/rechner/spec/breakeven/testData2.js | JavaScript | agpl-3.0 | 829 |
Ext.define("CMDBuild.controller.management.common.CMModClassAndWFCommons", {
/*
* retrieve the form to use as target for the
* templateResolver asking it to its view
*
* returns null if something is not right
*/
getFormForTemplateResolver: function() {
var form = null;
if (this.view) {
var wm = this.view.getWidgetManager();
if (wm && typeof wm.getFormForTemplateResolver == "function") {
form = wm.getFormForTemplateResolver() || null;
}
}
return form;
}
}); | jzinedine/CMDBuild | cmdbuild/src/main/webapp/javascripts/cmdbuild/controller/management/common/CMModClassAndWFCommons.js | JavaScript | agpl-3.0 | 497 |
/*
* Copyright (C) 2016 OpenMotics BV
*
* 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/>.
*/
import {inject, customElement, bindable, bindingMode} from 'aurelia-framework';
import 'bootstrap';
import 'bootstrap-toggle';
import {Base} from '../base';
import {Toolbox} from '../../components/toolbox';
import Shared from '../../components/shared';
@bindable({
name: 'thermostat',
defaultBindingMode: bindingMode.twoWay
})
@customElement('global-thermostat')
@inject(Element)
export class GlobalThermostat extends Base {
constructor(element, ...rest) {
super(...rest);
this.element = element;
this.bool = false;
}
thermostatWidth() {
let offset = Shared === undefined || Shared.locale === 'en' ? 0 : 20;
let width = Toolbox.getDeviceViewport() === 'lg' ? 110 + offset : 40;
return `${width}px`;
}
}
| openmotics/gateway-frontend | src/resources/globalthermostat/thermostat.js | JavaScript | agpl-3.0 | 1,490 |
// Copyright 2015 by Paulo Augusto Peccin. See license.txt distributed with this file.
// Implements the 64K "X07" AtariAge format
jt.Cartridge64K_X07 = function(rom, format) {
"use strict";
function init(self) {
self.rom = rom;
self.format = format;
bytes = rom.content; // uses the content of the ROM directly
self.bytes = bytes;
}
this.read = function(address) {
// Always add the correct offset to access bank selected
return bytes[bankAddressOffset + (address & ADDRESS_MASK)];
};
this.performBankSwitchOnMonitoredAccess = function(address) {
if ((address & 0x180f) === 0x080d) // Method 1
bankAddressOffset = ((address & 0x00f0) >> 4) * BANK_SIZE; // Pick bank from bits 7-4
else if (bankAddressOffset >= BANK_14_ADDRESS && (address & 0x1880) === 0x0000) // Method 2, only if at bank 14 or 15
bankAddressOffset = ((address & 0x0040) === 0 ? 14 : 15) * BANK_SIZE; // Pick bank 14 or 15 from bit 6
};
// Savestate -------------------------------------------
this.saveState = function() {
return {
f: this.format.name,
r: this.rom.saveState(),
b: jt.Util.compressInt8BitArrayToStringBase64(bytes),
bo: bankAddressOffset
};
};
this.loadState = function(state) {
this.format = jt.CartridgeFormats[state.f];
this.rom = jt.ROM.loadState(state.r);
bytes = jt.Util.uncompressStringBase64ToInt8BitArray(state.b, bytes);
this.bytes = bytes;
bankAddressOffset = state.bo;
};
var bytes;
var bankAddressOffset = 0;
var ADDRESS_MASK = 0x0fff;
var BANK_SIZE = 4096;
var BANK_14_ADDRESS = 14 * BANK_SIZE;
if (rom) init(this);
};
jt.Cartridge64K_X07.prototype = jt.CartridgeBankedByBusMonitoring.base;
jt.Cartridge64K_X07.recreateFromSaveState = function(state, prevCart) {
var cart = prevCart || new jt.Cartridge64K_X07();
cart.loadState(state);
return cart;
};
| ppeccin/javatari.js | src/main/atari/cartridge/formats/Cartridge64K_X07.js | JavaScript | agpl-3.0 | 2,125 |
'use strict'
exports.up = function(knex) {
return knex.schema.createTable('comments', function(table) {
table.increments()
table.string('text').notNullable()
table.integer('userId')
table.integer('pageId')
table.integer('parentId')
table.timestamp('createdAt').defaultTo(knex.raw('CURRENT_TIMESTAMP'))
table.timestamp('modifiedAt').defaultTo(knex.raw('CURRENT_TIMESTAMP'))
table.timestamp('deletedAt')
})
}
exports.down = function(knex) {
return knex.schema.dropTable('comments')
}
| fiddur/some-comments | migrations/20150923143009_comments.js | JavaScript | agpl-3.0 | 524 |
var utils = require('../../utils');
var discoverHelper = require('../../helpers/discover-helper');
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
describe('discover search', () => {
before(async () => {
browser.get(browser.params.glob.host + 'discover/search');
await utils.common.waitLoader();
});
it('screenshot', async () => {
await utils.common.takeScreenshot("discover", "discover-search");
});
describe('top bar', async () => {
after(async () => {
browser.get(browser.params.glob.host + 'discover/search');
await utils.common.waitLoader();
});
it('filters', async () => {
let htmlChanges = await utils.common.outerHtmlChanges(discoverHelper.searchProjectsList());
discoverHelper.searchFilter(3);
await htmlChanges();
let url = await browser.getCurrentUrl();
let projects = discoverHelper.searchProjects();
expect(await projects.count()).to.be.above(0);
expect(url).to.be.equal(browser.params.glob.host + 'discover/search?filter=people');
});
it('search by text', async () => {
discoverHelper.searchInput().sendKeys('Project Example 0');
discoverHelper.sendSearch();
let projects = discoverHelper.searchProjects();
expect(await projects.count()).to.be.equal(1);
});
});
describe('most liked', async () => {
after(async () => {
browser.get(browser.params.glob.host + 'discover/search');
await utils.common.waitLoader();
});
it('default', async () => {
discoverHelper.mostLiked();
utils.common.takeScreenshot("discover", "discover-search-filter");
let url = await browser.getCurrentUrl();
expect(url).to.be.equal(browser.params.glob.host + 'discover/search?order_by=-total_fans_last_week');
});
it('filter', async () => {
discoverHelper.searchOrder(3);
let projects = discoverHelper.searchProjects();
let url = await browser.getCurrentUrl();
expect(await projects.count()).to.be.above(0);
expect(url).to.be.equal(browser.params.glob.host + 'discover/search?order_by=-total_fans');
});
it('clear', async () => {
discoverHelper.clearOrder();
let orderSelector = discoverHelper.orderSelectorWrapper();
expect(await orderSelector.isPresent()).to.be.equal(false);
});
});
describe('most active', async () => {
after(async () => {
browser.get(browser.params.glob.host + 'discover/search');
await utils.common.waitLoader();
});
it('default', async () => {
discoverHelper.mostActived();
utils.common.takeScreenshot("discover", "discover-search-filter");
let url = await browser.getCurrentUrl();
expect(url).to.be.equal(browser.params.glob.host + 'discover/search?order_by=-total_activity_last_week');
});
it('filter', async () => {
discoverHelper.searchOrder(3);
let projects = discoverHelper.searchProjects();
let url = await browser.getCurrentUrl();
expect(await projects.count()).to.be.above(0);
expect(url).to.be.equal(browser.params.glob.host + 'discover/search?order_by=-total_activity');
});
it('clear', async () => {
discoverHelper.clearOrder();
let orderSelector = discoverHelper.orderSelectorWrapper();
expect(await orderSelector.isPresent()).to.be.equal(false);
});
});
});
| Rademade/taiga-front | e2e/suites/discover/discover-search.e2e.js | JavaScript | agpl-3.0 | 3,834 |
'use strict';
app.
factory("DashboardResource",function($resource,urlApi){
return $resource(urlApi+'dashboard',{},{
dashboard: {
method: 'GET'
}
});
}); | appsindicato/APP-Sindicado-Eleicoes | webapp/app/scripts/resources/dashboard.js | JavaScript | agpl-3.0 | 168 |
/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'undo', 'nl', {
redo: 'Opnieuw uitvoeren',
undo: 'Ongedaan maken'
} );
| astrobin/astrobin | astrobin/static/astrobin/ckeditor/plugins/undo/lang/nl.js | JavaScript | agpl-3.0 | 265 |
const setup = require('../../setup')
const SessionController = require('../../../api/controllers/SessionController')
var factories = require('../../setup/factories')
var passport = require('passport')
describe('SessionController.findUser', () => {
var u1, u2
var findUser = SessionController.findUser
before(() => {
u1 = factories.user()
u2 = factories.user()
return Promise.all([u1.save(), u2.save()])
})
describe('with no directly linked user', () => {
it('picks a user with matching email address', () => {
return findUser('facebook', u2.get('email'), 'foo')
.then(user => {
expect(user.id).to.equal(u2.id)
})
})
})
describe('with a directly linked user', () => {
before(() => {
return LinkedAccount.create(u1.id, {type: 'facebook', profile: {id: 'foo'}})
})
after(() => {
return LinkedAccount.query().where('user_id', u1.id).del()
})
it('returns that user, not one with a matching email address', () => {
return findUser('facebook', u2.get('email'), 'foo')
.then(user => {
expect(user.id).to.equal(u1.id)
})
})
})
})
describe('SessionController.upsertLinkedAccount', () => {
var user, req, profile
const upsertLinkedAccount = SessionController.upsertLinkedAccount
const facebookUrl = 'http://facebook.com/foo'
before(() => {
profile = {
id: 'foo',
_json: {
link: facebookUrl
}
}
user = factories.user()
return user.save()
.then(() => {
req = {session: {userId: user.id}}
})
})
describe('with a directly linked user ', () => {
before(() => {
return LinkedAccount.create(user.id, {type: 'facebook', profile: {id: profile.id}})
})
after(() => {
return LinkedAccount.query().where('user_id', user.id).del()
})
it('updates the user facebook_url', () => {
return upsertLinkedAccount(req, 'facebook', profile)
.then(() => user.refresh())
.then(() => {
expect(user.get('facebook_url')).to.equal(facebookUrl)
})
})
})
})
describe('SessionController', function () {
var req, res, cat
before(() => {
req = factories.mock.request()
res = factories.mock.response()
})
describe('.create', function () {
before(() => {
_.extend(req, {
params: {
email: '[email protected]',
password: 'password'
}
})
cat = new User({name: 'Cat', email: '[email protected]', active: true})
return cat.save().then(() =>
new LinkedAccount({
provider_user_id: '$2a$10$UPh85nJvMSrm6gMPqYIS.OPhLjAMbZiFnlpjq1xrtoSBTyV6fMdJS',
provider_key: 'password',
user_id: cat.id
}).save())
})
it('works with a valid username and password', function () {
return SessionController.create(req, res)
.then(() => User.find(cat.id))
.then(user => {
expect(res.status).not.to.have.been.called()
expect(res.ok).to.have.been.called()
expect(req.session.userId).to.equal(cat.id)
expect(user.get('last_login_at').getTime()).to.be.closeTo(new Date().getTime(), 2000)
})
})
})
describe('.createWithToken', () => {
var user, token
before(() => {
UserSession.login = spy(UserSession.login)
user = factories.user()
return user.save({created_at: new Date()})
.then(() => user.generateToken())
.then(t => token = t)
})
it('logs a user in and redirects (Web/GET request)', () => {
_.extend(req.params, {u: user.id, t: token})
req.method = 'GET'
return SessionController.createWithToken(req, res)
.then(() => {
expect(UserSession.login).to.have.been.called()
expect(res.redirect).to.have.been.called()
expect(res.redirected).to.equal(Frontend.Route.evo.passwordSetting())
})
})
it("logs a user in doesn't redirect (API/POST request)", () => {
_.extend(req.params, {u: user.id, t: token})
req.method = 'POST'
res = factories.mock.response()
return SessionController.createWithToken(req, res)
.then(() => {
expect(UserSession.login).to.have.been.called()
expect(res.redirect).not.to.have.been.called()
expect(res.ok).to.have.been.called()
})
})
it('rejects an invalid token', () => {
var error
_.extend(req.params, {u: user.id, t: token + 'x'})
res.send = spy(function (msg) { error = msg })
return SessionController.createWithToken(req, res)
.then(() => {
expect(res.send).to.have.been.called()
expect(error).to.equal('Link expired')
})
})
})
describe('.createWithJWT', () => {
var user, token
before(async () => {
user = factories.user()
await user.save({created_at: new Date()})
.then(() => user.generateJWT())
.then(t => token = t)
req.url = `https://hylo.com?u=${user.id}&token=${token}`
})
it('for valid JWT and GET it will redirect', () => {
_.extend(req.params, {u: user.id, token})
req.method = 'GET'
req.session.authenticated = true
return SessionController.createWithJWT(req, res)
.then(() => {
expect(res.redirect).to.have.been.called()
expect(res.redirected).to.equal(Frontend.Route.evo.passwordSetting())
})
})
it("for valid JWT and POST returns success", () => {
_.extend(req.params, {u: user.id, token})
req.method = 'POST'
req.session.authenticated = true
return SessionController.createWithJWT(req, res)
.then(() => {
expect(res.ok).to.have.been.called()
})
})
it('for invalid token and GET it will still redirect', () => {
req.method = 'GET'
req.session.authenticated = false
return SessionController.createWithJWT(req, res)
.then(() => {
expect(res.redirect).to.have.been.called()
expect(res.redirected).to.equal(Frontend.Route.evo.passwordSetting())
})
})
it('for invalid token and POST it returns error', () => {
let error
res.send = spy(function (msg) { error = msg })
req.method = 'POST'
req.session.authenticated = false
return SessionController.createWithJWT(req, res)
.then(() => {
expect(res.send).to.have.been.called()
expect(error).to.equal('Invalid link, please try again')
})
})
})
describe('.finishFacebookOAuth', () => {
var req, res, origPassportAuthenticate
var mockProfile = {
displayName: 'Lawrence Wang',
email: '[email protected]',
emails: [ { value: '[email protected]' } ],
gender: 'male',
id: '100101',
name: 'Lawrence Wang',
profileUrl: 'http://www.facebook.com/100101',
provider: 'facebook'
}
const expectMatchMockProfile = userId => {
return User.find(userId, {withRelated: 'linkedAccounts'})
.then(user => {
var account = user.relations.linkedAccounts.first()
expect(account).to.exist
expect(account.get('provider_key')).to.equal('facebook')
expect(user.get('facebook_url')).to.equal(mockProfile.profileUrl)
expect(user.get('avatar_url')).to.equal('https://graph.facebook.com/100101/picture?type=large&access_token=186895474801147|zzzzzz')
return user
})
}
before(() => {
origPassportAuthenticate = passport.authenticate
})
beforeEach(() => {
req = factories.mock.request()
res = factories.mock.response()
UserSession.login = spy(UserSession.login)
User.create = spy(User.create)
passport.authenticate = spy(function (strategy, callback) {
return () => callback(null, mockProfile)
})
return setup.clearDb()
})
afterEach(() => {
passport.authenticate = origPassportAuthenticate
})
it('creates a new user', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => {
expect(UserSession.login).to.have.been.called()
expect(User.create).to.have.been.called()
expect(res.view).to.have.been.called()
expect(res.viewTemplate).to.equal('popupDone')
expect(res.viewAttrs.error).not.to.exist
return User.find('[email protected]', {withRelated: 'linkedAccounts'})
})
.then(user => {
expect(user).to.exist
expect(user.get('facebook_url')).to.equal('http://www.facebook.com/100101')
var account = user.relations.linkedAccounts.find(a => a.get('provider_key') === 'facebook')
expect(account).to.exist
})
})
describe('with no email in the auth response', () => {
beforeEach(() => {
var profile = _.merge(_.cloneDeep(mockProfile), {email: null, emails: null})
passport.authenticate = spy((strategy, callback) => () => callback(null, profile))
})
afterEach(() => {
passport.authenticate = origPassportAuthenticate
})
it('sets an error in the view parameters', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => {
expect(UserSession.login).not.to.have.been.called()
expect(res.view).to.have.been.called()
expect(res.viewTemplate).to.equal('popupDone')
expect(res.viewAttrs.error).to.equal('no email')
})
})
})
describe('with no user in the auth response', () => {
beforeEach(() => {
passport.authenticate = spy(function (strategy, callback) {
return () => callback(null, null)
})
})
afterEach(() => {
passport.authenticate = origPassportAuthenticate
})
it('sets an error in the view parameters', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => {
expect(res.view).to.have.been.called()
expect(res.viewAttrs.error).to.equal('no user')
})
})
})
describe('for an existing user', () => {
var user
beforeEach(() => {
user = factories.user()
mockProfile.email = user.get('email')
return user.save()
})
it.skip('creates a new linked account', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => expectMatchMockProfile(user.id))
})
describe('with an existing Facebook account', () => {
beforeEach(() => LinkedAccount.create(user.id, {type: 'facebook', profile: {id: 'foo'}}))
it('leaves the existing account unchanged', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => user.load('linkedAccounts'))
.then(user => {
expect(user.relations.linkedAccounts.length).to.equal(2)
var account = user.relations.linkedAccounts.first()
expect(account.get('provider_user_id')).to.equal('foo')
})
})
})
})
describe('for a logged-in user', () => {
var user
beforeEach(() => {
user = factories.user()
return user.save().then(() => req.login(user.id))
})
it('creates a new linked account even if the email does not match', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => expectMatchMockProfile(user.id))
})
describe('with a linked account that belongs to a different user', () => {
var account
beforeEach(() => {
return factories.user().save()
.then(u2 => LinkedAccount.create(u2.id, {type: 'facebook', profile: {id: mockProfile.id}}))
.then(a => { account = a; return a})
})
it('changes ownership', () => {
return SessionController.finishFacebookOAuth(req, res)
.then(() => expectMatchMockProfile(user.id))
.then(user => expect(user.relations.linkedAccounts.first().id).to.equal(account.id))
})
})
})
})
})
| Hylozoic/hylo-node | test/unit/controllers/SessionController.test.js | JavaScript | agpl-3.0 | 11,949 |
Ext.ns('CMDBuild');
CMDBuild.FormPlugin = function(config) {
Ext.apply(this, config);
};
Ext.extend(CMDBuild.FormPlugin, Ext.util.Observable, {
init: function(formPanel) {
var basicForm = formPanel.getForm();
/**
*
* clears the form,
* to use when trackResetOnLoad = true; in these case the reset() function
* set the form with the last loaded values. If you want to clear completely
* the form call clearForm()
*
*/
formPanel.clearForm = function() {
var blankValues = {};
basicForm.items.each(function(f){
blankValues[f.getName()]="";
});
basicForm.setValues(blankValues);
};
/**
*
* Keeps in sync two fields, usually name and description. If the
* master field changes and the slave is empty, or it has the same
* value as the old value of the master, its value is updated with
* the new one.
*
* These function has to be used with the change listener,
* example:
*
* name.on('change', function(field, newValue, oldValue) {
* formPanel.autoComplete(fieldToComplete, newValue, oldValue)
* })
*
*/
formPanel.autoComplete = function(fieldToComplete, newValue, oldValue) {
var actualValue = fieldToComplete.getValue();
if ( actualValue == "" || actualValue == oldValue )
fieldToComplete.setValue(newValue);
};
}
}); | jzinedine/CMDBuild | cmdbuild/src/main/webapp/javascripts/cmdbuild/form/FormPlugin.js | JavaScript | agpl-3.0 | 1,392 |
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":53,"id":68288,"methods":[{"el":39,"sc":2,"sl":34},{"el":44,"sc":2,"sl":41},{"el":48,"sc":2,"sl":46},{"el":52,"sc":2,"sl":50}],"name":"DoubleArrayPointer","sl":29}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
| cm-is-dog/rapidminer-studio-core | report/html/de/bwaldvogel/liblinear/DoubleArrayPointer.js | JavaScript | agpl-3.0 | 726 |
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":50,"id":42785,"methods":[{"el":42,"sc":2,"sl":35},{"el":49,"sc":2,"sl":44}],"name":"ListeningJSlider","sl":30}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
| cm-is-dog/rapidminer-studio-core | report/html/com/rapidminer/gui/plotter/settings/ListeningJSlider.js | JavaScript | agpl-3.0 | 662 |
/*
* 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/>.
*/
'use strict';
angular.module('huborcidApp')
.factory('EnvVariable', function ($resource, DateUtils) {
return $resource('api/envVariables/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
},
'update': { method:'PUT' }
});
});
| Cineca/OrcidHub | src/main/webapp/scripts/components/entities/envVariable/envVariable.service.js | JavaScript | agpl-3.0 | 1,196 |
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
class ThermalVoid extends Analyzer {
static dependencies = {
combatants: Combatants,
};
casts = 0;
buffApplied = 0;
extraUptime = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.THERMAL_VOID_TALENT.id);
}
on_toPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.ICY_VEINS.id) {
this.casts += 1;
this.buffApplied = event.timestamp;
}
}
on_finished() {
if (this.combatants.selected.hasBuff(SPELLS.ICY_VEINS.id)) {
this.casts -= 1;
this.extraUptime = this.owner.currentTimestamp - this.buffApplied;
}
}
get uptime() {
return this.combatants.selected.getBuffUptime(SPELLS.ICY_VEINS.id) - this.extraUptime;
}
get averageDuration() {
return this.uptime / this.casts;
}
get suggestionThresholds() {
return {
actual: this.averageDuration / 1000,
isLessThan: {
minor: 40,
average: 37,
major: 33,
},
style: 'number',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Your <SpellLink id={SPELLS.THERMAL_VOID_TALENT.id} /> duration boost can be improved. Make sure you use <SpellLink id={SPELLS.FROZEN_ORB.id} /> during <SpellLink id={SPELLS.ICY_VEINS.id} /> in order to get extra <SpellLink id={SPELLS.FINGERS_OF_FROST.id} /> Procs</span>)
.icon(SPELLS.ICY_VEINS.icon)
.actual(`${formatNumber(actual)} seconds Average Icy Veins Duration`)
.recommended(`${formatNumber(recommended)} is recommended`);
});
}
statistic() {
const averageDurationSeconds = this.averageDuration / 1000;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.ICY_VEINS.id} />}
value={`${formatNumber(averageDurationSeconds)}s`}
label="Avg Icy Veins Duration"
tooltip="Icy Veins Casts that do not complete before the fight ends are removed from this statistic"
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(0);
}
export default ThermalVoid;
| enragednuke/WoWAnalyzer | src/Parser/Mage/Frost/Modules/Features/ThermalVoid.js | JavaScript | agpl-3.0 | 2,491 |
//-*- coding: utf-8 -*-
//############################################################################
//
// OpenERP, Open Source Management Solution
// This module copyright (C) 2015 Therp BV <http://therp.nl>.
//
// 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/>.
//
//############################################################################
openerp.attachment_edit = function(instance)
{
instance.web.Sidebar.include(
{
on_attachments_loaded: function(attachments)
{
var self = this;
return jQuery.when(this._super.apply(this, arguments))
.then(function()
{
self.$el.find('.oe-sidebar-attachment-edit')
.click(self.on_attachment_edit);
});
},
on_attachment_edit: function(e)
{
var $target = jQuery(e.currentTarget),
attachment_id = parseInt($target.attr('data-id')),
title = $target.attr('title');
e.preventDefault();
e.stopPropagation();
this.do_action({
type: 'ir_actions.act_window',
name: title,
views: [[false, 'form']],
res_model: 'ir.attachment',
res_id: attachment_id,
flags: {
initial_mode: 'edit',
},
});
},
})
}
| acsone/knowledge | attachment_edit/static/src/js/attachment_edit.js | JavaScript | agpl-3.0 | 2,047 |
import React from 'react';
import { shallow } from 'enzyme';
import SideBar from 'components/projects/SideBar';
describe('<SideBar />', () => {
const render = props => {
const defaultProps = {
reverse: false,
visibleColumns: {
chillyBin: true,
backlog: true,
done: true,
},
toggleColumn: sinon.stub(),
reverseColumns: sinon.stub()
};
return shallow(<SideBar {...defaultProps} {...props } />);
};
it('renders the component', () => {
const wrapper = render();
expect(wrapper).toExist();
});
});
| Codeminer42/cm42-central | spec/javascripts/components/projects/side_bar/side_bar_spec.js | JavaScript | agpl-3.0 | 579 |
class Challenge {
constructor(model = {}) {
this.skills = model.skills || [];
}
addSkill(skill) {
this.skills.push(skill);
}
hasSkill(searchedSkill) {
return this.skills.filter((skill) => skill.name === searchedSkill.name).length > 0;
}
isPublished() {
return ['validé', 'validé sans test', 'pré-validé'].includes(this.status);
}
}
module.exports = Challenge;
| sgmap/pix | api/lib/domain/models/Challenge.js | JavaScript | agpl-3.0 | 402 |
/**
* 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: 'bcd7a4769ebde941674f6b76ed8222ff',
/***************************************************************************
* *
* 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
// }
/***************************************************************************
* *
* In production, uncomment the following lines to set up a shared redis *
* session store that can be shared across multiple Sails.js servers *
***************************************************************************/
// 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 use your Mongo adapter as a session *
* store *
* *
***************************************************************************/
// adapter: 'mongo',
// host: 'localhost',
// port: 27017,
// db: 'sails',
// collection: 'sessions',
/***************************************************************************
* *
* Optional Values: *
* *
* # Note: url will override other connection settings url: *
* 'mongodb://user:pass@host:port/database/collection', *
* *
***************************************************************************/
// username: '',
// password: '',
// auto_reconnect: false,
// ssl: false,
// stringify: true
};
| asm-products/hereapp | config/session.js | JavaScript | agpl-3.0 | 4,320 |
const mongoose = require('mongoose');
const config = require('../../config/config');
const _ = require('underscore');
const urlLib = require('url');
function getSellerFromURL(url) {
if (!url) {
return null;
}
const sellers = _.keys(config.sellers);
return _.find(sellers, function(seller) {
if (url.indexOf(config.sellers[seller].url) >=0 ) {
return seller;
}
});
}
function getVideoSiteFromURL(url) {
const videoSites = _.keys(config.videoSites);
const youtubeDLSites = config.youtubeDLSites;
const locallyProcessedSite = _.find(videoSites, function(site) {
return (url.indexOf(config.videoSites[site].url) >=0);
});
if (locallyProcessedSite) {
return locallyProcessedSite;
}
const purlObject = urlLib.parse(url);
const host = purlObject.host;
return _.find(youtubeDLSites, function(youtubeDLSite) {
return host.indexOf(youtubeDLSite) >= 0;
});
}
function getDeepLinkURL(seller, url) {
if (seller === 'amazon') {
// extract ASIN from the url
// http://stackoverflow.com/questions/1764605/scrape-asin-from-amazon-url-using-javascript
const asin = url.match('/([a-zA-Z0-9]{10})(?:[/?]|$)');
if (asin && asin[1]) {
return ('http://www.amazon.in/dp/'+ asin[1]);
}
return url;
} else if (seller === 'flipkart') {
// http://nodejs.org/api/url.html
// signature: url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
const parsedURL = urlLib.parse(url, true);
const pidQueryString = (parsedURL.query.pid && (parsedURL.query.pid !== undefined)) ? ('?pid=' + parsedURL.query.pid) : '';
const affiliateHost = parsedURL.host;
if (parsedURL.pathname.indexOf('/dl') !== 0) {
parsedURL.pathname = '/dl' + parsedURL.pathname;
}
affiliateHost = affiliateHost.replace('www.flipkart.com', 'dl.flipkart.com');
const normalizedURL = parsedURL.protocol + '//' + affiliateHost + parsedURL.pathname + pidQueryString;
return normalizedURL;
} else if (seller === 'snapdeal') {
//snapdeal has a few junk chars in `hash`
//"#bcrumbSearch:AF-S%20Nikkor%2050mm%20f/1.8G"
//so lets ignore the hash altogether and return url until pathname
const pUrl = urlLib.parse(url, true);
return (pUrl.protocol + '//' + pUrl.host + pUrl.pathname);
}
return url;
}
function getURLWithAffiliateId(url) {
const urlSymbol = url.indexOf('?') > 0 ? '&': '?';
const seller = getSellerFromURL(url);
const sellerKey = config.sellers[seller].key,
sellerValue = config.sellers[seller].value,
sellerExtraParams = config.sellers[seller].extraParams;
if (sellerKey && sellerValue) {
const stringToMatch = sellerKey + '=' + sellerValue;
let urlWithAffiliate;
if (url.indexOf(stringToMatch) > 0) {
urlWithAffiliate = url;
} else {
urlWithAffiliate = url + urlSymbol + stringToMatch;
}
//for snapdeal, they have a offer id param as well
//in the config file, I've put it as a query string
//so simply appending it here would work
if (sellerExtraParams) {
return urlWithAffiliate + sellerExtraParams;
} else {
return urlWithAffiliate;
}
}
return url;
}
function increaseCounter(counterName) {
const counterModel = mongoose.model('Counter');
counterModel.findOne().lean().exec(function(err, doc) {
if (!doc) {
return;
}
const updateQuery = {_id: doc._id};
const updateObject = {};
const updateOptions = {};
updateObject[counterName] = doc[counterName] + 1;
counterModel.update(updateQuery, updateObject, updateOptions, function() {});
});
}
module.exports = {
getSellerFromURL: getSellerFromURL,
getDeepLinkURL: getDeepLinkURL,
getVideoSiteFromURL: getVideoSiteFromURL,
increaseCounter: increaseCounter,
getURLWithAffiliateId: getURLWithAffiliateId,
getSellerJobModelInstance: function(seller) {
const jobSellerModelName = seller + '_job';
return mongoose.model(jobSellerModelName);
},
getSellerProductPriceHistoryModelInstance: function (seller) {
return mongoose.model(seller + '_product_price_history');
},
getProcessingMode: function(url) {
//2 modes. 'seller' or 'site'
if (getVideoSiteFromURL(url)) {
return 'site';
}
return 'seller';
},
isLegitSeller: function(seller) {
if (!seller) {
return false;
}
const sellers = _.keys(config.sellers);
return !!_.find(sellers, function(legitSeller) {
return seller.trim().toLowerCase() === legitSeller;
});
}
};
| Cheapass/cheapass | src/utils/seller.js | JavaScript | agpl-3.0 | 4,500 |
/**
* Created by helge on 24.08.16.
*/
import React from 'react';
import PropTypes from 'prop-types';
import FlagAmountBet from './FlagAmountBet';
import FlagAmountCall from './FlagAmountCall';
import FlagButton from './FlagButton';
import ControlBetRaise from './ControlBetRaise';
import ControlCheckCall from './ControlCheckCall';
import ControlFold from './ControlFold';
import Slider from '../Slider';
import {
ActionBarWrapper,
ControlPanel,
ControlWrapper,
FlagContainer,
} from './styles';
const ActionBar = (props) => {
const {
active,
disabled,
sliderOpen,
visible,
} = props;
if (visible) {
return (
<ActionBarWrapper
active={active}
disabled={disabled}
name="action-bar-wrapper"
>
<FlagAmountCall {...props} />
<FlagAmountBet {...props} />
<FlagContainer active={active} name="flag-container">
<FlagButton type={0.25} {...props} />
<FlagButton type={0.50} {...props} />
<FlagButton type={1.00} {...props} />
</FlagContainer>
<ControlPanel name="control-panel-visible">
<ControlWrapper sliderOpen={sliderOpen} >
<ControlFold {...props} />
<ControlCheckCall {...props} />
<ControlBetRaise {...props} />
{sliderOpen &&
<Slider {...props} />
}
</ControlWrapper>
</ControlPanel>
</ActionBarWrapper>
);
}
return null;
};
ActionBar.propTypes = {
visible: PropTypes.bool,
active: PropTypes.bool,
disabled: PropTypes.bool,
sliderOpen: PropTypes.bool,
};
export default ActionBar;
| VonIobro/ab-web | app/components/ActionBar/index.js | JavaScript | agpl-3.0 | 1,656 |
import _, { messages } from 'intl'
import ActionButton from 'action-button'
import decorate from 'apply-decorators'
import Icon from 'icon'
import React from 'react'
import { addSubscriptions, resolveId } from 'utils'
import { alert, confirm } from 'modal'
import { createRemote, editRemote, subscribeRemotes } from 'xo'
import { error } from 'notification'
import { format } from 'xo-remote-parser'
import { generateId, linkState } from 'reaclette-utils'
import { injectState, provideState } from 'reaclette'
import { map, some, trimStart } from 'lodash'
import { Password, Number } from 'form'
import { SelectProxy } from 'select-objects'
const remoteTypes = {
file: 'remoteTypeLocal',
nfs: 'remoteTypeNfs',
smb: 'remoteTypeSmb',
s3: 'remoteTypeS3',
}
export default decorate([
addSubscriptions({
remotes: subscribeRemotes,
}),
provideState({
initialState: () => ({
domain: undefined,
host: undefined,
name: undefined,
options: undefined,
password: undefined,
path: undefined,
port: undefined,
proxyId: undefined,
type: undefined,
username: undefined,
directory: undefined,
bucket: undefined,
}),
effects: {
linkState,
setPort: (_, port) => state => ({
port: port === undefined && state.remote !== undefined ? '' : port,
}),
setProxy(_, proxy) {
this.state.proxyId = resolveId(proxy)
},
editRemote: ({ reset }) => state => {
const {
remote,
domain = remote.domain || '',
host = remote.host,
name,
options = remote.options || '',
password = remote.password,
port = remote.port,
proxyId = remote.proxy,
type = remote.type,
username = remote.username,
} = state
let { path = remote.path } = state
if (type === 's3') {
const { parsedPath, bucket = parsedPath.split('/')[0], directory = parsedPath.split('/')[1] } = state
path = bucket + '/' + directory
}
return editRemote(remote, {
name,
url: format({
domain,
host,
password,
path,
port: port || undefined,
type,
username,
}),
options: options !== '' ? options : null,
proxy: proxyId,
}).then(reset)
},
createRemote: ({ reset }) => async (state, { remotes }) => {
if (some(remotes, { name: state.name })) {
return alert(
<span>
<Icon icon='error' /> {_('remoteTestName')}
</span>,
<p>{_('remoteTestNameFailure')}</p>
)
}
const {
domain = 'WORKGROUP',
host,
name,
options,
password,
path,
port,
proxyId,
type = 'nfs',
username,
} = state
const urlParams = {
host,
path,
port,
type,
}
if (type === 's3') {
const { bucket, directory } = state
urlParams.path = bucket + '/' + directory
}
username && (urlParams.username = username)
password && (urlParams.password = password)
domain && (urlParams.domain = domain)
if (type === 'file') {
await confirm({
title: _('localRemoteWarningTitle'),
body: _('localRemoteWarningMessage'),
})
}
const url = format(urlParams)
return createRemote(name, url, options !== '' ? options : undefined, proxyId === null ? undefined : proxyId)
.then(reset)
.catch(err => error('Create Remote', err.message || String(err)))
},
setSecretKey(_, { target: { value } }) {
this.state.password = value
},
},
computed: {
formId: generateId,
inputTypeId: generateId,
parsedPath: ({ remote }) => remote && trimStart(remote.path, '/'),
},
}),
injectState,
({ state, effects, formatMessage }) => {
const {
remote = {},
domain = remote.domain || 'WORKGROUP',
host = remote.host || '',
name = remote.name || '',
options = remote.options || '',
password = remote.password || '',
parsedPath,
path = parsedPath || '',
parsedBucket = parsedPath != null && parsedPath.split('/')[0],
bucket = parsedBucket || '',
parsedDirectory = parsedPath != null && parsedPath.split('/')[1],
directory = parsedDirectory || '',
port = remote.port,
proxyId = remote.proxy,
type = remote.type || 'nfs',
username = remote.username || '',
} = state
return (
<div>
<h2>{_('newRemote')}</h2>
<form id={state.formId}>
<div className='form-group'>
<label htmlFor={state.inputTypeId}>{_('remoteType')}</label>
<select
className='form-control'
id={state.inputTypeId}
name='type'
onChange={effects.linkState}
required
value={type}
>
{map(remoteTypes, (label, key) => _({ key }, label, message => <option value={key}>{message}</option>))}
</select>
{type === 'smb' && <em className='text-warning'>{_('remoteSmbWarningMessage')}</em>}
{type === 's3' && <em className='text-warning'>Backup to Amazon S3 is a BETA feature</em>}
</div>
<div className='form-group'>
<input
className='form-control'
name='name'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteMyNamePlaceHolder)}
required
type='text'
value={name}
/>
</div>
<div className='form-group'>
<SelectProxy onChange={effects.setProxy} value={proxyId} />
</div>
{type === 'file' && (
<fieldset className='form-group'>
<div className='input-group'>
<span className='input-group-addon'>/</span>
<input
className='form-control'
name='path'
onChange={effects.linkState}
pattern='^(([^/]+)+(/[^/]+)*)?$'
placeholder={formatMessage(messages.remoteLocalPlaceHolderPath)}
required
type='text'
value={path}
/>
</div>
</fieldset>
)}
{type === 'nfs' && (
<fieldset>
<div className='form-group'>
<input
className='form-control'
name='host'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteNfsPlaceHolderHost)}
required
type='text'
value={host}
/>
<br />
<Number
onChange={effects.setPort}
placeholder={formatMessage(messages.remoteNfsPlaceHolderPort)}
value={port}
/>
</div>
<div className='input-group form-group'>
<span className='input-group-addon'>/</span>
<input
className='form-control'
name='path'
onChange={effects.linkState}
pattern='^(([^/]+)+(/[^/]+)*)?$'
placeholder={formatMessage(messages.remoteNfsPlaceHolderPath)}
required
type='text'
value={path}
/>
</div>
<div className='input-group form-group'>
<span className='input-group-addon'>-o</span>
<input
className='form-control'
name='options'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteNfsPlaceHolderOptions)}
type='text'
value={options}
/>
</div>
</fieldset>
)}
{type === 'smb' && (
<fieldset>
<div className='input-group form-group'>
<span className='input-group-addon'>\\</span>
<input
className='form-control'
name='host'
onChange={effects.linkState}
pattern='^[^\\/]+\\[^\\/]+$'
placeholder={formatMessage(messages.remoteSmbPlaceHolderAddressShare)}
required
type='text'
value={host}
/>
<span className='input-group-addon'>\</span>
<input
className='form-control'
name='path'
onChange={effects.linkState}
pattern='^([^\\/]+(\\[^\\/]+)*)?$'
placeholder={formatMessage(messages.remoteSmbPlaceHolderRemotePath)}
type='text'
value={path}
/>
</div>
<div className='form-group'>
<input
className='form-control'
name='username'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteSmbPlaceHolderUsername)}
required
type='text'
value={username}
/>
</div>
<div className='form-group'>
<Password
name='password'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteSmbPlaceHolderPassword)}
required
value={password}
/>
</div>
<div className='form-group'>
<input
className='form-control'
onChange={effects.linkState}
name='domain'
placeholder={formatMessage(messages.remoteSmbPlaceHolderDomain)}
required
type='text'
value={domain}
/>
</div>
<div className='input-group form-group'>
<span className='input-group-addon'>-o</span>
<input
className='form-control'
name='options'
onChange={effects.linkState}
placeholder={formatMessage(messages.remoteSmbPlaceHolderOptions)}
type='text'
value={options}
/>
</div>
</fieldset>
)}
{type === 's3' && (
<fieldset className='form-group form-group'>
<div className='input-group '>
<input
className='form-control'
name='host'
onChange={effects.linkState}
// pattern='^[^\\/]+\\[^\\/]+$'
placeholder='AWS S3 endpoint (ex: s3.us-east-2.amazonaws.com)'
required
type='text'
value={host}
/>
</div>
<div className='input-group '>
<input
className='form-control'
name='bucket'
onChange={effects.linkState}
// https://stackoverflow.com/a/58248645/72637
pattern='(?!^(\d{1,3}\.){3}\d{1,3}$)(^[a-z0-9]([a-z0-9-]*(\.[a-z0-9])?)*$)'
placeholder={formatMessage(messages.remoteS3PlaceHolderBucket)}
required
type='text'
value={bucket}
/>
</div>
<div className='input-group form-group'>
<input
className='form-control'
name='directory'
onChange={effects.linkState}
pattern='^(([^/]+)+(/[^/]+)*)?$'
placeholder={formatMessage(messages.remoteS3PlaceHolderDirectory)}
required
type='text'
value={directory}
/>
</div>
<div className='input-group'>
<input
className='form-control'
name='username'
onChange={effects.linkState}
placeholder='Access key ID'
required
type='text'
value={username}
/>
</div>
<div className='input-group'>
<input
className='form-control'
name='password'
onChange={effects.setSecretKey}
placeholder='Paste secret here to change it'
autoComplete='off'
required
type='text'
/>
</div>
</fieldset>
)}
<div className='form-group'>
<ActionButton
btnStyle='primary'
form={state.formId}
handler={state.remote === undefined ? effects.createRemote : effects.editRemote}
icon='save'
type='submit'
>
{_('savePluginConfiguration')}
</ActionButton>
<ActionButton className='pull-right' handler={effects.reset} icon='reset' type='reset'>
{_('formReset')}
</ActionButton>
</div>
</form>
</div>
)
},
])
| vatesfr/xo-web | packages/xo-web/src/xo-app/settings/remotes/remote.js | JavaScript | agpl-3.0 | 13,904 |
// note file for simple notes, to do it from 'message-file-2.js'
//
// The old file name got as: notes-file.js, but the 's' of 'notes' looks wierd,
// dropping it.
//
// it's an plain text file. But it render as easy and fast to writ and read.
//
// make_note_file(meta, callback)
// - make a note file, save it to s3, callback(err, file_obj)
// get_note_file(meta, callback)
// - retrieve a old note file, callback(err, file_obj)
//
// 0221, 2015
var u = require('underscore');
var path = require('path');
var util = require('util');
var md = require("./markdown-file.js");
var bucket = require('./bucket.js');
var ft = require('../myutils/filetype.js');
var myutil = require('../myutils/myutil.js');
var folder5 = require("./folder-v5.js");
var simple = require("./simple-file-v3.js");
//var json_file= require("./json-file.js");
function note_file(file_meta, pass_file_obj){
//
// It will be based on plain and simple file, without any other parents,
// to be more reliable.
//
// The content will be utf-8 string, and render out head part of contents
// during listing, by default.
//
// file extension would be: ".ggnotes", or ".ggn".
// filetype would be : "goodagood-notes"
// if need in future it should get markdown syntax work as well.
//
// Meta.note : a string, default utf-8 if needed, it's contents. This
// makes a separate storage not necessary for small piece of text, but
// do it for simple coding at first.
// If there is not 'Meta.storage.key', 'Meta.note' can be used anyway.
//
//
var Meta = file_meta;
//Meta.filetype = 'goodagood-notes';
//var Editor_prefix = "/edit-note";
var Editor_prefix = "/edit-md";
var File_type = "goodagood-note";
var File_extensions = ['.ggn', '.ggnote'];
simple.simple_s3_file_obj(Meta, function(err, fobj){
if(err) return pass_file_obj(err, null);
// Now, we have file object and Meta data. Here it get modified
// for message files:
function get_parent_obj(){
return fobj;
}
function correct_extension(ext){
ext = ext || '.ggn';
if(ext.search(/\$$/) !== (ext.length -1)) ext += '$';
var pat = RegExp(ext);
if(! pat.test(Meta.name)){
Meta.name += File_extensions[0];
Meta.path = path.join(path.dirname(Meta.path), Meta.name);
}
}
function set_filetype(){
Meta.filetype = File_type;
}
// todo: prepare html ele., render as markdown
function set_new_meta(_meta, callback){
Meta = _meta;
build_meta(callback);
}
function build_meta(callback){
set_filetype();
simple.fix_file_meta(Meta);
fobj.calculate_meta_defaults();
//prepare_html_elements(); // parent's render will do it.
prepare_html_elements(function(err, what){
render_html_repr(function(err, md){
callback(null, Meta);
});
});
}
function update_storage(str, callback){
if(str.trim() == '') return callback('empty string in "update storage" for note', null);
Meta.note = str;
fobj.save_file_to_folder().then(function(asw_reply){
callback(null, str);
});
}
// need test, Sat Feb 21 06:39:35 UTC 2015
// For notes, it naturally short in length, for most notes, it will be
// enough to put it in a string. In addition, if codes not change, it
// should be ok to just use the string. 'update storage' is enough.
function save_note_s3(callback){
// write content to a separate s3 obj
var error = 'error in "save content" in "note file": ' + Meta.path;
if(Meta.storage.key){
fobj.write_s3_storage(Meta.note, callback);
}else{
error = 'where to store the content? ' ;
return callback(error, null);
}
callback(err, null);
}
function read_to_string(callback){
// @callback is for same with other file type.
p('in "read to string", Meta.note: ', Meta.note);
if(callback){
return callback(null, Meta.note);
}
return Meta.note;
}
// it pass to callback
function prepare_html_elements(callback){
fobj.prepare_html_elements();
render_note_as_markdown(function(err, markdonw){
callback(null, Meta.html);
});
}
// use markdown file to render the note as markdown.
function render_note_as_markdown(callback){
if(!Meta.note) return callback('no note?', null);
// make a markdown file object from Meta, then use it to render note:
md.markdown_file_obj(Meta, function(err, md_file){
Meta.md_renderred = md_file.render_string(Meta.note);
callback(null, Meta.md_renderred);
});
}
function short_note(){
Meta.short_note = Meta.note.slice(0, 15);
return Meta.short_note;
}
function render_html_repr(callback){
// it past by callback
//
// Results will be saved to Meta.html.li
//
// Using font awesome.
//
fobj.render_html_repr(); //parent's way
var text = Meta.note; //? Meta.note?
if(!text) text = "WoW! note something and nothing.";
// first, from whom:
var li = '<li class="file ggnote">\n';
li += Meta.html.elements["file-selector"] + "\n";
li += '<i class="fa fa-paperclip"></i>\n';
if ( Meta.timestamp ){
li += util.format('<span class="timestamp" data-timestamp="%s"> %s </span>\n',
Meta.timestamp, Meta.timestamp);
}
//if ( Meta.name ) li += '<span class="note-title">' + Meta.name + '</span>\n';
if( Meta.md_renderred ){
li += '<div class="note-content markdown"> <span class="markdown">' + Meta.md_renderred + '</span></div>\n';
}else{
li += '<div class="note-content"><span class="text">' + text + '</span></div>\n';
}
li += '<ul class="file-info-extra"><li>'; // put others into a sub <ul>, 0515
var remove = '<span class="remove"> <i class="fa fa-trash-o"></i>' +
util.format('<a href="%s">', Meta['delete_href']) +
//'<span class="glyphicon glyphicon-trash"> </span>' +
'Delete</a></span>\n';
li += remove;
var editor_link = path.join(Editor_prefix, Meta['path_uuid']);
var editor_element =
'<span class="editor"> <i class="fa fa-edit"></i>' +
util.format('<a href="%s">', editor_link) +
'Edit</a></span>\n';
li += editor_element;
li += '</li></ul>';
li += '</li>\n';
if( !Meta.html ) Meta.html = {};
Meta.html.li = li;
callback(li);
return li;
}
// Object with new functionalities
var new_functions = {
version : 'note file, 0224',
set_filetype : set_filetype,
get_parent_obj : get_parent_obj,
set_new_meta : set_new_meta,
build_meta : build_meta,
save_note_s3 : save_note_s3,
prepare_html_elements : prepare_html_elements,
render_note_as_markdown : render_note_as_markdown,
render_html_repr : render_html_repr,
update_storage : update_storage,
read_to_string : read_to_string,
short_note : short_note,
};
// u.extend(fobj, new_functions); //d, this will change the parent obj.
//
// This make new_functions get default functionalities from the parent
// object, and keep fobj as untouched:
u.defaults(new_functions, fobj);
//if(typeof Meta.html.li === 'undefined') _render_html_repr(); //?
pass_file_obj(null, new_functions); // This is callback
});
}
function json_note(note_json, callback){
// @note_json : object, where 'owner' and 'note' (content) is must.
var name = 'note';
var cwd = note_json.owner;
var npath= path.join(cwd, name);
Meta = u.defaults(note_json, {
name : name,
title: name,
path : npath
});
note_file(Meta, function(err, note){
if (err){ p ('what err?'); return this.err = err; }
note.build_meta(function(err, nmeta){
p ('err, nmeta: ', err, nmeta);
// This gives promise!
note.save_file_to_folder().then(function(what){
callback(null, note);
});
});
});
}
/*
* write a note file, to work with the form post: editor.js post md-note
*
* meta: {
* title :
* text :
* username :
* userid :
* cwd :
* }
*/
function write_note_0514(meta, callback){
var name;
// Try to make a name from meta.title:
if (u.isString(meta.title) && meta.title.length > 0) name = meta.title.slice(0,32);
if (name){
name = name + '.ggnote';
} else {
name = "notes" + Date.now().toString() + '.ggnote';
}
p('the name: ', name);
var jmeta = u.defaults({}, meta);
jmeta.name = name;
jmeta.cwd = meta.cwd;
jmeta.owner= meta.username;
jmeta.id = meta.userid;
jmeta.note = meta.text;
jmeta.path = path.join(jmeta.cwd, jmeta.name);
p('the meta: ', jmeta);
note_file(jmeta, function(err, nobj){
if (err){
p ('what err?', err);
callback(err, null);
}
nobj.build_meta (function(err, meta_){
p ('err, meta_: ', err, meta_);
nobj.save_file_to_folder().then(function(what){
callback(null, nobj);
}).catch(function(err){
callback(err, null);
});
});
});
}
// do some fast checkings //
var p = console.log;
function stop(seconds){
seconds = seconds || 1;
setTimeout(process.exit, seconds*1000);
}
function empty_obj(meta){
var name = 'test-note.ggnote';
meta = meta || {
name : name
, path : 'abc/test/' + name
, owner: 'abc'
, note: 'just test, at ' + (new Date()).toString()
};
note_file(meta, function(err, note){
if (err){ p ('what err?'); return this.err = err; }
note.build_meta(function(err, what){
p ('err, element: ', err, what);
});
stop();
});
}
if (require.main === module){
empty_obj();
}
module.exports.note_file = note_file;
module.exports.json_note = json_note;
module.exports.make_note_file = json_note;
module.exports.get_note_file = note_file;
module.exports.write_note_0514 = write_note_0514;
// vim: set et ts=2 sw=2 fdm=indent:
| goodagood/gg | plain/aws/note-file.js | JavaScript | lgpl-2.1 | 10,202 |
// constant definition
const c = 11;
shouldBe("c", "11");
// attempt to redefine should have no effect
c = 22;
shouldBe("c", "11");
const dummy = 0;
for (var v = 0;;) {
++v;
shouldBe("v", "1");
break;
}
// local vars & consts
function h ()
{
function shouldBe(_a, _b)
{
if (typeof _a != "string" || typeof _b != "string")
debug("WARN: shouldBe() expects string arguments");
var _av, _bv;
try {
_av = eval(_a);
} catch (e) {
_av = evalError(_a, e);
}
try {
_bv = eval(_b);
} catch (e) {
_bv = evalError(_b, e);
}
if (_av === _bv)
testPassed(_a + " is " + _b);
else
testFailed(_a + " should be " + _bv + ". Was " + _av);
}
var hvar = 1;
const hconst = 1;
shouldBe("hvar", "1");
shouldBe("hconst", "1");
hvar = 2;
hconst = 2;
shouldBe("hvar", "2");
shouldBe("hconst", "1");
++hvar;
++hconst;
shouldBe("hvar", "3");
shouldBe("hconst", "1");
shouldBe("(hvar = 4)", "4");
shouldBe("(hconst = 4)", "4");
shouldBe("hvar", "4");
shouldBe("hconst", "1");
}
h();
h();
// ### check for forbidden redeclaration
| KDE/kjs | tests/const.js | JavaScript | lgpl-2.1 | 1,109 |
module.exports = iterator
const normalizePaginatedListResponse = require('./normalize-paginated-list-response')
function iterator (octokit, options) {
const headers = options.headers
let url = octokit.request.endpoint(options).url
return {
[Symbol.asyncIterator]: () => ({
next () {
if (!url) {
return Promise.resolve({ done: true })
}
return octokit.request({ url, headers })
.then((response) => {
normalizePaginatedListResponse(octokit, url, response)
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((response.headers.link || '').match(/<([^>]+)>;\s*rel="next"/) || [])[1]
return { value: response }
})
}
})
}
}
| checkstyle/contribution | comment-action/node_modules/@octokit/rest/plugins/pagination/iterator.js | JavaScript | lgpl-2.1 | 993 |
function extension_runAudits(callback)
{
evaluateOnFrontend("InspectorTest.startExtensionAudits(reply);", callback);
}
// runs in front-end
var initialize_ExtensionsAuditsTest = function()
{
InspectorTest.startExtensionAudits = function(callback)
{
const launcherView = WebInspector.panels.audits._launcherView;
launcherView._selectAllClicked(false);
launcherView._auditPresentStateElement.checked = true;
var extensionCategories = document.evaluate("label[starts-with(.,'Extension ')]/input[@type='checkbox']",
WebInspector.panels.audits._launcherView._categoriesElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < extensionCategories.snapshotLength; ++i)
extensionCategories.snapshotItem(i).click();
function onAuditsDone()
{
InspectorTest.runAfterPendingDispatches(function() {
InspectorTest.collectAuditResults();
callback();
});
}
InspectorTest.addSniffer(WebInspector.panels.audits, "_auditFinishedCallback", onAuditsDone, true);
launcherView._launchButtonClicked();
}
}
| youfoh/webkit-efl | LayoutTests/inspector/extensions/extensions-audits-tests.js | JavaScript | lgpl-2.1 | 1,188 |
const DEPLOYMENT_TYPE_COSTS = {
kubernetes_custom: 95000,
kubernetes_existing: 0,
kubernetes_reference: 45000,
openstack_custom: 150000,
openstack_existing: 0,
openstack_reference: 75000
};
const MANAGED_SERVICE_COSTS = {
maas: 300,
openstack: 4275,
kubernetes: 3250,
openstack_and_kubernetes: 6465
};
const SERVICE_LEVEL_COST_PER_HOST = {
none: 0,
essential: 225,
standard: 750,
advanced: 1500
};
const STORAGE_COSTS = {
standard: {
tier_one: { base: 0, multiplier: 16.67 },
tier_two: { base: 2500, multiplier: 12.5 },
tier_three: { base: 19375, multiplier: 6.67 },
tier_four: { base: 29375, multiplier: 3.33 },
tier_five: { base: 69375, multiplier: 1.67 },
tier_six: { base: 94375, multiplier: 0 }
},
advanced: {
tier_one: { base: 0, multiplier: 33.33 },
tier_two: { base: 5000, multiplier: 25 },
tier_three: { base: 38750, multiplier: 13.33 },
tier_four: { base: 58750, multiplier: 6.67 },
tier_five: { base: 138750, multiplier: 3.33 },
tier_six: { base: 188750, multiplier: 0 }
}
};
function initTCOCalculator() {
updateTotals();
attachInputEvents();
}
function attachInputEvents() {
const rangeContainers = document.querySelectorAll(
".js-tco-calculator__range"
);
const checkboxInputs = document.querySelectorAll(
".js-tco-calculator__checkbox"
);
const radioInputs = document.querySelectorAll(".js-tco-calculator__radio");
rangeContainers.forEach(container => {
let input = container.querySelector("input[type='number']");
let range = container.querySelector("input[type='range']");
input.addEventListener("input", e => {
range.value = e.target.value;
updateTotals();
});
range.addEventListener("input", e => {
input.value = e.target.value;
updateTotals();
});
});
checkboxInputs.forEach(checkbox => {
checkbox.addEventListener("input", () => {
updateTotals();
});
});
radioInputs.forEach(radio => {
radio.addEventListener("input", () => {
updateTotals();
});
});
}
function calculateStorageCost(serviceLevel, dataVolume) {
let tier = "tier_";
let adjustment = 0;
if (dataVolume <= 150) {
tier += "one";
} else if (dataVolume > 150 && dataVolume <= 1500) {
tier += "two";
adjustment = 150;
} else if (dataVolume > 1500 && dataVolume <= 3000) {
tier += "three";
adjustment = 1500;
} else if (dataVolume > 3000 && dataVolume <= 15000) {
tier += "four";
adjustment = 3000;
} else if (dataVolume > 15000 && dataVolume <= 30000) {
tier += "five";
adjustment = 15000;
} else if (dataVolume > 30000) {
tier += "six";
adjustment = 30000;
}
const storageCosts = STORAGE_COSTS[serviceLevel][tier];
const adjustedVolume = dataVolume - adjustment;
const finalCosts =
storageCosts.base + adjustedVolume * storageCosts.multiplier;
return finalCosts;
}
function renderTotals(rollout, yearly, selfYearly) {
const rolloutEl = document.querySelector("#intial-rollout--managed");
const selfRolloutEl = document.querySelector("#intial-rollout--self");
const yearlyEl = document.querySelector("#yearly-cost--managed");
const selfYearlyEl = document.querySelector("#yearly-cost--self");
const formattedRollout = `$${new Intl.NumberFormat("en-US").format(rollout)}`;
const formattedYearly = `$${new Intl.NumberFormat("en-US").format(yearly)}`;
const formattedSelfYearly = `$${new Intl.NumberFormat("en-US").format(
selfYearly
)}`;
rolloutEl.innerHTML = formattedRollout;
selfRolloutEl.innerHTML = formattedRollout;
yearlyEl.innerHTML = formattedYearly;
selfYearlyEl.innerHTML = formattedSelfYearly;
}
function updateTotals() {
const dataVolume = parseInt(
document.querySelector("#data-volume__input").value
);
const deploymentType = document.querySelector(
"[name='deployment-type']:checked"
).value;
const hosts = parseInt(document.querySelector("#hosts__input").value)-3;
const kubernetes = document.querySelector("#ct-k8s");
const kubernetesDeploymentCost =
DEPLOYMENT_TYPE_COSTS[`kubernetes_${deploymentType}`];
const openstack = document.querySelector("#ct-openstack");
const openstackDeploymentCost =
DEPLOYMENT_TYPE_COSTS[`openstack_${deploymentType}`];
const serviceLevel = document.querySelector("[name='self-managed']:checked")
.value;
// an additional 3 hosts are required to host MAAS, Juju, etc
const hostCost = SERVICE_LEVEL_COST_PER_HOST[serviceLevel] * (hosts + 3);
const maasHostCost = MANAGED_SERVICE_COSTS["maas"] * 3;
const managedSupportCost =
SERVICE_LEVEL_COST_PER_HOST["advanced"] * (hosts + 3);
let managedServicesCost = 0;
let rollout = 0;
let selfYearly = 0;
let storageCost = 0;
let yearly = 0;
if (
dataVolume / hosts > 48 &&
serviceLevel !== "none" &&
serviceLevel !== "essential"
) {
storageCost += calculateStorageCost(serviceLevel, dataVolume);
}
if (openstack.checked && kubernetes.checked) {
rollout += kubernetesDeploymentCost + openstackDeploymentCost;
managedServicesCost +=
hosts * MANAGED_SERVICE_COSTS["openstack_and_kubernetes"];
} else if (openstack.checked) {
rollout += openstackDeploymentCost;
managedServicesCost += hosts * MANAGED_SERVICE_COSTS["openstack"];
} else if (kubernetes.checked) {
rollout += kubernetesDeploymentCost;
managedServicesCost += hosts * MANAGED_SERVICE_COSTS["kubernetes"];
}
if (openstack.checked || kubernetes.checked) {
yearly +=
managedServicesCost + managedSupportCost + storageCost + maasHostCost;
selfYearly += hostCost + storageCost;
}
renderTotals(rollout, yearly, selfYearly);
}
window.addEventListener("DOMContentLoaded", () => {
const calculator = document.querySelector(".js-tco-calculator");
if (calculator) {
initTCOCalculator();
}
});
| barrymcgee/www.ubuntu.com | static/js/src/tco-calculator.js | JavaScript | lgpl-3.0 | 5,881 |
/* ************************************************************************
GUI for JavaScript Client for XMPP (jc4xmpp)
Copyright
2012 Dirk Woestefeld
License:
LGPL v3: http://www.gnu.org/licenses/lgpl.html
A Copy of the License can be found in the directory of this project.
Authors:
Dirk Woestefeld
************************************************************************ */
/**
* @ignore(jc4xmppConfig.*)
*/
/**
* Config-Panel general setting
*/
qx.Class.define("jc4xmpp_ui.config.GeneralConfig",
{
extend:qx.ui.tabview.Page,
/*
*****************************************************************************
CONSTRUCTOR
*****************************************************************************
*/
/**
*
*/
construct : function(){
//TODO: Show info if not connected
this.base(arguments,this.tr("General"),jc4xmpp_ui.Icons.icon16("user-desktop"));
this._cfg = jc4xmpp_ui.Application.config;
this._cfg.addListener("change", this._hdlCfgChange, this);
this.setLayout(new qx.ui.layout.VBox(10));
this._uiObj = {};
this.add(new qx.ui.basic.Label().set({
rich:true,
value:this.tr("general_config_info")
}));
var panel = new qx.ui.container.Composite(new qx.ui.layout.VBox());
var panel2 = new qx.ui.container.Composite(new qx.ui.layout.HBox());
panel.add(new qx.ui.basic.Label(this.tr("Backgroundimage")));
this._bgImg = new qx.ui.form.ComboBox();
var select = this._cfg.get("backgroundImage","");
var bgImgs = jc4xmppConfig.BackgroundImages;
for(var e in bgImgs){
if(bgImgs[e] == select){
select = e;
}
this._bgImg.add(new qx.ui.form.ListItem(e));
}
this._bgImg.setValue(select);
panel2.add(this._bgImg,{flex:1});
this._btnBgApply = new qx.ui.form.Button(null,jc4xmpp_ui.Icons.icon16("view-refresh"));
this._btnBgApply.setToolTipText(this.tr("Load selected Image"));
this._btnBgApply.addListener("execute", function(){
var val = this._bgImg.getValue();
this._cfg.set("backgroundImage",bgImgs[val] || val);
},this)
panel2.add(this._btnBgApply);
panel.add(panel2);
this.add(panel);
panel = new qx.ui.container.Composite(new qx.ui.layout.VBox());
// Position of the "taskbar"
panel.add(new qx.ui.basic.Label(this.tr("The Position of the Buttonbar")).set({alignY:"middle"}));
var posLst = { "top":{"txt":this.marktr("Top")},
"left":{"txt":this.marktr("Left")},
"right":{"txt":this.marktr("Right")},
"bottom":{"txt":this.marktr("Bottom")}
};
this.winBarPos = new qx.ui.form.SelectBox();
var select = this._cfg.get("appWinbarPosition");
for(var e in posLst){
var item = new qx.ui.form.ListItem(this.tr(posLst[e].txt));
posLst[e].item = item;
this.winBarPos.add(item);
if(e === select){
this.winBarPos.setSelection([item]);
}
}
this.winBarPos.addListener("changeSelection", function(evt) {
var item = this.winBarPos.getSelection()[0];
for(var e in posLst){
if(item == posLst[e].item){
this._cfg.set("appWinbarPosition",""+e);
}
}
},this);
this.winBarPos.setMaxWidth(150);
panel.add(this.winBarPos);
this.add(panel);
},
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :{
/**
* prepare data before save
*/
_prepareSave: function(){
var val = this._bgImg.getValue();
var bgImgs = jc4xmppConfig.BackgroundImages;
this._cfg.set("backgroundImage",bgImgs[val] || val);
},
/**
* handle config change
* @param evt {jc4xmpp.Event}
*/
_hdlCfgChange: function(evt){
var name = evt["name"];
var obj = this._uiObj[name];
if(obj){
if(obj.getValue() != evt["value"]){
obj.setValue(evt["value"]);
}
}
},
/**
* Called by the dialog if the dialog is opened.
*/
_dialogOpen:function(){}
}
}); | hobbytuxer/jc4xmpp | gui/source/class/jc4xmpp_ui/config/GeneralConfig.js | JavaScript | lgpl-3.0 | 4,742 |
/**
* Created by LABS on 30.08.2016.
*/
$('document').ready(function(){
$('#alerts').jplist({
itemsBox: '.list'
,itemPath: '.list-item'
,panelPath: '.jplist-panel'
});
});
function send_ajax_post_request(cve_id, software_id, option) {
$.ajax({
type: "POST",
url: "alerts.html",
data: {
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
cve_id: cve_id,
software_id: software_id,
option: option
},
success: function (result) { location.reload(); }
});
}
function set_cve_as_negative(cve_id, software_id) {
send_ajax_post_request(cve_id, software_id, 'set_cve_as_negative');
}
function notify(cve_id, sw_id, sw) {
show_element('sending');
hide_element('sent_email_failed');
hide_element('sent_email_ok');
$('#sending').html('<div class="info-msg">sending alert for ' + sw + '</div>');
$.ajax({
type: "POST",
url: "alerts.html",
data: {
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
software_id: sw_id,
option: 'notify'
},
success: function (result) {
if (result == 'failed') {
show_element('sent_email_failed');
$("#sent_email_failed").html('<div class="error-msg">failed to sent alert for ' + sw + '</div>');
} else {
location.reload();
}
hide_element('sending')
}
});
}
| fkie-cad/iva | frontend/iva/static/iva/js/alerts.js | JavaScript | lgpl-3.0 | 1,532 |
jsh.App[modelid] = new (function(){
var _this = this;
this.menu_id_auto = 0;
this.oninit = function(){
XModels[modelid].menu_id_auto = function () {
if(!_this.menu_id_auto) _this.menu_id_auto = xmodel.controller.form.Data.menu_id_auto;
return _this.menu_id_auto;
};
jsh.$root('.menu_id_auto.tree').data('oncontextmenu','return '+XExt.getJSApp(modelid)+'.oncontextmenu(this, n);');
};
this.oncontextmenu = function(ctrl, n){
var menuid = '._item_context_menu_menu_id_auto';
var menu_add = jsh.$root(menuid).children('.insert');
var menu_delete = jsh.$root(menuid).children('.delete');
var jctrl = $(ctrl);
var level = 0;
var jpctrl = jctrl;
while(!jpctrl.hasClass('tree') && (level < 100)){ level++; jpctrl = jpctrl.parent(); }
if(level == 1){
menu_add.show();
menu_delete.hide();
}
else if(level == 2){
menu_add.show();
menu_delete.show();
}
else if(level == 3){
menu_add.hide();
menu_delete.show();
}
else { /* Do nothing */ }
XExt.ShowContextMenu(menuid, $(ctrl).data('value'), { id:n });
return false;
};
this.menu_id_onchange = function(obj, newval, undoChange) {
if(jsh.XPage.GetChanges().length){
undoChange();
return XExt.Alert('Please save changes before navigating to a different record.');
}
jsh.App[modelid].select_menu_id_auto(newval);
};
this.select_menu_id_auto = function(newval, cb){
xmodel.set('cur_menu_id_auto', newval);
xmodel.controller.form.Data.menu_id_auto = newval;
this.menu_id_auto = newval;
jsh.XPage.Select({ modelid: XBase[xmodel.module_namespace+'Dev/Menu'][0], force: true }, cb);
};
this.item_insert = function(context_item){
if(jsh.XPage.GetChanges().length) return XExt.Alert('Please save changes before adding menu items.');
var fields = {
'menu_name': { 'caption': 'Menu ID', 'actions': 'BI', 'type': 'varchar', 'length': 30, 'validators': [XValidate._v_Required(), XValidate._v_MaxLength(30)] },
'menu_desc': { 'caption': 'Display Name', 'actions': 'BI', 'type': 'varchar', 'length': 255, 'validators': [XValidate._v_Required(), XValidate._v_MaxLength(255)] },
};
var data = { 'menu_id_parent': jsh.xContextMenuItemData.id };
var validate = new XValidate();
_.each(fields, function (val, key) { validate.AddControlValidator('.Menu_InsertPopup .' + key, '_obj.' + key, val.caption, 'BI', val.validators); });
XExt.CustomPrompt('.Menu_InsertPopup','\
<div class="Menu_InsertPopup xdialogbox xpromptbox" style="width:360px;"> \
<h3>Add Child Item</h3> \
<div align="left" style="padding-top:15px;"> \
<div style="width:100px;display:inline-block;margin-bottom:8px;text-align:right;">Menu ID:</div> <input autocomplete="off" type="text" class="menu_name" style="width:150px;" maxlength="255" /> (ex. ORDERS)<br/> \
<div style="width:100px;display:inline-block;text-align:right;">Display Name:</div> <input autocomplete="off" type="text" class="menu_desc" style="width:150px;"maxlength="255" /><br/> \
<div style="text-align:center;"><input type="button" value="Add" class="button_ok" style="margin-right:15px;" /> <input type="button" value="Cancel" class="button_cancel" /></div> \
</div> \
</div> \
',function(){ //onInit
window.setTimeout(function(){jsh.$root('.Menu_InsertPopup .menu_name').focus();},1);
}, function (success) { //onAccept
_.each(fields, function (val, key) { data[key] = jsh.$root('.Menu_InsertPopup .' + key).val(); });
if (!validate.ValidateControls('I', data, '')) return;
var insertTarget = xmodel.module_namespace+'Dev/Menu_Exec_Insert';
XForm.prototype.XExecutePost(insertTarget, data, function (rslt) { //On success
if ('_success' in rslt) {
jsh.App[modelid].select_menu_id_auto(parseInt(rslt[insertTarget][0].menu_id_auto), function(){
success();
jsh.XPage.Refresh();
});
}
});
}, function () { //onCancel
}, function () { //onClosed
});
};
this.getSMbyValue = function(menu_id_auto){
if(!menu_id_auto) return null;
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_val]==menu_id_auto.toString()) return lov[i];
}
return null;
};
this.getSMbyID = function(menu_id){
if(!menu_id) return null;
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_id]==menu_id.toString()) return lov[i];
}
return null;
};
this.item_delete = function(context_item){
if(jsh.XPage.GetChanges().length) return XExt.Alert('Please save changes before deleting menu items.');
var item_desc = XExt.getLOVTxt(xmodel.controller.form.LOVs.menu_id_auto,context_item);
var menu = jsh.App[modelid].getSMbyValue(context_item);
var menu_parent = null;
var has_children = false;
if(menu){
if(!menu[jsh.uimap.code_parent_id]) return XExt.Alert('Cannot delete root node');
menu_parent = jsh.App[modelid].getSMbyID(menu[jsh.uimap.code_parent_id]);
var lov = xmodel.controller.form.LOVs.menu_id_auto;
for(var i=0;i<lov.length;i++){
if(lov[i][jsh.uimap.code_parent_id] && (lov[i][jsh.uimap.code_parent_id].toString()==menu[jsh.uimap.code_id].toString())) has_children = true;
}
}
if(has_children){ XExt.Alert('Cannot delete menu item with children. Please delete child items first.'); return; }
//Move to parent ID if the deleted node is selected
var new_menu_id_auto = null;
if(_this.menu_id_auto==context_item){
if(menu_parent) new_menu_id_auto = menu_parent[jsh.uimap.code_val];
}
XExt.Confirm('Are you sure you want to delete \''+item_desc+'\'?',function(){
XForm.prototype.XExecutePost(xmodel.module_namespace+'Dev/Menu_Exec_Delete', { menu_id_auto: context_item }, function (rslt) { //On success
if ('_success' in rslt) {
//Select parent
if(new_menu_id_auto) XExt.TreeSelectNode(jsh.$root('.menu_id_auto.tree'),new_menu_id_auto);
jsh.XPage.Refresh();
}
});
});
};
})(); | apHarmony/jsharmony-factory | models/Dev_Menu_Tree_Editor.js | JavaScript | lgpl-3.0 | 6,260 |
import {IDOC_STATE} from 'idoc/idoc-constants';
// Gets any prefix:uuid until ?, # or / is matched
const INSTANCE_ID_REGEX = new RegExp('([a-z]+:[^?#/]+)', 'g');
export class UrlUtils {
/**
* Searches for an a parameter in a URL.
*
* @param url url to process
* @param name name of the parameter
* @returns {string} value of the parameter or null if missing
*/
static getParameter(url, name) {
let result = UrlUtils.getParameterArray(url, name);
return result instanceof Array && result.length > 0 ? result[0] : null;
}
/**
* @param url
* @param name
* @returns {*} an array with URL parameters values (multiple parameters with the same name) or undefined
*/
static getParameterArray(url, name) {
let decodedUrl = decodeURIComponent(url);
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
let regex = new RegExp('[\\?&]' + name + '=([^&#]*)', 'g');
let results, match;
while ((match = regex.exec(decodedUrl)) !== null) {
if (results === undefined) {
results = [];
}
results.push(decodeURIComponent(match[1].replace(/\+/g, ' ')));
}
return results;
}
static getParamSeparator(url) {
return url.indexOf('?') !== -1 ? '&' : '?';
}
/**
* Extracts url fragment from given url if any. The url is decoded first.
*
* @param url
* @returns The url fragment string or empty string if no fragment is found.
*/
static getUrlFragment(url) {
let hash = url.replace('/#', '');
hash = decodeURIComponent(hash);
hash = hash.indexOf('#') !== -1 ? hash.slice(hash.indexOf('#') + 1) : '';
return hash;
}
/**
* Extract instance identifier from url by specific pattern.
*
* @returns instance identifier or null
*/
static getIdFromUrl(url) {
if (!url) {
return null;
}
var decodedUrl = decodeURIComponent(url);
var results = decodedUrl.match(INSTANCE_ID_REGEX);
// Returns the last match (if host:port is matched too)
return results === null ? null : results[results.length - 1];
}
static buildIdocUrl(instanceId, tabId = '', params = {}) {
if (!instanceId) {
throw Error('Instance id is required!');
}
let url = `/#/${IDOC_STATE}/${instanceId}`;
let paramsLen = Object.keys(params).length;
if (paramsLen > 0) {
url += '?';
Object.keys(params).forEach((key) => {
url += `${key}=${params[key]}&`;
});
url = url.substring(0, url.length - 1);
}
if (tabId) {
url += `#${tabId}`;
}
return url;
}
static appendQueryParam(url, param, value) {
let querySeparator = UrlUtils.getParamSeparator(url);
return `${url}${querySeparator}${param}=${value}`;
}
/**
* Removes query param from url along with its value, if the param is available.
*
* @param window the window object, could be the global window or an adapter
* @param paramName name of the query param that will be removed
*/
static removeQueryParam(window, paramName) {
let url = window.location.href;
if (url.indexOf(paramName + '=') !== -1) {
let regex = new RegExp('[?&]{0,1}' + paramName + '=[^&#]+');
let replaced = url.replace(regex, '');
UrlUtils.replaceUrl(window, replaced);
}
}
/**
* Replaces the current url with given one without making redirect.
*
* @param window the window object, could be the global window or an adapter
* @param url that will be set
*/
static replaceUrl(window, url) {
window.history.replaceState({}, '', url);
}
} | SirmaITT/conservation-space-1.7.0 | docker/sep-ui/src/common/url-utils.js | JavaScript | lgpl-3.0 | 3,561 |
$.fn.croneditor = function(opts) {
var el = this;
// Write the HTML template to the document
$(el).html(tmpl);
var cronArr = ["*", "*", "*", "*", "*", "*"];
if (typeof opts.value === "string") {
cronArr = opts.value.split(' ');
}
$( ".tabs" ).tabs({
activate: function( event, ui ) {
switch ($(ui.newTab).attr('id')) {
// Seconds
case 'button-second-every':
cronArr[0] = "*";
break;
case 'button-second-n':
cronArr[0] = "*/" + $( "#tabs-second .slider" ).slider("value");
break;
// Minutes
case 'button-minute-every':
cronArr[1] = "*";
break;
case 'button-minute-n':
cronArr[1] = "*/" + $( "#tabs-minute .slider" ).slider("value");
break;
case 'button-minute-each':
cronArr[1] = "*";
// TODO: toggle off selected minutes on load
//$('.tabs-minute-format input[checked="checked"]').click()
$('.tabs-minute-format').html('');
drawEachMinutes();
break;
// Hours
case 'button-hour-every':
cronArr[2] = "*";
break;
case 'button-hour-n':
cronArr[2] = "*/" + $( "#tabs-hour .slider" ).slider("value");
break;
case 'button-hour-each':
cronArr[2] = "*";
$('.tabs-hour-format').html('');
drawEachHours();
break;
// Days
case 'button-day-every':
cronArr[3] = "*";
break;
case 'button-day-each':
cronArr[3] = "*";
$('.tabs-day-format').html('');
drawEachDays();
break;
// Months
case 'button-month-every':
cronArr[4] = "*";
break;
case 'button-month-each':
cronArr[4] = "*";
$('.tabs-month-format').html('');
drawEachMonths();
break;
// Weeks
case 'button-week-every':
cronArr[5] = "*";
break;
case 'button-week-each':
cronArr[5] = "*";
$('.tabs-week-format').html('');
drawEachWeek();
break;
}
drawCron();
}
});
function drawCron () {
var newCron = cronArr.join(' ');
$('#cronString').val(newCron);
// TODO: add back next estimated cron time
/*
var last = new Date();
$('.next').html('');
var job = new cron.CronTime(newCron);
var next = job._getNextDateFrom(new Date());
$('.next').append('<span id="nextRun">' + dateformat(next, "ddd mmm dd yyyy HH:mm:ss") + '</span><br/>');
*/
/*
setInterval(function(){
drawCron();
}, 500);
*/
/*
$('#cronString').keyup(function(){
cronArr = $('#cronString').val().split(' ');
console.log('updated', cronArr)
});
*/
}
$('#clear').click(function(){
$('#cronString').val('* * * * * *');
cronArr = ["*","*","*","*","*", "*"];
});
$( "#tabs-second .slider" ).slider({
min: 1,
max: 59,
slide: function( event, ui ) {
cronArr[0] = "*/" + ui.value;
$('#tabs-second-n .preview').html('每隔 ' + ui.value + ' 秒');
drawCron();
}
});
$( "#tabs-minute .slider" ).slider({
min: 1,
max: 59,
slide: function( event, ui ) {
cronArr[1] = "*/" + ui.value;
$('#tabs-minute-n .preview').html('每隔 ' + ui.value + ' 分钟');
drawCron();
}
});
$( "#tabs-hour .slider" ).slider({
min: 1,
max: 23,
slide: function( event, ui ) {
cronArr[2] = "*/" + ui.value;
$('#tabs-hour-n .preview').html('每隔 ' + ui.value + ' 小时');
drawCron();
}
});
// TOOD: All draw* functions can be combined into a few smaller methods
function drawEachMinutes () {
// minutes
for (var i = 0; i < 60; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-minute-format').append('<input type="checkbox" id="minute-check' + i + '"><label for="minute-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i+1) % 10 === 0) {
$('.tabs-minute-format').append('<br/>');
}
}
$('.tabs-minute-format input').button();
$('.tabs-minute-format').buttonset();
$('.tabs-minute-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('minute-check', '');
if(cronArr[1] === "*") {
cronArr[1] = $(this).attr('id').replace('minute-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[1].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[1] = list.join(',');
} else {
// else toggle it on
cronArr[1] = cronArr[1] + "," + newItem;
}
if(cronArr[1] === "") {
cronArr[1] = "*";
}
}
drawCron();
});
}
function drawEachHours () {
// hours
for (var i = 0; i < 24; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-hour-format').append('<input type="checkbox" id="hour-check' + i + '"><label for="hour-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i+1) % 12 === 0) {
$('.tabs-hour-format').append('<br/>');
}
}
$('.tabs-hour-format input').button();
$('.tabs-hour-format').buttonset();
$('.tabs-hour-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('hour-check', '');
if(cronArr[2] === "*") {
cronArr[2] = $(this).attr('id').replace('hour-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[2].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[2] = list.join(',');
} else {
// else toggle it on
cronArr[2] = cronArr[2] + "," + newItem;
}
if(cronArr[2] === "") {
cronArr[2] = "*";
}
}
drawCron();
});
};
function drawEachDays () {
// days
for (var i = 1; i < 32; i++) {
var padded = i;
if(padded.toString().length === 1) {
padded = "0" + padded;
}
$('.tabs-day-format').append('<input type="checkbox" id="day-check' + i + '"><label for="day-check' + i + '">' + padded + '</label>');
if (i !== 0 && (i) % 7 === 0) {
$('.tabs-day-format').append('<br/>');
}
}
$('.tabs-day-format input').button();
$('.tabs-day-format').buttonset();
$('.tabs-day-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('day-check', '');
if(cronArr[3] === "*") {
cronArr[3] = $(this).attr('id').replace('day-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[3].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[3] = list.join(',');
} else {
// else toggle it on
cronArr[3] = cronArr[3] + "," + newItem;
}
if(cronArr[3] === "") {
cronArr[3] = "*";
}
}
drawCron();
});
};
function drawEachMonths () {
// months
//var months = [null, 'Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
var months = [null, '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
for (var i = 1; i < 13; i++) {
var padded = i;
if(padded.toString().length === 1) {
//padded = "0" + padded;
}
$('.tabs-month-format').append('<input type="checkbox" id="month-check' + i + '"><label for="month-check' + i + '">' + months[i] + '</label>');
}
$('.tabs-month-format input').button();
$('.tabs-month-format').buttonset();
$('.tabs-month-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('month-check', '');
if(cronArr[4] === "*") {
cronArr[4] = $(this).attr('id').replace('month-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[4].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[4] = list.join(',');
} else {
// else toggle it on
cronArr[4] = cronArr[4] + "," + newItem;
}
if(cronArr[4] === "") {
cronArr[4] = "*";
}
}
drawCron();
});
};
function drawEachWeek () {
// weeks
//var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var days = ['星期天', '星期一', '星期二', '星期三', '星期四', '星球五', '星期六'];
for (var i = 0; i < 7; i++) {
var padded = i;
if(padded.toString().length === 1) {
//padded = "0" + padded;
}
$('.tabs-week-format').append('<input type="checkbox" id="week-check' + i + '"><label for="week-check' + i + '">' + days[i] + '</label>');
}
$('.tabs-week-format input').button();
$('.tabs-week-format').buttonset();
$('.tabs-week-format input[type="checkbox"]').click(function(){
var newItem = $(this).attr('id').replace('week-check', '');
if(cronArr[5] === "*") {
cronArr[5] = $(this).attr('id').replace('week-check', '');
} else {
// if value already in list, toggle it off
var list = cronArr[5].split(',');
if (list.indexOf(newItem) !== -1) {
list.splice(list.indexOf(newItem), 1);
cronArr[5] = list.join(',');
} else {
// else toggle it on
cronArr[5] = cronArr[5] + "," + newItem;
}
if(cronArr[5] === "") {
cronArr[5] = "*";
}
}
drawCron();
});
};
// TODO: Refactor these methods into smaller methods
drawEachMinutes();
drawEachHours();
drawEachDays();
drawEachMonths();
drawCron();
};
// HTML Template for plugin
var tmpl = '<input type="text" id="cronString" value="* * * * * * ?" size="80"/>\
<br/>\
<input type="button" value="重置" id="clear"/>\
<br/>\
<!-- TODO: add back next estimated time -->\
<!-- <span>Will run next at:<em><span class="next"></span></em></span> -->\
<!-- the cron editor will be here -->\
<div id="tabs" class="tabs">\
<ul>\
<li><a href="#tabs-second">秒</a></li>\
<li><a href="#tabs-minute">分钟</a></li>\
<li><a href="#tabs-hour">小时</a></li>\
<li><a href="#tabs-day">月份中的天</a></li>\
<li><a href="#tabs-month">月份</a></li>\
<li><a href="#tabs-week">星期几?</a></li>\
</ul>\
<div id="tabs-second">\
<div class="tabs">\
<ul>\
<li id="button-second-every"><a href="#tabs-second-every">每秒</a></li>\
<li id="button-second-n"><a href="#tabs-second-n">隔几秒</a></li>\
</ul>\
<div id="tabs-second-every" class="preview">\
<div>*</div>\
<div>每秒</div>\
</div>\
<div id="tabs-second-n">\
<div class="preview"> 每隔1秒</div>\
<div class="slider"></div>\
</div>\
</div>\
</div>\
<div id="tabs-minute">\
<div class="tabs">\
<ul>\
<li id="button-minute-every"><a href="#tabs-minute-every">每分钟</a></li>\
<li id="button-minute-n"><a href="#tabs-minute-n">隔几分钟</a></li>\
<li id="button-minute-each"><a href="#tabs-minute-each">隔选定的分钟</a></li>\
</ul>\
<div id="tabs-minute-every" class="preview">\
<div>*</div>\
<div>每分钟</div>\
</div>\
<div id="tabs-minute-n">\
<div class="preview">每隔1分钟</div>\
<div class="slider"></div>\
</div>\
<div id="tabs-minute-each" class="preview">\
<div>隔选定的分钟</div><br/>\
<div class="tabs-minute-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-hour">\
<div class="tabs">\
<ul>\
<li id="button-hour-every"><a href="#tabs-hour-every">每小时</a></li>\
<li id="button-hour-n"><a href="#tabs-hour-n">隔几小时</a></li>\
<li id="button-hour-each"><a href="#tabs-hour-each">隔选定的小时</a></li>\
</ul>\
<div id="tabs-hour-every" class="preview">\
<div>*</div>\
<div>每小时</div>\
</div>\
<div id="tabs-hour-n">\
<div class="preview">每隔1小时</div>\
<div class="slider"></div>\
</div>\
<div id="tabs-hour-each" class="preview">\
<div>隔选定的小时</div><br/>\
<div class="tabs-hour-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-day">\
<div class="tabs">\
<ul>\
<li id="button-day-every"><a href="#tabs-day-every">每天/月</a></li>\
<li id="button-day-each"><a href="#tabs-day-each">选定的日期</a></li>\
</ul>\
<div id="tabs-day-every" class="preview">\
<div>*</div>\
<div>每天/月</div>\
</div>\
<div id="tabs-day-each" class="preview">\
<div>选定的日期</div><br/>\
<div class="tabs-day-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-month">\
<div class="tabs">\
<ul>\
<li id="button-month-every"><a href="#tabs-month-every">每月</a></li>\
<li id="button-month-each"><a href="#tabs-month-each">选定的月份</a></li>\
</ul>\
<div id="tabs-month-every" class="preview">\
<div>*</div>\
<div>每月</div>\
</div>\
<div id="tabs-month-each" class="preview">\
<div>选定的月份</div><br/>\
<div class="tabs-month-format"></div>\
</div>\
</div>\
</div>\
<div id="tabs-week">\
<div class="tabs">\
<ul>\
<li id="button-week-every"><a href="#tabs-week-every">每天/周</a></li>\
<li id="button-week-each"><a href="#tabs-week-each">选定的星期几</a></li>\
</ul>\
<div id="tabs-week-every" class="preview">\
<div>*</div>\
<div>每天/周</div>\
</div>\
<div id="tabs-week-each">\
<div class="preview">选定的星期几</div><br/>\
<div class="tabs-week-format"></div>\
</div>\
</div>\
</div>\
</div>'; | liushuishang/YayCrawler | yaycrawler.admin/src/main/resources/static/assets/global/plugins/cron-editor/js/jquery.croneditor.js | JavaScript | lgpl-3.0 | 14,595 |
"use strict";
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = getLookup;
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
/**
@name $SP().getLookup
@function
@category utils
@description Split the ID and Value
@param {String} str The string to split
@return {Object} .id returns the ID (or an array of IDs), and .value returns the value (or an array of values)
@example
$SP().getLookup("328;#Foo"); // --> {id:"328", value:"Foo"}
$SP().getLookup("328;#Foo;#191;#Other Value"); // --> {id:["328", "191"], value:["Foo", "Other Value"]}
$SP().getLookup("328"); // --> {id:"328", value:"328"}
*/
function getLookup(str) {
if (!str) return {
id: "",
value: ""
};
var a = str.split(";#");
if (a.length <= 2) return {
id: a[0],
value: typeof a[1] === "undefined" ? a[0] : a[1]
};else {
var _context;
// we have several lookups
return {
id: (0, _slice.default)(_context = str.replace(/([0-9]+;#)([^;]+)/g, "$1").replace(/;#;#/g, ",")).call(_context, 0, -2).split(","),
value: str.replace(/([0-9]+;#)([^;]+)/g, "$2").split(";#")
};
}
}
module.exports = exports.default; | Aymkdn/SharepointPlus | dist/utils/getLookup.js | JavaScript | lgpl-3.0 | 1,429 |
module.exports = function(grunt) {
var version = grunt.option('release');
if (process.env.SELENIUM_BROWSER_CAPABILITIES != undefined) {
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
}
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
openpgp: {
files: {
'dist/openpgp.js': [ './src/index.js' ]
},
options: {
browserifyOptions: {
standalone: 'openpgp',
external: [ 'crypto', 'node-localstorage' ]
}
}
},
openpgp_debug: {
files: {
'dist/openpgp_debug.js': [ './src/index.js' ]
},
options: {
browserifyOptions: {
debug: true,
standalone: 'openpgp',
external: [ 'crypto', 'node-localstorage' ]
}
}
},
worker: {
files: {
'dist/openpgp.worker.js': [ './src/worker/worker.js' ]
}
},
worker_min: {
files: {
'dist/openpgp.worker.min.js': [ './src/worker/worker.js' ]
}
},
unittests: {
files: {
'test/openpgp.js': [ './test/src/index.js' ],
'test/lib/unittests-bundle.js': [ './test/unittests.js' ]
},
options: {
browserifyOptions: {
external: [ 'openpgp', 'crypto', 'node-localstorage']
}
}
}
},
replace: {
openpgp: {
src: ['dist/openpgp.js'],
dest: ['dist/openpgp.js'],
replacements: [{
from: /OpenPGP.js VERSION/g,
to: 'OpenPGP.js v<%= pkg.version %>'
}]
},
openpgp_debug: {
src: ['dist/openpgp_debug.js'],
dest: ['dist/openpgp_debug.js'],
replacements: [{
from: /OpenPGP.js VERSION/g,
to: 'OpenPGP.js v<%= pkg.version %>'
}]
},
worker_min: {
src: ['dist/openpgp.worker.min.js'],
dest: ['dist/openpgp.worker.min.js'],
replacements: [{
from: "importScripts('openpgp.js')",
to: "importScripts('openpgp.min.js')"
}]
}
},
uglify: {
openpgp: {
files: {
'dist/openpgp.min.js' : [ 'dist/openpgp.js' ],
'dist/openpgp.worker.min.js' : [ 'dist/openpgp.worker.min.js' ]
}
},
options: {
banner: '/*! OpenPGPjs.org this is LGPL licensed code, see LICENSE/our website for more information.- v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */'
}
},
jsbeautifier: {
files: ['src/**/*.js'],
options: {
indent_size: 2,
preserve_newlines: true,
keep_array_indentation: false,
keep_function_indentation: false,
wrap_line_length: 120
}
},
jshint: {
all: ['src/**/*.js']
},
jsdoc: {
dist: {
src: ['README.md', 'src'],
options: {
destination: 'doc',
recurse: true,
template: 'jsdoc.template'
}
}
},
mocha_istanbul: {
coverage: {
src: 'test',
options: {
root: 'node_modules/openpgp',
timeout: 240000,
}
},
coveralls: {
src: ['test'],
options: {
root: 'node_modules/openpgp',
timeout: 240000,
coverage: true,
reportFormats: ['cobertura','lcovonly']
}
}
},
mochaTest: {
unittests: {
options: {
reporter: 'spec',
timeout: 120000
},
src: [ 'test/unittests.js' ]
}
},
copy: {
npm: {
expand: true,
flatten: true,
cwd: 'node_modules/',
src: ['mocha/mocha.css', 'mocha/mocha.js', 'chai/chai.js', 'whatwg-fetch/fetch.js'],
dest: 'test/lib/'
},
unittests: {
expand: true,
flatten: false,
cwd: './',
src: ['src/**'],
dest: 'test/'
},
zlib: {
expand: true,
cwd: 'node_modules/zlibjs/bin/',
src: ['rawdeflate.min.js','rawinflate.min.js','zlib.min.js'],
dest: 'src/compression/'
}
},
clean: ['dist/'],
connect: {
dev: {
options: {
port: 3000,
base: '.'
}
}
},
'saucelabs-mocha': {
all: {
options: {
username: 'openpgpjs',
key: '60ffb656-2346-4b77-81f3-bc435ff4c103',
urls: ['http://127.0.0.1:3000/test/unittests.html'],
build: process.env.TRAVIS_BUILD_ID,
testname: 'Sauce Unit Test for openpgpjs',
browsers: [browser_capabilities],
public: "public",
maxRetries: 3,
throttled: 2,
pollInterval: 4000,
statusCheckAttempts: 200
}
},
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jsdoc');
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.registerTask('set_version', function() {
if (!version) {
throw new Error('You must specify the version: "--release=1.0.0"');
}
patchFile({
fileName: 'package.json',
version: version
});
patchFile({
fileName: 'bower.json',
version: version
});
});
function patchFile(options) {
var fs = require('fs'),
path = './' + options.fileName,
file = require(path);
if (options.version) {
file.version = options.version;
}
fs.writeFileSync(path, JSON.stringify(file, null, 2));
}
grunt.registerTask('default', 'Build OpenPGP.js', function() {
grunt.task.run(['clean', 'copy:zlib', 'browserify', 'replace', 'uglify', 'npm_pack']);
//TODO jshint is not run because of too many discovered issues, once these are addressed it should autorun
grunt.log.ok('Before Submitting a Pull Request please also run `grunt jshint`.');
});
grunt.registerTask('documentation', ['jsdoc']);
// Alias the `npm_pack` task to run `npm pack`
grunt.registerTask('npm_pack', 'npm pack', function () {
var done = this.async();
var npm = require('child_process').exec('npm pack ../', { cwd: 'dist'}, function (err, stdout) {
var package = stdout;
if (err === null) {
var install = require('child_process').exec('npm install dist/' + package, function (err) {
done(err);
});
install.stdout.pipe(process.stdout);
install.stderr.pipe(process.stderr);
} else {
done(err);
}
});
npm.stdout.pipe(process.stdout);
npm.stderr.pipe(process.stderr);
});
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(err){
if (err) {
return done(err);
}
done();
});
});
// Test/Dev tasks
grunt.registerTask('test', ['copy:npm', 'copy:unittests', 'mochaTest']);
grunt.registerTask('coverage', ['default', 'copy:npm', 'copy:unittests', 'mocha_istanbul:coverage']);
grunt.registerTask('coveralls', ['default', 'copy:npm', 'copy:unittests', 'mocha_istanbul:coveralls']);
grunt.registerTask('saucelabs', ['default', 'copy:npm', 'copy:unittests', 'connect', 'saucelabs-mocha']);
};
| vSaKv/openpgpjs | Gruntfile.js | JavaScript | lgpl-3.0 | 7,704 |
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: '/'
}).listen(3000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
| devsli/browser-webpack-brotli-error | devserver.js | JavaScript | unlicense | 348 |
/*===============================================================+
| 0-ZeT Library for Nashorn-JsX [ 1.0 ] |
| Asserts & Errors |
| / [email protected] / |
+===============================================================*/
var ZeT = JsX.once('./checks.js')
ZeT.extend(ZeT,
{
/**
* Returns exception concatenating the optional
* arguments into string message. The stack is
* appended as string after the new line.
*/
ass : function(/* messages */)
{
var m = ZeT.cati(0, arguments)
var x = ZeT.stack()
//?: {has message}
if(!ZeT.ises(m)) x = m.concat('\n', x)
//!: return error to throw later
return new Error(x)
},
/**
* First argument of assertion tested with ZeT.test().
* The following optional arguments are the message
* components concatenated to string.
*
* The function returns the test argument.
*/
assert : function(test /* messages */)
{
if(ZeT.test(test)) return test
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'Assertion failed!'
throw ZeT.ass(m)
},
/**
* Checks that given object is not null, or undefined.
*/
assertn : function(obj /* messages */)
{
if(!ZeT.isx(obj)) return obj
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'The object is undefined or null!'
throw ZeT.ass(m)
},
/**
* Tests the the given object is a function
* and returns it back.
*/
assertf : function(f /* messages */)
{
if(ZeT.isf(f)) return f
var m = ZeTS.cati(1, arguments)
if(ZeT.ises(m)) m = 'A function is required!'
throw ZeT.ass(m)
},
/**
* Tests that the first argument is a string
* that is not whitespace-empty. Returns it.
*/
asserts : function(str /* messages */)
{
if(!ZeT.ises(str)) return str
var m = ZeT.cati(1, arguments)
if(ZeT.ises(m)) m = 'Not a whitespace-empty string is required!'
throw ZeT.ass(m)
},
/**
* Tests the the given object is a not-empty array
* and returns it back.
*/
asserta : function(array /* messages */)
{
if(ZeT.isa(array) && array.length)
return array
var m = ZeTS.cati(1, arguments)
if(ZeT.ises(m)) m = 'Not an empty array is required!'
throw ZeT.ass(m)
}
}) //<-- return this value | AntonBaukin/embeddy | springer/sources/net/java/osgi/embeddy/springer/jsx/zet/asserts.js | JavaScript | unlicense | 2,337 |
exports.run = function (callback) {
console.log("Hello from worker");
var uri = require.sandbox.id + require.id("./worker-runner.js");
console.log("Worker runner uri: " + uri);
return require.sandbox(uri, function(sandbox) {
return sandbox.main(callback);
}, function (err) {
console.log("Error while loading bundle '" + uri + "':", err.stack);
return callback(err);
});
}
| pinf-it/pinf-it-bundler | test/assets/packages/multiple-declared-exports-bundles/util/worker.js | JavaScript | unlicense | 392 |
I.regist('z.Win',function(W,D){
var CFG={
skin:'Default',
mask:true,
mask_opacity:10,
mask_color:'#FFF',
mask_close:false,
width:400,
height:250,
shadow:'#333 0px 0px 8px',
round:6,
title:'窗口',
title_height:30,
title_background:'#EFEFF0',
title_color:'#000',
title_border_color:'#BBB',
title_border_height:1,
close_icon:'fa fa-times',
close_background:'#EFEFF0',
close_color:'#000',
close_hover_background:'#EFEFF0',
close_hover_color:'#000',
content:'',
content_background:'#FFF',
footer_height:0,
footer_background:'#FFF',
footer_border_color:'#EEE',
footer_border_height:0,
callback:function(){}
};
var _create=function(obj){
var cfg=obj.config;
if(cfg.mask){
obj.mask=I.ui.Mask.create({skin:cfg.skin,opacity:cfg.mask_opacity,color:cfg.mask_color});
}
var o=I.insert('div');
I.cls(o,obj.className);
o.innerHTML='<i class="i-header"></i><a href="javascript:void(0);" class="i-close"></a><i class="i-body"></i><i class="i-footer"></i>';
obj.layer=o;
I.util.Boost.round(o,cfg.round);
I.util.Boost.addStyle(o,'-webkit-box-shadow:'+cfg.shadow+';-moz-box-shadow:'+cfg.shadow+';-ms-box-shadow:'+cfg.shadow+';-o-box-shadow:'+cfg.shadow+';box-shadow:'+cfg.shadow+';');
obj.titleBar=I.$(o,'class','i-header')[0];
obj.titleBar.innerHTML=cfg.title;
I.util.Boost.addStyle(obj.titleBar,'background:'+cfg.title_background+';color:'+cfg.title_color+';border-bottom:'+cfg.title_border_height+'px inset '+cfg.title_border_color+';');
obj.closeButton=I.$(o,'class','i-close')[0];
if(cfg.close_icon){
I.cls(obj.closeButton,'i-close '+cfg.close_icon);
}
I.util.Boost.addStyle(obj.closeButton,'background:'+cfg.close_background+';color:'+cfg.close_color);
I.listen(obj.closeButton,'click',function(){
obj.close();
});
obj.contentPanel=I.$(o,'class','i-body')[0];
obj.contentPanel.innerHTML=cfg.content;
obj.contentPanel.style.background=cfg.content_background;
obj.footerBar=I.$(o,'class','i-footer')[0];
I.util.Boost.addStyle(obj.footerBar,'background:'+cfg.footer_background+';border-top:'+cfg.footer_border_height+'px solid '+cfg.footer_border_color+';');
if(cfg.mask){
if(cfg.mask_close){
I.listen(obj.mask.layer,'click',function(m,e){
obj.close();
return true;
});
}
}
obj.suit=function(){
var that=this;
var c=that.config;
var r=I.region();
var wd=c.width;
var ht=c.height+c.title_height+c.footer_height;
I.util.Boost.addStyle(that.layer,'width:'+wd+'px;height:'+ht+'px;');
I.util.Boost.addStyle(that.titleBar,'width:'+wd+'px;height:'+c.title_height+'px;line-height:'+c.title_height+'px;');
I.util.Boost.addStyle(that.closeButton,'width:'+(c.title_height-c.title_border_height)+'px;height:'+(c.title_height-c.title_border_height)+'px;line-height:'+c.title_height+'px;');
I.util.Boost.addStyle(that.contentPanel,'top:'+c.title_height+'px;width:'+wd+'px;height:'+c.height+'px;');
I.util.Boost.addStyle(that.footerBar,'width:'+wd+'px;height:'+c.footer_height+'px;');
};
obj.resizeTo=function(w,h){
var that=this;
var c=that.config;
c.width=w;
c.height=h;
that.suit();
};
obj.goCenter=function(){
var that=this;
var c=that.config;
var r=I.region();
var wd=c.width;
var ht=c.height+c.title_height+c.footer_height;
I.util.Boost.addStyle(that.layer,'left:'+(r.x+Math.floor((r.width-wd)/2))+'px;top:'+(r.y+Math.floor((r.height-ht)/2))+'px;');
};
obj.moveTo=function(x,y){
I.util.Boost.addStyle(this.layer,'left:'+x+'px;top:'+y+'px;');
};
obj.goCenter();
obj.suit();
I.util.Drager.drag(obj.titleBar,obj.layer);
};
var _prepare=function(config){
var obj={layer:null,mask:null,titleBar:null,closeButton:null,contentPanel:null,footerBar:null,className:null,config:cfg};
var cfg=I.ui.Component.initConfig(config,CFG);
obj.config=cfg;
obj.className='i-z-Win-'+cfg.skin;
I.util.Skin.init(cfg.skin);
_create(obj);
obj.close=function(){
this.config.callback.call(this);
try{this.mask.close();}catch(e){}
this.layer.parentNode.removeChild(this.layer);
};
return obj;
};
return{
create:function(cfg){return _prepare(cfg);}
};
}+''); | 6tail/nlf | WebContent/js/z/Win.js | JavaScript | unlicense | 4,167 |
/**
* A dock
* @param {Object} The options
* @constructor
*/
hui.ui.IFrame = function(options) {
this.options = options;
this.element = hui.get(options.element);
this.name = options.name;
hui.ui.extend(this);
};
hui.ui.IFrame.prototype = {
/** Change the url of the iframe
* @param {String} url The url to change the iframe to
*/
setUrl : function(url) {
this.element.setAttribute('src',url);
//hui.frame.getDocument(this.element).location.href=url;
},
clear : function() {
this.setUrl('about:blank');
},
getDocument : function() {
return hui.frame.getDocument(this.element);
},
getWindow : function() {
return hui.frame.getWindow(this.element);
},
reload : function() {
this.getWindow().location.reload();
},
show : function() {
this.element.style.display='';
},
hide : function() {
this.element.style.display='none';
}
}; | Humanise/hui | js/IFrame.js | JavaScript | unlicense | 904 |
import React from 'react'
import { Button } from 'styled-mdl'
const demo = () => <Button raised>Raised</Button>
const caption = 'Raised Button'
const code = '<Button raised>Raised</Button>'
export default { demo, caption, code }
| isogon/styled-mdl-website | demos/buttons/demos/raised-default.js | JavaScript | unlicense | 231 |
const bcrypt = require("bcryptjs");
const Promise = require("bluebird");
const hashPasswordHook = require('./utils/hashPasswordHook');
const Op = require("sequelize").Op;
module.exports = function(sequelize, DataTypes) {
const log = require("logfilename")(__filename);
const models = sequelize.models;
const User = sequelize.define(
"User",
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
username: {
type: DataTypes.STRING(64),
unique: true,
allowNull: false
},
email: {
type: DataTypes.STRING(64),
unique: true,
allowNull: false
},
firstName: {
type: DataTypes.STRING(64),
field: "first_name"
},
lastName: {
type: DataTypes.STRING(64),
field: "last_name"
},
picture: {
type: DataTypes.JSONB
},
password: DataTypes.VIRTUAL,
passwordHash: {
type: DataTypes.TEXT,
field: "password_hash"
}
},
{
tableName: "users",
hooks: {
beforeCreate: hashPasswordHook,
beforeUpdate: hashPasswordHook
}
}
);
User.seedDefault = async function() {
let usersJson = require("./fixtures/users.json");
//log.debug("seedDefault: ", JSON.stringify(usersJson, null, 4));
for (let userJson of usersJson) {
await User.createUserInGroups(userJson, userJson.groups);
}
};
User.findByKey = async function(key, value) {
return this.findOne({
include: [
{
model: models.Profile,
as: "profile",
attributes: ["biography"]
},
{
model: models.AuthProvider,
as: "auth_provider",
attributes: ["name", "authId"]
}
],
where: { [key]: value },
attributes: ["id", "email", "username", "picture", "createdAt", "updatedAt"]
});
};
User.findByEmail = async function(email) {
return this.findByKey("email", email);
};
User.findByUserId = async function(userid) {
return this.findByKey("id", userid);
};
User.findByUsername = async function(userName) {
return this.findByKey("username", userName);
};
User.findByUsernameOrEmail = async function(username) {
return this.findOne({
where: {
[Op.or]: [{ email: username }, { username: username }]
}
});
};
User.createUserInGroups = async function(userJson, groups) {
log.debug("createUserInGroups user:%s, group: ", userJson, groups);
return sequelize
.transaction(async function(t) {
let userCreated = await models.User.create(userJson, {
transaction: t
});
const userId = userCreated.get().id;
await models.UserGroup.addUserIdInGroups(groups, userId, t);
//Create the profile
let profile = await models.Profile.create(
{ ...userJson.profile, user_id: userId },
{ transaction: t }
);
log.debug("profile created ", profile.get());
//Create the eventual authentication provider
if (userJson.authProvider) {
await models.AuthProvider.create(
{ ...userJson.authProvider, user_id: userId },
{ transaction: t }
);
}
/*
sqlite doesn't support this
await models.UserPending.destroy({
where: {
email: userJson.email
}
},{transaction: t});
*/
return userCreated;
})
.then(async userCreated => {
await models.UserPending.destroy({
where: {
email: userJson.email
}
});
return userCreated;
})
.catch(function(err) {
log.error("createUserInGroups: rolling back", err);
throw err;
});
};
User.checkUserPermission = async function(userId, resource, action) {
log.debug("Checking %s permission for %s on %s", action, userId, resource);
let where = {
resource: resource
};
where[action.toUpperCase()] = true;
let res = await this.findOne({
include: [
{
model: models.Group,
include: [
{
model: models.Permission,
where: where
}
]
}
],
where: {
id: userId
}
});
let authorized = res.Groups.length > 0 ? true : false;
return authorized;
};
User.getPermissions = function(username) {
return this.findOne({
include: [
{
model: models.Group,
include: [
{
model: models.Permission
}
]
}
],
where: {
username: username
}
});
};
User.prototype.comparePassword = function(candidatePassword) {
let me = this;
return new Promise(function(resolve, reject) {
let hashPassword = me.get("passwordHash") || "";
bcrypt.compare(candidatePassword, hashPassword, function(err, isMatch) {
if (err) {
return reject(err);
}
resolve(isMatch);
});
});
};
User.prototype.toJSON = function() {
let values = this.get({ clone: true });
delete values.passwordHash;
return values;
};
return User;
};
| FredericHeem/starhackit | server/src/plugins/users/models/UserModel.js | JavaScript | unlicense | 5,359 |
/**
* Created by charques on 23/8/16.
*/
'use strict';
var express = require('express');
var router = express.Router();
var User = require(__base + 'app/models/user');
var hash = require(__base + 'app/helpers/crypto');
router.get('/', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
router.get('/:id', function(req, res) {
User.findById(req.params.id, function (err, user) {
if (err) {
throw err;
}
res.json(user);
});
});
router.post('/', function(req, res) {
// TODO validate input
// create a sample user
var user = new User({
email: req.body.email,
password: hash(req.body.password, req.app.get('secret-key')),
admin: req.body.admin
});
//var error = user.validateSync();
// save the sample user
user.save(function(err) {
if (err) {
throw err;
}
console.log('User saved successfully');
res.json({ success: true });
});
});
module.exports = router;
| charques/macrolayer | macrolayer-srv-login/app/controllers/users.js | JavaScript | unlicense | 1,068 |
describe('test', function() {
it('ok', function() {
if (2 + 2 !== 4) throw(new Error('Test failed'))
})
})
;; | sunflowerdeath/broccoli-karma-plugin | test/files/ok.js | JavaScript | unlicense | 113 |
const types = require('recast/lib/types')
const { namedTypes: n, NodePath } = types
const ABORT_EXCEPTION = Symbol('ABORT_EXCEPTION')
/**
* Low-level pre-order (breadth-first) traversal of an AST.
* It invokes `callback` for everything in the AST, not just nodes.
*
* The callback can return false to skip the traversal of the current node's children.
* It can also call `this.abort()` to stop the whole traversal.
*/
function preOrder(ast, callback) {
preOrderTwo(ast, null, function(path1) {
return callback.call(this, path1)
})
}
/**
* Traverses two AST trees and calls `callback` on each pair of paths.
*/
function preOrderTwo(ast1, ast2, callback) {
// https://github.com/benjamn/ast-types/blob/d3b32/lib/path-visitor.js#L126
const root1 = (ast1 instanceof NodePath) ? ast1 : new NodePath({ root: ast1 }).get('root')
const root2 = (ast2 instanceof NodePath) ? ast2 : new NodePath({ root: ast2 }).get('root')
// A queue that keeps pairs of paths to be traversed.
const queue = []
queue.push([root1, root2])
let didAbort = false
const context = {
abort() {
didAbort = true
throw ABORT_EXCEPTION
},
}
while (queue.length > 0) {
const [path1, path2] = queue.shift()
let traverseChildren = true
try {
traverseChildren = callback.call(context, path1, path2)
} finally {
if (didAbort) {
return false // eslint-disable-line no-unsafe-finally
}
}
if (traverseChildren !== false) {
const usedKeys = {}
const appendChildrenPair = (key) => {
if (!usedKeys[key]) {
usedKeys[key] = true
queue.push([path1.get(key), path2.get(key)])
}
}
getChildKeys(path1.value).forEach(appendChildrenPair)
getChildKeys(path2.value).forEach(appendChildrenPair)
}
}
}
/**
* Pre-order traversal with filtering by node type.
*/
function preOrderType(ast, type, callback) {
preOrder(ast, function preOrderTypeVisitor(path) {
if (n[type].check(path.value)) {
return callback.call(this, path)
}
})
}
/**
* Pre-order (breadth-first) traversal of a subtree inside an AST.
*/
function preOrderSubtree(ast, subtree, callback) {
const path = getNodePath(ast, subtree)
preOrderType(path, 'Node', callback)
}
/**
* Get the path of a `subtree` inside an AST.
*/
function getNodePath(ast, node) {
if (node instanceof NodePath) {
return node
}
let nodePath
preOrder(ast, function findSubtreePathVisitor(path) {
if (path.value === node) {
nodePath = path
this.abort()
}
})
return nodePath
}
/**
* Get keys for children of a value in an AST. The "value" could be anything
* inside the AST (e.g. node, array, etc).
*/
function getChildKeys(value) {
if (!value || typeof value !== 'object') {
return []
}
if (Array.isArray(value)) {
return value.map((_, i) => i)
} else {
return types.getFieldNames(value)
}
}
module.exports = {
preOrder, preOrderTwo, preOrderType, preOrderSubtree,
getNodePath,
getChildKeys,
}
| mdebbar/reshift | src/ast-traverse.js | JavaScript | unlicense | 3,055 |
var _ = require("/lib/underscore");
function ActionBar (options, btnText) {
options = (options) ? options : {};
var title = (options.title) ? options.title : "";
btnText = btnText || "...";
options = _.extend({
backgroundColor: '#5B7663',
top: 0, left: 0, height: 45, width: Ti.UI.FILL, // fullscreen
}, _.omit(options, "title"));
var self = Ti.UI.createView(options);
self.toggleButton = Ti.UI.createButton({
title: btnText,
borderRadius: 5,
color: '#FFF',
backgroundColor: '#437653',
borderColor: '#1C2920',
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
left: 3, top: 3, bottom: 3, width: 30,
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
verticalAlign: Ti.UI.TEXT_VERTICAL_ALIGNMENT_CENTER
});
self.add(self.toggleButton);
var t = Ti.UI.createLabel({
text: title,
left: 0, right: 0,
color: '#291c1c',
font: {fontSize: 24, fontFamily: 'Verdana', fontStyle: 'normal'},
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
});
self.add(t);
return self;
}
module.exports = ActionBar; | rcelha/x360achievements2 | Resources/ui/ActionBar.js | JavaScript | unlicense | 1,018 |
$('#buscador').on("input", function() {
var dInput = this.value;
console.log("res es",dInput);
}); | dsaqp1516g4/www | js/buscador.js | JavaScript | apache-2.0 | 109 |
import { blue6, gold6, grey7, grey9, red6 } from "./colors";
/*
SIZES
*/
export const FONT_SIZE_DEFAULT = "14px";
export const FONT_SIZE_LARGE = "16px";
export const FONT_SIZE_SMALL = "12px";
/*
WEIGHTS
*/
export const FONT_WEIGHT_DEFAULT = 300;
export const FONT_WEIGHT_HEAVY = 500;
/*
COLOURS
*/
export const FONT_COLOR_DEFAULT = grey9;
export const FONT_COLOR_MUTED = grey7;
export const FONT_COLOR_PRIMARY = blue6;
export const FONT_COLOR_INFO = blue6;
export const FONT_COLOR_ERROR = red6;
export const FONT_COLOR_WARNING = gold6;
/*
FONT FAMILIES
*/
export const ANT_DESIGN_FONT_FAMILY = `-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif`;
| phac-nml/irida | src/main/webapp/resources/js/styles/fonts.js | JavaScript | apache-2.0 | 727 |
import '@polymer/polymer/polymer-legacy.js';
import {PolymerElement} from '@polymer/polymer/polymer-element.js';
import Dexie from 'dexie';
import EtoolsAjaxRequestMixin from '../etools-ajax-request-mixin.js';
// set logging level
window.EtoolsLogsLevel = window.EtoolsLogsLevel || 'INFO';
// custom dexie db that will be used by etoolsAjax
var etoolsCustomDexieDb = new Dexie('etoolsAjax2DexieDb');
etoolsCustomDexieDb.version(1).stores({
listsExpireMapTable: "&name, expire",
ajaxDefaultDataTable: "&cacheKey, data, expire",
countries: "&id, name"
});
// configure app dexie db to be used for caching
window.EtoolsRequestCacheDb = etoolsCustomDexieDb;
class DirectAjaxCalls extends EtoolsAjaxRequestMixin(PolymerElement) {
static get is() {
return 'direct-ajax-calls';
}
ready() {
super.ready();
// console.log(this.etoolsAjaxCacheDb);
this._setCookie();
this.get_WithNoCache();
// this.get_WithCacheToDefaultTable();
// this.get_WithCacheToSpecifiedTable();
this.post_Json();
this.patch_WithJsonContent();
this.patch_WithCsrfCheck();
this.patch_WithAdditionalHeaders();
// this.post_WithMultipartData();
}
post_Json() {
this.sendRequest({
method: 'DELETE',
endpoint: {
url: 'http://httpbin.org/delete',
},
body: {
id: "14",
firstName: "JaneTEST",
lastName: "DoeTest"
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithJsonContent() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithNoCache() {
this.sendRequest({
endpoint: {
url: 'http://httpbin.org/get',
},
params: {
id: 10,
name: 'Georgia'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
this.sendRequest({
endpoint: {
url: 'http://httpbin.org/status/403',
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithCacheToDefaultTable() {
this.sendRequest({
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/countries-data',
exp: 5 * 60 * 1000, // cache set for 5m
cachingKey: 'countries',
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithCacheToSpecifiedTable() {
this.sendRequest({
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/countries-data',
exp: 5 * 60 * 1000, // cache set for 5m
cacheTableName: 'countries'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithCsrfCheck() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
},
csrfCheck: true
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithAdditionalHeaders() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
},
headers: {
'Authorization': 'Bearer lt8fnG9CNmLmsmRX8LTp0pVeJqkccEceXfNM8s_f624'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
post_WithMultipartData() {
this.sendRequest({
method: 'POST',
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/handle-post-put-delete-data',
},
body: this._getBodyWithBlobsOrFilesData(),
multiPart: true,
prepareMultipartData: true
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
_setCookie() {
// set cookie
var cookieVal = 'someCookieValue123';
var d = new Date();
d.setTime(d.getTime() + (1 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString(); // cookie will expire in 1 hour
document.cookie = "csrftoken=" + cookieVal + "; " + expires + "; path=/";
}
// just a body object that will be used by EtoolsAjaxRequestMixin to prepare multipart body data of request
// to fit etools app needs, on backend there must be a custom parser for this data
_getBodyWithBlobsOrFilesData() {
return {
id: "13",
firstName: "John",
lastName: "Doe",
testObj: {
id: 1,
name: 'testing'
},
testArr: [
{
id: 2,
name: 'testing 2',
someArray: [1, 3],
dummyData: {
test: [1, 2, 3, function () {
var content = '<a id="id1"><b id="b">hey you 1!</b></a>';
return new Blob([content], {type: "text/xml"});
}()],
dummyDataChild: {
id: 1,
id_2: [
{
file: function () {
var content = '<a id="id2"><b id="b">hey you 2!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
}
],
randomObject: {
partner: 1,
agreement: 2,
assessment: function () {
var content = '<a id="id3"><b id="b">hey you 3!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
}
}
}
},
1, 2, 3, 4, 5,
function () {
var content = '<a id="someId"><b id="b">hey you!</b></a>';
return new Blob([content], {type: "text/xml"});
}(),
],
testArr2: [],
someFile: function () {
var content = '<a id="a"><b id="b">hey!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
};
}
}
customElements.define(DirectAjaxCalls.is, DirectAjaxCalls);
| unicef-polymer/etools-ajax | demo/direct-etools-ajax-requests.js | JavaScript | apache-2.0 | 6,501 |
/* Copyright 2016 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
animationStarted,
DEFAULT_SCALE,
DEFAULT_SCALE_VALUE,
MAX_SCALE,
MIN_SCALE,
noContextMenuHandler,
} from "./ui_utils.js";
const PAGE_NUMBER_LOADING_INDICATOR = "visiblePageIsLoading";
// Keep the two values below up-to-date with the values in `web/viewer.css`:
const SCALE_SELECT_CONTAINER_WIDTH = 140; // px
const SCALE_SELECT_WIDTH = 162; // px
/**
* @typedef {Object} ToolbarOptions
* @property {HTMLDivElement} container - Container for the secondary toolbar.
* @property {HTMLSpanElement} numPages - Label that contains number of pages.
* @property {HTMLInputElement} pageNumber - Control for display and user input
* of the current page number.
* @property {HTMLSpanElement} scaleSelectContainer - Container where scale
* controls are placed. The width is adjusted on UI initialization.
* @property {HTMLSelectElement} scaleSelect - Scale selection control.
* @property {HTMLOptionElement} customScaleOption - The item used to display
* a non-predefined scale.
* @property {HTMLButtonElement} previous - Button to go to the previous page.
* @property {HTMLButtonElement} next - Button to go to the next page.
* @property {HTMLButtonElement} zoomIn - Button to zoom in the pages.
* @property {HTMLButtonElement} zoomOut - Button to zoom out the pages.
* @property {HTMLButtonElement} viewFind - Button to open find bar.
* @property {HTMLButtonElement} openFile - Button to open a new document.
* @property {HTMLButtonElement} presentationModeButton - Button to switch to
* presentation mode.
* @property {HTMLButtonElement} download - Button to download the document.
* @property {HTMLAElement} viewBookmark - Element to link current url of
* the page view.
*/
class Toolbar {
/**
* @param {ToolbarOptions} options
* @param {EventBus} eventBus
* @param {IL10n} l10n - Localization service.
*/
constructor(options, eventBus, l10n) {
this.toolbar = options.container;
this.eventBus = eventBus;
this.l10n = l10n;
this.buttons = [
{ element: options.previous, eventName: "previouspage" },
{ element: options.next, eventName: "nextpage" },
{ element: options.zoomIn, eventName: "zoomin" },
{ element: options.zoomOut, eventName: "zoomout" },
{ element: options.openFile, eventName: "openfile" },
{ element: options.print, eventName: "print" },
{
element: options.presentationModeButton,
eventName: "presentationmode",
},
{ element: options.download, eventName: "download" },
{ element: options.viewBookmark, eventName: null },
];
this.items = {
numPages: options.numPages,
pageNumber: options.pageNumber,
scaleSelectContainer: options.scaleSelectContainer,
scaleSelect: options.scaleSelect,
customScaleOption: options.customScaleOption,
previous: options.previous,
next: options.next,
zoomIn: options.zoomIn,
zoomOut: options.zoomOut,
};
this._wasLocalized = false;
this.reset();
// Bind the event listeners for click and various other actions.
this._bindListeners();
}
setPageNumber(pageNumber, pageLabel) {
this.pageNumber = pageNumber;
this.pageLabel = pageLabel;
this._updateUIState(false);
}
setPagesCount(pagesCount, hasPageLabels) {
this.pagesCount = pagesCount;
this.hasPageLabels = hasPageLabels;
this._updateUIState(true);
}
setPageScale(pageScaleValue, pageScale) {
this.pageScaleValue = (pageScaleValue || pageScale).toString();
this.pageScale = pageScale;
this._updateUIState(false);
}
reset() {
this.pageNumber = 0;
this.pageLabel = null;
this.hasPageLabels = false;
this.pagesCount = 0;
this.pageScaleValue = DEFAULT_SCALE_VALUE;
this.pageScale = DEFAULT_SCALE;
this._updateUIState(true);
this.updateLoadingIndicatorState();
}
_bindListeners() {
const { pageNumber, scaleSelect } = this.items;
const self = this;
// The buttons within the toolbar.
for (const { element, eventName } of this.buttons) {
element.addEventListener("click", evt => {
if (eventName !== null) {
this.eventBus.dispatch(eventName, { source: this });
}
});
}
// The non-button elements within the toolbar.
pageNumber.addEventListener("click", function () {
this.select();
});
pageNumber.addEventListener("change", function () {
self.eventBus.dispatch("pagenumberchanged", {
source: self,
value: this.value,
});
});
scaleSelect.addEventListener("change", function () {
if (this.value === "custom") {
return;
}
self.eventBus.dispatch("scalechanged", {
source: self,
value: this.value,
});
});
// Suppress context menus for some controls.
scaleSelect.oncontextmenu = noContextMenuHandler;
this.eventBus._on("localized", () => {
this._wasLocalized = true;
this._adjustScaleWidth();
this._updateUIState(true);
});
}
_updateUIState(resetNumPages = false) {
if (!this._wasLocalized) {
// Don't update the UI state until we localize the toolbar.
return;
}
const { pageNumber, pagesCount, pageScaleValue, pageScale, items } = this;
if (resetNumPages) {
if (this.hasPageLabels) {
items.pageNumber.type = "text";
} else {
items.pageNumber.type = "number";
this.l10n.get("of_pages", { pagesCount }).then(msg => {
items.numPages.textContent = msg;
});
}
items.pageNumber.max = pagesCount;
}
if (this.hasPageLabels) {
items.pageNumber.value = this.pageLabel;
this.l10n.get("page_of_pages", { pageNumber, pagesCount }).then(msg => {
items.numPages.textContent = msg;
});
} else {
items.pageNumber.value = pageNumber;
}
items.previous.disabled = pageNumber <= 1;
items.next.disabled = pageNumber >= pagesCount;
items.zoomOut.disabled = pageScale <= MIN_SCALE;
items.zoomIn.disabled = pageScale >= MAX_SCALE;
this.l10n
.get("page_scale_percent", { scale: Math.round(pageScale * 10000) / 100 })
.then(msg => {
let predefinedValueFound = false;
for (const option of items.scaleSelect.options) {
if (option.value !== pageScaleValue) {
option.selected = false;
continue;
}
option.selected = true;
predefinedValueFound = true;
}
if (!predefinedValueFound) {
items.customScaleOption.textContent = msg;
items.customScaleOption.selected = true;
}
});
}
updateLoadingIndicatorState(loading = false) {
const pageNumberInput = this.items.pageNumber;
pageNumberInput.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading);
}
/**
* Increase the width of the zoom dropdown DOM element if, and only if, it's
* too narrow to fit the *longest* of the localized strings.
* @private
*/
async _adjustScaleWidth() {
const { items, l10n } = this;
const predefinedValuesPromise = Promise.all([
l10n.get("page_scale_auto"),
l10n.get("page_scale_actual"),
l10n.get("page_scale_fit"),
l10n.get("page_scale_width"),
]);
// The temporary canvas is used to measure text length in the DOM.
let canvas = document.createElement("canvas");
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("MOZCENTRAL || GENERIC")
) {
canvas.mozOpaque = true;
}
let ctx = canvas.getContext("2d", { alpha: false });
await animationStarted;
const { fontSize, fontFamily } = getComputedStyle(items.scaleSelect);
ctx.font = `${fontSize} ${fontFamily}`;
let maxWidth = 0;
for (const predefinedValue of await predefinedValuesPromise) {
const { width } = ctx.measureText(predefinedValue);
if (width > maxWidth) {
maxWidth = width;
}
}
const overflow = SCALE_SELECT_WIDTH - SCALE_SELECT_CONTAINER_WIDTH;
maxWidth += 2 * overflow;
if (maxWidth > SCALE_SELECT_CONTAINER_WIDTH) {
items.scaleSelect.style.width = `${maxWidth + overflow}px`;
items.scaleSelectContainer.style.width = `${maxWidth}px`;
}
// Zeroing the width and height cause Firefox to release graphics resources
// immediately, which can greatly reduce memory consumption.
canvas.width = 0;
canvas.height = 0;
canvas = ctx = null;
}
}
export { Toolbar };
| nawawi/pdf.js | web/toolbar.js | JavaScript | apache-2.0 | 9,112 |
"use strict";
var utils = exports;
var emitter = require('./emitter');
/**
* @returns {window}
*/
utils.getWindow = function () {
return window;
};
/**
*
* @returns {HTMLDocument}
*/
utils.getDocument = function () {
return document;
};
/**
* Get the current x/y position crossbow
* @returns {{x: *, y: *}}
*/
utils.getBrowserScrollPosition = function () {
var $window = exports.getWindow();
var $document = exports.getDocument();
var scrollX;
var scrollY;
var dElement = $document.documentElement;
var dBody = $document.body;
if ($window.pageYOffset !== undefined) {
scrollX = $window.pageXOffset;
scrollY = $window.pageYOffset;
} else {
scrollX = dElement.scrollLeft || dBody.scrollLeft || 0;
scrollY = dElement.scrollTop || dBody.scrollTop || 0;
}
return {
x: scrollX,
y: scrollY
};
};
/**
* @returns {{x: number, y: number}}
*/
utils.getScrollSpace = function () {
var $document = exports.getDocument();
var dElement = $document.documentElement;
var dBody = $document.body;
return {
x: dBody.scrollHeight - dElement.clientWidth,
y: dBody.scrollHeight - dElement.clientHeight
};
};
/**
* Saves scroll position into cookies
*/
utils.saveScrollPosition = function () {
var pos = utils.getBrowserScrollPosition();
pos = [pos.x, pos.y];
utils.getDocument.cookie = "bs_scroll_pos=" + pos.join(",");
};
/**
* Restores scroll position from cookies
*/
utils.restoreScrollPosition = function () {
var pos = utils.getDocument().cookie.replace(/(?:(?:^|.*;\s*)bs_scroll_pos\s*\=\s*([^;]*).*$)|^.*$/, "$1").split(",");
utils.getWindow().scrollTo(pos[0], pos[1]);
};
/**
* @param tagName
* @param elem
* @returns {*|number}
*/
utils.getElementIndex = function (tagName, elem) {
var allElems = utils.getDocument().getElementsByTagName(tagName);
return Array.prototype.indexOf.call(allElems, elem);
};
/**
* Force Change event on radio & checkboxes (IE)
*/
utils.forceChange = function (elem) {
elem.blur();
elem.focus();
};
/**
* @param elem
* @returns {{tagName: (elem.tagName|*), index: *}}
*/
utils.getElementData = function (elem) {
var tagName = elem.tagName;
var index = utils.getElementIndex(tagName, elem);
return {
tagName: tagName,
index: index
};
};
/**
* @param {string} tagName
* @param {number} index
*/
utils.getSingleElement = function (tagName, index) {
var elems = utils.getDocument().getElementsByTagName(tagName);
return elems[index];
};
/**
* Get the body element
*/
utils.getBody = function () {
return utils.getDocument().getElementsByTagName("body")[0];
};
/**
* @param {{x: number, y: number}} pos
*/
utils.setScroll = function (pos) {
utils.getWindow().scrollTo(pos.x, pos.y);
};
/**
* Hard reload
*/
utils.reloadBrowser = function () {
emitter.emit("browser:hardReload");
utils.getWindow().location.reload(true);
};
/**
* Foreach polyfill
* @param coll
* @param fn
*/
utils.forEach = function (coll, fn) {
for (var i = 0, n = coll.length; i < n; i += 1) {
fn(coll[i], i, coll);
}
};
/**
* Are we dealing with old IE?
* @returns {boolean}
*/
utils.isOldIe = function () {
return typeof utils.getWindow().attachEvent !== "undefined";
};
| BrowserSync/browser-sync-core | client/lib/browser.utils.js | JavaScript | apache-2.0 | 3,359 |
var dynode = exports;
dynode.Client = require('./dynode/client').Client;
dynode.AmazonError = require('./dynode/amazon-error');
var defaultClient;
dynode.auth = function(config) {
defaultClient = new dynode.Client(config);
};
var methods = [
'listTables',
'describeTable',
'createTable',
'deleteTable',
'updateTable',
'putItem',
'updateItem',
'getItem',
'deleteItem',
'query',
'scan',
'batchGetItem',
'batchWriteItem',
'truncate',
'_request'
];
methods.forEach(function (method) {
dynode[method] = function () {
return defaultClient[method].apply(defaultClient, arguments);
};
}); | Wantworthy/dynode | lib/dynode.js | JavaScript | apache-2.0 | 625 |
'use strict';
// Convenient Node cluster setup, which monitors and restarts child processes
// as needed. Creates workers, monitors them, restarts them as needed, and
// manages the flow of event messages between the cluster master and the
// workers.
// We use process.exit() intentionally here
/* eslint no-process-exit: 1 */
const _ = require('underscore');
const cluster = require('cluster');
const events = require('abacus-events');
const vcapenv = require('abacus-vcapenv');
const map = _.map;
const clone = _.clone;
const range = _.range;
// Setup debug log
const debuglog = require('abacus-debug');
const debug = debuglog('abacus-cluster');
const xdebug = debuglog('@x-abacus/cluster');
// Set up an event emitter allowing a cluster to listen to messages from other
// modules and propagate them to the entire cluster
const emitter = events.emitter('abacus-cluster/emitter');
const on = (e, l) => {
emitter.on(e, l);
};
// We're monitoring the health of cluster workers by requiring them to send
// heartbeat messages and monitoring these heartbeats in the cluster master.
// We terminate a worker if it stops sending heartbeats, resulting in a new
// worker getting forked to replace it. The following two times (in ms)
// are used to configure the expected worker heart rate and our monitoring
// interval.
const heartbeatInterval = parseInt(process.env.CLUSTER_HEARTBEAT) || 30000;
const heartMonitorInterval = heartbeatInterval * 2;
// Return true if we're in a cluster master process
const isMaster = () => cluster.isMaster;
// Return true if we're in a cluster worker process
const isWorker = () => cluster.noCluster || cluster.isWorker;
// Return the current worker id
const wid = () => cluster.worker ? cluster.worker.id : 0;
// Configure the number of workers to use in the cluster
// Warning: workers is a mutable variable
let workers = parseInt(process.env.CLUSTER_WORKERS) || 1;
const scale = (w) => {
// Broadcast workers event to all instances of this module
workers = w || parseInt(process.env.CLUSTER_WORKERS) || 1;
debug('Requesting cluster update to %d workers', workers);
emitter.emit('workers', workers);
return workers;
};
// Return the number of workers in the cluster
const size = () => {
return workers;
};
// Configure the cluster to run a single worker
const singleton = () => scale(1);
// Handle event requesting configuration of the number of workers to use
emitter.on('workers', (w) => {
// Warning: mutating variable workers
debug('Updating cluster to %d workers', w);
workers = w;
});
// Monitor a worker process and emit its messages to the emitter listeners
const monitor = (worker) => {
// Give the worker an initial heartbeat, as we don't want to erroneously
// terminate it just after we've forked it if we hit our heart monitoring
// cutoff before that worker gets a chance to report its heartbeat
worker.heartbeat = Date.now();
worker.on('message', (m) => {
const msg = clone(m);
// Record a worker heartbeat message in the worker, we're monitoring
// these messages in our worker heart monitor function
// Warning: mutating variable worker, but that's the simplest thing to
// do here
if(msg.heartbeat)
worker.heartbeat = msg.heartbeat;
// Store worker information in the message so any listener that's interested
// can determine which worker the message is coming from
msg.worker = {
id: worker.id,
process: {
pid: worker.process.pid
}
};
xdebug('Cluster master got message from worker %o', msg);
emitter.emit('message', msg);
});
};
// Fork a number of workers, configurable with a default of 1
const fork = () => {
debug('Forking %d cluster workers', workers);
map(range(workers), () => monitor(cluster.fork()));
};
// Handle process signals
const signals = (t, cleanupcb) => {
process.on('SIGINT', () => {
debug('%s interrupted', t);
cleanupcb(() => process.exit(0));
});
process.on('SIGTERM', () => {
debug('%s terminated', t);
cleanupcb(() => process.exit(0));
process.exit(0);
});
if(process.env.HEAPDUMP) {
// Trigger heapdumps
process.on('SIGWINCH', () => {
if(global.gc) {
debug('%s gc\'ing');
global.gc();
}
});
// Save heapdumps
require('heapdump');
}
process.on('exit', (code) => {
if(code !== 0)
debug('Cluster %s exiting with code %d', t, code);
else
debug('Cluster %s exiting', t);
emitter.emit('log', {
category: 'cluster',
event: 'exiting',
type: t,
pid: process.pid,
code: code
});
});
};
// A simple worker heart monitor, which regularly checks if workers have
// reported a heartbeat and terminates them if they haven't
const heartMonitor = () => {
const cutoff = Date.now() - heartMonitorInterval;
map(cluster.workers, (worker) => {
// Disconnect worker if it failed to report a heartbeat within the
// last monitoring interval
if(worker.heartbeat < cutoff) {
debug('Cluster worker %d didn\'t report heartbeat, disconnecting it',
worker.process.pid);
worker.disconnect();
}
});
};
// Setup a Node cluster master process
const master = () => {
debug('Cluster master started');
emitter.emit('log', {
category: 'cluster',
event: 'started',
type: 'master',
pid: process.pid
});
// Monitor the heartbeats of our workers at regular intervals
const i = setInterval(heartMonitor, heartMonitorInterval);
if(i.unref) i.unref();
// Set the master process title
process.title = 'node ' +
(process.env.TITLE || [vcapenv.appname(), vcapenv.appindex()].join('-')) +
' master';
// Handle process signals
signals('master', (exitcb) => {
// Terminate the workers
// Let the master process exit
exitcb();
});
// Restart worker on disconnect unless it's marked with a noretry flag
cluster.on('disconnect', (worker) => {
debug('Cluster worker %d disconnected', worker.process.pid);
if(!worker.noretry)
monitor(cluster.fork());
});
cluster.on('exit', (worker, code, signal) => {
debug('Cluster worker %d exited with code %d', worker.process.pid, code);
});
// Handle messages from worker servers
emitter.on('message', (msg) => {
if(msg.server) {
if(msg.server.noretry) {
debug('Cluster worker %d reported fatal error', msg.worker.process
.pid);
// Mark worker with a noretry flag if it requested it, typically to
// avoid infinite retries when the worker has determined that retrying
// would fail again anyway
// Warning: mutating worker variable here
cluster.workers[msg.worker.id].noretry = true;
}
if(msg.server.listening)
debug('Cluster worker %d listening on %d',
msg.worker.process.pid, msg.server.listening);
if(msg.server.exiting) debug('Cluster worker %d exiting', msg.worker
.process.pid);
}
});
};
// Setup a Node cluster worker process
const worker = () => {
debug('Cluster worker started');
emitter.emit('log', {
category: 'cluster',
event: 'started',
type: 'worker',
pid: process.pid
});
// Set the worker process title
process.title = 'node ' +
(process.env.TITLE || [vcapenv.appname(), vcapenv.appindex()].join('-')) +
' worker';
// Handle process signals
signals('worker', (exitcb) => {
// Let the process exit
exitcb();
});
// Send a heartbeat message to the master at regular intervals
// If the worker fails to send a heartbeat, well, we know it's not going
// well and the master will terminate it
const heartbeatReporter = setInterval(() => {
process.send({
heartbeat: Date.now()
});
}, heartbeatInterval);
// Shutdown the heartbeat reporter when the worker is getting disconnected
process.on('disconnect', () => {
clearInterval(heartbeatReporter);
});
// Emit messages from the master to the emitter listeners
process.on('message', (msg) => {
emitter.emit('message', msg);
});
};
// Configure a server for clustering
const clusterify = (server) => {
// Optionally disable clustering to help debugging and profiling
if(process.env.CLUSTER === 'false') {
cluster.noCluster = true;
// Handle process signals
signals('worker', (exitcb) => {
// Let the process exit
exitcb();
});
return server;
}
if(cluster.isMaster) {
// Setup the master process
master();
// Monkey patch the listen function, as in the master we want to fork
// worker processes instead of actually listening
if(server.listen)
server.listen = fork;
}
// Setup a worker process
else worker();
return server;
};
// Process messages from other modules
const onMessage = (msg) => {
xdebug('Got message in onMessage %o', msg);
if(cluster.isWorker) {
// In a worker process, send message to the master
xdebug('Cluster worker sending message to master %o', msg);
process.send(msg);
}
else {
// In the master process, send message to all the workers
const mmsg = clone(msg);
mmsg.master = process.pid;
map(cluster.workers, (worker) => {
xdebug('Cluster master sending message to worker %d %o', worker.process
.pid, mmsg);
worker.send(mmsg);
});
}
};
// Stitch the debug and cluster emitters and listeners together to make debug
// config messages flow from workers to master and back to workers and
// broadcast the log config across the cluster
// Let the debug module send messages to the cluster master
debuglog.on('message', onMessage);
// Pass cluster messages to the debug module
emitter.on('message', debuglog.onMessage);
// Export our public functions
module.exports = clusterify;
module.exports.onMessage = onMessage;
module.exports.on = on;
module.exports.isWorker = isWorker;
module.exports.isMaster = isMaster;
module.exports.scale = scale;
module.exports.singleton = singleton;
module.exports.size = size;
module.exports.wid = wid;
| sasrin/cf-abacus | lib/utils/cluster/src/index.js | JavaScript | apache-2.0 | 10,064 |
export { default as withGuardian } from './withGuardian'
export const holder = 1
| mydearxym/mastani | src/hoc/index.js | JavaScript | apache-2.0 | 81 |
cc.Class({
extends: cc.Component,
properties: {
self: {
default: null, type: cc.Button
},
other1: {
default: null, type: cc.Button
},
other2: {
default: null, type: cc.Button
},
},
// called every frame, uncomment this function to activate update callback
shifter: function () {
this.self.interactable = false;
this.other1.interactable = true;
this.other2.interactable = true;
},
});
| lllyasviel/style2paints | V3/client/assets/script/toggleBTN.js | JavaScript | apache-2.0 | 518 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const {assert} = require('chai');
const {describe, it} = require('mocha');
const {AutoMlClient} = require('@google-cloud/automl').v1beta1;
const cp = require('child_process');
const DELETE_MODEL_REGION_TAG = 'beta/delete-model.js';
const LOCATION = 'us-central1';
describe('Automl Delete Model Tests', () => {
const client = new AutoMlClient();
it('should delete a model', async () => {
// As model creation can take many hours, instead try to delete a
// nonexistent model and confirm that the model was not found, but other
// elements of the request were valid.
const projectId = await client.getProjectId();
const args = [
DELETE_MODEL_REGION_TAG,
projectId,
LOCATION,
'TRL0000000000000000000',
];
const output = cp.spawnSync('node', args, {encoding: 'utf8'});
assert.match(output.stderr, /NOT_FOUND/);
assert.match(output.stderr, /The model does not exist./);
});
});
| googleapis/nodejs-automl | samples/test/delete-model.beta.test.js | JavaScript | apache-2.0 | 1,548 |
// @autogenerated:start:ti.cloud.html_it-helloacs
//var html_it-helloacs = require("ti.cloud.html_it-helloacs");
// @autogenerated:end:ti.cloud.html_it-helloacs
// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};
Alloy.Globals.service = require("ti.cloud.html_it-helloacs");
| alessioricco/html_it-helloacs | app/alloy.js | JavaScript | apache-2.0 | 755 |
//>>built
define("dojox/editor/plugins/nls/it/Blockquote",{blockquote:"Blockquote"});
//# sourceMappingURL=Blockquote.js.map | Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dojox/editor/plugins/nls/it/Blockquote.js | JavaScript | apache-2.0 | 124 |
var respecConfig = {
specStatus: "ED",
editors: [{
name: "Simon Cox",
company: "CSIRO",
companyURL: "http://www.csiro.au/",
w3cid: 1796
}],
otherLinks: [{
key: "Contributors",
data: [
{ value: "Peter Brenton" },
]
}],
shortName: "vocab-project",
edDraftURI: "http://dr-shorthair.github.io/project-ont/docs/",
// wg: "Data eXchange Working Group",
// wgURI: "https://www.w3.org/2017/dxwg/",
// wgPublicList: "public-dxwg-comments",
// wgPatentURI: "https://www.w3.org/2004/01/pp-impl/75471/status",
noRecTrack: true,
overrideCopyright: "<p class='copyright'><a href='https://www.w3.org/Consortium/Legal/ipr-notice#Copyright'>Copyright</a> © 2017 <a href='http://www.csiro.au'><abbr title='Commonwealth Scientific and Industrial Organisation'>CSIRO</abbr></a> & <a href='https://www.w3.org/'> <abbr title='World Wide Web Consortium'>W3C</abbr> </a><sup>®</sup> , <abbr title='World Wide Web Consortium'>W3C</abbr> <a href='https://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer'>liability</a>, <a href='https://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks'>trademark</a> and <a href='https://www.w3.org/Consortium/Legal/copyright-documents'>document use</a> rules apply.</p>",
localBiblio: {
"schema-org":{
href:"https://schema.org/",
title:"Schema.org"
},
"dbpedia-ont":{
href:"http://dbpedia.org/ontology/",
title:"DBPedia ontology"
},
"doap":{
href:"https://github.com/ewilderj/doap/wiki",
title:"Description of a Project",
authors: ["Edd Wilder-James"]
},
"frapo":{
href:"http://www.sparontologies.net/ontologies/frapo",
title:"FRAPO, the Funding, Research Administration and Projects Ontology",
authors: ["David Shotton"],
date: "04 September 2017"
},
"obo":{
href:"http://www.obofoundry.org/",
title:"The OBO Foundry"
},
"pdo":{
href:"http://vocab.deri.ie/pdo",
title:"Project Documents Ontology",
authors: ["Pradeep Varma"],
date: "09 July 2010"
},
"vivo-isf":{
href:"http://github.com/vivo-isf/vivo-isf",
title:"VIVO-ISF Data Standard"
}
},
issueBase: "https://github.com/dr-shorthair/project-ont/issues"
};
| dr-shorthair/ont | docs/projconfig.js | JavaScript | apache-2.0 | 2,270 |
import {LogManager} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {Router} from 'aurelia-router';
import {Configure} from 'aurelia-configuration';
import 'fetch';
import {Authentication} from './authentication';
let logger = LogManager.getLogger('openbelapi-client');
export class OpenbelApiClient {
client;
openbelApiUrl;
static inject = [Authentication, Router, Configure];
constructor(auth, router, config) {
this.auth = auth;
this.router = router;
this.config = config;
this.selectedOpenbelApiUrl = this.getApiUrl();
this.client = this.configureClient(this.selectedOpenbelApiUrl);
}
configureClient(selectedOpenbelApiUrl){
let self = this;
let client = new HttpClient().configure(config => {
config
.withBaseUrl(selectedOpenbelApiUrl.api)
.withDefaults({
credentials: 'same-origin',
headers: {
'Accept': 'application/hal+json',
'X-Requested-With': 'Fetch'
}
})
.rejectErrorResponses()
.withInterceptor({
request(req) {
logger.debug(`Requesting ${req.method} ${req.url}`);
// If id_token exists as a query param - save it
// TODO - rework this to check for id_token first
// TODO - update the location directly instead of redirecting in Aurelia
let urlParams = location.href.split(/[?&#]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
let token = self.auth.getToken();
req.headers.append('Authorization', 'Bearer ' + token);
return req; // you can return a modified Request, or you can short-circuit the request by returning a Response
},
response(resp) {
logger.debug(`Received ${resp.status} ${resp.url}`);
if (resp.status === 401) {
let rejection = Promise.reject(resp);
return rejection;
}
return resp; // you can return a modified Response
},
responseError(resp) {
if (resp.status === 401) {
logger.info('Backend returned HTTP 401, redirecting to loginUrl.');
// window.location.href = window.location.origin;
self.auth.authenticate(window.location.protocol, window.location.host, window.location.pathname, window.location.hash);
}
logger.debug(`Received ${resp.status} ${resp.url}`);
let rejection = Promise.reject(resp);
return rejection;
}
});
});
return client;
}
getApiUrl() {
let openbelApiUrls = this.config.get('openbelApiUrls');
let selectedOpenbelApiUrl = JSON.parse(localStorage.getItem('selectedAPI'));
if (! selectedOpenbelApiUrl) {
localStorage.setItem('selectedAPI', JSON.stringify(openbelApiUrls[0]));
return openbelApiUrls[0];
}
return selectedOpenbelApiUrl;
}
}
| OpenBEL/belmgr | plugin/src/resources/openbelapi-client.js | JavaScript | apache-2.0 | 3,666 |
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
angular.module('mm.core.login')
/**
* Controller to handle input of user credentials.
*
* @module mm.core.login
* @ngdoc controller
* @name mmLoginCredentialsCtrl
*/
.controller('mmLoginCredentialsCtrl', function($scope, $stateParams, $mmSitesManager, $mmUtil, $ionicHistory, $mmApp,
$q, $mmLoginHelper, $mmContentLinksDelegate, $mmContentLinksHelper, $translate) {
$scope.siteurl = $stateParams.siteurl;
$scope.credentials = {
username: $stateParams.username,
password: $stateParams.password
};
$scope.siteChecked = false;
var urlToOpen = $stateParams.urltoopen,
siteConfig = $stateParams.siteconfig;
treatSiteConfig(siteConfig);
// Function to check if a site uses local_mobile, requires SSO login, etc.
// This should be used only if a fixed URL is set, otherwise this check is already performed in mmLoginSiteCtrl.
function checkSite(siteurl) {
// If the site is configured with http:// protocol we force that one, otherwise we use default mode.
var checkmodal = $mmUtil.showModalLoading(),
protocol = siteurl.indexOf('http://') === 0 ? 'http://' : undefined;
return $mmSitesManager.checkSite(siteurl, protocol).then(function(result) {
$scope.siteChecked = true;
$scope.siteurl = result.siteurl;
treatSiteConfig(result.config);
if (result && result.warning) {
$mmUtil.showErrorModal(result.warning, true, 4000);
}
if ($mmLoginHelper.isSSOLoginNeeded(result.code)) {
// SSO. User needs to authenticate in a browser.
$scope.isBrowserSSO = true;
// Check that there's no SSO authentication ongoing and the view hasn't changed.
if (!$mmApp.isSSOAuthenticationOngoing() && !$scope.$$destroyed) {
$mmLoginHelper.confirmAndOpenBrowserForSSOLogin(
result.siteurl, result.code, result.service, result.config && result.config.launchurl);
}
} else {
$scope.isBrowserSSO = false;
}
}).catch(function(error) {
$mmUtil.showErrorModal(error);
return $q.reject();
}).finally(function() {
checkmodal.dismiss();
// $scope.login();
});
}
// Treat the site's config, setting scope variables.
function treatSiteConfig(siteConfig) {
if (siteConfig) {
$scope.sitename = siteConfig.sitename;
$scope.logourl = siteConfig.logourl || siteConfig.compactlogourl;
$scope.authInstructions = siteConfig.authinstructions || $translate.instant('mm.login.loginsteps');
$scope.canSignup = siteConfig.registerauth == 'email' && !$mmLoginHelper.isEmailSignupDisabled(siteConfig);
} else {
$scope.sitename = null;
$scope.logourl = null;
$scope.authInstructions = null;
$scope.canSignup = false;
}
}
if ($mmLoginHelper.isFixedUrlSet()) {
// Fixed URL, we need to check if it uses browser SSO login.
checkSite($scope.siteurl);
} else {
$scope.siteChecked = true;
}
$scope.login = function() {
$mmApp.closeKeyboard();
// Get input data.
var siteurl = $scope.siteurl,
username = $scope.credentials.username,
password = $scope.credentials.password;
if (!$scope.siteChecked) {
// Site wasn't checked (it failed), let's check again.
return checkSite(siteurl).then(function() {
if (!$scope.isBrowserSSO) {
// Site doesn't use browser SSO, throw app's login again.
return $scope.login();
}
});
} else if ($scope.isBrowserSSO) {
// A previous check determined that browser SSO is needed. Let's check again, maybe site was updated.
return checkSite(siteurl);
}
if (!username) {
$mmUtil.showErrorModal('mm.login.usernamerequired', true);
return;
}
if (!password) {
$mmUtil.showErrorModal('mm.login.passwordrequired', true);
return;
}
var modal = $mmUtil.showModalLoading();
// Start the authentication process.
return $mmSitesManager.getUserToken(siteurl, username, password).then(function(data) {
return $mmSitesManager.newSite(data.siteurl, data.token, data.privatetoken).then(function() {
delete $scope.credentials; // Delete username and password from the scope.
$ionicHistory.nextViewOptions({disableBack: true});
if (urlToOpen) {
// There's a content link to open.
return $mmContentLinksDelegate.getActionsFor(urlToOpen, undefined, username).then(function(actions) {
action = $mmContentLinksHelper.getFirstValidAction(actions);
if (action && action.sites.length) {
// Action should only have 1 site because we're filtering by username.
action.action(action.sites[0]);
} else {
return $mmLoginHelper.goToSiteInitialPage();
}
});
} else {
return $mmLoginHelper.goToSiteInitialPage();
}
});
}).catch(function(error) {
$mmLoginHelper.treatUserTokenError(siteurl, error);
}).finally(function() {
modal.dismiss();
});
};
});
| balirwa/logs | www/core/components/login/controllers/credentials.js | JavaScript | apache-2.0 | 6,343 |
const assert = require('assert');
const Promise = require('bluebird');
const moment = require('moment');
const withV4 = require('../support/withV4');
const BucketUtility = require('../../lib/utility/bucket-util');
const checkError = require('../../lib/utility/checkError');
const changeObjectLock = require('../../../../utilities/objectLock-util');
const changeLockPromise = Promise.promisify(changeObjectLock);
const bucketName = 'lockenabledbucket';
const unlockedBucket = 'locknotenabledbucket';
const objectName = 'putobjectretentionobject';
const noRetentionObject = 'objectwithnoretention';
const retainDate = moment().add(1, 'days').toISOString();
const retentionConfig = {
Mode: 'GOVERNANCE',
RetainUntilDate: retainDate,
};
// aws sdk manipulates dates by removing milliseconds
// and converting date strings to date objects
function manipulateDate() {
const noMillis = `${retainDate.slice(0, 19)}.000Z`;
return new Date(noMillis);
}
const expectedConfig = {
Mode: 'GOVERNANCE',
RetainUntilDate: manipulateDate(),
};
const isCEPH = process.env.CI_CEPH !== undefined;
const describeSkipIfCeph = isCEPH ? describe.skip : describe;
describeSkipIfCeph('GET object retention', () => {
withV4(sigCfg => {
const bucketUtil = new BucketUtility('default', sigCfg);
const s3 = bucketUtil.s3;
const otherAccountBucketUtility = new BucketUtility('lisa', {});
const otherAccountS3 = otherAccountBucketUtility.s3;
let versionId;
beforeEach(() => {
process.stdout.write('Putting buckets and objects\n');
return s3.createBucket({
Bucket: bucketName,
ObjectLockEnabledForBucket: true,
}).promise()
.then(() => s3.createBucket({ Bucket: unlockedBucket }).promise())
.then(() => s3.putObject({ Bucket: unlockedBucket, Key: objectName }).promise())
.then(() => s3.putObject({ Bucket: bucketName, Key: noRetentionObject }).promise())
.then(() => s3.putObject({ Bucket: bucketName, Key: objectName }).promise())
.then(res => {
versionId = res.VersionId;
process.stdout.write('Putting object retention\n');
return s3.putObjectRetention({
Bucket: bucketName,
Key: objectName,
Retention: retentionConfig,
}).promise();
})
.catch(err => {
process.stdout.write('Error in beforeEach\n');
throw err;
});
});
afterEach(() => {
process.stdout.write('Removing object lock\n');
return changeLockPromise([{ bucket: bucketName, key: objectName, versionId }], '')
.then(() => {
process.stdout.write('Emptying and deleting buckets\n');
return bucketUtil.empty(bucketName);
})
.then(() => bucketUtil.empty(unlockedBucket))
.then(() => bucketUtil.deleteMany([bucketName, unlockedBucket]))
.catch(err => {
process.stdout.write('Error in afterEach');
throw err;
});
});
it('should return AccessDenied putting retention with another account',
done => {
otherAccountS3.getObjectRetention({
Bucket: bucketName,
Key: objectName,
}, err => {
checkError(err, 'AccessDenied', 403);
done();
});
});
it('should return NoSuchKey error if key does not exist', done => {
s3.getObjectRetention({
Bucket: bucketName,
Key: 'thiskeydoesnotexist',
}, err => {
checkError(err, 'NoSuchKey', 404);
done();
});
});
it('should return NoSuchVersion error if version does not exist', done => {
s3.getObjectRetention({
Bucket: bucketName,
Key: objectName,
VersionId: '000000000000',
}, err => {
checkError(err, 'NoSuchVersion', 404);
done();
});
});
it('should return MethodNotAllowed if object version is delete marker',
done => {
s3.deleteObject({ Bucket: bucketName, Key: objectName }, (err, res) => {
assert.ifError(err);
s3.getObjectRetention({
Bucket: bucketName,
Key: objectName,
VersionId: res.VersionId,
}, err => {
checkError(err, 'MethodNotAllowed', 405);
done();
});
});
});
it('should return InvalidRequest error getting retention to object ' +
'in bucket with no object lock enabled', done => {
s3.getObjectRetention({
Bucket: unlockedBucket,
Key: objectName,
}, err => {
checkError(err, 'InvalidRequest', 400);
done();
});
});
it('should return NoSuchObjectLockConfiguration if no retention set',
done => {
s3.getObjectRetention({
Bucket: bucketName,
Key: noRetentionObject,
}, err => {
checkError(err, 'NoSuchObjectLockConfiguration', 404);
done();
});
});
it('should get object retention', done => {
s3.getObjectRetention({
Bucket: bucketName,
Key: objectName,
}, (err, res) => {
assert.ifError(err);
assert.deepStrictEqual(res.Retention, expectedConfig);
changeObjectLock([
{ bucket: bucketName, key: objectName, versionId }], '', done);
});
});
});
});
| scality/S3 | tests/functional/aws-node-sdk/test/object/getRetention.js | JavaScript | apache-2.0 | 6,001 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.