hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3dc68ff328f7a3f6b4f7313d5c41c4e451dfd632 | 2,798 | js | JavaScript | index.js | vanceleon/authmini | 26386d1b578d1bc02fb7cbc53cfea8b1b36d9a6d | [
"MIT"
] | null | null | null | index.js | vanceleon/authmini | 26386d1b578d1bc02fb7cbc53cfea8b1b36d9a6d | [
"MIT"
] | null | null | null | index.js | vanceleon/authmini | 26386d1b578d1bc02fb7cbc53cfea8b1b36d9a6d | [
"MIT"
] | null | null | null | const express = require("express");
const cors = require("cors");
const bcrypt = require("bcryptjs");
const db = require("./database/dbConfig.js");
const session = require('express-session');
//require your library store
const KnexSessionStore = require('connect-session-knex')(session);
const server = express();
const sessionConfig = {
name: 'monkey', // default is connect.sid
secret: 'nobody tosses a dwarf!',
cookie: {
maxAge: 1 * 24 * 60 * 60 * 1000, // a day
secure: false, // only set cookies over https. Server will not send back a cookie over http.
}, // 1 day in milliseconds
httpOnly: true, // don't let JS code access cookies. Browser extensions run JS code on your browser!
resave: false,
saveUninitialized: false,
store: new KnexSessionStore({
tablename: 'sessions',
sidfieldname: 'sid',
knex: db,
createtable: true,
clearInterval: 1000 * 60 * 60,
}),
};
server.use(session(sessionConfig));
server.use(express.json());
server.use(cors());
server.get("/", (req, res) => {
res.send("Its Alive!");
});
//guidelines for auth
server.post("/api/register", (req, res) => {
//grab credentials
const creds = req.body;
//hash the password, 16 is the time it takes and how many times the password is hashed, 2^n, n=16
const hash = bcrypt.hashSync(creds.password, 16);
//replace the user password with the hash
//TlS secure communication between nodes
//computer > isp > node1 > node 3 > node13 > server
creds.password = hash;
//save the user
db("users")
.insert(creds)
.then(ids => {
const id = ids[0];
res.status(201).json(id);
})
.catch(err => res.status(500).send(err));
//return 201
});
server.post("/api/login", (req, res) => {
//grab the creds
const creds = req.body;
//find the user
db("users")
.where({ username: creds.username })
.first()
.then(user => {
//check creds
if(user && bcrypt.compareSync(creds.password, user.password)) {
res.status(200).send(`Welcome ${req.session.username}`);
}else{
res.status(401).json({message:"You shall not pass!"});
}
})
.catch(err => res.status(500).send(err));
//check the creds
});
server.get('/setname', (req, res) => {
req.session.name = 'Frodo';
res.send('got it');
});
server.get('/greet', (req, res) => {
const name = req.session.name;
res.send(`hello ${req.session.name}`);
});
// protect this route, only authenticated users should see it
server.get("/api/users", (req, res) => {
db("users")
.select("id", "username", "password")
.then(users => {
res.json(users);
})
.catch(err => res.send(err));
});
server.listen(3300, () => console.log("\nrunning on port 3300\n"));
| 26.903846 | 102 | 0.615082 |
3dc6b586cb1d66d68732d372f9982b317402a131 | 377 | js | JavaScript | resources/assets/js/app/modules/member/notification/index.js | VamsiMudunuri/LocalAmbition | 1d2af8657f82e6f572c9adf1e7949a2a604e00c1 | [
"MIT"
] | null | null | null | resources/assets/js/app/modules/member/notification/index.js | VamsiMudunuri/LocalAmbition | 1d2af8657f82e6f572c9adf1e7949a2a604e00c1 | [
"MIT"
] | null | null | null | resources/assets/js/app/modules/member/notification/index.js | VamsiMudunuri/LocalAmbition | 1d2af8657f82e6f572c9adf1e7949a2a604e00c1 | [
"MIT"
] | null | null | null | $(function() {
var $module = $('.member-notification-index');
var $infinite = $module.find('.infinite');
$infinite.infinite_loading({url : $infinite.data('url'), 'id' : 'notification-id', paging: $infinite.data('paging'), 'emptyText' : $infinite.data('empty-text'), 'endingText' : $infinite.data('ending-text'), 'complete' : function(response, lastID){} });
}); | 41.888889 | 256 | 0.644562 |
3dc70a62109089a494ae9016b331e299dc7d4504 | 126 | js | JavaScript | backend/src/server.js | lulukc/projeto_gostack | 0eb3157612b463bd8cbb20db975dd8d0050364ee | [
"MIT"
] | null | null | null | backend/src/server.js | lulukc/projeto_gostack | 0eb3157612b463bd8cbb20db975dd8d0050364ee | [
"MIT"
] | 9 | 2021-03-10T01:02:56.000Z | 2022-02-26T20:58:09.000Z | backend/src/server.js | lulukc/projeto_gostack | 0eb3157612b463bd8cbb20db975dd8d0050364ee | [
"MIT"
] | null | null | null | import app from './app';
const port = 3003;
app.listen(port, () => {
console.log(`Servidor rodando na porta ${port}`);
});
| 18 | 51 | 0.619048 |
3dc7d0c874adf041cb49c439f745a30dfdb134a7 | 81 | js | JavaScript | node_modules/carbon-icons-svelte/lib/BatteryFull32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/BatteryFull32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | node_modules/carbon-icons-svelte/lib/BatteryFull32/index.js | seekersapp2013/new | 1e393c593ad30dc1aa8642703dad69b84bad3992 | [
"MIT"
] | null | null | null | import BatteryFull32 from "./BatteryFull32.svelte";
export default BatteryFull32; | 40.5 | 51 | 0.839506 |
3dc819db02096a5d6b87f79ee2ea3227825c3d2a | 1,011 | js | JavaScript | resources/js/components/teacher/router/index.js | richardordinario/df-lms | 91c017437928201992f1e2a1499db0802393ce13 | [
"MIT"
] | null | null | null | resources/js/components/teacher/router/index.js | richardordinario/df-lms | 91c017437928201992f1e2a1499db0802393ce13 | [
"MIT"
] | null | null | null | resources/js/components/teacher/router/index.js | richardordinario/df-lms | 91c017437928201992f1e2a1499db0802393ce13 | [
"MIT"
] | null | null | null |
import Dashboard from '../pages/Dashboard.vue'
import MyCourses from '../pages/MyCourses.vue'
import MyStudents from '../pages/MyStudents.vue'
import MyAccount from '../pages/MyAccount.vue'
import Middlewares from '../../../middlewares'
export default [
{
path: '/',
redirect: '/dashboard'
},
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: {
middleware: [Middlewares.teacher]
}
},
{
path: '/my-courses',
name: 'My Courses',
component: MyCourses,
meta: {
middleware: [Middlewares.teacher]
}
},
{
path: '/my-students',
name: 'My Students',
component: MyStudents,
meta: {
middleware: [Middlewares.teacher]
}
},
{
path: '/my-account',
name: 'My Account',
component: MyAccount,
meta: {
middleware: [Middlewares.teacher]
}
},
]
| 21.510638 | 48 | 0.513353 |
3dcbca0f7af7c6ae3da9aed9c239167376d89403 | 136 | js | JavaScript | events/ready.js | Kiarea/V12-music | 4b8cd71412dacc64229c1cf58d17f40f9fb3b491 | [
"MIT"
] | null | null | null | events/ready.js | Kiarea/V12-music | 4b8cd71412dacc64229c1cf58d17f40f9fb3b491 | [
"MIT"
] | null | null | null | events/ready.js | Kiarea/V12-music | 4b8cd71412dacc64229c1cf58d17f40f9fb3b491 | [
"MIT"
] | null | null | null | client.on('ready', async () => {
client.user.setStatus('online');
console.log(`${client.user.username} ismiyle discorda bağlandı.`);
})
| 27.2 | 66 | 0.691176 |
3dcd4ce29db3dc8177a18851cd3033c05c0fb72e | 917 | js | JavaScript | node_modules/@styled-icons/icomoon/CoinPound/CoinPound.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | null | null | null | node_modules/@styled-icons/icomoon/CoinPound/CoinPound.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | null | null | null | node_modules/@styled-icons/icomoon/CoinPound/CoinPound.esm.js | chs6558/chs6558.github.io | 32dd0275105d1db5b085d3162126b0e847ec9c16 | [
"MIT"
] | 1 | 2021-05-13T23:13:59.000Z | 2021-05-13T23:13:59.000Z | import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var CoinPound = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 16 16" }, props, { ref: ref }),
React.createElement("path", { d: "M7.5 1a7.5 7.5 0 100 15 7.5 7.5 0 000-15zm0 13.5a6 6 0 110-12 6 6 0 010 12z", key: "k0" }),
React.createElement("path", { d: "M9.5 11H6V9h1.5a.5.5 0 000-1H6v-.5a1.502 1.502 0 012.8-.75.499.499 0 10.865-.501A2.51 2.51 0 007.5 4.999a2.503 2.503 0 00-2.5 2.5v.5h-.5a.5.5 0 000 1H5v3h4.5a.5.5 0 000-1z", key: "k1" })));
});
CoinPound.displayName = 'CoinPound';
export var CoinPoundDimensions = { height: 16, width: 16 };
| 61.133333 | 231 | 0.643402 |
3dcd370cab488ddb09c7b6cfb7599d5c3521d4e8 | 4,248 | js | JavaScript | js/src/session.js | ptejada/ApePubSub | a081098147267d8e3a6403b24567f79db807c30e | [
"MIT"
] | 4 | 2015-02-04T20:08:25.000Z | 2016-01-03T15:00:04.000Z | js/src/session.js | ptejada/ApePubSub | a081098147267d8e3a6403b24567f79db807c30e | [
"MIT"
] | 1 | 2019-01-06T17:04:27.000Z | 2019-01-06T17:04:27.000Z | js/src/session.js | ptejada/ApePubSub | a081098147267d8e3a6403b24567f79db807c30e | [
"MIT"
] | null | null | null | /**
* The session object constructor
*
* @param {APS} client
* @constructor
* @memberOf module:Client~
*/
APS.Session = function(client){
this._client = client;
this._data = {};
this.store = {};
/**
* Gets the current session ID
* @returns {bool|string}
*/
this.getID = function(){
if ( this._client.option.session )
{
return this.store.get('sid');
}
else
{
return this._id;
}
}
/**
* Get the current frequency number
* @returns {*}
*/
this.getFreq = function(){
return this.store.get('freq');
}
/**
* Get the current challenge number
* @returns {*}
*/
this.getChl = function(){
return this.store.get('chl');
}
/**
* Saves all the values required for persistent session
* @private
*/
this.save = function(id){
if ( this._client.option.session )
{
this.store.set('sid', id);
}
else
{
this._id = id;
}
}
/**
* Increments the frequency number by one and saves it
* @private
*/
this.saveFreq = function(){
var current = parseInt(this.store.get('freq') || 0);
this.store.set('freq',++current);
}
/**
* Destroys the session and all its data
* @param {bool} KeepFreq - Flag whether to keep the frequency
* @private
*/
this.destroy = function(KeepFreq){
this.store.remove('sid');
this.store.remove('chl');
if(!KeepFreq)
this.store.set('freq',0);
this._data = {};
}
/**
* Get a value from the session
* @param {string} key - The key of the value to get
* @returns {*}
*/
this.get = function(key){
return this._data[key];
}
/**
* Assign value to a session key
* @param {string} key - The value key, identifier
* @param {*} val - The value to store in session
*/
this.set = function(key, val){
var obj = {};
if ( typeof key == 'object' )
{
obj = key;
}
else
{
obj[key] = val;
}
this._client.sendCmd('SESSION_SET', obj);
this._update(obj);
}
/**
* Used to updates the internal session storage cache _data
* @param updates
* @private
*/
this._update = function(updates){
for ( var key in updates)
{
this._data[key] = updates[key];
}
}
/**
* Restores all the the necessary values from the store to restore a session
* @private
* @returns {*}
*/
this.restore = function(){
var client = this._client;
// Initialize the store object
this.store = new APS.Store(client.identifier + '_');
//Initial frequency value
if( ! this.store.get('freq') ) this.store.set('freq','0');
var sid = this.store.get('sid');
if(typeof sid != "string" || sid.length !== 32){
return false;
}
//Restoring session state == 2
client.state = 2;
// return data
return {sid: sid};
}
}
/**
* A persistent storage object
* @param _prefix the store identifier
* @constructor
* @private
* @memberOf module:Client~
*/
APS.Store = function(_prefix){
if (typeof _prefix == 'undefined' )
{
_prefix = '';
}
if ( 'Storage' in window )
{
// Use the HTML5 storage
/**
* Get a value from the store
* @param key The value key
* @returns {*}
*/
this.get = function(key){
key = _prefix + key;
return localStorage.getItem(key);
}
/**
* Set value to a store key
* @param key The value key
* @param value The key value
*/
this.set = function(key, value){
key = _prefix + key;
localStorage.setItem(key, value);
}
/**
* Removes a key and its value from the store
* @param key
*/
this.remove = function(key){
key = _prefix + key;
localStorage.removeItem(key);
}
}
else
{
// Use cookies as a storage
this.get = function(key){
key = _prefix + key;
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
this.set = function(key, value){
key = _prefix + key;
document.cookie = key+"="+value+"; path=/";
}
this.remove = function(key){
key = _prefix + key;
var date = new Date();
date.setTime(date.getTime()-1);
var expires = "; expires="+date.toGMTString();
document.cookie = key+"= "+expires+"; path=/";
}
}
} | 18.550218 | 77 | 0.596281 |
3db83becfcf3ac60704863e95b3f596dca4403e5 | 752 | js | JavaScript | routes/problem.js | Arthelon/submission | 434dfd6b546593ddb68acb42261c8717e77b82de | [
"MIT"
] | 2 | 2016-03-24T08:58:34.000Z | 2016-05-17T02:52:15.000Z | routes/problem.js | Arthelon/submission | 434dfd6b546593ddb68acb42261c8717e77b82de | [
"MIT"
] | null | null | null | routes/problem.js | Arthelon/submission | 434dfd6b546593ddb68acb42261c8717e77b82de | [
"MIT"
] | 1 | 2022-01-14T08:11:08.000Z | 2022-01-14T08:11:08.000Z | var router = require('express').Router()
var models = require('../models')
var validateRoom = require('../util').clientValidateRoom
router.route('/:room_path')
.get(validateRoom, function (req, res) {
if (req.user) {
res.render('pages/create_prob', {
room_name: req.room.name,
})
} else {
res.redirect('/')
}
})
router.route('/:room_path/:problem')
.get(validateRoom, function (req, res) {
if (req.user) {
res.render('pages/problem', {
title: 'Problem | '+req.params.problem,
prob_name: req.params.problem,
})
} else {
res.redirect('/')
}
})
module.exports = router | 26.857143 | 56 | 0.513298 |
3db4a28cda11d88a0db24622101fdcb5993d7e5b | 1,803 | js | JavaScript | core/client/app/utils/document-title.js | CavHack/Ghost | 8d414880f447a5162f7ec9f05848f2aeb9d3ea17 | [
"MIT"
] | 1 | 2016-08-04T17:20:53.000Z | 2016-08-04T17:20:53.000Z | core/client/app/utils/document-title.js | CavHack/Ghost | 8d414880f447a5162f7ec9f05848f2aeb9d3ea17 | [
"MIT"
] | 2 | 2016-04-29T04:32:26.000Z | 2016-06-01T03:47:59.000Z | core/client/app/utils/document-title.js | CavHack/Ghost | 8d414880f447a5162f7ec9f05848f2aeb9d3ea17 | [
"MIT"
] | 1 | 2017-12-07T10:57:07.000Z | 2017-12-07T10:57:07.000Z | import Ember from 'ember';
export default function () {
Ember.Route.reopen({
// `titleToken` can either be a static string or a function
// that accepts a model object and returns a string (or array
// of strings if there are multiple tokens).
titleToken: null,
// `title` can either be a static string or a function
// that accepts an array of tokens and returns a string
// that will be the document title. The `collectTitleTokens` action
// stops bubbling once a route is encountered that has a `title`
// defined.
title: null,
_actions: {
collectTitleTokens: function (tokens) {
var titleToken = this.titleToken,
finalTitle;
if (typeof this.titleToken === 'function') {
titleToken = this.titleToken(this.currentModel);
}
if (Ember.isArray(titleToken)) {
tokens.unshift.apply(this, titleToken);
} else if (titleToken) {
tokens.unshift(titleToken);
}
if (this.title) {
if (typeof this.title === 'function') {
finalTitle = this.title(tokens);
} else {
finalTitle = this.title;
}
this.router.setTitle(finalTitle);
} else {
return true;
}
}
}
});
Ember.Router.reopen({
updateTitle: Ember.on('didTransition', function () {
this.send('collectTitleTokens', []);
}),
setTitle: function (title) {
window.document.title = title;
}
});
}
| 31.631579 | 75 | 0.494731 |
3daee84047e48403c02a01d7fafeebd91702e18e | 1,085 | js | JavaScript | chrome/phraseapp.js | Vadorequest/PhraseApp-AutoTranslate | d8517a58f84f13756bc11794765ddf39d6a98882 | [
"MIT"
] | 1 | 2016-08-22T09:05:53.000Z | 2016-08-22T09:05:53.000Z | chrome/phraseapp.js | Vadorequest/PhraseApp-AutoTranslate | d8517a58f84f13756bc11794765ddf39d6a98882 | [
"MIT"
] | null | null | null | chrome/phraseapp.js | Vadorequest/PhraseApp-AutoTranslate | d8517a58f84f13756bc11794765ddf39d6a98882 | [
"MIT"
] | null | null | null | // Name of the pck.
PHRASE_APP_PCK = 'PhraseApp';
// Create our own pck to avoid gobals that could interfere with the website.
window[PHRASE_APP_PCK] = {};
// Create shortcut.
holdsport = window[PHRASE_APP_PCK];
// True will display debug messages.
holdsport.DEBUG = false;
holdsport.dev = function(callback){
if(holdsport.DEBUG && callback){
callback();
}
return holdsport.DEBUG;
}
// Auto running once DOM loaded.
$(function(){
var consoleDev = function(content){
holdsport.dev(function(){
console.log(content);
});
}
consoleDev("PhraseApp AutoTranslate processing");
var translationSuggested = $('.translation-suggest');
consoleDev("There are "+translationSuggested.length+" translations detected to to!");
if(translationSuggested.length > 0){
// We are running in a page where we can autoload suggested translations.
for(var i in translationSuggested){
// If the object is clickable, just click on it!
if(translationSuggested[i].click){
translationSuggested[i].click();
consoleDev("Starting auto translate phrase "+i);
}
}
}
}); | 24.659091 | 86 | 0.715207 |
3dc56e8d6f705e88c4e6c805b4fd3a293446c9a9 | 695 | js | JavaScript | app/util/index.js | roby-rodriguez/react-tweets | a51a30001d14efb42241b2454a7d3618d33d6491 | [
"MIT"
] | 1 | 2016-10-06T15:28:56.000Z | 2016-10-06T15:28:56.000Z | app/util/index.js | roby-rodriguez/react-tweets | a51a30001d14efb42241b2454a7d3618d33d6491 | [
"MIT"
] | null | null | null | app/util/index.js | roby-rodriguez/react-tweets | a51a30001d14efb42241b2454a7d3618d33d6491 | [
"MIT"
] | null | null | null | module.exports = {
isEmpty (element) {
return element == null || element == '' || element == 'null' || element == 'undefined'
},
getQuery ({ query, resultType, language, until }) {
const search = {
q: query,
result_type: resultType,
}
if (!this.isEmpty(language)) search.lang = language
if (!this.isEmpty(until)) search.until = until
return search
},
getStreamQuery ({ query, resultType, language, until }) {
const search = {
track: query,
// filter_level: 'medium',
}
if (!this.isEmpty(language)) search.language = language
return search
}
}
| 30.217391 | 94 | 0.536691 |
3da1b407046527195f408ae0107f7bb4535705d3 | 12,603 | js | JavaScript | api/articles.js | Phlen/soccer | f15b8cbb351677be6776c3019eae708f042558df | [
"MIT"
] | 3 | 2017-01-23T02:33:21.000Z | 2017-02-22T06:45:54.000Z | api/articles.js | Phlen/soccer | f15b8cbb351677be6776c3019eae708f042558df | [
"MIT"
] | null | null | null | api/articles.js | Phlen/soccer | f15b8cbb351677be6776c3019eae708f042558df | [
"MIT"
] | null | null | null | let articles = [
{
meta: {
id: "1",
type: "MVP",
belong: "中超",
title: "高拉特颁奖&专访:我的偶像是卡卡;结婚早对事业有帮助",
author: "空调君",
post_time: "10-15 07:30",
communications: "371"
},
list: [
{
type: "TEXT",
content: "北京时间10月13日,懂球帝小编和球迷一行四人来到了燕赵名城石家庄,对获得懂球帝中超第25轮最佳球员的高拉特进行了颁奖和采访。高拉特在与辽足的比赛中完成一射三传,他是怎么评价自己的表现呢,对于中超和中国,他又有着怎样的理解?接下来让我们一起去了解他。"
},
{
type: "IMAGE",
content: "../../images/temp/article/1/1.jpg",
description: "高拉特与采访球迷合照"
},
{
type: "TEXT",
content: "Q:首先恭喜你在第25轮的比赛中获得MVP,请问你有什么获奖感言?\n\nA:我非常开心,更令我开心的是,在赛季快要结束的时候,我还依旧保持着这样的状态。\n\nQ:你在本赛季才是第一次获奖,而你的队友比如郜林、阿兰、于汉超等人都已经获奖过,你们私下对此会有交流吗?\n\nA:我觉得获奖对我来说只是一部分,更重要的今年能保持这样一个好的状态,在进球和助攻上都有斩获,因为我一直对自己有这样的严格要求,我第一年来到这里,表现很出色。但我不会停下脚步,我会要求自己在比赛和训练中都能做得更好。\n\n Q:赛季临近结束,恒大队领跑积分榜,你个人也成为射手榜第一,你觉得自己有信心能拿下这两个奖项吗?\n\nA:我很有信心,但我最想拿到的还是咱们中超的六连冠,拿下中超冠军是最重要的,其次我才会去考虑我个人的荣誉。\n\nQ:所以你觉得是进球更值得开心呢,还是助攻?\n\nA:我认为进球和助攻都是非常令人开心的事情,和辽足的那场比赛,对手踢得也不保守,和我们打对攻。郑龙上场以后表现也很出色,所以让我完成了助攻,杀死了比赛。\n\nQ:有认为自己这个赛季有比上赛季更出色吗?\n\nA:两个赛季不太一样吧,上赛季我个人的能力展现出来了,我今年的数据可能没有去年出色,但我在一些比赛中还是表现很好,我也在关键比赛中进球,帮助球队赢球。当然这一切都离不开我的队友,因为在这样一个团队里,我的个人能力才能发挥到极致。非常感谢他们,和他们在一起踢球很开心。"
},
{
type: "IMAGE",
content: "../../images/temp/article/1/2.jpg"
},
{
type: "TEXT",
content: "Q:你对队友给了极高的评价,对于你的中国队友,你们私下的关系怎么样?\n\nA:我和队友们相处都很融洽,在这个团队里,无论是工作上和业余时间,他们对我都非常好。队友们都是有说有笑,十分和谐。我们外援和本土球员关系都非常好。\n\nQ:那么作为锋线球员,你和你的前场搭档们又有没有一些额外的交流?和哪位队员最默契呢?\n\nA:前段时间,我们刚和郜林去吃了火锅,他请我们几位外援和家属一起,品尝中国的特色食物,我觉得非常开心。我们队是一个人人都互相尊重的集体,没有说谁去命令谁之类的,大家互相都很尊重,这是保证我们有一个好成绩的大环境。\n\nQ:这两个赛季的出色表现,让你成为了许多球迷的偶像。那么你自己的偶像是谁呢?\n\nA:我在足球上追求的偶像是卡卡,我和他风格相似,有影锋的感觉,喜欢前插上到禁区打门,取得进球。当然我也崇拜过罗纳尔迪尼奥,但卡卡是最重要的。\n\nQ:中超联赛目前有几名巴西球员都获得了国家队的征召,你自己是否也有进入国家队的梦想呢?\n\nA:我首先还是要帮助广州队取得更多荣誉,因为广州队给我们提供了这么好的条件,有这么好的训练,这么好的教练。入选国家队的梦想我从未放弃,在做好俱乐部工作的前提下,如果我获得了国家队的召唤,那我一定一如既往为国付出一切。\n\nQ:在中国的巴西外援越来越多,和其他队的外援交往多吗?\n\nA:我们之间的实际来往并不多,因为中国太大了,我们更多的还是生活在各自的城市,但是我们都相互认识,在比赛的时候遇到的话,我们也会互相去到更衣室唠唠嗑,拉拉家常。"
},
{
type: "IMAGE",
content: "../../images/temp/article/1/3.jpg"
},
{
type: "TEXT",
content: "Q:中国对于你来说是一个陌生的国家,当时选择来到这里踢球是有怎样的考虑?\n\nA:我来之前对中国足球有一定的认识,我知道中国足球在一个飞速发展的过程中,联赛水平也非常高,我觉得来中国联赛效力是非常荣幸的。同时,我也通过保隆(曾效力恒大的巴西籍后卫)知道了恒大,知道这是一支体系完善的球队,有着很宏伟的目标,所以我选择来这里。\n\nQ:来了这里之后,觉得中国联赛和巴西联赛的区别大么?\n\nA:现在中国联赛和巴西联赛的差距并不大,因为中国联赛涌入了许多优秀的球员和教练,他们极大提高了中国联赛的水平。在巴西、在南美的影响力也越来越大,那边也会播放我们的中超联赛,包括我的家人朋友都会看,我认为,这是让两国更为紧密的地方。\n\nQ:你刚来中国的时候,不少人从视频、照片上看你有小肚子,会怀疑你的身体状况不好,但其实你的身材非常标准,你怎么看这个事情?\n\nA:其实我的身材一直都是这样,可能电视会把人给拉大,但我本人不是这样。就像你看有的球员很高,但见到真人就不高了,有的看着很瘦,但也不是这样。\n\nQ:你的朋友、前队友会关心中国联赛吗,你是否会推荐他们来中超?\n\nA:巴西人对于中国的印象都是遥远的古老国度。当我来到中国,我也有带我的朋友来中国,让他们了解到中国的先进的发展。包括回去过后,他们也会问我中国是怎样的国家。在我看来,中国目前已经是一个顶尖的国家,非常先进,非常发达,大家都应该多了解这个国家。我也会推荐他们来到中超,就像当时保隆推荐我来恒大一样。\n\nQ:队中最老的郑智36岁了还在广州队踢球,你是否希望也能长期为广州效力?\n\nA:郑智是我绝对的榜样,在这个年龄还能保持这么好的状态是非常不容易的,对我来说是一个榜样,也应该是全体球员的榜样。我个人当然希望能够长期留在广州,但具体的东西还要和俱乐部谈。"
}
]
},
{
meta: {
id: "2",
type: "article",
belong: "",
title: "多特蒙德1-1柏林赫塔,奥巴梅扬失点后破门,双方各一人染红",
author: "颜佳俊",
post_time: "2016-10-15 04:22:10",
communications: "321"
},
list: [
{
type: "VIDEO",
content: "https://o6yh618n9.qnssl.com/Dortmund%201-1%20Berli%CC%81n.mp4",
description: ""
},
{
type: "TEXT",
content: "北京时间10月15日凌晨2:30,德甲第7轮先赛一场,多特蒙德队主场迎战柏林赫塔队。上半场,双方未能改写比分;下半场,施托克推射近角打破僵局,奥巴梅扬点球被扑,随后奥巴梅扬铲射破门将比分扳平,终场前莫尔、施托克染红被罚离场。最终,多特蒙德1-1柏林赫塔。"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/1.jpg"
},
{
type: "TEXT",
content: "开场第6分钟,格策前场分球,普里希奇右路突破下底传中,禁区内莫尔跟上左脚凌空打门,球高出横梁。"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/2.gif"
},
{
type: "TEXT",
content: "第11分钟,普里希奇中线得球长驱直入,连过三人后将球分到禁区左侧,裁判吹哨示意越位。"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/3.gif"
},
{
type: "TEXT",
content: "第16分钟,原口元气左路下底传中,禁区前沿埃斯魏因左脚抽射,球稍稍高出横梁。"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/4.gif"
},
{
type: "TEXT",
content: "第51分钟,柏林赫塔取得领先,魏泽掷出界外球,伊比舍维奇停球后用脚后跟一磕,施托克带球到禁区内推射近角得手,0-1!"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/5.gif"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/6.gif"
},
{
type: "TEXT",
content: "第80分钟,多特蒙德将比分扳平,奥斯曼-登贝莱禁区左侧将球横传,奥巴梅扬倒地铲射将球打进,1-1!"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/7.gif"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/8.gif"
},
{
type: "TEXT",
content: "技术统计:"
},
{
type: "IMAGE",
content: "../../images/temp/article/2/9.jpg"
}
]
},
{
meta: {
id: "5",
type: "article",
belong: "",
title: "中国U19国家队出征亚青赛海报:红日初升,其道大光",
author: "不闯绿灯_侠",
post_time: "2016-10-15 07:49:12",
communications: "321"
},
list: [
{
type: "TEXT",
content: "2016年巴林亚足联U19锦标赛已经打响,北京时间10月16日凌晨00:30,中国U-19国青队的足球小将们将迎来本届亚青赛的首个对手澳大利亚队。赛前,中国之队官方发布了预热海报,主题为:红日初升,其道大光。"
},
{
type: "IMAGE",
content: "../../images/temp/article/5/1.jpg"
},
{
type: "TEXT",
content: "“红日初升,其道大光”出自梁启超的《少年中国说》,在国家队遭遇失利后,国人也希望这群年轻的小伙子们在亚青赛上能用优异的表现让大家看到希望。中国之队官方也对海报做出了注解:“面对澳大利亚和乌兹别克斯坦等实力强劲的小组对手,中国队的出线之路并不轻松。但面对前路艰险,我们的足球小将们总是要义无反顾地前行。就如中国足协中国之队发布的海报——‘红日初升 其道大光’,有明天有光明就会有希望,无论多深沉的黑夜都将迎来远方叩击人心的曙光。”"
}
]
},
{
meta: {
id: "6",
type: "article",
belong: "",
title: "恐怖的威斯特法伦!多特25场主场不败创队史纪录",
author: "Milioti",
post_time: "2016-10-15 06:40:54",
communications: "321"
},
list: [
{
type: "TEXT",
content: "北京时间10月15日凌晨,多特蒙德在主场1-1战平柏林赫塔,多特也创造了一项队史新纪录。"
},
{
type: "IMAGE",
content: "../../images/temp/article/6/1.jpg"
},
{
type: "TEXT",
content: "在凌晨的比赛中多特一度落后,第77分钟奥巴梅扬还罚丢了点球,不过后者在第80分钟接登贝莱助攻为球队扳平了比分。收获了平局的多特已经在德甲中连续25个主场比赛保持不败,这也创造了新的队史纪录。"
}
]
},
{
meta: {
id: "7",
type: "article",
belong: "",
title: "法甲综述:尼斯2-0里昂继续领跑,巴神失点;摩纳哥1-3图卢兹",
author: "Milioti",
post_time: "2016-10-15 05:30:39",
communications: "321"
},
list: [
{
type: "TEXT",
content: "北京时间10月15日凌晨,法甲联赛展开第9轮的比赛。最终联赛第一尼斯2-0击败里昂,巴洛特利在比赛中罚丢点球,图卢兹则在一球落后的情况下3-1逆转击败摩纳哥。"
},
{
type: "TEXT",
content: "【尼斯2-0里昂】"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/1.jpg"
},
{
type: "TEXT",
content: "比赛第5分钟主队就取得领先,萨尔在底线附近头球回做,拜斯在中路轻松破门。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/2.gif"
},
{
type: "TEXT",
content: "比赛第28分钟里昂中场大将费基尔因为恶意犯规被直接红牌罚下。比赛第76分钟尼斯中场塞里禁区外补射得手,这粒进球也帮助球队锁定胜局。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/3.gif"
},
{
type: "TEXT",
content: "第80分钟加斯帕尔犯规,裁判判罚点球,但是巴洛特利罚出的点球被安东尼-洛佩斯扑出。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/4.gif"
},
{
type: "TEXT",
content: "最终尼斯两球击败对手,继续强势领跑。-洛佩斯扑出。"
},
{
type: "TEXT",
content: "【图卢兹3-1摩纳哥】"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/5.jpg"
},
{
type: "TEXT",
content: "比赛刚开场第3分钟客队就取得领先,博施利亚助攻热尔曼完成闪击。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/6.gif"
},
{
type: "TEXT",
content: "下半场图卢兹加强了攻势,第65分钟布莱斯维特助攻特雷霍扳平比分。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/7.gif"
},
{
type: "TEXT",
content: "在第84分钟和第87分钟,本场状态极好的布莱斯维特又攻入两球,最终图卢兹坐镇主场3-1逆转摩纳哥。"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/8.gif"
},
{
type: "IMAGE",
content: "../../images/temp/article/7/9.gif"
},
{
type: "TEXT",
content: "目前摩纳哥依然位于积分榜次席,不过如果巴黎圣日耳曼在今晚的比赛中能击败南锡,那么摩纳哥就要让出第二的位置。"
}
]
},
{
meta: {
id: "8",
type: "article",
belong: "",
title: "《金融时报》点评国足失败:中国企业因习主席而投身足球",
author: "Milioti",
post_time: "2016-10-15 06:40:54",
communications: "321"
},
list: [
{
type: "TEXT",
content: "国足客场0-2不敌乌兹别克斯坦的比赛已经过去,但关于国足的讨论还远没有停止。《金融时报》撰文对中国的足球梦进行了解读,我们一起来看看吧。"
},
{
type: "IMAGE",
content: "../../images/temp/article/8/1.jpg"
},
{
type: "TEXT",
content: "在2018年世界杯预选赛中中国国家队遭遇挫折,这也让习近平主席的“中国足球强国”梦变成了一场噩梦。先后负于叙利亚和乌兹别克斯坦的两场比赛也直接点燃了中国球迷以及媒体的怒火。像《环球时报》这样受中国自吹自擂民族主义影响的小报都提出了“放下足球,还是练乒乓球”这样的看法。他们在中国版Twitter——微博上写道:“怎么才能让心灰意冷的中国球迷继续支持这样一支国家队?”"
},
{
type: "TEXT",
content: "在0-2负于乌兹别克斯坦后,中国国家队主教练高洪波选择立刻辞职,事实上上一场0-1败给叙利亚后已经有球迷在街上发出让前者下课的声音。"
},
{
type: "TEXT",
content: "中国国家主席习近平是一个足球迷,是他带来了中国在足球领域的变化。2011年,他表示中国足球有三个梦想:进一次世界杯、举办一次世界杯、赢得一次世界杯。作为他足球计划的一部分,习主席表示2020年时中国会有20000个训练中心,70000块球场。"
},
{
type: "TEXT",
content: "自从习主席2012年上任以来,大批的中国企业家投身足球,以示对习主席计划的支持。他们前去欧洲,购买马竞、曼城这样的俱乐部的股份,还把像拉米雷斯、格乌瓦尼奥这样的高水平球员引进到自己在中国的球队。"
},
{
type: "TEXT",
content: "上个冬季转会窗,中超联赛在购买外援上花费了超过2亿8千万美元,也有公司花费80亿元人民币(12亿美元左右)购买中超联赛五年的转播权。"
},
{
type: "TEXT",
content: "大量的金钱虽然引来了关注和期望,但似乎对中国本土球员没什么影响。足球评论员丁伟杰就表示大批海外球员的到来也许已经挤压了中国本土才俊的成长空间:“中超有世界级名帅、海外球员和各种资源,但这些和国家队似乎关系不大,甚至会有负面影响。会出现中国本土球员在身边没了外援后不知道该怎么踢球的情况。”"
},
{
type: "TEXT",
content: "前天空体育记者Mark Dreyer运营着一个关注中国体育的博客,他的看法是:“大量的投资注入中国足球,或者说,是因为习近平主席的个人影响才这样。但现在的情况是中国民众对于足球的期望已经到了一个不切实际的层面。”也许中国足球的这次失败震惊了很多球迷,但对于圈内人士来说这并不令人吃惊。"
},
{
type: "TEXT",
content: "北京一家青训俱乐部的主教练告诉我们:“中国足球的希望在青训。也许十年、二十年后中国的青训才开始收获。现在的失败太正常了,每个熟悉中国足球的人都不会觉得失败令人吃惊。球迷不断提升的期待才是失望的主要来源。”"
},
{
type: "TEXT",
content: "Cameron Wilson在上海运营着一个足球博客,他用这么一句话评价了现在的情况:“你明知道剧本是怎么写的,但最终一幕上演后并没有减少心中的失望。”"
}
]
},
]
module.exports = {
articles: articles
} | 37.508929 | 796 | 0.496628 |
3dbaebdbf18a473ca98ac211c28d80f3e10a56ec | 229 | js | JavaScript | config/global.js | atreeyang/weixin-rss | 7883c00d608a60684f7d8ba7714bed33c6378a7b | [
"MIT"
] | 1 | 2017-02-24T05:12:40.000Z | 2017-02-24T05:12:40.000Z | config/global.js | atreeyang/weixin-rss | 7883c00d608a60684f7d8ba7714bed33c6378a7b | [
"MIT"
] | null | null | null | config/global.js | atreeyang/weixin-rss | 7883c00d608a60684f7d8ba7714bed33c6378a7b | [
"MIT"
] | null | null | null | module.exports = {
proxyEnable: true,
redis: {
host: process.env.REDIS_PORT_6379_TCP_ADDR,
port: process.env.REDIS_PORT_6379_TCP_PORT,
auth: process.env.REDIS_PASSWORD
},
proxy: process.env.PROXY
}
| 15.266667 | 49 | 0.68559 |
3dbe0ea6d39b2ceda7448ad734a5894827893779 | 15,317 | js | JavaScript | node_modules/pouchdb/lib/extras/checkpointer-browser.js | markprisacaru/wabashlightspxt | 29c5952c1efc6c1142d2da80d0d6b133716a44ec | [
"MIT"
] | 1 | 2018-05-28T14:08:12.000Z | 2018-05-28T14:08:12.000Z | app/webroot/bower_components/pouchdb/lib/extras/checkpointer-browser.js | TerrasAppSolutions/seeg-mapbiomas-workspace | cf8784ab4fa4acb76edc35cd7b85b72d57d70a38 | [
"MIT"
] | 27 | 2016-08-25T13:24:35.000Z | 2021-08-24T19:41:40.000Z | app/webroot/bower_components/pouchdb/lib/extras/checkpointer-browser.js | TerrasAppSolutions/seeg-mapbiomas-workspace | cf8784ab4fa4acb76edc35cd7b85b72d57d70a38 | [
"MIT"
] | 2 | 2016-10-26T20:26:42.000Z | 2017-06-14T18:03:37.000Z | 'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var lie = _interopDefault(require('lie'));
var getArguments = _interopDefault(require('argsarray'));
var debug = _interopDefault(require('debug'));
var events = require('events');
var inherits = _interopDefault(require('inherits'));
var pouchdbCollate = require('pouchdb-collate');
/* istanbul ignore next */
var PouchPromise = typeof Promise === 'function' ? Promise : lie;
// most of this is borrowed from lodash.isPlainObject:
// https://github.com/fis-components/lodash.isplainobject/
// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
var funcToString = Function.prototype.toString;
var objectCtorString = funcToString.call(Object);
var log = debug('pouchdb:api');
// like underscore/lodash _.pick()
function pick(obj, arr) {
var res = {};
for (var i = 0, len = arr.length; i < len; i++) {
var prop = arr[i];
if (prop in obj) {
res[prop] = obj[prop];
}
}
return res;
}
function isChromeApp() {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
}
var hasLocal;
if (isChromeApp()) {
hasLocal = false;
} else {
try {
localStorage.setItem('_pouch_check_localstorage', 1);
hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
} catch (e) {
hasLocal = false;
}
}
function hasLocalStorage() {
return hasLocal;
}
inherits(Changes, events.EventEmitter);
/* istanbul ignore next */
function attachBrowserEvents(self) {
if (isChromeApp()) {
chrome.storage.onChanged.addListener(function (e) {
// make sure it's event addressed to us
if (e.db_name != null) {
//object only has oldValue, newValue members
self.emit(e.dbName.newValue);
}
});
} else if (hasLocalStorage()) {
if (typeof addEventListener !== 'undefined') {
addEventListener("storage", function (e) {
self.emit(e.key);
});
} else { // old IE
window.attachEvent("storage", function (e) {
self.emit(e.key);
});
}
}
}
function Changes() {
events.EventEmitter.call(this);
this._listeners = {};
attachBrowserEvents(this);
}
Changes.prototype.addListener = function (dbName, id, db, opts) {
/* istanbul ignore if */
if (this._listeners[id]) {
return;
}
var self = this;
var inprogress = false;
function eventFunction() {
/* istanbul ignore if */
if (!self._listeners[id]) {
return;
}
if (inprogress) {
inprogress = 'waiting';
return;
}
inprogress = true;
var changesOpts = pick(opts, [
'style', 'include_docs', 'attachments', 'conflicts', 'filter',
'doc_ids', 'view', 'since', 'query_params', 'binary'
]);
/* istanbul ignore next */
function onError() {
inprogress = false;
}
db.changes(changesOpts).on('change', function (c) {
if (c.seq > opts.since && !opts.cancelled) {
opts.since = c.seq;
opts.onChange(c);
}
}).on('complete', function () {
if (inprogress === 'waiting') {
setTimeout(function (){
eventFunction();
},0);
}
inprogress = false;
}).on('error', onError);
}
this._listeners[id] = eventFunction;
this.on(dbName, eventFunction);
};
Changes.prototype.removeListener = function (dbName, id) {
/* istanbul ignore if */
if (!(id in this._listeners)) {
return;
}
events.EventEmitter.prototype.removeListener.call(this, dbName,
this._listeners[id]);
};
/* istanbul ignore next */
Changes.prototype.notifyLocalWindows = function (dbName) {
//do a useless change on a storage thing
//in order to get other windows's listeners to activate
if (isChromeApp()) {
chrome.storage.local.set({dbName: dbName});
} else if (hasLocalStorage()) {
localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
}
};
Changes.prototype.notify = function (dbName) {
this.emit(dbName);
this.notifyLocalWindows(dbName);
};
function guardedConsole(method) {
if (console !== 'undefined' && method in console) {
var args = Array.prototype.slice.call(arguments, 1);
console[method].apply(console, args);
}
}
// designed to give info to browser users, who are disturbed
// when they see http errors in the console
function explainError(status, str) {
guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
}
inherits(PouchError, Error);
function PouchError(opts) {
Error.call(this, opts.reason);
this.status = opts.status;
this.name = opts.error;
this.message = opts.reason;
this.error = true;
}
PouchError.prototype.toString = function () {
return JSON.stringify({
status: this.status,
name: this.name,
message: this.message,
reason: this.reason
});
};
var UNAUTHORIZED = new PouchError({
status: 401,
error: 'unauthorized',
reason: "Name or password is incorrect."
});
var MISSING_BULK_DOCS = new PouchError({
status: 400,
error: 'bad_request',
reason: "Missing JSON list of 'docs'"
});
var MISSING_DOC = new PouchError({
status: 404,
error: 'not_found',
reason: 'missing'
});
var REV_CONFLICT = new PouchError({
status: 409,
error: 'conflict',
reason: 'Document update conflict'
});
var INVALID_ID = new PouchError({
status: 400,
error: 'bad_request',
reason: '_id field must contain a string'
});
var MISSING_ID = new PouchError({
status: 412,
error: 'missing_id',
reason: '_id is required for puts'
});
var RESERVED_ID = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Only reserved document ids may start with underscore.'
});
var NOT_OPEN = new PouchError({
status: 412,
error: 'precondition_failed',
reason: 'Database not open'
});
var UNKNOWN_ERROR = new PouchError({
status: 500,
error: 'unknown_error',
reason: 'Database encountered an unknown error'
});
var BAD_ARG = new PouchError({
status: 500,
error: 'badarg',
reason: 'Some query argument is invalid'
});
var INVALID_REQUEST = new PouchError({
status: 400,
error: 'invalid_request',
reason: 'Request was invalid'
});
var QUERY_PARSE_ERROR = new PouchError({
status: 400,
error: 'query_parse_error',
reason: 'Some query parameter is invalid'
});
var DOC_VALIDATION = new PouchError({
status: 500,
error: 'doc_validation',
reason: 'Bad special document member'
});
var BAD_REQUEST = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Something wrong with the request'
});
var NOT_AN_OBJECT = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Document must be a JSON object'
});
var DB_MISSING = new PouchError({
status: 404,
error: 'not_found',
reason: 'Database not found'
});
var IDB_ERROR = new PouchError({
status: 500,
error: 'indexed_db_went_bad',
reason: 'unknown'
});
var WSQ_ERROR = new PouchError({
status: 500,
error: 'web_sql_went_bad',
reason: 'unknown'
});
var LDB_ERROR = new PouchError({
status: 500,
error: 'levelDB_went_went_bad',
reason: 'unknown'
});
var FORBIDDEN = new PouchError({
status: 403,
error: 'forbidden',
reason: 'Forbidden by design doc validate_doc_update function'
});
var INVALID_REV = new PouchError({
status: 400,
error: 'bad_request',
reason: 'Invalid rev format'
});
var FILE_EXISTS = new PouchError({
status: 412,
error: 'file_exists',
reason: 'The database could not be created, the file already exists.'
});
var MISSING_STUB = new PouchError({
status: 412,
error: 'missing_stub'
});
var INVALID_URL = new PouchError({
status: 413,
error: 'invalid_url',
reason: 'Provided URL is invalid'
});
// BEGIN Math.uuid.js
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix.
* // (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
var chars = (
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz'
).split('');
var CHECKPOINT_VERSION = 1;
var REPLICATOR = "pouchdb";
// This is an arbitrary number to limit the
// amount of replication history we save in the checkpoint.
// If we save too much, the checkpoing docs will become very big,
// if we save fewer, we'll run a greater risk of having to
// read all the changes from 0 when checkpoint PUTs fail
// CouchDB 2.0 has a more involved history pruning,
// but let's go for the simple version for now.
var CHECKPOINT_HISTORY_SIZE = 5;
var LOWEST_SEQ = 0;
function updateCheckpoint(db, id, checkpoint, session, returnValue) {
return db.get(id).catch(function (err) {
if (err.status === 404) {
if (db.type() === 'http') {
explainError(
404, 'PouchDB is just checking if a remote checkpoint exists.'
);
}
return {
session_id: session,
_id: id,
history: [],
replicator: REPLICATOR,
version: CHECKPOINT_VERSION
};
}
throw err;
}).then(function (doc) {
if (returnValue.cancelled) {
return;
}
// Filter out current entry for this replication
doc.history = (doc.history || []).filter(function (item) {
return item.session_id !== session;
});
// Add the latest checkpoint to history
doc.history.unshift({
last_seq: checkpoint,
session_id: session
});
// Just take the last pieces in history, to
// avoid really big checkpoint docs.
// see comment on history size above
doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);
doc.version = CHECKPOINT_VERSION;
doc.replicator = REPLICATOR;
doc.session_id = session;
doc.last_seq = checkpoint;
return db.put(doc).catch(function (err) {
if (err.status === 409) {
// retry; someone is trying to write a checkpoint simultaneously
return updateCheckpoint(db, id, checkpoint, session, returnValue);
}
throw err;
});
});
}
function Checkpointer(src, target, id, returnValue) {
this.src = src;
this.target = target;
this.id = id;
this.returnValue = returnValue;
}
Checkpointer.prototype.writeCheckpoint = function (checkpoint, session) {
var self = this;
return this.updateTarget(checkpoint, session).then(function () {
return self.updateSource(checkpoint, session);
});
};
Checkpointer.prototype.updateTarget = function (checkpoint, session) {
return updateCheckpoint(this.target, this.id, checkpoint,
session, this.returnValue);
};
Checkpointer.prototype.updateSource = function (checkpoint, session) {
var self = this;
if (this.readOnlySource) {
return PouchPromise.resolve(true);
}
return updateCheckpoint(this.src, this.id, checkpoint,
session, this.returnValue)
.catch(function (err) {
if (isForbiddenError(err)) {
self.readOnlySource = true;
return true;
}
throw err;
});
};
var comparisons = {
"undefined": function (targetDoc, sourceDoc) {
// This is the previous comparison function
if (pouchdbCollate.collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {
return sourceDoc.last_seq;
}
/* istanbul ignore next */
return 0;
},
"1": function (targetDoc, sourceDoc) {
// This is the comparison function ported from CouchDB
return compareReplicationLogs(sourceDoc, targetDoc).last_seq;
}
};
Checkpointer.prototype.getCheckpoint = function () {
var self = this;
return self.target.get(self.id).then(function (targetDoc) {
if (self.readOnlySource) {
return PouchPromise.resolve(targetDoc.last_seq);
}
return self.src.get(self.id).then(function (sourceDoc) {
// Since we can't migrate an old version doc to a new one
// (no session id), we just go with the lowest seq in this case
/* istanbul ignore if */
if (targetDoc.version !== sourceDoc.version) {
return LOWEST_SEQ;
}
var version;
if (targetDoc.version) {
version = targetDoc.version.toString();
} else {
version = "undefined";
}
if (version in comparisons) {
return comparisons[version](targetDoc, sourceDoc);
}
/* istanbul ignore next */
return LOWEST_SEQ;
}, function (err) {
if (err.status === 404 && targetDoc.last_seq) {
return self.src.put({
_id: self.id,
last_seq: LOWEST_SEQ
}).then(function () {
return LOWEST_SEQ;
}, function (err) {
if (isForbiddenError(err)) {
self.readOnlySource = true;
return targetDoc.last_seq;
}
/* istanbul ignore next */
return LOWEST_SEQ;
});
}
throw err;
});
}).catch(function (err) {
if (err.status !== 404) {
throw err;
}
return LOWEST_SEQ;
});
};
// This checkpoint comparison is ported from CouchDBs source
// they come from here:
// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906
function compareReplicationLogs(srcDoc, tgtDoc) {
if (srcDoc.session_id === tgtDoc.session_id) {
return {
last_seq: srcDoc.last_seq,
history: srcDoc.history
};
}
return compareReplicationHistory(srcDoc.history, tgtDoc.history);
}
function compareReplicationHistory(sourceHistory, targetHistory) {
// the erlang loop via function arguments is not so easy to repeat in JS
// therefore, doing this as recursion
var S = sourceHistory[0];
var sourceRest = sourceHistory.slice(1);
var T = targetHistory[0];
var targetRest = targetHistory.slice(1);
if (!S || targetHistory.length === 0) {
return {
last_seq: LOWEST_SEQ,
history: []
};
}
var sourceId = S.session_id;
/* istanbul ignore if */
if (hasSessionId(sourceId, targetHistory)) {
return {
last_seq: S.last_seq,
history: sourceHistory
};
}
var targetId = T.session_id;
if (hasSessionId(targetId, sourceRest)) {
return {
last_seq: T.last_seq,
history: targetRest
};
}
return compareReplicationHistory(sourceRest, targetRest);
}
function hasSessionId(sessionId, history) {
var props = history[0];
var rest = history.slice(1);
if (!sessionId || history.length === 0) {
return false;
}
if (sessionId === props.session_id) {
return true;
}
return hasSessionId(sessionId, rest);
}
function isForbiddenError(err) {
return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;
}
module.exports = Checkpointer; | 24.986949 | 114 | 0.650584 |
3dcb58d5fc7b0be06356fc22c270b4d8754f5e91 | 482 | js | JavaScript | utiles/setLog.js | S-I-T/Carepalito | 47d80f6db9ea30b9a344b6d0476b7c07d17683ef | [
"MIT"
] | 10 | 2017-04-20T19:44:42.000Z | 2018-06-07T04:17:50.000Z | utiles/setLog.js | S-I-T/Carepalito | 47d80f6db9ea30b9a344b6d0476b7c07d17683ef | [
"MIT"
] | null | null | null | utiles/setLog.js | S-I-T/Carepalito | 47d80f6db9ea30b9a344b6d0476b7c07d17683ef | [
"MIT"
] | 4 | 2017-04-17T16:25:54.000Z | 2018-09-27T14:00:10.000Z | //var exec = require('child_process').exec
const log = require('ss-logger')
function setLog(logInstance,logLevel) {
ll = log.levels.silly
switch(logLevel){
case "error":
ll = log.levels.error
break;
case "warn":
ll = log.levels.warn
break;
case "info":
ll = log.levels.info
break;
case "verbose":
ll = log.levels.verbose
break;
case "debug":
ll = log.levels.debug
break;
}
logInstance.setLevel(ll)
}
module.exports = exports = setLog
| 17.214286 | 42 | 0.651452 |
3da85b25ea9056b432a6ba1b291537b518dcf482 | 573 | js | JavaScript | src/libs/WebDriverIO.js | smildlzj/spectron-window | a8bab497bce5c113d20d31117093e64d87941ef2 | [
"MIT"
] | 1 | 2019-11-27T11:20:56.000Z | 2019-11-27T11:20:56.000Z | src/libs/WebDriverIO.js | smildlzj/spectron-window | a8bab497bce5c113d20d31117093e64d87941ef2 | [
"MIT"
] | null | null | null | src/libs/WebDriverIO.js | smildlzj/spectron-window | a8bab497bce5c113d20d31117093e64d87941ef2 | [
"MIT"
] | null | null | null | export default class WebDriverIO {
click (...args) {
return this.browser.click(...args)
}
getAttribute (...args) {
return this.browser.getAttribute(...args)
}
isVisible (...args) {
return this.browser.isVisible(...args)
}
execute (...args) {
return this.browser.execute(...args)
}
getText (...args) {
return this.browser.getText(...args)
}
isExisting (...args) {
return this.browser.isExisting(...args)
}
$ (...args) {
return this.browser.$(...args)
}
$$ (...args) {
return this.browser.$$(...args)
}
} | 17.363636 | 45 | 0.574171 |
3dc657ba856c4fecc1d5d026bd94239c8bb9d026 | 9,851 | js | JavaScript | packages/component/src/createLoadable.js | shredor/loadable-components | 11aaaaa9bcb5a57ed7d799178f77b3d9710d3ded | [
"MIT"
] | 3,318 | 2017-06-23T07:51:07.000Z | 2019-12-06T11:39:20.000Z | packages/component/src/createLoadable.js | mauvpark/loadable-components | 11aaaaa9bcb5a57ed7d799178f77b3d9710d3ded | [
"MIT"
] | 428 | 2017-06-23T14:32:32.000Z | 2019-12-06T10:39:25.000Z | packages/component/src/createLoadable.js | mauvpark/loadable-components | 11aaaaa9bcb5a57ed7d799178f77b3d9710d3ded | [
"MIT"
] | 222 | 2017-06-23T14:23:04.000Z | 2019-12-05T07:02:33.000Z | /* eslint-disable no-use-before-define, react/no-multi-comp, no-underscore-dangle */
import React from 'react'
import * as ReactIs from 'react-is'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { invariant } from './util'
import Context from './Context'
import { LOADABLE_SHARED } from './shared'
const STATUS_PENDING = 'PENDING'
const STATUS_RESOLVED = 'RESOLVED'
const STATUS_REJECTED = 'REJECTED'
function resolveConstructor(ctor) {
if (typeof ctor === 'function') {
return {
requireAsync: ctor,
resolve() {
return undefined
},
chunkName() {
return undefined
},
}
}
return ctor
}
const withChunkExtractor = Component => {
const LoadableWithChunkExtractor = props => (
<Context.Consumer>
{extractor => <Component __chunkExtractor={extractor} {...props} />}
</Context.Consumer>
)
if (Component.displayName) {
LoadableWithChunkExtractor.displayName = `${Component.displayName}WithChunkExtractor`
}
return LoadableWithChunkExtractor
}
const identity = v => v
function createLoadable({
defaultResolveComponent = identity,
render,
onLoad,
}) {
function loadable(loadableConstructor, options = {}) {
const ctor = resolveConstructor(loadableConstructor)
const cache = {}
/**
* Cachekey represents the component to be loaded
* if key changes - component has to be reloaded
* @param props
* @returns {null|Component}
*/
function getCacheKey(props) {
if (options.cacheKey) {
return options.cacheKey(props)
}
if (ctor.resolve) {
return ctor.resolve(props)
}
return 'static'
}
/**
* Resolves loaded `module` to a specific `Component
* @param module
* @param props
* @param Loadable
* @returns Component
*/
function resolve(module, props, Loadable) {
const Component = options.resolveComponent
? options.resolveComponent(module, props)
: defaultResolveComponent(module)
if (options.resolveComponent && !ReactIs.isValidElementType(Component)) {
throw new Error(
`resolveComponent returned something that is not a React component!`,
)
}
hoistNonReactStatics(Loadable, Component, {
preload: true,
})
return Component
}
const cachedLoad = props => {
const cacheKey = getCacheKey(props)
let promise = cache[cacheKey]
if (!promise || promise.status === STATUS_REJECTED) {
promise = ctor.requireAsync(props)
promise.status = STATUS_PENDING
cache[cacheKey] = promise
promise.then(
() => {
promise.status = STATUS_RESOLVED
},
error => {
console.error(
'loadable-components: failed to asynchronously load component',
{
fileName: ctor.resolve(props),
chunkName: ctor.chunkName(props),
error: error ? error.message : error,
},
)
promise.status = STATUS_REJECTED
},
)
}
return promise
}
class InnerLoadable extends React.Component {
static getDerivedStateFromProps(props, state) {
const cacheKey = getCacheKey(props)
return {
...state,
cacheKey,
// change of a key triggers loading state automatically
loading: state.loading || state.cacheKey !== cacheKey,
}
}
constructor(props) {
super(props)
this.state = {
result: null,
error: null,
loading: true,
cacheKey: getCacheKey(props),
}
invariant(
!props.__chunkExtractor || ctor.requireSync,
'SSR requires `@loadable/babel-plugin`, please install it',
)
// Server-side
if (props.__chunkExtractor) {
// This module has been marked with no SSR
if (options.ssr === false) {
return
}
// We run load function, we assume that it won't fail and that it
// triggers a synchronous loading of the module
ctor.requireAsync(props).catch(() => null)
// So we can require now the module synchronously
this.loadSync()
props.__chunkExtractor.addChunk(ctor.chunkName(props))
return
}
// Client-side with `isReady` method present (SSR probably)
// If module is already loaded, we use a synchronous loading
// Only perform this synchronous loading if the component has not
// been marked with no SSR, else we risk hydration mismatches
if (
options.ssr !== false &&
// is ready - was loaded in this session
((ctor.isReady && ctor.isReady(props)) ||
// is ready - was loaded during SSR process
(ctor.chunkName &&
LOADABLE_SHARED.initialChunks[ctor.chunkName(props)]))
) {
this.loadSync()
}
}
componentDidMount() {
this.mounted = true
// retrieve loading promise from a global cache
const cachedPromise = this.getCache()
// if promise exists, but rejected - clear cache
if (cachedPromise && cachedPromise.status === STATUS_REJECTED) {
this.setCache()
}
// component might be resolved synchronously in the constructor
if (this.state.loading) {
this.loadAsync()
}
}
componentDidUpdate(prevProps, prevState) {
// Component has to be reloaded on cacheKey change
if (prevState.cacheKey !== this.state.cacheKey) {
this.loadAsync()
}
}
componentWillUnmount() {
this.mounted = false
}
safeSetState(nextState, callback) {
if (this.mounted) {
this.setState(nextState, callback)
}
}
/**
* returns a cache key for the current props
* @returns {Component|string}
*/
getCacheKey() {
return getCacheKey(this.props)
}
/**
* access the persistent cache
*/
getCache() {
return cache[this.getCacheKey()]
}
/**
* sets the cache value. If called without value sets it as undefined
*/
setCache(value = undefined) {
cache[this.getCacheKey()] = value
}
triggerOnLoad() {
if (onLoad) {
setTimeout(() => {
onLoad(this.state.result, this.props)
})
}
}
/**
* Synchronously loads component
* target module is expected to already exists in the module cache
* or be capable to resolve synchronously (webpack target=node)
*/
loadSync() {
// load sync is expecting component to be in the "loading" state already
// sounds weird, but loading=true is the initial state of InnerLoadable
if (!this.state.loading) return
try {
const loadedModule = ctor.requireSync(this.props)
const result = resolve(loadedModule, this.props, Loadable)
this.state.result = result
this.state.loading = false
} catch (error) {
console.error(
'loadable-components: failed to synchronously load component, which expected to be available',
{
fileName: ctor.resolve(this.props),
chunkName: ctor.chunkName(this.props),
error: error ? error.message : error,
},
)
this.state.error = error
}
}
/**
* Asynchronously loads a component.
*/
loadAsync() {
const promise = this.resolveAsync()
promise
.then(loadedModule => {
const result = resolve(loadedModule, this.props, Loadable)
this.safeSetState(
{
result,
loading: false,
},
() => this.triggerOnLoad(),
)
})
.catch(error => this.safeSetState({ error, loading: false }))
return promise
}
/**
* Asynchronously resolves(not loads) a component.
* Note - this function does not change the state
*/
resolveAsync() {
const { __chunkExtractor, forwardedRef, ...props } = this.props
return cachedLoad(props)
}
render() {
const {
forwardedRef,
fallback: propFallback,
__chunkExtractor,
...props
} = this.props
const { error, loading, result } = this.state
if (options.suspense) {
const cachedPromise = this.getCache() || this.loadAsync()
if (cachedPromise.status === STATUS_PENDING) {
throw this.loadAsync()
}
}
if (error) {
throw error
}
const fallback = propFallback || options.fallback || null
if (loading) {
return fallback
}
return render({
fallback,
result,
options,
props: { ...props, ref: forwardedRef },
})
}
}
const EnhancedInnerLoadable = withChunkExtractor(InnerLoadable)
const Loadable = React.forwardRef((props, ref) => (
<EnhancedInnerLoadable forwardedRef={ref} {...props} />
))
Loadable.displayName = 'Loadable'
// In future, preload could use `<link rel="preload">`
Loadable.preload = props => {
Loadable.load(props)
}
Loadable.load = props => {
return cachedLoad(props)
}
return Loadable
}
function lazy(ctor, options) {
return loadable(ctor, { ...options, suspense: true })
}
return { loadable, lazy }
}
export default createLoadable
| 26.769022 | 106 | 0.569282 |
3d9df3b8651b6e12b0059c8b9b4ebed1ac377eeb | 575 | js | JavaScript | src/pages/LoginPage/MessageLoginFormComponent.js | WhiteRobe/hypethron | 63090c9221c04e8b7fdbe4a3ba4959f3dab86c94 | [
"MIT"
] | 2 | 2019-07-15T06:12:36.000Z | 2020-03-27T02:03:42.000Z | src/pages/LoginPage/MessageLoginFormComponent.js | WhiteRobe/hypethron | 63090c9221c04e8b7fdbe4a3ba4959f3dab86c94 | [
"MIT"
] | 5 | 2019-08-23T09:59:08.000Z | 2022-02-26T15:18:37.000Z | src/pages/LoginPage/MessageLoginFormComponent.js | WhiteRobe/hypethron | 63090c9221c04e8b7fdbe4a3ba4959f3dab86c94 | [
"MIT"
] | 3 | 2019-07-16T14:01:33.000Z | 2020-03-31T03:22:50.000Z | import React from 'react';
import {Row, Col} from 'antd';
import 'antd/es/style/index.css' // col & row
import 'antd/es/grid/style/index.css' // col & row
class MessageLoginFormComponent extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<Row style={{minHeight: '473.5px'}}>
<Col span={5}> </Col>
<Col span={14} style={{textAlign: 'center'}}>
短信登录暂未制作
</Col>
<Col span={5}> </Col>
</Row>
)
}
}
export default MessageLoginFormComponent; | 22.115385 | 57 | 0.587826 |
3dc7cdf0e4dc42b1cca0ca5ffc7ce4da1524afa9 | 10,853 | js | JavaScript | index.js | monkeylord/BitDiary | 75e5d78831f90a0760eb74583a865a8d340f3bb5 | [
"MIT"
] | 2 | 2019-11-23T21:14:27.000Z | 2020-03-27T11:18:53.000Z | index.js | monkeylord/BitDiary | 75e5d78831f90a0760eb74583a865a8d340f3bb5 | [
"MIT"
] | null | null | null | index.js | monkeylord/BitDiary | 75e5d78831f90a0760eb74583a865a8d340f3bb5 | [
"MIT"
] | null | null | null | var bsv = require('bsv')
// Extend BSV
require('bitcoin-ibe')
var CryptoJS = require('crypto-js')
const DEBUG = false
/*
BitDiary
Basic Function:
Constructor - Create a diary instance
readDiary - Read a single diary with ViewKey from remote node
readDiaries - Read all diaries from remote node
getDiaries - Get decrpyted diaries
getDiaryUpdateOutput - Create a diary output (for building transaction)
Advanced Function:
getEditKey - Get EditKey for specified index
getCrypticPrefix - Get CrypticPrefix for indexing
getEncryptedDiaries - Get raw diaries data
readDiariesFromCache - read diaries from parameters(raw diaries data)
Utilities:
AESDecrypt - Do decryption
AESEncrypt - Do encryption
getDecryptResult - Diary ciphertext decrypt
editKey - Create EditKey
getSignature - Generate ECDSA secp256k1 signature with bitcoin library
verifySignature - Verify ECDSA secp256k1 signature with bitcoin library
*/
function BitDiary(privkey, prefix) {
this.prefix = "BitDiary"
this.privkey = bsv.PrivateKey(privkey)
this.newEditKey = null
this.newIndex = 0
this.diaries = []
this.encryptedDiaries = []
this.status = BitDiary.STATUS.INIT
this.prefix = prefix || "BitDiary"
}
BitDiary.STATUS = {
INIT: 0,
HASLAST: 1,
ALLREAD: 2
}
BitDiary.prototype.getDiaryUpdateOutput = function (diary, EditKey) {
EditKey = EditKey || this.newEditKey
var crypticPrefix = this.getCrypticPrefix(EditKey.publicKey)
var encDiary = BitDiary.AESEncrypt(diary, EditKey.publicKey)
var diaryhashbuf = bsv.deps.Buffer.from(diary)
var signature = BitDiary.getSignature(diaryhashbuf, EditKey)
var script = new bsv.Script.buildDataOut(crypticPrefix)
script.add(bsv.deps.Buffer.from(encDiary))
script.add(bsv.deps.Buffer.from(signature))
return new bsv.Transaction.Output({
satoshis: 0,
script: script
})
}
BitDiary.prototype.incCurKey = function () {
this.newIndex++
}
BitDiary.prototype.getEditKey = function (index) {
return BitDiary.editKey(this.privkey, String(index))
}
BitDiary.prototype.getCrypticPrefix = function (pubkey) {
return bsv.crypto.Hash.sha256(bsv.deps.Buffer.from(this.prefix + pubkey.toString())).toString('base64')
}
BitDiary.prototype.readDiariesFromCache = function (cachedDiaries) {
var diaries = JSON.parse(cachedDiaries)
if (!Array.isArray(diaries)) return
var verfied = diaries.every((entry, index) => {
if (!entry) return false
var viewKey = BitDiary.editKey(this.privkey, String(index)).publicKey
return BitDiary.verifySignature(BitDiary.getDecryptResult(entry.diary, viewKey), entry.sigstr, viewKey)
})
if (verfied) this.encryptedDiaries = diaries
}
BitDiary.prototype.readDiaries = async function (index) {
if (this.privkey == null || this.privkey == "") {
throw new Error("Invalid Privkey")
}
// Read specific diary
if(index){
var editKey = BitDiary.editKey(this.privkey, String(index))
if(DEBUG) console.log(index + ":" + editKey)
var diaryRecord = await this.readDiary(curVKey.publicKey)
if (diaryRecord.length > 0) {
this.encryptedDiaries[index] = diaryRecord
this.diaries[index] = diaryRecord[0]
var plaintext = BitDiary.getDecryptResult(diaryRecord[0].diary, editKey.publicKey)
if(DEBUG) console.log(index + ":" + plaintext)
return true
}
return false
}
// binary search algorithm
// by doing binary search, we can locate the last entry quickly, so we can do push before we read everything
var keyIndex = this.diaries.length
var lastKnown = this.diaries.filter(diary => diary.time != null).length > 0 ? this.diaries.filter(diary => diary.time != null).length - 1 : -1
var boundary = -1
var hasLatest = false
do {
var curEditKey = BitDiary.editKey(this.privkey, String(keyIndex))
if(DEBUG) console.log(keyIndex + ":" + curEditKey)
var diaryRecord = await this.readDiary(curEditKey.publicKey)
if (diaryRecord.length > 0) {
this.encryptedDiaries[keyIndex] = diaryRecord
this.diaries[keyIndex] = diaryRecord[0]
var plaintext = BitDiary.getDecryptResult(diaryRecord[0].diary, curEditKey.publicKey)
if(DEBUG) console.log(keyIndex + ":" + plaintext)
}
// 指数递进,随后二分确定最新日志及curEditKey
// 确保可以在短时间内可以写新日记
// 随后加载所有日志
if(DEBUG) console.log(`Searching Index: ${keyIndex} lastKnown: ${lastKnown} boundary: ${boundary}`)
if (!hasLatest) {
// 不知道最新的日志是什么,还在搜索
if(DEBUG) console.log("boundary still unknow")
if (diaryRecord.length > 0) {
// 命中了,更新lastknown
if(DEBUG) console.log("update lastknown")
lastKnown = keyIndex
if (boundary == -1) {
// 还不知道上限,指数递进
if(DEBUG) console.log("binary increase search index")
keyIndex = (keyIndex + 1) * 2 - 1
} else {
// 已经知道范围上限,区间内指数递进缩小搜索范围
if(DEBUG) console.log("as we knows boundary, closing the range to last one")
if (boundary - keyIndex == 1) {
// 找到了尾部
if(DEBUG) console.log("we have the last one")
hasLatest = true
keyIndex = keyIndex + 1
this.newEditKey = BitDiary.editKey(this.privkey, String(keyIndex))
this.newIndex = keyIndex
this.status = BitDiary.STATUS.HASLAST
} else {
// 前进到二分之一处
keyIndex = lastKnown + Math.floor((boundary - lastKnown) / 2)
}
}
} else {
// 未命中,说明达到了上限
if(DEBUG) console.log("index out of boundary")
boundary = keyIndex
if (keyIndex - lastKnown == 1) {
// 找到了尾部
if(DEBUG) console.log("we have the last one")
hasLatest = true
this.newEditKey = BitDiary.editKey(this.privkey, String(keyIndex))
this.newIndex = keyIndex
this.status = BitDiary.STATUS.HASLAST
} else {
// 后退到二分之一处
keyIndex = lastKnown + Math.floor((boundary - lastKnown) / 2)
}
}
}
if (hasLatest) {
// 已经知道最新了,那么进行逐一回退搜索
if(DEBUG) console.log("as we know the last, read entries one by one now")
while (keyIndex > 0 && this.diaries[keyIndex - 1] != undefined && this.diaries[keyIndex - 1].time != null) {
// 跳过已经知道的日志
if(DEBUG) console.log(`Skipping already known ${keyIndex - 1}`)
keyIndex = keyIndex - 1
}
keyIndex = keyIndex - 1
}
if(DEBUG) console.log(`Next index :${keyIndex}`)
this.loading = !this.loading
} while (keyIndex > 0)
this.status = BitDiary.STATUS.ALLREAD
//if(DEBUG) console.log("缓存日志")
//localStorage.setItem("cachedDiaries", JSON.stringify(this.diaries))
return true
}
BitDiary.prototype.getEncryptedDiaries = function () {
return this.encryptedDiaries
}
BitDiary.prototype.getDiaries = function () {
return this.encryptedDiaries.map((diaryRecord, index) => {
return diaryRecord.map(diary => {
return {
block: diary.blk,
time: diary.time,
diary: BitDiary.getDecryptResult(diary.diary, BitDiary.editKey(this.privkey, String(index)).publicKey)
}
})
})
}
BitDiary.prototype.readDiary = function (ViewKey) {
var crypticPrefix = this.getCrypticPrefix(ViewKey)
var query = {
"v": 3,
"q": {
"find": { "out.s1": crypticPrefix },
},
"r": {
"f": "[ .[] | {diary: .out[0].s2, ldiary: .out[0].ls2, sigstr: .out[0].s3, txid: .tx.h, blk:.blk.i, time:.blk.t} ]"
}
}
var b64 = btoa(JSON.stringify(query));
var myendpoint = window["endpoint"] || "https://genesis.bitdb.network/q/1FnauZ9aUH2Bex6JzdcV4eNX7oLSSEbxtN/"
var url = myendpoint + b64;
var header = {
headers: { key: ['159bcdKY4spcahzfTZhBbFBXrTWpoh4rd3'] }
};
return fetch(url, header)
.then(r => r.json())
.then(r => r.u.concat(r.c.sort((a, b) => b.blk - a.blk)))
.then(r => r.reverse())
.then(r => { r.forEach(entry => entry.diary = entry.diary || entry.ldiary); return r })
.then(r => r.filter(entry => BitDiary.verifySignature(BitDiary.getDecryptResult(entry.diary, ViewKey), entry.sigstr, ViewKey)))
}
/*
Utilities
*/
BitDiary.AESDecrypt = function (ciphertext, key) {
var keybuf = bsv.crypto.Hash.sha256(key.toBuffer())
var key = CryptoJS.enc.Hex.parse(keybuf.slice(0, 8).toString('hex'));
var iv = CryptoJS.enc.Hex.parse(keybuf.slice(8, 16).toString('hex'));
var decrypt = CryptoJS.AES.decrypt(ciphertext, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
BitDiary.AESEncrypt = function (plaintext, key) {
var keybuf = bsv.crypto.Hash.sha256(key.toBuffer())
var key = CryptoJS.enc.Hex.parse(keybuf.slice(0, 8).toString('hex'));
var iv = CryptoJS.enc.Hex.parse(keybuf.slice(8, 16).toString('hex'));
var srcs = CryptoJS.enc.Utf8.parse(plaintext);
var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}
BitDiary.getDecryptResult = function (ciphertext, key) {
try {
return BitDiary.AESDecrypt(ciphertext, key)
} catch (err) {
return err
}
}
BitDiary.editKey = function (masterkey, index) {
return bsv.PrivateKey(bsv.crypto.Hash.sha256sha256(bsv.PrivateKey(masterkey).childKey(String(index)).toBuffer()).toString('hex'))
}
BitDiary.getSignature = function (content, privateKey) {
var hashbuf = bsv.crypto.Hash.sha256(bsv.deps.Buffer.from(content))
return bsv.crypto.ECDSA.sign(hashbuf, privateKey).toDER().toString('base64')
}
BitDiary.verifySignature = function (content, sigstr, publicKey) {
var hashbuf = bsv.crypto.Hash.sha256(bsv.deps.Buffer.from(content))
var signature = bsv.crypto.Signature.fromDER(bsv.deps.Buffer.from(sigstr, 'base64'))
return bsv.crypto.ECDSA.verify(hashbuf, signature, publicKey)
}
module.exports = BitDiary
| 38.214789 | 146 | 0.615406 |
3da4258eeab4ba22c390eaa472854c2c24d744a7 | 11,038 | js | JavaScript | index.js | samridhgupta/react-native-sketch-canvas | e52b2c8a6c3bd433ce1101f4e4a1bdfc89890969 | [
"MIT"
] | 2 | 2020-03-17T03:17:28.000Z | 2020-04-05T03:54:41.000Z | index.js | samridhgupta/react-native-sketch-canvas | e52b2c8a6c3bd433ce1101f4e4a1bdfc89890969 | [
"MIT"
] | null | null | null | index.js | samridhgupta/react-native-sketch-canvas | e52b2c8a6c3bd433ce1101f4e4a1bdfc89890969 | [
"MIT"
] | 1 | 2019-05-17T09:54:31.000Z | 2019-05-17T09:54:31.000Z | import React from 'react'
import PropTypes from 'prop-types'
import ReactNative, {
View,
Text,
TouchableOpacity,
FlatList,
ViewPropTypes,
} from 'react-native'
import SketchCanvas from './src/SketchCanvas'
import { requestPermissions } from './src/handlePermissions';
export default class RNSketchCanvas extends React.Component {
static propTypes = {
containerStyle: ViewPropTypes.style,
canvasStyle: ViewPropTypes.style,
onStrokeStart: PropTypes.func,
onStrokeChanged: PropTypes.func,
onStrokeEnd: PropTypes.func,
onClosePressed: PropTypes.func,
onUndoPressed: PropTypes.func,
onClearPressed: PropTypes.func,
onPathsChange: PropTypes.func,
user: PropTypes.string,
closeComponent: PropTypes.node,
eraseComponent: PropTypes.node,
undoComponent: PropTypes.node,
clearComponent: PropTypes.node,
saveComponent: PropTypes.node,
deleteSelectedShapeComponent: PropTypes.node,
strokeComponent: PropTypes.func,
strokeSelectedComponent: PropTypes.func,
strokeWidthComponent: PropTypes.func,
strokeColors: PropTypes.arrayOf(PropTypes.shape({ color: PropTypes.string })),
defaultStrokeIndex: PropTypes.number,
defaultStrokeWidth: PropTypes.number,
minStrokeWidth: PropTypes.number,
maxStrokeWidth: PropTypes.number,
strokeWidthStep: PropTypes.number,
savePreference: PropTypes.func,
onSketchSaved: PropTypes.func,
onShapeSelectionChanged: PropTypes.func,
shapeConfiguration: PropTypes.shape({ shapeBorderColor: PropTypes.string, shapeBorderStyle: PropTypes.string, shapeBorderStrokeWidth: PropTypes.number, shapeColor: PropTypes.string, shapeStrokeWidth: PropTypes.number }),
text: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string,
font: PropTypes.string,
fontSize: PropTypes.number,
fontColor: PropTypes.string,
overlay: PropTypes.oneOf(['TextOnSketch', 'SketchOnText']),
anchor: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }),
position: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }),
coordinate: PropTypes.oneOf(['Absolute', 'Ratio']),
alignment: PropTypes.oneOf(['Left', 'Center', 'Right']),
lineHeightMultiple: PropTypes.number,
})),
localSourceImage: PropTypes.shape({ filename: PropTypes.string, directory: PropTypes.string, mode: PropTypes.string }),
permissionDialogTitle: PropTypes.string,
permissionDialogMessage: PropTypes.string,
};
static defaultProps = {
containerStyle: null,
canvasStyle: null,
onStrokeStart: () => { },
onStrokeChanged: () => { },
onStrokeEnd: () => { },
onClosePressed: () => { },
onUndoPressed: () => { },
onClearPressed: () => { },
onPathsChange: () => { },
user: null,
closeComponent: null,
eraseComponent: null,
undoComponent: null,
clearComponent: null,
saveComponent: null,
deleteSelectedShapeComponent: null,
strokeComponent: null,
strokeSelectedComponent: null,
strokeWidthComponent: null,
strokeColors: [
{ color: '#000000' },
{ color: '#FF0000' },
{ color: '#00FFFF' },
{ color: '#0000FF' },
{ color: '#0000A0' },
{ color: '#ADD8E6' },
{ color: '#800080' },
{ color: '#FFFF00' },
{ color: '#00FF00' },
{ color: '#FF00FF' },
{ color: '#FFFFFF' },
{ color: '#C0C0C0' },
{ color: '#808080' },
{ color: '#FFA500' },
{ color: '#A52A2A' },
{ color: '#800000' },
{ color: '#008000' },
{ color: '#808000' }],
alphlaValues: ['33', '77', 'AA', 'FF'],
defaultStrokeIndex: 0,
defaultStrokeWidth: 3,
minStrokeWidth: 3,
maxStrokeWidth: 15,
strokeWidthStep: 3,
savePreference: null,
onSketchSaved: () => { },
onShapeSelectionChanged: () => { },
shapeConfiguration: { shapeBorderColor: 'transparent', shapeBorderStyle: 'Dashed', shapeBorderStrokeWidth: 1, shapeColor: '#000000', shapeStrokeWidth: 3 },
text: null,
localSourceImage: null,
permissionDialogTitle: '',
permissionDialogMessage: '',
};
constructor(props) {
super(props)
this.state = {
color: props.strokeColors[props.defaultStrokeIndex].color,
strokeWidth: props.defaultStrokeWidth,
alpha: 'FF'
}
this._colorChanged = false
this._strokeWidthStep = props.strokeWidthStep
this._alphaStep = -1
}
clear() {
this._sketchCanvas.clear()
}
undo() {
return this._sketchCanvas.undo()
}
addPath(data) {
this._sketchCanvas.addPath(data)
}
deletePath(id) {
this._sketchCanvas.deletePath(id)
}
deleteSelectedShape() {
this._sketchCanvas.deleteSelectedShape();
}
addShape(config) {
this._sketchCanvas.addShape(config);
}
increaseSelectedShapeFontsize() {
this._sketchCanvas.increaseSelectedShapeFontsize();
}
decreaseSelectedShapeFontsize() {
this._sketchCanvas.decreaseSelectedShapeFontsize();
}
changeSelectedShapeText(newText) {
this._sketchCanvas.changeSelectedShapeText(newText);
}
save() {
if (this.props.savePreference) {
const p = this.props.savePreference()
this._sketchCanvas.save(p.imageType, p.transparent, p.folder ? p.folder : '', p.filename, p.includeImage !== false, p.includeText !== false, p.cropToImageSize || false)
} else {
const date = new Date()
this._sketchCanvas.save('png', false, '',
date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + ('0' + date.getDate()).slice(-2) + ' ' + ('0' + date.getHours()).slice(-2) + '-' + ('0' + date.getMinutes()).slice(-2) + '-' + ('0' + date.getSeconds()).slice(-2),
true, true, false)
}
}
nextStrokeWidth() {
if ((this.state.strokeWidth >= this.props.maxStrokeWidth && this._strokeWidthStep > 0) ||
(this.state.strokeWidth <= this.props.minStrokeWidth && this._strokeWidthStep < 0))
this._strokeWidthStep = -this._strokeWidthStep
this.setState({ strokeWidth: this.state.strokeWidth + this._strokeWidthStep })
}
_renderItem = ({ item, index }) => (
<TouchableOpacity style={{ marginHorizontal: 2.5 }} onPress={() => {
if (this.state.color === item.color) {
const index = this.props.alphlaValues.indexOf(this.state.alpha)
if (this._alphaStep < 0) {
this._alphaStep = index === 0 ? 1 : -1
this.setState({ alpha: this.props.alphlaValues[index + this._alphaStep] })
} else {
this._alphaStep = index === this.props.alphlaValues.length - 1 ? -1 : 1
this.setState({ alpha: this.props.alphlaValues[index + this._alphaStep] })
}
} else {
this.setState({ color: item.color })
this._colorChanged = true
}
}}>
{this.state.color !== item.color && this.props.strokeComponent && this.props.strokeComponent(item.color)}
{this.state.color === item.color && this.props.strokeSelectedComponent && this.props.strokeSelectedComponent(item.color + this.state.alpha, index, this._colorChanged)}
</TouchableOpacity>
)
componentDidUpdate() {
this._colorChanged = false
}
async componentDidMount() {
const isStoragePermissionAuthorized = await requestPermissions(
this.props.permissionDialogTitle,
this.props.permissionDialogMessage,
);
}
render() {
return (
<View style={this.props.containerStyle}>
<View style={{ flexDirection: 'row' }}>
<View style={{ flexDirection: 'row', flex: 1, justifyContent: 'flex-start' }}>
{this.props.closeComponent && (
<TouchableOpacity onPress={() => { this.props.onClosePressed() }}>
{this.props.closeComponent}
</TouchableOpacity>)
}
{this.props.eraseComponent && (
<TouchableOpacity onPress={() => { this.setState({ color: '#00000000' }) }}>
{this.props.eraseComponent}
</TouchableOpacity>)
}
{this.props.deleteSelectedShapeComponent && (
<TouchableOpacity style={{ opacity: this.props.touchEnabled ? 0.5 : 1 }} disabled={this.props.touchEnabled} onPress={() => { this.deleteSelectedShape() }}>
{this.props.deleteSelectedShapeComponent}
</TouchableOpacity>)
}
</View>
<View style={{ flexDirection: 'row', flex: 1, justifyContent: 'flex-end' }}>
{this.props.strokeWidthComponent && (
<TouchableOpacity onPress={() => { this.nextStrokeWidth() }}>
{this.props.strokeWidthComponent(this.state.strokeWidth)}
</TouchableOpacity>)
}
{this.props.undoComponent && (
<TouchableOpacity onPress={() => { this.props.onUndoPressed(this.undo()) }}>
{this.props.undoComponent}
</TouchableOpacity>)
}
{this.props.clearComponent && (
<TouchableOpacity onPress={() => { this.clear(); this.props.onClearPressed() }}>
{this.props.clearComponent}
</TouchableOpacity>)
}
{this.props.saveComponent && (
<TouchableOpacity onPress={() => { this.save() }}>
{this.props.saveComponent}
</TouchableOpacity>)
}
</View>
</View>
<SketchCanvas
ref={ref => this._sketchCanvas = ref}
style={this.props.canvasStyle}
strokeColor={this.state.color + (this.state.color.length === 9 ? '' : this.state.alpha)}
shapeConfiguration={this.props.shapeConfiguration}
onStrokeStart={this.props.onStrokeStart}
onStrokeChanged={this.props.onStrokeChanged}
onStrokeEnd={this.props.onStrokeEnd}
user={this.props.user}
strokeWidth={this.state.strokeWidth}
onSketchSaved={(success, path) => this.props.onSketchSaved(success, path)}
onShapeSelectionChanged={(isShapeSelected) => this.props.onShapeSelectionChanged(isShapeSelected)}
touchEnabled={this.props.touchEnabled}
onPathsChange={this.props.onPathsChange}
text={this.props.text}
localSourceImage={this.props.localSourceImage}
permissionDialogTitle={this.props.permissionDialogTitle}
permissionDialogMessage={this.props.permissionDialogMessage}
/>
<View style={{ flexDirection: 'row' }}>
<FlatList
data={this.props.strokeColors}
extraData={this.state}
keyExtractor={() => Math.ceil(Math.random() * 10000000).toString()}
renderItem={this._renderItem}
horizontal
showsHorizontalScrollIndicator={false}
/>
</View>
</View>
);
}
};
RNSketchCanvas.MAIN_BUNDLE = SketchCanvas.MAIN_BUNDLE;
RNSketchCanvas.DOCUMENT = SketchCanvas.DOCUMENT;
RNSketchCanvas.LIBRARY = SketchCanvas.LIBRARY;
RNSketchCanvas.CACHES = SketchCanvas.CACHES;
export {
SketchCanvas
}
| 34.386293 | 228 | 0.631908 |
3daacf965871a6437f848ff6ad3c3d578e430cfa | 1,042 | js | JavaScript | src/pages/index.js | guidingdigital/yt-gatsby-schema-completed | 1c65b737d1591252d981022d35ef5a580fbf63b8 | [
"MIT"
] | 1 | 2020-05-23T22:55:03.000Z | 2020-05-23T22:55:03.000Z | src/pages/index.js | guidingdigital/yt-gatsby-schema-completed | 1c65b737d1591252d981022d35ef5a580fbf63b8 | [
"MIT"
] | null | null | null | src/pages/index.js | guidingdigital/yt-gatsby-schema-completed | 1c65b737d1591252d981022d35ef5a580fbf63b8 | [
"MIT"
] | 1 | 2021-04-29T20:25:35.000Z | 2021-04-29T20:25:35.000Z | import React from "react"
import { Link, useStaticQuery, graphql } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => {
const { site } = useStaticQuery(
graphql`
query {
site {
siteMetadata {
description
siteUrl
}
}
}
`
)
const schema = {
"@context": "https://schema.org",
"@type": "Organization",
"name": "Guiding Digital",
"description" : site.siteMetadata.description,
"url": site.siteMetadata.siteUrl,
"logo": "https://www.guidingdigital.com/images/logo.png"
}
return (
<Layout>
<SEO title="Home" schemaMarkup={schema} />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
}
export default IndexPage
| 23.155556 | 64 | 0.586372 |
3dad3e6a96bbb421980f3e83ec1c803ef9223330 | 2,826 | js | JavaScript | src/components/Footer.js | liubin/www.katacontainers.io | 0f4774fa39ddf5375f54ca2d574d2b3599c2ebfd | [
"MIT"
] | 21 | 2017-12-04T08:40:52.000Z | 2020-12-18T09:03:00.000Z | src/components/Footer.js | liubin/www.katacontainers.io | 0f4774fa39ddf5375f54ca2d574d2b3599c2ebfd | [
"MIT"
] | 85 | 2017-12-04T12:00:43.000Z | 2022-03-28T09:00:12.000Z | src/components/Footer.js | liubin/www.katacontainers.io | 0f4774fa39ddf5375f54ca2d574d2b3599c2ebfd | [
"MIT"
] | 48 | 2017-12-03T20:13:43.000Z | 2022-02-28T12:48:44.000Z | import React from 'react'
import { Link } from 'gatsby'
import { OutboundLink } from 'gatsby-plugin-google-analytics'
import logo from '../img/svg/logo_white.svg'
import content from '../content/footer-nav.json'
const Footer = class extends React.Component {
render() {
return (
<footer className="footer is-dark">
<div className="container container-medium">
<div className="footer-inner">
<div className="columns">
<div className="column">
<div className="footer-content">
<div className="columns is-mobile">
{content.sections.map((col, index) => {
return(
<div className="column" key={index}>
<h6 className="footer-title">{col.title}</h6>
<ul className="footer-list nobullet">
{col.nav.map((item, index) => {
return(
<li className="item-no-bullet" key={index}>
{item.link.match(/^https?:\/\//) ?
<OutboundLink href={item.link}>{item.text}</OutboundLink>
:
<Link to={item.link}>
{item.text}
</Link>
}
</li>
)
})}
</ul>
</div>
)
})}
</div>
</div>
</div>
<div className="column">
<div className="footer-aside">
<div className="footer-entry">
<p>
Kata Containers is an independent open source community collaboratively developing code under the Apache 2 license. The project is supported by the Open Infrastructure Foundation; the community follows the OpenInfra Foundation <OutboundLink href="//openinfra.dev/legal/code-of-conduct/">Code of Conduct</OutboundLink>.
</p>
</div>
<div className="footer-brand">
<a href="/" className="router-link-exact-active router-link-active">
<img src={logo} alt="Kata Containers" />
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</footer>
)
}
}
export default Footer
| 42.179104 | 340 | 0.403397 |
3da0b6094babe437b5f673ef3859ddb9fac7a07e | 498 | js | JavaScript | packages/mdxast/test/test.js | jhalvorson/mdx | ee5cd3ec834605248020a3ff39188bfd1c43060d | [
"MIT"
] | 1 | 2021-02-12T17:43:37.000Z | 2021-02-12T17:43:37.000Z | packages/mdxast/test/test.js | jhalvorson/mdx | ee5cd3ec834605248020a3ff39188bfd1c43060d | [
"MIT"
] | 18 | 2021-05-09T03:37:06.000Z | 2022-02-27T09:24:44.000Z | packages/mdxast/test/test.js | jhalvorson/mdx | ee5cd3ec834605248020a3ff39188bfd1c43060d | [
"MIT"
] | 1 | 2020-08-04T01:28:32.000Z | 2020-08-04T01:28:32.000Z | const fs = require('fs')
const unified = require('unified')
const remark = require('remark-parse')
const rehype = require('remark-rehype')
const html = require('rehype-stringify')
const toMdx = require('..')
const fixture = fs.readFileSync('test/fixture.md', 'utf8')
const parseFixture = str => {
const parser = unified()
.use(remark)
.use(toMdx)
.use(rehype)
.use(html)
return parser.processSync(str).contents
}
test('it parses a file', () => {
parseFixture(fixture)
})
| 20.75 | 58 | 0.668675 |
3db381d6ae9ecbb767d2b4029610da77d3414d27 | 1,255 | js | JavaScript | index.js | coderofsalvation/parse-server-queue | 5c88cab1df7a3a6bbf00e5d700f78a813cdb723e | [
"MIT"
] | 1 | 2021-02-19T01:41:44.000Z | 2021-02-19T01:41:44.000Z | index.js | coderofsalvation/parse-server-queue | 5c88cab1df7a3a6bbf00e5d700f78a813cdb723e | [
"MIT"
] | null | null | null | index.js | coderofsalvation/parse-server-queue | 5c88cab1df7a3a6bbf00e5d700f78a813cdb723e | [
"MIT"
] | null | null | null | var mongodb = require('mongodb')
var Q = require('mongodb-queue')
const Parse = require('parse/node');
const ParseQ = require('./ParseQ')(Parse,Q)
const url = process.env.DATABASE_URI
console.log(url)
const client = new mongodb.MongoClient(url, { useNewUrlParser: true,useUnifiedTopology:true })
Parse.initialize( process.env.APP_ID, process.env.API_KEY_JAVASCRIPT, process.env.MASTER_KEY )
Parse.serverURL = process.env.SERVER_URL
let work = (queue) => {
done = () => work(queue) // repeat infinitely!
queue.get((err, msg) => {
try{
if( !msg ) return done()
if( err ) throw err
console.dir(msg)
console.log('msg.id=' + msg.id)
console.log('msg.ack=' + msg.ack)
console.log('msg.payload=' + msg.payload) // 'Hello, World!'
console.log('msg.tries=' + msg.tries)
queue.ack( msg.ack, console.error )
done()
}catch(e){
console.error(e)
done()
}
})
}
client.connect( async (err) => {
const db = client.db('test')
console.log("connected")
try{
const queue = await ParseQ.get(db,'Q_email')
queue.add({foo:123}, (err, id) => {
// Message with payload 'Hello, World!' added.
// 'id' is returned, useful for logging.
})
work(queue)
}catch(e){ console.error(e) }
})
| 26.145833 | 94 | 0.635857 |
3d9d1bdcb1ef3cdfcddec65702cdd8b3936e9ba2 | 3,457 | js | JavaScript | studio/node_modules/@sanity/base/lib/datastores/document/listenQuery.js | liammews/Briefrr | da164d300ce5914fd8bad209fd90850ebb3bea95 | [
"MIT"
] | 3 | 2018-03-25T02:20:11.000Z | 2021-06-15T07:30:27.000Z | studio/node_modules/@sanity/base/lib/datastores/document/listenQuery.js | liammews/Briefrr | da164d300ce5914fd8bad209fd90850ebb3bea95 | [
"MIT"
] | 38 | 2018-03-30T19:12:20.000Z | 2022-03-28T07:25:07.000Z | studio/node_modules/@sanity/base/lib/datastores/document/listenQuery.js | liammews/Briefrr | da164d300ce5914fd8bad209fd90850ebb3bea95 | [
"MIT"
] | 1 | 2018-03-30T19:09:35.000Z | 2018-03-30T19:09:35.000Z | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.listenQuery = void 0;
var _client = _interopRequireDefault(require("part:@sanity/base/client"));
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var fetch = (query, params) => (0, _rxjs.defer)(() => _client.default.observable.fetch(query, params));
var listen = (query, params) => (0, _rxjs.defer)(() => _client.default.listen(query, params, {
events: ['welcome', 'mutation', 'reconnect'],
includeResult: false,
visibility: 'query'
}));
function isWelcomeEvent(event) {
return event.type === 'welcome';
} // todo: promote as building block for better re-use
// todo: optimize by patching collection in-place
var listenQuery = (query, params) => {
var fetchOnce$ = fetch(query, params);
var events$ = listen(query, params).pipe((0, _operators.mergeMap)((ev, i) => {
var isFirst = i === 0;
if (isFirst && !isWelcomeEvent(ev)) {
// if the first event is not welcome, it is most likely a reconnect and
// if it's not a reconnect something is very wrong
return (0, _rxjs.throwError)(new Error(ev.type === 'reconnect' ? 'Could not establish EventSource connection' : "Received unexpected type of first event \"".concat(ev.type, "\"")));
}
return (0, _rxjs.of)(ev);
}), (0, _operators.share)());
var _partition = (0, _rxjs.partition)(events$, isWelcomeEvent),
_partition2 = _slicedToArray(_partition, 2),
welcome$ = _partition2[0],
mutationAndReconnect$ = _partition2[1];
return (0, _rxjs.merge)(welcome$.pipe((0, _operators.take)(1)), mutationAndReconnect$.pipe((0, _operators.throttleTime)(1000, _rxjs.asyncScheduler, {
leading: true,
trailing: true
}))).pipe((0, _operators.switchMapTo)(fetchOnce$));
};
exports.listenQuery = listenQuery; | 51.597015 | 489 | 0.667342 |
3dacc274d732275924b9baa52372ca3e4511e3c4 | 213 | js | JavaScript | public/script/main.js | Diegooliveyra/dashboard-road-to-dev | c1156887ec4b5b107b33af4f33b709bc52e0bee6 | [
"MIT"
] | 1 | 2021-07-01T20:45:19.000Z | 2021-07-01T20:45:19.000Z | public/script/main.js | Diegooliveyra/dashboard-road-to-dev | c1156887ec4b5b107b33af4f33b709bc52e0bee6 | [
"MIT"
] | null | null | null | public/script/main.js | Diegooliveyra/dashboard-road-to-dev | c1156887ec4b5b107b33af4f33b709bc52e0bee6 | [
"MIT"
] | null | null | null | import menuMobile from "./menu-mobile.js";
import navCourses from "./nav-cousers.js";
import contador from './contador.js'
import dropMenu from './dropMenu.js'
menuMobile();
navCourses();
contador();
dropMenu(); | 21.3 | 42 | 0.732394 |
3db5156c2ef5d3b210adf42d38785a914bb978e0 | 531 | js | JavaScript | src/store.js | rcereghini/open-mat | 557573f721c6d07e1367780b3ffaa08365b86aee | [
"MIT"
] | 9 | 2019-03-21T12:27:28.000Z | 2021-10-12T04:00:11.000Z | src/store.js | rcereghini/open-mat | 557573f721c6d07e1367780b3ffaa08365b86aee | [
"MIT"
] | 6 | 2021-08-31T18:18:31.000Z | 2022-02-27T00:07:43.000Z | src/store.js | rcereghini/open-mat | 557573f721c6d07e1367780b3ffaa08365b86aee | [
"MIT"
] | 4 | 2019-04-13T21:58:32.000Z | 2021-09-03T15:41:59.000Z | import { createStore, combineReducers, compose } from 'redux'
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase'
const rrfConfig = {
userProfile: 'users',
}
export const createStoreWithFirebase = firebase => {
const createStoreWithFirebase = compose(
reactReduxFirebase(firebase, rrfConfig)
)(createStore)
const rootReducer = combineReducers({
firebase: firebaseReducer,
})
const initialState = {}
const store = createStoreWithFirebase(rootReducer, initialState)
return store
}
| 24.136364 | 74 | 0.753296 |
3db9c5b18251511671e534001831f9a81476e55c | 354 | js | JavaScript | components/__tests__/ViewIcon.test.js | ReactNativeGallery/reactnative-gallery-web | 23b0da7aa46b629151017635d5a492255d625f5f | [
"MIT"
] | 56 | 2018-03-14T22:31:21.000Z | 2021-12-06T12:24:50.000Z | components/__tests__/ViewIcon.test.js | jackburrus/reactnative-gallery-web | 67b78699a304ce44a075c004863aff264ea62c5f | [
"MIT"
] | 9 | 2020-08-19T21:17:30.000Z | 2021-12-09T01:01:17.000Z | components/__tests__/ViewIcon.test.js | jackburrus/reactnative-gallery-web | 67b78699a304ce44a075c004863aff264ea62c5f | [
"MIT"
] | 5 | 2018-05-12T13:26:37.000Z | 2021-06-19T00:19:26.000Z | import React from 'react'
import renderer from 'react-test-renderer'
import ViewIcon from '../ViewIcon'
it('ViewIcon can be created', () => {
const comp = renderer.create(<ViewIcon />)
expect(comp).toBeDefined()
})
it('<ViewIcon /> toMatchSnapshot', () => {
const tree = renderer.create(<ViewIcon />).toJSON()
expect(tree).toMatchSnapshot()
})
| 25.285714 | 53 | 0.683616 |
3daa605177c85be8f2928fcaf1ba80c27fe98de3 | 134 | js | JavaScript | .storybook/manager.js | autoguru-au/overdrive | 3ac26bfc7260498f08355cfb189e7fb6a7fbc390 | [
"MIT"
] | 41 | 2019-03-05T11:21:14.000Z | 2022-01-05T09:33:00.000Z | .storybook/manager.js | autoguru-au/overdrive | 3ac26bfc7260498f08355cfb189e7fb6a7fbc390 | [
"MIT"
] | 589 | 2019-03-06T07:27:48.000Z | 2022-03-22T06:58:27.000Z | .storybook/manager.js | autoguru-au/overdrive | 3ac26bfc7260498f08355cfb189e7fb6a7fbc390 | [
"MIT"
] | 2 | 2021-03-09T05:53:25.000Z | 2022-01-05T10:32:46.000Z | import { addons } from '@storybook/addons';
import { themes } from '@storybook/theming';
addons.setConfig({
theme: themes.dark,
});
| 19.142857 | 44 | 0.69403 |
3dbdf87f4b8afc5dd6d7cfaa78930d57a65e1288 | 367 | js | JavaScript | node_modules/react-icons/io/android-cloud.js | antarikshray/websiterudra | 7043525ac75866c829f065b63645bdd95ae98138 | [
"MIT"
] | 2 | 2020-01-14T14:00:46.000Z | 2022-01-06T04:46:01.000Z | node_modules/react-icons/io/android-cloud.js | antarikshray/websiterudra | 7043525ac75866c829f065b63645bdd95ae98138 | [
"MIT"
] | 26 | 2020-07-21T06:38:39.000Z | 2022-03-26T23:23:58.000Z | node_modules/react-icons/io/android-cloud.js | antarikshray/websiterudra | 7043525ac75866c829f065b63645bdd95ae98138 | [
"MIT"
] | 5 | 2018-03-30T14:14:30.000Z | 2020-10-20T21:50:21.000Z |
import React from 'react'
import Icon from 'react-icon-base'
const IoAndroidCloud = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m31.2 17c4.1 0.2 7.3 3.5 7.3 7.7 0 4.3-3.5 7.8-7.8 7.8h-20.3c-5.2 0-9.4-4.2-9.4-9.4 0-4.8 3.7-8.8 8.4-9.3 1.9-3.7 5.8-6.3 10.3-6.3 5.8 0 10.4 4.1 11.5 9.5z"/></g>
</Icon>
)
export default IoAndroidCloud
| 30.583333 | 182 | 0.585831 |
3dcca045f3bb4783b88c03ffd305e797ee87de3b | 241 | js | JavaScript | gatsby-ssr.js | pittica/site | 07b2fabd79f3bb79c050201c46d5f8ba13d99939 | [
"MIT"
] | 2 | 2020-09-28T23:13:51.000Z | 2022-01-10T00:21:25.000Z | gatsby-ssr.js | pittica/site | 07b2fabd79f3bb79c050201c46d5f8ba13d99939 | [
"MIT"
] | null | null | null | gatsby-ssr.js | pittica/site | 07b2fabd79f3bb79c050201c46d5f8ba13d99939 | [
"MIT"
] | 1 | 2022-01-30T16:11:33.000Z | 2022-01-30T16:11:33.000Z | export { wrapRootElement } from "./gatsby-browser"
export const onRenderBody = ({ setHtmlAttributes }) => {
setHtmlAttributes({
itemScope: true,
itemType: "http://schema.org/WebPage",
className: "has-navbar-fixed-top",
})
}
| 24.1 | 56 | 0.672199 |
3dc633d650620dfb3e90f1b02b7497965e150f6f | 237 | js | JavaScript | notifications/notification.types.js | chrispaskvan/destiny-ghost-api | 4e708def610837d00734025257b0bd045d3b8932 | [
"MIT"
] | 6 | 2016-01-16T14:23:17.000Z | 2022-01-21T04:09:40.000Z | notifications/notification.types.js | chrispaskvan/destiny-ghost-api | 4e708def610837d00734025257b0bd045d3b8932 | [
"MIT"
] | 15 | 2017-11-05T21:28:39.000Z | 2022-03-07T02:41:26.000Z | notifications/notification.types.js | chrispaskvan/destiny-ghost-api | 4e708def610837d00734025257b0bd045d3b8932 | [
"MIT"
] | 1 | 2020-04-12T14:05:47.000Z | 2020-04-12T14:05:47.000Z | /**
* Allowed Actions
* @type {{Gunsmith: string, Xur: string}}
*/
const notificationTypes = {
Foundry: 'Orders',
Gunsmith: 'Banshee-44',
IronBanner: 'Lord Saladin',
Xur: 'Xur',
};
module.exports = notificationTypes;
| 18.230769 | 42 | 0.632911 |
3db82d1d5c8da009fc51d35ef141d8a70a399a27 | 163 | js | JavaScript | migrations/2_deploy.js | soralit/nft-toolkit | 3df5ccfd033d1ca598db8d7eeba962f0498b877b | [
"MIT"
] | 17 | 2021-05-04T17:45:06.000Z | 2022-01-26T11:42:36.000Z | migrations/2_deploy.js | soralit/nft-toolkit | 3df5ccfd033d1ca598db8d7eeba962f0498b877b | [
"MIT"
] | null | null | null | migrations/2_deploy.js | soralit/nft-toolkit | 3df5ccfd033d1ca598db8d7eeba962f0498b877b | [
"MIT"
] | 1 | 2021-04-05T12:44:28.000Z | 2021-04-05T12:44:28.000Z | // migrations/2_deploy.js
// SPDX-License-Identifier: MIT
const Box = artifacts.require("MyNFT");
module.exports = function(deployer) {
deployer.deploy(Box);
}; | 23.285714 | 39 | 0.730061 |
3da22df73c3a7ca69845f9673d097630ad23219b | 139 | js | JavaScript | glossary/index.js | designstem/projects | 757d1946506509e06368ed9d110a75bc0cfe383b | [
"MIT"
] | 1 | 2022-02-12T17:47:16.000Z | 2022-02-12T17:47:16.000Z | glossary/index.js | designstem/projects | 757d1946506509e06368ed9d110a75bc0cfe383b | [
"MIT"
] | null | null | null | glossary/index.js | designstem/projects | 757d1946506509e06368ed9d110a75bc0cfe383b | [
"MIT"
] | null | null | null | import { fachwerk } from "https://designstem.github.io/fachwerk/fachwerk.js";
fachwerk({ type: 'document', editor: 'none', menu: 'none' }) | 46.333333 | 77 | 0.697842 |
3da98811ece1ab95552818018642756626538e53 | 450 | js | JavaScript | ui/app/pages/send/send-footer/send-footer.selectors.js | Conflux-Chain/conflux-portal | e16c680b5c63cbcdc961ac859d1307fb159c6def | [
"MIT"
] | 66 | 2020-01-16T11:30:43.000Z | 2022-02-15T08:51:20.000Z | ui/app/pages/send/send-footer/send-footer.selectors.js | Conflux-Chain/conflux-portal | e16c680b5c63cbcdc961ac859d1307fb159c6def | [
"MIT"
] | 293 | 2020-01-19T02:25:08.000Z | 2022-03-02T09:43:26.000Z | ui/app/pages/send/send-footer/send-footer.selectors.js | Conflux-Chain/conflux-portal | e16c680b5c63cbcdc961ac859d1307fb159c6def | [
"MIT"
] | 18 | 2020-02-17T08:07:03.000Z | 2022-01-18T09:22:26.000Z | import { getSendErrors } from '../send.selectors'
export function isSendFormInError(state, advancedInlineGasShown) {
const sendErrors = { ...getSendErrors(state) }
// when advancedInlineGasShown is false, there's no gas ui in send component,
// so we shouldn't check gas here
if (!advancedInlineGasShown) {
sendErrors.gasAndCollateralFee = null
sendErrors.gasPriceTooLow = null
}
return Object.values(sendErrors).some(n => n)
}
| 32.142857 | 79 | 0.735556 |
3dc3385025be6a5af70885d9fb8c4236c27c36b7 | 765 | js | JavaScript | login/src/Hero.js | lamodots/Dashboard-Login-by-Batuhan-Kara- | 1c5c535c7838ff7ea5df7bcdfc0d9bb0fe0addf6 | [
"MIT"
] | 1 | 2022-03-11T23:07:17.000Z | 2022-03-11T23:07:17.000Z | login/src/Hero.js | lamodots/Dashboard-Login | 1c5c535c7838ff7ea5df7bcdfc0d9bb0fe0addf6 | [
"MIT"
] | null | null | null | login/src/Hero.js | lamodots/Dashboard-Login | 1c5c535c7838ff7ea5df7bcdfc0d9bb0fe0addf6 | [
"MIT"
] | null | null | null | import illustration from './images/ill.jpg';
import './App.css';
function Hero(){
return(
<div className="Container">
<div className="Hero-Container">
<div className="Content">
<h1 className="Heading-1">Ominicron Studios</h1>
<p className="HeroParagraph">We make sure you have fun to the fullest. comment with different game players from all over the globe.</p>
<a className="Cta" href="https://www.reactjs.org">Get started</a>
</div>
<div className="Illustration">
<img src={illustration} alt="Ominicro identitity" className="illustare" />
</div>
</div>
</div>
);
}
export default Hero; | 29.423077 | 151 | 0.559477 |
3dc4e68579c2bc28f979cb9b14659f54290ddb2a | 2,990 | js | JavaScript | src/context-menu.js | danmarshall/piling.js | d053a7135e0e83ebc11bb26bf006f9f504c74c13 | [
"MIT"
] | 84 | 2019-10-30T11:39:37.000Z | 2022-03-31T08:59:27.000Z | src/context-menu.js | danmarshall/piling.js | d053a7135e0e83ebc11bb26bf006f9f504c74c13 | [
"MIT"
] | 180 | 2019-10-29T17:51:38.000Z | 2022-02-28T03:47:00.000Z | src/context-menu.js | danmarshall/piling.js | d053a7135e0e83ebc11bb26bf006f9f504c74c13 | [
"MIT"
] | 7 | 2021-04-22T01:43:16.000Z | 2022-03-26T10:45:21.000Z | import styleToCss from 'style-object-to-css-string';
const STYLES_ROOT = {
position: 'absolute',
zIndex: 2,
display: 'none',
};
const STYLES_UL = {
listStyle: 'none',
padding: 0,
margin: 0,
borderRadius: '0.25rem',
backgroundColor: 'white',
boxShadow:
'0 0 0 1px rgba(0, 0, 0, 0.25), 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 2px 6px 0 rgba(0, 0, 0, 0.075)',
};
const STYLES_BUTTON = {
width: '100%',
height: '1.5rem',
margin: 0,
padding: '0.25rem 0.5rem',
fontSize: '0.85rem',
color: 'black',
border: 'none',
backgroundColor: 'transparent',
cursor: 'pointer',
outline: 'none',
whiteSpace: 'nowrap',
};
const STYLES_BUTTON_HOVER = {
backgroundColor: '#ff7ff6',
};
const STYLES_BUTTON_ACTIVE = {
backgroundColor: '#dd33ff',
};
const STYLES_BUTTON_INACTIVE = {
cursor: 'default',
opacity: 0.3,
backgroundColor: 'transparent !important',
};
const STYLES_FIRST_BUTTON = {
borderRadius: '0.25rem 0.25rem 0 0',
};
const STYLES_LAST_BUTTON = {
borderRadius: '0 0 0.25rem 0.25rem',
};
const STYLES = {
root: STYLES_ROOT,
ul: STYLES_UL,
button: STYLES_BUTTON,
'button:hover': STYLES_BUTTON_HOVER,
'button:active': STYLES_BUTTON_ACTIVE,
'button.inactive': STYLES_BUTTON_INACTIVE,
'li:first-child > button': STYLES_FIRST_BUTTON,
'li:last-child > button': STYLES_LAST_BUTTON,
};
const TEMPLATE = `<ul id="piling-js-context-menu-list">
<li>
<button id="depile-button">Depile</button>
</li>
<li>
<button id="temp-depile-button">Temp. Depile</button>
</li>
<li>
<button id="browse-separately">Browse Separately</button>
</li>
<li>
<button id="grid-button">Show Grid</button>
</li>
<li>
<button id="align-button">Align by Grid</button>
</li>
<li>
<button id="magnify-button">Magnify</button>
</li>
</ul>`;
const createContextMenu = ({
template = TEMPLATE,
styles = STYLES,
customItems = [],
} = {}) => {
const rootElement = document.createElement('nav');
rootElement.id = 'piling-js-context-menu';
// Create CSS
const css = document.createElement('style');
css.setAttribute('type', 'text/css');
let cssString = '';
Object.entries(styles).forEach(([key, value]) => {
const identifier = key === 'root' ? '' : ` ${key}`;
cssString += `#piling-js-context-menu${identifier} { ${styleToCss(
value
)} }\n`;
});
css.textContent = cssString;
rootElement.appendChild(css);
// Add menu
rootElement.insertAdjacentHTML('beforeend', template);
// Add custom items
const ul = rootElement.querySelector('#piling-js-context-menu-list');
customItems.forEach((item, index) => {
const li = document.createElement('li');
const button = document.createElement('button');
button.textContent = item.label;
if (item.id) button.id = item.id;
else button.id = `piling-js-context-menu-custom-item-${index}`;
li.appendChild(button);
ul.appendChild(li);
});
return rootElement;
};
export default createContextMenu;
| 22.651515 | 102 | 0.651171 |
3dba4d2a27d02d9ab00a7bac158aaf75b827952d | 648 | js | JavaScript | src/drop-down-list/inline.js | Saranya13/ej2-javascript-samples | 7d4badab3b239d611c6c084116dfe35823fb5d76 | [
"FSFAP"
] | 1 | 2020-07-23T20:36:00.000Z | 2020-07-23T20:36:00.000Z | src/drop-down-list/inline.js | Saranya13/ej2-javascript-samples | 7d4badab3b239d611c6c084116dfe35823fb5d76 | [
"FSFAP"
] | null | null | null | src/drop-down-list/inline.js | Saranya13/ej2-javascript-samples | 7d4badab3b239d611c6c084116dfe35823fb5d76 | [
"FSFAP"
] | null | null | null | this.default = function () {
// initialize DropDownList component
var dropDownListObj = new ej.dropdowns.DropDownList({
// set the employees data to dataSource property
dataSource: window.inlineData,
// map the appropriate columns to fields property
fields: { text: 'Name' },
value: 'Michael',
// set the placeholder to DropDownList input element
placeholder: 'Select an employee',
// set the width to component
width: '60px',
popupWidth: '140px',
popupHeight: '200px',
cssClass:'inlinecss'
});
dropDownListObj.appendTo('#inline');
};
| 32.4 | 60 | 0.621914 |
3d9ed570c9f56cad146e4edb7282e6caec4dbf2a | 906 | js | JavaScript | shared/src/persistence/dynamo/workitems/updateWorkItemDocketNumberSuffix.js | cogentcloud/ef-cms | d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f | [
"CC0-1.0"
] | null | null | null | shared/src/persistence/dynamo/workitems/updateWorkItemDocketNumberSuffix.js | cogentcloud/ef-cms | d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f | [
"CC0-1.0"
] | null | null | null | shared/src/persistence/dynamo/workitems/updateWorkItemDocketNumberSuffix.js | cogentcloud/ef-cms | d6f8105bbc4e552c4764f7f2cdfbf9fb75f9594f | [
"CC0-1.0"
] | 1 | 2020-04-04T10:31:46.000Z | 2020-04-04T10:31:46.000Z | const client = require('../../dynamodbClientService');
exports.updateWorkItemDocketNumberSuffix = async ({
applicationContext,
docketNumberSuffix,
workItemId,
}) => {
const workItems = await client.query({
ExpressionAttributeNames: {
'#gsi1pk': 'gsi1pk',
},
ExpressionAttributeValues: {
':gsi1pk': `workitem-${workItemId}`,
},
IndexName: 'gsi1',
KeyConditionExpression: '#gsi1pk = :gsi1pk',
applicationContext,
});
for (let workItem of workItems) {
await client.update({
ExpressionAttributeNames: {
'#docketNumberSuffix': 'docketNumberSuffix',
},
ExpressionAttributeValues: {
':docketNumberSuffix': docketNumberSuffix,
},
Key: {
pk: workItem.pk,
sk: workItem.sk,
},
UpdateExpression: 'SET #docketNumberSuffix = :docketNumberSuffix',
applicationContext,
});
}
};
| 24.486486 | 72 | 0.631347 |
3da8efa29e8119369024707ec55d63ca6ddc03f7 | 918 | js | JavaScript | methodOf.js | dioxide/lodash-learning | 3dd52b4af3a0fc1e7be50e26ca311727ba2d7fa9 | [
"CC0-1.0"
] | null | null | null | methodOf.js | dioxide/lodash-learning | 3dd52b4af3a0fc1e7be50e26ca311727ba2d7fa9 | [
"CC0-1.0"
] | null | null | null | methodOf.js | dioxide/lodash-learning | 3dd52b4af3a0fc1e7be50e26ca311727ba2d7fa9 | [
"CC0-1.0"
] | null | null | null | import invoke from './invoke.js'
/**
* The opposite of `method` this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
* 与`method`相对的方法,此方法创建一个函数,该函数在给定的对象`object`的路径`path`处调用该方法。
* 任何其他参数都提供给调用的方法。
*
* @since 3.7.0
* @category Util
* @param {Object} object The object to query. 要查询的对象
* @param {Array} [args] The arguments to invoke the method with. 调用方法时的参数
* @returns {Function} Returns the new invoker function. 新的函数
* @example
*
* const array = times(3, i => () => i)
* const object = { 'a': array, 'b': array, 'c': array }
*
* map(['a[2]', 'c[0]'], methodOf(object))
* // => [2, 0]
*
* map([['a', '2'], ['c', '0']], methodOf(object))
* // => [2, 0]f
*/
function methodOf(object, args) {
return (path) => invoke(object, path, args) // 借调invoke来实现指定路径调用,但path可由调用时指定
}
export default methodOf
| 29.612903 | 79 | 0.64488 |
3dc91eebca5ae1c8caa12d2c59c572042d277728 | 71 | js | JavaScript | src/components/categories/DesignElements/Typography/index.js | tinkertrain/sguide | 4426db973ce831e1858787b1b26954f9aa4e9821 | [
"CC0-1.0"
] | 29 | 2019-03-15T12:56:14.000Z | 2022-03-29T10:20:12.000Z | src/components/categories/DesignElements/Typography/index.js | tinkertrain/sguide | 4426db973ce831e1858787b1b26954f9aa4e9821 | [
"CC0-1.0"
] | 1,052 | 2019-03-22T09:58:11.000Z | 2022-03-29T15:07:20.000Z | src/components/categories/DesignElements/Typography/index.js | tinkertrain/sguide | 4426db973ce831e1858787b1b26954f9aa4e9821 | [
"CC0-1.0"
] | 6 | 2019-06-17T08:58:06.000Z | 2021-07-07T14:11:02.000Z | import { Typography } from './Typography';
export default Typography;
| 17.75 | 42 | 0.746479 |
3dba30f30da8b1d9993b2e85a8a8dca49a1024fe | 258 | js | JavaScript | data/js/00/0c/5f/00/00/00.24.js | p-g-krish/deepmac-tracker | 44d625a6b1ec30bf52f8d12a44b0afc594eb5f94 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | data/js/00/0c/5f/00/00/00.24.js | p-g-krish/deepmac-tracker | 44d625a6b1ec30bf52f8d12a44b0afc594eb5f94 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | data/js/00/0c/5f/00/00/00.24.js | p-g-krish/deepmac-tracker | 44d625a6b1ec30bf52f8d12a44b0afc594eb5f94 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | deepmacDetailCallback("000c5f000000/24",[{"d":"2003-02-07","t":"add","a":"4335 Augusta Hwy\nGilbert SC 29054\n\n","c":"UNITED STATES","o":"Avtec, Inc."},{"d":"2015-08-27","t":"change","a":"4335 Augusta Hwy Gilbert SC US 29054","c":"US","o":"Avtec, Inc."}]);
| 129 | 257 | 0.624031 |
3db6bbd190f4d0650d69ba8983fa53460a336fa2 | 2,022 | js | JavaScript | client/src/pages/Login.js | al-moreno/MERN-eCommerce | d26ed133be67035fafa3046f8cd7195d1416c0da | [
"Unlicense"
] | null | null | null | client/src/pages/Login.js | al-moreno/MERN-eCommerce | d26ed133be67035fafa3046f8cd7195d1416c0da | [
"Unlicense"
] | 1 | 2021-09-25T23:04:03.000Z | 2021-09-25T23:04:03.000Z | client/src/pages/Login.js | al-moreno/MERN-eCommerce | d26ed133be67035fafa3046f8cd7195d1416c0da | [
"Unlicense"
] | null | null | null | import React, { useState } from 'react';
import axios from "axios";
import './Signup.css';
function Login(props) {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const signupFormHandler = (event) => {
event.preventDefault();
if (email && password) {
axios.post('/api/users/login', {
email,
password
})
.then((response) => {
const userData = response && response.data ? response.data : '';
//save the token and the user
localStorage.setItem("user", JSON.stringify(userData));
props.history.push("/");
window.location.reload();
}).catch((err) => {
alert(err.response.data);
})
}
};
return (
<main>
<div className="col-1">
<form onSubmit={(e) => signupFormHandler(e)} className="card-body card">
<div>
<h3> Login </h3>
</div>
<div className="row ">
<label for="text" type="input" className="form-label">Email</label>
<input type="email" onChange={(e) => setEmail(e.target.value)} className="form-control" id="email-login" />
</div>
<div class="row ">
<label for="exampleInputPassword1" className="form-label">Password</label>
<input type="password" onChange={(e) => setPassword(e.target.value)} className="form-control" id="password-login" />
</div>
<div class="row ">
<label>Welcome Back</label >
<input type="submit" value="Login" className=" " />
</div>
</form>
</div>
</main>
);
}
export default Login;
| 35.473684 | 140 | 0.451533 |
3dc68e5869f8330a6bf01b7e4708dd1f2b54f31d | 974 | js | JavaScript | src/components/Header.js | josh-robbs/wandwizardquiz | be11a87c0e4538486bf2eac42cec089b39585ecc | [
"Unlicense"
] | null | null | null | src/components/Header.js | josh-robbs/wandwizardquiz | be11a87c0e4538486bf2eac42cec089b39585ecc | [
"Unlicense"
] | null | null | null | src/components/Header.js | josh-robbs/wandwizardquiz | be11a87c0e4538486bf2eac42cec089b39585ecc | [
"Unlicense"
] | null | null | null | import React from 'react'
const Header = () => {
return (
<header>
<div className="header flex">
<img src="https://vignette.wikia.nocookie.net/harrypotter/images/8/8e/0.31_Gryffindor_Crest_Transparent.png/revision/latest?cb=20161124074004"
alt="gryffindor crest" />
<img src="https://vignette.wikia.nocookie.net/harrypotter/images/4/40/Ravenclaw_Crest_1.png/revision/latest?cb=20150413213520"
alt="ravenclaw crest"/>
<h1>The Wand Chooses the Wizard.</h1>
<img src="https://vignette.wikia.nocookie.net/harrypotter/images/d/d3/0.61_Slytherin_Crest_Transparent.png/revision/latest?cb=20161020182557"
alt="slytherin crest"/>
<img src="https://vignette.wikia.nocookie.net/harrypotter/images/5/50/0.51_Hufflepuff_Crest_Transparent.png/revision/latest?cb=20161020182518"
alt="hufflepuff crest"/>
</div>
</header>
)
}
export default Header | 37.461538 | 152 | 0.671458 |
3dc701e298a50b2a5c8683261294f8216a087b40 | 242 | js | JavaScript | client/src/services/serverAPI.js | halkim44/trello-clone | 2b3e855e5910d57d09dfa45dae7ed8378620ce6f | [
"Unlicense",
"MIT"
] | null | null | null | client/src/services/serverAPI.js | halkim44/trello-clone | 2b3e855e5910d57d09dfa45dae7ed8378620ce6f | [
"Unlicense",
"MIT"
] | 3 | 2021-01-14T12:53:54.000Z | 2021-01-14T12:59:19.000Z | client/src/services/serverAPI.js | halkim44/trello-clone | 2b3e855e5910d57d09dfa45dae7ed8378620ce6f | [
"Unlicense",
"MIT"
] | null | null | null | import axios from "axios";
const serverUrl =
process.env.NODE_ENV === "production"
? "https://immense-wave-33493.herokuapp.com"
: "http://localhost:3000";
export const serverAPI = axios.create({
baseURL: `${serverUrl}/api`,
});
| 22 | 48 | 0.669421 |
3d9d7979d5f01559d1a026dce9d88f4cc69c142c | 6,633 | js | JavaScript | scripts/system/controllers/controllerModules/webSurfaceLaserInput.js | cain-kilgore/hifi | 51bf3c1466f4e7fe783a81baae4dd96912560c92 | [
"Apache-2.0"
] | null | null | null | scripts/system/controllers/controllerModules/webSurfaceLaserInput.js | cain-kilgore/hifi | 51bf3c1466f4e7fe783a81baae4dd96912560c92 | [
"Apache-2.0"
] | null | null | null | scripts/system/controllers/controllerModules/webSurfaceLaserInput.js | cain-kilgore/hifi | 51bf3c1466f4e7fe783a81baae4dd96912560c92 | [
"Apache-2.0"
] | null | null | null | "use strict";
// webSurfaceLaserInput.js
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
/* global Script, Entities, Controller, RIGHT_HAND, LEFT_HAND, enableDispatcherModule, disableDispatcherModule,
makeRunningValues, Messages, Quat, Vec3, makeDispatcherModuleParameters, Overlays, ZERO_VEC, HMD,
INCHES_TO_METERS, DEFAULT_REGISTRATION_POINT, getGrabPointSphereOffset, COLORS_GRAB_SEARCHING_HALF_SQUEEZE,
COLORS_GRAB_SEARCHING_FULL_SQUEEZE, COLORS_GRAB_DISTANCE_HOLD, DEFAULT_SEARCH_SPHERE_DISTANCE, TRIGGER_ON_VALUE,
TRIGGER_OFF_VALUE, getEnabledModuleByName, PICK_MAX_DISTANCE, LaserPointers, RayPick, ContextOverlay, Picks, makeLaserParams
*/
Script.include("/~/system/libraries/controllerDispatcherUtils.js");
Script.include("/~/system/libraries/controllers.js");
(function() {
function WebSurfaceLaserInput(hand) {
this.hand = hand;
this.otherHand = this.hand === RIGHT_HAND ? LEFT_HAND : RIGHT_HAND;
this.running = false;
this.parameters = makeDispatcherModuleParameters(
120,
this.hand === RIGHT_HAND ? ["rightHand"] : ["leftHand"],
[],
100,
makeLaserParams(hand, true));
this.grabModuleWantsNearbyOverlay = function(controllerData) {
if (controllerData.triggerValues[this.hand] > TRIGGER_ON_VALUE) {
var nearGrabName = this.hand === RIGHT_HAND ? "RightNearParentingGrabOverlay" : "LeftNearParentingGrabOverlay";
var nearGrabModule = getEnabledModuleByName(nearGrabName);
if (nearGrabModule) {
var candidateOverlays = controllerData.nearbyOverlayIDs[this.hand];
var grabbableOverlays = candidateOverlays.filter(function(overlayID) {
return Overlays.getProperty(overlayID, "grabbable");
});
var target = nearGrabModule.getTargetID(grabbableOverlays, controllerData);
if (target) {
return true;
}
}
}
return false;
};
this.getOtherModule = function() {
return this.hand === RIGHT_HAND ? leftOverlayLaserInput : rightOverlayLaserInput;
};
this.isPointingAtWebEntity = function(controllerData) {
var intersection = controllerData.rayPicks[this.hand];
var entityProperty = Entities.getEntityProperties(intersection.objectID);
var entityType = entityProperty.type;
if ((intersection.type === Picks.INTERSECTED_ENTITY && entityType === "Web")) {
return true;
}
return false;
};
this.isPointingAtOverlay = function(controllerData) {
var intersection = controllerData.rayPicks[this.hand];
return intersection.type === Picks.INTERSECTED_OVERLAY;
};
this.deleteContextOverlay = function() {
var farGrabModule = getEnabledModuleByName(this.hand === RIGHT_HAND
? "RightFarActionGrabEntity" : "LeftFarActionGrabEntity");
if (farGrabModule) {
var entityWithContextOverlay = farGrabModule.entityWithContextOverlay;
if (entityWithContextOverlay) {
ContextOverlay.destroyContextOverlay(entityWithContextOverlay);
farGrabModule.entityWithContextOverlay = false;
}
}
};
this.updateAllwaysOn = function() {
var PREFER_STYLUS_OVER_LASER = "preferStylusOverLaser";
this.parameters.handLaser.allwaysOn = !Settings.getValue(PREFER_STYLUS_OVER_LASER, false);
};
this.getDominantHand = function() {
return MyAvatar.getDominantHand() === "right" ? 1 : 0;
};
this.dominantHandOverride = false;
this.isReady = function(controllerData) {
var otherModuleRunning = this.getOtherModule().running;
otherModuleRunning = otherModuleRunning && this.getDominantHand() !== this.hand; // Auto-swap to dominant hand.
var isTriggerPressed = controllerData.triggerValues[this.hand] > TRIGGER_OFF_VALUE
&& controllerData.triggerValues[this.otherHand] <= TRIGGER_OFF_VALUE;
if ((!otherModuleRunning || isTriggerPressed)
&& (this.isPointingAtOverlay(controllerData) || this.isPointingAtWebEntity(controllerData))) {
this.updateAllwaysOn();
if (isTriggerPressed) {
this.dominantHandOverride = true; // Override dominant hand.
this.getOtherModule().dominantHandOverride = false;
}
if (this.parameters.handLaser.allwaysOn || isTriggerPressed) {
return makeRunningValues(true, [], []);
}
}
return makeRunningValues(false, [], []);
};
this.run = function(controllerData, deltaTime) {
var otherModuleRunning = this.getOtherModule().running;
otherModuleRunning = otherModuleRunning && this.getDominantHand() !== this.hand; // Auto-swap to dominant hand.
otherModuleRunning = otherModuleRunning || this.getOtherModule().dominantHandOverride; // Override dominant hand.
var grabModuleNeedsToRun = this.grabModuleWantsNearbyOverlay(controllerData);
if (!otherModuleRunning && !grabModuleNeedsToRun && (controllerData.triggerValues[this.hand] > TRIGGER_OFF_VALUE
|| this.parameters.handLaser.allwaysOn
&& (this.isPointingAtOverlay(controllerData) || this.isPointingAtWebEntity(controllerData)))) {
this.running = true;
return makeRunningValues(true, [], []);
}
this.deleteContextOverlay();
this.running = false;
this.dominantHandOverride = false;
return makeRunningValues(false, [], []);
};
}
var leftOverlayLaserInput = new WebSurfaceLaserInput(LEFT_HAND);
var rightOverlayLaserInput = new WebSurfaceLaserInput(RIGHT_HAND);
enableDispatcherModule("LeftWebSurfaceLaserInput", leftOverlayLaserInput);
enableDispatcherModule("RightWebSurfaceLaserInput", rightOverlayLaserInput);
function cleanup() {
disableDispatcherModule("LeftWebSurfaceLaserInput");
disableDispatcherModule("RightWebSurfaceLaserInput");
}
Script.scriptEnding.connect(cleanup);
}());
| 47.042553 | 127 | 0.640434 |
3da023010f0fc40a5f4796dd02939717e85fddbc | 10,804 | js | JavaScript | modules/UI/UI.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | modules/UI/UI.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | modules/UI/UI.js | navalsynergy/jitsi | 33891094a69579ef9480d74f86c7324be6187747 | [
"Apache-2.0"
] | null | null | null | /* global APP, $, config */
const UI = {};
import EventEmitter from 'events';
import Logger from 'jitsi-meet-logger';
import { isMobileBrowser } from '../../react/features/base/environment/utils';
import { setColorAlpha } from '../../react/features/base/util';
import { setDocumentUrl } from '../../react/features/etherpad';
import { setFilmstripVisible } from '../../react/features/filmstrip';
import { joinLeaveNotificationsDisabled, setNotificationsEnabled } from '../../react/features/notifications';
import {
dockToolbox,
setToolboxEnabled,
showToolbox
} from '../../react/features/toolbox/actions.web';
import UIEvents from '../../service/UI/UIEvents';
import EtherpadManager from './etherpad/Etherpad';
import messageHandler from './util/MessageHandler';
import UIUtil from './util/UIUtil';
import VideoLayout from './videolayout/VideoLayout';
const logger = Logger.getLogger(__filename);
UI.messageHandler = messageHandler;
const eventEmitter = new EventEmitter();
UI.eventEmitter = eventEmitter;
let etherpadManager;
const UIListeners = new Map([
[
UIEvents.ETHERPAD_CLICKED,
() => etherpadManager && etherpadManager.toggleEtherpad()
], [
UIEvents.TOGGLE_FILMSTRIP,
() => UI.toggleFilmstrip()
]
]);
/**
* Indicates if we're currently in full screen mode.
*
* @return {boolean} {true} to indicate that we're currently in full screen
* mode, {false} otherwise
*/
UI.isFullScreen = function() {
return UIUtil.isFullScreen();
};
/**
* Notify user that server has shut down.
*/
UI.notifyGracefulShutdown = function() {
messageHandler.showError({
descriptionKey: 'dialog.gracefulShutdown',
titleKey: 'dialog.serviceUnavailable'
});
};
/**
* Notify user that reservation error happened.
*/
UI.notifyReservationError = function(code, msg) {
messageHandler.showError({
descriptionArguments: {
code,
msg
},
descriptionKey: 'dialog.reservationErrorMsg',
titleKey: 'dialog.reservationError'
});
};
/**
* Initialize conference UI.
*/
UI.initConference = function() {
UI.showToolbar();
};
/**
* Starts the UI module and initializes all related components.
*
* @returns {boolean} true if the UI is ready and the conference should be
* established, false - otherwise (for example in the case of welcome page)
*/
UI.start = function() {
VideoLayout.initLargeVideo();
// Do not animate the video area on UI start (second argument passed into
// resizeVideoArea) because the animation is not visible anyway. Plus with
// the current dom layout, the quality label is part of the video layout and
// will be seen animating in.
VideoLayout.resizeVideoArea();
if (isMobileBrowser()) {
$('body').addClass('mobile-browser');
} else {
$('body').addClass('desktop-browser');
if (config.backgroundAlpha !== undefined) {
const backgroundColor = $('body').css('background-color');
const alphaColor = setColorAlpha(backgroundColor, config.backgroundAlpha);
$('body').css('background-color', alphaColor);
}
}
if (config.iAmRecorder) {
// in case of iAmSipGateway keep local video visible
if (!config.iAmSipGateway) {
APP.store.dispatch(setNotificationsEnabled(false));
}
APP.store.dispatch(setToolboxEnabled(false));
}
};
/**
* Setup some UI event listeners.
*/
UI.registerListeners
= () => UIListeners.forEach((value, key) => UI.addListener(key, value));
/**
* Setup some DOM event listeners.
*/
UI.bindEvents = () => {
/**
*
*/
function onResize() {
VideoLayout.onResize();
}
// Resize and reposition videos in full screen mode.
$(document).on(
'webkitfullscreenchange mozfullscreenchange fullscreenchange',
onResize);
$(window).resize(onResize);
};
/**
* Unbind some DOM event listeners.
*/
UI.unbindEvents = () => {
$(document).off(
'webkitfullscreenchange mozfullscreenchange fullscreenchange');
$(window).off('resize');
};
/**
* Setup and show Etherpad.
* @param {string} name etherpad id
*/
UI.initEtherpad = name => {
if (etherpadManager || !config.etherpad_base || !name) {
return;
}
logger.log('Etherpad is enabled');
etherpadManager = new EtherpadManager(eventEmitter);
const url = new URL(name, config.etherpad_base);
APP.store.dispatch(setDocumentUrl(url.toString()));
if (config.openSharedDocumentOnJoin) {
etherpadManager.toggleEtherpad();
}
};
/**
* Returns the shared document manager object.
* @return {EtherpadManager} the shared document manager object
*/
UI.getSharedDocumentManager = () => etherpadManager;
/**
* Show user on UI.
* @param {JitsiParticipant} user
*/
UI.addUser = function(user) {
const status = user.getStatus();
if (status) {
// FIXME: move updateUserStatus in participantPresenceChanged action
UI.updateUserStatus(user, status);
}
};
/**
* Updates the user status.
*
* @param {JitsiParticipant} user - The user which status we need to update.
* @param {string} status - The new status.
*/
UI.updateUserStatus = (user, status) => {
const reduxState = APP.store.getState() || {};
const { calleeInfoVisible } = reduxState['features/invite'] || {};
// We hide status updates when join/leave notifications are disabled,
// as jigasi is the component with statuses and they are seen as join/leave notifications.
if (!status || calleeInfoVisible || joinLeaveNotificationsDisabled()) {
return;
}
const displayName = user.getDisplayName();
messageHandler.participantNotification(
displayName,
'',
'connected',
'dialOut.statusMessage',
{ status: UIUtil.escapeHtml(status) });
};
/**
* Toggles filmstrip.
*/
UI.toggleFilmstrip = function() {
const { visible } = APP.store.getState()['features/filmstrip'];
APP.store.dispatch(setFilmstripVisible(!visible));
};
/**
* Sets muted audio state for participant
*/
UI.setAudioMuted = function(id) {
// FIXME: Maybe this can be removed!
if (APP.conference.isLocalId(id)) {
APP.conference.updateAudioIconEnabled();
}
};
/**
* Sets muted video state for participant
*/
UI.setVideoMuted = function(id) {
VideoLayout._updateLargeVideoIfDisplayed(id, true);
if (APP.conference.isLocalId(id)) {
APP.conference.updateVideoIconEnabled();
}
};
UI.updateLargeVideo = (id, forceUpdate) => VideoLayout.updateLargeVideo(id, forceUpdate);
/**
* Adds a listener that would be notified on the given type of event.
*
* @param type the type of the event we're listening for
* @param listener a function that would be called when notified
*/
UI.addListener = function(type, listener) {
eventEmitter.on(type, listener);
};
/**
* Removes the all listeners for all events.
*
* @returns {void}
*/
UI.removeAllListeners = function() {
eventEmitter.removeAllListeners();
};
/**
* Emits the event of given type by specifying the parameters in options.
*
* @param type the type of the event we're emitting
* @param options the parameters for the event
*/
UI.emitEvent = (type, ...options) => eventEmitter.emit(type, ...options);
// Used by torture.
UI.showToolbar = timeout => APP.store.dispatch(showToolbox(timeout));
// Used by torture.
UI.dockToolbar = dock => APP.store.dispatch(dockToolbox(dock));
/**
* Updates the displayed avatar for participant.
*
* @param {string} id - User id whose avatar should be updated.
* @param {string} avatarURL - The URL to avatar image to display.
* @returns {void}
*/
UI.refreshAvatarDisplay = function(id) {
VideoLayout.changeUserAvatar(id);
};
/**
* Notify user that connection failed.
* @param {string} stropheErrorMsg raw Strophe error message
*/
UI.notifyConnectionFailed = function(stropheErrorMsg) {
let descriptionKey;
let descriptionArguments;
if (stropheErrorMsg) {
descriptionKey = 'dialog.connectErrorWithMsg';
descriptionArguments = { msg: stropheErrorMsg };
} else {
descriptionKey = 'dialog.connectError';
}
messageHandler.showError({
descriptionArguments,
descriptionKey,
titleKey: 'connection.CONNFAIL'
});
};
/**
* Notify user that maximum users limit has been reached.
*/
UI.notifyMaxUsersLimitReached = function() {
messageHandler.showError({
hideErrorSupportLink: true,
descriptionKey: 'dialog.maxUsersLimitReached',
titleKey: 'dialog.maxUsersLimitReachedTitle'
});
};
/**
* Notify user that he was automatically muted when joned the conference.
*/
UI.notifyInitiallyMuted = function() {
messageHandler.participantNotification(
null,
'notify.mutedTitle',
'connected',
'notify.muted',
null);
};
UI.handleLastNEndpoints = function(leavingIds, enteringIds) {
VideoLayout.onLastNEndpointsChanged(leavingIds, enteringIds);
};
/**
* Update audio level visualization for specified user.
* @param {string} id user id
* @param {number} lvl audio level
*/
UI.setAudioLevel = (id, lvl) => VideoLayout.setAudioLevel(id, lvl);
UI.notifyTokenAuthFailed = function() {
messageHandler.showError({
descriptionKey: 'dialog.tokenAuthFailed',
titleKey: 'dialog.tokenAuthFailedTitle'
});
};
UI.notifyFocusDisconnected = function(focus, retrySec) {
messageHandler.participantNotification(
null, 'notify.focus',
'disconnected', 'notify.focusFail',
{ component: focus,
ms: retrySec }
);
};
/**
* Update list of available physical devices.
*/
UI.onAvailableDevicesChanged = function() {
APP.conference.updateAudioIconEnabled();
APP.conference.updateVideoIconEnabled();
};
/**
* Returns the id of the current video shown on large.
* Currently used by tests (torture).
*/
UI.getLargeVideoID = function() {
return VideoLayout.getLargeVideoID();
};
/**
* Returns the current video shown on large.
* Currently used by tests (torture).
*/
UI.getLargeVideo = function() {
return VideoLayout.getLargeVideo();
};
// TODO: Export every function separately. For now there is no point of doing
// this because we are importing everything.
export default UI;
| 26.875622 | 110 | 0.646612 |
3da5126c678a0e752856c83e9c002ad7f52e7ce0 | 1,769 | js | JavaScript | src/redux/actions/request-actions-s.js | ManageIQ/approval-ui | 565526886eeb659a4d8da9b3c5d1818a09749994 | [
"Apache-2.0"
] | null | null | null | src/redux/actions/request-actions-s.js | ManageIQ/approval-ui | 565526886eeb659a4d8da9b3c5d1818a09749994 | [
"Apache-2.0"
] | 71 | 2019-02-14T08:47:12.000Z | 2019-11-11T12:52:42.000Z | src/redux/actions/request-actions-s.js | ManageIQ/approval-ui | 565526886eeb659a4d8da9b3c5d1818a09749994 | [
"Apache-2.0"
] | 7 | 2019-02-13T18:39:53.000Z | 2019-04-16T21:13:25.000Z | import * as ActionTypes from '../action-types';
import * as RequestHelper from '../../helpers/request/request-helper-s';
import { defaultSettings } from '../../helpers/shared/pagination';
import actionModalMessages from '../../messages/action-modal.messages';
export const fetchRequests = (persona, pagination) => (dispatch, getState) => {
const { sortBy, requests, filterValue } = getState().requestReducer;
let finalPagination = pagination || defaultSettings;
if (!pagination && requests) {
const { limit, offset } = requests.meta;
finalPagination = { limit, offset };
}
return dispatch({
type: ActionTypes.FETCH_REQUESTS,
payload: RequestHelper.fetchRequests(filterValue, finalPagination, persona, sortBy)
});
};
export const fetchRequest = (apiProps, persona) => ({
type: ActionTypes.FETCH_REQUEST,
payload: RequestHelper.fetchRequestWithSubrequests(apiProps, persona)
});
export const fetchRequestContent = (apiProps, persona) => ({
type: ActionTypes.FETCH_REQUEST_CONTENT,
payload: RequestHelper.fetchRequestContent(apiProps, persona)
});
export const createRequestAction = (actionName, requestId, actionIn, intl) => ({
type: ActionTypes.CREATE_REQUEST_ACTION,
payload: RequestHelper.createRequestAction(requestId, actionIn),
meta: {
notifications: {
fulfilled: {
variant: 'success',
title: intl.formatMessage(actionModalMessages.successTitle),
description: intl.formatMessage(actionModalMessages.fulfilledAction, { actionName })
},
rejected: {
variant: 'danger',
title: intl.formatMessage(actionModalMessages.failedTitle, { actionName }),
description: intl.formatMessage(actionModalMessages.failedAction, { actionName })
}
}
}
});
| 35.38 | 92 | 0.715093 |
3da5ecb5e5a62caa234928feba41d93dbe570cf7 | 2,694 | js | JavaScript | tasks/sf-sns-report/tests/index.js | Jkovarik/cumulus_test | 573dbdcf0d51f9365b964a551731a99495eae4c2 | [
"Apache-2.0"
] | null | null | null | tasks/sf-sns-report/tests/index.js | Jkovarik/cumulus_test | 573dbdcf0d51f9365b964a551731a99495eae4c2 | [
"Apache-2.0"
] | null | null | null | tasks/sf-sns-report/tests/index.js | Jkovarik/cumulus_test | 573dbdcf0d51f9365b964a551731a99495eae4c2 | [
"Apache-2.0"
] | null | null | null | 'use strict';
const test = require('ava');
const { recursivelyDeleteS3Bucket, s3 } = require('@cumulus/common/aws');
const cloneDeep = require('lodash.clonedeep');
const { randomString } = require('@cumulus/common/test-utils');
const { publishSnsMessage } = require('..');
let bucket;
test.before(async () => {
bucket = randomString();
await s3().createBucket({ Bucket: bucket }).promise();
});
test('send report when sfn is running', async (t) => {
const event = {
input: {
meta: { topic_arn: 'test_topic_arn' },
anykey: 'anyvalue',
payload: { someKey: 'someValue' }
}
};
const output = await publishSnsMessage(cloneDeep(event));
t.deepEqual(output, event.input.payload);
});
test('send report when sfn is running with exception', (t) => {
const event = {
input: {
meta: { topic_arn: 'test_topic_arn' },
exception: {
Error: 'TheError',
Cause: 'bucket not found'
},
anykey: 'anyvalue',
payload: { someKey: 'someValue' }
}
};
return publishSnsMessage(cloneDeep(event))
.catch((e) => {
t.is(e.message, event.input.exception.Cause);
});
});
test('send report when sfn is running with TypeError', (t) => {
const event = {
input: {
meta: { topic_arn: 'test_topic_arn' },
error: {
Error: 'TypeError',
Cause: 'resource not found'
},
anykey: 'anyvalue'
}
};
return publishSnsMessage(cloneDeep(event))
.catch((e) => {
t.is(e.message, event.input.error.Cause);
});
});
test('send report when sfn is running with known error type', (t) => {
const event = {
input: {
meta: { topic_arn: 'test_topic_arn' },
error: {
Error: 'PDRParsingError',
Cause: 'format error'
},
anykey: 'anyvalue'
}
};
return publishSnsMessage(cloneDeep(event))
.catch((e) => {
t.is(e.message, event.input.error.Cause);
});
});
test('send report when sfn is finished and granule has succeeded', async (t) => {
const input = {
meta: {
topic_arn: 'test_topic_arn',
granuleId: randomString()
},
anykey: 'anyvalue'
};
const event = {};
event.input = input;
event.config = {};
event.config.sfnEnd = true;
event.config.stack = 'test_stack';
event.config.bucket = bucket;
event.config.stateMachine = 'arn:aws:states:us-east-1:000000000000:stateMachine:TestCumulusParsePdrStateMach-K5Qk90fc8w4U';
event.config.executionName = '7c543392-1da9-47f0-9c34-f43f6519412a';
const output = await publishSnsMessage(cloneDeep(event));
t.deepEqual(output, {});
});
test.after.always(async () => {
await recursivelyDeleteS3Bucket(bucket);
});
| 24.715596 | 125 | 0.617298 |
3dabb014f21e8d0c9795ac1441ab17439c08ea7e | 3,643 | js | JavaScript | addons/website_sale/static/src/snippets/s_dynamic_snippet_products/options.js | SHIVJITH/Odoo_Machine_Test | 310497a9872db7844b521e6dab5f7a9f61d365a4 | [
"Apache-2.0"
] | null | null | null | addons/website_sale/static/src/snippets/s_dynamic_snippet_products/options.js | SHIVJITH/Odoo_Machine_Test | 310497a9872db7844b521e6dab5f7a9f61d365a4 | [
"Apache-2.0"
] | null | null | null | addons/website_sale/static/src/snippets/s_dynamic_snippet_products/options.js | SHIVJITH/Odoo_Machine_Test | 310497a9872db7844b521e6dab5f7a9f61d365a4 | [
"Apache-2.0"
] | null | null | null | odoo.define('website_sale.s_dynamic_snippet_products_options', function (require) {
'use strict';
const options = require('web_editor.snippets.options');
const s_dynamic_snippet_carousel_options = require('website.s_dynamic_snippet_carousel_options');
const dynamicSnippetProductsOptions = s_dynamic_snippet_carousel_options.extend({
/**
*
* @override
*/
init: function () {
this._super.apply(this, arguments);
this.productCategories = {};
},
/**
*
* @override
*/
onBuilt: function () {
this._super.apply(this, arguments);
this._rpc({
route: '/website_sale/snippet/options_filters'
}).then((data) => {
if (data.length) {
this.$target.get(0).dataset.filterId = data[0].id;
this.$target.get(0).dataset.numberOfRecords = this.dynamicFilters[data[0].id].limit;
this._refreshPublicWidgets();
// Refresh is needed because default values are obtained after start()
}
});
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
*
* @override
* @private
*/
_computeWidgetVisibility: function (widgetName, params) {
if (widgetName === 'filter_opt') {
return false;
}
return this._super.apply(this, arguments);
},
/**
* Fetches product categories.
* @private
* @returns {Promise}
*/
_fetchProductCategories: function () {
return this._rpc({
model: 'product.public.category',
method: 'search_read',
kwargs: {
domain: [],
fields: ['id', 'name'],
}
});
},
/**
*
* @override
* @private
*/
_renderCustomXML: async function (uiFragment) {
await this._super.apply(this, arguments);
await this._renderProductCategorySelector(uiFragment);
},
/**
* Renders the product categories option selector content into the provided uiFragment.
* @private
* @param {HTMLElement} uiFragment
*/
_renderProductCategorySelector: async function (uiFragment) {
const productCategories = await this._fetchProductCategories();
for (let index in productCategories) {
this.productCategories[productCategories[index].id] = productCategories[index];
}
const productCategoriesSelectorEl = uiFragment.querySelector('[data-name="product_category_opt"]');
return this._renderSelectUserValueWidgetButtons(productCategoriesSelectorEl, this.productCategories);
},
/**
* Sets default options values.
* @override
* @private
*/
_setOptionsDefaultValues: function () {
this._super.apply(this, arguments);
const templateKeys = this.$el.find("we-select[data-attribute-name='templateKey'] we-selection-items we-button");
if (templateKeys.length > 0) {
this._setOptionValue('templateKey', templateKeys.attr('data-select-data-attribute'));
}
const productCategories = this.$el.find("we-select[data-attribute-name='productCategoryId'] we-selection-items we-button");
if (productCategories.length > 0) {
this._setOptionValue('productCategoryId', productCategories.attr('data-select-data-attribute'));
}
},
});
options.registry.dynamic_snippet_products = dynamicSnippetProductsOptions;
return dynamicSnippetProductsOptions;
});
| 33.118182 | 131 | 0.591271 |
3daf99328fffbaa15d17edd7b5cf81979d7b96dd | 2,124 | js | JavaScript | js/model/meta.js | jfseb/fdevsta_monmove | c11c260c7b0d48ebb8a17f54118ca190465560bc | [
"Apache-2.0"
] | null | null | null | js/model/meta.js | jfseb/fdevsta_monmove | c11c260c7b0d48ebb8a17f54118ca190465560bc | [
"Apache-2.0"
] | null | null | null | js/model/meta.js | jfseb/fdevsta_monmove | c11c260c7b0d48ebb8a17f54118ca190465560bc | [
"Apache-2.0"
] | null | null | null | /**
* Functionality managing the match models
*
* @file
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//import * as intf from 'constants';
var debug = require("debug");
var debuglog = debug('meta');
/**
* the model path, may be controlled via environment variable
*/
var modelPath = process.env["ABOT_MODELPATH"] || "testmodel";
var separator = " -:- ";
var validTypes = ["relation", "category", "domain"];
var AMeta = (function () {
function AMeta(type, name) {
if (validTypes.indexOf(type) < 0) {
throw new Error("Illegal Type " + type);
}
this.name = name;
this.type = type;
}
AMeta.prototype.toName = function () {
return this.name;
};
AMeta.prototype.toFullString = function () {
return this.type + separator + this.name;
};
AMeta.prototype.toType = function () {
return this.type;
};
return AMeta;
}());
exports.AMeta = AMeta;
function getStringArray(arr) {
return arr.map(function (oMeta) {
return oMeta.toName();
});
}
exports.getStringArray = getStringArray;
exports.RELATION_hasCategory = "hasCategory";
exports.RELATION_isCategoryOf = "isCategoryOf";
function parseAMeta(a) {
var r = a.split(separator);
if (!r || r.length !== 2) {
throw new Error("cannot parse " + a + " as Meta");
}
switch (r[0]) {
case "category":
return getMetaFactory().Category(r[1]);
case "relation":
return getMetaFactory().Relation(r[1]);
case "domain":
return getMetaFactory().Domain(r[1]);
default:
throw new Error("unknown meta type" + r[0]);
}
}
function getMetaFactory() {
return {
Domain: function (a) {
return new AMeta("domain", a);
},
Category: function (a) {
return new AMeta("category", a);
},
Relation: function (a) {
return new AMeta("relation", a);
},
parseIMeta: parseAMeta
};
}
exports.getMetaFactory = getMetaFactory;
//# sourceMappingURL=meta.js.map
| 27.230769 | 62 | 0.584275 |
3db1740c2772b1966b961acfa8713bba0d03fc72 | 1,806 | js | JavaScript | node_modules/@babel/core/lib/transformation/block-hoist-plugin.js | amitovadia-did/github-action-slack-notify-deployment | 76720db4964db1af8f7a08861637b3a35ba8a93c | [
"Apache-2.0"
] | null | null | null | node_modules/@babel/core/lib/transformation/block-hoist-plugin.js | amitovadia-did/github-action-slack-notify-deployment | 76720db4964db1af8f7a08861637b3a35ba8a93c | [
"Apache-2.0"
] | null | null | null | node_modules/@babel/core/lib/transformation/block-hoist-plugin.js | amitovadia-did/github-action-slack-notify-deployment | 76720db4964db1af8f7a08861637b3a35ba8a93c | [
"Apache-2.0"
] | 1 | 2022-01-03T11:17:36.000Z | 2022-01-03T11:17:36.000Z | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.default = loadBlockHoistPlugin;
function _traverse() {
const data = require('@babel/traverse');
_traverse = function() {
return data;
};
return data;
}
var _plugin = require('../config/plugin');
let LOADED_PLUGIN;
function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) {
LOADED_PLUGIN = new _plugin.default(
Object.assign({}, blockHoistPlugin, {
visitor: _traverse().default.explode(blockHoistPlugin.visitor),
}),
{}
);
}
return LOADED_PLUGIN;
}
function priority(bodyNode) {
const priority = bodyNode == null ? void 0 : bodyNode._blockHoist;
if (priority == null) return 1;
if (priority === true) return 2;
return priority;
}
function stableSort(body) {
const buckets = Object.create(null);
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
const bucket = buckets[p] || (buckets[p] = []);
bucket.push(n);
}
const keys = Object.keys(buckets)
.map(k => +k)
.sort((a, b) => b - a);
let index = 0;
for (const key of keys) {
const bucket = buckets[key];
for (const n of bucket) {
body[index++] = n;
}
}
return body;
}
const blockHoistPlugin = {
name: 'internal.blockHoist',
visitor: {
Block: {
exit({ node }) {
const { body } = node;
let max = Math.pow(2, 30) - 1;
let hasChange = false;
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
if (p > max) {
hasChange = true;
break;
}
max = p;
}
if (!hasChange) return;
node.body = stableSort(body.slice());
},
},
},
};
| 19.010526 | 71 | 0.555925 |
3dbc6874b862aad3807608931406c2b2a938dd82 | 700 | js | JavaScript | packages/main/src/icons/curriculum.js | lnoenssap/ui5-webcomponents | dedb51e2ee25afd27087d1abbf70d34e84f8d67a | [
"Apache-2.0"
] | null | null | null | packages/main/src/icons/curriculum.js | lnoenssap/ui5-webcomponents | dedb51e2ee25afd27087d1abbf70d34e84f8d67a | [
"Apache-2.0"
] | null | null | null | packages/main/src/icons/curriculum.js | lnoenssap/ui5-webcomponents | dedb51e2ee25afd27087d1abbf70d34e84f8d67a | [
"Apache-2.0"
] | null | null | null | import { registerIcon } from "@ui5/webcomponents-base/dist/SVGIconRegistry.js";
const name = "sap-icon://curriculum";
const d = "M365 158q8 4 13.5 9.5T384 181v164q0 4-1 8-2 8-6 11-2 1-6 1-5 0-13-2-4-1-6-3V200q0-8-2-11.5t-10-8.5l-88-20h-5q-6 0-9 1l-53 14 116 33q8 4 13.5 9.5T320 231v163q0 11-7 17.5t-17 6.5h-5l-144-49q-8-2-13.5-8.5T128 346V179q0-17 15-22l90-27q6-2 9-2t5 1zm-205 44v137l128 45V238zM480 64q11 0 18 5t10 11q4 7 4 16v352q0 12-5 18.5t-11 9.5q-7 4-16 4H32q-9 0-16-4-6-3-11-9.5T0 448V64q0-9 4-16 3-6 9.5-11T32 32h187l37 32h224zm0 64q-1-9-5-16-3-6-9.5-11T448 96H224l-32-32H64q-12 0-18.5 5T36 80q-4 7-4 16v320q0 13 5 19t11 9q7 4 16 4h384q9 0 16-4 6-3 11-9t5-19V128z";
registerIcon(name, d);
| 100 | 556 | 0.714286 |
3dbf4c13cd4789efa84b58a7c150d4ea2ffdeac3 | 22,304 | js | JavaScript | stories/fn-toggles/fn-toggles.stories.js | dostarora97/fundamental-styles | 601b6b6f1492d09076d5986048555f10ba029fa8 | [
"Apache-2.0"
] | null | null | null | stories/fn-toggles/fn-toggles.stories.js | dostarora97/fundamental-styles | 601b6b6f1492d09076d5986048555f10ba029fa8 | [
"Apache-2.0"
] | null | null | null | stories/fn-toggles/fn-toggles.stories.js | dostarora97/fundamental-styles | 601b6b6f1492d09076d5986048555f10ba029fa8 | [
"Apache-2.0"
] | null | null | null | export default {
title: 'FN Components/Toggles',
parameters: {
description: `
`,
components: ['fn-checkbox', 'fn-fieldset', 'fn-radio', 'fn-switch']
}
};
const localStyles = `
<style>
.docs-fn-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
column-gap: 0.1rem;
row-gap: 0.1rem;
background: white;
padding: 1rem;
justify-items: center;
align-items: center;
}
.docs-fn-header-container {
display: flex;
align-items: center;
}
.docs-fn-header-container code {
margin: 0 1rem;
}
.docs-fn-container-group {
background: white;
padding: 1rem;
justify-items: center;
align-items: center;
}
</style>
`;
export const Checkbox = () => `${localStyles}
<div class="docs-fn-container">
<div><b>:normal</b></div>
<label class="fn-checkbox" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:hover</b></div>
<label class="fn-checkbox is-hover" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-hover" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox is-hover" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-hover" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:focus</b></div>
<label class="fn-checkbox is-focus" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-focus" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox is-focus" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-focus" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:disabled</b></div>
<label class="fn-checkbox is-disabled">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox" disabled>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-disabled">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox" disabled>
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox is-disabled">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox" disabled>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-disabled">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox" disabled>
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:read-only</b></div>
<label class="fn-checkbox is-readonly">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox" readonly disabled>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-readonly">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox" readonly disabled>
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox is-readonly">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox" readonly disabled>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-readonly">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox" readonly disabled>
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:display</b></div>
<label class="fn-checkbox is-display" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-display" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
<label class="fn-checkbox is-display" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox is-display" tabindex="0">
<input class="fn-checkbox__input" type="checkbox" checked="checked" tabindex="-1" aria-label="checkbox">
<span class="fn-checkbox__checkmark"></span>
</label>
</div>
`;
Checkbox.parameters = {
docs: {
iframeHeight: 500
}
};
export const CheckboxGroup = () => `${localStyles}
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset">
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group"
tabindex="-1"
aria-label="checkbox"
checked="checked"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">First</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Second</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Third</span>
</label>
</fieldset>
</div>
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset fn-fieldset--full-width" style="width: 120px;">
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_width"
tabindex="-1"
aria-label="checkbox"
checked="checked"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">First</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_width"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Second</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_width"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Third</span>
</label>
</fieldset>
</div>
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset fn-fieldset--horizontal">
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_horizontal"
tabindex="-1"
aria-label="checkbox"
checked="checked"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_horizontal"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
<label class="fn-checkbox" tabindex="0">
<input
class="fn-checkbox__input"
type="checkbox"
name="checkbox_group_horizontal"
tabindex="-1"
aria-label="checkbox"
>
<span class="fn-checkbox__checkmark"></span>
<span class="fn-checkbox__label">Checkbox</span>
</label>
</fieldset>
</div>
`;
CheckboxGroup.parameters = {
docs: {
iframeHeight: 500,
description: {
story: 'Use the `<fieldset>` HTML element with class `.fn-fieldset` to group checkbox controls. The controls are displayed vertically and have `fit-content` width. The `.fn-fieldset--full-width` modifier class will display the checkbox controls with the same width as the parent element. To display the controls horizontally apply the `.fn-fieldset--horizontal` modifier class.'
}
}
};
export const Radio = () => `${localStyles}
<div class="docs-fn-container">
<div><b>:normal</b></div>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:hover</b></div>
<label class="fn-radio is-hover" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-hover" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio is-hover" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-hover" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:focus</b></div>
<label class="fn-radio is-focus" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-focus" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio is-focus" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-focus" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:disabled</b></div>
<label class="fn-radio is-disabled">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" disabled>
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-disabled">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" disabled>
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio is-disabled">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio" disabled>
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-disabled">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio" disabled>
<span class="fn-radio__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:read-only</b></div>
<label class="fn-radio is-readonly">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" readonly disabled>
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-readonly">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" readonly disabled>
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio is-readonly">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio" readonly disabled>
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-readonly">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio" readonly disabled>
<span class="fn-radio__checkmark"></span>
</label>
</div>
<div class="docs-fn-container">
<div><b>:display</b></div>
<label class="fn-radio is-display" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-display" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
<label class="fn-radio is-display" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio is-display" tabindex="0">
<input class="fn-radio__input" type="radio" checked="checked" tabindex="-1" aria-label="radio">
<span class="fn-radio__checkmark"></span>
</label>
</div>
`;
Radio.parameters = {
docs: {
iframeHeight: 500
}
};
export const RadioGroup = () => `${localStyles}
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset">
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" checked="checked" name="group1">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">First</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group1">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Second</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group1">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Third</span>
</label>
</fieldset>
</div>
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset fn-fieldset--full-width" style="width: 120px;">
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" checked="checked" name="group2">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">First</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group2">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Second</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group2">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Third</span>
</label>
</fieldset>
</div>
<div class="docs-fn-container-group">
<fieldset class="fn-fieldset fn-fieldset--horizontal">
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" checked="checked" name="group3">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group3">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
<label class="fn-radio" tabindex="0">
<input class="fn-radio__input" type="radio" tabindex="-1" aria-label="radio" name="group3">
<span class="fn-radio__checkmark"></span>
<span class="fn-radio__label">Radio Button</span>
</label>
</fieldset>
</div>
`;
RadioGroup.parameters = {
docs: {
iframeHeight: 500,
description: {
story: 'Use the `<fieldset>` HTML element with class `.fn-fieldset` to group radio button controls. The controls are displayed vertically and have `fit-content` width. The `.fn-fieldset--full-width` modifier class will display the radio buttons with the same width as the parent element. To display the controls horizontally apply the `.fn-fieldset--horizontal` modifier class.'
}
}
};
export const SwitchToggle = () => `${localStyles}
<div class="docs-fn-container">
<div class="fn-switch">
<label class="fn-switch__toggle">
<input type="checkbox" class="fn-switch__input">
<span class="fn-switch__slider"></span>
<span class="fn-switch__label">Toggle</span>
</label>
</div>
</div>
`;
SwitchToggle.storyName = 'Switch';
SwitchToggle.parameters = {
docs: {
iframeHeight: 500
}
};
| 38.588235 | 390 | 0.606707 |
3dc4b678f983bed82344553986243d464a192887 | 7,931 | js | JavaScript | app-layout-addon/src/main/resources/META-INF/resources/frontend/com/github/appreciated/app-layout/left/left-responsive-small-no-app-bar.js | axpendix/vaadin-app-layout | db3348e9b4a05bff36730442c3aca9db1ff314f8 | [
"Apache-2.0"
] | null | null | null | app-layout-addon/src/main/resources/META-INF/resources/frontend/com/github/appreciated/app-layout/left/left-responsive-small-no-app-bar.js | axpendix/vaadin-app-layout | db3348e9b4a05bff36730442c3aca9db1ff314f8 | [
"Apache-2.0"
] | null | null | null | app-layout-addon/src/main/resources/META-INF/resources/frontend/com/github/appreciated/app-layout/left/left-responsive-small-no-app-bar.js | axpendix/vaadin-app-layout | db3348e9b4a05bff36730442c3aca9db1ff314f8 | [
"Apache-2.0"
] | null | null | null | /*
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import {html, PolymerElement} from '@polymer/polymer/polymer-element.js';
import '@polymer/polymer/lib/elements/custom-style.js';
import '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
import '@vaadin/vaadin-icons/vaadin-icons.js';
import '@polymer/app-layout/app-drawer/app-drawer.js';
import '@polymer/app-layout/app-drawer-layout/app-drawer-layout.js';
import '@polymer/app-layout/app-header/app-header.js';
import '@polymer/app-layout/app-header-layout/app-header-layout.js';
import '@polymer/app-layout/app-toolbar/app-toolbar.js';
import '@polymer/iron-media-query/iron-media-query.js';
class AppLayoutLeftResponsiveSmallNoAppBar extends PolymerElement {
static get template() {
return html`<style>
:root {
--paper-badge-background: var(--app-layout-badge-background);
--paper-badge-text-color: var(--app-layout-badge-font-color);
--primary-color: var(--app-layout-primary-color);
--app-layout-bar-padding: var(--app-layout-bar-padding-small);
}
slot[name="app-bar-content"]::slotted(*) {
pointer-events: inherit;
}
app-header {
right: 0px !important;
background: var(--app-layout-bar-background-base-color);
top: 0px;
height: var(--app-layout-bar-height);
}
app-toolbar {
height: var(--app-layout-bar-height);
background: var(--app-layout-bar-background-color);
box-shadow: var(--app-layout-bar-shadow);
color: var(--app-layout-bar-font-color);
padding: var(--app-layout-bar-padding);
}
#app-bar-elements {
min-width: 0;
}
/* non-overlay */
:root {
--app-drawer-scrim-background: rgba(0, 0, 0, 0);
}
app-toolbar {
z-index: 1;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
}
#drawer {
margin-top: var(--app-layout-bar-height);
}
/* non-overlay */
.application-content {
width: 100%;
background: var(--app-layout-background);
}
#drawer {
--app-drawer-content-container: {
box-shadow: var(--app-layout-drawer-shadow);
background-color: var(--app-layout-drawer-background-base-color);
max-width: 100%;
};
transition: 1s width;
}
#drawer .drawer-content {
height: 100%;
width: 100%;
background: var(--app-layout-drawer-background-color);
}
#toggle {
flex-shrink: 0;
width: calc(var(--app-layout-bar-height) - calc(var(--app-layout-space-s) * 2));
height: calc(var(--app-layout-bar-height) - calc(var(--app-layout-space-s) * 2));
margin: var(--app-layout-space-s);
}
app-menu {
background: transparent;
}
:host([narrow]) .application-content {
padding-top: var(--app-layout-bar-height);
box-sizing: border-box;
}
:host(:not([narrow])) #toggle:not(.show-back-arrow) {
display: none;
}
:host(:not([narrow])) #drawerLayout {
--app-drawer-width: var(--app-layout-drawer-small-width);
--app-layout-badge-width: var(--app-layout-badge-small-width);
--app-layout-badge-height: var(--app-layout-badge-small-height);
--app-layout-badge-top: var(--app-layout-badge-small-top);
--app-layout-badge-right: var(--app-layout-badge-small-right);
--app-layout-badge-color: transparent;
--app-layout-menu-button-margin: 0;
--app-layout-menu-button-padding: 0 11px;
}
:host(:not([narrow])) #drawerLayout .app-menu-item {
overflow: hidden;
}
:host(:not([narrow])) #drawerLayout * {
--expand-icon-fill-color: transparent !important;
--app-layout-badge-font-color: transparent;
}
:host(:not([narrow])) app-header {
display: none;
}
:host(:not([narrow])) #drawer {
margin-top: 0px;
}
</style>
<app-header-layout id="layout-wrapper" fullbleed>
<app-header part="app-bar" fixed slot="header">
<app-toolbar style="height: var(--app-layout-bar-height);">
<vaadin-button id="toggle" theme="large tertiary icon">
</vaadin-button>
<div class="app-bar-content" id="app-bar-elements" style="width: 100%;height: 100%;">
<slot name="app-bar-content"></slot>
</div>
</app-toolbar>
</app-header>
<app-drawer-layout id="drawerLayout" fullbleed>
<app-drawer part="drawer" id="drawer" slot="drawer">
<div class="drawer-content" id="menu-elements">
<slot name="drawer-content"></slot>
</div>
</app-drawer>
<div class="application-content" part="application-content" id="content">
<slot name="application-content"></slot>
</div>
</app-drawer-layout>
</app-header-layout>
<iron-media-query query="[[_computeMediaQuery(responsiveWidth)]]" on-query-matches-changed="_onQueryMatchesChanged"></iron-media-query>`;
}
static get is() {
return 'app-layout-left-responsive-small-no-app-bar'
}
static get properties() {
return {
responsiveWidth: {
type: String,
value: "640px",
observer: "_responsiveWidthChanged"
}
};
}
ready() {
super.ready();
this.shadowRoot.querySelector("#toggle").addEventListener('click', evt => this.onclick());
}
onclick() {
var drawer = this.shadowRoot.querySelector("#drawer");
if (!this.shadowRoot.querySelector("#toggle").classList.contains('show-back-arrow')) {
drawer.toggle();
} else {
this.onUpNavigation();
}
}
onUpNavigation() {
}
closeIfNotPersistent() {
var drawer = this.shadowRoot.querySelector("#drawer");
if (!drawer.persistent) {
drawer.close();
}
}
_responsiveWidthChanged() {
this.shadowRoot.querySelector("#drawerLayout").responsiveWidth = this.responsiveWidth;
}
_onQueryMatchesChanged(event) {
if (event.detail.value)
this.setAttribute("narrow", "");
else
this.removeAttribute("narrow");
}
_computeMediaQuery(responsiveWidth) {
return "(max-width: " + responsiveWidth + ")";
}
}
customElements.define(AppLayoutLeftResponsiveSmallNoAppBar.is, AppLayoutLeftResponsiveSmallNoAppBar); | 35.725225 | 145 | 0.534863 |
3dc4b71ca3761a4227beb2295ade1c3126e63570 | 373 | js | JavaScript | packages/code-du-travail-frontend/__tests__/recherche.test.js | SocialGouv/code-du-travail-frontend | 22fb2e5d46e4553e76c0b73b0bdf95b5f269924d | [
"Apache-2.0"
] | null | null | null | packages/code-du-travail-frontend/__tests__/recherche.test.js | SocialGouv/code-du-travail-frontend | 22fb2e5d46e4553e76c0b73b0bdf95b5f269924d | [
"Apache-2.0"
] | 33 | 2018-09-28T14:07:52.000Z | 2018-10-10T15:35:46.000Z | packages/code-du-travail-frontend/__tests__/recherche.test.js | SocialGouv/code-du-travail-frontend | 22fb2e5d46e4553e76c0b73b0bdf95b5f269924d | [
"Apache-2.0"
] | 1 | 2018-10-04T14:08:34.000Z | 2018-10-04T14:08:34.000Z | import { render } from "@testing-library/react";
import React from "react";
import Recherche from "../pages/recherche";
jest.mock("@socialgouv/matomo-next", () => {
return {
push: jest.fn(),
};
});
describe("<Recherche />", () => {
it("should render", () => {
const { container } = render(<Recherche />);
expect(container).toMatchSnapshot();
});
});
| 20.722222 | 48 | 0.595174 |
3dc8d1de9917ae7c9ecc9dd084f1ff8912b94004 | 5,947 | js | JavaScript | splunk_add_on_ucc_framework/UCC-UI-lib/bower_components/SplunkWebCore/search_mrsparkle/exposed/js/views/deploymentserver/EditServerClassesLink.js | livehybrid/addonfactory-ucc-generator | 421c4f9cfb279f02fa8927cc7cf21f4ce48e7af5 | [
"Apache-2.0"
] | null | null | null | splunk_add_on_ucc_framework/UCC-UI-lib/bower_components/SplunkWebCore/search_mrsparkle/exposed/js/views/deploymentserver/EditServerClassesLink.js | livehybrid/addonfactory-ucc-generator | 421c4f9cfb279f02fa8927cc7cf21f4ce48e7af5 | [
"Apache-2.0"
] | null | null | null | splunk_add_on_ucc_framework/UCC-UI-lib/bower_components/SplunkWebCore/search_mrsparkle/exposed/js/views/deploymentserver/EditServerClassesLink.js | livehybrid/addonfactory-ucc-generator | 421c4f9cfb279f02fa8927cc7cf21f4ce48e7af5 | [
"Apache-2.0"
] | null | null | null | define(
[
'jquery',
'module',
'views/Base',
'underscore',
'uri/route',
'models/services/deploymentserver/RenameServerClass',
'views/shared/dialogs/TextDialog',
'views/shared/dialogs/TextInputDialog',
'collections/services/deploymentserver/DeploymentServerClasses',
'views/deploymentserver/shared/DropDownMenuWithReadOnlyMode'
],
function(
$,
module,
BaseView,
_,
route,
RenameServerClass,
TextDialog,
TextInputDialog,
ServerClassesCollection,
DropDownMenu
) {
return BaseView.extend({
moduleId: module.id,
tagName: 'div',
initialize: function() {
BaseView.prototype.initialize.apply(this, arguments);
var items = [];
if (this.collection.deploymentApps.length > 0) {
items = [{ label: _('Edit Clients').t(), value: 'edit_clients' },
{ label: _('Edit Apps').t(), value: 'edit_apps' },
{ label: _('Rename').t(), value: 'rename' },
{ label: _('Delete').t(), value: 'delete' }];
} else {
items = [{ label: _('Edit Clients').t(), value: 'edit_clients' },
{ label: _('Rename').t(), value: 'rename' },
{ label: _('Delete').t(), value: 'delete' }];
}
this.children.createDropDown = new DropDownMenu({
label: _('Edit').t(),
className: 'btn-combo create-drop-down',
anchorClassName: ' ',
items: items,
isReadOnly: this.options.isReadOnly
});
this.children.createDropDown.on('itemClicked', function(type) {
var return_to = window.location.href.split('/').slice(-1);
if(type === 'edit_clients') {
window.location.href = route.manager(this.options.application.get('root'), this.options.application.get('locale'), this.options.application.get('app'),'deploymentserver_add_clients', {data: {id: this.model.serverclass.id, return_to: return_to}});
} else if(type === 'edit_apps') {
window.location.href = route.manager(this.options.application.get('root'), this.options.application.get('locale'), this.options.application.get('app'),'deploymentserver_add_apps', {data: {id: this.model.serverclass.id, return_to: return_to}});
} else if(type === 'rename') {
this.renderRenameServerClassDialog();
} else if(type === 'delete') {
this.renderDeleteServerClassDialog();
}
}, this);
},
render: function() {
this.$el.append(this.children.createDropDown.render().el);
return this;
},
renderDeleteServerClassDialog: function() {
this.children.deleteServerClassDialog = new TextDialog({id: "modal_delete", parent: this, flashModel: this.model.serverclass});
this.children.deleteServerClassDialog.settings.set("titleLabel",_("Delete Server Class").t());
this.children.deleteServerClassDialog.settings.set("primaryButtonLabel",_("Delete").t());
this.children.deleteServerClassDialog.settings.set("cancelButtonLabel",_("Cancel").t());
this.children.deleteServerClassDialog.setText(_("Are you sure you wish to delete this server class?").t());
this.children.deleteServerClassDialog.preventDefault();
$("body").append(this.children.deleteServerClassDialog.render().el);
this.children.deleteServerClassDialog.show();
this.children.deleteServerClassDialog.on('click:primaryButton', function() {
var that = this;
this.model.serverclass.destroy({
success: function(serverclass, response) {
//Triggering the 'itemDeleted' event will cause the paginator to re-fetch the collection
that.model.paginator.trigger('itemDeleted');
that.children.deleteServerClassDialog.hide();
}
});
}, this);
},
renderRenameServerClassDialog: function() {
var originalName = this.model.serverclass.entry.get("name");
var renameModel = new RenameServerClass({oldName: originalName, newName: originalName});
this.children.renameServerClassDialog = new TextInputDialog({id: "modal_rename",
parent: this,
model: renameModel,
modelAttribute: "newName",
label: _("Name").t()});
this.children.renameServerClassDialog.settings.set("titleLabel",_("Rename Server Class").t());
this.children.renameServerClassDialog.show();
this.children.renameServerClassDialog.on('click:primaryButton', function() {
var that = this;
renameModel.save({}, {
success: function(model, response, options){
// We get the updated server class as a response. We use a backdoor to update the model
// since the ID is now different.
that.model.serverclass.setFromSplunkD(response);
that.model.paginator.trigger('change:data');
}
});
}, this);
return false;
}
});
});
| 47.198413 | 271 | 0.525475 |
3da45e96fdb7401e470e3622de108d5e9ec85766 | 5,509 | js | JavaScript | priv/public/ui/app/mn_admin/mn_security/mn_user_roles/mn_user_roles_service.js | couchbaselabs/analytics_ns_server | 321f72e2761a570c7fe854be53391dddde9e0ffe | [
"Apache-2.0"
] | 1 | 2019-06-27T07:10:59.000Z | 2019-06-27T07:10:59.000Z | priv/public/ui/app/mn_admin/mn_security/mn_user_roles/mn_user_roles_service.js | couchbaselabs/analytics_ns_server | 321f72e2761a570c7fe854be53391dddde9e0ffe | [
"Apache-2.0"
] | null | null | null | priv/public/ui/app/mn_admin/mn_security/mn_user_roles/mn_user_roles_service.js | couchbaselabs/analytics_ns_server | 321f72e2761a570c7fe854be53391dddde9e0ffe | [
"Apache-2.0"
] | null | null | null | (function () {
"use strict";
angular
.module("mnUserRolesService", ['mnHelper'])
.factory("mnUserRolesService", mnUserRolesFactory);
function mnUserRolesFactory($q, $http, mnHelper, mnPoolDefault) {
var mnUserRolesService = {
getState: getState,
addUser: addUser,
getRoles: getRoles,
deleteUser: deleteUser,
getRolesByRole: getRolesByRole,
getRolesTree: getRolesTree,
prepareUserRoles: prepareUserRoles
};
return mnUserRolesService;
function getRoles() {
return $http({
method: "GET",
url: "/settings/rbac/roles"
}).then(function (resp) {
return resp.data;
});
}
function sort(array) {
if (angular.isArray(array) && angular.isArray(array[0])) {
array.forEach(sort);
array.sort(function(a, b) {
var aHasTitle = angular.isArray(a[1]) || !!a[0].bucket_name;
var bHasTitle = angular.isArray(b[1]) || !!b[0].bucket_name;
if (!aHasTitle && bHasTitle) {
return -1;
}
if (aHasTitle && !bHasTitle) {
return 1;
}
return 0;
});
}
}
function getRolesTree(roles) {
roles = _.sortBy(roles, "name");
var roles1 = _.groupBy(roles, 'role');
var roles2 = _.groupBy(roles1, function (array, role) {
return role.split("_")[0];
});
var roles3 = _.values(roles2);
sort(roles3);
return roles3;
}
function getUser(user) {
return $http({
method: "GET",
url: getUserUrl(user)
});
}
function getUsers(params) {
var config = {
method: "GET",
url: "/settings/rbac/users"
};
if (params && params.pageSize) {
config.params = {
pageSize: params.pageSize,
startFromDomain: params.startFromDomain,
startFrom: params.startFrom
};
}
return $http(config);
}
function deleteUser(user) {
return $http({
method: "DELETE",
url: getUserUrl(user)
});
}
function getUserUrl(user) {
var base = "/settings/rbac/users/";
if (mnPoolDefault.export.compat.atLeast50) {
return base + encodeURIComponent(user.domain) + "/" + encodeURIComponent(user.id);
} else {
return base + encodeURIComponent(user.id);
}
}
function prepareUserRoles(userRoles) {
return $q.all([getRolesByRole(userRoles), getRolesByRole()])
.then(function (rv) {
var userRolesByRole = rv[0];
var rolesByRole = rv[1];
var i;
for (i in userRolesByRole) {
if (!rolesByRole[i]) {
delete userRolesByRole[i];
} else {
userRolesByRole[i] = true;
}
}
return userRolesByRole;
});
}
function getRolesByRole(userRoles) {
return (userRoles ? $q.when(userRoles) : getRoles()).then(function (roles) {
var rolesByRole = {};
angular.forEach(roles, function (role) {
rolesByRole[role.role + (role.bucket_name ? '[' + role.bucket_name + ']' : '')] = role;
});
return rolesByRole;
});
}
function packData(user, roles) {
var data = {
roles: roles.join(','),
name: user.name
};
if (user.password) {
data.password = user.password;
}
return data;
}
function doAddUser(data, user) {
return $http({
method: "PUT",
data: data,
url: getUserUrl(user)
});
}
function prepareRolesForSaving(roles) {
if (_.isArray(roles)) {
return _.map(roles, function (role) {
return role.role + (role.bucket_name ? '[' + role.bucket_name + ']' : '');
});
}
if (roles.admin) {
return ["admin"];
}
if (roles.cluster_admin) {
return ["cluster_admin"];
}
var i;
for (i in roles) {
var name = i.split("[");
if (name[1] !== "*]" && roles[name[0] + "[*]"]) {
delete roles[i];
}
}
return mnHelper.checkboxesToList(roles);
}
function addUser(user, roles, isEditingMode) {
if (!user || !user.id) {
return $q.reject({username: "username is required"});
}
roles = prepareRolesForSaving(roles);
if (!roles || !roles.length) {
return $q.reject({roles: "at least one role should be added"});
}
if (isEditingMode) {
return doAddUser(packData(user, roles), user);
} else {
return getUser(user).then(function (users) {
return $q.reject({username: "username already exists"});
}, function () {
return doAddUser(packData(user, roles), user);
});
}
}
function getState(params) {
return getUsers(params).then(function (resp) {
var i;
for (i in resp.data.links) {
resp.data.links[i] = resp.data.links[i].split("?")[1]
.split("&")
.reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
if (!resp.data.users) {//in oreder to support compatibility mode
return {
users: resp.data
};
} else {
return resp.data;
}
});
}
}
})();
| 26.109005 | 97 | 0.52151 |
3d9d7f6a0b5101e4d2ac0c3e960831f961aa4304 | 59 | js | JavaScript | src/utils/status/host/index.js | pcbailey/web-ui-components | ec299dbbe14a473d480170ef7d2b23d77e4eb67f | [
"Apache-2.0"
] | 6 | 2018-09-20T09:40:46.000Z | 2020-04-14T03:41:48.000Z | src/utils/status/host/index.js | pcbailey/web-ui-components | ec299dbbe14a473d480170ef7d2b23d77e4eb67f | [
"Apache-2.0"
] | 510 | 2018-09-13T13:30:56.000Z | 2020-04-26T03:06:39.000Z | src/utils/status/host/index.js | pcbailey/web-ui-components | ec299dbbe14a473d480170ef7d2b23d77e4eb67f | [
"Apache-2.0"
] | 21 | 2018-09-18T14:36:38.000Z | 2021-04-03T09:25:53.000Z | export * from './constants';
export * from './hostStatus';
| 19.666667 | 29 | 0.661017 |
3dbb1b9f6ac060be44180603acaa11cec9a3bd75 | 380 | js | JavaScript | docs/cpp_sat/search/enums_0.js | matbesancon/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | 1 | 2021-07-06T13:01:46.000Z | 2021-07-06T13:01:46.000Z | docs/cpp_sat/search/enums_0.js | matbesancon/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | null | null | null | docs/cpp_sat/search/enums_0.js | matbesancon/or-tools | b37d9c786b69128f3505f15beca09e89bf078a89 | [
"Apache-2.0"
] | 1 | 2021-07-24T22:52:41.000Z | 2021-07-24T22:52:41.000Z | var searchData=
[
['constraintcase_4298',['ConstraintCase',['../classoperations__research_1_1sat_1_1_p_r_o_t_o_b_u_f___f_i_n_a_l.html#ada030f50fcddb646af448ac7c5705e35',1,'operations_research::sat::PROTOBUF_FINAL']]],
['cpsolverstatus_4299',['CpSolverStatus',['../namespaceoperations__research_1_1sat.html#aedc4ddb96acc28481c09828d2e016815',1,'operations_research::sat']]]
];
| 63.333333 | 201 | 0.823684 |
3da54f52fed3b4922a977b42e56ab9893d0b628f | 5,081 | js | JavaScript | packages/jsdoc-tag/lib/inline.js | bitfocus/jsdoc | 4dfcf0c61846fc7347d90cd3a2fc0894bc8ba88a | [
"Apache-2.0"
] | 3 | 2017-04-14T10:00:18.000Z | 2021-08-31T03:26:00.000Z | packages/jsdoc-tag/lib/inline.js | bitfocus/jsdoc | 4dfcf0c61846fc7347d90cd3a2fc0894bc8ba88a | [
"Apache-2.0"
] | 2 | 2015-04-30T00:30:36.000Z | 2017-01-14T03:18:15.000Z | packages/jsdoc-tag/lib/inline.js | bitfocus/jsdoc | 4dfcf0c61846fc7347d90cd3a2fc0894bc8ba88a | [
"Apache-2.0"
] | 2 | 2015-05-05T18:21:49.000Z | 2017-01-03T22:07:58.000Z | /**
* @module @jsdoc/tag/lib/inline
* @alias @jsdoc/tag.inline
*/
/**
* Information about an inline tag that was found within a string.
*
* @typedef {Object} InlineTagInfo
* @memberof module:@jsdoc/tag.inline
* @property {?string} completeTag - The entire inline tag, including its enclosing braces.
* @property {?string} tag - The tag whose text was found.
* @property {?string} text - The tag text that was found.
*/
/**
* Information about the results of replacing inline tags within a string.
*
* @typedef {Object} InlineTagResult
* @memberof module:@jsdoc/tag.inline
* @property {Array.<module:@jsdoc/tag.inline.InlineTagInfo>} tags - The inline tags that were
* found.
* @property {string} newString - The updated text string after extracting or replacing the inline
* tags.
*/
/**
* Text-replacing function for strings that contain an inline tag.
*
* @callback InlineTagReplacer
* @memberof module:@jsdoc/tag.inline
* @param {string} string - The complete string containing the inline tag.
* @param {module:@jsdoc/tag.inline.InlineTagInfo} tagInfo - Information about the inline tag.
* @return {string} An updated version of the complete string.
*/
/**
* Create a regexp that matches a specific inline tag, or all inline tags.
*
* @private
* @memberof module:@jsdoc/tag.inline
* @param {?string} tagName - The inline tag that the regexp will match. May contain regexp
* characters. If omitted, matches any string.
* @param {?string} prefix - A prefix for the regexp. Defaults to an empty string.
* @param {?string} suffix - A suffix for the regexp. Defaults to an empty string.
* @returns {RegExp} A regular expression that matches the requested inline tag.
*/
function regExpFactory(tagName = '\\S+', prefix = '', suffix = '') {
return new RegExp(`${prefix}\\{@${tagName}\\s+((?:.|\n)+?)\\}${suffix}`, 'i');
}
/**
* Check whether a string is an inline tag. You can check for a specific inline tag or for any valid
* inline tag.
*
* @param {string} string - The string to check.
* @param {?string} tagName - The inline tag to match. May contain regexp characters. If this
* parameter is omitted, this method returns `true` for any valid inline tag.
* @returns {boolean} Set to `true` if the string is a valid inline tag or `false` in all other
* cases.
*/
exports.isInlineTag = (string, tagName) => regExpFactory(tagName, '^', '$').test(string);
/**
* Replace all instances of multiple inline tags with other text.
*
* @param {string} string - The string in which to replace the inline tags.
* @param {Object} replacers - The functions that are used to replace text in the string. The keys
* must contain tag names (for example, `link`), and the values must contain functions with the
* type {@link module:@jsdoc/tag.inline.InlineTagReplacer}.
* @return {module:@jsdoc/tag.inline.InlineTagResult} The updated string, as well as information
* about the inline tags that were found.
*/
const replaceInlineTags = exports.replaceInlineTags = (string, replacers) => {
const tagInfo = [];
function replaceMatch(replacer, tag, match, text) {
const matchedTag = {
completeTag: match,
tag: tag,
text: text
};
tagInfo.push(matchedTag);
return replacer(string, matchedTag);
}
string = string || '';
Object.keys(replacers).forEach(replacer => {
const tagRegExp = regExpFactory(replacer);
let matches;
let previousString;
// call the replacer once for each match
do {
matches = tagRegExp.exec(string);
if (matches) {
previousString = string;
string = replaceMatch(replacers[replacer], replacer, matches[0], matches[1]);
}
} while (matches && previousString !== string);
});
return {
tags: tagInfo,
newString: string.trim()
};
};
/**
* Replace all instances of an inline tag with other text.
*
* @param {string} string - The string in which to replace the inline tag.
* @param {string} tag - The name of the inline tag to replace.
* @param {module:@jsdoc/tag.inline.InlineTagReplacer} replacer - The function that is used to
* replace text in the string.
* @return {module:@jsdoc/tag.inline.InlineTagResult} The updated string, as well as information
* about the inline tags that were found.
*/
const replaceInlineTag = exports.replaceInlineTag = (string, tag, replacer) => {
const replacers = {};
replacers[tag] = replacer;
return replaceInlineTags(string, replacers);
};
/**
* Extract inline tags from a string, replacing them with an empty string.
*
* @param {string} string - The string from which to extract text.
* @param {?string} tag - The inline tag to extract.
* @return {module:@jsdoc/tag.inline.InlineTagResult} The updated string, as well as information
* about the inline tags that were found.
*/
exports.extractInlineTag = (string, tag) =>
replaceInlineTag(string, tag, (str, {completeTag}) =>
str.replace(completeTag, ''));
| 36.292857 | 100 | 0.677819 |
3dbbdbf37170bb4bcb209a795a1cd2a93f9110fd | 2,882 | js | JavaScript | htdocs/libs/dojo/dojox/widget/DynamicTooltip.js | henry-gobiernoabierto/geomoose | a8031be68ef1dccf0c1588143afc5712b125acdb | [
"MIT"
] | 24 | 2015-01-24T14:49:22.000Z | 2022-02-23T18:16:21.000Z | training-web/src/main/webapp/js/dojotoolkit/dojox/widget/DynamicTooltip.js | sulistionoadi/belajar-springmvc-dojo | ac68fddb26bf8076bfa09b2f192170ff3ea3122b | [
"Apache-2.0"
] | 36 | 2015-04-21T12:20:57.000Z | 2018-06-21T09:49:53.000Z | training-web/src/main/webapp/js/dojotoolkit/dojox/widget/DynamicTooltip.js | sulistionoadi/belajar-springmvc-dojo | ac68fddb26bf8076bfa09b2f192170ff3ea3122b | [
"Apache-2.0"
] | 27 | 2015-01-02T09:34:03.000Z | 2018-06-11T11:12:35.000Z | dojo.provide("dojox.widget.DynamicTooltip");
dojo.experimental("dojox.widget.DynamicTooltip");
dojo.require("dijit.Tooltip");
dojo.requireLocalization("dijit", "loading");
dojo.declare("dojox.widget.DynamicTooltip", dijit.Tooltip,
{
// summary:
// Extention of dijit.Tooltip providing content set via XHR
// request via href param
// hasLoaded: Boolean
// false if the contents are yet to be loaded from the HTTP request
hasLoaded: false,
// href: String
// location from where to fetch the contents
href: "",
// label: String
// contents to diplay in the tooltip. Initialized to a loading icon.
label: "",
// preventCache: Boolean
// Cache content retreived externally
preventCache: false,
postMixInProperties: function(){
this.inherited(arguments);
this._setLoadingLabel();
},
_setLoadingLabel: function(){
// summary:
// Changes the tooltip label / contents to loading message, only if
// there's an href param, otherwise acts as normal tooltip
if(this.href){
this.label = dojo.i18n.getLocalization("dijit", "loading", this.lang).loadingState;
}
},
// MOW: this is a new widget, do we really need a deprecated stub?
// setHref: function(/*String|Uri*/ href){
// // summary:
// // Deprecated. Use set('href', ...) instead.
// dojo.deprecated("dojox.widget.DynamicTooltip.setHref() is deprecated. Use set('href', ...) instead.", "", "2.0");
// return this.set("href", href);
// },
_setHrefAttr: function(/*String|Uri*/ href){
// summary:
// Hook so attr("href", ...) works.
// description:
// resets so next show loads new href
// href:
// url to the content you want to show, must be within the same domain as your mainpage
this.href = href;
this.hasLoaded = false;
},
loadContent: function(node){
// summary:
// Download contents of href via XHR and display
// description:
// 1. checks if content already loaded
// 2. if not, sends XHR to download new data
if(!this.hasLoaded && this.href){
this._setLoadingLabel();
this.hasLoaded = true;
dojo.xhrGet({
url: this.href,
handleAs: "text",
tooltipWidget: this,
load: function(response, ioArgs){
this.tooltipWidget.label = response;
this.tooltipWidget.close();
this.tooltipWidget.open(node);
},
preventCache: this.preventCache
});
}
},
refresh: function(){
// summary:
// Allows re-download of contents of href and display
// Useful with preventCache = true
this.hasLoaded = false;
},
open: function(/*DomNode*/ target){
// summary:
// Display the tooltip; usually not called directly.
target = target || (this._connectNodes && this._connectNodes[0]);
if(!target){ return; }
this.loadContent(target);
this.inherited(arguments);
}
}
);
| 26.685185 | 118 | 0.647814 |
3db278ce20ab42d02aad495360a4c1b455614222 | 4,259 | js | JavaScript | third_party/closure/goog/messaging/loggerclient.js | davidgonzalezbarbe/Selenium | 55e370c99a289d36a6ecc41978f7fe2d3813b21c | [
"Apache-2.0"
] | 200 | 2016-03-08T07:59:28.000Z | 2022-03-10T13:27:41.000Z | third_party/closure/goog/messaging/loggerclient.js | davidgonzalezbarbe/Selenium | 55e370c99a289d36a6ecc41978f7fe2d3813b21c | [
"Apache-2.0"
] | 107 | 2016-03-08T08:21:34.000Z | 2022-03-28T19:26:28.000Z | third_party/closure/goog/messaging/loggerclient.js | davidgonzalezbarbe/Selenium | 55e370c99a289d36a6ecc41978f7fe2d3813b21c | [
"Apache-2.0"
] | 105 | 2016-02-24T09:03:09.000Z | 2022-02-07T23:04:05.000Z | // Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This class sends logging messages over a message channel to a
* server on the main page that prints them using standard logging mechanisms.
*
*/
goog.provide('goog.messaging.LoggerClient');
goog.require('goog.Disposable');
goog.require('goog.debug');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.Logger');
/**
* Creates a logger client that sends messages along a message channel for the
* remote end to log. The remote end of the channel should use a
* {goog.messaging.LoggerServer} with the same service name.
*
* @param {!goog.messaging.MessageChannel} channel The channel that on which to
* send the log messages.
* @param {string} serviceName The name of the logging service to use.
* @constructor
* @extends {goog.Disposable}
* @final
*/
goog.messaging.LoggerClient = function(channel, serviceName) {
if (goog.messaging.LoggerClient.instance_) {
return goog.messaging.LoggerClient.instance_;
}
goog.messaging.LoggerClient.base(this, 'constructor');
/**
* The channel on which to send the log messages.
* @type {!goog.messaging.MessageChannel}
* @private
*/
this.channel_ = channel;
/**
* The name of the logging service to use.
* @type {string}
* @private
*/
this.serviceName_ = serviceName;
/**
* The bound handler function for handling log messages. This is kept in a
* variable so that it can be deregistered when the logger client is disposed.
* @type {Function}
* @private
*/
this.publishHandler_ = goog.bind(this.sendLog_, this);
goog.debug.LogManager.getRoot().addHandler(this.publishHandler_);
goog.messaging.LoggerClient.instance_ = this;
};
goog.inherits(goog.messaging.LoggerClient, goog.Disposable);
/**
* The singleton instance, if any.
* @type {goog.messaging.LoggerClient}
* @private
*/
goog.messaging.LoggerClient.instance_ = null;
/**
* Sends a log message through the channel.
* @param {!goog.debug.LogRecord} logRecord The log message.
* @private
*/
goog.messaging.LoggerClient.prototype.sendLog_ = function(logRecord) {
var name = logRecord.getLoggerName();
var level = logRecord.getLevel();
var msg = logRecord.getMessage();
var originalException = logRecord.getException();
var exception;
if (originalException) {
var normalizedException =
goog.debug.normalizeErrorObject(originalException);
exception = {
'name': normalizedException.name,
'message': normalizedException.message,
'lineNumber': normalizedException.lineNumber,
'fileName': normalizedException.fileName,
// Normalized exceptions without a stack have 'stack' set to 'Not
// available', so we check for the existance of 'stack' on the original
// exception instead.
'stack': originalException.stack ||
goog.debug.getStacktrace(goog.debug.Logger.prototype.log)
};
if (goog.isObject(originalException)) {
// Add messageN to the exception in case it was added using
// goog.debug.enhanceError.
for (var i = 0; 'message' + i in originalException; i++) {
exception['message' + i] = String(originalException['message' + i]);
}
}
}
this.channel_.send(this.serviceName_, {
'name': name,
'level': level.value,
'message': msg,
'exception': exception
});
};
/** @override */
goog.messaging.LoggerClient.prototype.disposeInternal = function() {
goog.messaging.LoggerClient.base(this, 'disposeInternal');
goog.debug.LogManager.getRoot().removeHandler(this.publishHandler_);
delete this.channel_;
goog.messaging.LoggerClient.instance_ = null;
};
| 31.316176 | 80 | 0.708852 |
3dc83432ec2f025b75eedbff1a0583507620f585 | 26,210 | js | JavaScript | bio/webapp/resources/webapp/model/genomic_region_search/genomic_region_search_results_default.js | elsiklab/MaizeMine | 2d0bbde4d36e25522f8f2ee06afe13b44d3365e6 | [
"PostgreSQL"
] | 4 | 2017-12-22T06:04:46.000Z | 2020-10-05T02:39:07.000Z | bio/webapp/resources/webapp/model/genomic_region_search/genomic_region_search_results_default.js | elsiklab/MaizeMine | 2d0bbde4d36e25522f8f2ee06afe13b44d3365e6 | [
"PostgreSQL"
] | 16 | 2015-10-29T15:04:16.000Z | 2021-02-08T20:16:50.000Z | bio/webapp/resources/webapp/model/genomic_region_search/genomic_region_search_results_default.js | elsiklab/MaizeMine | 2d0bbde4d36e25522f8f2ee06afe13b44d3365e6 | [
"PostgreSQL"
] | 5 | 2016-08-01T18:54:24.000Z | 2021-04-15T12:43:53.000Z |
var is_all_queries_finished = false;
var finishedQueryCount = 0;
var current_page_size = 10;
var current_page_no = 1;
var spanResultWaitingIntervalId = "";
jQuery(document).ready(function(){
init();
// polling
jQuery.PeriodicalUpdater("genomicRegionSearchAjax.do", {
method: 'post', // method; get or post
data: {spanUUIDString: span_uuid_string, getProgress: "true"}, // array of values to be passed to the page - e.g. {name: "John", greeting: "hello"}
minTimeout: 500, // starting value for the timeout in milliseconds
maxTimeout: 5000, // maximum length of time between requests
multiplier: 2, // if set to 2, timerInterval will double each time the response hasn't changed (up to maxTimeout)
type: 'text', // response type - text, xml, json, etc. See $.ajax config options
maxCalls: 0, // maximum number of calls. 0 = no limit.
autoStop: 50 // automatically stop requests after this many returns of the same data. 0 = disabled.
}, function(data) {
finishedQueryCount = parseInt(data);
if (finishedQueryCount < span_query_total_count) {
var percentage = Math.floor(100 * finishedQueryCount / span_query_total_count);
jQuery("#progressbar").progressBar(percentage);
jQuery("#progressbar_status").html(finishedQueryCount + "/" + span_query_total_count);
} else { // all queries finished
is_all_queries_finished = true;
jQuery("#progressbar_div").hide();
displayJBrowse();
enableExportAll();
updatePageNavBarAfterQueryFinish(current_page_no, current_page_size);
}
});
// Start to load the first 10 results
loadResultData(current_page_size, current_page_no);
});
function init() {
// disable export all
disableExportAll()
// page size 10 is selected by default
jQuery('#pageSizeList option[value=10]').attr('selected','selected');
// page navigation
updatePageNavBarBeforeQueryFinish();
// progressBar init
jQuery("#progressbar").progressBar({
showText: false,
boxImage: 'model/jquery_progressbar/images/progressbar.gif',
barImage: {
0: 'model/jquery_progressbar/images/progressbg_red.gif',
30: 'model/jquery_progressbar/images/progressbg_orange.gif',
70: 'model/jquery_progressbar/images/progressbg_green.gif'
}
});
}
function disableExportAll() {
jQuery("#export-all-div").empty();
jQuery("#export-all-div").append('Export data for all features within each region: <span style="color:grey;">TAB</span> | <span style="color:grey;">CSV</span> | <span style="color:grey;">GFF3</span> | <span style="color:grey;">SEQ</span> or Create List by feature type: <select></select>');
}
function enableExportAll() {
jQuery("#export-all-div").empty();
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, isEmptyFeature: "true" }, function(isEmptyFeature){
if (isEmptyFeature.trim() == "hasFeature") {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, generateCreateListHtml: "true" }, function(createListHtml){
exportButtonsHtml = '<span class="export-region">Export data for all features within all regions:</span>'
+ '<span class="tab export-region">'
+ '<a title="Export data for all features within all regions in tab-delimited format" href="javascript: exportFeatures(\'all\', \'SequenceFeature\', \'tab\');"></a></span>'
+ '<span class="csv export-region">'
+ '<a title="Export data for all features within all regions in comma-delimited format" href="javascript: exportFeatures(\'all\', \'SequenceFeature\', \'csv\');"></a></span>'
+ '<span class="gff3 export-region">'
+ '<a title="Export data for all features within all regions in GFF3 format" href="javascript: exportFeatures(\'all\', \'SequenceFeature\', \'gff3\');"></a></span>'
+ '<span class="bed export-region">'
+ '<a title="Export data for all features within all regions in BED format" href="javascript: exportFeatures(\'all\', \'SequenceFeature\', \'bed\');"></a></span>'
+ '<span class="fasta export-region">'
+ '<a title="Export all features as individual sequences" href="javascript: exportFeatures(\'all\', \'SequenceFeature\', \'sequence\');"></a></span>';
if (export_chromosome_segment == "false") {
jQuery("#export-all-div").append(exportButtonsHtml + '<br/>' + createListHtml);
} else {
jQuery("#export-all-div").append(exportButtonsHtml + '<br/>'
+ '<span class="export-region">Export entire sequences for all regions: </span><a href="javascript: exportFeatures(\'all\', \'\', \'chrSeg\');"><img title="Export entire sequences for all regions" class="fasta" style="margin-top: 0px;" src="model/images/fasta.gif"></a><br/>'
+ createListHtml);
}
});
} else {
jQuery("#export-all-div").append('Export data for all features within all regions: <span style="color:grey;">TAB</span> | <span style="color:grey;">CSV</span> | <span style="color:grey;">GFF3</span> | <span style="color:grey;">SEQ</span> or Create List by feature type: <select></select>');
}
});
}
function exportFeatures(criteria, facet, format) {
jQuery.download("genomicRegionSearchAjax.do", "exportFeatures=true&spanUUIDString=" + span_uuid_string + "&criteria=" + criteria + "&facet=" + facet + "&format=" + format);
}
function createList(criteria, id, facet) { // id e.g. I-100-200
if (id) { // JS will convert null, undefined, 0 and "" to bollean false
facet = jQuery("#"+id).val();
}
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, getFeatureCount: "true", criteria: criteria, facet: facet }, function(count){
var feature_count = parseInt(count);
if (feature_count >= 100000) {
alert("It is not allowed to create a list with 100,000+ genomic features...");
} else {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, createList: "true", criteria: criteria, facet: facet }, function(bagName){
window.location.href = "/" + webapp_path + "/bagDetails.do?bagName=" + bagName;
/*window.open(
"/" + webapp_path + "/bagDetails.do?bagName=" + bagName,
'_blank' // <- This is what makes it open in a new window.
);*/
}, "text"); // would use but triggers pop up blocker
}
}, "text");
}
function exportToGalaxy(genomicRegion) {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, getFeatures: "true", grString: genomicRegion }, function(featureIds){
featureIds ='<input type="hidden" name="featureIds" value="' + featureIds + '" />';
orgName ='<input type="hidden" name="orgName" value="' + genomicRegion.split("|")[genomicRegion.split("|").length - 1] + '" />';
jQuery('<form action="galaxyExportOptions.do" method="post">' + featureIds + orgName + '</form>').appendTo('body').submit().remove();
}, "text");
}
function changePageSize() {
current_page_size = jQuery('#pageSizeList').val();
current_page_no = 1;
loadResultData(current_page_size, current_page_no);
if(finishedQueryCount < span_query_total_count){
updatePageNavBarBeforeQueryFinish();
} else {
updatePageNavBarAfterQueryFinish(current_page_no, current_page_size);
}
}
function loadResultData(page_size, page_num) {
clearInterval(spanResultWaitingIntervalId);
var from_index = (page_num - 1) * page_size; // the start index in the result map
var to_index = page_num * page_size -1; // the end index in the result map
if (to_index > span_query_total_count)
{ to_index = span_query_total_count - 1;}
if (is_all_queries_finished == true || (finishedQueryCount - 1) > to_index) {
paginationGetResult(from_index, to_index);
}
if ((finishedQueryCount - 1) < to_index) {
spanResultWaitingIntervalId = setInterval(waitingForSpanResult, 500);
}
function waitingForSpanResult()
{
jQuery("#genomic-region-results-table > tbody").html('<img src="images/wait30.gif"/>');
if ((finishedQueryCount - 1) >= to_index) {
clearInterval(spanResultWaitingIntervalId);
paginationGetResult(from_index, to_index);
}
}
}
function paginationGetResult(from_index, to_index) {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, getData: "true", fromIdx: from_index, toIdx: to_index }, function(results){
addResultToTable(results);
}, "html");
}
function addResultToTable(spanResult) {
jQuery("#genomic-region-results-table").empty();
resultToDisplay = spanResult.paginatedSpanResult;
jQuery("#genomic-region-results-table").append(spanResult);
}
function gbrowseThumbnail(title, organism, url) {
gb_img_url = gbrowse_image_url + organism + "/?" + url+";width=600;b=1";
gb_server_url = gbrowse_base_url + organism + "/?" + url;
jQuery("#gbrowseThumbnail").html("<a href='" + gb_server_url + "' target='_blank'><img title='GBrowse' src='" + gb_img_url + "'></a>");
jQuery("#gbrowseThumbnail").dialog( "destroy" );
jQuery("#gbrowseThumbnail").dialog({
title: '',
height: 400,
width: 500,
show: "fade",
hide: "fade"
});
jQuery("#gbrowseThumbnail").dialog("option", "title", title);
// jQuery("#gbrowseThumbnail").dialog("option", "position", [50, 50]);
}
function updatePageNavBarAfterQueryFinish(current_page_no, current_page_size) {
jQuery("#upperNav").empty();
jQuery("#lowerNav").empty();
total_page = getTotalPageNumber();
if (total_page <= 1) {
jQuery("#upperNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">1 - '+span_query_total_count+' of '+span_query_total_count+'</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else {
if (current_page_no <= 1) {
jQuery("#upperNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span class="fakelink" onclick="pageNavigate(\'last\');"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">1 - '+current_page_no*current_page_size+' of '+span_query_total_count+'</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span class="fakelink" onclick="pageNavigate(\'last\');"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else if (current_page_no >= total_page) {
jQuery("#upperNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">'+((current_page_no-1)*current_page_size+1)+' - '+span_query_total_count+' of '+span_query_total_count+'</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else {
jQuery("#upperNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span class="fakelink" onclick="pageNavigate(\'last\');"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">'+((current_page_no-1)*current_page_size+1)+' - '+current_page_no*current_page_size+' of '+span_query_total_count+'</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span class="fakelink" onclick="pageNavigate(\'last\');"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
}
}
function updatePageNavBarBeforeQueryFinish() {
jQuery("#upperNav").empty();
jQuery("#lowerNav").empty();
total_page = getTotalPageNumber();
if (total_page <= 1) {
jQuery("#upperNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">1 - '+span_query_total_count+' of '+span_query_total_count+'</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else {
if (current_page_no <= 1) {
jQuery("#upperNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span style="color:grey;"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">1 - '+current_page_no*current_page_size+' of '+span_query_total_count+'</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else if (current_page_no >= total_page) {
jQuery("#upperNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">'+((current_page_no-1)*current_page_size+1)+' - '+span_query_total_count+' of '+span_query_total_count+'</span>')
.append('<span style="color:grey;"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
else {
jQuery("#upperNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">|</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
jQuery("#lowerNav").append('<span class="fakelink" onclick="pageNavigate(\'first\');"><span style="font-family:\'Comic Sans MS\';"><<</span> First </span>')
.append('<span class="fakelink" onclick="pageNavigate(\'prev\');"><span style="font-family:\'Comic Sans MS\';"><</span> Prev </span>')
.append('<span style="color:grey;">'+((current_page_no-1)*current_page_size+1)+' - '+current_page_no*current_page_size+' of '+span_query_total_count+'</span>')
.append('<span class="fakelink" onclick="pageNavigate(\'next\');"> Next <span style="font-family:\'Comic Sans MS\';">></span></span>')
.append('<span style="color:grey;"> Last <span style="font-family:\'Comic Sans MS\';">>></span></span>');
}
}
}
function pageNavigate(method) {
if (method == "first") { current_page_no = 1; }
if (method == "last") { current_page_no = getTotalPageNumber(); }
if (method == "prev") { current_page_no--; }
if (method == "next") { current_page_no++; }
loadResultData(current_page_size, current_page_no);
if(finishedQueryCount < span_query_total_count){
updatePageNavBarBeforeQueryFinish();
} else {
updatePageNavBarAfterQueryFinish(current_page_no, current_page_size);
}
}
function getTotalPageNumber() {
total_page = Math.floor(span_query_total_count / current_page_size);
if (span_query_total_count % current_page_size != 0) { total_page++; }
return total_page;
}
function displayJBrowse() {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, getDropDownList: "true" }, function(data){
var regions = data.split(",");
jQuery.each(regions, function(index, value) {
bits = value.split("|"); // e.g. 2L:14615455..14619002|0|D. melanogaster
jQuery('#region-select-list').append( new Option(bits[0],jQuery.trim(value)) );
});
jQuery("#region-select-list").change(function () {
var selectedRegion = jQuery(this).val();
// change JBrowse
// mock up:
var url = "http://www.metabolicmine.org/jbrowse?loc=Homo_sapiens_chr_3:12328867..12475843&tracks=Gene%20Track,mRNA%20Track,%20SNPs"
window.open(url, 'jbrowse'); // open in iframe id = jbrowse
// change results view
if (selectedRegion != "all") {
jQuery.post("genomicRegionSearchAjax.do", { spanUUIDString: span_uuid_string, getGivenRegionsResults: "true", regions: selectedRegion }, function(results){
jQuery("#upper-pag-div").hide();
jQuery("#export-all-div").hide();
jQuery("#bottom-pag-div").hide();
addResultToTable(results);
}, "html");
} else {
updatePageNavBarAfterQueryFinish(1, 10);
jQuery("#upper-pag-div").show();
jQuery("#export-all-div").show();
jQuery("#bottom-pag-div").show();
loadResultData(10, 1);
}
}); // add .change() at the tail will trigger on load
}, "text");
}
| 67.726098 | 341 | 0.544907 |
3da544d3c45f8fd9c3abfc3ae18a7a20bfbde52c | 9,906 | js | JavaScript | tests/unit/Stateful.js | tkrugg/decor | 74b1866173abe9c8975569340c395d19f8a15ca7 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/Stateful.js | tkrugg/decor | 74b1866173abe9c8975569340c395d19f8a15ca7 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/Stateful.js | tkrugg/decor | 74b1866173abe9c8975569340c395d19f8a15ca7 | [
"BSD-3-Clause"
] | null | null | null | define([
"intern!object",
"intern/chai!assert",
"../../Stateful",
"dcl/dcl"
], function (registerSuite, assert, Stateful, dcl) {
registerSuite({
name: "Stateful",
"accessors": function () {
var StatefulClass1 = dcl(Stateful, {
foo: 0,
bar: 0,
baz: "",
_getFooAttr: function () {
return this._fooAttr - 1;
},
_setBarAttr: function (value) {
this._set("bar", value + 1);
}
});
var attr1 = new StatefulClass1();
attr1.foo = 4;
attr1.bar = 2;
attr1.baz = "bar";
assert.strictEqual(attr1.foo, 3, "attr1.foo getter works");
assert.strictEqual(attr1.bar, 3, "attr1.bar setter works");
assert.strictEqual(attr1.baz, "bar", "attribute set properly");
},
"paramHandling": function () {
var StatefulClass2 = dcl(Stateful, {
foo: null,
bar: 5,
_setFooAttr: function (value) {
this._set("foo", value);
},
_setBarAttr: function (value) {
this._set("bar", value);
}
});
var attr2 = new StatefulClass2({
foo: function () {
return "baz";
},
bar: 4
});
assert.strictEqual(typeof attr2.foo, "function", "function attribute set");
assert.strictEqual(attr2.foo(), "baz", "function has proper return value");
assert.strictEqual(attr2.bar, 4, "attribute has proper value");
// Check if user overrides widget to not process constructor params
var IgnoreParamsStateful = dcl(Stateful, {
foo: 3,
processConstructorParameters: function () {
}
});
var ignore = new IgnoreParamsStateful({
foo: 4
});
assert.strictEqual(ignore.foo, 3, "constructor foo ignored");
// And make sure it works even if the argument isn't a hash
var ignore2 = new IgnoreParamsStateful(5, 4, 3, 2, 1);
assert.strictEqual(ignore2.foo, 3, "ignore2 created");
},
"_get": function () {
var StatefulClass5 = dcl(Stateful, {
foo: "",
_getFooAttr: function () {
return this._get("foo") + "modified";
}
});
var attr5 = new StatefulClass5();
assert.strictEqual(attr5.foo, "modified", "value get properly");
attr5.foo = "further";
assert.strictEqual(attr5.foo, "furthermodified");
},
"moreCorrelatedProperties": function () {
var Widget = dcl(Stateful, {
foo: 10,
_setFooAttr: function (val) {
this._set("foo", val);
this._set("bar", val + 1);
},
bar: 11,
_setBarAttr: function (val) {
this._set("bar", val);
this._set("foo", val - 1);
}
});
var w1 = new Widget({foo: 30});
assert.strictEqual(w1.foo, 30, "w1.foo");
assert.strictEqual(w1.bar, 31, "w1.bar");
var w2 = new Widget({bar: 30});
assert.strictEqual(w2.bar, 30, "w2.bar");
assert.strictEqual(w2.foo, 29, "w2.foo");
var w3 = new Widget({});
assert.strictEqual(w3.foo, 10, "w3.foo");
assert.strictEqual(w3.bar, 11, "w3.bar");
},
"getSetObserve": function () {
var dfd = this.async(1000),
count = 0,
s = new (dcl(Stateful, {
foo: 3
}))();
assert.strictEqual(s.foo, 3);
var watching = s.observe(dfd.rejectOnError(function (oldValues) {
if (++count > 1) {
throw new Error("Observer callback should not be called after observation is stopped.");
}
assert.deepEqual(oldValues, {foo: 3});
assert.strictEqual(s.foo, 4);
watching.remove();
s.foo = 5;
assert.strictEqual(s.foo, 5);
setTimeout(dfd.resolve.bind(dfd), 100);
}));
s.foo = 4;
assert.strictEqual(s.foo, 4);
},
"removeObserveHandleTwice": function () {
var dfd = this.async(1000),
s = new (dcl(Stateful, {
foo: 3
}))(),
changes = [];
var watching = s.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "toBeRemoved", oldValues: oldValues});
}));
s.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "toBeAlive", oldValues: oldValues});
}));
s.foo = 4;
watching.remove();
watching.remove();
s.foo = 5;
setTimeout(dfd.callback(function () {
assert.deepEqual(changes, [
{id: "toBeAlive", oldValues: {foo: 3}}
]);
}), 100);
},
"setHash: observe()": function () {
var dfd = this.async(1000),
s = new (dcl(Stateful, {
foo: 0,
bar: 0
}))(),
changes = [];
s.observe(dfd.rejectOnError(function (oldValues) {
changes.push(oldValues);
}));
s.mix({
foo: 3,
bar: 5
});
assert.strictEqual(s.foo, 3);
assert.strictEqual(s.bar, 5);
setTimeout(dfd.rejectOnError(function () {
assert.deepEqual(changes, [{foo: 0, bar: 0}]);
var Clz2 = dcl(Stateful, {
foo: 0,
bar: 0
}),
s2 = new Clz2();
s2.mix(s);
assert.strictEqual(s2.foo, 3);
assert.strictEqual(s2.bar, 5);
setTimeout(dfd.callback(function () {
// s watchers should not be copied to s2
assert.strictEqual(changes.length, 1);
}), 100);
}), 100);
},
"_set: observe()": function () {
var dfd = this.async(1000),
StatefulClass4 = dcl(Stateful, {
foo: null,
bar: null,
_setFooAttr: function (value) {
this._set("bar", value);
this._set("foo", value);
},
_setBarAttr: function (value) {
this._set("foo", value);
this._set("bar", value);
}
}),
attr4 = new StatefulClass4(),
changes = [];
attr4.observe(dfd.rejectOnError(function (oldValues) {
changes.push(oldValues);
}));
attr4.foo = 3;
assert.strictEqual(attr4.bar, 3, "value set properly");
attr4.bar = 4;
assert.strictEqual(attr4.foo, 4, "value set properly");
setTimeout(dfd.callback(function () {
assert.deepEqual(changes, [{foo: null, bar: null}]);
}), 100);
},
"subclasses1: observe()": function () {
// Test when superclass and subclass are declared first, and afterwards instantiated
var dfd = this.async(1000),
SuperClass = dcl(Stateful, {
foo: null,
bar: null
}),
SubClass = dcl(SuperClass, {
bar: 5
}),
sub = new SubClass(),
changes = [];
sub.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "sub", oldValues: oldValues});
}));
sub.foo = 3;
sub.bar = 4;
var sup = new SuperClass();
sup.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "sup", oldValues: oldValues});
}));
sup.foo = 5;
sup.bar = 6;
setTimeout(dfd.callback(function () {
assert.deepEqual(changes, [
{id: "sub", oldValues: {foo: null, bar: 5}},
{id: "sup", oldValues: {foo: null, bar: null}}
]);
}), 100);
},
"subclasses2: observe()": function () {
// Test when superclass is declared and instantiated, then subclass is declared and use later
var dfd = this.async(1000),
SuperClass = dcl(Stateful, {
foo: null,
bar: null
}),
sup = new SuperClass(),
changes = [];
sup.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "sup", oldValues: oldValues});
}));
sup.foo = 5;
sup.bar = 6;
var customSetterCalled,
SubClass = dcl(SuperClass, {
bar: 5,
_setBarAttr: function (val) {
// this should get called even though SuperClass doesn't have a custom setter for "bar"
customSetterCalled = true;
this._set("bar", val);
}
}),
sub = new SubClass();
sub.observe(dfd.rejectOnError(function (oldValues) {
changes.push({id: "sub", oldValues: oldValues});
}));
sub.foo = 3;
sub.bar = 4;
assert.ok(customSetterCalled, "SubClass custom setter called");
setTimeout(dfd.rejectOnError(function () {
assert.deepEqual(changes, [
{id: "sup", oldValues: {foo: null, bar: null}},
{id: "sub", oldValues: {foo: null, bar: 5}}
]);
sup.bar = 6;
setTimeout(dfd.callback(function () {
assert.strictEqual(changes.length, 2);
}), 100);
}), 100);
},
"observe(): Changing some properties while some of them don't yield actual changes": function () {
var dfd = this.async(1000),
stateful = new (dcl(Stateful, {
foo: undefined,
bar: undefined,
baz: undefined,
quux: undefined
}))({
foo: "Foo",
bar: "Bar0",
baz: NaN,
quux: 0
});
stateful.observe(dfd.callback(function (oldValues) {
assert.deepEqual(oldValues, {
bar: "Bar0",
quux: 0
});
}));
stateful.foo = "Foo";
stateful.bar = "Bar1";
stateful.bar = "Bar2";
stateful.baz = NaN;
stateful.quux = -0;
},
"notifyCurrentValue()": function () {
var dfd = this.async(1000),
stateful = new (dcl(Stateful, {
foo: undefined
}))({
foo: "Foo"
});
stateful.observe(dfd.callback(function (oldValues) {
assert.deepEqual(oldValues, {foo: "Foo"});
}));
stateful.notifyCurrentValue("foo");
},
"Stateful.PropertyListObserver#deliver(), Stateful.PropertyListObserver#discardChanges()": function () {
var changes = [],
stateful = new (dcl(Stateful, {
foo: undefined
}))({
foo: "Foo0"
}),
hObserve = stateful.observe(function (oldValues) {
changes.push(oldValues);
});
stateful.foo = "Foo1";
hObserve.discardChanges();
stateful.foo = "Foo2";
hObserve.deliver();
assert.deepEqual(changes, [{foo: "Foo1"}]);
},
"observe filter": function () {
// Check to make sure reported changes are consistent between platforms with and without Object.observe()
// native support
var dfd = this.async(1000),
stateful = new (dcl(Stateful, {
_private: 1,
foo: 2,
_setFooAttr: function (val) {
this._set("foo", val);
},
constructor: function () {
this.instanceProp = 3;
},
anotherFunc: function () { }
}))({});
stateful.observe(dfd.callback(function (oldValues) {
assert.deepEqual(oldValues, {
_private: 1,
foo: 2
});
}));
stateful._private = 11;
stateful.foo = 22;
stateful.anotherFunc = function () { };
stateful.instanceProp = 33;
},
});
});
| 25.530928 | 108 | 0.593882 |
3db1e4dbaad4f4de8e56e78c024f3af27ee3ac90 | 1,113 | js | JavaScript | flow-typed/recast.js | maciej-gurban/react-docgen | 62af3782a0f976449761d58fa6f31cf3ff9009fa | [
"BSD-3-Clause"
] | null | null | null | flow-typed/recast.js | maciej-gurban/react-docgen | 62af3782a0f976449761d58fa6f31cf3ff9009fa | [
"BSD-3-Clause"
] | null | null | null | flow-typed/recast.js | maciej-gurban/react-docgen | 62af3782a0f976449761d58fa6f31cf3ff9009fa | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*eslint no-unused-vars: 0*/
/**
* A minimal set of declarations to make flow work with the recast API.
*/
type ASTNode = Object;
declare class Scope {
lookup(name: string): ?Scope;
lookupType(name: string): ?Scope;
getBindings(): { [key: string]: Array<NodePath> };
getTypes(): { [key: string]: Array<NodePath> };
node: NodePath;
}
declare class NodePath {
value: ASTNode | Array<ASTNode>;
node: ASTNode;
parent: NodePath;
parentPath: NodePath;
scope: Scope;
get(...x: Array<string | number>): NodePath;
each(f: (p: NodePath) => any): any;
map<T>(f: (p: NodePath) => T): Array<T>;
filter(f: (p: NodePath) => boolean): Array<NodePath>;
push(node: ASTNode): void;
}
type Recast = {
parse: (src: string) => ASTNode,
print: (path: NodePath) => { code: string },
};
| 24.733333 | 79 | 0.654088 |
3db91d7a612bebb38b7e0b323495822174012e01 | 2,002 | js | JavaScript | shared/settings/nav/settings-item.js | darwin/client | 80d540ecbbce1fae11614d6ee49e2ce1f9396e2c | [
"BSD-3-Clause"
] | null | null | null | shared/settings/nav/settings-item.js | darwin/client | 80d540ecbbce1fae11614d6ee49e2ce1f9396e2c | [
"BSD-3-Clause"
] | null | null | null | shared/settings/nav/settings-item.js | darwin/client | 80d540ecbbce1fae11614d6ee49e2ce1f9396e2c | [
"BSD-3-Clause"
] | null | null | null | // @flow
import React from 'react'
import type {SettingsItemProps} from './index'
import {Badge, ClickableBox, Text, Icon} from '../../common-adapters'
import * as Style from '../../styles'
export default function SettingsItem(props: SettingsItemProps) {
return (
<ClickableBox
onClick={props.onClick}
style={Style.collapseStyles([
styles.item,
props.selected
? {
borderLeftColor: Style.globalColors.blue,
borderLeftStyle: 'solid',
borderLeftWidth: 3,
}
: {},
])}
>
{props.icon && (
<Icon
type={props.icon}
color={Style.globalColors.black_20}
style={{marginRight: Style.globalMargins.small}}
/>
)}
<Text
type="BodySemibold"
style={Style.collapseStyles([
props.selected ? styles.selectedText : styles.itemText,
props.textColor ? {color: props.textColor} : {},
])}
>
{props.text}
</Text>
{!!props.badgeNumber && props.badgeNumber > 0 && (
<Badge badgeNumber={props.badgeNumber} badgeStyle={styles.badge} />
)}
</ClickableBox>
)
}
const styles = Style.styleSheetCreate({
badge: {
marginLeft: 6,
},
item: Style.platformStyles({
common: {
...Style.globalStyles.flexBoxRow,
alignItems: 'center',
paddingLeft: Style.globalMargins.small,
paddingRight: Style.globalMargins.small,
position: 'relative',
},
isElectron: {
height: 32,
textTransform: 'uppercase',
width: '100%',
},
isMobile: {
borderBottomColor: Style.globalColors.black_10,
borderBottomWidth: Style.hairlineWidth,
height: 56,
},
}),
itemText: Style.platformStyles({
isElectron: {
color: Style.globalColors.black_50,
},
isMobile: {
color: Style.globalColors.black_75,
},
}),
selectedText: {
color: Style.globalColors.black_75,
},
})
| 25.025 | 75 | 0.581419 |
3dcd9629f88e324d0438f21319b97d59a16d1db5 | 30,841 | js | JavaScript | html/js/controllers/send_coins.js | shinesli/openwallet-rebase | 3355d496494641d2a95424a3676ff1a4bdc6e6d1 | [
"BSD-3-Clause"
] | null | null | null | html/js/controllers/send_coins.js | shinesli/openwallet-rebase | 3355d496494641d2a95424a3676ff1a4bdc6e6d1 | [
"BSD-3-Clause"
] | null | null | null | html/js/controllers/send_coins.js | shinesli/openwallet-rebase | 3355d496494641d2a95424a3676ff1a4bdc6e6d1 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2014-2017, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
thinwalletCtrls.controller('SendCoinsCtrl', function($scope, $http, $q,
AccountService, ModalService,
ApiCalls)
{
"use strict";
$scope.status = "";
$scope.error = "";
$scope.submitting = false;
$scope.targets = [{}];
$scope.totalAmount = JSBigInt.ZERO;
$scope.mixins = config.defaultMixin.toString();
$scope.view_only = AccountService.isViewOnly();
$scope.success_page = false;
$scope.sent_tx = {};
var view_only = AccountService.isViewOnly();
var explorerUrl = config.testnet ? config.testnetExplorerUrl : config.mainnetExplorerUrl;
// few multiplayers based on uint64_t wallet2::get_fee_multiplier
var fee_multiplayers = [1, 4, 20, 166];
var default_priority = 2;
$scope.priority = default_priority.toString();
$scope.openaliasDialog = undefined;
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
function confirmOpenAliasAddress(domain, address, name, description, dnssec_used) {
var deferred = $q.defer();
if ($scope.openaliasDialog !== undefined) {
deferred.reject("OpenAlias confirm dialog is already being shown!");
return;
}
$scope.openaliasDialog = {
address: address,
domain: domain,
name: name,
description: description,
dnssec_used: dnssec_used,
confirm: function() {
$scope.openaliasDialog = undefined;
console.log("User confirmed OpenAlias resolution for " + domain + " to " + address);
deferred.resolve();
},
cancel: function() {
$scope.openaliasDialog = undefined;
console.log("User rejected OpenAlias resolution for " + domain + " to " + address);
deferred.reject("OpenAlias resolution rejected by user");
}
};
return deferred.promise;
}
$scope.transferConfirmDialog = undefined;
function confirmTransfer(address, amount, tx_hash, fee, tx_prv_key,
payment_id, mixin, priority, txBlobKBytes) {
var deferred = $q.defer();
if ($scope.transferConfirmDialog !== undefined) {
deferred.reject("transferConfirmDialog is already being shown!");
return;
}
var priority_names = ["Low", "Medium", "High", "Paranoid"];
$scope.transferConfirmDialog = {
address: address,
fee: fee,
tx_hash: tx_hash,
amount: amount,
tx_prv_key: tx_prv_key,
payment_id: payment_id,
mixin: mixin + 1,
txBlobKBytes: Math.round(txBlobKBytes*1e3) / 1e3,
priority: priority_names[priority - 1],
confirm: function() {
$scope.transferConfirmDialog = undefined;
deferred.resolve();
},
cancel: function() {
$scope.transferConfirmDialog = undefined;
deferred.reject("Transfer canceled by user");
}
};
return deferred.promise;
}
function getTxCharge(amount) {
amount = new JSBigInt(amount);
// amount * txChargeRatio
return amount.divide(1 / config.txChargeRatio);
}
$scope.removeTarget = function(index) {
$scope.targets.splice(index, 1);
};
$scope.$watch('targets', function() {
var totalAmount = JSBigInt.ZERO;
for (var i = 0; i < $scope.targets.length; ++i) {
try {
var amount = cnUtil.parseMoney($scope.targets[i].amount);
totalAmount = totalAmount.add(amount);
} catch (e) {
}
}
$scope.totalAmount = totalAmount;
}, true);
$scope.resetSuccessPage = function() {
$scope.success_page = false;
$scope.sent_tx = {};
};
$scope.sendCoins = function(targets, mixin, payment_id) {
if ($scope.submitting) return;
$scope.status = "";
$scope.error = "";
$scope.submitting = true;
mixin = parseInt(mixin);
var rct = true; //maybe want to set this later based on inputs (?)
var realDsts = [];
var targetPromises = [];
for (var i = 0; i < targets.length; ++i) {
var target = targets[i];
if (!target.address && !target.amount) {
continue;
}
var deferred = $q.defer();
targetPromises.push(deferred.promise);
(function(deferred, target) {
var amount;
try {
amount = cnUtil.parseMoney(target.amount);
} catch (e) {
deferred.reject("Failed to parse amount (#" + i + ")");
return;
}
if (target.address.indexOf('.') === -1) {
try {
// verify that the address is valid
cnUtil.decode_address(target.address);
deferred.resolve({
address: target.address,
amount: amount
});
} catch (e) {
deferred.reject("Failed to decode address (#" + i + "): " + e);
return;
}
} else {
var domain = target.address.replace(/@/g, ".");
ApiCalls.get_txt_records(domain)
.then(function(response) {
var data = response.data;
var records = data.records;
var oaRecords = [];
console.log(domain + ": ", data.records);
if (data.dnssec_used) {
if (data.secured) {
console.log("DNSSEC validation successful");
} else {
deferred.reject("DNSSEC validation failed for " + domain + ": " + data.dnssec_fail_reason);
return;
}
} else {
console.log("DNSSEC Not used");
}
for (var i = 0; i < records.length; i++) {
var record = records[i];
if (record.slice(0, 4 + config.openAliasPrefix.length + 1) !== "oa1:" + config.openAliasPrefix + " ") {
continue;
}
console.log("Found OpenAlias record: " + record);
oaRecords.push(parseOpenAliasRecord(record));
}
if (oaRecords.length === 0) {
deferred.reject("No OpenAlias records found for: " + domain);
return;
}
if (oaRecords.length !== 1) {
deferred.reject("Multiple addresses found for given domain: " + domain);
return;
}
console.log("OpenAlias record: ", oaRecords[0]);
var oaAddress = oaRecords[0].address;
try {
cnUtil.decode_address(oaAddress);
confirmOpenAliasAddress(domain, oaAddress,
oaRecords[0].name, oaRecords[0].description,
data.dnssec_used && data.secured)
.then(function() {
deferred.resolve({
address: oaAddress,
amount: amount,
domain: domain
});
}, function(err) {
deferred.reject(err);
});
} catch (e) {
deferred.reject("Failed to decode OpenAlias address: " + oaRecords[0].address + ": " + e);
return;
}
}, function(data) {
deferred.reject("Failed to resolve DNS records for '" + domain + "': " + "Unknown error");
});
}
})(deferred, target);
}
var strpad = function(org_str, padString, length)
{ // from http://stackoverflow.com/a/10073737/248823
var str = org_str;
while (str.length < length)
str = padString + str;
return str;
};
// Transaction will need at least 1KB fee (13KB for RingCT)
var feePerKB = new JSBigInt(config.feePerKB);
var priority = $scope.priority || default_priority;
if (!isInt(priority))
{
$scope.submitting = false;
$scope.error = "Priority is not an integer number";
return;
}
if (!(priority >= 1 && priority <= 4))
{
$scope.submitting = false;
$scope.error = "Priority is not between 1 and 4";
return;
}
var fee_multiplayer = fee_multiplayers[priority - 1]; // default is 4
var neededFee = rct ? feePerKB.multiply(13) : feePerKB;
var totalAmountWithoutFee;
var unspentOuts;
var pid_encrypt = false; //don't encrypt payment ID unless we find an integrated one
$q.all(targetPromises).then(function(destinations) {
totalAmountWithoutFee = new JSBigInt(0);
for (var i = 0; i < destinations.length; i++) {
totalAmountWithoutFee = totalAmountWithoutFee.add(destinations[i].amount);
}
realDsts = destinations;
console.log("Parsed destinations: " + JSON.stringify(realDsts));
console.log("Total before fee: " + cnUtil.formatMoney(totalAmountWithoutFee));
if (realDsts.length === 0) {
$scope.submitting = false;
$scope.error = "You need to enter a valid destination";
return;
}
if (payment_id)
{
if (payment_id.length <= 64 && /^[0-9a-fA-F]+$/.test(payment_id))
{
// if payment id is shorter, but has correct number, just
// pad it to required length with zeros
payment_id = strpad(payment_id, "0", 64);
}
// now double check if ok, when we padded it
if (payment_id.length !== 64 || !(/^[0-9a-fA-F]{64}$/.test(payment_id)))
{
$scope.submitting = false;
$scope.error = "The payment ID you've entered is not valid";
return;
}
}
if (realDsts.length === 1) {//multiple destinations aren't supported by MyMonero, but don't include integrated ID anyway (possibly should error in the future)
var decode_result = cnUtil.decode_address(realDsts[0].address);
if (decode_result.intPaymentId && payment_id) {
$scope.submitting = false;
$scope.error = "Payment ID field must be blank when using an Integrated Address";
return;
} else if (decode_result.intPaymentId) {
payment_id = decode_result.intPaymentId;
pid_encrypt = true; //encrypt if using an integrated address
}
}
if (totalAmountWithoutFee.compare(0) <= 0) {
$scope.submitting = false;
$scope.error = "The amount you've entered is too low";
return;
}
$scope.status = "Generating transaction...";
console.log("Destinations: ");
// Log destinations to console
for (var j = 0; j < realDsts.length; j++) {
console.log(realDsts[j].address + ": " + cnUtil.formatMoneyFull(realDsts[j].amount));
}
var getUnspentOutsRequest = {
address: AccountService.getAddress(),
view_key: AccountService.getViewKey(),
amount: '0',
mixin: mixin,
// Use dust outputs only when we are using no mixins
use_dust: mixin === 0,
dust_threshold: config.dustThreshold.toString()
};
ApiCalls.get_unspent_outs(getUnspentOutsRequest)
.then(function(request) {
var data = request.data;
unspentOuts = checkUnspentOuts(data.outputs || []);
unused_outs = unspentOuts.slice(0);
using_outs = [];
using_outs_amount = new JSBigInt(0);
if (data.per_kb_fee)
{
feePerKB = new JSBigInt(data.per_kb_fee);
neededFee = feePerKB.multiply(13).multiply(fee_multiplayer);
}
transfer().then(transferSuccess, transferFailure);
}, function(data) {
$scope.status = "";
$scope.submitting = false;
if (data && data.Error) {
$scope.error = data.Error;
console.warn(data.Error);
} else {
$scope.error = "Something went wrong with getting your available balance for spending";
}
});
}, function(err) {
$scope.submitting = false;
$scope.error = err;
console.log("Error decoding targets: " + err);
});
function checkUnspentOuts(outputs) {
for (var i = 0; i < outputs.length; i++) {
for (var j = 0; outputs[i] && j < outputs[i].spend_key_images.length; j++) {
var key_img = AccountService.cachedKeyImage(outputs[i].tx_pub_key, outputs[i].index);
if (key_img === outputs[i].spend_key_images[j]) {
console.log("Output was spent with key image: " + key_img + " amount: " + cnUtil.formatMoneyFull(outputs[i].amount));
// Remove output from list
outputs.splice(i, 1);
if (outputs[i]) {
j = outputs[i].spend_key_images.length;
}
i--;
} else {
console.log("Output used as mixin (" + key_img + "/" + outputs[i].spend_key_images[j] + ")");
}
}
}
console.log("Unspent outs: " + JSON.stringify(outputs));
return outputs;
}
function transferSuccess(tx_h) {
var prevFee = neededFee;
var raw_tx = tx_h.raw;
var tx_hash = tx_h.hash;
var tx_prvkey = tx_h.prvkey;
// work out per-kb fee for transaction
var txBlobBytes = raw_tx.length / 2;
var txBlobKBytes = txBlobBytes / 1024.0;
var numKB = Math.floor(txBlobKBytes);
if (txBlobBytes % 1024) {
numKB++;
}
console.log(txBlobBytes + " bytes <= " + numKB + " KB (current fee: " + cnUtil.formatMoneyFull(prevFee) + ")");
neededFee = feePerKB.multiply(numKB).multiply(fee_multiplayer);
// if we need a higher fee
if (neededFee.compare(prevFee) > 0) {
console.log("Previous fee: " + cnUtil.formatMoneyFull(prevFee) + " New fee: " + cnUtil.formatMoneyFull(neededFee));
transfer().then(transferSuccess, transferFailure);
return;
}
// generated with correct per-kb fee
console.log("Successful tx generation, submitting tx");
console.log("Tx hash: " + tx_hash);
$scope.status = "Submitting...";
var request = {
address: AccountService.getAddress(),
view_key: AccountService.getViewKey(),
tx: raw_tx
};
confirmTransfer(realDsts[0].address, realDsts[0].amount,
tx_hash, neededFee, tx_prvkey, payment_id,
mixin, priority, txBlobKBytes).then(function() {
//alert('Confirmed ');
ApiCalls.submit_raw_tx(request.address, request.view_key, request.tx)
.then(function(response) {
var data = response.data;
if (data.status === "error")
{
$scope.status = "";
$scope.submitting = false;
$scope.error = "Something unexpected occurred when submitting your transaction: " + data.error;
return;
}
//console.log("Successfully submitted tx");
$scope.targets = [{}];
$scope.sent_tx = {
address: realDsts[0].address,
domain: realDsts[0].domain,
amount: realDsts[0].amount,
payment_id: payment_id,
tx_id: tx_hash,
tx_prvkey: tx_prvkey,
tx_fee: neededFee/*.add(getTxCharge(neededFee))*/,
explorerLink: explorerUrl + "tx/" + tx_hash
};
$scope.success_page = true;
$scope.status = "";
$scope.submitting = false;
}, function(error) {
$scope.status = "";
$scope.submitting = false;
$scope.error = "Something unexpected occurred when submitting your transaction: ";
});
}, function(reason) {
//alert('Failed: ' + reason);
transferFailure("Transfer canceled");
});
}
function transferFailure(reason) {
$scope.status = "";
$scope.submitting = false;
$scope.error = reason;
console.log("Transfer failed: " + reason);
}
var unused_outs;
var using_outs;
var using_outs_amount;
function random_index(list) {
return Math.floor(Math.random() * list.length);
}
function pop_random_value(list) {
var idx = random_index(list);
var val = list[idx];
list.splice(idx, 1);
return val;
}
function select_outputs(target_amount) {
console.log("Selecting outputs to use. Current total: " + cnUtil.formatMoney(using_outs_amount) + " target: " + cnUtil.formatMoney(target_amount));
while (using_outs_amount.compare(target_amount) < 0 && unused_outs.length > 0) {
var out = pop_random_value(unused_outs);
if (!rct && out.rct) {continue;} //skip rct outs if not creating rct tx
using_outs.push(out);
using_outs_amount = using_outs_amount.add(out.amount);
console.log("Using output: " + cnUtil.formatMoney(out.amount) + " - " + JSON.stringify(out));
}
}
function transfer() {
var deferred = $q.defer();
(function() {
var dsts = realDsts.slice(0);
// Calculate service charge and add to tx destinations
//var chargeAmount = getTxCharge(neededFee);
//dsts.push({
// address: config.txChargeAddress,
// amount: chargeAmount
//});
// Add fee to total amount
var totalAmount = totalAmountWithoutFee.add(neededFee)/*.add(chargeAmount)*/;
console.log("Balance required: " + cnUtil.formatMoneySymbol(totalAmount));
select_outputs(totalAmount);
//compute fee as closely as possible before hand
if (using_outs.length > 1 && rct)
{
var newNeededFee = JSBigInt(Math.ceil(cnUtil.estimateRctSize(using_outs.length, mixin, 2) / 1024)).multiply(feePerKB).multiply(fee_multiplayer);
totalAmount = totalAmountWithoutFee.add(newNeededFee);
//add outputs 1 at a time till we either have them all or can meet the fee
while (using_outs_amount.compare(totalAmount) < 0 && unused_outs.length > 0)
{
var out = pop_random_value(unused_outs);
using_outs.push(out);
using_outs_amount = using_outs_amount.add(out.amount);
console.log("Using output: " + cnUtil.formatMoney(out.amount) + " - " + JSON.stringify(out));
newNeededFee = JSBigInt(Math.ceil(cnUtil.estimateRctSize(using_outs.length, mixin, 2) / 1024)).multiply(feePerKB).multiply(fee_multiplayer);
totalAmount = totalAmountWithoutFee.add(newNeededFee);
}
console.log("New fee: " + cnUtil.formatMoneySymbol(newNeededFee) + " for " + using_outs.length + " inputs");
neededFee = newNeededFee;
}
if (using_outs_amount.compare(totalAmount) < 0)
{
deferred.reject("Not enough spendable outputs / balance too low (have "
+ cnUtil.formatMoneyFull(using_outs_amount) + " but need "
+ cnUtil.formatMoneyFull(totalAmount)
+ " (estimated fee " + cnUtil.formatMoneyFull(neededFee) + " included)");
return;
}
else if (using_outs_amount.compare(totalAmount) > 0)
{
var changeAmount = using_outs_amount.subtract(totalAmount);
if (!rct)
{ //for rct we don't presently care about dustiness
//do not give ourselves change < dust threshold
var changeAmountDivRem = changeAmount.divRem(config.dustThreshold);
if (changeAmountDivRem[1].toString() !== "0") {
// add dusty change to fee
console.log("Adding change of " + cnUtil.formatMoneyFullSymbol(changeAmountDivRem[1]) + " to transaction fee (below dust threshold)");
}
if (changeAmountDivRem[0].toString() !== "0") {
// send non-dusty change to our address
var usableChange = changeAmountDivRem[0].multiply(config.dustThreshold);
console.log("Sending change of " + cnUtil.formatMoneySymbol(usableChange) + " to " + AccountService.getAddress());
dsts.push({
address: AccountService.getAddress(),
amount: usableChange
});
}
}
else
{
//add entire change for rct
console.log("Sending change of " + cnUtil.formatMoneySymbol(changeAmount)
+ " to " + AccountService.getAddress());
dsts.push({
address: AccountService.getAddress(),
amount: changeAmount
});
}
}
else if (using_outs_amount.compare(totalAmount) === 0 && rct)
{
//create random destination to keep 2 outputs always in case of 0 change
var fakeAddress = cnUtil.create_address(cnUtil.random_scalar()).public_addr;
console.log("Sending 0 XMR to a fake address to keep tx uniform (no change exists): " + fakeAddress);
dsts.push({
address: fakeAddress,
amount: 0
});
}
if (mixin > 0)
{
var amounts = [];
for (var l = 0; l < using_outs.length; l++)
{
amounts.push(using_outs[l].rct ? "0" : using_outs[l].amount.toString());
//amounts.push("0");
}
var request = {
amounts: amounts,
count: mixin + 1 // Add one to mixin so we can skip real output key if necessary
};
ApiCalls.get_random_outs(request.amounts, request.count)
.then(function(response) {
var data = response.data;
createTx(data.amount_outs);
}, function(data) {
deferred.reject('Failed to get unspent outs');
});
} else if (mixin < 0 || isNaN(mixin)) {
deferred.reject("Invalid mixin");
return;
} else { // mixin === 0
createTx();
}
// Create & serialize transaction
function createTx(mix_outs)
{
var signed;
try {
console.log('Destinations: ');
cnUtil.printDsts(dsts);
//need to get viewkey for encrypting here, because of splitting and sorting
if (pid_encrypt)
{
var realDestViewKey = cnUtil.decode_address(dsts[0].address).view;
}
var splittedDsts = cnUtil.decompose_tx_destinations(dsts, rct);
console.log('Decomposed destinations:');
cnUtil.printDsts(splittedDsts);
signed = cnUtil.create_transaction(
AccountService.getPublicKeys(),
AccountService.getSecretKeys(),
splittedDsts, using_outs,
mix_outs, mixin, neededFee,
payment_id, pid_encrypt,
realDestViewKey, 0, rct);
} catch (e) {
deferred.reject("Failed to create transaction: " + e);
return;
}
console.log("signed tx: ", JSON.stringify(signed));
//move some stuff here to normalize rct vs non
var raw_tx_and_hash = {};
if (signed.version === 1) {
raw_tx_and_hash.raw = cnUtil.serialize_tx(signed);
raw_tx_and_hash.hash = cnUtil.cn_fast_hash(raw_tx);
raw_tx_and_hash.prvkey = signed.prvkey;
} else {
raw_tx_and_hash = cnUtil.serialize_rct_tx_with_hash(signed);
}
console.log("raw_tx and hash:");
console.log(raw_tx_and_hash);
deferred.resolve(raw_tx_and_hash);
}
})();
return deferred.promise;
}
};
});
function parseOpenAliasRecord(record) {
var parsed = {};
if (record.slice(0, 4 + config.openAliasPrefix.length + 1) !== "oa1:" + config.openAliasPrefix + " ") {
throw "Invalid OpenAlias prefix";
}
function parse_param(name) {
var pos = record.indexOf(name + "=");
if (pos === -1) {
// Record does not contain param
return undefined;
}
pos += name.length + 1;
var pos2 = record.indexOf(";", pos);
return record.substr(pos, pos2 - pos);
}
parsed.address = parse_param('recipient_address');
parsed.name = parse_param('recipient_name');
parsed.description = parse_param('tx_description');
return parsed;
}
| 44.121602 | 170 | 0.484971 |
3dcdd7fc8cf15da71ce7dc889be5167b08c8a2ac | 890 | js | JavaScript | node_modules/@cucumber/gherkin-streams/dist/src/ParserMessageStream.js | MA87604/ClientMI | ea08185117a2a88b859e4d672aa721124feebc99 | [
"BSD-3-Clause"
] | null | null | null | node_modules/@cucumber/gherkin-streams/dist/src/ParserMessageStream.js | MA87604/ClientMI | ea08185117a2a88b859e4d672aa721124feebc99 | [
"BSD-3-Clause"
] | null | null | null | node_modules/@cucumber/gherkin-streams/dist/src/ParserMessageStream.js | MA87604/ClientMI | ea08185117a2a88b859e4d672aa721124feebc99 | [
"BSD-3-Clause"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const gherkin_1 = require("@cucumber/gherkin");
/**
* Stream that reads Source messages and writes GherkinDocument and Pickle messages.
*/
class ParserMessageStream extends stream_1.Transform {
constructor(options) {
super({ writableObjectMode: true, readableObjectMode: true });
this.options = options;
}
_transform(envelope, encoding, callback) {
if (envelope.source) {
const messageList = gherkin_1.generateMessages(envelope.source.data, envelope.source.uri, envelope.source.mediaType, this.options);
for (const message of messageList) {
this.push(message);
}
}
callback();
}
}
exports.default = ParserMessageStream;
//# sourceMappingURL=ParserMessageStream.js.map | 37.083333 | 143 | 0.678652 |
3da2d2061ade493c2a3ac4b6b7549951768e3aac | 667 | js | JavaScript | external/contributions/Google/sputnik_conformance_modified/09_Type_Conversion/9.2_ToBoolean/S9.2_A5_T4.js | domenic/test262 | 9b669da66c78bd583bc130a7ca3151258e4681a1 | [
"BSD-3-Clause"
] | 27 | 2015-06-07T18:10:47.000Z | 2021-11-11T03:53:18.000Z | external/contributions/Google/sputnik_conformance_modified/09_Type_Conversion/9.2_ToBoolean/S9.2_A5_T4.js | domenic/test262 | 9b669da66c78bd583bc130a7ca3151258e4681a1 | [
"BSD-3-Clause"
] | 8 | 2015-03-11T14:29:53.000Z | 2017-02-09T14:38:26.000Z | external/contributions/Google/sputnik_conformance_modified/09_Type_Conversion/9.2_ToBoolean/S9.2_A5_T4.js | domenic/test262 | 9b669da66c78bd583bc130a7ca3151258e4681a1 | [
"BSD-3-Clause"
] | 6 | 2015-02-18T20:38:35.000Z | 2021-04-21T00:21:23.000Z | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S9.2_A5_T4;
* @section: 9.2, 11.4.9;
* @assertion: Result of boolean conversion from nonempty string value (length is not zero) is true; from empty String (length is zero) is false;
* @description: Any nonempty string convert to Boolean by implicit transformation;
*/
// CHECK#1
if (!(" ") !== false) {
$ERROR('#1: !(" ") === false. Actual: ' + (!(" ")));
}
// CHECK#2
if (!("Nonempty String") !== false) {
$ERROR('#2: !("Nonempty String") === false. Actual: ' + (!("Nonempty String")));
}
| 33.35 | 146 | 0.613193 |
3dbbb867b41f22e3e6bda20b94904cb6ac0cd5b1 | 5,489 | js | JavaScript | web/web_mat/js/test.js | BenzPowder/e-office | e9289a8f4d15faf7d462d82da7422ed89bf0ac5e | [
"BSD-3-Clause",
"MIT"
] | 1 | 2020-02-16T11:47:05.000Z | 2020-02-16T11:47:05.000Z | web/web_mat/js/test.js | BenzPowder/e-office | e9289a8f4d15faf7d462d82da7422ed89bf0ac5e | [
"BSD-3-Clause",
"MIT"
] | 1 | 2021-03-09T09:26:36.000Z | 2021-03-09T09:26:36.000Z | web/web_mat/js/test.js | BenzPowder/e-office | e9289a8f4d15faf7d462d82da7422ed89bf0ac5e | [
"BSD-3-Clause",
"MIT"
] | null | null | null | loadScript(plugin_path + "chart.flot/jquery.flot.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.resize.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.time.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.fillbetween.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.orderBars.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.pie.min.js", function(){
loadScript(plugin_path + "chart.flot/jquery.flot.tooltip.min.js", function(){
if (jQuery("#flot-sales").length > 0) {
/* DEFAULTS FLOT COLORS */
var $color_border_color = "#eaeaea", /* light gray */
$color_second = "#6595b4"; /* blue */
var d = [
[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 4568], [1198450800000, 686], [1198537200000, 4122], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 544], [1199574000000, 500], [1199660400000, 476], [1199746800000, 462], [1199833200000, 500], [1199919600000, 700], [1200006000000, 750], [1200092400000, 600], [1200178800000, 500], [1200265200000, 900], [1200351600000, 930], [1200438000000, 1200], [1200524400000, 980], [1200610800000, 950], [1200697200000, 900], [1200783600000, 1000], [1200870000000, 1050], [1200956400000, 1150], [1201042800000, 1100], [1201129200000, 1200], [1201215600000, 1300], [1201302000000, 1700], [1201388400000, 1450], [1201474800000, 1500], [1201561200000, 1510], [1201647600000, 1510], [1201734000000, 1510], [1201820400000, 1700], [1201906800000, 1800], [1201993200000, 1900], [1202079600000, 2000], [1202166000000, 2100], [1202252400000, 2200], [1202338800000, 2300], [1202425200000, 2400], [1202511600000, 2550], [1202598000000, 2600], [1202684400000, 2500], [1202770800000, 2700], [1202857200000, 2750], [1202943600000, 2800], [1203030000000, 3245], [1203116400000, 3345], [1203202800000, 3000], [1203289200000, 3200], [1203375600000, 3300], [1203462000000, 3400], [1203548400000, 3600], [1203634800000, 3700], [1203721200000, 3800], [1203807600000, 4000], [1203894000000, 4500]];
for (var i = 0; i < d.length; ++i) {
d[i][0] += 60 * 60 * 1000;
}
var options = {
xaxis : {
mode : "time",
tickLength : 5
},
series : {
lines : {
show : true,
lineWidth : 1,
fill : true,
fillColor : {
colors : [{
opacity : 0.1
}, {
opacity : 0.15
}]
}
},
//points: { show: true },
shadowSize : 0
},
selection : {
mode : "x"
},
grid : {
hoverable : true,
clickable : true,
tickColor : $color_border_color,
borderWidth : 0,
borderColor : $color_border_color,
},
tooltip : true,
tooltipOpts : {
content : "Sales: %x <span class='block'>$%y</span>",
dateFormat : "%y-%0m-%0d",
defaultTheme : false
},
colors : [$color_second],
};
var plot = jQuery.plot(jQuery("#flot-sales"), [d], options);
}
});
});
});
});
});
});
}); | 68.6125 | 1,988 | 0.429769 |
c1b032359883d0e62ea3ec51aaea37a8ce796159 | 40,375 | js | JavaScript | metaversefile-api.js | koreex/app | 4d498cb8c43dd5c1e0927052ed71ca89f3c99713 | [
"MIT"
] | null | null | null | metaversefile-api.js | koreex/app | 4d498cb8c43dd5c1e0927052ed71ca89f3c99713 | [
"MIT"
] | null | null | null | metaversefile-api.js | koreex/app | 4d498cb8c43dd5c1e0927052ed71ca89f3c99713 | [
"MIT"
] | null | null | null | /*
metaversefile uses plugins to load files from the metaverse and load them as apps.
it is an interface between raw data and the engine.
metaversfile can load many file types, including javascript.
*/
import * as THREE from 'three';
import {Text} from 'troika-three-text';
import React from 'react';
import * as ReactThreeFiber from '@react-three/fiber';
import metaversefile from 'metaversefile';
import {getRenderer, scene, sceneHighPriority, sceneLowPriority, rootScene, camera} from './renderer.js';
import cameraManager from './camera-manager.js';
import physicsManager from './physics-manager.js';
import Avatar from './avatars/avatars.js';
import {world} from './world.js';
import ERC721 from './erc721-abi.json';
import ERC1155 from './erc1155-abi.json';
import {web3} from './blockchain.js';
import {moduleUrls, modules} from './metaverse-modules.js';
import {componentTemplates} from './metaverse-components.js';
import postProcessing from './post-processing.js';
import {makeId, getRandomString, getPlayerPrefix, memoize} from './util.js';
import JSON6 from 'json-6';
import * as materials from './materials.js';
import * as geometries from './geometries.js';
import * as avatarCruncher from './avatar-cruncher.js';
import * as avatarSpriter from './avatar-spriter.js';
import {chatManager} from './chat-manager.js';
import loreAI from './ai/lore/lore-ai.js';
import npcManager from './npc-manager.js';
import universe from './universe.js';
import {PathFinder} from './npc-utils.js';
import {localPlayer, remotePlayers} from './players.js';
import loaders from './loaders.js';
import * as voices from './voices.js';
import * as procgen from './procgen/procgen.js';
import {getHeight} from './avatars/util.mjs';
import performanceTracker from './performance-tracker.js';
import renderSettingsManager from './rendersettings-manager.js';
import questManager from './quest-manager.js';
import {murmurhash3} from './procgen/murmurhash3.js';
import debug from './debug.js';
import * as sceneCruncher from './scene-cruncher.js';
import * as scenePreviewer from './scene-previewer.js';
import * as sounds from './sounds.js';
import hpManager from './hp-manager.js';
// const localVector = new THREE.Vector3();
// const localVector2 = new THREE.Vector3();
const localVector2D = new THREE.Vector2();
// const localQuaternion = new THREE.Quaternion();
// const localMatrix = new THREE.Matrix4();
// const localMatrix2 = new THREE.Matrix4();
class App extends THREE.Object3D {
constructor() {
super();
this.isApp = true;
this.components = [];
this.modules = [];
this.modulesHash = 0;
// cleanup tracking
this.physicsObjects = [];
this.hitTracker = null;
this.appType = 'none';
this.hasRenderSettings = false;
this.lastMatrix = new THREE.Matrix4();
const startframe = () => {
performanceTracker.decorateApp(this);
};
performanceTracker.addEventListener('startframe', startframe);
this.addEventListener('destroy', () => {
performanceTracker.removeEventListener('startframe', startframe);
});
}
getComponent(key) {
const component = this.components.find(component => component.key === key);
return component ? component.value : null;
}
#setComponentInternal(key, value) {
let component = this.components.find(component => component.key === key);
if (!component) {
component = {key, value};
this.components.push(component);
}
component.key = key;
component.value = value;
this.dispatchEvent({
type: 'componentupdate',
key,
value,
});
}
setComponent(key, value = true) {
this.#setComponentInternal(key, value);
this.dispatchEvent({
type: 'componentsupdate',
keys: [key],
});
}
setComponents(o) {
const keys = Object.keys(o);
for (const k of keys) {
const v = o[k];
this.#setComponentInternal(k, v);
}
this.dispatchEvent({
type: 'componentsupdate',
keys,
});
}
hasComponent(key) {
return this.components.some(component => component.key === key);
}
removeComponent(key) {
const index = this.components.findIndex(component => component.type === key);
if (index !== -1) {
this.components.splice(index, 1);
this.dispatchEvent({
type: 'componentupdate',
key,
value: null,
});
}
}
get contentId() {
return this.getComponent('contentId') + '';
}
set contentId(contentId) {
this.setComponent('contentId', contentId + '');
}
get instanceId() {
return this.getComponent('instanceId') + '';
}
set instanceId(instanceId) {
this.setComponent('instanceId', instanceId + '');
}
get paused() {
return this.getComponent('paused') === true;
}
set paused(paused) {
this.setComponent('paused', !!paused);
}
addModule(m) {
throw new Error('method not bound');
}
updateModulesHash() {
this.modulesHash = murmurhash3(this.modules.map(m => m.contentId).join(','));
}
getPhysicsObjects() {
return this.physicsObjects;
}
hit(damage, opts) {
this.hitTracker && this.hitTracker.hit(damage, opts);
}
getRenderSettings() {
if (this.hasRenderSettings) {
return renderSettingsManager.findRenderSettings(this);
} else {
return null;
}
}
activate() {
this.dispatchEvent({
type: 'activate',
});
}
wear() {
localPlayer.wear(this);
}
unwear() {
localPlayer.unwear(this);
}
use() {
this.dispatchEvent({
type: 'use',
use: true,
});
}
destroy() {
this.dispatchEvent({
type: 'destroy',
});
}
}
const defaultModules = {
moduleUrls,
modules,
};
const loreAIScene = loreAI.createScene(localPlayer);
const _bindAppManagerToLoreAIScene = (appManager, loreAIScene) => {
const bindings = new WeakMap();
appManager.addEventListener('appadd', e => {
const app = e.data;
const object = loreAIScene.addObject({
name: app.name,
description: app.description,
});
bindings.set(app, object);
});
appManager.addEventListener('appremove', e => {
const app = e.data;
const object = bindings.get(app);
loreAIScene.removeObject(object);
bindings.delete(app);
});
};
_bindAppManagerToLoreAIScene(world.appManager, loreAIScene);
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
// logErrorToMyService(error, errorInfo);
console.warn(error);
}
render() {
if (this.state.hasError) {
return null;
}
return this.props.children;
}
}
function createPointerEvents(store) {
// const { handlePointer } = createEvents(store)
const handlePointer = key => e => {
// const handlers = eventObject.__r3f.handlers;
// console.log('handle pointer', key, e);
};
const names = {
onClick: 'click',
onContextMenu: 'contextmenu',
onDoubleClick: 'dblclick',
onWheel: 'wheel',
onPointerDown: 'pointerdown',
onPointerUp: 'pointerup',
onPointerLeave: 'pointerleave',
onPointerMove: 'pointermove',
onPointerCancel: 'pointercancel',
onLostPointerCapture: 'lostpointercapture',
};
return {
connected: false,
handlers: (Object.keys(names).reduce(
(acc, key) => ({ ...acc, [key]: handlePointer(key) }),
{},
)),
connect: (target) => {
const { set, events } = store.getState()
events.disconnect?.()
set((state) => ({ events: { ...state.events, connected: target } }))
Object.entries(events?.handlers ?? []).forEach(([name, event]) =>
target.addEventListener(names[name], event, { passive: true }),
)
},
disconnect: () => {
const { set, events } = store.getState()
if (events.connected) {
Object.entries(events.handlers ?? []).forEach(([name, event]) => {
if (events && events.connected instanceof HTMLElement) {
events.connected.removeEventListener(names[name], event)
}
})
set((state) => ({ events: { ...state.events, connected: false } }))
}
},
}
}
const _loadImageTexture = src => {
const img = new Image();
img.onload = () => {
texture.needsUpdate = true;
};
img.onerror = err => {
console.warn(err);
};
img.crossOrigin = 'Anonymous';
img.src = src;
const texture = new THREE.Texture(img);
texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter;
// texture.anisotropy = 16;
return texture;
};
const _threeTone = memoize(() => {
return _loadImageTexture('/textures/threeTone.jpg');
});
const _fiveTone = memoize(() => {
return _loadImageTexture('/textures/fiveTone.jpg');
});
const _twentyTone = memoize(() => {
return _loadImageTexture('/textures/twentyTone.png');
});
const gradientMaps = {
get threeTone() {
return _threeTone();
},
get fiveTone() {
return _fiveTone();
},
get twentyTone() {
return _twentyTone();
},
};
const abis = {
ERC721,
ERC1155,
};
/* debug.addEventListener('enabledchange', e => {
document.getElementById('statsBox').style.display = e.data.enabled ? null : 'none';
}); */
let currentAppRender = null;
let iframeContainer = null;
let recursion = 0;
let wasDecapitated = false;
// const apps = [];
const mirrors = [];
metaversefile.setApi({
// apps,
async import(s) {
if (/^(?:ipfs:\/\/|https?:\/\/|weba:\/\/|data:)/.test(s)) {
const prefix = location.protocol + '//' + location.host + '/@proxy/';
if (s.startsWith(prefix)) {
s = s.slice(prefix.length);
}
s = `/@proxy/${s}`;
}
// console.log('do import', s);
try {
const m = await import(s);
return m;
} catch(err) {
console.warn('error loading', JSON.stringify(s), err.stack);
return null;
}
},
/* async load(u) {
const m = await metaversefile.import(u);
const app = metaversefile.createApp();
await metaversefile.addModule(app, m);
return app;
}, */
useApp() {
const app = currentAppRender;
if (app) {
return app;
} else {
throw new Error('useApp cannot be called outside of render()');
}
},
useRenderer() {
return getRenderer();
},
useRenderSettings() {
return renderSettingsManager;
},
useScene() {
return scene;
},
useSound() {
return sounds;
},
useCamera() {
return camera;
},
/* usePostOrthographicScene() {
return postSceneOrthographic;
},
usePostPerspectiveScene() {
return postScenePerspective;
}, */
getMirrors() {
return mirrors;
},
registerMirror(mirror) {
mirrors.push(mirror);
},
unregisterMirror(mirror) {
const index = mirrors.indexOf(mirror);
if (index !== -1) {
mirrors.splice(index, 1);
}
},
useWorld() {
return {
appManager: world.appManager,
getApps() {
return world.appManager.apps;
},
};
},
useChatManager() {
return chatManager;
},
useQuests() {
return questManager;
},
useLoreAI() {
return loreAI;
},
useLoreAIScene() {
return loreAIScene;
},
useVoices() {
return voices;
},
useAvatarCruncher() {
return avatarCruncher;
},
useAvatarSpriter() {
return avatarSpriter;
},
useSceneCruncher() {
return sceneCruncher;
},
useScenePreviewer() {
return scenePreviewer;
},
usePostProcessing() {
return postProcessing;
},
/* createAvatar(o, options) {
return new Avatar(o, options);
}, */
useAvatarAnimations() {
return Avatar.getAnimations();
},
useFrame(fn) {
const app = currentAppRender;
if (app) {
const frame = e => {
if (!app.paused) {
performanceTracker.startCpuObject(app.modulesHash, app.name);
fn(e.data);
performanceTracker.endCpuObject();
}
};
world.appManager.addEventListener('frame', frame);
const destroy = () => {
cleanup();
};
app.addEventListener('destroy', destroy);
const cleanup = () => {
world.appManager.removeEventListener('frame', frame);
app.removeEventListener('destroy', destroy);
};
return {
cleanup,
};
} else {
throw new Error('useFrame cannot be called outside of render()');
}
},
clearFrame(frame) {
frame.cleanup();
},
useBeforeRender() {
recursion++;
if (recursion === 1) {
// scene.directionalLight.castShadow = false;
if (localPlayer.avatar) {
wasDecapitated = localPlayer.avatar.decapitated;
localPlayer.avatar.undecapitate();
}
}
},
useAfterRender() {
recursion--;
if (recursion === 0) {
// console.log('was decap', wasDecapitated);
if (localPlayer.avatar && wasDecapitated) {
localPlayer.avatar.decapitate();
localPlayer.avatar.skeleton.update();
}
}
},
useCleanup(fn) {
const app = currentAppRender;
if (app) {
app.addEventListener('destroy', () => {
fn();
});
} else {
throw new Error('useCleanup cannot be called outside of render()');
}
},
useLocalPlayer() {
return localPlayer;
},
useRemotePlayer(playerId) {
let player = remotePlayers.get(playerId);
/* if (!player) {
player = new RemotePlayer();
} */
return player;
},
useRemotePlayers() {
return Array.from(remotePlayers.values());
},
useNpcManager() {
return npcManager;
},
usePathFinder() {
return PathFinder;
},
useLoaders() {
return loaders;
},
usePhysics() {
const app = currentAppRender;
if (app) {
const physics = {};
for (const k in physicsManager) {
physics[k] = physicsManager[k];
}
/* const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
const localQuaternion = new THREE.Quaternion();
const localMatrix = new THREE.Matrix4(); */
// const localMatrix2 = new THREE.Matrix4();
physics.addBoxGeometry = (addBoxGeometry => function(position, quaternion, size, dynamic) {
/* const basePosition = position;
const baseQuaternion = quaternion;
const baseScale = size;
app.updateMatrixWorld();
localMatrix
.compose(position, quaternion, size)
.premultiply(app.matrixWorld)
.decompose(localVector, localQuaternion, localVector2);
position = localVector;
quaternion = localQuaternion;
size = localVector2; */
const physicsObject = addBoxGeometry.call(this, position, quaternion, size, dynamic);
// physicsObject.position.copy(app.position);
// physicsObject.quaternion.copy(app.quaternion);
// physicsObject.scale.copy(app.scale);
// const {physicsMesh} = physicsObject;
// physicsMesh.position.copy(position);
// physicsMesh.quaternion.copy(quaternion);
// physicsMesh.scale.copy(size);
// app.add(physicsObject);
// physicsObject.updateMatrixWorld();
app.physicsObjects.push(physicsObject);
return physicsObject;
})(physics.addBoxGeometry);
physics.addCapsuleGeometry = (addCapsuleGeometry => function(position, quaternion, radius, halfHeight, physicsMaterial, dynamic, flags) {
// const basePosition = position;
// const baseQuaternion = quaternion;
// const baseScale = new THREE.Vector3(radius, halfHeight*2, radius)
// app.updateMatrixWorld();
// localMatrix
// .compose(position, quaternion, new THREE.Vector3(radius, halfHeight*2, radius))
// .premultiply(app.matrixWorld)
// .decompose(localVector, localQuaternion, localVector2);
// position = localVector;
// quaternion = localQuaternion;
//size = localVector2;
const physicsObject = addCapsuleGeometry.call(this, position, quaternion, radius, halfHeight, physicsMaterial, dynamic, flags);
// physicsObject.position.copy(app.position);
// physicsObject.quaternion.copy(app.quaternion);
// physicsObject.scale.copy(app.scale);
// physicsObject.updateMatrixWorld();
// const {physicsMesh} = physicsObject;
// physicsMesh.position.copy(basePosition);
// physicsMesh.quaternion.copy(baseQuaternion);
// physicsMesh.scale.copy(baseScale);
// app.add(physicsObject);
// physicsObject.updateMatrixWorld();
// const localPlayer = metaversefile.useLocalPlayer();
/*if(localPlayer.avatar) {
if(localPlayer.avatar.height) {
console.log(localPlayer.avatar.height);
}
}*/
app.physicsObjects.push(physicsObject);
// physicsManager.pushUpdate(app, physicsObject);
//physicsManager.setTransform(physicsObject);
return physicsObject;
})(physics.addCapsuleGeometry);
/* physics.addSphereGeometry = (addSphereGeometry => function(position, quaternion, radius, physicsMaterial, ccdEnabled) {
const basePosition = position;
const baseQuaternion = quaternion;
const baseScale = new THREE.Vector3(radius, radius, radius);
// app.updateMatrixWorld();
// localMatrix
// .compose(position, quaternion, new THREE.Vector3(1, 1, 1))
// .premultiply(app.matrixWorld)
// .decompose(localVector, localQuaternion, localVector2);
// position = localVector;
// quaternion = localQuaternion;
//size = localVector2;
const physicsObject = addSphereGeometry.call(this, position, quaternion, radius, physicsMaterial, ccdEnabled);
//physicsObject.position.copy(app.position);
//physicsObject.quaternion.copy(app.quaternion);
//physicsObject.scale.copy(app.scale);
const {physicsMesh} = physicsObject;
physicsMesh.position.copy(basePosition);
physicsMesh.quaternion.copy(baseQuaternion);
//physicsMesh.scale.copy(baseScale);
// app.add(physicsObject);
physicsObject.updateMatrixWorld();
app.physicsObjects.push(physicsObject);
// physicsManager.pushUpdate(app, physicsObject);
return physicsObject;
})(physics.addSphereGeometry); */
physics.addGeometry = (addGeometry => function(mesh) {
/* const oldParent = mesh.parent;
const parentMesh = new THREE.Object3D();
parentMesh.position.copy(app.position);
parentMesh.quaternion.copy(app.quaternion);
parentMesh.scale.copy(app.scale);
parentMesh.add(mesh);
parentMesh.updateMatrixWorld(); */
const physicsObject = addGeometry.call(this, mesh);
/* physicsObject.position.copy(app.position);
physicsObject.quaternion.copy(app.quaternion);
physicsObject.scale.copy(app.scale);
physicsObject.updateMatrixWorld(); */
// window.physicsObject = physicsObject;
/* if (oldParent) {
oldParent.add(mesh);
mesh.updateMatrixWorld();
} */
// app.add(physicsObject);
app.physicsObjects.push(physicsObject);
return physicsObject;
})(physics.addGeometry);
physics.addCookedGeometry = (addCookedGeometry => function(buffer, position, quaternion, scale) {
const physicsObject = addCookedGeometry.apply(this, arguments);
// app.add(physicsObject);
app.physicsObjects.push(physicsObject);
return physicsObject;
})(physics.addCookedGeometry);
physics.addConvexGeometry = (addConvexGeometry => function(mesh) {
const physicsObject = addConvexGeometry.apply(this, arguments);
// app.add(physicsObject);
app.physicsObjects.push(physicsObject);
return physicsObject;
})(physics.addConvexGeometry);
physics.addCookedConvexGeometry = (addCookedConvexGeometry => function(buffer, position, quaternion, scale) {
const physicsObject = addCookedConvexGeometry.apply(this, arguments);
// app.add(physicsObject);
app.physicsObjects.push(physicsObject);
return physicsObject;
})(physics.addCookedConvexGeometry);
/* physics.enablePhysicsObject = (enablePhysicsObject => function(physicsObject) {
enablePhysicsObject.call(this, physicsObject);
})(physics.enablePhysicsObject);
physics.disablePhysicsObject = (disablePhysicsObject => function(physicsObject) {
disablePhysicsObject.call(this, physicsObject);
})(physics.disablePhysicsObject);
physics.enableGeometryQueries = (enableGeometryQueries => function(physicsObject) {
enableGeometryQueries.call(this, physicsObject);
})(physics.enableGeometryQueries);
physics.disableGeometryQueries = (disableGeometryQueries => function(physicsObject) {
disableGeometryQueries.call(this, physicsObject);
})(physics.disableGeometryQueries); */
/* physics.setTransform = (setTransform => function(physicsObject) {
setTransform.call(this, physicsObject);
})(physics.setTransform); */
/* physics.getPhysicsTransform = (getPhysicsTransform => function(physicsId) {
const transform = getPhysicsTransform.apply(this, arguments);
const {position, quaternion} = transform;
app.updateMatrixWorld();
localMatrix
.compose(position, quaternion, localVector2.set(1, 1, 1))
.premultiply(localMatrix2.copy(app.matrixWorld).invert())
.decompose(position, quaternion, localVector2);
return transform;
})(physics.getPhysicsTransform);
physics.setPhysicsTransform = (setPhysicsTransform => function(physicsId, position, quaternion, scale) {
app.updateMatrixWorld();
localMatrix
.compose(position, quaternion, scale)
.premultiply(app.matrixWorld)
.decompose(localVector, localQuaternion, localVector2);
position = localVector;
quaternion = localQuaternion;
return setPhysicsTransform.call(this, physicsId, position, quaternion, scale);
})(physics.setPhysicsTransform); */
physics.removeGeometry = (removeGeometry => function(physicsObject) {
removeGeometry.apply(this, arguments);
const index = app.physicsObjects.indexOf(physicsObject);
if (index !== -1) {
app.remove(physicsObject);
app.physicsObjects.splice(index);
}
})(physics.removeGeometry);
return physics;
} else {
throw new Error('usePhysics cannot be called outside of render()');
}
},
useHpManager() {
return hpManager;
},
useProcGen() {
return procgen;
},
useCameraManager() {
return cameraManager;
},
useParticleSystem() {
return world.particleSystem;
},
useDefaultModules() {
return defaultModules;
},
useWeb3() {
return web3.mainnet;
},
useAbis() {
return abis;
},
/* useUi() {
return ui;
}, */
useActivate(fn) {
const app = currentAppRender;
if (app) {
app.addEventListener('activate', e => {
fn(e);
});
app.addEventListener('destroy', () => {
app.removeEventListener('activate', fn);
});
} else {
throw new Error('useActivate cannot be called outside of render()');
}
},
useWear(fn) {
const app = currentAppRender;
if (app) {
app.addEventListener('wearupdate', e => {
fn(e);
});
app.addEventListener('destroy', () => {
app.removeEventListener('wearupdate', fn);
});
} else {
throw new Error('useWear cannot be called outside of render()');
}
},
useUse(fn) {
const app = currentAppRender;
if (app) {
app.addEventListener('use', e => {
fn(e);
});
app.addEventListener('destroy', () => {
app.removeEventListener('use', fn);
});
} else {
throw new Error('useUse cannot be called outside of render()');
}
},
useResize(fn) {
const app = currentAppRender;
if (app) {
window.addEventListener('resize', e => {
fn(e);
});
app.addEventListener('destroy', () => {
window.removeEventListener('resize', fn);
});
} else {
throw new Error('useResize cannot be called outside of render()');
}
},
getNextInstanceId() {
return getRandomString();
},
createAppInternal({
start_url = '',
module = null,
components = [],
position = null,
quaternion = null,
scale = null,
parent = null,
in_front = false,
} = {}, {onWaitPromise = null} = {}) {
const app = new App();
// transform
const _updateTransform = () => {
let matrixNeedsUpdate = false;
if (Array.isArray(position)) {
app.position.fromArray(position);
matrixNeedsUpdate = true;
} else if (position?.isVector3) {
app.position.copy(position);
matrixNeedsUpdate = true;
}
if (Array.isArray(quaternion)) {
app.quaternion.fromArray(quaternion);
matrixNeedsUpdate = true;
} else if (quaternion?.isQuaternion) {
app.quaternion.copy(quaternion);
matrixNeedsUpdate = true;
}
if (Array.isArray(scale)) {
app.scale.fromArray(scale);
matrixNeedsUpdate = true;
} else if (scale?.isVector3) {
app.scale.copy(scale);
matrixNeedsUpdate = true;
}
if (in_front) {
app.position.copy(localPlayer.position).add(new THREE.Vector3(0, 0, -1).applyQuaternion(localPlayer.quaternion));
app.quaternion.copy(localPlayer.quaternion);
app.scale.setScalar(1);
matrixNeedsUpdate = true;
}
if (parent) {
parent.add(app);
matrixNeedsUpdate = true;
}
if (matrixNeedsUpdate) {
app.updateMatrixWorld();
app.lastMatrix.copy(app.matrixWorld);
}
};
_updateTransform();
// components
const _updateComponents = () => {
if (Array.isArray(components)) {
for (const {key, value} of components) {
app.setComponent(key, value);
}
} else if (typeof components === 'object' && components !== null) {
for (const key in components) {
const value = components[key];
app.setComponent(key, value);
}
}
};
_updateComponents();
// load
if (start_url || module) {
const p = (async () => {
let m;
if (start_url) {
m = await metaversefile.import(start_url);
} else {
m = module;
}
await metaversefile.addModule(app, m);
})();
if (onWaitPromise) {
onWaitPromise(p);
}
}
return app;
},
createApp(opts) {
return metaversefile.createAppInternal(opts);
},
async createAppAsync(opts) {
let p = null;
const app = metaversefile.createAppInternal(opts, {
onWaitPromise(newP) {
p = newP;
},
});
if (p !== null) {
await p;
}
return app;
},
createModule: (() => {
const dataUrlPrefix = `data:application/javascript;charset=utf-8,`;
const jsPrefix = `\
import * as THREE from 'three';
import metaversefile from 'metaversefile';
const {Vector3, Quaternion, Euler, Matrix4, Box3, Object3D, Texture} = THREE;
const {apps, createApp, createModule, addApp, removeApp, useFrame, useLocalPlayer, getAppByName, getAppsByName, getAppsByType, getAppsByTypes, getAppsByComponent} = metaversefile;
export default () => {
`;
const jsSuffix = '\n};';
return s => {
const result = dataUrlPrefix + encodeURIComponent(jsPrefix + s.replace(/\%/g, '%25') + jsSuffix);
console.log('got', {dataUrlPrefix, jsPrefix, s, jsSuffix, result});
return result;
};
})(),
addApp(app) {
return world.appManager.addApp.apply(world.appManager, arguments);
},
removeApp() {
return world.appManager.removeApp.apply(world.appManager, arguments);
},
addTrackedApp() {
return world.appManager.addTrackedApp.apply(world.appManager, arguments);
},
removeTrackedApp(app) {
return world.appManager.removeTrackedApp.apply(world.appManager, arguments);
},
getAppByInstanceId(instanceId) {
let result = world.appManager.getAppByInstanceId(instanceId) ||
localPlayer.appManager.getAppByInstanceId(instanceId);
if (result) {
return result;
} else {
const remotePlayers = metaversefile.useRemotePlayers();
for (const remotePlayer of remotePlayers) {
const remoteApp = remotePlayer.appManager.getAppByInstanceId(instanceId);
if (remoteApp) {
return remoteApp;
}
}
return null;
}
},
getAppByPhysicsId(physicsId) {
let result = world.appManager.getAppByPhysicsId(physicsId) ||
localPlayer.appManager.getAppByPhysicsId(physicsId);
if (result) {
return result;
} else {
const remotePlayers = metaversefile.useRemotePlayers();
for (const remotePlayer of remotePlayers) {
const remoteApp = remotePlayer.appManager.getAppByPhysicsId(physicsId);
if (remoteApp) {
return remoteApp;
}
}
return null;
}
},
getPhysicsObjectByPhysicsId(physicsId) {
let result = world.appManager.getPhysicsObjectByPhysicsId(physicsId) ||
localPlayer.appManager.getPhysicsObjectByPhysicsId(physicsId);
if (result) {
return result;
} else {
const remotePlayers = metaversefile.useRemotePlayers();
for (const remotePlayer of remotePlayers) {
const remotePhysicsObject = remotePlayer.appManager.getPhysicsObjectByPhysicsId(physicsId);
if (remotePhysicsObject) {
return remotePhysicsObject;
}
}
return null;
}
},
getPairByPhysicsId(physicsId) {
let result = world.appManager.getPairByPhysicsId(physicsId) ||
localPlayer.appManager.getPairByPhysicsId(physicsId);
if (result) {
return result;
} else {
const remotePlayers = metaversefile.useRemotePlayers();
for (const remotePlayer of remotePlayers) {
const remotePair = remotePlayer.appManager.getPairByPhysicsId(physicsId);
if (remotePair) {
return remotePair;
}
}
return null;
}
},
getAvatarHeight(obj) {
return getHeight(obj);
},
useInternals() {
if (!iframeContainer) {
iframeContainer = document.getElementById('iframe-container');
iframeContainer.getFov = () => camera.projectionMatrix.elements[ 5 ] * (window.innerHeight / 2);
iframeContainer.updateSize = function updateSize() {
const fov = iframeContainer.getFov();
iframeContainer.style.cssText = `
position: fixed;
left: 0;
top: 0;
width: ${window.innerWidth}px;
height: ${window.innerHeight}px;
perspective: ${fov}px;
pointer-events: none;
user-select: none;
`;
};
iframeContainer.updateSize();
}
const renderer = getRenderer();
return {
renderer,
scene,
rootScene,
// postSceneOrthographic,
// postScenePerspective,
camera,
sceneHighPriority,
sceneLowPriority,
iframeContainer,
};
},
/* useRigManagerInternal() {
return rigManager;
}, */
/* useAvatar() {
return Avatar;
}, */
useText() {
return Text;
},
useGeometries() {
return geometries;
},
useMaterials() {
return materials;
},
useJSON6Internal() {
return JSON6;
},
useGradientMapsInternal() {
return gradientMaps;
},
isSceneLoaded() {
return universe.isSceneLoaded();
},
async waitForSceneLoaded() {
await universe.waitForSceneLoaded();
},
useDebug() {
return debug;
},
async addModule(app, m) {
// wait to make sure module initialization happens in a clean tick loop,
// even when adding a module from inside of another module's initialization
await Promise.resolve();
app.name = m.name ?? (m.contentId ? m.contentId.match(/([^\/\.]*)$/)[1] : '');
app.description = m.description ?? '';
app.contentId = m.contentId ?? '';
if (Array.isArray(m.components)) {
for (const {key, value} of m.components) {
if (!app.hasComponent(key)) {
app.setComponent(key, value);
}
}
}
app.modules.push(m);
app.updateModulesHash();
let renderSpec = null;
let waitUntilPromise = null;
const _initModule = () => {
currentAppRender = app;
try {
const fn = m.default;
if (typeof fn === 'function') {
renderSpec = fn({
waitUntil(p) {
waitUntilPromise = p;
},
});
} else {
console.warn('module default export is not a function', m);
return null;
}
} catch(err) {
console.warn(err);
return null;
} finally {
currentAppRender = null;
}
};
_initModule();
if (waitUntilPromise) {
await waitUntilPromise;
}
const _bindDefaultComponents = app => {
// console.log('bind default components', app); // XXX
currentAppRender = app;
// component handlers
const componentHandlers = {};
for (const {key, value} of app.components) {
const componentHandlerTemplate = componentTemplates[key];
if (componentHandlerTemplate) {
componentHandlers[key] = componentHandlerTemplate(app, value);
}
}
app.addEventListener('componentupdate', e => {
const {key, value} = e;
currentAppRender = app;
const componentHandler = componentHandlers[key];
if (!componentHandler && value !== undefined) {
const componentHandlerTemplate = componentTemplates[key];
if (componentHandlerTemplate) {
componentHandlers[key] = componentHandlerTemplate(app, value);
}
} else if (componentHandler && value === undefined) {
componentHandler.remove();
delete componentHandlers[key];
}
currentAppRender = null;
});
currentAppRender = null;
};
if (renderSpec instanceof THREE.Object3D) {
const o = renderSpec;
if (o !== app) {
app.add(o);
o.updateMatrixWorld();
}
app.addEventListener('destroy', () => {
if (o !== app) {
app.remove(o);
}
});
_bindDefaultComponents(app);
return app;
} else if (React.isValidElement(renderSpec)) {
const o = new THREE.Object3D();
// o.contentId = contentId;
// o.getPhysicsIds = () => app.physicsIds;
o.destroy = () => {
app.destroy();
(async () => {
const roots = ReactThreeFiber._roots;
const root = roots.get(rootDiv);
const fiber = root?.fiber
if (fiber) {
const state = root?.store.getState()
if (state) state.internal.active = false
await new Promise((accept, reject) => {
ReactThreeFiber.reconciler.updateContainer(null, fiber, null, () => {
if (state) {
// setTimeout(() => {
state.events.disconnect?.()
// state.gl?.renderLists?.dispose?.()
// state.gl?.forceContextLoss?.()
ReactThreeFiber.dispose(state)
roots.delete(canvas)
// if (callback) callback(canvas)
// }, 500)
}
accept();
});
});
}
})();
};
app.add(o);
const renderer = getRenderer();
const sizeVector = renderer.getSize(localVector2D);
const rootDiv = document.createElement('div');
let rtfScene = null;
world.appManager.addEventListener('frame', e => {
const renderer2 = Object.create(renderer);
renderer2.render = () => {
// nothing
// console.log('elide render');
};
renderer2.setSize = () => {
// nothing
};
renderer2.setPixelRatio = () => {
// nothing
};
ReactThreeFiber.render(
React.createElement(ErrorBoundary, {}, [
React.createElement(fn, {
// app: appContextObject,
key: 0,
}),
]),
rootDiv,
{
gl: renderer2,
camera,
size: {
width: sizeVector.x,
height: sizeVector.y,
},
events: createPointerEvents,
onCreated: state => {
// state = newState;
// scene.add(state.scene);
console.log('got state', state);
const {scene: newRtfScene} = state;
if (newRtfScene !== rtfScene) {
if (rtfScene) {
o.remove(rtfScene);
rtfScene = null;
}
rtfScene = newRtfScene;
o.add(rtfScene);
}
},
frameloop: 'demand',
}
);
});
app.addEventListener('destroy', async () => {
const roots = ReactThreeFiber._roots;
const root = roots.get(rootDiv);
const fiber = root?.fiber
if (fiber) {
const state = root?.store.getState()
if (state) state.internal.active = false
await new Promise((accept, reject) => {
ReactThreeFiber.reconciler.updateContainer(null, fiber, null, () => {
if (state) {
// setTimeout(() => {
state.events.disconnect?.()
// state.gl?.renderLists?.dispose?.()
// state.gl?.forceContextLoss?.()
ReactThreeFiber.dispose(state)
roots.delete(canvas)
// if (callback) callback(canvas)
// }, 500)
}
accept();
});
});
}
});
_bindDefaultComponents(app);
return app;
} else if (renderSpec === false || renderSpec === null || renderSpec === undefined) {
app.destroy();
return null;
} else if (renderSpec === true) {
// console.log('background app', app);
return null;
} else {
app.destroy();
console.warn('unknown renderSpec:', renderSpec);
throw new Error('unknown renderSpec');
}
},
});
App.prototype.addModule = function(m) {
return metaversefile.addModule(this, m);
};
export default metaversefile;
| 30.844156 | 180 | 0.585238 |
c1b0481dc679dd5847ab57b88c12567fa56a41b9 | 606 | js | JavaScript | services/analysis.js | edevars/esFakeBackend | 8e4aebfc8dcfdde8d5d62646e84260db2fa4a5b9 | [
"MIT"
] | null | null | null | services/analysis.js | edevars/esFakeBackend | 8e4aebfc8dcfdde8d5d62646e84260db2fa4a5b9 | [
"MIT"
] | null | null | null | services/analysis.js | edevars/esFakeBackend | 8e4aebfc8dcfdde8d5d62646e84260db2fa4a5b9 | [
"MIT"
] | null | null | null | const { sequelize } = require("../lib/database/db");
class AnalysisService {
constructor() {
this.table = sequelize.models.analysis;
}
async createAnalysis(analysis) {
try {
const newAnalysis = await this.table.create(analysis);
return newAnalysis;
} catch (error) {
console.error(error);
}
}
async getAnalysis({ id }) {
try {
const newApiKey = await this.table.findOne({
where: {
id,
},
});
return newApiKey;
} catch (error) {
console.error(error);
}
}
}
module.exports = { AnalysisService };
| 18.9375 | 60 | 0.574257 |
c1b057a44014336db39d33623b0f56b27be4f55c | 284 | js | JavaScript | Section 8/code/8.3/todo/routes/error.js | PacktPublishing/Build-a-Network-Application-with-Node-v- | 5d2923622a6079d447c998257c8e720fb56a4613 | [
"MIT"
] | 1 | 2021-10-01T23:00:49.000Z | 2021-10-01T23:00:49.000Z | Section 8/code/8.3/todo/routes/error.js | PacktPublishing/Build-a-Network-Application-with-Node-v- | 5d2923622a6079d447c998257c8e720fb56a4613 | [
"MIT"
] | null | null | null | Section 8/code/8.3/todo/routes/error.js | PacktPublishing/Build-a-Network-Application-with-Node-v- | 5d2923622a6079d447c998257c8e720fb56a4613 | [
"MIT"
] | 2 | 2019-12-25T21:13:53.000Z | 2020-09-20T15:51:40.000Z |
// error.js
//
// Packt Publishing - Build a Network Application with Node
// GET error route
exports.report = function(req, res) {
var msg = res.app.settings.errorMessage || "Internal server error.";
res.render("error.ejs", {
"title": "2 Deux",
"msg": msg
});
} | 17.75 | 70 | 0.626761 |
c1b06ab2176eb1586c13d53ecf8b66fc0e5e0a85 | 760 | js | JavaScript | src/textarea/styled-components.js | afzalsayed96/baseweb | 38e0a6c8ef943c345b28226ad23c01555654d527 | [
"MIT"
] | 1 | 2020-04-22T20:23:10.000Z | 2020-04-22T20:23:10.000Z | src/textarea/styled-components.js | afzalsayed96/baseweb | 38e0a6c8ef943c345b28226ad23c01555654d527 | [
"MIT"
] | 1 | 2020-04-09T16:25:03.000Z | 2020-04-09T16:25:03.000Z | src/textarea/styled-components.js | afzalsayed96/baseweb | 38e0a6c8ef943c345b28226ad23c01555654d527 | [
"MIT"
] | 1 | 2021-07-14T17:19:46.000Z | 2021-07-14T17:19:46.000Z | /*
Copyright (c) 2018-2020 Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
import {styled} from '../styles/index.js';
import {
getInputStyles,
getInputContainerStyles,
} from '../input/styled-components.js';
import type {SharedStylePropsT} from './types.js';
// $FlowFixMe https://github.com/facebook/flow/issues/7745
export const StyledTextareaContainer = styled<SharedStylePropsT>(
'div',
props => ({
...getInputContainerStyles(props),
}),
);
// $FlowFixMe https://github.com/facebook/flow/issues/7745
export const StyledTextarea = styled<SharedStylePropsT>('textarea', props => ({
...getInputStyles(props),
resize: 'none',
}));
| 27.142857 | 79 | 0.721053 |
c1b0d94b64fd6b0394cccbcea6fa33bee52df4b2 | 798 | js | JavaScript | lib/db.js | jlleblanc/nodejs-joomla | a0037eed442e1168277c5ab85ed2de1f895ff0d7 | [
"BSD-2-Clause"
] | 26 | 2015-02-16T16:35:33.000Z | 2022-03-24T08:34:13.000Z | lib/db.js | jlleblanc/nodejs-joomla | a0037eed442e1168277c5ab85ed2de1f895ff0d7 | [
"BSD-2-Clause"
] | 2 | 2016-05-12T14:26:43.000Z | 2016-08-11T17:19:35.000Z | lib/db.js | jlleblanc/nodejs-joomla | a0037eed442e1168277c5ab85ed2de1f895ff0d7 | [
"BSD-2-Clause"
] | 17 | 2015-05-06T07:03:40.000Z | 2022-02-11T13:26:25.000Z | var MySQL = require('mysql'),
config = require('./config');
var Db = module.exports;
Db.connect = function (callback) {
var host = config.configuration.host.split(':');
Db.client = MySQL.createClient({
user: config.configuration.user,
password: config.configuration.password,
host: host[0],
database: config.configuration.db,
port: host[1] == undefined ? 3306 : host[1]
});
};
Db.query = function (query_string, callback) {
query_string = query_string.replace('#__', config.configuration.dbprefix);
Db.client.query(query_string, function (error, results) {
if (error) {
console.log('MySQL query error, following query failed: ' + query_string + "\nWith this message: " + error);
callback();
return;
}
callback(results);
});
};
| 25.741935 | 114 | 0.655388 |
c1b1da3bbc92ea26c9b594b23ca3b8b1bf305409 | 382 | js | JavaScript | travel_web/src/main/resources/static/js/chunk-743b7a67.48e3d193.js | orchid-ding/travel | 1529d31b3ed4d925cda1ad855116972326550f9c | [
"MIT"
] | 1 | 2020-03-10T04:51:39.000Z | 2020-03-10T04:51:39.000Z | travel_web/src/main/resources/static/js/chunk-743b7a67.48e3d193.js | sev7e0/travel | 0bf4f8151d8beded3a136fcadf582d492625f49b | [
"MIT"
] | null | null | null | travel_web/src/main/resources/static/js/chunk-743b7a67.48e3d193.js | sev7e0/travel | 0bf4f8151d8beded3a136fcadf582d492625f49b | [
"MIT"
] | null | null | null | (window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-743b7a67"],{"0026a":function(n,a,e){"use strict";e.r(a);var t=function(){var n=this,a=n.$createElement,e=n._self._c||a;return e("div",[n._v("\n道路拥堵分析\n\n ")])},c=[],u={},r=u,s=e("5511"),i=Object(s["a"])(r,t,c,!1,null,"2aa90ac0",null);a["default"]=i.exports}}]);
//# sourceMappingURL=chunk-743b7a67.48e3d193.js.map | 191 | 330 | 0.641361 |
c1b20674234a35cce399441076ee5770373f4ba9 | 298 | js | JavaScript | resources/assets/js/app/admin/admin.module.js | choeungeol/mthocs | ce44fa4c8ec94950d0a9e75809cfacb2a3e6fd4e | [
"MIT"
] | null | null | null | resources/assets/js/app/admin/admin.module.js | choeungeol/mthocs | ce44fa4c8ec94950d0a9e75809cfacb2a3e6fd4e | [
"MIT"
] | null | null | null | resources/assets/js/app/admin/admin.module.js | choeungeol/mthocs | ce44fa4c8ec94950d0a9e75809cfacb2a3e6fd4e | [
"MIT"
] | null | null | null | /**
* Created by hankwanghoon on 2016. 8. 14..
*/
(function() {
'use strict';
angular.module('Mth.Admin',
[
'ngResource',
'ui.router',
'angular-ladda',
'Mth.Utils',
'ngAnimate',
'toastr'
]);
})();
| 15.684211 | 43 | 0.40604 |
c1b22325d90e107582f9a5bf7ebf5afb02ad9c69 | 2,723 | js | JavaScript | src/index.js | chime-experiment/anastasia | f62fd0dcfe9474f67027d0ceb8feefe4f920faa4 | [
"MIT"
] | null | null | null | src/index.js | chime-experiment/anastasia | f62fd0dcfe9474f67027d0ceb8feefe4f920faa4 | [
"MIT"
] | 4 | 2020-10-21T20:28:05.000Z | 2021-01-04T21:32:47.000Z | src/index.js | chime-experiment/anastasia | f62fd0dcfe9474f67027d0ceb8feefe4f920faa4 | [
"MIT"
] | null | null | null | 'use strict';
require('dotenv').config();
const express = require('express');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const report = require('./report');
const signature = require('./verifySignature');
const api = require('./api');
const payloads = require('./payloads');
const debug = require('debug')('anastasia:index');
const app = express();
app.use(helmet());
/*
* Parse application/x-www-form-urlencoded && application/json
* Use body-parser's `verify` callback to export a parsed raw body
* that you need to use to verify the signature
*/
const rawBodyBuffer = (req, res, buf, encoding) => {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
};
app.use(bodyParser.urlencoded({verify: rawBodyBuffer, extended: true}));
app.use(bodyParser.json({verify: rawBodyBuffer}));
/*
* Endpoint to receive /signoff slash command from Slack.
* Checks verification token and opens a dialog to capture more info.
*/
app.post('/signoff', async(
req, res) => {
// Verify the signing secret
if (!signature.isVerified(req)) {
debug('Verification token mismatch');
return res.status(404).send();
}
// extract the trigger ID from payload
const {trigger_id} = req.body;
// create the modal payload - includes the dialog structure, Slack API token,
// and trigger ID
let view = payloads.modal({
trigger_id,
});
let result = await api.callAPIMethod('views.open', view);
debug('views.open: %o', result);
return res.send('');
});
/*
* Endpoint to receive /signin slash command from Slack.
* Checks verification token and sends a message to the
* channel with the user name.
*/
app.post('/signin', async(
req, res) => {
// Verify the signing secret
if (!signature.isVerified(req)) {
debug('Verification token mismatch');
return res.status(404).send();
}
let message = payloads.signin({
channel_id: process.env.ANASTASIA_SLACK_CHANNEL,
user: req.body.user_id,
});
let result = await api.callAPIMethod('chat.postMessage', message);
debug('sendConfirmation: %o', result);
return res.send('');
});
/*
* Endpoint to receive the dialog submission. Checks the verification token
* and creates a report entry
*/
app.post('/report', (req,
res) => {
// Verify the signing secret
if (!signature.isVerified(req)) {
debug('Verification token mismatch');
return res.status(404).send();
}
const body = JSON.parse(req.body.payload);
res.send('');
report.create(body.user.id, body.view);
});
const server = app.listen(process.env.PORT || 8010, () => {
console.log('Express server listening on port %d in %s mode',
server.address().port, app.settings.env);
});
| 26.696078 | 79 | 0.676093 |
c1b32f8aa335017d51a514454021cadb05b293dc | 388 | js | JavaScript | frontend/src/config/default/admin.config.js | Rhinob1/datafan-report | a3109fab253a1c4700732cd364bea9f1c00d7199 | [
"Apache-2.0"
] | 1 | 2022-01-21T08:06:14.000Z | 2022-01-21T08:06:14.000Z | frontend/src/config/default/admin.config.js | Rhinob1/datafan-report | a3109fab253a1c4700732cd364bea9f1c00d7199 | [
"Apache-2.0"
] | null | null | null | frontend/src/config/default/admin.config.js | Rhinob1/datafan-report | a3109fab253a1c4700732cd364bea9f1c00d7199 | [
"Apache-2.0"
] | null | null | null | // admin 配置
const ADMIN = {
palettes: [
'#f5222d',
'#fa541c',
'#fadb14',
'#3eaf7c',
'#13c2c2',
'#1890ff',
'#722ed1',
'#eb2f96'
],
animates: require('./animate.config').preset,
theme: {
mode: {
DARK: 'dark',
LIGHT: 'light',
NIGHT: 'night'
}
},
layout: {
SIDE: 'side',
HEAD: 'head'
}
}
module.exports = ADMIN
| 13.857143 | 47 | 0.474227 |
c1b3bc59a7d8a588f56d0f8dd824a7dadc171ab5 | 5,969 | js | JavaScript | docs/dist/plugins/cEngine.file-min.js | renmuell/canvasEngine | a0f8f5147c87ce78d52d9211f99b334cdab0af0e | [
"MIT"
] | 1 | 2019-02-19T21:10:01.000Z | 2019-02-19T21:10:01.000Z | docs/dist/plugins/cEngine.file-min.js | renmuell/canvasEngine | a0f8f5147c87ce78d52d9211f99b334cdab0af0e | [
"MIT"
] | 2 | 2018-09-05T09:46:22.000Z | 2018-11-02T15:43:16.000Z | docs/dist/plugins/cEngine.file-min.js | renmuell/canvasEngine | a0f8f5147c87ce78d52d9211f99b334cdab0af0e | [
"MIT"
] | null | null | null | !function e(t,n,o){function i(a,f){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!f&&u)return u(a,!0);if(r)return r(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,o)}return n[a].exports}for(var r="function"==typeof require&&require,a=0;a<o.length;a++)i(o[a]);return i}({1:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var i=e("../vendors/FileSaver"),r=o(i);e("../vendors/canvas-toBlob"),function(e){e.extend("file",{create:function(){var e={cEnginePlugin:{name:"file",version:"0.0.1"},engine:void 0,fileInput:void 0,init:function(t){e.engine=t,e.fileInput=document.createElement("input"),e.fileInput.type="file",e.fileInput.style.visibility="hidden",e.fileInput.onchange=function(){var t=new FileReader;t.onload=function(){var n=new Image;n.onload=function(){e.engine.clear(),e.engine.resizeTo(n.width,n.height),e.engine.canvas.getContext("2d").drawImage(n,0,0)},n.src=t.result},t.readAsDataURL(e.fileInput.files[0])},document.body.appendChild(e.fileInput)},destroy:function(){e.fileInput.remove()},saveToFile:function(t){e.engine.canvas.toBlob(function(e){r["default"].saveAs(e,t)})},loadFile:function(){e.fileInput.click()}};return e}})}(cEngine)},{"../vendors/FileSaver":2,"../vendors/canvas-toBlob":3}],2:[function(e,t,n){var o=o||function(e){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var t=e.document,n=function(){return e.URL||e.webkitURL||e},o=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in o,r=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),f=e.webkitRequestFileSystem,u=e.requestFileSystem||f||e.mozRequestFileSystem,c=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",l=0,d=500,v=function(t){var o=function(){"string"==typeof t?n().revokeObjectURL(t):t.remove()};e.chrome?o():setTimeout(o,d)},p=function(e,t,n){t=[].concat(t);for(var o=t.length;o--;){var i=e["on"+t[o]];if("function"==typeof i)try{i.call(e,n||e)}catch(r){c(r)}}},w=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\ufeff",e],{type:e.type}):e},y=function(t,c,d){d||(t=w(t));var y,g,h,m=this,b=t.type,R=!1,I=function(){p(m,"writestart progress write writeend".split(" "))},S=function(){if(g&&a&&"undefined"!=typeof FileReader){var o=new FileReader;return o.onloadend=function(){var e=o.result;g.location.href="data:attachment/file"+e.slice(e.search(/[,;]/)),m.readyState=m.DONE,I()},o.readAsDataURL(t),void(m.readyState=m.INIT)}if(!R&&y||(y=n().createObjectURL(t)),g)g.location.href=y;else{var i=e.open(y,"_blank");void 0===i&&a&&(e.location.href=y)}m.readyState=m.DONE,I(),v(y)},E=function(e){return function(){if(m.readyState!==m.DONE)return e.apply(this,arguments)}},D={create:!0,exclusive:!1};return m.readyState=m.INIT,c||(c="download"),i?(y=n().createObjectURL(t),void setTimeout(function(){o.href=y,o.download=c,r(o),I(),v(y),m.readyState=m.DONE})):(e.chrome&&b&&b!==s&&(h=t.slice||t.webkitSlice,t=h.call(t,0,t.size,s),R=!0),f&&"download"!==c&&(c+=".download"),(b===s||f)&&(g=e),u?(l+=t.size,void u(e.TEMPORARY,l,E(function(e){e.root.getDirectory("saved",D,E(function(e){var n=function(){e.getFile(c,D,E(function(e){e.createWriter(E(function(n){n.onwriteend=function(t){g.location.href=e.toURL(),m.readyState=m.DONE,p(m,"writeend",t),v(e)},n.onerror=function(){var e=n.error;e.code!==e.ABORT_ERR&&S()},"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=m["on"+e]}),n.write(t),m.abort=function(){n.abort(),m.readyState=m.DONE},m.readyState=m.WRITING}),S)}),S)};e.getFile(c,{create:!1},E(function(e){e.remove(),n()}),E(function(e){e.code===e.NOT_FOUND_ERR?n():S()}))}),S)}),S)):void S())},g=y.prototype,h=function(e,t,n){return new y(e,t,n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return n||(e=w(e)),navigator.msSaveOrOpenBlob(e,t||"download")}:(g.abort=function(){var e=this;e.readyState=e.DONE,p(e,"abort")},g.readyState=g.INIT=0,g.WRITING=1,g.DONE=2,g.error=g.onwritestart=g.onprogress=g.onwrite=g.onabort=g.onerror=g.onwriteend=null,h)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof t&&t.exports?t.exports.saveAs=o:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return o})},{}],3:[function(e,t,n){!function(e){"use strict";var t,n=e.Uint8Array,o=e.HTMLCanvasElement,i=o&&o.prototype,r=/\s*;\s*base64\s*(?:;|$)/i,a="toDataURL",f=function(e){for(var o,i,r,a=e.length,f=new n(a/4*3|0),u=0,c=0,s=[0,0],l=0,d=0;a--;)i=e.charCodeAt(u++),o=t[i-43],255!==o&&o!==r&&(s[1]=s[0],s[0]=i,d=d<<6|o,l++,4===l&&(f[c++]=d>>>16,61!==s[1]&&(f[c++]=d>>>8),61!==s[0]&&(f[c++]=d),l=0));return f};n&&(t=new n([62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51])),o&&!i.toBlob&&(i.toBlob=function(e,t){if(t||(t="image/png"),this.mozGetAsFile)return void e(this.mozGetAsFile("canvas",t));if(this.msToBlob&&/^\s*image\/png\s*(?:$|;)/i.test(t))return void e(this.msToBlob());var o,i=Array.prototype.slice.call(arguments,1),u=this[a].apply(this,i),c=u.indexOf(","),s=u.substring(c+1),l=r.test(u.substring(0,c));Blob.fake?(o=new Blob,l?o.encoding="base64":o.encoding="URI",o.data=s,o.size=s.length):n&&(o=l?new Blob([f(s)],{type:t}):new Blob([decodeURIComponent(s)],{type:t})),e(o)},i.toDataURLHD?i.toBlobHD=function(){a="toDataURLHD";var e=this.toBlob();return a="toDataURL",e}:i.toBlobHD=i.toBlob)}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content||this)},{}]},{},[1]);
//# sourceMappingURL=cEngine.file-min.js.map
| 1,989.666667 | 5,923 | 0.674987 |
c1b3c25661b382becac9e164afd021ba457e6eb8 | 74 | js | JavaScript | jest.setup.js | DrXama/RPG-MAKER-MZ | 62551053d650adb2468d952fbc0cd196cc42929c | [
"MIT"
] | null | null | null | jest.setup.js | DrXama/RPG-MAKER-MZ | 62551053d650adb2468d952fbc0cd196cc42929c | [
"MIT"
] | null | null | null | jest.setup.js | DrXama/RPG-MAKER-MZ | 62551053d650adb2468d952fbc0cd196cc42929c | [
"MIT"
] | 1 | 2022-01-30T23:59:57.000Z | 2022-01-30T23:59:57.000Z | const dotenv = require('dotenv');
dotenv.config({ path: './.env.test' }); | 24.666667 | 39 | 0.635135 |
c1b3d8d6479695b6b6dc7502938689fd336d5451 | 23,615 | js | JavaScript | assets/js/12.2a563cd8.js | fariztiger/vittominacori.github.io | a360b161c4691175ba3e603090e59bcb2b3df9a6 | [
"MIT"
] | null | null | null | assets/js/12.2a563cd8.js | fariztiger/vittominacori.github.io | a360b161c4691175ba3e603090e59bcb2b3df9a6 | [
"MIT"
] | null | null | null | assets/js/12.2a563cd8.js | fariztiger/vittominacori.github.io | a360b161c4691175ba3e603090e59bcb2b3df9a6 | [
"MIT"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[12],{367:function(e,t,o){"use strict";o.r(t);var r=o(42),i=Object(r.a)({},(function(){var e=this,t=e.$createElement,o=e._self._c||t;return o("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[o("h2",{attrs:{id:"terms-and-conditions"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#terms-and-conditions"}},[e._v("#")]),e._v(" Terms and Conditions")]),e._v(" "),o("h3",{attrs:{id:"data-controller-and-owner"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#data-controller-and-owner"}},[e._v("#")]),e._v(" Data Controller and Owner")]),e._v(" "),o("p",[e._v("https://vittominacori.github.io")]),e._v(" "),o("p",[e._v("Owner contact email: info@vmlab.it")]),e._v(" "),o("h3",{attrs:{id:"general"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#general"}},[e._v("#")]),e._v(" General")]),e._v(" "),o("p",[e._v("By accessing and using this website (our or this “Website”), you agree to the following terms of use as they may be modified, changed, supplemented or updated from time to time (collectively, these “terms”), as well as all applicable laws and regulations. Please read the following terms and conditions carefully. If you do not agree to all of these terms, please do not use this Website or any information, links or content contained on this Website. Your access to and use of this Website constitutes your acceptance of and agreement to abide by each of the terms set forth below including our "),o("a",{attrs:{href:"/privacy"}},[e._v("Privacy Policy")]),e._v(" which is hereby incorporated in these terms by reference. If you are using our Website on behalf of your organization, that organization accepts these terms.")]),e._v(" "),o("p",[e._v("These terms may be modified, changed, supplemented or updated by Website (“we”, “us” or “our”) in its sole discretion at any time without advance notice. We suggest that you visit this page regularly to keep up to date with any changes. Your continued use of this Website will confirm your acceptance of these terms as modified, changed, supplemented or updated by us. If you do not agree to such revised terms you must stop using this Website and any information, links or content contained on this Website.")]),e._v(" "),o("h3",{attrs:{id:"use-of-website"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#use-of-website"}},[e._v("#")]),e._v(" Use of Website")]),e._v(" "),o("p",[e._v("The purpose of our Website is to provide you with some general information about the software being developed. You must not breach any of the following terms or our Acceptable Use Policy set out below.")]),e._v(" "),o("h3",{attrs:{id:"open-source-software"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#open-source-software"}},[e._v("#")]),e._v(" Open Source Software")]),e._v(" "),o("p",[e._v("We will make (but are not obligated to make) the source code for the software we develop available for download as open source software. You agree to be bound by, and comply with, any license agreement that applies to this open source software. You will not indicate that you are associated with us in connection with your use, modifications or distributions of this open source software.")]),e._v(" "),o("p",[e._v("When we host any software and enable you to access and use such software through our websites including this Website, then these terms will apply to such access and use, as well as any license agreements that we may enter into with you.")]),e._v(" "),o("h3",{attrs:{id:"third-party-content"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#third-party-content"}},[e._v("#")]),e._v(" Third Party Content")]),e._v(" "),o("p",[e._v("We may display third-party content, advertisements, links, promotions, logos and other materials on our Website (collectively, the “Third-Party Content”) for your convenience only. We do not approve of, control, endorse or sponsor any third parties or Third-Party Content, and we make no representations or warranties of any kind regarding such Third-Party Content, including, without limitation, the accuracy, validity, legality, copyright compliance, or decency of such content. Your use of or interactions with any Third-Party Content, and any third party that provides Third-Party Content, are solely between you and such third parties and we are not responsible or liable in any manner for such use or interactions. We are not responsible for any of the content on third party sites linked to our Website nor can it be assumed that we have reviewed or approved of such sites or their content, nor do we warrant that the links to these sites work or are up to date.")]),e._v(" "),o("h3",{attrs:{id:"user-content"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#user-content"}},[e._v("#")]),e._v(" User Content")]),e._v(" "),o("p",[e._v("If you post, upload, input, provide or submit your personal data to us, including without limitation, your name, email address, IP address, cryptocurrency address, text, code or other information and materials or sign up to our mailing list (collectively, your “User Content”), you must ensure that the User Content provided by you at that or at any other time is true, accurate, up to date and complete and that any User Content you post, upload, input, provide or submit to us or via our Website do not breach or infringe the intellectual property rights of any third party. We do not own, control or endorse any User Content that is transmitted, stored or processed via our Website or sent to us and we are not responsible or liable for any User Content. You are solely responsible and liable for all of your User Content and for your use of any interactive features, links or information or content on our Website, and you represent and warrant that")]),e._v(" "),o("p",[e._v("i) you own all intellectual property rights (or have obtained all necessary permissions) to provide your User Content and to grant the licenses in these terms;")]),e._v(" "),o("p",[e._v("ii) your User Content will not violate any agreements or confidentiality obligations;")]),e._v(" "),o("p",[e._v("iii) your User Content will not violate, infringe or misappropriate any intellectual property right or other proprietary right, including the right of publicity or privacy, of any person or entity.")]),e._v(" "),o("p",[e._v("You are entirely responsible for maintaining the confidentiality of your User Content and any of your non-public information. Furthermore, you are entirely responsible for any and all activities that occur under your account (if any). You agree to notify us immediately of any unauthorized use of your User Content, account or any other breach of security. We will not be liable for any loss or damages that you may incur as a result of someone else using your User Content or account, either with or without your knowledge. However, you could be held liable for losses incurred by the Website Parties (as defined below) or another party due to someone else using your User Content or account. You may not use anyone else’s User Content or account at any time without the permission of such person or entity.")]),e._v(" "),o("p",[e._v("By posting, uploading, inputting, providing or submitting your User Content to us, you grant Website, its affiliates and any necessary sub-licensees a non-exclusive, worldwide, perpetual, right and permission to use, reproduce, copy, edit, modify, translate, reformat, create derivative works from, distribute, transmit, publicly perform and publicly display your User Content and sub-license such rights to others.")]),e._v(" "),o("p",[e._v("You must immediately update and inform us of any changes to your User Content by updating your personal data by contacting us at Owner contact email, so that we can communicate with you effectively and provide accurate and up to date information to you.")]),e._v(" "),o("p",[e._v("Although we have no obligation to screen, edit or monitor User Content, we reserve the right, and have absolute discretion, to remove, screen or edit User Content. Furthermore, if we have reason to believe that there is likely to be a breach of security, breach or misuse of our Website or if you breach any of your obligations under these terms or the Privacy Policy, we may suspend your use of this Website at any time and for any reason.")]),e._v(" "),o("p",[e._v("Any User Content submitted by you on this Website may be accessed by us globally.")]),e._v(" "),o("h3",{attrs:{id:"feedback"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#feedback"}},[e._v("#")]),e._v(" Feedback")]),e._v(" "),o("p",[e._v("If you decide to submit questions, comments, suggestions, ideas, original or creative materials or other information to us (collectively, “Feedback”), you do so on your own accord and not based on any request or solicitation from us. Feedback does not include User Content. We reserve the right to use Feedback for any purpose at no charge and without compensation to you. Do not send us Feedback if you expect to be paid or want to continue to own or claim rights to your Feedback. The purpose of these terms is to avoid potential misunderstandings or disputes if Website’ products, services, business ideas or business strategies might seem similar to ideas submitted to us as Feedback. If you decide to send us Feedback, you acknowledge and understand that the Website Parties make no assurances that your Feedback will be treated as confidential or proprietary.")]),e._v(" "),o("h3",{attrs:{id:"aggregate-information"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#aggregate-information"}},[e._v("#")]),e._v(" Aggregate Information")]),e._v(" "),o("p",[e._v("We may gather information and statistics collectively about all visitors to this Website which may include the information supplied by you. This information helps us to design and arrange our Web pages in a user-friendly manner and to continually improve our Website to better meet the needs of our Website users. We may share this kind of aggregate data with selected third parties to assist with these purposes. Personal data is processed by us in accordance with our Privacy Policy.")]),e._v(" "),o("h3",{attrs:{id:"intellectual-property"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#intellectual-property"}},[e._v("#")]),e._v(" Intellectual Property")]),e._v(" "),o("p",[e._v("Website and its licensors retain all right, title and interest in and to this Website and its products and services, including all copyrights, patents, trade secrets, trademarks, other intellectual property rights, trade names, logos, slogans, custom graphics, button icons, scripts, videos, text, images, software, code, files, content, information and other material available on our Website and nothing on this Website may be copied, imitated or used, in whole or in part, without our or the applicable licensor’s prior written permission. Website reserves all rights not expressly granted.")]),e._v(" "),o("p",[e._v("Any unauthorised reproduction is prohibited.")]),e._v(" "),o("p",[e._v("You may only access, use and print the information and material on this Website for non-commercial or personal use provided that you are authorized to access such information or material and keep intact all copyright and proprietary notices.")]),e._v(" "),o("p",[e._v("You must not otherwise reproduce, adapt, store, transmit, distribute, print, display, commercialise, publish or create derivative works from any part of the content, format or design of this Website.")]),e._v(" "),o("p",[e._v("If you seek to reproduce or otherwise use the content on this Website in any way it is your responsibility to obtain approval from us for such use. Nothing in these terms will be construed as conferring any right or license to any patent, trademark, copyright or other proprietary rights of Website or any third party, whether by estoppel, implication or otherwise.")]),e._v(" "),o("h3",{attrs:{id:"acceptable-use-policy"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#acceptable-use-policy"}},[e._v("#")]),e._v(" Acceptable Use Policy")]),e._v(" "),o("p",[e._v("You must only use the content or services provided through this Website for their stated purpose. You must not use this Website to:")]),e._v(" "),o("p",[e._v("a) publish, post, send, upload, submit, display or disseminate any information or material and/or otherwise make available or engage in any conduct that is unlawful, discriminatory, harassing, libellous, defamatory, abusive, threatening, harmful, offensive, obscene, tortious or otherwise objectionable;")]),e._v(" "),o("p",[e._v("b) display, upload or transmit material that encourages conduct that may constitute a criminal offence, result in civil liability or otherwise violate or breach any applicable laws, regulations or code of practice;")]),e._v(" "),o("p",[e._v("c) interfere or violate the legal rights (such as rights of privacy and publicity) of others or violate others use or enjoyment of this Website;")]),e._v(" "),o("p",[e._v("d) violate any applicable laws or regulations;")]),e._v(" "),o("p",[e._v("e) use this Website or links on this Website in any manner that could interfere with, disrupt, negatively affect or inhibit other users from using this Website or links on this Website or that could damage, disable, overburden or impair the functioning of this Website or our servers or any networks connected to any of our servers in any manner;")]),e._v(" "),o("p",[e._v("f) create a false identity for the purpose of misleading others or fraudulently or otherwise misrepresent yourself to be another person or a representative of another entity including, but not limited to, an authorized user of this Website or a Website representative, or fraudulently or otherwise misrepresent that you have an affiliation with a person, entity or group;")]),e._v(" "),o("p",[e._v("g) mislead or deceive us, our representatives and any third parties who may rely on the information provided by you, by providing inaccurate or false information, which includes omissions of information;")]),e._v(" "),o("p",[e._v("h) disguise the origin of any material transmitted through the services provided by this Website (whether by forging message/packet headers or otherwise manipulating normal identification information);")]),e._v(" "),o("p",[e._v("i) violate, infringe or misappropriate any intellectual or industrial property right of any person (such as copyright, trademarks, patents, or trade secrets, or other proprietary rights of any party) or commit a tort;")]),e._v(" "),o("p",[e._v("j) upload files that contain viruses, Trojan horses, worms, time bombs, cancelbots, corrupted files, or any other similar software or programs that may damage the operation of another’s computer or property;")]),e._v(" "),o("p",[e._v("k) send, upload, display or disseminate or otherwise make available material containing or associated with spam, junk mail, advertising for pyramid schemes, chain letters, virus warnings (without first confirming the authenticity of the warning), or any other form of unauthorised advertising or promotional material;")]),e._v(" "),o("p",[e._v("l) access any content, area or functionality of this Website that you are prohibited or restricted from accessing or attempt to bypass or circumvent measures employed to prevent or limit your access to any content, area or functionality of this Website;")]),e._v(" "),o("p",[e._v("m) obtain unauthorised access to or interfere with the performance of the servers which host this Website or provide the services on this Website or any servers on any associated networks or otherwise fail to comply with any policies or procedures relating to the use of those servers;")]),e._v(" "),o("p",[e._v("n) attempt to gain unauthorized access to any services or products, other accounts, computer systems, or networks connected to any of our servers through hacking, password mining, or any other means;")]),e._v(" "),o("p",[e._v("o) obtain or attempt to obtain any materials or information through any means not intentionally made available through this Website or its services;")]),e._v(" "),o("p",[e._v("p) harvest or otherwise collect, whether aggregated or otherwise, data about others including e-mail addresses and/or distribute or sell such data in any manner;")]),e._v(" "),o("p",[e._v("q) use any part of this Website other than for its intended purpose; or")]),e._v(" "),o("p",[e._v("r) use this Website to engage in or promote any activity that violates these terms.")]),e._v(" "),o("h3",{attrs:{id:"indemnification"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#indemnification"}},[e._v("#")]),e._v(" Indemnification")]),e._v(" "),o("p",[e._v("To the fullest extent permitted by applicable law, you will indemnify, defend and hold harmless us and our respective past, present and future employees, officers, directors, contractors, consultants, equity holders, suppliers, vendors, service providers, parent companies, subsidiaries, affiliates, agents, representatives, predecessors, successors and assigns (collectively, the “Website Parties”) from and against all claims, damages, liabilities, losses, costs and expenses (including attorneys’ fees) that arise from or relate to: (i) your access to or use of our Website, products or services; (ii) your User Content; (iii) any Feedback you provide; or (iv) your violation of these Terms.")]),e._v(" "),o("p",[e._v("We reserve the right to exercise sole control over the defence, at your expense, of any claim subject to indemnification pursuant to these terms. This indemnity is in addition to, and not in lieu of, any other indemnities set forth in a written agreement between you and Website.")]),e._v(" "),o("h3",{attrs:{id:"disclaimer"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#disclaimer"}},[e._v("#")]),e._v(" Disclaimer")]),e._v(" "),o("p",[e._v("THIS WEBSITE AND ALL INFORMATION, PRODUCTS AND SERVICES PROVIDED THROUGH THIS WEBSITE ARE PROVIDED “AS IS” AND ON AN “AS AVAILABLE” BASIS WITHOUT ANY REPRESENTATIONS, WARRANTIES, PROMISES OR GUARANTEES WHATSOEVER OF ANY KIND INCLUDING, WITHOUT LIMITATION, ANY REPRESENTATIONS, WARRANTIES, PROMISES OR GUARANTEES REGARDING THE ACCURACY, CURRENCY, COMPLETENESS, ADEQUACY, AVAILBILITY, SUITABLITY OR OPERATION OF THIS WEBSITE, ANY PRODUCTS OR SERVICES WE MAY PROVIDE THROUGH IT OR THE INFORMATION OR MATERIAL IT CONTAINS.\nEACH OF THE WEBSITE PARTIES DISCLAIM ALL REPRESENTATIONS AND WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, WITH REGARD TO THE FOREGOING, INCLUDING, WITHOUT LIMITATION:")]),e._v(" "),o("p",[e._v("A) ANY WARRANTY WITH RESPECT TO THE CONTENT, INFORMATION, DATA, SERVICES, AVAILABLITY, UNINTERRUPTED ACCESS, OR SERVICES OR PRODUCTS PROVIDED THROUGH OR IN CONNECTION WITH THIS WEBSITE;")]),e._v(" "),o("p",[e._v("B) ANY WARRANTIES THAT THIS WEBSITE OR THE SERVER THAT MAKES IT AVAILABLE ARE FREE OF VIRUSES, WORMS, TROJAN HORSES OR OTHER HARMFUL COMPONENTS;")]),e._v(" "),o("p",[e._v("C) ANY WARRANTIES THAT THIS WEBSITE, ITS CONTENT AND ANY SERVICES OR PRODUCTS PROVIDED THROUGH IT ARE ERROR-FREE OR THAT DEFECTS IN THIS WEBSITE, ITS CONTENT OR SUCH SERVICES OR PRODUCTS WILL BE CORRECTED;")]),e._v(" "),o("p",[e._v("D) ANY WARRANTIES OF TITLE OR IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE;")]),e._v(" "),o("p",[e._v("E) ANY WARRANTIES THAT THIS WEBSITE WILL BE COMPATIBLE WITH YOUR COMPUTER OR OTHER ELECTRONIC EQUIPMENT;")]),e._v(" "),o("p",[e._v("F) ANY WARRANTIES OF NON-INFRINGEMENT. THE MATERIALS AND RELATED GRAPHICS PUBLISHED ON THIS WEBSITE COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION CONTAINED ON THIS WEBSITE. THE WEBSITE PARTIES MAY MAKE IMPROVEMENTS AND/OR CHANGES TO THE WEBSITE, ITS PRODUCTS, SERVICES AND/OR THE MATERIALS DESCRIBED ON THIS WEBSITE AT ANY TIME.")]),e._v(" "),o("p",[e._v("In addition, to the maximum extent permitted by law, none of the Website Parties shall be responsible or liable for:")]),e._v(" "),o("p",[e._v("a) any loss, liability, cost, expense or damage suffered or incurred arising out of or in connection with any access to or use of this Website or any of its content;")]),e._v(" "),o("p",[e._v("b) any reliance on, or decision made on the basis of, information or material shown on or omitted from this Website;")]),e._v(" "),o("p",[e._v("c) any representation or otherwise in respect of the existence or availability of any job, vacancy, assignment or other engagement or appointment advertised on this Website (if any) and any representation or otherwise that we have or will ask for a candidate’s information, will or have asked to interview or hire a candidate, or that any candidates will meet our needs;")]),e._v(" "),o("p",[e._v("d) any matter affecting this Website or any of its content caused by circumstances beyond our reasonable control;")]),e._v(" "),o("p",[e._v("e) the performance of this Website and any fault, delays, interruptions or lack of availability of this Website and any of the services or products provided through this Website, which may occur due to increased usage of this Website, intermittent failures of this Website or the need for repairs, maintenance or the introduction of new facilities, products or services;")]),e._v(" "),o("p",[e._v("f) any information or material on any website operated by a third party which may be accessed from this Website.")]),e._v(" "),o("p",[e._v("IN NO EVENT WILL THE WEBSITE PARTIES BE RESPONSIBLE OR LIABLE FOR ANY CLAIMS, DAMAGES, LIABILITIES, LOSSES, COSTS OR EXPENSES OF ANY KIND, WHETHER DIRECT OR INDIRECT, CONSEQUENTIAL, COMPENSATORY, INCIDENTAL, ACTUAL, EXEMPLARY, PUNITIVE OR SPECIAL (INCLUDING DAMAGES FOR LOSS OF BUSINESS, REVENUES, PROFITS, DATA, USE, GOODWILL OR OTHER INTANGIBLE LOSSES) REGARDLESS OF WHETHER THE WEBSITE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, LIABILITIES, LOSSES, COSTS OR EXPENSES, ARISING OUT OF OR IN CONNECTION WITH:")]),e._v(" "),o("p",[e._v("A) THE USE OR PERFORMANCE OF THIS WEBSITE;")]),e._v(" "),o("p",[e._v("B) ANY PROVISION OF OR FAILURE TO PROVIDE THIS WEBSITE OR ITS SERVICES (INCLUDING WITHOUT LIMITATION ANY LINKS ON OUR WEBSITE);")]),e._v(" "),o("p",[e._v("C) ANY INFORMATION AVAILABLE FROM THIS WEBSITE;")]),e._v(" "),o("p",[e._v("D) ANY CONDUCT OR CONTENT OF ANY THIRD PARTY;")]),e._v(" "),o("p",[e._v("E) UNAUTHORIZED ACCESS, USE OR ALTERATION OF THE TRANSMISSION OF DATA OR CONTENT TO OR FROM US;")]),e._v(" "),o("p",[e._v("F) THE FAILURE TO RECEIVE IN ANY WAY THE TRANSMISSION OF ANY DATA, CONTENT, FUNDS OR PROPERTY FROM YOU.")]),e._v(" "),o("p",[e._v("IN NO CIRCUMSTANCES WILL THE AGGREGATE LIABILITY OF THE WEBSITE PARTIES ARISING UNDER THESE TERMS EXCEED $1.00 USD.")]),e._v(" "),o("h3",{attrs:{id:"conclusion"}},[o("a",{staticClass:"header-anchor",attrs:{href:"#conclusion"}},[e._v("#")]),e._v(" Conclusion")]),e._v(" "),o("p",[e._v("These terms control the relationship between us and you. They do not create any third-party beneficiary rights.")]),e._v(" "),o("p",[e._v("If you do not comply with these terms, and we don’t take action right away, this doesn’t mean that we are giving up any rights that we may have (such as taking action in the future).")]),e._v(" "),o("p",[e._v("If it turns out that a particular term is not enforceable, the term will be modified such that it is enforceable and this will not affect any other terms contained herein.")]),e._v(" "),o("p",[e._v("If you have any questions regarding these terms, please contact us at Owner contact email.")])])}),[],!1,null,null,null);t.default=i.exports}}]); | 23,615 | 23,615 | 0.748041 |
c1b46c4e69f2f4fe881c132f1a7673ee87671d49 | 1,795 | js | JavaScript | assets/javascripts/bootstrap/min/product-features-min.js | kdooley89/APM-Build | 18d7ffd39ef2acfc94c77d09b25685e177d8be95 | [
"MIT"
] | null | null | null | assets/javascripts/bootstrap/min/product-features-min.js | kdooley89/APM-Build | 18d7ffd39ef2acfc94c77d09b25685e177d8be95 | [
"MIT"
] | null | null | null | assets/javascripts/bootstrap/min/product-features-min.js | kdooley89/APM-Build | 18d7ffd39ef2acfc94c77d09b25685e177d8be95 | [
"MIT"
] | null | null | null | $(document).ready(function(){$(".ft-one").click(function(){$(".feature-wrap").hide("slow"),$(".ft-1-description").show(1e3)}),$(".go-back").click(function(){$(".ft-1-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-two").click(function(){$(".feature-wrap").hide("slow"),$(".ft-2-description").show(1e3)}),$(".go-back").click(function(){$(".ft-2-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-three").click(function(){$(".feature-wrap").hide("slow"),$(".ft-3-description").show(1e3)}),$(".go-back").click(function(){$(".ft-3-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-four").click(function(){$(".feature-wrap").hide("slow"),$(".ft-4-description").show(1e3)}),$(".go-back").click(function(){$(".ft-4-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-five").click(function(){$(".feature-wrap").hide("slow"),$(".ft-5-description").show(1e3)}),$(".go-back").click(function(){$(".ft-5-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-six").click(function(){$(".feature-wrap").hide("slow"),$(".ft-6-description").show(1e3)}),$(".go-back").click(function(){$(".ft-6-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-seven").click(function(){$(".feature-wrap").hide("slow"),$(".ft-7-description").show(1e3)}),$(".go-back").click(function(){$(".ft-7-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-eight").click(function(){$(".feature-wrap").hide("slow"),$(".ft-8-description").show(1e3)}),$(".go-back").click(function(){$(".ft-8-description").hide("slow"),$(".feature-wrap").show(1e3)}),$(".ft-nine").click(function(){$(".feature-wrap").hide("slow"),$(".ft-9-description").show(1e3)}),$(".go-back").click(function(){$(".ft-9-description").hide("slow"),$(".feature-wrap").show(1e3)})}); | 1,795 | 1,795 | 0.603343 |
c1b4a4a2f6c0a98a6aba51a42591bb40c2b343ca | 6,670 | js | JavaScript | src/avatar/__tests__/Avatar.js | dquessenberry/react-native-elements | b040b1204408f9442e0a73b68dc8b49bb955f550 | [
"MIT"
] | 3 | 2020-06-15T11:23:20.000Z | 2021-03-11T17:13:44.000Z | src/avatar/__tests__/Avatar.js | MssText/react-native-elements | 208467cf0577e3372dea231cca45db393a5b5beb | [
"MIT"
] | 3 | 2021-10-06T22:26:56.000Z | 2022-02-27T10:53:22.000Z | src/avatar/__tests__/Avatar.js | MssText/react-native-elements | 208467cf0577e3372dea231cca45db393a5b5beb | [
"MIT"
] | 1 | 2020-05-06T22:22:06.000Z | 2020-05-06T22:22:06.000Z | import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { create } from 'react-test-renderer';
import { ThemeProvider } from '../../config';
import ThemedAvatar, { Avatar } from '../Avatar';
describe('Avatar Component', () => {
jest.useFakeTimers();
it('should render without issues', () => {
const component = shallow(
<Avatar source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }} />
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('renders rounded', () => {
const component = shallow(
<Avatar source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }} rounded />
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('allows custom imageProps', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
imageProps={{ resizeMode: 'contain' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('renders touchable if onPress given', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
onPress={() => null}
/>
);
expect(component.find(TouchableOpacity)).toBeTruthy();
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should apply values from theme', () => {
const theme = {
Avatar: {
source: { uri: 'https://i.imgur.com/0y8Ftya.jpg' },
},
};
const component = create(
<ThemeProvider theme={theme}>
<ThemedAvatar />
</ThemeProvider>
);
expect(component.root.findByType('Image').props.source.uri).toBe(
'https://i.imgur.com/0y8Ftya.jpg'
);
expect(component.toJSON()).toMatchSnapshot();
});
describe('Sizes', () => {
it('accepts small', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
size="small"
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('accepts medium', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
size="medium"
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('accepts large', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
size="large"
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('accepts xlarge', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
size="xlarge"
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('defaults to small if invalid string given', () => {
const error = jest.fn();
global.console.error = error;
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
size="asdasdas"
/>
);
expect(error).toHaveBeenCalledWith(
expect.stringContaining(
'Failed prop type: Invalid prop `size` supplied to `Avatar`'
)
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('accepts a number', () => {
const component = shallow(
<Avatar source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }} size={30} />
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
});
describe('Accessory shows', () => {
it('ios', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
showAccessory
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('android', () => {
jest.mock('Platform', () => ({
OS: 'android',
}));
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
showAccessory
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('image source', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
accessory={{
source: {
uri: 'https://homepages.cae.wisc.edu/~ece533/images/baboon.png',
},
}}
showAccessory
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
});
describe('Placeholders', () => {
it('renders title if given', done => {
shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
title="MH"
/>
);
jest.advanceTimersByTime(200);
done();
});
it('renders custom', () => {
shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
renderPlaceholderContent={<Text>Hey</Text>}
/>
);
});
it('renders using icon prop', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
icon={{
name: 'home',
type: 'material-community',
}}
iconStyle={{
backgroundColor: 'red',
}}
/>
);
expect(toJson(component)).toMatchSnapshot();
});
it('renders using icon with defaults', () => {
const component = shallow(
<Avatar
source={{ uri: 'https://i.imgur.com/0y8Ftya.jpg' }}
iconStyle={{
backgroundColor: 'red',
}}
icon={{}}
/>
);
expect(toJson(component)).toMatchSnapshot();
});
it("shouldn't show placeholder if not using source", () => {
const component = shallow(
<Avatar
size="medium"
overlayContainerStyle={{ backgroundColor: 'pink' }}
title="MD"
/>
);
expect(component.props().style.backgroundColor).toBe('transparent');
expect(toJson(component)).toMatchSnapshot();
});
});
});
| 25.852713 | 80 | 0.531934 |
c1b4a93b176690f3cbef57a8f3d47455b870732f | 88,226 | js | JavaScript | public/assets/libraries/bootstrap-fileinput/js/fileinput.min.js | warlesrivera/ekklesia | 6a6a1f354444e9dd21b0e5c52091d100c2f6f8e7 | [
"MIT"
] | null | null | null | public/assets/libraries/bootstrap-fileinput/js/fileinput.min.js | warlesrivera/ekklesia | 6a6a1f354444e9dd21b0e5c52091d100c2f6f8e7 | [
"MIT"
] | null | null | null | public/assets/libraries/bootstrap-fileinput/js/fileinput.min.js | warlesrivera/ekklesia | 6a6a1f354444e9dd21b0e5c52091d100c2f6f8e7 | [
"MIT"
] | null | null | null | !function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=e(require("jquery")):e(window.jQuery)}(function(e){"use strict";var t,i;e.fn.fileinputLocales={},e.fn.fileinputThemes={},String.prototype.setTokens=function(e){var t,i,a=this.toString();for(t in e)e.hasOwnProperty(t)&&(i=new RegExp("{"+t+"}","g"),a=a.replace(i,e[t]));return a},t={FRAMES:".kv-preview-thumb",SORT_CSS:"file-sortable",OBJECT_PARAMS:'<param name="controller" value="true" />\n<param name="allowFullScreen" value="true" />\n<param name="allowScriptAccess" value="always" />\n<param name="autoPlay" value="false" />\n<param name="autoStart" value="false" />\n<param name="quality" value="high" />\n',DEFAULT_PREVIEW:'<div class="file-preview-other">\n<span class="{previewFileIconClass}">{previewFileIcon}</span>\n</div>',MODAL_ID:"kvFileinputModal",MODAL_EVENTS:["show","shown","hide","hidden","loaded"],objUrl:window.URL||window.webkitURL,compare:function(e,t,i){return void 0!==e&&(i?e===t:e.match(t))},isIE:function(e){if("Microsoft Internet Explorer"!==navigator.appName)return!1;if(10===e)return new RegExp("msie\\s"+e,"i").test(navigator.userAgent);var t,i=document.createElement("div");return i.innerHTML="\x3c!--[if IE "+e+"]> <i></i> <![endif]--\x3e",t=i.getElementsByTagName("i").length,document.body.appendChild(i),i.parentNode.removeChild(i),t},initModal:function(t){var i=e("body");i.length&&t.appendTo(i)},isEmpty:function(t,i){return null==t||0===t.length||i&&""===e.trim(t)},isArray:function(e){return Array.isArray(e)||"[object Array]"===Object.prototype.toString.call(e)},ifSet:function(e,t,i){return i=i||"",t&&"object"==typeof t&&e in t?t[e]:i},cleanArray:function(e){return e instanceof Array||(e=[]),e.filter(function(e){return null!=e})},spliceArray:function(e,t){var i,a=0,n=[];if(!(e instanceof Array))return[];for(i=0;i<e.length;i++)i!==t&&(n[a]=e[i],a++);return n},getNum:function(e,t){return t=t||0,"number"==typeof e?e:("string"==typeof e&&(e=parseFloat(e)),isNaN(e)?t:e)},hasFileAPISupport:function(){return!(!window.File||!window.FileReader)},hasDragDropSupport:function(){var e=document.createElement("div");return!t.isIE(9)&&(void 0!==e.draggable||void 0!==e.ondragstart&&void 0!==e.ondrop)},hasFileUploadSupport:function(){return t.hasFileAPISupport()&&window.FormData},hasBlobSupport:function(){try{return!!window.Blob&&Boolean(new Blob)}catch(e){return!1}},hasArrayBufferViewSupport:function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(e){return!1}},dataURI2Blob:function(e){var i,a,n,r,s,o,l=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,d=t.hasBlobSupport();if(!((d||l)&&window.atob&&window.ArrayBuffer&&window.Uint8Array))return null;for(i=e.split(",")[0].indexOf("base64")>=0?atob(e.split(",")[1]):decodeURIComponent(e.split(",")[1]),a=new ArrayBuffer(i.length),n=new Uint8Array(a),r=0;r<i.length;r+=1)n[r]=i.charCodeAt(r);return s=e.split(",")[0].split(":")[1].split(";")[0],d?new Blob([t.hasArrayBufferViewSupport()?n:a],{type:s}):((o=new l).append(a),o.getBlob(s))},addCss:function(e,t){e.removeClass(t).addClass(t)},getElement:function(i,a,n){return t.isEmpty(i)||t.isEmpty(i[a])?n:e(i[a])},uniqId:function(){return Math.round((new Date).getTime())+"_"+Math.round(100*Math.random())},htmlEncode:function(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")},replaceTags:function(t,i){var a=t;return i?(e.each(i,function(e,t){"function"==typeof t&&(t=t()),a=a.split(e).join(t)}),a):a},cleanMemory:function(e){var i=e.is("img")?e.attr("src"):e.find("source").attr("src");t.objUrl.revokeObjectURL(i)},findFileName:function(e){var t=e.lastIndexOf("/");return-1===t&&(t=e.lastIndexOf("\\")),e.split(e.substring(t,t+1)).pop()},checkFullScreen:function(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement},toggleFullScreen:function(e){var i=document,a=i.documentElement;a&&e&&!t.checkFullScreen()?a.requestFullscreen?a.requestFullscreen():a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i.exitFullscreen?i.exitFullscreen():i.msExitFullscreen?i.msExitFullscreen():i.mozCancelFullScreen?i.mozCancelFullScreen():i.webkitExitFullscreen&&i.webkitExitFullscreen()},moveArray:function(e,t,i){if(i>=e.length)for(var a=i-e.length;1+a--;)e.push(void 0);return e.splice(i,0,e.splice(t,1)[0]),e},cleanZoomCache:function(e){var t=e.closest(".kv-zoom-cache-theme");t.length||(t=e.closest(".kv-zoom-cache")),t.remove()},setOrientation:function(e,t){var i,a,n=new DataView(e),r=0,s=1;if(65496!==n.getUint16(r)||e.length<2)t&&t();else{for(r+=2,i=n.byteLength;r<i-2;)switch(a=n.getUint16(r),r+=2,a){case 65505:i=n.getUint16(r)-r,r+=2;break;case 274:s=n.getUint16(r+6,!1),i=0}t&&t(s)}},validateOrientation:function(e,i){if(window.FileReader&&window.DataView){var a,n=new FileReader;n.onloadend=function(){a=n.result,t.setOrientation(a,i)},n.readAsArrayBuffer(e)}},adjustOrientedImage:function(e,t){var i;e.hasClass("is-portrait-gt4")&&(t?e.css({width:e.parent().height()}):(e.css({height:"auto",width:e.height()}),i=e.parent().offset().top-e.offset().top,e.css("margin-top",i)))}},(i=function(i,a){this.$element=e(i),this.$parent=this.$element.parent(),this._validate()&&(this.isPreviewable=t.hasFileAPISupport(),this.isIE9=t.isIE(9),this.isIE10=t.isIE(10),(this.isPreviewable||this.isIE9)&&(this._init(a),this._listen()),this.$element.removeClass("file-loading"))}).prototype={constructor:i,_cleanup:function(){this.reader=null,this.formdata={},this.uploadCount=0,this.uploadStatus={},this.uploadLog=[],this.uploadAsyncCount=0,this.loadedImages=[],this.totalImagesCount=0,this.ajaxRequests=[],this.clearStack(),this.fileInputCleared=!1,this.fileBatchCompleted=!0,this.isPreviewable||(this.showPreview=!1),this.isError=!1,this.ajaxAborted=!1,this.cancelling=!1},_init:function(i,a){var n,r,s,o=this,l=o.$element;o.options=i,e.each(i,function(e,i){switch(e){case"minFileCount":case"maxFileCount":case"minFileSize":case"maxFileSize":case"maxFilePreviewSize":case"resizeImageQuality":case"resizeIfSizeMoreThan":case"progressUploadThreshold":case"initialPreviewCount":case"zoomModalHeight":case"minImageHeight":case"maxImageHeight":case"minImageWidth":case"maxImageWidth":o[e]=t.getNum(i);break;default:o[e]=i}}),o.rtl&&(s=o.previewZoomButtonIcons.prev,o.previewZoomButtonIcons.prev=o.previewZoomButtonIcons.next,o.previewZoomButtonIcons.next=s),a||o._cleanup(),o.$form=l.closest("form"),o._initTemplateDefaults(),o.uploadFileAttr=t.isEmpty(l.attr("name"))?"file_data":l.attr("name"),r=o._getLayoutTemplate("progress"),o.progressTemplate=r.replace("{class}",o.progressClass),o.progressCompleteTemplate=r.replace("{class}",o.progressCompleteClass),o.progressErrorTemplate=r.replace("{class}",o.progressErrorClass),o.dropZoneEnabled=t.hasDragDropSupport()&&o.dropZoneEnabled,o.isDisabled=l.attr("disabled")||l.attr("readonly"),o.isDisabled&&l.attr("disabled",!0),o.isUploadable=t.hasFileUploadSupport()&&!t.isEmpty(o.uploadUrl),o.isClickable=o.browseOnZoneClick&&o.showPreview&&(o.isUploadable&&o.dropZoneEnabled||!t.isEmpty(o.defaultPreviewContent)),o.slug="function"==typeof i.slugCallback?i.slugCallback:o._slugDefault,o.mainTemplate=o.showCaption?o._getLayoutTemplate("main1"):o._getLayoutTemplate("main2"),o.captionTemplate=o._getLayoutTemplate("caption"),o.previewGenericTemplate=o._getPreviewTemplate("generic"),!o.imageCanvas&&o.resizeImage&&(o.maxImageWidth||o.maxImageHeight)&&(o.imageCanvas=document.createElement("canvas"),o.imageCanvasContext=o.imageCanvas.getContext("2d")),t.isEmpty(l.attr("id"))&&l.attr("id",t.uniqId()),o.namespace=".fileinput_"+l.attr("id").replace(/-/g,"_"),void 0===o.$container?o.$container=o._createContainer():o._refreshContainer(),n=o.$container,o.$dropZone=n.find(".file-drop-zone"),o.$progress=n.find(".kv-upload-progress"),o.$btnUpload=n.find(".fileinput-upload"),o.$captionContainer=t.getElement(i,"elCaptionContainer",n.find(".file-caption")),o.$caption=t.getElement(i,"elCaptionText",n.find(".file-caption-name")),o.$previewContainer=t.getElement(i,"elPreviewContainer",n.find(".file-preview")),o.$preview=t.getElement(i,"elPreviewImage",n.find(".file-preview-thumbnails")),o.$previewStatus=t.getElement(i,"elPreviewStatus",n.find(".file-preview-status")),o.$errorContainer=t.getElement(i,"elErrorContainer",o.$previewContainer.find(".kv-fileinput-error")),t.isEmpty(o.msgErrorClass)||t.addCss(o.$errorContainer,o.msgErrorClass),a||(o.$errorContainer.hide(),o.previewInitId="preview-"+t.uniqId(),o._initPreviewCache(),o._initPreview(!0),o._initPreviewActions(),o._setFileDropZoneTitle(),o.$parent.hasClass("file-loading")&&(o.$container.insertBefore(o.$parent),o.$parent.remove())),l.attr("disabled")&&o.disable(),o._initZoom(),o.hideThumbnailContent&&t.addCss(o.$preview,"hide-content")},_initTemplateDefaults:function(){var i,a,n,r,s,o,l,d,c=this;i='<div id="'+t.MODAL_ID+'" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="'+t.MODAL_ID+'Label"></div>',a='<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}" data-template="{template}"',n='<video class="kv-preview-data file-preview-video" controls {style}>\n<source src="{data}" type="{type}">\n'+t.DEFAULT_PREVIEW+"\n</video>\n",r='<audio class="kv-preview-data file-preview-audio" controls {style}>\n<source src="{data}" type="{type}">\n'+t.DEFAULT_PREVIEW+"\n</audio>\n",s='<object class="kv-preview-data file-preview-flash file-object" type="application/x-shockwave-flash" data="{data}" {style}>\n'+t.OBJECT_PARAMS+" "+t.DEFAULT_PREVIEW+"\n</object>\n",o='<object class="kv-preview-data file-preview-object file-object {typeCss}" data="{data}" type="{type}" {style}>\n<param name="movie" value="{caption}" />\n'+t.OBJECT_PARAMS+" "+t.DEFAULT_PREVIEW+"\n</object>\n",l='<div class="kv-preview-data file-preview-other-frame" {style}>\n'+t.DEFAULT_PREVIEW+"\n</div>\n",d={width:"100%",height:"100%","min-height":"480px"},c.defaults={layoutTemplates:{main1:'{preview}\n<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n<div class="input-group {class}">\n {caption}\n <div class="input-group-btn">\n {remove}\n {cancel}\n {upload}\n {browse}\n </div>\n</div>',main2:'{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',preview:'<div class="file-preview {class}">\n {close} <div class="{dropClass}">\n <div class="file-preview-thumbnails">\n </div>\n <div class="clearfix"></div> <div class="file-preview-status text-center text-success"></div>\n <div class="kv-fileinput-error"></div>\n </div>\n</div>',close:'<button type="button" class="close fileinput-remove">×</button>\n',fileIcon:'<i class="glyphicon glyphicon-file kv-caption-icon"></i>',caption:'<div tabindex="500" class="form-control file-caption {class}">\n <div class="file-caption-name"></div>\n</div>\n',modalMain:i,modal:'<div class="modal-dialog modal-lg{rtl}" role="document">\n <div class="modal-content">\n <div class="modal-header">\n <h5 class="modal-title">{heading}</h5>\n <span class="kv-zoom-title"></span>\n <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n </div>\n <div class="modal-body">\n <div class="floating-buttons"></div>\n <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n{prev} {next}\n </div>\n </div>\n</div>\n',progress:'<div class="progress">\n <div class="{class}" role="progressbar" aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n {status}\n </div>\n</div>',size:" <samp>({sizeText})</samp>",footer:'<div class="file-thumbnail-footer">\n <div class="file-footer-caption" title="{caption}">\n <div class="file-caption-info">{caption}</div>\n <div class="file-size-info">{size}</div>\n </div>\n {progress}\n{indicator}\n{actions}\n</div>',indicator:'<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>',actions:'<div class="file-actions">\n <div class="file-footer-buttons">\n {download} {upload} {delete} {zoom} {other} </div>\n</div>\n{drag}\n<div class="clearfix"></div>',actionDelete:'<button type="button" class="kv-file-remove {removeClass}" title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n',actionUpload:'<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">{uploadIcon}</button>',actionDownload:'<a href="{downloadUrl}" class="{downloadClass}" title="{downloadTitle}" download="{caption}">{downloadIcon}</a>',actionZoom:'<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>',actionDrag:'<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>',btnDefault:'<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</button>',btnLink:'<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>',btnBrowse:'<div tabindex="500" class="{css}" {status}>{icon} {label}</div>',zoomCache:'<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>'},previewMarkupTags:{tagBefore1:'<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}" data-template="{template}"><div class="kv-file-content">\n',tagBefore2:'<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}" data-template="{template}" title="{caption}"><div class="kv-file-content">\n',tagAfter:"</div>{footer}\n</div>\n"},previewContentTemplates:{generic:"{content}\n",html:'<div class="kv-preview-data file-preview-html" title="{caption}" {style}>{data}</div>\n',image:'<img src="{data}" class="file-preview-image kv-preview-data" title="{caption}" alt="{caption}" {style}>\n',text:'<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly {style}>{data}</textarea {style}>\n',video:n,audio:r,flash:s,object:o,pdf:'<embed class="kv-preview-data file-preview-pdf" src="{data}" type="application/pdf" {style}>\n',other:l},allowedPreviewTypes:["image","html","text","video","audio","flash","pdf","object"],previewTemplates:{},previewSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"213px",height:"160px"},text:{width:"213px",height:"160px"},video:{width:"213px",height:"160px"},audio:{width:"100%",height:"30px"},flash:{width:"213px",height:"160px"},object:{width:"213px",height:"160px"},pdf:{width:"213px",height:"160px"},other:{width:"213px",height:"160px"}},previewSettingsSmall:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:{width:"100%",height:"160px"},text:{width:"100%",height:"160px"},video:{width:"100%",height:"auto"},audio:{width:"100%",height:"30px"},flash:{width:"100%",height:"auto"},object:{width:"100%",height:"auto"},pdf:{width:"100%",height:"160px"},other:{width:"100%",height:"160px"}},previewZoomSettings:{image:{width:"auto",height:"auto","max-width":"100%","max-height":"100%"},html:d,text:d,video:{width:"auto",height:"100%","max-width":"100%"},audio:{width:"100%",height:"30px"},flash:{width:"auto",height:"480px"},object:{width:"auto",height:"100%","max-width":"100%","min-height":"480px"},pdf:d,other:{width:"auto",height:"100%","min-height":"480px"}},fileTypeSettings:{image:function(e,i){return t.compare(e,"image.*")||t.compare(i,/\.(gif|png|jpe?g)$/i)},html:function(e,i){return t.compare(e,"text/html")||t.compare(i,/\.(htm|html)$/i)},text:function(e,i){return t.compare(e,"text.*")||t.compare(i,/\.(xml|javascript)$/i)||t.compare(i,/\.(txt|md|csv|nfo|ini|json|php|js|css)$/i)},video:function(e,i){return t.compare(e,"video.*")&&(t.compare(e,/(ogg|mp4|mp?g|mov|webm|3gp)$/i)||t.compare(i,/\.(og?|mp4|webm|mp?g|mov|3gp)$/i))},audio:function(e,i){return t.compare(e,"audio.*")&&(t.compare(i,/(ogg|mp3|mp?g|wav)$/i)||t.compare(i,/\.(og?|mp3|mp?g|wav)$/i))},flash:function(e,i){return t.compare(e,"application/x-shockwave-flash",!0)||t.compare(i,/\.(swf)$/i)},pdf:function(e,i){return t.compare(e,"application/pdf",!0)||t.compare(i,/\.(pdf)$/i)},object:function(){return!0},other:function(){return!0}},fileActionSettings:{showRemove:!0,showUpload:!0,showDownload:!0,showZoom:!0,showDrag:!0,removeIcon:'<i class="glyphicon glyphicon-trash"></i>',removeClass:"btn btn-sm btn-default btn-outline-secondary",removeErrorClass:"btn btn-sm btn-danger",removeTitle:"Remove file",uploadIcon:'<i class="glyphicon glyphicon-upload"></i>',uploadClass:"btn btn-sm btn-default btn-outline-secondary",uploadTitle:"Upload file",uploadRetryIcon:'<i class="glyphicon glyphicon-repeat"></i>',uploadRetryTitle:"Retry upload",downloadIcon:'<i class="glyphicon glyphicon-download"></i>',downloadClass:"btn btn-sm btn-default btn-outline-secondary",downloadTitle:"Download file",zoomIcon:'<i class="fa fa-search-plus"></i>',zoomClass:"btn btn-sm btn-default btn-outline-secondary",zoomTitle:"View Details",dragIcon:'<i class="glyphicon glyphicon-move"></i>',dragClass:"text-info",dragTitle:"Move / Rearrange",dragSettings:{},indicatorNew:'<i class="glyphicon glyphicon-plus-sign text-warning"></i>',indicatorSuccess:'<i class="glyphicon glyphicon-ok-sign text-success"></i>',indicatorError:'<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',indicatorLoading:'<i class="glyphicon glyphicon-hourglass text-muted"></i>',indicatorNewTitle:"Not uploaded yet",indicatorSuccessTitle:"Uploaded",indicatorErrorTitle:"Upload Error",indicatorLoadingTitle:"Uploading ..."}},e.each(c.defaults,function(t,i){"allowedPreviewTypes"!==t?c[t]=e.extend(!0,{},i,c[t]):void 0===c.allowedPreviewTypes&&(c.allowedPreviewTypes=i)}),c._initPreviewTemplates()},_initPreviewTemplates:function(){var i,a=this,n=a.defaults,r=a.previewMarkupTags,s=r.tagAfter;e.each(n.previewContentTemplates,function(e,n){t.isEmpty(a.previewTemplates[e])&&(i=r.tagBefore2,"generic"!==e&&"image"!==e&&"html"!==e&&"text"!==e||(i=r.tagBefore1),a.previewTemplates[e]=i+n+s)})},_initPreviewCache:function(){var i=this;i.previewCache={data:{},init:function(){var e=i.initialPreview;e.length>0&&!t.isArray(e)&&(e=e.split(i.initialPreviewDelimiter)),i.previewCache.data={content:e,config:i.initialPreviewConfig,tags:i.initialPreviewThumbTags}},count:function(){return i.previewCache.data&&i.previewCache.data.content?i.previewCache.data.content.length:0},get:function(a,n){var r,s,o,l,d,c,h,p="init_"+a,u=i.previewCache.data,f=u.config[a],m=u.content[a],g=i.previewInitId+"-"+p,v=t.ifSet("previewAsData",f,i.initialPreviewAsData),w=function(e,a,n,r,s,o,l,d,c){return d=" file-preview-initial "+t.SORT_CSS+(d?" "+d:""),i._generatePreviewTemplate(e,a,n,r,s,!1,null,d,o,l,c)};return m?(n=void 0===n||n,o=t.ifSet("type",f,i.initialPreviewFileType||"generic"),d=t.ifSet("filename",f,t.ifSet("caption",f)),c=t.ifSet("filetype",f,o),l=i.previewCache.footer(a,n,f&&f.size||null),h=t.ifSet("frameClass",f),r=v?w(o,m,d,c,g,l,p,h):w("generic",m,d,c,g,l,p,h,o).setTokens({content:u.content[a]}),u.tags.length&&u.tags[a]&&(r=t.replaceTags(r,u.tags[a])),t.isEmpty(f)||t.isEmpty(f.frameAttr)||((s=e(document.createElement("div")).html(r)).find(".file-preview-initial").attr(f.frameAttr),r=s.html(),s.remove()),r):""},add:function(e,a,n,r){var s,o=i.previewCache.data;return t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),r?(s=o.content.push(e)-1,o.config[s]=a,o.tags[s]=n):(s=e.length-1,o.content=e,o.config=a,o.tags=n),i.previewCache.data=o,s},set:function(e,a,n,r){var s,o=i.previewCache.data;if(e&&e.length&&(t.isArray(e)||(e=e.split(i.initialPreviewDelimiter)),e.filter(function(e){return null!==e}).length)){if(void 0===o.content&&(o.content=[]),void 0===o.config&&(o.config=[]),void 0===o.tags&&(o.tags=[]),r){for(s=0;s<e.length;s++)e[s]&&o.content.push(e[s]);for(s=0;s<a.length;s++)a[s]&&o.config.push(a[s]);for(s=0;s<n.length;s++)n[s]&&o.tags.push(n[s])}else o.content=e,o.config=a,o.tags=n;i.previewCache.data=o}},unset:function(e){var t=i.previewCache.count();if(t){if(1===t)return i.previewCache.data.content=[],i.previewCache.data.config=[],i.previewCache.data.tags=[],i.initialPreview=[],i.initialPreviewConfig=[],void(i.initialPreviewThumbTags=[]);i.previewCache.data.content.splice(e,1),i.previewCache.data.config.splice(e,1),i.previewCache.data.tags.splice(e,1)}},out:function(){var e,t="",a=i.previewCache.count();if(0===a)return{content:"",caption:""};for(e=0;e<a;e++)t+=i.previewCache.get(e);return{content:t,caption:i._getMsgSelected(a)}},footer:function(e,a,n){var r=i.previewCache.data;if(!r||!r.config||0===r.config.length||t.isEmpty(r.config[e]))return"";a=void 0===a||a;var s,o=r.config[e],l=t.ifSet("caption",o),d=t.ifSet("width",o,"auto"),c=t.ifSet("url",o,!1),h=t.ifSet("key",o,null),p=i.fileActionSettings,u=i.initialPreviewShowDelete||!1,f=o.downloadUrl||i.initialPreviewDownloadUrl||"",m=o.filename||o.caption||"",g=!!f,v=t.ifSet("showDelete",o,t.ifSet("showDelete",p,u)),w=t.ifSet("showDownload",o,t.ifSet("showDownload",p,g)),_=t.ifSet("showZoom",o,t.ifSet("showZoom",p,!0)),b=t.ifSet("showDrag",o,t.ifSet("showDrag",p,!0)),C=!1===c&&a;return w=w&&!1!==o.downloadUrl&&!!f,s=i._renderFileActions(!1,w,v,_,b,C,c,h,!0,f,m),i._getLayoutTemplate("footer").setTokens({progress:i._renderThumbProgress(),actions:s,caption:l,size:i._getSize(n),width:d,indicator:""})}},i.previewCache.init()},_handler:function(e,t,i){var a=this.namespace,n=t.split(" ").join(a+" ")+a;e&&e.length&&e.off(n).on(n,i)},_log:function(e){var t=this.$element.attr("id");t&&(e='"'+t+'": '+e),void 0!==window.console.log?window.console.log(e):window.alert(e)},_validate:function(){var e="file"===this.$element.attr("type");return e||this._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.'),e},_errorsExist:function(){var t;return!!this.$errorContainer.find("li").length||((t=e(document.createElement("div")).html(this.$errorContainer.html())).find(".kv-error-close").remove(),t.find("ul").remove(),!!e.trim(t.text()).length)},_errorHandler:function(e,t){var i=this,a=e.target.error,n=function(e){i._showError(e.replace("{name}",t))};a.code===a.NOT_FOUND_ERR?n(i.msgFileNotFound):a.code===a.SECURITY_ERR?n(i.msgFileSecured):a.code===a.NOT_READABLE_ERR?n(i.msgFileNotReadable):a.code===a.ABORT_ERR?n(i.msgFilePreviewAborted):n(i.msgFilePreviewError)},_addError:function(e){var t=this.$errorContainer;e&&t.length&&(t.html(this.errorCloseButton+e),this._handler(t.find(".kv-error-close"),"click",function(){t.fadeOut("slow")}))},_resetErrors:function(e){var t=this.$errorContainer;this.isError=!1,this.$container.removeClass("has-error"),t.html(""),e?t.fadeOut("slow"):t.hide()},_showFolderError:function(e){var i,a=this.$errorContainer;e&&(i=this.msgFoldersNotAllowed.replace("{n}",e),this._addError(i),t.addCss(this.$container,"has-error"),a.fadeIn(800),this._raise("filefoldererror",[e,i]))},_showUploadError:function(e,i,a){var n=this.$errorContainer,r=a||"fileuploaderror",s=i&&i.id?'<li data-file-id="'+i.id+'">'+e+"</li>":"<li>"+e+"</li>";return 0===n.find("ul").length?this._addError("<ul>"+s+"</ul>"):n.find("ul").append(s),n.fadeIn(800),this._raise(r,[i,e]),this.$container.removeClass("file-input-new"),t.addCss(this.$container,"has-error"),!0},_showError:function(e,i,a){var n=this.$errorContainer,r=a||"fileerror";return(i=i||{}).reader=this.reader,this._addError(e),n.fadeIn(800),this._raise(r,[i,e]),this.isUploadable||this._clearFileInput(),this.$container.removeClass("file-input-new"),t.addCss(this.$container,"has-error"),this.$btnUpload.attr("disabled",!0),!0},_noFilesError:function(e){var i=this.minFileCount>1?this.filePlural:this.fileSingle,a=this.msgFilesTooLess.replace("{n}",this.minFileCount).replace("{files}",i),n=this.$errorContainer;this._addError(a),this.isError=!0,this._updateFileDetails(0),n.fadeIn(800),this._raise("fileerror",[e,a]),this._clearFileInput(),t.addCss(this.$container,"has-error")},_parseError:function(t,i,a,n){var r,s=e.trim(a+""),o=void 0!==i.responseJSON&&void 0!==i.responseJSON.error?i.responseJSON.error:i.responseText;return this.cancelling&&this.msgUploadAborted&&(s=this.msgUploadAborted),this.showAjaxErrorDetails&&o&&(r=(o=e.trim(o.replace(/\n\s*\n/g,"\n"))).length?"<pre>"+o+"</pre>":"",s+=s?r:o),s||(s=this.msgAjaxError.replace("{operation}",t)),this.cancelling=!1,n?"<b>"+n+": </b>"+s:s},_parseFileType:function(e){var i,a,n,r=this.allowedPreviewTypes||[];for(n=0;n<r.length;n++)if(a=r[n],i=(0,this.fileTypeSettings[a])(e.type,e.name)?a:"",!t.isEmpty(i))return i;return"other"},_getPreviewIcon:function(t){var i,a=this,n=null;return t&&t.indexOf(".")>-1&&(i=t.split(".").pop(),a.previewFileIconSettings&&(n=a.previewFileIconSettings[i]||a.previewFileIconSettings[i.toLowerCase()]||null),a.previewFileExtSettings&&e.each(a.previewFileExtSettings,function(e,t){a.previewFileIconSettings[e]&&t(i)&&(n=a.previewFileIconSettings[e])})),n},_parseFilePreviewIcon:function(e,t){var i=this._getPreviewIcon(t)||this.previewFileIcon,a=e;return a.indexOf("{previewFileIcon}")>-1&&(a=a.setTokens({previewFileIconClass:this.previewFileIconClass,previewFileIcon:i})),a},_raise:function(t,i){var a=e.Event(t);if(void 0!==i?this.$element.trigger(a,i):this.$element.trigger(a),a.isDefaultPrevented()||!1===a.result)return!1;switch(t){case"filebatchuploadcomplete":case"filebatchuploadsuccess":case"fileuploaded":case"fileclear":case"filecleared":case"filereset":case"fileerror":case"filefoldererror":case"fileuploaderror":case"filebatchuploaderror":case"filedeleteerror":case"filecustomerror":case"filesuccessremove":break;default:this.ajaxAborted||(this.ajaxAborted=a.result)}return!0},_listenFullScreen:function(e){var t,i,a=this.$modal;a&&a.length&&(t=a&&a.find(".btn-fullscreen"),i=a&&a.find(".btn-borderless"),t.length&&i.length&&(t.removeClass("active").attr("aria-pressed","false"),i.removeClass("active").attr("aria-pressed","false"),e?t.addClass("active").attr("aria-pressed","true"):i.addClass("active").attr("aria-pressed","true"),a.hasClass("file-zoom-fullscreen")?this._maximizeZoomDialog():e?this._maximizeZoomDialog():i.removeClass("active").attr("aria-pressed","false")))},_listen:function(){var i=this,a=i.$element,n=i.$form,r=i.$container;i._handler(a,"change",e.proxy(i._change,i)),i.showBrowse&&i._handler(i.$btnFile,"click",e.proxy(i._browse,i)),i._handler(r.find(".fileinput-remove:not([disabled])"),"click",e.proxy(i.clear,i)),i._handler(r.find(".fileinput-cancel"),"click",e.proxy(i.cancel,i)),i._initDragDrop(),i._handler(n,"reset",e.proxy(i.clear,i)),i.isUploadable||i._handler(n,"submit",e.proxy(i._submitForm,i)),i._handler(i.$container.find(".fileinput-upload"),"click",e.proxy(i._uploadClick,i)),i._handler(e(window),"resize",function(){i._listenFullScreen(screen.width===window.innerWidth&&screen.height===window.innerHeight)}),i._handler(e(document),"webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",function(){i._listenFullScreen(t.checkFullScreen())}),i._autoFitContent(),i._initClickable()},_autoFitContent:function(){var t,i=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=this,n=i<400?a.previewSettingsSmall||a.defaults.previewSettingsSmall:a.previewSettings||a.defaults.previewSettings;e.each(n,function(e,i){t=".file-preview-frame .file-preview-"+e,a.$preview.find(t+".kv-preview-data,"+t+" .kv-preview-data").css(i)})},_initClickable:function(){var i,a=this;a.isClickable&&(i=a.isUploadable?a.$dropZone:a.$preview.find(".file-default-preview"),t.addCss(i,"clickable"),i.attr("tabindex",-1),a._handler(i,"click",function(t){var n=e(t.target);n.parents(".file-preview-thumbnails").length&&!n.parents(".file-default-preview").length||(a.$element.trigger("click"),i.blur())}))},_initDragDrop:function(){var t=this.$dropZone;this.isUploadable&&this.dropZoneEnabled&&this.showPreview&&(this._handler(t,"dragenter dragover",e.proxy(this._zoneDragEnter,this)),this._handler(t,"dragleave",e.proxy(this._zoneDragLeave,this)),this._handler(t,"drop",e.proxy(this._zoneDrop,this)),this._handler(e(document),"dragenter dragover drop",this._zoneDragDropInit))},_zoneDragDropInit:function(e){e.stopPropagation(),e.preventDefault()},_zoneDragEnter:function(i){var a=e.inArray("Files",i.originalEvent.dataTransfer.types)>-1;if(this._zoneDragDropInit(i),this.isDisabled||!a)return i.originalEvent.dataTransfer.effectAllowed="none",void(i.originalEvent.dataTransfer.dropEffect="none");t.addCss(this.$dropZone,"file-highlighted")},_zoneDragLeave:function(e){this._zoneDragDropInit(e),this.isDisabled||this.$dropZone.removeClass("file-highlighted")},_zoneDrop:function(e){e.preventDefault(),this.isDisabled||t.isEmpty(e.originalEvent.dataTransfer.files)||(this._change(e,"dragdrop"),this.$dropZone.removeClass("file-highlighted"))},_uploadClick:function(e){var i,a=this.$container.find(".fileinput-upload"),n=!a.hasClass("disabled")&&t.isEmpty(a.attr("disabled"));e&&e.isDefaultPrevented()||(this.isUploadable?(e.preventDefault(),n&&this.upload()):n&&"submit"!==a.attr("type")&&((i=a.closest("form")).length&&i.trigger("submit"),e.preventDefault()))},_submitForm:function(){return this._isFileSelectionValid()&&!this._abort({})},_clearPreview:function(){var i=this.$preview;(this.showUploadedThumbs?this.getFrames(":not(.file-preview-success)"):this.getFrames()).each(function(){var a=e(this);a.remove(),t.cleanZoomCache(i.find("#zoom-"+a.attr("id")))}),this.getFrames().length&&this.showPreview||this._resetUpload(),this._validateDefaultPreview()},_initSortable:function(){var i,a=this,n=a.$preview,r="."+t.SORT_CSS;window.KvSortable&&0!==n.find(r).length&&(i={handle:".drag-handle-init",dataIdAttr:"data-preview-id",scroll:!1,draggable:r,onSort:function(i){var n,r=i.oldIndex,s=i.newIndex;a.initialPreview=t.moveArray(a.initialPreview,r,s),a.initialPreviewConfig=t.moveArray(a.initialPreviewConfig,r,s),a.previewCache.init();for(var o=0;o<a.initialPreviewConfig.length;o++)null!==a.initialPreviewConfig[o]&&(n=a.initialPreviewConfig[o].key,e(".kv-file-remove[data-key='"+n+"']").closest(t.FRAMES).attr("data-fileindex","init_"+o).attr("data-fileindex","init_"+o));a._raise("filesorted",{previewId:e(i.item).attr("id"),oldIndex:r,newIndex:s,stack:a.initialPreviewConfig})}},n.data("kvsortable")&&n.kvsortable("destroy"),e.extend(!0,i,a.fileActionSettings.dragSettings),n.kvsortable(i))},_setPreviewContent:function(e){this.$preview.html(e),this._autoFitContent()},_initPreview:function(e){var i,a=this.initialCaption||"";if(!this.previewCache.count())return this._clearPreview(),void(e?this._setCaption(a):this._initCaption());i=this.previewCache.out(),a=e&&this.initialCaption?this.initialCaption:i.caption,this._setPreviewContent(i.content),this._setInitThumbAttr(),this._setCaption(a),this._initSortable(),t.isEmpty(i.content)||this.$container.removeClass("file-input-new")},_getZoomButton:function(e){var t=this.previewZoomButtonIcons[e],i=this.previewZoomButtonClasses[e],a=' title="'+(this.previewZoomButtonTitles[e]||"")+'" '+("close"===e?' data-dismiss="modal" aria-hidden="true"':"");return"fullscreen"!==e&&"borderless"!==e&&"toggleheader"!==e||(a+=' data-toggle="button" aria-pressed="false" autocomplete="off"'),'<button type="button" class="'+i+" btn-"+e+'"'+a+">"+t+"</button>"},_getModalContent:function(){return this._getLayoutTemplate("modal").setTokens({rtl:this.rtl?" kv-rtl":"",zoomFrameClass:this.frameClass,heading:this.msgZoomModalHeading,prev:this._getZoomButton("prev"),next:this._getZoomButton("next"),toggleheader:this._getZoomButton("toggleheader"),fullscreen:this._getZoomButton("fullscreen"),borderless:this._getZoomButton("borderless"),close:this._getZoomButton("close")})},_listenModalEvent:function(e){var i=this,a=i.$modal;a.on(e+".bs.modal",function(n){var r=a.find(".btn-fullscreen"),s=a.find(".btn-borderless");i._raise("filezoom"+e,function(e){return{sourceEvent:e,previewId:a.data("previewId"),modal:a}}(n)),"shown"===e&&(s.removeClass("active").attr("aria-pressed","false"),r.removeClass("active").attr("aria-pressed","false"),a.hasClass("file-zoom-fullscreen")&&(i._maximizeZoomDialog(),t.checkFullScreen()?r.addClass("active").attr("aria-pressed","true"):s.addClass("active").attr("aria-pressed","true")))})},_initZoom:function(){var i,a=this,n=a._getLayoutTemplate("modalMain"),r="#"+t.MODAL_ID;a.showPreview&&(a.$modal=e(r),a.$modal&&a.$modal.length||(i=e(document.createElement("div")).html(n).insertAfter(a.$container),a.$modal=e(r).insertBefore(i),i.remove()),t.initModal(a.$modal),a.$modal.html(a._getModalContent()),e.each(t.MODAL_EVENTS,function(e,t){a._listenModalEvent(t)}))},_initZoomButtons:function(){var t,i,a=this.$modal.data("previewId")||"",n=this.getFrames().toArray(),r=n.length,s=this.$modal.find(".btn-prev"),o=this.$modal.find(".btn-next");if(n.length<2)return s.hide(),void o.hide();s.show(),o.show(),r&&(t=e(n[0]),i=e(n[r-1]),s.removeAttr("disabled"),o.removeAttr("disabled"),t.length&&t.attr("id")===a&&s.attr("disabled",!0),i.length&&i.attr("id")===a&&o.attr("disabled",!0))},_maximizeZoomDialog:function(){var t=this.$modal,i=t.find(".modal-header:visible"),a=t.find(".modal-footer:visible"),n=t.find(".modal-body"),r=e(window).height();t.addClass("file-zoom-fullscreen"),i&&i.length&&(r-=i.outerHeight(!0)),a&&a.length&&(r-=a.outerHeight(!0)),n&&n.length&&(r-=n.outerHeight(!0)-n.height()),t.find(".kv-zoom-body").height(r)},_resizeZoomDialog:function(e){var i=this.$modal,a=i.find(".btn-fullscreen"),n=i.find(".btn-borderless");if(i.hasClass("file-zoom-fullscreen"))t.toggleFullScreen(!1),e?a.hasClass("active")||(i.removeClass("file-zoom-fullscreen"),this._resizeZoomDialog(!0),n.hasClass("active")&&n.removeClass("active").attr("aria-pressed","false")):a.hasClass("active")?a.removeClass("active").attr("aria-pressed","false"):(i.removeClass("file-zoom-fullscreen"),this.$modal.find(".kv-zoom-body").css("height",this.zoomModalHeight));else{if(!e)return void this._maximizeZoomDialog();t.toggleFullScreen(!0)}i.focus()},_setZoomContent:function(i,a){var n,r,s,o,l,d,c,h,p=this,u=i.attr("id"),f=p.$modal,m=f.find(".btn-prev"),g=f.find(".btn-next"),v=f.find(".btn-fullscreen"),w=f.find(".btn-borderless"),_=f.find(".btn-toggleheader"),b=p.$preview.find("#zoom-"+u);r=b.attr("data-template")||"generic",s=(n=b.find(".kv-file-content")).length?n.html():"",o=(i.data("caption")||"")+" "+(i.data("size")||""),f.find(".kv-zoom-title").html(o),l=f.find(".kv-zoom-body"),f.removeClass("kv-single-content"),a?(h=l.addClass("file-thumb-loading").clone().insertAfter(l),l.html(s).hide(),h.fadeOut("fast",function(){l.fadeIn("fast",function(){l.removeClass("file-thumb-loading")}),h.remove()})):l.html(s),(c=p.previewZoomSettings[r])&&(d=l.find(".kv-preview-data"),t.addCss(d,"file-zoom-detail"),e.each(c,function(e,t){d.css(e,t),(d.attr("width")&&"width"===e||d.attr("height")&&"height"===e)&&d.removeAttr(e)})),f.data("previewId",u);var C=l.find("img");C.length&&t.adjustOrientedImage(C,!0),p._handler(m,"click",function(){p._zoomSlideShow("prev",u)}),p._handler(g,"click",function(){p._zoomSlideShow("next",u)}),p._handler(v,"click",function(){p._resizeZoomDialog(!0)}),p._handler(w,"click",function(){p._resizeZoomDialog(!1)}),p._handler(_,"click",function(){var e,t=f.find(".modal-header"),i=f.find(".modal-body .floating-buttons"),a=t.find(".kv-zoom-actions"),n=function(e){var i=p.$modal.find(".kv-zoom-body"),a=p.zoomModalHeight;f.hasClass("file-zoom-fullscreen")&&(a=i.outerHeight(!0),e||(a-=t.outerHeight(!0))),i.css("height",e?a+e:a)};t.is(":visible")?(e=t.outerHeight(!0),t.slideUp("slow",function(){a.find(".btn").appendTo(i),n(e)})):(i.find(".btn").appendTo(a),t.slideDown("slow",function(){n()})),f.focus()}),p._handler(f,"keydown",function(e){var t=e.which||e.keyCode;37!==t||m.attr("disabled")||p._zoomSlideShow("prev",u),39!==t||g.attr("disabled")||p._zoomSlideShow("next",u)})},_zoomPreview:function(e){var i,a=this.$modal;if(!e.length)throw"Cannot zoom to detailed preview!";t.initModal(a),a.html(this._getModalContent()),i=e.closest(t.FRAMES),this._setZoomContent(i),a.modal("show"),this._initZoomButtons()},_zoomSlideShow:function(t,i){var a,n,r,s=this.$modal.find(".kv-zoom-actions .btn-"+t),o=this.getFrames().toArray(),l=o.length;if(!s.attr("disabled")){for(n=0;n<l;n++)if(e(o[n]).attr("id")===i){r="prev"===t?n-1:n+1;break}r<0||r>=l||!o[r]||((a=e(o[r])).length&&this._setZoomContent(a,!0),this._initZoomButtons(),this._raise("filezoom"+t,{previewId:i,modal:this.$modal}))}},_initZoomButton:function(){var t=this;t.$preview.find(".kv-file-zoom").each(function(){var i=e(this);t._handler(i,"click",function(){t._zoomPreview(i)})})},_clearObjects:function(t){t.find("video audio").each(function(){this.pause(),e(this).remove()}),t.find("img object div").each(function(){e(this).remove()})},_clearFileInput:function(){var i,a,n,r=this.$element;this.fileInputCleared=!0,t.isEmpty(r.val())||(this.isIE9||this.isIE10?(i=r.closest("form"),a=e(document.createElement("form")),n=e(document.createElement("div")),r.before(n),i.length?i.after(a):n.after(a),a.append(r).trigger("reset"),n.before(r).remove(),a.remove()):r.val(""))},_resetUpload:function(){this.uploadCache={content:[],config:[],tags:[],append:!0},this.uploadCount=0,this.uploadStatus={},this.uploadLog=[],this.uploadAsyncCount=0,this.loadedImages=[],this.totalImagesCount=0,this.$btnUpload.removeAttr("disabled"),this._setProgress(0),this.$progress.hide(),this._resetErrors(!1),this.ajaxAborted=!1,this.ajaxRequests=[],this._resetCanvas(),this.cacheInitialPreview={},this.overwriteInitial&&(this.initialPreview=[],this.initialPreviewConfig=[],this.initialPreviewThumbTags=[],this.previewCache.data={content:[],config:[],tags:[]})},_resetCanvas:function(){this.canvas&&this.imageCanvasContext&&this.imageCanvasContext.clearRect(0,0,this.canvas.width,this.canvas.height)},_hasInitialPreview:function(){return!this.overwriteInitial&&this.previewCache.count()},_resetPreview:function(){var e,t;this.previewCache.count()?(e=this.previewCache.out(),this._setPreviewContent(e.content),this._setInitThumbAttr(),t=this.initialCaption?this.initialCaption:e.caption,this._setCaption(t)):(this._clearPreview(),this._initCaption()),this.showPreview&&(this._initZoom(),this._initSortable())},_clearDefaultPreview:function(){this.$preview.find(".file-default-preview").remove()},_validateDefaultPreview:function(){this.showPreview&&!t.isEmpty(this.defaultPreviewContent)&&(this._setPreviewContent('<div class="file-default-preview">'+this.defaultPreviewContent+"</div>"),this.$container.removeClass("file-input-new"),this._initClickable())},_resetPreviewThumbs:function(e){var t;if(e)return this._clearPreview(),void this.clearStack();this._hasInitialPreview()?(t=this.previewCache.out(),this._setPreviewContent(t.content),this._setInitThumbAttr(),this._setCaption(t.caption),this._initPreviewActions()):this._clearPreview()},_getLayoutTemplate:function(e){var i=this.layoutTemplates[e];return t.isEmpty(this.customLayoutTags)?i:t.replaceTags(i,this.customLayoutTags)},_getPreviewTemplate:function(e){var i=this.previewTemplates[e];return t.isEmpty(this.customPreviewTags)?i:t.replaceTags(i,this.customPreviewTags)},_getOutData:function(e,t,i){return e=e||{},t=t||{},i=i||this.filestack.slice(0)||{},{form:this.formdata,files:i,filenames:this.filenames,filescount:this.getFilesCount(),extra:this._getExtraData(),response:t,reader:this.reader,jqXHR:e}},_getMsgSelected:function(e){var t=1===e?this.fileSingle:this.filePlural;return e>0?this.msgSelected.replace("{n}",e).replace("{files}",t):this.msgNoFilesSelected},_getFrame:function(t){var i=e("#"+t);return i.length?i:(this._log('Invalid thumb frame with id: "'+t+'".'),null)},_getThumbs:function(e){return e=e||"",this.getFrames(":not(.file-preview-initial)"+e)},_getExtraData:function(e,t){var i=this.uploadExtraData;return"function"==typeof this.uploadExtraData&&(i=this.uploadExtraData(e,t)),i},_initXhr:function(e,t,i){var a=this;return e.upload&&e.upload.addEventListener("progress",function(e){var n=0,r=e.total,s=e.loaded||e.position;e.lengthComputable&&(n=Math.floor(s/r*100)),t?a._setAsyncUploadStatus(t,n,i):a._setProgress(n)},!1),e},_mergeAjaxCallback:function(e,t,i){var a,n=this.ajaxSettings,r=this.mergeAjaxCallbacks;"delete"===i&&(n=this.ajaxDeleteSettings,r=this.mergeAjaxDeleteCallbacks),a=n[e],n[e]=r&&"function"==typeof a?"before"===r?function(){a.apply(this,arguments),t.apply(this,arguments)}:function(){t.apply(this,arguments),a.apply(this,arguments)}:t,"delete"===i?this.ajaxDeleteSettings=n:this.ajaxSettings=n},_ajaxSubmit:function(t,i,a,n,r,s){var o,l=this;l._raise("filepreajax",[r,s])&&(l._uploadExtra(r,s),l._mergeAjaxCallback("beforeSend",t),l._mergeAjaxCallback("success",i),l._mergeAjaxCallback("complete",a),l._mergeAjaxCallback("error",n),o=e.extend(!0,{},{xhr:function(){var t=e.ajaxSettings.xhr();return l._initXhr(t,r,l.getFileStack().length)},url:s&&l.uploadUrlThumb?l.uploadUrlThumb:l.uploadUrl,type:"POST",dataType:"json",data:l.formdata,cache:!1,processData:!1,contentType:!1},l.ajaxSettings),l.ajaxRequests.push(e.ajax(o)))},_mergeArray:function(e,i){var a=t.cleanArray(this[e]),n=t.cleanArray(i);this[e]=a.concat(n)},_initUploadSuccess:function(i,a,n){var r,s,o,l,d,c,h,p,u,f=this;f.showPreview&&"object"==typeof i&&!e.isEmptyObject(i)&&void 0!==i.initialPreview&&i.initialPreview.length>0&&(f.hasInitData=!0,c=i.initialPreview||[],h=i.initialPreviewConfig||[],p=i.initialPreviewThumbTags||[],r=void 0===i.append||i.append,c.length>0&&!t.isArray(c)&&(c=c.split(f.initialPreviewDelimiter)),f._mergeArray("initialPreview",c),f._mergeArray("initialPreviewConfig",h),f._mergeArray("initialPreviewThumbTags",p),void 0!==a?n?(u=a.attr("data-fileindex"),f.uploadCache.content[u]=c[0],f.uploadCache.config[u]=h[0]||[],f.uploadCache.tags[u]=p[0]||[],f.uploadCache.append=r):(o=f.previewCache.add(c,h[0],p[0],r),s=f.previewCache.get(o,!1),(d=(l=e(document.createElement("div")).html(s).hide().insertAfter(a)).find(".kv-zoom-cache"))&&d.length&&d.insertAfter(a),a.fadeOut("slow",function(){var e=l.find(".file-preview-frame");e&&e.length&&e.insertBefore(a).fadeIn("slow").css("display:inline-block"),f._initPreviewActions(),f._clearFileInput(),t.cleanZoomCache(f.$preview.find("#zoom-"+a.attr("id"))),a.remove(),l.remove(),f._initSortable()})):(f.previewCache.set(c,h,p,r),f._initPreview(),f._initPreviewActions()))},_initSuccessThumbs:function(){var i=this;i.showPreview&&i._getThumbs(t.FRAMES+".file-preview-success").each(function(){var a=e(this),n=i.$preview,r=a.find(".kv-file-remove");r.removeAttr("disabled"),i._handler(r,"click",function(){var e=a.attr("id"),r=i._raise("filesuccessremove",[e,a.attr("data-fileindex")]);t.cleanMemory(a),!1!==r&&a.fadeOut("slow",function(){t.cleanZoomCache(n.find("#zoom-"+e)),a.remove(),i.getFrames().length||i.reset()})})})},_checkAsyncComplete:function(){var t,i;for(i=0;i<this.filestack.length;i++)if(this.filestack[i]&&(t=this.previewInitId+"-"+i,-1===e.inArray(t,this.uploadLog)))return!1;return this.uploadAsyncCount===this.uploadLog.length},_uploadExtra:function(t,i){var a=this,n=a._getExtraData(t,i);0!==n.length&&e.each(n,function(e,t){a.formdata.append(e,t)})},_uploadSingle:function(i,a){var n,r,s,o,l,d,c,h,p,u,f,m=this,g=m.getFileStack().length,v=new FormData,w=m.previewInitId+"-"+i,_=m.filestack.length>0||!e.isEmptyObject(m.uploadExtraData),b=e("#"+w).find(".file-thumb-progress"),C={id:w,index:i};m.formdata=v,m.showPreview&&(r=e("#"+w+":not(.file-preview-initial)"),o=r.find(".kv-file-upload"),l=r.find(".kv-file-remove"),b.show()),0===g||!_||o&&o.hasClass("disabled")||m._abort(C)||(f=function(e,t){d||m.updateStack(e,void 0),m.uploadLog.push(t),m._checkAsyncComplete()&&(m.fileBatchCompleted=!0)},s=function(){var e,i,a,n=m.uploadCache,r=0,s=m.cacheInitialPreview;m.fileBatchCompleted&&(s&&s.content&&(r=s.content.length),setTimeout(function(){var o=0===m.getFileStack(!0).length;if(m.showPreview){if(m.previewCache.set(n.content,n.config,n.tags,n.append),r){for(i=0;i<n.content.length;i++)a=i+r,s.content[a]=n.content[i],s.config.length&&(s.config[a]=n.config[i]),s.tags.length&&(s.tags[a]=n.tags[i]);m.initialPreview=t.cleanArray(s.content),m.initialPreviewConfig=t.cleanArray(s.config),m.initialPreviewThumbTags=t.cleanArray(s.tags)}else m.initialPreview=n.content,m.initialPreviewConfig=n.config,m.initialPreviewThumbTags=n.tags;m.cacheInitialPreview={},m.hasInitData&&(m._initPreview(),m._initPreviewActions())}m.unlock(o),o&&m._clearFileInput(),e=m.$preview.find(".file-preview-initial"),m.uploadAsync&&e.length&&(t.addCss(e,t.SORT_CSS),m._initSortable()),m._raise("filebatchuploadcomplete",[m.filestack,m._getExtraData()]),m.uploadCount=0,m.uploadStatus={},m.uploadLog=[],m._setProgress(101)},100))},c=function(s){n=m._getOutData(s),m.fileBatchCompleted=!1,m.showPreview&&(r.hasClass("file-preview-success")||(m._setThumbStatus(r,"Loading"),t.addCss(r,"file-uploading")),o.attr("disabled",!0),l.attr("disabled",!0)),a||m.lock(),m._raise("filepreupload",[n,w,i]),e.extend(!0,C,n),m._abort(C)&&(s.abort(),m._setProgressCancelled())},h=function(s,l,c){var h=m.showPreview&&r.attr("id")?r.attr("id"):w;n=m._getOutData(c,s),e.extend(!0,C,n),setTimeout(function(){t.isEmpty(s)||t.isEmpty(s.error)?(m.showPreview&&(m._setThumbStatus(r,"Success"),o.hide(),m._initUploadSuccess(s,r,a),m._setProgress(101,b)),m._raise("fileuploaded",[n,h,i]),a?f(i,h):m.updateStack(i,void 0)):(d=!0,m._showUploadError(s.error,C),m._setPreviewError(r,i,m.filestack[i],m.retryErrorUploads),m.retryErrorUploads||o.hide(),a&&f(i,h),m._setProgress(101,e("#"+h).find(".file-thumb-progress"),m.msgUploadError))},100)},p=function(){setTimeout(function(){m.showPreview&&(o.removeAttr("disabled"),l.removeAttr("disabled"),r.removeClass("file-uploading")),a?s():(m.unlock(!1),m._clearFileInput()),m._initSuccessThumbs()},100)},u=function(t,n,s){var l=m.ajaxOperations.uploadThumb,c=m._parseError(l,t,s,a&&m.filestack[i].name?m.filestack[i].name:null);d=!0,setTimeout(function(){a&&f(i,w),m.uploadStatus[w]=100,m._setPreviewError(r,i,m.filestack[i],m.retryErrorUploads),m.retryErrorUploads||o.hide(),e.extend(!0,C,m._getOutData(t)),m._setProgress(101,b,m.msgAjaxProgressError.replace("{operation}",l)),m._setProgress(101,e("#"+w).find(".file-thumb-progress"),m.msgUploadError),m._showUploadError(c,C)},100)},v.append(m.uploadFileAttr,m.filestack[i],m.filenames[i]),v.append("file_id",i),m._ajaxSubmit(c,h,p,u,w,i))},_uploadBatch:function(){var i,a,n,r,s,o=this,l=o.filestack,d=l.length,c=o.filestack.length>0||!e.isEmptyObject(o.uploadExtraData);o.formdata=new FormData,0!==d&&c&&!o._abort({})&&(s=function(){e.each(l,function(e){o.updateStack(e,void 0)}),o._clearFileInput()},i=function(i){o.lock();var a=o._getOutData(i);o.showPreview&&o._getThumbs().each(function(){var i=e(this),a=i.find(".kv-file-upload"),n=i.find(".kv-file-remove");i.hasClass("file-preview-success")||(o._setThumbStatus(i,"Loading"),t.addCss(i,"file-uploading")),a.attr("disabled",!0),n.attr("disabled",!0)}),o._raise("filebatchpreupload",[a]),o._abort(a)&&(i.abort(),o._setProgressCancelled())},a=function(i,a,n){var r=o._getOutData(n,i),l=0,d=o._getThumbs(":not(.file-preview-success)"),c=t.isEmpty(i)||t.isEmpty(i.errorkeys)?[]:i.errorkeys;t.isEmpty(i)||t.isEmpty(i.error)?(o._raise("filebatchuploadsuccess",[r]),s(),o.showPreview?(d.each(function(){var t=e(this);o._setThumbStatus(t,"Success"),t.removeClass("file-uploading"),t.find(".kv-file-upload").hide().removeAttr("disabled")}),o._initUploadSuccess(i)):o.reset(),o._setProgress(101)):(o.showPreview&&(d.each(function(){var t=e(this),i=t.attr("data-fileindex");t.removeClass("file-uploading"),t.find(".kv-file-upload").removeAttr("disabled"),t.find(".kv-file-remove").removeAttr("disabled"),0===c.length||-1!==e.inArray(l,c)?(o._setPreviewError(t,i,o.filestack[i],o.retryErrorUploads),o.retryErrorUploads||(t.find(".kv-file-upload").hide(),o.updateStack(i,void 0))):(t.find(".kv-file-upload").hide(),o._setThumbStatus(t,"Success"),o.updateStack(i,void 0)),t.hasClass("file-preview-error")&&!o.retryErrorUploads||l++}),o._initUploadSuccess(i)),o._showUploadError(i.error,r,"filebatchuploaderror"),o._setProgress(101,o.$progress,o.msgUploadError))},r=function(){o.unlock(),o._initSuccessThumbs(),o._clearFileInput(),o._raise("filebatchuploadcomplete",[o.filestack,o._getExtraData()])},n=function(t,i,a){var n=o._getOutData(t),r=o.ajaxOperations.uploadBatch,s=o._parseError(r,t,a);o._showUploadError(s,n,"filebatchuploaderror"),o.uploadFileCount=d-1,o.showPreview&&(o._getThumbs().each(function(){var t=e(this),i=t.attr("data-fileindex");t.removeClass("file-uploading"),void 0!==o.filestack[i]&&o._setPreviewError(t)}),o._getThumbs().removeClass("file-uploading"),o._getThumbs(" .kv-file-upload").removeAttr("disabled"),o._getThumbs(" .kv-file-delete").removeAttr("disabled"),o._setProgress(101,o.$progress,o.msgAjaxProgressError.replace("{operation}",r)))},e.each(l,function(e,i){t.isEmpty(l[e])||o.formdata.append(o.uploadFileAttr,i,o.filenames[e])}),o._ajaxSubmit(i,a,r,n))},_uploadExtraOnly:function(){var e,i,a,n,r=this,s={};r.formdata=new FormData,r._abort(s)||(e=function(e){r.lock();var t=r._getOutData(e);r._raise("filebatchpreupload",[t]),r._setProgress(50),s.data=t,s.xhr=e,r._abort(s)&&(e.abort(),r._setProgressCancelled())},i=function(e,i,a){var n=r._getOutData(a,e);t.isEmpty(e)||t.isEmpty(e.error)?(r._raise("filebatchuploadsuccess",[n]),r._clearFileInput(),r._initUploadSuccess(e),r._setProgress(101)):r._showUploadError(e.error,n,"filebatchuploaderror")},a=function(){r.unlock(),r._clearFileInput(),r._raise("filebatchuploadcomplete",[r.filestack,r._getExtraData()])},n=function(e,t,i){var a=r._getOutData(e),n=r.ajaxOperations.uploadExtra,o=r._parseError(n,e,i);s.data=a,r._showUploadError(o,a,"filebatchuploaderror"),r._setProgress(101,r.$progress,r.msgAjaxProgressError.replace("{operation}",n))},r._ajaxSubmit(e,i,a,n))},_deleteFileIndex:function(i){var a=i.attr("data-fileindex");"init_"===a.substring(0,5)&&(a=parseInt(a.replace("init_","")),this.initialPreview=t.spliceArray(this.initialPreview,a),this.initialPreviewConfig=t.spliceArray(this.initialPreviewConfig,a),this.initialPreviewThumbTags=t.spliceArray(this.initialPreviewThumbTags,a),this.getFrames().each(function(){var t=e(this),i=t.attr("data-fileindex");"init_"===i.substring(0,5)&&(i=parseInt(i.replace("init_","")))>a&&(i--,t.attr("data-fileindex","init_"+i))}),this.uploadAsync&&(this.cacheInitialPreview=this.getPreview()))},_initFileActions:function(){var i=this,a=i.$preview;i.showPreview&&(i._initZoomButton(),i.getFrames(" .kv-file-remove").each(function(){var n,r,s,o=e(this),l=o.closest(t.FRAMES),d=l.attr("id"),c=l.attr("data-fileindex");i._handler(o,"click",function(){if(!1===i._raise("filepreremove",[d,c])||!i._validateMinCount())return!1;n=l.hasClass("file-preview-error"),t.cleanMemory(l),l.fadeOut("slow",function(){t.cleanZoomCache(a.find("#zoom-"+d)),i.updateStack(c,void 0),i._clearObjects(l),l.remove(),d&&n&&i.$errorContainer.find('li[data-file-id="'+d+'"]').fadeOut("fast",function(){e(this).remove(),i._errorsExist()||i._resetErrors()}),i._clearFileInput();var o=i.getFileStack(!0),h=i.previewCache.count(),p=o.length,u=i.showPreview&&i.getFrames().length;0!==p||0!==h||u?(s=(r=h+p)>1?i._getMsgSelected(r):o[0]?i._getFileNames()[0]:"",i._setCaption(s)):i.reset(),i._raise("fileremoved",[d,c])})})}),i.getFrames(" .kv-file-upload").each(function(){var a=e(this);i._handler(a,"click",function(){var e=a.closest(t.FRAMES),n=e.attr("data-fileindex");i.$progress.hide(),e.hasClass("file-preview-error")&&!i.retryErrorUploads||i._uploadSingle(n,!1)})}))},_initPreviewActions:function(){var i=this,a=i.$preview,n=i.deleteExtraData||{},r=t.FRAMES+" .kv-file-remove",s=i.fileActionSettings,o=s.removeClass,l=s.removeErrorClass,d=function(){var e=i.isUploadable?i.previewCache.count():i.$element.get(0).files.length;a.find(t.FRAMES).length||e||(i._setCaption(""),i.reset(),i.initialCaption="")};i._initZoomButton(),a.find(r).each(function(){var r,s,c,h=e(this),p=h.data("url")||i.deleteUrl,u=h.data("key");h.closest(".file-preview-frame");if(!t.isEmpty(p)&&void 0!==u){var f,m,g,v,w=h.closest(t.FRAMES),_=i.previewCache.data,b=w.attr("data-fileindex");b=parseInt(b.replace("init_","")),g=t.isEmpty(_.config)&&t.isEmpty(_.config[b])?null:_.config[b],"function"==typeof(v=t.isEmpty(g)||t.isEmpty(g.extra)?n:g.extra)&&(v=v()),m={id:h.attr("id"),key:u,extra:v},r=function(e){i.ajaxAborted=!1,i._raise("filepredelete",[u,e,v]),h.removeClass(l),i._abort()?e.abort():(t.addCss(w,"file-uploading"),t.addCss(h,"disabled "+o))},s=function(e,n,r){var s,c;if(!t.isEmpty(e)&&!t.isEmpty(e.error))return m.jqXHR=r,m.response=e,i._showError(e.error,m,"filedeleteerror"),w.removeClass("file-uploading"),h.removeClass("disabled "+o).addClass(l),void d();w.removeClass("file-uploading").addClass("file-deleted"),w.fadeOut("slow",function(){b=parseInt(w.attr("data-fileindex").replace("init_","")),i.previewCache.unset(b),s=i.previewCache.count(),c=s>0?i._getMsgSelected(s):"",i._deleteFileIndex(w),i._setCaption(c),i._raise("filedeleted",[u,r,v]),t.cleanZoomCache(a.find("#zoom-"+w.attr("id"))),i._clearObjects(w),w.remove(),d()})},c=function(e,t,a){var n=i.ajaxOperations.deleteThumb,r=i._parseError(n,e,a);m.jqXHR=e,m.response={},i._showError(r,m,"filedeleteerror"),w.removeClass("file-uploading"),h.removeClass("disabled "+o).addClass(l),d()},i._mergeAjaxCallback("beforeSend",r,"delete"),i._mergeAjaxCallback("success",s,"delete"),i._mergeAjaxCallback("error",c,"delete"),f=e.extend(!0,{},{url:p,type:"POST",dataType:"json",data:e.extend(!0,{},{key:u},v)},i.ajaxDeleteSettings),i._handler(h,"click",function(){if(!i._validateMinCount())return!1;i.ajaxAborted=!1,i._raise("filebeforedelete",[u,v]),i.ajaxAborted instanceof Promise?i.ajaxAborted.then(function(t){t||e.ajax(f)}):i.ajaxAborted||e.ajax(f)})}})},_hideFileIcon:function(){this.overwriteInitial&&this.$captionContainer.find(".kv-caption-icon").hide()},_showFileIcon:function(){this.$captionContainer.find(".kv-caption-icon").show()},_getSize:function(t){var i,a,n,r=parseFloat(t),s=this.fileSizeGetter;return e.isNumeric(t)&&e.isNumeric(r)?("function"==typeof s?n=s(r):0===r?n="0.00 B":(i=Math.floor(Math.log(r)/Math.log(1024)),a=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],n=1*(r/Math.pow(1024,i)).toFixed(2)+" "+a[i]),this._getLayoutTemplate("size").replace("{sizeText}",n)):""},_generatePreviewTemplate:function(i,a,n,r,s,o,l,d,c,h,p){var u,f=this,m=f.slug(n),g="",v="",w=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)<400?f.previewSettingsSmall[i]||f.defaults.previewSettingsSmall[i]:f.previewSettings[i]||f.defaults.previewSettings[i],_=c||f._renderFileFooter(m,l,"auto",o),b=f._getPreviewIcon(n),C="type-default",y=b&&f.preferIconicPreview,x=b&&f.preferIconicZoomPreview;return w&&e.each(w,function(e,t){v+=e+":"+t+";"}),u=function(a,o,l,c){var u=l?"zoom-"+s:s,g=f._getPreviewTemplate(a),w=(d||"")+" "+c;return f.frameClass&&(w=f.frameClass+" "+w),l&&(w=w.replace(" "+t.SORT_CSS,"")),g=f._parseFilePreviewIcon(g,n),"text"===a&&(o=t.htmlEncode(o)),"object"!==i||r||e.each(f.defaults.fileTypeSettings,function(e,t){"object"!==e&&"other"!==e&&t(n,r)&&(C="type-"+e)}),g.setTokens({previewId:u,caption:m,frameClass:w,type:r,fileindex:h,typeCss:C,footer:_,data:o,template:p||i,style:v?'style="'+v+'"':""})},h=h||s.slice(s.lastIndexOf("-")+1),f.fileActionSettings.showZoom&&(g=u(x?"other":i,a,!0,"kv-zoom-thumb")),g="\n"+f._getLayoutTemplate("zoomCache").replace("{zoomContent}",g),u(y?"other":i,a,!1,"kv-preview-thumb")+g},_previewDefault:function(i,a,n){var r=this.$preview;if(this.showPreview){var s,o=i?i.name:"",l=i?i.type:"",d=i.size||0,c=this.slug(o),h=!0===n&&!this.isUploadable,p=t.objUrl.createObjectURL(i);this._clearDefaultPreview(),s=this._generatePreviewTemplate("other",p,o,l,a,h,d),r.append("\n"+s),this._setThumbAttr(a,c,d),!0===n&&this.isUploadable&&this._setThumbStatus(e("#"+a),"Error")}},_previewFile:function(e,i,a,n,r){if(this.showPreview){var s,o=this,l=o._parseFileType(i),d=i?i.name:"",c=o.slug(d),h=o.allowedPreviewTypes,p=o.allowedPreviewMimeTypes,u=o.$preview,f=h&&h.indexOf(l)>=0,m=i.size||0,g=i.type,v="text"===l||"html"===l||"image"===l?a.target.result:r,w=p&&-1!==p.indexOf(g);if("html"===l&&o.purifyHtml&&window.DOMPurify&&(v=window.DOMPurify.sanitize(v)),f||w){s=o._generatePreviewTemplate(l,v,d,g,n,!1,m),o._clearDefaultPreview(),u.append("\n"+s);var _=u.find("#"+n+" img");_.length&&o.autoOrientImage?t.validateOrientation(i,function(e){if(e){var a=u.find("#zoom-"+n+" img"),r="rotate-"+e;e>4&&(r+=_.width()>_.height()?" is-portrait-gt4":" is-landscape-gt4"),t.addCss(_,r),t.addCss(a,r),o._raise("fileimageoriented",{$img:_,file:i}),o._validateImage(n,c,g,m,v),t.adjustOrientedImage(_)}else o._validateImage(n,c,g,m,v)}):o._validateImage(n,c,g,m,v)}else o._previewDefault(i,n);o._setThumbAttr(n,c,m),o._initSortable()}},_setThumbAttr:function(t,i,a){var n=e("#"+t);n.length&&(a=a&&a>0?this._getSize(a):"",n.data({caption:i,size:a}))},_setInitThumbAttr:function(){var e,i,a,n,r=this.previewCache.data,s=this.previewCache.count();if(0!==s)for(var o=0;o<s;o++)e=r.config[o],n=this.previewInitId+"-init_"+o,i=t.ifSet("caption",e,t.ifSet("filename",e)),a=t.ifSet("size",e),this._setThumbAttr(n,i,a)},_slugDefault:function(e){return t.isEmpty(e)?"":String(e).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g,"_")},_readFiles:function(i){this.reader=new FileReader;var a,n=this,r=n.$element,s=n.$preview,o=n.reader,l=n.$previewContainer,d=n.$previewStatus,c=n.msgLoading,h=n.msgProgress,p=n.previewInitId,u=i.length,f=n.fileTypeSettings,m=n.filestack.length,g=n.allowedFileTypes,v=g?g.length:0,w=n.allowedFileExtensions,_=t.isEmpty(w)?"":w.join(", "),b=n.maxFilePreviewSize&&parseFloat(n.maxFilePreviewSize),C=s.length&&(!b||isNaN(b)),y=function(t,r,s,o){var l,d=e.extend(!0,{},n._getOutData({},{},i),{id:s,index:o}),c={id:s,index:o,file:r,files:i};return n._previewDefault(r,s,!0),n.isUploadable&&(n.addToStack(void 0),setTimeout(function(){a(o+1)},100)),n._initFileActions(),(l=e("#"+s)).find(".kv-file-upload").hide(),n.removeFromPreviewOnError&&l.remove(),n.isUploadable?n._showUploadError(t,d):n._showError(t,c)};n.loadedImages=[],n.totalImagesCount=0,e.each(i,function(e,t){var i=n.fileTypeSettings.image;i&&i(t.type)&&n.totalImagesCount++}),(a=function(e){if(t.isEmpty(r.attr("multiple"))&&(u=1),e>=u)return n.isUploadable&&n.filestack.length>0?n._raise("filebatchselected",[n.getFileStack()]):n._raise("filebatchselected",[i]),l.removeClass("file-thumb-loading"),void d.html("");var x,E,T,S,F,k,I,P,A,D,z=p+"-"+(m+e),$=i[e],U=$.name?n.slug($.name):"",j=($.size||0)/1e3,B="",R=t.objUrl.createObjectURL($),O=0,L="";if(v>0)for(S=0;S<v;S++)P=g[S],A=n.msgFileTypes[P]||P,L+=0===S?A:", "+A;if(!1!==U){if(0===U.length)return F=n.msgInvalidFileName.replace("{name}",t.htmlEncode($.name)),void(n.isError=y(F,$,z,e));if(t.isEmpty(w)||(B=new RegExp("\\.("+w.join("|")+")$","i")),T=j.toFixed(2),n.maxFileSize>0&&j>n.maxFileSize)return F=n.msgSizeTooLarge.setTokens({name:U,size:T,maxSize:n.maxFileSize}),void(n.isError=y(F,$,z,e));if(null!==n.minFileSize&&j<=t.getNum(n.minFileSize))return F=n.msgSizeTooSmall.setTokens({name:U,size:T,minSize:n.minFileSize}),void(n.isError=y(F,$,z,e));if(!t.isEmpty(g)&&t.isArray(g)){for(S=0;S<g.length;S+=1)k=g[S],O+=(D=f[k])&&"function"==typeof D&&D($.type,$.name)?1:0;if(0===O)return F=n.msgInvalidFileType.setTokens({name:U,types:L}),void(n.isError=y(F,$,z,e))}if(0===O&&!t.isEmpty(w)&&t.isArray(w)&&!t.isEmpty(B)&&(I=t.compare(U,B),0===(O+=t.isEmpty(I)?0:I.length)))return F=n.msgInvalidFileExtension.setTokens({name:U,extensions:_}),void(n.isError=y(F,$,z,e));if(!n.showPreview)return n.isUploadable&&n.addToStack($),setTimeout(function(){a(e+1),n._updateFileDetails(u)},100),void n._raise("fileloaded",[$,z,e,o]);if(!C&&j>b)return n.addToStack($),l.addClass("file-thumb-loading"),n._previewDefault($,z),n._initFileActions(),n._updateFileDetails(u),void a(e+1);s.length&&void 0!==FileReader?(d.html(c.replace("{index}",e+1).replace("{files}",u)),l.addClass("file-thumb-loading"),o.onerror=function(e){n._errorHandler(e,U)},o.onload=function(t){n._previewFile(e,$,t,z,R),n._initFileActions()},o.onloadend=function(){F=h.setTokens({index:e+1,files:u,percent:50,name:U}),setTimeout(function(){d.html(F),n._updateFileDetails(u),a(e+1)},100),n._raise("fileloaded",[$,z,e,o])},o.onprogress=function(t){if(t.lengthComputable){var i=t.loaded/t.total*100,a=Math.ceil(i);F=h.setTokens({index:e+1,files:u,percent:a,name:U}),setTimeout(function(){d.html(F)},100)}},x=f.text,E=f.image,x($.type,U)?o.readAsText($,n.textEncoding):E($.type,U)?o.readAsDataURL($):o.readAsArrayBuffer($)):(n._previewDefault($,z),setTimeout(function(){a(e+1),n._updateFileDetails(u)},100),n._raise("fileloaded",[$,z,e,o])),n.addToStack($)}else a(e+1)})(0),n._updateFileDetails(u,!1)},_updateFileDetails:function(e){var i=this.$element,a=this.getFileStack(),n=t.isIE(9)&&t.findFileName(i.val())||i[0].files[0]&&i[0].files[0].name||a.length&&a[0].name||"",r=this.slug(n),s=this.isUploadable?a.length:e,o=this.previewCache.count()+s,l=s>1?this._getMsgSelected(o):r;this.isError?(this.$previewContainer.removeClass("file-thumb-loading"),this.$previewStatus.html(""),this.$captionContainer.find(".kv-caption-icon").hide()):this._showFileIcon(),this._setCaption(l,this.isError),this.$container.removeClass("file-input-new file-input-ajax-new"),1===arguments.length&&this._raise("fileselect",[e,r]),this.previewCache.count()&&this._initPreviewActions()},_setThumbStatus:function(e,t){if(this.showPreview){var i="indicator"+t,a=i+"Title",n="file-preview-"+t.toLowerCase(),r=e.find(".file-upload-indicator"),s=this.fileActionSettings;e.removeClass("file-preview-success file-preview-error file-preview-loading"),"Success"===t&&e.find(".file-drag-handle").remove(),r.html(s[i]),r.attr("title",s[a]),e.addClass(n),"Error"!==t||this.retryErrorUploads||e.find(".kv-file-upload").attr("disabled",!0)}},_setProgressCancelled:function(){this._setProgress(101,this.$progress,this.msgCancelled)},_setProgress:function(e,i,a){var n,r=Math.min(e,100),s=this.progressUploadThreshold,o=e<=100?this.progressTemplate:this.progressCompleteTemplate,l=r<100?this.progressTemplate:a?this.progressErrorTemplate:o;i=i||this.$progress,t.isEmpty(l)||(n=s&&r>s&&e<=100?l.setTokens({percent:s,status:this.msgUploadThreshold}):l.setTokens({percent:r,status:e>100?this.msgUploadEnd:r+"%"}),i.html(n),a&&i.find('[role="progressbar"]').html(a))},_setFileDropZoneTitle:function(){var e,i=this.$container.find(".file-drop-zone"),a=this.dropZoneTitle;this.isClickable&&(e=t.isEmpty(this.$element.attr("multiple"))?this.fileSingle:this.filePlural,a+=this.dropZoneClickTitle.replace("{files}",e)),i.find("."+this.dropZoneTitleClass).remove(),this.isUploadable&&this.showPreview&&0!==i.length&&!(this.getFileStack().length>0)&&this.dropZoneEnabled&&(0===i.find(t.FRAMES).length&&t.isEmpty(this.defaultPreviewContent)&&i.prepend('<div class="'+this.dropZoneTitleClass+'">'+a+"</div>"),this.$container.removeClass("file-input-new"),t.addCss(this.$container,"file-input-ajax-new"))},_setAsyncUploadStatus:function(t,i,a){var n=0;this._setProgress(i,e("#"+t).find(".file-thumb-progress")),this.uploadStatus[t]=i,e.each(this.uploadStatus,function(e,t){n+=t}),this._setProgress(Math.floor(n/a))},_validateMinCount:function(){var e=this.isUploadable?this.getFileStack().length:this.$element.get(0).files.length;return!(this.validateInitialCount&&this.minFileCount>0&&this._getFileCount(e-1)<this.minFileCount)||(this._noFilesError({}),!1)},_getFileCount:function(e){return this.validateInitialCount&&!this.overwriteInitial&&(e+=this.previewCache.count()),e},_getFileId:function(e){var t,i=this.generateFileId;return"function"==typeof i?i(e,event):e&&(t=String(e.webkitRelativePath||e.fileName||e.name||null))?e.size+"-"+t.replace(/[^0-9a-zA-Z_-]/gim,""):null},_getFileName:function(e){return e&&e.name?this.slug(e.name):void 0},_getFileIds:function(e){return this.fileids.filter(function(t){return e?void 0!==t:null!=t})},_getFileNames:function(e){return this.filenames.filter(function(t){return e?void 0!==t:null!=t})},_setPreviewError:function(e,t,i,a){void 0!==t&&this.updateStack(t,i),!this.removeFromPreviewOnError||a?(this._setThumbStatus(e,"Error"),this._refreshUploadButton(e,a)):e.remove()},_refreshUploadButton:function(e,t){var i=e.find(".kv-file-upload"),a=this.fileActionSettings,n=a.uploadIcon,r=a.uploadTitle;i.length&&(t&&(n=a.uploadRetryIcon,r=a.uploadRetryTitle),i.attr("title",r).html(n))},_checkDimensions:function(e,i,a,n,r,s,o){var l,d,c,h=this[("Small"===i?"min":"max")+"Image"+s];!t.isEmpty(h)&&a.length&&(c=a[0],d="Width"===s?c.naturalWidth||c.width:c.naturalHeight||c.height,("Small"===i?d>=h:d<=h)||(l=this["msgImage"+s+i].setTokens({name:r,size:h}),this._showUploadError(l,o),this._setPreviewError(n,e,null)))},_validateImage:function(t,i,a,n,r){var s,o,l,d,c=this,h=c.$preview,p=h.find("#"+t),u=p.attr("data-fileindex"),f=p.find("img");i=i||"Untitled",f.one("load",function(){o=p.width(),l=h.width(),o>l&&f.css("width","100%"),s={ind:u,id:t},c._checkDimensions(u,"Small",f,p,i,"Width",s),c._checkDimensions(u,"Small",f,p,i,"Height",s),c.resizeImage||(c._checkDimensions(u,"Large",f,p,i,"Width",s),c._checkDimensions(u,"Large",f,p,i,"Height",s)),c._raise("fileimageloaded",[t]),d=window.piexif?window.piexif.load(r):null,c.loadedImages.push({ind:u,img:f,thumb:p,pid:t,typ:a,siz:n,validated:!1,imgData:r,exifObj:d}),p.data("exif",d),c._validateAllImages()}).one("error",function(){c._raise("fileimageloaderror",[t])}).each(function(){this.complete?e(this).trigger("load"):this.error&&e(this).trigger("error")})},_validateAllImages:function(){var e,t,i,a={val:0},n=this.loadedImages.length,r=this.resizeIfSizeMoreThan;if(n===this.totalImagesCount&&(this._raise("fileimagesloaded"),this.resizeImage))for(e=0;e<this.loadedImages.length;e++)(t=this.loadedImages[e]).validated||((i=t.siz)&&i>1e3*r&&this._getResizedImage(t,a,n),this.loadedImages[e].validated=!0)},_getResizedImage:function(i,a,n){var r,s,o,l,d,c,h=this,p=e(i.img)[0],u=p.naturalWidth,f=p.naturalHeight,m=1,g=h.maxImageWidth||u,v=h.maxImageHeight||f,w=!(!u||!f),_=h.imageCanvas,b=h.imageCanvasContext,C=i.typ,y=i.pid,x=i.ind,E=i.thumb,T=i.exifObj;if(d=function(e,t,i){h.isUploadable?h._showUploadError(e,t,i):h._showError(e,t,i),h._setPreviewError(E,x)},h.filestack[x]&&w&&!(u<=g&&f<=v)||(w&&h.filestack[x]&&h._raise("fileimageresized",[y,x]),a.val++,a.val===n&&h._raise("fileimagesresized"),w)){C=C||h.resizeDefaultImageType,s=u>g,o=f>v,m="width"===h.resizePreference?s?g/u:o?v/f:1:o?v/f:s?g/u:1,h._resetCanvas(),u*=m,f*=m,_.width=u,_.height=f;try{b.drawImage(p,0,0,u,f),l=_.toDataURL(C,h.resizeQuality),T&&(c=window.piexif.dump(T),l=window.piexif.insert(c,l)),r=t.dataURI2Blob(l),h.filestack[x]=r,h._raise("fileimageresized",[y,x]),a.val++,a.val===n&&h._raise("fileimagesresized",[void 0,void 0]),r instanceof Blob||d(h.msgImageResizeError,{id:y,index:x},"fileimageresizeerror")}catch(e){a.val++,a.val===n&&h._raise("fileimagesresized",[void 0,void 0]),d(h.msgImageResizeException.replace("{errors}",e.message),{id:y,index:x},"fileimageresizeexception")}}else d(h.msgImageResizeError,{id:y,index:x},"fileimageresizeerror")},_initBrowse:function(e){this.showBrowse?(this.$btnFile=e.find(".btn-file"),this.$btnFile.append(this.$element)):this.$element.hide()},_initCaption:function(){var e=this.initialCaption||"";return this.overwriteInitial||t.isEmpty(e)?(this.$caption.html(""),!1):(this._setCaption(e),!0)},_setCaption:function(i,a){var n,r,s,o,l=this.getFileStack();if(this.$caption.length){if(a)n=e("<div>"+this.msgValidationError+"</div>").text(),o=(s=l.length)?1===s&&l[0]?this._getFileNames()[0]:this._getMsgSelected(s):this._getMsgSelected(this.msgNo),r='<span class="'+this.msgValidationErrorClass+'">'+this.msgValidationErrorIcon+(t.isEmpty(i)?o:i)+"</span>";else{if(t.isEmpty(i))return;n=e("<div>"+i+"</div>").text(),r=this._getLayoutTemplate("fileIcon")+n}this.$caption.html(r),this.$caption.attr("title",n),this.$captionContainer.find(".file-caption-ellipsis").attr("title",n)}},_createContainer:function(){var t={class:"file-input file-input-new"+(this.rtl?" kv-rtl":"")},i=e(document.createElement("div")).attr(t).html(this._renderMain());return this.$element.before(i),this._initBrowse(i),this.theme&&i.addClass("theme-"+this.theme),i},_refreshContainer:function(){var e=this.$container;e.before(this.$element),e.html(this._renderMain()),this._initBrowse(e)},_renderMain:function(){var e=this.isUploadable&&this.dropZoneEnabled?" file-drop-zone":"file-drop-disabled",t=this.showClose?this._getLayoutTemplate("close"):"",i=this.showPreview?this._getLayoutTemplate("preview").setTokens({class:this.previewClass,dropClass:e}):"",a=this.isDisabled?this.captionClass+" file-caption-disabled":this.captionClass,n=this.captionTemplate.setTokens({class:a+" kv-fileinput-caption"});return this.mainTemplate.setTokens({class:this.mainClass+(!this.showBrowse&&this.showCaption?" no-browse":""),preview:i,close:t,caption:n,upload:this._renderButton("upload"),remove:this._renderButton("remove"),cancel:this._renderButton("cancel"),browse:this._renderButton("browse")})},_renderButton:function(e){var i=this._getLayoutTemplate("btnDefault"),a=this[e+"Class"],n=this[e+"Title"],r=this[e+"Icon"],s=this[e+"Label"],o=this.isDisabled?" disabled":"",l="button";switch(e){case"remove":if(!this.showRemove)return"";break;case"cancel":if(!this.showCancel)return"";a+=" kv-hidden";break;case"upload":if(!this.showUpload)return"";this.isUploadable&&!this.isDisabled?i=this._getLayoutTemplate("btnLink").replace("{href}",this.uploadUrl):l="submit";break;case"browse":if(!this.showBrowse)return"";i=this._getLayoutTemplate("btnBrowse");break;default:return""}return a+="browse"===e?" btn-file":" fileinput-"+e+" fileinput-"+e+"-button",t.isEmpty(s)||(s=' <span class="'+this.buttonLabelClass+'">'+s+"</span>"),i.setTokens({type:l,css:a,title:n,status:o,icon:r,label:s})},_renderThumbProgress:function(){return'<div class="file-thumb-progress kv-hidden">'+this.progressTemplate.setTokens({percent:"0",status:this.msgUploadBegin})+"</div>"},_renderFileFooter:function(e,i,a,n){var r,s=this.fileActionSettings,o=s.showRemove,l=s.showDrag,d=s.showUpload,c=s.showZoom,h=this._getLayoutTemplate("footer"),p=this._getLayoutTemplate("indicator"),u=n?s.indicatorError:s.indicatorNew,f=n?s.indicatorErrorTitle:s.indicatorNewTitle,m=p.setTokens({indicator:u,indicatorTitle:f});return i=this._getSize(i),r=this.isUploadable?h.setTokens({actions:this._renderFileActions(d,!1,o,c,l,!1,!1,!1),caption:e,size:i,width:a,progress:this._renderThumbProgress(),indicator:m}):h.setTokens({actions:this._renderFileActions(!1,!1,!1,c,l,!1,!1,!1),caption:e,size:i,width:a,progress:"",indicator:m}),r=t.replaceTags(r,this.previewThumbTags)},_renderFileActions:function(e,t,i,a,n,r,s,o,l,d,c){if(!(e||t||i||a||n))return"";var h,p=!1===s?"":' data-url="'+s+'"',u=!1===o?"":' data-key="'+o+'"',f="",m="",g="",v="",w="",_=this._getLayoutTemplate("actions"),b=this.fileActionSettings,C=this.otherActionButtons.setTokens({dataKey:u,key:o}),y=r?b.removeClass+" disabled":b.removeClass;return i&&(f=this._getLayoutTemplate("actionDelete").setTokens({removeClass:y,removeIcon:b.removeIcon,removeTitle:b.removeTitle,dataUrl:p,dataKey:u,key:o})),e&&(m=this._getLayoutTemplate("actionUpload").setTokens({uploadClass:b.uploadClass,uploadIcon:b.uploadIcon,uploadTitle:b.uploadTitle})),t&&(g=(g=this._getLayoutTemplate("actionDownload").setTokens({downloadClass:b.downloadClass,downloadIcon:b.downloadIcon,downloadTitle:b.downloadTitle,downloadUrl:d||this.initialPreviewDownloadUrl})).setTokens({filename:c,key:o})),a&&(v=this._getLayoutTemplate("actionZoom").setTokens({zoomClass:b.zoomClass,zoomIcon:b.zoomIcon,zoomTitle:b.zoomTitle})),n&&l&&(h="drag-handle-init "+b.dragClass,w=this._getLayoutTemplate("actionDrag").setTokens({dragClass:h,dragTitle:b.dragTitle,dragIcon:b.dragIcon})),_.setTokens({delete:f,upload:m,download:g,zoom:v,drag:w,other:C})},_browse:function(e){this._raise("filebrowse"),e&&e.isDefaultPrevented()||(this.isError&&!this.isUploadable&&this.clear(),this.$captionContainer.focus())},_filterDuplicate:function(e,t,i){var a=this._getFileId(e);a&&i&&i.indexOf(a)>-1||(i||(i=[]),t.push(e),i.push(a))},_change:function(i){var a=this,n=a.$element;if(!a.isUploadable&&t.isEmpty(n.val())&&a.fileInputCleared)a.fileInputCleared=!1;else{a.fileInputCleared=!1;var r,s,o,l,d,c,h,p,u,f,m=[],g=arguments.length>1,v=a.isUploadable,w=g?i.originalEvent.dataTransfer.files:n.get(0).files,_=a.filestack.length,b=t.isEmpty(n.attr("multiple"))&&_>0,C=0,y=a._getFileIds();if(a.reader=null,a._resetUpload(),a._hideFileIcon(),a.isUploadable&&a.$container.find(".file-drop-zone ."+a.dropZoneTitleClass).remove(),g?e.each(w,function(e,t){t&&!t.type&&void 0!==t.size&&t.size%4096==0?C++:a._filterDuplicate(t,m,y)}):(w=i.target&&void 0===i.target.files?i.target.value?[{name:i.target.value.replace(/^.+\\/,"")}]:[]:i.target.files||{},v?e.each(w,function(e,t){a._filterDuplicate(t,m,y)}):m=w),t.isEmpty(m)||0===m.length)return v||a.clear(),a._showFolderError(C),void a._raise("fileselectnone");if(a._resetErrors(),l=m.length,s=a._getFileCount(a.isUploadable?a.getFileStack().length+l:l),a.maxFileCount>0&&s>a.maxFileCount){if(!a.autoReplace||l>a.maxFileCount)return o=a.autoReplace&&l>a.maxFileCount?l:s,r=a.msgFilesTooMany.replace("{m}",a.maxFileCount).replace("{n}",o),a.isError=(d=r,c=null,h=null,p=null,u=e.extend(!0,{},a._getOutData({},{},w),{id:h,index:p}),f={id:h,index:p,file:c,files:w},a.isUploadable?a._showUploadError(d,u):a._showError(d,f)),a.$captionContainer.find(".kv-caption-icon").hide(),a._setCaption("",!0),void a.$container.removeClass("file-input-new file-input-ajax-new");s>a.maxFileCount&&a._resetPreviewThumbs(v)}else!v||b?(a._resetPreviewThumbs(!1),b&&a.clearStack()):!v||0!==_||a.previewCache.count()&&!a.overwriteInitial||a._resetPreviewThumbs(!0);a.isPreviewable?a._readFiles(m):a._updateFileDetails(1),a._showFolderError(C)}},_abort:function(t){var i;return!(!this.ajaxAborted||"object"!=typeof this.ajaxAborted||void 0===this.ajaxAborted.message)&&((i=e.extend(!0,{},this._getOutData(),t)).abortData=this.ajaxAborted.data||{},i.abortMessage=this.ajaxAborted.message,this._setProgress(101,this.$progress,this.msgCancelled),this._showUploadError(this.ajaxAborted.message,i,"filecustomerror"),this.cancel(),!0)},_resetFileStack:function(){var i=this,a=0,n=[],r=[],s=[];i._getThumbs().each(function(){var o,l=e(this),d=l.attr("data-fileindex"),c=i.filestack[d],h=l.attr("id");"-1"!==d&&-1!==d&&(void 0!==c?(n[a]=c,r[a]=i._getFileName(c),s[a]=i._getFileId(c),l.attr({id:i.previewInitId+"-"+a,"data-fileindex":a}),a++):(o="uploaded-"+t.uniqId(),l.attr({id:o,"data-fileindex":"-1"}),i.$preview.find("#zoom-"+h).attr("id","zoom-"+o)))}),i.filestack=n,i.filenames=r,i.fileids=s},_isFileSelectionValid:function(e){return e=e||0,this.required&&!this.getFilesCount()?(this.$errorContainer.html(""),this._showUploadError(this.msgFileRequired),!1):!(this.minFileCount>0&&this._getFileCount(e)<this.minFileCount)||(this._noFilesError({}),!1)},clearStack:function(){return this.filestack=[],this.filenames=[],this.fileids=[],this.$element},updateStack:function(e,t){return this.filestack[e]=t,this.filenames[e]=this._getFileName(t),this.fileids[e]=t&&this._getFileId(t)||null,this.$element},addToStack:function(e){return this.filestack.push(e),this.filenames.push(this._getFileName(e)),this.fileids.push(this._getFileId(e)),this.$element},getFileStack:function(e){return this.filestack.filter(function(t){return e?void 0!==t:null!=t})},getFilesCount:function(){var e=this.isUploadable?this.getFileStack().length:this.$element.get(0).files.length;return this._getFileCount(e)},lock:function(){return this._resetErrors(),this.disable(),this.showRemove&&this.$container.find(".fileinput-remove").hide(),this.showCancel&&this.$container.find(".fileinput-cancel").show(),this._raise("filelock",[this.filestack,this._getExtraData()]),this.$element},unlock:function(e){return void 0===e&&(e=!0),this.enable(),this.showCancel&&this.$container.find(".fileinput-cancel").hide(),this.showRemove&&this.$container.find(".fileinput-remove").show(),e&&this._resetFileStack(),this._raise("fileunlock",[this.filestack,this._getExtraData()]),this.$element},cancel:function(){var t,i=this,a=i.ajaxRequests,n=a.length;if(n>0)for(t=0;t<n;t+=1)i.cancelling=!0,a[t].abort();return i._setProgressCancelled(),i._getThumbs().each(function(){var t=e(this),a=t.attr("data-fileindex");t.removeClass("file-uploading"),void 0!==i.filestack[a]&&(t.find(".kv-file-upload").removeClass("disabled").removeAttr("disabled"),t.find(".kv-file-remove").removeClass("disabled").removeAttr("disabled")),i.unlock()}),i.$element},clear:function(){var i,a=this;if(a._raise("fileclear"))return a.$btnUpload.removeAttr("disabled"),a._getThumbs().find("video,audio,img").each(function(){t.cleanMemory(e(this))}),a._resetUpload(),a.clearStack(),a._clearFileInput(),a._resetErrors(!0),a._hasInitialPreview()?(a._showFileIcon(),a._resetPreview(),a._initPreviewActions(),a.$container.removeClass("file-input-new")):(a._getThumbs().each(function(){a._clearObjects(e(this))}),a.isUploadable&&(a.previewCache.data={}),a.$preview.html(""),i=!a.overwriteInitial&&a.initialCaption.length>0?a.initialCaption:"",a.$caption.html(i),a.$caption.attr("title",""),t.addCss(a.$container,"file-input-new"),a._validateDefaultPreview()),0===a.$container.find(t.FRAMES).length&&(a._initCaption()||a.$captionContainer.find(".kv-caption-icon").hide()),a._hideFileIcon(),a._raise("filecleared"),a.$captionContainer.focus(),a._setFileDropZoneTitle(),a.$element},reset:function(){if(this._raise("filereset"))return this._resetPreview(),this.$container.find(".fileinput-filename").text(""),t.addCss(this.$container,"file-input-new"),(this.getFrames().length||this.isUploadable&&this.dropZoneEnabled)&&this.$container.removeClass("file-input-new"),this.clearStack(),this.formdata={},this._setFileDropZoneTitle(),this.$element},disable:function(){return this.isDisabled=!0,this._raise("filedisabled"),this.$element.attr("disabled","disabled"),this.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled"),this.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",!0),t.addCss(this.$container.find(".btn-file"),"disabled"),this._initDragDrop(),this.$element},enable:function(){return this.isDisabled=!1,this._raise("fileenabled"),this.$element.removeAttr("disabled"),this.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled"),this.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled"),this.$container.find(".btn-file").removeClass("disabled"),this._initDragDrop(),this.$element},upload:function(){var i,a,n,r=this.getFileStack().length,s=!e.isEmptyObject(this._getExtraData());if(this.isUploadable&&!this.isDisabled&&this._isFileSelectionValid(r))if(this._resetUpload(),0!==r||s)if(this.$progress.show(),this.uploadCount=0,this.uploadStatus={},this.uploadLog=[],this.lock(),this._setProgress(2),0===r&&s)this._uploadExtraOnly();else{if(n=this.filestack.length,this.hasInitData=!1,!this.uploadAsync)return this._uploadBatch(),this.$element;for(a=this._getOutData(),this._raise("filebatchpreupload",[a]),this.fileBatchCompleted=!1,this.uploadCache={content:[],config:[],tags:[],append:!0},this.uploadAsyncCount=this.getFileStack().length,i=0;i<n;i++)this.uploadCache.content[i]=null,this.uploadCache.config[i]=null,this.uploadCache.tags[i]=null;for(this.$preview.find(".file-preview-initial").removeClass(t.SORT_CSS),this._initSortable(),this.cacheInitialPreview=this.getPreview(),i=0;i<n;i++)this.filestack[i]&&this._uploadSingle(i,!0)}else this._showUploadError(this.msgUploadEmpty)},destroy:function(){var t=this.$form,i=this.$container,a=this.$element,n=this.namespace;return e(document).off(n),e(window).off(n),t&&t.length&&t.off(n),this.isUploadable&&this._clearFileInput(),this._cleanup(),this._initPreviewCache(),a.insertBefore(i).off(n).removeData(),i.off().remove(),a},refresh:function(i,a){var n=this.$element;return i="object"!=typeof i||t.isEmpty(i)?this.options:e.extend(!0,{},this.options,i),this._init(i,!0),this._listen(),a&&n.trigger("change"+this.namespace),n},zoom:function(e){var i=this._getFrame(e),a=this.$modal;i&&(t.initModal(a),a.html(this._getModalContent()),this._setZoomContent(i),a.modal("show"),this._initZoomButtons())},getExif:function(e){var t=this._getFrame(e);return t&&t.data("exif")||null},getFrames:function(e){return e=e||"",this.$preview.find(t.FRAMES+e)},getPreview:function(){return{content:this.initialPreview,config:this.initialPreviewConfig,tags:this.initialPreviewThumbTags}}},e.fn.fileinput=function(a){if(t.hasFileAPISupport()||t.isIE(9)){var n=Array.apply(null,arguments),r=[];switch(n.shift(),this.each(function(){var s,o=e(this),l=o.data("fileinput"),d="object"==typeof a&&a,c=d.theme||o.data("theme"),h={},p={},u=d.language||o.data("language")||e.fn.fileinput.defaults.language||"en";l||(c&&(p=e.fn.fileinputThemes[c]||{}),"en"===u||t.isEmpty(e.fn.fileinputLocales[u])||(h=e.fn.fileinputLocales[u]||{}),s=e.extend(!0,{},e.fn.fileinput.defaults,p,e.fn.fileinputLocales.en,h,d,o.data()),l=new i(this,s),o.data("fileinput",l)),"string"==typeof a&&r.push(l[a].apply(l,n))}),r.length){case 0:return this;case 1:return r[0];default:return r}}},e.fn.fileinput.defaults={language:"en",showCaption:!0,showBrowse:!0,showPreview:!0,showRemove:!0,showUpload:!0,showCancel:!0,showClose:!0,showUploadedThumbs:!0,browseOnZoneClick:!1,autoReplace:!1,autoOrientImage:!0,required:!1,rtl:!1,hideThumbnailContent:!1,generateFileId:null,previewClass:"",captionClass:"",frameClass:"krajee-default",mainClass:"file-caption-main",mainTemplate:null,purifyHtml:!0,fileSizeGetter:null,initialCaption:"",initialPreview:[],initialPreviewDelimiter:"*$$*",initialPreviewAsData:!1,initialPreviewFileType:"image",initialPreviewConfig:[],initialPreviewThumbTags:[],previewThumbTags:{},initialPreviewShowDelete:!0,initialPreviewDownloadUrl:"",removeFromPreviewOnError:!1,deleteUrl:"",deleteExtraData:{},overwriteInitial:!0,previewZoomButtonIcons:{prev:'<i class="glyphicon glyphicon-triangle-left"></i>',next:'<i class="glyphicon glyphicon-triangle-right"></i>',toggleheader:'<i class="fas fa-arrows-alt-h"></i>',fullscreen:'<i class="fas fa-arrows-alt"></i>',borderless:'<i class="fas fa-external-link-alt"></i>',close:'<i class="fas fa-times"></i>'},previewZoomButtonClasses:{prev:"btn btn-navigate",next:"btn btn-navigate",toggleheader:"btn btn-default btn-secondary btn-header-toggle",fullscreen:"btn btn-default btn-secondary",borderless:"btn btn-default btn-secondary",close:"btn btn-default btn-secondary"},preferIconicPreview:!1,preferIconicZoomPreview:!1,allowedPreviewTypes:void 0,allowedPreviewMimeTypes:null,allowedFileTypes:null,allowedFileExtensions:null,defaultPreviewContent:null,customLayoutTags:{},customPreviewTags:{},previewFileIcon:'<i class="glyphicon glyphicon-file"></i>',previewFileIconClass:"file-other-icon",previewFileIconSettings:{},previewFileExtSettings:{},buttonLabelClass:"hidden-xs",browseIcon:'<i class="glyphicon glyphicon-folder-open"></i> ',browseClass:"btn btn-primary",removeIcon:'<i class="glyphicon glyphicon-trash"></i>',removeClass:"btn btn-default btn-secondary",cancelIcon:'<i class="glyphicon glyphicon-ban-circle"></i>',cancelClass:"btn btn-default btn-secondary",uploadIcon:'<i class="glyphicon glyphicon-upload"></i>',uploadClass:"btn btn-default btn-secondary",uploadUrl:null,uploadUrlThumb:null,uploadAsync:!0,uploadExtraData:{},zoomModalHeight:480,minImageWidth:null,minImageHeight:null,maxImageWidth:null,maxImageHeight:null,resizeImage:!1,resizePreference:"width",resizeQuality:.92,resizeDefaultImageType:"image/jpeg",resizeIfSizeMoreThan:0,minFileSize:0,maxFileSize:0,maxFilePreviewSize:25600,minFileCount:0,maxFileCount:0,validateInitialCount:!1,msgValidationErrorClass:"text-danger",msgValidationErrorIcon:'<i class="glyphicon glyphicon-exclamation-sign"></i> ',msgErrorClass:"file-error-message",progressThumbClass:"progress-bar bg-success progress-bar-success progress-bar-striped active",progressClass:"progress-bar bg-success progress-bar-success progress-bar-striped active",progressCompleteClass:"progress-bar bg-success progress-bar-success",progressErrorClass:"progress-bar bg-danger progress-bar-danger",progressUploadThreshold:99,previewFileType:"image",elCaptionContainer:null,elCaptionText:null,elPreviewContainer:null,elPreviewImage:null,elPreviewStatus:null,elErrorContainer:null,errorCloseButton:'<button class="close kv-error-close">×</button>',slugCallback:null,dropZoneEnabled:!0,dropZoneTitleClass:"file-drop-zone-title",fileActionSettings:{},otherActionButtons:"",textEncoding:"UTF-8",ajaxSettings:{},ajaxDeleteSettings:{},showAjaxErrorDetails:!0,mergeAjaxCallbacks:!1,mergeAjaxDeleteCallbacks:!1,retryErrorUploads:!0},e.fn.fileinputLocales.en={fileSingle:"file",filePlural:"files",browseLabel:"Browse …",removeLabel:"Remove",removeTitle:"Clear selected files",cancelLabel:"Cancel",cancelTitle:"Abort ongoing upload",uploadLabel:"Upload",uploadTitle:"Upload selected files",msgNo:"No",msgNoFilesSelected:"No files selected",msgCancelled:"Cancelled",msgZoomModalHeading:"Detailed Preview",msgFileRequired:"You must select a file to upload.",msgSizeTooSmall:'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',msgSizeTooLarge:'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',msgFilesTooLess:"You must select at least <b>{n}</b> {files} to upload.",msgFilesTooMany:"Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.",msgFileNotFound:'File "{name}" not found!',msgFileSecured:'Security restrictions prevent reading the file "{name}".',msgFileNotReadable:'File "{name}" is not readable.',msgFilePreviewAborted:'File preview aborted for "{name}".',msgFilePreviewError:'An error occurred while reading the file "{name}".',msgInvalidFileName:'Invalid or unsupported characters in file name "{name}".',msgInvalidFileType:'Invalid type for file "{name}". Only "{types}" files are supported.',msgInvalidFileExtension:'Invalid extension for file "{name}". Only "{extensions}" files are supported.',msgFileTypes:{image:"image",html:"HTML",text:"text",video:"video",audio:"audio",flash:"flash",pdf:"PDF",object:"object"},msgUploadAborted:"The file upload was aborted",msgUploadThreshold:"Processing...",msgUploadBegin:"Initializing...",msgUploadEnd:"Done",msgUploadEmpty:"No valid data available for upload.",msgUploadError:"Error",msgValidationError:"Validation Error",msgLoading:"Loading file {index} of {files} …",msgProgress:"Loading file {index} of {files} - {name} - {percent}% completed.",msgSelected:"{n} {files} selected",msgFoldersNotAllowed:"Drag & drop files only! {n} folder(s) dropped were skipped.",msgImageWidthSmall:'Width of image file "{name}" must be at least {size} px.',msgImageHeightSmall:'Height of image file "{name}" must be at least {size} px.',msgImageWidthLarge:'Width of image file "{name}" cannot exceed {size} px.',msgImageHeightLarge:'Height of image file "{name}" cannot exceed {size} px.',msgImageResizeError:"Could not get the image dimensions to resize.",msgImageResizeException:"Error while resizing the image.<pre>{errors}</pre>",msgAjaxError:"Something went wrong with the {operation} operation. Please try again later!",msgAjaxProgressError:"{operation} failed",ajaxOperations:{deleteThumb:"file delete",uploadThumb:"file upload",uploadBatch:"batch file upload",uploadExtra:"form data upload"},dropZoneTitle:"Drag & drop files here …",dropZoneClickTitle:"<br>(or click to select {files})",previewZoomButtonTitles:{prev:"View previous file",next:"View next file",toggleheader:"Toggle header",fullscreen:"Toggle full screen",borderless:"Toggle borderless mode",close:"Close detailed preview"}},e.fn.fileinput.Constructor=i,e(document).ready(function(){var t=e("input.file[type=file]");t.length&&t.fileinput()})});
| 44,113 | 88,225 | 0.730272 |
c1b4b004d4a53e5e843958833124f8bba0265822 | 9,937 | js | JavaScript | src/_layout/footer/index.js | clasi2020home/WEB-gprb | 311187f4b5355f41768d49e46eb55d3aabb1d85a | [
"MIT"
] | null | null | null | src/_layout/footer/index.js | clasi2020home/WEB-gprb | 311187f4b5355f41768d49e46eb55d3aabb1d85a | [
"MIT"
] | null | null | null | src/_layout/footer/index.js | clasi2020home/WEB-gprb | 311187f4b5355f41768d49e46eb55d3aabb1d85a | [
"MIT"
] | null | null | null | import React, { useContext } from "react";
import { Link as GatsbyLink, Link } from "gatsby";
import Context from "../../_context";
import { Container, Row, Col, Visible, Hidden } from "react-grid-system";
import { Button } from "../../_components/buttons";
import styled from "styled-components";
const Footer = styled.footer``;
const MainFooter = styled.div`
padding: 4rem 0;
`;
const FooterRightsCont = styled.div`
background-color: ${(props) => props.theme.main.primaryColor};
color: ${(props) => props.theme.main.secondaryColor};
padding: 2rem 0;
@media (min-width: 768px) {
padding: 0.5rem 0;
}
`;
const OfficeInfoCont = styled.ul`
padding: 0;
margin: 0;
//margin-top: 2rem;
list-style: none;
`;
const OfficeInfo = styled.li`
color: #8e8787;
margin-bottom: 0.5rem;
`;
const FooterRights = styled.ul`
padding: 0;
margin: 0;
list-style: none;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
@media (min-width: 768px) {
flex-direction: row;
align-items: center;
}
`;
const NavCont = styled.div`
margin: 2rem 0;
@media (min-width: 768px) {
margin: 0;
}
`;
const NavLink = styled(Link)`
color: #212121;
transition: 250ms ease;
text-decoration: none;
margin-bottom: 1rem;
@media (min-width: 768px) {
display: block;
}
&:hover {
color: ${(props) => props.theme.main.primaryColor} !important;
}
&:visited {
color: #212121;
}
`;
const SvgIcon = styled.svg`
fill: ${(props) => (props.social ? props.theme.main.primaryColor : "#fff")};
margin-right: 0.5rem;
`;
const SocialNav = styled.ul`
padding: 0;
margin: 0;
list-style: none;
//color: ${(props) => props.theme.main.primaryColor};
display: flex;
align-content: center;
justify-content: flex-end;
margin-top: 2rem;
`;
const SocialItem = styled.li`
margin-left: 0.5rem;
`;
const Logo = styled.img`
object-fit: cover;
object-position: center;
max-width: 180px;
`;
const HeaderTitle = styled.h1`
color: ${(props) => props.theme.main.primaryColor};
font-size: 1rem;
font-weight: bold;
`;
const DevelopBy = styled.a`
color: #fff !important;
font-weight: bold;
margin-left: 0.5rem;
`;
const LogoCont = styled.div`
margin-bottom: 2rem;
`;
const BackTopCont = styled.div`
display: flex;
justify-content: flex-end;
`;
const BackTop = styled.button`
display: flex;
justify-content: center;
border: none;
cursor: pointer;
align-items: center;
width: 30px;
height: 30px;
border-radius: 50%;
background: ${(props) => props.theme.main.primaryColor};
margin-bottom: 1rem;
transition: 250ms ease;
box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.12), 0px 2px 2px rgba(0, 0, 0, 0.12),
0px 4px 4px rgba(0, 0, 0, 0.12), 0px 8px 8px rgba(0, 0, 0, 0.12);
&:hover {
filter: brightness(1.1);
}
&:active {
box-shadow: none;
}
`;
export default () => {
const office = useContext(Context).office;
const state = useContext(Context);
const builderId = useContext(Context).builderId;
const handleTop = () => window.scrollTo(0, 0);
return (
<Footer>
<MainFooter>
<Container>
<Row>
<Col xs={12} md={4}>
<Row>
<Col xs={12}>
<GatsbyLink
to={`/?builderId=${builderId}`}
style={{ textDecoration: "none" }}
>
<LogoCont>
{state.main.logoDark.isImage ? (
<Logo src={state.main.logoDark.value} alt='logo' />
) : (
<HeaderTitle>{state.main.logoDark.value}</HeaderTitle>
)}
</LogoCont>
</GatsbyLink>
</Col>
<Col xs={12}>
<OfficeInfoCont>
{/* <OfficeInfo>
{office.address}
</OfficeInfo> */}
<OfficeInfo>{office.phone}</OfficeInfo>
<OfficeInfo>{office.email}</OfficeInfo>
</OfficeInfoCont>
</Col>
</Row>
</Col>
<Col xs={12} md={4}>
<NavCont>
<Row>
<Col xs={6} md={6}>
<NavLink to={`/about?builderId=${builderId}`}>
Nosotros
</NavLink>
</Col>
<Col xs={6} md={6}>
<NavLink to={`/properties?builderId=${builderId}`}>
Propiedades
</NavLink>
</Col>
{/* <Visible md xs xxl lg xl>
<Col xs={6} md={6}>
<NavLink to="/news">
Noticias
</NavLink>
</Col>
</Visible>*/}
<Col xs={6} md={6}>
<NavLink to={`/contact?builderId=${builderId}`}>
Contacto
</NavLink>
</Col>
</Row>
</NavCont>
</Col>
<Col xs={12} md={4}>
<Row>
<Col xs={12}></Col>
<Col xs={12}>
<Hidden xs>
<BackTopCont>
<BackTop onClick={handleTop} href='#top'>
<img src='/icons/chevron-up.svg' alt='backtop' />
</BackTop>
</BackTopCont>
</Hidden>
<SocialNav>
<li>Siguenos en</li>
<SocialItem style={{ marginLeft: "1rem" }}>
<a
href='https://www.facebook.com'
alt='facebook'
rel='noopener'
>
<SvgIcon
social={true}
width='9'
height='17'
viewBox='0 0 9 17'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<path
fillRule='evenodd'
clipRule='evenodd'
d='M6.27373 2.90134C5.87719 2.90134 5.47699 3.28387 5.47699 3.56846V5.47396H8.27186C8.15933 6.93509 7.9283 8.27121 7.9283 8.27121H5.46269V16.5517H1.78855V8.27032H0V5.48389H1.78855V3.20574C1.78855 2.78916 1.69814 0 5.5531 0H8.27586V2.90134H6.27373Z'
/>
</SvgIcon>
</a>
</SocialItem>
<SocialItem>
<a
href='https://www.instagram.com'
alt='instagram'
rel='noopener'
>
<SvgIcon
social={true}
width='18'
height='18'
viewBox='0 0 18 18'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<path
fillRule='evenodd'
clipRule='evenodd'
d='M5.54187 0H12.1921C15.2523 0 17.734 2.48165 17.734 5.54187V12.1921C17.734 15.2523 15.2523 17.734 12.1921 17.734H5.54187C2.48165 17.734 0 15.2523 0 12.1921V5.54187C0 2.48165 2.48165 0 5.54187 0ZM12.1921 16.0714C14.3313 16.0714 16.0714 14.3313 16.0714 12.1921V5.54187C16.0714 3.40271 14.3313 1.66256 12.1921 1.66256H5.54187C3.40271 1.66256 1.66256 3.40271 1.66256 5.54187V12.1921C1.66256 14.3313 3.40271 16.0714 5.54187 16.0714H12.1921Z'
/>
<path
fillRule='evenodd'
clipRule='evenodd'
d='M4.43359 8.86697C4.43359 6.41857 6.41869 4.43347 8.86709 4.43347C11.3155 4.43347 13.3006 6.41857 13.3006 8.86697C13.3006 11.3154 11.3155 13.3005 8.86709 13.3005C6.41869 13.3005 4.43359 11.3154 4.43359 8.86697ZM6.09616 8.86697C6.09616 10.3943 7.33975 11.6379 8.86709 11.6379C10.3944 11.6379 11.638 10.3943 11.638 8.86697C11.638 7.33852 10.3944 6.09603 8.86709 6.09603C7.33975 6.09603 6.09616 7.33852 6.09616 8.86697Z'
/>
<circle
cx='13.6332'
cy='4.10096'
r='0.590764'
fill='#A05FFF'
/>
</SvgIcon>
</a>
</SocialItem>
</SocialNav>
</Col>
</Row>
</Col>
</Row>
</Container>
</MainFooter>
<FooterRightsCont>
<Container>
<FooterRights>
<li>© Todos los derechos reservados</li>
<li>
Desarrollado por{" "}
<DevelopBy
href='https://clasihome.com/'
alt='clasihome website'
rel='noopener'
target='_blank'
>
Clasihome
</DevelopBy>
</li>
</FooterRights>
</Container>
</FooterRightsCont>
</Footer>
);
};
/*
<GatsbyLink to="/" style={{ textDecoration: 'none' }}>
<a href="/">
{
state.main.logo.isImage
?<Logo src={state.main.logo.value} alt="logo" />
:<HeaderTitle>{state.main.logo.value}</HeaderTitle>
}
</a>
</GatsbyLink>
*/
| 32.903974 | 466 | 0.460199 |
c1b4b307a501687b51001f41a9799ed68afba76a | 479 | js | JavaScript | src/components/testimonials/arrow-right.js | CharterXavi/charter-official | c6ac809bfc231f8c794bb084284a7dd29d1ed7b3 | [
"RSA-MD"
] | null | null | null | src/components/testimonials/arrow-right.js | CharterXavi/charter-official | c6ac809bfc231f8c794bb084284a7dd29d1ed7b3 | [
"RSA-MD"
] | null | null | null | src/components/testimonials/arrow-right.js | CharterXavi/charter-official | c6ac809bfc231f8c794bb084284a7dd29d1ed7b3 | [
"RSA-MD"
] | null | null | null | import './arrow-right.css';
import React from 'react';
import arrowRight from '../../images/iconography/arrow-right.png';
const ArrowRight = (props) => {
const handleClick = () => {
props.goToNext();
}
return (
<div className='ArrowRight' onClick={handleClick} onKeyDown={handleClick} role='button' tabIndex='0' >
<img src={arrowRight} alt="forward arrow" width='20' height='11.5'/>
</div>
);
};
export default ArrowRight; | 25.210526 | 110 | 0.617954 |
c1b4fb1a568c808bb140a3b32f10c8f6a1d726cd | 349 | js | JavaScript | client/app/components/Cards/Cards.js | Teenterror/cardsGame | 4b49cadebc0742e643d63631987f65380a8cb6f4 | [
"MIT"
] | null | null | null | client/app/components/Cards/Cards.js | Teenterror/cardsGame | 4b49cadebc0742e643d63631987f65380a8cb6f4 | [
"MIT"
] | 2 | 2021-03-10T17:16:05.000Z | 2021-05-11T13:04:36.000Z | client/app/components/Cards/Cards.js | Teenterror/cardsGame | 4b49cadebc0742e643d63631987f65380a8cb6f4 | [
"MIT"
] | 1 | 2020-07-15T07:22:58.000Z | 2020-07-15T07:22:58.000Z | import React, { Component } from "react";
//Create two React components for stating a game and joining it:
class Cards extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {}
render() {
return (
<div>
<h1>Cards Game</h1>
</div>
);
}
}
export default Cards;
| 15.173913 | 64 | 0.593123 |
c1b5d26c75b4746491de1a2eb0c6babc9c17ddd5 | 4,611 | js | JavaScript | admin/src/components/ImageCropper/index.js | rmros/rant | bfabe5f9a6e89b08fee5d8fbc7798823b2a0000a | [
"MIT"
] | null | null | null | admin/src/components/ImageCropper/index.js | rmros/rant | bfabe5f9a6e89b08fee5d8fbc7798823b2a0000a | [
"MIT"
] | null | null | null | admin/src/components/ImageCropper/index.js | rmros/rant | bfabe5f9a6e89b08fee5d8fbc7798823b2a0000a | [
"MIT"
] | 1 | 2021-12-29T03:11:54.000Z | 2021-12-29T03:11:54.000Z | import React, { Fragment } from 'react';
import { Modal, Upload, Icon } from 'antd';
import AvatarEditor from 'react-avatar-editor';
const gEditorStyle = { display: 'block', margin: '10px auto' };
export function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime,
});
}
export default class ImageCropper extends React.Component {
state = {
imageFile: null,
scale: 1,
width: 400,
height: 200,
borderRadius: 0,
};
componentDidMount() {
const { scale, width, height, borderRadius } = this.props;
this.setState(state => ({
...state,
scale: scale || 1,
width: width || 400,
height: height || 200,
borderRadius: borderRadius || 0,
}));
const self = this;
const scrollFunc = function(e) {
// var direct = 0;
e = e || window.event;
if (e.wheelDelta) {
//判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta > 0) {
//当滑轮向上滚动时
self.setState({ scale: self.state.scale + 0.1 });
}
if (e.wheelDelta < 0) {
//当滑轮向下滚动时
self.setState({ scale: self.state.scale - 0.1 });
}
} else if (e.detail) {
//Firefox滑轮事件
if (e.detail > 0) {
//当滑轮向上滚动时
self.setState({ scale: self.state.scale + 0.1 });
}
if (e.detail < 0) {
//当滑轮向下滚动时
self.setState({ scale: self.state.scale - 0.1 });
}
}
};
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
} // W3C
window.onmousewheel = document.onmousewheel = scrollFunc; // IE/Opera/Chrome
}
beforeUpload = imageFile => {
this.setState({ imageFile });
return false;
};
toUpload = () => {
const { onUpload } = this.props;
const { imageFile } = this.state;
if (!!onUpload && !!imageFile && !!this.editor) {
const fakefile = dataURLtoBlob(this.editor.getImageScaledToCanvas().toDataURL('image/png'));
fakefile.name = imageFile.name;
onUpload(fakefile);
}
this.setState({ imageFile: null });
};
toCloseModal = () => {
const { onCancel } = this.props;
if (!!onCancel) onCancel();
this.setState({ imageFile: null });
};
onScaleChange = value => {
this.setState(state => ({
...state,
scale: value,
}));
};
onWidthChange = value => {
this.setState(state => ({
...state,
width: value,
}));
};
onHeightChange = value => {
this.setState(state => ({
...state,
height: value,
}));
};
onRadiusChange = value => {
this.setState(state => ({
...state,
borderRadius: value,
}));
};
render() {
const { imageFile, scale, width, height, borderRadius } = this.state;
const { url } = this.props;
return (
<Fragment>
<Upload
action={null}
accept="image/*"
showUploadList={false}
beforeUpload={this.beforeUpload}
>
<div
style={{
textAlign: 'center',
width,
height,
border: '1px #ccc dashed',
position: 'relative',
cursor: 'pointer',
}}
>
{!url ? (
<Fragment>
<p className="ant-upload-drag-icon" style={{ width, paddingTop: height * 0.3 }}>
<Icon type="upload" />
</p>
<p className="ant-upload-text">点击上传图片</p>
</Fragment>
) : (
<img style={{ maxWidth: width }} src={url} />
)}
</div>
</Upload>
<Modal
visible={!!imageFile}
title="图片裁剪"
okText="确认"
cancelText="取消"
width={width < 200 ? 400 : width + 100}
height={height}
onOk={this.toUpload}
onCancel={this.toCloseModal}
>
<AvatarEditor
border={1}
color={[72, 118, 255, 0.6]}
style={gEditorStyle}
ref={e => (this.editor = e)}
image={imageFile}
scale={scale}
width={width}
height={height}
borderRadius={borderRadius}
/>
<br />
<h3>{`请上传 ${width}px(宽) * ${height}px(高) 大小的图片`}</h3>
</Modal>
</Fragment>
);
}
}
| 24.657754 | 98 | 0.499241 |
c1b5df76b900fdcc4f396b851d6be9792699708e | 1,127 | js | JavaScript | node_modules/nexus/dist/definitions/extendInputType.js | melanieph/mooody-test | 0c515581bd0baad75e4fb9da7c9b19a73788b6ec | [
"MIT"
] | null | null | null | node_modules/nexus/dist/definitions/extendInputType.js | melanieph/mooody-test | 0c515581bd0baad75e4fb9da7c9b19a73788b6ec | [
"MIT"
] | null | null | null | node_modules/nexus/dist/definitions/extendInputType.js | melanieph/mooody-test | 0c515581bd0baad75e4fb9da7c9b19a73788b6ec | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _types_1 = require("./_types");
var graphql_1 = require("graphql");
var NexusExtendInputTypeDef = /** @class */ (function () {
function NexusExtendInputTypeDef(name, config) {
this.name = name;
this.config = config;
graphql_1.assertValidName(name);
}
Object.defineProperty(NexusExtendInputTypeDef.prototype, "value", {
get: function () {
return this.config;
},
enumerable: true,
configurable: true
});
return NexusExtendInputTypeDef;
}());
exports.NexusExtendInputTypeDef = NexusExtendInputTypeDef;
_types_1.withNexusSymbol(NexusExtendInputTypeDef, _types_1.NexusTypes.ExtendInputObject);
/**
* Adds new fields to an existing inputObjectType in the schema. Useful when
* splitting your schema across several domains.
*
* @see http://graphql-nexus.com/api/extendType
*/
function extendInputType(config) {
return new NexusExtendInputTypeDef(config.type, config);
}
exports.extendInputType = extendInputType;
//# sourceMappingURL=extendInputType.js.map | 35.21875 | 89 | 0.712511 |
c1b5f03fecdcc9051564fcb6b33a740bbcaa7577 | 1,701 | js | JavaScript | dist/index.js | taunoha/postcss-simple-svg | 5da96fc39e53470f3ddfb4031c5f1e5941c76882 | [
"MIT"
] | null | null | null | dist/index.js | taunoha/postcss-simple-svg | 5da96fc39e53470f3ddfb4031c5f1e5941c76882 | [
"MIT"
] | null | null | null | dist/index.js | taunoha/postcss-simple-svg | 5da96fc39e53470f3ddfb4031c5f1e5941c76882 | [
"MIT"
] | null | null | null | (function() {
var SVGCache, _, postcss;
postcss = require('postcss');
SVGCache = require('./lib/svg_cache');
_ = require('lodash');
module.exports = postcss.plugin("postcss-simple-svg", function(options = {}) {
var SVGRegExp, funcName, replaceRegExp, silent;
funcName = options.func || 'svg';
SVGRegExp = new RegExp(`${funcName}\\("([^"]+)"(,\\s*"([^"]+)")?\\)`);
replaceRegExp = new RegExp(`${funcName}\\(("[^"]+"|\'[^\']+\')(,\\s*("[^"]+"|\'[^\']+\'))?\\)`);
silent = _.isBoolean(options.silent) ? options.silent : true;
if (options.debug) {
silent = false;
}
SVGCache.init(options);
return function(style, result) {
return style.walkDecls(/^background|^filter|^content|image$/, function(decl) {
var ___, error, matches, name, params, replace, svg;
if (!decl.value) {
return;
}
while (matches = SVGRegExp.exec(decl.value.replace(/'/g, '"'))) {
[___, name, ...params] = matches;
if (options.debug) {
console.time(`Render svg ${name}`);
}
try {
svg = SVGCache.get(name);
} catch (error1) {
error = error1;
if (silent) {
decl.warn(result, `postcss-simple-svg: ${error}`);
} else {
throw decl.error(error);
}
}
if (!svg) {
return;
}
replace = replaceRegExp.exec(decl.value)[0];
decl.value = decl.value.replace(replace, svg.dataUrl(params[1]));
if (options.debug) {
console.timeEnd(`Render svg ${name}`);
}
}
});
};
});
}).call(this);
| 30.927273 | 100 | 0.497942 |
c1b715a09635189ce727f33e39e51304083ce4b2 | 346 | js | JavaScript | javascript/7DaysOfJavaScript/day1/js-if-else-statements.js | nhquiroz/hacker-rank | 11872292d98286fe9cd191c316fbf3384ec66772 | [
"MIT"
] | null | null | null | javascript/7DaysOfJavaScript/day1/js-if-else-statements.js | nhquiroz/hacker-rank | 11872292d98286fe9cd191c316fbf3384ec66772 | [
"MIT"
] | null | null | null | javascript/7DaysOfJavaScript/day1/js-if-else-statements.js | nhquiroz/hacker-rank | 11872292d98286fe9cd191c316fbf3384ec66772 | [
"MIT"
] | null | null | null | if (marks <= 30) {
console.log('FF');
} else if (marks <= 40) {
console.log('DD');
} else if (marks <= 50) {
console.log('CD');
} else if (marks <= 60) {
console.log('CC');
} else if (marks <= 70) {
console.log('BC');
} else if (marks <= 80) {
console.log('BB');
} else if (marks <= 90) {
console.log('AB');
} else {
console.log('AA');
}
| 19.222222 | 25 | 0.540462 |
c1b88409b3c7ee92555177a13933f6c99eef8568 | 124 | js | JavaScript | src/plugins/v-tooltip.client.js | Byxlarge/website | fa57abb547be43acd0b433a25888c5105270483f | [
"MIT"
] | 10 | 2021-11-10T10:05:48.000Z | 2022-02-28T15:29:15.000Z | src/plugins/v-tooltip.client.js | Mehmetali345Dev/site | dce849a12136280c80680739c20dabbef4e46167 | [
"MIT"
] | 13 | 2021-11-18T19:24:04.000Z | 2022-01-04T05:01:25.000Z | src/plugins/v-tooltip.client.js | Mehmetali345Dev/site | dce849a12136280c80680739c20dabbef4e46167 | [
"MIT"
] | 3 | 2021-11-25T17:42:35.000Z | 2022-02-17T17:25:25.000Z | import Vue from 'vue'
import VTooltipPlugin from 'v-tooltip'
import 'v-tooltip/dist/v-tooltip.css'
Vue.use(VTooltipPlugin)
| 20.666667 | 38 | 0.782258 |
c1b8a0c2802484238b4e11a6cc888e63c5eac25d | 473 | js | JavaScript | js/simple-tabs.js | TeBenachi/Jquery-Tabs | d4b78b69651c10b9d6dc3b82a1052182c9dd30ab | [
"MIT"
] | null | null | null | js/simple-tabs.js | TeBenachi/Jquery-Tabs | d4b78b69651c10b9d6dc3b82a1052182c9dd30ab | [
"MIT"
] | null | null | null | js/simple-tabs.js | TeBenachi/Jquery-Tabs | d4b78b69651c10b9d6dc3b82a1052182c9dd30ab | [
"MIT"
] | null | null | null | $(function() {
$('.tabs li').on('click', function(){
$('.tabs li.active').removeClass('active');
$(this).addClass('active');
//Show active panel
var visiblePanel = $(this).attr('data-tab');
//Hide inactive panel
$('.panel.active').fadeOut(300, HidePanel);
function HidePanel() {
$(this).removeClass('active');
$('#'+visiblePanel).fadeIn(300, ShowPanel);
function ShowPanel() {
$(this).addClass('active');
};
};
});
}); | 16.892857 | 46 | 0.572939 |
c1b8ad83a0ca1a9e408bae73d78a49c60f061e6b | 142 | js | JavaScript | tests/role.js | turingou/leancloud | 54c8b2c452944b265f0d450bda725eaf9dd88680 | [
"MIT"
] | 4 | 2015-08-20T02:01:45.000Z | 2015-09-10T15:04:12.000Z | tests/role.js | turingou/leancloud | 54c8b2c452944b265f0d450bda725eaf9dd88680 | [
"MIT"
] | null | null | null | tests/role.js | turingou/leancloud | 54c8b2c452944b265f0d450bda725eaf9dd88680 | [
"MIT"
] | null | null | null | import should from 'should'
import leancloud from './'
describe('#role', () => {
it('It should create a role', done => {
done()
})
}) | 17.75 | 41 | 0.577465 |
c1b9574c3b7765fed22cb0d3dfd19186b0968c64 | 2,321 | js | JavaScript | client-app/src/container/users/list/UsersList.js | code-en-design/econobis | 0b082160bad338691cc58223b8840d7f1fe2b1aa | [
"CECILL-B"
] | 4 | 2018-10-16T19:45:01.000Z | 2021-03-23T11:53:38.000Z | client-app/src/container/users/list/UsersList.js | code-en-design/econobis | 0b082160bad338691cc58223b8840d7f1fe2b1aa | [
"CECILL-B"
] | 11 | 2020-03-19T08:17:46.000Z | 2021-12-24T09:10:24.000Z | client-app/src/container/users/list/UsersList.js | code-en-design/econobis | 0b082160bad338691cc58223b8840d7f1fe2b1aa | [
"CECILL-B"
] | 3 | 2020-02-28T10:31:00.000Z | 2020-12-09T13:30:59.000Z | import React, { Component } from 'react';
import DataTable from '../../../components/dataTable/DataTable';
import DataTableHead from '../../../components/dataTable/DataTableHead';
import DataTableBody from '../../../components/dataTable/DataTableBody';
import DataTableHeadTitle from '../../../components/dataTable/DataTableHeadTitle';
import UsersListItem from './UsersListItem';
import { connect } from 'react-redux';
class UsersList extends Component {
constructor(props) {
super(props);
}
render() {
let loadingText = '';
let loading = true;
if (this.props.hasError) {
loadingText = 'Fout bij het ophalen van gebruikers.';
} else if (this.props.isLoading) {
loadingText = 'Gegevens aan het laden.';
} else if (this.props.users.length === 0) {
loadingText = 'Geen gebruikers gevonden!';
} else {
loading = false;
}
return (
<div>
<DataTable>
<DataTableHead>
<tr className="thead-title">
<DataTableHeadTitle title={'Voornaam'} width={'30%'} />
<DataTableHeadTitle title={'Achternaam'} width={'25%'} />
<DataTableHeadTitle title={'E-mail'} width={'30%'} />
<DataTableHeadTitle title={'Status'} width={'10%'} />
<DataTableHeadTitle title={''} width={'5%'} />
</tr>
</DataTableHead>
<DataTableBody>
{loading ? (
<tr>
<td colSpan={11}>{loadingText}</td>
</tr>
) : (
this.props.users.map(user => {
return <UsersListItem key={user.id} {...user} />;
})
)}
</DataTableBody>
</DataTable>
</div>
);
}
}
const mapStateToProps = state => {
return {
isLoading: state.loadingData.isLoading,
hasError: state.loadingData.hasError,
};
};
export default connect(mapStateToProps)(UsersList);
| 35.707692 | 85 | 0.476519 |
c1babf773fc1617c2fc021b6b741ba5a5e8c3564 | 4,790 | js | JavaScript | app/contact-app/contact-webapp/src/main/webapp/touch/sdk/src/device/communicator/Default.js | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 213 | 2015-01-11T16:07:13.000Z | 2022-03-29T13:19:50.000Z | app/contact-app/contact-webapp/src/main/webapp/touch/sdk/src/device/communicator/Default.js | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 8 | 2017-04-24T23:36:43.000Z | 2022-02-10T15:41:23.000Z | app/contact-app/contact-webapp/src/main/webapp/touch/sdk/src/device/communicator/Default.js | hiya492/spring | 95b49d64b5f6cab4ee911a92772e5ae446a380af | [
"Apache-2.0"
] | 250 | 2015-01-05T12:54:49.000Z | 2021-09-24T11:00:33.000Z | /**
* @private
*
* This object handles communication between the WebView and Sencha's native shell.
* Currently it has two primary responsibilities:
*
* 1. Maintaining unique string ids for callback functions, together with their scope objects
* 2. Serializing given object data into HTTP GET request parameters
*
* As an example, to capture a photo from the device's camera, we use `Ext.device.Camera.capture()` like:
*
* Ext.device.Camera.capture(
* function(dataUri){
* // Do something with the base64-encoded `dataUri` string
* },
* function(errorMessage) {
*
* },
* callbackScope,
* {
* quality: 75,
* width: 500,
* height: 500
* }
* );
*
* Internally, `Ext.device.Communicator.send()` will then be invoked with the following argument:
*
* Ext.device.Communicator.send({
* command: 'Camera#capture',
* callbacks: {
* onSuccess: function() { ... },
* onError: function() { ... },
* },
* scope: callbackScope,
* quality: 75,
* width: 500,
* height: 500
* });
*
* Which will then be transformed into a HTTP GET request, sent to native shell's local
* HTTP server with the following parameters:
*
* ?quality=75&width=500&height=500&command=Camera%23capture&onSuccess=3&onError=5
*
* Notice that `onSuccess` and `onError` have been converted into string ids (`3` and `5`
* respectively) and maintained by `Ext.device.Communicator`.
*
* Whenever the requested operation finishes, `Ext.device.Communicator.invoke()` simply needs
* to be executed from the native shell with the corresponding ids given before. For example:
*
* Ext.device.Communicator.invoke('3', ['DATA_URI_OF_THE_CAPTURED_IMAGE_HERE']);
*
* will invoke the original `onSuccess` callback under the given scope. (`callbackScope`), with
* the first argument of 'DATA_URI_OF_THE_CAPTURED_IMAGE_HERE'
*
* Note that `Ext.device.Communicator` maintains the uniqueness of each function callback and
* its scope object. If subsequent calls to `Ext.device.Communicator.send()` have the same
* callback references, the same old ids will simply be reused, which guarantee the best possible
* performance for a large amount of repeative calls.
*/
Ext.define('Ext.device.communicator.Default', {
SERVER_URL: 'http://localhost:3000', // Change this to the correct server URL
callbackDataMap: {},
callbackIdMap: {},
idSeed: 0,
globalScopeId: '0',
generateId: function() {
return String(++this.idSeed);
},
getId: function(object) {
var id = object.$callbackId;
if (!id) {
object.$callbackId = id = this.generateId();
}
return id;
},
getCallbackId: function(callback, scope) {
var idMap = this.callbackIdMap,
dataMap = this.callbackDataMap,
id, scopeId, callbackId, data;
if (!scope) {
scopeId = this.globalScopeId;
}
else if (scope.isIdentifiable) {
scopeId = scope.getId();
}
else {
scopeId = this.getId(scope);
}
callbackId = this.getId(callback);
if (!idMap[scopeId]) {
idMap[scopeId] = {};
}
if (!idMap[scopeId][callbackId]) {
id = this.generateId();
data = {
callback: callback,
scope: scope
};
idMap[scopeId][callbackId] = id;
dataMap[id] = data;
}
return idMap[scopeId][callbackId];
},
getCallbackData: function(id) {
return this.callbackDataMap[id];
},
invoke: function(id, args) {
var data = this.getCallbackData(id);
data.callback.apply(data.scope, args);
},
send: function(args) {
var callbacks, scope, name, callback;
if (!args) {
args = {};
}
else if (args.callbacks) {
callbacks = args.callbacks;
scope = args.scope;
delete args.callbacks;
delete args.scope;
for (name in callbacks) {
if (callbacks.hasOwnProperty(name)) {
callback = callbacks[name];
if (typeof callback == 'function') {
args[name] = this.getCallbackId(callback, scope);
}
}
}
}
this.doSend(args);
},
doSend: function(args) {
var xhr = new XMLHttpRequest();
xhr.open('GET', this.SERVER_URL + '?' + Ext.Object.toQueryString(args), false);
xhr.send(null);
}
});
| 28.511905 | 105 | 0.572234 |
c1bb0c5818681641c64358fb644e56ff708288e6 | 1,311 | js | JavaScript | src/components/FilterByPosition.test.js | rycu/team-player | 9154daf762721e6ce22acebfb328d492a7078fb5 | [
"MIT"
] | null | null | null | src/components/FilterByPosition.test.js | rycu/team-player | 9154daf762721e6ce22acebfb328d492a7078fb5 | [
"MIT"
] | null | null | null | src/components/FilterByPosition.test.js | rycu/team-player | 9154daf762721e6ce22acebfb328d492a7078fb5 | [
"MIT"
] | null | null | null | import React from 'react'
import { shallow, mount } from 'enzyme'
import FilterByPosition from './FilterByPosition'
const setup = testProps => {
const props = Object.assign({
updatePositionFilter: jest.fn(),
apiData__positions: [{id:1},{id:2},{id:3},{id:4}],
positionArr: [1,2,3,4],
className: 'test_pos_class'
}, testProps)
const output = shallow(<FilterByPosition {...props} />);
const fullDOM = mount(<FilterByPosition {...props} />);
return {
props: props,
output: output,
fullDOM: fullDOM
}
}
describe('components', () => {
describe('FilterByPosition', () => {
it('should render correctly', () => {
const { output, props } = setup()
expect(output.node.type).toBe('ul')
expect(output.node.props.className).toBe(props.className)
expect(output.node.props.placeholder).toBe(props.placeholder)
})
it('should call updatePositionFilter on change', () => {
const { output, props } = setup()
output.find('[type="checkbox"]').node.props.onChange({target: { checked: false, id:1 } })
expect(props.updatePositionFilter).toBeCalledWith(false, 1)
})
it('should uncheck positons not in positionArr prop', () => {
const { fullDOM, props } = setup()
fullDOM.setProps({positionArr:[1,2,3]})
fullDOM.node.renderCheckbox(4)
})
})
})
| 26.22 | 91 | 0.653699 |