max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
app/mock/friend.js
valarbore/ricebook-frontend
0
15998748
import avatar1 from './avatar/1.jpg'; import avatar2 from './avatar/2.jpg'; import avatar3 from './avatar/3.jpg'; export const friends = [ { id: 1, name: 'Alice', avatar: avatar1, status: 'fun', }, { id: 2, name: 'Bob', avatar: avatar2, status: 'happy', }, { id: 3, name: 'Jason', avatar: avatar3, status: 'sad', }, ];
0.699219
1
docs/search/classes_10.js
BryceStandley/TNAH
1
15998756
var searchData= [ ['scene_0',['Scene',['../class_scene.html',1,'Scene'],['../classtnah_1_1_scene.html',1,'tnah::Scene']]], ['scenecamera_1',['SceneCamera',['../classtnah_1_1_scene_camera.html',1,'tnah']]], ['scenecomponent_2',['SceneComponent',['../structtnah_1_1_scene_component.html',1,'tnah']]], ['scenedata_3',['SceneData',['../structtnah_1_1_renderer_1_1_scene_data.html',1,'tnah::Renderer']]], ['sceneserializer_4',['SceneSerializer',['../class_scene_serializer.html',1,'']]], ['scriptengine_5',['ScriptEngine',['../class_script_engine.html',1,'']]], ['serializer_6',['Serializer',['../classtnah_1_1_serializer.html',1,'tnah']]], ['shader_7',['Shader',['../classtnah_1_1_shader.html',1,'tnah']]], ['shaderlightinformation_8',['ShaderLightInformation',['../structtnah_1_1_light_1_1_shader_light_information.html',1,'tnah::Light']]], ['shaderresourcedeclaration_9',['ShaderResourceDeclaration',['../classtnah_1_1_shader_resource_declaration.html',1,'tnah']]], ['shaderuniform_10',['ShaderUniform',['../classtnah_1_1_shader_uniform.html',1,'tnah']]], ['singleton_11',['singleton',['../classtnah_1_1singleton.html',1,'tnah']]], ['skybox_12',['Skybox',['../classtnah_1_1_skybox.html',1,'tnah']]], ['skyboxcomponent_13',['SkyboxComponent',['../classtnah_1_1_skybox_component.html',1,'tnah']]], ['skyboxmaterial_14',['SkyboxMaterial',['../classtnah_1_1_skybox_material.html',1,'tnah']]], ['spotlight_15',['SpotLight',['../classtnah_1_1_spot_light.html',1,'tnah']]], ['state_16',['state',['../classstate.html',1,'']]], ['state_17',['State',['../classtnah_1_1_state.html',1,'tnah']]], ['statemachine_18',['stateMachine',['../classstate_machine.html',1,'']]], ['statemachine_19',['StateMachine',['../classtnah_1_1_state_machine.html',1,'tnah']]], ['stbi_5fio_5fcallbacks_20',['stbi_io_callbacks',['../structstbi__io__callbacks.html',1,'']]] ];
0.664063
1
resources/js/app.js
bovisp/motp-recruitment
0
15998764
require('./bootstrap') require('./plugins/jqScribble') axios.defaults.baseURL = window.baseURL import Vue from 'vue' import store from './store' window.Vue = Vue window.events = new Vue import './plugins/interceptors' /** * Gives Vue access to the Laravel translation strings on a per language basis. * * @param {string} key The translation string key. * * @return {string} The translation string value. */ Vue.prototype.trans = (key) => { let paths = key.split('.'), current = window.trans, i; for (i = 0; i < paths.length; ++i) { if (current[paths[i]] == undefined) { return undefined; } else { current = current[paths[i]]; } } return current; } Vue.component('qpf-table', require('./components/qpf-table/QpfTable.vue').default) Vue.component('draw-app', require('./components/draw/Draw.vue').default) Vue.component('textbox-answer', require('./components/textboxes/TextboxAnswer.vue').default) Vue.component('confirm-page', require('./components/confirm/Confirm.vue').default) Vue.component('score-item', require('./components/scores/ScoreItem.vue').default) Vue.component('image-map-two', require('./components/imagemap/ImageMapTwo.vue').default) Vue.component('image-map-one', require('./components/imagemap/ImageMapOne.vue').default) Vue.component('image-map-tephi', require('./components/imagemap/ImageMapTephi.vue').default) Vue.component('image-animator', require('./components/animator/ImageAnimator.vue').default) Vue.component('countdown-timer', require('./components/timer/CountdownTimer.vue').default) Vue.component('textbox-test', require('./components/test/TextboxTest.vue').default) const app = new Vue({ el: '#app', store })
1.25
1
src/Masu/MasuTemplateRecto.js
superfaz/origami-box
4
15998772
import env from "../env"; import { buildDefaultStyles, SvgPaper } from "../Generic/Svg"; import { SvgDebugAxis } from "../Generic/SvgDebug"; import SvgFooter from "../Generic/SvgFooter"; import SvgHeader from "../Generic/SvgHeader"; import { useTemplate } from "../hooks"; import { useMasuDimensions } from "./useMasuDimensions"; import SvgCut from "./SvgCut"; export default function MasuTemplateRecto({ lid = false, print = false }) { const { template, data: masu } = useTemplate(); const d = useMasuDimensions(masu, lid); const styles = buildDefaultStyles(); if (d === null) { return <SvgPaper className="template" pageWidth={210} pageHeight={297} />; } return ( <SvgPaper className="template" pageWidth={d.pageWidth} pageHeight={d.pageHeight} > {/* Header for print */} {print && ( <SvgHeader dimensions={d} blockName={lid ? "Lid" : masu.withLid ? "Base" : "Box"} title={template.title} /> )} <g transform="rotate(45)"> {env.debug.svg && <SvgDebugAxis />} <SvgCut d={d} styles={styles} /> </g> {/* Footer for print */} {print && <SvgFooter dimensions={d} />} </SvgPaper> ); }
1.601563
2
app/js/module/core/core.constant.js
jokidz90/angularjs-material-bootstrap
0
15998780
'use strict'; var app = angular.module('apps.core'); app.constant('API_URL', { 'CompanyDomain': 'https://qiji-dev.proseller.io/', 'GeneralInfo': '../masterdata/api/info/company', 'UserLogin': '../masterdata/api/user/login', 'GenerateNewAccessToken': '../masterdata/api/user/generatenewaccesstoken', 'LanguageTranslation': '../masterdata/api/appmodule/I18N/', 'AppSetting': '../masterdata/api/fetchappsetting', 'Outlet': '../masterdata/api/outlets', 'Product': '../product/api/productpreset/load', 'ProductCheck': '../product/api/productpreset/checkversion', // 'AppModule': '../masterdata/api/appmodule/fetchapp', // 'AppFilter': '../masterdata/api/appmodule/fetchdtfilter', // 'AppColumn': '../masterdata/api/appmodule/fetchdtcolumn', // 'SideBar': '../masterdata/api/appmodule/fetchsidebarmenu', // 'Notification': '../masterdata/api/notification/all/userAccount', // 'NotificationUnread': '../masterdata/api/notification/unread/userAccount', // 'User': '../masterdata/api/user', // 'UserLogout': '../masterdata/api/user/logout', });
0.726563
1
components/buttons/readMoreBtn2.js
vincezun/pocket
0
15998788
import Link from 'next/link'; import '../../static/styles/readMoreBtn2.scss'; class readMoreBtn2 extends React.Component { render() { const { link } = this.props; return ( <Link href={link}> <a className='readMoreBtn2'>READ MORE</a> </Link> ); } } export default readMoreBtn2;
0.847656
1
subOffices/mdcx_hetz.js
Morgas01/XDCC-HQ
6
15998796
exports = module.exports = require("../mercenaries/xdccList") ("irc.rizon.net","#mdcx","http://aion.mdcx.io:12345","mdcx|hetz");
0.412109
0
scripts/parse.js
robinfhu/swrm-events
0
15998804
const csv = require('csvtojson'); const fs = require('fs'); (async function() { const result = await csv().fromFile(process.argv[2]); fs.writeFileSync("./output.json", JSON.stringify(result,null,' ')); })();
0.816406
1
index.js
amandat85/Constructor-Word-Guess
0
15998812
var inquirer = require("inquirer"); var Word = require("./Word.js"); var chalk = require("chalk"); var figlet = require("figlet"); var words = ["frenchhorn", "trumpet", "clarinet", "trombone", "tuba", "violin", "viola", "doublebass", "flute", "bassoon", "cello", "timpanii"] var guessesRemaining = 9; var randomWord = " "; var randomWordString = " "; var currentWord = " "; var wordGuessed = false; figlet("Hangman Game", function (err, data) { if (err) { console.log('Something went wrong...'); console.dir(err); return; } console.log(data) console.log("Welcome to the Hangman Game!"); console.log("Theme is... orchestral instruments"); var howToPlay = chalk.cyan("==========================================================================================================" + "\r\n" + "How to play" + "\r\n" + "==========================================================================================================" + "\r\n" + "When prompted to enter a letter, press any letter (a-z) on the keyboard to guess a letter." + "\r\n" + "Keep guessing letters. When you guess a letter, your choice is either correct or incorrect." + "\r\n" + "If incorrect, the letter you guessed does not appear in the word." + "\r\n" + "For every incorrect guess, the number of guesses remaining decrease by 1." + "\r\n" + "If correct, the letter you guessed appears in the word." + "\r\n" + "If you correctly guess all the letters in the word before the number of guesses remaining reaches 0, you win." + "\r\n" + "If you run out of guesses before the entire word is revealed, you lose. Game over." + "\r\n" + "===========================================================================================================" + "\r\n" + "You can exit the game at any time by pressing Ctrl + C on your keyboard." + "\r\n" + "===========================================================================================================") console.log(howToPlay); confirmStart(); }); function confirmStart() { inquirer.prompt([ { type: "text", name: "playerName", message: "What is your name?" }, { type: "confirm", name: "readyToPlay", message: "Are you Ready to play?", default: true, } ]).then(function (response) { if (response.readyToPlay) { console.log("Great! Welcome, " + response.playerName + ". Let's begin..."); startGame(); } else { console.log("Good bye, " + response.playerName + "! Come back soon."); return; } }) } function startGame() { newWord(); query(); } var newWord = function () { randomWord = [Math.floor(Math.random() * words.length)]; randomWordString = words[randomWord] currentWord = new Word(randomWordString); currentWord.wordDisplay(); console.log("\r") }; function checked() { function guessedYes(letter) { return (letter.guessed === true) }; let array = currentWord.letters; let test = array.every(guessedYes); if (test === true) { wordGuessed = true; } } function reset() { inquirer.prompt([ { type: "list", name: "continue", message: "Would you like a new word?", choices: ["Yes", "No"] } ]).then(function (response) { if (response.continue === "Yes") { guessesRemaining = 9; wordGuessed = false; newWord(); query(); } else if (response.continue === "No") { console.log(chalk.magenta("See you next time!")); } }) } let query = function () { checked(); if (guessesRemaining > 0 && wordGuessed === false) { inquirer.prompt([ { name: "guess", message: "Guess a Letter! " } ]).then(function (response) { if (randomWordString.indexOf(response.guess) !== -1) { currentWord.checked(response.guess); console.log(chalk.green("\nCORRECT!")) console.log("\nGuesses Remaining: " + guessesRemaining + "\n") currentWord.wordDisplay(); console.log("\r") query(); } else if (randomWordString.indexOf(response.guess) === -1) { guessesRemaining--; console.log(chalk.red("\nINCORRECT!")); console.log("\nGuesses Remaining: " + guessesRemaining + "\n"); currentWord.wordDisplay(); console.log("\r") query(); } }) } else if (guessesRemaining <= 0 && wordGuessed === false) { console.log(chalk.blue("Out of guesses!")); reset(); } else if (guessesRemaining > 0 && wordGuessed === true) { console.log(chalk.cyan("You got it right!\n")); reset(); } }
2.1875
2
es6/RecordBuffer.js
citybound/share-state
0
15998820
const BUFFER_SIZE = Math.pow(2, 12); // 4kb export default class RecordBuffer { constructor (recordSize) { if (Number.isNaN(recordSize)) throw new Error("Invalid record size!"); if (recordSize > BUFFER_SIZE) throw new Error("Record bigger than max. Buffer size"); this.recordSize = Math.max(4, recordSize + 1); // additional flag to distinguish between free/alloc. this.recordsPerBuffer = Math.max(10, Math.floor(BUFFER_SIZE / this.recordSize)); this.bufferSize = BUFFER_SIZE; this.firstFreeIndex = 0; this.buffers = []; } allocate () { let index = this.firstFreeIndex; let buffer = this.getBuffer(index); let offset = this.getOffset(index); let nextIndexInfo = buffer.readUInt32LE(offset); this.firstFreeIndex = nextIndexInfo === 0 ? index + 1 : nextIndexInfo - 1; buffer.fill(0, offset, offset + this.recordSize - 2); this.getBuffer(index).writeUInt8(1, this.getOffset(index) + this.recordSize - 1); // set alloc. return index; } free (index) { this.getBuffer(index).writeUInt32LE(index + 1, this.getOffset(index)); this.getBuffer(index).writeUInt8(0, this.getOffset(index) + this.recordSize - 1); // set free } * allocatedIndices () { let index = 0; for (let buffer of this.buffers) { for (let i = 0; i < this.recordsPerBuffer; i++, index++) { if (buffer.readUInt8(i * this.recordSize + this.recordSize - 1)) yield index; } } } isAllocated(index) { if (index < 0 || index > this.buffers.length * this.recordsPerFile) return false; let bufferIndex = Math.floor(index / this.recordsPerFile); let bufferOffset = (index % this.recordsPerFile) * this.recordSize; return !!this.buffers[bufferIndex].readUInt8(bufferOffset + this.recordSize - 1); } getBuffer (index) { let bufferIndex = Math.floor(index / this.recordsPerBuffer); return this.buffers[bufferIndex] || this.addBuffer(index); } getOffset (index) { return (index % this.recordsPerBuffer) * this.recordSize; } addBuffer (index) { let buffer = new Buffer(this.bufferSize); buffer.fill(0, 0, this.bufferSize); this.buffers.push(buffer); return buffer; } }
2.421875
2
src/app/services/userApiLocal.js
Yu-AnChen/flowthrough
0
15998828
class userApiLocalService { static get $inject() { return ['$resource','$http', '$window']; } constructor($resource, $http, $window) { this.$window = $window; this.storageKey = 'flowThroughUsers'; } // local version for demo getCurrentUser() { return new Promise((resolve, reject) => { let res = {}; let usersJSON = this.$window.localStorage.getItem(this.storageKey); let users; let indexOfLoggedinUser; if (!usersJSON) { res.status = 401; return reject(res); } users = JSON.parse(usersJSON); if (!users.map) { res.status = 500; return reject(res); } indexOfLoggedinUser = users.findIndex(element => element.isSignedin); if (indexOfLoggedinUser == -1) { res.status = 401; return reject(res); } res.status = 200; res.data = users[indexOfLoggedinUser]; return resolve(res); }); } signup(user) { // this.$window.localStorage.setItem('flowThroughUser', user); return new Promise((resolve, reject) => { let res = {}; let usersJSON = this.$window.localStorage.getItem(this.storageKey); let users; if (!usersJSON) { user.isSignedin = true; this.$window.localStorage.setItem(this.storageKey, JSON.stringify([user])); res.status = 200; res.data = user; return resolve(res); } users = JSON.parse(usersJSON); if (!users.map) { res.status = 500; return reject(res); } let emailExist = users.map(element => element.email) .includes(user.email); if (emailExist) { res.status = 403; res.data = 'email already exist'; return reject(res); } user.isSignedin = true; users.push(user); this.$window.localStorage.setItem(this.storageKey, JSON.stringify(users)); res.status = 200; res.data = user; return resolve(res); }); } signin(user) { return new Promise((resolve, reject) => { let res = {}; let usersJSON = this.$window.localStorage.getItem(this.storageKey); let users; let foundUser; let indexOfFoundUser; if (!usersJSON) { res.status = 404; return reject(res); } users = JSON.parse(usersJSON); if (!users.map) { res.status = 500; return reject(res); } foundUser = users.find(element => element.email == user.email); if (!foundUser) { res.status = 404; res.data = 'db.find:x,db.update:x'; return reject(res); } indexOfFoundUser = users.findIndex(element => element.email == user.email); users.forEach((element, index) => { element.isSignedin = (index === indexOfFoundUser) ? true : false; }); this.$window.localStorage.setItem(this.storageKey, JSON.stringify(users)); res.status = 200; res.data = user; return resolve(res); }); } signout(json) { return new Promise((resolve, reject) => { let res = {}; let usersJSON = this.$window.localStorage.getItem(this.storageKey); let users; if (!usersJSON) { res.status = 404; return reject(res); } users = JSON.parse(usersJSON); if (!users.map) { res.status = 500; return reject(res); } users.forEach((element, index) => { element.isSignedin = false; }); this.$window.localStorage.setItem(this.storageKey, JSON.stringify(users)); res.status = 200; return resolve(res); }); } } export default userApiLocalService;
1.796875
2
pages/gabriella.js
Mishmeia/next-starter-jamstack
0
15998836
import React from 'react' import Head from 'next/head' import Link from 'next/link' import styled from 'styled-components' const Tudo = styled.createGlobalStyle` body { background: ${props => props.theme.bg}; width: 100%; height: 100%; } ` const TemaTeste = styled.div` height: 100vh; position: relative; display: flex; align-items: center; justify-content: center; background: ${props => props.theme.bg}; color: ${props => props.theme.fontColor}; `; const Gabriella = () => ( <div> <Tudo> <Head> <title>Para Gabriella ❤️</title> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> </Head> <TemaTeste> <h1>Para Gabriella ❤️:</h1> </TemaTeste> <style jsx>{` :global(html,body) { margin: 0; padding: 0; height: 100%; } :global(body) { font-size: calc(10px + 1vmin); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; display: flex; flex-direction: column; align-items: center; } `}</style> </Tudo> </div> ) export default Gabriella
1.570313
2
src/errors/not-found-error.js
nmanichev/deel-task
0
15998844
const DeelError = require("./deel-error"); class NotFoundError extends DeelError{ constructor(message){ if(!message){ message = "The requested entity could not be found in Deel service."; } super(message); this._status = 404; } } module.exports = NotFoundError;
1.148438
1
src/components/Header.js
QuintonJason/activate-fall-19
0
15998852
import PropTypes from "prop-types" import React from "react" const Header = ({ siteTitle }) => ( <header className="header-wrapper"> <div className="l-header landing-section"> <h2 className="header__subhead"><span className="header__subhead--bold">activate</span> presents</h2> <h1 className="header__display">Lightning Night</h1> <time className="header__time" dateTime="2020-01-14T18:30:00"><span className="header__time-bold">January 14</span> @ 6:30 PM</time> </div> </header> ) Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
1.226563
1
config/mailer.js
StarLord07/federalist
372
15998860
module.exports = { host: 'http://echo:8989', };
0.279297
0
app/setup/start-loading/route.js
eercast/nano-wallet-desktop
36
15998868
import Route from '@ember/routing/route'; export default class SetupStartLoadingRoute extends Route {}
0.78125
1
test/circular/main.js
bauerca/dynapack
32
15998876
var ensure = require('node-ensure'); var a = './a.js' /*js*/; var canceled; var sync1; ensure([a], function(err) { var a1 = require(a); sync1 = true; if (a1 !== 'a') { iso.fail('on first fetch'); } else { var sync2; ensure([a], function(err) { var a2 = require(a); sync2 = true; iso.report( a1 === a2 ? 'Success' : 'Failure: modules were different' ); }); if (sync2) { iso.fail('second fetch was synchronous.'); } } }); if (sync1) { iso.fail('first fetch was synchronous.'); } setTimeout(function() { iso.fail('timeout.'); }, 1000);
1.507813
2
src/graphqlSchema/byway/GeometryType.js
aliakseimaniuk/park-detective-api
0
15998884
import { GraphQLObjectType, GraphQLNonNull, GraphQLFloat, GraphQLList, GraphQLScalarType } from 'graphql'; var GeoJSON = new GraphQLScalarType({ name: 'GeoJSON', serialize: (value) => { return value; }, parseValue: (value) => { return value; }, parseLiteral: (ast) => { return ast.value; } }); export default new GraphQLObjectType({ name: 'geometry', description: 'This object represents the geometry of the byway', fields: { paths: {type: GeoJSON }, }, });
1.179688
1
angular/js/teacher/controllers/accountantControllers.js
ITAAcademy/IntITA
2
15998892
/** * Created by adm on 19.07.2016. */ angular .module('teacherApp') .controller('agreementsCtrl', ['$scope', 'agreementsService', 'paymentSchemaService', 'NgTableParams', 'lodash', 'agreementsInformation','usersService','paymentSchemaService', function ($scope, agreements, paymentSchema, NgTableParams, _, agreementsInformation, usersService, paymentSchemaService) { $scope.changePageHeader('Список договорів'); $scope.currentDate = currentDate; $scope.agreementsTableParams = new NgTableParams({sorting: {create_date: "desc"}}, { getData: function (params) { return agreements .list(params.url()) .$promise .then(function (data) { params.total(data.count); agreementsInformation.setInformation(data); return data.rows; }); } }); $scope.confirm = function (id) { return agreements .confirm({id: id}) .$promise .then(function (data) { $scope.agreementsTableParams.reload(); return data; }); }; $scope.cancel = function (id) { bootbox.confirm('Ви впевнені, що хочете скасувати договір?', function (result) { if (result) { return agreements .cancel({id: id}) .$promise .then(function (data) { $scope.agreementsTableParams.reload(); return data; }); } }); }; $scope.getSchemas = paymentSchema .query() .$promise .then(function (data) { return data.map(function (item) { return {id: item.pay_count, title: item.title_ua} }) }); $scope.groupsNames = usersService .getGroupNumber() .$promise .then(function (data) { var res = data; $scope.temp = []; $scope.temp = $scope.temp.concat(res); return $scope.temp; }) .catch(function () { bootbox.alert('Помилка, зверніться до адміністратора'); }); $scope.updateContractInfo = function (id_student, attr, text) { text = text?text:''; bootbox.dialog({ title: "Введіть нову назву:", message: '<div class="panel-body"><div class="row"><form role="form" name="commentMessage"><div class="form-group col-md-12">'+ '<textarea class="form-control" style="resize: none" rows="6" id="commentMessageText" ' + 'placeholder="тут можна ввести нову назву поля">' +text+ '</textarea>'+'</div></form></div></div>', buttons: {success: {label: "Підтвердити", className: "btn btn-primary", callback: function () { var data = $jq('#commentMessageText').val(); usersService.updateStudentData({id_student: id_student, data: data, attr: attr}) .$promise .then(function(){ $scope.agreementsTableParams.reload(); }); } }, cancel: {label: "Скасувати", className: "btn btn-default", callback: function () { } } } } ); } $scope.getAgreementStatuses = paymentSchemaService .statuses() .$promise .then(function (data) { return data.map(function (item) { return {id: item.id, title: item.title_ua} }) }); }]) .controller('agreementDetailCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) { $scope.changePageHeader('Договір та його рахунки'); $scope.agreementId = $stateParams.agreementId; }]) .controller('invoiceDetailCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) { $scope.changePageHeader('Рахунок'); $scope.invoiceId = $stateParams.invoiceId; }]) .controller('invoicesCtrl', ['$scope', 'invoicesService', 'NgTableParams', function ($scope, invoicesService, NgTableParams) { $scope.changePageHeader('Рахунки'); }]) .controller('operationCtrl', ['$scope', '$state', function ($scope, $state) { $scope.createOperation = function createOperation() { $state.go('accountant/operation/create'); }; }]) .controller('createOperationCtrl', [ '$scope', '$state', '$q', 'lodash', 'agreementsService', 'invoicesService', 'userService', 'operationsService', 'externalPaymentsService', 'ngToast', function ($scope, $state, $q, _, agreements, invoices, user, operations, externalPayments, ngToast) { $scope.Math = window.Math; $scope.typeaheadProviders = { user: { name: 'користувачу', searchField: 'email', provider: user, label: function (user) { return user ? (((user.firstName || '' ) + ' ' + (user.middleName || '') + ' ' + (user.secondName || '') + ' <' + (user.email || '')) + '>').trim() : ''; }, onSelect: function ($model) { $scope.operation.userId = $model.id; $scope.updateUserData({id: $scope.operation.userId}); $scope.updateAgreementData({'extraParams[user_id]': $scope.operation.userId}) .then(function (data) { if (data && data.length) { $scope.operation.agreementId = data[0].id; } }); } }, agreement: { name: '<NAME>', searchField: 'number', provider: agreements, label: function (agreements) { return agreements ? (agreements.service.description + (agreements.number || '') + ' від ' + (agreements.create_date || '')) : ''; }, onSelect: function ($model) { $scope.clearOperation(); $scope.operation.agreementId = $model.id; $scope.operation.userId = $model.user_id.user_id; $scope.updateUserData({id: $model.user_id.user_id}); $scope.updateAgreementData({'extraParams[id]': $model.id}); $scope.updateInvoiceData({'extraParams[agreement_id]': $scope.operation.agreementId}); } }, invoice: { name: '<NAME>', searchField: 'number', provider: invoices, label: function (invoice) { return invoice ? ((invoice.number || '') + ' від ' + (invoice.date_created || '') + ' сума ' + (invoice.summa || '') + ' (погашено: ' + (invoice.paidAmount || '0') + ')') : ''; }, onSelect: function ($model) { $scope.operation.invoiceId = $model.id; $scope.operation.agreementId = $model.agreement_id.agreement_id; $scope.updateInvoiceData({'extraParams[id]': $model.id}); $scope.updateAgreementData({'extraParams[id]': $model.agreement_id.agreement_id}) .then(function () { $scope.operation.userId = $scope.agreementsList[0].user_id; $scope.updateUserData({id: $scope.operation.userId}) }); } } }; $scope.operation = { addInvoice: function addInvoice(id) { if (id && _.find($scope.operation.invoices, ['id', id]) === undefined) { $scope.operation.invoices.push(_.find($scope.invoicesList, ['id', id])); } }, removeInvoice: function removeInvoice(id) { _.remove($scope.operation.invoices, function (item) { $scope.operation.sum = $scope.operation.sum - item.amount; return item.id == id }); } }; $scope.initData = function initData() { $scope.externalPayment = {}; $scope.providerId = 'user'; $scope.currentProvider = $scope.typeaheadProviders[$scope.providerId]; $scope.operation.userId = null; $scope.operation.agreementId = null; $scope.operation.invoiceId = null; $scope.operation.invoices = []; $scope.operation.sum = 0; $scope.usersList = []; $scope.agreementsList = []; $scope.invoicesList = []; $scope.selected = ''; $scope.toastMessages = []; }; $scope.initData(); $scope.clearDocument = function clearDocument($event, $selectedIndex) { $scope.externalPayment = {}; }; $scope.clearOperation = function () { $scope.operation.invoiceId = null; $scope.operation.invoices = []; $scope.operation.sum = 0; }; $scope.invoicesSum = function () { return $scope.operation.invoices.reduce(function (sum, item) { var roundSum = Number(parseFloat(sum).toFixed(2)); $scope.operation.sum = sum = roundSum + Number(item.amount); return $scope.operation.sum }, 0); }; $scope.cleanUp = function cleanUp() { $scope.initData(); angular.element(document.querySelector('#selectedPayment')).val(''); }; $scope.invoiceById = function invoiceById(id) { return $scope.invoicesList.filter(function (item) { return item.id == id })[0]; }; $scope.externalPaymentsReload = function (externalPaymentId) { externalPayments .getById({id: externalPaymentId}) .$promise .then(function (data) { data.amount = Number(data.amount); $scope.externalPayment = data; }) }; $scope.updateOperationInvoicesData = function () { $scope.operation.invoices.forEach(function (item, key) { if (_.find($scope.operation.invoices, ['id', item.id]) && _.find($scope.invoicesList, ['id', item.id])) { $scope.operation.invoices[key] = _.find($scope.invoicesList, ['id', item.id]); } }); $scope.operation.invoices.forEach(function (item, key) { if ($scope.operation.invoices[key].paidAmount == $scope.operation.invoices[key].summa) $scope.operation.removeInvoice($scope.operation.invoices[key].id); }); }; $scope.$watch('providerId', function (newValue, oldValue) { if (newValue != oldValue) { $scope.currentProvider = $scope.typeaheadProviders[newValue]; $scope.selected = ''; } }); $scope.$watch('operation.agreementId', function (newValue, oldValue) { if (newValue != oldValue && newValue != null) { $scope.clearOperation(); $scope.updateInvoiceData({'extraParams[agreement_id]': newValue}) .then(function (data) { data.forEach(function (invoice) { if (invoice.paidAmount != invoice.summa) $scope.operation.addInvoice(invoice.id); }) }); } }); $scope.$watch('operation.userId', function (newValue, oldValue) { if (newValue != oldValue && newValue != null) { $scope.clearOperation(); $scope.updateAgreementData({'extraParams[user_id]': newValue}); } }); $scope.getTypeahead = function getTypeahead(value) { return $scope.currentProvider.provider .typeahead({ query: value }) .$promise }; $scope.onSelect = function onSelect($item, $model, $label, $event) { $scope.currentProvider.onSelect($model); }; $scope.getExternalPayment = function () { if (!$scope.externalPayment.id) { return externalPayments .create($scope.externalPayment) .$promise .then(function (data) { if (data.status && data.status == 'error') { return $q.reject(data); } else { ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'success', content: 'Нове надходження коштів успішно створено' }); $scope.formDirty = false; $scope.externalPayment = {}; return data; } }) } else { return $q.when($scope.externalPayment); } }; $scope.createOperation = function createOperation() { $scope.toastMessages = ''; ngToast.dismiss(); $scope.loaderControl.show(); var sendData = {}; sendData.userId = $scope.operation.userId; sendData.agreementId = $scope.operation.agreementId; sendData.invoices = $scope.operation.invoices.map(function (item) { return {id: item.id, amount: item.amount} }); $scope.getExternalPayment() .then( function success(data) { if (sendData.agreementId) { sendData.sourceId = data.id; sendData.amount = $scope.operation.sum; return operations .create(null, sendData) .$promise; } } ) .then( function (response) { if ($scope.externalPayment.id) $scope.externalPaymentsReload($scope.externalPayment.id); if ($scope.operation.agreementId) $scope.updateInvoiceData({'extraParams[agreement_id]': $scope.operation.agreementId}) .then( function success() { $scope.updateOperationInvoicesData(); } ) if (response) { if (response.status !== 'error') { if (response.message && response.message.length) { if (_.isArray(response.message)) { response.message.forEach(function (item) { $scope.toastMessages += item + '<br>'; }); ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'success', content: response.message }); } else { ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'success', content: 'Операція пройшла успішно' }); } } } else { ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'danger', content: response.message }) } } $scope.loaderControl.hide(); }) .catch( function (response) { if (response.message) { $scope.formDirty = true; response.message.forEach(function (item) { $scope.toastMessages += item + '<br>'; }); ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'danger', content: $scope.toastMessages, }) } else { ngToast.create({ dismissOnTimeout: false, dismissButton: true, className: 'danger', content: "Виникла помилка" }) } $scope.loaderControl.hide(); }); }; $scope.updateUserData = function updateUserSelect(params) { var defer = $q.defer(); user .query(params) .$promise .then(function (data) { $scope.usersList = data; defer.resolve(data); }); return defer.promise; }; $scope.updateAgreementData = function updateAgreementSelect(params) { var defer = $q.defer(); agreements .list(params) .$promise .then(function (data) { $scope.agreementsList = data.rows; defer.resolve(data.rows); }); return defer.promise; }; $scope.updateInvoiceData = function updateInvoiceData(params) { var defer = $q.defer(); invoices .list(params) .$promise .then(function (data) { $scope.invoicesList = data.rows.map(function (item) { item.paidAmount = 0; item.summa = Number(item.summa); item.internalPayment.forEach(function (pays) { item.paidAmount = Number(item.paidAmount) + Number(pays.summa); }); item.amount = item.summa - item.paidAmount; return item; }); defer.resolve(data.rows); }); return defer.promise; }; $scope.showAgreement = function showAgreement(id) { if (id) { $state.go('accountant/agreement/', {agreementId: id}); } }; $scope.showInvoice = function showInvoice(id) { if (id) { $state.go('accountant/invoice/', {invoiceId: id}); } }; }]) .controller('companiesCtrl', function ($scope, NgTableParams, companiesService) { $scope.changePageHeader('Компанії'); $scope.companiesTable = new NgTableParams({sorting: {}}, { getData: function (params) { return companiesService .list(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); }) .controller('oneCompanyCtrl', function ($scope, $state) { $scope.changePageHeader($state.params.header); if ($state.is('accountant.company.view')) { $state.go('.card'); } $scope.companyId = $state.params.companyId; $scope.representativeId = $state.params.representativeId; }) .controller('representativesCtrl', function ($scope, NgTableParams, $resource) { $scope.changePageHeader('Представники'); $scope.companyRepresentativesTable = new NgTableParams({ sorting: {}, }, { getData: function (params) { return $resource(basePath + '/_teacher/_accountant/representative/getCompanyRepresentativesList').get(params.url()).$promise.then(function (data) { params.total(data.count); // return data.rows; return data.data; }); } }); $scope.representativesTable = new NgTableParams({ sorting: {}, }, { getData: function (params) { return $resource(basePath + '/_teacher/_accountant/representative/getRepresentativesList').get(params.url()).$promise.then(function (data) { params.total(data.count); return data.rows; }); } }); }) .controller('oneRepresentativeCtrl', function ($scope, $http, $state) { $scope.changePageHeader('Представник'); $scope.$watch('newRepresentative', function () { if ($scope.newRepresentative) $jq('#typeaheadRepresentative').css('background-color', '#eee'); else $jq('#typeaheadRepresentative').css('background-color', 'inherit'); }); $scope.addRepresentative = function (url) { var error = false; if ($jq('#representative').val() == 0 && !($jq('[name="full_name"]').val())) { bootbox.alert('Виберіть існуючого представника зі списку або додайте нового.'); error = true; } if ($jq('#companyId').val() == 0) { bootbox.alert('Виберіть існуючу компанію зі списку або створіть нову'); error = true; } if (!error) { $http({ url: url, method: "POST", data: $jq.param({ representative: $jq('#representative').val(), fullName: $jq('[name="full_name"]').val(), position: $jq('[name="position"]').val(), company: $jq('#companyId').val(), order: $jq('[name="order"]').val(), }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { bootbox.alert(response.data, function () { $state.go("accountant/representative", {}, {reload: true}); }); }, function errorCallback() { bootbox.alert("Операцію не вдалося виконати."); }); } } }) .controller('operationTypeCtrl', function ($scope, $http, $resource, NgTableParams) { $jq('#operationTypes').DataTable({ language: { "url": "https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Ukranian.json" } } ); $scope.operationTypesTable = new NgTableParams({ sorting: {}, }, { getData: function (params) { return $resource(basePath + '/_teacher/_accountant/operationType/loadList').get(params.url()).$promise.then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.deleteOperationType = function (id) { bootbox.confirm('Ви впевнені що хочете видалити тип проплати ' + id + '?', function (result) { if (result) { $http({ method: 'POST', url: basePath + '/_teacher/_accountant/operationType/delete', data: $jq.param({id: id}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }) .success(function (data) { bootbox.alert('Тип проплат видалений.', function () { $scope.operationTypesTable.reload(); }) }) .error(function () { bootbox.alert('Операцію не вдалося виконати.') }) } }) } }) .controller('externalSourcesTableCtrl', function ($scope, externalSourcesService, NgTableParams, $http) { $scope.changePageHeader('Джерела зовнішніх коштів'); $scope.externalSourcesParams = new NgTableParams({}, { getData: function (params) { return externalSourcesService .getExternalSourcesList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.deleteExternalSources = function (id) { bootbox.confirm('Ви впевнені що хочете видалити зовнішнє джерело коштів?', function (result) { if (result) { $http({ url: basePath + '/_teacher/_accountant/externalSources/delete', method: "POST", data: $jq.param({id: id}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.externalSourcesParams.reload(); }, function errorCallback() { bootbox.alert("Операцію не вдалося виконати."); }); } }); } }) .controller('cancelReasonTypeCtrl', function ($http, $scope, NgTableParams, auditorService) { $scope.changePageHeader('Додати причину відміни проплат'); $scope.cancelReasonTypeTableParams = new NgTableParams({}, { getData: function (params) { return auditorService .cancelReasonTypeList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.deleteCancelReasonTypes = function (id) { bootbox.confirm('Ви впевнені що хочете видалити причину відміни проплат?', function (result) { if (result != null) { $http({ url: basePath + '/_teacher/_auditor/cancelReasonType/delete', method: "POST", data: $jq.param({id: id}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback() { $scope.cancelReasonTypeTableParams.reload(); }, function errorCallback() { bootbox.alert("Операцію не вдалося виконати."); }); } else { bootbox.alert("Операцію не вдалося виконати."); } }); } }) .controller('paymentsSchemaCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) { $scope.schemeType = defineSchemaType($stateParams.schemeType); }]) .controller('addPaymentsSchemaCtrl', [ '$scope', '$stateParams', 'ngToast', 'userService', 'courseService', 'moduleService', 'paymentSchemaService', function ($scope, $stateParams, ngToast, user, course, module, paymentSchema) { $scope.schemeType = defineSchemaType($stateParams.schemeType); $scope.paymentSchema = { educationForm: 1 }; $scope.user = { isSelect: $scope.schemeType === 'user', typeahead: function getUserTypeahead(value) { return user.typeahead({query: value}).$promise }, label: function (user) { return user ? ((user.firstName || '' ) + ' ' + (user.middleName || '') + ' ' + (user.secondName || '') + ', ' + (user.email || '')) : ''; }, onSelect: selectFromTypeahead.bind(null, $scope.paymentSchema, 'userId', 'id') }; $scope.course = { isSelect: $scope.schemeType === 'user' || $scope.schemeType === 'course', typeahead: function getCourseTypeahead(value) { return course.typeahead({query: value}).$promise }, label: function (course) { return course ? ((course.title_ua || '' ) + ', ' + (course.language || '')) : ''; }, onSelect: selectFromTypeahead.bind(null, $scope.paymentSchema, 'courseId', 'course_ID') }; $scope.module = { isSelect: $scope.schemeType === 'user' || $scope.schemeType === 'module', typeahead: function getModuleTypeahead(value) { return module.typeahead({query: value}).$promise }, label: function (module) { return module ? ((module.title_ua || '' ) + ', ' + (module.language || '')) : ''; }, onSelect: selectFromTypeahead.bind(null, $scope.paymentSchema, 'moduleId', 'module_ID') }; $scope.startDateOptions = new DateOptions(); $scope.endDateOptions = new DateOptions(); $scope.createSchema = function () { paymentSchema .create($scope.paymentSchema) .$promise .then(function (data) { if (data.message === 'OK') { ngToast.create({ content: 'Схема створена успішно' }) } else { ngToast.create({ className: 'danger', content: "Під час створення схеми виникла помилка." }) } }); } } ] ) .controller('externalSourceCtrl', function ($scope, $http, $stateParams, externalSourcesService) { $scope.loadExternalSourceData = function (id) { externalSourcesService.externalSource({'id': id}).$promise .then(function successCallback(response) { $scope.source = response; $scope.source.cash = Number($scope.source.cash); }, function errorCallback() { bootbox.alert("Отримати дані джерела коштів не вдалося"); }); }; if ($stateParams.id) { $scope.modelId = $stateParams.id; $scope.loadExternalSourceData($scope.modelId); } $scope.sendExternalSourceForm = function (scenario, name, cash, modelId) { if (scenario == 'create') $scope.createExternalSource(name, cash); else if (scenario == 'update') $scope.updateExternalSource(modelId, name, cash); }; $scope.clearForm = function () { $scope.source.name = null; $scope.externalSourceForm.name.$setPristine(); }; $scope.createExternalSource = function (name, cash) { $http({ url: basePath + '/_teacher/_accountant/externalSources/createExternalSource', method: "POST", data: $jq.param({ name: name, cash: cash }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.addUIHandlers(response.data); $scope.clearForm(); }, function errorCallback() { bootbox.alert("Створити зовнішнє джерело не вдалося. Помилка сервера."); }); }; $scope.updateExternalSource = function (id, name, cash) { $http({ url: basePath + '/_teacher/_accountant/externalSources/updateExternalSource', method: "POST", data: $jq.param({ id: id, name: name, cash: cash }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.addUIHandlers(response.data); }, function errorCallback() { bootbox.alert("Оновити зовнішнє джерело не вдалося. Помилка сервера."); }); }; }) .controller('datePickerCtrl', function ($scope) { $scope.startDateOptions = new ExternalPaymentDateOptions(); }) .controller('paymentsSchemaTemplateTableCtrl', ['$scope', '$stateParams', 'NgTableParams', 'paymentSchemaService', '$http', '$attrs', function ($scope, $stateParams, NgTableParams, paymentSchemaService, $http, $attrs) { $scope.changePageHeader('Шаблони схем'); $scope.schemesTemplateTableParams = new NgTableParams({organization: $attrs.organization}, { getData: function (params) { return paymentSchemaService .schemesTemplatesList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); }]) .controller('paymentsSchemesTableCtrl', ['$scope', 'NgTableParams', 'paymentSchemaService', '$http', '$attrs', function ($scope, NgTableParams, paymentSchemaService, $http, $attrs) { $scope.changePageHeader('Список застосованих шаблонів'); $scope.mainTemplateTableParams = new NgTableParams({}, { getData: function (params) { return paymentSchemaService .mainAppliedTemplatesList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.servicesTemplateTableParams = new NgTableParams({organization: $attrs.organization}, { getData: function (params) { return paymentSchemaService .servicesAppliedTemplatesList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.usersTemplateTableParams = new NgTableParams({ sorting: {id: "desc"}, organization: $attrs.organization }, { getData: function (params) { return paymentSchemaService .usersAppliedTemplatesList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.cancelPaymentScheme = function (id) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/cancelPaymentScheme', method: "POST", data: $jq.param({ id: id, }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback() { $scope.servicesTemplateTableParams.reload(); $scope.usersTemplateTableParams.reload(); }, function errorCallback() { bootbox.alert("Скасувати не вдалося"); }); } }]) .controller('paymentsSchemaTemplateCtrl', ['$scope', 'lodash', '$http', '$state', '$stateParams','companiesService', function ($scope, _, $http, $state, $stateParams, companiesService) { $scope.changePageHeader('Створення та редагування шаблонів схем'); $scope.loadSchemesTemplate = function (templateId) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getSchemesTemplate', method: "POST", data: $jq.param({ templateId: templateId, }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.schemes = response.data.schemes; $scope.schemes.forEach(function (item) { item.discount = Number(item.discount); item.loan = Number(item.loan); item.pay_count = Number(item.pay_count); item.contract = Boolean(item.contract); }); $scope.template = { id: response.data.id, name_ua: response.data.template_name_ua, name_ru: response.data.template_name_ru, name_en: response.data.template_name_en, description_ua: response.data.description_ua, description_ru: response.data.description_ru, description_en: response.data.description_en, duration: Number(response.data.duration), schemes: $scope.schemes, start_date: response.data.start_date ? new Date(response.data.start_date) : null, company: response.data.checkingAccount?response.data.checkingAccount.corporate_entity:'', id_checking_account: response.data.checkingAccount?response.data.checkingAccount.id:'', }; $scope.companyList(); }, function errorCallback() { bootbox.alert("Отримати дані шаблона схем не вдалося"); }); }; $scope.companyList = function () { companiesService.list() .$promise .then(function (response) { $scope.companies = response.rows; if($scope.template.id_checking_account){ $scope.loadCheckingAccounts($scope.template.id_checking_account); } }) .catch(function () { bootbox.alert('Помилка завантаження данних'); }); }; $scope.loadCheckingAccounts = function (companyId) { companiesService.companyCheckingAccountsList({companyId:companyId}) .$promise .then(function (response) { $scope.checkingAccounts = response; }) .catch(function () { bootbox.alert('Помилка завантаження данних'); }); } if ($stateParams.id) { $scope.loadSchemesTemplate($stateParams.id); }else{ $scope.companyList(); } $scope.schemes = [ {pay_count: 1, discount: 30, loan: 0, name: 'Проплата наперед', contract: false}, {pay_count: 2, discount: 10, loan: 0, name: '2 проплати', contract: false}, {pay_count: 4, discount: 8, loan: 0, name: '4 проплати', contract: false}, {pay_count: 12, discount: 0, loan: 0, name: 'помісячно', contract: false}, {pay_count: 24, discount: 0, loan: 24, name: '24 проплати', contract: true}, {pay_count: 36, discount: 0, loan: 24, name: '36 проплат', contract: true}, {pay_count: 48, discount: 0, loan: 24, name: '48 проплат', contract: true}, {pay_count: 60, discount: 0, loan: 24, name: '60 проплат', contract: true}, ]; $scope.template = { name: '', schemes: $scope.schemes, duration: 12, } $scope.payCount = [ {value: 1, name: 'Проплата наперед'}, {value: 2, name: '2 проплати'}, {value: 3, name: '3 проплати'}, {value: 4, name: '4 проплати'}, {value: 6, name: '6 проплат'}, {value: 9, name: '9 проплат'}, {value: 12, name: 'помісячно'}, {value: 24, name: '24 проплати'}, {value: 36, name: '36 проплат'}, {value: 48, name: '48 проплат'}, {value: 60, name: '60 проплат'}, ] $scope.updateScheme = function (payCount, index) { $scope.schemes[index]['name'] = _.find($scope.payCount, ['value', payCount]).name; if (payCount > 12) { $scope.schemes[index]['discount'] = 0; } else { $scope.schemes[index]['loan'] = 0; } }; $scope.operation = { addScheme: function addScheme() { $scope.schemes.push({pay_count: 1, discount: 0, loan: 0, name: 'Проплата наперед'}); }, removeScheme: function removeScheme(index) { _($scope.schemes) .splice(index, 1) .value(); } }; $scope.createTemplate = function (template) { var check = true; var msgError = ''; if (_.filter(template.schemes, ['pay_count', 1]).length == 0) { msgError = 'Шаблон схем обов\'язково має містити схему "проплата наперід"'; check = false; } template.schemes.forEach(function (item) { if (_.filter(template.schemes, ['pay_count', item.pay_count]).length > 1) { msgError = 'Шаблон схем не може містити схеми з однаковою кількість проплат'; check = false; return false; } }); if (check) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/createSchemeTemplate', method: "POST", data: $jq.param({ template: JSON.stringify(template), }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { bootbox.alert(response.data, function () { $state.go("accountant/paymentSchemas/schemas/template", {}, {reload: true}); }); }, function errorCallback() { bootbox.alert("Створити шаблон схем не вдалося. Помилка сервера."); }); } else { bootbox.alert(msgError); } }; $scope.updateTemplate = function (template) { var check = true; var msgError = ''; if (_.filter(template.schemes, ['pay_count', 1]).length == 0) { msgError = 'Шаблон схем обов\'язково має містити схему "проплата наперід"'; check = false; } template.schemes.forEach(function (item) { if (_.filter(template.schemes, ['pay_count', item.pay_count]).length > 1) { msgError = 'Шаблон схем не може містити схеми з однаковою кількість проплат'; check = false; return false; } }); if (check) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/updateSchemeTemplate', method: "POST", data: $jq.param({ template: JSON.stringify(template), }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { bootbox.alert(response.data, function () { $state.reload(); }); }, function errorCallback() { bootbox.alert("Оновити шаблон схем не вдалося. Помилка сервера."); }); } else { bootbox.alert(msgError); } }; $scope.startDateOptions = new DateOptions(); }]) .controller('paymentsSchemaTemplateApplyCtrl', ['$scope', 'lodash', '$http', '$state', '$stateParams', 'paymentSchemaService', '$q', '$rootScope', function ($scope, _, $http, $state, $stateParams, paymentSchemaService, $q, $rootScope) { if ($stateParams.id) { $scope.changePageHeader('Редагування застосованого шаблону схем'); } else { $scope.changePageHeader('Застосування шаблону схем'); } $scope.paymentSchema = {}; $scope.today = function () { var nowDate = new Date(); nowDate.setHours(0, 0, 0, 0); $scope.paymentSchema.startDate = nowDate; }; $scope.today(); $scope.loadService = function (id) { if (id) { var promise = $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getServiceContent', method: "POST", data: $jq.param({ serviceId: id, }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { return response.data; }, function errorCallback() { bootbox.alert("Вибачте, виникла помилка при завантажені сервісу."); }); return promise; } }; $scope.loadUserName = function (id) { if (id) { var promise = $http({ url: basePath + '/_teacher/user/loadUserName', method: "POST", data: $jq.param({ userId: id, }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { return response.data; }, function errorCallback() { bootbox.alert("Вибачте, виникла помилка при завантажені ім'я користувача."); }); return promise; } }; $scope.loadTemplates = function () { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getSchemesTemplatesList?organization=1', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.templates = response.data; if ($stateParams.request) { paymentSchemaService.getSchemesRequest({id_message: $stateParams.request}).$promise.then(function (response) { $q.all([$scope.loadUserName(response.id_user), $scope.loadService(response.id_service)]).then(function (results) { $scope.userSelected = results[0]; $scope.paymentSchema = { userId: response.id_user, courseId: results[1]['courseId'], moduleId: results[1]['moduleId'], template: _.find($scope.templates, ['id', response.id_schema_template]), serviceType: 1, request: $stateParams.request, } if ($scope.paymentSchema.courseId) { $http.get(basePath + "/course/getCourseTitle/?id=" + $scope.paymentSchema.courseId).then(function (response) { $scope.selectedCourse = response.data; }); } if ($scope.paymentSchema.moduleId) { $http.get(basePath + "/module/getModuleTitle/?id=" + $scope.paymentSchema.moduleId).then(function (response) { $scope.selectedModule = response.data; }); } }); }); } // else if($stateParams.id){ // $scope.loadAppliedTemplateData($stateParams.id); // } }, function errorCallback() { bootbox.alert("Отримати шаблони схем не вдалося"); }); }; $scope.loadTemplates(); $scope.startDateOptions = new DateOptions(); $scope.endDateOptions = new DateOptions(); $scope.onSelectCourse = function ($item) { $scope.paymentSchema['courseId'] = $item.id; $scope.paymentSchema.serviceType = $scope.services[0].value; $scope.paymentSchema.moduleId = null; $scope.selectedModule = null; }; $scope.reloadCourse = function () { $scope.paymentSchema['courseId'] = null; }; $scope.onSelectModule = function ($item) { $scope.paymentSchema['moduleId'] = $item.id; $scope.paymentSchema.serviceType = $scope.services[1].value; $scope.paymentSchema.courseId = null; $scope.selectedCourse = null; }; $scope.reloadModule = function () { $scope.paymentSchema['moduleId'] = null; }; $scope.onSelectUser = function ($item) { $scope.paymentSchema['userId'] = $item.id; }; $scope.reloadUser = function () { $scope.paymentSchema['userId'] = null; }; //load service title $scope.loadModuleTitle = function (moduleId) { $http.get(basePath + "/module/getModuleTitle/?id=" + moduleId).then(function (response) { $scope.selectedModule = response.data; }); }; $scope.loadCourseTitle = function (courseId) { $http.get(basePath + "/course/getCourseTitle/?id=" + courseId).then(function (response) { $scope.selectedCourse = response.data; }); }; $scope.loadAppliedTemplateData = function (id) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getPaymentSchemeData', method: "POST", data: $jq.param({id: id}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $q.all([$scope.loadUserName(response.data.userId), $scope.loadService(response.data.serviceId)]).then(function (results) { $scope.userSelected = results[0]; $scope.paymentSchema = { id: response.data.id, userId: response.data.userId, courseId: results[1]['courseId'], moduleId: results[1]['moduleId'], serviceType: Number(response.data.serviceType ? response.data.serviceType : 1), template: _.find($scope.templates, ['id', response.data.id_template]), startDate: response.data.startDate ? new Date(response.data.startDate) : null, endDate: response.data.endDate ? new Date(response.data.endDate) : null, }; if ($scope.paymentSchema.courseId) { $scope.loadCourseTitle($scope.paymentSchema.courseId); } if ($scope.paymentSchema.moduleId) { $scope.loadModuleTitle($scope.paymentSchema.moduleId); } }); }, function errorCallback() { bootbox.alert("Отримати дані акційної схеми не вдалося"); }); }; $scope.sendFormApplyTemplate = function (scenario) { if (scenario == 'create') $scope.applyTemplate(); else $scope.updateAppliedTemplate(); }; $scope.applyTemplate = function () { paymentSchemaService .applyTemplate($scope.paymentSchema) .$promise .then(function (data) { if (data.message === 'OK') { bootbox.alert('Шаблон схем успішно застосовано', function () { if ($stateParams.request) { paymentSchemaService.getActualSchemesRequests().$promise.then(function (response) { $rootScope.countOfActualSchemesRequests = response[0]; $state.go("accountant/schemesrequests", {}, {reload: true}); }); } else { $state.reload(); } }); } else { bootbox.alert(data.reason); } }) .catch(function (error) { bootbox.alert(error.data.reason); }); }; $scope.updateAppliedTemplate = function () { // paymentSchemaService // .updateAppliedTemplate($scope.paymentSchema) // .$promise // .then(function (data) { // if (data.message === 'OK') { // bootbox.alert('Шаблон схем успішно оновлено', function () { // $state.reload(); // }); // } else { // bootbox.alert(data.reason); // } // }); }; $scope.services = [ { name: 'Курси', value: 1 }, { name: 'Модулі', value: 2 } ]; }]) .controller('documentsCtrl', ['$scope', '$stateParams', 'NgTableParams', 'accountantService', '$http', '$attrs', function ($scope, $stateParams, NgTableParams, accountantService, $http, $attrs) { $scope.changePageHeader('Копії документів'); $scope.docStatus = [{id: 0, title: 'не перевірені'}, {id: 1, title: 'перевірені'}]; $scope.documentsTableParams = new NgTableParams({organization: $attrs.organization}, { getData: function (params) { return accountantService .documentsList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.createDocumentsFolder = function () { $http({ method: 'POST', url: basePath + '/_teacher/_accountant/accountant/createDocumentsFolder', headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(function successCallback() { bootbox.alert("Папку створено"); }, function errorCallback() { bootbox.alert("Операцію не вдалося виконати"); }); } $scope.getDocument = function (documentID) { bootbox.alert({ message: "<img width='100%' src='" + basePath + '/_teacher/_accountant/accountant/getDocument?id=' + documentID + "'>", size: 'large' }) } }]) .controller('promotionPaymentsSchemesTableCtrl', ['$scope', 'NgTableParams', 'paymentSchemaService', '$http', '$attrs', function ($scope, NgTableParams, paymentSchemaService, $http, $attrs) { $scope.changePageHeader('Список акцій застосованих до сервісів'); $scope.promotionPaymentsSchemaTableParams = new NgTableParams({organization: $attrs.organization}, { getData: function (params) { return paymentSchemaService .promotionPaymentsSchemaList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.cancelPromotionPaymentScheme = function (id) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/cancelPromotionPaymentScheme', method: "POST", data: $jq.param({ id: id, }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback() { $scope.promotionPaymentsSchemaTableParams.reload(); }, function errorCallback() { bootbox.alert("Скасувати не вдалося"); }); } }]) .controller('displayPromotionSchemesCtrl', ['$scope', 'lodash', '$http', '$state', '$stateParams', 'paymentSchemaService', '$filter', function ($scope, _, $http, $state, $stateParams, paymentSchemaService, $filter) { $scope.paymentSchema = {}; $scope.today = function () { var nowDate = new Date(); nowDate.setHours(0, 0, 0, 0); $scope.paymentSchema.showDate = nowDate; $scope.paymentSchema.startDate = nowDate; }; $scope.today(); $scope.loadPromotionData = function (id) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getPromotionSchemeData', method: "POST", data: $jq.param({id: id}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.paymentSchema = { id: response.data.id, courseId: response.data.courseId, moduleId: response.data.moduleId, template: _.find($scope.templates, ['id', response.data.id_template]), serviceType: Number(response.data.serviceType ? response.data.serviceType : 1), showDate: response.data.showDate ? new Date(response.data.showDate) : null, startDate: response.data.startDate ? new Date(response.data.startDate) : null, endDate: response.data.endDate ? new Date(response.data.endDate) : null, } if (response.data.courseId) { $scope.loadCourseTitle(response.data.courseId); } if (response.data.moduleId) { $scope.loadModuleTitle(response.data.moduleId); } }, function errorCallback() { bootbox.alert("Отримати дані акційної схеми не вдалося"); }); }; if ($stateParams.id) { $scope.changePageHeader('Редагування акційної схеми'); } else { $scope.changePageHeader('Відображення акційних схем для сервісів'); } $scope.loadTemplates = function () { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/getSchemesTemplatesList?organization=1', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.templates = response.data; if ($stateParams.id) { $scope.loadPromotionData($stateParams.id); } }, function errorCallback() { bootbox.alert("Отримати шаблони схем не вдалося"); }); }; $scope.loadTemplates(); $scope.sendFormPromotion = function (scenario) { if (scenario == 'create') $scope.applyPromotionTemplate(); else $scope.updatePromotionTemplate(); }; $scope.startShowOptions = new DateOptions(); $scope.startDateOptions = new DateOptions(); $scope.endDateOptions = new DateOptions(); $scope.onSelectCourse = function ($item) { $scope.paymentSchema['courseId'] = $item.id; }; $scope.reloadCourse = function () { $scope.paymentSchema['courseId'] = null; }; $scope.onSelectModule = function ($item) { $scope.paymentSchema['moduleId'] = $item.id; }; $scope.reloadModule = function () { $scope.paymentSchema['moduleId'] = null; }; //load service title $scope.loadModuleTitle = function (moduleId) { $http.get(basePath + "/module/getModuleTitle/?id=" + moduleId).then(function (response) { $scope.selectedModule = response.data; }); }; $scope.loadCourseTitle = function (courseId) { $http.get(basePath + "/course/getCourseTitle/?id=" + courseId).then(function (response) { $scope.selectedCourse = response.data; }); }; $scope.applyPromotionTemplate = function () { paymentSchemaService .applyPromotionTemplate($scope.paymentSchema) .$promise .then(function (data) { if (data.message === 'OK') { bootbox.alert('Акційний шаблон схем успішно застосовано', function () { $state.reload(); }); } else { bootbox.alert(data.reason); } }); } $scope.updatePromotionTemplate = function () { paymentSchemaService .updatePromotionTemplate($scope.paymentSchema) .$promise .then(function (data) { if (data.message === 'OK') { bootbox.alert('Акційний шаблон схем успішно оновлено', function () { $state.reload(); }); } else { bootbox.alert(data.reason); } }); } $scope.services = [ { name: 'Курси', value: 1 }, { name: 'Модулі', value: 2 } ]; }]) .controller('schemesRequestsTableCtrl', ['$scope', '$stateParams', 'NgTableParams', 'paymentSchemaService', '$http', '$rootScope', function ($scope, $stateParams, NgTableParams, paymentSchemaService, $http, $rootScope) { $scope.changePageHeader('Запити на застосування схем проплат'); $scope.status = [ {id: '0', title: 'нові'}, {id: '1', title: 'в процесі'}, {id: '2', title: 'затвердженні'}, {id: '3', title: 'відхилені'}, {id: '4', title: 'нові та в процесі'} ]; $scope.schemesRequestsTableParams = new NgTableParams({filter: {'status': '4'}}, { getData: function (params) { return paymentSchemaService .schemesRequestsList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.setRequestStatus = function (idMessage, status) { $http({ url: basePath + '/_teacher/_accountant/paymentSchema/setRequestStatus', method: "POST", data: $jq.param({idMessage: idMessage, status: status}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback() { paymentSchemaService.getActualSchemesRequests().$promise.then(function (response) { $rootScope.countOfActualSchemesRequests = response[0]; $scope.schemesRequestsTableParams.reload(); }); }, function errorCallback() { bootbox.alert("Змінити статус не вдалося"); }); }; $scope.rejectRequest = function (idMessage) { bootbox.dialog({ title: "Ти впевнений, що хочеш відхилити запит?", message: '<div class="panel-body"><div class="row"><form role="form" name="rejectMessage"><div class="form-group col-md-12">' + '<textarea class="form-control" style="resize: none" rows="6" id="rejectMessageText" ' + 'placeholder="тут можна залишити коментар, причина відхилення запиту на застосування схеми проплат, яка надійде користувачу на його email"></textarea>' + '</div></form></div></div>', buttons: { success: { label: "Підтвердити", className: "btn btn-primary", callback: function () { var comment = $jq('#rejectMessageText').val(); paymentSchemaService.rejectSchemesRequest({ id: idMessage, comment: comment }).$promise.then(function () { $scope.schemesRequestsTableParams.reload(); }); paymentSchemaService.getActualSchemesRequests().$promise.then(function (response) { $rootScope.countOfActualSchemesRequests = response[0]; }); } }, cancel: { label: "Скасувати", className: "btn btn-default", callback: function () { } } } } ); }; $scope.setComment = function (idMessage, oldComment) { if (typeof oldComment == 'undefined') oldComment = ''; bootbox.dialog({ title: "Коментар до запиту", message: '<div class="panel-body"><div class="row"><form role="form" name="commentMessage"><div class="form-group col-md-12">' + '<textarea class="form-control" style="resize: none" rows="6" id="commentMessageText" ' + 'placeholder="тут можна залишити коментар до запиту, котрий бачить лише бухгалтер">' + oldComment + '</textarea>' + '</div></form></div></div>', buttons: { success: { label: "Підтвердити", className: "btn btn-primary", callback: function () { var comment = $jq('#commentMessageText').val(); paymentSchemaService.setRequestComment({ id_message: idMessage, comment: comment }).$promise.then(function () { $scope.schemesRequestsTableParams.reload(); }); } }, cancel: { label: "Скасувати", className: "btn btn-default", callback: function () { } } } } ); }; }]) .controller('userAgreementsCtrl', ['$scope', 'agreementsService', 'NgTableParams', 'lodash', '$stateParams', 'paymentSchemaService', 'agreementsInformation', function ($scope, agreements, NgTableParams, _, $stateParams, paymentSchema, agreementsInformation) { $scope.changePageHeader('Договори студента'); $scope.currentDate = currentDate; $scope.userAgreementsTableParams = new NgTableParams({ user: $stateParams.studentId, sorting: {create_date: "desc"} }, { getData: function (params) { return agreements .userAgreements(params.url()) .$promise .then(function (data) { params.total(data.count); agreementsInformation.setInformation(data); return data.rows; }); } }); $scope.getSchemas = paymentSchema .query() .$promise .then(function (data) { return data.map(function (item) { return {id: item.pay_count, title: item.title_ua} }) }); }]) .controller('trainerUsersAgreementsCtrl', ['$scope', 'agreementsService', 'NgTableParams', 'lodash', '$stateParams', 'paymentSchemaService', 'agreementsInformation', function ($scope, agreements, NgTableParams, _, $stateParams, paymentSchema, agreementsInformation) { $scope.changePageHeader('Договори студентів закріплених за тренером'); $scope.currentDate = currentDate; $scope.trainerUsersAgreementsTableParams = new NgTableParams({ user: $stateParams.studentId, sorting: {create_date: "desc"} }, { getData: function (params) { return agreements .trainerUsersAgreements(params.url()) .$promise .then(function (data) { params.total(data.count); agreementsInformation.setInformation(data); return data.rows; }); } }); $scope.getSchemas = paymentSchema .query() .$promise .then(function (data) { return data.map(function (item) { return {id: item.pay_count, title: item.title_ua} }) }); $scope.getAgreementStatuses = paymentSchema .statuses() .$promise .then(function (data) { return data.map(function (item) { return {id: item.id, title: item.title_ua} }) }); }]) .controller('agreementsRequestsTableCtrl', ['$scope', '$stateParams', 'NgTableParams', 'agreementsService', '$http', '$rootScope', function ($scope, $stateParams, NgTableParams, agreementsService, $http, $rootScope) { $scope.changePageHeader('Запити на затвердження паперових договорів'); $scope.action = [ {id: '0', title: 'нові'}, {id: '2', title: 'затвердженні'}, {id: '1', title: 'відхилені'}, ]; $scope.agreementsRequestsTableParams = new NgTableParams({filter: {'action': '0'}}, { getData: function (params) { return agreementsService .agreementsRequestsList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.rejectAgreementRequest = function (id) { bootbox.dialog({ title: "Ти впевнений, що хочеш відхилити запит?", message: '<div class="panel-body"><div class="row"><form role="form" name="rejectMessage"><div class="form-group col-md-12">' + '<textarea class="form-control" style="resize: none" rows="6" id="rejectMessageText" ' + 'placeholder="тут можна залишити коментар, причина відхилення запиту на затвердження договору, яка надійде користувачу на його email"></textarea>' + '</div></form></div></div>', buttons: { success: { label: "Підтвердити", className: "btn btn-primary", callback: function () { var comment = $jq('#rejectMessageText').val(); agreementsService.rejectAgreementRequest({ id: id, comment: comment }).$promise.then(function () { $scope.agreementsRequestsTableParams.reload(); }); } }, cancel: { label: "Скасувати", className: "btn btn-default", callback: function () { } } } } ); }; }]) .controller('writtenAgreementsTableCtrl', ['$scope', '$stateParams', 'NgTableParams', 'agreementsService', '$http', '$rootScope', function ($scope, $stateParams, NgTableParams, agreementsService, $http, $rootScope) { $scope.changePageHeader('Паперові договори'); $scope.status = [ {id: '1', title: 'затвердженні і згенеровані(не роздруковані)'}, {id: '2', title: 'очікують затвердження користувача'}, {id: '3', title: 'затверджені користувачем, але не згенеровані'}, {id: '4', title: 'роздруковані'}, ]; $scope.writtenAgreementsTableParams = new NgTableParams({filter: {'status': '3'}, sorting: { updatedAt: 'desc' },}, { getData: function (params) { return agreementsService .writtenAreementsList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); }]) .controller('writtenAgreementsAppliedTableCtrl', ['$scope', '$stateParams', 'NgTableParams', 'agreementsService', '$http', '$rootScope', function ($scope, $stateParams, NgTableParams, agreementsService, $http, $rootScope) { $scope.changePageHeader('Застосовані паперові договори до сервісів'); $scope.writtenAgreementsAppliedTableParams = new NgTableParams({}, { getData: function (params) { return agreementsService .writtenAreementsAppliedList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); $scope.cancelAppliedAgreement = function (id) { bootbox.confirm('Ти впевнений, що хочеш скасувати шаблон?', function (result) { if (result) { agreementsService.cancelAppliedAgreement({service_id: id}).$promise .then(function (data) { $scope.writtenAgreementsAppliedTableParams.reload(); }); } }); }; $scope.loadTemplates = function () { $http({ url: basePath + '/_teacher/_accountant/template/GetTemplatesList', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.templates = response.data; }, function errorCallback() { bootbox.alert("Отримати шаблони схем не вдалося"); }); }; $scope.loadTemplates(); $scope.formData = {}; $scope.clearInputs=function () { $scope.formData.service_id=null; $scope.serviceSelected=null; }; $scope.onSelectService = function ($item) { $scope.formData.service_id = $item.id; }; $scope.reloadService = function(){ $scope.formData.service_id=null; }; $scope.setWrittenAgreementTemplateForService = function(data){ if (data.written_agreement_template_id && data.service_id){ agreementsService .applyWrittenAgreementForService(data) .$promise .then(function successCallback(response) { $scope.writtenAgreementsAppliedTableParams.reload(); $scope.clearInputs(); }, function errorCallback(response) { console.log(response); bootbox.alert("Операцію не вдалося виконати"); }); }else{ bootbox.alert("Користувача або модуль не вибрано"); } } }]) .controller('writtenAgreementViewCtrl', ['$scope', 'agreementsService', '$stateParams','$state', function ($scope, agreementsService, $stateParams, $state) { $scope.date = new Date(); $scope.options={}; $scope.editorOptionsAgreement = { toolbar: 'agreement', height: '1000' }; $scope.getAgreementTemplate = function(id){ agreementsService .getAgreementTemplate({agreementId: id, id: $scope.options.selectedTemplate}) .$promise .then(function successCallback(response) { $scope.options.selectedTemplate= response.data.id; $scope.agreementTemplate = response.data.template; }, function errorCallback() { bootbox.alert("Шаблон договору отримати не вдалося"); }); } $scope.getAgreementRequestStatus = function (request) { agreementsService .getAgreementRequestStatus({'idMessage': request}) .$promise .then(function (data) { $scope.agreementRequestStatus = data.status; }); }; if($stateParams.request){ $scope.getAgreementRequestStatus($stateParams.request); } $scope.writtenAgreementPreview = function (agreementId) { agreementsService .getWrittenAgreementData({'id': agreementId}) .$promise .then(function (data) { $scope.getAgreementTemplate(agreementId); $scope.writtenAgreement = data; if($stateParams.request){ $scope.getAgreementRequestStatus($stateParams.request); } }); }; $scope.checkAgreementPdf = function (agreementId) { agreementsService .checkAgreementPdf({agreementId:agreementId}) .$promise .then(function (response) { $scope.actualAgreement=response.data; if ($scope.actualAgreement) { if (parseInt($scope.actualAgreement.checked)) { $scope.pdfAgreement=true; }else{ $scope.pdfAgreement=false; $scope.agreementTemplate = $scope.actualAgreement.html_for_edit; } }else{ $scope.pdfAgreement=false; } $scope.writtenAgreementPreview(agreementId); }); }; $scope.getAgreementContract = function (agreementId) { agreementsService .getAgreementContract({'id': agreementId}) .$promise .then(function (response) { $scope.contract = response; }); }; $scope.checkWrittenAgreement = function (data, agreementTemplate) { agreementsService .approveAgreement( { 'idRequest': $stateParams.request, 'writtenAgreementId': $stateParams.id, 'sessionTime': data.sessionTime, 'id_agreement': data.agreement.id, 'html_for_pdf': document.getElementById('printableArea').innerHTML, 'html_for_edit': agreementTemplate }) .$promise .then(function (response) { $scope.checkAgreementPdf(data.agreement.id); }) .catch(function (error) { bootbox.alert(error.data.reason); }) }; $scope.cancelAgreementRequestToUser = function (data, id) { agreementsService .cancelAgreementRequestToUser({'id':id}) .$promise .then(function (response) { $scope.checkAgreementPdf(data.agreement.id); }) .catch(function (error) { bootbox.alert(error.data.reason); }) }; $scope.sendAgreementRequestToUser = function (data, agreementTemplate) { agreementsService .agreementRequestToUser( { 'id_agreement':data.agreement.id, 'html_for_pdf': document.getElementById('printableArea').innerHTML, 'html_for_edit': agreementTemplate }) .$promise .then(function (response) { $scope.checkAgreementPdf(data.agreement.id); }) .catch(function (error) { bootbox.alert(error.data.reason); }) }; $scope.rejectAgreementRequest = function (agreementId) { bootbox.dialog({ title: "Ти впевнений, що хочеш відхилити запит?", message: '<div class="panel-body"><div class="row"><form role="form" name="rejectMessage"><div class="form-group col-md-12">' + '<textarea class="form-control" style="resize: none" rows="6" id="rejectMessageText" ' + 'placeholder="тут можна залишити коментар, причина відхилення запиту на затвердження договору, яка надійде користувачу на його email"></textarea>' + '</div></form></div></div>', buttons: { success: { label: "Підтвердити", className: "btn btn-primary", callback: function () { var comment = $jq('#rejectMessageText').val(); agreementsService.rejectAgreementRequest({ id: $stateParams.request, comment: comment }).$promise.then(function () { $scope.writtenAgreementPreview(agreementId); }); } }, cancel: { label: "Скасувати", className: "btn btn-default", callback: function () { } } } } ); }; $scope.loadWrittenAgreementTemplates=function(){ return agreementsService .getTemplatesList() .$promise .then(function (data) { $scope.writtenTemplates=data; }); }; $scope.loadWrittenAgreementTemplates(); $scope.editUserAgreement=function () { if(!$scope.editModeAgreement){ $scope.options.updatedUserAgreement=$scope.agreementTemplate; $scope.editModeAgreement=true; }else{ $scope.agreementTemplate=$scope.options.updatedUserAgreement; $scope.editModeAgreement=false; } } $scope.saveUpdateAgreement =function (agreement, template) { agreementsService .saveUpdateAgreement({agreementId:agreement.id,template: template}) .$promise .then(function (data) { $scope.editUserAgreement(); }); } $scope.removeWrittenAgreement = function (data, id) { bootbox.confirm('Ви впевнені, що хочете скасувати договір?', function (result) { if (result) { agreementsService .removeWrittenAgreement( {'id':id}) .$promise .then(function (response) { $state.go('accountant/writtenAgreementsList'); }) .catch(function (error) { bootbox.alert(error.data.reason); }) } }); } $scope.getAgreementPdf = function (id) { agreementsService .getAgreementFile({'id':id}) .$promise .then(function (response) { $scope.agreementPdf=response.data; }) .catch(function (error) { bootbox.alert("Отримати файл договору не вдалося"); }) } $scope.getDocument = function (documentID) { bootbox.alert({ message: "<img width='100%' src='" + basePath + '/_teacher/_accountant/accountant/getDocument?id=' + documentID + "'>", size: 'large' }) } $scope.printed = function (id, idAgreement) { agreementsService.writtenAreementPrinted({ id: id, }).$promise.then(function () { $scope.writtenAgreementPreview(idAgreement); }); } }]) .controller('writtenAgreementTemplate', ['$scope', '$http', '$stateParams', '$state', 'agreementsService', function ($scope, $http, $stateParams, $state, agreementsService) { $scope.changePageHeader('Шаблон паперового договору'); $scope.date = new Date(); $scope.editorOptionsAgreement = { toolbar: 'agreement' }; $http.get(basePath + '/angular/js/teacher/templates/accountancy/agreementExample.json').success(function (response) { $scope.writtenAgreement = response; }); $scope.saveAgreementTemplate = function (agreement, action) { if(!agreement.template || !agreement.name){ bootbox.alert('Тіло шаблону або назва не може бути пустою'); }else{ $http({ method: "POST", url: basePath + '/_teacher/_accountant/template/'+action, data: $jq.param({template: agreement}), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}, cache: false }).success(function (response) { bootbox.alert('Шаблон успішно збережено', function () { $state.go('accountant/writtenAgreementsList'); }); }).error(function () { bootbox.alert("Шаблон договору створити не вдалося"); }); } } if($stateParams.id){ agreementsService .getAgreementTemplate({id: $stateParams.id}) .$promise .then(function successCallback(response) { $scope.agreementTemplate = response.data; }, function errorCallback() { bootbox.alert("Шаблон договору отримати не вдалося"); }); } }]) .controller('agreementTemplatesList', ['$scope', '$http', '$stateParams', '$state', 'agreementsService','NgTableParams', function ($scope, $http, $stateParams, $state, agreementsService,NgTableParams) { $scope.changePageHeader('Шаблони паперових договорів'); $scope.templatesTableParams = new NgTableParams({}, { getData: function (params) { return agreementsService .writtenAgreementsTemplateList(params.url()) .$promise .then(function (data) { params.total(data.count); return data.rows; }); } }); }]) .controller('agreementsForGroupCtrl', ['$scope','$compile','$http','$stateParams', function ($scope, $compile, $http, $stateParams) { $scope.checkboxes = {'checked': false, items: {}}; $scope.$watch('checkboxes.items', function (values) { $scope.selectedStudents = [] for (var key in values) { if (values[key]) { $scope.selectedStudents.push(key) } } if ($scope.selectedStudents.length < $scope.offlineStudentsTableParams.data.length && $scope.selectedStudents.length > 0) angular.element(document.querySelector("#select_all")).prop('indeterminate', true) else if ($scope.selectedStudents.length == 0) { angular.element(document.querySelector("#select_all")).prop('indeterminate', false) } }, true); $scope.setService=function (type, id) { if(type=='module'){ $scope.selectedCourseService=null; } else $scope.selectedModuleService=null; $scope.selectedContent=id; $scope.serviceType=type; var schemesBlock=$jq('#agreementBlock'); schemesBlock.show(); ($compile(schemesBlock)($scope)); } $scope.loadTemplates = function () { $http({ url: basePath + '/_teacher/_accountant/template/getTemplatesList', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.templates = response.data; }, function errorCallback() { bootbox.alert("Отримати шаблони схем не вдалося"); }); }; $scope.loadTemplates(); $scope.createStudentsAgreement = function (moduleId, courseId, serviceType, scheme, templateId, allStudents, students) { if(typeof scheme == 'object'){ bootbox.alert("Спочатку обери схему проплати"); }else{ var scheme = JSON.parse(scheme); $scope.disabledButton=true; $http({ url: basePath + '/_teacher/_accountant/agreements/setAgreementForStudents', method: "POST", data:$jq.param({moduleId: moduleId, courseId: courseId, serviceType: serviceType, scheme:scheme, templateId:templateId, allStudents:allStudents,students:students, group: $stateParams.id }), headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'} }).then(function successCallback(response) { $scope.disabledButton=false; bootbox.alert(response.data); }, function errorCallback(response) { $scope.disabledButton=false; bootbox.alert(response.data.reason); }); } }; }]) .filter('timestamp', function(){ return function(input) { return Date.parse( angular.isString(input) ? input.replace(/\-/g, '/') : input ); } }) function selectFromTypeahead(context, field, modelField, $item, $model, $label, $event) { context[field] = $model[modelField]; } function defineSchemaType(input) { return ['module', 'user', 'course'].indexOf(input) >= 0 ? input : 'default' } function DateOptions() { this.popupOpened = false; this.maxDate = new Date(2020, 5, 22); this.minDate = new Date(); this.startingDay = 1; } DateOptions.prototype.open = function () { this.popupOpened = true; }; function ExternalPaymentDateOptions() { this.popupOpened = false; this.startingDay = 1; } ExternalPaymentDateOptions.prototype.open = function () { this.popupOpened = true; };
1.351563
1
app/containers/HomePage/index.js
martinqueija/hash-linked-logger-react
0
15998900
import PropTypes from 'prop-types'; import React, { memo, useEffect, useState } from 'react'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { createStructuredSelector } from 'reselect'; import { makeSelectLogs, makeSelectLoading, makeSelectError, } from 'containers/App/selectors'; import { loadLogs, createLogEntry } from 'containers/App/actions'; import { useInjectSaga } from 'utils/injectSaga'; import LogList from 'components/LogList'; import CorruptedLogFileError from 'components/CorruptedLogFileError'; import Form from './Form'; import Input from './Input'; import saga from './saga'; const key = 'home'; export function HomePage({ loading, error, logs, onNeedLogs, onSubmitForm }) { useInjectSaga({ key, saga }); const [draftMessage, setDraftMessage] = useState(''); useEffect(() => { if (!error && logs === null) { onNeedLogs(); } }, []); const logListProps = { loading, logs, }; return ( <article> <Helmet> <title> Home </title> <meta name="description" content="Hash linked logger application home page" /> </Helmet> <div> {error === 'corrupted_log_file' ? ( <CorruptedLogFileError /> ) : ( <div style={{ marginTop: '20px' }}> <Form onKeyDown={e => { if (e.key === 'Enter' && draftMessage.length) { e.preventDefault(); e.stopPropagation(); onSubmitForm(draftMessage); setDraftMessage(''); } }} > <label htmlFor="username"> <Input id="username-search" type="text" placeholder="Type your message here and press enter to send it!" value={draftMessage} onChange={i => setDraftMessage(i.target.value)} autoComplete="off" /> </label> </Form> <LogList {...logListProps} /> </div> )} </div> </article> ); } HomePage.propTypes = { loading: PropTypes.bool, error: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]), logs: PropTypes.array, onNeedLogs: PropTypes.func, onSubmitForm: PropTypes.func, onChangeDraftMessage: PropTypes.func, }; const mapStateToProps = createStructuredSelector({ logs: makeSelectLogs(), loading: makeSelectLoading(), error: makeSelectError(), }); export function mapDispatchToProps(dispatch) { return { onNeedLogs: () => dispatch(loadLogs()), onSubmitForm: msg => dispatch(createLogEntry(msg)), }; } const withConnect = connect( mapStateToProps, mapDispatchToProps, ); export default compose( withConnect, memo, )(HomePage);
1.664063
2
src/app/rules.js
Saviio/JD-Book-Plugin
2
15998908
let rules = { 1:[ { name:'author', type:Array, label:'作者', computed: value => value.join(' / ') }, { name:'title', type:String, label:'书名' } ], 2:[ { name:'translator', type:Array, label:'译者', computed: value => value.join(' / ') }, { name:'pages', type:String, label:'页数' }, { name:'publisher', type:String, label:'出版社' }, { name:'subtile', type:String, label:'副标题' }, { name:'id', type:String, label:'豆瓣ID' } ], 3:[ { name:'pubdate', type:String, label:'出版日期' }, { name:'price', type:String, label:'价格' } ], 4:[ { name:'binding', type:String, label:'装帧' }, { name:'isbn13', type:String, label:'ISBN' }, { name:'origin_title', type:String, label:'原作名' } ] } let NoMatched = 'No matched' let assert = function(rule, value){ let expectedType let valid = true switch (rule.type) { case String: expectedType = 'string' valid = typeof value === expectedType && value !== "" break case Number: expectedType = 'number' valid = typeof value === expectedType break case Array: expectedType = 'array' valid = Array.isArray(value) && value.length > 0 break case Object: expectedType = 'object' valid = value.toString() === '[object Object]' break case Boolean: expectedType = 'boolean' valid = typeof value === expectedType break default: expectedType = NoMatched valid = false } return valid } export {rules, assert}
1.90625
2
src/containers/DisplayPreference.js
misterpaul4/crypto-stats
1
15998916
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { darkMode, lightMode } from '../actions'; import light from '../img/light.svg'; import dark from '../img/dark.svg'; const DisplayPreference = ({ darkmode: { darkmode }, switchToDark, switchToLight, }) => { const handleClick = () => { if (darkmode) { switchToLight(); document.body.style.backgroundColor = '#f8f9fa'; document.body.style.color = '#343a40'; } else { switchToDark(); document.body.style.backgroundColor = '#343a40'; document.body.style.color = '#f8f9fa'; } }; return ( <button type="button" onClick={handleClick} className="display-mode-btn"> <img src={darkmode ? dark : light} alt="display preference" className="display-mode" /> </button> ); }; const mapStateToProps = state => ({ darkmode: state.darkmode, }); const mapDispatchToProps = dispatch => ({ switchToDark: preference => { dispatch(darkMode(preference)); }, switchToLight: preference => { dispatch(lightMode(preference)); }, }); DisplayPreference.propTypes = { darkmode: PropTypes.shape({ darkmode: PropTypes.bool.isRequired, }).isRequired, switchToDark: PropTypes.func.isRequired, switchToLight: PropTypes.func.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(DisplayPreference);
1.71875
2
node_modules/streamqueue/tests/index.mocha.js
JJardin77580/pdf.js
41
15998924
/* eslint max-nested-callbacks: 0 */ 'use strict'; const assert = require('assert'); const StreamTest = require('streamtest'); const StreamQueue = require('../src'); // Tests describe('StreamQueue', () => { // Iterating through versions StreamTest.versions.forEach(version => { describe('for ' + version + ' streams', () => { describe('in binary mode', () => { describe('and with async streams', () => { it('should work with functionnal API', done => { const createStreamQueue = StreamQueue; createStreamQueue( StreamTest[version].fromChunks(['wa', 'dup']), StreamTest[version].fromChunks(['pl', 'op']), StreamTest[version].fromChunks(['ki', 'koo', 'lol']) ).pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); }); it('should work with functionnal API and options', done => { const createStreamQueue = StreamQueue; createStreamQueue( {}, StreamTest[version].fromChunks(['wa', 'dup']), StreamTest[version].fromChunks(['pl', 'op']), StreamTest[version].fromChunks(['ki', 'koo', 'lol']) ).pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); }); it('should work with POO API', done => { const queue = new StreamQueue(); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(StreamTest[version].fromChunks(['pl', 'op'])); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should pause streams in flowing mode', done => { const queue = new StreamQueue({ pauseFlowingStream: true, resumeFlowingStream: true, }); const flowingStream = StreamTest[version].fromChunks(['pl', 'op']); flowingStream.on('data', () => {}); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(flowingStream); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should work with POO API and options', done => { const queue = new StreamQueue({ pauseFlowingStream: true, resumeFlowingStream: true, }); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(StreamTest[version].fromChunks(['pl', 'op'])); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should work with POO API and a late done call', done => { const queue = new StreamQueue(); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(StreamTest[version].fromChunks(['pl', 'op'])); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); setTimeout(() => { queue.done(); }, 100); }); it('should work with POO API and no stream plus sync done', done => { const queue = new StreamQueue(); assert.equal(queue.length, 0); queue.queue(); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); queue.done(); }); it('should work with POO API and no stream plus async done', done => { const queue = new StreamQueue(); assert.equal(queue.length, 0); queue.queue(); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); setTimeout(() => { queue.done(); }, 100); }); it('should work with POO API and a streamqueue stream plus async done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); queue.queue(child); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); child.done(); setTimeout(() => { queue.done(); }, 100); }); it('should work with POO API and a streamqueue stream plus async done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); queue.queue(child); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); child.done(); queue.done(); }); it('should work with POO API and a streamqueue ended stream plus async done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); queue.queue(child); child.done(); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); setTimeout(() => { queue.done(); }, 100); }); it('should fire end asynchronously with streams', done => { const queue = new StreamQueue(); let ended = false; queue.queue( StreamTest[version].fromChunks(['wa', 'dup']).on('end', () => { assert.equal(ended, false); }) ); queue.queue( StreamTest[version].fromChunks(['pl', 'op']).on('end', () => { assert.equal(ended, false); }) ); queue.queue( StreamTest[version] .fromChunks(['ki', 'koo', 'lol']) .on('end', () => { assert.equal(ended, false); }) ); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.on('end', () => { ended = true; }); queue.done(); assert.equal(ended, false); }); it('should fire end asynchronously when empty', done => { const queue = new StreamQueue(); let ended = false; assert.equal(queue.length, 0); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); queue.on('end', () => { ended = true; }); queue.done(); assert.equal(ended, false); }); it('should work with POO API and a streamqueue ended stream plus sync done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); queue.queue(child); child.done(); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); queue.done(); }); it('should work with POO API and a streamqueue ended stream plus async done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); child.done(); queue.queue(child); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); setTimeout(() => { queue.done(); }, 100); }); it('should work with POO API and a streamqueue ended stream plus sync done', done => { const queue = new StreamQueue(); const child = new StreamQueue(); child.done(); queue.queue(child); assert.equal(queue.length, 1); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, ''); done(); }) ); queue.done(); }); if ('v2' === version) { it('should reemit errors', done => { let _err; const queue = new StreamQueue(); queue.queue( StreamTest[version].fromErroredChunks(new Error('Aouch!'), []) ); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(StreamTest[version].fromChunks(['pl', 'op'])); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 4); queue.on('error', err => { _err = err; }); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert(_err); assert.equal(_err.message, 'Aouch!'); assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); } if ('v2' === version) { it('should reemit errors elsewhere', done => { let _err; const queue = new StreamQueue(); queue.queue(StreamTest[version].fromChunks(['wa', 'dup'])); queue.queue(StreamTest[version].fromChunks(['pl', 'op'])); queue.queue( StreamTest[version].fromErroredChunks(new Error('Aouch!'), []) ); queue.queue(StreamTest[version].fromChunks(['ki', 'koo', 'lol'])); assert.equal(queue.length, 4); queue.on('error', err => { _err = err; }); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert(_err); assert.equal(_err.message, 'Aouch!'); assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); } }); describe('and with sync streams', () => { it('should work with functionnal API', done => { const stream1 = StreamTest[version].syncReadableChunks(); const stream2 = StreamTest[version].syncReadableChunks(); const stream3 = StreamTest[version].syncReadableChunks(); const createStreamQueue = StreamQueue; createStreamQueue(stream1, stream2, stream3).pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); StreamTest[version].syncWrite(stream1, ['wa', 'dup']); StreamTest[version].syncWrite(stream2, ['pl', 'op']); StreamTest[version].syncWrite(stream3, ['ki', 'koo', 'lol']); }); it('should work with POO API', done => { const queue = new StreamQueue(); const stream1 = StreamTest[version].syncReadableChunks(); const stream2 = StreamTest[version].syncReadableChunks(); const stream3 = StreamTest[version].syncReadableChunks(); queue.queue(stream1); queue.queue(stream2); queue.queue(stream3); StreamTest[version].syncWrite(stream1, ['wa', 'dup']); StreamTest[version].syncWrite(stream2, ['pl', 'op']); StreamTest[version].syncWrite(stream3, ['ki', 'koo', 'lol']); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should emit an error when calling done twice', done => { const queue = new StreamQueue(); const stream1 = StreamTest[version].syncReadableChunks(); const stream2 = StreamTest[version].syncReadableChunks(); const stream3 = StreamTest[version].syncReadableChunks(); queue.queue(stream1); queue.queue(stream2); queue.queue(stream3); StreamTest[version].syncWrite(stream1, ['wa', 'dup']); StreamTest[version].syncWrite(stream2, ['pl', 'op']); StreamTest[version].syncWrite(stream3, ['ki', 'koo', 'lol']); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); assert.throws(() => { queue.done(); }); }); it('should emit an error when queueing after done was called', done => { const queue = new StreamQueue(); const stream1 = StreamTest[version].syncReadableChunks(); const stream2 = StreamTest[version].syncReadableChunks(); const stream3 = StreamTest[version].syncReadableChunks(); queue.queue(stream1); queue.queue(stream2); queue.queue(stream3); StreamTest[version].syncWrite(stream1, ['wa', 'dup']); StreamTest[version].syncWrite(stream2, ['pl', 'op']); StreamTest[version].syncWrite(stream3, ['ki', 'koo', 'lol']); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); assert.throws(() => { queue.queue(StreamTest[version].syncReadableChunks()); }); }); if ('v2' === version) { it('should reemit errors', done => { let _err; const queue = new StreamQueue(); const stream1 = StreamTest[version].syncReadableChunks(); const stream2 = StreamTest[version].syncReadableChunks(); const stream3 = StreamTest[version].syncReadableChunks(); const stream4 = StreamTest[version].syncReadableChunks(); queue.queue(stream1); queue.queue(stream2); queue.queue(stream3); queue.queue(stream4); queue.on('error', err => { _err = err; }); StreamTest[version].syncError(stream1, new Error('Aouch!')); StreamTest[version].syncWrite(stream2, ['wa', 'dup']); StreamTest[version].syncWrite(stream3, ['pl', 'op']); StreamTest[version].syncWrite(stream4, ['ki', 'koo', 'lol']); assert.equal(queue.length, 4); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert(_err); assert.equal(_err.message, 'Aouch!'); assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); } }); describe('and with functions returning streams', () => { it('should work with functionnal API', done => { const createStreamQueue = StreamQueue; createStreamQueue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']), StreamTest[version].fromChunks.bind(null, ['pl', 'op']), StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ).pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); }); it('should work with functionnal API and options', done => { const createStreamQueue = StreamQueue; createStreamQueue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']), StreamTest[version].fromChunks.bind(null, ['pl', 'op']), StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ).pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); }); it('should work with POO API', done => { const queue = new StreamQueue(); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['pl', 'op']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should pause streams in flowing mode', done => { const queue = new StreamQueue({ pauseFlowingStream: true, resumeFlowingStream: true, }); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue(() => { const stream = StreamTest[version].fromChunks(['pl', 'op']); stream.on('data', () => {}); return stream; }); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should work with POO API and options', done => { const queue = new StreamQueue({ pauseFlowingStream: true, resumeFlowingStream: true, }); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['pl', 'op']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); it('should work with POO API and a late done call', done => { const queue = new StreamQueue(); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['pl', 'op']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 3); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert.equal(text, 'wadupplopkikoolol'); done(); }) ); setTimeout(() => { queue.done(); }, 100); }); if ('v2' === version) { it('should reemit errors', done => { let _err; const queue = new StreamQueue(); queue.queue( StreamTest[version].fromErroredChunks.bind( null, new Error('Aouch!'), [] ) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['pl', 'op']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 4); queue.on('error', err => { _err = err; }); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert(_err); assert.equal(_err.message, 'Aouch!'); assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); } if ('v2' === version) { it('should reemit errors elsewhere', done => { let _err; const queue = new StreamQueue(); queue.queue( StreamTest[version].fromChunks.bind(null, ['wa', 'dup']) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['pl', 'op']) ); queue.queue( StreamTest[version].fromErroredChunks.bind( null, new Error('Aouch!'), [] ) ); queue.queue( StreamTest[version].fromChunks.bind(null, ['ki', 'koo', 'lol']) ); assert.equal(queue.length, 4); queue.on('error', err => { _err = err; }); queue.pipe( StreamTest[version].toText((err, text) => { if (err) { done(err); return; } assert(_err); assert.equal(_err.message, 'Aouch!'); assert.equal(text, 'wadupplopkikoolol'); done(); }) ); queue.done(); }); } }); }); describe('in object mode', () => { it('should work', done => { const queue = new StreamQueue({ objectMode: true }); queue.queue( StreamTest[version].fromObjects([{ s: 'wa' }, { s: 'dup' }]) ); queue.queue( StreamTest[version].fromObjects([{ s: 'pl' }, { s: 'op' }]) ); queue.queue( StreamTest[version].fromObjects([ { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]) ); queue.pipe( StreamTest[version].toObjects((err, objs) => { if (err) { done(err); return; } assert.deepEqual(objs, [ { s: 'wa' }, { s: 'dup' }, { s: 'pl' }, { s: 'op' }, { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]); done(); }) ); queue.done(); }); }); describe('in object mode with the .obj() shortcut', () => { it('should work without options', done => { StreamQueue.obj( StreamTest[version].fromObjects([{ s: 'wa' }, { s: 'dup' }]), StreamTest[version].fromObjects([{ s: 'pl' }, { s: 'op' }]), StreamTest[version].fromObjects([ { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]) ).pipe( StreamTest[version].toObjects((err, objs) => { if (err) { done(err); return; } assert.deepEqual(objs, [ { s: 'wa' }, { s: 'dup' }, { s: 'pl' }, { s: 'op' }, { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]); done(); }) ); }); it('should work with options', done => { StreamQueue.obj( {}, StreamTest[version].fromObjects([{ s: 'wa' }, { s: 'dup' }]), StreamTest[version].fromObjects([{ s: 'pl' }, { s: 'op' }]), StreamTest[version].fromObjects([ { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]) ).pipe( StreamTest[version].toObjects((err, objs) => { if (err) { done(err); return; } assert.deepEqual(objs, [ { s: 'wa' }, { s: 'dup' }, { s: 'pl' }, { s: 'op' }, { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]); done(); }) ); }); it('should work without options nor streams', done => { const queue = StreamQueue.obj(); queue.queue( StreamTest[version].fromObjects([{ s: 'wa' }, { s: 'dup' }]) ); queue.queue( StreamTest[version].fromObjects([{ s: 'pl' }, { s: 'op' }]) ); queue.queue( StreamTest[version].fromObjects([ { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]) ); queue.done(); queue.pipe( StreamTest[version].toObjects((err, objs) => { if (err) { done(err); return; } assert.deepEqual(objs, [ { s: 'wa' }, { s: 'dup' }, { s: 'pl' }, { s: 'op' }, { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]); done(); }) ); }); it('should work with options and no streams', done => { const queue = StreamQueue.obj({}); queue.queue( StreamTest[version].fromObjects([{ s: 'wa' }, { s: 'dup' }]) ); queue.queue( StreamTest[version].fromObjects([{ s: 'pl' }, { s: 'op' }]) ); queue.queue( StreamTest[version].fromObjects([ { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]) ); queue.done(); queue.pipe( StreamTest[version].toObjects((err, objs) => { if (err) { done(err); return; } assert.deepEqual(objs, [ { s: 'wa' }, { s: 'dup' }, { s: 'pl' }, { s: 'op' }, { s: 'ki' }, { s: 'koo' }, { s: 'lol' }, ]); done(); }) ); }); }); }); }); });
1.523438
2
EunomiaReactApp/src/App.js
orectique/Eleutherios_SreehariPSreedhar
0
15998932
import React, { useEffect, useState } from "react"; import { ethers } from "ethers"; import './App.css'; import eunomiaNFT from './utils/eunomiaNFT.json'; const App = () => { const [currentAccount, setCurrentAccount] = useState(""); const contractAddress = "0x0969C4BF8290F0fBFF7942d0CF4d4A659e76613d"; const checkIfWalletIsConnected = async () => { try { const { ethereum } = window; if (!ethereum) { console.log("Make sure you have metamask!"); return; } else { console.log("We have the ethereum object", ethereum); } const accounts = await ethereum.request({ method: 'eth_accounts' }); if (accounts.length !== 0) { const account = accounts[0]; console.log("Found an authorized account:", account); setCurrentAccount(account); setupEventListener() } else { console.log("No authorized account found") } } catch (error) { console.log(error); } } const connectWallet = async () => { try { const { ethereum } = window; if (!ethereum) { alert("Get MetaMask!"); return; } const accounts = await ethereum.request({ method: "eth_requestAccounts" }); console.log("Connected", accounts[0]); setCurrentAccount(accounts[0]); setupEventListener() } catch (error) { console.log(error) } } const setupEventListener = async () => { // Most of this looks the same as our function askContractToMintNft try { const { ethereum } = window; if (ethereum) { // Same stuff again const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const connectedContract = new ethers.Contract(contractAddress, eunomiaNFT.abi, signer); // THIS IS THE MAGIC SAUCE. // This will essentially "capture" our event when our contract throws it. // If you're familiar with webhooks, it's very similar to that! connectedContract.on("NFTMinted", (from, tokenId) => { console.log(from, tokenId.toNumber()) alert(`Hey there! We've minted your NFT and sent it to your wallet. It may be blank right now. It can take a max of 10 min to show up on OpenSea. Here's the link: https://testnets.opensea.io/assets/${contractAddress}/${tokenId.toNumber()}`) }); console.log("Setup event listener!") } else { console.log("Ethereum object doesn't exist!"); } } catch (error) { console.log(error) } } const dump = async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const EunomiaContract = new ethers.Contract(contractAddress, eunomiaNFT.abi, signer); //let count = await EunomiaContract.get_dump(); //console.log("Retrieved total dump count...", count.toNumber()); const weight = document.getElementById("weight_input").value; const type = document.getElementById("type_input").value; const text_input = 'Type: ' + type.toString() + ' ; Weight: ' + weight.toString() + ' grams'; const dumpTxn = await EunomiaContract.makeAnNFT(text_input, { gasLimit: 5000000 }); console.log("Mining...", dumpTxn.hash); await dumpTxn.wait(); console.log(`Mined, see transaction: https://ropsten.etherscan.io/tx/${dumpTxn.hash}`); //count = await EunomiaContract.get_dump(); //console.log("Retrieved total dump count...", count.toNumber()); const text = 'Your transaction has been mined -- ' + dumpTxn.hash.toString() + ' . Thank you for making the responsible choice.'; alert(text) } else { console.log("Ethereum object doesn't exist!"); } } catch (error) { console.log(error) alert('There has been an error. Your request was not processed.') } } useEffect(() => { checkIfWalletIsConnected(); }, []) return ( <div className="mainContainer"> <div className="dataContainer"> <div className="header"> Welcome to Eunomia </div> <p>This is a simulation of a terminal attached to the smart trash bin. There, the type will be predicted using computer vision and the weight will be computed <i>vice</i>.</p> <div className="bio"> <h3>Types of trash:</h3> <ol type="1"> <li>Low Density Polyeurethylene (including coated paper)</li> <li>Paper</li> <li>Bottles/Food containers/High Density Polyethylene</li> <li>Electronic Waste</li> <li>Metal Artefacts</li> </ol> </div> <label for="type_input">Enter the type of your trash - refer above: </label> <input type="number" id = "type_input" name = "type_input" min="1" max="5"/> <label for="weight_input">Enter the weight of your trash in grams: </label> <input type="number" id = "weight_input" name = "weight_input" min = "1"/> <button className="waveButton" onClick={dump}> Submit </button> {!currentAccount && ( <button className="waveButton" onClick={connectWallet}> Connect Wallet </button> )} </div> </div> ); } export default App
1.773438
2
dist/libs/vue/src/webpack.js
japhy-team/nx-plus
0
15998940
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.modifyBabelLoader = exports.modifyCopyAssets = exports.modifyTypescriptAliases = exports.modifyCachePaths = exports.modifyTsConfigPaths = exports.modifyEntryPoint = exports.modifyIndexHtmlPath = void 0; const core_1 = require("@angular-devkit/core"); const semver = require("semver"); const utils_1 = require("./utils"); function modifyIndexHtmlPath(config, options, context) { config.plugin('html').tap((args) => { args[0].template = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), options.index)); return args; }); } exports.modifyIndexHtmlPath = modifyIndexHtmlPath; function modifyEntryPoint(config, options, context) { config.entry('app').clear(); config .entry('app') .add(core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), options.main))); } exports.modifyEntryPoint = modifyEntryPoint; function modifyTsConfigPaths(config, options, context) { const tsConfigPath = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), options.tsConfig)); const vue = utils_1.loadModule('vue', context.workspaceRoot); const isVue3 = semver.major(vue.version) === 3; config.module .rule('ts') .use('ts-loader') .tap((loaderOptions) => { loaderOptions.configFile = tsConfigPath; return loaderOptions; }); config.module .rule('tsx') .use('ts-loader') .tap((loaderOptions) => { loaderOptions.configFile = tsConfigPath; return loaderOptions; }); config.plugin('fork-ts-checker').tap((args) => { if (isVue3) { args[0].typescript.configFile = tsConfigPath; } else { args[0].tsconfig = tsConfigPath; } return args; }); } exports.modifyTsConfigPaths = modifyTsConfigPaths; function modifyCachePaths(config, context) { const vueLoaderCachePath = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), 'node_modules/.cache/vue-loader')); const tsLoaderCachePath = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), 'node_modules/.cache/ts-loader')); config.module .rule('vue') .use('cache-loader') .tap((options) => { options.cacheDirectory = vueLoaderCachePath; return options; }); config.module .rule('vue') .use('vue-loader') .tap((options) => { options.cacheDirectory = vueLoaderCachePath; return options; }); config.module .rule('ts') .use('cache-loader') .tap((options) => { options.cacheDirectory = tsLoaderCachePath; return options; }); config.module .rule('tsx') .use('cache-loader') .tap((options) => { options.cacheDirectory = tsLoaderCachePath; return options; }); } exports.modifyCachePaths = modifyCachePaths; function modifyTypescriptAliases(config, options, context) { const tsConfigPath = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), options.tsConfig)); const extensions = [ '.tsx', '.ts', '.mjs', '.js', '.jsx', '.vue', '.json', '.wasm', ]; config.resolve.alias.delete('@'); config.resolve .plugin('tsconfig-paths') // eslint-disable-next-line @typescript-eslint/no-var-requires .use(require('tsconfig-paths-webpack-plugin'), [ { configFile: tsConfigPath, extensions, }, ]); } exports.modifyTypescriptAliases = modifyTypescriptAliases; function modifyCopyAssets(config, options, context, projectRoot) { const transformedAssetPatterns = ['package.json', 'README.md'].map((file) => ({ from: core_1.getSystemPath(core_1.join(projectRoot, file)), to: core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), options.dest)), })); config .plugin('copy') // eslint-disable-next-line @typescript-eslint/no-var-requires .use(require('copy-webpack-plugin'), [transformedAssetPatterns]); } exports.modifyCopyAssets = modifyCopyAssets; function modifyBabelLoader(config, babelConfig, context) { ['js', 'ts', 'tsx'].forEach((ext) => config.module .rule(ext) .use('babel-loader') .tap((options) => (Object.assign(Object.assign({}, options), { configFile: babelConfig })))); const babelLoaderCachePath = core_1.getSystemPath(core_1.join(core_1.normalize(context.workspaceRoot), 'node_modules/.cache/babel-loader')); config.module .rule('js') .use('cache-loader') .tap((options) => { options.cacheDirectory = babelLoaderCachePath; return options; }); } exports.modifyBabelLoader = modifyBabelLoader; //# sourceMappingURL=webpack.js.map
1.242188
1
js/test.js
SnehalGolhar/TestingApp
0
15998948
/** * Created by Vaibhav on 11/17/2015. */ function food() { $("#foodtest").addClass("hidden"); $("#desttest").addClass("hidden"); $("#actortest").addClass("hidden"); $("#habittest").addClass("hidden"); $("#pictest").addClass("hidden"); $("#gifttest").addClass("hidden"); var count=0; //code for food if(document.getElementById("sandwich").checked==true) { $("#foodtest").removeClass("hidden"); $("#foodrightanswer").removeClass("hidden"); $("#foodwronganswer").addClass("hidden"); count++; } else { $("#foodtest").removeClass("hidden"); $("#foodrightanswer").addClass("hidden"); $("#foodwronganswer").removeClass("hidden"); } //code for destination if(document.getElementById("tarkarli").checked==true) { $("#desttest").removeClass("hidden"); $("#destrightanswer").removeClass("hidden"); $("#destwronganswer").addClass("hidden"); count++; } else { $("#desttest").removeClass("hidden"); $("#destwronganswer").removeClass("hidden"); $("#destrightanswer").addClass("hidden"); } //code for habit if(document.getElementById("legs").checked==true) { $("#habittest").removeClass("hidden"); $("#habitrightanswer").removeClass("hidden"); $("#habitwronganswer").addClass("hidden"); count++; } else { $("#habittest").removeClass("hidden"); $("#habitrightanswer").addClass("hidden"); $("#habitwronganswer").removeClass("hidden"); } //code for actor if(document.getElementById("nana").checked==true) { $("#actortest").removeClass("hidden"); $("#actorrightanswer").removeClass("hidden"); $("#actorwronganswer").addClass("hidden"); count++; } else { $("#actortest").removeClass("hidden"); $("#actorrightanswer").addClass("hidden"); $("#actorwronganswer").removeClass("hidden"); } //code for worry if(document.getElementById("weight").checked==true) { $("#worrytest").removeClass("hidden"); $("#worryrightanswer").removeClass("hidden"); $("#worrywronganswer").addClass("hidden"); count++; } else { $("#worrytest").removeClass("hidden"); $("#worryrightanswer").addClass("hidden"); $("#worrywronganswer").removeClass("hidden"); } //code for Gift if(document.getElementById("card").checked==true) { $("#gifttest").removeClass("hidden"); $("#giftrightanswer").removeClass("hidden"); $("#giftwronganswer").addClass("hidden"); count++; } else { $("#gifttest").removeClass("hidden"); $("#giftrightanswer").addClass("hidden"); $("#giftwronganswer").removeClass("hidden"); } //code for pic if(document.getElementById("pic").checked==true) { $("#pictest").removeClass("hidden"); $("#picrightanswer").removeClass("hidden"); $("#picwronganswer").addClass("hidden"); count++; } else { $("#pictest").removeClass("hidden"); $("#picrightanswer").addClass("hidden"); $("#picwronganswer").removeClass("hidden"); } if(count==7) { $("#clue").removeClass("hidden"); } } function test() { window.open('contact.html'); }
1.429688
1
src/goo/entities/Entity.js
rlugojr/goojs
1,307
15998956
var Component = require('../entities/components/Component'); var StringUtils = require('../util/StringUtils'); var EventTarget = require('../util/EventTarget'); /** * An Entity is a generic container of data. * This data is wrapped in [Components]{@link Component}, which usually provide isolated features (transforms, geometries, materials, scripts and so on). * By setting components to an entity, the entity will get the functionality provided by the components. * For example, an entity with a {@link TransformComponent} and a {@link LightComponent} will be a light source in 3D space. * Note that when attaching components to an entity, methods of the component will be injected into the entity, extending its interface. * @param {World} world The {@link World} this entity will be part of after calling .addToWorld(). * @param {string} [name] Entity name. * @param {number} [id] Entity id. */ function Entity(world, name, id) { EventTarget.apply(this); this._world = world; this._components = []; this.id = id !== undefined ? id : StringUtils.createUniqueId('entity'); this._index = Entity.entityCount; this._tags = new Set(); this._attributes = new Map(); /*Object.defineProperty(this, 'id', { value : Entity.entityCount++, writable : false });*/ this.name = name !== undefined ? name : 'Entity_' + this._index; // (move to meshrenderercomponent) /** Set to true to skip all processing (rendering, script updating, et cetera) of the entity. * @type {boolean} * @default false */ this.skip = false; /** Holds the hidden status of the entity. The hidden status will not however propagate to components or child entities. * @deprecated The usage of this flag changed. Please use entity.hide/show() instead to change the hidden status of the entity and entity.isHidden/isVisiblyHidden() to query the status * @type {boolean} * @default false */ this.hidden = false; //! AT: users are always confused about this - I'll have to hide it /** * Has the same function as the `hidden` property, except it's now private. * @type {boolean} * @private */ this._hidden = false; /** * True if the entity is within the frustum * @type {boolean} */ this.isVisible = false; /** Mark entity as static. * Non static entities become roots in the tree of combined ones so one can have statics under a moving node that combines but you can still move the parent node. * @type {boolean} * @default false */ this.static = false; Entity.entityCount++; } Entity.prototype = Object.create(EventTarget.prototype); Entity.prototype.constructor = Entity; //! AT: not sure if 'add' is a better name - need to search for something short and compatible with the other 'set' methods /** * Sets components on the entity or tries to create and set components out of the supplied parameters. * @example-link http://code.gooengine.com/latest/examples/goo/entities/Entity/Entity-set-example.html Working example * @example * // Create three entities with different components, add them to world * var sphereEntity = new Entity(world).set(sphere, material, [2, 0, 0]).addToWorld(); * var lightEntity = new Entity(world).set(light, [0, 1, 0]).addToWorld(); * var spinningEntity = new Entity(world).set(box, material, [-2, 0, 0], script).addToWorld(); * * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.set = function () { for (var i = 0; i < arguments.length; i++) { var argument = arguments[i]; if (argument instanceof Component) { this.setComponent(argument); } else { // ask all components if they are compatible with the given data if (!this._world) { return this; } var components = this._world._components; for (var j = 0; j < components.length; j++) { var component = components[j]; var applied = component.applyOnEntity(argument, this); if (applied) { break; } } } } // allow chaining return this; }; /** * Add the entity to the world, making it active and processed by systems and managers. * @param {boolean} [recursive=true] Add children of the transform hierarchy recursively. * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.addToWorld = function (recursive) { this._world.addEntity(this, recursive); return this; }; /** * Remove entity from the world. * @param {boolean} [recursive=true] Remove children of the transform hierarchy recursively. * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.removeFromWorld = function (recursive) { this._world.removeEntity(this, recursive); return this; }; /** * lower cases the first character of the type parameter. * @param {string} type name. * @returns {string} lower cased type name. * @private */ function getTypeAttributeName(type) { return type.charAt(0).toLowerCase() + type.substr(1); } /** * Set component of a certain type on entity. The operation has no effect if the entity already contains a component of the same type. * * @param {Component} component Component to set on the entity. * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.setComponent = function (component) { if (this.hasComponent(component.type)) { return this; } else { this._components.push(component); } this[getTypeAttributeName(component.type)] = component; component.entity = this; // inform the component it's being attached to an entity component.attached(this); component.applyAPI(this); if (this._world && this._world.entityManager.containsEntity(this)) { this._world.changedEntity(this, component, 'addedComponent'); } return this; }; /** * Checks if a component of a specific type is present or not. * * @param {string} type Type of component to check for (eg. 'meshDataComponent'). * @returns {boolean} */ Entity.prototype.hasComponent = function (type) { var typeAttributeName = getTypeAttributeName(type); return !!this[typeAttributeName]; }; /** * Retrieve a component of a specific type. * * @param {string} type Type of component to retrieve (eg. 'transformComponent'). * @returns {Component} Component with requested type or undefined if not present. */ Entity.prototype.getComponent = function (type) { var typeAttributeName = getTypeAttributeName(type); return this[typeAttributeName]; }; /** * Remove a component of a specific type from entity. * * @param {string} type Type of component to remove (eg. 'meshDataComponent'). * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.clearComponent = function (type) { var typeAttributeName = getTypeAttributeName(type); var component = this[typeAttributeName]; if (!!component && this._components.indexOf(component) > -1) { // inform the component it's being detached from the entity component.detached(this); component.entity = null; // removing API component.removeAPI(this); // removing from dense array var index = this._components.indexOf(component); this._components.splice(index, 1); // removing from entity delete this[typeAttributeName]; // notifying the world of the change if (this._world && this._world.entityManager.containsEntity(this)) { this._world.changedEntity(this, component, 'removedComponent'); } } return this; }; /** * Adds a tag to the entity. * @param {string} tag * @example-link http://code.gooengine.com/latest/examples/goo/entities/Entity/Entity-tags-example.html Working example * @example * var banana = world.createEntity().setTag('fruit').setTag('green'); * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.setTag = function (tag) { this._tags.add(tag); return this; }; /** * Checks whether an entity has a tag or not. * @param {string} tag * @example-link http://code.gooengine.com/latest/examples/goo/entities/Entity/Entity-tags-example.html Working example * @example * if (banana.hasTag('yellow')) { * console.log('The banana is yellow'); * } * @returns {boolean}. */ Entity.prototype.hasTag = function (tag) { return this._tags.has(tag); }; /** * Clears a tag on an entity. * @param {string} tag * @example-link http://code.gooengine.com/latest/examples/goo/entities/Entity/Entity-tags-example.html Working example * @example * // Remove 'alive' tag if hit points drops to zero * if (hero.getAttribute('hit-points') <= 0) { * hero.clearTag('alive'); * } * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.clearTag = function (tag) { this._tags.delete(tag); return this; }; /** * Sets an attribute and its value on the entity. * * @param {string} attribute * @param value * @example-link http://code.gooengine.com/latest/examples/goo/entities/Entity/Entity-attributes-example.html Working example * @example * // Create an entity with tags and attributes, and add it to world * var hero = world.createEntity() * .setTag('hero') * .setAttribute('hit-points', 30) * .setAttribute('attack-power', 3) * .setTag('alive') * .addToWorld(); * * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.setAttribute = function (attribute, value) { this._attributes.set(attribute, value); return this; }; /** * Checks whether an entity has an attribute or not. * @param {string} attribute * @returns {boolean} */ Entity.prototype.hasAttribute = function (attribute) { return this._attributes.has(attribute); }; /** * Gets the value of the specified attribute. * @param {string} attribute * @example * // Check hit points on monster entity * if (monster.getAttribute('hit-points') <= 0) { * console.log('The hero triumphs!'); * } * * @returns {*} */ Entity.prototype.getAttribute = function (attribute) { return this._attributes.get(attribute); }; /** * Clears an attribute of the entity. * @param {string} attribute * @returns {Entity} Returns self to allow chaining. */ Entity.prototype.clearAttribute = function (attribute) { this._attributes.delete(attribute); return this; }; /** * @returns {string} Name of entity. */ Entity.prototype.toString = function () { //! AT: should also return a list of its components or something more descriptive than just the name return this.name; }; Entity.entityCount = 0; module.exports = Entity;
1.570313
2
models/cases.js
sabinusi/TangaHighCourt
0
15998964
const bcrypt = require('bcrypt-nodejs'); const crypto = require('crypto'); const mongoose = require('mongoose'); const cases = new mongoose.Schema({ name: { type: String, default: '' }, filenumber: { type: String, unique: true }, openDate: { type: String, default: '' }, closedDate: { type: String, default: '' }, judge: { id: String, firstname: String, lastname: String, }, recordManagementAssistance: { id: String, firstname: String, lastname: String, }, residentMigstrate: { id: String, firstname: String, lastname: String, } }, { timestamps: true }); const casess = mongoose.model('cases', cases); module.exports = casess;
1.101563
1
tests/period-selector-component-test.js
billysbilling/ember-period-selector
0
15998972
var periods = require('../src/js/periods'); var eventDispatcher, container, target, selector, selectedValue, selectEventCounter; QUnit.module('period-selector component', { setup: function() { eventDispatcher = Ember.EventDispatcher.create(); eventDispatcher.setup({ tap: 'click', click: null }, '#ember-testing'); container = buildTestContainer(); container.register('view:test-target', Em.View.extend({ attributeBindings: ['style'], style: 'width:20px; height:20px; background-color:#999; position:absolute; top:20px; left:20px;' })); target = container.lookup('view:test-target'); Ember.run(function() { target.appendTo('#ember-testing'); }); selectedValue = null; selectEventCounter = 0; }, teardown: function() { Em.run(function() { eventDispatcher.destroy(); if (selector) { selector.destroy(); } if (target) { target.destroy(); } if (container) { container.destroy(); } }); selector = target = container = null; } }); function createSelector() { selector = container.lookup('component:period-selector'); selector.on('select', function(value) { selectEventCounter++; selectedValue = value; }) } function showSelector() { Ember.run(function() { selector.show(target) }); } function setupSelector() { createSelector(); showSelector(); } test('Clicking all time selects instantly', function() { setupSelector(); click('.selector-item .name', t('period_selector.all')); equal(selectEventCounter, 1); equal(selectedValue, null); }); test('Clicking Month, applies .active class', function() { setupSelector(); click('.selector-item:eq(1) .name', t('period_selector.month')); ok(findWithAssert('.selector-item:eq(1)').hasClass('active')) }); test('Month default', function() { setupSelector(); Em.run(function() { selector.set('value', periods.Month.create({value: 'month:2012-04'})); }) click('.selector-item .name', t('period_selector.month')); click('.selector-item.active .tool'); equal(selectEventCounter, 1); ok(selectedValue instanceof periods.Month); equal(selectedValue.get('value'), 'month:2012-04'); }); test('Quarter default', function() { setupSelector(); Em.run(function() { selector.set('value', periods.Quarter.create({value: 'quarter:2012-2'})); }) click('.selector-item .name', t('period_selector.quarter')); click('.selector-item.active .tool'); equal(selectEventCounter, 1); ok(selectedValue instanceof periods.Quarter); equal(selectedValue.get('value'), 'quarter:2012-2'); }); test('Year default', function() { setupSelector(); Em.run(function() { selector.set('value', periods.Year.create({value: 'year:2012'})); }) click('.selector-item .name', t('period_selector.year')); click('.selector-item.active .tool'); equal(selectEventCounter, 1); ok(selectedValue instanceof periods.Year); equal(selectedValue.get('value'), 'year:2012'); }); test('Dates default', function() { setupSelector(); Em.run(function() { selector.set('value', periods.Dates.create({value: 'dates:2012-04-01...2012-04-30'})); }) click('.selector-item .name', t('period_selector.dates')); click('.selector-item.active .tool'); equal(selectEventCounter, 1); ok(selectedValue instanceof periods.Dates); equal(selectedValue.get('value'), 'dates:2012-04-01...2012-04-30'); });
1.546875
2
resources/assets/app/modules/tbaplayer/index.js
b9813147/sokradeo
0
15998980
require('./bootstrap') import TbaPlayerHelper from './helpers/tbaplayer' import CpntTbaPlayer from './components/tbaplayer.vue' window.Component = window.Component || {} window.Component.TbaPlayer = window.Component.TbaPlayer || {} window.Component.TbaPlayer.helper = TbaPlayerHelper window.Component.TbaPlayer.main = CpntTbaPlayer
0.6875
1
src/hydrate.js
steelbrain/redux-memory
1
15998988
// @flow import isPrimitive from 'is-primitive' import { TYPE_AS_IS } from './common' export function validateKnownTypes(knownTypes: Array<Function>) { const knownNames = new Set() knownTypes.forEach((item, index) => { if (typeof item !== 'function') { throw new Error(`options.knownTypes[${index}] must be a function/class`) } if (knownNames.has(item.name)) { throw new Error(`options.knownTypes has encountered more than one occurance of '${item.name}'`) } knownNames.add(item.name) }) } function dehydrateItem(obj: Object, knownTypes: Array<Function>) { const { type, value: rawValue } = obj let value if (isPrimitive(rawValue)) { value = rawValue } else { value = Array.isArray(rawValue) ? [] : {} Object.keys(rawValue).forEach(function(key) { value[key] = dehydrateItem(rawValue[key], knownTypes) }) } if (type === TYPE_AS_IS || type === 'Object' || type === 'Array') { return value } const Creed = knownTypes.find(i => i.name === type) if (!Creed) { throw new Error(`Unable to find '${type}' in given knownTypes`) } const hydrated = new Creed(value) // This is require for ImmutableJS::Record if (typeof hydrated === 'function') { return hydrated() } return hydrated } export default function hydrate(dehydrated: ?Object, knownTypes: Array<Function>) { if (!dehydrated) { return {} } return dehydrateItem(dehydrated, knownTypes) }
1.945313
2
msgcounter/routes/index.js
LocalizeFriends/message-counter
0
15998996
var express = require('express'), counter = require('../model/message-counter'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'FriendLocation / LocalizeFriends stats', count: counter.getCount() }); }); module.exports = router;
0.882813
1
.eslintrc.js
addy/tacos
0
15999004
module.exports = { parser: '@babel/eslint-parser', extends: ['airbnb', 'airbnb/hooks', 'prettier'], plugins: ['prettier', 'react-hooks'], rules: { 'prettier/prettier': ['error'], 'react/forbid-prop-types': 0, 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn', }, env: { browser: true, node: true, es6: true, }, }
0.683594
1
seeds/4topics.js
PortableTomb/Artikl-3.0
0
15999012
exports.seed = function(knex, Promise) { return knex('topics').del() .then(() => { return knex('topics').insert([{ id: 1, topic_id: 1, topic:"inspiration" }, { id: 2, topic_id: 2, topic:"admiration" }, { id: 3, topic_id: 3, topic:"resources" } ]); }) .then(() => { return knex.raw( "SELECT setval('topics_id_seq', (SELECT MAX(id) FROM topics));" ); }); };
1.109375
1
src/views/Pinjaman/components/PinjamanTable/index.js
apapGroupB/tugas-akhir-apap-b8-frontend
0
15999020
export { default } from './PinjamanTable'
-0.198242
0
commands/play.js
dsprenkels/discord-bot
0
15999028
const { Util } = require("discord.js"); const ytdl = require("youtube-dl"); const moment = require("moment"); const momentDurationFormatSetup = require("moment-duration-format"); const ytSearch = require('youtube-search'); const { ytApiKey, } = require('./playContext.json'); const searchOpts = { maxResults: 5, key: ytApiKey, type: "video" }; const urlPattern = new RegExp('^(https?:\\/\\/)?'+ // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(\\#[-a-z\\d_]*)?$','i'); // fragment locator function intOrNaN (x) { return /^\d+$/.test(x) ? +x : NaN } function isValidURL(str) { return !!urlPattern.test(str); } module.exports = { name: "play", description: "Play a song in your channel!", async execute(message) { try { const args = message.content.split(" "); const voiceChannel = message.member.voice.channel; if (!voiceChannel) return message.channel.send( "You need to be in a voice channel to play music!" ); const permissions = voiceChannel.permissionsFor(message.client.user); if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) { return message.channel.send( "I need the permissions to join and speak in your voice channel!" ); } if(isValidURL(args[1])) { this.queue(args[1], message); return; } const searchIndex = intOrNaN(args[1]); if(!isNaN(searchIndex)) { var searchResults = message.client.searchResults; var username = message.member.user.username; if(!(username in searchResults)) { message.channel.send("You did not perform a search yet."); return; } results = searchResults[username]; if(searchIndex < 0 || searchIndex >= results.length) { message.channel.send("Index out of range for search results"); return; } this.queue(results[searchIndex].link, message); return; } if(!isNaN(+args[1])) { message.channel.send("I'm not sure which integer you meant."); return; } args.shift(); this.search(args.join(' '), message); } catch (error) { console.log(error); message.channel.send(error.message); } }, async search(query, message) { ytSearch(query, searchOpts, (err, results) => { if(err) { console.log(err); return; } var searchResults = message.client.searchResults; searchResults[message.member.user.username] = results; var resultEntries = results.map((result, index) => `${index}) "${result.title}", by channel "${result.channelTitle}"`); var resultMessage = resultEntries.join("\n"); message.channel.send(resultMessage); }); }, async queue(url, message) { const queue = message.client.queue; const serverQueue = message.client.queue.get(message.guild.id); const voiceChannel = message.member.voice.channel; var self = this; ytdl.getInfo(url, async function (err, songInfo) { if (err) { console.log(err); return; } const nickname = message.member.nickname || message.member.user.username; const song = { title: songInfo.title, url: songInfo.url, queuer: nickname, duration: songInfo._duration_raw, durationString: moment.duration(parseInt(songInfo._duration_raw), "seconds").format("h:mm:ss") }; if (!serverQueue) { const queueContruct = { textChannel: message.channel, voiceChannel: voiceChannel, connection: null, songs: [], volume: 4, playing: true }; queue.set(message.guild.id, queueContruct); queueContruct.songs.push(song); try { var connection = await voiceChannel.join(); queueContruct.connection = connection; self.play(message, queueContruct.songs[0]); } catch (err) { console.log(err); queue.delete(message.guild.id); return message.channel.send(err); } } else { serverQueue.songs.push(song); return message.channel.send( `${song.title} (${song.durationString}) has been added to the queue!` ); } }) }, async play(message, song) { const queue = message.client.queue; const guild = message.guild; const serverQueue = queue.get(message.guild.id); if (!song) { serverQueue.voiceChannel.leave(); queue.delete(guild.id); return; } var stream = ytdl(song.url); stream.on('error', err => { if(err.code == 'ESOCKETTIMEDOUT') return; serverQueue.songs.shift(); return this.play(message, serverQueue.songs[0]); }); stream.on('info', async () => { const dispatcher = serverQueue.connection .play(stream) .on("finish", async () => { serverQueue.songs.shift(); await this.play(message, serverQueue.songs[0]); }) .on("error", error => console.error(error)); dispatcher.setVolumeLogarithmic(serverQueue.volume / 5); serverQueue.textChannel.send(`Start playing: **${song.title}** (${song.durationString})`); }); } };
1.78125
2
packages/react-app/src/helpers/index.js
tricelex/tip.party
20
15999036
export { default as Transactor } from "./Transactor"; export { default as Address } from "./Address";
0.103027
0
src/view/gateway/options.js
wp1016/wlan
0
15999044
export const simNumberSourceOptions = { 0: '本地', 1: 'ESPS', 2: 'ETMS', 3: '不限制' } export const operatorsSourceOptions = { 0: '注册运营商', 1: 'IMSI' } export const callDurationDataSourceOptions = { 0: '禁用', 1: 'FLASH' }
0.578125
1
external/flowtest/test/flow/types/this_constraints/function_type_1.js
asklar/hermes-windows
20,996
15999052
type Fn = (this: {...}, x: string) => void;
0.636719
1
src/pages/forms/components/Forms/LeadDetails.js
davidtraverso/PartyApp
0
15999060
import React, {Component} from 'react'; import Container from '@material-ui/core/Container'; import Geosuggest from 'react-geosuggest'; class LeadDetails extends Component { // Function to go to next form continue = event => { event.preventDefault() this.props.nextStep(); } // Function to go back to previous form back = event => { event.preventDefault() this.props.prevStep(); } render() { const {values, handleChange} = this.props; return( <div> <div id="paper" className="container p-5 text-center shadow-lg"> <h1>Tell us about yourself:</h1> <label className="control-label sr-only">Your name:</label> <input type="text" onChange={handleChange('uName')} placeholder="Your Name" defaultValue={values.uName} className="d-block w-100" /> <label className="control-label sr-only">Your email:</label> <input type="text" onChange={handleChange('uEmail')} placeholder="Your Email" defaultValue={values.uEmail} className="d-block w-100" /> <label className="control-label sr-only">Your phone:</label> <input type="text" onChange={handleChange('uPhone')} placeholder="Your Phone Number" defaultValue={values.uPhone} className="d-block w-100" /> <label for="residence" className="control-label"><h5>Your city of residence:</h5></label> <Geosuggest /> <label className="control-label"><h5>How do you know {values.bride}:</h5></label> <input type="text" onChange={handleChange('uBio')} placeholder="Relationship?" defaultValue={values.uBio} className="d-block w-100" /> {/* Navigation Buttons */} <input className="w-25 btn btn-lg btn-outline-light submit-item rounded-0" type="button" label="Back" value="Back" onClick={this.back} /> <input className="w-25 btn btn-lg btn-outline-light submit-item rounded-0" type="button" label="Continue" value="Continue" onClick={this.continue} /> </div> </div> ); } } export default LeadDetails
1.75
2
client/components/add-product.js
GraceShopper-Team7/grace-shopper
1
15999068
import {connect} from 'react-redux' import React, {Component} from 'react' import {addProduct} from '../store/product' import ProductForm from './product-form' const initialState = { title: '', imageUrl: '', price: 0, description: '', ingredients: [], inventoryQty: 0, typeId: 0 } class AddProduct extends Component { constructor(props) { super(props) this.state = initialState this.handleSubmit = this.handleSubmit.bind(this) this.handleChange = this.handleChange.bind(this) } handleChange(evt) { evt.target.name === 'ingredients' ? this.setState({[evt.target.name]: evt.target.value.split(', ')}) : this.setState({[evt.target.name]: evt.target.value}) } handleSubmit(evt) { evt.preventDefault() this.props.submitProduct({...this.state}).then(() => { this.props.history.push('/products') }) } render() { return ( <ProductForm handleSubmit={this.handleSubmit} handleChange={this.handleChange} {...this.state} /> ) } } const mapDispatch = dispatch => ({ submitProduct: product => dispatch(addProduct(product)) }) export default connect(null, mapDispatch)(AddProduct)
1.734375
2
pi-dotnetcore/projects/monit-hackernews/wwwroot/js/utils.js
tongni1975/stackup-workshops
12
15999076
// https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1 // Blazor will automatically escape raw html. // Run a client-side script to decode for readability in the browser. // https://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript function htmlDecode(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; } window.unescapeHtml = (rawHtml) => { return htmlDecode(rawHtml); };
1.375
1
src/main/resources/br/com/arsmachina/tapestrycrud/javascript/treeselect.js
thiagohp/tapestry-crud
2
15999084
var TreeSelect = { disableDescendentInputs: function(id) { // id is always an <input>, so we need its parent, a <li> var parent = $(id).parentNode; parent.select("li").each( function(li) { // the no parent option is always enabled if (li.hasClassName("noParentOption") == false) { li.addClassName("disabled"); } } ); // turning off disabled option <input>s de opções parent.select("input").each( function(input) { if (!input.checked) { input.disabled = true; } } ); }, handleChange: function(radioId, clientId) { $(clientId).select("li.checked").each( function(label) { label.removeClassName("checked"); } ); var parentNode = $(radioId).parentNode; if (parentNode.addClassName == undefined) { Element.extend(parentNode); } parentNode.addClassName("checked"); } };
1.398438
1
client/src/components/Onboarding/CreateTeam.js
labs12-slack-standup/labs12-slack-standup-FE
1
15999092
import React, { Component } from 'react'; import { Card, Button, Fab, Icon, Dialog, DialogTitle, Slide } from '@material-ui/core'; import ChipInput from 'material-ui-chip-input'; import './onboarding.css'; function Transition(props) { return <Slide direction="up" {...props} />; } class CreateTeam extends Component { render() { return ( <div className="onboarding"> <Card raised={true} className="onboardingCard"> <div className="onboarding-card-content"> <h3>Add Team Members by Email</h3> <ChipInput label="Email" variant="outlined" defaultValue={[]} onChange={chips => this.props.handleChipChange(chips)} placeholder="Press 'Enter' after each email" /> <Button color="primary" variant="contained" onClick={this.props.createTeam} > Create Team </Button> </div> </Card> <Dialog open={this.props.errorModal} TransitionComponent={Transition} keepMounted onClose={this.props.clearError} aria-labelledby="alert-dialog-slide-title" aria-describedby="alert-dialog-slide-description" > <DialogTitle id="alert-dialog-slide-title"> {this.props.error} </DialogTitle> <Button onClick={() => this.props.clearError()}>x</Button> </Dialog> <div className="create-team-buttons"> <Fab onClick={this.props.toggleAllOff} color="default" className="onboarding-back" > <Icon>arrow_back</Icon> </Fab> <Button variant="outlined" onClick={this.props.joinToggle}> Join an Existing Team </Button> </div> </div> ); } } export default CreateTeam;
1.585938
2
app/containers/DashboardPage/actions.js
RobertSomodi/RAU
0
15999100
import { SIGN_IN_ERROR, SIGN_IN, CHANGE_USER_CREDENTIALS } from './constants' export function onChangeUserCredentials(user) { return { type: CHANGE_USER_CREDENTIALS, user, } } export function signIn(user) { return { type: SIGN_IN, user, } } /** * Dispatched when loading the repositories fails * * @param {object} error The error * * @return {object} An action object with a type of LOAD_REPOS_ERROR passing the error */ export function signInError(error) { return { type: SIGN_IN_ERROR, error, } }
0.960938
1
tests/acceptance/pretender-test.js
mydea/ember-cli-pretender
50
15999108
import { module, test } from 'qunit'; import { visit, currentURL } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import Pretender from 'pretender'; module('Acceptance | pretender', function(hooks) { setupApplicationTest(hooks); test('visiting /', async function(assert) { let server = new Pretender(); server.get('/test-pretender', () => [200, {"Content-Type": "application/json"}, JSON.stringify({ status: 'ok' })]); await visit('/'); assert.equal(currentURL(), '/'); assert.equal(this.element.querySelector('#status').textContent, 'ok'); }); });
1.375
1
client/src/redux/actions/patient/auth.js
mohsinyaqoob/ihealth
2
15999116
import { PATIENT_LOADED, AUTH_ERROR, LOGOUT, LOGIN_SUCCESS, LOGIN_FAIL } from './types' import axios from 'axios' import { toast } from 'react-toastify' import setAuthToken from '../../../utils/setAuthToken' const loadPatient = () => async dispatch => { if (localStorage.patientAuthToken) { setAuthToken(localStorage.patientAuthToken) } try { const res = await axios.get('/api/patient/auth'); dispatch({ type: PATIENT_LOADED, payload: res.data.patient }) } catch (err) { dispatch({ type: AUTH_ERROR }) // const errors = err.response.data.errors; // errors.forEach(error => toast(error.msg, { type: 'error' })) } } const login = ({ aadhaarNumber, password }) => async dispatch => { const body = JSON.stringify({ aadhaarNumber, password }) const config = { headers: { 'Content-type': 'application/json' } } try { const res = await axios.post('/api/patient/auth', body, config) dispatch({ type: LOGIN_SUCCESS, payload: res.data.token }) dispatch(loadPatient()) toast('You are logged in', { type: 'success' }) } catch (err) { dispatch({ type: LOGIN_FAIL }) const errors = err.response.data.errors errors.forEach(error => toast(error.msg, { type: 'error' })) } } const logout = () => async dispatch => { dispatch({ type: LOGOUT }) } export { loadPatient, login, logout }
1.367188
1
client/src/pages/index.js
jorupp/secure-static-blog
0
15999124
import React from "react" export default () => <div>Hello world 2!</div>
0.34375
0
_design/blueink/lib/lodash-filter.js
BigBlueHat/BlueInk
22
15999132
/** * https://wzrd.in/standalone/lodash.filter@latest **/ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),(f.lodash||(f.lodash={})).filter=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * lodash 3.1.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var arrayFilter = require('lodash._arrayfilter'), baseCallback = require('lodash._basecallback'), baseFilter = require('lodash._basefilter'), isArray = require('lodash.isarray'); /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias select * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.filter([4, 5, 6], function(n) { * return n % 2 == 0; * }); * // => [4, 6] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.filter(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.filter(users, 'active'), 'user'); * // => ['barney'] */ function filter(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = baseCallback(predicate, thisArg, 3); return func(collection, predicate); } module.exports = filter; },{"lodash._arrayfilter":2,"lodash._basecallback":3,"lodash._basefilter":8,"lodash.isarray":10}],2:[function(require,module,exports){ /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `_.filter` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[++resIndex] = value; } } return result; } module.exports = arrayFilter; },{}],3:[function(require,module,exports){ /** * lodash 3.3.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseIsEqual = require('lodash._baseisequal'), bindCallback = require('lodash._bindcallback'), isArray = require('lodash.isarray'), pairs = require('lodash.pairs'); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { return value == null ? '' : (value + ''); } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } return function(object) { return baseIsMatch(object, matchData); }; } /** * The base implementation of `_.matchesProperty` which does not clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Creates a function that returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = baseCallback; },{"lodash._baseisequal":4,"lodash._bindcallback":6,"lodash.isarray":10,"lodash.pairs":7}],4:[function(require,module,exports){ /** * lodash 3.0.7 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var isArray = require('lodash.isarray'), isTypedArray = require('lodash.istypedarray'), keys = require('lodash.keys'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseIsEqual; },{"lodash.isarray":10,"lodash.istypedarray":5,"lodash.keys":11}],5:[function(require,module,exports){ /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{}],6:[function(require,module,exports){ /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = bindCallback; },{}],7:[function(require,module,exports){ /** * lodash 3.0.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = require('lodash.keys'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; },{"lodash.keys":11}],8:[function(require,module,exports){ /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var baseEach = require('lodash._baseeach'); /** * The base implementation of `_.filter` without support for callback * shorthands or `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } module.exports = baseFilter; },{"lodash._baseeach":9}],9:[function(require,module,exports){ /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var keys = require('lodash.keys'); /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = baseEach; },{"lodash.keys":11}],10:[function(require,module,exports){ /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var arrayTag = '[object Array]', funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = isArray; },{}],11:[function(require,module,exports){ /** * lodash 3.1.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ var getNative = require('lodash._getnative'), isArguments = require('lodash.isarguments'), isArray = require('lodash.isarray'); /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keys; },{"lodash._getnative":12,"lodash.isarguments":13,"lodash.isarray":10}],12:[function(require,module,exports){ /** * lodash 3.9.1 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = getNative; },{}],13:[function(require,module,exports){ /** * lodash 3.0.4 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 <NAME>, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; },{}]},{},[1])(1) });
1.757813
2
src/migrator_config.js
caiges/migs
0
15999140
import Bluebird from 'bluebird'; import path from 'path'; export var MigratorConfig = function(options) { return { // The storage. // Possible values: 'json', 'sequelize', an object storage: options.run ? 'json' : path.join(__dirname, '/storages/dry.js'), // The options for the storage. // Check the available storages for further details. storageOptions: {}, // The logging function. // A function that gets executed everytime migrations start and have ended. logging: false, // The name of the positive method in migrations. upName: 'up', // The name of the negative method in migrations. downName: 'down', migrations: { // The params that gets passed to the migrations. // Might be an array or a synchronous function which returns an array. params: [], // The path to the migrations directory. path: path.join(process.cwd(), 'migrations'), // The pattern that determines whether or not a file is a migration. pattern: /^.*.js$/, wrap: function(func) { return Bluebird.promisify(func.bind({ env: options.env, dependencies: options.dependencies || null, run: options.run })); } } }; };
1.179688
1
Frontend/debouncing/debounce.js
kush1912/Machine-Coding
1
15999148
let counter=0; const getData = () => { console.log("Fetching Data..."+ counter++); } const debounce = (fname, delay)=>{ let timer; return function(...args){ if(timer){ clearTimeout(timer); } timer = setTimeout(()=>{ fname(...args); },delay); } } const betterfunction=debounce(getData,500);
1.359375
1
test/collateral/valid-insertionindex-with-copyright/fake-test262/test/runtime.js
bocoup/test262-stream
9
15999156
// Copyright (C) 2048 $ContributorName. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: License and correct insertionIndex ---*/ assert(true);
0.636719
1
spec/frontend/pipeline_editor/components/popovers/file_tree_popover_spec.js
HinchK/gitlabhq
0
15999164
import { nextTick } from 'vue'; import { GlLink, GlPopover, GlSprintf } from '@gitlab/ui'; import { shallowMount } from '@vue/test-utils'; import FileTreePopover from '~/pipeline_editor/components/popovers/file_tree_popover.vue'; import { FILE_TREE_POPOVER_DISMISSED_KEY } from '~/pipeline_editor/constants'; import { mockIncludesHelpPagePath } from '../../mock_data'; describe('FileTreePopover component', () => { let wrapper; const findPopover = () => wrapper.findComponent(GlPopover); const findLink = () => findPopover().findComponent(GlLink); const createComponent = ({ stubs } = {}) => { wrapper = shallowMount(FileTreePopover, { provide: { includesHelpPagePath: mockIncludesHelpPagePath, }, stubs, }); }; afterEach(() => { localStorage.clear(); wrapper.destroy(); }); describe('default', () => { beforeEach(async () => { createComponent({ stubs: { GlSprintf } }); }); it('renders dismissable popover', async () => { expect(findPopover().exists()).toBe(true); findPopover().vm.$emit('close-button-clicked'); await nextTick(); expect(findPopover().exists()).toBe(false); }); it('renders learn more link', () => { expect(findLink().exists()).toBe(true); expect(findLink().attributes('href')).toBe(mockIncludesHelpPagePath); }); }); describe('when popover has already been dismissed before', () => { it('does not render popover', async () => { localStorage.setItem(FILE_TREE_POPOVER_DISMISSED_KEY, 'true'); createComponent(); expect(findPopover().exists()).toBe(false); }); }); });
1.28125
1
components/JForm/index.js
niharjyoti333/sample-storybook
1
15999172
export {default} from './JForm';
0.234375
0
src/open-in-google-maps.js
niksy/bookmarklets
1
15999180
/* Verify current url looks like Google Maps URL *and* has query String then swap in URL protocol for Google Maps iOS app */ if ( window.location.hostname == 'maps.google.com' && window.location.search ) { window.location.assign('comgooglemaps://' + window.location.search); }
0.722656
1
src/components/templates/content_header.js
hisarkaya/polinsur
0
15999188
import React from 'react'; const ContentHeader = props => { return ( <div className="widget-title"> <span className="icon"> <i className={`icon-${props.icon}`}></i> </span> <h5>{props.title}</h5> {props.children} </div> ); } export default ContentHeader;
0.90625
1
react/outline/minimaize-circle.js
la-moore/scarlab-icons
3
15999196
import * as React from "react" function SvgComponent(props) { return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="scarlab scarlab-minimaize-circle" {...props}> <path d="M11 17L11 16L10.9999 13.5V13.5C10.9999 13.2239 10.7761 13 10.5 13V13L8 13L7 13" /> <path d="M13 7L13 8V10.5V10.5C13 10.7761 13.2239 11 13.5 11V11L16 11L17 11" /> <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" /> </svg> } export default SvgComponent
1.085938
1
lib/abacus.js
frapontillo/poppins-pr-vote
2
15999204
module.exports = { log2: function (x) { return Math.log(x) / Math.LN2; }, entropy: function (yays, nays) { var sum = yays + nays; var y = yays / sum; var n = nays / sum; return - (y * this.log2(y)) - (n * this.log2(n)); } };
1.296875
1
samples/blog/fragments/text/htmltovue.js
tsaurabh74/peregrine-cms
0
15999212
module.exports = { convert: function($, f) { f.bindPath($) f.mapRichField($.find('div'), 'text') } }
0.498047
0
imports/api/comments.js
jcpinilla/final-exam-webdev
0
15999220
import { Meteor } from "meteor/meteor"; import { Mongo } from "meteor/mongo"; export const Comments = new Mongo.Collection("comments"); if (Meteor.isServer) { Meteor.publish("comments", function commentsPublication() { return Comments.find(); }); } Meteor.methods({ "comments.insert"(agency, route, text) { let commentId = "" + (Comments.find({}).count() + 1); let comment = { _id: commentId, author: Meteor.user().username, text, agency, route, createdAt: new Date() }; Comments.insert(comment); } });
1.335938
1
services/ses-forwarder/handler.js
breezewang-0101/breezewang-0101.github.io
1
15999228
'use strict'; var sesForwarder = require('aws-lambda-ses-forwarder') module.exports.sesForwarder = function (evt, ctx) { // Configure the S3 bucket and key prefix for stored raw emails, and the // mapping of email addresses to forward from and to. // // Expected keys/values: // - fromEmail: Forwarded emails will come from this verified address // - emailBucket: S3 bucket name where SES stores emails. // - emailKeyPrefix: S3 key name prefix where SES stores email. Include the // trailing slash. // - forwardMapping: Object where the key is the email address from which to // forward and the value is an array of email addresses to which to send the // message. var overrides = { config: { fromEmail: "<EMAIL>", emailBucket: "habd.as-ses-email", emailKeyPrefix: "", forwardMapping: { "@habd.as": [ "<EMAIL>" ] } } }; sesForwarder.handler(evt, ctx, overrides); }
1.585938
2
main.js
wkwiatek/babel-async-test
0
15999236
const fs = require('fs') const babel = require('babel-core') const customPlugin = require('./plugin') const fileName = process.argv[2] fs.readFile(fileName, (err, data) => { if (err) throw err const src = data.toString() const out = babel.transform(src, { plugins: [customPlugin], presets: ['stage-0'] }) console.log(out.code) })
1.21875
1
src/pages/TechnicianDash.js
hassaankhan235/ThyssenRecords
0
15999244
import React, {useContext} from 'react' import Layout from './layout/layout' import IdentityContext from '../../IdentityContext' import WelcomeCard from '../WelcomeCard' import TechnicianMatrix from '../Components/TechnicianDash/TechnicianMatrix' import MenuContext from '../../MenuContext' import LoginCard from './app/components/LoginCard' function TechnicianDash() { const {user} = useContext(IdentityContext) const {Menustatus} = useContext(MenuContext) return ( <div > <Layout /> {user.email ? <> <WelcomeCard /> <TechnicianMatrix /> </> : <LoginCard /> } {/* {Menustatus ? <MenuCar /> : null} */} </div> ) } export default TechnicianDash
1.148438
1
examples/alternation.js
danigb/SVM
1
15999252
const Gibberish = require('gibberish-dsp') const AshVM = require('..') const vm = AshVM.init(Gibberish) window.onclick = () => { vm.stopAll() } const iterator = (opts) => { const len = opts.length let i = 0 return () => opts[i++ % len] } function alternation (rhythm) { const steps = (rhythm + rhythm).split('') const iter = iterator(['@conga', '@clave']) const alternated = steps.map(s => s === '.' ? s : iter()) return alternated } function toPattern (rhythm) { return rhythm.reduce((ptn, step) => { if (step !== '.') ptn.push(step) ptn.push('0.25') ptn.push('@wait') return ptn }, []) } vm.run(['@loop', toPattern(alternation('x.xxx.x.'))])
2.140625
2
lib/io-utils.js
loicortola/cdg-parser
1
15999260
const Promise = require('bluebird'); require('node-zip'); const fs = require('fs'); const path = require('path'); const mkdirp = Promise.promisify(require('mkdirp')); const readFile = Promise.promisify(fs.readFile); const writeFile = Promise.promisify(fs.writeFile); const access = Promise.promisify(fs.access); const unlink = Promise.promisify(fs.unlink); const readdir = Promise.promisify(fs.readdir); const stat = Promise.promisify(fs.stat); /** * Compress song data into destination zip * @param cdgFile * @param mp3File * @param destName * @returns {*} zip binary data */ const compressSongData = (cdgFile, mp3File, destName) => { const zip = new JSZip(); zip.file(destName + '.cdg', fs.readFileSync(cdgFile)); zip.file(destName + '.mp3', fs.readFileSync(mp3File)); return zip.generate({base64: false, compression: 'DEFLATE'}); }; /** * Get file with either lower or upper case extension * @param root the folder * @param name the file name (without extension) * @param ext the file extension (with dot. Ex: .zip) * @returns {string} or undefined if no file is found */ const getFileSync = (root, name, ext) => { let file = path.join(root, name + ext.toLowerCase()); try { fs.accessSync(file); return file; } catch (err) { } file = path.join(root, name + ext.toUpperCase()); try { fs.accessSync(file); return file; } catch (err) { } return; }; /** * Copy input file to error directory * @param config the configuration * @param input the input file path * @param output the output file name */ const copyToError = (config, input, output) => { fs.createReadStream(input).pipe(fs.createWriteStream(path.join(config.outputDir, 'errors', output))); }; /** * Copy input file to output file * @param input file * @param output file */ const copyTo = (input, output) => { fs.createReadStream(input).pipe(fs.createWriteStream(output)); }; /** * Check whether lockfile is already present or not * @param lockFile the lockfile * @param callback the callback once response is ready */ const alreadyLocked = (lockFile, callback) => { fs.access(lockFile, (err) => { callback(!err); }); }; /** * Attempt to remove lock * @param lockFile * @param maxRetries * @param callback */ const removeLock = (lockFile, maxRetries, callback) => { // Remove lock unlink(lockFile) .then(() => { // Finish processing and callback callback(); }) .catch((err) => { if (err.code === 'ENOENT') { console.error('Lock for file ' + lockFile + ' was already removed.'); callback(); } else if (maxRetries > 0) { console.error('Attempted to remove lock but unknown error occured. Trying again'); setTimeout(() => removeLock(lockFile, --maxRetries, callback), 100 + Math.random() * 50); } else { console.error('Failed to remove lock for file ' + lockFile); console.error(err); throw new Error('Failed to remove lock for file ' + lockFile); } }); }; /** * Will check whether lock if present or not. If lock is present, will re-attempt until timeout is reached. * When lock is gone, will call processor function * @param lockFile * @param processor (err) => {} * @param maxRetries */ const lockOrWaitThenProcess = (lockFile, processor, maxRetries) => { if (maxRetries <= 0) { processor(new Error('Locked for too long!')); return; } alreadyLocked(lockFile, (locked) => { if (locked) { setTimeout(() => lockOrWaitThenProcess(lockFile, processor, --maxRetries), 200 + Math.random() * 100); } else { // Create lock (blocking) fs.closeSync(fs.openSync(lockFile, 'w')); processor(); } }); }; /** * Store song archive at destination * @param song the song metadata * @param lockFile the lockfile to remove after done * @param dest the destination zip path * @param zippedData the zip data * @param callback the callback(err, song) once done */ const storeZip = (song, lockFile, dest, zippedData, callback) => { // Create destination directory recursively mkdirp(dest.directory) .then(() => { // Write zip file in destination writeFile(path.join(dest.directory, dest.file), zippedData, 'binary') .then(() => { // Remove lock removeLock(lockFile, 8, () => { // Finish processing and callback song.isDuplicate = dest.isDuplicate || false; callback(null, song); }); }) .catch((err) => { console.log('Something unexpected happened.'); console.log(err); removeLock(lockFile, 8, () => { callback(err); }); }); }) .catch((err) => { callback('Error creating sub directories. Should not happen.\n' + err, song); }); }; /** * Store song archive at destination * @param song the song metadata * @param lockFile the lockfile to remove after done * @param dest the destination zip path * @param zipFile the zip file * @param callback the callback(err, song) once done */ const storeExistingZip = (song, lockFile, dest, zipFile, callback) => { // Create destination directory recursively mkdirp(dest.directory) .then(() => { // Write zip file in destination try { copyTo(zipFile, path.join(dest.directory, dest.file)); // Remove lock removeLock(lockFile, 8, () => { // Finish processing and callback song.isDuplicate = dest.isDuplicate || false; callback(null, song); }); } catch (err) { removeLock(lockFile, 8, () => { callback(err); }); } }) .catch((err) => { callback('Error creating sub directories. Should not happen.\n' + err, song); }); }; module.exports = { storeExistingZip, storeZip, lockOrWaitThenProcess, copyTo, copyToError, getFileSync, compressSongData, mkdirp, writeFile, access, unlink, readdir, readFile, stat };
1.71875
2
src/main.js
SihenZhang/library-ms-ui
2
15999268
import Vue from 'vue' import App from './App.vue' import router from './router' import axios from 'axios' import './plugins/element.js' // 导入全局样式表 import './assets/css/global.css' // 导入自定义字体图标 import './assets/fonts/iconfont.css' // 全局配置 axios,在组件内使用 this.$http 即可直接使用 axios Vue.prototype.$http = axios // 设置 axios 请求默认根路径 axios.defaults.baseURL = 'http://localhost:8090/api' // axios 请求拦截器,在请求头中挂载 token axios.interceptors.request.use(config => { config.headers.Authorization = window.sessionStorage.getItem('token') return config }) // axios 响应拦截器,判断 token 是否过期 axios.interceptors.response.use(response => { // 如果响应结果状态码为 401,代表 token 已过期 if (response.data.status === 401) { // 清空 sessionStorage window.sessionStorage.clear() // 跳转至登录页面 router.replace('login') } return response }) Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
1.078125
1
test/mocks/mock_runtime.js
rixter13/circ
223
15999276
// Generated by CoffeeScript 1.4.0 (function() { "use strict"; var Runtime, exports, _ref, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var exports = (_ref = window.mocks) != null ? _ref : window.mocks = {}; Runtime = (function() { Runtime.useMock = function() { chrome.runtime = new Runtime; return spyOn(chrome.runtime, 'reload'); }; function Runtime() { this._addUpdateListener = __bind(this._addUpdateListener, this); this.onUpdateAvailable = {}; this.onUpdateAvailable.addListener = this._addUpdateListener; } Runtime.prototype.reload = function() {}; Runtime.prototype._addUpdateListener = function(callback) { return this.updateAvailable = callback; }; return Runtime; })(); exports.Runtime = Runtime; }).call(this);
1.21875
1
assets/js/constant/http-headers-constant.js
ahmetyesil/YTIzlen-Extension-Frontend
0
15999284
class HTTPHeaders { static get SESSION_ID() { return 'Session-ID'; } }
0.249023
0
next.config.js
charmas3r/west-coast-pumeria-storefront
0
15999292
const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true", }); module.exports = withBundleAnalyzer({ reactStrictMode: true, swcMinify: true, images: { domains: [ "vercel.saleor.cloud", "img.youtube.com", "westcoastplumeria.s3.amazonaws.com", "images.unsplash.com"], formats: ["image/avif", "image/webp"], }, i18n: { locales: ["en-US"], defaultLocale: "en-US", }, });
1.132813
1
index.js
IAIAE/react-component-assume
0
15999300
module.exports = function(item){ return item?item:function(){return false}; }
0.523438
1
calculator.js
Anvi98/jest_tests
0
15999308
class Calculator { add(a, b) { if(a === undefined && b){ return ('number a missing'); } else if (b === undefined && a) { return ('b number not provided'); } else if(a === undefined && b === undefined) { return ('both value missing') } else { return a+b; } } substract(a,b) { if(a === undefined){ return ('number a missing'); } else if (b === undefined) { return ('b number missing'); } else { return a - b; } } multiply(a,b) { if(a === undefined && b){ return ('number a missing'); } else if (b === undefined && a) { return ('b number not provided'); } else if (a === undefined && b === undefined) { return ('both value missing') } else { return a*b; } } divide(a,b) { if(a === undefined || a === 0){ return ('number a missing or invalid number'); } else if (b === undefined || b === 0) { return ('b number missing or invalid number'); } else { return a/b; } } } module.exports = Calculator;
1.734375
2
public/assets/js/app.js
codenameyau/playground
2
15999316
'use strict'; // Initialize engine with options. var options = { dom: '#threejs-canvas', antialias: true }; var core = new ThreeJSCore(options); core.enableGrid(40, 4); core.scene.add(new THREE.AxisHelper(40)); core.setCameraPosition(0, 60, 90); // Light sources. var lightAmbient = new THREE.AmbientLight(0x5a5a5a); core.scene.add(lightAmbient); // Add Box to scene. var size = 8; var material = new THREE.MeshLambertMaterial(); var geometry = new THREE.BoxGeometry(size, size, size); geometry.applyMatrix( new THREE.Matrix4().makeTranslation(-size/2, size/2, size/2) ); var boxMesh = new THREE.Mesh(geometry, material); core.scene.add(boxMesh);
1.679688
2
public/app.js
Robert-Queeney/TODO-List-API-Project
1
15999324
// import { updateTodo } from "../helpers/todos"; // import { createTodo } from "../helpers/todos"; $(document).ready(() => { // this will get al of the existing tasks we have $.getJSON("api/todos") .then(addTodos) .catch((err) => { console.log(err) }); $('#todoInput').keypress((event) => { // this listens for keypress '13' which is 'enter' event.which === 13 ? createTodo() : ''; }); $('.list').on('click', 'li', function(){ updateTodo($(this)); }) // we are making this listener on the UL 'list' becasue the span itself isnt loaded when the page loads, but the UL is. this is b/c the span is added dynamically and the UL is hard coded in $('.list').on('click', 'span', function(e) { // need to use this code to get it to stop bubbling up - there is another click on the li that needs to happen independently from this one e.stopPropagation(); removeTodo($(this).parent()) }) }) addTodos = (todos) => { todos.forEach((todo) => { addTodo(todo); }); } // this is what makes the list addTodo = (todo) => { const newTodo = $('<li class="task">' + todo.name + '<span>x</span></li>') // this gives all created li's a data id of todo._id (dynamically creayed when we create new li's), which will allow us to delete them later newTodo.data('id', todo._id) // this is so we can reference the 'completed' data in order to make the list item appear done newTodo.data('completed', todo.completed) // this adds the class 'done' to the <li> and gives it the strikethrough effect todo.completed == true ? newTodo.addClass('done') : ''; $('.list').append(newTodo) } createTodo = () =>{ // send req to create new todo // below gets the value from the input const userInput = $('#todoInput').val(); // console.log(userInput); $.post('/api/todos', {name: userInput}) .then((newTodo) => { // directly below clears form $('#todoInput').val(''); // this calls 'addTodo' and adds the newToto (user input) addTodo(newTodo); }) .catch((err) => { console.log(err) }) } removeTodo = (todo) => { let clickedId = todo.data('id'); let deleteUrl = '/api/todos/' + clickedId; $.ajax({ method: 'DELETE', url: deleteUrl, }) .then((data) => { todo.remove(); }) } function updateTodo(todo){ let updateUrl = '/api/todos/' + todo.data('id'); // need to get the true/false data ('isDone') then use that in updateData to change the data let isDone = !todo.data('completed'); let updateData = {completed: isDone} $.ajax({ method: 'PUT', url: updateUrl, data: updateData }) .then((updatedTodo) => { // this will change completed from true to false in the view todo.toggleClass('done'); // this allows for it to change the data todo.data('completed', isDone) }) }
2.015625
2
dist/lib/commonComponents/CommonModal.js
shrutishankar28/react-native-common-lib
0
15999332
//# sourceMappingURL=CommonModal.js.map
0.223633
0
pages/contacts.js
vasyl-007/next
0
15999340
const Contacts = () => { return <h1>Contacts page</h1>; }; export default Contacts;
0.486328
0
frontend/src/pages/login.js
Meira-JH/pokeapi
0
15999348
import { useRouter } from 'next/router' import { useEffect } from 'react'; import LoginSection from '../containers/LoginSection' export default function Login(props) { const router = useRouter() useEffect(() => { const token = localStorage.getItem("token"); console.log(token) if(token){ router.push('/') } }, [] ); return ( <> <LoginSection /> </> ); } export function getStaticProps() { return { props: {}, }; }
1.179688
1
L06/practice/task03.js
PMDimitrova/HomeWorkITT
0
15999356
let arr = ['a', 'b', 'c']; let char = 'c'; let indexOfChar = arr.indexOf(char); console.log(indexOfChar === -1 ? "the array DOES NOT contain the char" : "the array contains the char on index " + indexOfChar);
1.8125
2
webshop-api/routes/users.js
Vdf-HumansInLearning/stefanb-vdf
0
15999364
var express = require("express"); var router = express.Router(); const fs = require("fs"); const path = require("path"); router.get("/", function (req, res) { let users = JSON.parse( fs.readFileSync(path.resolve(__dirname, "../data/users.json"), "utf8") ); if (!users) { res.status(404).send("Users not found"); } res.json(users); }); router.get("/:id", function (req, res) { let users = JSON.parse( fs.readFileSync(path.resolve(__dirname, "../data/users.json"), "utf8") ); const user = users.find((user) => user.id == req.params.id); if (!user) { res.status(404).send("The user with the given id was not found"); } res.json(user); }); router.delete("/:id", function (req, res) { let users = JSON.parse( fs.readFileSync(path.resolve(__dirname, "../data/users.json"), "utf8") ); let updatedUsers = users.filter((user) => user.id != req.params.id); try { fs.writeFileSync( path.resolve(__dirname, "../data/users.json"), JSON.stringify(updatedUsers) ); res.send(`User with id:${req.params.id} deleted`); } catch (err) { console.error(err); res.send("Error"); } }); router.post("/", function (req, res) { let users = JSON.parse( fs.readFileSync(path.resolve(__dirname, "../data/users.json"), "utf8") ); if ( req.body.username && req.body.name && req.body.email && req.body.password ) { let userToAdd = { id: users[users.length - 1].id + 1, name: req.body.name, username: req.body.username, email: req.body.email, password: <PASSWORD>, address: { street: "", suite: "", city: "", zipcode: "", }, phone: "", website: "", company: { name: "", catchPhrase: "", bs: "", }, }; if (validUser(userToAdd)) { users.push(userToAdd); fs.writeFileSync( path.resolve(__dirname, "../data/users.json"), JSON.stringify(users) ); res.json(userToAdd); } else { res.status(400).send("User is not valid"); } } else { res.status(400).send("Please complete all fields"); } }); router.put("/:id", function (req, res) { let users = JSON.parse( fs.readFileSync(path.resolve(__dirname, "../data/users.json"), "utf8") ); let index = users.findIndex((item) => item.id === Number(req.params.id)); console.log(index); let user = users.find((user) => user.id == req.params.id); if ( req.body.username && req.body.name && req.body.email && req.body.password && user ) { let userToUpdate = { id: user.id, name: req.body.name, username: req.body.username, email: req.body.email, password: <PASSWORD>, address: { street: "", suite: "", city: "", zipcode: "", }, phone: "", website: "", company: { name: "", catchPhrase: "", bs: "", }, }; if (validUser(userToUpdate)) { users[index] = userToUpdate; fs.writeFileSync( path.resolve(__dirname, "../data/users.json"), JSON.stringify(users) ); res.json(userToUpdate); } else { res.status(400).send("User is not valid"); } } else { res.status(400).send("Please complete all fields"); } }); function validUser(user) { const letters = /^[A-Za-z]+$/; const lowerCaseLetters = /[a-z]/g; const upperCaseLetters = /[A-Z]/g; const numbers = /[0-9]/g; const minLengthPassword = 8; const minLengthName = 3; const minLengthUsername = 3; const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; let valid = false; if ( user.name.match(letters) && user.name.length >= minLengthName && user.username.length >= minLengthUsername && user.password.match(lowerCaseLetters) && user.password.match(upperCaseLetters) && user.password.match(numbers) && user.password.length >= minLengthPassword && emailRegex.test(user.email) ) { valid = true; } return valid; } module.exports = router;
1.507813
2
assets/js/components/Navigation/Search.js
nailsapp/module-admin
0
15999372
class Search { /** * Constructs Search * @param {Navigation} mainController The main navigation controller * @param {DOMElement} element The DOMElement to bind to */ constructor(mainController, element) { this.mainController = mainController; this.element = element; if (this.element) { this.init(); } } // -------------------------------------------------------------------------- /** * Initlaises the sidebar search * @returns {Search} */ init() { this.element .addEventListener('keyup', (e) => { clearTimeout(this.debounce); this.debounce = setTimeout(() => { let keywords = this.normaliseSearchString(e.srcElement.value); if (this.keywords !== keywords) { this.keywords = keywords; this.search(keywords); } }, 250); }); return this; } // -------------------------------------------------------------------------- /** * Performs a search * @param {string} keywords The search keywords * @returns {Search} */ search(keywords) { if (keywords.length) { this.filter(keywords); } else { this.reset(); } return this; } // -------------------------------------------------------------------------- /** * Filters the sidebar sections by the given keywords * @param {string} keywords * @returns {Search} */ filter(keywords) { this.mainController.adminController.log(`Filtering nav sections by: ${keywords}`); this.mainController .disableAnimation() .disableSorting(); this.hideToggles(); let regex = new RegExp(keywords, 'i'); this.mainController .sections .forEach((section) => { section.instance.box.container .querySelectorAll('li') .forEach((item) => { let link = item.querySelector('a'); let text = this.normaliseSearchString( [link.textContent, link.dataset['search-terms']].join('') ); if (regex.test(text)) { item.classList.remove('hidden'); } else { item.classList.add('hidden'); } }); // If there are no visible options, hide the box let visible = section.instance.box.container .querySelectorAll('li:not(.hidden)') if (visible.length) { section.instance.box.element.classList.remove('hidden', 'closed'); // Size the box to accommodate visible options let height = section.instance.box.container.querySelector('ul').offsetHeight; section.instance.box.container.style.height = `${height}px`; } else { section.instance.box.element.classList.add('hidden'); } }); return this; } // -------------------------------------------------------------------------- /** * Resets the sidebar to how it was prior to searching * @returns {Search} */ reset() { this.mainController.adminController.log('Resetting...'); this.mainController .sections .forEach((section) => { section.instance.box.element .classList.remove('hidden'); section.instance.box.container .querySelectorAll('li') .forEach((item) => { item.classList.remove('hidden'); }); if (section.instance.isOpen()) { section.instance.open(); } else { section.instance.close(); } }); this.showToggles(); this.mainController .enableAnimation() .enableSorting(); return this; } // -------------------------------------------------------------------------- /** * Normalises the search term * @param searchString * @returns {string} */ normaliseSearchString(searchString) { return searchString.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); }; // -------------------------------------------------------------------------- /** * Hides all the section tiggles * @returns {Search} */ hideToggles() { this.mainController .sections .forEach((section) => { section.instance.hideToggles(); }); return this; } // -------------------------------------------------------------------------- /** * Shows all the section tiggles * @returns {Search} */ showToggles() { this.mainController .sections .forEach((section) => { section.instance.showToggles(); }); return this; } } export default Search;
1.835938
2
lib/Stores/Room.js
Snipey/hiven.js
0
15999380
// Store Base const Store = require('./Store'); // Room class class Room extends Store { constructor(Client) { super(); this.Client = Client; this.rest = global.rest; } async collect(key, value) { if (typeof value == 'object') { value.send = this.send; value.delete = this.delete; } super.set(key, value); return super.get(key); } async send(content) { // Send the message to the api let sendMessage = await global.rest.post(`/houses/${this.house.id}/rooms/${this.id}/messages`, { data: { content } }); let message = { id: sendMessage.data.data.id, content: sendMessage.data.data.content, timestamp: new Date(sendMessage.data.data.timestamp), room: global.Client.rooms.get(sendMessage.data.data.room_id), house: global.Client.houses.get(sendMessage.data.data.house_id), author: global.Client.users.get(sendMessage.data.data.author_id) }; let collect = await global.Client.messages.collect(message.id, message); return collect; } async delete() { let deleteRoom = await global.rest.delete(`/houses/${this.house.id}/rooms/${this.id}`); return deleteRoom; } } // Export class module.exports = Room;
1.5625
2
gw-frontend/app/containers/App/index.js
iotmaxx/gw-webinterface
0
15999388
/** * * App.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * */ import React, { useEffect } from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import AuthRoute from 'components/AuthRoute'; import LoginView from 'containers/LoginView/Loadable'; import Dashboard from 'containers/Dashboard/Loadable'; import IoComServer from 'containers/IoComServer/Loadable'; import IoInputs from 'containers/IoInputs/Loadable'; import IoOutputs from 'containers/IoOutputs/Loadable'; import IoPhonebook from 'containers/IoPhonebook/Loadable'; import IoSocketServer from 'containers/IoSocketServer/Loadable'; import LocalNetworkDhcpServer from 'containers/LocalNetworkDhcpServer/Loadable'; import LocalNetworkIpConfig from 'containers/LocalNetworkIpConfig/Loadable'; import LocalNetworkStaticRoutes from 'containers/LocalNetworkStaticRoutes/Loadable'; import NetworkSecurityFirewall from 'containers/NetworkSecurityFirewall/Loadable'; import NetworkSecurityGeneralSetup from 'containers/NetworkSecurityGeneralSetup/Loadable'; import NetworkSecurityIpAndPortForwarding from 'containers/NetworkSecurityIpAndPortForwarding/Loadable'; import StatusComServer from 'containers/StatusComServer/Loadable'; import StatusDhcpLeases from 'containers/StatusDhcpLeases/Loadable'; import StatusIoStats from 'containers/StatusIoStats/Loadable'; import StatusNetworkConnections from 'containers/StatusNetworkConnections/Loadable'; import StatusRadio from 'containers/StatusRadio/Loadable'; import StatusRoutingTable from 'containers/StatusRoutingTable/Loadable'; import StatusSystemInfo from 'containers/StatusSystemInfo/Loadable'; import SystemConfiguration from 'containers/SystemConfiguration/Loadable'; import SystemHardware from 'containers/SystemHardware/Loadable'; import SystemLogFile from 'containers/SystemLogFile/Loadable'; import SystemReboot from 'containers/SystemReboot/Loadable'; import SystemRtc from 'containers/SystemRtc/Loadable'; import SystemSmtpConfiguration from 'containers/SystemSmtpConfiguration/Loadable'; import SystemSnmpConfiguration from 'containers/SystemSnmpConfiguration/Loadable'; import SystemSoftware from 'containers/SystemSoftware/Loadable'; import SystemSystemConfiguration from 'containers/SystemSystemConfiguration/Loadable'; import SystemUpAndDownload from 'containers/SystemUpAndDownload/Loadable'; import SystemUser from 'containers/SystemUser/Loadable'; import SystemFirmwareUpdate from 'containers/SystemFirmwareUpdate/Loadable'; import VpnIPsecCertificates from 'containers/VpnIPsecCertificates/Loadable'; import VpnIPsecConnections from 'containers/VpnIPsecConnections/Loadable'; import VpnIPsecStatus from 'containers/VpnIPsecStatus/Loadable'; import VpnOpenVpnCertificates from 'containers/VpnOpenVpnCertificates/Loadable'; import VpnOpenVpnConnections from 'containers/VpnOpenVpnConnections/Loadable'; import VpnOpenVpnPortForwarding from 'containers/VpnOpenVpnPortForwarding/Loadable'; import VpnOpenVpnStaticKeys from 'containers/VpnOpenVpnStaticKeys/Loadable'; import VpnOpenVpnStatus from 'containers/VpnOpenVpnStatus/Loadable'; import WirelessNetworkBackupSim from 'containers/WirelessNetworkBackupSim/Loadable'; import WirelessNetworkConnectionCheck from 'containers/WirelessNetworkConnectionCheck/Loadable'; import WirelessNetworkDynDns from 'containers/WirelessNetworkDynDns/Loadable'; import WirelessNetworkPacketDataSetup from 'containers/WirelessNetworkPacketDataSetup/Loadable'; import WirelessNetworkRadioSetup from 'containers/WirelessNetworkRadioSetup/Loadable'; import WirelessNetworkSim from 'containers/WirelessNetworkSim/Loadable'; import WirelessNetworkSmsConfig from 'containers/WirelessNetworkSmsConfig/Loadable'; import WirelessNetworkStaticRoutes from 'containers/WirelessNetworkStaticRoutes/Loadable'; import SettingsView from 'containers/SettingsView/Loadable'; import NotFoundPage from 'containers/NotFoundPage/Loadable'; import SideNav from 'components/SideNav/Loadable'; import Header from 'components/Header'; import styled from 'styled-components'; import injectReducer from 'utils/injectReducer'; import { connect } from 'react-redux'; import { compose } from 'redux'; import LoginReducer from './reducers'; import GlobalStyle from '../../global-styles'; import { ROUTES, ACCESS_TOKEN } from './constants'; import { logout, loginSuccess } from './actions'; import ContentHeader from '../../components/ContentHeader'; const MainWrapper = styled.div` display: flex; flex-direction: column; height: inherit; `; const BodyWrapper = styled.div` display: flex; flex-direction: row; height: calc(100% - 10vh); justify-content: flex-start; `; const ContentWrapper = styled.div` width: 100%; display: flex; flex-direction: column; align-items: flex-start; `; function App(props) { useEffect(() => { const accessToken = localStorage.getItem(ACCESS_TOKEN); if (accessToken !== null && accessToken !== undefined && !props.loggedIn) props.doLoginSuccess(); }); return ( <MainWrapper> <Header /> <BodyWrapper> <SideNav logout={props.doLogout} loggedIn={props.loggedIn} /> <ContentWrapper> {props.loggedIn && <ContentHeader />} <Switch> <Route exact path="/"> <Redirect to={ROUTES.dashboard} /> </Route> <Route exact path={ROUTES.login} component={LoginView} /> <AuthRoute exact path={ROUTES.dashboard} component={Dashboard} /> <AuthRoute exact path={ROUTES.status.radio} component={StatusRadio} /> <AuthRoute exact path={ROUTES.status.networkConnection} component={StatusNetworkConnections} /> <AuthRoute exact path={ROUTES.status.ioStatus} component={StatusIoStats} /> <AuthRoute exact path={ROUTES.status.comServer} component={StatusComServer} /> <AuthRoute exact path={ROUTES.status.routingTable} component={StatusRoutingTable} /> <AuthRoute exact path={ROUTES.status.dhcpLease} component={StatusDhcpLeases} /> <AuthRoute exact path={ROUTES.status.systemInfo} component={StatusSystemInfo} /> <AuthRoute exact path={ROUTES.localNetwork.ipConfig} component={LocalNetworkIpConfig} /> <AuthRoute exact path={ROUTES.localNetwork.dhcpServer} component={LocalNetworkDhcpServer} /> <AuthRoute exact path={ROUTES.localNetwork.staticRoutes} component={LocalNetworkStaticRoutes} /> <AuthRoute exact path={ROUTES.wifi.radioSetup} component={WirelessNetworkRadioSetup} /> <AuthRoute exact path={ROUTES.wifi.sim} component={WirelessNetworkSim} /> <AuthRoute exact path={ROUTES.wifi.backupSim} component={WirelessNetworkBackupSim} /> <AuthRoute exact path={ROUTES.wifi.smsConfig} component={WirelessNetworkSmsConfig} /> <AuthRoute exact path={ROUTES.wifi.packetDataSetup} component={WirelessNetworkPacketDataSetup} /> <AuthRoute exact path={ROUTES.wifi.staticRoutes} component={WirelessNetworkStaticRoutes} /> <AuthRoute exact path={ROUTES.wifi.dynDns} component={WirelessNetworkDynDns} /> <AuthRoute exact path={ROUTES.wifi.connectionCheck} component={WirelessNetworkConnectionCheck} /> <AuthRoute exact path={ROUTES.networkSecurity.general} component={NetworkSecurityGeneralSetup} /> <AuthRoute exact path={ROUTES.networkSecurity.firewall} component={NetworkSecurityFirewall} /> <AuthRoute exact path={ROUTES.networkSecurity.ipPortForwarding} component={NetworkSecurityIpAndPortForwarding} /> <AuthRoute exact path={ROUTES.ipSec.connection} component={VpnIPsecConnections} /> <AuthRoute exact path={ROUTES.ipSec.certificates} component={VpnIPsecCertificates} /> <AuthRoute exact path={ROUTES.ipSec.status} component={VpnIPsecStatus} /> <AuthRoute exact path={ROUTES.openVpn.connections} component={VpnOpenVpnConnections} /> <AuthRoute exact path={ROUTES.openVpn.portForwarding} component={VpnOpenVpnPortForwarding} /> <AuthRoute exact path={ROUTES.openVpn.certificates} component={VpnOpenVpnCertificates} /> <AuthRoute exact path={ROUTES.openVpn.staticKeys} component={VpnOpenVpnStaticKeys} /> <AuthRoute exact path={ROUTES.openVpn.status} component={VpnOpenVpnStatus} /> <AuthRoute exact path={ROUTES.io.inputs} component={IoInputs} /> <AuthRoute exact path={ROUTES.io.outputs} component={IoOutputs} /> <AuthRoute exact path={ROUTES.io.phonebook} component={IoPhonebook} /> <AuthRoute exact path={ROUTES.io.socketServer} component={IoSocketServer} /> <AuthRoute exact path={ROUTES.io.comServer} component={IoComServer} /> <AuthRoute exact path={ROUTES.system.hardware} component={SystemHardware} /> <AuthRoute exact path={ROUTES.system.software} component={SystemSoftware} /> <AuthRoute exact path={ROUTES.system.systemConfiguration} component={SystemSystemConfiguration} /> <AuthRoute exact path={ROUTES.system.user} component={SystemUser} /> <AuthRoute exact path={ROUTES.system.logFiles} component={SystemLogFile} /> <AuthRoute exact path={ROUTES.system.snmpConfig} component={SystemSnmpConfiguration} /> <AuthRoute exact path={ROUTES.system.smtpConfig} component={SystemSmtpConfiguration} /> <AuthRoute exact path={ROUTES.system.config} component={SystemConfiguration} /> <AuthRoute exact path={ROUTES.system.upDownload} component={SystemUpAndDownload} /> <AuthRoute exact path={ROUTES.system.rtc} component={SystemRtc} /> <AuthRoute exact path={ROUTES.system.reboot} component={SystemReboot} /> <AuthRoute exact path={ROUTES.system.firmwareUpdate} component={SystemFirmwareUpdate} /> <AuthRoute exact path={ROUTES.settings} component={SettingsView} /> <Route component={NotFoundPage} /> </Switch> </ContentWrapper> </BodyWrapper> <GlobalStyle /> </MainWrapper> ); } App.propTypes = { doLogout: PropTypes.func, doLoginSuccess: PropTypes.func, loggedIn: PropTypes.bool, }; function mapDispatchToProps(dispatch) { return { doLogout: () => { dispatch(logout()); }, doLoginSuccess: () => { dispatch(loginSuccess()); }, }; } function mapStateToProps(state) { return { loggedIn: state.App.loggedIn, }; } const withConnect = connect( mapStateToProps, mapDispatchToProps, ); const withReducer = injectReducer({ key: 'App', reducer: LoginReducer }); export default compose( withReducer, withConnect, )(App);
1.09375
1
part5/bloglist-frontend/src/components/BlogForm.test.js
PortoRAF/fullstack-open
0
15999396
import React from 'react' import '@testing-library/jest-dom/extend-expect' import { render, fireEvent } from '@testing-library/react' import BlogForm from './BlogForm' test('form should call event handler with correct details', () => { const newBlog = { title: 'test blog title', author: 'test blog author', url: 'test blog url' } const createBlog = jest.fn() const component = render( <BlogForm createBlog={createBlog} /> ) const form = component.container.querySelector('form') const titleInput = component.container.querySelector('#title') const authorInput = component.container.querySelector('#author') const urlInput = component.container.querySelector('#url') fireEvent.change(titleInput, { target: { value: newBlog.title } }) fireEvent.change(authorInput, { target: { value: newBlog.author } }) fireEvent.change(urlInput, { target: { value: newBlog.url } }) fireEvent.submit(form) expect(createBlog.mock.calls).toHaveLength(1) expect(createBlog).toHaveBeenCalledWith(newBlog) })
1.648438
2
static/searchface/js/components/banner.js
samdebug/Beego-web
2
15999404
"use strict" var pageDocName = ["surveillance", "history", "task", "target", "statistic", "search"];//文件名 var pageName = ["Monitor", "History", "Task", "Target", "Statistic", "Match"];//页面名 var suffixHtml = "";//文件后缀名 var Banner = '<ul>'; var Logo = '<li id="logo" class="logo-li logo-highlight"><div class="logo-li-div"><img id="logo-img" src="../img/logo.png"></div></li>'; var Navigation = ''; (function printNavigation (){ var fileName = location.href.substr(location.href.lastIndexOf('/')+1); //fileName = fileName.replace(/.html/, ""); var isCurrent = ""; if (fileName == pageDocName[0]) { isCurrent = " current"; } Navigation = Navigation + '<li class="logo-li' + isCurrent +'"><ul class="logo-li-ul">' + '<li class="navigation-li"><div class="logo-li-div"><img src="../img/' + pageDocName[0] + '.png" /></div></li>' + '<li class="navigation-li"><div class="logo-li-div logo-alpha-40"><a class="navigation-anchor" href="' + pageDocName[0] + suffixHtml + '">' + pageName[0] + '</a></div></li>' + '</ul></li>'; pageName.splice(0, 1); pageDocName.splice(0, 1); if (pageName.length > 0){ printNavigation(); } }()); Banner = Banner + Logo + Navigation + '</ul><ul class="account">'; var Avatar = '<li class="account-outside-base"><div class="account-outside-base">' + '<div id="account-li-div" onclick="goToAccount()"><ul>' + '<li class="account-li"><div><img id="user-avatar" src="../img/avatar.jpg"><!--user s avatar--></div></li>' + '<li class="account-li"><div id="div-username"><span id="username">Admin</span></div></li>' + //<!--最长4个中文字符--> '</ul></div>' + '</div></li>'; var Clock = '<div id="clock"><ul><li class="clock-li"><div class="clock-div"><img src="../img/clock.png" /></div></li>' + '<li class="clock-li"><div class="clock-div">' + '<span id="full-date"></span> ' + '<span id="now-time"></span>' + '</div></li><div>'; Banner = Banner + Avatar + '</ul>' + Clock; document.getElementById("banner").innerHTML = Banner; (function (){ $(".navigation-anchor").on("mouseenter", function(){ var logoList = this.parentNode.parentNode.parentNode.parentNode; $(logoList).addClass("actived"); }); $(".navigation-anchor").on("mouseleave", function(){ var logoList = this.parentNode.parentNode.parentNode.parentNode; $(logoList).removeClass("actived"); }); }()); function goToAccount(){ window.location.href = "/account"; }
1.28125
1
src/reactapp/src/context/Form/index.js
rajeev-k-tomy/magento2-hyva-checkout
9
15999412
import FormStepProvider from './Step/StepProvider'; import FormStepCxt from './Step/StepContext'; export const StepProvider = FormStepProvider; export const StepContext = FormStepCxt;
0.142578
0
coding-exercise/array:string/Convert array into Zig-Zag fashion.js
afrozaahmed/JavaScript-Practise
1
15999420
function abc(arr){ let temp=""; for(let i=0;i<arr.length;i=i+2){ if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } if(arr[i+1]<arr[i+2]){ temp=arr[i+1]; arr[i+1]=arr[i+2]; arr[i+2]=temp; } } console.log(arr); } abc([1, 4, 3, 2]);
2.03125
2
src/database/seeders/20200504040517-seed-status_dream.js
guilhermeDTNA/API_Flourish
0
15999428
'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('status_dreams', [ { description_status: 'Realizado' }, { description_status: 'Realizando' }, { description_status: 'Não Realizado' } ], {}) }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('status_dreams', null, {}) } }
0.871094
1
assets/front/js/controllers/example_controller.js
opsone/wordpress-theme-kit
10
15999436
// TODO : DELETE CONTROLLER import BaseController from './base_controller' export default class extends BaseController { initialize() { console.log('Stimulus : controller Example') } }
0.65625
1
resources/assets/js/routes.js
yigeFYW/adminrule
0
15999444
import VueRouter from 'vue-router' let routes = [ { path:"/", component:require("./components/IndexComm"), children:[ { path:'login', name:"login", component:require("./components/Login") }, { path:'about', name:"about", component:require("./components/About") }, { path:'/', name:"index", component:require("./components/Home") }, ] } ]; export default new VueRouter({ mode:'history', routes })
0.894531
1
tests/modules-source/ti.modulesdk920/example/app.js
caspahouzer/titanium_mobile
1,191
15999452
alert('No example code.');
-0.138672
0
dao/main.ts2.js
daodao10/chart
1
15999460
require.config({ baseUrl: 'dist', paths: { 'typeahead': '../assets/js/typeahead.bundle.min', 'doT': '../assets/js/doT.min', 'hc-theme': '../assets/highcharts/themes/grid', 'anounymous': 'ProtoUtil', 's-t': '../assets/js/stupidtable.min' }, urlArgs: "_0.162" // urlArgs: "_" + (new Date()).getTime() // development }).onError = function (err) { console.log(err.requireType); if (err.requireType === 'timeout') { console.log('modules: ' + err.requireModules); } throw err; }; if (!window.Promise) { console.log('patch to support Promise'); (function () { var script, scripts = document.getElementsByTagName('script'); function loadJs(uri, isAsync, isFirst) { script = document.createElement('script'); script.src = uri; script.async = isAsync; if (isFirst && scripts) { scripts[0].parentNode.insertBefore(script, scripts[0]); } else { document.body.appendChild(script); } } loadJs('assets/js/promise-6.1.0.min.js'); } ()); } var global = { category: null, cr: { t: '\u00a9\u5200\u5c0f\u4e00' }, startDate: "1995-01", $factSet: null, datum: null, maxTryTimes: 2, cache: false, //true for deployment debug: false }; (function ($, globalSettings) { $.cacheScript = function (url, options) { options = $.extend(options || {}, { dataType: "script", cache: globalSettings.cache, url: url }); return $.ajax(options); }; $.cacheJSON = function (url, options) { options = $.extend(options || {}, { dataType: "json", cache: globalSettings.cache, url: url }); return $.ajax(options); }; $.cacheTemplate = function (options) { var settings = { type: "GET", dataType: "html", cache: globalSettings.cache }; if (Array.isArray(options)) { return Promise.all(options.map(function (element) { return new Promise(function (resolve, reject) { $.ajax(require.s.contexts._.config.baseUrl + 'tmpl/' + element.file, settings) .done(function (content, textStatus, jqXHR) { resolve({ id: element.id, content: content }); }).fail(function (jqXHR, textStatus, errorThrown) { reject(errorThrown); }); }); })); } else { return new Promise(function (resolve, reject) { reject('template: cannot support'); }); } }; })(jQuery, global); ErrorHandler = { _$error: null, init: function () { _$error = $("#error-panel > p"); window.onerror = function (errorMsg, url, lineNumber, column, errorObj) { ErrorHandler.show(errorMsg); }; }, show: function (message) { _$error.text(message).parent().transition('fade'); }, hide: function () { _$error.parent().transition('hide'); } }; require(['u', 't', 'f', 'doT', 'e', 'peg', 'e0', 'peg0', 'e1', 'peg1', 'anounymous', 'typeahead', 'hc-theme', 's-t'], function (daoU, daoT, daoF, doT, daoE, daoPEG, daoE0, daoPEG0, daoE1, daoPEG1) { $.cacheTemplate([ { file: 't-sets.html', id: '__set1' }, { file: 'f-t.html', id: 'taFactor' }, { file: 'f-f.html', id: 'faFactor' }, { file: 'f-f-t.html', id: 'faTable' }]).then(function (elements) { var tmpls = {}; elements.forEach(function (element) { if (element.id.startsWith('__')) { parseTmpl(element.content, tmpls); } else { tmpls[element.id] = doT.template(element.content); } }); doT.tmpls = tmpls; $(function () { global.$factSet = [$('#fact-chart-0'), $('#fact-set-0'), $('#fact-chart-1'), $('#fact-chart-2'), $('#fact-set-1'), $('#fact-set-2'), $("#security-info")]; var $category = $('#category'), $sector = $('#sector'), $symbol = $('#symbol'); ErrorHandler.init(); $('.menu .item').tab(); // get filter from window hash var hash = window.location.hash; if (hash) { var m = /#f=(-\d|\d)/g.exec(decodeURIComponent(hash)); //f=3,2,1,0,-1,-2 if (m && m.length === 2) { hash = parseInt(m[1], 10); } } // ticker-pick initialize (function () { return Promise.all(['world', 'cn', 'hk', 'sg', 'us'].map(function (element) { $category.append(buildItem(element, element.toUpperCase())); return new Promise(function (resolve, reject) { require([element], function (data) { resolve(data.filter(function (security) { security['cat'] = element; return hash === '' || security.f === hash; })); }); }); })); } ()).then(function (data) { var securities = {}, xx; data.forEach(function (element) { element.forEach(function (item, index) { if (index === 0) securities[item.cat] = {}; if (item.s) { if (!securities[item.cat][item.s]) securities[item.cat][item.s] = {}; securities[item.cat][item.s][item.c] = item; } }); }); $category.change(function (evt) { var val = evt.target.value; global.category = val; xx = Object.keys(securities[val]).map(function (key) { return buildItem(key, key.toUpperCase()); }); xx.unshift(buildItem('', '-- sector --')); $sector.html(xx.join('\n')); $symbol.html(buildItem('', '-- security --'));//reset }); $sector.change(function (evt) { var val = evt.target.value, obj = securities[global.category][val]; global.sector = val; xx = Object.keys(obj).map(function (key) { var element = obj[key]; return buildItem(element.c, element.n); }); xx.unshift(buildItem('', '-- security --')); $symbol.html(xx.join('\n')); }); $symbol.change(function (evt) { var val = evt.target.value; preload(securities[global.category][global.sector][val]); }); }).catch(function (err) { console.log("broken: " + err.message); }); // set start date $("#startDate").val(global.startDate) .change(function () { var val = $(this).val(); if (val && val.length > 0) { val = val.replace('-', ''); } global.startDate = val; }); // refresh $("#refreshBtn").click(function () { load(global.period, global.maxTryTimes); }); $('.message .close').on('click', function () { $(this).closest('.message').transition('fade'); }); }); }).catch(function (error) { console.error(error); }); var onComplete = function (chart) { if (!global.cr.x) { global.cr.x = chart.plotWidth + chart.plotLeft - 100; global.cr.y = chart.plotHeight + chart.plotTop - 10; } chart.renderer.text(global.cr.t, global.cr.x, global.cr.y) .css({ color: '#ccc', fontSize: '2em' }).attr({ zIndex: 99 }).add(); }, preload = function (datum) { global.period = daoU.getPeriod(global.category); global.datum = datum; load(global.period, global.maxTryTimes); }, load = function (period, maxTryTimes) { var $factSet = global.$factSet, /** datum: * { * c: symbol, * n: name, * s: sector, * pv: peakValley * } */ datum = global.datum, url = daoU.getCounterUrl(datum.c, global.category, period), jsonUrl = daoU.getFaUrl(global.category, datum.c); maxTryTimes--; // reset all panels for (var i = 0; i < 6; i++) { $factSet[i].text(''); } $factSet[6].text('CAPITAL'); ErrorHandler.hide(); $.cacheScript(url) .done(function (script, textStatus) { // filter source data data = data.filter(function (item) { return item[0] > global.startDate; }); var options = daoU.processData(data, { "period": period, "pv": datum.pv }); $factSet[0].highcharts(daoT.getChartOptions(options), onComplete); var taFactor = daoU.Calc.ta(options); var taFactorBak = { "p": taFactor.major.p, "cagr": taFactor.major.cagr, "opt": taFactor.opt }; $factSet[1].html(populateTa(taFactor)) .find('.tooltip').popup({ inline: true }); if (global.category == 'sg' || global.category == 'us') { if (datum.mv) { $factSet[6].text("Shares {0} M, MarketCap: {1} M".format(datum.mv.toFixed(4), (datum.mv * taFactorBak.p).toFixed(4))); } } else if (global.category == 'cn' && !(datum.c.startsWith('8') || datum.c.startsWith('S'))) { $factSet[6].text("总股本 {0} 亿({1}%流通),总市值 {2} 亿".format( Math.trunc(datum.mv / 1000) / 10.0, (datum.mv > 0 ? Math.trunc(datum.nv / datum.mv * 1000) / 10.0 : NaN), Math.trunc(datum.mv * taFactorBak.p / 1000) / 10.0)); $.cacheJSON(jsonUrl).done(function (data, textStatus) { var faSerie1 = daoU.toSeries(data.lastn), faSerie2 = daoU.toSeries(data.ttm); if (!global.debug) { $factSet[2].highcharts(daoF.getChartOptions('FA - Annual', faSerie1)); $factSet[3].highcharts(daoF.getChartOptions('FA - TTM', faSerie2)); } var faFactor = daoU.Calc.fa(taFactorBak, faSerie1.roe); faFactor.ttm = daoU.Calc.gn(taFactorBak, faSerie2); // set peg and earning faFactor.peg = daoPEG[datum.c]; updatePEG(faFactor.peg, '201608'); faFactor.ee = daoE[datum.c]; faFactor.peg0 = daoPEG0[datum.c]; updatePEG(faFactor.peg0, '201703'); faFactor.ee0 = daoE0[datum.c]; faFactor.peg1 = daoPEG1[datum.c]; updatePEG(faFactor.peg1, '201612'); faFactor.ee1 = daoE1[datum.c]; $factSet[4].html(populateFa(faFactor)) .find('.tooltip').popup({ inline: true }); $factSet[5].html(doT.tmpls.faTable(data)) .find('table:first-child').stupidtable(); }).fail(function (jqxhr, textStatus, err) { ErrorHandler.show("failed to load json data:" + jsonUrl); }); } }).fail(function (jqxhr, textStatus, err) { console.log("failed to load data:", url); if (jqxhr.status === 404 && maxTryTimes > 0 && period === "monthly") { console.log("try again", maxTryTimes); load("daily", maxTryTimes); } }); }, populateTa = function (taFactor) { stylish.ta(taFactor); taFactor.opt = daoU.trunc(taFactor.opt, 2); taFactor.factor = daoU.trunc(taFactor.factor, 1); daoU.debug("taFactor:", taFactor); return doT.tmpls.taFactor({ ta: taFactor }); }, populateFa = function (faFactor) { stylish.fa(faFactor); faFactor.avg = daoU.trunc(faFactor.avg, 2); faFactor.gap = daoU.trunc(faFactor.gap, 3); daoU.debug('faFactor:', faFactor); return doT.tmpls.faFactor({ fa: faFactor }); }, stylish = { ta: function (obj) { var cssClass = obj.stylish || {}; if (obj.major.r2 < 0.3) { cssClass.r2 = 'red'; } else if (obj.major.r2 < 0.5) { cssClass.r2 = 'olive'; } else if (obj.major.r2 > 0.8) { cssClass.r2 = 'green'; } else { cssClass.r2 = 'teal'; } obj.stylish = cssClass; }, fa: function (obj) { var cssClass = obj.stylish || {}; if (obj.avg.cra <= 0) { cssClass.avg = 'down red'; } else { cssClass.avg = 'up green'; } var x = 10 cssClass.gap = {}; Object.getOwnPropertyNames(obj.gap).forEach(function (key) { if (obj.gap[key] > x) { cssClass.gap[key] = 'red'; //negative } else if (obj.gap[key] < -x) { cssClass.gap[key] = 'green'; //positive } else if (obj.gap[key] <= x && obj.gap[key] >= -x) { cssClass.gap[key] = 'yellow'; //warning } }); obj.stylish = cssClass; } }, buildItem = function (value, text) { return "<option value='{0}'>{1}</option>".format(value, text); }, updatePEG = function (obj, updated) { if (Array.isArray(obj)) if (obj.length === 3) obj.push(updated); else obj[3] = updated; }, parseTmpl = function (content, tmpls) { var divs = $(content), div; if (divs.length > 0) { for (var i = 0; i < divs.length; i++) { div = divs.get(i); if (div.nodeName === "DIV") { tmpls[div.id] = doT.template(div.innerHTML); } } } }; });
1.078125
1
src/client/manipulation/execute/dom/move.test.js
mybrainpal/brainjs
0
15999468
/** * Proudly created by ohad on 25/12/2016. */ let _ = require('../../../common/util/wrapper'), $ = require('../../../common/util/dom'), Storage = require('../../../common/storage/storage'), InMemoryStorage = require('../../../common/storage/in-memory.storage'), Level = require('../../../common/log/logger').Level, BaseError = require('../../../common/log/base.error'), expect = require('chai').expect, MoveExecutor = require('./move'), Master = require('../master'); describe('MoveExecutor', function () { let div, p1, p2, a, span, ul, li; before(() => { Storage.set(Storage.names.IN_MEMORY); div = document.createElement('div'); div.setAttribute('id', 'div'); $('body').appendChild(div); p1 = document.createElement('p'); p1.textContent = 'p1'; p1.classList.add('first'); span = document.createElement('span'); span.textContent = 'span'; p1.appendChild(span); div.appendChild(p1); p2 = document.createElement('p'); p2.textContent = 'p2'; div.appendChild(p2); ul = document.createElement('ul'); li = document.createElement('li'); ul.appendChild(li); li.textContent = 'li'; div.appendChild(ul); }); beforeEach(() => { a = document.createElement('a'); a.textContent = 'a'; p2.appendChild(a); InMemoryStorage.flush(); }); afterEach(() => { document.querySelectorAll('a').forEach((elem) => {elem.parentNode.removeChild(elem)}); InMemoryStorage.flush(); }); after(() => { div.parentNode.removeChild(div); }); it('move based on parent', () => { MoveExecutor.execute({target: '#div a', parentSelector: '#div>.first'}); expect(a.parentNode).to.be.equal(p1); expect(a.previousSibling).to.be.equal(span); }); it('move logged', (done) => { Master.execute(MoveExecutor.name, {target: '#div a', parentSelector: '#div>.first', toLog: true}); setTimeout(() => { expect(InMemoryStorage.messages[0].level).to.equal(Level.INFO.name); done(); }); }); it('copy to another parent', () => { MoveExecutor.execute({target: '#div a', parentSelector: '#div>.first', copy: true}); expect(a.parentNode).to.be.equal(p2); expect(p2.querySelector('a')).to.be.ok; }); it('move to a ul parent', () => { MoveExecutor.execute({target: '#div a', parentSelector: '#div>ul'}); expect(a.parentNode.nodeName).to.be.equal('LI'); expect(a.parentNode.parentNode).to.be.equal(ul); }); it('move based on sibling', () => { MoveExecutor.execute({target: '#div a', nextSiblingSelector: '#div span'}); expect(a.parentNode).to.be.equal(p1); expect(_.isNil(a.previousSibling)).to.not.be.ok; }); it('do not move if parent is not changed', () => { MoveExecutor.execute({target: '#div a', parentSelector: '#div>p:nth-child(2)'}); expect(a.parentNode).to.be.equal(p2); }); it('do not move if next sibling is not changed', () => { a.parentNode.removeChild(a); p1.insertBefore(a, span); MoveExecutor.execute({target: '#div a', nextSiblingSelector: '#div span'}); expect(a.parentNode).to.be.equal(p1); expect(_.isNil(a.previousSibling)).to.not.be.ok; }); it('Preconditions', () => { expect(() => {MoveExecutor.preconditions({})}).to.throw(BaseError); expect(() => {MoveExecutor.preconditions({target: '#div a',})}).to.throw(BaseError); expect(() => { MoveExecutor.preconditions({ target : '#div a', parentSelector: 'effy', nextSiblingSelector: 'effy' }) }).to.throw(BaseError); expect(() => { MoveExecutor.preconditions({ target : '#div a', parentSelector : '#div>.first', nextSiblingSelector: '#div' }) }).to.throw(BaseError); expect(() => { MoveExecutor.preconditions({target: '#div a', parentSelector: 'div', copy: 1}) }).to.throw(BaseError); expect(() => { MoveExecutor.preconditions({target: '#div a', parentSelector: 'div'}) }).to.not.throw(Error); expect(() => { MoveExecutor.preconditions({ target : '#div a', parentSelector: 'div', nextSiblingSelector: 'effy' }) }).to.throw(BaseError); }) });
1.664063
2
node_modules/tedious/lib/library.js
SiliconDare/wedshine
1
15999476
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.name = void 0; const name = 'Tedious'; exports.name = name;
0.535156
1
pattern.min.js
awj5/pattern
1
15999484
/* Pattern v2.3 A JavaScript router utilising the HTML5 history API. Compatible with modern browsers only (ES6+). https://github.com/awj5/pattern By <NAME> MIT License 2019 Usage: let patrn = new Pattern(); patrn.init(); history.pushState(null, null, 'about'); // Change URL with pushState */ "use strict";class Pattern{constructor(t){this.path=t,this.storedParams=[]}init(){const t=history.pushState,a=this;history.pushState=function(){t.apply(history,arguments),a.urlHandler()},window.addEventListener("popstate",()=>{a.urlHandler()}),a.urlHandler()}urlHandler(){var t=location.pathname.replace(this.path,"");-1!==(t=t.replace("/","")).indexOf("?")&&(t=t.substr(0,t.indexOf("?"))),window.pattern=t||"home";var a=location.search.split("?").pop();a=new URLSearchParams(a);for(let t=0;t<this.storedParams.length;t++){var e=this.storedParams[t];a.has(e)||(window[e]="")}this.storedParams=[];for(let t of a.entries()){let a=t[0];window[a]=t[1],this.storedParams.push(a)}const r=window[window.pattern];"function"==typeof r&&r(),"function"==typeof patternChange&&patternChange()}}
2.125
2
src/__tests__/components/College.test.js
rajkumardas2701/medical-colleges
1
15999492
import React from 'react'; import renderer from 'react-test-renderer'; import { render, cleanup } from '@testing-library/react'; import College from '../../components/College'; afterEach(cleanup); const college = { state: 'A & N Islands', name: 'Andaman and Nicobar Islands Insitute of Medical Sciences, Port Blair', city: 'Port Blair', ownership: 'Govt.', admissionCapacity: 100, hospitalBeds: 460, }; it('renders item component correctly', () => { const drink = renderer.create(<College college={college} />).toJSON(); expect(drink).toMatchSnapshot(); }); it('renders a link to see college details', () => { const { getByTestId } = render(<College college={college} />); const link = getByTestId('college-link'); expect(link.innerHTML).toMatch(college.name); });
1.453125
1
lib/actions/process_associations.js
djforth/redux-helpers
0
15999500
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _core = require('lodash/core'); var _core2 = _interopRequireDefault(_core); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (dispatch) { return function (data, creator, type) { var obj = {}; if (_core2.default.isString(data)) { obj[type + '_title'] = data; obj[type + '_id'] = null; if (_core2.default.isFunction(creator)) { dispatch(creator({ title: data })); } return obj; } obj[type + '_id'] = data; return obj; }; };
1.132813
1
src/apiSecurity/Broadcast/deleteBroadcast.js
hiteshsomani/dashboard
0
15999508
import { getEntitiesList, checkUserPermission, canExecuteAction } from '../commonApi'; import pollingService from '../../service/PollService'; import botService from '../../service/BotService'; import broadcastService from '../../service/BroadcastService'; import { getAllowedPermissions, getUserAccessDocs } from '../../server'; import { permissionError, authenticationError, successResponse, requestFailError } from '../../constants/apiResponseType'; import _ from 'lodash'; import fetch from 'node-fetch'; // TODO async function preAction() { } async function postAction() { } export async function executeAction(acl, userId, entityType, permission, broadcastId) { const broadcastEntry = await broadcastService.getBroadcastEntry(broadcastId); let permissionResp = canExecuteAction(acl, userId, entityType, permission, broadcastEntry) if (permissionResp.error) { return permissionResp; } let pollId = ''; try { if (broadcastEntry.jobType === 'poll-broadcast') { pollId = broadcastEntry.pollId; } await broadcastService.deleteBroadcastEntry(broadcastId); const poll = await pollingService.getPollData(pollId); if (poll && poll.wrapupBroadcastId) { poll.wrapupBroadcastId = ''; await pollingService.save(poll); } return successResponse; } catch (e) { console.log(e); requestFailError.data = e; return requestFailError; } }
1.3125
1
.eslintrc.js
discoNeko/vue-template
0
15999516
/** * Googleのコーディングスタイルに準拠し、一部独自のlintルールを設定しています * @see https://github.com/google/eslint-config-google */ module.exports = { 'env': { 'browser': true, 'es2021': true, }, 'extends': [ 'plugin:vue/essential', 'google', ], 'parserOptions': { 'ecmaVersion': 12, 'sourceType': 'module', }, 'plugins': [ 'vue', ], 'rules': { /** * アロー関数の引数は()を必須としない * @see https://eslint.org/docs/rules/arrow-parens */ 'arrow-parens': ['error', 'as-needed'], /** * インデントは半角スペース2個 * @see https://eslint.org/docs/rules/indent */ 'indent': ['error', 2], /** * 一行の長さの制限はしない(SVGを埋め込むと一行2000文字などになってしまうため) * @see https://eslint.org/docs/rules/max-len */ 'max-len': ['off'], /** * windowに紐付けているモジュールはCapitalCaseを許容(例:window.Stripe...) * @see https://eslint.org/docs/rules/new-cap */ 'new-cap': ['error', { 'capIsNewExceptionPattern': '^window\..' }], /** * オブジェクトの{}内にスペースを開ける * @see https://eslint.org/docs/rules/object-curly-spacing */ 'object-curly-spacing': ['error', 'always'], /** * 関数の()前後にスペースを開ける * @see https://eslint.org/docs/rules/space-before-function-paren */ 'space-before-function-paren': ['error', 'always'], /** * 末尾のセミコロンを削除する * @see https://eslint.org/docs/rules/semi */ 'semi': ['error', 'never'], /** * htmlタグが2行に分離しないよう設定 * @see https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/html-closing-bracket-newline.md */ 'vue/html-closing-bracket-newline': ['error', { 'multiline': 'never' }], /** * htmlのインデントがずれていたら自動補正 * @see https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/html-indent.md */ 'vue/html-indent': ['error', 2], }, }
1.359375
1
application/src/ui/elements/styles/misc.js
okebinda/base.app.react
0
15999524
/** * Styles for Miscellaneous Elements */ import {Dimensions, StyleSheet} from 'react-native'; import Theme from './Theme'; let styles = StyleSheet.create({ // loading spinner spinnerContainer: { position: 'absolute', bottom: 50, left: 0, right: 0, justifyContent: 'center', alignItems: 'center' }, spinnerContainerHidden: { display: 'none' }, spinner: { backgroundColor: 'rgba(50, 50, 50, 0.6)', borderColor: 'rgba(0, 0, 0, 0.1)', paddingTop: 8, paddingLeft: 8, paddingBottom: 6, paddingRight: 6, borderRadius: 6, } }); export default styles;
1.03125
1
poriksha_Frontend/src/redux/actions/index.js
partha-nm/PORI_REP
0
15999532
export * from "./auth.action"; export * from "./student.action" export * from "./teacherRoom.action"; export * from './exams.action' export * from './mcq.action' export * from './institute.action' export * from "./socket.io.action"; export * from "./anticheat.action";
-0.25
0
src/icons/IconThumbsUp.js
thejellyfish/feather-icons
0
15999540
import React from 'react'; import Icon from '../Icon'; /* eslint-disable react/jsx-props-no-spreading */ export default function IconThumbsUp(props) { return ( <Icon {...props}> <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" /> </Icon> ); }
0.863281
1