max_stars_repo_path
stringlengths
5
220
max_stars_repo_name
stringlengths
7
101
max_stars_count
int64
0
172k
id
stringlengths
1
4
content
stringlengths
11
779k
score
float64
0.34
1
label
stringclasses
3 values
05.plugins/src/js/index.js
alexjcm/webpack-4
0
6562
import "../css/index.css"; document.body.innerHTML = "Hello world desde Home css-style-loader";
0.925781
low
src/store/modules/permission.js
lanlianjiu/vue-system
0
6563
import { constantRouterMap } from '@/router' import { asyncRouterMap } from '@/router/asyncRouterMap' import * as types from '../mutaion-types' import { getMenu } from '@/api/login' import _import from '@/utils/import' const Layout = _import('layout/Layout') const filterAsyncRouter = (asyncRouterMap) => { asyncRouterMap.forEach(function (value, index) { let old_path = value.path; if (value.meta.redirect) { value.redirect = value.meta.redirect } if (value.parent) { let onestr = (value.path).slice(((value.path).indexOf("/")) + 1) value.path = (onestr).slice(((onestr).indexOf("/")) + 1) } if (value.children) { value.component = Layout; filterAsyncRouter(value.children, value.path); } else { let p_path = (old_path).slice(((old_path).indexOf("/")) + 1); value.component = _import(p_path); } }); return asyncRouterMap } const permission = { state: { routers: constantRouterMap, addRouters: [] }, mutations: { [types.SET_ROUTERS]: (state, routers) => { state.addRouters = routers state.routers = constantRouterMap.concat(routers) } }, actions: { generateRoutes({ commit }, roles) { return new Promise(async (resolve, reject) => { let routers = null const response = await getMenu() routers = filterAsyncRouter(response); if (routers) { commit(types.SET_ROUTERS, routers) resolve() } }) } } } export default permission
0.988281
high
node_modules/react-vis/dist/plot/series/arc-series.js
laokingshineUAV/VoTT
80
6564
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _animation = require('../../animation'); var _animation2 = _interopRequireDefault(_animation); var _seriesUtils = require('../../utils/series-utils'); var _d3Shape = require('d3-shape'); var _abstractSeries = require('./abstract-series'); var _abstractSeries2 = _interopRequireDefault(_abstractSeries); var _scalesUtils = require('../../utils/scales-utils'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var predefinedClassName = 'rv-xy-plot__series rv-xy-plot__series--arc'; var ATTRIBUTES = ['radius', 'angle']; var defaultProps = _extends({}, _abstractSeries2.default.defaultProps, { center: { x: 0, y: 0 }, arcClassName: '', className: '', style: {}, padAngle: 0 }); /** * Prepare the internal representation of row for real use. * This is necessary because d3 insists on starting at 12 oclock and moving * clockwise, rather than starting at 3 oclock and moving counter clockwise * as one might expect from polar * @param {Object} row - coordinate object to be modifed * @return {Object} angle corrected object */ function modifyRow(row) { var radius = row.radius, angle = row.angle, angle0 = row.angle0; var truedAngle = -1 * angle + Math.PI / 2; var truedAngle0 = -1 * angle0 + Math.PI / 2; return _extends({}, row, { x: radius * Math.cos(truedAngle), y: radius * Math.sin(truedAngle), angle: truedAngle, angle0: truedAngle0 }); } var ArcSeries = function (_AbstractSeries) { _inherits(ArcSeries, _AbstractSeries); function ArcSeries(props) { _classCallCheck(this, ArcSeries); var _this = _possibleConstructorReturn(this, (ArcSeries.__proto__ || Object.getPrototypeOf(ArcSeries)).call(this, props)); var scaleProps = _this._getAllScaleProps(props); _this.state = { scaleProps: scaleProps }; return _this; } _createClass(ArcSeries, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.setState({ scaleProps: this._getAllScaleProps(nextProps) }); } /** * Get the map of scales from the props. * @param {Object} props Props. * @param {Array} data Array of all data. * @returns {Object} Map of scales. * @private */ }, { key: '_getAllScaleProps', value: function _getAllScaleProps(props) { var defaultScaleProps = this._getDefaultScaleProps(props); var userScaleProps = (0, _scalesUtils.extractScalePropsFromProps)(props, ATTRIBUTES); var missingScaleProps = (0, _scalesUtils.getMissingScaleProps)(_extends({}, defaultScaleProps, userScaleProps), props.data, ATTRIBUTES); return _extends({}, defaultScaleProps, userScaleProps, missingScaleProps); } /** * Get the list of scale-related settings that should be applied by default. * @param {Object} props Object of props. * @returns {Object} Defaults. * @private */ }, { key: '_getDefaultScaleProps', value: function _getDefaultScaleProps(props) { var innerWidth = props.innerWidth, innerHeight = props.innerHeight; var radius = Math.min(innerWidth / 2, innerHeight / 2); return { radiusRange: [0, radius], _radiusValue: radius, angleType: 'literal' }; } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, arcClassName = _props.arcClassName, animation = _props.animation, className = _props.className, center = _props.center, data = _props.data, disableSeries = _props.disableSeries, hideSeries = _props.hideSeries, marginLeft = _props.marginLeft, marginTop = _props.marginTop, padAngle = _props.padAngle, style = _props.style; if (!data) { return null; } if (animation) { var cloneData = data.map(function (d) { return _extends({}, d); }); return _react2.default.createElement( 'g', { className: 'rv-xy-plot__series--arc__animation-wrapper' }, _react2.default.createElement( _animation2.default, _extends({}, this.props, { animatedProps: _seriesUtils.ANIMATED_SERIES_PROPS, data: cloneData }), _react2.default.createElement(ArcSeries, _extends({}, this.props, { animation: null, disableSeries: true, data: cloneData })) ), _react2.default.createElement(ArcSeries, _extends({}, this.props, { animation: null, hideSeries: true, style: { stroke: 'red' } })) ); } var scaleProps = this.state.scaleProps; var radiusDomain = scaleProps.radiusDomain; // need to generate our own functors as abstract series doesnt have anythign for us var radius = (0, _scalesUtils.getAttributeFunctor)(scaleProps, 'radius'); var radius0 = (0, _scalesUtils.getAttr0Functor)(scaleProps, 'radius'); var angle = (0, _scalesUtils.getAttributeFunctor)(scaleProps, 'angle'); var angle0 = (0, _scalesUtils.getAttr0Functor)(scaleProps, 'angle'); // but it does have good color support! var fill = this._getAttributeFunctor('fill') || this._getAttributeFunctor('color'); var stroke = this._getAttributeFunctor('stroke') || this._getAttributeFunctor('color'); var opacity = this._getAttributeFunctor('opacity'); var x = this._getAttributeFunctor('x'); var y = this._getAttributeFunctor('y'); return _react2.default.createElement( 'g', { className: predefinedClassName + ' ' + className, onMouseOver: this._seriesMouseOverHandler, onMouseOut: this._seriesMouseOutHandler, onClick: this._seriesClickHandler, onContextMenu: this._seriesRightClickHandler, opacity: hideSeries ? 0 : 1, pointerEvents: disableSeries ? 'none' : 'all', transform: 'translate(' + (marginLeft + x(center)) + ',' + (marginTop + y(center)) + ')' }, data.map(function (row, i) { var noRadius = radiusDomain[1] === radiusDomain[0]; var arcArg = { innerRadius: noRadius ? 0 : radius0(row), outerRadius: radius(row), startAngle: angle0(row) || 0, endAngle: angle(row) }; var arcedData = (0, _d3Shape.arc)().padAngle(padAngle); var rowStyle = row.style || {}; var rowClassName = row.className || ''; return _react2.default.createElement('path', { style: _extends({ opacity: opacity && opacity(row), stroke: stroke && stroke(row), fill: fill && fill(row) }, style, rowStyle), onClick: function onClick(e) { return _this2._valueClickHandler(modifyRow(row), e); }, onContextMenu: function onContextMenu(e) { return _this2._valueRightClickHandler(modifyRow(row), e); }, onMouseOver: function onMouseOver(e) { return _this2._valueMouseOverHandler(modifyRow(row), e); }, onMouseOut: function onMouseOut(e) { return _this2._valueMouseOutHandler(modifyRow(row), e); }, key: i, className: predefinedClassName + '-path ' + arcClassName + ' ' + rowClassName, d: arcedData(arcArg) }); }) ); } }]); return ArcSeries; }(_abstractSeries2.default); ArcSeries.propTypes = _extends({}, _abstractSeries2.default.propTypes, (0, _scalesUtils.getScalePropTypesByAttribute)('radius'), (0, _scalesUtils.getScalePropTypesByAttribute)('angle'), { center: _propTypes2.default.shape({ x: _propTypes2.default.number, y: _propTypes2.default.number }), arcClassName: _propTypes2.default.string, padAngle: _propTypes2.default.oneOfType([_propTypes2.default.func, _propTypes2.default.number]) }); ArcSeries.defaultProps = defaultProps; ArcSeries.displayName = 'ArcSeries'; exports.default = ArcSeries;
0.996094
high
lib/repository/interface.js
knowark/modelarkjs
0
6565
export class RepositoryInterface { /** @return {typeof Entity} */ get model () { if (!this._model) { throw new Error('Not implemented') } return this._model } /** @param {Entity | Array<Entity>} items @return {Array<Entity>} */ async add (item) { console.assert(item) throw new Error('Not implemented') } /** @param {Entity | Array<Entity>} items @return {Array<Entity>} */ async remove (item) { console.assert(item) throw new Error('Not implemented') } async count (domain) { console.assert(domain) throw new Error('Not implemented') } /** @param { Array<Any> } domain * @param {{ * limit: number | null, offset: number | null, order: string | null * }} * @return {Array<Entity>} */ async search (domain, { limit = null, offset = null } = {}) { console.assert([domain, limit, offset]) throw new Error('Not implemented') } }
0.992188
high
src/isRotateSVGTransform/isRotateSVGTransform.index.js
marpple/FxSVG
11
6566
<filename>src/isRotateSVGTransform/isRotateSVGTransform.index.js import { $$isSVGTransform } from "../isSVGTransform/isSVGTransform.index.js"; export const $$isRotateSVGTransform = (transform) => { if (!$$isSVGTransform(transform)) { return false; } const { type, SVG_TRANSFORM_ROTATE } = transform; return type === SVG_TRANSFORM_ROTATE; };
0.988281
high
gatsby-config.js
elizeumatheus/gatsby-netlify-cms
3
6567
const path = require("path"); module.exports = { siteMetadata: { title: `Netlify CSM com Gatsby`, description: `This is a sample project to show how create a site with Gatsby and Netlify CMS`, author: `@elizeumatheus`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `uploads`, path: path.join(__dirname, "static", "images", "uploads"), }, }, { resolve: `gatsby-source-filesystem`, options: { name: `news`, path: path.join(__dirname, "static", "content", "news"), }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, `gatsby-plugin-typescript`, { resolve: `gatsby-plugin-root-import`, options: { src: path.join(__dirname, "src"), }, }, `gatsby-transformer-remark`, { resolve: `gatsby-plugin-netlify-cms`, options: { modulePath: path.join(__dirname, "src", "cms", "cms.js"), }, }, ], };
0.984375
high
test/meta/include_test.js
benstepp/tays
0
6568
<reponame>benstepp/tays import { include } from 'lib/meta' import { isEqual as match_array } from 'lodash' describe('include', () => { it('is a function', () => { expect(include).to.exist expect(include).to.be.a('function') }) it('returns a function', () => { expect(include()).to.be.a('function') }) it('includes nothing if no option passed', () => { @include() class A {} class B {} const a_methods = Object.getOwnPropertyNames(A) const b_methods = Object.getOwnPropertyNames(B) expect(match_array(a_methods, b_methods)).to.eq(true) }) it('it adds the instance methods of a class', () => { class A { a() { return 'a' } } @include(A) class B {} const instance = new B() expect(instance.a).to.be.a('function') expect(instance.a()).to.eq('a') }) it('it adds the static methods of a class', () => { class A { static a() { return 'a' } } @include(A) class B {} expect(B.a).to.be.a('function') expect(B.a()).to.eq('a') }) it('does not change the name of the class', () => { class A { a() { return 'a' } } @include(A) class B {} expect(B.name).to.eq('B') }) it('can add multiple classes at once', () => { class A { static a() { return 'a' } } class B { static b() { return 'b' } } @include(A, B) class C {} expect(C.a).to.be.a('function') expect(C.a()).to.eq('a') expect(C.b).to.be.a('function') expect(C.b()).to.eq('b') }) it('can add symbol propertyies', () => { const a = Symbol() class A { static [a]() { return 'a' } } @include(A) class B {} expect(() => B[a]()).to.not.throw(Error) expect(B[a]).to.be.a('function') expect(B[a]()).to.eq('a') }) })
0.996094
high
src/windows/savedStreams/savedStreams.js
MarkMichon1/BitGlitter
212
6569
<gh_stars>100-1000 const { BrowserWindow } = require('electron') const { operatingSystem, productionMode } = require('../../../config') function createSavedStreamsWindow (parentWindow) { let savedStreamsWindow = new BrowserWindow({ backgroundColor: '#25282C', title: 'Saved Streams', width: 800, height: 625, resizable: !productionMode, icon: './assets/icons/icon.png', parent: parentWindow, modal: true, webPreferences: { contextIsolation: false, enableRemoteModule: true, nodeIntegration: true } }) if (productionMode) { savedStreamsWindow.setMenu(null) } else { savedStreamsWindow.webContents.openDevTools() } savedStreamsWindow.loadFile(`${__dirname}/savedStreams.html`) // External links open in browser rather than in app savedStreamsWindow.webContents.on('new-window', function(event, url) { event.preventDefault(); require('electron').shell.openExternal(url); }) return savedStreamsWindow } module.exports = createSavedStreamsWindow
0.890625
high
examples/medium-app/src/messages/pt-BR.js
tlwu2013/grommet
0
6570
// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P. module.exports = { 'Active Alerts': 'Alertas Ativos', Dashboard: 'Painel de Controle', Activity: 'Atividade', Enclosures: 'Enclosures', 'Server Hardware': 'Hardware do Servidor', 'Server Profiles': 'Perfis do Servidor', Reports: 'Relatórios', Settings: 'Configurações', Overview: 'Sumário', Map: 'Mapa', deviceBays: 'Baias do Dispositivo', bay: 'Baia', flavor: 'Tipo', switches: 'Switches' };
0.957031
high
docs/html/search/enums_0.js
Astomih/NenEngine
2
6571
var searchData= [ ['state_0',['state',['../classnen_1_1base__actor.html#afecb2cfb95af8adb2afc771bdbb81972',1,'nen::base_actor']]] ];
0.949219
low
__tests__/Transform.test.js
skmail/react-free-transform
22
6572
import React from 'react'; import ReactDOM from 'react-dom'; import Transform from '../src/index'; import Enzyme,{mount} from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({ adapter: new Adapter() }); it('renders without crashing', () => { const div = document.createElement('div'); const element = <Transform classPrefix="tr" width={100} height={100} x={0} y={0} scaleX={1} scaleY={0} scaleLimit={0.1} angle={0} onUpdate={() => {}} > <div/> </Transform>; ReactDOM.render(element, div); ReactDOM.unmountComponentAtNode(div); const wrapper = mount(element) wrapper.find('.tr-transform').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__rotator').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--tl').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--ml').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--tr').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--tm').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--mr').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--bl').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--bm').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); wrapper.find('.tr-transform__scale-point--br').simulate('mousedown'); global.document.dispatchEvent(new Event('mousemove')); global.document.dispatchEvent(new Event('mouseup')); });
0.960938
high
test/index.spec.js
kenberkeley/express-auto-routes
14
6573
var path = require('path'), request = require('supertest'), should = require('chai').should(), async = require('async'), app = require('express')(), autoRoutes = require('..')(app); autoRoutes(path.resolve(__dirname, '../example/controllers/')); describe('auto mount controllers to routes', function() { var api = request(app.listen()); it('test APIs of example/', function(done) { async.parallel([ function(cb) { api.get('/').expect(200, cb) }, function(cb) { api.post('/log').expect(200, cb) }, function(cb) { api.put('/user').expect(200, cb) }, function(cb) { api.post('/login').expect(200, cb) }, function(cb) { api.get('/home').expect(200, cb) }, function(cb) { api.get('/login').expect(200, cb) }, function(cb) { api.post('/setting').expect(200, cb) }, function(cb) { api.get('/home/xyz').expect(200, cb) }, function(cb) { api.get('/home/foo').expect(200, cb) }, function(cb) { api.get('/user/:uid').expect(200, cb) }, function(cb) { api.get('/user/logout').expect(200, cb) }, function(cb) { api.get('/home/foo/bar').expect(200, cb) }, function(cb) { api.get('/home/foo/hello').expect(200, cb) }, function(cb) { api.del('/user/logout/:uid').expect(200, cb) }, function(cb) { api.get('/user/setting/:uid').expect(200, cb) }, function(cb) { api.get('/home/foo/bar/world').expect(200, cb) } ], done); }); });
0.972656
high
src/generate-site.js
noellecrow/teamprofilecreator
0
6574
<filename>src/generate-site.js const generateTeam = (team) => { console.log(team); // Create an empty array to push html elements on to and loop through team data const html = []; // Create functions for each type of employee that returns HTML data const generateManager = manager => { console.log(manager); let managerHTML = ` <div class="card" style="width: 18rem;"> <div class="card-header"> ${manager.name} <br/> <i class="fas fa-mug-hot"></i>Manager</div> <ul class="list-group list-group-flush"> <li class="list-group-item">ID: ${manager.id}</li> <li class="list-group-item">Email: <span id="email"><a href="mailto:${manager.email}">${manager.email}</a></span></li> <li class="list-group-item">Office Number: ${manager.officeNumber}</li> </ul> </div> `; html.push(managerHTML); } const generateEngineer = engineer => { console.log(engineer); let engineerHTML = ` <div class="card" style="width: 18rem;"> <div class="card-header"> ${engineer.name} <br/> <i class="fas fa-glasses"></i>Engineer</div> <ul class="list-group list-group-flush"> <li class="list-group-item">ID: ${engineer.id}</li> <li class="list-group-item">Email: <span id="email"><a href="mailto:${engineer.email}">${engineer.email}</a></span></li> <li class="list-group-item">Github Username: <a target="_blank" href="https://github.com/${engineer.githubUsername}">${engineer.githubUsername}</a></li> </ul> </div> `; html.push(engineerHTML); } const generateIntern = intern => { console.log(intern); let internHTML = ` <div class="card" style="width: 18rem;"> <div class="card-header"> ${intern.name} <br/> <i class="fas fa-user-graduate"></i>Intern</div> <ul class="list-group list-group-flush"> <li class="list-group-item">ID: ${intern.id}</li> <li class="list-group-item">Email: <span id="email"><a href="mailto:${intern.email}">${intern.email}</a></span></li> <li class="list-group-item">School: ${intern.school}</li> </ul> </div> `; html.push(internHTML); } // create a loop for all employees for (let i=0; i < team.length; i++) { if (team[i].getRole() === "Manager") { generateManager(team[i]); } if (team[i].getRole() === "Engineer") { generateEngineer(team[i]); } if (team[i].getRole() === "Intern") { generateIntern(team[i]); } } // join the HTML blocks return html.join(''); } // export function to generate entire page module.exports = team => { return ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" /> <script src="https://kit.fontawesome.com/1e0a13a89f.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="../dist/style.css" /> <title>Team Profile Generator</title> </head> <body> <header> <h1> My Team </h1> </header> <main> ${generateTeam(team)} </main> </body> </html> `; }
0.996094
high
extensions/amp-story-interactive/0.1/amp-story-interactive-poll.js
grgr-dkrk/amphtml
2
6575
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { AmpStoryInteractive, InteractiveType, } from './amp-story-interactive-abstract'; import {CSS} from '../../../build/amp-story-interactive-poll-0.1.css'; import {computedStyle, setStyle} from '../../../src/style'; import {dev} from '../../../src/log'; import {htmlFor} from '../../../src/static-template'; import {toArray} from '../../../src/types'; /** * Generates the template for the poll. * * @param {!Element} element * @return {!Element} */ const buildPollTemplate = (element) => { const html = htmlFor(element); return html` <div class="i-amphtml-story-interactive-poll-container"> <div class="i-amphtml-story-interactive-prompt-container"></div> <div class="i-amphtml-story-interactive-option-container"></div> </div> `; }; /** * Generates the template for each option. * * @param {!Element} option * @return {!Element} */ const buildOptionTemplate = (option) => { const html = htmlFor(option); return html` <button class="i-amphtml-story-interactive-option" aria-live="polite"> <span class="i-amphtml-story-interactive-option-text"></span> <span class="i-amphtml-story-interactive-option-percentage"> <span class="i-amphtml-story-interactive-option-percentage-text"></span> <span class="i-amphtml-story-interactive-option-percentage-sign" >%</span > </span> </button> `; }; export class AmpStoryInteractivePoll extends AmpStoryInteractive { /** * @param {!AmpElement} element */ constructor(element) { super(element, InteractiveType.POLL, [2, 4]); } /** @override */ buildCallback() { return super.buildCallback(CSS); } /** @override */ buildComponent() { this.rootEl_ = buildPollTemplate(this.element); this.attachContent_(this.rootEl_); return this.rootEl_; } /** @override */ layoutCallback() { return this.adaptFontSize_(dev().assertElement(this.rootEl_)).then(() => super.layoutCallback() ); } /** * Finds the prompt and options content * and adds it to the quiz element. * * @private * @param {Element} root */ attachContent_(root) { this.attachPrompt_(root); this.options_.forEach((option, index) => this.configureOption_(option, index) ); } /** * Creates an option container with option content, * adds styling and answer choices, * and adds it to the quiz element. * * @param {!./amp-story-interactive-abstract.OptionConfigType} option * @param {number} index * @private */ configureOption_(option, index) { const convertedOption = buildOptionTemplate(this.element); convertedOption.optionIndex_ = index; // Extract and structure the option information convertedOption.querySelector( '.i-amphtml-story-interactive-option-text' ).textContent = option.text; this.rootEl_ .querySelector('.i-amphtml-story-interactive-option-container') .appendChild(convertedOption); } /** * @override */ displayOptionsData(optionsData) { if (!optionsData) { return; } const percentages = this.preprocessPercentages_(optionsData); this.getOptionElements().forEach((el, index) => { if (optionsData[index].selected) { const textEl = el.querySelector( '.i-amphtml-story-interactive-option-text' ); textEl.setAttribute('aria-label', 'selected ' + textEl.textContent); } el.querySelector( '.i-amphtml-story-interactive-option-percentage-text' ).textContent = percentages[index]; setStyle(el, '--option-percentage', percentages[index] + '%'); }); } /** * This method changes the font-size to best display the options, measured only once on create. * * If two lines appear, it will add the class 'i-amphtml-story-interactive-poll-two-lines' * It measures the number of lines on all options and generates the best size. * - font-size: 22px (1.375em) - All options are one line * - font-size: 18px (1.125em) - Any option is two lines if displayed at 22px. * * @private * @param {!Element} root * @return {!Promise} */ adaptFontSize_(root) { let hasTwoLines = false; const allOptionTexts = toArray( root.querySelectorAll('.i-amphtml-story-interactive-option-text') ); return this.measureMutateElement( () => { hasTwoLines = allOptionTexts.some((e) => { const lines = Math.round( e./*OK*/ clientHeight / parseFloat( computedStyle(this.win, e)['line-height'].replace('px', '') ) ); return lines >= 2; }); }, () => { this.rootEl_.classList.toggle( 'i-amphtml-story-interactive-poll-two-lines', hasTwoLines ); }, root ); } }
0.996094
high
standup/static/js/standup.js
rlr/standup
2
6576
$(function() { fixTimezones(); var currentUser = localStorage.getItem('personaEmail'); /* Authenticatication for Persona */ $('#login').click(function(ev) { ev.preventDefault(); navigator.id.request(); }); $('#logout').click(function(ev) { ev.preventDefault(); navigator.id.logout(); }); navigator.id.watch({ loggedInUser: currentUser, onlogin: function(assertion) { $.ajax({ type: 'POST', url: '/authenticate', data: { assertion: assertion }, success: function(res, status, xhr) { localStorage.setItem('personaEmail', res.email); window.location.reload(); }, error: function(res, status, xhr) { console.log('Login failure:' + res.status + ': ' + res.statusText); // Remove any old notices $('.notice.sign-in-error').remove(); var message = $('<div></div>'); message.addClass('notice error dismissable sign-in-error'); message.html('We were unable to sign you in. Please try again.'); message.on('click', function() { $(this).fadeOut(600, function() { $(this).remove(); }); }); message.hide(); $('#main-notices').prepend(message); message.fadeOut(0, function() { message.fadeIn(400); }); } }); }, onlogout: function() { $.ajax({ type: 'POST', url: '/logout', success: function(res, status, xhr) { localStorage.removeItem('personaEmail'); window.location.reload(); }, error: function(res, status, xhr) { console.log('Logout failure: ' + res.status + ': ' + res.statusText); } }); } }); }); /* Find all datetime objects and modify them to match the user's current * timezone. */ function fixTimezones() { $('time').each(function(elem) { var $t = $(this); var utc_dt_str = $t.attr('datetime'); var local_dt = new Date(utc_dt_str); var hours = local_dt.getHours(); var minutes = local_dt.getMinutes(); var ampm = 'am'; if (hours > 12) { hours -= 12; ampm = 'pm'; } if (minutes < 10) { // single digit minutes = '0' + minutes; } $t.text(hours + ':' + minutes + ' ' + ampm); }); } function random(upper, lower) { if (!lower) { lower = 0; } return Math.floor(Math.random() * (upper - lower) + 1) + lower; }
0.992188
high
test/components/widget-zoom-spec.js
SportScheck/amplience-sdk-client
17
6577
describe('amp.ampZoom', function(){ var sdk, widgets, self = "widget-zoom", possibleCombinations = ["sdk and widgets", "no sdk but all widgets", 'no other widgets but sdk', 'just self'], makeCombinations, options = { "zoom": {"valid":9, "invalid":["string", [], {}, true], "default": 3}, "url": {"valid":'', "invalid":[ 5, [], {}, false, true], "default": ''} , "activate": {"valid":"over", "invalid":[[], {}, 5, false ], "default": 'onClick'}, "lens": {"valid":false, "invalid":[1, "5", {}, []], "default": true } , "fade": {"valid":false, "invalid":[1, "2", {}, []], "default": true } , "preload": {"valid":false, "invalid":[1, "4", {}, []], "default": true } , "responsive": {"valid":false, "invalid":[1, "2", {}, []], "default": true } , "cursor": {"valid": {"active": 'auto', "inactive": 'auto'}, invalid:[{}, [], 1, false], "default": {"active": 'auto', "inactive": 'auto'}}, "states": { "valid":{ "active":"active", "inactive":"inactive" }, "invalid":[{}, [], 1, false], "default": { "active":"amp-active", "inactive":"amp-inactive" } } }; makeCombinations = function(com){ $.amp = widgets; amp = sdk; if(com == "no sdk but all widgets"){ amp = undefined; }else if (com == 'no other widgets but sdk'){ $.amp = {}; $.amp = {ampZoom: widgets.ampZoom}; }else if(com == 'just self'){ amp = undefined; $.amp = {}; $.amp = {ampZoom: widgets.ampZoom}; }else{ return; } }; beforeEach(function(){ sdk = $.extend(true, {}, window.amp); widgets = $.extend(true, {}, $.amp); jasmine.getStyleFixtures().fixturesPath = 'base'; loadStyleFixtures('dist/amplience-sdk-client.css'); jasmine.Clock.useMock(); }); afterEach(function(){ $.amp = widgets; amp = sdk; }); describe('options', function(){ for(var option in options){ if(options.hasOwnProperty(option, options)){ (function(option){ it('should set the ' + option, function(){ var obj = {}; obj[option] = options[option].valid; setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test').ampZoom(obj); var zoom = $zoom.data('amp-ampZoom'); expect(zoom.options[option]).toEqual(options[option].valid) }); })(option, options); } } it('should set zoom container height and width when responsive option is set to false', function(){ setFixtures('<div id="main"><img id="zoom-test" src="http://placehold.it/350x100"></div>'); var $main = $('#main'); $main.width(500); var w = 200, h = 100; var $zoom = $('#zoom-test'); $zoom.ampZoom({width:w, height:h, responsive:false}); var zoom = $zoom.data('amp-ampZoom'); zoom._calcSize(); expect($zoom.closest('.amp-zoom-container').width()).toBe(w); expect($zoom.closest('.amp-zoom-container').height()).toBe(h); }); it('should set zoom component height ratio and width', function(){ setFixtures('<div id="main"><img id="zoom-test" src="http://placehold.it/1x1"></div>'); var $main = $('#main'); $main.width(500); var w = 16, h = 9; var $zoom = $('#zoom-test'); $zoom.ampZoom({width:w, height:h}); var zoom = $zoom.data('amp-ampZoom'); zoom._calcSize(); expect($zoom.closest('.amp-zoom-container').width()).toBe(500); expect($zoom.closest('.amp-zoom-container').height()).toBe(Math.round($zoom.width() * (h/w))); }); it('should use the url of the zoom alternative as the zoom image - no alternative target', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test'); var alt = "http://placehold.it/650x650"; $zoom.ampZoom({url:alt}); var zoom = $zoom.data('amp-ampZoom'); expect(zoom._getUrl()).toEqual(alt); }); it('should use the url of the zoom alternative as the zoom image - with alternative target', function(){ setFixtures('<div id="box"></div><img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test'); var $main = $('#box'); var alt = "http://placehold.it/650x650"; $zoom.ampZoom({url:alt, target:$main}); var zoom = $zoom.data('amp-ampZoom'); expect(zoom._getUrl()).toEqual(alt); }); }); describe('methods', function(){ describe('create', function(){ it('should be able to create a zoom component with the class of amp-zoom', function(){ var $zoom = setFixtures('<img id="zoom-test">').ampZoom({}); expect($zoom).toBeInDOM(); expect($zoom).toHaveClass('amp-zoom'); }); it('should be able to create a zoom component containing the correct dom structure', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test').ampZoom({}); expect($zoom.parent().parent()).toHaveClass('amp-zoom-container'); expect($zoom.parent().parent()).toHaveClass('amp-inactive'); expect($zoom.parent()).toBe('div'); expect($zoom.parent()).toContain('div.amp-zoom-wrapper'); expect($zoom.parent().children('div.amp-zoom-wrapper')).toContain('img'); expect($zoom.parent().find('.amp-zoom-wrapper img')).toHaveClass('amp-zoom-img'); }); it('should be able to create a zoom component containing the correct dom structure if a zoom box is set', function(){ setFixtures('<div id="box"></div><img id="zoom-test" src="http://placehold.it/350x150">'); var $box = $('#box'); var $zoom = $('#zoom-test').ampZoom({target:$box}); expect($zoom.parent().parent()).toHaveClass('amp-zoom-container'); expect($zoom.parent()).toBe('div'); expect($box).toContain('div.amp-zoom-wrapper'); expect($box.children('div.amp-zoom-wrapper')).toContain('img'); expect($box.find('img')).toHaveClass('amp-zoom-img'); }); it('should be able to create a zoom component containing the correct dom structure if a zoom box is set by jquery selector or selector string', function(){ setFixtures('<div id="box"></div><img id="zoom-test" src="http://placehold.it/350x150">'); var $box = $('#box'), box = '#box'; var $zoom1 = $('#zoom-test').ampZoom({target:$box}); var $zoom2 = $('#zoom-test').ampZoom({target:box}); expect($zoom1.data('amp-ampZoom').box.length).toBe(1); expect($zoom2.data('amp-ampZoom').box.length).toBe(1); }); var arr = [possibleCombinations[2], possibleCombinations[3]]; for(var i = 0; i < arr.length; i++){ (function(arr) { xit('should work if multiple zoom options have been set to use the same external element -' + arr, function(){ setFixtures('<div id="box"></div>' + '<img id="zoom-test1" src="http://placehold.it/350x150">' + '<img id="zoom-test2" src="http://placehold.it/350x150">' + '<img id="zoom-test3" src="http://placehold.it/350x150">' + '<img id="zoom-test4" src="http://placehold.it/350x150">'); var $box = $('#box'); var $zoomTests = [$('#zoom-test1'), $('#zoom-test2'), $('#zoom-test3'), $('#zoom-test4')]; var options = [{target:$box, animate:false}]; for(var i = 0; i < $zoomTests.length; i++){ for(var c = 0; c < options.length; c++){ var test = $zoomTests[i].ampZoom(options[c]); var offset = test.offset(); var mm = $.Event("mousemove", {originalEvent: {clientX: offset.left + 25, clientY: offset.top + 25 }}); var md = $.Event("mousedown", {originalEvent: {clientX: offset.left + 25, clientY: offset.top + 25 }}); var ml = $.Event("mouseleave"); test.ampZoom('zoom', true, md); onIn(options[c]); test.ampZoom('zoom', false, ml); onOut(); test.ampZoom('zoom', true, mm); onIn(options[c]); test.ampZoom('zoom', false, ml); onOut(); } } function onIn(options){ expect($box.children('.amp-zoom-wrapper').eq(i)).toHaveClass('amp-active'); expect($box.children('.amp-zoom-wrapper').eq(i)).toEqual(test.data('amp-ampZoom').wrapper); expect($box.children('.amp-zoom-wrapper').eq(i)).toBeVisible(); // expect($box.children('.amp-zoom-wrapper').eq(i).find('img')).toBeVisible(); } function onOut(){ expect($box.children('.amp-zoom-wrapper').eq(i)).toHaveClass('amp-inactive'); expect($box.children('.amp-zoom-wrapper').eq(i)).toEqual(test.data('amp-ampZoom').wrapper); expect($box.children('.amp-zoom-wrapper').eq(i)).not.toBeVisible(); expect($box.children('.amp-zoom-wrapper').eq(i).find('img')).not.toBeVisible(); } }) }(arr[i])) } it('should merge data-amp-zoom options with options set on create, options set on creation should take precedence', function(){ var zoomStrength = 5, box1 = '.one', box2 = '.two', responsive = false; setFixtures("<img id='zoom-test' data-amp-zoom='{\"zoom\":"+zoomStrength+",\"box\":\""+box1+"\"}'>"); var $zoom = $('#zoom-test').ampZoom({responsive:responsive, target:box2}); var zoom = $zoom.data('amp-ampZoom'); expect(parseInt(zoom.options.zoom)).toEqual(zoomStrength); expect(zoom.options.responsive).toEqual(responsive); expect(zoom.options.target).toEqual(box2); }); var arr = possibleCombinations; for(var i = 0; i < arr.length; i++){ (function(arr) { xit('should have correct loading state whilst loading / loading gif -' + arr, function(){ makeCombinations(arr); setFixtures('<img id="zoom-test" src="http://i1-orig-qa.adis.ws/i/chris_test_2/5?w=500">'); var $zoom = $('#zoom-test').ampZoom({zoom:10 }); var zoom = $zoom.data('amp-ampZoom'); expect(zoom._loading).toBe(true); expect(zoom._loaded).toBe(false); }) }(arr[i])) } it('should default to inner zoom if no box found', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test').ampZoom({target:$('#zoom-box')}); var zoom = $zoom.data('amp-ampZoom'); expect(zoom.box).toBe(false); expect($zoom.parent()).toContain('.amp-zoom-wrapper'); }); it('should default to lens = true unless stated otherwise', function(){ setFixtures('<div id="zoom-box" style="width:500px;height:200px"></div><img id="zoom-test" src="http://placehold.it/1x1">'); var $zoom = $('#zoom-test').ampZoom({target:$('#zoom-box')}); var zoom = $zoom.data('amp-ampZoom'); expect(zoom.lens).toBeTruthy(); expect(zoom.box).toBeTruthy(); expect($zoom.parent().parent()).toContain('.amp-zoom-lens'); }); it('should not allow lens to exceed the width and height of its container', function(){ var bw = 600; var bh = 300; var pw = 300; var ph = 150; setFixtures('<div id="zoom-box"></div>' + '<div id="main"><img id="zoom-test" src="http://placehold.it/1x1"></div>'); var $zoom = $('#zoom-test'); $zoom.ampZoom({zoom:1,target:$('#zoom-box')}); var zoom = $zoom.data('amp-ampZoom'); zoom._makeLens(zoom.lens, bw, bh, 1, {w:pw, h:ph}); expect(zoom.lens.outerWidth()).toEqual(pw); expect(zoom.lens.outerHeight()).toEqual(ph); }); }); describe('resize', function(){ it('should resize after container resizing', function(){ setFixtures('<div id="main"><img id="zoom-test" src="http://placehold.it/1x1"></div>'); var $zoom = $('#zoom-test'); var $main = $('#main'); $zoom.ampZoom({width:w, height:h}); var zoom = $zoom.data("amp-ampZoom"); var fw = 500, sw = 1000; var w = 16, h = 9; $main.width(fw); expect($zoom.parent().width()).toBe(fw); $main.width(sw); zoom._calcSize(); expect($zoom.parent().width()).toBe(sw); }); }); describe('toggleZoom', function(){ it('should toggle zoom state', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test').ampZoom(); var zoom = $zoom.data('amp-ampZoom'); expect($zoom.closest('.amp-zoom-container')).toHaveClass(zoom.options.states.inactive); expect(zoom.zoomed).toBe(false); zoom._onImageLoad(); zoom._zoomLoaded = true; zoom.toggle(); expect($zoom.closest('.amp-zoom-container')).toHaveClass(zoom.options.states.active); expect(zoom.zoomed).toBe(true); zoom.toggle(); expect($zoom.closest('.amp-zoom-container')).toHaveClass(zoom.options.states.inactive); expect(zoom.zoomed).toBe(false); }); }); describe('zoom', function(){ it('should have the correct state while active / inactive', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/350x150">'); var $zoom = $('#zoom-test').ampZoom(); var zoom = $zoom.data('amp-ampZoom'); expect($zoom.closest('.amp-zoom-container')).toHaveClass(zoom.options.states.inactive); expect(zoom.zoomed).toBe(false); zoom._onImageLoad(); zoom._zoomLoaded = true; zoom.zoom(true); expect($zoom.closest('.amp-zoom-container')).toHaveClass('amp-active'); expect(zoom.zoomed).toBe(true); zoom.zoom(false); expect($zoom.closest('.amp-zoom-container')).toHaveClass('amp-inactive'); expect(zoom.zoomed).toBe(false); }); }); describe('getUrl', function(){ var arr = [possibleCombinations[2], possibleCombinations[3]]; for(var i = 0; i < arr.length; i++){ (function(arr) { it('should return the zoom alternative url -' + arr, function(){ makeCombinations(arr); var url = "http://placehold.it/350x150"; setFixtures('<img id="zoom-test" src="'+url+'">'); var $zoom = $('#zoom-test').ampZoom({zoom:5, url:url}); var zoom = $zoom.data("amp-ampZoom"); zoom._originalImage = { width:300, height:150 }; expect(zoom._getUrl()).toEqual(url); }); it('should return the zoom image url with zoomed width and height -' + arr, function(){ makeCombinations(arr); var url = "http://placehold.it/1x1?"; setFixtures('<img id="zoom-test" src="'+url+"w=350"+'">'); var $zoom = $('#zoom-test').ampZoom({zoom:5}); var zoom = $zoom.data("amp-ampZoom"); zoom._originalImage = { width:300, height:150 }; expect(zoom._getUrl()).toEqual(url + "h=" +(zoom.options.zoom * zoom._originalImage.height) + "&w=" +(zoom.options.zoom * zoom._originalImage.width)); }); it('should return the zoom image url with transforms -' + arr, function(){ makeCombinations(arr); var transforms = 'qlt=20'; var url = "http://placehold.it/1x1?"; setFixtures('<img id="zoom-test" src="'+url+transforms+"&w=350"+'">'); var $zoom = $('#zoom-test').ampZoom({zoom:5,transforms:transforms}); var zoom = $zoom.data("amp-ampZoom"); zoom._originalImage = { width:300, height:150 }; expect(zoom._getUrl()).toEqual(url +transforms + "&h=" +(zoom.options.zoom * zoom._originalImage.height) + "&w=" +(zoom.options.zoom * zoom._originalImage.width)); }); it('should return a stringified url with the new width -' + arr, function(){ makeCombinations(arr); var url = "http://placehold.it/350x150"; setFixtures('<img id="zoom-test" src="'+url+'">'); var $zoom = $('#zoom-test').ampZoom(); var zoom = $zoom.data("amp-ampZoom"); zoom._originalImage = { width:300, height:150 }; expect(zoom._setWidth(url, {w:500})).toEqual(url + "?w=500"); }); it('should return the width set on a parameter -'+ arr, function(){ makeCombinations(arr); var url = "http://placehold.it/350x150?w=500"; setFixtures('<img id="zoom-test" src="'+url+'">'); var $zoom = $('#zoom-test').ampZoom(); var zoom = $zoom.data("amp-ampZoom"); expect(zoom._getWidth(url)).toEqual(500); }); }(arr[i])); } }); describe('visible', function(){ it('should recalculate on visible', function(){ var url = "http://placehold.it/350x150?w=500"; setFixtures('<div id="main" style="width:450px;"><img id="zoom-test" src="http://placehold.it/350x150"></div>'); var $main = $('#main').hide(); var $zoom = $('#zoom-test').ampZoom(); var zoom = $zoom.data("amp-ampZoom"); expect($zoom.parent().width()).toEqual(0); expect($zoom.parent().height()).toEqual(0); zoom.visible((function(){ $main.show(); return true; })()); expect(zoom._visible).toBe(true); expect($zoom.parent().width()).toEqual($main.width()); expect($zoom.parent().height()).toEqual($main.height()); }); }); }); describe('events', function(){ it('should call create on create', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'create'); var $zoom = $(selector).ampZoom(); expect("create").toHaveBeenTriggeredOnAndWith(selector, {}); }); it('should call created on created', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'created'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); zoom._onImageLoad(); expect("created").toHaveBeenTriggeredOnAndWith(selector, {}); }); it('should call visible on visible', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'visible'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom").visible(true); expect("visible").toHaveBeenTriggeredOnAndWith(selector, {visible: true}); }); it('should call startPreload', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'startpreload'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); zoom._onImageLoad(); zoom.preload(); expect("startpreload").toHaveBeenTriggeredOnAndWith(selector, {}); }); it('should call startMove', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'startmove'); var $zoom = $(selector).ampZoom({url:'http://placehold.it/2x2'}); var zoom = $zoom.data("amp-ampZoom"); var offset = $zoom.offset(); var md = $.Event("mousedown", {originalEvent: {clientX: offset.left + 25, clientY: offset.top + 25 }}); zoom._onImageLoad(); zoom._zoomLoaded = true; zoom.zoom(true, md); expect("startmove").toHaveBeenTriggeredOn(selector); }); it('should call move', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'move'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); var offset = $zoom.offset(); zoom._onImageLoad(); zoom._zoomLoaded = true; var mm = $.Event("mousemove", {originalEvent: {clientX: offset.left + 25, clientY: offset.top + 25 }}); zoom.zoom(true, mm); expect("move").toHaveBeenTriggeredOn(selector); }); it('should call stopMove', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'stopmove'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); var mm = $.Event("mousemove"); var ml = $.Event("mouseleave"); zoom._onImageLoad(); zoom._zoomLoaded = true; zoom.zoom(true, mm); zoom.zoom(false, mm); expect("stopmove").toHaveBeenTriggeredOn(selector); }); it('should call zoomedIn', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'zoomedin'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); zoom._onImageLoad(); zoom._zoomLoaded = true; var mm = $.Event("mousemove"); zoom.zoom(true, mm); expect("zoomedin").toHaveBeenTriggeredOn(selector); }); it('should call zoomedOut', function(){ setFixtures('<img id="zoom-test" src="http://placehold.it/1x1">'); var selector = '#zoom-test'; var spyEvent = spyOnEvent(selector, 'zoomedout'); var $zoom = $(selector).ampZoom(); var zoom = $zoom.data("amp-ampZoom"); zoom.zoom(true); zoom.zoom(false); expect("zoomedout").toHaveBeenTriggeredOnAndWith(selector, {}); }); }); });
0.972656
high
playground/src/events/events.js
BrendonCurmi/amp.dev
1
6578
<reponame>BrendonCurmi/amp.dev<gh_stars>1-10 // Copyright 2018 The AMPHTML Authors // // 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. class EventBus { constructor() { this._observers = new Map(); } subscribe(channel, observer) { if (!channel) throw new Error('empty channel'); const channels = Array.isArray(channel) ? channel : [channel]; channels.forEach(c => { this._observersForChannel(c).push(observer); }); } publish(channel, data) { if (!channel) throw new Error('empty channel'); this._observersForChannel(channel).forEach(o => { o(data); }); } _observersForChannel(channel) { let channelObservers = this._observers.get(channel); if (!channelObservers) { channelObservers = []; this._observers.set(channel, channelObservers); } return channelObservers; } } export default new EventBus();
0.992188
high
packages/app/lib/apps/board-routes.js
mfossen/wuffle
106
6579
<gh_stars>100-1000 const express = require('express'); const path = require('path'); /** * This component provides the publicly accessible board routes. * * @param {import('express').Router} router */ module.exports = async (router) => { const staticDirectory = path.join(__dirname, '..', '..', 'public'); router.get('/', (req, res, next) => { res.redirect('/board'); }); // board page router.get('/board', (req, res, next) => { res.sendFile(path.join(staticDirectory, 'index.html')); }); router.get('/robots.txt', (req, res, next) => { res.sendFile(path.join(staticDirectory, 'robots.txt')); }); router.get('/service-worker.js', (req, res, next) => { res.sendFile(path.join(staticDirectory, 'service-worker.js')); }); // static resources router.use('/board', express.static(staticDirectory)); };
0.980469
high
lib/actions/authorization/check_client.js
authok/node-oidc-provider
0
6580
const { strict: assert } = require('assert'); const { InvalidClient, InvalidRequestObject, } = require('../../helpers/errors'); const presence = require('../../helpers/validate_presence'); const base64url = require('../../helpers/base64url'); const instance = require('../../helpers/weak_cache'); const { PUSHED_REQUEST_URN } = require('../../consts'); const rejectRequestAndUri = require('./reject_request_and_uri'); const loadPushedAuthorizationRequest = require('./load_pushed_authorization_request'); /* * Checks client_id * - value presence in provided params * - value being resolved as a client * * @throws: invalid_request * @throws: invalid_client */ module.exports = async function checkClient(ctx, next) { const { oidc: { params } } = ctx; const { pushedAuthorizationRequests } = instance(ctx.oidc.provider).configuration('features'); try { presence(ctx, 'client_id'); } catch (err) { const { request_uri: requestUri } = params; let { request } = params; if ( !( pushedAuthorizationRequests.enabled && requestUri && requestUri.startsWith(PUSHED_REQUEST_URN) ) && request === undefined ) { throw err; } rejectRequestAndUri(ctx, () => {}); if (requestUri) { const loadedRequestObject = await loadPushedAuthorizationRequest(ctx); ({ request } = loadedRequestObject); } const parts = request.split('.'); let decoded; let clientId; try { assert(parts.length === 3 || parts.length === 5); parts.forEach((part, i, { length }) => { if (length === 3 && i === 1) { // JWT Payload decoded = JSON.parse(base64url.decodeToBuffer(part)); } else if (length === 5 && i === 0) { // JWE Header decoded = JSON.parse(base64url.decodeToBuffer(part)); } }); } catch (error) { throw new InvalidRequestObject(`Request Object is not a valid ${parts.length === 5 ? 'JWE' : 'JWT'}`); } if (decoded) { clientId = decoded.iss; } if (typeof clientId !== 'string' || !clientId) { throw err; } params.client_id = clientId; } const client = await ctx.oidc.provider.Client.find(ctx, ctx.oidc.params.client_id); if (!client) { // there's no point in checking again in authorization error handler ctx.oidc.noclient = true; throw new InvalidClient('client is invalid', 'client not found'); } ctx.oidc.entity('Client', client); return next(); };
0.996094
high
src/utils/utils.js
cameronbroe/clue-sheets
0
6581
import _ from 'lodash'; export async function getBoard (boardId) { let gamesListResponse = await fetch('static/games-list.json'); let gamesList = await gamesListResponse.json(); let listEntry = _.find(gamesList.games, (e) => { return e.boardId === boardId; }); let gameBoardResponse = await fetch(`static/${listEntry.filename}`); let gameBoard = await gameBoardResponse.json(); return gameBoard; }
0.957031
high
crates/swc_ecma_codegen/tests/test262/c964ed7bc2373c54.js
mengxy/swc
1
6582
function a({ a =(1) , b }) {} function b([b, c = (2)]) {} var { d =(3) , e } = d; var [d, e = (4)] = d;
0.867188
low
lib/commonAPI/coreapi/public/api/rhoapi-native.android.js
hanazuki/rhodes
0
6583
<reponame>hanazuki/rhodes /* Rho API Android native bridge */ (function ($, rho, rhoPlatform, rhoUtil) { 'use strict'; if (window[rhoUtil.flag.USE_AJAX_BRIDGE]) return; var RHO_API_CALL_TAG = '__rhoNativeApiCall'; var RHO_API_TAG = '__rhoNativeApi'; var nativeApi = { apiCall: function (cmdText, async, resultHandler) { //window.alert(cmdText); var nativeApiResult = {}; if (window[RHO_API_TAG] && 'function' == typeof window[RHO_API_TAG]['apiCall']) { nativeApiResult = window[RHO_API_TAG].apiCall(cmdText, async); } else { nativeApiResult = prompt(cmdText, RHO_API_CALL_TAG + ':prompt'); } //window.alert(nativeApiResult); resultHandler(JSON.parse(nativeApiResult)); } }; // TODO: uncomment as native handler will be implemented rhoPlatform.nativeApiCall = nativeApi.apiCall; })(Rho.jQuery, Rho, Rho.platform, Rho.util);
0.984375
high
src/VoxRenderer/Level/Level.js
dgoemans/VoxRenderer
3
6584
import * as THREE from 'three'; import Lamp from "../Objects/Lamp"; import Ball from "../Objects/Ball"; import Road from "../Objects/Road"; import PhysicsHelper from '../Physics/PhysicsHelper'; import VoxModelLoader from '../VoxModel/VoxModelLoader'; export default class Level { constructor(renderer, physics) { this.physics = physics; this.renderer = renderer; this.scene = new THREE.Scene(); this.scene.fog = new THREE.FogExp2( 0x1f2125, 0.0015 ); const light = new THREE.HemisphereLight( 0xfafaff, 0xffffff, 0.1 ); this.scene.add( light ); const floorGeometry = new THREE.BoxGeometry(4096, 1, 4096); const {shape, center} = PhysicsHelper.createBox(floorGeometry); const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 0, flatShading: true, roughness: 1 }); const floor = new THREE.Mesh(floorGeometry, floorMaterial); floor.userData.physicsShape = shape; floor.userData.physicsCenter = center; floor.receiveShadow = true; floor.position.set(0,-0.5,0); this.addToScene(floor, 0, 0.5); for(let i=-480; i<480; i+=40) { new Road(this, new THREE.Vector3(-20, 0, i)); } this.addLamps(); this.addBuildings(); } async addLamps() { for(let i=-1000; i <= 1000; i+= 280) { await new Lamp(this, new THREE.Vector3(-44.5,0, i - 44.5)); await new Lamp(this, new THREE.Vector3(35.5,0, i + 35.5)); } } async addBuildings() { for(let i=-2000; i <= 2000; i+= 150) { await this.loadVox('building_1', new THREE.Vector3(-200,0,i)); await this.loadVox('building_1', new THREE.Vector3(63,0,i)); } } async loadVox(model, position, rotation) { position = position || new THREE.Vector3(); rotation = rotation || new THREE.Euler(); const voxLoader = new VoxModelLoader(); const mesh = await voxLoader.load(`../models/${model}.vox`, position, rotation); this.addToScene(mesh, 0); } addToScene(mesh, mass = 1, restitution = 0) { this.scene.add(mesh); mesh.userData.physicsShape && this.physics.createRigidBody(mesh, mass, restitution); this.renderer.shadowMap.needsUpdate = true; } addBall(position) { return new Ball(this, position); } update(delta, totalElapsed) { /*if(totalElapsed > 5 && totalElapsed < 30 && Math.random() < 0.05) { const angle = Math.random() * Math.PI * 2 const radius = 20; const x = radius*Math.cos(angle); const z = radius*Math.sin(angle); this.addBall(new THREE.Vector3(x,105,z)); }*/ } }
0.992188
high
admin/tabs/userData/JsonBlobPanel.js
vaibhavantil2/hoist-react
13
6585
/* * This file belongs to Hoist, an application development toolkit * developed by Extremely Heavy Industries (www.xh.io | <EMAIL>) * * Copyright © 2021 Extremely Heavy Industries Inc. */ import {creates, hoistCmp} from '@xh/hoist/core'; import {fragment} from '@xh/hoist/cmp/layout'; import {restGrid} from '@xh/hoist/desktop/cmp/rest'; import {button} from '@xh/hoist/desktop/cmp/button'; import {Icon} from '@xh/hoist/icon'; import {JsonBlobModel} from './JsonBlobModel'; import {differ} from '../../differ/Differ'; export const jsonBlobPanel = hoistCmp.factory({ model: creates(JsonBlobModel), render({model}) { return fragment( restGrid({ extraToolbarItems: () => { return button({ icon: Icon.diff(), text: 'Compare w/ Remote', onClick: () => model.openDiffer() }); } }), differ({omit: !model.differModel}) ); } });
0.964844
high
study/boolean-tutor/js/app.js
tecanal/kids-corner
0
6586
<gh_stars>0 const exampleEl = document.getElementById("example"); const alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); // the starting probability of boolean expression nesting const EASY_DIFF_NESTING_PROBABILITY = 0.80; // the rate in which the nesting probability diminishes each recursive step const PROB_DECAY = 0.50; // global state variable let answer; let score = 0; /** * Initialize UI components when the script starts. */ (function initUI() { document.querySelector("#answerTrue").onclick = () => answerPrompt(true); document.querySelector("#answerFalse").onclick = () => answerPrompt(false); generateProblem(); })(); /** * Recursively create an evaluateable boolean expression. * @param {String[]} operands * @param {Number} nestingProbability * @returns {String} expression */ function getBooleanExpression(operands, nestingProbability) { // generate boolean expressions from the given operands let expressions = operands.map(x => { // if number is under the probabilty threshold, generate nested expression if (Math.random() < nestingProbability) { return `(${getBooleanExpression(operands, nestingProbability - PROB_DECAY)})`; } else { return x; } }); // choose the boolean operations that will be performed between expressions let operations = operands.map(_ => { // flip a coin to choose if (Math.round(Math.random())) { return " && "; } else { return " || "; } }); // combine the expressions and operations together return expressions.reduce((a, b, i) => [a, b].join(operations[(i - 1) % operations.length])); } /** * Create a new boolean expression problem to show on screen. */ function generateProblem() { let start = Math.round(Math.random()) ? "!" : ""; let booleanExpression = start; // generate a random number of operands depending on difficulty level // TODO skew towards lower numbers? and change based on diff level let min = 2, max = 2; let numOperands = Math.floor(Math.random() * (max - min + 1)) + min; // generate array of unique operand identifiers let operands =[...Array(numOperands).keys()].reduce((ids, _) => { ids.push(getRandomUniqueIdentifier(ids)); return ids; }, []); // if starts with negation, there needs to be parenthesis around the expression if (start == "!") { booleanExpression += `(${getBooleanExpression(operands, EASY_DIFF_NESTING_PROBABILITY)})`; } else { booleanExpression += `${getBooleanExpression(operands, EASY_DIFF_NESTING_PROBABILITY)}`; } // generate initial values for the operands let initValues = operands.map(_ => Math.round(Math.random()) ? 1 : 0); // if all initial values are true, make one false if (initValues.every(x => x === 1)) { initValues[Math.floor(Math.random() * initValues.length)] = 0; } // if all initial values are false, make one true else if (initValues.every(x => !x)) { initValues[Math.floor(Math.random() * initValues.length)] = 1; } // create the boolean expression let expression = initValues.reduce((acc, curr, i) => { return acc + `boolean ${operands[i]} = ${!!curr};\n`; }, ""); expression += `\n${booleanExpression}`; // create an executable javascript boolean expression to eval() let executableExpression = operands.reduce((acc, curr, i) => { return acc.replace(new RegExp(curr, "g"), initValues[i]); }, booleanExpression); // evaluate the expression and make that the answer answer = !!eval(executableExpression); // add code mirror className so syntax highlighting works exampleEl.className = "cm-s-default"; // run CodeMirror syntax highlighting on the code CodeMirror.runMode(expression, { name: "text/x-java" }, example); } /** * Answer the question. * @param {Boolean} input */ function answerPrompt(input) { // show the notification alert const notif = document.getElementById("notification"); notif.style.display = ""; if (input == answer) { setScore(10); // give the user feedback that they're right notif.innerHTML = "That's right!"; notif.className = "success"; } else { setScore(-10); // give the user feedback that they're wrong notif.innerHTML = "That's wrong."; notif.className = "failure"; } // hide the notification alert after 1 second setTimeout(() => notif.style.display = "none", 1000); generateProblem(); } /** * Change the score UI element. * @param {Number} delta */ function setScore(delta) { // change score by delta value score += delta; // update score UI element document.getElementById("score").innerText = "Score: " + score; } /** * Get a random one-letter identifier that does is not a duplicate of * any ones in the prev array. * @param {String[]} prev * @returns String */ function getRandomUniqueIdentifier(prev) { let id = alphabet[Math.floor(Math.random() * alphabet.length)]; if (prev.length && prev.includes(id)) { return getRandomUniqueIdentifier(prev); } return id; }
0.992188
high
lib/run-bot.js
lonelybots/lonelybots-sdk-node
1
6587
<gh_stars>1-10 var _ = require('lodash') var express = require('express') var getAttachmentFuncFactory = require('./get-attachment') var replyFuncFactory = require('./reply') var createFormFuncFactory = require('./create-form') var bodyParser = require('body-parser').json() module.exports = function (options, dependencies) { // validate input arguments if (!options) { throw new Error('missing required argument options') } if (!options.validationToken) { throw new Error('missing required argument options.validationToken') } if (!options.accessToken) { throw new Error('missing required argument options.accessToken') } if (!options.callback) { throw new Error('missing required argument options.callback') } if (typeof options.callback !== 'function') { throw new Error('options.callback must be a function') } // allow dependency injection for testability var getAttachment = dependencies && dependencies.getAttachment ? dependencies.getAttachment : getAttachmentFuncFactory(options) var reply = dependencies && dependencies.reply ? dependencies.reply : replyFuncFactory(options) var createForm = dependencies && dependencies.createForm ? dependencies.createForm : createFormFuncFactory(options) // sets up the result express middleware var router = express.Router() // GET requests are for ownership validation router.get('/', function (req, res, next) { if (req.get('authorization') === options.validationToken) { res.send(req.query['response']) } else { res.status(401).send('validation token mismatch') } }) // POST requests are receiving emails router.post('/', bodyParser, function (req, res, next) { if (req.get('authorization') === options.validationToken) { var mail = _.cloneDeep(req.body) mail.reply = function (outgoingEmail) { return reply(mail, outgoingEmail, true) } mail.replyAll = function (outgoingEmail) { return reply(mail, outgoingEmail, false) } mail.createForm = function (form) { return createForm(mail, form) } if (mail.attachments) { _.each(mail.attachments, function (attachment) { attachment.get = (function (mailId, generatedFileName) { return function () { return getAttachment( mailId, generatedFileName, dependencies) } })(mail.id, attachment.generatedFileName) }) } options.callback(mail) res.status(200).send('OK') } else { res.status(401).send('validation token mismatch') } }) return router }
0.976563
high
src/app/src/lib/navigation.js
GrupaZero/admin
4
6588
<reponame>GrupaZero/admin function Navigation() { 'use strict'; var items = []; /** * Function checks if 'item' structure is valid * * @param item object * @returns {boolean} */ var checkStructure = function(item) { if (_.has(item, 'divider')) { if (item.divider !== true) { throw new Error('Property: ' + '\'divider\'' + ' must be set to \'true\''); } } else if (!_.has(item, 'title')) { throw new Error('Property: ' + 'title' + ' is missing'); } else if (!_.has(item, 'action') && !_.has(item, 'href')) { throw new Error('Property: ' + '\'action\' or \'href\'' + ' are required'); } return true; }; /** * Function returns children of element specified by 'title' * * @param title string * @returns {Array} */ var getChildren = function(title) { var children = [], foundFlag = false; _.forEach(items, function(value, index) { if (value.title === title) { foundFlag = true; if (_.has(value, 'children') && Array.isArray(value.children)) { children = value.children; } return false; } }); if (foundFlag === false) { throw new Error('Parent: \'' + title + '\' have no children, because does not exist'); } return children; }; /** * Function adds element according to 'position' argument * position = 'before' - element will be added before element specified by 'title' * position = 'after' - element will be added after element specified by 'title' * * @param title string * @param item object * @param position string */ var addBeforeAfter = function(title, item, position) { if (typeof position === 'undefined') { throw new Error('Argument \'position\' is required, values: \'before\' or \'after\''); } else if (typeof position !== 'string') { throw new Error('Argument \'position\' must be of string type, values: \'before\' or \'after\''); } if (checkStructure(item)) { var foundFlag = false; _.forEach(items, function(value, index) { if (value.title === title) { foundFlag = true; if (position === 'before') { items.splice(index, 0, item); } else if (position === 'after') { items.splice(index + 1, 0, item); } return false; } }); if (foundFlag === false) { throw new Error('Element: \'' + title + '\' does not exist'); } } }; /** * Function adds child link according to 'position' argument * position = true - child will be added as first element * position = false - child will be added as last element * * @param parent string * @param item object * @param position boolean */ var addChild = function(parent, item, position) { if (typeof position === 'undefined') { position = false; } else if (typeof position !== 'boolean') { throw new Error('Argument \'position\' must be of boolean type'); } if (checkStructure(item)) { var foundFlag = false; _.forEach(items, function(value, index) { if (value.title === parent) { if (!_.has(value, 'children') || !Array.isArray(value.children)) { value.children = []; } if (position === true) { value.children.unshift(item); } else if (position === false) { value.children.push(item); } foundFlag = true; return false; } }); if (foundFlag === false) { throw new Error('Parent: \'' + parent + '\' does not exist'); } } }; /** * Function adds child link according to 'position' argument * position = 'before' - child will be added before element specified by 'title' * position = 'after' - child will be added after element specified by 'title' * * @param parent string * @param title string * @param item object * @param position string */ var addBeforeAfterChild = function(parent, title, item, position) { if (typeof position === 'undefined') { throw new Error('Argument \'position\' is required, values: \'before\' or \'after\''); } else if (typeof position !== 'string') { throw new Error('Argument \'position\' must be of string type, values: \'before\' or \'after\''); } if (checkStructure(item)) { var foundFlag = false, children = getChildren(parent); if (children.length === 0) { throw new Error('Parent: \'' + parent + '\' have no children'); } _.forEach(children, function(value, index) { if (value.title === title) { foundFlag = true; if (position === 'before') { children.splice(index, 0, item); } else if (position === 'after') { children.splice(index + 1, 0, item); } return false; } }); if (foundFlag === false) { throw new Error('Child: \'' + title + '\' does not exist'); } } }; return { /** * Function adds element to the end of menu * * @param item object */ add: function(item) { if (checkStructure(item)) { items.push(item); } }, /** * Function adds element to the menu as first * * @param item object */ addFirst: function(item) { if (checkStructure(item)) { items.unshift(item); } }, /** * Function adds element 'item' to the menu before element specified by 'title' * * @param title string * @param item object */ addBefore: function(title, item) { addBeforeAfter(title, item, 'before'); }, /** * Function adds element 'item' to the menu after element specified by 'title' * * @param title string * @param newItem object */ addAfter: function(title, newItem) { addBeforeAfter(title, newItem, 'after'); }, /** * Function adds child link as first to the element specified by 'parent' argument * * @param parent string * @param item object */ addFirstChild: function(parent, item) { addChild(parent, item, true); }, /** * Function adds child link as last to the element specified by 'parent' argument * * @param parent string * @param item object */ addLastChild: function(parent, item) { addChild(parent, item, false); }, /** * Function adds link to the element specified by 'parent' before child element specified by 'title' * * @param parent string * @param title string * @param item object */ addBeforeChild: function(parent, title, item) { addBeforeAfterChild(parent, title, item, 'before'); }, /** * Function adds link to the element specified by 'parent' after child element specified by 'title' * * @param parent string * @param title string * @param item object */ addAfterChild: function(parent, title, item) { addBeforeAfterChild(parent, title, item, 'after'); }, /** * Function return items from menu * * @returns {Array} */ getItems: function() { return items; }, /** * Function exports links to 'dropdown' menu * * @returns {Array} */ exportToDropdownMenu: function() { var results = []; var newItem = {}; _.forEach(items, function(value) { _.forIn(value, function(value, key) { if (key === 'title') { newItem.text = value; } else { newItem[key] = value; } }); results.push(newItem); newItem = {}; }); return results; } }; } module.exports = Navigation;
0.996094
high
packages/plugin-remove-useless-continue/test/fixture/if.js
sobolevn/putout
260
6589
<gh_stars>100-1000 for (const currentPath of bodyPath) { if (isUseStrict(currentPath)) { continue; } }
0.777344
low
src/containers/UsersNow.js
maxim-saplin/GA-RealtimeReport-PWA
1
6590
<reponame>maxim-saplin/GA-RealtimeReport-PWA import {connect} from 'react-redux'; import Users from '../components/Users'; const mapStateToProps = (state) => { return { users: state.gaData.usersNow, countriesAndUsers: state.gaData.countriesAndUsersNow, title: "Now" } } export default connect(mapStateToProps)(Users);
0.494141
high
node_modules/carbon-icons-svelte/lib/WatsonHealthAiResultsUrgent32/index.js
seekersapp2013/new
0
6591
import WatsonHealthAiResultsUrgent32 from "./WatsonHealthAiResultsUrgent32.svelte"; export default WatsonHealthAiResultsUrgent32;
0.65625
low
src/store/index.js
yuri2peter/naples-next
0
6592
// For more usage about redux: https://redux.js.org/tutorials/quick-start // Browser extension Redux DevTools is supported by default. import { configureStore } from '@reduxjs/toolkit'; import exampleSlice from './slices/example'; export default configureStore({ reducer: { example: exampleSlice, }, });
0.832031
high
cli/tests/test_unresolved_promise.js
Preta-Crowz/deno
5
6593
<gh_stars>1-10 Deno.test({ name: "unresolved promise", fn() { return new Promise((_resolve, _reject) => { console.log("in promise"); }); }, }); Deno.test({ name: "ok", fn() { console.log("ok test"); }, });
0.691406
high
klient/js/LoadingScreen.js
MStabryla/GwentZSL
0
6594
function LS() { var that = this; this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera( 45, // kąt patrzenia kamery (FOV - field of view) 0.8*window.innerWidth / window.innerHeight, // proporcje widoku, powinny odpowiadać proporjom naszego ekranu przeglądarki 0.1, // minimalna renderowana odległość 10000 // maxymalna renderowana odległość ); this.renderer = new THREE.WebGLRenderer(); this.renderer.setClearColor(0x76716A); this.renderer.setSize( window.innerWidth, window.innerHeight); var a = "76716A"; var axis = new THREE.AxisHelper(200000000); this.scene.add(axis); var light = new THREE.SpotLight(0xffffff, 100,500, 3.14); light.position.set(0, -101, 100); this.scene.add(light); document.getElementById("LoadingScreen").appendChild(this.renderer.domElement); this.camera.position.x = 0; this.camera.position.y = 120; this.camera.position.z = -150; this.camera.lookAt(0,100, 250); function Model() { var daeModel this.loadModel = function (url, callback) { var loader = new THREE.ColladaLoader(); loader.load(url, function (collada) { daeModel = collada.scene; daeModel.scale.set(10, 10, 10) daeModel.traverse(function (child) { if (child instanceof THREE.Mesh) { } }); callback(daeModel) }) } this.getModel = function () { return daeModel } } var model = new Model(); var witch = null; model.loadModel ("model/Witcher2.xml", function (modelData) { witch = modelData; modelData.position.y -= 100; modelData.position.z -= 250; modelData.rotation.y = Math.PI; //modelData.position.z -= 50; that.scene.add(modelData) var newpos = new THREE.Vector3(modelData.position.x,modelData.position.y+50,modelData.position.z) that.camera.lookAt(newpos); that.camera.position.z -= 30; /*function animateScene() { requestAnimationFrame(animateScene); modelData.rotation.z += 0.005 } animateScene();*/ }) this.stop = false; function animateScene() { if(!that.stop) { requestAnimationFrame(animateScene); } if(witch) { witch.rotation.z += 0.005; } that.renderer.render(that.scene, that.camera); } animateScene(); }
0.980469
high
10react/code20/react-hkzf/src/components/AuthRoute/index.js
nacker/web
2
6595
import React from 'react' import { Route, Redirect } from 'react-router-dom' import { isAuth } from '../../utils' /* ① 在 components 目录中创建 AuthRoute/index.js 文件。 ② 创建组件 AuthRoute 并导出。 ③ 在 AuthRoute 组件中返回 Route 组件(在 Route 基础上做了一层包装,用于实现自定义功能)。 ④ 给 Route 组件,添加 render 方法,指定该组件要渲染的内容(类似于 component 属性)。 ⑤ 在 render 方法中,调用 isAuth() 判断是否登录。 ⑥ 如果登录了,就渲染当前组件(通过参数 component 获取到要渲染的组件,需要重命名)。 ⑦ 如果没有登录,就重定向到登录页面,并且指定登录成功后要跳转到的页面路径。 ⑧ 将 AuthRoute 组件接收到的 props 原样传递给 Route 组件(保证与 Route 组件使用方式相同)。 ⑨ 使用 AuthRoute 组件配置路由规则,验证能否实现页面的登录访问控制。 // 去出租页面: <AuthRoute path="/rent/add" component={RentAdd} /> */ const AuthRoute = ({ component: Component, ...rest }) => { return ( <Route {...rest} render={props => { // props 表示:当前路由信息 if (isAuth()) { // 登录 // 注意:需要将 props 也就是路由信息传递给该组件,才能在被渲染的组件中获取到路由信息 return <Component {...props} /> } else { // 没有登录 return ( <Redirect to={{ // 要跳转到的页面路径 pathname: '/login', // 传递额外的数据,此处,用来指定登录后要返回的页面路径 state: { from: props.location } }} /> ) } }} /> ) } export default AuthRoute
0.976563
high
packages/transform-metering/test/test-transform.js
ctjlewis/agoric-sdk
0
6596
<reponame>ctjlewis/agoric-sdk /* eslint-disable no-await-in-loop */ import test from 'ava'; import fs from 'fs'; import path from 'path'; import { makeMeteringTransformer } from '../src/index.js'; import * as c from '../src/constants.js'; const filename = new URL(import.meta.url).pathname; const dirname = path.dirname(filename); test('meter transform', async t => { let getMeter; const meteringTransform = makeMeteringTransformer(undefined, { overrideMeterId: '$m', overrideRegExpIdPrefix: '$re_', }); const rewrite = (source, testName) => { let cMeter; getMeter = () => ({ [c.METER_COMPUTE]: units => (cMeter = units), }); const ss = meteringTransform.rewrite({ src: source, endowments: { getMeter }, sourceType: 'script', }); t.is(cMeter, source.length, `compute meter updated ${testName}`); return ss.src; }; t.throws( () => rewrite(`$m.l()`, 'blacklisted meterId'), { instanceOf: SyntaxError }, 'meterId cannot appear in source', ); const base = `${dirname}/../testdata`; const tests = await fs.promises.readdir(base); for (const testDir of tests) { const src = await fs.promises.readFile( `${base}/${testDir}/source.js`, 'utf8', ); const rewritten = await fs.promises .readFile(`${base}/${testDir}/rewrite.js`, 'utf8') // Fix golden files in case they have DOS or MacOS line endings. .then(s => s.replace(/(\r\n|\r)/g, '\n')) .catch(_ => undefined); const transformed = rewrite(src.trimRight(), testDir); if (rewritten === undefined) { console.log(transformed); } t.is(transformed, rewritten.trimRight(), `rewrite ${testDir}`); } });
0.996094
high
client/src/components/allInfo/FullPageWeeklySpecials.js
tsbolty/GoingsOn
0
6597
import React from 'react'; const FullPageWeeklySpecials = ({ specials }) => { const tableStyle = { paddingLeft: "20px", paddingRight: "20px" } return ( <div className="weekly-specials"> <h4>Weekly Specials</h4> {specials.weeklySpecials && specials.weeklySpecials.map(special => ( <table key= {special._id}> <thead> <tr> <th style={tableStyle} className="weekly-specials-table-header">Monday</th> <th style={tableStyle} className="weekly-specials-table-header">Tuesday</th> <th style={tableStyle} className="weekly-specials-table-header">Wednesday</th> <th style={tableStyle} className="weekly-specials-table-header">Thursday</th> <th style={tableStyle} className="weekly-specials-table-header">Friday</th> <th style={tableStyle} className="weekly-specials-table-header">Saturday</th> <th style={tableStyle} className="weekly-specials-table-header">Sunday</th> </tr> </thead> <tbody> <tr> <td style={tableStyle}><strong>{special.mondayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.tuesdayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.wednesdayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.thursdayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.fridayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.saturdayFoodSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.sundayFoodSpecialHeading}</strong></td> </tr> <tr> <td style={tableStyle}>{special.mondayFoodSpecialDescription}</td> <td style={tableStyle}>{special.tuesdayFoodSpecialDescription}</td> <td style={tableStyle}>{special.wednesdayFoodSpecialDescription}</td> <td style={tableStyle}>{special.thursdayFoodSpecialDescription}</td> <td style={tableStyle}>{special.fridayFoodSpecialDescription}</td> <td style={tableStyle}>{special.saturdayFoodSpecialDescription}</td> <td style={tableStyle}>{special.sundayFoodSpecialDescription}</td> </tr> <tr> <td style={tableStyle}><strong>{special.mondayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.tuesdayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.wednesdayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.thursdayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.fridayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.saturdayDrinkSpecialHeading}</strong></td> <td style={tableStyle}><strong>{special.sundayDrinkSpecialHeading}</strong></td> </tr> <tr> <td style={tableStyle}>{special.mondayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.tuesdayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.wednesdayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.thursdayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.fridayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.saturdayDrinkSpecialDescription}</td> <td style={tableStyle}>{special.sundayDrinkSpecialDescription}</td> </tr> </tbody> </table> ))} </div> ) } export default FullPageWeeklySpecials;
0.976563
high
frontend/portals/CartItemSubscriptionInfo/components/Label/styles.js
shopgate-professional-services/ext-recharge
0
6598
<reponame>shopgate-professional-services/ext-recharge import { css } from 'glamor'; const label = css({ fontSize: '12px', justifyContent: 'space-between', }).toString(); export default { label };
0.90625
high
rollup.config.js
exuanbo/module-from-string
14
6599
import esbuild from 'rollup-plugin-esbuild-transform' import dts from 'rollup-plugin-dts' import pkg from './package.json' export default [ { external: ['module', 'path', 'url', 'vm', ...Object.keys(pkg.dependencies), 'nanoid/async'], input: 'src/index.ts', output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ], plugins: [ esbuild([ { loader: 'ts' }, { output: true, target: 'node12.20.0' } ]), { name: 'dynamic-import', renderDynamicImport() { return { left: 'import(', right: ')' } } } ] }, { input: '.cache/index.d.ts', output: { file: pkg.types, format: 'es' }, plugins: [dts()] } ]
0.992188
high
api_demo/components/types/list.js
Dorajs/samples
69
6600
<filename>api_demo/components/types/list.js<gh_stars>10-100 const fs = require('fs') module.exports = { type: 'list', style: 'simple', actions: [ { id: 'update_menu', title: 'Update title', onClick: async function () { let newTitle = await $input.prompt({ title: 'Update title', hint: 'new title', value: this.title }) this.title = newTitle } } ], async fetch() { return [ // label { title: '样式: label', style: 'category' }, { title: 'Label 1', style: 'label' }, { title: 'Label 2', style: 'label' }, { title: 'Label 3', style: 'label' }, { title: 'Label 4', style: 'label' }, // chips { title: '样式: chips', style: 'category' }, { title: 'Chips title', style: 'chips', actions: [ { title: 'Action 1' }, { title: 'Action 2' }, { title: 'Action 3' }, { title: 'Action 4' } ] }, // simple { title: '样式:simple', style: 'category' }, { title: 'Hello World!', style: 'simple' }, { title: 'Hello World!', style: 'simple', summary: '一个简单的样式' }, { title: 'Hello World!', style: 'simple', image: $icon('face', 'black'), summary: '一个简单的样式' }, // icon { title: '样式:icon', style: 'category' }, { title: 'icon', style: 'icon', image: $icon('face', 'red') }, { title: 'icon', style: 'icon', image: $icon('code') }, { title: 'icon', style: 'icon', image: $icon('build', 'green') }, // dashboard { title: '样式:dashboard', style: 'category' }, { style: 'dashboard', image: $icon('memory'), title: '内存使用', summary: '1024 MB', color: '#8B355E', textColor: 'white' }, { style: 'dashboard', image: $icon('battery_alert'), title: '电池使用', summary: '1024MB', color: '#81AF37', textColor: 'white' }, // vod { title: '样式:vod', style: 'category' }, { title: '冰雪奇缘2', style: 'vod', thumb: 'https://p0.meituan.net/moviemachine/58ee13be6dc60bf5e636cf915bbbaaa55787785.jpg@464w_644h_1e_1c', label: '喜剧,动画,冒险', summary: '为什么艾莎(伊迪娜·门泽尔 配音)天生就拥有神奇魔法?谜题的答案一直呼唤着她,也威胁着王国的安全。她将和安娜(克里斯汀·贝尔 配音)、克斯托夫(乔纳森·格罗夫 配音)、雪宝(乔什·盖德 配音)和驯鹿斯特共同开启一场非凡的冒险旅程。艾莎曾担心世界不能接受自己的冰雪魔法,但在《冰雪奇缘2》中她却必须祈祷自己的魔法足够强大,能够拯救世界。本片由奥斯卡金牌团队打造——导演珍妮弗·李和克里斯·巴克、制作人彼得·戴尔·维克以及词曲作者克里斯汀·安德森-洛佩兹及罗伯特·洛佩兹悉数回归,原配音班底伊迪娜·门泽尔、克里斯汀·贝尔、乔纳森·格罗夫和乔什·盖德再度加盟。华特迪士尼动画工作室荣誉出品《冰雪奇缘2》将于2019年11月22日登陆北美院线。' }, { title: '复仇者联盟4:终局之战d', style: 'vod', thumb: 'https://p0.meituan.net/moviemachine/f7d2ad70eb79d6d9b8a197713db9b8c41711752.jpg@464w_644h_1e_1c', label: '动作,冒险,奇幻', summary: '一声响指,宇宙间半数生命灰飞烟灭。几近绝望的复仇者们在惊奇队长(布丽·拉尔森 饰)的帮助下找到灭霸(乔什·布洛林 饰)归隐之处,却得知六颗无限宝石均被销毁,希望彻底破灭。如是过了五年,迷失在量子领域的蚁人(保罗·路德 饰)意外回到现实世界,他的出现为幸存的复仇者们点燃了希望。与美国队长(克里斯·埃文斯 饰)冰释前嫌的托尼(小罗伯特·唐尼 饰)找到了穿越时空的方法,星散各地的超级英雄再度集结,他们分别穿越不同的时代去搜集无限宝石。而在这一过程中,平行宇宙的灭霸察觉了他们的计划。 注定要载入史册的最终决战,超级英雄们为了心中恪守的信念前仆后继……' }, // live { title: '样式:live', style: 'category' }, { title: 'Coding...', style: 'live', image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', label: '英雄联盟', viewerCount: '1.1k', author: { name: 'linroid', avatar: 'https://linroid.com/avatar.png' } }, { title: 'Coding...', style: 'live', image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', label: '英雄联盟', author: { name: 'linroid', avatar: 'https://linroid.com/avatar.png' } }, { title: 'Coding...', style: 'live', image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', spanCount: 12, label: '英雄联盟', author: { name: 'linroid', avatar: 'https://linroid.com/avatar.png' } }, // richMedia { title: '样式:richMedia', style: 'category' }, { title: 'Title goes here', style: 'richMedia', image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', rating: { score: 4.5, total: 5, text: '4.5(1000)' }, summary: 'Secondary line text Lorem ipsum dolor sit amet, nec no nominavi scaevola. Per et sint sapientem, nobis perpetua salutandi mei te.', subtitle: 'Subtitle goes here', tags: [ { title: 'Tag 1', onClick: this.simpleOnClick }, { title: 'Tag 2', onClick: this.simpleOnClick }, { title: 'Tag 3', onClick: this.simpleOnClick } ], actions: [ { title: 'Action1', onClick: this.simpleOnClick }, { title: 'Action 2', onClick: this.simpleOnClick } ] }, // category { title: '样式:gallery', style: 'category' }, { title: 'gallery', style: 'gallery', image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', author: { name: 'linroid', avatar: 'https://avatars0.githubusercontent.com/u/3192142?s=460&v=4' } }, // category { title: '样式:book', style: 'category' }, { image: 'https://img1.doubanio.com/view/subject/l/public/s2768378.jpg', title: '三体', style: 'book' }, { image: 'https://img3.doubanio.com/view/subject/l/public/s8958650.jpg', title: 'JavaScript高级程序设计', style: 'book' }, // article { title: '样式: article', style: 'category' }, { time: 'just now', title: '任天堂 Switch 国行版上市, 腾讯提供本地化网络服务', style: 'article', author: { name: 'xx媒体' }, image: 'https://weiliicimg9.pstatp.com/weili/l/778002376200945690.webp', summary: '12 月 4 日,腾讯集团和任天堂在上海举行发布会,宣布腾讯引进的任天堂新世代游戏机 Nintendo Switch 将于 12 月 10 日正式发售 ... 有「马力欧之父」称号的任天堂株式会社代表取缔役、专门领域开发主导宫本茂通过视频形式表示:任天堂长久以来,一直希望可以为中国顾客提供任天堂的游戏娱乐,现在这个梦想得以实现,真的感到十分高兴,也十分感谢 ... 腾讯游戏任天堂合作部总经理钱赓介绍,关于未来 Nintendo Switch 的网络服务方面,腾讯在国内架设了适合中国网络环境的网络系统,将通过云服务,设立了本地化的网络服务' }, // richContent { title: '样式: richContent', style: 'category' }, { title: 'README.md', style: 'richContent', content: { url: 'https://docs.dorajs.com/', markdown: this.readReadme() } }, { title: '百度一下', style: 'richContent', content: { url: 'https://baidu.com/' } } ] }, simpleOnClick(data) { $ui.toast(`onClick ${JSON.stringify(data)}`) }, readReadme() { return fs.readFileSync('./README.md', { encoding: 'utf8' }) } }
0.988281
high
src/array-source.js
emaclean03/nova-tables
5
6601
import FuzzyMatcher from './fuzzy-matcher.js'; import AbstractSource from './abstract-source.js'; class ArraySource extends AbstractSource { constructor(items, matcher) { super(); this.items = items; this.filterClosures = []; this.matcher = matcher || new FuzzyMatcher(); } addFilter(filter) { this.filterClosures.push(filter); } get() { var promise = Promise.resolve(this.items); this.filterClosures.map((filter) => { promise = promise.then(filter); }); return promise .then((items) => { return items.filter((item) => { if (this.search) { // find out if any fields match return _.find(this.search_fields, (field) => { return this.matcher.matches(this.search, item[field]); }); } return true; }); }) .then((items) => { var sort_field = this.sort_field; return items.sort((a, b) => { if (a[sort_field] < b[sort_field]) { return this.sort_direction === 'A' ? -1 : 1; } else if (a[sort_field] > b[sort_field]) { return this.sort_direction === 'A' ? 1 : -1; } return 0; }); }) .then((items) => { var page_length = this.page_length || items.length; if (!this.page) { this.page = 1; } var pageCount = page_length ? Math.ceil(items.length / page_length) : 1; if (this.page > pageCount) { this.page = pageCount; } var totalCount = items.length; items = items.slice((this.page - 1) * page_length, this.page * page_length); return { items: items, pageCount: pageCount, page: this.page, totalCount: totalCount, }; }); } } export default ArraySource;
0.996094
high
src/middleware/service/member/createList.js
ufwd-dev/system
1
6602
'use strict'; const { throwError} = require('error-standardize'); const Sequelize = require('sequelize'); module.exports = function* createMemberList(req, res, next) { const {accountId} = req.params; const {groupPool} = req.body; const Member = res.sequelize.model('ufwdMember'); const UfwdAccount = res.sequelize.model('ufwdAccount'); const Group = res.sequelize.model('ufwdGroup'); const ufwdAccount = yield UfwdAccount.findOne({ where: { accountId } }); if (!ufwdAccount) { throwError('The account is not exist.', 403); } const groupList = yield Group.findAll({ where: { id: { [Sequelize.Op.in]: groupPool } } }); const group = groupList.map(group => group.id); const accountMemberList = yield Member.findAll({ where: { accountId, groupId: { [Sequelize.Op.in]: groupPool } } }); const member = accountMemberList.map(member => member.groupId); const list = group.filter(item => { if (member.indexOf(item) === -1) { return true; } }).map(item => { return { accountId, groupId: item }; }); const memberList = yield Member.bulkCreate(list); res.data(memberList); next(); };
0.984375
high
ssc/export-annotated-parts.js
jb892/sstk
0
6603
#!/usr/bin/env node var fs = require('fs'); var async = require('async'); var shell = require('shelljs'); var STK = require('./stk-ssc'); var cmd = require('commander'); cmd .version('0.0.1') .description('Export part annotations') .option('--id <id>', 'Model id [default: 101]', STK.util.cmd.parseList, ['101']) .option('--source <source>', 'Model source [default: p5d]', 'p5d') // .option('--ann_type <type>', 'Annotation type', /^(raw|clean|aggr)$/) .option('-n, --ann_limit <num>', 'Limit on number of annotations to export', STK.util.cmd.parseInt, 1) .option('--output_dir <dir>', 'Base directory for output files', '.') .option('--include_annId [flag]', 'Whether to include ann id in output filename', STK.util.cmd.parseBoolean, false) .option('--skip_existing [flag]', 'Whether to skip output of existing files', STK.util.cmd.parseBoolean, false) .parse(process.argv); var argv = cmd; // Parse arguments and initialize globals var skip_existing = argv.skip_existing; var assetManager = new STK.assets.AssetManager({ autoAlignModels: false, autoScaleModels: false }); var ids = argv.id; var assets = require('./data/assets.json'); var assetsMap = _.keyBy(assets, 'name'); STK.assets.registerCustomAssetGroupsSync(assetsMap, [argv.source]); var assetGroup = STK.assets.AssetGroups.getAssetGroup(argv.source); var assetsDb = assetGroup? assetGroup.assetDb : null; if (!assetsDb) { console.log('Unrecognized asset source ' + argv.source); return; } if (ids.indexOf('all') >= 0) { ids = assetsDb.getAssetIds().map(function (x) { return x.split('.', 2)[1]; }); } else if (ids.indexOf('annotated') >= 0) { var annotationsUrl = STK.Constants.baseUrl + '/part-annotations/list?format=json&$columns=itemId'; var data = STK.util.readSync(annotationsUrl); var itemIds = _.uniq(JSON.parse(data).map(function(x) { return x.itemId; })).filter(function(x) { return x; }); ids = itemIds.map(function (x) { return x.split('.', 2)[1]; }); } else { if (ids.length === 1 && ids[0].endsWith('.txt')) { // Read files form input file var data = STK.util.readSync(ids[0]); ids = data.split('\n').map(function(x) { return STK.util.trim(x); }).filter(function(x) { return x.length > 0; }); } } var source = argv.source; var segmentsType = 'part-annotations'; // if (argv.ann_type === 'raw') { // segmentsType = 'segment-annotations-raw'; // } else if (argv.ann_type === 'clean') { // segmentsType = 'segment-annotations-clean'; // } var annNum = argv.ann_limit; console.log('segmentsType is ' + segmentsType); var segments = new STK.geo.Segments({ showNodeCallback: function (segmentedObject3D) { } }, segmentsType); function exportAnnotation(loadInfo, outdir, callback) { shell.mkdir('-p', outdir); assetManager.getModelInstanceFromLoadModelInfo(loadInfo, function (mInst) { segments.init(mInst); mInst.model.info.annId = loadInfo.annId; segments.loadSegments(function (err, res) { if (!err) { var id = loadInfo.id; var annId = loadInfo.annId; var annIndex = loadInfo.annIndex; var basename = id; if (argv.include_annId) { basename = (annId != undefined)? id + '_' + annIndex : id; } else { basename = (annIndex != undefined) ? id + '_' + annIndex : id; } basename = outdir + '/' + basename; segments.indexedSegmentation.annId = loadInfo.annId; fs.writeFileSync(basename + '.json', JSON.stringify(segments.indexedSegmentation)); callback(err, res); } else { console.error(err, res); callback(err, res); } }); }); } function processIds(ids, outdir, doneCallback) { async.forEachSeries(ids, function (id, callback) { var mInfo = assetsDb.getAssetInfo(argv.source + '.' + id); var loadInfo = assetManager.getLoadModelInfo(argv.source, id, mInfo); var segmentsInfo = loadInfo[segmentsType]; STK.util.clearCache(); var basename = outdir + '/' + id; console.log('skip_existing is ' + skip_existing); if (skip_existing && shell.test('-d', basename)) { console.warn('Skipping existing output at: ' + basename); setTimeout(function () { callback(); }, 0); } else if (segmentsInfo) { if (segmentsInfo.files && segmentsInfo.files.annIds) { console.log('fetching from ' + segmentsInfo.files.annIds); STK.util.getJSON(segmentsInfo.files.annIds) .done(function (data) { shell.mkdir('-p', basename); data.forEach(function(x) { if (typeof x.data === 'string') { x.data = JSON.parse(x.data); } }); fs.writeFileSync(basename + '/' + id + '.anns.json', JSON.stringify(data)); var annIds = data.map(function (rec) { return rec.id; }); if (annNum > 0) { annIds = _.sortBy(annIds, function(id) { return -id; }); annIds = _.take(annIds, annNum); } async.forEachOfSeries(annIds, function (annId, index, cb) { var loadInfoCopy = _.clone(loadInfo); loadInfoCopy.annId = annId; loadInfoCopy.annIndex = (annNum !== 1)? index : undefined; exportAnnotation(loadInfoCopy, basename, cb); }, function (err, results) { callback(err, results); }); }) .fail(function (err) { callback(err, null); }) } else { exportAnnotation(loadInfo, basename, callback); } } else { setTimeout(function () { callback('No annotations for ' + id + ', segmentsType ' + segmentsType, null); }, 0); } }, function (err, results) { if (doneCallback) { doneCallback(err, results); } else { console.log('DONE'); } }); } processIds(ids, argv.output_dir);
0.957031
high
src/Components/PlayPause/stories.js
booyaa/breathe
1
6604
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import PlayPause from '.'; export const mode = { isPlaying: true } export const actions = { onPressed: action('onPressed') } storiesOf('PlayPause', module) .add('default', () => <PlayPause mode={mode} {...actions}/>) .add('paused', () => <PlayPause mode={{...mode, isPlaying: false}} {...actions} />) ;
0.804688
medium
intervalMessages/rule.js
TelevisionNinja/Row-Bot
0
6605
<reponame>TelevisionNinja/Row-Bot<filename>intervalMessages/rule.js import { getImageRule0 } from '../commands/rule.js'; import { default as config } from '../config.json'; import DailyInterval from 'daily-intervals'; import { getChannel, sendImg } from '../lib/msgUtils.js'; import { tagArrToParsedTagArr } from '../lib/stringUtils.js'; import { randomMath } from '../lib/randomFunctions.js'; import { cutOff } from '../lib/stringUtils.js'; const ruleConfig = config.rule, noResultsMsg = config.noResultsMsg; const filter = ruleConfig.filterTags.map(t => `-${t}`); // posts a daily rule image export async function execute(client) { const recipient = await getChannel(client, ruleConfig.intervalChannelID); const interval = new DailyInterval( async () => { const randIndex = randomMath(ruleConfig.intervalTags.length); const selection = ruleConfig.intervalTags[randIndex]; let tagArr = [selection, ...filter]; tagArr = tagArrToParsedTagArr(tagArr, ruleConfig.sites[0].whitespace); const img = await getImageRule0(tagArr); if (img.results) { sendImg(recipient, img, false); } else { recipient.send(cutOff(`${noResultsMsg}\nTags:\n\`${tagArr}\``, 2000)); } }, '0:0', ruleConfig.intervalWait, 5000 // 5 second offset ); interval.start(); }
0.953125
high
Fundamentals Project HOOKS,ROUTES,API/15.course-goals/src/Components/CourseGoals/CourseGoalList/CourseGoalList.js
georgiangelov2000/React-Js-Development
0
6606
import React from "react"; import styled from "styled-components"; import CourseGoalItem from "../CourseGoalItem/CourseGoalItem"; const GoalList = styled.ul` list-style: none; margin: 0; padding: 0; `; const CourseGoalList = (props) => { return ( <GoalList> {props.items.map((goal) => ( <CourseGoalItem key={goal.id} id={goal.id} onDelete={props.onDeleteItem} > {goal.text} </CourseGoalItem> ))} </GoalList> ); }; export default CourseGoalList;
0.734375
medium
CUDA/matrix_mult/node_modules/mathjs/lib/function/statistics/min.js
leiverandres/HPC_assignments
8
6607
'use strict'; var deepForEach = require('../../utils/collection/deepForEach'); var reduce = require('../../utils/collection/reduce'); var containsCollections = require('../../utils/collection/containsCollections'); function factory (type, config, load, typed) { var smaller = load(require('../relational/smaller')); /** * Compute the maximum value of a matrix or a list of values. * In case of a multi dimensional array, the maximum of the flattened array * will be calculated. When `dim` is provided, the maximum over the selected * dimension will be calculated. Parameter `dim` is zero-based. * * Syntax: * * math.min(a, b, c, ...) * math.min(A) * math.min(A, dim) * * Examples: * * math.min(2, 1, 4, 3); // returns 1 * math.min([2, 1, 4, 3]); // returns 1 * * // maximum over a specified dimension (zero-based) * math.min([[2, 5], [4, 3], [1, 7]], 0); // returns [1, 3] * math.min([[2, 5], [4, 3], [1, 7]], 1); // returns [2, 3, 1] * * math.max(2.7, 7.1, -4.5, 2.0, 4.1); // returns 7.1 * math.min(2.7, 7.1, -4.5, 2.0, 4.1); // returns -4.5 * * See also: * * mean, median, max, prod, std, sum, var * * @param {... *} args A single matrix or or multiple scalar values * @return {*} The minimum value */ var min = typed('min', { // min([a, b, c, d, ...]) 'Array | Matrix': _min, // min([a, b, c, d, ...], dim) 'Array | Matrix, number | BigNumber': function (array, dim) { return reduce(array, dim.valueOf(), _smallest); }, // min(a, b, c, d, ...) '...': function (args) { if (containsCollections(args)) { throw new TypeError('Scalar values expected in function min'); } return _min(args); } }); min.toTex = '\\min\\left(${args}\\right)'; return min; /** * Return the smallest of two values * @param {*} x * @param {*} y * @returns {*} Returns x when x is smallest, or y when y is smallest * @private */ function _smallest(x, y) { return smaller(x, y) ? x : y; } /** * Recursively calculate the minimum value in an n-dimensional array * @param {Array} array * @return {number} min * @private */ function _min(array) { var min = undefined; deepForEach(array, function (value) { if (min === undefined || smaller(value, min)) { min = value; } }); if (min === undefined) { throw new Error('Cannot calculate min of an empty array'); } return min; } } exports.name = 'min'; exports.factory = factory;
0.996094
high
resources/js/AxiosRepository.js
julfiker/laravel-mail
0
6608
<filename>resources/js/AxiosRepository.js import axios from "axios"; export default { GET_COMMAND: 'GET', POST_COMMAND: 'POST', PUT_COMMAND: 'PUT', PATCH_COMMAND: 'PATCH', DELETE_COMMAND: 'DELETE', apiBasePath: 'http://127.0.0.1:8000/v1', callApi: async function(requestType='GET', url, params={}, headers={}) { url = this.apiBasePath + url; const methodName = requestType.toUpperCase(); if (methodName === 'GET') { return await axios.get(url, params, headers) .then(response => { return response; }) .catch(error => { return error; }); } else if (methodName === 'POST') { return await axios.post(url, params, headers) .then(response => { return response; }) .catch(error => { return error; }); } else if ((methodName === 'PUT') || (methodName === 'PATCH')) { return await axios.put(url, params, headers) .then(response => { return response; }); } else if (methodName === 'DELETE') { return await axios.delete(url, params, headers) .then(response => { return response; }); } else { return false; } } }
0.96875
high
src/screens/Platform/index.js
ElrondNetwork/ledger-live-mobile
1
6609
// @flow import React, { useMemo, useCallback, useState } from "react"; import { StyleSheet, ScrollView, View, Linking } from "react-native"; import { Trans } from "react-i18next"; import { useNavigation, useTheme } from "@react-navigation/native"; import { usePlatformApp } from "@ledgerhq/live-common/lib/platform/PlatformAppProvider"; import { filterPlatformApps } from "@ledgerhq/live-common/lib/platform/PlatformAppProvider/helpers"; import type { AccountLike, Account } from "@ledgerhq/live-common/lib/types"; import type { AppManifest } from "@ledgerhq/live-common/lib/platform/types"; import { useBanner } from "../../components/banners/hooks"; import TrackScreen from "../../analytics/TrackScreen"; import { urls } from "../../config/urls"; import { ScreenName } from "../../const"; import IconCode from "../../icons/Code"; import CatalogTwitterBanner from "./CatalogTwitterBanner"; import DAppDisclaimer from "./DAppDisclaimer"; import type { Props as DisclaimerProps } from "./DAppDisclaimer"; import CatalogBanner from "./CatalogBanner"; import CatalogCTA from "./CatalogCTA"; import AppCard from "./AppCard"; import AnimatedHeaderView from "../../components/AnimatedHeader"; type RouteParams = { defaultAccount: ?AccountLike, defaultParentAccount: ?Account, }; type DisclaimerOpts = $Diff<DisclaimerProps, { isOpened: boolean }> | null; const DAPP_DISCLAIMER_ID = "PlatformAppDisclaimer"; const PlatformCatalog = ({ route }: { route: { params: RouteParams } }) => { const { params: routeParams } = route; const { colors } = useTheme(); const navigation = useNavigation(); const { manifests } = usePlatformApp(); const filteredManifests = useMemo(() => { const branches = ["stable", "soon"]; return filterPlatformApps(Array.from(manifests.values()), { version: "0.0.1", platform: "mobile", branches, }); }, []); // Disclaimer State const [disclaimerOpts, setDisclaimerOpts] = useState<DisclaimerOpts>(null); const [disclaimerOpened, setDisclaimerOpened] = useState<boolean>(false); const [disclaimerDisabled, setDisclaimerDisabled] = useBanner( DAPP_DISCLAIMER_ID, ); const handlePressCard = useCallback( (manifest: AppManifest) => { const openDApp = () => navigation.navigate(ScreenName.PlatformApp, { ...routeParams, platform: manifest.id, name: manifest.name, }); if (!disclaimerDisabled) { setDisclaimerOpts({ disableDisclaimer: () => setDisclaimerDisabled(), closeDisclaimer: () => setDisclaimerOpened(false), icon: manifest.icon, onContinue: openDApp, }); setDisclaimerOpened(true); } else { openDApp(); } }, [navigation, routeParams, setDisclaimerDisabled, disclaimerDisabled], ); const handleDeveloperCTAPress = useCallback(() => { Linking.openURL(urls.platform.developerPage); }, []); return ( <AnimatedHeaderView titleStyle={styles.title} title={<Trans i18nKey={"platform.catalog.title"} />} > <TrackScreen category="Platform" name="Catalog" /> {disclaimerOpts && ( <DAppDisclaimer disableDisclaimer={disclaimerOpts.disableDisclaimer} closeDisclaimer={disclaimerOpts.closeDisclaimer} onContinue={disclaimerOpts.onContinue} isOpened={disclaimerOpened} icon={disclaimerOpts.icon} /> )} <ScrollView style={styles.wrapper}> <CatalogBanner /> <CatalogTwitterBanner /> {filteredManifests.map(manifest => ( <AppCard key={manifest.id} manifest={manifest} onPress={handlePressCard} /> ))} <View style={[styles.separator, { backgroundColor: colors.fog }]} /> <CatalogCTA Icon={IconCode} title={<Trans i18nKey={"platform.catalog.developerCTA.title"} />} onPress={handleDeveloperCTAPress} > <Trans i18nKey={"platform.catalog.developerCTA.description"} /> </CatalogCTA> </ScrollView> </AnimatedHeaderView> ); }; const styles = StyleSheet.create({ root: { flex: 1, }, wrapper: { flex: 1, }, title: { fontSize: 34, lineHeight: 40, textAlign: "left", }, separator: { width: "100%", height: 1, marginBottom: 24, }, }); export default PlatformCatalog;
0.976563
high
packages/i18n/I18nDecorator/I18nDecorator.js
jeonghee27/enact
0
6610
/** * Adds Internationalization (I18N) support to an application using ilib. * * @module i18n/I18nDecorator * @exports I18nDecorator * @exports I18nContextDecorator * @exports I18nContext */ import {on, off} from '@enact/core/dispatcher'; import hoc from '@enact/core/hoc'; import {Publisher, contextTypes as stateContextTypes} from '@enact/core/internal/PubSub'; import PropTypes from 'prop-types'; import React from 'react'; import ilib from '../src/index.js'; import {isRtlLocale, updateLocale} from '../locale'; import getI18nClasses from './getI18nClasses'; const contextTypes = { rtl: PropTypes.bool, updateLocale: PropTypes.func }; const I18nContext = React.createContext(null); /** * A higher-order component that is used to wrap the root element in an app. It provides an `rtl` member on the * context of the wrapped component, allowing the children to check the current text directionality as well as * an `updateLocale` method that can be used to update the current locale. * * There are no configurable options on this HOC. * * @class I18nDecorator * @memberof i18n/I18nDecorator * @hoc * @public */ const I18nDecorator = hoc((config, Wrapped) => { return class extends React.Component { static displayName = 'I18nDecorator' static propTypes = /** @lends i18n/I18nDecorator.I18nDecorator.prototype */ { /** * Classname for a root app element. * * @type {String} * @public */ className: PropTypes.string, /** * A string with a {@link https://tools.ietf.org/html/rfc5646|BCP 47 language tag}. * * The system locale will be used by default. * * @type {String} * @public */ locale: PropTypes.string } static contextTypes = stateContextTypes static childContextTypes = {...contextTypes, ...stateContextTypes} constructor (props) { super(props); const ilibLocale = ilib.getLocale(); const locale = props.locale && props.locale !== ilibLocale ? updateLocale(props.locale) : ilibLocale; this.state = { locale: locale, rtl: isRtlLocale(), updateLocale: this.updateLocale }; } getChildContext () { return { Subscriber: this.publisher.getSubscriber(), rtl: isRtlLocale(), updateLocale: this.updateLocale }; } componentWillMount () { this.publisher = Publisher.create('i18n', this.context.Subscriber); this.publisher.publish({ locale: this.state.locale, rtl: isRtlLocale() }); } componentDidMount () { if (typeof window === 'object') { on('languagechange', this.handleLocaleChange, window); } } componentWillReceiveProps (newProps) { if (newProps.locale) { this.updateLocale(newProps.locale); } } componentWillUnmount () { if (typeof window === 'object') { off('languagechange', this.handleLocaleChange, window); } } handleLocaleChange = () => { this.updateLocale(); } /** * Updates the locale for the application. If `newLocale` is omitted, the locale will be * reset to the device's default locale. * * @param {String} newLocale Locale identifier string * * @returns {undefined} * @public */ updateLocale = (newLocale) => { const locale = updateLocale(newLocale); const updated = { locale, rtl: isRtlLocale() }; this.setState(updated); this.publisher.publish(updated); } render () { const props = Object.assign({}, this.props); let classes = getI18nClasses(); if (this.props.className) { classes = this.props.className + ' ' + classes; } delete props.locale; return ( <I18nContext.Provider value={this.state}> <Wrapped {...props} className={classes} /> </I18nContext.Provider> ); } }; }); const defaultConfig = { localeProp: null, rtlProp: null, updateLocaleProp: null }; const I18nContextDecorator = hoc(defaultConfig, (config, Wrapped) => { const {localeProp, rtlProp, updateLocaleProp} = config; // eslint-disable-next-line no-shadow return function I18nContextDecorator (props) { return ( <I18nContext.Consumer> {(i18nContext) => { if (i18nContext) { const {locale, rtl, updateLocale: update} = i18nContext; props = Object.assign({}, props); if (localeProp) { props[localeProp] = locale; } if (rtlProp) { props[rtlProp] = rtl; } if (updateLocaleProp) { props[updateLocaleProp] = update; } } return ( <Wrapped {...props} /> ); }} </I18nContext.Consumer> ); }; }); export default I18nDecorator; export { contextTypes, I18nContext, I18nContextDecorator, I18nDecorator };
0.996094
high
functions/files/music/handlePlaylist.js
loughreykian/Aurora
3
6611
<filename>functions/files/music/handlePlaylist.js<gh_stars>1-10 module.exports = async function(message, playlist, options) { try { if(message.author.id == message.client.config.ownerID) options.override = true if (!message.member.voiceChannel) return message.send(`${message.emote('error')} Get in a voice channel`); const serverQueue = message.client.queue[message.guild.id]; const voiceChannel = message.member.voiceChannel; let msg = await message.send(`${message.emote('mag')} Fetching playlist...`); const pl = await message.client.functions['getPlaylist'](message.client, playlist); //if(!options.override && serverQueue ? (serverQueue.tracks.length + pl.length) > 75 : pl.length > 75) { pl.splice(76, pl.length.toFixed(2)), message.send(`${message.emote('list')} Shortened queue to \`${pl.length}\` songs.`) }; msg.edit(`${message.emote('add')} Enqueued \`${pl.length}\` songs.`); pl.forEach(async list => { await message.client.functions['handleTrack'](message, list, voiceChannel, { playlist: true, override: options.override, link: false }); }); } catch (err) { return message.send(`${message.emote('error')} Error getting playlist: ${e}`); }; };
0.609375
high
src/containers/dashboard/sortableTable.js
vlganev/react-admin-panel
4
6612
<reponame>vlganev/react-admin-panel import * as React from "react"; import { Menu, MenuItem } from "@blueprintjs/core"; import { Cell, Column, ColumnHeaderCell, CopyCellsMenuItem, SelectionModes, Table, Utils, } from "@blueprintjs/table"; // tslint:disable-next-line:no-var-requires // const sumo = [ // ["A", "Apple", "Ape", "Albania", "Anchorage"], // ["B", "Banana", "Boa", "Brazil", "Boston"], // ["C", "Cranberry", "Cougar", "Croatia", "Chicago"], // ["D", "Dragonfruit", "Deer", "Denmark", "Denver"], // ["E", "Eggplant", "Elk", "Eritrea", "El Paso"], // ]; // export type ICellLookup = (rowIndex: number, columnIndex: number) => any; // export type ISortCallback = (columnIndex: number, comparator: (a: any, b: any) => number) => void; // export interface ISortableColumn { // getColumn(getCellData: ICellLookup, sortColumn: ISortCallback): JSX.Element; // } class TextSortableColumn { constructor(name, index) { this.name = name, this.index = index } getColumn(getCellData, sortColumn) { const cellRenderer = (rowIndex, columnIndex) => ( <Cell>{getCellData(rowIndex, columnIndex)}</Cell> ); const menuRenderer = this.renderMenu.bind(this, sortColumn); const columnHeaderCellRenderer = () => <ColumnHeaderCell name={this.name} menuRenderer={menuRenderer} />; return ( <Column cellRenderer={cellRenderer} columnHeaderCellRenderer={columnHeaderCellRenderer} key={this.index} name={this.name} /> ); } renderMenu(sortColumn) { const sortAsc = () => sortColumn(this.index, (a, b) => this.compare(a, b)); const sortDesc = () => sortColumn(this.index, (a, b) => this.compare(b, a)); return ( <Menu> <MenuItem icon="sort-asc" onClick={sortAsc} text="Sort Asc" /> <MenuItem icon="sort-desc" onClick={sortDesc} text="Sort Desc" /> </Menu> ); } compare(a, b) { return a.toString().localeCompare(b); } } export class SortableTable extends React.PureComponent { constructor(props) { super(props); this.state = { columns: [ new TextSortableColumn("К 1", 0), new TextSortableColumn("Колона 2", 1), new TextSortableColumn("Колона 3", 2), new TextSortableColumn("Колона 4", 3), new TextSortableColumn("Колона 5", 4), new TextSortableColumn("Колона 6", 5), new TextSortableColumn("Колона 7", 6), new TextSortableColumn("Колона 8", 7), new TextSortableColumn("Колона 9", 8), new TextSortableColumn("Колона 10", 9), new TextSortableColumn("Колона 11", 10), new TextSortableColumn("Колона 12", 11), new TextSortableColumn("Колона 13", 12), ], data: props.data, sortedIndexMap: [], columnWidths: [30, 140, 250, 100, 200, 100, 100, 100, 100, 100, 100, 100, 100], }; } render() { const numRows = this.state.data.length; const columns = this.state.columns.map(col => col.getColumn(this.getCellData, this.sortColumn)); return ( <Table bodyContextMenuRenderer={this.renderBodyContextMenu} numRows={numRows} selectionModes={SelectionModes.COLUMNS_AND_CELLS} columnWidths={this.state.columnWidths} > {columns} </Table> ); } componentWillReceiveProps(props) { if (props.data != undefined) { this.setState({ data: props.data }) } else { this.setState({ data: [] }); } } getCellData = (rowIndex, columnIndex) => { const sortedRowIndex = this.state.sortedIndexMap[rowIndex]; if (sortedRowIndex != null) { rowIndex = sortedRowIndex; } return this.state.data[rowIndex][columnIndex]; }; renderBodyContextMenu = (context) => { return ( <Menu> <CopyCellsMenuItem context={context} getCellData={this.getCellData} text="Copy" /> </Menu> ); }; sortColumn = (columnIndex, comparator) => { const { data } = this.state; const sortedIndexMap = Utils.times(data.length, (i) => i); sortedIndexMap.sort((a, b) => { return comparator(data[a][columnIndex], data[b][columnIndex]); }); this.setState({ sortedIndexMap }); }; }
0.988281
high
modules/weblounge-ui/src/main/resources/editor/scripts/docs.js
digitalcafe/weblounge
2
6613
<reponame>digitalcafe/weblounge<filename>modules/weblounge-ui/src/main/resources/editor/scripts/docs.js //js editor/scripts/doc.js load('steal/rhino/steal.js'); steal.plugins("documentjs").then(function(){ DocumentJS('editor/editor.html'); });
0.679688
low
src/angular_demo_addin/js/mainController.js
InteractiveIntelligence/ConnectAddinDevEnvironment
1
6614
clientaddin.controller('MainController', function($scope, $rootScope, QueueService){ $scope.$watch(function () { return QueueService.getInteractions(); }, function (data) { $scope.interactions = data; }, true); });
0.601563
high
applications/luci-app-vnstat2/htdocs/luci-static/resources/view/vnstat2/config.js
fanck0605/luci-1
4
6615
// This is free software, licensed under the Apache License, Version 2.0 'use strict'; 'require view'; 'require fs'; 'require ui'; 'require uci'; 'require form'; 'require tools.widgets as widgets'; var isReadonlyView = !L.hasViewPermission() || null; return view.extend({ handleDeleteModal: function(m, iface, ev) { L.showModal(_('Delete interface <em>%h</em>').format(iface), [ E('p', _('The interface will be removed from the database permanently. This cannot be undone.')), E('div', { 'class': 'right' }, [ E('div', { 'class': 'btn', 'click': L.hideModal }, _('Cancel')), ' ', E('div', { 'class': 'btn cbi-button-negative', 'click': ui.createHandlerFn(this, 'handleDelete', m, iface) }, _('Delete')) ]) ]); }, handleDelete: function(m, iface, ev) { return fs.exec('/usr/bin/vnstat', ['--remove', '-i', iface, '--force']) .then(L.bind(m.render, m)) .catch(function(e) { ui.addNotification(null, E('p', e.message)); }) .finally(L.hideModal); }, render: function() { var m, s, o; m = new form.Map('vnstat', _('vnStat'), _('vnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).')); s = m.section(form.TypedSection, 'vnstat', _('Interfaces')); s.anonymous = true; s.addremove = false; o = s.option(widgets.DeviceSelect, 'interface', _('Monitor interfaces'), _('The selected interfaces are automatically added to the vnStat database upon startup.')); o.rmempty = true; o.multiple = true; o.noaliases = true; o.nobridges = false; o.noinactive = false; o.nocreate = false; o = s.option(form.DummyValue, '_database'); o.load = function(section_id) { return fs.exec('/usr/bin/vnstat', ['--json', 'f', '1']).then(L.bind(function(result) { var databaseInterfaces = []; if (result.code == 0) { var vnstatData = JSON.parse(result.stdout); for (var i = 0; i < vnstatData.interfaces.length; i++) { databaseInterfaces.push(vnstatData.interfaces[i].name); } } var configInterfaces = uci.get_first('vnstat', 'vnstat', 'interface') || []; this.interfaces = databaseInterfaces.filter(function(iface) { return configInterfaces.indexOf(iface) == -1; }); }, this)); }; o.render = L.bind(function(view, section_id) { var table = E('div', { 'class': 'table' }, [ E('div', { 'class': 'tr table-titles' }, [ E('div', { 'class': 'th' }, _('Interface')), E('div', { 'class': 'th right' }, _('Delete')) ]) ]); var rows = []; for (var i = 0; i < this.interfaces.length; i++) { rows.push([ this.interfaces[i], E('button', { 'class': 'btn cbi-button-remove', 'click': ui.createHandlerFn(view, 'handleDeleteModal', m, this.interfaces[i]), 'disabled': isReadonlyView }, [ _('Delete…') ]) ]); } cbi_update_table(table, rows, E('em', _('No unconfigured interfaces found in database.'))); return E([], [ E('h3', _('Unconfigured interfaces')), E('div', { 'class': 'cbi-section-descr' }, _('These interfaces are present in the vnStat database, but are not configured above.')), table ]); }, o, this); return m.render(); } });
0.972656
high
chrome/test/data/extensions/api_test/tabs/connect/test.js
zealoussnow/chromium
14,668
6616
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // browser_tests --gtest_filter=ExtensionApiTest.TabConnect // The test tab used for all tests. var testTab = null; // Path to the empty HTML document, fetched from the test configuration. var emptyDocumentURL = null; // The could-not-establish-connection error message. Used in a number of tests. var couldNotEstablishError = 'Could not establish connection. Receiving end does not exist.'; var assertEq = chrome.test.assertEq; var assertFalse = chrome.test.assertFalse; var assertTrue = chrome.test.assertTrue; var callbackFail = chrome.test.callbackFail; var fail = chrome.test.fail; var listenForever = chrome.test.listenForever; var listenOnce = chrome.test.listenOnce; var pass = chrome.test.callbackPass; function waitForReady(ready) { chrome.test.listenOnce(chrome.runtime.onMessage, function(msg, sender) { assertEq('ready', msg); ready(sender.tab); }); } chrome.test.runTests([ function setup() { chrome.test.getConfig(pass(function(config) { emptyDocumentURL = 'http://localhost:' + config.testServer.port + '/extensions/api_test/tabs/connect/empty.html'; setupWindow([emptyDocumentURL], pass()); waitForReady(pass(function(tab) { testTab = tab; })); })); }, function connectMultipleConnects() { var connectCount = 0; function connect10() { var port = chrome.tabs.connect(testTab.id); listenOnce(port.onMessage, function(msg) { assertEq(++connectCount, msg.connections); if (connectCount < 10) connect10(); }); port.postMessage('GET'); } connect10(); }, function connectName() { var name = 'akln3901n12la'; var port = chrome.tabs.connect(testTab.id, {'name': name}); listenOnce(port.onMessage, function(msg) { assertEq(name, msg.name); var port = chrome.tabs.connect(testTab.id); listenOnce(port.onMessage, function(msg) { assertEq('', msg.name); }); port.postMessage('GET'); }); port.postMessage('GET'); }, function connectPostMessageTypes() { var port = chrome.tabs.connect(testTab.id); // Test the content script echoes the message back. var echoMsg = {'num': 10, 'string': 'hi', 'array': [1,2,3,4,5], 'obj':{'dec': 1.0}}; listenOnce(port.onMessage, function(msg) { assertEq(echoMsg.num, msg.num); assertEq(echoMsg.string, msg.string); assertEq(echoMsg.array[4], msg.array[4]); assertEq(echoMsg.obj.dec, msg.obj.dec); }); port.postMessage(echoMsg); }, function connectPostManyMessages() { var port = chrome.tabs.connect(testTab.id); var count = 0; var done = listenForever(port.onMessage, function(msg) { assertEq(count++, msg); if (count == 100) { done(); } }); for (var i = 0; i < 100; i++) { port.postMessage(i); } }, function connectToRemovedTab() { // Expect a disconnect event when you connect to a non-existent tab, and // once disconnected, expect an error while trying to post messages. chrome.tabs.create({}, pass(function(tab) { chrome.tabs.remove(tab.id, pass(function() { var p = chrome.tabs.connect(tab.id); p.onDisconnect.addListener(callbackFail(couldNotEstablishError, function() { try { p.postMessage(); fail('Error should have been thrown.'); } catch (e) { // Do nothing- an exception should be thrown. } })); })); })); }, function sendRequest() { var request = 'test'; chrome.tabs.sendRequest(testTab.id, request, pass(function(response) { assertEq(request, response); })); }, function sendRequestToImpossibleTab() { chrome.tabs.sendRequest(9999, 'test', callbackFail(couldNotEstablishError)); }, function sendRequestToRemovedTab() { chrome.tabs.create({}, pass(function(tab) { chrome.tabs.remove(tab.id, pass(function() { chrome.tabs.sendRequest(tab.id, 'test', callbackFail(couldNotEstablishError)); })); })); }, function sendRequestMultipleTabs() { // Regression test for crbug.com/520303. Instruct the test tab to create // another tab, then send a message to each. The bug was that the message // is sent to both, if they're in the same process. // // The tab itself must do the open so that they share a process, // chrome.tabs.create doesn't guarantee that. chrome.tabs.sendMessage(testTab.id, {open: emptyDocumentURL}); waitForReady(pass(function(secondTab) { var gotDuplicates = false; var messages = new Set(); var done = listenForever(chrome.runtime.onMessage, function(msg) { if (messages.has(msg)) gotDuplicates = true; else messages.add(msg); }); chrome.tabs.sendMessage(testTab.id, {send: 'msg1'}, function() { chrome.tabs.sendMessage(secondTab.id, {send: 'msg2'}, function() { // Send an empty final message to hopefully ensure that the events // for msg1 and msg2 have been fired. chrome.tabs.sendMessage(testTab.id, {}, function() { assertEq(2, messages.size); assertTrue(messages.has('msg1')); assertTrue(messages.has('msg2')); assertFalse(gotDuplicates); done(); }); }); }); })); }, ]);
0.996094
high
widgets/foursquare/foursquare.js
FlyNYCMeter/sonia
5
6617
var Foursquare = Class.create(Widget, { initialize: function($super, widget_id, config) { this.checkins = []; return($super(widget_id, config)); }, handlePayload: function(payload) { this.checkins = []; payload.each(function(checkin) { this.checkins.push(checkin); }.bind(this)); this.update(); }, build: function() { this.checkinsContainer = this.buildCheckins(); this.headerContainer = this.buildHeader(); this.container.insert(this.headerContainer); this.container.insert(this.buildWidgetIcon()); this.container.insert(this.checkinsContainer); this.makeDraggable(); }, update: function() { this.checkinsContainer.childElements().invoke('remove'); this.checkins.each(function(checkin) { var cont = new Element('p', { id: checkin.id}); cont.appendChild(new Element('img', { src: checkin.avatar_url, height:48, width:48})); cont.appendChild(new Element('div', {'class':'author'}).update(checkin.name)); cont.appendChild(new Element('div').update(checkin.venue + " " + checkin.when + " ago")); cont.insert(new Element('hr' )); this.checkinsContainer.insert(cont); // new Effect.Pulsate(this.container, { pulses: 2, duration: 1 }); }.bind(this)); }, buildWidgetIcon: function() { return(new Element("img", {src: "images/foursquare/icon.png", width: 32, height: 32, className: 'foursquare icon'})); }, buildHeader: function() { return(new Element("h2", { 'class': 'handle' }).update(this.title)); }, buildCheckins: function() { return(new Element("div", { 'class': 'checkins' })); } });
0.988281
high
dist/constants.js
theroyalwhee0/snowman
1
6618
<gh_stars>1-10 "use strict"; /** * @file Snowman constants. * @author <NAME> <<EMAIL>> * @copyright Copyright 2021 <NAME> * @license Apache-2.0 */ Object.defineProperty(exports, "__esModule", { value: true }); exports.MAX_ID = exports.MAX_SEQUENCE = exports.MAX_NODE = exports.MAX_TIMESTAMP = exports.MIN_SEQUENCE = exports.MIN_ID = exports.MIN_NODE = exports.MIN_TIMESTAMP = exports.RESERVED = exports.OFFSET_SEQUENCE = exports.OFFSET_NODE = exports.OFFSET_TIMESTAMP = exports.OFFSET_RESERVED = exports.MASK_SEQUENCE = exports.MASK_NODE = exports.MASK_TIMESTAMP = exports.MASK_RESERVED = exports.MASK_ID = exports.DEFAULT_OFFSET = void 0; /** * Constants. * @private */ exports.DEFAULT_OFFSET = 1577836800000; // 2020-01-01T00:00:00+00:00 exports.MASK_ID = 0x7fffffffffffffffn; exports.MASK_RESERVED = 0x8000000000000000n; // 1 = 1 exports.MASK_TIMESTAMP = 0x7fffffffff800000n; // 7+8+8+8+8+1 = 40 exports.MASK_NODE = 0x00000000007fe000n; // 7+3 = 10 exports.MASK_SEQUENCE = 0x0000000000001fffn; // 5+8 = 13 exports.OFFSET_RESERVED = 39n; exports.OFFSET_TIMESTAMP = 23n; exports.OFFSET_NODE = 13n; exports.OFFSET_SEQUENCE = 0n; exports.RESERVED = 0; // Reserved may only be zero. exports.MIN_TIMESTAMP = 1; // 0 = offset time exports.MIN_NODE = 0n; exports.MIN_ID = 0; exports.MIN_SEQUENCE = 0n; exports.MAX_TIMESTAMP = 1099511627775; // 2**40-1, ~34.8 years exports.MAX_NODE = 1023n; // 2**10-1 exports.MAX_SEQUENCE = 8191; // 2**13-1 exports.MAX_ID = 9223372036854775807n; // 2n**63n-1n //# sourceMappingURL=constants.js.map
0.996094
high
src/domains/manager/index.js
fagocbr/project-manager
0
6619
<reponame>fagocbr/project-manager<gh_stars>0 import { meta } from 'genesis/support/model' import { route } from 'genesis/infra/router/resources' import project from 'src/domains/manager/project/routes' import repository from 'src/domains/manager/repository/routes' import issue from 'src/domains/manager/issue/routes' export const managerPath = '/dashboard/manager' export const managerName = 'manager.index' export const managerComponent = 'app/modules/dashboard/components/DashboardRouterView' export const managerMeta = Object.assign( {}, {noLink: true}, meta('format_quote', '<~>', '<~>') ) export const routes = [ route(managerPath, managerName, managerComponent, {}, managerMeta, [ ...project, ...repository, ...issue ]) ]
0.960938
high
src/containers/login/index.js
vlganev/react-admin-panel
4
6620
import React, { Component } from 'react'; import { connect } from 'react-redux'; // import logo from '../image/-logo.png' import {Redirect} from 'react-router-dom'; import { Button, Label, InputGroup } from "@blueprintjs/core"; import { isLoggedIn, login } from '../../actions/login'; import { Row } from 'react-simple-flex-grid'; import "react-simple-flex-grid/lib/main.css"; class LoginForm extends Component { constructor(props) { super(props); this.state = { username: '', password: '' }; this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); this.props.login(this.state.username, this.state.password); } componentWillUpdate() { this.props.isLoggedIn(); } render() { let {isLoginSuccess, loginError} = this.props; let { from } = this.props.location.state || { from: { pathname: '/dashboard' } } if (isLoginSuccess) { return ( <Redirect to={from}/> ) } return ( <div className="container-login"> <Row justify="center"> <div className="login"> <h2>Добре дошли в Admin panel</h2> <article> <div className="error-message text-center">{ loginError && <div>{loginError.message}</div> }</div> <form onSubmit={this.onSubmit}> <Label className="h2" text="<NAME>" > <InputGroup className="bp3-large" type="text" name="username" id="username" ref="username" placeholder="<NAME>" dir="auto" onChange={event => this.setState({username: event.target.value}) } value={this.state.username} /> </Label> <Label text="Парола" > <InputGroup className="bp3-large" type="password" name="password" id="password" ref="password" placeholder="Парола" dir="auto" onChange={event => this.setState({ password: event.target.value })} value={this.state.password} /> </Label> <Button className="bp3-button bp3-fill" icon="log-in" type="submit" text="Вход" /> </form> </article> </div> </Row> </div> ) } } const mapStateToProps = (state) => { return { isLoginPending: state.login.isLoginPending, isLoginSuccess: state.login.isLoginSuccess, loginError: state.login.loginError, }; } const mapDispatchToProps = (dispatch) => { return { dispatch, login: (username, password) => dispatch(login(username, password)), isLoggedIn: () => dispatch(isLoggedIn()) }; } export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
0.859375
high
commands/messages/emojiSteal.js
dannyhpy/_Cleckzie
0
6621
<gh_stars>0 const { Client, Message, MessageEmbed, Util } = require("discord.js"); module.exports = { name: "steal-emoji", aliases: ['emoji-stealer', 'ems'], usage: "*steal-emoji :superflushed:", /** * @param {Client} client * @param {Message} message * @param {String[]} args */ run: async (client, message, args) => { if(!args.length) return message.reply(`Please specify some emojis.`) for (const rawEmoji of args) { const parsedEmoji = Util.parseEmoji(rawEmoji); if(parsedEmoji.id) { const extention = parsedEmoji.animated ? " .gif" : " .png"; const url = `https://cdn.discordapp.com/emojis/${parsedEmoji.id + extention}`; message.guild.emojis.create(url, parsedEmoji.name) .then((emoji) => message.channel.send(`Added: \`${emoji.url}\``)); } } } }
0.535156
high
src/components/Link/index.js
vdonoladev/QuizCatolico
0
6622
<filename>src/components/Link/index.js import NextLink from 'next/link'; export default function Link({children, href, ...props}) { return ( <NextLink href={href} passHref> <a {...props}> {children} </a> </NextLink> ); }
0.941406
high
assets/js/app.js
Heylias/hub
0
6623
import './../css/app.scss'; import authAPI from './services/authAPI'; import AuthContext from './contexts/AuthContext'; import 'react-toastify/dist/ReactToastify.css'; //modules import { ToastContainer, toast } from 'react-toastify'; import React, { useState } from 'react'; import ReactDom from 'react-dom'; import { HashRouter, Switch, Route, withRouter } from 'react-router-dom'; //components import Navbar from './components/Navbar'; import PrivateRoute from './components/PrivateRoute'; // other pages import HomePage from './pages/HomePage'; import LoginPage from './pages/LoginPage'; import RegisterPage from './pages/RegisterPage'; //edit pages import EditFanfictionPage from './pages/itemPages/EditFanfictionPage'; import EditUserPage from './pages/itemPages/EditUserPage'; import PasswordChangePage from './pages/itemPages/PasswordChangePage'; import UploadChapterPage from './pages/itemPages/UploadChapterPage'; //item pages import FanfictionPage from './pages/itemPages/FanfictionPage'; import UserPage from './pages/itemPages/UserPage'; //collection pages import FanfictionsPage from './pages/collectionPages/FanfictionsPage'; import RecentUploadPage from './pages/collectionPages/RecentUploadsPage'; import BestRatedPage from './pages/collectionPages/BestRatedPage'; console.log('Hello Webpack Encore! Edit me in assets/js/app.js') authAPI.setup() const App = () => { const [isAuthenticated, setIsAuthenticated] = useState(authAPI.isAuthenticated()) const NavbarWithRouter = withRouter(Navbar) const contextValue = { isAuthenticated: isAuthenticated, setIsAuthenticated : setIsAuthenticated } return ( <AuthContext.Provider value={ contextValue }> <HashRouter> <NavbarWithRouter/> <main className="container pt-5"> <Switch> <PrivateRoute path="/fanfictions/new" component={ EditFanfictionPage } /> <PrivateRoute path="/fanfictions/:id/edit" component={ EditFanfictionPage } /> <PrivateRoute path="/fanfictions/:id/upload" component={ UploadChapterPage } /> <Route path="/fanfictions/best" component={ BestRatedPage } /> <Route path="/fanfictions/latest" component={ RecentUploadPage } /> <Route path="/fanfictions/:id" component={ FanfictionPage } /> <Route path="/fanfictions" component={ FanfictionsPage } /> <PrivateRoute path="/users/:id/password" component={ PasswordChangePage } /> <PrivateRoute path="/users/:id/edit" component={ EditUserPage } /> <Route path="/users/:id" component={ UserPage } /> <Route path="/register" component={ RegisterPage }/> <Route path="/login" component={ LoginPage }/> <Route path="/" component={ HomePage } /> </Switch> </main> </HashRouter> <ToastContainer position={ toast.POSITION.BOTTOM_LEFT } /> </AuthContext.Provider> ) } const rootElement = document.querySelector('#app') ReactDom.render(<App />, rootElement)
0.976563
high
client/src/theme/materialTheme.js
yg1110/NetListers
0
6624
<reponame>yg1110/NetListers<filename>client/src/theme/materialTheme.js import createMuiTheme from "@material-ui/core/styles/createMuiTheme"; export const PrimaryTheme = createMuiTheme({ palette: { default: "#fefefe", kournikova: "#ffee82", selago: "#f6e3fd", frostedmint: "#dafff7", yourpink: "#ffcabf", }, });
0.953125
high
bundle/microservices/client/client-mqtt.js
jeckhart/nest
0
6625
<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const logger_service_1 = require("@nestjs/common/services/logger.service"); const load_package_util_1 = require("@nestjs/common/utils/load-package.util"); const constants_1 = require("../constants"); const client_proxy_1 = require("./client-proxy"); const constants_2 = require("./constants"); let mqttPackage = {}; class ClientMqtt extends client_proxy_1.ClientProxy { constructor(options) { super(); this.options = options; this.logger = new logger_service_1.Logger(client_proxy_1.ClientProxy.name); this.url = this.getOptionsProp(this.options, 'url') || constants_1.MQTT_DEFAULT_URL; mqttPackage = load_package_util_1.loadPackage('mqtt', ClientMqtt.name); } getAckPatternName(pattern) { return `${pattern}_ack`; } getResPatternName(pattern) { return `${pattern}_res`; } close() { this.mqttClient && this.mqttClient.end(); this.mqttClient = null; } connect() { if (this.mqttClient) { return Promise.resolve(); } this.mqttClient = this.createClient(); this.handleError(this.mqttClient); return this.connect$(this.mqttClient).toPromise(); } createClient() { return mqttPackage.connect(this.url, this.options); } handleError(client) { client.addListener(constants_1.ERROR_EVENT, err => err.code !== constants_2.ECONNREFUSED && this.logger.error(err)); } createResponseCallback(packet, callback) { return (channel, buffer) => { const { err, response, isDisposed, id } = JSON.parse(buffer.toString()); if (id !== packet.id) { return undefined; } if (isDisposed || err) { return callback({ err, response: null, isDisposed: true, }); } callback({ err, response, }); }; } publish(partialPacket, callback) { try { const packet = this.assignPacketId(partialPacket); const pattern = this.normalizePattern(partialPacket.pattern); const responseChannel = this.getResPatternName(pattern); const responseCallback = this.createResponseCallback(packet, callback); this.mqttClient.on(constants_1.MESSAGE_EVENT, responseCallback); this.mqttClient.subscribe(responseChannel); this.mqttClient.publish(this.getAckPatternName(pattern), JSON.stringify(packet)); return () => { this.mqttClient.unsubscribe(responseChannel); this.mqttClient.removeListener(constants_1.MESSAGE_EVENT, responseCallback); }; } catch (err) { callback({ err }); } } } exports.ClientMqtt = ClientMqtt;
0.992188
high
src/scopeReducer.js
iamrickyspanish/redux-scoped-ducks
0
6626
<gh_stars>0 const isActionTypeScoped = (scope, actionType) => { const splittedActionType = actionType.split("/"); return splittedActionType.length >= 3 && splittedActionType[1] === scope; }; /** * Scopes a reducer function. * * Accepts a scope and a reducer function and returns a scoped reducer fucnction. A scoped reducer works and can be used like a regular reducer - the only difference is that the scoped reducer will ignore all actions that aren't scoped the same. * If not of type "function", the given reducer is returned as it is. * * @example * * const setValue = payload => ({ * type: "app/reducerA/SET_VALUE", * payload * }) * * const scopedSetValue = scopeAction("reducerB", setValue) * * const reducer = (state = 0, action) => action.type === "app/reducerA/SET_VALUE" ? action.payload : state * const scopedReducer = scopeReducer("reducerB", reducer) * * // scoped reducer ignores unscoped action * console.log(scopedReducer(0, setValue(42))) * // 0 * * // scoped reducer handles scoped action * console.log(scopedReducer(0, scopedSetValue(42))) * // 42 * * @param {string} scope * @param {function} reducer * @returns {function} */ const scopeReducer = (scope, reducer) => scope && typeof reducer === "function" ? (state, action) => { const shouldProcessAction = action.meta && action.meta.unscopedActionType && isActionTypeScoped(scope, action.type); return shouldProcessAction ? reducer(state, { ...action, type: action.meta.unscopedActionType }) : reducer(state, {}); } : reducer; export default scopeReducer;
0.996094
high
src/components/Content.js
fetus-hina/ikalog-webui-dev
0
6627
<filename>src/components/Content.js /* * IkaLog * ====== * * Copyright (C) 2015 <NAME> * Copyright (C) 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { Component } from 'react'; import { stopEvent } from '../Utils'; import Sidebar from './Sidebar'; import MainContent from './MainContent'; export default class Content extends Component { render() { const classesMain = this._addPushClass([ 'col-12', 'col-sm-7', 'col-md-8', 'col-lg-9', 'col-xl-9', ]); const classesSide = this._addPullClass(this._makeCounterSide(classesMain)); return ( <div className="container mt-2"> <div className="row"> <XsHelper {...this.props} /> <MainContent className={classesMain.join(' ')} {...this.props} /> <Sidebar className={classesSide.join(' ')} {...this.props} /> </div> </div> ); } // 左右入れ替えのための push-**-** クラスを生成して返す (col-md-10 => col-md-10 push-md-2) _addPushClass(classes) { return this._addPushPullClass(classes, 'push'); } // 左右入れ替えのための pull-**-** クラスを生成して返す (col-md-10 => col-md-10 pull-md-2) _addPullClass(classes) { return this._addPushPullClass(classes, 'pull'); } // _addPushClass/_addPullClass の実装関数 _addPushPullClass(classes, pushOrPull) { const ret = []; classes.forEach(className => { const match = className.match(/^col-([a-z]{2})-(\d+)$/); ret.push(className); if (!match || match[2] === '12') { return; } const push = 12 - parseInt(match[2], 10); ret.push(`${pushOrPull}-${match[1]}-${push}`); }); return ret; } // 2カラムレイアウトの反対側のクラスを自動生成する(col-**-** の合計が12になるように作る) _makeCounterSide(classes) { const ret = []; classes.forEach(className => { const match = className.match(/^col-(?:([a-z]{2})-)?(\d+)$/); if (!match) { return; } if (match[2] === '12') { ret.push(className); return; } const width = 12 - parseInt(match[2], 10); ret.push(`col-${match[1]}-${width}`); }); return ret; } } class XsHelper extends Component { constructor(props) { super(props); this._onClick = this._onClick.bind(this); } render() { return ( <div className="col-12 hidden-sm-up"> <div className="text-right text-xs-right mb-2"> <button className="btn btn-secondary" onClick={this._onClick}> <span className="fa fa-fw fa-angle-double-down" /> {window.i18n.t('Menu', {ns: 'sidebar'})} </button> </div> </div> ); } _onClick(e) { const $ = window.jQuery; const $target = $('#menu'); $('body,html').animate({scrollTop:$target.offset().top - 16}, 'fast'); $('body,html').animate({scrollLeft:0}, 'fast'); stopEvent(e); } }
0.996094
high
files/code/segmentsCloudViewer/js/lib/conjugate-gradient/twiddle.js
Ammarkhat/ammarkhat.github.io
0
6628
<filename>files/code/segmentsCloudViewer/js/lib/conjugate-gradient/twiddle.js /** * Bit twiddling hacks for JavaScript. * * Author: <NAME> * * Ported from Stanford bit twiddling hack library: * http://graphics.stanford.edu/~seander/bithacks.html */ "use strict"; "use restrict"; var twiddle = {}; //Number of bits in an integer var INT_BITS = 32; //Constants twiddle.INT_BITS = INT_BITS; twiddle.INT_MAX = 0x7fffffff; twiddle.INT_MIN = -1 << (INT_BITS - 1); //Returns -1, 0, +1 depending on sign of x twiddle.sign = function (v) { return (v > 0) - (v < 0); } //Computes absolute value of integer twiddle.abs = function(v) { var mask = v >> (INT_BITS-1); return (v ^ mask) - mask; } //Computes minimum of integers x and y twiddle.min = function(x, y) { return y ^ ((x ^ y) & -(x < y)); } //Computes maximum of integers x and y twiddle.max = function(x, y) { return x ^ ((x ^ y) & -(x < y)); } //Checks if a number is a power of two twiddle.isPow2 = function(v) { return !(v & (v-1)) && (!!v); } //Computes log base 2 of v twiddle.log2 = function(v) { var r, shift; r = (v > 0xFFFF) << 4; v >>>= r; shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; return r | (v >> 1); } //Computes log base 10 of v twiddle.log10 = function(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } //Counts number of bits twiddle.popCount = function(v) { v = v - ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } //Counts number of trailing zeros function countTrailingZeros(v) { var c = 32; v &= -v; if (v) c--; if (v & 0x0000FFFF) c -= 16; if (v & 0x00FF00FF) c -= 8; if (v & 0x0F0F0F0F) c -= 4; if (v & 0x33333333) c -= 2; if (v & 0x55555555) c -= 1; return c; } twiddle.countTrailingZeros = countTrailingZeros; //Rounds to next power of 2 twiddle.nextPow2 = function(v) { v += v === 0; --v; v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; v |= v >>> 8; v |= v >>> 16; return v + 1; } //Rounds down to previous power of 2 twiddle.prevPow2 = function(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; v |= v >>> 8; v |= v >>> 16; return v - (v>>>1); } //Computes parity of word twiddle.parity = function(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; v &= 0xf; return (0x6996 >>> v) & 1; } var REVERSE_TABLE = new Array(256); (function(tab) { for(var i=0; i<256; ++i) { var v = i, r = i, s = 7; for (v >>>= 1; v; v >>>= 1) { r <<= 1; r |= v & 1; --s; } tab[i] = (r << s) & 0xff; } })(REVERSE_TABLE); //Reverse bits in a 32 bit word twiddle.reverse = function(v) { return (REVERSE_TABLE[ v & 0xff] << 24) | (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | REVERSE_TABLE[(v >>> 24) & 0xff]; } //Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes twiddle.interleave2 = function(x, y) { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y &= 0xFFFF; y = (y | (y << 8)) & 0x00FF00FF; y = (y | (y << 4)) & 0x0F0F0F0F; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); } //Extracts the nth interleaved component twiddle.deinterleave2 = function(v, n) { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; v = (v | (v >>> 4)) & 0x00FF00FF; v = (v | (v >>> 16)) & 0x000FFFF; return (v << 16) >> 16; } //Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes twiddle.interleave3 = function(x, y, z) { x &= 0x3FF; x = (x | (x<<16)) & 4278190335; x = (x | (x<<8)) & 251719695; x = (x | (x<<4)) & 3272356035; x = (x | (x<<2)) & 1227133513; y &= 0x3FF; y = (y | (y<<16)) & 4278190335; y = (y | (y<<8)) & 251719695; y = (y | (y<<4)) & 3272356035; y = (y | (y<<2)) & 1227133513; x |= (y << 1); z &= 0x3FF; z = (z | (z<<16)) & 4278190335; z = (z | (z<<8)) & 251719695; z = (z | (z<<4)) & 3272356035; z = (z | (z<<2)) & 1227133513; return x | (z << 2); } //Extracts nth interleaved component of a 3-tuple twiddle.deinterleave3 = function(v, n) { v = (v >>> n) & 1227133513; v = (v | (v>>>2)) & 3272356035; v = (v | (v>>>4)) & 251719695; v = (v | (v>>>8)) & 4278190335; v = (v | (v>>>16)) & 0x3FF; return (v<<22)>>22; } //Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) twiddle.nextCombination = function(v) { var t = v | (v - 1); return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); }
0.996094
high
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card