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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5db3fe741cdb60ad55cffa7f51d4af57938f48d | 1,643 | js | JavaScript | src/test/2.js | archguard/archguard-cli | e6970f68812058ac2ba0026127b44cc428b0813f | [
"MIT"
] | 16 | 2022-02-15T15:10:21.000Z | 2022-02-23T03:04:34.000Z | src/test/2.js | archguard/archguard-cli | e6970f68812058ac2ba0026127b44cc428b0813f | [
"MIT"
] | null | null | null | src/test/2.js | archguard/archguard-cli | e6970f68812058ac2ba0026127b44cc428b0813f | [
"MIT"
] | null | null | null | const parser = require('@babel/parser');
const fs = require('fs');
const testData = `const menuList = configForTargets({
default: [
{ key: '/system-evaluation/Summary', text: '总览' },
{
key: 'systemEvaluation',
text: '架构评估',
children: [
{ key: '/system-evaluation/sizing-evaluation', text: '体量维度' },
{ key: '/system-evaluation/coupling-evaluation', text: '耦合维度' },
{ key: '/system-evaluation/cohesion-evaluation', text: '内聚度维度' },
{ key: '/system-evaluation/Redundancy', text: '冗余度维度' },
],
},
],
});`;
const generator = require('@babel/generator').default;
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
function createMemberExpression() {
return t.objectExpression([
{
key: t.identifier('a'),
type: 'ObjectProperty',
// computed: false,
// shorthand: true,
// decorators: null,
value: t.identifier('2222222'),
},
]);
}
function compile(code) {
const ast = parser.parse(code);
traverse(ast, {
StringLiteral(path) {
if (path.node.value === 'systemEvaluation') {
// const parent = path.parent;
// console.log('parent: ', parent);
// console.log('path 的值是:', path);
}
},
ArrayExpression(path) {
const { node } = path;
node.elements.push(createMemberExpression());
path.stop();
},
});
return generator(ast, {}, code);
}
const result = compile(testData);
console.log('result: ', result);
fs.writeFileSync('message.js', JSON.stringify(result));
// console.log('result 的值是:', JSON.stringify(result));
| 25.276923 | 73 | 0.597079 |
d5dc1a0b9147e9ec7e5bf81993e81f2cfcc0894b | 2,909 | js | JavaScript | Gruntfile.js | scottbcovert/ng-countdown-ribbon | 83340a746cb836d80381b2f5a2e36ad783b81001 | [
"MIT"
] | 9 | 2015-08-12T22:26:29.000Z | 2018-06-26T13:15:57.000Z | Gruntfile.js | scottbcovert/ng-countdown-ribbon | 83340a746cb836d80381b2f5a2e36ad783b81001 | [
"MIT"
] | 16 | 2015-01-08T15:41:53.000Z | 2021-07-26T06:20:03.000Z | Gruntfile.js | scottbcovert/ng-countdown-ribbon | 83340a746cb836d80381b2f5a2e36ad783b81001 | [
"MIT"
] | 1 | 2022-02-26T13:19:03.000Z | 2022-02-26T13:19:03.000Z | module.exports = function(grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-processhtml');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
jshint: {
files: [
'Gruntfile.js',
'src/scripts/**/*.js',
'demo/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
clean: {
dist: ['dist']
},
sass: {
build: {
files: {
'src/styles/ng-countdown-ribbon.css': 'src/styles/ng-countdown-ribbon.scss'
}
}
},
cssmin: {
build: {
files: {
'dist/ng-countdown-ribbon.min.css': 'src/styles/ng-countdown-ribbon.css'
}
},
demo: {
files: {
'_gh-pages/demo.min.css': [
'src/styles/ng-countdown-ribbon.css',
'demo/demo.css'
]
}
}
},
processhtml: {
build: {
files: {
'_gh-pages/index.html': 'demo/index.html'
}
}
},
htmlmin: {
options: {
removeComments: true,
collapseWhitespace: true
},
index: {
files: {
'_gh-pages/index.html': '_gh-pages/index.html'
}
}
},
uglify: {
build: {
files: {
'dist/ng-countdown-ribbon.min.js': 'src/**/*.js'
}
},
demo: {
files: {
'_gh-pages/demo.min.js': [
'bower_components/angular/angular.js',
'src/scripts/ng-countdown-ribbon.js',
'demo/demo.js'
]
}
}
},
watch: {
scripts: {
files: ['src/**/*', 'demo/**/*'],
tasks: ['build']
}
}
});
grunt.registerTask('build', [
'jshint',
'clean',
'sass',
'cssmin:build',
'uglify:build',
'demo'
]);
grunt.registerTask('demo', [
'processhtml',
'htmlmin',
'cssmin:demo',
'uglify:demo'
]);
grunt.registerTask('default', ['build']);
grunt.registerTask('dev', ['build', 'watch']);
};
| 24.241667 | 95 | 0.385356 |
d5de3566b9720092994c571b720ad79b5b426238 | 347 | js | JavaScript | blueprints/recognizer/files/__root__/ember-gestures/recognizers/__name__.js | iarroyo/ember-gestures | 2fd0814be9304be8900a7d7216b532c14a9aecc9 | [
"MIT"
] | 46 | 2016-11-06T11:09:30.000Z | 2021-08-10T14:44:24.000Z | blueprints/recognizer/files/__root__/ember-gestures/recognizers/__name__.js | iarroyo/ember-gestures | 2fd0814be9304be8900a7d7216b532c14a9aecc9 | [
"MIT"
] | 80 | 2016-11-03T18:21:01.000Z | 2022-01-03T16:48:10.000Z | blueprints/recognizer/files/__root__/ember-gestures/recognizers/__name__.js | iarroyo/ember-gestures | 2fd0814be9304be8900a7d7216b532c14a9aecc9 | [
"MIT"
] | 35 | 2016-11-24T04:18:09.000Z | 2021-11-05T08:54:04.000Z | export default {
include: ['tap'], //an array of recognizers to recognize with.
exclude: [], //an array of recognizers that must first fail
options: {
taps: 2 // the settings to pass to the recognizer, event will be added automatically
},
recognizer: 'tap' // `tap|press|pan|swipe|rotate|pinch` the base Hammer recognizer to use
};
| 38.555556 | 91 | 0.700288 |
d5de50d93f97eb524abf879295b16a7225d31323 | 510 | js | JavaScript | home/resource/js/sign.js | 78778443/permeate | 7f923d1632e16a5b5e94b5a914c9426c1accd460 | [
"MIT"
] | 260 | 2017-06-28T01:20:22.000Z | 2022-03-29T08:47:03.000Z | static/dist/js/sign.js | wangyu-geek/permeate | 2d4ec0a22a95200391b46f90e1aee8e367060254 | [
"MIT"
] | 7 | 2018-06-14T04:50:53.000Z | 2022-01-28T03:25:41.000Z | static/dist/js/sign.js | wangyu-geek/permeate | 2d4ec0a22a95200391b46f90e1aee8e367060254 | [
"MIT"
] | 60 | 2017-10-21T17:05:22.000Z | 2022-02-22T03:03:49.000Z | !(function ($, w, d) {
// 登陆注册切换
var $controller = $('.sign-controller-item').find('a');
var $container = $('.sign-container-item');
$controller.on('click',function(event){
event.preventDefault();
var $this = this;
var index = $controller.index($this);
var active = 'is-active';
$container.removeClass(active).eq(index).addClass(active);
$controller.removeClass(active).eq(index).addClass(active);
});
})($, window, document) | 23.181818 | 67 | 0.576471 |
d5df2cdc68c8f41733ce1e41886a5e459a8e3a27 | 2,092 | js | JavaScript | dist/modules/Html/downloadSDK.js | divvy-digital/androidjs-builder | a396e4fe1491b054dd0538572f7f3fb91998d1f5 | [
"MIT"
] | null | null | null | dist/modules/Html/downloadSDK.js | divvy-digital/androidjs-builder | a396e4fe1491b054dd0538572f7f3fb91998d1f5 | [
"MIT"
] | null | null | null | dist/modules/Html/downloadSDK.js | divvy-digital/androidjs-builder | a396e4fe1491b054dd0538572f7f3fb91998d1f5 | [
"MIT"
] | null | null | null | #!/usr/bin/env node
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadSDK = void 0;
const fs = __importStar(require("fs"));
const request = __importStar(require("request"));
const ProgressBar_1 = require("./ProgressBar");
function downloadSDK(env, url, to, callback) {
// process.stdout.write(`Downloading ${link}`);
let fileStream = fs.createWriteStream(to);
let loading = new ProgressBar_1.LoadingBar();
let receivedBytes = 0;
request
.get({ url: url, headers: { 'User-Agent': 'request' } })
.on('response', response => {
if (response.statusCode === 200) {
loading.start();
// bar.total = parseInt(response.headers['content-length']);
// console.log("H:",parseInt(response.headers['content-length']));
}
else {
console.log("error");
}
})
.on('data', (chunk) => {
receivedBytes += chunk.length;
})
.on('end', (code) => {
loading.stop();
})
.on('error', (err) => {
// @ts-ignore
fs.unlink(local_file);
loading.stop();
})
.pipe(fileStream);
// callback();
}
exports.downloadSDK = downloadSDK;
| 35.457627 | 131 | 0.581262 |
d5df90acefd2bc9f8c7b935a4deebd177d9523db | 2,917 | js | JavaScript | packages/razzle-plugin-oreact/src/index.js | oreactjs/oreact | 5e9fe8dad23a8d59cd27c75d60ef76b8d9b11455 | [
"MIT"
] | 9 | 2020-06-03T05:19:46.000Z | 2021-01-22T07:38:22.000Z | packages/razzle-plugin-oreact/src/index.js | oreactjs/oreact | 5e9fe8dad23a8d59cd27c75d60ef76b8d9b11455 | [
"MIT"
] | 7 | 2021-05-11T16:12:27.000Z | 2022-02-27T05:55:10.000Z | packages/razzle-plugin-oreact/src/index.js | oreactjs/oreact | 5e9fe8dad23a8d59cd27c75d60ef76b8d9b11455 | [
"MIT"
] | 1 | 2022-01-16T21:39:33.000Z | 2022-01-16T21:39:33.000Z | 'use strict';
const path = require('path');
const fs = require('fs');
const LoadableWebpackPlugin = require('@loadable/webpack-plugin');
const loaderFinder = require('razzle-dev-utils/makeLoaderFinder');
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const scssExtend = require('./scss');
const graphqlExtend = require('./graphql');
module.exports = (
config,
{target, dev},
webpack,
userOptions = {}
) => {
let appConfig = Object.assign({}, config);
// Webpack config
appConfig['resolve']['modules'] = [
...appConfig['resolve']['modules'],
'src',
'src/app'
];
appConfig['resolve']['alias'] = {
...appConfig['resolve']['alias'],
react: resolveApp('node_modules/react'),
'react-dom': resolveApp('node_modules/react-dom'),
'@material-ui/styles': resolveApp('node_modules/@material-ui/styles')
};
appConfig['resolve']['extensions'] = [...appConfig['resolve']['extensions'], '.ts', '.tsx'];
// Reference : https://github.com/smooth-code/loadable-components/blob/master/examples/razzle/razzle.config.js
if (target === 'web') {
// Extend webpack plugin by loadable
appConfig.plugins = [
...appConfig.plugins,
new LoadableWebpackPlugin({
filename: 'chunks.json',
writeToDisk: {filename : resolveApp('build')},
outputAsset: false
})
];
// Fix style order for development
if(dev) {
appConfig['devServer'] = {
...appConfig['devServer'],
inline: true
};
const cssRule = appConfig.module.rules.find(loaderFinder('style-loader'));
cssRule.use[0] = {
loader: cssRule.use[0],
options: {
insertInto: 'body'
}
};
} else {
appConfig.output = {
...appConfig.output,
filename: 'static/js/[name].[chunkhash:8].js'
}
}
appConfig.node = {fs: 'empty'}; // fix "Cannot find module 'fs'" problem.
appConfig.optimization = Object.assign({}, appConfig.optimization, {
runtimeChunk: true,
splitChunks: {
chunks: 'all',
name: dev,
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: -5,
chunks: 'all'
}
}
}
});
}
// Graphql config
appConfig = graphqlExtend(appConfig,{ target, dev }, webpack, userOptions);
return scssExtend(appConfig, { target, dev }, webpack, userOptions);
};
| 31.365591 | 114 | 0.520055 |
d5e045cea81e0e8b986b70f44cfce2aa7c8b6acd | 2,262 | js | JavaScript | index.js | AdityaGovardhan/ga-pull-requests-projects | a6db1ac3de249a9aee04fb14fbc420cbbabc3cc9 | [
"MIT"
] | 2 | 2020-05-16T00:58:52.000Z | 2021-02-23T09:35:08.000Z | index.js | AdityaGovardhan/ga-pull-requests-projects | a6db1ac3de249a9aee04fb14fbc420cbbabc3cc9 | [
"MIT"
] | null | null | null | index.js | AdityaGovardhan/ga-pull-requests-projects | a6db1ac3de249a9aee04fb14fbc420cbbabc3cc9 | [
"MIT"
] | null | null | null | const core = require('@actions/core');
const fetch = require('node-fetch');
async function github_query(github_token, query, variables) {
return fetch('https://api.github.com/graphql', {
method: 'POST',
body: JSON.stringify({query, variables}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `bearer ${github_token}`,
}
}).then(function(response) {
return response.json();
});
}
// most @actions toolkit packages have async methods
async function run() {
try {
const pull_request = core.getInput('pull_request');
const repository = core.getInput('repository');
const github_token = core.getInput('github_token');
let query = `
query($owner:String!, $name:String!){
repository(owner: $owner, name: $name) {
projects(first:1) {
nodes {
id
name
}
}
}
}`;
let variables = { owner: repository.split("/")[0], name: repository.split("/")[1] };
let response = await github_query(github_token, query, variables);
console.log(response);
const project = response['data']['repository']['projects']['nodes'][0];
query = `
query($owner:String!, $name:String!, $number:Int!){
repository(owner: $owner, name: $name) {
pullRequest(number:$number) {
id
}
}
}`;
variables = { owner: repository.split("/")[0], name: repository.split("/")[1], number: parseInt(pull_request) };
response = await github_query(github_token, query, variables);
console.log(response);
const pullRequestId = response['data']['repository']['pullRequest']['id'];
console.log(`Adding Pull Request ${pull_request} to ${project['name']}`);
console.log("");
query = `
mutation($pullRequestId:ID!, $projectId:ID!) {
updatePullRequest(input:{pullRequestId:$pullRequestId, projectIds:[$projectId]}) {
pullRequest {
id
}
}
}`;
variables = { pullRequestId, projectId: project['id'] };
response = await github_query(github_token, query, variables);
console.log(response);
console.log(`Done!`)
}
catch (error) {
core.setFailed(error.message);
}
}
run()
| 28.632911 | 116 | 0.608311 |
d5e05d459d33c9397e04b91e9436e6f3921aee41 | 157 | js | JavaScript | src/page-link.js | Lumavate-Team/js-properties | b631b7f63ef56dabc9fda1fcf4c5cfa69e5f0e9e | [
"MIT"
] | null | null | null | src/page-link.js | Lumavate-Team/js-properties | b631b7f63ef56dabc9fda1fcf4c5cfa69e5f0e9e | [
"MIT"
] | null | null | null | src/page-link.js | Lumavate-Team/js-properties | b631b7f63ef56dabc9fda1fcf4c5cfa69e5f0e9e | [
"MIT"
] | null | null | null | import { BaseProperty } from './base'
export class PageLinkProperty extends BaseProperty {
constructor() {
super()
this.type = 'page-link'
}
}
| 15.7 | 52 | 0.66242 |
d5e1855fcff29b7a7293cbc80b832864e5626066 | 1,324 | js | JavaScript | web/src/components/main/filterContentSection.js | OceanOver/react-todo | 41f6648f887878486518ee69996b7208aec25f93 | [
"MIT"
] | 3 | 2016-11-07T04:42:28.000Z | 2017-03-28T10:04:10.000Z | web/src/components/main/filterContentSection.js | OceanOver/react-todo | 41f6648f887878486518ee69996b7208aec25f93 | [
"MIT"
] | null | null | null | web/src/components/main/filterContentSection.js | OceanOver/react-todo | 41f6648f887878486518ee69996b7208aec25f93 | [
"MIT"
] | null | null | null | import React, {Component, PropTypes} from 'react'
import {Row, Col} from 'antd'
import FilterContentCell from './filterContentCell'
import './style/filterContentSection.less'
import moment from 'moment'
import _ from 'lodash'
class FilterContentSection extends Component {
render() {
const {todos,actions,section,contentState} = this.props
var time
let headItem = _.head(section)
if (contentState == 1) {
time = headItem.expireTime
} else {
time = headItem.completeTime
}
let completedDate = moment.utc(time, 'YYYYMMDDHHmmss').local()
let date = completedDate.format('MM月DD日')
let day = completedDate.format('dddd')
return (
<li>
<Row className="section">
<Col span={4}>
<div className="section-title">
<span className="title-date">{date}</span><br/>{day}
</div>
</Col>
<Col span={20}>
<ul className="section-list">
{_.map(section, function(item) {
return <FilterContentCell todos={todos} actions={actions} item={item} key={item.id}/>
})}
</ul>
</Col>
</Row>
</li>
)
}
}
FilterContentSection.propTypes = {
section: PropTypes.array.isRequired
}
export default FilterContentSection
| 27.583333 | 101 | 0.598943 |
d5e195a16702385b9db6e95a3d3e3cd24b1301f0 | 8,349 | js | JavaScript | tests/routes/Selections/modules/selections.spec.js | jobdoc/selections-app | b0f2d3913596ef3822ccbc17f0306c7badab7da5 | [
"MIT"
] | null | null | null | tests/routes/Selections/modules/selections.spec.js | jobdoc/selections-app | b0f2d3913596ef3822ccbc17f0306c7badab7da5 | [
"MIT"
] | null | null | null | tests/routes/Selections/modules/selections.spec.js | jobdoc/selections-app | b0f2d3913596ef3822ccbc17f0306c7badab7da5 | [
"MIT"
] | null | null | null | import {
ADD_SELECTION,
POST_SELECTION_REQUEST,
POST_SELECTION_FAILURE,
POST_SELECTION_SUCCESS,
FETCH_SELECTIONS_REQUEST,
FETCH_SELECTIONS_FAILURE,
FETCH_SELECTIONS_SUCCESS,
addSelection,
loadSelections,
default as selectionsReducer
} from 'routes/Selections/modules/selections'
import fetchMock from 'fetch-mock'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import {
API_ROOT,
default as api
} from 'middleware/api'
const middlewares = [thunk, api]
const mockStore = configureMockStore(middlewares)
describe('(Redux Module) Selections', () => {
const selection = {
item: 'Door knob downstairs',
product: 'Fancy one from the cool store'
}
const selectionId = '1234'
it('Should export a constant ADD_SELECTION.', () => {
expect(ADD_SELECTION).to.equal('ADD_SELECTION')
})
describe('(Reducer)', () => {
it('Should be a function.', () => {
expect(selectionsReducer).to.be.a('function')
})
it('Should initialize with a state of {} (Object).', () => {
expect(selectionsReducer(undefined, {})).to.deep.equal({})
})
it('Should return the previous state if an action was not matched.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: '@@@@@@@' })
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: ADD_SELECTION, payload: selection })
expect(state).to.deep.equal({
justAdded: selection
})
state = selectionsReducer(state, { type: '@@@@@@@' })
expect(state).to.deep.equal({
justAdded: selection
})
})
})
describe('(Action Creator) loadSelections', () => {
afterEach(() => fetchMock.restore())
it('Should be exported as a function.', () => {
expect(loadSelections).to.be.a('function')
})
it('Should return a function (is a thunk).', () => {
expect(loadSelections()).to.be.a('function')
})
it('Should create "FETCH_SELECTIONS_SUCCESS" when fetching selections has been done.', () => {
const selectionWithId = {
...selection,
id: selectionId
}
fetchMock.get(`${API_ROOT}getSelections`, { body: [ selectionWithId ] })
const expectedActions = [
{ type: FETCH_SELECTIONS_REQUEST },
{
type: FETCH_SELECTIONS_SUCCESS,
response: {
entities: {
selections: {
[selectionId]: selectionWithId
}
},
result: [
selectionId
],
nextPageUrl: null
}
}
]
const store = mockStore({ selections: {} })
return store.dispatch(loadSelections())
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions)
})
})
it('Should create "FETCH_SELECTIONS_FAILURE" when fetching selections has failed.', () => {
fetchMock.get(`${API_ROOT}getSelections`, 500)
const expectedActions = [
{ type: FETCH_SELECTIONS_REQUEST },
{
type: FETCH_SELECTIONS_FAILURE,
error: 'JSON Parse error: Unexpected EOF'
}
]
const store = mockStore({ selections: {} })
return store.dispatch(loadSelections())
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions)
})
})
})
describe('(Action Creator) addSelection', () => {
afterEach(() => fetchMock.restore())
it('Should be exported as a function.', () => {
expect(addSelection).to.be.a('function')
})
it('Should return a function (is a thunk).', () => {
expect(addSelection()).to.be.a('function')
})
it('Should create "POST_SELECTION_SUCCESS" when adding selection has been done.', () => {
const selectionWithId = {
...selection,
id: selectionId
}
fetchMock.post(`${API_ROOT}addSelection`, { body: selectionWithId })
const expectedActions = [
{
type: ADD_SELECTION,
payload: selection
},
{ type: POST_SELECTION_REQUEST },
{
type: POST_SELECTION_SUCCESS,
response: {
entities: {
selections: {
[selectionId]: selectionWithId
}
},
result: selectionId,
nextPageUrl: null
}
}
]
const store = mockStore({ selections: {} })
return store.dispatch(addSelection(selection))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions)
})
})
it('Should create "FETCH_SELECTIONS_FAILURE" when fetching selections has failed.', () => {
fetchMock.post(`${API_ROOT}addSelection`, 500)
const expectedActions = [
{
type: ADD_SELECTION,
payload: selection
},
{ type: POST_SELECTION_REQUEST },
{
type: POST_SELECTION_FAILURE,
error: 'JSON Parse error: Unexpected EOF'
}
]
const store = mockStore({ selections: {} })
return store.dispatch(addSelection(selection))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions)
})
})
})
describe('(Action Handler) ADD_SELECTION', () => {
it('Should update the state\'s justAdded property with the action payload.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: ADD_SELECTION, payload: selection })
expect(state).to.deep.equal({ justAdded: selection })
state = selectionsReducer(state, { type: ADD_SELECTION, payload: selection })
expect(state).to.deep.equal({ justAdded: selection })
})
})
describe('(Action Handler) FETCH_SELECTIONS_REQUEST', () => {
it('Should update the state\'s isFetching property to `true`.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: FETCH_SELECTIONS_REQUEST })
expect(state).to.deep.equal({ isFetching: true })
})
})
describe('(Action Handler) FETCH_SELECTIONS_SUCCESS', () => {
it('Should update the state\'s isFetching property to `false`.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: FETCH_SELECTIONS_SUCCESS })
expect(state).to.deep.equal({ isFetching: false })
})
})
describe('(Action Handler) FETCH_SELECTIONS_FAILURE', () => {
it('Should update the state\'s isFetching property to `false` and the error property to error payload.', () => {
const error = 'Something terrible happened'
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: FETCH_SELECTIONS_FAILURE, error })
expect(state).to.deep.equal({
isFetching: false,
error
})
})
})
describe('(Action Handler) POST_SELECTION_REQUEST', () => {
it('Should update the state\'s isPosting property to `true`.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: POST_SELECTION_REQUEST })
expect(state).to.deep.equal({ isPosting: true })
})
})
describe('(Action Handler) POST_SELECTION_SUCCESS', () => {
it('Should update the state\'s isPosting property to `false`.', () => {
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: POST_SELECTION_SUCCESS })
expect(state).to.deep.equal({ isPosting: false })
})
})
describe('(Action Handler) POST_SELECTION_FAILURE', () => {
it('Should update the state\'s isPosting property to `false` and the error property to error payload.', () => {
const error = 'Something terrible happened'
let state = selectionsReducer(undefined, {})
expect(state).to.deep.equal({})
state = selectionsReducer(state, { type: POST_SELECTION_FAILURE, error })
expect(state).to.deep.equal({
isPosting: false,
error
})
})
})
})
| 31.387218 | 116 | 0.600671 |
d5e1a2d7fee97f7eaf35dcaaed22d7614b1967fb | 513 | js | JavaScript | components/admin/tableRow.js | danielmartinsen/bruker-reg-system | b7d470a732037502d2083b9948eba12310c1f86d | [
"Unlicense",
"MIT"
] | null | null | null | components/admin/tableRow.js | danielmartinsen/bruker-reg-system | b7d470a732037502d2083b9948eba12310c1f86d | [
"Unlicense",
"MIT"
] | 15 | 2020-06-06T12:37:39.000Z | 2022-03-26T14:39:18.000Z | components/admin/tableRow.js | danielmartinsen/bruker-reg-system | b7d470a732037502d2083b9948eba12310c1f86d | [
"Unlicense",
"MIT"
] | null | null | null | import React from 'react'
import TableCell from '@material-ui/core/TableCell'
import TableRow from '@material-ui/core/TableRow'
import styles from '../../styles/admin/table.module.scss'
export default function Row({ row }) {
return (
<React.Fragment>
<TableRow>
<TableCell>{row.klokkeslett}</TableCell>
<TableCell>{row.navn}</TableCell>
<TableCell>
<button className={styles.button}>Slett</button>
</TableCell>
</TableRow>
</React.Fragment>
)
}
| 25.65 | 58 | 0.647173 |
d5e1b49b16b26c52d68ccca01e79004e3e0c4adf | 1,547 | js | JavaScript | src/components/atoms/Button.js | andibalo/personal-website-v2 | 7e9d798cc16fdd100abccd9ed03680fd997c0cde | [
"RSA-MD"
] | null | null | null | src/components/atoms/Button.js | andibalo/personal-website-v2 | 7e9d798cc16fdd100abccd9ed03680fd997c0cde | [
"RSA-MD"
] | null | null | null | src/components/atoms/Button.js | andibalo/personal-website-v2 | 7e9d798cc16fdd100abccd9ed03680fd997c0cde | [
"RSA-MD"
] | null | null | null | import React from "react"
import styled from "styled-components"
import { Link } from "gatsby"
const StyledButtonWrapper = styled.div`
a,
button {
display: inline-block;
background-color: ${({ dark }) =>
dark ? "var(--black-light)" : "transparent"};
border-radius: 5px;
padding: 10px 20px;
border: ${({ dark }) =>
dark ? "1px solid var(--black-light)" : "1px solid var(--primary-blue)"};
color: ${({ dark }) => (dark ? " var(--white)" : " var(--primary-blue)")};
font-family: Roboto;
transition: all 0.3s;
&:hover {
background-color: var(--primary-blue);
color: var(--white);
}
}
@media (max-width: 767px) {
a,
button {
padding: 8px 16px;
}
}
`
const Button = ({
title,
href = null,
newWindow,
role,
download,
dark,
gatsbyLink,
className,
}) => {
if (role === "button") {
return (
<StyledButtonWrapper dark={dark} className={className}>
<button>{title}</button>
</StyledButtonWrapper>
)
}
if (download) {
return (
<StyledButtonWrapper dark={dark} className={className}>
<a href={href || "#"} download>
{title}
</a>
</StyledButtonWrapper>
)
}
return (
<StyledButtonWrapper dark={dark} className={className}>
{gatsbyLink ? (
<Link to={href}>{title}</Link>
) : (
<a href={href || "#"} target={newWindow ? "_blank" : "_self"}>
{title}
</a>
)}
</StyledButtonWrapper>
)
}
export default Button
| 21.191781 | 79 | 0.546865 |
d5e1d9d59562548644d78c60b42a461eb79c1073 | 1,925 | js | JavaScript | docs/morpheuz/utils-38.min.js | JamesFowler42/morpheuz | 6538e76e3dd687df48eef1ffd927f1436c69bee6 | [
"MIT"
] | null | null | null | docs/morpheuz/utils-38.min.js | JamesFowler42/morpheuz | 6538e76e3dd687df48eef1ffd927f1436c69bee6 | [
"MIT"
] | null | null | null | docs/morpheuz/utils-38.min.js | JamesFowler42/morpheuz | 6538e76e3dd687df48eef1ffd927f1436c69bee6 | [
"MIT"
] | null | null | null | function mUtil(){return{emailUrl:"json_email.php",emailToken:"morpheuz20",okResponse:"Sent OK",failResponse:"Failed to send with ",failGeneral:"Failed to send"}}function getParameterByName(a){a=a.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var c=new RegExp("[\\?&]"+a+"=([^&#]*)"),b=c.exec(location.search);return b==null?"":decodeURIComponent(b[1].replace(/\+/g," "))}function setScreenMessageBasedOnVersion(a){$(".versproblem").show();$.ajaxSetup({scriptCharset:"utf-8",contentType:"application/json; charset=utf-8"});$.getJSON("currentversion.json?v="+new Date().getTime(),function(d){if(typeof d!=="undefined"&&typeof d.version!=="undefined"){var c=parseInt(d.version,10);var b=parseInt(a,10);$(".versproblem").hide();if(c>b){$(".verswarning").show()}else{if(c<b){$(".versbeta").show()}}}}).error(function(b){$(".versproblem").text("Error attempting to find the current version: "+JSON.stringify(b))})}function scaleToViewport(){var a=$(window).width();if(a>800){a=800}else{if(a<320){a=320}}a-=5;$(".vpwidth").width(a);$(".vpheight").height(a*250/318);if(typeof document.plot1!=="undefined"){document.plot1.replot()}if(typeof document.plot2!=="undefined"){document.plot2.replot()}}function adjustForViewport(){scaleToViewport();$(window).resize(scaleToViewport)}function sendMailViaServer(a,e){try{var d="email="+encodeURIComponent(JSON.stringify(a));var c=new XMLHttpRequest();c.open("POST",mUtil().emailUrl,true);c.setRequestHeader("Content-type","application/x-www-form-urlencoded");c.setRequestHeader("X-Client-token",mUtil().emailToken);c.onreadystatechange=function(f){if(c.readyState==4){if(c.status==200){e(1,mUtil().okResponse)}else{e(0,mUtil().failResponse+c.status)}}};c.onerror=function(f){e(0,mUtil().failGeneral)};c.send(d)}catch(b){e(0,mUtil().failResponse+b.message)}}function validateEmail(a){var b=/[^\s@]+@[^\s@]+\.[^\s@]+/;return b.test(a)}function safeTrim(b){try{return b.trim()}catch(a){return b}}; | 1,925 | 1,925 | 0.708571 |
d5e40f744b9cc0cb4d3144065f3226154c317af2 | 176 | js | JavaScript | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/doc/html/search/enums_2.js | tianhao13/ngkchain | 25d59f3161dd85c8cf9b4ce4bd210bd859deca05 | [
"MIT"
] | 15 | 2016-04-12T17:12:19.000Z | 2019-08-14T17:46:17.000Z | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/doc/html/search/enums_2.js | tianhao13/ngkchain | 25d59f3161dd85c8cf9b4ce4bd210bd859deca05 | [
"MIT"
] | 63 | 2016-03-22T14:35:31.000Z | 2018-07-04T22:17:07.000Z | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/doc/html/search/enums_2.js | tianhao13/ngkchain | 25d59f3161dd85c8cf9b4ce4bd210bd859deca05 | [
"MIT"
] | 4 | 2020-11-02T11:25:56.000Z | 2021-01-22T14:12:22.000Z | var searchData=
[
['level',['level',['../namespacequickcpplib_1_1__xxx_1_1ringbuffer__log.html#add4cc747a8c90cbfd538b0f07dfdd1e2',1,'quickcpplib::_xxx::ringbuffer_log']]]
];
| 35.2 | 154 | 0.784091 |
d5e4c97612eb92e3961e6ae43a18ffbac6ee814d | 344 | js | JavaScript | server.js | leftiness/hex-build | 868906f646f0d129cdcc3e0d42f1ee71c629111e | [
"MIT"
] | null | null | null | server.js | leftiness/hex-build | 868906f646f0d129cdcc3e0d42f1ee71c629111e | [
"MIT"
] | null | null | null | server.js | leftiness/hex-build | 868906f646f0d129cdcc3e0d42f1ee71c629111e | [
"MIT"
] | null | null | null | var express = require('express');
var app = express();
var options = {
root: __dirname + '/dist/',
}
app.use('/assets', express.static(__dirname + '/assets'));
app.use(express.static(__dirname + '/dist'));
app.all('/*', function (req, res) {
res.sendFile('index.html', options);
});
app.listen('5000');
console.log('All systems are go!');
| 21.5 | 58 | 0.642442 |
d5e5528e094f9c7750ff92e151b7de28b4c93883 | 865 | js | JavaScript | AssertObject.js | evanx/rhlib | e27e29948c6a60a642e24e03ef47fc2474780d7e | [
"0BSD"
] | null | null | null | AssertObject.js | evanx/rhlib | e27e29948c6a60a642e24e03ef47fc2474780d7e | [
"0BSD"
] | null | null | null | AssertObject.js | evanx/rhlib | e27e29948c6a60a642e24e03ef47fc2474780d7e | [
"0BSD"
] | null | null | null |
import assert from 'assert';
function format(type, options) {
return type + ': ' + options.toString();
}
exports = {
hasOwnProperty(object, key) {
if (object.hasOwnProperty(key)) throw new ValidationError(`missing: ${key}`);
return object;
},
hasFunction(object, key) {
if (object.hasOwnProperty(key)) throw new ValidationError(`missing: ${key}`);
const value = object[key];
if (!lodash.isFunction(value)) throw new ValidationError(`missing function: ${key}`);
return object;
},
parseIntDefault(object, key, defaultValue) {
const value = object[key];
if (!Values.isDefined(key)) return defaultValue;
const parsedValue = parseInt(value);
if (parsedValue.toString() === value.toString()) {
return parsedValue;
}
throw new ValidationError(`integer ${key}`);
}
};
| 29.827586 | 91 | 0.636994 |
d5e5a3133938a5b616d9c12224c455bc3c266d6b | 1,573 | js | JavaScript | src/son/similarity-tpq.js | folkvir/webrtc-dequenpeda | d5490cea5fbfde0c53cfe38e1bf8e4bf2c1d7505 | [
"MIT"
] | 3 | 2018-05-16T11:35:48.000Z | 2021-11-30T00:35:11.000Z | src/son/similarity-tpq.js | folkvir/webrtc-dequenpeda | d5490cea5fbfde0c53cfe38e1bf8e4bf2c1d7505 | [
"MIT"
] | null | null | null | src/son/similarity-tpq.js | folkvir/webrtc-dequenpeda | d5490cea5fbfde0c53cfe38e1bf8e4bf2c1d7505 | [
"MIT"
] | null | null | null | const debug = require('debug')('dequenpeda:similarity')
// DEBUG=dequenpeda:similarity node tests/test-similarity.js
const SCORES = {
spo: Infinity,
equal: Infinity,
containment: 2,
subset: 1,
empty: 0
}
const spo = {
subject: '_',
predicate: '_',
object: '_'
}
function compare(profileA, profileB) {
let score = 0
profileA.forEach(tpa => {
profileB.forEach(tpb => {
score += getScore(tpa, tpb)
})
})
return score
}
function getScore(tpa, tpb) {
if(equal(tpa, tpb)) {
debug('equality')
return SCORES.equal
} else if(containment(tpa, tpb)) {
debug('containment')
return SCORES.containment
} else if(subset(tpa, tpb)) {
debug('subset')
return SCORES.subset
} else {
debug('nothing')
return SCORES.empty
}
}
function containment(tpa, tpb) {
return contain(tpa.subject, tpb.subject) && contain(tpa.predicate, tpb.predicate) && contain(tpa.object, tpb.object)
}
function subset(tpa, tpb) {
return sub(tpa.subject, tpb.subject) && sub(tpa.predicate, tpb.predicate) && sub(tpa.object, tpb.object)
}
function isSPO(tp) {
return equal(tp, spo)
}
function equal(tpa, tpb) {
return eq(tpa.subject, tpb.subject) && eq(tpa.predicate, tpb.predicate) && eq(tpa.object, tpb.object)
}
function contain(v1, v2) {
return eq(v1, v2) || ( !eq(v1, '_') && eq(v2, '_'))
}
function sub(v1, v2) {
return eq(v1, v2) || ( eq(v1, '_') && !eq(v2, '_'))
}
function eq(v1, v2) {
return (v1 === v2)
}
module.exports = {
isSPO,
compare,
containment,
subset,
equal,
eq,
contain,
sub
}
| 19.182927 | 118 | 0.631914 |
d5e5b0605eea124af731ccf52a6dc751ac08ab04 | 36 | js | JavaScript | coms/zimoli/onselectstart.js | yunxu1019/efront | b30398485e702785ae7360190e50fe329addcfb3 | [
"MIT"
] | 1 | 2019-04-26T02:56:54.000Z | 2019-04-26T02:56:54.000Z | coms/zimoli/onselectstart.js | yunxu1019/efront | b30398485e702785ae7360190e50fe329addcfb3 | [
"MIT"
] | 3 | 2019-06-10T02:59:29.000Z | 2021-06-06T01:09:58.000Z | coms/zimoli/onselectstart.js | yunxu1019/efront | b30398485e702785ae7360190e50fe329addcfb3 | [
"MIT"
] | 1 | 2020-08-16T03:19:29.000Z | 2020-08-16T03:19:29.000Z | var onselectstart=on("selectstart"); | 36 | 36 | 0.805556 |
d5e7f8446dc8b3aa7e3813e49b0fe024a9620143 | 156 | js | JavaScript | dist/resources/beta/1524/30/insertHtmlBeforeBegin-da3818cf.js | gschizas/fallenswordhelper | 15ad9412961f17e6a0f35aa96927e9388a143809 | [
"MIT"
] | 1 | 2015-03-22T12:51:42.000Z | 2015-03-22T12:51:42.000Z | dist/resources/beta/1524/30/insertHtmlBeforeBegin-da3818cf.js | gschizas/fallenswordhelper | 15ad9412961f17e6a0f35aa96927e9388a143809 | [
"MIT"
] | 1 | 2022-03-22T08:49:20.000Z | 2022-03-22T08:49:20.000Z | dist/resources/beta/1524/30/insertHtmlBeforeBegin-da3818cf.js | gschizas/fallenswordhelper | 15ad9412961f17e6a0f35aa96927e9388a143809 | [
"MIT"
] | 3 | 2015-03-20T07:16:43.000Z | 2015-09-16T04:35:01.000Z | import{R as e}from"./calfSystem-ebf4b17d.js"
function f(f,o){e(f,"beforebegin",o)}export{f as i}
//# sourceMappingURL=insertHtmlBeforeBegin-da3818cf.js.map
| 39 | 58 | 0.762821 |
d5e89812734b06437000b8685bc89792e94e41fc | 2,375 | js | JavaScript | arangodb/arangodbinit/product_schema.js | camba1/cdcon21BuildDriver | 7b75e241af7ac95633e6079b99270d4f7eb645a7 | [
"Apache-2.0"
] | 52 | 2021-01-27T04:57:31.000Z | 2022-03-17T02:59:57.000Z | arangodb/arangodbinit/product_schema.js | camba1/cdcon21BuildDriver | 7b75e241af7ac95633e6079b99270d4f7eb645a7 | [
"Apache-2.0"
] | 9 | 2021-01-25T17:55:47.000Z | 2021-01-25T18:12:30.000Z | arangodb/arangodbinit/product_schema.js | camba1/cdcon21BuildDriver | 7b75e241af7ac95633e6079b99270d4f7eb645a7 | [
"Apache-2.0"
] | 10 | 2021-01-27T04:57:40.000Z | 2022-03-18T16:12:49.000Z | db._createDatabase('product', {}, [{ username: "productUser", passwd: "TestDB@home2", active: true}]);
db._useDatabase('product');
db._create('product');
db._createEdgeCollection("isparentof");
db._createEdgeCollection("iscomponentof");
db.product.insert({"_key": "switch", "name": "Play Switch Console", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "sku", "externalId": "12345"});
db.product.insert({"_key": "tele", "name": "Watch me TV", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "sku"});
db.product.insert({"_key": "fridge", "name": "Cool Stuff Fridge", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "sku"});
db.product.insert({"_key": "intamd", "name": "IntAmd processor", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "sku"});
db.product.insert({"_key": "elec", "name": "Electronics", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "cat"});
db.product.insert({"_key": "appli", "name": "Appliances", "validityDates": {"validFrom": {"seconds": 1592692598,"nanos": 274583000}, "validThru": {"seconds": 1615792598, "nanos": 274584000}}, "hierarchylevel": "cat"});
db.isparentof.insert({"_from":"product/elec" , "_to":"product/tele", "validFrom": "2019-01-02", "validThru": "2021-01-02"});
db.isparentof.insert({"_from":"product/elec" , "_to":"product/switch", "validFrom": "2019-01-02", "validThru": "2021-01-02"});
db.isparentof.insert({"_from":"product/elec" , "_to":"product/intamd", "validFrom": "2019-01-02", "validThru": "2021-01-02"});
db.isparentof.insert({"_from":"product/appli" , "_to":"product/fridge", "validFrom": "2019-01-02", "validThru": "2021-01-02"});
db.iscomponentof.insert({"_from":"product/intamd" , "_to":"product/switch", "validFrom": "2019-01-02", "validThru": "2021-01-02"});
db.iscomponentof.insert({"_from":"product/intamd" , "_to":"product/tele", "validFrom": "2019-01-02", "validThru": "2021-01-02"}); | 103.26087 | 251 | 0.677053 |
d5eb42c083589fb50644c9f5dfab78dd5f2d13fb | 3,487 | js | JavaScript | server/session.js | Eyevinn/vod-to-live.js | 85c35423d3c7efa7951cece456dd6d462edf00ee | [
"MIT",
"Unlicense"
] | 8 | 2018-02-19T06:54:08.000Z | 2021-11-20T02:56:14.000Z | server/session.js | Eyevinn/vod-to-live.js | 85c35423d3c7efa7951cece456dd6d462edf00ee | [
"MIT",
"Unlicense"
] | 3 | 2020-03-28T17:32:21.000Z | 2020-03-28T17:32:23.000Z | server/session.js | Eyevinn/vod-to-live.js | 85c35423d3c7efa7951cece456dd6d462edf00ee | [
"MIT",
"Unlicense"
] | 4 | 2018-08-01T21:29:27.000Z | 2021-05-24T17:07:22.000Z | const crypto = require('crypto');
const HLSVod = require('../index.js');
const exampleVod = [
"https://maitv-vod.lab.eyevinn.technology/VINN.mp4/master.m3u8",
"https://maitv-vod.lab.eyevinn.technology/tearsofsteel_4k.mov/master.m3u8",
"https://maitv-vod.lab.eyevinn.technology/Attjobbapavinnter.mp4/master.m3u8",
];
const SessionState = Object.freeze({
VOD_INIT: 1,
VOD_PLAYING: 2,
VOD_NEXT_INIT: 3,
});
class Session {
constructor() {
this._sessionId = crypto.randomBytes(20).toString('hex');
this._state = {
mediaSeq: 0,
discSeq: 0,
vodMediaSeq: 0,
state: SessionState.VOD_INIT,
};
this.currentVod;
}
get sessionId() {
return this._sessionId;
}
getMediaManifest(bw) {
return new Promise((resolve, reject) => {
this._tick().then(() => {
const m3u8 = this.currentVod.getLiveMediaSequences(this._state.mediaSeq, bw, this._state.vodMediaSeq, this._state.discSeq);
this._state.vodMediaSeq++;
resolve(m3u8);
}).catch(reject);
});
}
getMasterManifest() {
return new Promise((resolve, reject) => {
this._tick().then(() => {
let m3u8 = "#EXTM3U\n";
this.currentVod.getUsageProfiles().forEach(profile => {
m3u8 += '#EXT-X-STREAM-INF:BANDWIDTH=' + profile.bw + ',RESOLUTION=' + profile.resolution + ',CODECS="' + profile.codecs + '"\n';
m3u8 += "master" + profile.bw + ".m3u8;session=" + this._sessionId + "\n";
});
resolve(m3u8);
}).catch(reject);
});
}
_tick() {
return new Promise((resolve, reject) => {
// State machine
switch(this._state.state) {
case SessionState.VOD_INIT:
console.log("[VOD_INIT]");
this._getNextVod().then(hlsVod => {
this.currentVod = hlsVod;
return this.currentVod.load();
}).then(() => {
this._state.state = SessionState.VOD_PLAYING;
//this._state.vodMediaSeq = this.currentVod.getLiveMediaSequencesCount() - 5;
this._state.vodMediaSeq = 0;
resolve();
})
break;
case SessionState.VOD_PLAYING:
console.log("[VOD_PLAYING]");
if (this._state.vodMediaSeq === this.currentVod.getLiveMediaSequencesCount() - 1) {
this._state.state = SessionState.VOD_NEXT_INIT;
}
resolve();
break;
case SessionState.VOD_NEXT_INIT:
console.log("[VOD_NEXT_INIT]");
const length = this.currentVod.getLiveMediaSequencesCount();
const lastDiscontinuity = this.currentVod.getLastDiscontinuity();
let newVod;
this._getNextVod().then(hlsVod => {
newVod = hlsVod;
return hlsVod.loadAfter(this.currentVod);
}).then(() => {
this.currentVod = newVod;
this._state.state = SessionState.VOD_PLAYING;
this._state.vodMediaSeq = 0;
this._state.mediaSeq += length;
this._state.discSeq += lastDiscontinuity;
resolve();
});
break;
default:
reject("Invalid state: " + this.state.state);
}
});
}
_getNextVod() {
return new Promise((resolve, reject) => {
const rndIdx = Math.floor(Math.random() * exampleVod.length);
console.log(exampleVod[rndIdx]);
const newVod = new HLSVod(exampleVod[rndIdx|0]);
resolve(newVod);
});
}
}
module.exports = Session; | 31.133929 | 139 | 0.586464 |
d5eb50615d4efeb825b2a326fe96e21dc29d8bce | 48 | js | JavaScript | src/components/SearchFiltersRange/index.js | demiurg/fogg | 62233ab77be41f8013797c248b0dda221015dd7b | [
"Apache-2.0"
] | 23 | 2020-05-19T21:14:49.000Z | 2022-01-08T22:13:22.000Z | src/components/SearchFiltersRange/index.js | demiurg/fogg | 62233ab77be41f8013797c248b0dda221015dd7b | [
"Apache-2.0"
] | 9 | 2020-05-19T21:07:57.000Z | 2022-02-28T01:49:43.000Z | src/components/SearchFiltersRange/index.js | demiurg/fogg | 62233ab77be41f8013797c248b0dda221015dd7b | [
"Apache-2.0"
] | 4 | 2020-05-21T02:15:51.000Z | 2022-03-31T03:28:20.000Z | export { default } from './SearchFiltersRange';
| 24 | 47 | 0.729167 |
d5ecf73b662a0ffbb30512a983ca8282f330cff6 | 1,105 | js | JavaScript | dist/test/query-builders/shared/DefaultConvention.test.js | nhat-phan/najs-eloquent-new-structure | 16d830af391b6181c6cbad743b6e30a6cb978633 | [
"MIT"
] | 26 | 2018-01-03T16:07:31.000Z | 2021-02-22T07:04:15.000Z | dist/test/query-builders/shared/DefaultConvention.test.js | nhat-phan/najs-eloquent-new-structure | 16d830af391b6181c6cbad743b6e30a6cb978633 | [
"MIT"
] | 10 | 2018-04-04T12:00:30.000Z | 2018-05-21T10:49:40.000Z | dist/test/query-builders/shared/DefaultConvention.test.js | nhat-phan/najs-eloquent-new-structure | 16d830af391b6181c6cbad743b6e30a6cb978633 | [
"MIT"
] | 7 | 2018-01-03T16:07:36.000Z | 2018-09-06T15:45:09.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("jest");
const DefaultConvention_1 = require("../../../lib/query-builders/shared/DefaultConvention");
describe('DefaultConvention', function () {
const convention = new DefaultConvention_1.DefaultConvention();
describe('.formatFieldName()', function () {
it('simply returns name from parameter', function () {
const dataList = {
test: 'test',
id: 'id'
};
for (const name in dataList) {
expect(convention.formatFieldName(name)).toEqual(dataList[name]);
}
});
});
describe('.getNullValueFor()', function () {
it('simply returns null', function () {
const dataList = {
// tslint:disable-next-line
test: null,
// tslint:disable-next-line
id: null
};
for (const name in dataList) {
expect(convention.getNullValueFor(name)).toBeNull();
}
});
});
});
| 34.53125 | 92 | 0.531222 |
d5ed48f786147d9b6ca7c5c87ddf7b50c80c2507 | 11,457 | js | JavaScript | FE-Img/BlockImgCurves.js | NORYOM/noryom.github.io | 77ee4a7cac5c03766091dc5aaba6247fce296dc3 | [
"MIT"
] | null | null | null | FE-Img/BlockImgCurves.js | NORYOM/noryom.github.io | 77ee4a7cac5c03766091dc5aaba6247fce296dc3 | [
"MIT"
] | null | null | null | FE-Img/BlockImgCurves.js | NORYOM/noryom.github.io | 77ee4a7cac5c03766091dc5aaba6247fce296dc3 | [
"MIT"
] | null | null | null | function BlockImgCurves(){
Block.call(this);
var cvs = canvas;
var curvePadSize = 127;
var curvePtDistance = 10;
var controlPtSize = 5;
var linearBarW = 5;
this.parentType = new Block();
this.id = (new Date()).getTime()+Math.random();
this.h=curvePadSize+this.r+linearBarW;
this.w=curvePadSize+this.r;
this.title="曲线编辑器";
this.titleColor = 'rgba(0,200,200,0.5)';
this.inPt = [new ParamPoint()];
this.outPt = [new ParamPoint()];
var drag = false;
var dragTitle = false;
var mx,my;
var dx = [],dy = [];
var ptS,ptE,ptC;
var currentPtCNum;
var dragPt = false;
var maxCtlPtNum = 8;
var curvX = [];
var curvY = [];
this.btnAddCtlPt = new Button();
this.btnDelCtlPt = new Button();
this.btnAddCtlPt.label = "+";
this.btnDelCtlPt.label = "-";
var addCtlPt = false;
var delCtlPt = false;
this.btnAddCtlPt.doAction = function(){
addCtlPt = true;
};
this.btnDelCtlPt.doAction = function(){
delCtlPt = true;
};
// process image
var img = new Image();
var imageView = new ImageView();
var done = false;
var oldImgSrc;
var asyncFunc = new Promise((resolve, reject) => {
resolve();
});
var clnImg;
this.doAction = function(){
if(this.inPt[0].value && this.inPt[0].value instanceof Image){
if(!oldImgSrc){
oldImgSrc = this.inPt[0].value.accessKey;
clnImg = imageView.getImgClone(this.inPt[0].value,this.w*1.5,this.h*1.5);
}else{
if(oldImgSrc!=this.inPt[0].value.accessKey){
done = false;
oldImgSrc = this.inPt[0].value.accessKey;
clnImg = imageView.getImgClone(this.inPt[0].value,this.w*1.5,this.h*1.5);
}
}
if(!done){
asyncFunc.then(() => {
curvX = [0];
curvY = [0];
//calculate curve array
for(var i=0;i<ptC.length;i++){
curvX.push(parseInt(ptC[i].x-(this.x+this.r/2))*2);
curvY.push(parseInt(this.y+this.r/2+curvePadSize-ptC[i].y)*2);
}
curvX.push(255);
curvY.push(255);
// clone image
img = imageView.cloneImg(clnImg);
$AI(clnImg).act("curve",curvX,curvY).replace(img);
// make sure out value is the newest and will not lost
this.outPt[0].value = img;
this.outPt[0].operation = [];
if(this.inPt[0].operation){
for(var j=0;j<this.inPt[0].operation.length;j++){
this.outPt[0].operation.push(this.inPt[0].operation[j]);
}
}
this.outPt[0].operation.push({type:"act",value:{action:"curve",param:[curvX,curvY]}});
img.accessKey = oldImgSrc;
});
done = true;
}
}else{
done = false;
// clear img value make sure output is no value
img = null;
this.outPt[0].value = null;
}
};
this.refreshOutPut=function(){
done = false;
if(this.outPt[0].value && this.outPt[0].value.accessKey){
this.outPt[0].value.accessKey *= -1;
}
};
this.isInPadW = function(e){
mx = e.clientX-cvsRect.left*(cvs.width/cvsRect.width);
if(mx>=this.x+this.r/2+controlPtSize/2 && mx<=this.x+this.r/2+curvePadSize-controlPtSize/2){
return true;
}
return false;
};
this.isInPadH = function(e){
my = e.clientY-cvsRect.top*(cvs.height/cvsRect.height);
if(my>=this.y+this.r/2+controlPtSize/2 && my<=this.y+this.r/2+curvePadSize-controlPtSize/2){
return true;
}
return false;
};
this.isInControlPt = function(ctlPt,ex,ey){
var tempX = ex-cvsRect.left*(cvs.width/cvsRect.width);
var tempY = ey-cvsRect.top*(cvs.height/cvsRect.height);
if(tempX>=ctlPt.x-controlPtSize/2 && tempX<=ctlPt.x+controlPtSize/2 &&
tempY>=ctlPt.y-controlPtSize/2 && tempY<=ctlPt.y+controlPtSize/2){
return true;
}
return false;
};
this.onmousedown = function(e){
this.parentType.onmousedown.call(this,e);
this.btnAddCtlPt.onmousedown(e);
this.btnDelCtlPt.onmousedown(e);
if(!this.isInTitleBar(e.clientX,e.clientY)){
if(this.isInPadW(e) && this.isInPadH(e)){
drag = true;
for(var i=0;i<ptC.length;i++){
if(this.isInControlPt(ptC[i],e.clientX,e.clientY)){
ptC[i].x = e.clientX-cvsRect.left*(cvs.width/cvsRect.width);
ptC[i].y = e.clientY-cvsRect.top*(cvs.height/cvsRect.height);
currentPtCNum = i;
dragPt = true;
break;
}
}
}
}else{
dragTitle = true;
for(var i=0;i<ptC.length;i++){
dx[i] = e.clientX - ptC[i].x;
dy[i] = e.clientY - ptC[i].y;
}
}
};
this.onmouseup = function(e){
this.parentType.onmouseup.call(this,e);
this.btnAddCtlPt.onmouseup(e);
this.btnDelCtlPt.onmouseup(e);
drag = false;
dragTitle = false;
dragPt = false;
};
this.onmousemove = function(e){
this.parentType.onmousemove.call(this,e);
this.btnAddCtlPt.onmousemove(e);
this.btnDelCtlPt.onmousemove(e);
if(drag){
if(dragPt){
if(this.isInPadW(e)){
ptC[currentPtCNum].x = e.clientX-cvsRect.left*(cvs.width/cvsRect.width);
if(ptC[currentPtCNum].x<this.x+this.r/2+controlPtSize){
ptC[currentPtCNum].x = this.x+this.r/2+controlPtSize;
}
if(ptC[currentPtCNum].x>this.x+this.r/2+curvePadSize-controlPtSize){
ptC[currentPtCNum].x = this.x+this.r/2+curvePadSize-controlPtSize;
}
}
if(this.isInPadH(e)){
ptC[currentPtCNum].y = e.clientY-cvsRect.top*(cvs.height/cvsRect.height);
if(ptC[currentPtCNum].y<this.y+this.r/2+controlPtSize){
ptC[currentPtCNum].y = this.y+this.r/2+controlPtSize;
}
if(ptC[currentPtCNum].y>this.y+this.r/2+curvePadSize-controlPtSize){
ptC[currentPtCNum].y = this.y+this.r/2+curvePadSize-controlPtSize;
}
}
//refresh output
this.refreshOutPut();
}
}
if(dragTitle){
for(var i=0;i<ptC.length;i++){
ptC[i].x = e.clientX - dx[i];
ptC[i].y = e.clientY - dy[i];
}
}
};
this.rend = function(){
this.parentType.rend.call(this);
ptS = {
x:this.x+this.r/2,
y:this.y+this.r/2+curvePadSize
};
ptE = {
x:this.x+this.r/2+curvePadSize,
y:this.y+this.r/2
};
if(!ptC){
ptC = [
{
x:this.x+this.r/2+curvePadSize/2,
y:this.y+this.r/2+curvePadSize/2
}
];
currentPtCNum = 1;
}
if(addCtlPt){
addCtlPt = false;
ptC.push(
{
x:this.x+this.r/2+curvePadSize/2,
y:this.y+this.r/2+curvePadSize/2
}
);
currentPtCNum = ptC.length-1;
if(ptC.length==maxCtlPtNum){
this.btnAddCtlPt.setDisable(true);
}
if(ptC.length>0){
this.btnDelCtlPt.setDisable(false);
}
this.refreshOutPut();
}
if(delCtlPt){
delCtlPt = false;
ptC.splice(ptC.length-1,1);
currentPtCNum = ptC.length-1;
if(ptC.length<maxCtlPtNum){
this.btnAddCtlPt.setDisable(false);
}
if(ptC.length==0){
this.btnDelCtlPt.setDisable(true);
}
this.refreshOutPut();
}
ctx.save();
ctx.lineWidth=1;
ctx.fillStyle="#aaaaaa";
ctx.fillRect(this.x+this.r/2,this.y+this.r/2,curvePadSize,curvePadSize);
ctx.beginPath();
ctx.moveTo(ptS.x,ptS.y);
for(var i=0;i<ptC.length;i++){
if(i==0){
ctx.bezierCurveTo(ptS.x+curvePtDistance,ptS.y-curvePtDistance,
ptC[0].x-curvePtDistance,ptC[0].y+curvePtDistance,
ptC[0].x,ptC[0].y);
}
if(i!=ptC.length-1 && ptC.length>1){
ctx.bezierCurveTo(ptC[i].x+curvePtDistance,ptC[i].y-curvePtDistance,
ptC[i+1].x-curvePtDistance,ptC[i+1].y+curvePtDistance,
ptC[i+1].x,ptC[i+1].y);
}
if(i==ptC.length-1){
ctx.bezierCurveTo(ptC[ptC.length-1].x+curvePtDistance,ptC[ptC.length-1].y-curvePtDistance,
ptE.x-curvePtDistance,ptE.y+curvePtDistance,
ptE.x,ptE.y);
}
}
ctx.stroke();
ctx.closePath();
ctx.fillStyle="#999977";
for(var i=0;i<ptC.length;i++){
ctx.strokeRect(ptC[i].x-controlPtSize/2,ptC[i].y-controlPtSize/2,controlPtSize,controlPtSize);
}
ctx.fillStyle="#ffff77";
if(ptC.length>0){
if(ptC.length==1){
currentPtCNum = 0;
}
ctx.fillRect(ptC[currentPtCNum].x-controlPtSize/2,ptC[currentPtCNum].y-controlPtSize/2,controlPtSize,controlPtSize);
}
var lgV = ctx.createLinearGradient(this.x+this.r/2,this.y+this.r/2, this.x+this.r/2, this.y+this.r/2+curvePadSize);
var lgH = ctx.createLinearGradient(this.x+this.r/2,this.y+this.r/2+curvePadSize, this.x+this.r/2+curvePadSize, this.y+this.r/2+curvePadSize);
lgV.addColorStop(0, '#ffffff');
lgV.addColorStop(1, '#000000');
lgH.addColorStop(0, '#000000');
lgH.addColorStop(1, '#ffffff');
ctx.fillStyle = lgV;
ctx.fillRect(this.x+linearBarW,this.y+this.r/2, linearBarW, curvePadSize+linearBarW);
ctx.fillStyle = lgH;
ctx.fillRect(this.x+this.r/2,this.y+this.r/2+curvePadSize, curvePadSize, linearBarW);
ctx.restore();
// add button
this.btnAddCtlPt.setPos(this.x+this.w-this.r*2,this.y+this.h);
this.btnAddCtlPt.rend();
this.btnDelCtlPt.setPos(this.x+this.w-this.r,this.y+this.h);
this.btnDelCtlPt.rend();
};
}
| 36.839228 | 150 | 0.486166 |
d5ede683c209b5461bcfe2eb22972ff11396470a | 3,369 | js | JavaScript | src/controllers/usuariosController.js | danielsrod/api-formulario | 7f4ccd09524509447f5aa48691378bc97210f1c8 | [
"MIT"
] | null | null | null | src/controllers/usuariosController.js | danielsrod/api-formulario | 7f4ccd09524509447f5aa48691378bc97210f1c8 | [
"MIT"
] | null | null | null | src/controllers/usuariosController.js | danielsrod/api-formulario | 7f4ccd09524509447f5aa48691378bc97210f1c8 | [
"MIT"
] | null | null | null | const {
dadosUsuario,
inserirTermoAssinado,
validarNr,
validarNrForm,
} = require('../DAO/usuariosDAO');
// Função pra pegar o termo HTML preenchido com os dados do usuário
const findUser = async (req, res) => {
const { nr_atendimento, nr_sequencia } = req.query;
if (!nr_atendimento || !nr_sequencia) {
return res.status(400).json({
"status": "fail",
"err message": "falta de query params"
});
}
try {
const resultado = await dadosUsuario(nr_atendimento, nr_sequencia);
if (resultado) {
return res.json(resultado);
} else {
throw new Error('Ocorreu um erro ao tentar encontrar o usuario');
}
} catch (err) {
return res.status(400).json({
"status": "fail",
"error message": err
});
};
};
// Função pra validar se o nr_atendimento existe
const checkNr = async (req, res) => {
const { nr_atendimento } = req.query;
if (!nr_atendimento) {
return res.status(400).json({
"status": "fail",
"err message": "nr_atendimento não informado"
});
}
try {
const resultado = await validarNr(nr_atendimento);
if (resultado) {
return res.json(resultado);
} else {
throw new Error('Ocorreu um erro ao tentar validar o nr_atendimento');
}
} catch (err) {
return res.status(400).json({
"status": "fail",
"error message": err
});
};
};
// Função pra validar se o formulario já foi preenchido com algum nr_atendimento
const checkNrForm = async (req, res) => {
const { nr_atendimento } = req.query;
if (!nr_atendimento) {
return res.status(400).json({
"status": "fail",
"err message": "nr_atendimento não informado"
});
}
try {
const resultado = await validarNrForm(nr_atendimento);
if (resultado) {
return res.json({ resultado });
} else {
throw new Error('Ocorreu um erro ao tentar validar os formularios ja preenchidos');
}
} catch (err) {
return res.status(400).json({
"status": "fail",
"error message": err
});
};
};
// Função pra inserir o termo preenchido no banco
const insertTerm = async (req, res) => {
const {
nr_atendimento,
nr_seq_termo_padrao,
termo_image
} = req.body;
if (!nr_atendimento || !nr_seq_termo_padrao || !termo_image) {
return res.status(400).json({
"status": "fail",
"err message": "falta de query params"
});
};
try {
const resultado = await inserirTermoAssinado(nr_atendimento, nr_seq_termo_padrao, termo_image);
if (resultado) {
return res.json({
"resultado": resultado,
"status": "success",
"message": "enviado com sucesso"
});
} else {
throw new Error('Ocorreu um erro ao tentar inserir o termo preenchido');
}
} catch (err) {
return res.status(400).json({
"status": "fail",
"error message": err
});
};
};
module.exports = {
findUser,
insertTerm,
checkNr,
checkNrForm,
}; | 24.064286 | 103 | 0.540813 |
d5ede9423af7253a89018f64d173163b61a2b79b | 72 | js | JavaScript | packages/ember-templates/lib/dom-helper.js | lan0/ember.js | 8112e7112ddabf871044fdce1a893d78e6852d3f | [
"MIT"
] | null | null | null | packages/ember-templates/lib/dom-helper.js | lan0/ember.js | 8112e7112ddabf871044fdce1a893d78e6852d3f | [
"MIT"
] | null | null | null | packages/ember-templates/lib/dom-helper.js | lan0/ember.js | 8112e7112ddabf871044fdce1a893d78e6852d3f | [
"MIT"
] | null | null | null | export { NodeDOMTreeConstruction as default } from 'ember-glimmer/dom';
| 36 | 71 | 0.791667 |
d5f005e897c807bf63d7e2654cda47924e861b64 | 801 | js | JavaScript | src/lib/clappr-responsive-container-plugin.js | Shugah/nani | 5063b1abb087f719fc96eeffcb904b631624dc63 | [
"MIT"
] | null | null | null | src/lib/clappr-responsive-container-plugin.js | Shugah/nani | 5063b1abb087f719fc96eeffcb904b631624dc63 | [
"MIT"
] | 6 | 2020-07-07T04:41:46.000Z | 2022-03-25T18:39:20.000Z | src/lib/clappr-responsive-container-plugin.js | ericlyssyllas/nani | be4124f924345e8ce24fad513e96fbdaf8b89330 | [
"MIT"
] | null | null | null | // https://github.com/paluh/clappr-responsive-container-plugin/blob/master/src/index.js
import {UICorePlugin, PlayerInfo, $} from 'clappr'
export default class ResponsiveContainer extends UICorePlugin {
get name () { return 'responsive_container' }
constructor (core) {
super(core)
let playerInfo = PlayerInfo.getInstance(this.options.playerId)
this.playerWrapper = playerInfo.options.parentElement
$(document).ready(() => { this.resize() })
}
bindEvents () {
$(window).resize(() => {
this.resize()
})
}
resize () {
const width = (this.playerWrapper.clientWidth === 0 ? this.options.width : this.playerWrapper.clientWidth)
const height = this.options.height / this.options.width * width
this.core.resize({ width: width, height: height })
}
}
| 32.04 | 110 | 0.686642 |
d5f1dbb6eb2f97ca820ba553d39eb6e11138dd5e | 199 | js | JavaScript | packages/babel-plugin-proposal-class-properties/test/fixtures/assumption-setPublicClassFields/length-name-use-define/input.js | magic-akari/babel | 2c7e9f79bb8c28c73ecc52c53fa1bc3a25c21b63 | [
"MIT"
] | 1 | 2015-02-15T09:55:00.000Z | 2015-02-15T09:55:00.000Z | packages/babel-plugin-proposal-class-properties/test/fixtures/assumption-setPublicClassFields/length-name-use-define/input.js | magic-akari/babel | 2c7e9f79bb8c28c73ecc52c53fa1bc3a25c21b63 | [
"MIT"
] | 1 | 2015-02-15T09:34:56.000Z | 2015-02-15T09:36:47.000Z | packages/babel-plugin-proposal-class-properties/test/fixtures/assumption-setPublicClassFields/length-name-use-define/input.js | magic-akari/babel | 2c7e9f79bb8c28c73ecc52c53fa1bc3a25c21b63 | [
"MIT"
] | null | null | null | class A {
static name = 1;
static length = 2;
static foo = 3;
static [bar] = 4;
static ["name"] = 5;
static [name] = 6;
static "name" = 7;
name = 8;
length = 9;
} | 16.583333 | 24 | 0.477387 |
d5f1eb16dfed88b84c41339d8e6b01b21f5ed340 | 2,739 | js | JavaScript | resolvers/earthquake.resolver.js | aminfaz/USGS_Earthquake_GraphQL | aa5566cef0bf68fa4a7bfb86d5215ba7a36160a3 | [
"MIT"
] | null | null | null | resolvers/earthquake.resolver.js | aminfaz/USGS_Earthquake_GraphQL | aa5566cef0bf68fa4a7bfb86d5215ba7a36160a3 | [
"MIT"
] | 1 | 2020-03-17T10:07:34.000Z | 2020-03-17T10:07:34.000Z | resolvers/earthquake.resolver.js | aminfaz/USGS_Earthquake_GraphQL | aa5566cef0bf68fa4a7bfb86d5215ba7a36160a3 | [
"MIT"
] | null | null | null | const config = require('config');
const axios = require('axios');
const geolib = require('geolib');
const API_Summary_30d = config.get('API_Summary_30d');
async function getGeoDetails() {
try {
const content = await axios.get(API_Summary_30d);
return content.data;
} catch {
return null;
}
}
const filterByName = async ({
name
}) => {
if (!name) {
name = '';
}
let content = await getGeoDetails();
if (content === null) {
return null;
}
const matchingFeatures = content.features.filter(function (feature) {
return (feature.properties.place.toLowerCase().indexOf(name.toLowerCase()) >= 0);
});
return matchingFeatures;
}
const filterByRadius = async ({
input
}) => {
let content = await getGeoDetails();
const origin = content.features.find(feature => feature.id === input.originId);
if (!origin) {
return null;
}
const matchingFeatures = content.features.filter(function (feature) {
//filtering based on magnitude
if (typeof input.minMagnitude !== 'number') {
input.minMagnitude = 0;
}
if (typeof input.maxMagnitude !== 'number') {
input.maxMagnitude = 11;
}
if (feature.properties.mag < input.minMagnitude || feature.properties.mag > input.maxMagnitude) {
return false;
}
//filtering based on hasTsunami
if (typeof input.hasTsunami === 'boolean' && (
(input.hasTsunami && feature.properties.tsunami == null) ||
(!input.hasTsunami && feature.properties.tsunami !== null)
)) {
return false;
}
//filtering based on dates
startDate = new Date(input.startDatetime);
endDate = new Date(input.endDatetime);
earthquakeDate = new Date(parseInt(feature.properties.time));
if (earthquakeDate > endDate || earthquakeDate < startDate) {
return false;
}
//filtering based on the radius
return geolib.isPointWithinRadius({
latitude: feature.geometry.coordinates[1],
longitude: feature.geometry.coordinates[0]
}, {
latitude: origin.geometry.coordinates[1],
longitude: origin.geometry.coordinates[0]
},
input.radius * 1000
);
});
return matchingFeatures;
}
const filterById = async ({
id
}) => {
let content = await getGeoDetails();
return content.features.find(feature => feature.id === id);
}
const geoReslver = {
filterByName: filterByName,
filterByRadius: filterByRadius,
filterById: filterById
};
module.exports = geoReslver; | 29.138298 | 105 | 0.593647 |
d5f2b377afa14f4f003c20c987b7e908499600d0 | 714 | js | JavaScript | app/services/mysql.js | Morriso8D/MordhauRCON | 3b55aa7a9d95d103a518d3908b593792a996dc34 | [
"MIT"
] | 2 | 2021-08-09T09:01:48.000Z | 2021-09-02T16:53:26.000Z | app/services/mysql.js | Morriso8D/MordhauRCON | 3b55aa7a9d95d103a518d3908b593792a996dc34 | [
"MIT"
] | null | null | null | app/services/mysql.js | Morriso8D/MordhauRCON | 3b55aa7a9d95d103a518d3908b593792a996dc34 | [
"MIT"
] | null | null | null | require('dotenv').config();
const mysql = require('mysql2');
let instance = null;
class MySQL{
conn;
constructor(){
this.conn = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
});
}
connect(query){
this.conn.getConnection(function(err, connection) {
if(err) console.warn(err);
query(connection);
});
}
static singleton(){
if(!instance){
instance = new MySQL();
}
return instance;
}
}
module.exports = MySQL; | 19.833333 | 59 | 0.542017 |
d5f34151159656a3b665f726530bf92a179a9cee | 12,016 | js | JavaScript | assets/js/components/filter/FilterComponent.js | astutemyndz/adultlounge | 91329049f9d38ad1d0351342ebbdacaeaaa0a955 | [
"MIT"
] | null | null | null | assets/js/components/filter/FilterComponent.js | astutemyndz/adultlounge | 91329049f9d38ad1d0351342ebbdacaeaaa0a955 | [
"MIT"
] | 2 | 2021-03-10T06:01:26.000Z | 2021-05-11T01:46:48.000Z | assets/js/components/filter/FilterComponent.js | astutemyndz/adultlounge | 91329049f9d38ad1d0351342ebbdacaeaaa0a955 | [
"MIT"
] | 2 | 2020-11-04T08:26:51.000Z | 2020-11-06T07:37:44.000Z | import QueryStringComponent from '../query_string/QueryStringComponent.js';
class FilterComponent extends QueryStringComponent {
filterAttrs = null;
_filterElements;
_shortListingElements;
key;
value;
queryStringInstance;
_renderFilterElement;
state;
assetsDirPath;
baseURL;
_app;
api;
_context;
constructor() {
super();
this.setState({
models: [],
tags: [],
category: null,
message: null,
paramsArr: [],
params: {},
isLoading: false,
})
this.onInitDOM();
this.api = this.getBaseUrl() + 'api/v1';
this.assetsDirPath = 'assets/';
this.baseURL = this.getBaseUrl();
// this.onClickFilterElementEventHandler = this.onClickFilterElementEventHandler.bind(this);
// this.FilterEmptyComponent = this.FilterEmptyComponent.bind(this);
// this.HeadingComponent = this.HeadingComponent.bind(this);
// this.render = this.render.bind(this);
// this.reload = this.reload.bind(this);
// this.setQueryString = this.setQueryString.bind(this);
// this.objectToQueryString = this.objectToQueryString.bind(this);
// this.onInitDOM = this.onInitDOM.bind(this);
//this.onload = this.onload.bind(this);
}
setState = (obj) => {
this.state = obj;
return this;
}
onInitDOM = () => {
this._filterElements = document.querySelectorAll('._filter');
this._renderModelElement = document.querySelector('#_render_model_element');
this._renderFilterElement = document.querySelector('#_render_filter_element');
this._app = document.querySelector('._app');
this._shortListingElements = document.querySelector('._tag');
this.componentDidMount();
this.onClickFilterElementEventHandler();
//this.onClickRemoveTagElementEventHandler();
//this.reload();
}
initReloadDOMCallBack() {
//this._reload = document.querySelector('#_reload');
}
reload = () => {
//Event Delegation
this._app.addEventListener('click', (e) => {
console.log(this);
if(e.target.matches('_tag')) {
console.log(event.currentTarget);
window.setTimeout(() => {
this.componentDidMount();
console.log('fetched');
}, 200);
} else {
console.log(event.currentTarget);
}
})
}
WithLoading(component) {
return function WihLoadingComponent({ isLoading, ...props }) {
if (!isLoading) return component();
return (`<p>Be Hold, fetching data may take some time :)</p>`);
}
}
componentDidMount = () => {
const {paramsArr, params} = this.state;
this.fetchModels(API_URL + 'filter/model')
.then(res => {
if(res.data.length > 0) {
this.setState({
...this.state,
models: res.data,
tags: paramsArr,
category: (params.category) ? params.category: '',
message: ''
});
this.render();
} else {
this.setState({
...this.state,
models: [],
tags: [],
category: '',
message: res.message
})
this.render();
}
//console.log('componentDidMount',this.state);
})
}
componentDidUpdate = () => {
const {paramsArr, params} = this.state;
this.fetchModels(API_URL + 'filter/model?', params)
.then(res => {
if(res.data.length > 0) {
this.setState({
...this.state,
models: res.data,
tags: paramsArr,
category: (params.category) ? params.category: '',
message: ''
});
this.render();
} else {
this.setState({
...this.state,
models: [],
tags: [],
category: '',
message: res.message
})
this.render();
}
//console.log('componentDidUpdate',this.state);
})
}
setQueryString = (key, value) => this.updateQueryStringParam(key, value);
queryStringToObject = (str) => this.queryStringToJSObject(str);
objectToQueryString = (obj) => this.jSObjectToQueryString(obj);
onClickFilterElementEventHandlerCallBack = () => {
}
onClickFilterElementEventHandler = (e) => {
var self = this;
this._filterElements.forEach((filterElement) => {
filterElement.addEventListener('click', function() {
const queryString = self.setQueryString(filterElement.getAttribute('data-key'),filterElement.getAttribute('data-value'));
const params = self.queryStringToObject(queryString);
let paramsArr = [];
for (const property in params) {
if(property != 'category') {
paramsArr.push({
key: property,
value: params[property],
})
}
}
self.setState({
...self.state,
paramsArr: paramsArr,
params: params,
})
//console.log(self.state);
self.componentDidUpdate();
self.render();
});
})
}
onClickRemoveTagElementEventHandler = (e) => {
var self = this;
this._shortListingElements.forEach((shortListingElement) => {
shortListingElement.addEventListener('click', function() {
if(e.target.matches('_tag')) {
console.log(1);
}
// const queryString = self.setQueryString(filterElement.getAttribute('data-key'),filterElement.getAttribute('data-value'));
// const params = self.queryStringToObject(queryString);
// let paramsArr = [];
// for (const property in params) {
// if(property != 'category') {
// paramsArr.push({
// key: property,
// value: params[property],
// })
// }
// }
// self.setState({
// ...self.state,
// paramsArr: paramsArr,
// params: params,
// })
// self.componentDidUpdate();
// self.render();
});
})
}
async fetchModels(url, params) {
const objToQueryString = this.objectToQueryString(params);
let response = await fetch(url + `${objToQueryString}`);
let data = await response.json()
return data;
}
render = () => {
var self = this;
const {models, tags, category, params} = self.state;
const items = []
const _tags = [];
if(models) {
models.map((model) => items.push(this.ItemComponent(model)));
}
if(tags) {
tags.map((tag) => {
if(tag.value.length > 0) {
_tags.push(this.TagComponent(tag));
}
});
}
let heading = this.HeadingComponent({category: 'All Girls Cams', totalModel: models.length});
if(category) {
heading = this.HeadingComponent({category, totalModel: models.length});
}
if(Object.keys(params).length > 0) {
if(models.length > 0) {
this._renderFilterElement.innerHTML = (
`<div class="list-widget">
${heading}
<div class="shorting-list">
<ul>
${_tags}
</ul>
</div>
<div class="col gridview">
${items}
</div>
</div>`
);
} else {
this._renderFilterElement.innerHTML = this.FilterEmptyComponent();
}
} else {
if(models.length > 0) {
this._renderModelElement.innerHTML = (
`<div class="list-widget">
${heading}
<div class="shorting-list">
<ul>
${_tags}
</ul>
</div>
<div class="col gridview">
${items}
</div>
</div>`
);
} else {
this._renderModelElement.innerHTML = this.FilterEmptyComponent();
}
}
}
FilterEmptyComponent = () => {
const {message} = this.state;
return (`<div class="main-heading"><h3>${message}<a href="javascript:void(0);"><img src="${this.baseURL}${this.assetsDirPath}images/icon-reload.png"></a> <span><a href="#">0 Models Found</a></span></h3></div>`)
}
HeadingComponent = (props) => {
const {category, totalModel} = props;
return (`
<div class="main-heading">
<h3>${category.toUpperCase()} <a href="javascript:void(0);" id="reload"><img src="${this.baseURL}${this.assetsDirPath}images/icon-reload.png"></a> <span><a href="#">${totalModel} Models Found </a></span></h3>
</div>
`);
}
TagComponent = (props) => (`<li class="_tag" data-key="${props.key}" data-value="${props.value}">${props.value.toUpperCase()} <a href="javascript:void(0);" ><i class="fa fa-times-circle" aria-hidden="true"></i></a></li>`);
ItemComponent(props) {
const {id, name,slug, display_name, price_in_private, price_in_group, img} = props;
let performType;
//const performType = (price_in_private && price_in_private != '0.00') ? 'In Private' : (price_in_group && price_in_group != '0.00') ? 'In Group' : 'In Private';
if(price_in_private && price_in_private != '0.00') {
performType = 'In Private';
}
if(price_in_group && price_in_group != '0.00') {
performType = 'In Group';
}
return(`
<div class="col-grid">
<figure class="active">
<span class="strapbox">${performType}</span>
<a href="performer/${id}/${slug}"><img src="${img}" alt="${display_name}" /></a>
<figcaption>
<h4><span class="active-circle"></span><a href="performer/${id}/${slug}">${display_name}</a></h4>
<ul>
<li>PRIVATE: <span>£${price_in_private}</span> p/m</li>
<li>GROUP: <span>£${price_in_group}</span> p/M</li>
</ul>
</figcaption>
</figure>
</div>
`);
}
}
new FilterComponent(); | 36.192771 | 226 | 0.45531 |
d5f40f153e57d3ce9a9ccd0a901e349b0c871343 | 7,974 | js | JavaScript | examples/office/src/scripts/office.js | gbdrummer/chassis-lib | 5ad1f6be32fce3801bf5dc206744ca7f80a64dc5 | [
"BSD-3-Clause"
] | 5 | 2015-10-25T01:39:34.000Z | 2017-05-12T06:45:34.000Z | examples/office/src/scripts/office.js | gbdrummer/chassis-lib | 5ad1f6be32fce3801bf5dc206744ca7f80a64dc5 | [
"BSD-3-Clause"
] | 25 | 2015-11-18T20:59:31.000Z | 2017-09-13T18:56:31.000Z | examples/office/src/scripts/office.js | gbdrummer/chassis-lib | 5ad1f6be32fce3801bf5dc206744ca7f80a64dc5 | [
"BSD-3-Clause"
] | 3 | 2015-10-25T01:40:14.000Z | 2021-07-06T23:26:26.000Z | // hide body to prevent FOUC
document.body.style.opacity = 0
window.addEventListener('WebComponentsReady', function () {
setTimeout(function () {
document.body.style.opacity = 1
}, 100)
})
// set the dialog boxes to vars
var editEmployeeDialog = document.querySelector('chassis-overlay[name="editEmployee"]')
var addEmployeeDialog = document.querySelector('chassis-overlay[name="addEmployee"]')
// create the employee model
var Employee = new NGN.DATA.Model({
autoid: true,
fields: {
first: {
type: String
},
last: {
type: String
},
dob: {
type: Date
}
},
virtuals: {
fullName: function () {
return this.first + ' ' + this.last
},
age: function (e) {
return moment().diff(moment(this.dob), 'years') // eslint-disable-line no-undef
}
}
})
// create the employee store
var EmployeeStore = new NGN.DATA.Store({
model: Employee,
allowDuplicates: false
})
// pre-populate the employee list
var employees = [{
first: 'Michael',
last: 'Skott',
dob: '1973-08-14'
}, {
first: 'Jim',
last: 'Haplert',
dob: moment().year('1978').format('YYYY-MM-DD') // eslint-disable-line no-undef
}, {
first: 'Stanley',
last: 'Hudson',
dob: '1965-08-14'
}]
/**
* Set click handlers for an array of elements
* @param {String} type
* @param {Array} elements An array of dom elements to add handlers to
*/
function setHandlers (type, elements) {
elements = elements || []
elements.forEach(function (el) {
el.onclick = function (e) {
var data = e.currentTarget.dataset
var model = EmployeeStore.find(data.id)
if (type === 'undo') {
model.undo(3) // each update modifies 3 fields
refreshEmployees()
} else if (type === 'remove') {
removeEmployee(data.id)
} else if (type === 'edit') {
document.querySelector('input[name="editName"]').value = data.name
document.querySelector('input[name="editDob"]').value = data.dob
document.querySelector('input[name="id"]').value = data.id
editEmployeeDialog.open()
}
}
})
}
/**
* Refresh the employee list and set the handlers
*/
function refreshEmployees () {
document.getElementById('employees').innerHTML = getEmployeesHtml()
// set the onclick handlers for undo and remove buttons
setHandlers('undo', document.querySelectorAll('button[name="undo"]'))
setHandlers('remove', document.querySelectorAll('button[name="remove"]'))
setHandlers('edit', document.querySelectorAll('button[name="editEmployee"]'))
}
/**
* Edit the employee model and refresh the view
*
* @param {String} modelId
* @param {Object} data
* @param {String} data.first
* @param {String} data.last
* @param {String} data.dob
*/
function editEmployee (modelId, data) {
var model = EmployeeStore.find(modelId)
model.first = data.first
model.last = data.last
model.dob = data.dob
refreshEmployees()
}
/**
* Add an employee model to the store, set all event listeners on the model,
* and refresh the view
*
* @param {Object} data
* @param {String} data.first
* @param {String} data.last
* @param {String} data.dob
*/
function addEmployee (data) {
addEvents(EmployeeStore.add(data))
refreshEmployees()
}
/**
* Remove an employee model from the store and refresh the view
*
* @param {String} id
*/
function removeEmployee (id) {
var model = EmployeeStore.find(id)
var index = EmployeeStore.indexOf(model)
EmployeeStore.remove(index)
refreshEmployees()
}
// Take the provided data, modify the employee, and close the dialog
document.querySelector('button[name="submitEditDialog"]').onclick = function (e) {
var data = {
first: document.querySelector('input[name="editName"]').value.split(' ')[0],
last: document.querySelector('input[name="editName"]').value.split(' ')[1] || '',
dob: document.querySelector('input[name="editDob"]').value
}
editEmployee(document.querySelector('input[name="id"]').value, data)
editEmployeeDialog.close()
}
// Take the provided data, add the new employee, and close/clear the dialog
document.querySelector('button[name="submitAddDialog"]').onclick = function (e) {
var data = {
first: document.querySelector('input[name="addName"]').value.split(' ')[0],
last: document.querySelector('input[name="addName"]').value.split(' ')[1] || '',
dob: document.querySelector('input[name="addDob"]').value
}
addEmployee(data)
// close and clear the dialog
document.querySelector('button[name="closeAddDialog"]').click()
}
// Close the edit dialog
document.querySelector('button[name="closeEditDialog"]').onclick = function (e) {
editEmployeeDialog.close()
}
// Close the add dialog and clear the values on the input
document.querySelector('button[name="closeAddDialog"]').onclick = function (e) {
document.querySelector('input[name="addName"]').value = ''
document.querySelector('input[name="addDob"]').value = ''
addEmployeeDialog.close()
}
// Add each employee to the store
employees.forEach(function (e) {
addEmployee(e)
})
/**
* Add event handling to a givel model
*
* @param {Object} model An instance of an NGN model
*/
function addEvents (model) {
var events = [
'field.update',
'field.create',
'field.remove',
'field.invalid',
'validator.add',
'validator.remove',
'relationship.create',
'relationship.remove'
]
events.forEach(function (event) {
model['on'](event, function (e) {
console.log(e)
if (event.search(/field/) >= 0) {
refreshEmployees()
}
})
})
}
function filterAndSortRecords () {
EmployeeStore.clearFilters()
var filterVal = document.querySelector('input[name="filter"]').value
var regex = new RegExp(filterVal, 'i')
EmployeeStore.addFilter(function (employee) {
return !filterVal || employee.first.search(regex) >= 0 || employee.last.search(regex) >= 0
})
EmployeeStore.sort({
last: 'asc',
first: 'asc'
})
}
/**
* Apply filtering and sorting to the data store, before returning
* the appropriate HTML for refreshing the employees currently clocked in
*
* @return {String} HTML
*/
function getEmployeesHtml () {
filterAndSortRecords()
// This function is broken right now in conjunction with addFilter. We'll do a hacky sort manually
var employees = EmployeeStore.records
var html = ''
employees.forEach(function (employee) {
var htmlClass = 'employeeData'
var birthday = false
employee = EmployeeStore.find(employee.id)
/* eslint-disable no-undef */
if (moment().date() === moment(employee.dob).date() &&
moment().month() === moment(employee.dob).month()) {
birthday = true
htmlClass += ' birthday'
}
html += '<div class="employee">' +
'<div class="' + htmlClass + '">' +
'Name: ' + employee.fullName + '<br>' +
'Dob: ' + moment(employee.dob).format('YYYY-MM-DD') +
(birthday ? '<br> Happy Birthday (' + employee.age + ') ' + employee.first + '!' : '') +
'</div>' +
'<button name="editEmployee" data-id="' + employee.id + '"' +
'data-name="' + employee.fullName + '" data-dob="' + moment(employee.dob).format('YYYY-MM-DD') + '">Edit</button>' +
'<button name="undo" data-id="' + employee.id + '">Undo</button>' +
'<button name="remove" data-id="' + employee.id + '">Clock Out</button>' +
' </div>'
})
return html
/* eslint-enable */
}
// open the addEmployee dialog
document.getElementById('clockIn').onclick = function () {
addEmployeeDialog.open()
}
// clear the filter input text box and refresh the employee list
document.querySelector('button[name="clearFilter"]').onclick = function () {
document.querySelector('input[name="filter"]').value = ''
refreshEmployees()
}
// filter the employees by name, given a filter input
document.querySelector('input[name="filter"]').onkeyup = function (e) {
refreshEmployees()
}
// initialize the employee list
refreshEmployees()
| 28.891304 | 124 | 0.658014 |
d5f4bf601d3e71cca7a4e4179f18b4ecd722a277 | 1,051 | js | JavaScript | js/tap.js | dhval/dhval.github.io | c4bfc03179239499155ce5453ef2341aaae08a09 | [
"MIT"
] | null | null | null | js/tap.js | dhval/dhval.github.io | c4bfc03179239499155ce5453ef2341aaae08a09 | [
"MIT"
] | null | null | null | js/tap.js | dhval/dhval.github.io | c4bfc03179239499155ce5453ef2341aaae08a09 | [
"MIT"
] | null | null | null | /**
* Adds "tap" event to jQuery, which bypasses 300ms delay that normally follows
* the click event on mobile devices.
*
* @param {jQuery} $
* @returns {undefined}
*/
define(["jquery"], function($) {
$.event.special.tap = {
setup: function() {
var self = this, $self = $(self);
// Bind touch start
$self.on('touchstart', function(startEvent) {
// Save the target element of the start event
var target = startEvent.target;
// When a touch starts, bind a touch end handler exactly once,
$self.one('touchend', function(endEvent) {
// When the touch end event fires, check if the target of the
// touch end is the same as the target of the start, and if
// so, fire a click.
if (target === endEvent.target) {
$.event.simulate('tap', self, endEvent);
}
});
});
}
};
}); | 33.903226 | 81 | 0.495718 |
d5f52d43ff883a4a4351c6a44382b777741b5991 | 657 | js | JavaScript | systemjs.builder.js | spencersmb/angular2-maxbuild | ae43bd4fcdce05d0867fd9281fa593d59d2bf2dc | [
"MIT"
] | null | null | null | systemjs.builder.js | spencersmb/angular2-maxbuild | ae43bd4fcdce05d0867fd9281fa593d59d2bf2dc | [
"MIT"
] | null | null | null | systemjs.builder.js | spencersmb/angular2-maxbuild | ae43bd4fcdce05d0867fd9281fa593d59d2bf2dc | [
"MIT"
] | null | null | null | var path = require("path");
var Builder = require('systemjs-builder');
const del = require('del');
// optional constructor options
// sets the baseURL and loads the configuration file
var builder = new Builder('', 'systemjs.config.js');
builder
.buildStatic('./dist/app/main.js', './dist/app/main.js', { minify: true})
.then(function() {
del(['./dist/app/**/*', '!./dist/app/main.js']).then(function (paths) {
console.log('Deleted files and folders:\n', paths.join('\n'));
});
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
}); | 32.85 | 79 | 0.598174 |
d5f895c12a2b81238df593d1124329fdb5387115 | 3,651 | js | JavaScript | index.js | bakzkndd/CodeBlockEnhanced | 3c7cad3f51173232678d1449aec7540d1211d6c8 | [
"MIT"
] | null | null | null | index.js | bakzkndd/CodeBlockEnhanced | 3c7cad3f51173232678d1449aec7540d1211d6c8 | [
"MIT"
] | null | null | null | index.js | bakzkndd/CodeBlockEnhanced | 3c7cad3f51173232678d1449aec7540d1211d6c8 | [
"MIT"
] | null | null | null | import React from "react";
import { getReactInstance } from "@vizality/util/react";
import { patch, unpatch } from "@vizality/patcher";
import HighlightedCodeBlock from "./components/HighlightedCodeBlock";
import { getModule } from "@vizality/webpack";
import { Plugin } from "@vizality/entities";
const { shiki } = require("./shiki.min.js");
const fs = require("fs");
const path = require("path");
const highlighter = require("./components/Highlighter");
const { getHighlighter, loadHighlighter } = highlighter.highlighter;
const CDN_PATH = "https://unpkg.com/shiki@0.9.4/";
export default class SuperCodeBlocks extends Plugin {
async start() {
if (this.settings.get("custom-theme-loaded", false)) {
let localTheme = this.settings.get("custom-theme-url");
let customTheme;
try {
const tempCDN = localTheme.split("/").slice(0, -2).join("/") + "/";
shiki.setCDN(tempCDN);
const tempThemeFile = localTheme.split("/").slice(-2).join("/");
customTheme = await shiki.loadTheme(tempThemeFile);
shiki.setCDN(CDN_PATH);
await loadHighlighter(customTheme);
} catch (error) {
shiki.setCDN(CDN_PATH);
await loadHighlighter(
shiki.BUNDLED_THEMES[this.settings.get("theme", 0)]
);
}
} else
await loadHighlighter(
shiki.BUNDLED_THEMES[this.settings.get("theme", 0)]
);
this.patchCodeBlocks();
this.injectStyles("./style.scss");
}
stop() {
unpatch("better-code-blocks-inline");
unpatch("better-code-blocks-embed");
this._forceUpdate();
}
patchCodeBlocks() {
const parser = getModule("parse", "parseTopic");
patch(
"better-code-blocks-inline",
parser.defaultRules.codeBlock,
"react",
(args, res) => {
this.injectCodeBlock(args, res);
return res;
}
);
this._forceUpdate();
}
injectCodeBlock(args, codeblock) {
const { render } = codeblock?.props;
codeblock.props.render = (codeblock) => {
let lang, content, contentIsRaw, res;
if (!args) {
res = render(codeblock);
lang = res?.props?.children?.props?.className
?.split(" ")
?.find(
(className) => !className.includes("-") && className !== "hljs"
);
if (res?.props?.children?.props?.children) {
content = res.props.children.props.children;
} else {
content =
res?.props?.children?.props?.dangerouslySetInnerHTML?.__html;
contentIsRaw = true;
}
} else {
[{ lang, content }] = args;
}
res = (
<HighlightedCodeBlock
language={lang}
content={content}
contentIsRaw={contentIsRaw}
hasWrapper={false}
theme={shiki.BUNDLED_THEMES[this.settings.get("theme", 0)]}
highlighter={getHighlighter()}
showCopyButton={this.settings.get("copyButton", true)}
showCopyButtonQuickCode={this.settings.get(
"copyToQuickCodeButton",
true
)}
showHeader={this.settings.get("showHeader", true)}
showLineNumbers={this.settings.get("showLineNumbers", true)}
/>
);
return res;
};
}
_forceUpdate() {
/*
* @todo Make this better.
* @note Some messages don't have onMouseMove, so check for that first.
*/
document
.querySelectorAll(`[id^='chat-messages-']`)
.forEach(
(e) =>
Boolean(getReactInstance(e)?.memoizedProps?.onMouseMove) &&
getReactInstance(e).memoizedProps.onMouseMove()
);
}
}
| 28.97619 | 75 | 0.594358 |
936e1d880ac1f7112fed76fac72c8611424a6d3a | 2,029 | js | JavaScript | server/src/graphql/mutations/game.js | KiranJKurian/Codenames | d3b5bf1c9848f4e55dd1df9a1dd7b8210b33a548 | [
"MIT"
] | 2 | 2020-07-28T15:28:51.000Z | 2020-08-30T20:52:59.000Z | server/src/graphql/mutations/game.js | KiranJKurian/Codenames | d3b5bf1c9848f4e55dd1df9a1dd7b8210b33a548 | [
"MIT"
] | 8 | 2020-08-15T18:59:19.000Z | 2022-02-27T01:31:09.000Z | server/src/graphql/mutations/game.js | KiranJKurian/Codenames | d3b5bf1c9848f4e55dd1df9a1dd7b8210b33a548 | [
"MIT"
] | null | null | null | import { ActionTypes } from '../../constants';
const { Sides } = require('../../constants');
export const createGame = async (roomCode, Room) => {
try {
const game = Room.findOne({ roomCode })
.then(room => room.createGame())
.then(room => {
const newGame = room.games[room.games.length - 1];
room.addAction({ type: ActionTypes.NEW_GAME, gameId: newGame.id });
return newGame;
})
.catch(e => {
console.error(e);
return null;
});
if (game === null) {
throw new Error(`Could not create game in room ${roomCode}`);
}
return {
code: 200,
success: true,
message: 'Created game',
game,
};
} catch (e) {
return {
code: 500,
success: false,
message: e.toString(),
};
}
};
export const endTurn = async (name, roomCode, Room) => {
try {
const game = await Room.findOne(
{ roomCode },
{ games: { $slice: -1 }, players: { $elemMatch: { name } }, actions: 1 }
)
.then(room => {
const {
players: [playerEndingTurn],
games: [currentGame],
} = room;
if (playerEndingTurn.side !== currentGame.turn) {
throw new Error();
}
currentGame.turn = currentGame.turn === Sides.RED ? Sides.BLUE : Sides.RED;
return room
.save()
.then(() =>
room.addAction({
type: ActionTypes.END_TURN,
playerName: name,
playerSide: playerEndingTurn.side,
})
)
.then(() => currentGame);
})
.catch(e => {
console.error(e);
return null;
});
if (game === null) {
throw new Error(`Could not end turn of player ${name} of room ${roomCode}`);
}
return {
code: '200',
success: true,
message: 'Ended turn',
game,
};
} catch (e) {
return {
code: '500',
success: false,
message: e.toString(),
};
}
};
| 22.797753 | 83 | 0.495318 |
936eed9b68168b2ea173d3290032e55d03ef6334 | 1,048 | js | JavaScript | src/actions/types.js | quangtuyendev/Learn-English | 2bbe881fe80a5e386f5cfb338e900aabd638d16a | [
"MIT"
] | null | null | null | src/actions/types.js | quangtuyendev/Learn-English | 2bbe881fe80a5e386f5cfb338e900aabd638d16a | [
"MIT"
] | null | null | null | src/actions/types.js | quangtuyendev/Learn-English | 2bbe881fe80a5e386f5cfb338e900aabd638d16a | [
"MIT"
] | null | null | null | export const URL = 'http://5e6753ea1937020016fed960.mockapi.io';
export const AUTH_USER = 'AUTH_USER';
export const SIGN_OUT = 'SIGN_OUT';
export const SIGN_UP = 'SIGN_UP';
export const FETCH_USERS = 'FETCH_USERS';
export const FETCH_ITEMS = 'FETCH_ITEMS';
export const FETCH_ITEMS_ERROR = 'FETCH_ITEMS_ERROR';
export const SAVE_ITEM = 'SAVE_ITEM';
export const SAVE_ITEM_ERROR = 'SAVE_ITEM_ERROR';
export const DELETE_ITEM = 'DELETE_ITEM';
export const DELETE_ITEM_ERROR = 'DELETE_ITEM_ERROR';
export const SEARCH_ITEM = 'SEARCH_ITEM';
export const SORT_ITEM = 'SORT_ITEM';
export const FETCH_ITEM_EDIT = 'FETCH_ITEM_EDIT';
export const CLEAR_ITEM_EDIT = 'CLEAR_ITEM_EDIT';
export const SHOW_MODAL = 'SHOW_MODAL';
export const HIDE_MODAL = 'HIDE_MODAL';
export const SHOW_LOADING = 'SHOW_LOADING';
export const HIDE_LOADING = 'HIDE_LOADING';
export const STATUS_CODE = {
SUCCESS: 200,
CREATED: 201,
ERROR: 404,
};
export const GOOGLE_TRANSLATE_URL =
'https://translate.google.com/?hl=vi#view=home&op=translate&sl=en&tl=vi&text=';
| 29.111111 | 81 | 0.769084 |
936f69b853ca71527ee29b6f404e06b00d5c56de | 314 | js | JavaScript | examples/radish34/ui/src/pages/PurchaseOrder.js | ShipChain/baseline | 630987d661944e66065b501f4f7f6fe0bd6263a4 | [
"CC0-1.0"
] | 533 | 2020-03-19T16:04:37.000Z | 2021-06-28T11:55:25.000Z | examples/radish34/ui/src/pages/PurchaseOrder.js | ShipChain/baseline | 630987d661944e66065b501f4f7f6fe0bd6263a4 | [
"CC0-1.0"
] | 220 | 2020-03-19T19:16:32.000Z | 2021-06-23T17:39:12.000Z | examples/radish34/ui/src/pages/PurchaseOrder.js | ShipChain/baseline | 630987d661944e66065b501f4f7f6fe0bd6263a4 | [
"CC0-1.0"
] | 216 | 2020-03-19T16:06:40.000Z | 2021-06-27T19:57:11.000Z | import React from 'react';
import NoticeLayout from '../components/NoticeLayout';
import PurchaseOrderDetail from './PurchaseOrderDetail';
const PurchaseOrder = () => {
return (
<NoticeLayout selected="purchaseorder">
<PurchaseOrderDetail />
</NoticeLayout>
);
};
export default PurchaseOrder;
| 22.428571 | 56 | 0.719745 |
936fdf09b69d1822c75220b285a2ea72985a911e | 4,317 | js | JavaScript | src/store/modules/user.js | SaltyFish6952/eilieili-vue | 52da77e8d3e2efd86a4caa40f7ec07319312718d | [
"MIT"
] | null | null | null | src/store/modules/user.js | SaltyFish6952/eilieili-vue | 52da77e8d3e2efd86a4caa40f7ec07319312718d | [
"MIT"
] | null | null | null | src/store/modules/user.js | SaltyFish6952/eilieili-vue | 52da77e8d3e2efd86a4caa40f7ec07319312718d | [
"MIT"
] | null | null | null | // import {login, logout, getInfo} from '@/api/user'
import {getUserInfo, login} from '@/api/user'
import {getToken, setToken, removeToken, getUser, setUser, removeUser} from '@/utils/auth'
import {Encrypt} from '@/utils/crypto'
// import { resetRouter } from '@/router'
const getDefaultState = () => {
const user = JSON.parse(getUser());
if (user != null) {
return {
token: getToken(),
name: user.userName,
avatar: user.userPicPath,
uid: user.userId,
ulv: user.userLevel,
ulvprogress: user.userLevelProgress
}
} else {
return {
token: '',
name: '',
avatar: '',
uid: '',
ulv: '',
ulvprogress: ''
}
}
}
const state = getDefaultState()
const mutations = {
RESET_STATE: (state) => {
Object.assign(state, getDefaultState())
},
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_ULV: (state, ulv) => {
state.ulv = ulv
},
SET_ULVPROGRESS: (state, ulvprogress) => {
state.ulvprogress = ulvprogress
},
SET_UID: (state, uid) => {
state.uid = uid
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
}
}
const actions = {
// user login
login({commit}, userInfo) {
const {userAccount, password} = userInfo
return new Promise((resolve, reject) => {
window.console.log(userAccount, Encrypt(password))
login({"userAccount": userAccount, "password": Encrypt(password)}).then(response => {
window.console.log(response);
if (response.code === 0) {
const {data} = response;
commit('SET_TOKEN', data.token);
commit('SET_ULV', data.user.userLevel);
commit('SET_ULVPROGRESS', data.user.userLevelProgress);
commit('SET_UID', data.user.userId);
commit('SET_NAME', data.user.userName);
commit('SET_AVATAR', data.user.userPicPath)
setToken(data.token)
setUser(data.user)
}
resolve(response.code)
}).catch(error => {
reject(error)
})
})
},
// get user info
getInfo({commit, state}) {
return new Promise((resolve, reject) => {
getUserInfo({userId: state.uid}).then(response => {
window.console.log(response)
const {user} = response.data
if (!user) {
reject('Verification failed, please Login again.')
}
commit('SET_ULV', user.userLevel);
commit('SET_ULVPROGRESS', user.userLevelProgress);
commit('SET_UID', user.userId);
commit('SET_NAME', user.userName);
commit('SET_AVATAR', user.userPicPath)
setUser(user)
resolve(user)
}).catch(error => {
reject(error)
})
})
},
// user logout
// eslint-disable-next-line no-unused-vars
logout({commit, state}) {
return new Promise((resolve, reject) => {
// logout(state.token).then(() => {
// removeToken() // must remove token first
// // resetRouter()
// commit('RESET_STATE')
// resolve(0)
// }).catch(error => {
// reject(error)
// })
try {
removeToken(); // must remove token first
removeUser();
// resetRouter()
commit('RESET_STATE')
resolve(0)
} catch (error) {
reject(error)
}
})
},
// remove token
resetToken({commit}) {
return new Promise(resolve => {
removeToken() // must remove token first
removeUser()
commit('RESET_STATE')
resolve()
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
| 26.813665 | 97 | 0.479268 |
937136811307d6c614f2e77b65310caeb804ca77 | 38,689 | js | JavaScript | js/animate/out/bundle.js | ScottLouvau/kingdomrush | a3c8218c19fab8e43596309de31eeeeb4a0bc8d6 | [
"MIT"
] | null | null | null | js/animate/out/bundle.js | ScottLouvau/kingdomrush | a3c8218c19fab8e43596309de31eeeeb4a0bc8d6 | [
"MIT"
] | null | null | null | js/animate/out/bundle.js | ScottLouvau/kingdomrush | a3c8218c19fab8e43596309de31eeeeb4a0bc8d6 | [
"MIT"
] | null | null | null | // ../common/drawing.mjs
var Drawing = class {
constructor(canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
}
drawImage(image) {
this.ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, this.canvas.width, this.canvas.height);
}
drawSprite(pos, spriteMap, spriteGeo, spriteIndex) {
const from = {
x: spriteGeo.w * (spriteIndex % spriteGeo.cols),
y: spriteGeo.h * Math.floor(spriteIndex / spriteGeo.cols)
};
const to = {
x: pos.x + (spriteGeo.relX ?? 0),
y: pos.y + (spriteGeo.relY ?? 0)
};
this.ctx.drawImage(spriteMap, from.x, from.y, spriteGeo.w, spriteGeo.h, to.x, to.y, spriteGeo.w, spriteGeo.h);
}
drawText(pos, text, options) {
const lines = text.split(/\r?\n/);
const padX = options.padX ?? options.pad ?? 2;
const padY = options.padY ?? options.pad ?? 2;
this.ctx.textAlign = "left";
this.ctx.textBaseline = "alphabetic";
this.ctx.font = `${options.fontWeight ?? ""} ${options.fontSizePx ?? "24"}px ${options.fontFace ?? "Arial"}`;
let width = 0;
let height = 0;
let measures = [];
for (const line of lines) {
const measure = this.ctx.measureText(line);
measures.push(measure);
width = Math.max(width, measure.actualBoundingBoxRight + 2 * padX, options.minWidth ?? 0);
height = Math.max(height, measure.actualBoundingBoxAscent + 2 * padY, options.minHeight ?? 0);
}
const fullHeight = height * lines.length + padY;
const box = {
x: Math.ceil(pos.x - (options.left ? 0 : width / 2) + (options.relX ?? 0)),
y: Math.ceil(pos.y - fullHeight + (options.relY ?? 0)),
w: Math.ceil(width),
h: Math.ceil(fullHeight)
};
this.drawBox(box, options);
let nextY = box.y;
for (let i = 0; i < lines.length; ++i) {
const line = lines[i];
const measure = measures[i];
this.ctx.fillStyle = options.highlightIndex === i ? options.highlightColor : options.textColor;
this.ctx.fillText(line, Math.floor(box.x + +padX), Math.floor(nextY + height));
nextY += height;
}
}
drawBox(box, options) {
const width = options.width ?? 2;
if (options.borderColor) {
this.ctx.fillStyle = options.borderColor;
this.ctx.fillRect(box.x - width, box.y - width, width, box.h + 2 * width);
this.ctx.fillRect(box.x + box.w, box.y - width, width, box.h + 2 * width);
this.ctx.fillRect(box.x - width, box.y - width, box.w + 2 * width, width);
this.ctx.fillRect(box.x - width, box.y + box.h, box.w + 2 * width, width);
}
if (options.backColor) {
this.ctx.fillStyle = options.backColor;
this.ctx.fillRect(box.x, box.y, box.w, box.h);
}
}
drawTriangle(box, options) {
this.ctx.beginPath();
if (options.dir === "right") {
this.ctx.moveTo(box.x, box.y);
this.ctx.lineTo(box.x, box.y + box.h);
this.ctx.lineTo(box.x + box.w, box.y + box.h / 2);
this.ctx.lineTo(box.x, box.y);
} else {
this.ctx.moveTo(box.x + box.w, box.y);
this.ctx.lineTo(box.x + box.w, box.y + box.h);
this.ctx.lineTo(box.x, box.y + box.h / 2);
this.ctx.lineTo(box.x + box.w, box.y);
}
if (options.backColor) {
this.ctx.fillStyle = options.backColor;
this.ctx.fill();
}
if (options.borderColor) {
this.ctx.strokeStyle = options.borderColor;
this.ctx.lineWidth = options.width ?? 2;
this.ctx.stroke();
}
}
drawGradientCircle(center, options) {
var r = {
x: center.x + (options.relX ?? 0) - options.radius,
y: center.y + (options.relY ?? 0) - options.radius,
w: 2 * options.radius,
h: 2 * options.radius
};
var grad = this.ctx.createRadialGradient(r.x + r.w / 2, r.y + r.h / 2, 0, r.x + r.w / 2, r.y + r.h / 2, options.radius);
grad.addColorStop(0, options.color);
grad.addColorStop(1, "transparent");
if (options.mid) {
grad.addColorStop(options.mid.at, options.mid.color);
}
this.ctx.fillStyle = grad;
this.ctx.fillRect(r.x, r.y, r.w, r.h);
}
};
// ../data/positions.min.mjs
var positions_min_default = {
L1: { A9: { x: 761, y: 340 }, A8: { x: 646, y: 380 }, B5: { x: 781, y: 559 }, C3: { x: 909, y: 660 }, B3: { x: 774, y: 662 }, E3: { x: 1166, y: 683 }, G1: { x: 1381, y: 792 }, D1: { x: 1024, y: 836 } },
L2: { C9: { x: 1117, y: 259 }, A9: { x: 869, y: 282 }, C8: { x: 1116, y: 371 }, A6: { x: 771, y: 487 }, C3: { x: 1017, y: 664 }, A3: { x: 879, y: 693 }, C1: { x: 1033, y: 866 } },
L3: { C9: { x: 943, y: 162 }, A9: { x: 808, y: 195 }, E7: { x: 1238, y: 324 }, D7: { x: 1076, y: 327 }, B7: { x: 924, y: 362 }, D5: { x: 1161, y: 504 }, B4: { x: 816, y: 594 }, C3: { x: 967, y: 655 }, D2: { x: 1110, y: 697 }, A1: { x: 697, y: 792 }, F1: { x: 1362, y: 829 }, B1: { x: 834, y: 844 } },
L4: { D9: { x: 898, y: 236 }, E9: { x: 1042, y: 241 }, C9: { x: 763, y: 275 }, B8: { x: 682, y: 352 }, G7: { x: 1249, y: 394 }, B6: { x: 670, y: 456 }, G6: { x: 1310, y: 500 }, B5: { x: 711, y: 535 }, G4: { x: 1319, y: 617 }, A4: { x: 493, y: 632 }, G3: { x: 1220, y: 698 }, D3: { x: 916, y: 700 }, E3: { x: 1075, y: 712 }, H1: { x: 1384, y: 854 }, F1: { x: 1175, y: 885 } },
L5: { E9: { x: 1021, y: 178 }, B8: { x: 636, y: 260 }, A7: { x: 514, y: 326 }, G7: { x: 1286, y: 348 }, E7: { x: 1013, y: 378 }, G6: { x: 1348, y: 416 }, C6: { x: 770, y: 437 }, D4: { x: 964, y: 589 }, F4: { x: 1186, y: 597 }, B3: { x: 667, y: 625 }, D3: { x: 951, y: 677 }, F3: { x: 1168, y: 690 }, F1: { x: 1135, y: 795 }, B1: { x: 750, y: 840 } },
L6: { G9: { x: 1252, y: 221 }, A9: { x: 646, y: 223 }, C9: { x: 789, y: 223 }, E9: { x: 1116, y: 226 }, B7: { x: 664, y: 421 }, C7: { x: 806, y: 421 }, E7: { x: 1110, y: 421 }, F7: { x: 1251, y: 421 }, D4: { x: 957, y: 612 }, H4: { x: 1373, y: 612 }, C4: { x: 813, y: 615 }, E4: { x: 1096, y: 615 }, A4: { x: 533, y: 624 }, C1: { x: 789, y: 833 }, E1: { x: 1124, y: 833 } },
L7: { A9: { x: 767, y: 340 }, B9: { x: 914, y: 341 }, C9: { x: 1062, y: 345 }, C5: { x: 1007, y: 563 }, B5: { x: 868, y: 567 }, D5: { x: 1151, y: 567 }, A5: { x: 727, y: 570 }, B1: { x: 886, y: 777 }, C1: { x: 1024, y: 777 }, D1: { x: 1161, y: 783 }, E1: { x: 1279, y: 835 } },
L8: { E9: { x: 1024, y: 375 }, F9: { x: 1162, y: 378 }, G9: { x: 1301, y: 380 }, D5: { x: 936, y: 580 }, C5: { x: 799, y: 583 }, E5: { x: 1075, y: 586 }, A3: { x: 526, y: 698 }, G2: { x: 1249, y: 749 }, H2: { x: 1381, y: 749 }, D2: { x: 950, y: 785 }, C2: { x: 806, y: 787 }, D1: { x: 993, y: 861 } },
L9: { D9: { x: 903, y: 205 }, E9: { x: 1047, y: 210 }, F9: { x: 1187, y: 216 }, B7: { x: 680, y: 371 }, C7: { x: 805, y: 411 }, D7: { x: 945, y: 411 }, E7: { x: 1085, y: 413 }, G5: { x: 1336, y: 549 }, D4: { x: 934, y: 625 }, E4: { x: 1073, y: 625 }, F4: { x: 1214, y: 625 }, G4: { x: 1356, y: 650 }, F1: { x: 1179, y: 832 }, E1: { x: 1027, y: 835 }, C1: { x: 878, y: 837 }, A1: { x: 518, y: 858 } },
L10: { E8: { x: 1093, y: 311 }, F8: { x: 1229, y: 311 }, C7: { x: 810, y: 331 }, F6: { x: 1159, y: 410 }, E5: { x: 1079, y: 487 }, B4: { x: 733, y: 546 }, C4: { x: 867, y: 546 }, G3: { x: 1364, y: 569 }, E3: { x: 1061, y: 594 }, D2: { x: 943, y: 645 }, E1: { x: 1058, y: 718 }, H1: { x: 1377, y: 742 }, A1: { x: 536, y: 745 }, B1: { x: 674, y: 745 } },
L11: { B9: { x: 788, y: 186 }, E9: { x: 1123, y: 186 }, D7: { x: 1030, y: 372 }, C7: { x: 877, y: 373 }, F7: { x: 1168, y: 383 }, B7: { x: 743, y: 387 }, F6: { x: 1284, y: 434 }, A6: { x: 630, y: 435 }, A5: { x: 602, y: 541 }, G5: { x: 1319, y: 542 }, A3: { x: 660, y: 635 }, F3: { x: 1253, y: 643 }, B3: { x: 785, y: 676 }, E3: { x: 1117, y: 679 }, D1: { x: 1021, y: 809 }, C1: { x: 888, y: 812 }, A1: { x: 569, y: 833 }, G1: { x: 1324, y: 843 } },
L12: { A9: { x: 636, y: 317 }, F9: { x: 1294, y: 330 }, F8: { x: 1310, y: 427 }, F6: { x: 1290, y: 521 }, A6: { x: 706, y: 538 }, B6: { x: 853, y: 538 }, C6: { x: 992, y: 538 }, B2: { x: 792, y: 763 }, C2: { x: 931, y: 763 }, D2: { x: 1066, y: 763 }, E2: { x: 1203, y: 763 }, F2: { x: 1332, y: 767 }, G1: { x: 1395, y: 859 } },
L13: { A8: { x: 622, y: 335 }, G7: { x: 1297, y: 373 }, B4: { x: 649, y: 532 }, A4: { x: 515, y: 534 }, E4: { x: 1085, y: 548 }, F4: { x: 1221, y: 565 }, D4: { x: 940, y: 566 }, H4: { x: 1356, y: 566 }, C2: { x: 865, y: 657 }, A1: { x: 611, y: 715 }, B1: { x: 747, y: 719 }, F1: { x: 1124, y: 750 }, G1: { x: 1262, y: 760 }, H1: { x: 1401, y: 767 } },
L14: { B9: { x: 749, y: 303 }, A9: { x: 595, y: 306 }, C9: { x: 891, y: 311 }, F9: { x: 1225, y: 333 }, G9: { x: 1370, y: 335 }, B8: { x: 774, y: 396 }, C7: { x: 843, y: 484 }, A6: { x: 542, y: 504 }, G6: { x: 1348, y: 538 }, E5: { x: 1080, y: 631 }, B4: { x: 742, y: 700 }, C4: { x: 888, y: 700 }, E3: { x: 1023, y: 739 }, G3: { x: 1331, y: 743 }, F3: { x: 1176, y: 745 }, C1: { x: 826, y: 904 } },
L15: { C9: { x: 903, y: 216 }, B9: { x: 767, y: 220 }, E9: { x: 1104, y: 278 }, G7: { x: 1388, y: 378 }, E7: { x: 1116, y: 403 }, C7: { x: 836, y: 434 }, B7: { x: 699, y: 437 }, H6: { x: 1439, y: 475 }, E5: { x: 1111, y: 535 }, B5: { x: 678, y: 555 }, A4: { x: 559, y: 594 }, D4: { x: 993, y: 659 }, F4: { x: 1166, y: 659 }, H2: { x: 1429, y: 747 }, B2: { x: 719, y: 776 }, G1: { x: 1356, y: 857 }, E1: { x: 1071, y: 888 } },
L16: { G9: { x: 1300, y: 275 }, A9: { x: 529, y: 309 }, D7: { x: 900, y: 383 }, G7: { x: 1224, y: 383 }, A7: { x: 566, y: 403 }, E6: { x: 1009, y: 445 }, B6: { x: 660, y: 454 }, F5: { x: 1206, y: 501 }, E5: { x: 1069, y: 521 }, C4: { x: 840, y: 583 }, B3: { x: 644, y: 639 }, F2: { x: 1159, y: 701 }, E2: { x: 1024, y: 721 }, A1: { x: 495, y: 794 } },
L17: { F9: { x: 1138, y: 172 }, C9: { x: 840, y: 181 }, C7: { x: 813, y: 372 }, D7: { x: 952, y: 372 }, E7: { x: 1093, y: 372 }, A7: { x: 522, y: 390 }, F4: { x: 1154, y: 566 }, C4: { x: 864, y: 574 }, A4: { x: 559, y: 601 }, C3: { x: 768, y: 659 }, F3: { x: 1151, y: 676 }, G3: { x: 1301, y: 683 }, E2: { x: 1051, y: 739 }, A1: { x: 564, y: 805 }, G1: { x: 1244, y: 863 } },
L18: { C9: { x: 937, y: 335 }, D9: { x: 1076, y: 335 }, A9: { x: 792, y: 341 }, E6: { x: 1256, y: 541 }, D6: { x: 1079, y: 546 }, B6: { x: 902, y: 565 }, A4: { x: 674, y: 659 }, E4: { x: 1162, y: 663 }, F4: { x: 1339, y: 680 }, C2: { x: 957, y: 811 }, B1: { x: 824, y: 839 }, F1: { x: 1307, y: 888 } },
L19: { F9: { x: 1170, y: 184 }, D9: { x: 1038, y: 224 }, C8: { x: 912, y: 274 }, A7: { x: 583, y: 338 }, F7: { x: 1266, y: 378 }, H7: { x: 1404, y: 394 }, B6: { x: 775, y: 410 }, E5: { x: 1092, y: 480 }, A4: { x: 560, y: 607 }, G4: { x: 1294, y: 625 }, C3: { x: 895, y: 638 }, H3: { x: 1426, y: 671 }, C2: { x: 809, y: 745 }, B1: { x: 702, y: 816 }, F1: { x: 1260, y: 846 } },
L20: { F9: { x: 1151, y: 196 }, B8: { x: 605, y: 321 }, C7: { x: 765, y: 372 }, H7: { x: 1438, y: 386 }, G7: { x: 1301, y: 390 }, F6: { x: 1187, y: 445 }, A5: { x: 577, y: 531 }, D4: { x: 891, y: 573 }, B4: { x: 661, y: 610 }, C3: { x: 750, y: 687 }, A2: { x: 466, y: 746 }, G2: { x: 1196, y: 769 }, E2: { x: 1024, y: 770 }, C1: { x: 742, y: 854 } },
L21: { F6: { x: 1199, y: 489 }, E6: { x: 1009, y: 496 }, B6: { x: 594, y: 497 }, A5: { x: 442, y: 546 }, H5: { x: 1443, y: 552 }, E5: { x: 1072, y: 574 }, C5: { x: 761, y: 577 }, G4: { x: 1317, y: 607 }, A3: { x: 552, y: 695 }, D2: { x: 916, y: 736 }, F2: { x: 1152, y: 742 }, H2: { x: 1507, y: 753 }, C1: { x: 744, y: 812 }, G1: { x: 1277, y: 818 }, E1: { x: 1009, y: 832 } },
L22: { C9: { x: 730, y: 245 }, G9: { x: 1355, y: 289 }, E8: { x: 1059, y: 333 }, B8: { x: 657, y: 341 }, D8: { x: 936, y: 366 }, F8: { x: 1213, y: 366 }, H6: { x: 1421, y: 489 }, B5: { x: 602, y: 531 }, C5: { x: 805, y: 538 }, E5: { x: 1052, y: 544 }, B4: { x: 632, y: 643 }, F3: { x: 1245, y: 679 }, H3: { x: 1512, y: 693 }, D3: { x: 850, y: 695 }, F2: { x: 1125, y: 741 }, A2: { x: 445, y: 784 }, G1: { x: 1332, y: 873 }, C1: { x: 833, y: 884 } },
L23: { G9: { x: 1307, y: 245 }, H9: { x: 1443, y: 296 }, B8: { x: 697, y: 319 }, G8: { x: 1280, y: 356 }, D8: { x: 909, y: 382 }, F6: { x: 1099, y: 487 }, B6: { x: 692, y: 517 }, G5: { x: 1335, y: 584 }, C4: { x: 788, y: 634 }, A4: { x: 497, y: 660 }, F3: { x: 1100, y: 728 }, B2: { x: 666, y: 788 }, D2: { x: 936, y: 788 }, F1: { x: 1201, y: 874 } },
L24: { D9: { x: 943, y: 243 }, F9: { x: 1218, y: 297 }, B8: { x: 668, y: 366 }, H6: { x: 1395, y: 449 }, A6: { x: 452, y: 452 }, E6: { x: 1073, y: 466 }, D6: { x: 858, y: 490 }, B4: { x: 649, y: 577 }, C4: { x: 829, y: 642 }, F3: { x: 1137, y: 649 }, H3: { x: 1402, y: 649 }, D2: { x: 957, y: 714 }, H2: { x: 1519, y: 731 }, B1: { x: 644, y: 791 }, G1: { x: 1258, y: 844 } },
L25: { H9: { x: 1408, y: 316 }, G8: { x: 1310, y: 380 }, F7: { x: 1232, y: 461 }, A6: { x: 615, y: 507 }, H6: { x: 1525, y: 517 }, D5: { x: 978, y: 577 }, C4: { x: 840, y: 629 }, F4: { x: 1246, y: 684 }, G3: { x: 1383, y: 715 }, A3: { x: 525, y: 718 }, A2: { x: 643, y: 761 }, D2: { x: 999, y: 808 }, G1: { x: 1341, y: 823 }, D1: { x: 905, y: 873 } },
L26: { E9: { x: 990, y: 171 }, C9: { x: 720, y: 240 }, F7: { x: 1110, y: 366 }, E6: { x: 1002, y: 425 }, B6: { x: 583, y: 448 }, C6: { x: 739, y: 456 }, A6: { x: 428, y: 463 }, H5: { x: 1289, y: 510 }, E3: { x: 959, y: 645 }, B3: { x: 636, y: 667 }, A3: { x: 486, y: 684 }, F2: { x: 1055, y: 725 }, C2: { x: 727, y: 760 }, H1: { x: 1369, y: 799 }, E1: { x: 979, y: 854 } }
};
// ../data/towers.min.mjs
var towers_min_default = {
base: [
{ ln: "Barr", sn: "p1", on: null, cost: 70, unlock: 1, index: 0 },
{ ln: "Barr2", sn: "p2", on: "p1", cost: 110, unlock: 2, index: 1 },
{ ln: "Barr3", sn: "p3", on: "p2", cost: 160, unlock: 4, index: 2 },
{ ln: "Holy", sn: "p4", on: "p3", cost: 230, unlock: 6, index: 3 },
{ ln: "Barb", sn: "p5", on: "p3", cost: 230, unlock: 8, index: 4 },
{ ln: "Arch", sn: "r1", on: null, cost: 70, unlock: 1, index: 5 },
{ ln: "Arch2", sn: "r2", on: "r1", cost: 110, unlock: 2, index: 6 },
{ ln: "Arch3", sn: "r3", on: "r2", cost: 160, unlock: 4, index: 7 },
{ ln: "Rang", sn: "r4", on: "r3", cost: 230, unlock: 5, index: 8 },
{ ln: "Musk", sn: "r5", on: "r3", cost: 230, unlock: 7, index: 9 },
{ ln: "Mage", sn: "s1", on: null, cost: 100, unlock: 1, index: 10 },
{ ln: "Mage2", sn: "s2", on: "s1", cost: 160, unlock: 2, index: 11 },
{ ln: "Mage3", sn: "s3", on: "s2", cost: 240, unlock: 4, index: 12 },
{ ln: "Arca", sn: "s4", on: "s3", cost: 300, unlock: 6, index: 13 },
{ ln: "Sorc", sn: "s5", on: "s3", cost: 300, unlock: 9, index: 14 },
{ ln: "Arti", sn: "t1", on: null, cost: 125, unlock: 1, index: 15 },
{ ln: "Arti2", sn: "t2", on: "t1", cost: 220, unlock: 2, index: 16 },
{ ln: "Arti3", sn: "t3", on: "t2", cost: 320, unlock: 4, index: 17 },
{ ln: "BigB", sn: "t4", on: "t3", cost: 400, unlock: 8, index: 18 },
{ ln: "Tesl", sn: "t5", on: "t3", cost: 375, unlock: 10, index: 19 }
],
upgrades: [
{ ln: "Heal", sn: "x", on: "p4", cost: [150, 150, 150], index: 0 },
{ ln: "Shie", sn: "y", on: "p4", cost: [250], index: 1 },
{ ln: "HolS", sn: "z", on: "p4", cost: [220, 150, 150], index: 2 },
{ ln: "More", sn: "x", on: "p5", cost: [300, 100, 100], index: 3 },
{ ln: "Whir", sn: "y", on: "p5", cost: [150, 100, 100], index: 4 },
{ ln: "Thro", sn: "z", on: "p5", cost: [200, 100, 100], index: 5 },
{ ln: "Pois", sn: "x", on: "r4", cost: [250, 250, 250], index: 6 },
{ ln: "Wrat", sn: "y", on: "r4", cost: [300, 150, 150], index: 7 },
{ ln: "Snip", sn: "x", on: "r5", cost: [250, 250, 250], index: 9 },
{ ln: "Shra", sn: "y", on: "r5", cost: [300, 300, 300], index: 10 },
{ ln: "Deat", sn: "x", on: "s4", cost: [350, 200, 200], index: 12 },
{ ln: "Tele", sn: "y", on: "s4", cost: [300, 100, 100], index: 13 },
{ ln: "Poly", sn: "x", on: "s5", cost: [300, 150, 150], index: 15 },
{ ln: "Summ", sn: "y", on: "s5", cost: [350, 150, 150], index: 16 },
{ ln: "Drag", sn: "x", on: "t4", cost: [250, 100, 100], index: 18 },
{ ln: "Clus", sn: "y", on: "t4", cost: [250, 125, 125], index: 19 },
{ ln: "Supe", sn: "x", on: "t5", cost: [250, 250], index: 21 },
{ ln: "Over", sn: "y", on: "t5", cost: [250, 125, 125], index: 22 }
]
};
// ../common/planParser.mjs
var PlanParser = class {
parse(planText) {
const steps = planText.split(/\r?\n/);
if (steps.length === 1) {
return this.parseShort(planText);
}
let mapName = null;
let positions = null;
let result = { steps: [], errors: [] };
let world = {};
for (let i = 0; i < steps.length; ++i) {
let text = steps[i];
if (text === "") {
continue;
}
if (text.startsWith("#")) {
continue;
}
let stepParts = text.split(" ");
let positionName = stepParts?.[0]?.toUpperCase();
let action = stepParts?.[1]?.toLowerCase();
if (!mapName) {
mapName = positionName;
positions = positions_min_default[mapName];
result.mapName = mapName;
if (!positions) {
result.errors.push(`Line ${i + 1}: Unknown map name ${mapName}.`);
return result;
}
continue;
}
if (!positionName || !action) {
result.errors.push(`Line ${i + 1}: Did not have a position and action.`);
continue;
}
let position = positions[positionName];
if (!position) {
result.errors.push(`Line ${i + 1}: Unknown position '${positionName}' on ${mapName}.`);
continue;
}
let base = towers_min_default.base.find((t) => t.ln.toLowerCase() === action);
let upgrade = towers_min_default.upgrades.find((u) => action.startsWith(u.ln.toLowerCase()));
if (!base && !upgrade) {
result.errors.push(`Line ${i + 1}: Unknown action '${action}' at ${positionName} on ${mapName}.`);
continue;
}
let previous = world[positionName];
let step = {
text,
positionName,
position,
action: stepParts[1]
};
if (base) {
step.base = base;
step.shortAction = base.sn;
if (previous) {
if (base.sn[0] !== previous.base.sn[0]) {
result.errors.push(`Line ${i + 1}: Can't build ${base.ln} on ${previous.base.ln} at ${step.positionName}.`);
continue;
}
if (base.sn[1] <= previous.base.sn[1]) {
result.errors.push(`Line ${i + 1}: Tower downgrade ${base.ln} on ${previous.base.ln} at ${step.positionName}.`);
continue;
}
}
}
if (upgrade) {
if (!previous) {
result.errors.push(`Line ${i + 1}: Upgrade '${upgrade.ln}' on nothing at ${step.positionName}.`);
continue;
}
let lastUpgradeOfType = previous[upgrade.sn];
let newLevel = parseInt(action?.[action?.length - 1]) || (lastUpgradeOfType?.level ?? 0) + 1;
if (upgrade.on !== previous.base.sn) {
result.errors.push(`Line ${i + 1}: There is no '${upgrade.ln}' upgrade for ${previous.base.ln} at ${step.positionName}.`);
continue;
}
if (lastUpgradeOfType && newLevel <= lastUpgradeOfType.level) {
result.errors.push(`Line ${i + 1}: Ability downgrade from '${upgrade.ln}${lastUpgradeOfType.level}' to '${upgrade.ln}${newLevel}' at ${step.positionName}.`);
continue;
}
if (newLevel > upgrade.cost.length) {
result.errors.push(`Line ${i + 1}: Ability upgrade to level ${newLevel} when '${upgrade.ln}' max level is ${upgrade.cost.length} at ${step.positionName}.`);
continue;
}
step.upgrade = upgrade;
step.shortAction = `${upgrade.sn}${newLevel}`;
step[upgrade.sn] = { ...upgrade, level: newLevel };
}
this.apply(step, world);
result.steps.push(step);
}
return result;
}
parseShort(shortText) {
let ctx = { text: shortText, i: 0 };
this.parseLevel(ctx);
while (ctx.i < ctx.text.length) {
this.parseStep(ctx);
}
return ctx.result;
}
parseLevel(ctx) {
this.skipWhitespace(ctx);
this.require(ctx, "L", "Plan didn't start with map (ex: 'L26').");
const number = this.number(ctx);
this.require(ctx, ":", "Plan must have ':' after map name (ex: 'L26:').");
const mapName = `L${number}`;
ctx.positions = positions_min_default[mapName];
ctx.result = { mapName, steps: [], errors: [] };
ctx.world = {};
if (!ctx.positions) {
throw `@${ctx.i}: Unknown map '${mapName}' at beginning of plan.`;
}
}
parseStep(ctx) {
this.skipWhitespace(ctx);
const ii = ctx.i;
const posName = this.parsePosition(ctx) ?? ctx.lastPosition;
if (!posName) {
throw `@${ctx.i}: No position provided and no previous position to re-use.`;
}
const pos = ctx.positions[posName];
if (!pos) {
throw `@${ctx.i}: Unknown position '${posName}'.`;
}
this.skipWhitespace(ctx);
const previous = ctx.world[posName];
const on = previous?.base?.sn;
const action = this.parseAction(ctx);
if (!action) {
throw `@${ctx.i}: Incomplete step at end of plan.`;
}
let step = {
positionName: posName,
position: pos,
action
};
if (action.base) {
if (action.base.length === 2) {
step.base = towers_min_default.base.find((t) => t.sn === action.base);
} else {
step.base = towers_min_default.base.find((t) => t.sn === `${action.base}${on ? +on[1] + 1 : 1}`);
}
if (!step.base) {
throw `@${ctx.i}: Invalid tower name/level '${action.base}' at ${step.positionName}.`;
}
if (on) {
if (step.base.sn[0] !== on[0]) {
throw `@${ctx.i}: Can't build ${step.base.ln} on ${previous.base.ln} at ${step.positionName}.`;
}
if (step.base.sn[1] <= on[1]) {
throw `@${ctx.i}: Tower downgrade ${step.base.ln} on ${previous.base.ln} at ${step.positionName}.`;
}
}
step.shortAction = step.base.sn;
step.text = `${posName} ${step.base.ln}`;
} else if (action.upgrade) {
if (!on) {
throw `@${ctx.i}: Upgrade '${action.upgrade}' on nothing at ${posName}.`;
}
step.upgrade = towers_min_default.upgrades.find((u) => u.on === on && u.sn === action.upgrade);
if (!step.upgrade) {
throw `@${ctx.i}: There is no '${action.upgrade}' upgrade for ${previous.base.ln} at ${posName}.`;
}
let lastUpgradeOfType = previous[step.upgrade.sn];
let newLevel = action.level ?? (lastUpgradeOfType?.level ?? 0) + 1;
if (newLevel <= (lastUpgradeOfType?.level ?? 0)) {
throw `@${ctx.i}: Ability downgrade from '${action.upgrade}${lastUpgradeOfType?.level}' to '${action.upgrade}${action.level}' at ${posName}.`;
}
if (newLevel > step.upgrade.cost.length) {
throw `@${ctx.i}: Ability upgrade to level ${newLevel} when ${step.upgrade.ln} max level is ${step.upgrade.cost.length} at ${posName}.`;
}
step[step.upgrade.sn] = { ...step.upgrade, level: newLevel };
step.shortAction = `${step.upgrade.sn}${newLevel}`;
step.text = `${posName} ${step.upgrade.ln}${newLevel}`;
}
this.apply(step, ctx.world);
ctx.result.steps.push(step);
ctx.lastPosition = posName;
}
parsePosition(ctx) {
if (ctx.i + 1 >= ctx.text.length) {
return null;
}
const letter = ctx.text[ctx.i].toUpperCase();
if (letter < "A" || letter > "H") {
return null;
}
const digit = ctx.text[ctx.i + 1];
if (digit < "0" || digit > "9") {
return null;
}
ctx.i += 2;
return `${letter}${digit}`;
}
parseAction(ctx) {
if (ctx.i >= ctx.text.length) {
return null;
}
const letter = ctx.text[ctx.i].toLowerCase();
const digit = ctx.i + 1 < ctx.text.length ? ctx.text[ctx.i + 1] : "";
if (letter >= "p" && letter <= "t") {
if (digit >= "1" && digit <= "5") {
ctx.i += 2;
return { base: `${letter}${digit}` };
} else {
ctx.i++;
return { base: letter };
}
} else if (letter >= "x" && letter <= "z") {
if (digit >= "1" && digit <= "3") {
ctx.i += 2;
return { upgrade: letter, level: digit };
} else {
ctx.i++;
return { upgrade: letter };
}
} else {
throw `@${ctx.i}: Unknown action ${letter}${digit}.`;
}
}
require(ctx, value, error) {
if (ctx.i >= ctx.text.length || ctx.text[ctx.i++].toUpperCase() !== value.toUpperCase()) {
throw error;
}
}
number(ctx) {
let numberString = "";
while (ctx.i < ctx.text.length) {
const c = ctx.text[ctx.i];
if (c < "0" || c > "9") {
break;
}
numberString += c;
ctx.i++;
}
return numberString;
}
skipWhitespace(ctx) {
while (ctx.i < ctx.text.length) {
const c = ctx.text[ctx.i];
if (c !== " " && c !== " " && c !== "\r" && c !== "\n" && c !== "." && c !== ";") {
break;
}
ctx.i++;
}
}
toShortText(plan, spacer) {
let result = `${plan.mapName}:`;
spacer = spacer || "";
let last = {};
for (let i = 0; i < plan.steps.length; ++i) {
let step = plan.steps[i];
if (i !== 0) {
result += spacer;
}
if (step.positionName !== last.positionName) {
result += step.positionName;
}
if (step.shortAction.endsWith("1")) {
result += step.shortAction.slice(0, -1);
} else {
result += step.shortAction;
}
last = step;
}
return result;
}
apply(step, world) {
if (!world.steps) {
world.steps = [];
}
world.steps.push(step);
world[step.positionName] = { ...world[step.positionName], ...step };
}
};
// ../data/settings.mjs
var settings_default = {
maps: {
count: 26,
width: 1920,
height: 1080,
originalsFolder: "../../source-data/maps",
crop: { x: 128, y: 60, w: 1664, h: 936 },
tileOrder: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 17, 14, 18, 19, 13, 15, 22, 20, 21, 23, 24, 25, 26]
},
labels: {
small: { textColor: "#49463a", backColor: "#efeddc", borderColor: "#49463a", fontWeight: "bold", fontSizePx: 24, relY: -16, pad: 3 },
medium: { textColor: "#49463a", backColor: "#efeddc", borderColor: "#49463a", fontWeight: "bold", fontSizePx: 36, relY: -12, pad: 3 },
large: { textColor: "#49463a", backColor: "#efeddc", borderColor: "#49463a", fontWeight: "bold", fontSizePx: 56, relY: 12, pad: 4 },
message: { x: 148, y: 46, textColor: "#DDD", backColor: "#231C17", fontSizePx: 18, minWidth: 170, minHeight: 26 },
plan: { x: 12, y: 1050, left: true, textColor: "#eee", borderColor: "#eee", backColor: "#222", highlightColor: "#fe0", fontFace: "monospace", fontSizePx: 20, padX: 6, padY: 4, minWidth: 120 },
error: { x: 960, y: 720, textColor: "#f00", borderColor: "#e00", backColor: "#222", fontSizePx: 60, pad: 30 }
},
geo: {
tower: { w: 160, h: 140, relX: -80, relY: -104, cols: 5 },
upgrade: { w: 28, h: 26, pad: 1, cols: 3, backColor: "#24211d", borderColor: "#efeddc" },
upgradeLarge: { w: 56, h: 52 },
profile: { w: 80, h: 80, relX: -40, relY: -64 },
towerDiagnostics: { w: 90, h: 90, relX: -45, relY: -69 }
},
circles: {
glow: { radius: 120, relY: -20, color: "rgba(255, 215, 0, 0.8)", mid: { at: 0.3, color: "rgba(255, 215, 0, 0.6)" } },
pip: { radius: 5, color: "rgba(26, 181, 255, 1)", mid: { at: 0.5, color: "rgba(26, 181, 255, 0.6)" } }
},
colors: {
beige: { r: 221, g: 216, b: 179, length: 20, relX: 9, relY: 20 },
black: { r: 25, g: 18, b: 14, length: 17, relX: -19, relY: -55 }
},
upgradeSourcePos: { x: 606, y: 554, w: 275, h: 275, map: "L14", pos: "B4" }
};
// ../common/animator.mjs
var Animator = class {
constructor(loadImage2, targetCanvas, onDraw) {
this.loadImage = loadImage2;
this.targetDrawing = new Drawing(targetCanvas);
this.onDraw = onDraw;
this.showControls = false;
this.paused = false;
this.drawUntil = 0;
}
async init(imageFormat) {
if (!this.planParser) {
imageFormat ??= "png";
this.imageFormat = imageFormat;
try {
const [towerSprites, upgradeSprites] = await Promise.all([
this.loadImage(`../img/${imageFormat}/sprites/towers.${imageFormat}`),
this.loadImage(`../img/${imageFormat}/sprites/upgrades.${imageFormat}`)
]);
this.towerSprites = towerSprites;
this.upgradeSprites = upgradeSprites;
} catch (error) {
this.error = error;
}
this.planParser = new PlanParser();
}
}
async parsePlan(planText, imageFormat) {
try {
await this.init(imageFormat);
this.planText = planText;
this.plan = this.planParser.parse(planText);
this.positions = positions_min_default[this.plan.mapName];
if (!this.positions) {
this.error = `Map '${this.plan?.mapName}' is invalid.`;
} else {
this.map = await this.loadImage(`../img/${this.imageFormat}/maps/${this.plan.mapName}.${this.imageFormat}`);
}
} catch (error) {
this.error = "Plan Errors:\n" + error;
}
this.drawWorld();
return this.plan;
}
drawControlHints() {
const can = this.targetDrawing.canvas;
this.drawControlPane({ x: 0, y: 0, w: can.width * 1 / 4, h: can.height * 2 / 3 }, "prev");
this.drawControlPane({ x: 0, y: can.height * 2 / 3, w: can.width * 1 / 4, h: can.height * 1 / 3 }, "start");
this.drawControlPane({ x: can.width * 1 / 4, y: 0, w: can.width * 1 / 2, h: can.height }, this.paused ? "play" : "pause");
this.drawControlPane({ x: can.width * 3 / 4, y: 0, w: can.width * 1 / 4, h: can.height * 2 / 3 }, "next");
this.drawControlPane({ x: can.width * 3 / 4, y: can.height * 2 / 3, w: can.width * 1 / 4, h: can.height * 1 / 3 }, "end");
}
drawControlPane(box, command) {
const can = this.targetDrawing.canvas;
const ctx = this.targetDrawing.ctx;
const h = can.height / 10;
const w = command === "play" ? h * 2 / 3 : h / 2;
let r = { x: box.x + box.w / 2 - w / 2, y: box.y + box.h / 2 - h / 2, w, h };
let bo = { backColor: "rgba(20, 20, 20, 0.3)", borderColor: "rgba(0, 0, 0, 1)" };
let to = { borderColor: "#111", backColor: "#86C6F4", dir: command === "start" || command === "prev" ? "left" : "right" };
let shift = to.dir === "left" ? -(r.w + 4) : r.w + 4;
this.targetDrawing.drawBox(box, bo);
if (command === "pause") {
r.w = h / 4;
this.targetDrawing.drawBox(r, to);
r.x += h / 2;
this.targetDrawing.drawBox(r, to);
return;
}
this.targetDrawing.drawTriangle(r, to);
if (command !== "play") {
r.x += shift;
this.targetDrawing.drawTriangle(r, to);
}
if (command === "end") {
r.x += shift;
r.w = h / 12;
this.targetDrawing.drawBox(r, to);
} else if (command === "start") {
r.w = h / 12;
r.x -= r.w + 4;
this.targetDrawing.drawBox(r, to);
}
}
drawPlan() {
const end = Math.min(this.plan.steps.length, Math.max(this.drawUntil + 5, 20));
const start = Math.max(0, end - 20);
let text = "";
if (start > 0) {
text += "...";
}
for (let i = start; i < end; ++i) {
text += `${i > 0 ? "\n" : ""}${i === this.drawUntil - 1 ? " " : ""}${this.plan.steps[i].text}`;
}
if (end < this.plan.steps.length) {
text += "\n...";
}
this.targetDrawing.drawText(settings_default.labels.plan, text, { ...settings_default.labels.plan, highlightIndex: this.drawUntil - (start > 0 ? start : 1) });
}
drawWorld() {
if (this.error || this.plan?.errors?.length > 0) {
this.targetDrawing.drawText(settings_default.labels.error, this.error ?? this.plan.errors.join("\n"), settings_default.labels.error);
if (this.onDraw) {
this.onDraw();
}
return;
}
if (!this.plan) {
return;
}
let world = { steps: [] };
for (let i = 0; i < this.drawUntil; ++i) {
this.planParser.apply(this.plan.steps[i], world);
}
this.targetDrawing.drawImage(this.map);
this.drawPlan();
const current = world.steps?.[world.steps?.length - 1];
if (current) {
this.targetDrawing.drawGradientCircle(current.position, settings_default.circles.glow);
}
for (let posName in this.positions) {
const pos = this.positions[posName];
const state = world[posName];
if (state) {
this.targetDrawing.drawSprite(pos, this.towerSprites, settings_default.geo.tower, state.base.index);
}
}
for (let posName in this.positions) {
const pos = this.positions[posName];
const state = world[posName];
if (state) {
this.drawUpgrades(state);
}
this.targetDrawing.drawText(pos, posName, settings_default.labels.small);
}
if (this.showControls) {
this.drawControlHints();
}
if (this.onDraw) {
this.onDraw();
}
}
drawUpgrades(state) {
const count = (state?.x ? 1 : 0) + (state?.y ? 1 : 0) + (state?.z ? 1 : 0);
if (count === 0) {
return;
}
const geo = settings_default.geo.upgrade;
const pip = settings_default.circles.pip;
let upgradeBox = {
w: geo.w + geo.pad * 2,
h: pip.radius * 2 + geo.h + geo.pad * 2
};
const sharedBox = {
x: this.centerToLeft(state.position.x, upgradeBox.w, 0, count),
y: state.position.y - 8,
w: count * upgradeBox.w,
h: upgradeBox.h
};
this.targetDrawing.drawBox(sharedBox, geo);
upgradeBox.x = sharedBox.x;
upgradeBox.y = sharedBox.y + geo.pad;
let index = 0;
if (state.x) {
this.drawUpgrade(state.x, upgradeBox);
upgradeBox.x += upgradeBox.w;
}
if (state.y) {
this.drawUpgrade(state.y, upgradeBox);
upgradeBox.x += upgradeBox.w;
}
if (state.z) {
this.drawUpgrade(state.z, upgradeBox);
upgradeBox.x += upgradeBox.w;
}
}
drawUpgrade(upgrade, box) {
const geo = settings_default.geo.upgrade;
const pip = settings_default.circles.pip;
this.targetDrawing.drawSprite({ x: box.x + geo.pad, y: box.y + pip.radius * 2 }, this.upgradeSprites, geo, upgrade.index);
let pipPos = { x: this.centerToLeft(box.x + box.w / 2, pip.radius * 2, 0, upgrade.level) + pip.radius, y: box.y + pip.radius };
for (var i = 0; i < upgrade.level; ++i) {
this.targetDrawing.drawGradientCircle(pipPos, settings_default.circles.pip);
pipPos.x += pip.radius * 2;
}
}
centerToLeft(center, width, index, count) {
const totalWidth = width * count;
const left = center - totalWidth / 2;
return left + index * width;
}
start() {
this.drawUntil = 0;
this.drawWorld();
}
prev() {
this.drawUntil = Math.max(this.drawUntil - 1, 0);
this.drawWorld();
}
next() {
this.drawUntil = Math.min(this.drawUntil + 1, this.plan?.steps?.length ?? 0);
this.drawWorld();
}
end() {
this.drawUntil = this.plan?.steps?.length ?? 0;
this.drawWorld();
}
isDone() {
return this.drawUntil >= (this.plan?.steps?.length ?? 0);
}
};
// index.js
async function loadImage(url) {
const img = new Image();
const loadPromise = new Promise((resolve, reject) => {
img.onload = () => {
resolve();
};
img.onerror = () => {
reject(`Image '${url}' was invalid or not found.`);
};
});
img.src = url;
await loadPromise;
return img;
}
var justEntered = false;
var animator = null;
async function run(planText) {
if (animator === null) {
const canvas = document.createElement("canvas");
canvas.width = 1920;
canvas.height = 1080;
const outCanvas = document.getElementById("main");
const drawOut = new Drawing(outCanvas);
animator = new Animator(loadImage, canvas, () => {
drawOut.drawImage(canvas);
});
outCanvas.addEventListener("mousemove", () => mouse(true));
outCanvas.addEventListener("mouseleave", () => mouse(false));
outCanvas.addEventListener("click", canvasClicked);
document.getElementById("demo").addEventListener("click", async () => run("L5:G7t3E9p2E7r4xG6pE7y3G6p2E7x2"));
document.addEventListener("keydown", keyDown);
document.addEventListener("dragover", (e) => {
e.preventDefault();
});
document.addEventListener("drop", onDrop);
}
if (planText !== null) {
document.getElementById("main").style.display = "";
document.getElementById("help-container").style.display = "none";
await animator.parsePlan(planText, document.imageFormat);
animator.paused = false;
animator.start();
animate();
const params = new URLSearchParams(window.location.search);
if (params.get("p") !== planText) {
params.set("p", animator.planParser.toShortText(animator.plan));
window.history.replaceState(null, null, `?${params.toString()}`);
}
}
}
function canvasClicked(e) {
e.stopPropagation();
const r = e.target.getBoundingClientRect();
const x = (e.clientX - r.left) / r.width;
const y = (e.clientY - r.top) / r.height;
if (!justEntered) {
if (x < 0.25) {
if (y < 0.67) {
animator.prev();
} else {
animator.start();
}
} else if (x > 0.75) {
if (y < 0.67) {
animator.next();
} else {
animator.end();
}
} else {
togglePause();
}
}
}
var hideControlsTimer = null;
function mouse(enter) {
if (animator.showControls !== enter) {
animator.showControls = enter;
animator.drawWorld();
justEntered = true;
setTimeout(() => justEntered = false, 50);
}
if (enter) {
if (hideControlsTimer !== null) {
clearTimeout(hideControlsTimer);
}
hideControlsTimer = setTimeout(() => mouse(false), 2500);
}
}
function togglePause() {
animator.paused = !animator.paused;
if (animator.isDone()) {
animator.start();
}
animate();
}
function animate() {
if (animator.paused) {
animator.drawWorld();
return;
}
animator.next();
if (animator.isDone()) {
animator.paused = true;
animator.drawWorld();
} else {
setTimeout(animate, 500);
}
}
function keyDown(e) {
if (e.keyCode === 36 || e.keyCode === 38) {
animator.start();
} else if (e.keyCode === 37) {
animator.prev();
} else if (e.keyCode === 32) {
togglePause();
} else if (e.keyCode === 39) {
animator.next();
} else if (e.keyCode === 35 || e.keyCode === 40) {
animator.end();
}
}
async function onDrop(e) {
e.preventDefault();
if (e.dataTransfer.items && e.dataTransfer.items.length >= 1) {
let item = e.dataTransfer.items[0];
if (item.kind === "file") {
const file = item.getAsFile();
const planText = await file.text();
await run(planText);
}
}
}
export {
run
};
| 45.570082 | 451 | 0.526196 |
93714305c9266729237a51a5580b0c30091e34b8 | 8,728 | js | JavaScript | XUXUCAM/Resource/Drawing/Draw/Image/Image.js | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 13 | 2018-11-06T12:37:42.000Z | 2021-07-22T11:49:35.000Z | XUXUCAM/Resource/Drawing/Draw/Image/Image.js | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 1 | 2020-05-15T07:21:06.000Z | 2020-05-28T05:10:35.000Z | XUXUCAM/Resource/Drawing/Draw/Image/Image.js | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 11 | 2018-11-06T12:37:52.000Z | 2021-09-25T08:02:27.000Z | /**
* Copyright (c) 2011-2017 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QCAD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QCAD.
*/
/**
* \defgroup ecma_draw_image Image Drawing Tool
* \ingroup ecma_draw
*
* \brief This module contains the ECMAScript implementation of the image
* drawing tool.
*/
include("../Draw.js");
/**
* \class Image
* \brief Inserts an image (bitmap) into the drawing.
* \ingroup ecma_draw_image
*/
function Image(guiAction) {
Draw.call(this, guiAction);
this.fileName = undefined;
this.image = undefined;
this.width = undefined;
this.height = undefined;
this.angle = undefined;
this.setUiOptions("scripts/Draw/Image/Image.ui");
}
Image.State = {
SettingPosition : 0
};
Image.prototype = new Draw();
Image.includeBasePath = includeBasePath;
Image.prototype.beginEvent = function() {
Draw.prototype.beginEvent.call(this);
if (isNull(this.fileName)) {
this.fileName = this.getFileName();
}
if (isNull(this.fileName)) {
this.terminate();
return;
}
this.image = new RImageEntity(
this.getDocument(),
new RImageData(this.fileName,
new RVector(0,0),
new RVector(1,0),
new RVector(0,1),
50, 50, 0)
);
// initial size is image size in pixels (i.e. one pixel -> one unit):
this.width = this.image.getPixelWidth();
this.height = this.image.getPixelHeight();
var optionsToolBar = EAction.getOptionsToolBar();
var widthEdit = optionsToolBar.findChild("Width");
var heightEdit = optionsToolBar.findChild("Height");
widthEdit.setValue(this.width);
heightEdit.setValue(this.height);
this.setState(Image.State.SettingPosition);
};
Image.prototype.finishEvent = function() {
Draw.prototype.finishEvent.call(this);
if (!isNull(this.image)) {
this.image.destroy();
}
};
Image.prototype.getFileName = function() {
var lastOpenFileDir = RSettings.getStringValue(
"Image/Path",
RSettings.getDocumentsLocation());
var formats = QImageReader.supportedImageFormats();
var filters = [];
var filterAllImages = "";
for (var i=0; i<formats.length; ++i) {
var format = formats[i];
var formatAlt = "";
// ignore format aliases:
if (format=="jpg" ||
format=="tif") {
continue;
}
// ignore unsupported formats:
if (format=="ico" || format=="mng" ||
format=="pbm" || format=="pgm" || format=="ppm" ||
format=="svg" || format=="svgz" ||
format=="xbm" || format=="xpm") {
continue;
}
if (format=="jpeg") {
formatAlt = "jpg";
}
else if (format=="tiff") {
formatAlt = "tif";
}
// if (filters.length!==0) {
// filters += ";;";
// }
var filter = format.toUpper() + " " + qsTr("Files") + " (";
filter += "*." + format;
if (filterAllImages.length!==0) {
filterAllImages += " ";
}
filterAllImages += "*." + format;
if (formatAlt.length!==0) {
filter += " *." + formatAlt;
filterAllImages += " *." + formatAlt;
}
filter += ")";
filters.push(filter);
}
// default filter (first) is for all image files:
var allFilter = qsTr("All Image Files (%1)").arg(filterAllImages);
filters.push(allFilter);
filters.push(qsTr("All Files") + " (*)");
// Shorter, but crashes under XUbuntu:
//var fileName = QFileDialog.getOpenFileName(this, qsTr("Import Bitmap"),
// initialPath, filters);
var appWin = EAction.getMainWindow();
var fileDialog = new QFileDialog(appWin, qsTr("Import Bitmap"), lastOpenFileDir, "");
fileDialog.setNameFilters(filters);
fileDialog.selectNameFilter(allFilter);
fileDialog.setOption(QFileDialog.DontUseNativeDialog, getDontUseNativeDialog());
if (!isNull(QFileDialog.DontUseCustomDirectoryIcons)) {
fileDialog.setOption(QFileDialog.DontUseCustomDirectoryIcons, true);
}
fileDialog.fileMode = QFileDialog.ExistingFiles;
fileDialog.setLabelText(QFileDialog.FileType, qsTr("Format:"));
if (!fileDialog.exec()) {
fileDialog.destroy();
return undefined;
}
var files = fileDialog.selectedFiles();
if (files.length===0) {
fileDialog.destroy();
return undefined;
}
RSettings.setValue("Image/Path", fileDialog.directory().absolutePath());
return files[0];
};
Image.prototype.setState = function(state) {
Draw.prototype.setState.call(this, state);
this.setCrosshairCursor();
this.getDocumentInterface().setClickMode(RAction.PickCoordinate);
var appWin = RMainWindowQt.getMainWindow();
this.setLeftMouseTip(qsTr("Position"));
this.setRightMouseTip(EAction.trCancel);
EAction.showSnapTools();
};
Image.prototype.pickCoordinate = function(event, preview) {
if (isNull(this.width) || isNull(this.height) || isNull(this.angle)) {
return;
}
var pos = event.getModelPosition();
this.getDocumentInterface().setRelativeZero(pos);
this.image.setInsertionPoint(pos);
this.image.setWidth(this.width);
this.image.setHeight(this.height);
this.image.setAngle(this.angle);
var op = new RAddObjectOperation(this.image.clone(), this.getToolTitle());
if (preview) {
this.getDocumentInterface().previewOperation(op);
}
else {
this.getDocumentInterface().applyOperation(op);
}
};
Image.prototype.slotKeepProportionsChanged = function(value) {
var optionsToolBar = EAction.getOptionsToolBar();
var widthEdit = optionsToolBar.findChild("Width");
var heightEdit = optionsToolBar.findChild("Height");
//var heightLabel = optionsToolBar.findChild("HeightLabel");
var keepProportionsSwitch = optionsToolBar.findChild("KeepProportions");
if (value===true) {
//heightEdit.enabled = false;
//heightLabel.enabled = false;
keepProportionsSwitch.icon = new QIcon(Image.includeBasePath + "/KeepProportionsOn.svg");
// adjust height to width:
var w = this.image.getPixelWidth();
var f = widthEdit.getValue() / w;
var h = this.image.getPixelHeight();
heightEdit.setValue(h * f);
}
else {
//heightEdit.enabled = true;
//heightLabel.enabled = true;
keepProportionsSwitch.icon = new QIcon(Image.includeBasePath + "/KeepProportionsOff.svg");
}
}
Image.prototype.slotWidthChanged = function(value) {
if (isNaN(value)) {
return;
}
var optionsToolBar = EAction.getOptionsToolBar();
var heightEdit = optionsToolBar.findChild("Height");
var keepProportionsSwitch = optionsToolBar.findChild("KeepProportions");
var keepProportions = keepProportionsSwitch.checked;
this.width = value;
if (!isNull(this.image)) {
this.image.setWidth(value, keepProportions);
this.height = this.image.getHeight();
//qDebug("kp: ", keepProportions);
//qDebug("height: ", this.height);
heightEdit.blockSignals(true);
heightEdit.setValue(this.height);
heightEdit.blockSignals(false);
}
};
Image.prototype.slotHeightChanged = function(value) {
if (isNaN(value)) {
return;
}
var optionsToolBar = EAction.getOptionsToolBar();
var widthEdit = optionsToolBar.findChild("Width");
var keepProportionsSwitch = optionsToolBar.findChild("KeepProportions");
var keepProportions = keepProportionsSwitch.checked;
this.height = value;
if (!isNull(this.image)) {
this.image.setHeight(value, keepProportions);
this.width = this.image.getWidth();
widthEdit.blockSignals(true);
widthEdit.setValue(this.width);
widthEdit.blockSignals(false);
}
};
Image.prototype.slotAngleChanged = function(value) {
this.angle = value;
if (!isNull(this.image)) {
this.image.setAngle(value);
}
};
| 29.586441 | 98 | 0.631989 |
9373029f504c5a9355a8a3cdff403b23d9b4370e | 646 | js | JavaScript | app/controllers/RatingsController.js | pumamaheswaran/proteus-ui | 6996b96b8d83cc22f19aeb0afacd1bf6c01776f0 | [
"MIT"
] | null | null | null | app/controllers/RatingsController.js | pumamaheswaran/proteus-ui | 6996b96b8d83cc22f19aeb0afacd1bf6c01776f0 | [
"MIT"
] | null | null | null | app/controllers/RatingsController.js | pumamaheswaran/proteus-ui | 6996b96b8d83cc22f19aeb0afacd1bf6c01776f0 | [
"MIT"
] | null | null | null | /**
* Created by Pravin on 3/17/2016.
*/
(function() {
'use strict';
angular
.module('io.egen.proteus')
.controller('RatingsController',RatingsController);
function RatingsController($routeParams,ratingService) {
var ratingsVm = this;
ratingsVm.submitRating = submitRating;
function submitRating() {
ratingService.registerUserRating($routeParams.id, ratingsVm.rating)
.then(function(data){
console.log(data);
},
function(error){
console.log(error);
});
}
}
})(); | 26.916667 | 79 | 0.535604 |
9374b50491979b6fbc0e4727487c033b804b6eed | 2,040 | js | JavaScript | example/http-app/server.js | DigitalBrainJS/antifreeze2 | 11899939f2af432ffa50b531b661645be7d9bf9e | [
"Unlicense"
] | null | null | null | example/http-app/server.js | DigitalBrainJS/antifreeze2 | 11899939f2af432ffa50b531b661645be7d9bf9e | [
"Unlicense"
] | null | null | null | example/http-app/server.js | DigitalBrainJS/antifreeze2 | 11899939f2af432ffa50b531b661645be7d9bf9e | [
"Unlicense"
] | null | null | null | import CPKoa from "cp-koa";
import Router from "@koa/router";
import { CPromise, CanceledError, E_REASON_CANCELED } from "c-promise2";
import assert from "assert";
import {antifreeze, isNeeded} from "../../lib/antifreeze2.js";
const fibAsync = CPromise.promisify(function* (n) {
this.innerWeight(0);
let a = 1n, b = 1n, sum, i = n - 2;
while (i-- > 0) {
sum = a + b;
a = b;
b = sum;
if (isNeeded()) {
yield antifreeze();
this.progress(1 - (i /(n-2)));
}
}
return b;
});
const app = new CPKoa();
const router = new Router();
app.use(function* (ctx, next) {
const ts = Date.now();
try {
yield next();
const passed = Date.now() - ts;
console.warn(`Request [${ctx.req.url}] completed in [${passed}ms]`);
ctx.set('X-Response-Time',`${passed}ms`);
} catch (err) {
if(CPromise.isCanceledError(err)){
console.warn(`Request [${ctx.req.url}] canceled in [${Date.now() - ts}ms]`);
}
throw err;
}
});
router.get('/', async(ctx)=>{
ctx.body = `
<html><body>
<a href="/time">Current time</a><br/>
<a href="/fibonacci/10000">fibonacci 10k</a><br/>
<a href="/fibonacci/100000">fibonacci 100k</a><br/>
<a href="/fibonacci/1000000">fibonacci 1M</a><br/>
<a href="/fibonacci/2000000">fibonacci 2M</a><br/>
</body></html>`
})
router.get("/time", async function (ctx, next) {
const now = new Date();
ctx.body= `Time is: ${now.toLocaleString()} (${+now})`
});
router.get("/fibonacci/:n", async function (ctx, next) {
await ctx.run(function* () {
let {n = 1000} = ctx.request.params;
console.log('start calculation...');
n *= 1;
assert.ok(n >= 1 && n <= 10000000, `n must be in range [1..10M]`);
const promise = fibAsync(n);
ctx.body = `Fibonacci result for n= ${n}: ${yield promise}`;
})
});
app
.use(router.routes())
.use(router.allowedMethods())
.on("progress", (ctx, score) => {
console.log(`Request [${ctx.req.url}] progress [${ctx.ip}]: ${(score * 100).toFixed(1)}%`);
})
.listen(3000);
| 26.493506 | 95 | 0.581863 |
9376018b9b53f8fea679c049b90e7ea47bed9463 | 23,983 | js | JavaScript | nbextensions/editorCell_bill/widgets/jobLogViewer.js | msneddon/narrative | 499d7e7773c40144a4c130f9de4668501d940f90 | [
"MIT"
] | null | null | null | nbextensions/editorCell_bill/widgets/jobLogViewer.js | msneddon/narrative | 499d7e7773c40144a4c130f9de4668501d940f90 | [
"MIT"
] | null | null | null | nbextensions/editorCell_bill/widgets/jobLogViewer.js | msneddon/narrative | 499d7e7773c40144a4c130f9de4668501d940f90 | [
"MIT"
] | null | null | null | /*global define*/
/*jslint white:true,browser:true*/
define([
'bluebird',
'common/runtime',
'common/props',
'common/dom',
'common/events',
'common/fsm',
'kb_common/html',
'css!kbase/css/kbaseJobLog.css'
], function (
Promise,
Runtime,
Props,
Dom,
Events,
Fsm,
html
) {
'use strict';
var t = html.tag,
div = t('div'), button = t('button'), span = t('span'), pre = t('pre'),
fsm,
appStates = [
{
state: {
mode: 'new'
},
meta: {
description: 'Widget just created, do not yet know the state of the job'
},
ui: {
buttons: {
enabled: [],
disabled: ['play', 'stop', 'top', 'back', 'forward', 'bottom']
}
},
next: [
{
mode: 'active',
auto: true
},
{
mode: 'complete'
},
{
mode: 'error'
}
]
},
{
state: {
mode: 'active',
auto: true
},
meta: {
description: 'The Job is currently active, receiving log updates automatically'
},
ui: {
buttons: {
enabled: ['stop', 'top', 'back', 'forward', 'bottom'],
disabled: ['play']
}
},
next: [
{
mode: 'active',
auto: false
},
{
mode: 'active',
auto: true
},
{
mode: 'complete'
},
{
mode: 'error'
}
]
},
{
state: {
mode: 'active',
auto: false
},
meta: {
description: 'The job is currently active, no automatic updates'
},
ui: {
buttons: {
enabled: ['play', 'top', 'back', 'forward', 'bottom'],
disabled: ['stop']
}
},
next: [
{
mode: 'active',
auto: true
},
{
mode: 'complete'
},
{
mode: 'error'
}
]
},
{
state: {
mode: 'complete'
},
ui: {
buttons: {
enabled: ['top', 'back', 'forward', 'bottom'],
disabled: ['play', 'stop']
}
}
},
{
state: {
mode: 'error'
},
ui: {
buttons: {
enabled: ['top', 'back', 'forward', 'bottom'],
disabled: ['play', 'stop']
}
}
}
];
function factory(config) {
var config = config || {},
runtime = Runtime.make(),
bus = runtime.bus().makeChannelBus(null, 'Log Viewer Bus'),
container,
jobId,
model,
dom,
linesPerPage = config.linesPerPage || 10,
loopFrequency = 5000,
looping = false;
// VIEW ACTIONS
function scheduleNextRequest() {
if (!looping) {
return;
}
window.setTimeout(function () {
if (!looping) {
return;
}
requestLatestJobLog();
}, loopFrequency);
}
function stopAutoFetch() {
var state = fsm.getCurrentState().state;
if (state.mode === 'active' && state.auto) {
looping = false;
fsm.newState({mode: 'active', auto: false});
}
}
function startAutoFetch() {
var state = fsm.getCurrentState().state;
if (state.mode === 'new' || (state.mode === 'active' && !state.auto)) {
looping = true;
fsm.newState({mode: 'active', auto: true});
runtime.bus().emit('request-latest-job-log', {
jobId: jobId,
options: {
num_lines: linesPerPage
}
});
}
}
function doStartFetchingLogs() {
startAutoFetch();
}
function doStopFetchingLogs() {
stopAutoFetch();
}
function requestJobLog(firstLine) {
dom.showElement('spinner');
runtime.bus().emit('request-job-log', {
jobId: jobId,
options: {
first_line: firstLine,
num_lines: linesPerPage
}
});
}
function requestLatestJobLog() {
dom.showElement('spinner');
runtime.bus().emit('request-latest-job-log', {
jobId: jobId,
options: {
num_lines: linesPerPage
}
});
}
function doFetchFirstLogChunk() {
var currentLine = model.getItem('currentLine');
if (currentLine === 0) {
return;
}
stopAutoFetch();
requestJobLog(0);
}
function doFetchPreviousLogChunk() {
var currentLine = model.getItem('currentLine'),
newFirstLine = currentLine - linesPerPage;
stopAutoFetch();
if (currentLine === 0) {
return;
}
if (newFirstLine < 0) {
newFirstLine = 0;
}
requestJobLog(newFirstLine);
}
function doFetchNextLogChunk() {
var currentLine = model.getItem('currentLine'),
lastLine = model.getItem('lastLine'),
newFirstLine;
stopAutoFetch();
// Get the current set of log lines again, since we don't have
// a full page.
// TODO: don't do this if the job state is completed
if ((lastLine - currentLine) < linesPerPage) {
newFirstLine = currentLine;
} else {
// NB this is actually the next line after the end
newFirstLine = currentLine + linesPerPage;
}
requestJobLog(newFirstLine);
}
function doFetchLastLogChunk() {
var firstLine,
lastLine = model.getItem('lastLine');
stopAutoFetch();
if (!lastLine) {
requestLatestJobLog();
} else {
firstLine = lastLine - (lastLine % linesPerPage);
requestJobLog(firstLine);
}
}
// VIEW
function renderControls(events) {
return div({dataElement: 'header', style: {margin: '0 0 10px 0'}}, [
button({
class: 'btn btn-sm btn-default',
dataButton: 'play',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Start fetching logs',
id: events.addEvent({
type: 'click',
handler: doStartFetchingLogs
})
}, [
span({class: 'fa fa-play'})
]),
button({
class: 'btn btn-sm btn-default',
dataButton: 'stop',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Stop fetching logs',
id: events.addEvent({
type: 'click',
handler: doStopFetchingLogs
})
}, [
span({class: 'fa fa-stop'})
]),
button({
class: 'btn btn-sm btn-default',
dataButton: 'top',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Jump to the top',
id: events.addEvent({
type: 'click',
handler: doFetchFirstLogChunk
})
}, [
span({class: 'fa fa-fast-backward'})
]),
button({
class: 'btn btn-sm btn-default',
dataButton: 'back',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Fetch previous log chunk',
id: events.addEvent({
type: 'click',
handler: doFetchPreviousLogChunk
})
}, [
span({class: 'fa fa-backward'})
]),
button({
class: 'btn btn-sm btn-default',
dataButton: 'forward',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Fetch next log chunk',
id: events.addEvent({
type: 'click',
handler: doFetchNextLogChunk
})
}, [
span({class: 'fa fa-forward'})
]),
button({
class: 'btn btn-sm btn-default',
dataButton: 'bottom',
dataToggle: 'tooltip',
dataPlacement: 'top',
title: 'Jump to the end',
id: events.addEvent({
type: 'click',
handler: doFetchLastLogChunk
})
}, [
span({class: 'fa fa-fast-forward'})
]),
// div({dataElement: 'fsm-debug'}),
div({dataElement: 'spinner', class: 'pull-right'}, [
span({class: 'fa fa-spinner fa-pulse fa-ex fa-fw'})
])
]);
}
function renderLayout() {
var events = Events.make(),
content = div({dataElement: 'kb-log', style: {marginTop: '10px'}}, [
div({class: 'kblog-line'}, [
div({class: 'kblog-num-wrapper'}, [
div({class: 'kblog-line-num'}, [
])
]),
div({class: 'kblog-text'}, [
renderControls(events)
])
]),
div({dataElement: 'panel'}, [
pre(['Log viewer initialized, awaiting most recent log messages...'])
])
]);
return {
content: content,
events: events
};
}
function sanitize(text) {
return text;
}
function renderLine(line) {
var extraClass = line.isError ? ' kb-error' : '';
return div({class: 'kblog-line' + extraClass}, [
div({class: 'kblog-num-wrapper'}, [
div({class: 'kblog-line-num'}, [
String(line.lineNumber)
])
]),
div({class: 'kblog-text'}, [
div({style: {marginBottom: '6px'}}, sanitize(line.text))
])
]);
}
function renderLines(lines) {
return lines.map(function (line) {
return renderLine(line);
}).join('\n');
}
function render() {
var startingLine = model.getItem('currentLine'),
lines = model.getItem('lines'),
viewLines;
if (lines) {
if (lines.length === 0) {
dom.setContent('panel', 'Sorry, no log entries to show');
return;
}
viewLines = lines.map(function (line, index) {
return {
text: line.line,
isError: (line.is_error === 1 ? true : false),
lineNumber: startingLine + index + 1
};
});
dom.setContent('panel', renderLines(viewLines));
} else {
dom.setContent('panel', 'Sorry, no log yet...');
}
}
var externalEventListeners = [];
function startEventListeners() {
var ev;
ev = runtime.bus().listen({
channel: {
jobId: jobId
},
key: {
type: 'job-logs'
},
handle: function (message) {
dom.hideElement('spinner');
if (message.logs.lines.length === 0) {
// TODO: add an alert area and show a dismissable alert.
if (!looping) {
// alert('No log entries returned');
console.warn('No log entries returned', message);
}
} else {
model.setItem('lines', message.logs.lines);
model.setItem('currentLine', message.logs.first);
model.setItem('latest', true);
model.setItem('fetchedAt', new Date().toUTCString());
// Detect end of log.
var lastLine = model.getItem('lastLine'),
batchLastLine = message.logs.first + message.logs.lines.length;
if (!lastLine) {
lastLine = batchLastLine;
} else {
if (batchLastLine > lastLine) {
lastLine = batchLastLine;
}
}
model.setItem('lastLine', lastLine);
}
if (looping) {
scheduleNextRequest();
}
}
});
externalEventListeners.push(ev);
ev = runtime.bus().listen({
channel: {
jobId: jobId
},
key: {
type: 'job-status'
},
handle: function (message) {
// console.log('LOGS job-status', message)
// if the job is finished, we don't want to reflect
// this in the ui, and disable play/stop controls.
var jobStatus = message.jobState.job_state,
mode = fsm.getCurrentState().state.mode,
newState;
switch (mode) {
case 'new':
switch (jobStatus) {
case 'queued':
case 'in-progress':
doStartFetchingLogs();
newState = {
mode: 'active',
auto: true
};
break;
case 'completed':
requestLatestJobLog();
newState = {
mode: 'complete'
};
break;
case 'error':
case 'suspend':
requestLatestJobLog();
newState = {
mode: 'error'
};
break;
default:
console.error('Unknown job status', jobStatus, message);
throw new Error('Unknown job status ' + jobStatus);
}
break;
case 'active':
switch (jobStatus) {
case 'queued':
case 'in-progress':
break;
case 'completed':
newState = {
mode: 'complete'
};
break;
case 'error':
case 'suspend':
newState = {
mode: 'error'
};
break;
default:
console.error('Unknown jog status', jobStatus, message);
throw new Error('Unknown jog status ' + jobStatus);
}
break;
case 'complete':
switch (jobStatus) {
case 'completed':
return;
default:
// technically, an error, what to do?
return;
}
case 'error':
switch (jobStatus) {
case 'error':
case 'suspend':
// nothing to do;
return;
default:
// technically, an error, what to do?
return;
}
default:
throw new Error('Mode ' + mode + ' not yet implemented');
}
if (newState) {
fsm.newState(newState);
}
}
});
externalEventListeners.push(ev);
ev = runtime.bus().listen({
channel: {
jobId: jobId
},
key: {
type: 'job-log-deleted'
},
handle: function (message) {
stopAutoFetch();
console.warn('No job log :( -- it has been deleted');
}
});
externalEventListeners.push(ev);
}
function stopEventListeners() {
externalEventListeners.forEach(function (ev) {
runtime.bus().removeListener(ev);
});
}
// LIFECYCLE API
function renderFSM() {
//showFsmBar();
var state = fsm.getCurrentState();
// Button state
if (state.ui.buttons) {
state.ui.buttons.enabled.forEach(function (button) {
dom.enableButton(button);
});
state.ui.buttons.disabled.forEach(function (button) {
dom.disableButton(button);
});
}
// Element state
if (state.ui.elements) {
state.ui.elements.show.forEach(function (element) {
dom.showElement(element);
});
state.ui.elements.hide.forEach(function (element) {
dom.hideElement(element);
});
}
// Emit messages for this state.
if (state.ui.messages) {
state.ui.messages.forEach(function (message) {
bus.send(message.message, message.address);
// widgets[message.widget].bus.send(message.message, message.address);
});
}
// dom.setContent('fsm-debug', JSON.stringify(state.state) + ',' + jobId);
}
function initializeFSM() {
fsm = Fsm.make({
states: appStates,
initialState: {
mode: 'new'
},
onNewState: function (fsm) {
// save the state?
renderFSM(fsm);
}
});
fsm.start();
}
function start() {
return Promise.try(function () {
bus.on('run', function (message) {
var root = message.node;
container = root.appendChild(document.createElement('div'));
dom = Dom.make({node: container});
jobId = message.jobId;
var layout = renderLayout();
container.innerHTML = layout.content;
layout.events.attachEvents(container);
initializeFSM();
renderFSM();
// dom.disableButton('stop');
// We need to initially listen purely for the presence of a
// job id. We cannot assume we have it when we start, and
// we also must be prepared for it to be deleted.
// OR should the lifetime of this widget just be assumed to
// intersect with the lifetime of the job?
startEventListeners();
runtime.bus().emit('request-job-status', {
jobId: jobId
});
// always start with the latest log entries, if any.
// requestLatestLog();
});
});
}
function stop() {
stopEventListeners();
bus.stop();
}
// MAIN
model = Props.make({
data: {
cache: [],
lines: [],
currentLine: null,
lastLine: null,
linesPerPage: 10,
fetchedAt: null
},
onUpdate: function () {
render();
}
});
// API
return Object.freeze({
start: start,
stop: stop,
bus: bus
});
}
return {
make: function (config) {
return factory(config);
}
};
}); | 33.263523 | 99 | 0.350748 |
9376b36241f9f6c2ffa0319a5a57a5e207fc1d4b | 433 | js | JavaScript | templates/jquery/js/pie-chart/pie-chart/files/data.js | mahesh7502/ignite-grid | fee06e2845e0b946274b696af01cf5d81b45ef0c | [
"MIT"
] | 94 | 2017-10-06T13:18:17.000Z | 2017-11-28T15:19:45.000Z | templates/jquery/js/pie-chart/pie-chart/files/data.js | mahesh7502/ignite-grid | fee06e2845e0b946274b696af01cf5d81b45ef0c | [
"MIT"
] | 887 | 2017-11-29T14:27:52.000Z | 2022-03-28T09:32:27.000Z | templates/jquery/js/pie-chart/pie-chart/files/data.js | mahesh7502/ignite-grid | fee06e2845e0b946274b696af01cf5d81b45ef0c | [
"MIT"
] | 2 | 2021-03-28T07:02:56.000Z | 2021-10-18T06:14:06.000Z | var data = [
{ "CountryName": "China", "Pop1990": 1141, "Pop2008": 1333, "Pop2025": 1458 },
{ "CountryName": "India", "Pop1990": 849, "Pop2008": 1140, "Pop2025": 1398 },
{ "CountryName": "United States", "Pop1990": 250, "Pop2008": 304, "Pop2025": 352 },
{ "CountryName": "Indonesia", "Pop1990": 178, "Pop2008": 228, "Pop2025": 273 },
{ "CountryName": "Brazil", "Pop1990": 150, "Pop2008": 192, "Pop2025": 223 }
];
| 54.125 | 87 | 0.586605 |
9376bbc2d1b6521e67bca5d5f799e51fbb49bb89 | 462 | js | JavaScript | test/app/routes.js | smile-soft/wchat | 34bda1653f54fbac6e5210b54b96442dd310fb31 | [
"MIT"
] | null | null | null | test/app/routes.js | smile-soft/wchat | 34bda1653f54fbac6e5210b54b96442dd310fb31 | [
"MIT"
] | 2 | 2020-02-28T08:55:02.000Z | 2020-02-28T08:55:02.000Z | test/app/routes.js | smile-soft/wchat | 34bda1653f54fbac6e5210b54b96442dd310fb31 | [
"MIT"
] | null | null | null | var path = require('path');
module.exports = function(app){
app.get('/', function (req, res, next){
res.append('Content-Type', 'text/html; charset=windows-1251');
res.sendFile(path.resolve('app/views/index.html'));
});
app.get('/products', function (req, res, next){
res.sendFile(path.resolve('app/views/products.html'));
});
app.get('/solutions', function (req, res, next){
res.sendFile(path.resolve('app/views/solutions.html'));
});
};
| 28.875 | 63 | 0.651515 |
9377e23af2297a63dc16b3fadde618f7016080b1 | 7,300 | js | JavaScript | addon/mixins/components/auto-save-form.js | onedata/onedata-gui-common | 9dbd5d50ede87cbb7a7671b175baec9a3e761af8 | [
"MIT"
] | null | null | null | addon/mixins/components/auto-save-form.js | onedata/onedata-gui-common | 9dbd5d50ede87cbb7a7671b175baec9a3e761af8 | [
"MIT"
] | 2 | 2020-04-07T15:31:48.000Z | 2022-02-15T02:27:22.000Z | addon/mixins/components/auto-save-form.js | onedata/onedata-gui-common | 9dbd5d50ede87cbb7a7671b175baec9a3e761af8 | [
"MIT"
] | null | null | null | /**
* Base for creating forms that submits data automatically with delay.
*
* @module mixins/components/auto-save-form
* @author Jakub Liput
* @copyright (C) 2018-2020 ACK CYFRONET AGH
* @license This software is released under the MIT license cited in 'LICENSE.txt'.
*/
import Mixin from '@ember/object/mixin';
import EmberObject, { computed, get } from '@ember/object';
import { run, debounce, later, cancel } from '@ember/runloop';
import notImplementedReject from 'onedata-gui-common/utils/not-implemented-reject';
const formSendDebounceTime = 4000;
export default Mixin.create({
_window: window,
/**
* Action called on data send. The only arguments is an object with
* modified data.
* @virtual
* @type {Function}
* @returns {Promise<undefined|any>} resolved value will be ignored
*/
onSave: notImplementedReject,
/**
* Form send debounce time.
* @type {number}
*/
formSendDebounceTime: formSendDebounceTime,
/**
* @type {string}
* One of: '', 'modified', 'saving', 'saved'.
* Used for displaying information about auto save progress.
*/
formStatus: '',
/**
* If true, form has some unsaved changes.
* @type {boolean}
*/
isDirty: false,
/**
* If true, some input have lost its focus since last save.
* @type {boolean}
*/
lostInputFocus: false,
/**
* Save debounce timer handle
* @type {Array}
*/
saveDebounceTimer: null,
generateInitialData() {
return EmberObject.create(this.get('configuration'));
},
/**
* Fields errors.
* @type {computed.Object}
*/
formFieldsErrors: computed(
'validations.errors.[]',
'sourceFieldNames',
function formFieldsErrors() {
const sourceFieldNames = this.get('sourceFieldNames');
const errors = this.get('validations.errors');
const fieldsErrors = {};
sourceFieldNames
.forEach((fieldName) => {
fieldsErrors[fieldName] =
errors.find(i => i.attribute === ('formData.' + fieldName));
});
return fieldsErrors;
}
),
/**
* Form data (has different format than the `data` property).
* @type {Ember.Object}
*/
formData: computed('data', {
get() {
return this.generateInitialData();
},
set(key, value) {
return value;
},
}),
/**
* Modification state of fields.
* @type {Ember.Object}
*/
formFieldsModified: computed(function formFieldsModified() {
return EmberObject.create();
}),
/**
* Page unload handler.
* @type {ComputedProperty<Function>}
*/
unloadHandler: computed(function unloadHandler() {
return () => {
this.scheduleSendChanges(false);
this.sendChanges();
};
}),
init() {
this._super(...arguments);
let {
_window,
unloadHandler,
} = this.getProperties('_window', 'unloadHandler');
_window.addEventListener('beforeunload', unloadHandler);
},
willDestroyElement() {
try {
let {
_window,
unloadHandler,
} = this.getProperties('_window', 'unloadHandler');
_window.removeEventListener('beforeunload', unloadHandler);
unloadHandler();
} finally {
this._super(...arguments);
}
},
/**
* Checks if modified values are valid and can be saved
* @returns {boolean} true if values are valid, false otherwise
*/
isValid() {
let {
formFieldsErrors,
formFieldsModified: modified,
sourceFieldNames,
} = this.getProperties(
'formFieldsErrors',
'formFieldsModified',
'formData',
'sourceFieldNames',
);
let isValid = true;
sourceFieldNames.forEach(fieldName => {
const isModified = get(modified, fieldName);
if (isModified && formFieldsErrors[fieldName]) {
isValid = false;
}
});
return isValid;
},
modifiedData() {
const {
formData,
sourceFieldNames,
formFieldsModified,
} = this.getProperties(
'formFieldsModified',
'formData',
'sourceFieldNames',
);
const data = {};
sourceFieldNames.forEach(fieldName => {
if (get(formFieldsModified, fieldName)) {
data[fieldName] = Number(formData.get(fieldName));
}
});
return data;
},
/**
* Sends modified data.
*/
sendChanges() {
const {
isDirty,
onSave,
formSavedInfoHideTimeout,
} = this.getProperties(
'isDirty',
'onSave',
'formSavedInfoHideTimeout'
);
if (isDirty && this.isValid()) {
const data = this.modifiedData();
if (Object.keys(data).length === 0) {
return;
}
this.cleanModificationState();
this.set('formStatus', 'saving');
onSave(data).then(() => {
if (!this.isDestroyed && !this.isDestroying) {
this.set('formStatus', 'saved');
later(this, () => {
if (!this.isDestroyed && !this.isDestroying) {
// prevent resetting state other than saved
if (this.get('formStatus') === 'saved') {
this.set('formStatus', '');
}
}
}, formSavedInfoHideTimeout);
}
}).catch(() => {
this.set('formStatus', 'failed');
this.set('formData', this.generateInitialData());
this.cleanModificationState();
});
this.setProperties({
lostInputFocus: false,
isDirty: false,
});
}
},
/**
* Schedules changes send (with debounce).
* @param {boolean} schedule If false, scheduled save will be canceled.
*/
scheduleSendChanges(schedule = true) {
const formSendDebounceTime = this.get('formSendDebounceTime');
if (schedule === false) {
this.cancelDebounceTimer();
} else {
const data = this.modifiedData();
if (Object.keys(data).length > 0 && this.isValid()) {
this.set('formStatus', 'modified');
this.set(
'saveDebounceTimer',
debounce(this, 'sendChanges', formSendDebounceTime)
);
run.next(() => {
if (!this.isValid()) {
this.cancelDebounceTimer();
}
});
} else {
this.cancelDebounceTimer();
}
}
},
cancelDebounceTimer() {
if (this.get('formStatus') === 'modified') {
this.set('formStatus', '');
}
cancel(this.get('saveDebounceTimer'));
},
/**
* Marks all fields as not modified.
*/
cleanModificationState() {
let formFieldsModified = this.get('formFieldsModified');
Object.keys(formFieldsModified)
.forEach((key) => formFieldsModified.set(key, false));
},
actions: {
dataChanged(fieldName, eventOrValue) {
const value = eventOrValue.target ? eventOrValue.target.value : eventOrValue;
this.set('formData.' + fieldName, value);
this.set('isDirty', true);
this.set('formFieldsModified.' + fieldName, true);
},
lostFocus() {
this.set('lostInputFocus', true);
this.scheduleSendChanges();
},
forceSave() {
this.scheduleSendChanges(false);
this.sendChanges();
},
inputOnKeyUp(keyEvent) {
switch (keyEvent.keyCode) {
case 13:
// enter
return this.send('forceSave');
default:
break;
}
},
},
});
| 24.745763 | 83 | 0.590822 |
93782c20d05add917f41cdb16ae5a310a6e1ced2 | 495 | js | JavaScript | web/src/store/modules/student/sagas.js | NearMaick/alpha-template-omni | f03347c0fa752e4035cf5fcfe4a2ed895a3e8351 | [
"MIT"
] | null | null | null | web/src/store/modules/student/sagas.js | NearMaick/alpha-template-omni | f03347c0fa752e4035cf5fcfe4a2ed895a3e8351 | [
"MIT"
] | 11 | 2021-05-08T20:19:26.000Z | 2022-02-27T01:21:43.000Z | web/src/store/modules/student/sagas.js | NearMaick/alpha-template-omni | f03347c0fa752e4035cf5fcfe4a2ed895a3e8351 | [
"MIT"
] | null | null | null | import { all, call, takeLatest } from 'redux-saga/effects';
import api from '../../../services/api';
import history from '../../../services/history';
export function* registerStudent({ payload }) {
const { name, email, age, weight, height } = payload;
yield call(api.post, 'student', {
name,
email,
age,
weight,
height,
is_active: false,
});
// history.push('/');
}
export default all([
takeLatest('@student/REGISTER_STUDENT_REQUEST', registerStudent),
]);
| 21.521739 | 67 | 0.636364 |
937853ef4f9e56fa5378b0a3a918af5c4af081e9 | 828 | js | JavaScript | app/containers/Campaign/constants.js | AnkitPat/music-app | ccd4373849d51c27e31138078ef54f1c0d5f2e0a | [
"MIT"
] | null | null | null | app/containers/Campaign/constants.js | AnkitPat/music-app | ccd4373849d51c27e31138078ef54f1c0d5f2e0a | [
"MIT"
] | null | null | null | app/containers/Campaign/constants.js | AnkitPat/music-app | ccd4373849d51c27e31138078ef54f1c0d5f2e0a | [
"MIT"
] | null | null | null | /*
*
* Tastemaker constants
*
*/
export const LAUNCH_CAMPAIGN = 'app/campaign/LAUNCH_CAMPAIGN';
export const FETCH_CAMPAIGN = 'app/campaign/FETCH_CAMPAIGN';
export const PUT_CAMPAIGN = 'app/campaign/PUT_CAMPAIGN';
export const SELECT_CAMPAIGN = 'app/campaign/SELECT_CAMPAIGN';
export const VERIFY_CAMPAIGN = 'app/campaign/VERIFY_CAMPAIGN';
export const ADD_INFLUENCER_RATING = 'app/campaign/ADD_INFLUENCER_RATING';
export const ADD_INFLUENCER_REVIEW = 'app/campaign/ADD_INFLUENCER_REVIEW';
export const REVIEW_SUBMITTING = 'app/campaign/REVIEW_SUBMITTING';
export const RATING_SUBMITTING = 'app/campaign/RATING_SUBMITTING';
export const VERIFY_SUBMITTING = 'app/campaign/VERIFY_SUBMITTING';
export const DECLINE_SUBMITTING = 'app/campaign/DECLINE_SUBMITTING';
export const DECLINE_REQUEST = 'app/campaign/DECLINE_REQUEST';
| 43.578947 | 74 | 0.817633 |
93789a860dc73033cdc70eb70fa350ccbcca8762 | 98 | js | JavaScript | menu/index.js | victorwpbastos/vue-components | 0c4ee2df3ce80e2dcf60ed6f1966c68127872eb4 | [
"MIT"
] | null | null | null | menu/index.js | victorwpbastos/vue-components | 0c4ee2df3ce80e2dcf60ed6f1966c68127872eb4 | [
"MIT"
] | null | null | null | menu/index.js | victorwpbastos/vue-components | 0c4ee2df3ce80e2dcf60ed6f1966c68127872eb4 | [
"MIT"
] | null | null | null | import Menu from './menu.vue';
import MenuItem from './menu-item.vue';
export { Menu, MenuItem }; | 24.5 | 39 | 0.693878 |
9378a4ac08fa744c871f044e23335915774f0717 | 201 | js | JavaScript | src/apis/systemApi.js | vdt040499/sParking_Admin | 3c59066a264d8c6c069156f8a5c59ce243b3edd1 | [
"MIT"
] | null | null | null | src/apis/systemApi.js | vdt040499/sParking_Admin | 3c59066a264d8c6c069156f8a5c59ce243b3edd1 | [
"MIT"
] | null | null | null | src/apis/systemApi.js | vdt040499/sParking_Admin | 3c59066a264d8c6c069156f8a5c59ce243b3edd1 | [
"MIT"
] | null | null | null | import axiosClient from './axiosClient'
const systemApi = {
updateSystem(spaceId, data) {
const url = `/spaces/${spaceId}`
return axiosClient.post(url, data)
}
}
export default systemApi
| 18.272727 | 39 | 0.696517 |
93791c40c483114009fdf30edbdfbe8f9820e66b | 23,641 | js | JavaScript | dist/components/carousel/index.min.js | tabbyz/buefy | d26da047e4fa4c2f8a8c0f4029bf50ff6344bfc9 | [
"MIT"
] | null | null | null | dist/components/carousel/index.min.js | tabbyz/buefy | d26da047e4fa4c2f8a8c0f4029bf50ff6344bfc9 | [
"MIT"
] | null | null | null | dist/components/carousel/index.min.js | tabbyz/buefy | d26da047e4fa4c2f8a8c0f4029bf50ff6344bfc9 | [
"MIT"
] | null | null | null | /*! Buefy v0.9.4 | MIT License | github.com/buefy/buefy */
!(function (t, e) { typeof exports === 'object' && typeof module !== 'undefined' ? e(exports) : typeof define === 'function' && define.amd ? define(['exports'], e) : e((t = t || self).Carousel = {}) }(this, function (t) { 'use strict'; function e(t) { return (e = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (t) { return typeof t } : function (t) { return t && typeof Symbol === 'function' && t.constructor === Symbol && t !== Symbol.prototype ? 'symbol' : typeof t })(t) } function i(t, e, i) { return e in t ? Object.defineProperty(t, e, {value: i, enumerable: !0, configurable: !0, writable: !0}) : t[e] = i, t } function n(t, e) { var i = Object.keys(t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(t); e && (n = n.filter(function (e) { return Object.getOwnPropertyDescriptor(t, e).enumerable })), i.push.apply(i, n) } return i } function s(t) { for (var e = 1; e < arguments.length; e++) { var s = arguments[e] != null ? arguments[e] : {}; e % 2 ? n(Object(s), !0).forEach(function (e) { i(t, e, s[e]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(s)) : n(Object(s)).forEach(function (e) { Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(s, e)) }) } return t } function o(t) { return (function (t) { if (Array.isArray(t)) return t }(t)) || (function (t) { if (Symbol.iterator in Object(t) || Object.prototype.toString.call(t) === '[object Arguments]') return Array.from(t) }(t)) || (function () { throw new TypeError('Invalid attempt to destructure non-iterable instance') }()) } var a = {defaultContainerElement: null, defaultIconPack: 'mdi', defaultIconComponent: null, defaultIconPrev: 'chevron-left', defaultIconNext: 'chevron-right', defaultLocale: void 0, defaultDialogConfirmText: null, defaultDialogCancelText: null, defaultSnackbarDuration: 3500, defaultSnackbarPosition: null, defaultToastDuration: 2e3, defaultToastPosition: null, defaultNotificationDuration: 2e3, defaultNotificationPosition: null, defaultTooltipType: 'is-primary', defaultTooltipDelay: null, defaultInputAutocomplete: 'on', defaultDateFormatter: null, defaultDateParser: null, defaultDateCreator: null, defaultTimeCreator: null, defaultDayNames: null, defaultMonthNames: null, defaultFirstDayOfWeek: null, defaultUnselectableDaysOfWeek: null, defaultTimeFormatter: null, defaultTimeParser: null, defaultModalCanCancel: ['escape', 'x', 'outside', 'button'], defaultModalScroll: null, defaultDatepickerMobileNative: !0, defaultTimepickerMobileNative: !0, defaultNoticeQueue: !0, defaultInputHasCounter: !0, defaultTaginputHasCounter: !0, defaultUseHtml5Validation: !0, defaultDropdownMobileModal: !0, defaultFieldLabelPosition: null, defaultDatepickerYearsRange: [-100, 10], defaultDatepickerNearbyMonthDays: !0, defaultDatepickerNearbySelectableMonthDays: !1, defaultDatepickerShowWeekNumber: !1, defaultDatepickerWeekNumberClickable: !1, defaultDatepickerMobileModal: !0, defaultTrapFocus: !0, defaultAutoFocus: !0, defaultButtonRounded: !1, defaultSwitchRounded: !0, defaultCarouselInterval: 3500, defaultTabsExpanded: !1, defaultTabsAnimated: !0, defaultTabsType: null, defaultStatusIcon: !0, defaultProgrammaticPromise: !1, defaultLinkTags: ['a', 'button', 'input', 'router-link', 'nuxt-link', 'n-link', 'RouterLink', 'NuxtLink', 'NLink'], defaultImageWebpFallback: null, defaultImageLazy: !0, defaultImageResponsive: !0, defaultImageRatio: null, defaultImageSrcsetFormatter: null, customIconPacks: null}; var r = Math.sign || function (t) { return t < 0 ? -1 : t > 0 ? 1 : 0 }; function c(t, e) { return (t & e) === e } function u(t, e) { return (t % e + e) % e } function l(t, e, i) { return Math.max(e, Math.min(i, t)) } var d = function (t) { return e(t) === 'object' && !Array.isArray(t) }, h = function t(e, n) { var o = arguments.length > 2 && void 0 !== arguments[2] && arguments[2]; if (o || !Object.assign) { var a = Object.getOwnPropertyNames(n).map(function (s) { return i({}, s, (function (t) { return d(n[t]) && e !== null && e.hasOwnProperty(t) && d(e[t]) }(s)) ? t(e[s], n[s], o) : n[s]) }).reduce(function (t, e) { return s({}, t, {}, e) }, {}); return s({}, e, {}, a) } return Object.assign(e, n) }, f = {sizes: {default: 'mdi-24px', 'is-small': null, 'is-medium': 'mdi-36px', 'is-large': 'mdi-48px'}, iconPrefix: 'mdi-'}, p = function () { var t = a && a.defaultIconComponent ? '' : 'fa-'; return {sizes: {default: null, 'is-small': null, 'is-medium': t + 'lg', 'is-large': t + '2x'}, iconPrefix: t, internalIcons: {information: 'info-circle', alert: 'exclamation-triangle', 'alert-circle': 'exclamation-circle', 'chevron-right': 'angle-right', 'chevron-left': 'angle-left', 'chevron-down': 'angle-down', 'eye-off': 'eye-slash', 'menu-down': 'caret-down', 'menu-up': 'caret-up', 'close-circle': 'times-circle'}} }; var m = function (t, e, i, n, s, o, a, r, c, u) { typeof a !== 'boolean' && (c = r, r = a, a = !1); var l, d = typeof i === 'function' ? i.options : i; if (t && t.render && (d.render = t.render, d.staticRenderFns = t.staticRenderFns, d._compiled = !0, s && (d.functional = !0)), n && (d._scopeId = n), o ? (l = function (t) { (t = t || this.$vnode && this.$vnode.ssrContext || this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) || typeof __VUE_SSR_CONTEXT__ === 'undefined' || (t = __VUE_SSR_CONTEXT__), e && e.call(this, c(t)), t && t._registeredComponents && t._registeredComponents.add(o) }, d._ssrRegister = l) : e && (l = a ? function () { e.call(this, u(this.$root.$options.shadowRoot)) } : function (t) { e.call(this, r(t)) }), l) if (d.functional) { var h = d.render; d.render = function (t, e) { return l.call(e), h(t, e) } } else { var f = d.beforeCreate; d.beforeCreate = f ? [].concat(f, l) : [l] } return i }; var v = m({render: function () { var t = this, e = t.$createElement, i = t._self._c || e; return i('span', {staticClass: 'icon', class: [t.newType, t.size]}, [t.useIconComponent ? i(t.useIconComponent, {tag: 'component', class: [t.customClass], attrs: {icon: [t.newPack, t.newIcon], size: t.newCustomSize}}) : i('i', {class: [t.newPack, t.newIcon, t.newCustomSize, t.customClass]})], 1) }, staticRenderFns: []}, void 0, {name: 'BIcon', props: {type: [String, Object], component: String, pack: String, icon: String, size: String, customSize: String, customClass: String, both: Boolean}, computed: {iconConfig: function () { var t; return (t = {mdi: f, fa: p(), fas: p(), far: p(), fad: p(), fab: p(), fal: p()}, a && a.customIconPacks && (t = h(t, a.customIconPacks, !0)), t)[this.newPack] }, iconPrefix: function () { return this.iconConfig && this.iconConfig.iconPrefix ? this.iconConfig.iconPrefix : '' }, newIcon: function () { return ''.concat(this.iconPrefix).concat(this.getEquivalentIconOf(this.icon)) }, newPack: function () { return this.pack || a.defaultIconPack }, newType: function () { if (this.type) { var t = []; if (typeof this.type === 'string')t = this.type.split('-'); else for (var e in this.type) if (this.type[e]) { t = e.split('-'); break } if (!(t.length <= 1)) { var i = o(t).slice(1); return 'has-text-'.concat(i.join('-')) } } }, newCustomSize: function () { return this.customSize || this.customSizeByPack }, customSizeByPack: function () { if (this.iconConfig && this.iconConfig.sizes) { if (this.size && void 0 !== this.iconConfig.sizes[this.size]) return this.iconConfig.sizes[this.size]; if (this.iconConfig.sizes.default) return this.iconConfig.sizes.default } return null }, useIconComponent: function () { return this.component || a.defaultIconComponent }}, methods: {getEquivalentIconOf: function (t) { return this.both && this.iconConfig && this.iconConfig.internalIcons && this.iconConfig.internalIcons[t] ? this.iconConfig.internalIcons[t] : t }}}, void 0, !1, void 0, void 0, void 0); var g = m({render: function () { var t = this, e = t.$createElement, i = t._self._c || e; return i('div', {staticClass: 'carousel', class: {'is-overlay': t.overlay}, on: {mouseenter: t.checkPause, mouseleave: t.startTimer}}, [t.progress ? i('progress', {staticClass: 'progress', class: t.progressType, attrs: {max: t.childItems.length - 1}, domProps: {value: t.activeChild}}, [t._v(' ' + t._s(t.childItems.length - 1) + ' ')]) : t._e(), i('div', {staticClass: 'carousel-items', on: {mousedown: t.dragStart, mouseup: t.dragEnd, touchstart: function (e) { return e.stopPropagation(), t.dragStart(e) }, touchend: function (e) { return e.stopPropagation(), t.dragEnd(e) }}}, [t._t('default'), t.arrow ? i('div', {staticClass: 'carousel-arrow', class: {'is-hovered': t.arrowHover}}, [i('b-icon', {directives: [{name: 'show', rawName: 'v-show', value: t.hasPrev, expression: 'hasPrev'}], staticClass: 'has-icons-left', attrs: {pack: t.iconPack, icon: t.iconPrev, size: t.iconSize, both: ''}, nativeOn: {click: function (e) { return t.prev(e) }}}), i('b-icon', {directives: [{name: 'show', rawName: 'v-show', value: t.hasNext, expression: 'hasNext'}], staticClass: 'has-icons-right', attrs: {pack: t.iconPack, icon: t.iconNext, size: t.iconSize, both: ''}, nativeOn: {click: function (e) { return t.next(e) }}})], 1) : t._e()], 2), t.autoplay && t.pauseHover && t.pauseInfo && t.isPause ? i('div', {staticClass: 'carousel-pause'}, [i('span', {staticClass: 'tag', class: t.pauseInfoType}, [t._v(' ' + t._s(t.pauseText) + ' ')])]) : t._e(), t.withCarouselList && !t.indicator ? [t._t('list', null, {active: t.activeChild, switch: t.changeActive})] : t._e(), t.indicator ? i('div', {staticClass: 'carousel-indicator', class: t.indicatorClasses}, t._l(t.sortedItems, function (e, n) { return i('a', {key: e._uid, staticClass: 'indicator-item', class: {'is-active': e.isActive}, on: {mouseover: function (e) { return t.modeChange('hover', n) }, click: function (e) { return t.modeChange('click', n) }}}, [t._t('indicators', [i('span', {staticClass: 'indicator-style', class: t.indicatorStyle})], {i: n})], 2) }), 0) : t._e(), t.overlay ? [t._t('overlay')] : t._e()], 2) }, staticRenderFns: []}, void 0, {name: 'BCarousel', components: i({}, v.name, v), mixins: [(function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, n = {provide: function () { return i({}, 'b' + t, this) }}; return c(e, 1) && (n.data = function () { return {childItems: []} }, n.methods = {_registerItem: function (t) { this.childItems.push(t) }, _unregisterItem: function (t) { this.childItems = this.childItems.filter(function (e) { return e !== t }) }}, c(e, 3) && (n.watch = {childItems: function (t) { if (t.length > 0 && this.$scopedSlots.default) { var e = t[0].$vnode.tag, i = 0; !(function n(s) { var o = !0, a = !1, r = void 0; try { for (var c, u = function () { var s = c.value; if (s.tag === e) { var o = t.find(function (t) { return t.$vnode === s }); o && (o.index = i++) } else if (s.tag) { var a = s.componentInstance ? s.componentInstance.$scopedSlots.default ? s.componentInstance.$scopedSlots.default() : s.componentInstance.$children : s.children; Array.isArray(a) && a.length > 0 && n(a.map(function (t) { return t.$vnode })) } }, l = s[Symbol.iterator](); !(o = (c = l.next()).done); o = !0)u() } catch (t) { a = !0, r = t } finally { try { o || l.return == null || l.return() } finally { if (a) throw r } } return !1 }(this.$scopedSlots.default())) } }}, n.computed = {sortedItems: function () { return this.childItems.slice().sort(function (t, e) { return t.index - e.index }) }})), n }('carousel', 3))], props: {value: {type: Number, default: 0}, animated: {type: String, default: 'slide'}, interval: Number, hasDrag: {type: Boolean, default: !0}, autoplay: {type: Boolean, default: !0}, pauseHover: {type: Boolean, default: !0}, pauseInfo: {type: Boolean, default: !0}, pauseInfoType: {type: String, default: 'is-white'}, pauseText: {type: String, default: 'Pause'}, arrow: {type: Boolean, default: !0}, arrowHover: {type: Boolean, default: !0}, repeat: {type: Boolean, default: !0}, iconPack: String, iconSize: String, iconPrev: {type: String, default: function () { return a.defaultIconPrev }}, iconNext: {type: String, default: function () { return a.defaultIconNext }}, indicator: {type: Boolean, default: !0}, indicatorBackground: Boolean, indicatorCustom: Boolean, indicatorCustomSize: {type: String, default: 'is-small'}, indicatorInside: {type: Boolean, default: !0}, indicatorMode: {type: String, default: 'click'}, indicatorPosition: {type: String, default: 'is-bottom'}, indicatorStyle: {type: String, default: 'is-dots'}, overlay: Boolean, progress: Boolean, progressType: {type: String, default: 'is-primary'}, withCarouselList: Boolean}, data: function () { return {transition: 'next', activeChild: this.value || 0, isPause: !1, dragX: !1, timer: null} }, computed: {indicatorClasses: function () { return [{'has-background': this.indicatorBackground, 'has-custom': this.indicatorCustom, 'is-inside': this.indicatorInside}, this.indicatorCustom && this.indicatorCustomSize, this.indicatorInside && this.indicatorPosition] }, hasPrev: function () { return this.repeat || this.activeChild !== 0 }, hasNext: function () { return this.repeat || this.activeChild < this.childItems.length - 1 }}, watch: {value: function (t) { this.changeActive(t) }, sortedItems: function (t) { this.activeChild >= t.length && this.activeChild > 0 && this.changeActive(this.activeChild - 1) }, autoplay: function (t) { t ? this.startTimer() : this.pauseTimer() }, repeat: function (t) { t && this.startTimer() }}, methods: {startTimer: function () { var t = this; this.autoplay && !this.timer && (this.isPause = !1, this.timer = setInterval(function () { !t.repeat && t.activeChild >= t.childItems.length - 1 ? t.pauseTimer() : t.next() }, this.interval || a.defaultCarouselInterval)) }, pauseTimer: function () { this.isPause = !0, this.timer && (clearInterval(this.timer), this.timer = null) }, restartTimer: function () { this.pauseTimer(), this.startTimer() }, checkPause: function () { this.pauseHover && this.autoplay && this.pauseTimer() }, changeActive: function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0; this.activeChild === t || isNaN(t) || (e = e || t - this.activeChild, t = this.repeat ? u(t, this.childItems.length) : l(t, 0, this.childItems.length - 1), this.transition = e > 0 ? 'prev' : 'next', this.activeChild = t, t !== this.value && this.$emit('input', t), this.restartTimer(), this.$emit('change', t)) }, modeChange: function (t, e) { if (this.indicatorMode === t) return this.changeActive(e) }, prev: function () { this.changeActive(this.activeChild - 1, -1) }, next: function () { this.changeActive(this.activeChild + 1, 1) }, dragStart: function (t) { this.hasDrag && t.target.draggable && (this.dragX = t.touches ? t.changedTouches[0].pageX : t.pageX, t.touches ? this.pauseTimer() : t.preventDefault()) }, dragEnd: function (t) { if (!1 !== this.dragX) { var e = (t.touches ? t.changedTouches[0].pageX : t.pageX) - this.dragX; Math.abs(e) > 30 ? e < 0 ? this.next() : this.prev() : (t.target.click(), this.sortedItems[this.activeChild].$emit('click'), this.$emit('click')), t.touches && this.startTimer(), this.dragX = !1 } }}, mounted: function () { this.startTimer() }, beforeDestroy: function () { this.pauseTimer() }}, void 0, !1, void 0, void 0, void 0); var y = m({render: function () { var t = this.$createElement, e = this._self._c || t; return e('transition', {attrs: {name: this.transition}}, [e('div', {directives: [{name: 'show', rawName: 'v-show', value: this.isActive, expression: 'isActive'}], staticClass: 'carousel-item'}, [this._t('default')], 2)]) }, staticRenderFns: []}, void 0, {name: 'BCarouselItem', mixins: [(function (t) { var e = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, i = {inject: {parent: {from: 'b' + t, default: !1}}, created: function () { if (this.parent) this.parent._registerItem && this.parent._registerItem(this); else if (!c(e, 2)) throw this.$destroy(), new Error('You should wrap ' + this.$options.name + ' in a ' + t) }, beforeDestroy: function () { this.parent && this.parent._unregisterItem && this.parent._unregisterItem(this) }}; return c(e, 1) && (i.data = function () { return {index: null} }), i }('carousel', 1))], data: function () { return {transitionName: null} }, computed: {transition: function () { return this.parent.animated === 'fade' ? 'fade' : this.parent.transition ? 'slide-' + this.parent.transition : void 0 }, isActive: function () { return this.parent.activeChild === this.index }}}, void 0, !1, void 0, void 0, void 0); var w, b = m({render: function () { var t = this, e = t.$createElement, i = t._self._c || e; return i('div', {staticClass: 'carousel-list', class: {'has-shadow': t.scrollIndex > 0}, on: {mousedown: function (e) { return e.preventDefault(), t.dragStart(e) }, touchstart: t.dragStart}}, [i('div', {staticClass: 'carousel-slides', class: t.listClass, style: 'transform:translateX(' + t.translation + 'px)'}, t._l(t.data, function (e, n) { return i('div', {key: n, staticClass: 'carousel-slide', class: {'is-active': t.asIndicator ? t.activeItem === n : t.scrollIndex === n}, style: t.itemStyle, on: {mouseup: function (e) { return t.checkAsIndicator(n, e) }, touchend: function (e) { return t.checkAsIndicator(n, e) }}}, [t._t('item', [i('figure', {staticClass: 'image'}, [i('img', {attrs: {src: e.image, alt: e.alt, title: e.title}})])], {index: n, active: t.activeItem, scroll: t.scrollIndex, list: e}, e)], 2) }), 0), t.arrow ? i('div', {staticClass: 'carousel-arrow', class: {'is-hovered': t.settings.arrowHover}}, [i('b-icon', {directives: [{name: 'show', rawName: 'v-show', value: t.hasPrev, expression: 'hasPrev'}], staticClass: 'has-icons-left', attrs: {pack: t.settings.iconPack, icon: t.settings.iconPrev, size: t.settings.iconSize, both: ''}, nativeOn: {click: function (e) { return e.preventDefault(), t.prev(e) }}}), i('b-icon', {directives: [{name: 'show', rawName: 'v-show', value: t.hasNext, expression: 'hasNext'}], staticClass: 'has-icons-right', attrs: {pack: t.settings.iconPack, icon: t.settings.iconNext, size: t.settings.iconSize, both: ''}, nativeOn: {click: function (e) { return e.preventDefault(), t.next(e) }}})], 1) : t._e()]) }, staticRenderFns: []}, void 0, {name: 'BCarouselList', components: i({}, v.name, v), props: {data: {type: Array, default: function () { return [] }}, value: {type: Number, default: 0}, scrollValue: {type: Number, default: 0}, hasDrag: {type: Boolean, default: !0}, hasGrayscale: Boolean, hasOpacity: Boolean, repeat: Boolean, itemsToShow: {type: Number, default: 4}, itemsToList: {type: Number, default: 1}, asIndicator: Boolean, arrow: {type: Boolean, default: !0}, arrowHover: {type: Boolean, default: !0}, iconPack: String, iconSize: String, iconPrev: {type: String, default: function () { return a.defaultIconPrev }}, iconNext: {type: String, default: function () { return a.defaultIconNext }}, breakpoints: {type: Object, default: function () { return {} }}}, data: function () { return {activeItem: this.value, scrollIndex: this.asIndicator ? this.scrollValue : this.value, delta: 0, dragX: !1, hold: 0, windowWidth: 0, touch: !1, observer: null, refresh_: 0} }, computed: {dragging: function () { return !1 !== this.dragX }, listClass: function () { return [{'has-grayscale': this.settings.hasGrayscale, 'has-opacity': this.settings.hasOpacity, 'is-dragging': this.dragging}] }, itemStyle: function () { return 'width: '.concat(this.itemWidth, 'px;') }, translation: function () { return -l(this.delta + this.scrollIndex * this.itemWidth, 0, (this.data.length - this.settings.itemsToShow) * this.itemWidth) }, total: function () { return this.data.length - this.settings.itemsToShow }, hasPrev: function () { return this.settings.repeat || this.scrollIndex > 0 }, hasNext: function () { return this.settings.repeat || this.scrollIndex < this.total }, breakpointKeys: function () { return Object.keys(this.breakpoints).sort(function (t, e) { return e - t }) }, settings: function () { var t = this, e = this.breakpointKeys.filter(function (e) { if (t.windowWidth >= e) return !0 })[0]; return e ? s({}, this.$props, {}, this.breakpoints[e]) : this.$props }, itemWidth: function () { return this.windowWidth ? (this.refresh_, this.$el.getBoundingClientRect().width / this.settings.itemsToShow) : 0 }}, watch: {value: function (t) { this.switchTo(this.asIndicator ? t - (this.itemsToShow - 3) / 2 : t), this.activeItem !== t && (this.activeItem = l(t, 0, this.data.length - 1)) }, scrollValue: function (t) { this.switchTo(t) }}, methods: {resized: function () { this.windowWidth = window.innerWidth }, switchTo: function (t) { t === this.scrollIndex || isNaN(t) || (this.settings.repeat && (t = u(t, this.total + 1)), t = l(t, 0, this.total), this.scrollIndex = t, this.asIndicator || this.value === t ? this.scrollIndex !== t && this.$emit('updated:scroll', t) : this.$emit('input', t)) }, next: function () { this.switchTo(this.scrollIndex + this.settings.itemsToList) }, prev: function () { this.switchTo(this.scrollIndex - this.settings.itemsToList) }, checkAsIndicator: function (t, e) { if (this.asIndicator) { var i = e.touches ? e.touches[0].clientX : e.clientX; this.hold - Date.now() > 2e3 || Math.abs(this.dragX - i) > 10 || (this.dragX = !1, this.hold = 0, e.preventDefault(), this.activeItem = t, this.$emit('switch', t)) } }, dragStart: function (t) { this.dragging || !this.settings.hasDrag || t.button !== 0 && t.type !== 'touchstart' || (this.hold = Date.now(), this.touch = !!t.touches, this.dragX = this.touch ? t.touches[0].clientX : t.clientX, window.addEventListener(this.touch ? 'touchmove' : 'mousemove', this.dragMove), window.addEventListener(this.touch ? 'touchend' : 'mouseup', this.dragEnd)) }, dragMove: function (t) { if (this.dragging) { var e = t.touches ? t.touches[0].clientX : t.clientX; this.delta = this.dragX - e, t.touches || t.preventDefault() } }, dragEnd: function () { if (this.dragging || this.hold) { if (this.hold) { var t = r(this.delta), e = Math.round(Math.abs(this.delta / this.itemWidth) + 0.15); this.switchTo(this.scrollIndex + t * e) } this.delta = 0, this.dragX = !1, window.removeEventListener(this.touch ? 'touchmove' : 'mousemove', this.dragMove), window.removeEventListener(this.touch ? 'touchend' : 'mouseup', this.dragEnd) } }, refresh: function () { var t = this; this.$nextTick(function () { t.refresh_++ }) }}, mounted: function () { if (typeof window !== 'undefined' && (window.ResizeObserver && (this.observer = new ResizeObserver(this.refresh), this.observer.observe(this.$el)), window.addEventListener('resize', this.resized), document.addEventListener('animationend', this.refresh), document.addEventListener('transitionend', this.refresh), document.addEventListener('transitionstart', this.refresh), this.resized()), this.$attrs.config) throw new Error('The config prop was removed, you need to use v-bind instead') }, beforeDestroy: function () { typeof window !== 'undefined' && (window.ResizeObserver && this.observer.disconnect(), window.removeEventListener('resize', this.resized), document.removeEventListener('animationend', this.refresh), document.removeEventListener('transitionend', this.refresh), document.removeEventListener('transitionstart', this.refresh), this.dragEnd()) }}, void 0, !1, void 0, void 0, void 0), C = function (t, e) { t.component(e.name, e) }, I = {install: function (t) { C(t, g), C(t, y), C(t, b) }}; w = I, typeof window !== 'undefined' && window.Vue && window.Vue.use(w), t.BCarousel = g, t.BCarouselItem = y, t.BCarouselList = b, t.default = I, Object.defineProperty(t, '__esModule', {value: !0}) }))
| 7,880.333333 | 23,581 | 0.669853 |
93797f36e7a4b337283d77076e0f50ef6a712eec | 939 | js | JavaScript | api/models/expenseModel.js | buggasai/RMS | da694dd1741f7a79f7e6017d810b3f68c37194a4 | [
"MIT"
] | null | null | null | api/models/expenseModel.js | buggasai/RMS | da694dd1741f7a79f7e6017d810b3f68c37194a4 | [
"MIT"
] | null | null | null | api/models/expenseModel.js | buggasai/RMS | da694dd1741f7a79f7e6017d810b3f68c37194a4 | [
"MIT"
] | null | null | null | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Expenses = new mongoose.Schema({
Description: {
type: String,
//required: 'FirstName is required'
},
BuildingId: {
type: ObjectId,
required: 'Vendor is required'
},
VendorId: {
type: ObjectId,
required: 'Vendor is required'
},
ExpensesAmount: {
type: String,
default: ''
},
Date: {
type: Date,
default: Date.now
},
chequeNumber: {
type: String,
default: ''
},
Catogery: {
type: String,
default: ''
},
ExpensesRepeat: {
type: String,
default: ''
},
Note: {
type: String,
default: ''
},
file: {
type: String,
default: ''
}
});
module.exports = mongoose.model('Expenses', Expenses); | 18.411765 | 54 | 0.502662 |
937a74e3465f34c920284950a7ca47999eeafb97 | 295 | js | JavaScript | app/util/common.js | win-winFE/dms | 92cff608875938455a860f1ab94d103bfa84c6fd | [
"MIT"
] | 225 | 2019-01-23T09:55:35.000Z | 2020-04-07T17:47:53.000Z | app/util/common.js | gavin1995/dms | 92cff608875938455a860f1ab94d103bfa84c6fd | [
"MIT"
] | 17 | 2020-04-09T14:28:36.000Z | 2022-03-08T22:42:32.000Z | app/util/common.js | win-winFE/dms | 92cff608875938455a860f1ab94d103bfa84c6fd | [
"MIT"
] | 15 | 2019-01-24T08:11:59.000Z | 2020-04-08T06:13:41.000Z | 'use strict';
module.exports = {
async checkEditModelAndDataAuth(model, userId, appId) {
const appRes = await ctx.model.Application.findIdByAppIdAndOwnerId(userId, appId);
const authRes = await model.Auth.findOneByUserIdAndAppId(userId, appId);
return appRes || authRes;
},
};
| 26.818182 | 86 | 0.732203 |
937aa51140bf0e61a368e6abc60ab3e6456b72aa | 2,785 | js | JavaScript | src/routes/signature/account_management/personal_certification/FirstPageContainer.js | Xzg-github/web_service | 87868562eed3ed804b6c1f72a959a2855db8f2a3 | [
"MIT"
] | null | null | null | src/routes/signature/account_management/personal_certification/FirstPageContainer.js | Xzg-github/web_service | 87868562eed3ed804b6c1f72a959a2855db8f2a3 | [
"MIT"
] | 4 | 2020-07-07T20:37:53.000Z | 2022-02-26T18:03:21.000Z | src/routes/signature/account_management/personal_certification/FirstPageContainer.js | Xzg-github/web_service | 87868562eed3ed804b6c1f72a959a2855db8f2a3 | [
"MIT"
] | null | null | null | import { connect } from 'react-redux';
import OrderPage from './components/OrderPage';
import {EnhanceLoading} from '../../../../components/Enhance';
import helper,{getObject, swapItems} from '../../../../common/common';
import {Action} from '../../../../action-reducer/action';
import {getPathValue} from '../../../../action-reducer/helper';
import execWithLoading from '../../../../standard-business/execWithLoading';
const TAB_KEY = 'one';
const STATE_PATH = ['personal_certification'];
const URL_USER = '/api/fadada/user'; //校验是否通过认证 0:禁用,1:待认证,2:认证失败 3:已认证
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH)[TAB_KEY];
};
const initActionCreator = () => async (dispatch, getState) => {
const state = getSelfState(getState());
dispatch(action.assign({status: 'loading'}, TAB_KEY));
try {
dispatch(action.assign({
...state,
text:'校验验证',
type:'default',
status: 'page',
disabled:false,
}, TAB_KEY));
} catch (e) {
helper.showError(e.message);
dispatch(action.assign({status: 'retry'}, TAB_KEY));
}
};
const toolbarActions = {
};
const clickActionCreator = (key) => {
if (toolbarActions.hasOwnProperty(key)) {
return toolbarActions[key];
} else {
console.log('unknown key:', key);
return {type: 'unknown'};
}
};
const changeActionCreator = (key, value) => (dispatch,getState) =>{
dispatch(action.assign({[key]: value}, [TAB_KEY,'value']));
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const exitValidActionCreator = () => {
return action.assign({valid: false},TAB_KEY);
};
const verificationAtionCreator = () => async(dispatch,getState) =>{
const {text,strCookie} = getSelfState(getState());
if(text === '已认证'){
return
}
execWithLoading(async()=>{
const {result,returnCode,returnMsg} = await helper.fetchJson(`${URL_USER}`);
if(returnCode != 0){
helper.showError(returnCode);
return
}
if(result.userAccountState == 0){
helper.showError('该账号禁止使用');
return
}else if(result.userAccountState == 1){
helper.showError('该账号待认证');
return
}else if(result.userAccountState == 2){
helper.showError('该账号认证失败');
return
}else if(result.userAccountState == 3){
helper.showSuccessMsg('该账号认证成功');
dispatch(action.assign({text:'已认证',type:'primary'},TAB_KEY));
return
}
});
};
const actionCreators = {
onClick: clickActionCreator,
onChange: changeActionCreator,
onInit: initActionCreator,
onExitValid: exitValidActionCreator,
verification:verificationAtionCreator
};
const Container = connect(mapStateToProps, actionCreators)(EnhanceLoading(OrderPage));
export default Container;
| 25.787037 | 86 | 0.6614 |
937abec8dda4a58b626c1abfb849414a9d827a4e | 1,211 | js | JavaScript | scripts/sandbox/teamChanger.js | Erisfiregamer1/Colloseus-Mod | 247de733b2944a8bafc3a99cab758e03dc662391 | [
"MIT"
] | 1 | 2022-02-25T01:03:50.000Z | 2022-02-25T01:03:50.000Z | scripts/sandbox/teamChanger.js | Erisfiregamer1/Colloseus-Mod | 247de733b2944a8bafc3a99cab758e03dc662391 | [
"MIT"
] | null | null | null | scripts/sandbox/teamChanger.js | Erisfiregamer1/Colloseus-Mod | 247de733b2944a8bafc3a99cab758e03dc662391 | [
"MIT"
] | 5 | 2021-12-27T09:18:57.000Z | 2022-02-25T01:05:35.000Z | const TeamChanger = extendContent(Block, "team-changer", {});
TeamChanger.buildType = prov(() => extend(Building, {
addButtonTeam(t, table){
table.button(new TextureRegionDrawable(Core.atlas.find("collos-team")).tint(Team.baseTeams[t].color),
Styles.clearFulli, run(() => {
this.team = Team.baseTeams[t];
Vars.player.team(Team.baseTeams[t]);
}))
},
draw(){
this.super$draw();
Draw.color(this.team.color);
Draw.rect(Core.atlas.find("collos-team-changer-team"), this.x, this.y);
Draw.color();
},
buildConfiguration(table) {
table.defaults().size(50);
for(var t = 0; t < Team.baseTeams.length; t++){;
this.addButtonTeam(t, table);
};
table.defaults().reset()
}
}));
TeamChanger.configurable = true;
TeamChanger.size = 2;
TeamChanger.health = 100;
TeamChanger.destructible = true;
TeamChanger.sync = true;
TeamChanger.expanded = true;
TeamChanger.breakable = true;
TeamChanger.solid = false;
TeamChanger.category = Category.effect;
TeamChanger.buildVisibility = BuildVisibility.sandboxOnly;
TeamChanger.requirements = ItemStack.with();
| 29.536585 | 108 | 0.629232 |
937c238dda3c71e4119efc1b9b0228f9e7c0122d | 5,326 | js | JavaScript | src/api/asset.js | DemonsL/hssmp-ui | 16c6db502d84c2fecbb018fc9a73a2d393d73a2d | [
"MIT"
] | null | null | null | src/api/asset.js | DemonsL/hssmp-ui | 16c6db502d84c2fecbb018fc9a73a2d393d73a2d | [
"MIT"
] | null | null | null | src/api/asset.js | DemonsL/hssmp-ui | 16c6db502d84c2fecbb018fc9a73a2d393d73a2d | [
"MIT"
] | null | null | null | import axios from '@/libs/api.request'
/**
* 设备详情
* @param {Long} deviceId 设备ID
*/
export const assetDeviceInfo = (deviceId) => {
return axios.request({
url: '/admin/assetmanagement/asset/device/info',
params: { deviceId: deviceId },
method: 'get'
})
}
/**
* 机柜详情
* @param {Long} cabinetId 机柜ID
*/
export const assetCabinetInfo = (cabinetId) => {
return axios.request({
url: '/admin/assetmanagement/asset/cabinet/info',
params: { cabinetId: cabinetId },
method: 'get'
})
}
/**
* 裸服务器电源状态
* @param {Long} deviceId 设备ID
*/
export const assetBmcPowerStatus = (deviceId) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/power/status',
params: { deviceId: deviceId },
method: 'get'
})
}
/**
* 裸服务器电源动作
* @param {Long} deviceId 设备ID
*/
export const assetBmcPowerAction = (deviceId, action, captcha) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/power/action',
params: { deviceId: deviceId, action: action, captcha: captcha },
method: 'get'
})
}
/**
* 获取vncurl
* @param {Long} deviceId 设备ID
*/
export const assetBmcVncUrl = (deviceId, captcha) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/vnc/url',
params: { deviceId: deviceId, captcha: captcha },
method: 'get'
})
}
/**
* 发送设备操作短信验证码
* @param {String} action
* @param {int} action
*/
export const assetSmsActionSend = (action, mode) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/ipmi/action/sms/send',
params: { action: action, mode: mode },
mathod: 'get'
})
}
/**
* 验证设备操作短信验证码
* @param {String} action
*/
export const assetSmsActionVerify = (action, code) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/ipmi/action/sms/verify',
params: { action: action, code: code },
mathod: 'get'
})
}
/**
* 修改redfish 设备属性( vncStatus,vncPassword,vncPort,vncTimeout)
* @param {*} params
*/
export const assetIpmiRedfishUpdate = (deviceId, config, captcha) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/redfish/update',
data: {deviceId: deviceId, config: config, captcha: captcha},
method: 'post'
})
}
/**
* 修改ipmi网络属性(ip,mac, user, password)
* @param {*} action
* @param {*} params
*/
export const assetIpmiLanUpdate = (deviceId, config, captcha) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/ipmi/update',
data: {deviceId: deviceId, config: config, captcha: captcha},
method: 'post'
})
}
/**
* 初始化ipmi网络属性(ip, user, password)
* @param {*} action
* @param {*} params
*/
export const assetIpmiLanInit = (deviceId, config, captcha) => {
return axios.request({
url: '/admin/assetmanagement/asset/bmc/ipmi/init',
data: {deviceId: deviceId, config: config, captcha: captcha},
method: 'post'
})
}
// 判断是进入首次配置页面还是进入列表页面
export const assetFirstTimeConfigurePageLoad = () => {
return axios.request({
url: '/admin/assetmanagement/asset/init/initload',
method: 'get'
})
}
// 首次配置列表展示
export const assetFirstTimeConfigureList = (fieldName, orderBy) => {
const data = {
'pageParam': {
'pageNum': 1,
'pageSize': 9999
},
'orderParam': [{
'asc': orderBy,
'dateAggregateBy': '',
'fieldName': fieldName
}]
}
return axios.request({
url: '/admin/assetmanagement/asset/init/list',
data: data,
method: 'post'
})
}
// 首次配置保存数据
export const assetFirstTimeConfigureAction = (d) => {
const data = {
params: d
}
return axios.request({
url: '/admin/assetmanagement/asset/init/configure',
data,
method: 'post'
})
}
// 首次配置下载批量导入模板
export const assetFirstTimeConfigureDownloadTemplate = (fieldName, orderBy) => {
const params = {
'pageParam': {
'pageNum': 1,
'pageSize': 9999
},
'orderParam': [{
'asc': orderBy,
'dateAggregateBy': '',
'fieldName': fieldName
}]
}
var headers = {
'content-disposition': 'attachment;filename=devices.xlsx'
}
return axios.request({
url: '/admin/assetmanagement/asset/init/download',
data: params,
responseType: 'blob',
headers: headers,
method: 'post'
})
}
/**
* 机柜列表
* @param filterBy
* @param orderParam
* @param pageParam
* @returns {*}
*/
export const assetCabinetList = (filterBy = {}, orderParam = [], pageParam = {}) => {
return axios.request({
url: '/admin/assetmanagement/asset/cabinet/list',
data: { filterBy: filterBy, orderParam: orderParam, pageParam: pageParam },
method: 'post'
})
}
/**
* 设备列表
* @param filterBy
* @param orderParam
* @param pageParam
* @returns {*}
*/
export const assetDeviceList = (filterBy = {}, orderParam = [], pageParam = {}) => {
return axios.request({
url: '/admin/assetmanagement/asset/device/list',
data: { filterBy: filterBy, orderParam: orderParam, pageParam: pageParam },
method: 'post'
})
}
/**
* 执行日志
* @param filterBy
* @param orderParam
* @param pageParam
* @returns {*}
*/
export const assetActionLogList = (filterBy = {}, orderParam = [], pageParam = {}) => {
return axios.request({
url: '/admin/assetmanagement/asset/actionLog/list',
data: { filterBy: filterBy, orderParam: orderParam, pageParam: pageParam },
method: 'post'
})
}
| 22.472574 | 87 | 0.635561 |
937e1477fdca30426d7a9e524b00e704902ea2ed | 2,130 | js | JavaScript | source/views/faqs/index.js | drewvolz/AAO-React-Native | 03c3a2721267beb0f100e3cdabecbc5e2addac3d | [
"MIT"
] | null | null | null | source/views/faqs/index.js | drewvolz/AAO-React-Native | 03c3a2721267beb0f100e3cdabecbc5e2addac3d | [
"MIT"
] | null | null | null | source/views/faqs/index.js | drewvolz/AAO-React-Native | 03c3a2721267beb0f100e3cdabecbc5e2addac3d | [
"MIT"
] | null | null | null | // @flow
import * as React from 'react'
import {RefreshControl, StyleSheet} from 'react-native'
import * as c from '../components/colors'
import {View, ScrollView} from 'glamorous-native'
import {Markdown} from '../components/markdown'
import {reportNetworkProblem} from '../../lib/report-network-problem'
import LoadingView from '../components/loading'
import * as defaultData from '../../../docs/faqs.json'
import delay from 'delay'
import {GH_PAGES_URL} from '../../globals'
const faqsUrl = GH_PAGES_URL('faqs.json')
const styles = StyleSheet.create({
container: {
paddingHorizontal: 15,
},
})
type Props = {}
type State = {
text: string,
loading: boolean,
refreshing: boolean,
}
export class FaqView extends React.PureComponent<Props, State> {
static navigationOptions = {
title: 'FAQs',
}
state = {
text: defaultData.text,
loading: true,
refreshing: false,
}
componentDidMount() {
this.fetchData().then(() => {
this.setState(() => ({loading: false}))
})
}
fetchData = async () => {
let {text} = await fetchJson(faqsUrl).catch(err => {
reportNetworkProblem(err)
return {text: 'There was a problem loading the FAQs'}
})
if (process.env.NODE_ENV === 'development') {
text = defaultData.text
}
this.setState(() => ({text}))
}
refresh = async (): any => {
const start = Date.now()
this.setState(() => ({refreshing: true}))
await this.fetchData()
// wait 0.5 seconds – if we let it go at normal speed, it feels broken.
const elapsed = Date.now() - start
if (elapsed < 500) {
await delay(500 - elapsed)
}
this.setState(() => ({refreshing: false}))
}
render() {
if (this.state.loading) {
return <LoadingView />
}
const refreshControl = (
<RefreshControl
onRefresh={this.refresh}
refreshing={this.state.refreshing}
/>
)
return (
<ScrollView
backgroundColor={c.white}
contentContainerStyle={styles.container}
contentInsetAdjustmentBehavior="automatic"
refreshControl={refreshControl}
>
<View paddingVertical={15}>
<Markdown source={this.state.text} />
</View>
</ScrollView>
)
}
}
| 21.515152 | 73 | 0.658216 |
937f4f1db61c0d99e430d33f44dc319f53858d0f | 826 | js | JavaScript | src/k8cher.web/src/lib/safariStore.js | michaelkacher/k8cher | fa1e68e3c29f35923a5048a4ebaa497e084c723f | [
"MIT"
] | 13 | 2021-09-03T13:29:48.000Z | 2022-03-07T13:00:05.000Z | src/k8cher.web/src/lib/safariStore.js | michaelkacher/k8cher | fa1e68e3c29f35923a5048a4ebaa497e084c723f | [
"MIT"
] | null | null | null | src/k8cher.web/src/lib/safariStore.js | michaelkacher/k8cher | fa1e68e3c29f35923a5048a4ebaa497e084c723f | [
"MIT"
] | 1 | 2021-09-06T18:40:55.000Z | 2021-09-06T18:40:55.000Z | import { writable } from 'svelte/store'
import { persistable } from './persistable';
const initialState = {
name: '',
date: undefined,
animals: [],
}
export const safariStore = createSafariStore();
function createSafariStore() {
// const { subscribe, update } = writable(initialState)
const { subscribe, update } = persistable('safari', initialState)
return {
subscribe,
addAnimal: async (animalName) => {
update(state => {
return { ...state, animals: [...state.animals, {name: animalName} ] }
})
},
setName: async(name) => {
update(state => (state = { ...state, name }));
},
setLocation: async(date) => {
update(state => (state = { ...state, date }));
}
};
}
| 25.030303 | 89 | 0.526634 |
937fd2157d79906fb61785a79b2f068944d2b649 | 1,117 | js | JavaScript | doxygen/ovs_all/html/structtc__ops.js | vladn-ma/vladn-ovs-doc | 516974aba363d3e22613fa06ce56d2b8f1b1aadf | [
"Apache-2.0"
] | null | null | null | doxygen/ovs_all/html/structtc__ops.js | vladn-ma/vladn-ovs-doc | 516974aba363d3e22613fa06ce56d2b8f1b1aadf | [
"Apache-2.0"
] | null | null | null | doxygen/ovs_all/html/structtc__ops.js | vladn-ma/vladn-ovs-doc | 516974aba363d3e22613fa06ce56d2b8f1b1aadf | [
"Apache-2.0"
] | null | null | null | var structtc__ops =
[
[ "class_delete", "structtc__ops.html#a2048fab3eb8470a241e4536a25c3b3d5", null ],
[ "class_dump_stats", "structtc__ops.html#ade9f3f6077ef2ef8936c6cbd886e0360", null ],
[ "class_get", "structtc__ops.html#a522a86eec90cde5c574340fb4ddefe36", null ],
[ "class_get_stats", "structtc__ops.html#add4c9f56d62e12620457852856bb86fc", null ],
[ "class_set", "structtc__ops.html#a05f2fd4e211f684cfa77d436de65a18e", null ],
[ "linux_name", "structtc__ops.html#a425f44aa5adf7769383763ad8c2effef", null ],
[ "n_queues", "structtc__ops.html#a8b08dcdd7a0669adceaff166c40c93aa", null ],
[ "ovs_name", "structtc__ops.html#a00532f31f1ec799df664722ec79868e8", null ],
[ "qdisc_get", "structtc__ops.html#ac4df63afceb0fc55ff8437549c56eda4", null ],
[ "qdisc_set", "structtc__ops.html#a15064d81dcaba6b452d8d419263a0e5a", null ],
[ "tc_destroy", "structtc__ops.html#ac18d9e8a1744f85453bc300a151df83b", null ],
[ "tc_install", "structtc__ops.html#a1b7ed55a0de3c0f3499da4737d9e565a", null ],
[ "tc_load", "structtc__ops.html#a819e98b83bdcce3979bff91b2144ceb9", null ]
]; | 69.8125 | 89 | 0.760967 |
9380af92f198a7e4c8c64b6d4527348a348e4452 | 213 | js | JavaScript | index.js | sm-project-dev/sm-communication-manager | 2124ca4eba618d3f7438f9fc9ca0e9a6f523671d | [
"MIT"
] | null | null | null | index.js | sm-project-dev/sm-communication-manager | 2124ca4eba618d3f7438f9fc9ca0e9a6f523671d | [
"MIT"
] | null | null | null | index.js | sm-project-dev/sm-communication-manager | 2124ca4eba618d3f7438f9fc9ca0e9a6f523671d | [
"MIT"
] | null | null | null | const AbstDeviceClient = require('./src/device-client/AbstDeviceClient');
module.exports = AbstDeviceClient;
// if __main process
if (require !== undefined && require.main === module) {
console.log('main');
}
| 23.666667 | 73 | 0.713615 |
9380cfa11c345341af480b7b5e46debdb20f00e9 | 1,217 | js | JavaScript | src/utils.js | Aryailia/denotational | 5634f4828ec3d946a3b80f383c256ca994570c8d | [
"MIT"
] | null | null | null | src/utils.js | Aryailia/denotational | 5634f4828ec3d946a3b80f383c256ca994570c8d | [
"MIT"
] | null | null | null | src/utils.js | Aryailia/denotational | 5634f4828ec3d946a3b80f383c256ca994570c8d | [
"MIT"
] | null | null | null | var toExport = {
INFINITY: 1 / 0,
isArrayLike: function (toTest) {
return typeof toTest === 'object' && toTest.hasOwnProperty('length');
},
inlineSlice: function (skip, until) {
return function () {
var length = arguments.length - until;
var result = new Array(length - skip);
var i = skip; while (i < length) {
result[i - skip] = arguments[i];
++i;
}
return result;
}
},
pushArray: function (result, input, targetLength) {
var source = toExport.isArrayLike(input) ? input : [input];
// var source = input;
var sourceLength = source.length;
var i = -1; while (++i < sourceLength && result.length < targetLength) {
result[result.length] = source[i];
}
},
baseFlattenMin1: function (result, depth) {
return function () {
var length = arguments.length;
var temp;
var i = -1; while (++i < length) {
temp = arguments[i];
toExport.isArrayLike(temp) && depth > 1
? toExport.baseFlattenMin1(result, depth - 1).apply(null, temp)
: toExport.pushArray(result, temp, toExport.INFINITY);
}
return result;
};
},
};
module.exports = toExport; | 26.456522 | 76 | 0.580937 |
938237e626ef586c9badc16453631a3216faf84d | 1,023 | js | JavaScript | src/service/config/file-loader.js | thomasbui93/lucida | 3b3fb0a82b4904a743d468f40c4ac9792f6a4c46 | [
"MIT"
] | null | null | null | src/service/config/file-loader.js | thomasbui93/lucida | 3b3fb0a82b4904a743d468f40c4ac9792f6a4c46 | [
"MIT"
] | null | null | null | src/service/config/file-loader.js | thomasbui93/lucida | 3b3fb0a82b4904a743d468f40c4ac9792f6a4c46 | [
"MIT"
] | null | null | null | import fs from 'fs';
import path from 'path';
/**
* Get config file content
* @returns false | Object
*/
export const getConfig = (envFilePath = 'env.json') => {
try {
const envPath = envFilePath || (process.env.NODE_ENV === 'test' ? 'env-sample.json' : 'env.json');
return JSON.parse(fs.readFileSync(path.join(process.cwd(), envPath), 'utf8'));
} catch (err) {
return false;
}
};
/**
* Read config by paths
* @param {*} paths
* @param {*} delimiter
*/
export const readConfig = (paths, delimiter = '/', envFilePath = 'env.json') => {
let configSource = getConfig(envFilePath);
if (!configSource) {
return false;
}
if (typeof paths === 'string' && typeof delimiter === 'string' && delimiter.length > 0) {
const pathFragments = paths.split(delimiter);
try {
pathFragments.forEach(fragment => {
configSource = configSource[fragment];
});
return configSource;
} catch (error) {
return undefined;
}
} else {
return undefined;
}
};
| 24.357143 | 102 | 0.610948 |
9383dc5d4540a086c6a3067ce2d80517d237ec66 | 1,299 | js | JavaScript | script.js | Student-Torsten/Quizbox | f00c7fd0a59a6cd4d8e68e624f1410b68e670a98 | [
"MIT"
] | null | null | null | script.js | Student-Torsten/Quizbox | f00c7fd0a59a6cd4d8e68e624f1410b68e670a98 | [
"MIT"
] | null | null | null | script.js | Student-Torsten/Quizbox | f00c7fd0a59a6cd4d8e68e624f1410b68e670a98 | [
"MIT"
] | null | null | null | const questionEl = document.querySelector("#question");
const nextBtn = document.querySelector("#next");
const restartBtn = document.querySelector("#restart");
const topic = document.querySelector("#topic");
function random() {
const l = currentQuestions.length;
const random = Math.floor(Math.random() * l);
const currentQuestion = currentQuestions.splice(random, 1)[0];
return currentQuestion;
}
let currentQuestions = [];
function showRandomQuestion() {
const currentQuestion = random();
if (currentQuestion !== undefined) {
questionEl.innerText = currentQuestion;
} else {
nextBtn.hidden = true;
restartBtn.hidden = false;
restartBtn.focus();
questionEl.innerText = "Done 🎉";
}
}
function restart() {
initQuizbox();
}
nextBtn.addEventListener("click", showRandomQuestion);
restartBtn.addEventListener("click", restart);
topic.addEventListener("change", initQuizbox);
function initQuizbox() {
nextBtn.hidden = false;
restartBtn.hidden = true;
nextBtn.focus();
const url = "questions/" + topic.value + ".json";
fetch(url)
.then((res) => res.json())
.then((data) => {
currentQuestions = data.questions;
showRandomQuestion();
})
.catch((err) => {
console.error("OH NO! Anyway", err);
});
}
initQuizbox();
| 24.509434 | 64 | 0.680523 |
938463b495188b509b3eb86a81cca84978ce86c8 | 5,517 | js | JavaScript | public/frontend/js/js_frontend.js | tienphat/laravel_shop | c81660caf3d3f1b0840d9ca52adb822b8cbd284a | [
"MIT"
] | null | null | null | public/frontend/js/js_frontend.js | tienphat/laravel_shop | c81660caf3d3f1b0840d9ca52adb822b8cbd284a | [
"MIT"
] | null | null | null | public/frontend/js/js_frontend.js | tienphat/laravel_shop | c81660caf3d3f1b0840d9ca52adb822b8cbd284a | [
"MIT"
] | null | null | null |
function dat_mua(id) {
if ($(".name").text() == "") {
alert("Vui lòng đăng nhập trước khi mua hàng!");
} else {
var filename = 'user/cart';
var html = "";
$.ajax({
url: "sanpham/mua_hang",
type: "post",
dataType: "json",
data: {id: id}
}).done(function (result) {
console.log(result);
html += "<a href='" + filename + "'><i class='fa fa-shopping-cart'></i> </a>";
html += "<span class='number_cart'>" + result.length + "</span>";
$(".cart-item").html(html);
});
}
}
$(function(){
// var url = window.location.pathname;
// url = url.split("/");
// if(url.slice(-1).pop() != "/"){
// $(".slideshow").hide();
// }
// if(url.slice(-1).pop() != ""){
// $(".slideshow").hide();
// }
$('#search_product').keypress(function (e) {
var key = e.which;
if (key == 13) // the enter key code
{
$.ajax({
url: "sanpham/search_product",
type: "post",
dataType: "json",
data: {keyword: $('#search_product').val()}
}).done(function (result) {
console.log(result);
var html = "";
html += "<div class='list_product'>";
$.each(result, function (key, item) {
html += " <div class=\"col-xs-6 col-sm-4 col-md-3\">";
html += " <div class=\"thumbnail\">";
html += " <div class=\"img-product\">";
html += " <a href=\"" + item['alias'] + "\">";
html += " <img src=\"http:\/\/demo.com\/ci_giantshop\/public\/img\/product\/" + item['img'] + "\" alt=\"Hình ảnh sản phẩm\">";
html += " <\/a>";
html += " <\/div>";
html += " <div class=\"caption\">";
html += " <div class=\"item-title\">";
html += " <a href=\"" + item['alias'] + "\">";
html += " <h3>" + item['name'] + "<\/h3>";
html += " <\/a>";
html += " <\/div>";
html += " <div class=\"item-content\">";
html += " <p>";
html += " <span>" + item['price_sale'] + "<sup><u>đ<\/u><\/sup><\/span> <span class=\"is_sale\">" + item['price'] + "<sup><u>đ<\/u><\/sup><\/span><\/p>";
html += " <\/div>";
html += " <\/div>";
html += " <div class=\"bg_hidden\">";
html += " <a href=\"" + item['alias'] + "\" class=\"over_bg\"><\/a>";
html += " <a href=\"javascript:void(0)\" onclick=\"dat_mua('" + item['id'] + "')\" class=\"btn btn-primary dat_mua\">Đặt mua<\/a>";
html += " <\/div>";
html += " <\/div>";
html += " <\/div>";
});
html += " <\/div>";
$(".list_product").html(html);
});
}
});
$(".nav.navbar-nav.target-active ul li").click(function () {
$("nav.navbar-nav.target-active ul li").removeClass("active");
$(this).addClass("active");
});
$(".gui_email_nhan_tin").click(function () {
var email = "";
email = $(".form-subcribe input[type=email]").val();
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email == "") {
alert("Vui lòng nhập email!");
}
else if (!re.test(email)) {
alert("Vui lòng nhập lại email!");
} else {
$.ajax({
url: "trangchu/signup_email",
type: "post",
dataType: "text",
data: {email: email}
}).done(function (result) {
if (result == "1") {
alert("Đăng ký nhận tin thành công!");
}
else {
alert("Không thành công!");
}
});
$(".form-subcribe input[type=email]").val("");
}
;
});
$(".btnLogin").click(function () {
var user = "", pass = "";
user = $("input[name=username]").val();
pass = $("input[name=password]").val();
if (user == "" || pass == "") {
alert("Vui lòng nhập tài khoản!");
}
else {
$.ajax({
url: "trangchu/sign_in",
type: "post",
dataType: "text",
data: {user: user, pass: pass}
}).done(function (result) {
if (result == "1") {
alert("Đăng nhập thành công!");
location.reload();
}
else {
alert("Tài khoản hoặc mật khẩu không đúng!");
}
});
}
});
});
| 41.171642 | 200 | 0.342577 |
9385ac5a26d593679f33961fc1a4969d35797ea9 | 11,931 | js | JavaScript | src/plugin/featureaction/featureactionmanager.js | bcleveland1022/opensphere | 6a8b792f7ec5bfd4d85159c3f06e54cc06805df7 | [
"Apache-2.0"
] | null | null | null | src/plugin/featureaction/featureactionmanager.js | bcleveland1022/opensphere | 6a8b792f7ec5bfd4d85159c3f06e54cc06805df7 | [
"Apache-2.0"
] | null | null | null | src/plugin/featureaction/featureactionmanager.js | bcleveland1022/opensphere | 6a8b792f7ec5bfd4d85159c3f06e54cc06805df7 | [
"Apache-2.0"
] | null | null | null | goog.provide('plugin.im.action.feature.Manager');
goog.require('goog.Timer');
goog.require('goog.log');
goog.require('goog.object');
goog.require('ol.events');
goog.require('os.data.OSDataManager');
goog.require('os.data.event.DataEventType');
goog.require('os.im.action.ImportActionCallbackConfig');
goog.require('os.im.action.ImportActionManager');
goog.require('os.implements');
goog.require('os.layer.preset.LayerPresetManager');
goog.require('os.source.IImportSource');
goog.require('plugin.im.action.feature');
goog.require('plugin.im.action.feature.Entry');
/**
* Manager for {@link ol.Feature} import actions.
*
* @extends {os.im.action.ImportActionManager<ol.Feature>}
* @constructor
*/
plugin.im.action.feature.Manager = function() {
plugin.im.action.feature.Manager.base(this, 'constructor');
this.entryTitle = plugin.im.action.feature.ENTRY_TITLE;
this.log = plugin.im.action.feature.Manager.LOGGER_;
this.xmlGroup = plugin.im.action.feature.TagName.FEATURE_ACTIONS;
this.xmlEntry = plugin.im.action.feature.TagName.FEATURE_ACTION;
/**
* Map of source listen keys.
* @type {!Object<string, ol.EventsKey>}
* @private
*/
this.sourceListeners_ = {};
/**
* Timer for periodically updating time-based feature actions.
* @type {goog.Timer}
* @private
*/
this.timer_ = new goog.Timer(15000);
this.timer_.listen(goog.Timer.TICK, this.refreshTimeEntries, false, this);
this.timer_.start();
};
goog.inherits(plugin.im.action.feature.Manager, os.im.action.ImportActionManager);
goog.addSingletonGetter(plugin.im.action.feature.Manager);
// replace the base ImportActionManager singleton with this one
Object.assign(os.im.action.ImportActionManager, {
getInstance: function() {
return plugin.im.action.feature.Manager.getInstance();
}
});
/**
* Logger for plugin.im.action.feature.Manager.
* @type {goog.log.Logger}
* @private
* @const
*/
plugin.im.action.feature.Manager.LOGGER_ = goog.log.getLogger('plugin.im.action.feature.Manager');
/**
* @type {number}
* @const
*/
plugin.im.action.feature.Manager.MIN_ITEMS_MERGE_NOTIFY_COLOR = 10000;
/**
* @inheritDoc
*/
plugin.im.action.feature.Manager.prototype.disposeInternal = function() {
plugin.im.action.feature.Manager.base(this, 'disposeInternal');
goog.dispose(this.timer_);
var dm = os.data.OSDataManager.getInstance();
if (dm) {
dm.unlisten(os.data.event.DataEventType.SOURCE_ADDED, this.onSourceAdded_, false, this);
dm.unlisten(os.data.event.DataEventType.SOURCE_REMOVED, this.onSourceRemoved_, false, this);
}
for (var key in this.sourceListeners_) {
ol.events.unlistenByKey(this.sourceListeners_[key]);
}
this.sourceListeners_ = {};
};
/**
* @inheritDoc
*/
plugin.im.action.feature.Manager.prototype.createActionEntry = function() {
return new plugin.im.action.feature.Entry();
};
/**
* @inheritDoc
*/
plugin.im.action.feature.Manager.prototype.getEntryItems = function(type) {
var source = os.data.OSDataManager.getInstance().getSource(type);
return source ? source.getFeatures() : null;
};
/**
* @inheritDoc
*/
plugin.im.action.feature.Manager.prototype.initialize = function() {
var dm = os.data.OSDataManager.getInstance();
dm.listen(os.data.event.DataEventType.SOURCE_ADDED, this.onSourceAdded_, false, this);
dm.listen(os.data.event.DataEventType.SOURCE_REMOVED, this.onSourceRemoved_, false, this);
var sources = dm.getSources();
for (var i = 0, n = sources.length; i < n; i++) {
this.addSource_(sources[i]);
}
};
/**
* @inheritDoc
*/
plugin.im.action.feature.Manager.prototype.processItemsProtected = function(
entryType,
items,
opt_unprocess,
opt_unprocessOnly) {
// run the actions normally
var configs = plugin.im.action.feature.Manager.base(
this,
'processItemsProtected',
entryType,
items,
opt_unprocess,
opt_unprocessOnly);
// notify
if (configs && configs.length) {
// once all processItems() are done, do a big notify of style and color changes
var config = /* @type {os.im.action.ImportActionCallbackConfig} */ ({
color: [],
labelUpdateShown: false,
notifyStyleChange: false,
setColor: false,
setFeaturesStyle: false
});
// merge the layer, source, colormodel, and label events into one
configs.forEach((cfg) => {
plugin.im.action.feature.Manager.mergeNotify_(config, cfg);
});
// optimize the colors to avoid overlaps (max N instead of N^2 events)
plugin.im.action.feature.Manager.mergeNotifyColor_(config);
// send events to synch with renderer and bins
plugin.im.action.feature.Manager.notify_(items, config);
}
};
/**
* Consolidate results of desired notification(s) from multiple FeatureActions
*
* @param {os.im.action.ImportActionCallbackConfig} target
* @param {os.im.action.ImportActionCallbackConfig} source
* @private
*/
plugin.im.action.feature.Manager.mergeNotify_ = function(target, source) {
if (!target) return;
if (source) {
target.labelUpdateShown = target.labelUpdateShown || source.labelUpdateShown;
target.notifyStyleChange = target.notifyStyleChange || source.notifyStyleChange;
target.setColor = target.setColor || source.setColor;
target.setFeaturesStyle = target.setFeaturesStyle || source.setFeaturesStyle;
if (source.color) {
// add the next colors
source.color.forEach((color) => {
if (!target.color) target.color = [];
// TODO merge same-colors into a single color entry
target.color.push(color); // flatten the tree
});
}
}
};
/**
* Optimize the colors to avoid overlaps (max N instead of N^2 events)
*
* @param {os.im.action.ImportActionCallbackConfig} config
* @suppress {accessControls} To allow direct access to feature metadata.
* @private
*/
plugin.im.action.feature.Manager.mergeNotifyColor_ = function(config) {
// TODO benchmark which is faster -- removing overlaps or just re-setting them when there's 25%...100% overlap
var len = (config && config.color) ? config.color.length : -1;
// only do this extra step when there are more than one (possibly conflicting) color actions
if (len > 1) {
var colorItemsCount = config.color.reduce((count, colorConfig) => {
return count + ((colorConfig[0]) ? colorConfig[0].length : 0);
}, 0);
// deconflicting is expensive; only do it when there are more than N items being colored
if (colorItemsCount > plugin.im.action.feature.Manager.MIN_ITEMS_MERGE_NOTIFY_COLOR) {
// the item(s) whose final color is already set
var all = {};
// loop backwards through colors... and remove items overlap in previous entries (last one wins)
for (var i = (len - 1); i >= 0; i--) {
var ids = {};
var [items] = config.color[i] || [];
// map the array by ids
if (i > 0) { // skip when no more loops to do
(items || []).reduce((map, item) => {
map[item.id_] = true;
return map;
}, ids);
}
// remove all's ids from these items
if (i != (len - 1)) { // skip when "all" is empty
config.color[i][0] = items.filter((item) => {
return !all[item.id_]; // fast lookup
});
}
// add these ids to all so they'll be filtered from prior color assignments
if (i > 0) { // skip when no more loops to do
for (var key in ids) { // for...in is faster than Object.assign(all, ids);
all[key] = true;
}
}
}
}
}
};
/**
* Send style event(s) to Layer, Source, and ColorModel
*
* @param {Array<T>} items The items.
* @param {os.im.action.ImportActionCallbackConfig} config
* @template T
* @private
*/
plugin.im.action.feature.Manager.notify_ = function(items, config) {
if (config) {
if (config.setFeaturesStyle) {
os.style.setFeaturesStyle(items);
}
// notify that the layer needs to be updated
var layer = os.feature.getLayer(items[0]);
if (layer) {
var source = /** @type {os.source.Vector} */ (layer.getSource());
if (source && config.setColor && config.color && config.color.length > 0) {
var colors = (config.color != null) ? config.color : []; // useless assign to get past the closure compiler
colors.forEach(([coloritems, color]) => {
if (color) {
source.setColor(coloritems, color); // set the color model's override for these items
} else {
source.setColor(coloritems); // only reset the color if there was a color override
}
});
}
if (config.notifyStyleChange) {
os.style.notifyStyleChange(
layer,
items,
undefined,
undefined,
!!(source && config.setColor) // bump the colormodel so dependencies can update/re-render
);
}
}
}
// kick off label hit detection
if (config.labelUpdateShown) {
os.style.label.updateShown();
}
};
/**
* Add a source to manager if it supports import actions.
*
* @param {os.source.ISource} source The source.
* @private
*/
plugin.im.action.feature.Manager.prototype.addSource_ = function(source) {
if (os.implements(source, os.source.IImportSource.ID)) {
var id = source.getId();
if (id && !this.sourceListeners_[id]) {
this.sourceListeners_[id] = ol.events.listen(/** @type {ol.events.EventTarget} */ (source),
goog.events.EventType.PROPERTYCHANGE, this.onSourcePropertyChange_, this);
var promise = os.layer.preset.LayerPresetManager.getInstance().getPresets(id, true);
if (promise) {
promise.thenAlways(() => {
this.processItems(id);
});
} else {
this.processItems(id);
}
}
}
};
/**
* Handle source added event from the data manager.
*
* @param {os.data.event.DataEvent} event The data manager event.
* @private
*/
plugin.im.action.feature.Manager.prototype.onSourceAdded_ = function(event) {
if (event && event.source) {
this.addSource_(event.source);
}
};
/**
* Handle source removed event from the data manager.
*
* @param {os.data.event.DataEvent} event
* @private
*/
plugin.im.action.feature.Manager.prototype.onSourceRemoved_ = function(event) {
if (event && event.source) {
var id = event.source.getId();
if (id in this.sourceListeners_) {
ol.events.unlistenByKey(this.sourceListeners_[id]);
delete this.sourceListeners_[id];
}
}
};
/**
* Handle property change events from a source.
*
* @param {os.events.PropertyChangeEvent|ol.Object.Event} event
* @private
*/
plugin.im.action.feature.Manager.prototype.onSourcePropertyChange_ = function(event) {
var p;
try {
// ol.ObjectEventType.PROPERTYCHANGE is the same as goog.events.EventType.PROPERTYCHANGE, so make sure the
// event is from us
p = event.getProperty();
} catch (e) {
return;
}
var source = /** @type {os.source.ISource} */ (event.target);
if (source) {
switch (p) {
case os.source.PropertyChange.PREPROCESS_FEATURES:
var features = /** @type {Array<!ol.Feature>|undefined} */ (event.getNewValue());
if (features && features.length > 0) {
this.processItems(source.getId(), features);
}
break;
default:
break;
}
}
};
/**
* Refreshes the time-based feature actions.
*
* @protected
*/
plugin.im.action.feature.Manager.prototype.refreshTimeEntries = function() {
var entries = this.getActionEntries();
var fn = function(entry) {
if (entry.isEnabled()) {
var filter = entry.getFilter();
if (filter && filter.indexOf(os.data.RecordField.TIME) != -1) {
this.updateItems(entry.type);
}
}
var children = entry.getChildren();
if (children) {
children.forEach(fn, this);
}
};
entries.forEach(fn, this);
};
| 29.029197 | 115 | 0.658034 |
9386eecb52cd7f0e060fb8dc44ad0e8ffe104fd3 | 35,401 | js | JavaScript | storefront/store/global.js | vgrdominik/tpg | ec0e6e05ef63b71e10b3e94363887fb44088bd59 | [
"MIT"
] | 1 | 2020-04-19T07:42:34.000Z | 2020-04-19T07:42:34.000Z | storefront/store/global.js | vgrdominik/tpg | ec0e6e05ef63b71e10b3e94363887fb44088bd59 | [
"MIT"
] | 5 | 2020-04-15T23:01:26.000Z | 2022-02-27T02:43:37.000Z | storefront/store/global.js | vgrdominik/tpg | ec0e6e05ef63b71e10b3e94363887fb44088bd59 | [
"MIT"
] | null | null | null | export const state = () => ({
is_container_needed: '',
date_format: new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}),
// miliseconds
time_to_sync: 8000,
default_time_to_sync: 8000,
config: {
initialized: false,
tax_identification: {
tax_name: null,
tax_identification: null,
address: null,
postal_code: null,
city: null,
province: null
},
branding: {
color_palette: {
primary: '#267699',
secondary: '#70B0CC',
accent: '#FF877A',
success: '#4CAF50',
error: '#FF5252',
warning: '#FFC107',
info: '#D19BA3'
},
style: {
button: 'text',
form: 'outlined',
card: 'shaped',
dialog_card: 'shaped'
}
},
customers: false,
turns: false,
layout_tpv: {
distribution: '1-2x2'
},
// Default config data. Updated by stored file config
config_tpv: {
// Actions
action: {
maximize: true,
open_money: false,
exit: true,
refresh: true,
alerts: true
},
// Ticket List
ticket: {
show_closed: true,
closed_number: 10,
name: false,
check: false,
collect: true,
collect_direct: true,
send_custom: true,
delete: true
},
// Ticket Opened
ticket_opened: {
save: false,
close: false,
save_close: true,
total_price: true,
send: true,
delete: true
},
// Ticket Opened - Customer
ticket_opened_customer: {
unfolded: false,
link: true,
update: true,
temporary_discount_product: true,
temporary_discount_pay_soon: true,
temporary_discount_customer: true,
temporary_apply_zone_tax: false,
temporary_apply_equivalence_surcharge: false,
temporary_apply_irpf: false,
temporary_apply_rate: '1',
temporary_save: true
},
// Ticket - Lines
ticket_line: {
discount: true,
unit_price: true,
unit: true,
total_price: true,
complements: true,
delete: true,
send: false
},
// Families
family: {
image: true,
image_size: 'md',
text: true,
text_size: 'md'
},
// Feature
feature: {
text_size: 'md'
},
// Quantities
quantities: {
unfolded: false,
linear: true
},
// Search
search: {
show: true
},
// Product List
product: {
show_price: false,
image: true,
image_size: 'md',
text: true,
text_size: 'md'
},
// Barcode
barcode: {
show: false
},
// Dining rooms
dining_room: {
show: false
}
},
// Turns
config_turns: {
text_size: 'md',
description: true
},
// SMTP
smtp: {
host: '',
user: '',
password: '',
port: '587',
type_encryption: 'TLS',
email_equal_user: true,
email: '',
email_password_equal_user: true,
email_password: ''
},
// Directories
data_dir: { name: 'data', path: 'app://data' }, // default -> { name: 'data', path: 'app://./data' }
import_dir: { name: 'import_data', path: 'app://import_data' }, // default -> { name: 'import_data', path: 'app://./import_data' }
// Import
import: {
type: 'json', // Currently only support json.
domain: {
product: {
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'id_taxonomy',
type: 'int'
},
{
name: 'iva',
type: 'float'
},
{
name: 'ids_send_to',
type: 'array'
},
{
name: 'name',
type: 'string'
},
{
name: 'cost',
type: 'float'
},
{
name: 'base',
type: 'float'
},
{
name: 'total',
type: 'float'
},
{
name: 'reference',
type: 'string'
},
{
name: 'complement_unique',
type: 'boolean'
},
{
name: 'complement_show',
type: 'boolean'
},
{
name: 'complement_ids_available',
type: 'string'
},
{
name: 'complement_price',
type: 'float'
},
{
name: 'complement_text_tpv',
type: 'string'
},
{
name: 'complement_taxonomy',
type: 'string'
},
{
name: 'complement_enabled',
type: 'boolean'
},
{
name: 'enabled',
type: 'boolean'
},
{
name: 'img',
type: 'string'
},
{
name: 'text_tpv',
type: 'string'
}
],
columns: [
'page',
'limit',
'pages',
'total',
'_links',
'_links.self',
'_links.first',
'_links.last',
'_links.next',
'items.code',
'items.name',
'items.taxRateAmount',
'items.slug',
'items.channelCode',
'items.averageRating',
'items.taxons.main',
'items.taxons.others[]',
'items.variants',
'items.variants.code',
'items.variants.axis[]',
'items.variants.nameAxis',
'items.variants.price',
'items.variants.price.current',
'items.variants.price.currency',
'items.variants.originalPrice',
'items.variants.originalPrice.current',
'items.variants.originalPrice.currency',
'items.variants.images',
'items.attributes[]',
'items.associations[]',
'items.images[]',
'items._links',
'items._links.self',
'items._links.self.href'
],
fields_columns: {
id: 'code',
id_taxonomy: 'taxons.main',
iva: 'taxRateAmount',
ids_send_to: null,
name: 'name',
cost: 'variants[id].originalPrice.current',
base: null,
total: 'variants[id].price.current',
reference: 'slug',
complement_unique: null,
complement_ids_available: null,
complement_price: null,
complement_text_tpv: null,
complement_taxonomy: null,
complement_enabled: null,
enabled: null,
// img: 'images[]',
img: null,
text_tpv: 'name'
}
},
family: {
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'img',
type: 'string'
},
{
name: 'text_tpv',
type: 'string'
}
],
columns: [
'code',
'name',
'slug',
'description',
'position',
'images[]',
'children[]'
],
fields_columns: {
id: 'code',
// img: 'images[]',
img: null,
text_tpv: 'name'
}
},
ticket: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'id_customer', type: 'int' },
{ name: 'id_user', type: 'int' },
{ name: 'id_terminal', type: 'int' },
{ name: 'id_turn', type: 'int' },
// Payment parameters
{ name: 'number', type: 'int' },
{ name: 'irpf', type: 'float' },
{ name: 'method_payment', type: 'string' },
{ name: 'discount_prompt_payment', type: 'float' },
{ name: 'discount_customer', type: 'float' },
{ name: 'total', type: 'float' },
// Number of customers related with ticket
{ name: 'diners', type: 'int' },
// pending, paid_check, paid
{ name: 'state', type: 'string' },
{ name: 'create_date', type: 'Date' },
{ name: 'update_date', type: 'Date' }
],
columns: [
'id',
'client',
'fecha',
'numero_document',
'irpf',
'forma_pagament',
'total',
'descompte_pp',
'descompte_client',
'estat',
'usuari',
'comensales',
'hora',
'id_terminal',
'id_turno'
],
fields_columns: {
id: 'id',
id_customer: 'client',
id_user: 'usuari',
id_terminal: 'id_terminal',
id_turn: 'id_turno',
// Payment parameters
number: 'numero_document',
irpf: 'irpf',
method_payment: 'forma_pagament',
discount_prompt_payment: 'descompte_pp',
discount_customer: 'descompte_client',
total: 'total',
// Number of customers related with ticket
diners: 'comensales',
// pending, paid_check, paid
state: 'estat',
create_date: 'fecha',
update_date: null
}
},
ticket_line: {
fields: [
{ name: 'id_ticket', type: 'int' },
{ name: 'id_ticket_line', type: 'int' },
{ name: 'id_attribute', type: 'int' },
{ name: 'id_user', type: 'int' },
// Used to determine with fields and how show
{ name: 'type', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'quantity', type: 'float' },
{ name: 'serial_number', type: 'string' }, // Technological identifier
{ name: 'lot', type: 'string' }, // Nutrition identifier
{ name: 'expiration', type: 'string' }, // It's a informative date
{ name: 'cost', type: 'float' },
{ name: 'price', type: 'float' },
{ name: 'iva', type: 'float' },
{ name: 'surcharge', type: 'float' },
{ name: 'discount', type: 'float' },
{ name: 'reference', type: 'string' },
{ name: 'reference_customer', type: 'string' },
{ name: 'create_date', type: 'Date' },
{ name: 'update_date', type: 'Date' }
],
columns: [
'id_document',
'descripcio_article',
'grup',
'element',
'quantitat',
'numero_serie',
'lot',
'caducitat',
'preu',
'descompte',
'tipo_article',
'preu_fixe',
'referencia_article',
'referencia_client',
'formato',
'iva',
'ordre_entrada',
'recarrec',
'fecha',
'usuari',
'venedor',
'compta'
],
fields_columns: {
id_ticket: 'id_document',
id_ticket_line: 'ordre_entrada',
id_attribute: null,
id_user: 'usuari',
// Used to determine with fields and how show
type: 'tipo_article',
description: 'descripcio_article',
quantity: 'quantitat',
serial_number: 'numero_serie', // Technological identifier
lot: 'lot', // Nutrition identifier
expiration: 'caducitat', // It's a informative date
cost: 'preu_fixe',
price: 'preu',
iva: 'iva',
surcharge: 'recarrec',
discount: 'descompte',
reference: 'referencia_article',
reference_customer: 'referencia_client',
create_date: 'fecha',
update_date: null
}
},
ticket_complement: {
fields: [
{ name: 'id_ticket_line', type: 'int' },
{ name: 'id_complement', type: 'int' },
// Same structure as ticket_line
{ name: 'description', type: 'string' },
{ name: 'quantity', type: 'float' },
{ name: 'serial_number', type: 'string' }, // Technological identifier
{ name: 'lot', type: 'string' }, // Nutrition identifier
{ name: 'expiration', type: 'string' }, // It's a informative date
{ name: 'cost', type: 'float' },
{ name: 'price', type: 'float' },
{ name: 'iva', type: 'float' },
{ name: 'surcharge', type: 'float' },
{ name: 'discount', type: 'float' },
{ name: 'reference', type: 'string' },
{ name: 'reference_customer', type: 'string' },
{ name: 'create_date', type: 'Date' },
{ name: 'update_date', type: 'Date' }
],
columns: [
'id',
'id_linea',
'quantitat',
'complemento',
'iva',
'import'
],
fields_columns: {
id_ticket_line: 'id_linea',
id_complement: 'id',
// Same structure as ticket_line
description: 'complemento',
quantity: 'quantitat',
serial_number: null, // Technological identifier
lot: null, // Nutrition identifier
expiration: null, // It's a informative date
cost: null,
price: 'import',
iva: 'iva',
surcharge: null,
discount: null,
reference: null,
reference_customer: null,
create_date: 'fecha',
update_date: null
}
},
ticket_receipt: {
fields: [
{ name: 'id_ticket', type: 'int' },
// receipt
{ name: 'id', type: 'int' },
{ name: 'id_invoice', type: 'int' },
{ name: 'id_user', type: 'int' },
{ name: 'id_income_account', type: 'int' },
{ name: 'number', type: 'int' },
{ name: 'collection_method', type: 'string' }, // cash, card, transfer, paypal, bizum, other
{ name: 'paid', type: 'float' }, // Float/Boolean
{ name: 'total', type: 'float' },
{ name: 'paid_date', type: 'Date' },
{ name: 'expiration_date', type: 'Date' },
{ name: 'create_date', type: 'Date' },
{ name: 'update_date', type: 'Date' }
],
columns: [
'codi',
'codi_factura',
'empresa',
'import',
'fecha',
'venciment',
'client',
'cobrat',
'fecha_cobro',
'codi_compte_ingres',
'modalitat_cobro',
'numero_efecte',
'usuari',
'tancat',
'caixa',
'id_torn'
],
fields_columns: {
id_ticket: 'codi_factura',
id: 'codi',
id_invoice: 'codi_factura',
id_user: 'usuari',
id_income_account: 'codi_compte_ingres',
number: 'numero_efecte',
collection_method: 'modalitat_cobro', // cash, card, transfer, paypal, bizum, other
paid: 'cobrat', // Float/Boolean
total: 'import',
paid_date: 'fecha_cobro',
expiration_date: 'venciment',
create_date: 'fecha',
update_date: null
}
},
customer: {
fields: [
{
label: 'Código',
description: 'Identificador único del cliente.',
modifiable: false,
name: 'id',
type: 'int'
},
{
label: 'Iva',
description: 'Impuesto sobre el valor añadido por defecto.',
modifiable: true,
name: 'iva',
type: 'float'
},
{
label: 'Irpf',
description:
'Impuesto sobre la renta de las personas físicas por defecto.',
modifiable: true,
name: 'irpf',
type: 'float'
},
{
label: 'Nombre comercial',
description: 'Nombre comercial del cliente.',
modifiable: true,
name: 'corporation_name',
type: 'string'
},
{
label: 'Nombre interno',
description: 'Nombre interno de la empresa.',
modifiable: true,
name: 'name',
type: 'string'
},
{
label: 'Nombre fiscal',
description: 'Nombre en terminos fiscales del cliente.',
modifiable: true,
name: 'taxonomy_name',
type: 'string'
},
{
label: 'Identificación fiscal',
description: 'Identificación fiscal del cliente.',
modifiable: true,
name: 'taxonomy_identification',
type: 'string'
},
{
label: 'Observaciones',
description: 'Observaciones internas de la empresa.',
modifiable: true,
name: 'observations',
type: 'string'
},
{
label: 'Texto TPV',
description: 'Texto que va a salir en el TPV.',
modifiable: true,
name: 'text_tpv',
type: 'string'
},
{
label: 'Imagen',
description: 'Imagen o logo del cliente.',
modifiable: true,
name: 'img',
type: 'string'
},
{
label: 'Imagen secundaria',
description:
'Imagen usada cuando el cliente está en el local o activo de alguna forma.',
modifiable: true,
name: 'img_secondary',
type: 'string'
},
{
label: 'Referencia',
description: 'Referencia interna y/o externa del cliente.',
modifiable: true,
name: 'reference',
type: 'string'
},
{
label: 'Género',
description:
'Género del cliente. Se pide un uso especialmente responsable de este dato.',
modifiable: true,
name: 'gender',
type: 'string'
},
{
label: 'Origen',
description:
'Cómo ha conocido la empresa el cliente. Se pide un uso especialmente responsable de este dato.',
modifiable: true,
name: 'origin',
type: 'string'
},
{
label: 'Tarjeta de la seguridad social',
description:
'Tarjeta de la seguridad social del cliente. Se pide un uso especialmente responsable de este dato.',
modifiable: true,
name: 'social_security_card',
type: 'string'
},
{
label: 'Importe de la pensión',
description:
'Importe de la pensail del cliente. Se pide un uso especialmente responsable de este dato.',
modifiable: true,
name: 'pension_amount',
type: 'float'
},
{
label: 'Dirección',
description: 'Dirección del cliente.',
modifiable: true,
name: 'address',
type: 'string'
},
{
label: 'Código Postal',
description: 'Código Postal del cliente.',
modifiable: true,
name: 'postal_code',
type: 'string'
},
{
label: 'Pueblo/Ciudad',
description: 'Pueblo o ciudad del cliente.',
modifiable: true,
name: 'town',
type: 'string'
},
{
label: 'Provincia/Estado',
description: 'Provincia o estado del cliente.',
modifiable: true,
name: 'state',
type: 'string'
},
{
label: 'Nombre de contacto',
description: 'Nombre para el contacto con el cliente.',
modifiable: true,
name: 'contact_name',
type: 'string'
},
{
label: 'Teléfono',
description: 'Teléfono del cliente.',
modifiable: true,
name: 'phone',
type: 'string'
},
{
label: 'Teléfono secundario',
description: 'Teléfono secundario del cliente.',
modifiable: true,
name: 'phone2',
type: 'string'
},
{
label: 'Fax',
description: 'Fax del cliente',
modifiable: true,
name: 'fax',
type: 'string'
},
{
label: 'Móvil',
description: 'Móvil del cliente',
modifiable: true,
name: 'mobile',
type: 'string'
},
{
label: 'Correo electrónico',
description: 'Correo electrónico del cliente',
modifiable: true,
name: 'email',
type: 'string'
},
{
label: 'Notificaciones habilitadas',
description: 'Notificaciones para el cliente habilitadas',
modifiable: true,
name: 'notifications_enabled',
type: 'boolean'
},
{
label: 'Notificaciones básicas habilitadas',
description: 'Notificaciones básicas para el cliente habilitadas',
modifiable: true,
name: 'notifications_basic_enabled',
type: 'boolean'
},
{
label: 'Notificaciones publicitarias habilitadas',
description:
'Notificaciones publicitarias para el cliente habilitadas',
modifiable: true,
name: 'notifications_publicity_enabled',
type: 'boolean'
},
{
label: 'Otras notificaciones habilitadas',
description: 'Otras notificaciones para el cliente habilitadas',
modifiable: true,
name: 'notifications_others_enabled',
type: 'boolean'
},
{
label: 'Categoría para SMS',
description:
'Categorización para el envío de sms para el cliente',
modifiable: true,
name: 'taxonomy_sms',
type: 'int'
},
{
label: 'Categoría para EMAIL',
description:
'Categorización para el envío de correos electrónicos para el cliente',
modifiable: true,
name: 'taxonomy_email',
type: 'int'
},
{
label: 'Puntos',
description: 'Puntos de fidelización del cliente',
modifiable: true,
name: 'points',
type: 'int'
},
{
label: 'Nivel',
description: 'Nivel de fidelización del cliente',
modifiable: true,
name: 'level',
type: 'int'
},
{
label: 'Periodicidad',
description: 'Periodicidad por defecto del cliente',
modifiable: true,
name: 'periodicity',
type: 'string'
},
{
label: 'Cuenta de cargos',
description: 'Cuenta donde se carga el importe de los tíquets',
modifiable: true,
name: 'account_charge',
type: 'string'
},
{
label: 'Tarifa',
description: 'Tarifa por defecto del cliente',
modifiable: true,
name: 'rate',
type: 'string'
},
{
label: 'Recargo',
description: 'Aplicación del recargo por defecto en los tíquets',
modifiable: true,
name: 'surcharge',
type: 'boolean'
},
{
label: 'Código contable',
description: 'Código contable del cliente',
modifiable: true,
name: 'countable_code',
type: 'string'
},
{
label: 'Día de pago',
description: 'Día de pago del cliente',
modifiable: true,
name: 'payment_day',
type: 'string'
},
{
label: 'Día de pago 2',
description: 'Segundo día de pago del cliente',
modifiable: true,
name: 'payment_day2',
type: 'string'
},
{
label: 'Banco de la cuenta',
description: 'Banco de la cuenta del cliente',
modifiable: true,
name: 'payment_bank',
type: 'int'
},
{
label: 'Entidad bancaria de la cuenta',
description: 'Entidad bancaria de la cuenta del cliente',
modifiable: true,
name: 'payment_entity',
type: 'int'
},
{
label: 'Agencia de la cuenta',
description: 'Agencia de la cuenta del cliente',
modifiable: true,
name: 'payment_agency',
type: 'int'
},
{
label: 'Dígito de control de la cuenta',
description: 'Dígito de control de la cuenta del cliente',
modifiable: true,
name: 'payment_control_digit',
type: 'int'
},
{
label: 'Número de la cuenta',
description: 'Número de la cuenta del cliente',
modifiable: true,
name: 'payment_account',
type: 'int'
},
{
label: 'Método de pago',
description: 'Método de pago del cliente por defecto',
modifiable: true,
name: 'payment_method',
type: 'string'
},
{
label: 'Descuento de tíquet',
description: 'Descuento en los tíquets por defecto',
modifiable: true,
name: 'discount_document',
type: 'float'
},
{
label: 'Descuento de producto',
description: 'Descuento en los productos por defecto',
modifiable: true,
name: 'discount_product',
type: 'float'
},
{
label: 'Descuento pronto pago',
description: 'Descuento de pronto pago por defecto',
modifiable: true,
name: 'discount_prompt_payment',
type: 'float'
},
{
label: 'Comensales',
description: 'Comensales que representa el cliente por defecto',
modifiable: true,
name: 'diners',
type: 'int'
},
{
label: 'Identificador de mesa',
description: 'Identificador de mesa del cliente',
modifiable: true,
name: 'table_id',
type: 'int'
},
{
label: 'Mesa en uso',
description: 'Valor por defecto de mesa en uso',
modifiable: true,
name: 'table_in_use',
type: 'boolean'
},
{
label: 'Identificador del comedor',
description: 'Identificador del comedor por defecto',
modifiable: true,
name: 'dinning_room_id',
type: 'int'
},
{
label: 'Habilitado',
description: 'Indica si el cliente está habilitado',
modifiable: true,
name: 'enabled',
type: 'boolean'
},
{
label: 'Identificador del creador',
description: 'Identificación del usuario que lo creó',
modifiable: true,
name: 'creator_user_id',
type: 'int'
},
{
label: 'Identificador del modificador',
description:
'Identificador del último usuario que lo ha modificado',
modifiable: true,
name: 'update_user_id',
type: 'int'
},
{
label: 'Identificador del vendedor',
description:
'Identificador del usuario que atiende al cliente por defecto',
modifiable: true,
name: 'seller_user_id',
type: 'int'
},
{
label: 'Fecha de nacimiento',
description: 'Fecha de nacimiento del cliente',
modifiable: true,
name: 'birthday_date',
type: 'Date'
},
{
label: 'Fecha de creación',
description: 'Fecha de creación del cliente',
modifiable: true,
name: 'create_date',
type: 'Date'
},
{
label: 'Fecha de eliminación',
description: 'Fecha de eliminación del cliente',
modifiable: true,
name: 'drop_date',
type: 'Date'
},
{
label: 'Fecha de modificación',
description: 'Fecha de modificación',
modifiable: true,
name: 'update_date',
type: 'Date'
}
],
columns: [
'id',
'email',
'birthday',
'emailCanonical',
'firstName',
'gender',
'lastName'
],
fields_columns: {
id: 'id',
iva: null,
irpf: null,
corporation_name: null,
name: 'firstName',
taxonomy_name: null,
taxonomy_identification: null,
observations: null,
address: null,
postal_code: null,
town: null,
state: null,
contact_name: null,
phone: null,
phone2: null,
fax: null,
mobile: null,
email: 'email',
notifications_enabled: null,
notifications_basic_enabled: null,
notifications_publicity_enabled: null,
notifications_others_enabled: null,
taxonomy_sms: null,
taxonomy_email: null,
discount_prompt_payment: null,
discount_product: null,
discount_document: null,
payment_method: null,
payment_account: null,
payment_entity: null,
payment_bank: null,
payment_control_digit: null,
payment_agency: null,
payment_day: null,
payment_day2: null,
countable_code: null,
surcharge: null,
rate: null,
account_charge: null,
periodicity: null,
diners: null,
table_id: null,
dinning_room_id: null,
table_in_use: null,
origin: null, // procedencia
gender: null,
social_security_card: null, // seguretat_social
pension_amount: null,
birthday_date: 'birthday',
reference: null,
creator_user_id: null,
update_user_id: null,
seller_user_id: null,
img: null,
img_secondary: null, // Sample: used to dinning room when customers fill table
text_tpv: null,
points: null,
level: null,
enabled: null, // inactiu
create_date: null,
drop_date: null,
update_date: null
}
},
customer_search: {
fields: [
{ name: 'id_customer', type: 'int' },
{ name: 'corporation_name', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'taxonomy_name', type: 'string' },
{ name: 'taxonomy_identification', type: 'string' },
{ name: 'reference', type: 'string' }
],
columns: [
'id',
'email',
'birthday',
'emailCanonical',
'firstName',
'gender',
'lastName'
],
fields_columns: {
id_customer: 'id',
corporation_name: null,
name: 'firstName',
taxonomy_name: null,
taxonomy_identification: null,
reference: null
}
}
}
}
}
})
export const actions = {
setIsContainerNeeded(state, is_container_needed) {
state.commit('updateIsContainerNeeded', is_container_needed)
},
setConfig(state, payload) {
state.commit('updateConfigValue', payload)
},
setConfigComplete(state, payload) {
state.commit('updateConfigComplete', payload)
},
setTimeToSync(state, payload) {
state.commit('updateTimeToSync', payload)
}
}
export const mutations = {
updateIsContainerNeeded(state, is_container_needed) {
state.is_container_needed = is_container_needed
},
updateConfigComplete(state, config) {
state.config = config
},
updateTimeToSync(state, time_to_sync) {
state.time_to_sync = time_to_sync
},
updateConfigValue(state, { path, value }) {
const pathStack = path.split('>')
let stateConfig = state.config
while (pathStack.length > 1) {
stateConfig = stateConfig[pathStack.shift()]
}
const elementToUpdate = pathStack.shift()
stateConfig[elementToUpdate] = value
}
}
| 28.572236 | 134 | 0.443349 |
9387e94e39e0bc9201d89af7889ee3906fe04a02 | 693 | js | JavaScript | src/components/Nav.js | wandji20/React-Calculator | 0113fb83466d01872969b714fcc6bd51b711286a | [
"MIT"
] | 5 | 2021-06-15T15:53:05.000Z | 2021-07-22T14:49:02.000Z | src/components/Nav.js | SarvarKh/React-Calculator-1 | 0113fb83466d01872969b714fcc6bd51b711286a | [
"MIT"
] | 2 | 2021-06-18T07:15:04.000Z | 2021-06-22T20:43:10.000Z | src/components/Nav.js | SarvarKh/React-Calculator-1 | 0113fb83466d01872969b714fcc6bd51b711286a | [
"MIT"
] | 1 | 2021-07-11T07:26:03.000Z | 2021-07-11T07:26:03.000Z | import React from 'react';
import { Link } from 'react-router-dom';
const Nav = () => {
const style = {
color: 'black',
textDecoration: 'none',
};
return (
<header>
<nav>
<Link style={style} to="/">
<h4>Math Magicians</h4>
</Link>
<ul>
<Link className="nav-link" to="/">
<li className="border">Home</li>
</Link>
<Link className="nav-link" to="./Calculator">
<li className="border">Calculator</li>
</Link>
<Link className="nav-link" to="/Quote">
<li>Quote</li>
</Link>
</ul>
</nav>
</header>
);
};
export default Nav;
| 21.65625 | 55 | 0.474747 |
93881fa69a8947de7759c1a43e98cee8e278b42c | 677 | js | JavaScript | src/components/kofi-widget.js | davidsharp/davidsharp.codes | d4883c45ce691e7c8916801d210a968ca7cddaaa | [
"MIT"
] | null | null | null | src/components/kofi-widget.js | davidsharp/davidsharp.codes | d4883c45ce691e7c8916801d210a968ca7cddaaa | [
"MIT"
] | null | null | null | src/components/kofi-widget.js | davidsharp/davidsharp.codes | d4883c45ce691e7c8916801d210a968ca7cddaaa | [
"MIT"
] | null | null | null | import React, {useEffect} from 'react';
export default function Kofi({name='davidsharp',text='Tip Me',backgroundColor='#fcbf47',textColor='#323842'}){
const widgetScript = (`console.log('Donate @ ko-fi.com/${name}')
kofiWidgetOverlay.draw('${name}', {
'type': 'floating-chat',
'floating-chat.donateButton.text': '${text}',
'floating-chat.donateButton.background-color': '${backgroundColor}',
'floating-chat.donateButton.text-color': '${textColor}'
});`)
useEffect(()=>fetch('https://storage.ko-fi.com/cdn/scripts/overlay-widget.js').then(response=>response.text()).then(script=>{
(new Function(`${script};${widgetScript}`))()
}))
return null
} | 42.3125 | 127 | 0.675037 |
93897696718635de1fcb765d9de2f9870eeadbc8 | 218 | js | JavaScript | public/javascripts/test.js | paulpod/protopod | 36600b9d041c7ab1873bb4bf5b9b06852dde2ddf | [
"MIT"
] | null | null | null | public/javascripts/test.js | paulpod/protopod | 36600b9d041c7ab1873bb4bf5b9b06852dde2ddf | [
"MIT"
] | 1 | 2019-06-09T14:29:08.000Z | 2019-06-18T20:25:40.000Z | node_modules/ideal-postcodes/test/test.js | paulpod/dartcharge | d1095be9da8cf9ed5cd40d8012383adda7c14328 | [
"MIT"
] | null | null | null | // Set API Key, currently set to service test user
var api_key = "ak_hkflvrgzDirR9aJW2qJuZKXi1UumW";
var client = require('../lib/index.js')(api_key);
require('./errors.js')(client);
require('./postcode.js')(client); | 31.142857 | 50 | 0.720183 |
938a6fafe6382a48a9e7a19991a1e9fd28f7a1a2 | 914 | js | JavaScript | server.js | tjcharm/RestingNode | b86e3e56fde77eb320f6c9bf1c2f0b8c8bbb27f2 | [
"MIT"
] | null | null | null | server.js | tjcharm/RestingNode | b86e3e56fde77eb320f6c9bf1c2f0b8c8bbb27f2 | [
"MIT"
] | 1 | 2020-08-15T19:05:42.000Z | 2020-08-15T19:05:42.000Z | server.js | tjcharm/RestingNode | b86e3e56fde77eb320f6c9bf1c2f0b8c8bbb27f2 | [
"MIT"
] | null | null | null | require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const server = express();
const database = mongoose.connection;
const dropBoxRouter = require("./routes/muterPoll/dropBoxs");
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
database.on("error", (error) => {
console.log(error);
});
database.once("open", () => {
console.log("connected to database");
});
server.use(express.json());
server.use((req, res, next) => {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.set(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
server.use("/dropBoxes", dropBoxRouter);
server.listen(process.env.PORT, () => {
console.log(`running at http://localhost:${process.env.PORT}`);
});
| 24.702703 | 65 | 0.677243 |
938b756d3d62b3e4c268d99c26916b09524ac1b7 | 253 | js | JavaScript | pi-dab-projects.config.js | mlenkeit/up-pi-pm2 | 1a1d1f47481c90fd96064e0b6857fe52e132fcd7 | [
"MIT"
] | 1 | 2020-06-04T00:19:36.000Z | 2020-06-04T00:19:36.000Z | pi-dab-projects.config.js | mlenkeit/up-pi-pm2 | 1a1d1f47481c90fd96064e0b6857fe52e132fcd7 | [
"MIT"
] | 9 | 2017-09-16T19:48:02.000Z | 2020-05-30T10:53:53.000Z | pi-dab-projects.config.js | mlenkeit/up-pi-pm2 | 1a1d1f47481c90fd96064e0b6857fe52e132fcd7 | [
"MIT"
] | null | null | null | 'use strict';
module.exports = require('./main.config.js')
.map(config => {
return {
name: config.githubSlug,
dir: config.dir,
githubWebhook: config.githubWebhook,
postCheckoutScript: config.postCheckoutScript
};
}); | 23 | 51 | 0.640316 |
938c77fef2109d676a130f5acab98ada403f3d15 | 3,158 | js | JavaScript | ForumArchive/dem/post_39542_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 136 | 2015-01-01T17:33:35.000Z | 2022-02-26T16:38:08.000Z | ForumArchive/dem/post_39542_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 60 | 2015-06-20T00:39:16.000Z | 2021-09-02T22:55:27.000Z | ForumArchive/dem/post_39542_page_1.js | doc22940/Extensions | d8dbc9be08e0b8c0bd6b72e068ef73223d2799a8 | [
"Apache-2.0"
] | 141 | 2015-04-29T09:50:11.000Z | 2022-03-18T09:20:44.000Z | [{"Owner":"JohnK","Date":"2018-08-21T10:17:04Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tFollowing _lt_a href_eq__qt_http_dd_//www.html5gamedevs.com/topic/2571-the-wingnut-chronicles/?do_eq_findComment&_sm_comment_eq_225145_qt_ rel_eq__qt__qt__gt_an idea_lt_/a_gt_ by _lt_span_gt__lt_a contenteditable_eq__qt_false_qt_ data-ipshover_eq__qt__qt_ data-ipshover-target_eq__qt_http_dd_//www.html5gamedevs.com/profile/5733-wingnut/?do_eq_hovercard_qt_ data-mentionid_eq__qt_5733_qt_ href_eq__qt_http_dd_//www.html5gamedevs.com/profile/5733-wingnut/_qt_ rel_eq__qt__qt__gt_@Wingnut_lt_/a_gt__lt_/span_gt_ here is an attempt at generating particles (Wingys addition) along a type of spirograph type of generator. I say _t_type of_t_ since I am not entirely sure I have the maths correct for multiple circles_co_ however the patterns are pretty\n_lt_/p_gt_\n\n_lt_p_gt_\n\t_lt_a href_eq__qt_https_dd_//www.babylonjs-playground.com/#1BTGPV%2315_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//www.babylonjs-playground.com/#1BTGPV#15_lt_/a_gt_\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Sebavan","Date":"2018-08-21T11:21:21Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tThis is pretty damn cool !!!\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Wingnut","Date":"2018-08-21T11:26:18Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tBeautiful_co_ and really nice tight spiro-code. Phew! Impressive_co_ JK ! Thx a bunch!\n_lt_/p_gt_\n\n_lt_p_gt_\n\tHere_t_s a slightly modded version... camera a bit closer_co_ mousewheel precision set _qt_fine_qt_ and minZ set low.\n_lt_/p_gt_\n\n_lt_p_gt_\n\t_lt_a href_eq__qt_https_dd_//www.babylonjs-playground.com/#1BTGPV%2316_qt_ rel_eq__qt_external nofollow_qt__gt_https_dd_//www.babylonjs-playground.com/#1BTGPV#16_lt_/a_gt_\n_lt_/p_gt_\n\n_lt_p_gt_\n\tLittle tweaks... which allows a user to be struck in the eye with a burning-hot particle. _lt_img alt_eq__qt__dd_)_qt_ data-emoticon_eq__qt__qt_ height_eq__qt_20_qt_ src_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/default_smile.png_qt_ srcset_eq__qt_http_dd_//www.html5gamedevs.com/uploads/emoticons/smile@2x.png 2x_qt_ title_eq__qt__dd_)_qt_ width_eq__qt_20_qt_ /_gt_ Love that retinal pain &_sm_ scarring!\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Wingnut","Date":"2018-09-10T11:32:05Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\t[ Wingnut ponders attaching a followCam to the pen_co_ but aborts the idea until he buys more motion sickness pills. ] _dd_)\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"},{"Owner":"Deltakosh","Date":"2018-09-10T15:39:58Z","Content":"_lt_div class_eq__qt_mages_qt__gt_\n\t\t\t\n_lt_p_gt_\n\tThis is so cool! Thanks guys!\n_lt_/p_gt_\n\n\n\t\t\t\n\t\t_lt_/div_gt_\n\n\t\t_lt_div class_eq__qt_ipsI_qt__gt__lt_/div_gt__lt_/div_gt_"}] | 3,158 | 3,158 | 0.824256 |
938cd79ba0712c1f83fc2323d4febb1a4c9813bf | 493 | js | JavaScript | applications/crud/fn-11-handled-uncaught-errors/index.js | eXigentCoder/azure-serverless-example | 3f99e7881c265de7fd5641f42fe8442c347eacd0 | [
"MIT"
] | null | null | null | applications/crud/fn-11-handled-uncaught-errors/index.js | eXigentCoder/azure-serverless-example | 3f99e7881c265de7fd5641f42fe8442c347eacd0 | [
"MIT"
] | 2 | 2021-09-02T02:52:45.000Z | 2022-01-22T09:54:04.000Z | applications/crud/fn-11-handled-uncaught-errors/index.js | eXigentCoder/azure-serverless-example | 3f99e7881c265de7fd5641f42fe8442c347eacd0 | [
"MIT"
] | 1 | 2021-04-29T18:39:49.000Z | 2021-04-29T18:39:49.000Z | 'use strict';
const { azureHttpWrapper } = require('ms-oss-example-common');
const { teapot, internal } = require('@hapi/boom');
let counter = 0;
module.exports = azureHttpWrapper(async function handledErrors({ logger }) {
logger.info({ counter });
counter++;
const data = {
someBool: true,
someString: 'heya',
};
if (counter % 2 === 0) {
throw internal('leeeeeEEEEeroy jenkins!!', data);
} else {
throw teapot('Yolo', data);
}
});
| 25.947368 | 76 | 0.592292 |
938cef45367fdced19f0340de1b02e999419d16a | 3,707 | js | JavaScript | cli.js | vladimyr/peludna-prognoza | 705fb639c5c42b67afbeb49425c09f839e02f344 | [
"MIT"
] | null | null | null | cli.js | vladimyr/peludna-prognoza | 705fb639c5c42b67afbeb49425c09f839e02f344 | [
"MIT"
] | 1 | 2018-05-23T10:05:47.000Z | 2018-05-23T10:05:47.000Z | cli.js | vladimyr/peludna-prognoza | 705fb639c5c42b67afbeb49425c09f839e02f344 | [
"MIT"
] | null | null | null | #!/usr/bin/env node
'use strict';
const { getCities, getPollenData } = require('./client');
const { URL } = require('url');
const chalk = require('chalk');
const diacritics = require('diacritics');
const flowers = require('./flowers');
const fuzzysearch = require('fuzzysearch');
const inquirer = require('inquirer');
const Lines = require('./lines');
const opn = require('opn');
const pkg = require('./package.json');
const print = require('./printer');
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
const jsonify = obj => JSON.stringify(obj, null, 2);
const removeDiacritics = str => diacritics.remove(str.replace(/đ/g, 'dj'));
const normalize = str => removeDiacritics(str.toLowerCase().trim());
const compare = (str1, str2) => normalize(str1) === normalize(str2);
const openUrl = url => opn(url, { wait: false });
const name = Object.keys(pkg.bin)[0];
const help = chalk`
{bold ${name}} v${pkg.version}
Usage:
$ ${name} [city]
$ ${name} -c <city>
Options:
-c, --city Select city [string]
-j, --json Output data in JSON format [boolean]
-x, --xml Output data in XML format [boolean]
-w, --web Show data using web browser [boolean]
-h, --help Show help [boolean]
-v, --version Show version number [boolean]
Homepage: {green ${pkg.homepage}}
Report issue: {green ${pkg.bugs.url}}
`;
const options = require('minimist-options')({
help: { type: 'boolean', alias: 'h' },
version: { type: 'boolean', alias: 'v' },
city: { type: 'string', alias: 'c' },
json: { type: 'boolean', alias: 'j' },
xml: { type: 'boolean', alias: 'x' },
web: { type: 'boolean', alias: 'w' }
});
const argv = require('minimist')(process.argv.slice(2), options);
program(argv).catch(err => { throw err; });
async function program(flags) {
if (flags.version) return console.log(pkg.version);
if (flags.help) return outputHelp(help, flowers);
const cities = await getCities();
const city = flags.city ? { name: flags.city } : await selectCity(cities);
let url;
if (city.url) ({ url } = city);
else ({ url } = cities.find(({ name }) => compare(name, city.name)) || {});
if (!url) {
const msg = chalk`Odabrani grad nije pronadjen: {blue ${city.name}}`;
console.error(chalk`{bgRed.whiteBright Error} ${msg}`);
process.exit(1);
}
if (flags.web) return openUrl(webpage(url));
const data = await getPollenData(url);
if (flags.json) return console.log(jsonify(data, null, 2));
if (flags.xml) return console.log(data.toXML());
return print(data);
}
async function selectCity(cities) {
cities = cities.map(city => {
city.value = city;
city.normalizedName = normalize(city.name);
return city;
});
const { city } = await inquirer.prompt([{
type: 'autocomplete',
name: 'city',
message: 'Select city',
pageSize: 10,
source: async (_, input) => {
if (!input) return cities;
const needle = normalize(input);
return cities.filter(city => fuzzysearch(needle, city.normalizedName));
}
}]);
return city;
}
function outputHelp(help, logo, margin = 66) {
const output = new Lines();
help.split('\n').forEach((line, row) => {
output.write(line);
const logoLine = logo[row];
if (!logoLine) return output.next();
output.restartLine(margin).write(logoLine);
output.next();
});
console.log(output.toString());
}
function webpage(url) {
const urlObj = new URL(url);
urlObj.search = '';
return urlObj.href;
}
| 32.517544 | 81 | 0.602913 |
938d9fcca62fa15f120f9548261b73e5d2d15c20 | 860 | js | JavaScript | src/core/db/mongo.js | marcopgordillo/practical-nodejs | f7b339a09d71a97d22a6040f67d5f70a2740e86b | [
"MIT"
] | null | null | null | src/core/db/mongo.js | marcopgordillo/practical-nodejs | f7b339a09d71a97d22a6040f67d5f70a2740e86b | [
"MIT"
] | 3 | 2020-11-27T16:21:17.000Z | 2021-04-06T17:51:17.000Z | src/core/db/mongo.js | marcopgordillo/practical-nodejs | f7b339a09d71a97d22a6040f67d5f70a2740e86b | [
"MIT"
] | null | null | null | 'use strict'
const MongoClient = require('mongodb').MongoClient
exports.db = async (url, db) => {
let client
try {
client = await MongoClient.connect(url, { useUnifiedTopology: true, useNewUrlParser: true })
return client.db(db)
} catch (err) {
console.error(err)
}
}
exports.collections = async (db, collections, result) => {
try {
for (const collection of collections) {
result[collection] = await db
.then(db => db.collection(collection))
.catch(err => { throw err })
}
} catch (err) {
console.error(err)
}
}
exports.close = (client) => {
if (client) {
client.close()
}
}
exports.list = (collection, cb, query = {}) => {
collection
.find(query, { sort: { _id: -1 } })
.toArray(cb)
}
exports.getBySlug = (collection, slug, cb) => {
collection
.findOne({ slug }, cb)
}
| 20 | 96 | 0.598837 |
938e29813391d904ce68478ba28aee357590a931 | 835 | js | JavaScript | src/components/Logo.js | FakeYou/zonky | 0ba0d920190df1bd9e3f80bfeddf08a17f28de39 | [
"MIT"
] | null | null | null | src/components/Logo.js | FakeYou/zonky | 0ba0d920190df1bd9e3f80bfeddf08a17f28de39 | [
"MIT"
] | null | null | null | src/components/Logo.js | FakeYou/zonky | 0ba0d920190df1bd9e3f80bfeddf08a17f28de39 | [
"MIT"
] | null | null | null | import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import ms from 'milliseconds';
const SPEED = ms.seconds(10);
const Image = styled.img`
height: 100px;
width: 300px;
overflow: visible;
object-fit: cover;
`;
const Logo = ({ className }) => {
const [logo, setLogo] = useState(1);
const timeoutRef = useRef();
useEffect(
() => {
timeoutRef.current = setTimeout(() => {
setLogo((logo % 16) + 1);
}, SPEED);
return () => clearTimeout(timeoutRef.current);
},
[logo]
);
return (
<Image
className={className}
src={`https://zonky.cz/images/nav-logo/svgs/zonky_cz_${logo}.svg`}
/>
);
};
Logo.propTypes = {
className: PropTypes.string
};
Logo.defaultProps = {
className: null
};
export default styled(Logo)``;
| 17.765957 | 69 | 0.647904 |
938ecd9883ce4f1f9baa638107742a9c230d1f46 | 9,670 | js | JavaScript | suricata/apis/flow_8h.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | suricata/apis/flow_8h.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | suricata/apis/flow_8h.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | var flow_8h =
[
[ "FlowCnf_", "structFlowCnf__.html", "structFlowCnf__" ],
[ "FlowKey_", "structFlowKey__.html", "structFlowKey__" ],
[ "FlowAddress_", "structFlowAddress__.html", "structFlowAddress__" ],
[ "Flow_", "structFlow__.html", "structFlow__" ],
[ "FlowProto_", "structFlowProto__.html", "structFlowProto__" ],
[ "addr_data16", "flow_8h.html#ab77fe4fe17634e3a7f407993d02ad1a1", null ],
[ "addr_data32", "flow_8h.html#a7c9624021227f535e449a955816a0593", null ],
[ "addr_data8", "flow_8h.html#a2e8d9eda662826ccacbc1b1bd417ee9b", null ],
[ "FLOW_ACTION_DROP", "flow_8h.html#a4fef493bf2d4fbc0109616c5f9a0818f", null ],
[ "FLOW_ALPROTO_DETECT_DONE", "flow_8h.html#a7f01f004d51da5be8d905f2c3de47fad", null ],
[ "FLOW_CLEAR_ADDR", "flow_8h.html#a0b2808fb32b8c9bc4e87e0b4eb967057", null ],
[ "FLOW_COPY_IPV4_ADDR_TO_PACKET", "flow_8h.html#a4323d718953c7858e81bb2b82a93b47a", null ],
[ "FLOW_COPY_IPV6_ADDR_TO_PACKET", "flow_8h.html#aa92ef4c1a76b1e8de0ef3e680a6c8137", null ],
[ "FLOW_END_FLAG_EMERGENCY", "flow_8h.html#abfe35eea6bfbe795ecf64bff39f8a44b", null ],
[ "FLOW_END_FLAG_FORCED", "flow_8h.html#a47d517507cea6faaee2675654b8f64fb", null ],
[ "FLOW_END_FLAG_SHUTDOWN", "flow_8h.html#aae639ac859503b2b8d172bb533862729", null ],
[ "FLOW_END_FLAG_STATE_CLOSED", "flow_8h.html#aade17255a478a77dddf6523277ef1ccf", null ],
[ "FLOW_END_FLAG_STATE_ESTABLISHED", "flow_8h.html#a89a6b9ee452875f32492c08b1b56d737", null ],
[ "FLOW_END_FLAG_STATE_NEW", "flow_8h.html#a6a86a2aacd765b4d70370fda4341ce80", null ],
[ "FLOW_END_FLAG_TIMEOUT", "flow_8h.html#a58c5c03289cab4b9d435f85ffb3d524e", null ],
[ "FLOW_FILE_NO_MAGIC_TC", "flow_8h.html#a51334561b90155a60b657079ef0d4753", null ],
[ "FLOW_FILE_NO_MAGIC_TS", "flow_8h.html#aab1be2b08eed4073d7d7d9ece5a87177", null ],
[ "FLOW_FILE_NO_MD5_TC", "flow_8h.html#aecc09e28ccd2c02d24c797f87d3778f9", null ],
[ "FLOW_FILE_NO_MD5_TS", "flow_8h.html#aad08c59b6ec9e48a5e1f3af895bf8020", null ],
[ "FLOW_FILE_NO_SIZE_TC", "flow_8h.html#a563656ad47e1ee8dd00267bbf71c6bb4", null ],
[ "FLOW_FILE_NO_SIZE_TS", "flow_8h.html#aa2dca72d6ae8e4affd88b1846efd8f7a", null ],
[ "FLOW_FILE_NO_STORE_TC", "flow_8h.html#a412868706924ba5a914c49f52d1eb7d3", null ],
[ "FLOW_FILE_NO_STORE_TS", "flow_8h.html#ad30fefe4f0be515fdfd763a22394368c", null ],
[ "FLOW_IPV4", "flow_8h.html#acbc83bd76c24ab679517e2ccf75f248f", null ],
[ "FLOW_IPV6", "flow_8h.html#aaa98f303be69eac6d039f0d4a142f12c", null ],
[ "FLOW_IS_IPV4", "flow_8h.html#aded97a0427468abfb12c69ba6aa5bac8", null ],
[ "FLOW_IS_IPV6", "flow_8h.html#a193aefcddae27756f16005fd2e6cf898", null ],
[ "FLOW_IS_PM_DONE", "flow_8h.html#ad2084ea1034b898b86b16757a2cbb43d", null ],
[ "FLOW_IS_PP_DONE", "flow_8h.html#a5f038731d9b265210652b8a4fb592b97", null ],
[ "FLOW_NOPACKET_INSPECTION", "flow_8h.html#a957fb3eda619940661bdb81029d4ab17", null ],
[ "FLOW_NOPAYLOAD_INSPECTION", "flow_8h.html#a0e9433b06fd1b0038a416efc3cb33516", null ],
[ "FLOW_PKT_ESTABLISHED", "flow_8h.html#ac45d712411c8e632a8ee2a74decbd2d5", null ],
[ "FLOW_PKT_TOCLIENT", "flow_8h.html#ae63f6c00ac1568656cab0d65659050cc", null ],
[ "FLOW_PKT_TOCLIENT_FIRST", "flow_8h.html#ab68dbf0d3c7119dc3e1df9927e8b957c", null ],
[ "FLOW_PKT_TOCLIENT_IPONLY_SET", "flow_8h.html#aafe969e4a1cdd878782706a7750427b9", null ],
[ "FLOW_PKT_TOSERVER", "flow_8h.html#a26683e28ff5cf63b88d73adec56897fa", null ],
[ "FLOW_PKT_TOSERVER_FIRST", "flow_8h.html#acd30b4ca9a35928335caa34b5964fc74", null ],
[ "FLOW_PKT_TOSERVER_IPONLY_SET", "flow_8h.html#a9755e42d75235f370a24419dc377302d", null ],
[ "FLOW_QUIET", "flow_8h.html#a3707f98578d5b07d481ab40b9a80f124", null ],
[ "FLOW_RESET_PM_DONE", "flow_8h.html#a9d7de838ab054fcaaec804ae2d6654f0", null ],
[ "FLOW_RESET_PP_DONE", "flow_8h.html#ac7c7241e5178b6012eb9477784da573e", null ],
[ "FLOW_SET_IPV4_DST_ADDR_FROM_PACKET", "flow_8h.html#acfab1588e5f64a0c7679fd3baa9d885d", null ],
[ "FLOW_SET_IPV4_SRC_ADDR_FROM_PACKET", "flow_8h.html#a8817271d3e3aa936b02b91d4721327f7", null ],
[ "FLOW_SET_IPV6_DST_ADDR_FROM_PACKET", "flow_8h.html#a445732a394eac4b6d4d963cfd1c98436", null ],
[ "FLOW_SET_IPV6_SRC_ADDR_FROM_PACKET", "flow_8h.html#ab5e75cb070767d7097cd11fc223feb96", null ],
[ "FLOW_SET_PM_DONE", "flow_8h.html#a0518eaf7d9e2b215c5718af189b80fb9", null ],
[ "FLOW_SET_PP_DONE", "flow_8h.html#a0bdf21b10f522d67ea93bfd6c306184d", null ],
[ "FLOW_SGH_TOCLIENT", "flow_8h.html#a0c9ade99105c6c785d6adfe3b41ef309", null ],
[ "FLOW_SGH_TOSERVER", "flow_8h.html#a6068585b593189419a26f1335626c37c", null ],
[ "FLOW_TC_PM_ALPROTO_DETECT_DONE", "flow_8h.html#a0bf3f5b6c6311936fd6697144ace3f0f", null ],
[ "FLOW_TC_PP_ALPROTO_DETECT_DONE", "flow_8h.html#aca809131d7b869da95a917769859104b", null ],
[ "FLOW_TCP_REUSED", "flow_8h.html#a9388dbacb1d3befd12208527790738ef", null ],
[ "FLOW_TIMEOUT_REASSEMBLY_DONE", "flow_8h.html#a9460ece6b11cd491e2a597326b9522b4", null ],
[ "FLOW_TO_DST_SEEN", "flow_8h.html#abd23a31d76b0ee1340240f5fccd2fa74", null ],
[ "FLOW_TO_SRC_SEEN", "flow_8h.html#ad937c55a9cbb559a578ae7ffde48e3cc", null ],
[ "FLOW_TOCLIENT_DROP_LOGGED", "flow_8h.html#a766f6836e289c73cc8cdbcc80e25e6ed", null ],
[ "FLOW_TOCLIENT_IPONLY_SET", "flow_8h.html#a2a643601821389a937a3bcabf6c4d364", null ],
[ "FLOW_TOSERVER_DROP_LOGGED", "flow_8h.html#ac42aaa83798d9bdb7c0ef3c6ac008318", null ],
[ "FLOW_TOSERVER_IPONLY_SET", "flow_8h.html#ad060ef4ef1c93faf45ae8aa725706814", null ],
[ "FLOW_TS_PM_ALPROTO_DETECT_DONE", "flow_8h.html#a2aa7ca14a895f27c91f1318b6152690f", null ],
[ "FLOW_TS_PP_ALPROTO_DETECT_DONE", "flow_8h.html#a16b46be9531d42948b3d7d3e3b8f5158", null ],
[ "FLOW_VERBOSE", "flow_8h.html#a17e61e3e0c738fb9cc4377845338ec03", null ],
[ "FLOWLOCK_DESTROY", "flow_8h.html#a16f423df380e1fef0f4f2c53c511d7ac", null ],
[ "FLOWLOCK_INIT", "flow_8h.html#ad75805421f1ba2ab6cebe1bc56820b81", null ],
[ "FLOWLOCK_MUTEX", "flow_8h.html#abfc32cfe23f27ea422263f6fce0ac0c2", null ],
[ "FLOWLOCK_RDLOCK", "flow_8h.html#ad3100bcbff5c6c02935a788485c7f2d9", null ],
[ "FLOWLOCK_TRYRDLOCK", "flow_8h.html#a7c96c7f43fe200e94c6200a29f71ff4e", null ],
[ "FLOWLOCK_TRYWRLOCK", "flow_8h.html#a0128160cdd5cb0caf7fca930f7f1a878", null ],
[ "FLOWLOCK_UNLOCK", "flow_8h.html#acf25fde8e121735a94680ef34943c2bf", null ],
[ "FLOWLOCK_WRLOCK", "flow_8h.html#af4a9710413faa92ce4626639f4d980a1", null ],
[ "TOCLIENT", "flow_8h.html#ad9b4fe0c8cc065e66caddd20056cd2ea", null ],
[ "TOSERVER", "flow_8h.html#ad9f6565d248eea8a9924f7a468a85248", null ],
[ "AppLayerParserState", "flow_8h.html#ac7aafb3687a1039b72416cfcd2c93931", null ],
[ "Flow", "flow_8h.html#a7669d014b29ca423cad5940bba00575b", null ],
[ "FlowAddress", "flow_8h.html#a1503a1283be31412810a06b11074fb08", null ],
[ "FlowConfig", "flow_8h.html#a103f0e4aff8fcfc15d23ffd3a3b0111d", null ],
[ "FlowKey", "flow_8h.html#aaa39f370419ea47a56df60c364dd9091", null ],
[ "FlowProto", "flow_8h.html#a4835c7636d15e559d8011b499cf66363", null ],
[ "FlowRefCount", "flow_8h.html#ae7af90d56c942eab65b020128f89cd63", null ],
[ "FlowStateType", "flow_8h.html#a2a33a7f7e50443057a206145aaad9fbf", null ],
[ "FlowThreadId", "flow_8h.html#a931c6751e62df6598719dd59bff39843", null ],
[ "FLOW_STATE_NEW", "flow_8h.html#adbaf9202177df73e6880eab6e6aab329a7ca81d7aaa9699f48bf36bfdc59a636c", null ],
[ "FLOW_STATE_ESTABLISHED", "flow_8h.html#adbaf9202177df73e6880eab6e6aab329ab04788283ebbdbd79169b056051d3316", null ],
[ "FLOW_STATE_CLOSED", "flow_8h.html#adbaf9202177df73e6880eab6e6aab329a7cbc99fa3daf05fd785f6724a2400161", null ],
[ "FlowCleanupAppLayer", "flow_8h.html#a644537e740c20168ca13af55c50edda0", null ],
[ "FlowClearMemory", "flow_8h.html#ac9dd7439447e120e4fdc6645f83b735f", null ],
[ "FlowGetAppProtocol", "flow_8h.html#a1135a66e64bd8fe19166c853ea0e7986", null ],
[ "FlowGetAppState", "flow_8h.html#afb864b6392ad4eddbdf7092d4ec4e78e", null ],
[ "FlowGetDisruptionFlags", "flow_8h.html#aca700f93b37d88672923ffb56949d640", null ],
[ "FlowGetFlowFromHashByPacket", "flow_8h.html#a628b6bcbde30406b081f469cc641386e", null ],
[ "FlowGetPacketDirection", "flow_8h.html#a65e6c49d11bbc6375751d3e7cbe95c9a", null ],
[ "FlowHandlePacket", "flow_8h.html#ae727a896e38d8ebdce4b7b050d08c178", null ],
[ "FlowHandlePacketUpdate", "flow_8h.html#a3d88a8d5aee8f279280f3d7976a15a61", null ],
[ "FlowHandlePacketUpdateRemove", "flow_8h.html#accc656c44694fa7460e7a5317c04fb47", null ],
[ "FlowInitConfig", "flow_8h.html#a897689d742258e918e752f50cd93915e", null ],
[ "FlowLookupFlowFromHash", "flow_8h.html#af6401dc236faa848127116084f11fb9d", null ],
[ "FlowPrintQueueInfo", "flow_8h.html#a0db828278a7c0504783b797c9ca2d3a4", null ],
[ "FlowRegisterTests", "flow_8h.html#a4fa1db77ebc6f5bd811ccf151f1c8218", null ],
[ "FlowSetIPOnlyFlag", "flow_8h.html#a73ba7779eccaaea21979291ebc5cbfef", null ],
[ "FlowSetIPOnlyFlagNoLock", "flow_8h.html#a14b6ff7cc781d3026b40dcedcdbfb4e3", null ],
[ "FlowSetProtoEmergencyTimeout", "flow_8h.html#ab1ae8442a76cc103be69b7ff88c2902b", null ],
[ "FlowSetProtoFreeFunc", "flow_8h.html#ae6e272a7eb70dfe726b9c241c5d1b30f", null ],
[ "FlowSetProtoTimeout", "flow_8h.html#a883d764885326fa4b40e767490490191", null ],
[ "FlowShutdown", "flow_8h.html#a8dae51c56800ed0e22279e49913cd15a", null ],
[ "FlowUpdateQueue", "flow_8h.html#aa6a4a83a21d3c0668777a8afedee9cd6", null ],
[ "FlowUpdateSpareFlows", "flow_8h.html#a0a2af32f22fdfd78a6fef1a70ee995d8", null ]
]; | 84.824561 | 122 | 0.769183 |
938fb5fff1a3a3f9e78ad46ccc73ff12a08e0a7f | 186 | js | JavaScript | tests/mocks/authentication.js | Vaelek/node-google-shared-locations | b81be369997566eaf40bf8cf39b7e4a1cc38f27b | [
"MIT"
] | 8 | 2018-08-09T03:26:20.000Z | 2022-03-16T13:15:53.000Z | tests/mocks/authentication.js | Vaelek/node-google-shared-locations | b81be369997566eaf40bf8cf39b7e4a1cc38f27b | [
"MIT"
] | 3 | 2018-11-12T14:40:27.000Z | 2020-07-12T00:14:34.000Z | tests/mocks/authentication.js | Vaelek/node-google-shared-locations | b81be369997566eaf40bf8cf39b7e4a1cc38f27b | [
"MIT"
] | 3 | 2018-08-17T08:42:09.000Z | 2021-09-07T08:10:18.000Z | // TODO: Create mocks for each step to test.
// This is of little importance, because it's important to see if the steps are responding correctly to Google's real pages not to the mocks. | 93 | 141 | 0.768817 |
939049d013370a9c0378bf1ffd5a0918c01c9223 | 949 | js | JavaScript | src/test/mocks/data/author.data.mock.js | saphyre/saphyre-data | 3d2460b2f1048e3728341f529c3895fd127b4932 | [
"MIT"
] | 4 | 2016-03-24T01:13:30.000Z | 2020-01-23T18:15:06.000Z | src/test/mocks/data/author.data.mock.js | saphyre/saphyre-data | 3d2460b2f1048e3728341f529c3895fd127b4932 | [
"MIT"
] | 12 | 2016-03-31T13:04:33.000Z | 2021-09-01T20:13:27.000Z | src/test/mocks/data/author.data.mock.js | saphyre/saphyre-data | 3d2460b2f1048e3728341f529c3895fd127b4932 | [
"MIT"
] | 1 | 2017-08-04T12:19:18.000Z | 2017-08-04T12:19:18.000Z | module.exports = function (saphyreData, models) {
var Author = models.Author,
model = saphyreData.createModel(Author);
model.projection('all', {
'author_id' : 'id',
'name' : 'name',
'Articles' : {
list : 'articles',
projection : {
'id' : 'id',
'title' : 'title',
'Tags' : 'tags'
}
}
});
model.projection('article-tags', {
'author_id' : 'id',
'name' : 'name',
'Articles.Tags' : {
list : 'articleTags',
projection : {
'id' : 'id',
'name' : 'name'
}
}
});
model.projection('list', {
'author_id' : 'id',
'name' : 'name'
});
model.criteria('id', {
name : 'id',
property : 'author_id',
operator : saphyreData.OPERATOR.EQUAL
});
return model;
}; | 21.568182 | 49 | 0.415174 |
9391d6cef30d9cb870884e83317e7d4f553daaec | 1,498 | js | JavaScript | Public/js/integral.js | zljpz/mgctdh | b0d7eec79dee26fe112f5fe21bd7853955d9eeff | [
"BSD-2-Clause"
] | 1 | 2017-05-26T01:36:14.000Z | 2017-05-26T01:36:14.000Z | Public/js/integral.js | zljpz/mgctdh | b0d7eec79dee26fe112f5fe21bd7853955d9eeff | [
"BSD-2-Clause"
] | null | null | null | Public/js/integral.js | zljpz/mgctdh | b0d7eec79dee26fe112f5fe21bd7853955d9eeff | [
"BSD-2-Clause"
] | null | null | null | $(function(){
//宝贝选页浮动居中
var page_ul = $('.choose_page > ul').width()/2;
$('.choose_page ul').css('margin-left',-page_ul);
$('#couples .praise p').click(function(){
var pathName=window.document.location.pathname;
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
// console.log(projectName);
$.ajax({
type: "GET",
url: projectName+"/User/checkIsLogin?"+Math.random(),
success: function(data){
// var result = eval(data);
// var status = result.status;
var status = data.status;
if(status){
$('#maskLayer').show();
$('#information').show();
}else{
$('#maskLayer').show();
$('#login').show();
$("#maskLayer").height(pageHeight());
}
}
});
});
$('#information .share_fork').click(function(){
$('#maskLayer').hide();
$('#information').hide();
});
$('.baby_details ul li .praise').click(function(){
var jifen = $(this).prev().children('span').html();
var name = $(this).parent().prev().children().children('p').html();
var a_id = $(this).parent().parent().attr('data-i_gid');
$('.t_info p:eq(0)').text(name);
$('.t_info p:eq(1)').text(jifen);
$('.t_info input:eq(0)').attr('value',a_id);
});
}); | 31.208333 | 80 | 0.471963 |
9392b547e66c8a2a7b73bfcfff8660f5efc6d2df | 1,595 | js | JavaScript | components/StickMixin.js | Timkor/nuxt-premium | d62b89c6ce4f8203965f3c21fbf092a0ba716883 | [
"MIT"
] | null | null | null | components/StickMixin.js | Timkor/nuxt-premium | d62b89c6ce4f8203965f3c21fbf092a0ba716883 | [
"MIT"
] | null | null | null | components/StickMixin.js | Timkor/nuxt-premium | d62b89c6ce4f8203965f3c21fbf092a0ba716883 | [
"MIT"
] | null | null | null |
export default {
methods: {
getNearestContainer() {
var current = this;
while (current.$parent) {
current = current.$parent;
if (current.isStickContainer && current.isStickContainer()) {
return current;
}
}
return null;
},
getDimensionsRelativeToViewport(element) {
return element.getBoundingClientRect();
},
getDimensionsRelativeToElement(element, containingElement) {
const thatDimensions = this.getDimensionsRelativeToViewport(element);
const thisDimensions = this.getDimensionsRelativeToViewport(containingElement);
return {
x: thisDimensions.x - thatDimensions.x,
y: thisDimensions.y - thatDimensions.y,
width: thisDimensions.width,
height: thisDimensions.height,
top: thisDimensions.top - thatDimensions.top,
right: thisDimensions.right - thatDimensions.right,
bottom: thisDimensions.bottom - thatDimensions.bottom,
left: thisDimensions.left - thatDimensions.left,
};
},
getAbsoluteDimensions(element) {
const dimensions = this.getDimensionsRelativeToViewport(element);
const scrollX = window.scrollX;
const scrollY = window.scrollY;
return {
x: dimensions.x + scrollX,
y: dimensions.y + scrollY,
width: dimensions.width,
height: dimensions.height,
top: dimensions.top + scrollY,
right: dimensions.right + scrollX,
bottom: dimensions.bottom + scrollY,
left: dimensions.left + scrollX,
};
}
}
}
| 26.583333 | 85 | 0.645141 |
9393428bda7964da0b5184d93078542f9e178ec0 | 57,218 | js | JavaScript | gev/js/gtexBubbleMap.js | gamazonlab/gtex-viz | 3a7246fa06117524ed1ddb4e0771afc4f9188bbc | [
"BSD-3-Clause"
] | 45 | 2018-09-27T05:43:47.000Z | 2022-02-02T10:02:37.000Z | gev/js/gtexBubbleMap.js | gamazonlab/gtex-viz | 3a7246fa06117524ed1ddb4e0771afc4f9188bbc | [
"BSD-3-Clause"
] | 7 | 2018-11-09T19:18:31.000Z | 2022-01-07T15:14:19.000Z | gev/js/gtexBubbleMap.js | gamazonlab/gtex-viz | 3a7246fa06117524ed1ddb4e0771afc4f9188bbc | [
"BSD-3-Clause"
] | 17 | 2018-11-14T03:09:07.000Z | 2022-03-14T13:26:25.000Z | /**
* Copyright © 2015 - 2018 The Broad Institute, Inc. All rights reserved.
* Licensed under the BSD 3-clause license (https://github.com/broadinstitute/gtex-viz/blob/master/LICENSE.md)
*/
// TODO: test config integrity and required fields
var gtexBubbleMap = function(geneId, config, urls, useRsId){
// this module is for the bubbleMap of the GTEx single-tissue eQTL data
var self = this;
var verbose = false;
var gene = undefined;
var snp;
var mat = {
y:[],
x:[],
data:[],
snp: {},
xlab: [] // for display purposes
};
var TISSUES = [];
var DATA = [];
var bMap, bMapMini, bMapBrush;
var dataFilters = {
r: { // pvalue
func: undefined,
value: undefined
},
value: { // effect size
func: undefined,
value: undefined
},
ld: { // linkage disequilibrium
func: undefined,
value: undefined
}
};
var xLabelMouseOverEvents = []; // for adding the column labels' mouse-over events
var xLabelMouseOutEvents = [];
this.querying = geneId;
this.getGeneId = function(){return geneId}; // is this used?
this.launch = function(){
// clear DOM from pre-existing bubble map
clear(config.bbMapDiv, config.infoDiv, config.bbMapCanvasDiv);
gene = undefined; // reset previously stored this.gene object (if stored) to undefined // why? how is this possible?
// nested ajax calls
if(verbose) console.info(urls.gene(geneId));
d3.json(urls.gene(geneId), function(error, gjson){ // api call to retrieve the gene and its TSS position
if(gjson === undefined) {
hideSpinner();
throw "Fatal Error: Gene data retrieval failed";
}
gene = gtexBubbleMapDataUtil.parseGene(gjson, geneId);
if(verbose) {
console.info(gene);
console.info(urls.eqtl(geneId));
}
// error checking
// if (gene.geneSymbol.toUpperCase() != self.querying.toUpperCase()) {
// console.error("Fatal error: gene query didn't return the right query ID.");
// return
// }
d3.json(urls.eqtl(geneId), function(err, eqtlJson){ // retrieve single-tissue eQTL data of the query gene
if(eqtlJson === undefined) {
hideSpinner();
throw "Fatal Error: eQTL data retrieval failed";
}
mat = gtexBubbleMapDataUtil.parseEqtl(eqtlJson, gene.tss);
if (mat === undefined) {
$('#'+config.rootDiv).html("No eQTL data found for " + geneId);
throw "No eQTL data found. Visualization terminated.";
}
TISSUES = mat.y.slice(0);
DATA = mat.data.slice(0);
hideSpinner();
setMini();
render();
});
});
};
this.changeXLabels = function(userRsId){
if(userRsId){
bMap.zoomGroup.selectAll('.xlab')
.each(function(){
var varId = $(this).attr("col");
$(this).text(mat.snp[varId].rsId);
});
}
else {
bMap.zoomGroup.selectAll('.xlab')
.each(function(){
var varId = $(this).attr("col");
$(this).text(mat.snp[varId].truncatedVariantId);
});
}
};
function setMini(){
// rendering the bubbleMap
config.needMini = mat.x.length > config.zoomN;
}
function clear(){
d3.select('#' + config.bbMapDiv).selectAll('*').remove(); // clear existing SVG
d3.select('#' + config.bbMapCanvasDiv).selectAll('*').remove();
d3.select('#' + config.ldCanvasDiv).selectAll('*').remove();
showSpinner();
$('#bbSnpSearch').val(''); // TODO: hard-coded
$('#pvalueSlider').val(0);
$('#pvalueLimit').val(0);
$('#effectSizeSlider').val(0);
$('#effectSizeLimit').val(0);
$('#filterInfo').hide();
$('#'+config.infoDiv).html('');
config.ldData = undefined;
}
function render(){
if(config.needMini){
bMapMini = new bubbleMapMini(mat, config);
bMapMini.init();
}
bMap = new bubbleMap(mat, config);
bMap.init();
self.changeXLabels(false);
if(config.needMini){
// create a mini map of the eqtl matrix
bMapBrush = new bubbleMapBrush('bbrushSvg', bMapMini, bMap, config);
// create the brush of the pre-defined zoomed range on the mini map
bMapBrush.create();
}
addCustomFeatures();
}
function addCustomFeatures(){
// text summary table
updateSummary();
// the boxplot modal
bubbleMapUtil.createDialog(config.rootDiv, config.dialogDiv, 'eQTL Boxplot');
// the tissue select functionality
addTissueSelect();
// Sorting and mouse events
bMap.svg.on('mouseout', function(){bMap.tooltip.hide();});
addXLabelMouseEvents();
addBubbleMouseEvents();
addSortTissueByAlphaBetButton();
addSnpSearch(); // Add SNP text search functionality
addDataFilters(); // Add p-value and effect size filtering
addTissueBadges(); // render external data
addSiteMarkers(); // TSS and TES
addTssDist();
addLD();
// update the brush
// this is a crucial step: for the brush to also apply to the external data and graphical components
if (config.needMini) bMapBrush.brushEvent();
}
function rerender(state){
var _resetMarkers = function(){
d3.selectAll('#xMarkerGroup').selectAll('.xMarker').transition().attr({'fill':'none'});
};
_resetMarkers();
switch(state){
case 'dataFilter': // superficial visual filtering, which doesn't change the underlying structure of self.mat
if(config.needMini) bMapMini.update(mat, state);
bMap.update(mat, state);
if(config.needMini) bMapBrush.brushEvent();
break;
case 'ldFilter':
drawLD();
break;
case 'sort': // essentially the order of mat.y has changed
if(config.needMini) bMapMini.update(mat, state);
bMap.update(mat, state);
addTissueBadges();
if(config.needMini) bMapBrush.brushEvent();
break;
default:
// when the self.mat dimensions are changed, such is the case of state == 'tissueSelect'
// the execution order of the steps is important
updateSummary();
if(config.needMini) bMapMini.update(mat, state);
bMap.update(mat, state);
if (bMapBrush) {
bMapBrush.update(bMapMini.scale);
}
addSnpSearch(state);
addSiteMarkers(state);
addTissueBadges();
addTssDist();
addLD();
if(snp !== undefined) sortTissuesBySnp(snp);
if(config.needMini) bMapBrush.brushEvent();
}
var _markSnp = function(){
// mark the selected SNP's column
if(snp !== undefined) {
var _draw = function(g, scale){
g.select('#xMarkerGroup').selectAll('.sortMarker').remove();
g.select('#xMarkerGroup').append('path')
.attr({
d: d3.svg.symbol().type("triangle-down"),
fill: '#000',
col: snp
})
.classed('xMarker sortMarker', true)
.attr('transform', function(d){return 'translate(' + scale.X(snp) + ',' + 0 + ')'});
};
_draw(bMap.zoomGroup, bMap.scale);
_draw(bMapBrush.svg, bMapMini.scale);
bMap.zoomGroup.select('#xLabel').selectAll('.xlab')
.attr('font-weight', undefined).filter(function (d) {
return d == snp
}).transition().attr({'fill': 'black', 'font-weight': 'bold'})
}
};
if(snp !== undefined) _markSnp(); // sort by a specific SNP
}
function hideSpinner(){
$('#fountainTextG').hide(); // hide the spinner
}
function showSpinner(){
$('#fountainTextG').show(); // hide the spinner
}
function mouseOverColumn(d){
// highlight the bar
var colSelect = '[col="' + d + '"]';
var col2Select = '[col2="' + d + '"]';
d3.selectAll('.ldLine').classed('bubbleMouseover', false);
d3.selectAll('circle'+colSelect).classed('bubbleMouseover', true);
d3.select('#tssrow').selectAll('rect'+colSelect).classed('bubbleMouseover', true);
d3.select('#ldwrapper').selectAll('rect'+colSelect).style({'stroke-width': 2, stroke:'#aaa'});
d3.select('#ldwrapper').selectAll('rect'+col2Select).style({'stroke-width': 2, stroke:'#aaa'});
d3.selectAll('.xlab'+colSelect).classed('textMouseover', true);
d3.selectAll('.ldLine' + colSelect).classed('bubbleMouseover', true);
}
function mouseOutColumn (d){
var colSelect = '[col="' + d + '"]';
var col2Select = '[col2="' + d + '"]';
d3.selectAll('circle'+colSelect).classed('bubbleMouseover', false);
d3.selectAll('rect'+colSelect).classed('bubbleMouseover', false);
d3.select('#ldwrapper').selectAll('rect'+colSelect).style({'stroke-width': 0});
d3.select('#ldwrapper').selectAll('rect'+col2Select).style({'stroke-width': 0});
d3.selectAll('.xlab'+colSelect).classed('textMouseover', false);
d3.selectAll('.ldLine' + colSelect).classed('bubbleMouseover', false);
}
function sortTissuesBySnp(selected){
// sorts tissue rows by a given SNP ID's effect size data
var _fetchData = function(data){
return data.filter(function(d){
return d.x == selected;
});
};
var _sortEffectSize = function(a,b){return Math.abs(b.value)-Math.abs(a.value)}; // descending
var matched = _fetchData(mat.data).sort(_sortEffectSize).map(function(d){return d.y}); // fetch snp's data, sort data by effect size, return the tissue list
// check missing tissues
if (matched.length != mat.y) {
// A SNP may not be present in all tissues,
// so missing tissues have to be appended to the newly sorted tissue list
var missed = mat.y.filter(function(d){return matched.indexOf(d)<0})
}
mat.y = matched.concat(missed);
snp = selected;
rerender('sort');
}
function addXLabelMouseEvents(){
// column label mouse events
var _mouseover = function(d, i){
var label = useRsId?mat.snp[d].rsId:mat.snp[d].variantId;
bMap.tooltip.show('click to sort tissue rows by: <br/>'
+ mat.snp[d].variantId
+ "<br/>" + mat.snp[d].rsId
);
mouseOverColumn(d, i);
if(xLabelMouseOverEvents.length > 0){
xLabelMouseOverEvents.forEach(function(e){
e(d);
});
}
};
var _click = function(d){
sortTissuesBySnp(d)
};
var _mouseout = function(d){
mouseOutColumn(d);
if(xLabelMouseOutEvents.length > 0){
xLabelMouseOutEvents.forEach(function(e){
e(d)
});
}
};
bMap.zoomGroup.selectAll('.xlab').style('cursor', 'pointer')
.on('mouseover', _mouseover)
.on('mouseout', _mouseout)
.on('click', _click);
}
function addBubbleMouseEvents(){
var _mouseover = function(d){
// show data in tooltip
var info = d.variantId + '<br>'
+ d.rsId + '<br>'
+ d.y + '<br>'
+ "normalized effect size (NES): " + d.value + "<br>";
bMap.tooltip.show(info);
// highlight row and column labels
var col = '[col="' + d.x + '"]';
var row = '[row="' + d.y + '"]';
d3.selectAll('.xlab' + col).classed('textMouseover',true);
d3.selectAll('.ylab' + row).classed('textMouseover', true);
// highlight the bubble
d3.select(this).classed('bubbleMouseover', true);
};
var _mouseout = function(){
d3.selectAll('.xlab').classed('textMouseover', false);
d3.selectAll('.ylab').classed('textMouseover', false);
d3.selectAll('.dcircle').classed('bubbleMouseover', false);
bMap.tooltip.hide();
};
var _click = function(d){
// TODO: review the box plot modal event
// draw the eqtl box plot when a bubble is clicked
$('#'+ config.dialogDiv).dialog('open');
// generate a unique div ID for this plot
var plotId = 'bbmap-'+mat.x.indexOf(d.x) + '-' + mat.y.indexOf(d.y);
// check if the plot already exists in the dialog, if so, do nothing
if ($('#'+plotId).length) return;
$modalBody = $('#' + config.dialogDiv + ' .bbMap-content');
$modalBody.append('<div style="float:left" id="' + plotId +
'"><span class="ui-icon ui-icon-closethick closePlot" id="' +
plotId+'Close"></span><div id="' + plotId+'Plot"></div>');
d3.select('#'+plotId)
.on('mouseover', function(){_mouseover(d)})
.on('mouseout', function(){_mouseout(d)});
$('#' + plotId + ' .closePlot').click(function(){
$('#'+plotId).empty();
$('#'+plotId).remove();
});
var plotDiv = d3.select('#' + plotId + 'Plot');
var url = urls.eqtlBoxplot();
var plotConfig = gtexBubbleMapConfig.plotviz(d.x, d.y);
var eqtlplot = new plotviz.EqtlPlot(plotDiv.node(), url, plotConfig); //can modify the dimensions by passing a 3rd object, for example: {width:100,height:100}
eqtlplot.query(d.x, gene.gencodeId, d.y, gene.geneSymbol, plotConfig);
};
bMap.zoomGroup.selectAll('.dcircle')
.on('mouseover', _mouseover)
.on('mouseout', _mouseout)
.on('click', _click);
}
function addSortTissueByAlphaBetButton(){
var _sortByTissueAlphabet = function(){
mat.y = mat.y.sort(function(a,b){return a>b?1:-1});
snp = undefined;
rerender('sort');
};
var _tooltip = function(){
var info='Click to sort tissues alphabetically';
bMap.tooltip.show(info);
};
var _addButton = function(selected){
return selected.append('rect')
.attr({
x:-100,
y:-10,
width: 110,
height: 16,
fill: '#eee',
cursor: 'pointer'
})
};
var _addText = function(selected){
return selected.append('text')
.text('Sort Tissues Alphabetically')
.attr({
x:-95,
y:0,
fill: '#000',
'font-size':8,
'text-anchor': 'start',
'class': 'bbadge',
cursor: 'pointer'
})
};
var _addEvents = function(selected){
selected.on('mouseover', _tooltip)
.on('click', _sortByTissueAlphabet)
};
var g = bMap.zoomGroup.append('g');
g.call(_addButton).call(_addEvents);
g.call(_addText).call(_addEvents);
}
function addTissueSelect(){
var _createSelectMenuModal = function(div, y){
$('#' + div + ' .modal-body').html(''); // first be sure that the tissue menu modal is empty
var modal = d3.select('#' + div + ' .modal-body').node();
var menu = new plotviz.Filter(modal);
var _createMenu = function(){
return y.map(function(d){return [d, true]});
};
var _createTextMap = function(){
var textMap = {};
y.forEach(function (d) {
if (typeof tissueMetadataJson != 'undefined' && d in tissueMetadataJson) { // this only works within gtex portal
if(!tissueMetadataJson[d].hasOwnProperty('tissueSiteDetail')) throw "Data structure parsing error.";
textMap[d] = tissueMetadataJson[d].tissueName;
}
else {
textMap[d] = d;
}
});
return textMap;
};
var input = {'data':_createMenu(), 'textMap': _createTextMap()};
menu.generate(input);
return menu;
};
var menu = _createSelectMenuModal(config.modalDiv, mat.y);
var _filter = function(){
// when the tissue menu modal closes, triggers the filtering of tissues
var tissues = menu.selected().filter(function(d){return d != 'All'});
if (tissues.length === 0) { // no tissue selected, prompt error message
$('#' + config.modalDiv).modal('show');
$('#' + config.modalDiv + ' .modal-footer').text('Error! Select one or more tissues!');
return;
}
var data = DATA.filter(function(d){return tissues.indexOf(d.y) > -1});
var _uniq = function(d, i, arr){
return i == arr.indexOf(d);
};
var _buildX = function(){
return data.map(function(d){return d.x}).filter(_uniq).sort(function(a,b){return mat.snp[a].pos-mat.snp[b].pos})
};
mat = {
y: tissues,
x:_buildX(),
data:data,
snp: mat.snp
};
rerender('tissueSelect');
};
$('#' + config.modalDiv).on('hidden.bs.modal', _filter);
}
function updateSummary(){
var _updateEqtlSummary = function(){
return '(' + gene.gencodeId + ') ' + gene.description + '<br>'
+ 'Gene Location: chromosome ' + gene.chromosome + ': ' + gene.start + ' - ' + gene.end + ' (' + gene.strand + ') <br>'
+ 'eQTLs: ' + mat.data.length + ' eQTLs (FDR <= 5%), including ' + mat.y.length + ' tissues (rows), ' + mat.x.length + ' SNPs (columns) <br> ';
};
var _getGenePageUrl = function(geneName, linkText) {
var geneNameString = "'" + geneName + "'";
if (typeof linkText == 'undefined') linkText = geneName;
return '<a href="javascript:portalClient.eqtl.gotoGeneExpression(' + geneNameString +
')">' + linkText + '</a>';
};
var _getBrowserUrl = function(featureId){
var featureIdString = "'" + featureId + "'";
return '<a href="javascript:gotoBrowser('+ featureIdString + ')">eQTL Browser</a>';
};
$('#'+config.infoDiv).html(_updateEqtlSummary());
$('#genePageLink').html(_getGenePageUrl(gene.geneSymbol, 'gene page'));
$('#geneSymbol').html(_getGenePageUrl(gene.geneSymbol));
$('#browserLink').html(_getBrowserUrl(gene.geneSymbol));
}
function addTissueBadges(){
// reports the number of samples with genotype for each tissue
var _tooltip = function(d){
var info=config.badgeData[d] + " samples with genotype in <br>" + d;
bMap.tooltip.show(info);
};
var _createBadges = function(selected){
selected.enter().append('ellipse');
selected.exit().remove();
selected.attr({
cx:-8,
cy:function(d){return bMap.scale.Y(d)},
rx: 11,
ry: 8,
fill: '#999',
cursor: 'default'
})
.on('mouseover', _tooltip);
};
var _createBadgeText = function(selected){
selected.enter().append('text').text(function(d){return config.badgeData[d]});
selected.exit().remove();
selected.attr({
x:-1,
y:function(d){return bMap.scale.Y(d) + 3 },
fill: '#fff',
'font-size':8,
'text-anchor': 'end',
'class': 'bbadge',
cursor: 'default'
})
.on('mouseover', _tooltip);
};
var id = 'tissueBadges';
var g = bMap.zoomGroup.select('#'+ id);
var _render = function(){
g = g.empty()? bMap.zoomGroup.append('g').attr('id', id):g;
g.selectAll('ellipse').data(mat.y, function(d){return d}).call(_createBadges);
g.selectAll('text').data(mat.y, function(d){return d}).call(_createBadgeText);
};
if(d3.keys(config.badgeData).length == 0){
if(verbose) console.info(urls.tissue());
d3.json(urls.tissue(), function(err, tjson) { // retrieve tissue sample count info
config.badgeData = gtexBubbleMapDataUtil.parseTissue(tjson);
_render();
});
}
else{
_render();
}
}
function addSnpSearch(state){
// add SNP search
var _addSnpMarkers = function(isMini, data){
var scale = isMini?bMapMini.scale:bMap.scale;
var xargs = { //column labels
g: isMini?bMapBrush.svg:bMap.zoomGroup,
data: data,
xscale: scale.X,
markerAdjust: isMini?5:0
};
bubbleMapUtil.makeColumnMarkers(xargs);
};
var _findSnps = function(){
// reset previously selected SNPs
var _resetMarkers = function(){
d3.selectAll('#xMarkerGroup').selectAll('.xMarker').classed('foundSnp', false);
bMap.zoomGroup.selectAll('.xlab').classed('textMatched', false);
};
_resetMarkers();
var snp = $('#bbSnpSearch').val();
if (snp.length>3) {
var __foundData = function(d){
var re = new RegExp(snp);
return re.test(d) == true; // why not return re.test(d)
};
var matched = mat.x.filter(__foundData);
if (matched.length == 0) return;
_addSnpMarkers(false, matched);
_addSnpMarkers(true, matched);
d3.selectAll('#xMarkerGroup').selectAll('.xMarker').classed('foundSnp', true);
var __textHighlight = function(selected){
selected.filter(function(d){
return matched.indexOf(d) >=0;
})
.classed('textMatched', true);
};
bMap.zoomGroup.selectAll('.xlab').call(__textHighlight);
}
};
var _addKeyEvent = function() {
$('#bbSnpSearch').keyup(_findSnps);
};
var _createEmptyMarkerGroup = function(){
if(bMapBrush !== undefined) bubbleMapUtil.makeColumnMarkers({g:bMapBrush.svg});
bubbleMapUtil.makeColumnMarkers({g:bMap.zoomGroup});
};
switch(state){
case 'tissueSelect':
_findSnps();
_createEmptyMarkerGroup();
break;
default:
_addKeyEvent();
_createEmptyMarkerGroup();
}
}
function addSiteMarkers(){
var _drawMarker = function(isMini, thingy, type){
var markerClass = type+'Marker';
// remove previously existing markers
if (isMini) {
bMapBrush.svg.select('.' + markerClass).remove();
}
else {
bMap.zoomGroup.select('.' + markerClass).remove();
}
var g = isMini?bMapBrush.svg.append('g'):bMap.zoomGroup.append('g');
g.classed(markerClass, true);
// calculate coordinates
var scale = isMini?bMapMini.scale:bMap.scale;
var x = scale.X(thingy) + (0.5*scale.X.rangeBand());
var y = isMini?scale.Y.range()[0] - 10:-scale.Y.rangeBand()*0.5;
var direction = gene.strand == '+'? scale.X.rangeBand() : -scale.X.rangeBand();
var __addLines = function(selected){
// vertical line
selected.append('line')
.attr({
x1: x,
x2: x,
y1: y,
y2: scale.Y.range()[(mat.y.length -1)],
stroke: '#999',
'stroke-width': '1',
col:thingy
})
.classed('xMarker', true); // xMarker controls the hide/show behavior
// horizontal line
if(type == 'tss'){
selected.append('line')
.attr({
x1: x,
x2: x + direction,
y1: y,
y2: y,
stroke: '#999',
'stroke-width': '1',
col: thingy
})
.classed('xMarker', true);
}
};
var __addTriangle = function(selected){
// triangle
var angle = gene.strand == '+'?90:-90;
var s = isMini?0.75:1;
selected.append('path')
.attr({
d: d3.svg.symbol().type("triangle-up"),
col:thingy, // important for hide/show the marker
'fill': '#999'
})
.classed('xMarker', true)
.attr('transform', 'translate('+(x + direction)+','+y+') rotate(' + angle + ') scale(' + s + ')')
};
var __addCircle = function(selected){
// circle
selected.append('circle')
.attr({
r: 3,
cx: x,
cy: y,
'class': 'xMarker',
col:thingy,
'fill': '#999'
})
};
var __addText = function(selected){
selected.append('text')
.text(gene.geneSymbol + ' ' + type.toUpperCase())
.attr({
x: gene.strand == '+'? x - (direction*3):x,
y: y - 3,
'fill': '#999',
'font-size': 8,
col:thingy
})
.classed('xMarker', true)
};
g.call(__addLines);
if(type == 'tss') g.call(__addTriangle);
if(type == 'tes') g.call(__addCircle);
if (!isMini) {
// add text label
g.call(__addText);
g.classed('additionalRow', true);
}
};
var _createTssSiteMarker = function(){
// Important Assumption: this filter assumes mat.x is sorted by the tss distance
// this function estimates where the site is located in mat.x
var sites = mat.x.filter(function(x, i){
if (i == mat.x.length - 1) return false;
if (mat.snp[x].dist == 0) return true;
var right = mat.x[i+1];
return mat.snp[x].dist * mat.snp[right].dist < 0; // the product is negative only if xdist < 0 and rightDist > 0
});
if (sites.length != 1) {
console.error('TSS site not found');
return null;
}
_drawMarker(false, sites[0], 'tss');
if (config.needMini) _drawMarker(true, sites[0], 'tss');
};
var _createTesSiteMarker = function(){
var sites = mat.x.filter(function(x, i) {
// estimate where the site is in mat.x
var tesPos = gene.strand == '+' ? gene.end : gene.start;
var right = mat.x[i + 1] || undefined;
if (typeof right == 'undefined') return false;
return (mat.snp[x].pos - tesPos) * (mat.snp[right].pos - tesPos) < 0; // the product is negative only if xdist < 0 and rightDist > 0 regardless of the strand
});
if (sites.length != 1) {
console.error('TES site not found');
return
}
_drawMarker(false, sites[0], 'tes');
if(config.needMini) _drawMarker(true, sites[0], 'tes');
};
_createTssSiteMarker();
_createTesSiteMarker();
}
function addTssDist(){
var unit = 1e5;
var range = ['#000', '#252525', '#525252', '#737373', '#969696', '#f0f0f0','#fff'];
var domain = [0,0.005, 0.01,0.1,0.5,2,3,4,5].map(function(d){return d*unit});
var cscale = d3.scale.linear()
.domain(domain)
.range(range);
var getPos = function(snp){
var dist = Math.abs(mat.snp[snp].dist);
return cscale(dist);
};
var markFeatureClass = function(snp){
// mark the SNPS in exon regions of the collapsed gene model
var exons = gene.exons;
var snpPos = mat.snp[snp].pos;
var overlap = exons.filter(function(exon){
// find the overlapping exon
if (!exon.hasOwnProperty('start') || !exon.hasOwnProperty('end')) throw 'Exon data structure error.';
return exon.start <= snpPos && snpPos <= exon.end;
});
var fClass = 'xMarker';
return (overlap.length > 0)? fClass + ' exon':fClass + ' noFeature';
};
var _drawRects = function(rects){
rects.enter().append('rect');
rects.exit().remove();
rects.attr({
x:function(d){return bMap.scale.X(d) - (0.5*bMap.scale.X.rangeBand())},
y: bMap.scale.Y(mat.y[mat.y.length-1]) + bMap.scale.Y.rangeBand(),
width: bMap.scale.X.rangeBand(),
height: bMap.scale.Y.rangeBand(),
fill:getPos,
'stroke-width': 1.2,
'class': markFeatureClass,
col: function(d){return d}
})
.on('mouseover', function(d){
// tooltip
var dist = gene.strand == '+'?mat.snp[d].dist:0-mat.snp[d].dist;
var pos = mat.snp[d].pos;
var info = mat.snp[d].variantId + '<br>'
+ mat.snp[d].rsId + '<br>'
+ 'TSS distance: ' + dist + '<br>'
+ 'Genomic location: ' + pos + '<br>';
if (d3.select(this).classed('exon')) {
info += 'Exon Region';
}
bMap.tooltip.show(info);
mouseOverColumn(d);
if(xLabelMouseOverEvents.length > 0){
xLabelMouseOverEvents.forEach(function(e){
e(d);
});
}
})
.on('mouseout', function(d){
mouseOutColumn(d);
if(xLabelMouseOutEvents.length > 0){
xLabelMouseOutEvents.forEach(function(e){
e(d)
});
}
});
};
var _drawTextLabel = function(selected){
bMap.zoomGroup.select('#tssLabel').remove();
selected.text('TSS Proximity')
.attr({
id: 'tssLabel',
x: -60,
y: bMap.scale.Y(mat.y[mat.y.length-1]) + (1.7*bMap.scale.Y.rangeBand()),
fill: '#999',
'font-size':10
});
};
// this is a 1D heatmap
var id = 'tssRow';
var g = bMap.zoomGroup.select('#' + id);
var _render = function() {
g = g.empty() ? bMap.zoomGroup.append('g').attr({'class': 'additionalRow', 'id': 'tssRow'}) : g;
g.selectAll('rect').data(mat.x, function (d) {return d}).call(_drawRects);
bMap.zoomGroup.append('text').call(_drawTextLabel);
if(config.needMini) bMapBrush.brushEvent();
};
if(gene.exons == undefined){
if(verbose) console.info(urls.exons(gene.gencodeId));
d3.json(urls.exons(gene.gencodeId), function(err, exonJson){ // retrieve exons
gene.exons = gtexBubbleMapDataUtil.parseExon(exonJson);// store the exons object as an attribute of the gene object
_render();
});
}
else{
_render();
}
}
function addLD(){
var top = (config.needMini)?parseInt(d3.select('#' + config.bbMapCanvasDiv).select('canvas').attr('height')):50; // TODO: remove hard-coded values
// TODO - Figure out why this isn't matched with padding. - Kane
d3.select('#'+config.ldCanvasDiv).attr({style:'position: relative; top: '+top+'px; left:'+bMap.getPadding().left+'px;'});
if(config.ldData === undefined){
var url = urls.ld(gene);
if(verbose) console.info(url);
$.ajax({
'url': url,
type: 'GET',
xhrFields: {
withCredentials: false
},
'success': function (data) {
// This is a fix for a race condition ---
// self.querying keeps track of what gene name is being
// queried for the LD Plot. If we're still querying the
// same gene when the LD Plot AJAX request resolves it is
// rendered. Otherwise the query is outdated and ignored.
if (geneId === self.querying) {
config.ldData = {};
data.ld.forEach(function (pair) {
config.ldData[pair[0]] = pair[1];
});
if (bMapBrush) {
bMapBrush.addEvent(drawLD);
}
drawLD();
}
else {
config.ldData = {} // erase ld data?
}
}
})
}
else {drawLD();}
}
function drawLD(){
var min = config.ldCutoff; // minimum LD value cutoff
var cellW = (bMap.scale.X.range()[1] - bMap.scale.X.range()[0]); // somehow it's different from bMap.scale.rangeBand())
var _cscale = d3.scale.linear()
.domain([0, 1])
.range(['#fff', '#000']);
var xlist = bMapBrush ? bMapBrush.xlist : bMap.scale.X.domain(); // updates the x range based on the brush range
// otherwise select the full range.
var _buildPairs = function(){
var ld = config.ldData;
var pairs = [];
xlist.forEach(function (x, i) {
xlist.forEach(function (x2, j) {
var r2 = ld[x + ',' + x2] || ld[x2 + ',' + x] || undefined;
if(i == j) pairs.push({x: x, y: x2, 'r2': 1});
if (i <= j && r2 != undefined && r2 > min) pairs.push({x: x, y: x2, 'r2': r2}); // when there's no data, the pair won't be included
})
});
return pairs;
};
// LD canvas always rerender based on the range of the brush
var data = _buildPairs(xlist); // LD pairs could change based on the eqtl data in view, so it is built each time
// create overlaying SVG and canvas
//var width = bMap.scale.X.range()[bMapBrush.xlist.length-1] + cellW; // annoying, should think of a better way to determine the width
var width = bMap.scale.X.range()[(bMapBrush ? bMapBrush.xlist.length : bMap.scale.X.domain().length)-1] + cellW; // annoying, should think of a better way to determine the width
var height = width;
d3.select('#'+config.ldCanvasDiv).style('height', height + 'px');
var _createCanvas = function(){
d3.select('#'+config.ldCanvasDiv).select('canvas').remove();
return d3.select('#' + config.ldCanvasDiv).append('canvas')
.attr({
width: width,
height: height
})
.style({
//border: '1px solid #eee',
position:'absolute',
top:0,
left:0
});
};
var _transformCanvas = function(canvas, left, top){
var context = canvas.node().getContext('2d');
context.translate(left , top); // shift the radius distance...
context.rotate(Math.PI*(-45/180));
};
var _createPosScale = function(){
return{
pos: function (d) {
// Use i to fetch and align with the bubble map position
// bMap.scale.X.range()[i] is the center of the bubble
var i = xlist.indexOf(d);
if (i == -1) return undefined;
return this.band() * i;
},
data: function () {
return data
},
band: function () {
return cellW / Math.sqrt(2);
},
index: function (d) {
var i = xlist.indexOf(d);
if (i == -1) return undefined;
return i;
}
}
};
var _drawCanvas = function(canvas, xScale, snp){
var context = canvas.node().getContext('2d');
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
var positions = [];
// Must be between 0.5 and 1.0
//var scaling = 3/4;
var scaling = 1;
xScale.data().forEach(function(d){
var x, y, xBand, yBand, shiftValue, xShift, yShift;
positions.push({x:xScale.pos(d.x), y:xScale.pos(d.y)});
context.beginPath();
context.fillStyle = _cscale(d.r2);
//context.rect(xScale.pos(d.x), xScale.pos(d.y), xScale.band(), xScale.band());
xBand = xScale.band();
yBand = xScale.band();
shiftValue = Math.abs(xScale.index(d.x) - xScale.index(d.y));
xShift = shiftValue * (1 - scaling) * xBand;
// TODO: Check (cellW / 4) offset for alignment. - Kane
yShift = -shiftValue * (1 - scaling) * yBand + (cellW / 4);
x = xScale.pos(d.x) + xShift;
y = xScale.pos(d.y) + yShift;
context.moveTo(x, y);
context.lineTo(x + (scaling * xBand), y + ((1 - scaling) * yBand));
context.lineTo(x + xBand, y + yBand);
context.lineTo(x + ((1 - scaling) * xBand), y + (scaling * yBand));
//context.rect(x, xScale.pos(d.y), xScale.band(), xScale.band());
context.fill();
// SNP highlight during mouseover
if(typeof(snp) != 'undefined' && (d.x == snp || d.y == snp)){
context.lineWidth = 1;
context.strokeStyle = '#fd8c94';
context.stroke();
}
context.closePath();
});
};
var _createSvg = function(){
d3.select('#'+config.ldCanvasDiv).select('svg').remove();
return d3.select('#'+config.ldCanvasDiv).append('svg')
.attr({
id:'ldSvg',
width:width,
height:height
})
.style({
position:'absolute',
top:0,
left:0,
cursor: 'none'
});
};
var _drawLines = function(){
// NOTE: this function renders the vertical lines that aid alignment between the SNP labels to the LD matrix
// However, it is rendered in SVG in bMap.zoomGroup because it's easier to implement in SVG
var initY = bMap.scale.Y(mat.y[mat.y.length-1]) + (1.7*bMap.scale.Y.rangeBand()) + 150; // TODO: get rid of hard-coded value
// vertical lines between the LD to SNP labels
// Note: these lines are drawn on the bMap not LD svg
var id = 'ldWrapper'; // TODO: hard-coded
var _createGroup = function(){
// create a nested group
return bMap.zoomGroup.append('g')
.attr('id', id) // this inner group is for rendering the triangle map
.classed('additionalRow', true);
};
var g = bMap.zoomGroup.select('#' + id);
if(g.empty()) g = _createGroup();
var lines = g.selectAll('line').data(xlist, function (d) {return d});
lines.enter().append('line');
lines.exit().remove();
lines.attr({
x1: function (d) {return bMap.scale.X(d)},
x2: function (d) {return bMap.scale.X(d)},
y1: initY,
y2: initY + 80,
stroke: '#cdcdcd',
'stroke-width': 1,
col: function(d){return d}
})
.classed('ldline', true);
};
var _getRad = function(theta){
return Math.PI*(theta/180);
};
var _highlight = function(svg, id, scale, dlist){
var g = svg.select('#'+id).empty()? svg.append('g').attr('id', id):svg.select('#'+id);
var line = d3.svg.line()
.x(function (d) {return d.x;})
.y(function (d) {return d.y;});
var lines = g.selectAll('path').data(dlist, function (d){
return d.x + d.y;
});
lines.enter().append('path');
lines.exit().remove();
lines.attr({
'd': function (d) {
var x, y, xBand, yBand, shiftValue, xShift, yShift;
var scaling = 1;
xBand = scale.band();
yBand = scale.band();
shiftValue = Math.abs(scale.index(d.x) - scale.index(d.y));
xShift = shiftValue * (1 - scaling) * xBand;
yShift = -shiftValue * (1 - scaling) * yBand + (cellW / 4);
x = scale.pos(d.x) + xShift;
y = scale.pos(d.y) + yShift;
var points = [
{ 'x': x, 'y': y },
{ 'x': x + (scaling * xBand), 'y': y + ((1 - scaling) * yBand) },
{ 'x': x + xBand, 'y': y + yBand },
{ 'x': x + ((1 - scaling) * xBand), 'y': y + (scaling * yBand)}
];
return line(points) + 'Z';
},
'fill': 'none',
'stroke': 'grey',
'stroke-width': 1
});
return lines;
/*
var rect = g.selectAll('rect').data(dlist, function(d){return d.x+ d.y});
rect.enter().append('rect');
rect.exit().remove(); // remove rect that are no longer needed
rect.attr({
width: scale.band(),
height: scale.band(),
x:function(d){return scale.pos(d.x)},
y:function(d){return scale.pos(d.y)},
fill: 'none',
stroke: 'grey',
'stroke-width': 1
});
return rect;
*/
};
var _addSvgEvents = function(svg, cursor, band){
svg.on('mousemove', function(){
cursor.attr('display','');
d3.selectAll('.xlab').classed('textMouseover', false);
d3.selectAll('.ldLine').classed('bubbleMouseover', false);
var pos = d3.mouse(this); // relative to the SVG
var x = pos[0];
var y = pos[1]; // minus cellW so that the mouse pointer stays to the lower right corner of the pointed cell
var rad = _getRad(45);
x2 = x*Math.cos(rad) - y*Math.sin(rad);
y2 = x*Math.sin(rad) + y*Math.cos(rad) - band;
// TODO: Check offset for alignment. - Kane
var i = Math.floor(x2/band) + 1;
var j = Math.floor(y2/band);
var show = true;
var rsq = config.ldData[xlist[i] + ',' + xlist[j]] || config.ldData[xlist[j] + ',' + xlist[i]];
if(xlist[i] == xlist[j]) {
rsq = 1;
}
else if(typeof(rsq) === 'undefined' ) {show = false;}
if(show){
var message = xlist[i] + '-' + xlist[j] + ': ' + rsq.toPrecision(3);
bMap.tooltip.show(message);
cursor.attr('stroke','red').attr('transform', 'translate'+ '(' + x+ ',' + y +') rotate(-45)');
var colSelect = '[col="' + xlist[i] + '"]';
var colSelect2 = '[col="' + xlist[j] + '"]';
d3.selectAll('.xlab'+colSelect).classed('textMouseover', true);
d3.selectAll('.xlab'+colSelect2).classed('textMouseover', true);
d3.selectAll('.ldLine' + colSelect).classed('bubbleMouseover', true);
d3.selectAll('.ldLine' + colSelect2).classed('bubbleMouseover', true);
}
else{
bMap.tooltip.hide();
cursor.attr('stroke','#ddd').attr('transform', 'translate'+ '(' + x+ ',' + y +') rotate(-45)');
}
})
svg.on('mouseleave', function(){
d3.selectAll('.xlab').classed('textMouseover', false);
d3.selectAll('.lbLine').classed('bubbleMouseover', false);
cursor.attr('display','none');
})
};
var _drawLdLegend = function(svg, ldTitle) {
var g = svg.append('g').attr('id', '#ldLegend');
var domain = [0.1, 1];
//var range = ['#ffffff', '#cccccc', '#b3b3b3', '#999999', '#808080', '#666666', '#4d4d4d', '#333333', '#1a1a1a', '#000000'];
var range = ['#f7f7f7', '#000000'];
//var range = ['#000000', '#1a1a1a', '#333333', '#4d4d4d', '#666666', '#808080', '#999999', '#b3b3b3', '#cccccc', '#ffffff'];
var scale = d3.scale.linear()
.domain(domain)
.range(range);
var cellW = (bMap.scale.X.range()[1] - bMap.scale.X.range()[0]); // somehow it's different from bMap.scale.rangeBand())
var w = cellW;
// legend title
//var initX = 10 + 10 - 10 + (cData.length + 2) * w + 10 + (rData.length + 2) * w + 100;
//var initY = 20;
var initX = 10;
var initY = 60;
g.append('text')
.text(ldTitle)
.attr({
x: 0,
y: 0,
'font-size': 10,
fill: 'black',
transform: 'translate(' + initX + ', ' + (initY + 150) + ') rotate(-90)'
});
// rectangles
var data = d3.range(0, 1.1, 0.1);
initX += 10;
initY += 30;
var colors = [];
g.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr({
width: w,
height: w,
x: initX,
y: function (d, i) {return initY + i * w;},
fill: function (d) {
colors.push(scale(d));
return scale(1 - d)
}
});
data = data.map(function (d) {
return (1 - d).toFixed(1);
});
// axis labels
g.selectAll('.ldLabels')
.data(data)
.enter()
.append('text')
.text(function (d) {
return d;
})
.attr({
x: initX + 10 + w,
y: function (d, i) {return initY + i * w + 2},
'font-size': 6,
fill: function (d, i) {return i%2 == 1 ? 'black': '#aaa'}
});
};
var canvas = _createCanvas();
var pScale = _createPosScale();
_transformCanvas(canvas, pScale.band()/2, pScale.band());
_drawCanvas(canvas, pScale);
_drawLines(xlist);
var svg = _createSvg();
_drawLdLegend(svg, config.ldTitle);
//Mouse Events
//var ghost = _highlight(svg, pScale, data);
var cursor = _highlight(svg, 'ldCursor', pScale, data.slice(0,1));
cursor.attr('display', 'none'); // hide it by default
_addSvgEvents(svg, cursor, pScale.band());
xLabelMouseOverEvents.push(function(snp){
var filtered = data.filter(function(d){return d.x == snp || d.y == snp});
var boxes = _highlight(svg, 'ldHighlight', pScale, filtered);
boxes.attr('stroke','red').attr('transform', 'translate('+pScale.band()/2 +',' + pScale.band() + ') rotate(-45)');
});
xLabelMouseOutEvents.push(function(){svg.select('#ldHighlight').selectAll('path').remove()});
}
function addDataFilters(){
var _storeFilter = function(name, callback){
dataFilters[name]['func'] = callback;
};
// create two data filter functions (using closure)
var _reportFilterResults = function(){
var l = mat.data.filter(function(d){
var temp = d.filters?d3.values(d.filters).filter(function(d){return d}):[];
return temp.length > 0;
})
.length;
var L = mat.data.length;
var after = L - l;
if(l > 0){
$('#filterInfo').show(); // Warning: hard-coded div name
$('#filterInfo').text('Remaining number of eQTLs: ' + after + ' (' + (after/L*100).toFixed(2) + '%)'); // reports the #eQTLs after filtering
}
else{
$('#filterInfo').hide();
}
};
var _createFilter = function (x, isMax, useAbs) { //x is a key in this.mat.data, isMax is boolean for maximum or minimum cutoff
// this function creates a filter function
var myfilter = function (v, state) {
if (undefined === state) {
state = 'dataFilter';
}
dataFilters[x]['value'] = v; // store the current filter value
var fClass = x + 'Filtered';
// var fClass = 'filtered';
if (useAbs) {
v = Math.abs(v);
}
var __smallerEqual = function (d) {
return useAbs ? Math.abs(d[x]) <= v : d[x] <= v;
};
var __largerThan = function (d) {
return useAbs ? Math.abs(d[x]) > v : d[x] > v;
};
if (isMax) {
// TODO: to be implemented
}
else {
var __failed = function (selected) {
selected.filter(__smallerEqual)
.classed(fClass, true)
};
var __passed = function (selected) {
selected.filter(__largerThan)
.classed(fClass, false);
};
mat.data.filter(
function(d){
if(typeof d.filters == 'undefined') d.filters = {};
d.filters[x] = useAbs ? Math.abs(d[x]) <= v : d[x] <= v; // true means the data point will be filtered
}
);
rerender(state);
// update bMap, using DOM class is faster than rerendering the SVG
var zoomCircles = bMap.zoomGroup.selectAll('.dcircle');
zoomCircles.call(__failed);
zoomCircles.call(__passed);
}
};
// store the filters in this.filters, for plot refreshing purposes
_storeFilter(x, myfilter);
return myfilter;
};
var _filterP = _createFilter('r', false, false); // note: r = -log10(p)
var _filterE = _createFilter('value', false, true); // note: value = effect size
var _filterLD = _createFilter('ld', false, false); // note: ld = linkage disequilibrium
var _addMouseEvents = function(){
$('#pvalueSlider').on('change mousemove', function(){
var v = $(this).val();
$('#pvalueLimit').val(v);
_filterP(parseFloat(v));
_reportFilterResults();
});
$('#pvalueLimit').keydown(function(e){
if(e.keyCode == 13){
var v = $('#pvalueLimit').val();
$('#pvalueSlider').val(v);
_filterP(parseFloat(v));
_reportFilterResults();
}
});
$('#effectSizeSlider').on('change mousemove', function(){
var v = $(this).val();
$('#effectSizeLimit').val(v);
_filterE(parseFloat(v));
_reportFilterResults();
});
$('#effectSizeLimit').keydown(function(e){
if(e.keyCode == 13){
var v = $('#effectSizeLimit').val();
$('#effectSizeSlider').val(v);
_filterE(parseFloat(v));
_reportFilterResults();
}
});
$('#linkageDisequilibriumSlider').on('change mousemove', function () {
var v = $(this).val();
config.ldCutoff = parseFloat(v);
$('#linkageDisequilibriumLimit').val(v);
_filterLD(parseFloat(v), 'ldFilter');
_reportFilterResults();
});
$('#linkageDisequilibriumLimit').keydown(function(e){
if(e.keyCode == 13){
var v = $('#linkageDisequilibriumLimit').val();
config.ldCutoff = parseFloat(v);
$('#linkageDisequilibriumSlider').val(v);
_filterLD(parseFloat(v), 'ldFilter');
_reportFilterResults();
}
});
};
_addMouseEvents();
}
};
| 40.522663 | 185 | 0.463421 |
93945a904dde0eeec2b29926f492ee3ddd3909d8 | 444 | js | JavaScript | src/types/Epoch.js | brianneisler/flareon | e6befbc945f4d40729df08267bb5fd91db532b65 | [
"MIT"
] | null | null | null | src/types/Epoch.js | brianneisler/flareon | e6befbc945f4d40729df08267bb5fd91db532b65 | [
"MIT"
] | null | null | null | src/types/Epoch.js | brianneisler/flareon | e6befbc945f4d40729df08267bb5fd91db532b65 | [
"MIT"
] | null | null | null | import { expect } from '../lang/assertion'
import { extend } from '../lang/lang'
import { mod } from '../lang/math'
import Number from './Number'
const Epoch = extend(Number, {
name: 'Epoch',
description: 'Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC, with leap seconds ignored',
validate: (value, schema, _super) => expect(mod(value, 1)).to.equal(0).and(_super(value))
})
export default Epoch
| 37 | 132 | 0.704955 |
9394e34b8be73c8cb99a6b4f4a7f82fcb3564e13 | 2,358 | js | JavaScript | Nodejs_Server/autofood.js | junyanl-code/IOT_Pro | c5e9264413d246896d71dcfefd7c2fd0f1361ffb | [
"MIT"
] | 1 | 2020-03-13T03:17:31.000Z | 2020-03-13T03:17:31.000Z | Nodejs_Server/autofood.js | junyanl-code/iot-yj | c5e9264413d246896d71dcfefd7c2fd0f1361ffb | [
"MIT"
] | null | null | null | Nodejs_Server/autofood.js | junyanl-code/iot-yj | c5e9264413d246896d71dcfefd7c2fd0f1361ffb | [
"MIT"
] | null | null | null | var mysql = require('mysql');
var schedule = require('node-schedule');
var conn = mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'nodemysql',
port:3306
});
conn.connect();
function change(x){
switch(x){
case 1:
console.log("type1");
var j =schedule.scheduleJob('feed','12 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
break;
case 2:
console.log("type2");
var j =schedule.scheduleJob('feed','9 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
var k =schedule.scheduleJob('feed','15 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
break;
case 3:
console.log("type3");
var j =schedule.scheduleJob('feed','8 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
var k =schedule.scheduleJob('feed','12 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
var l =schedule.scheduleJob('feed','18 * * * *',function(){
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
});
break;
default:
console.log("error");
break;
}
}
function check(x){
conn.query('select * from autofood', function(err,rows,fields){
let len = rows.length;
let tem = rows[len-1].type;
if (tem !== x) {
if (schedule.scheduledJobs['feed']) {
var result = schedule.cancelJob('feed');
console.log("关闭当前定时: ")
console.log(result)
}
big()
}else{
console.log("same")
}
})
}
function big(){
conn.query('select * from autofood',function(err,rows,fields){
var i = rows.length;
var tem = rows[i-1].type;
console.log(tem);
change(tem)
console.log(schedule.scheduledJobs)
setInterval(function(){
check(tem)
},3000)
})
}
big();
| 23.818182 | 79 | 0.596692 |
9395a195cd8f814e27aa1d9ec60c2bdfbaf68c61 | 1,145 | js | JavaScript | lesson30/app.js | mannysys/express4-demo | 1c075462fb5bb80b969bee006b2980668c2ebd85 | [
"MIT"
] | null | null | null | lesson30/app.js | mannysys/express4-demo | 1c075462fb5bb80b969bee006b2980668c2ebd85 | [
"MIT"
] | null | null | null | lesson30/app.js | mannysys/express4-demo | 1c075462fb5bb80b969bee006b2980668c2ebd85 | [
"MIT"
] | null | null | null | /**
* Created by shadow on 16/2/10.
*/
'use strict';
const express = require('express');
const app = express();
const consolidate = require('consolidate');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const bodyParser = require('body-parser');
app.use(cookieParser());
app.use(session({
secret: 'xxxx',
cookie:{maxAge:2000000}
}));
app.use(bodyParser());
app.engine('html',consolidate.ejs);
app.set('view engine','html');
app.set('views',__dirname + '/views');
//生成随机数
function generateRandomNum(x){
if(!x) x = 10;
return Math.round(Math.random() * x);
}
app.get('/validate',function(req,res){
const a = generateRandomNum();
const b = generateRandomNum();
req.session.a = a;
req.session.b = b;
res.locals.msg = `
${a} + ${b} =
`;
res.render('validate');
});
app.post('/validate',function(req,res){
var a = req.session.a;
var b = req.session.b;
var sum = a + b;
//parseInt转换类型
if(parseInt(req.body.sum) === sum){
res.send('success');
}else{
res.send('error');
}
});
app.listen(3000); | 17.615385 | 46 | 0.604367 |
9396058e88d302d6cb598a8c94b839cb8a9942de | 1,223 | js | JavaScript | src/components/desktopSidebarOpenButton.js | Bazif-Khan/appsody-website | 665073857afce7dfab6fd38104de98137964512c | [
"Apache-2.0"
] | 11 | 2019-06-27T11:42:48.000Z | 2021-11-08T12:46:45.000Z | src/components/desktopSidebarOpenButton.js | Bazif-Khan/appsody-website | 665073857afce7dfab6fd38104de98137964512c | [
"Apache-2.0"
] | 325 | 2019-06-27T07:52:36.000Z | 2020-10-03T21:15:20.000Z | src/components/desktopSidebarOpenButton.js | Bazif-Khan/appsody-website | 665073857afce7dfab6fd38104de98137964512c | [
"Apache-2.0"
] | 42 | 2019-06-27T07:49:46.000Z | 2020-10-03T21:13:43.000Z | import React from "react"
import styles from "../styles/desktopSidebarOpenButton.module.css"
const DesktopSidebarOpenButton = () => {
function openDesktopSidebar() {
window.sidebarOpen = true;
document.getElementById("accordion").style.display="block"
document.getElementById("sidebar").style.marginLeft= "0";
document.getElementById("desktop-hamburger-icon" ).style.marginLeft= "0";
document.getElementById("documents-window").style.paddingLeft = "23em";
document.getElementById("desktopHamburgerOpenbtnId").style.display = "none";
document.getElementById("appsody-sidebar-header").style.writingMode = "horizontal-tb";
document.getElementById("appsody-sidebar-header").style.marginLeft = "1.5rem";
document.getElementById("docs-sidebar-header").style.writingMode = "horizontal-tb";
document.getElementById("docs-sidebar-header").style.marginLeft = "0.25em";
}
return (
<section id="desktopHamburgerOpenbtnId" className={styles.desktopHamburgerOpenbtn} onClick={() => openDesktopSidebar()}>
<span></span>
<span></span>
<span></span>
</section>
)
}
export default DesktopSidebarOpenButton | 43.678571 | 125 | 0.69583 |
93969b51a1be08343b9f1130e581638fd877cde2 | 2,510 | js | JavaScript | js-utilities/date-in-sequenza.js | massimo-cassandro/front-end-utilities | 9a952b277d5ea740a44a9404d436e86396aece59 | [
"MIT"
] | null | null | null | js-utilities/date-in-sequenza.js | massimo-cassandro/front-end-utilities | 9a952b277d5ea740a44a9404d436e86396aece59 | [
"MIT"
] | null | null | null | js-utilities/date-in-sequenza.js | massimo-cassandro/front-end-utilities | 9a952b277d5ea740a44a9404d436e86396aece59 | [
"MIT"
] | null | null | null | export default function (context = document) {
//date in sequenza
/*
l'attributo `data-min` in un campo data indica l'id del campo il cui valore
imposta l'attributo `min` del campo corrente.
Funzionamento analogo per l'attributo `data-max`
Sulla data iniziale → data-max
Sulla data finale → data-min
Se uno dei deu campi viene disabilitato, i vincoli vengono rimossi
*/
// TODO riscrivere DRY
// TODO possibilità di conservare eventuali attributi min/max di default,
// indipendenti dal campo correlato (es: min=now per campo iniziale)
// data iniziale
context.querySelectorAll('input[type="date"][data-max], input[type="datetime-local"][data-max]').forEach(el => {
let campo_correlato = document.getElementById(el.dataset.max);
if(campo_correlato) {
el.setAttribute('max', campo_correlato.value);
campo_correlato.addEventListener('change', () => {
el.setAttribute('max', campo_correlato.value);
});
// l'attributo max viene rimosso se il campo correlato è disabilitato
el.addEventListener('focus', () => {
if(campo_correlato.disabled) {
el.removeAttribute('max');
} else {
// ripristina max
el.setAttribute('max', campo_correlato.value);
}
}, false);
}
});
// data finale
context.querySelectorAll('input[type="date"][data-min], input[type="datetime-local"][data-min]').forEach(el => {
let campo_correlato = document.getElementById(el.dataset.min);
if(campo_correlato) {
// NON funziona => verificare
// console.log(campo_correlato);
// console.log(campo_correlato.value);
// if(campo_correlato.value) { // nel caso fosse presente un'attributo min preimpostato e non fosse ancora impostato il valore iniziale
// el.setAttribute('min', campo_correlato.value);
// } else if(campo_correlato.getAttribute('min')) {
// console.log(campo_correlato.getAttribute('min'));
// el.setAttribute('min', campo_correlato.getAttribute('min'));
// }
campo_correlato.addEventListener('change', () => {
el.setAttribute('min', campo_correlato.value);
});
// l'attributo min viene rimosso se il campo correlato è disabilitato
el.addEventListener('focus', () => {
if(campo_correlato.disabled) {
el.removeAttribute('min');
} else {
// ripristina max
el.setAttribute('min', campo_correlato.value);
}
}, false);
}
});
}
| 32.179487 | 141 | 0.650199 |
9396e56f75e85ad7c4caa65af52fb7d8324d562c | 1,375 | js | JavaScript | mongo-select-tokens.js | immanuelfodor/rocketchat-push-gateway | ad956c866d7a4e5df74246b73dd8b6f3c9502491 | [
"WTFPL"
] | 37 | 2019-05-03T17:38:05.000Z | 2022-03-31T08:11:09.000Z | mongo-select-tokens.js | immanuelfodor/rocketchat-push-gateway | ad956c866d7a4e5df74246b73dd8b6f3c9502491 | [
"WTFPL"
] | 1 | 2021-05-07T15:26:58.000Z | 2021-05-25T18:44:59.000Z | mongo-select-tokens.js | immanuelfodor/rocketchat-push-gateway | ad956c866d7a4e5df74246b73dd8b6f3c9502491 | [
"WTFPL"
] | 5 | 2020-08-07T03:06:26.000Z | 2022-01-03T10:36:19.000Z | // get one enabled gcm push token of all active non-bot users
printjson(db.getCollection("users").aggregate([
{
$match: {
type: "user",
active: true
}
},
{
$lookup: {
from: "_raix_push_app_tokens",
let: {
uId: "$_id"
},
pipeline: [ // this is a left outer join
{
$match: {
$expr: {
$and:
[
{ $eq: [ "$userId", "$$uId" ] },
{ $eq: [ "$enabled", true ] }
]
}
}
},
{
$limit: 1 // we need just one enabled token per user for the gateway to work
}
],
as: "push"
}
},
{
$match: {
"push.token.gcm": {
$exists: true // no love for iOS users :(
}
}
},
{
$project: {
_id: 0,
uid: "$_id",
uname: "$username",
token: {
$arrayElemAt: [ "$push.token.gcm", 0 ] // at least one token exists at this stage
}
}
}
]).toArray());
| 26.442308 | 98 | 0.303273 |
939793c71e0d151fc98c6cd48ad988769bc31094 | 11,510 | js | JavaScript | src/components/Avatar/Parts/mouths/mouth-9.js | doc22940/thumb-friends-app | fb588cf696a2f0d9900a6cff79d3e5c4ad082db4 | [
"MIT"
] | 7 | 2020-12-02T03:01:55.000Z | 2021-06-28T13:24:12.000Z | src/components/Avatar/Parts/mouths/mouth-9.js | doc22940/thumb-friends-app | fb588cf696a2f0d9900a6cff79d3e5c4ad082db4 | [
"MIT"
] | null | null | null | src/components/Avatar/Parts/mouths/mouth-9.js | doc22940/thumb-friends-app | fb588cf696a2f0d9900a6cff79d3e5c4ad082db4 | [
"MIT"
] | 3 | 2020-12-20T01:49:33.000Z | 2022-03-26T03:42:52.000Z | import React from 'react';
/* eslint-disable max-len,no-tabs,camelcase */
const Mouth_9 = ({ skinColours, lipColours }) => {
const colour0 = lipColours.base;
const colour1 = lipColours.base;
const colour2 = lipColours.shadow;
const colour3 = '#40332E';
const colour4 = '#3B2E2A';
const colour5 = '#342723';
const colour6 = '#231A18';
const colour7 = '#FFFEF0';
const colour8 = '#FFE9CF';
const colour9 = '#EC4845';
const colour10 = '#F26767';
const colour11 = '#F37D79';
const colour12 = '#F58E87';
const colour13 = lipColours.base;
const colour14 = '#F2D5B2';
const colour15 = '#F8B2B3';
return (
<>
<g>
<path
fill={colour0}
d="M479.6,651.2c-0.2-2.5-158.8-10.6-158.5,6.4c0.3,17.8,21.7,55.8,30.6,66.8c13.4,16.6,74.6,17.6,91.7,1.6
C471.1,699.8,480.1,658.6,479.6,651.2z"
/>
<path
fill={colour1}
d="M320.6,656.9c0.3-12,6.7-106.4,28.4-120.2c21.7-13.8,37.1,6,48.5,4c11.4-2.1,33.7-11.6,44-6.8
c22.6,10.5,38.2,110.7,38.6,115.1c0.4,4.1-10.2,45.4-38,71.6c-17,16.1-75.4,15.9-88.8-0.8C344.4,708.8,320.3,666.5,320.6,656.9z"
/>
<path
fill={colour2}
d="M480.1,649c-0.2-2.5-5.6-37.4-14.5-68.3c-6.9,3.6-52.4-25-57-42.9c-4.2,1.2-8.1,2.3-11.1,2.9
c-3.9,0.7-8.3-1.2-13.3-3.4c-1.7,16.3-35.7,46-55.2,47.9c-6,30.5-8.2,64.8-8.4,71.7c-0.3,9.5,22.2,53.5,31.1,64.5
c13.4,16.6,74.6,17.7,91.7,1.6C471.1,696.7,480.5,653.1,480.1,649z M450.5,709.1c-6.9,9.2-27.6,22-51.6,22
c-32,0-48.1-12.3-52.9-22.8c-28.8-63.1,27.3-45.6,51.3-45.6C421.3,662.8,500.2,642.9,450.5,709.1z"
/>
<path
fill={colour0}
d="M323.2,654.5c-0.4,3.5,25.5,48.1,76.7,46.5c56.5-1.8,75.8-51.3,75.8-51.3c-11.5-69-42-91.2-75-91.4
C353.7,558.1,328.4,604.1,323.2,654.5z"
/>
<path
fill={colour3}
d="M323.5,653.2c-0.4,3.3,26.4,46.9,76.3,45.4c55.1-1.7,75.4-50.1,75.4-50.1c-11.2-66.3-44.3-86.7-74.7-87
C354.7,561,328.6,604.7,323.5,653.2z"
/>
<path
fill={colour4}
d="M334.9,654.9c-0.3,2.9,22.5,40.1,64.8,38.8c46.8-1.5,64-42.9,64-42.9c-9.5-57.7-37.6-74.1-63.5-74.4
C361.4,576.1,339.2,612.7,334.9,654.9z"
/>
<path
fill={colour5}
d="M348.8,658.3c-0.2,2.2,17.2,30.5,49.8,29.5c35.9-1.1,49.2-32.6,49.2-32.6c-7.3-43.9-28.9-56.4-48.7-56.6
C369.2,598.3,352.1,626.2,348.8,658.3z"
/>
<path
fill={colour6}
d="M363,660.2c-0.2,1.6,12.3,21.8,35.5,21c25.6-0.8,35-23.3,35-23.3c-5.2-31.3-20.6-40.2-34.7-40.3
C377.5,617.5,365.4,637.4,363,660.2z"
/>
<path
fill={colour5}
d="M389.8,617.9c12.7-2.2-1.2,20.1,8.3,20.8c13.6,0.9-4.6-24.8,11.9-19.3c0,0-4.5-6.2-13.2-6.8
C388.2,612.1,389.8,617.9,389.8,617.9z"
/>
<path
fill={colour7}
d="M346.4,605.3c-2.2,0.1-2.7-5.6,1-11.5c3.6-5.9,22.9-27.9,51.3-27.9c28.4-0.1,47.8,15.8,56.4,30.7
c2.2,3.8,1.8,8.6-0.1,9.1c-1.9,0.4-17.7-15.4-54.8-15.5C366.1,590,348.6,605.2,346.4,605.3z"
/>
<path
fill={colour8}
d="M455,603c-1.9,0.4-18.4-14.9-55.5-15c-34.2-0.1-51,14.6-53.2,14.7c-0.8,0-1.4-0.7-1.6-2
c-0.4,2.8,0.3,4.7,1.6,4.6c2.2-0.1,19.3-14.5,53.5-14.5c37,0.1,53.2,15.3,55.1,14.8c1.2-0.3,1.8-2.4,1.5-4.9
C456.3,602,455.8,602.8,455,603z"
/>
<path
fill={colour9}
d="M409.4,647.2l42.1,17.5l11.7-6.5C456,643.4,428.4,643,409.4,647.2z"
/>
<path
fill={colour9}
d="M383.9,647.2l-36.7,19.4l-11.7-6.5C342.7,645.3,364.9,643,383.9,647.2z"
/>
<path
fill={colour10}
d="M337.7,662.6c7.6-6.3,21.4-23.8,57.9-12.2c0,0,47.9-15.6,65.2,11.2C464.2,669,388.5,716.9,337.7,662.6z"
/>
<path
fill={colour11}
d="M341.6,663.7c7.1-5.9,19.8-24.2,54-13.3c0,0,45.1-12.8,61.3,12.3C460.1,669.7,389.2,714.6,341.6,663.7z"
/>
<path
fill={colour12}
d="M396.5,653.1c-1-4.3-15.7-8.1-29.4-5.7c-13.7,2.4-24.9,10.3-24.2,14.6c0.8,4.3,16.7,8.5,30.5,6.1
C387.2,665.7,398.5,662.1,396.5,653.1z"
/>
<path
fill={colour12}
d="M397.8,657.3c4.3-8.7,14.8-11.4,28.6-10.6c13.9,0.8,28.4,7.4,28.1,11.8c-0.3,4.4-21.6,12.4-35.4,11.6
C405.3,669.3,393.7,665.6,397.8,657.3z"
/>
<g>
<path
fill={colour10}
d="M396.1,657.7c1.4-4.4,5-7.6,9.9-9.9c-6.3,1.2-10.4,2.6-10.4,2.6c-0.9-0.3-1.7-0.5-2.6-0.8
C395.2,651.2,396.1,653.6,396.1,657.7z"
/>
<path
fill={colour10}
d="M460.7,661.6c-1.7-2.7-3.8-4.9-6-6.8c-4.9,6-68,28.2-111.4,2.9c-2.2,1.9-4.1,3.7-5.6,5
C388.5,716.9,464.2,669,460.7,661.6z"
/>
</g>
<path
fill={colour7}
d="M333,663.9c0,0,1-4.6,4.2-3.9c3.3,0.7,28.4,13,55.9,13.3c42.4,0.5,68.1-17.9,70.6-15.7
c2.5,2.2,1.4,4.4,1.4,4.4s-24.4,38.5-73.1,34.3C350.3,692.7,333,663.9,333,663.9z"
/>
<path
fill={colour13}
d="M405.7,727.1c11.5-2.6,22.1-12.9,16.2-15.6c-17.7-8-79.1-8.5-65.2,3.3C370.2,726.2,399.3,728.6,405.7,727.1z"
/>
<path
fill={colour4}
d="M392.3,592.8c-0.2-0.1-0.3-0.2-0.3-0.4s0.1-0.3,0.3-0.4c2.5-0.9,3.9-3.9,3.9-8.4c0,0,0.4,5.7,2.6,7.6
c0.2,0.2,0.3,0.4,0.3,0.7c0,0.3-0.2,0.5-0.4,0.6c-0.8,0.4-1.9,0.9-3.1,0.8C394.4,593.4,393.2,593.1,392.3,592.8z"
/>
<path
fill={colour4}
d="M425.3,594.5c-0.1-0.1-0.2-0.2-0.2-0.2c0-0.1,0.1-0.1,0.3-0.1c2.1,0.1,3.5-1.1,4.1-3.3c0,0-0.4,2.9,1.1,4.3
c0.1,0.1,0.2,0.3,0.1,0.4c-0.1,0.1-0.2,0.2-0.4,0.2c-0.7,0-1.6,0-2.5-0.3C426.8,595.2,425.9,594.8,425.3,594.5z"
/>
<path
fill={colour14}
d="M347.1,598.1c3.6-5.9,22.8-25.2,51.2-25.2c28.4-0.1,48.5,13.4,57.1,28.4c0.5,0.8,0.8,1.7,1,2.5
c0.6-2.1,0.5-5.5-1-8c-8.6-14.9-28.7-32-57.1-32c-28.4,0.1-47.6,22.9-51.2,28.8c-2.5,4.1-2.9,8.7-2.2,11.1
C345.3,601.9,346,599.9,347.1,598.1z"
/>
<path
fill={colour7}
d="M333,663.9c0,0,1-4.6,4.2-3.9c3.3,0.7,28.4,13,55.9,13.3c42.4,0.5,68.1-17.9,70.6-15.7
c2.5,2.2,1.4,4.4,1.4,4.4s-24.4,36.7-73.1,32.5C350.3,690.9,333,663.9,333,663.9z"
/>
<path
fill={colour8}
d="M337.5,661.6c3.3,0.7,28.4,13,55.9,13.3c42.4,0.5,68.1-17.9,70.6-15.7c0.6,0.6,1,1.1,1.3,1.6
c0.2-0.7,0.3-2.4-1.6-4c-2.5-2.2-28.2,16.2-70.6,15.7c-27.4-0.3-52.6-12.6-55.9-13.3c-3.3-0.7-4.2,3.9-4.2,3.9s0.2,0.4,0.7,1
C334.2,662.9,335.4,661.1,337.5,661.6z"
/>
<path
fill={colour14}
d="M463.7,657.6c-0.1-0.1-0.4-0.2-0.7-0.2c2,7.7-22,35.8-68.1,35.8c-34.2,0-60.6-26-59.3-33.1
c-2,0.8-2.6,3.8-2.6,3.8s17.3,28.8,59,32.4c48.7,4.2,73.1-34.3,73.1-34.3S466.2,659.8,463.7,657.6z"
/>
<path
fill={colour13}
d="M358.4,533.5c-14.6,2.8-18.7,20.4-18.1,24.2c0.7,3.9,30.6-9.5,34.7-17C378,535.3,367.2,531.8,358.4,533.5z"
/>
<path
fill={colour13}
d="M438.2,533.9c-8.5-1.4-21.5,1.5-16.5,9.3c5,7.7,28.7,19.7,30,15.7C454.6,550.5,446,535.1,438.2,533.9z"
/>
<path
fill={colour13}
d="M418.2,540.9c-1.4,1.4-5.5-0.5-4.9-2.3c0.5-1.8,5-1.9,5.7-1.5C419.7,537.5,418.8,540.4,418.2,540.9z"
/>
<path
fill={colour13}
d="M380.4,540.4c-1.7,0.2-4.9-3.8-4.1-4.5c0.8-0.7,4.8,0.9,5.3,1.7C382.1,538.4,381.2,540.3,380.4,540.4z"
/>
<g>
<path
fill={colour0}
d="M412.7,560.3c-6.4-2.9-8.7-7.4-9.3-8.8c1.1,3.3,0.2,8.1,0.2,8.1L412.7,560.3z"
/>
</g>
<polygon
fill={colour14}
points="396.8,695.2 397.1,685.8 399.4,695.2 "
/>
<path
fill={colour15}
d="M425.1,647.9c0-0.5-1-0.9-2.2-0.9s-2.2,0.4-2.2,0.9c0,0.5,1,0.9,2.2,0.9S425.1,648.4,425.1,647.9z"
/>
<path
fill={colour15}
d="M431.4,649.4c0-0.4-0.6-0.6-1.4-0.6c-0.8,0-1.4,0.3-1.4,0.6c0,0.4,0.6,0.6,1.4,0.6
C430.7,650,431.4,649.7,431.4,649.4z"
/>
<path
fill={colour15}
d="M417,650.5c0-0.4-0.6-0.6-1.4-0.6c-0.8,0-1.4,0.3-1.4,0.6c0,0.4,0.6,0.6,1.4,0.6
C416.4,651.2,417,650.9,417,650.5z"
/>
<path
fill={colour10}
d="M450,655.9c0-0.4-0.9-0.8-2-0.8c-1.1,0-2,0.4-2,0.8c0,0.4,0.9,0.8,2,0.8C449.1,656.7,450,656.4,450,655.9z"
/>
<path
fill={colour10}
d="M435.3,660.3c0-0.4-0.9-0.8-2-0.8c-1.1,0-2,0.4-2,0.8c0,0.4,0.9,0.8,2,0.8
C434.4,661.1,435.3,660.8,435.3,660.3z"
/>
<path
fill={colour10}
d="M440.3,655.1c0-0.3-0.5-0.6-1.2-0.6c-0.6,0-1.2,0.3-1.2,0.6c0,0.3,0.5,0.6,1.2,0.6
C439.7,655.7,440.3,655.4,440.3,655.1z"
/>
<path
fill={colour11}
d="M413.1,665.4c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C412.4,666.2,413.1,665.8,413.1,665.4z"
/>
<path
fill={colour11}
d="M408.5,652.3c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C407.8,653.1,408.5,652.7,408.5,652.3z"
/>
<path
fill={colour11}
d="M444,658.4c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C443.3,659.2,444,658.8,444,658.4z"
/>
<path
fill={colour10}
d="M391.5,652.8c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C390.8,653.6,391.5,653.3,391.5,652.8z"
/>
<path
fill={colour15}
d="M379.3,649.1c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C378.6,649.9,379.3,649.5,379.3,649.1z"
/>
<path
fill={colour15}
d="M366,651.1c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C365.2,651.9,366,651.5,366,651.1z"
/>
<path
fill={colour15}
d="M374.3,653c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C373.6,653.8,374.3,653.4,374.3,653z"
/>
<path
fill={colour11}
d="M377.1,665.4c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C376.4,666.2,377.1,665.8,377.1,665.4z"
/>
<path
fill={colour10}
d="M351.9,658c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C351.1,658.8,351.9,658.5,351.9,658z"
/>
<path
fill={colour10}
d="M392.7,659.3c0-0.4-0.7-0.8-1.6-0.8c-0.9,0-1.6,0.4-1.6,0.8c0,0.4,0.7,0.8,1.6,0.8
C392,660.1,392.7,659.7,392.7,659.3z"
/>
<path
fill={colour13}
d="M437.5,716.8c-2,2.9-9.5,5-11.5,4.8c-1.9-0.2,0.5-6.8,2.7-8.1C430.9,712.1,442.1,710.3,437.5,716.8z"
/>
<polygon fill={colour0} points="398,700 399.6,707.5 400.5,700.1 " />
<polygon fill={colour0} points="422,696.5 425.2,701.2 424.2,695.9 " />
<polygon fill={colour2} points="389.5,731.6 388.8,724 387.2,731.2 " />
<polygon fill={colour2} points="358.8,722.8 358.9,717.6 356.9,722.1 " />
<polygon fill={colour2} points="428,726.2 424.9,722.1 426.1,726.9 " />
<polygon fill={colour2} points="450.3,712.2 447.8,705.5 448.4,712.7 " />
<polygon
fill={colour14}
points="396.1,569.1 397.2,576.7 397.9,569.4 "
/>
<polygon fill={colour14} points="370,576.1 371,583.7 371.8,576.3 " />
</g>
</>
);
};
export default Mouth_9;
| 40.10453 | 126 | 0.506082 |
9398bd873b9055244bd52bd0b64c28aa9a5275ac | 9,454 | es6 | JavaScript | packages/client-app/src/flux/tasks/change-labels-task.es6 | cnheider/nylas-mail | e16cb1982e944ae7edb69b1abef1436dd16b442d | [
"MIT"
] | 24,369 | 2015-10-05T16:35:18.000Z | 2017-01-27T15:33:55.000Z | packages/client-app/src/flux/tasks/change-labels-task.es6 | tashby/nylas-mail | 653ff9b44a16468ef37dc109a39ef604d1369ff9 | [
"MIT"
] | 3,209 | 2015-10-05T17:37:34.000Z | 2017-01-27T18:36:01.000Z | packages/client-app/src/flux/tasks/change-labels-task.es6 | tashby/nylas-mail | 653ff9b44a16468ef37dc109a39ef604d1369ff9 | [
"MIT"
] | 1,308 | 2015-10-05T17:14:18.000Z | 2017-01-24T19:36:40.000Z | import _ from 'underscore';
import Thread from '../models/thread';
import Message from '../models/message';
import Category from '../models/category';
import DatabaseStore from '../stores/database-store';
import CategoryStore from '../stores/category-store';
import AccountStore from '../stores/account-store';
import ChangeMailTask from './change-mail-task';
import SyncbackCategoryTask from './syncback-category-task';
// Public: Create a new task to apply labels to a message or thread.
//
// Takes an options object of the form:
// - labelsToAdd: An {Array} of {Category}s or {Category} ids to add
// - labelsToRemove: An {Array} of {Category}s or {Category} ids to remove
// - threads: An {Array} of {Thread}s or {Thread} ids
// - messages: An {Array} of {Message}s or {Message} ids
export default class ChangeLabelsTask extends ChangeMailTask {
constructor(options = {}) {
super(options);
this.source = options.source
this.labelsToAdd = options.labelsToAdd || [];
this.labelsToRemove = options.labelsToRemove || [];
this.taskDescription = options.taskDescription;
}
label() {
return "Applying labels";
}
categoriesToAdd() {
return this.labelsToAdd;
}
categoriesToRemove() {
return this.labelsToRemove;
}
description() {
if (this.taskDescription) {
return this.taskDescription;
}
let countString = "";
if (this.threads.length > 1) {
countString = ` ${this.threads.length} threads`;
}
const removed = this.labelsToRemove[0];
const added = this.labelsToAdd[0];
const objectsAvailable = (added || removed) instanceof Category;
// Note: In the future, we could move this logic to the task
// factory and pass the string in as this.taskDescription (ala Snooze), but
// it's nice to have them declaratively based on the actual labels.
if (objectsAvailable) {
const looksLikeMove = (this.labelsToAdd.length === 1 && this.labelsToRemove.length > 0);
// Spam / trash interactions are always "moves" because they're the three
// folders of Gmail. If another folder is involved, we need to decide to
// return either "Moved to Bla" or "Added Bla".
if (added && added.name === 'spam') {
return `Marked${countString} as Spam`;
} else if (removed && removed.name === 'spam') {
return `Unmarked${countString} as Spam`;
} else if (added && added.name === 'trash') {
return `Trashed${countString}`;
} else if (removed && removed.name === 'trash') {
return `Removed${countString} from Trash`;
}
if (looksLikeMove) {
if (added.name === 'all') {
return `Archived${countString}`;
} else if (removed.name === 'all') {
return `Unarchived${countString}`;
}
return `Moved${countString} to ${added.displayName}`;
}
if (this.labelsToAdd.length === 1 && this.labelsToRemove.length === 0) {
return `Added ${added.displayName}${countString ? ' to' : ''}${countString}`;
}
if (this.labelsToAdd.length === 0 && this.labelsToRemove.length === 1) {
return `Removed ${removed.displayName}${countString ? ' from' : ''}${countString}`;
}
}
return `Changed labels${countString ? ' on' : ''}${countString}`;
}
isDependentOnTask(other) {
return super.isDependentOnTask(other) || (other instanceof SyncbackCategoryTask);
}
// In Gmail all threads /must/ belong to either All Mail, Trash and Spam, and
// they are mutually exclusive, so we need to make sure that any add/remove
// label operation still guarantees that constraint
_ensureAndUpdateLabels(account, existingLabelsToAdd, existingLabelsToRemove = {}) {
const labelsToAdd = existingLabelsToAdd;
let labelsToRemove = existingLabelsToRemove;
const setToAdd = new Set(_.compact(_.pluck(labelsToAdd, 'name')));
const setToRemove = new Set(_.compact(_.pluck(labelsToRemove, 'name')));
if (setToRemove.has('all')) {
if (!setToAdd.has('spam') && !setToAdd.has('trash')) {
labelsToRemove = _.reject(labelsToRemove, label => label.name === 'all');
}
} else if (setToAdd.has('all')) {
if (!setToRemove.has('trash')) {
labelsToRemove.push(CategoryStore.getTrashCategory(account));
}
if (!setToRemove.has('spam')) {
labelsToRemove.push(CategoryStore.getSpamCategory(account));
}
}
if (setToRemove.has('trash')) {
if (!setToAdd.has('spam') && !setToAdd.has('all')) {
labelsToAdd.push(CategoryStore.getAllMailCategory(account));
}
} else if (setToAdd.has('trash')) {
if (!setToRemove.has('all')) {
labelsToRemove.push(CategoryStore.getAllMailCategory(account))
}
if (!setToRemove.has('spam')) {
labelsToRemove.push(CategoryStore.getSpamCategory(account))
}
}
if (setToRemove.has('spam')) {
if (!setToAdd.has('trash') && !setToAdd.has('all')) {
labelsToAdd.push(CategoryStore.getAllMailCategory(account));
}
} else if (setToAdd.has('spam')) {
if (!setToRemove.has('all')) {
labelsToRemove.push(CategoryStore.getAllMailCategory(account))
}
if (!setToRemove.has('trash')) {
labelsToRemove.push(CategoryStore.getTrashCategory(account))
}
}
// This should technically not be possible, but we like to keep it safe
return {
labelsToAdd: _.compact(labelsToAdd),
labelsToRemove: _.compact(labelsToRemove),
};
}
performLocal() {
if (this.messages.length > 0) {
return Promise.reject(new Error("ChangeLabelsTask: N1 does not support viewing or changing labels on individual messages."))
}
if (this.labelsToAdd.length === 0 && this.labelsToRemove.length === 0) {
return Promise.reject(new Error("ChangeLabelsTask: Must specify `labelsToAdd` or `labelsToRemove`"))
}
if (this.threads.length > 0 && this.messages.length > 0) {
return Promise.reject(new Error("ChangeLabelsTask: You can move `threads` or `messages` but not both"))
}
if (this.threads.length === 0 && this.messages.length === 0) {
return Promise.reject(new Error("ChangeLabelsTask: You must provide a `threads` or `messages` Array of models or IDs."))
}
return super.performLocal();
}
_isArchive() {
const toAdd = this.labelsToAdd.map(l => l.name)
return toAdd.includes("all") || toAdd.includes("archive")
}
recordUserEvent() {
if (this.source === "Mail Rules") {
return
}
// Actions.recordUserEvent("Threads Changed Labels", {
// source: this.source,
// isArchive: this._isArchive(),
// labelTypesToAdd: this.labelsToAdd.map(l => l.name || "custom"),
// labelTypesToRemove: this.labelsToRemove.map(l => l.name || "custom"),
// labelDisplayNamesToAdd: this.labelsToAdd.map(l => l.displayName),
// labelDisplayNamesToRemove: this.labelsToRemove.map(l => l.displayName),
// numThreads: this.threads.length,
// numMessages: this.messages.length,
// description: this.description(),
// isUndo: this._isUndoTask,
// })
}
retrieveModels() {
// Convert arrays of IDs or models to models.
// modelify returns immediately if (no work is required)
return Promise.props({
labelsToAdd: DatabaseStore.modelify(Category, this.labelsToAdd),
labelsToRemove: DatabaseStore.modelify(Category, this.labelsToRemove),
threads: DatabaseStore.modelify(Thread, this.threads),
messages: DatabaseStore.modelify(Message, this.messages),
}).then(({labelsToAdd, labelsToRemove, threads, messages}) => {
if (_.any([].concat(labelsToAdd, labelsToRemove), _.isUndefined)) {
return Promise.reject(new Error("One or more of the specified labels could not be found."))
}
const account = AccountStore.accountForItems(threads);
if (!account) {
return Promise.reject(new Error("ChangeLabelsTask: You must provide a set of `threads` from the same Account"))
}
// In Gmail all threads /must/ belong to either All Mail, Trash and Spam, and
// they are mutually exclusive, so we need to make sure that any add/remove
// label operation still guarantees that constraint
const updated = this._ensureAndUpdateLabels(account, labelsToAdd, labelsToRemove)
// Remove any objects we weren't able to find. This can happen pretty easily
// if (you undo an action && other things have happened.)
this.labelsToAdd = updated.labelsToAdd;
this.labelsToRemove = updated.labelsToRemove;
this.threads = _.compact(threads);
this.messages = _.compact(messages);
// The base class does the heavy lifting and calls changesToModel
return Promise.resolve();
});
}
processNestedMessages() {
return false;
}
changesToModel(model) {
const labelsToRemoveIds = _.pluck(this.labelsToRemove, 'id')
let labels = _.reject(model.labels, ({id}) => labelsToRemoveIds.includes(id));
labels = labels.concat(this.labelsToAdd);
labels = _.uniq(labels, false, label => label.id);
return {labels};
}
requestBodyForModel(model) {
const folder = model.labels.find(l => l.object === 'folder')
const labels = model.labels.filter(l => l.object === 'label')
if (folder) {
return {
folder: folder.id,
labels: labels.map(l => l.id),
}
}
return {labels};
}
}
| 37.816 | 130 | 0.653057 |
9399bbac1a13ace4ee14d9f3781571662a27685a | 344 | js | JavaScript | components/Table/Holders/random.js | mattbajorek/blackJackReact | 2e46a28515028a8f92ee5bd17a03492d8fa6b3bd | [
"MIT"
] | null | null | null | components/Table/Holders/random.js | mattbajorek/blackJackReact | 2e46a28515028a8f92ee5bd17a03492d8fa6b3bd | [
"MIT"
] | null | null | null | components/Table/Holders/random.js | mattbajorek/blackJackReact | 2e46a28515028a8f92ee5bd17a03492d8fa6b3bd | [
"MIT"
] | null | null | null | let numbers = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'];
let symbols = ['\u2660', '\u2663', '\u2665', '\u2666'];
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
module.exports = function() {
return {
number: numbers[getRandomInt(0,12)],
symbol: symbols[getRandomInt(0,3)]
}
} | 26.461538 | 69 | 0.572674 |
9399cb347d3081c1e2d52c397848e1ce2967f4d1 | 541 | js | JavaScript | database/models/story.js | GeorgeSchlosser/Adventure-Book-v2 | a59302e84f6aef2ef36c0bfd5f9d65a5a880131d | [
"MIT"
] | null | null | null | database/models/story.js | GeorgeSchlosser/Adventure-Book-v2 | a59302e84f6aef2ef36c0bfd5f9d65a5a880131d | [
"MIT"
] | 10 | 2019-08-10T00:17:10.000Z | 2021-09-01T20:47:00.000Z | database/models/story.js | GeorgeSchlosser/Adventure-Book-v2 | a59302e84f6aef2ef36c0bfd5f9d65a5a880131d | [
"MIT"
] | 3 | 2019-08-18T19:27:32.000Z | 2020-01-09T18:28:17.000Z | // /database/story.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
const StorySchema = new Schema(
{
id: Number,
scene_title: String,
scene_text: String,
next_scene: Number,
correct_choice: String,
choice_a: String,
choice_b: String,
wrong_choice_result: String,
image_url: String
},
{ timestamps: false }
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("Story", StorySchema); | 24.590909 | 60 | 0.695009 |
939ab689e06d10dbf15f3d1892528a93c0da644a | 814 | js | JavaScript | doc/html/search/variables_6.js | hepingood/hcsr04 | 95c5a6346250cdf1e9d662202159ae23f9a917c5 | [
"MIT"
] | 42 | 2021-05-12T14:55:31.000Z | 2022-03-31T15:33:32.000Z | doc/html/search/variables_6.js | hepingood/hcsr04 | 95c5a6346250cdf1e9d662202159ae23f9a917c5 | [
"MIT"
] | null | null | null | doc/html/search/variables_6.js | hepingood/hcsr04 | 95c5a6346250cdf1e9d662202159ae23f9a917c5 | [
"MIT"
] | 8 | 2021-12-05T07:07:58.000Z | 2022-03-23T02:12:37.000Z | var searchData=
[
['temperature_5fmax_128',['temperature_max',['../structhcsr04__info__s.html#a3366a5dce9b829e03c3d321c2b4df3f6',1,'hcsr04_info_s']]],
['temperature_5fmin_129',['temperature_min',['../structhcsr04__info__s.html#a8f9dbe66ac0b66ebae0a36fcb4ba368e',1,'hcsr04_info_s']]],
['timestamp_5fread_130',['timestamp_read',['../structhcsr04__handle__s.html#ae79b7a157809fd4a1760be65de1078a5',1,'hcsr04_handle_s']]],
['trig_5fdeinit_131',['trig_deinit',['../structhcsr04__handle__s.html#a8718ff3ae6d699a9954bcc5ccfb63a65',1,'hcsr04_handle_s']]],
['trig_5finit_132',['trig_init',['../structhcsr04__handle__s.html#a9659dbaddeda5b509977a525914e62db',1,'hcsr04_handle_s']]],
['trig_5fwrite_133',['trig_write',['../structhcsr04__handle__s.html#a8519ecd7e11e0093ee1e7afc3559a6ab',1,'hcsr04_handle_s']]]
];
| 81.4 | 136 | 0.792383 |
939b024132ea9434e34cc940deed6455d45bee13 | 3,761 | js | JavaScript | Caffe/ocr.js | jingmingcn/blood-server | 0bcc1fda5d05b8e5acca2c9ce6857c7963fb84b5 | [
"Apache-2.0"
] | null | null | null | Caffe/ocr.js | jingmingcn/blood-server | 0bcc1fda5d05b8e5acca2c9ce6857c7963fb84b5 | [
"Apache-2.0"
] | null | null | null | Caffe/ocr.js | jingmingcn/blood-server | 0bcc1fda5d05b8e5acca2c9ce6857c7963fb84b5 | [
"Apache-2.0"
] | null | null | null | var ocrDemo = {
CANVAS_WIDTH: 200,
TRANSLATED_WIDTH: 20,
PIXEL_WIDTH: 10, // TRANSLATED_WIDTH = CANVAS_WIDTH / PIXEL_WIDTH
// 服务器端参数
PORT: "9000",
HOST: "http://localhost",
// 颜色变量
BLACK: "#000000",
onLoadFunction: function() {
this.resetCanvas();
},
resetCanvas: function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = this.BLACK;
ctx.fillRect(0, 0, this.CANVAS_WIDTH, this.CANVAS_WIDTH);
var matrixSize = 400;
// 绑定事件操作
canvas.onmousemove = function(e) { this.onMouseMove(e, ctx, canvas) }.bind(this);
canvas.onmousedown = function(e) { this.onMouseDown(e, ctx, canvas) }.bind(this);
canvas.onmouseup = function(e) { this.onMouseUp(e, ctx) }.bind(this);
},
onMouseMove: function(e, ctx, canvas) {
if (!canvas.isDrawing) {
return;
}
this.fillSquare(ctx, e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
},
onMouseDown: function(e, ctx, canvas) {
canvas.isDrawing = true;
this.fillSquare(ctx, e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
},
onMouseUp: function(e) {
canvas.isDrawing = false;
},
fillSquare: function(ctx, x, y) {
var xPixel = Math.floor(x / this.PIXEL_WIDTH);
var yPixel = Math.floor(y / this.PIXEL_WIDTH);
ctx.fillStyle = '#ffffff';
ctx.fillRect(xPixel * this.PIXEL_WIDTH, yPixel * this.PIXEL_WIDTH, this.PIXEL_WIDTH, this.PIXEL_WIDTH);
},
train: function() {
var digitVal = document.getElementById("digit").value;
if (!digitVal) {
alert("Please type and draw a digit value in order to train the network");
return;
}
var mycanvas = document.getElementById('canvas');
// canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持
var img_data = mycanvas.toDataURL("image/jpg");
//删除字符串前的提示信息 "data:image/jpg;base64,"
var b64 = img_data.substring(22);
// 将客服端训练数据集发送给服务器端
alert("Sending training data to server...");
var json = {
img: b64,
train: true
};
this.sendData(json);
},
// 发送预测请求
test: function() {
var mycanvas = document.getElementById('canvas')
// canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持
var img_data = mycanvas.toDataURL("image/jpg");
//删除字符串前的提示信息 "data:image/jpg;base64,"
var b64 = img_data.substring(22);
var json = {
img: b64,
pred: true
};
this.sendData(json);
},
// 处理服务器响应
receiveResponse: function(xmlHttp) {
if (xmlHttp.status != 200) {
alert("Server returned status " + xmlHttp.status);
return;
}
var responseJSON = JSON.parse(xmlHttp.responseText);
if (xmlHttp.responseText && responseJSON.type == "test") {
alert("The neural network predicts you wrote a \'" + responseJSON.result + '\'');
}
},
onError: function(e) {
alert("Error occurred while connecting to server: " + e.target.statusText);
},
sendData: function(json) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', this.HOST + ":" + this.PORT, false);
xmlHttp.onload = function() { this.receiveResponse(xmlHttp); }.bind(this);
xmlHttp.onerror = function() { this.onError(xmlHttp) }.bind(this);
var msg = JSON.stringify(json);
xmlHttp.setRequestHeader('Content-length', msg.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(msg);
}
}
| 31.872881 | 111 | 0.586546 |
939c73ce160504bb513876a9d8dcf47702339d39 | 216 | js | JavaScript | app/unbundled-webcomponents/app/dist/build/es5-amd/node_modules/@lrnwebcomponents/moment-element/lib/moment/src/lib/utils/mod.js | reyes-edwin/Hax11ty | 21ea3021da6924e36983d9a491b86b8e3837090e | [
"Apache-2.0"
] | 2 | 2022-02-23T23:52:44.000Z | 2022-02-28T22:49:20.000Z | app/unbundled-webcomponents/app/dist/build/es5-amd/node_modules/@lrnwebcomponents/moment-element/lib/moment/src/lib/utils/mod.js | reyes-edwin/Hax11ty | 21ea3021da6924e36983d9a491b86b8e3837090e | [
"Apache-2.0"
] | null | null | null | app/unbundled-webcomponents/app/dist/build/es5-amd/node_modules/@lrnwebcomponents/moment-element/lib/moment/src/lib/utils/mod.js | reyes-edwin/Hax11ty | 21ea3021da6924e36983d9a491b86b8e3837090e | [
"Apache-2.0"
] | 1 | 2022-02-27T21:10:30.000Z | 2022-02-27T21:10:30.000Z | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = mod;
function mod(n, x) {
return (n % x + x) % x;
}
}); | 18 | 49 | 0.583333 |
939e6d977a2d5094a80d1408e210d843f74ba03d | 748 | js | JavaScript | app/javascript/components/shared/Tabs/tabs.component.js | Vizzuality/forest-atlas-landpscape-cms | fd33a2b1e6d1f0b7ab496fb33d51d08a650da237 | [
"MIT"
] | 5 | 2016-10-05T04:48:15.000Z | 2019-08-19T02:14:40.000Z | app/javascript/components/shared/Tabs/tabs.component.js | Vizzuality/forest-atlas-landpscape-cms | fd33a2b1e6d1f0b7ab496fb33d51d08a650da237 | [
"MIT"
] | 100 | 2016-06-23T07:10:01.000Z | 2022-03-30T22:06:27.000Z | app/javascript/components/shared/Tabs/tabs.component.js | Vizzuality/forest-atlas-landpscape-cms | fd33a2b1e6d1f0b7ab496fb33d51d08a650da237 | [
"MIT"
] | 6 | 2017-02-10T06:56:42.000Z | 2019-06-03T16:33:07.000Z | import React from 'react';
import PropTypes from 'prop-types';
const Tabs = ({ tabs, selected, modifier, onChange }) => (
<div className={`c-tabs -${modifier}`} role="tablist">
{ tabs.map(tab => (
<button
type="button"
key={tab.name}
className="tab"
role="tab"
aria-selected={selected === tab.name}
onClick={() => onChange(tab)}
>
{tab.name}
</button>
)) }
</div>
);
Tabs.propTypes = {
selected: PropTypes.string.isRequired,
tabs: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string
})).isRequired,
onChange: PropTypes.func.isRequired,
modifier: PropTypes.string,
};
Tabs.defaultProps = {
modifier: 'secondary'
};
export default Tabs;
| 21.371429 | 58 | 0.601604 |
939f5208c5184545b0cdb2dc17659715049c8a2a | 1,558 | js | JavaScript | src/js/constants/MistralConstants.js | mail2nsrajesh/tripleo-ui | 68e8684162811c88fb10c8c43c8e59bec3510eb2 | [
"Apache-2.0"
] | null | null | null | src/js/constants/MistralConstants.js | mail2nsrajesh/tripleo-ui | 68e8684162811c88fb10c8c43c8e59bec3510eb2 | [
"Apache-2.0"
] | null | null | null | src/js/constants/MistralConstants.js | mail2nsrajesh/tripleo-ui | 68e8684162811c88fb10c8c43c8e59bec3510eb2 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2017 Red Hat Inc.
*
* 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.
*/
export default {
BAREMETAL_INTROSPECT: 'tripleo.baremetal.v1.introspect',
BAREMETAL_PROVIDE: 'tripleo.baremetal.v1.provide',
BAREMETAL_REGISTER_OR_UPDATE: 'tripleo.baremetal.v1.register_or_update',
CAPABILITIES_GET: 'tripleo.heat_capabilities.get',
CAPABILITIES_UPDATE: 'tripleo.heat_capabilities.update',
CREATE_CONTAINER: 'tripleo.plan.create_container',
DEPLOYMENT_DEPLOY_PLAN: 'tripleo.deployment.v1.deploy_plan',
PARAMETERS_GET: 'tripleo.parameters.get_flatten',
PARAMETERS_UPDATE: 'tripleo.parameters.update',
PLAN_CREATE: 'tripleo.plan_management.v1.create_deployment_plan',
PLAN_DELETE: 'tripleo.plan.delete',
PLAN_LIST: 'tripleo.plan.list',
PLAN_EXPORT: 'tripleo.plan_management.v1.export_deployment_plan',
ROLE_LIST: 'tripleo.role.list',
VALIDATIONS_LIST: 'tripleo.validations.list_validations',
VALIDATIONS_RUN: 'tripleo.validations.v1.run_validation',
VALIDATIONS_RUN_GROUPS: 'tripleo.validations.v1.run_groups'
};
| 43.277778 | 76 | 0.779846 |
93a06677138fb8215e176b430ecf9360cae6d8eb | 20,994 | js | JavaScript | projects/mercury/src/collections/CollectionDetails.js | fairspace/workspace | a437131837882d7b5f1a698f0457d53cadd115a5 | [
"Apache-2.0"
] | 5 | 2021-10-30T23:09:09.000Z | 2022-01-21T14:59:03.000Z | projects/mercury/src/collections/CollectionDetails.js | fairspace/workspace | a437131837882d7b5f1a698f0457d53cadd115a5 | [
"Apache-2.0"
] | 5 | 2021-09-08T09:48:24.000Z | 2022-02-12T06:32:13.000Z | projects/mercury/src/collections/CollectionDetails.js | fairspace/workspace | a437131837882d7b5f1a698f0457d53cadd115a5 | [
"Apache-2.0"
] | null | null | null | // @flow
import React, {useContext} from 'react';
import {
Card,
CardContent,
CardHeader,
FormControl, FormGroup, FormLabel,
IconButton,
Link,
List,
ListItem,
ListItemText,
Menu,
MenuItem,
Typography
} from '@material-ui/core';
import {CloudDownload, Folder, MoreVert} from '@material-ui/icons';
import {useHistory, withRouter} from 'react-router-dom';
import CollectionEditor from "./CollectionEditor";
import type {Collection, Resource, Status} from './CollectionAPI';
import CollectionsContext from './CollectionsContext';
import type {History} from '../types';
import WorkspaceContext from "../workspaces/WorkspaceContext";
import type {Workspace} from "../workspaces/WorkspacesAPI";
import ErrorDialog from "../common/components/ErrorDialog";
import LoadingInlay from "../common/components/LoadingInlay";
import ConfirmationDialog from "../common/components/ConfirmationDialog";
import PermissionCard from "../permissions/PermissionCard";
import MessageDisplay from "../common/components/MessageDisplay";
import UsersContext from "../users/UsersContext";
import WorkspaceUserRolesContext, {WorkspaceUserRolesProvider} from "../workspaces/WorkspaceUserRolesContext";
import CollectionStatusChangeDialog from "./CollectionStatusChangeDialog";
import CollectionOwnerChangeDialog from "./CollectionOwnerChangeDialog";
import {descriptionForStatus, isCollectionPage} from "./collectionUtils";
import {getDisplayName} from '../users/userUtils';
import {camelCaseToWords, formatDateTime} from '../common/utils/genericUtils';
import type {User} from '../users/UsersAPI';
import LinkedDataLink from '../metadata/common/LinkedDataLink';
import UserContext from "../users/UserContext";
import ProgressButton from "../common/components/ProgressButton";
export const ICONS = {
LOCAL_STORAGE: <Folder aria-label="Local storage" />,
AZURE_BLOB_STORAGE: <CloudDownload />,
S3_BUCKET: <CloudDownload />,
GOOGLE_CLOUD_BUCKET: <CloudDownload />
};
const DEFAULT_COLLECTION_TYPE = 'LOCAL_STORAGE';
type CollectionDetailsProps = {
loading: boolean;
collection: Collection;
onChangeOwner: () => void;
workspaces: Workspace[];
deleteCollection: (Resource) => Promise<void>;
undeleteCollection: (Resource) => Promise<void>;
unpublish: (Resource) => Promise<void>;
setStatus: (name: string, status: Status) => Promise<void>;
setOwnedBy: (name: string, owner: string) => Promise<void>;
setBusy: (boolean) => void;
history: History;
};
type CollectionDetailsState = {
editing: boolean;
changingStatus: boolean,
changingOwner: boolean,
deleting: boolean;
undeleting: boolean;
unpublishing: boolean;
anchorEl: any;
}
class CollectionDetails extends React.Component<CollectionDetailsProps, CollectionDetailsState> {
static defaultProps = {
onChangeOwner: () => {},
setBusy: () => {}
};
state = {
editing: false,
changingStatus: false,
changingOwner: false,
anchorEl: null,
deleting: false,
undeleting: false,
unpublishing: false,
isActiveOperation: false
};
unmounting = false;
componentWillUnmount() {
this.unmounting = true;
}
handleCollectionOperation = (operationPromise) => {
this.setState({isActiveOperation: true});
return operationPromise
.then(r => {
this.setState({isActiveOperation: false});
return r;
})
.catch(e => {
this.setState({isActiveOperation: false});
return Promise.reject(e);
});
};
handleEdit = () => {
if (this.props.collection.canWrite) {
this.setState({editing: true});
this.handleMenuClose();
}
};
handleChangeStatus = () => {
if (this.props.collection.canManage) {
this.setState({changingStatus: true});
this.handleMenuClose();
}
};
handleChangeOwner = () => {
if (this.props.collection.canManage) {
this.setState({changingOwner: true});
this.handleMenuClose();
}
};
handleDelete = () => {
if (this.props.collection.canDelete) {
this.setState({deleting: true});
this.handleMenuClose();
}
};
handleUndelete = () => {
if (this.props.collection.canUndelete) {
this.setState({undeleting: true});
this.handleMenuClose();
}
};
handleUnpublish = () => {
if (this.props.collection.canUnpublish) {
this.setState({unpublishing: true});
this.handleMenuClose();
}
};
handleCloseDelete = () => {
this.setState({deleting: false});
};
handleCloseUndelete = () => {
this.setState({undeleting: false});
};
handleCloseUnpublish = () => {
this.setState({unpublishing: false});
};
handleCloseChangingOwner = () => {
this.setState({changingOwner: false});
};
handleMenuClick = (event: Event) => {
this.setState({anchorEl: event.currentTarget});
};
handleMenuClose = () => {
this.setState({anchorEl: null});
};
handleCollectionDelete = (collection: Collection) => {
const {deleteCollection, history} = this.props;
this.handleCloseDelete();
this.handleCollectionOperation(deleteCollection(collection))
.then(() => {
if (isCollectionPage()) {
history.push('/collections');
}
})
.catch(e => ErrorDialog.showError(
"An error occurred while deleting a collection",
e,
() => this.handleCollectionDelete(collection)
));
};
handleCollectionUndelete = (collection: Collection) => {
const {undeleteCollection} = this.props;
this.handleCloseUndelete();
this.handleCollectionOperation(undeleteCollection(collection))
.catch(e => ErrorDialog.showError(
"An error occurred while undeleting a collection",
e,
() => this.handleCollectionUndelete(collection)
));
};
handleCollectionUnpublish = (collection: Collection) => {
const {unpublish} = this.props;
this.handleCloseUnpublish();
this.handleCollectionOperation(unpublish(collection))
.catch(err => ErrorDialog.showError(
"An error occurred while unpublishing a collection",
err,
() => this.handleCollectionUnpublish(collection)
));
};
handleCollectionOwnerChange = (collection: Collection, selectedOwner: Workspace) => {
const {setOwnedBy, onChangeOwner, history} = this.props;
this.handleCloseChangingOwner();
onChangeOwner();
this.handleCollectionOperation(setOwnedBy(collection.name, selectedOwner.iri))
.then(() => {
if (!selectedOwner.canCollaborate) {
history.push('/collections');
}
})
.catch(err => ErrorDialog.showError(
"An error occurred while changing an owner of a collection",
err,
() => this.handleCollectionOwnerChange(collection, selectedOwner)
));
};
renderCollectionOwner = (workspace: Workspace) => (
workspace
&& (
<FormControl>
<FormLabel>Owner workspace</FormLabel>
<FormGroup>
<Link
color="inherit"
underline="hover"
href={`/workspace?iri=${encodeURI(workspace.iri)}`}
onClick={(e) => {
e.preventDefault();
this.props.history.push(`/workspace?iri=${encodeURI(workspace.iri)}`);
}}
>
<Typography variant="body2">{workspace.code}</Typography>
</Link>
</FormGroup>
</FormControl>
)
);
renderCollectionStatus = () => (
this.props.collection.status
&& (
<FormControl>
<FormLabel>Status</FormLabel>
<FormGroup>
<ListItemText
primary={camelCaseToWords(this.props.collection.status, "-")}
secondary={descriptionForStatus(this.props.collection.status)}
/>
</FormGroup>
</FormControl>
)
);
renderDeleted = (dateDeleted: string, deletedBy: User) => (
dateDeleted && [
<ListItem key="dateDeleted" disableGutters>
<FormControl>
<FormLabel>Deleted</FormLabel>
<FormGroup>
<Typography variant="body2">
{formatDateTime(dateDeleted)}
</Typography>
</FormGroup>
</FormControl>
</ListItem>,
<ListItem key="deletedBy" disableGutters>
<FormControl>
<FormLabel>Deleted by</FormLabel>
<FormGroup>
<Typography variant="body2">
<LinkedDataLink uri={deletedBy.iri}>
{getDisplayName(deletedBy)}
</LinkedDataLink>
</Typography>
</FormGroup>
</FormControl>
</ListItem>
]
);
render() {
const {loading, error, collection, users, workspaceRoles, workspaces} = this.props;
const {anchorEl, editing, changingStatus, changingOwner, deleting, undeleting, unpublishing} = this.state;
const iconName = collection.type && ICONS[collection.type] ? collection.type : DEFAULT_COLLECTION_TYPE;
if (error) {
return (<MessageDisplay message="An error occurred loading collection details." />);
}
if (loading) {
return <LoadingInlay />;
}
const workspaceUsers = users.filter(u => workspaceRoles.some(r => r.iri === u.iri));
const ownerWorkspace = workspaces.find(w => w.iri === collection.ownerWorkspace);
const deletedBy = collection.deletedBy && users.find(u => u.iri === collection.deletedBy);
const menuItems = [];
if (collection.canWrite && !collection.dateDeleted) {
menuItems.push(
<MenuItem key="edit" onClick={this.handleEdit}>
Edit
</MenuItem>
);
}
if (collection.canManage) {
menuItems.push([
<MenuItem
key="ownership"
onClick={this.handleChangeOwner}
disabled={workspaces.length <= 1}
>
Transfer ownership …
</MenuItem>,
<MenuItem
key="status"
onClick={this.handleChangeStatus}
disabled={collection.availableStatuses.length === 1}
>
Change status …
</MenuItem>
]);
}
if (collection.canUndelete) {
menuItems.push(
<MenuItem key="undelete" onClick={this.handleUndelete}>
Undelete …
</MenuItem>
);
}
if (collection.canDelete) {
menuItems.push(
<MenuItem key="delete" onClick={this.handleDelete}>
<Typography color={collection.dateDeleted ? "error" : "inherit"}>
{collection.dateDeleted ? "Delete permanently" : "Delete"} …
</Typography>
</MenuItem>
);
}
if (collection.canUnpublish) {
menuItems.push(
<MenuItem key="unpublish" onClick={this.handleUnpublish}>
<Typography color="error">
Unpublish …
</Typography>
</MenuItem>
);
}
return (
<>
<Card>
<CardHeader
action={menuItems && menuItems.length > 0 && (
<>
<ProgressButton active={this.state.isActiveOperation}>
<IconButton
aria-label="More"
aria-owns={anchorEl ? 'long-menu' : undefined}
aria-haspopup="true"
onClick={this.handleMenuClick}
>
<MoreVert />
</IconButton>
</ProgressButton>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleMenuClose}
>
{menuItems}
</Menu>
</>
)}
titleTypographyProps={{variant: 'h6'}}
title={collection.name}
avatar={ICONS[iconName]}
style={{wordBreak: 'break-word'}}
/>
<CardContent style={{paddingTop: 0}}>
<Typography component="p" style={{whiteSpace: 'pre-line'}}>
{collection.description}
</Typography>
<List>
<ListItem disableGutters>
{this.renderCollectionOwner(ownerWorkspace)}
</ListItem>
<ListItem disableGutters>
{this.renderCollectionStatus()}
</ListItem>
{this.renderDeleted(collection.dateDeleted, deletedBy)}
</List>
</CardContent>
</Card>
<PermissionCard
collection={collection}
users={users}
workspaceUsers={workspaceUsers}
workspaces={workspaces}
setBusy={this.props.setBusy}
/>
{editing ? (
<CollectionEditor
collection={collection}
workspace={ownerWorkspace}
updateExisting
setBusy={this.props.setBusy}
onClose={() => { if (!this.unmounting) { this.setState({editing: false});} }}
/>
) : null}
{changingStatus ? (
<CollectionStatusChangeDialog
collection={collection}
setValue={this.props.setStatus}
onClose={() => this.setState({changingStatus: false})}
/>
) : null}
{changingOwner ? (
<CollectionOwnerChangeDialog
collection={collection}
workspaces={workspaces}
changeOwner={this.handleCollectionOwnerChange}
onClose={() => this.handleCloseChangingOwner()}
/>
) : null}
{undeleting ? (
<ConfirmationDialog
open
title="Confirmation"
content={(
<span>
Are you sure you want to <b>undelete</b> collection <em>{collection.name}</em>?
</span>
)}
dangerous
agreeButtonText="Undelete"
onAgree={() => this.handleCollectionUndelete(this.props.collection)}
onDisagree={this.handleCloseUndelete}
onClose={this.handleCloseUndelete}
/>
) : null}
{deleting && collection.dateDeleted && (
<ConfirmationDialog
open
title="Confirmation"
content={(
<span>
Collection {collection.name} is already marked as deleted.<br />
<b>Are you sure you want to delete it permanently</b>?
</span>
)}
dangerous
agreeButtonText="Delete permanently"
onAgree={() => this.handleCollectionDelete(this.props.collection)}
onDisagree={this.handleCloseDelete}
onClose={this.handleCloseDelete}
/>
)}
{deleting && !collection.dateDeleted && (
<ConfirmationDialog
open
title="Confirmation"
content={(
<span>
Are you sure you want to <b>delete</b> collection <em>{collection.name}</em>?
</span>
)}
dangerous
agreeButtonText="Delete"
onAgree={() => this.handleCollectionDelete(this.props.collection)}
onDisagree={this.handleCloseDelete}
onClose={this.handleCloseDelete}
/>
)}
{unpublishing && (
<ConfirmationDialog
open
title="Confirmation"
content={(
<span>
<b>Warning: The action is not recommended! Collection (meta)data may already be referenced in other systems.</b><br />
Are you sure you want to <b>unpublish</b> collection <em>{collection.name}</em>?<br />
Collection view mode will be changed to <em>Metadata published</em>.
</span>
)}
dangerous
agreeButtonText="Unpublish"
onAgree={() => this.handleCollectionUnpublish(this.props.collection)}
onDisagree={this.handleCloseUnpublish}
onClose={this.handleCloseUnpublish}
/>
)}
</>
);
}
}
const ContextualCollectionDetails = (props) => {
const history = useHistory();
const {users} = useContext(UsersContext);
const {currentUser} = useContext(UserContext);
const {deleteCollection, undeleteCollection, setStatus, setOwnedBy, unpublish} = useContext(CollectionsContext);
const {workspaces, workspacesError, workspacesLoading} = useContext(WorkspaceContext);
return (
<WorkspaceUserRolesProvider iri={props.collection.ownerWorkspace}>
<WorkspaceUserRolesContext.Consumer>
{({workspaceRoles, workspaceRolesError, workspaceRolesLoading}) => (
<CollectionDetails
{...props}
error={props.error || workspacesError || workspaceRolesError}
loading={props.loading || workspacesLoading || workspaceRolesLoading}
users={users}
currentUser={currentUser}
workspaceRoles={workspaceRoles}
workspaces={workspaces}
history={history}
deleteCollection={deleteCollection}
undeleteCollection={undeleteCollection}
unpublish={unpublish}
setStatus={setStatus}
setOwnedBy={setOwnedBy}
/>
)}
</WorkspaceUserRolesContext.Consumer>
</WorkspaceUserRolesProvider>
);
};
export default withRouter(ContextualCollectionDetails);
| 38.032609 | 150 | 0.493474 |
93a15bec5cf3b9746cd4b62fc70be707bff4060c | 1,006 | js | JavaScript | example/scripts/controllers/main.js | kdsingharneja/angular-resource-example | 83f51c0a943177ec7899588986ea344999091fe2 | [
"MIT"
] | null | null | null | example/scripts/controllers/main.js | kdsingharneja/angular-resource-example | 83f51c0a943177ec7899588986ea344999091fe2 | [
"MIT"
] | null | null | null | example/scripts/controllers/main.js | kdsingharneja/angular-resource-example | 83f51c0a943177ec7899588986ea344999091fe2 | [
"MIT"
] | null | null | null | angular.module('app')
.controller('MainCtrl', ['$scope', '$route', 'Comment',
function($scope, $route, Comment) {
$scope.comment = new Comment();
$scope.comments = Comment.query();
$scope.newComment = function() {
$scope.comment = new Comment();
$scope.editing = false;
}
$scope.activeComment = function(comment) {
$scope.comment = comment;
$scope.editing = true;
}
$scope.save = function(comment) {
if ($scope.comment._id) {
Comment.update({_id: $scope.comment._id}, $scope.comment);
} else {
$scope.comment.$save().then(function(response) {
$scope.comments.push(response)
});
}
$scope.editing = false;
$scope.comment = new Comment();
}
$scope.delete = function(comment) {
Comment.delete(comment)
_.remove($scope.comments, comment)
}
}
]);
| 27.189189 | 70 | 0.510934 |