hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
96d8de3f2b03566c0eb8e284e49854dd484dee7c | 1,063 | js | JavaScript | config/database.js | raulpe7eira/shortener | fa399e4351cbcb204974e39f2bb17bbf40c96e5e | [
"Apache-2.0"
] | 1 | 2017-03-15T11:21:50.000Z | 2017-03-15T11:21:50.000Z | config/database.js | raulpereira/shortener | fa399e4351cbcb204974e39f2bb17bbf40c96e5e | [
"Apache-2.0"
] | null | null | null | config/database.js | raulpereira/shortener | fa399e4351cbcb204974e39f2bb17bbf40c96e5e | [
"Apache-2.0"
] | null | null | null | // shortener/config/database.js
const mongoose = require('mongoose');
const config = require('./config')();
module.exports = (uri) => {
mongoose.Promise = require('bluebird');
mongoose.connect(uri);
mongoose.connection.on('connected', () => {
config.debug && console.log('[shortener-%s %s] Mongoose! Connect on %s ...',
config.env, new Date(Date.now()).toLocaleString('pt-BR'), uri);
});
mongoose.connection.on('disconnected', () => {
config.debug && console.log('\n[shortener-%s %s] Mongoose! Disconnected on %s ...',
config.env, new Date(Date.now()).toLocaleString('pt-BR'), uri);
});
mongoose.connection.on('error', (erro) => {
config.debug && console.log('[shortener-%s %s] Mongoose! Error in connection: %s',
config.env, new Date(Date.now()).toLocaleString('pt-BR'), erro);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
config.debug && console.log('[shortener-%s %s] Mongoose! Disconnected by terminal',
config.env, new Date(Date.now()).toLocaleString('pt-BR'));
process.exit(0);
});
});
}; | 31.264706 | 86 | 0.64064 |
96da5f2abf09f7b40108dbf9e318deaa584fc2a5 | 2,270 | js | JavaScript | test/transposer.mspec.js | vmollov/playMusicModes | 1e15cedb63c4e43fbc7aec7d188264ca343fc246 | [
"MIT"
] | 1 | 2015-12-16T02:56:50.000Z | 2015-12-16T02:56:50.000Z | test/transposer.mspec.js | vmollov/playMusicModes | 1e15cedb63c4e43fbc7aec7d188264ca343fc246 | [
"MIT"
] | null | null | null | test/transposer.mspec.js | vmollov/playMusicModes | 1e15cedb63c4e43fbc7aec7d188264ca343fc246 | [
"MIT"
] | null | null | null | 'use strict';
require('sinon');
var
expect = require('chai').expect,
mockery = require('mockery'),
transposer, noteFactory;
describe('transposer', function(){
before(function(){
mockery.enable({
warnOnReplace: false,
useCleanCache: true
});
mockery.registerAllowable('../ui/model/transposer');
mockery.registerAllowable('./transposer');
mockery.registerAllowable('../ui/model/noteFactory');
mockery.registerAllowable('./data/enharmonics');
mockery.registerAllowable('./enharmonicsData.json');
transposer = require('../ui/model/transposer');
noteFactory = require('../ui/model/noteFactory');
});
after(function(){
mockery.deregisterAll();
mockery.disable();
});
it('should return a singleton object', function(){
var anotherInstance = require('../ui/model/transposer');
expect(anotherInstance).to.deep.equal(transposer);
});
describe('transposer.setTransposition/transposer.removeTransposition', function(){
it('should set/remove transposition', function(){
var note = noteFactory.noteFromNameString('C4');
transposer.setTransposition({semitones: -2, steps: -1});
expect(note.name).to.equal('Bf3');
transposer.removeTransposition();
expect(note.name).to.equal('C4');
transposer.removeTransposition();
});
});
describe('transposer.transpose', function(){
it('should return a transposition object', function(){
var
note = noteFactory.noteFromNameString('C4'),
transposed;
transposer.setTransposition({ semitones: -3, steps: -2 });
transposed = transposer.transpose(note);
expect(transposed).to.have.property('semitones').that.equals(-3);
expect(transposed).to.have.property('steps').that.equals(-2);
expect(transposed).to.have.property('letter').that.equals('A');
expect(transposed).to.have.property('accidental').that.equals('n');
expect(transposed).to.have.property('octave').that.equals(3);
transposer.removeTransposition();
});
});
}); | 35.46875 | 86 | 0.607489 |
96db0551f384980b22df0fb6a071dd0bb3f0b8b5 | 274 | js | JavaScript | public/modules/core/controllers/home.client.controller.js | bluejellybean/portfolioSite | 42be744022768f02b2334edade37e338763925ca | [
"MIT"
] | null | null | null | public/modules/core/controllers/home.client.controller.js | bluejellybean/portfolioSite | 42be744022768f02b2334edade37e338763925ca | [
"MIT"
] | null | null | null | public/modules/core/controllers/home.client.controller.js | bluejellybean/portfolioSite | 42be744022768f02b2334edade37e338763925ca | [
"MIT"
] | null | null | null | 'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication', 'Menu',
function($scope, Authentication, Menu) {
// This provides Authentication context.
this.menu = Menu.getMenu('topbar');
this.authentication = Authentication;
}
]);
| 27.4 | 88 | 0.708029 |
96db88f28fe2336ff08e8ad91e9b7724601ec5e1 | 129 | js | JavaScript | src/data/account/actions.js | bryandcoulter/data-flow-playground | d2ea9574053c619e419f66382e3ace7a8514a309 | [
"Apache-2.0"
] | null | null | null | src/data/account/actions.js | bryandcoulter/data-flow-playground | d2ea9574053c619e419f66382e3ace7a8514a309 | [
"Apache-2.0"
] | null | null | null | src/data/account/actions.js | bryandcoulter/data-flow-playground | d2ea9574053c619e419f66382e3ace7a8514a309 | [
"Apache-2.0"
] | null | null | null | class AccountActions {
static updateAccount (account) {
return {
type: 'updateAccount',
account: account
}
}
}
| 14.333333 | 34 | 0.635659 |
96dbb2074322b20e9ce154c7464fc667a29ed1f9 | 302 | js | JavaScript | build/js/es2015.js | majofeechiou/try | 9f89f3c07e092026847e074ec0a2014356dc63ee | [
"MIT"
] | null | null | null | build/js/es2015.js | majofeechiou/try | 9f89f3c07e092026847e074ec0a2014356dc63ee | [
"MIT"
] | null | null | null | build/js/es2015.js | majofeechiou/try | 9f89f3c07e092026847e074ec0a2014356dc63ee | [
"MIT"
] | null | null | null | !function(t){function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var e={};return r.m=t,r.c=e,r.p="",r(0)}([function(t,r,e){"use strict";e(5),e(7)},,,,,function(t,r){"use strict";alert(123)},,function(t,r){}]); | 302 | 302 | 0.622517 |
96dbd6c283ae7b77274922df804c278c323049c3 | 465 | js | JavaScript | PatternTracker/doxygen/html/search/namespaces_1.js | Samsung/ColorPatterntracker | c2c41723062706b2b09799cdfaf2641d0fb36e68 | [
"Apache-2.0"
] | 8 | 2017-02-08T00:50:59.000Z | 2020-10-07T15:43:43.000Z | PatternTracker/doxygen/html/search/namespaces_1.js | Samsung/ColorPatterntracker | c2c41723062706b2b09799cdfaf2641d0fb36e68 | [
"Apache-2.0"
] | 1 | 2017-02-15T01:22:16.000Z | 2017-02-17T18:46:22.000Z | PatternTracker/doxygen/html/search/namespaces_1.js | Samsung/ColorPatterntracker | c2c41723062706b2b09799cdfaf2641d0fb36e68 | [
"Apache-2.0"
] | 8 | 2017-01-15T11:26:46.000Z | 2022-03-30T07:41:42.000Z | var searchData=
[
['camera',['camera',['../namespacepatterntracker_1_1camera.html',1,'patterntracker']]],
['patterntracker',['patterntracker',['../namespacepatterntracker.html',1,'']]],
['predictor',['predictor',['../namespacepatterntracker_1_1predictor.html',1,'patterntracker']]],
['stereo',['stereo',['../namespacepatterntracker_1_1stereo.html',1,'patterntracker']]],
['util',['util',['../namespacepatterntracker_1_1util.html',1,'patterntracker']]]
];
| 51.666667 | 98 | 0.705376 |
96dbf094e8f5ca6d9fde8b49bfa8f2d4ed7544d1 | 3,306 | js | JavaScript | spec/build-ios.spec.js | clotton/aemmobile | 3487cfe7cb0e8627a5eb7b8f87bcedccaf5047fe | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2016-05-05T07:19:12.000Z | 2022-03-14T03:36:13.000Z | spec/build-ios.spec.js | clotton/aemmobile | 3487cfe7cb0e8627a5eb7b8f87bcedccaf5047fe | [
"ECL-2.0",
"Apache-2.0"
] | 54 | 2016-05-04T21:14:21.000Z | 2019-09-16T07:31:20.000Z | spec/build-ios.spec.js | clotton/aemmobile | 3487cfe7cb0e8627a5eb7b8f87bcedccaf5047fe | [
"ECL-2.0",
"Apache-2.0"
] | 26 | 2016-05-30T14:10:43.000Z | 2022-02-04T07:41:43.000Z | /**
Copyright (c) 2016 Adobe Systems Incorporated. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var Q = require('q');
var rewire = require('rewire');
var cordova = require('../lib/cordova').lib.cordova;
var build_ios = rewire('../src/build-ios');
describe('build-ios', function() {
var build = build_ios.__get__('build');
beforeEach(function () {
spyOn(cordova.raw, 'build');
});
describe('build method', function() {
it('should call cordova build', function(done) {
return build([])
.then( () =>{
expect(cordova.raw.build.calls.argsFor(0)[0].platforms).toEqual(['ios']);
expect(cordova.raw.build.calls.argsFor(0)[0].options.codeSignIdentity).toEqual("Don't Code Sign");
expect(cordova.raw.build.calls.argsFor(0)[0].options.noSign).toEqual(true);
done();
});
});
it('should not throw if code signing is enabled for device builds', function(done) {
var platform = require('../src/platform-ios');
spyOn(platform, 'isCodeSigningDisabled').and.returnValue(Q(true));
this.wrapper( build({ 'options': { 'device' : true }}), done, function() {
expect(platform.isCodeSigningDisabled).toHaveBeenCalled();
expect(cordova.raw.build.calls.argsFor(0)[0].platforms).toEqual(['ios']);
expect(cordova.raw.build.calls.argsFor(0)[0].options.device).toEqual(true);
expect(cordova.raw.build.calls.argsFor(0)[0].options.codeSignIdentity).toEqual("Don't Code Sign");
expect(cordova.raw.build.calls.argsFor(0)[0].options.noSign).toEqual(true);
done();
});
});
it('should throw if code signing is disabled for device builds', function(done) {
var platform = require('../src/platform-ios');
spyOn(platform, 'isCodeSigningDisabled').and.returnValue(Q(false));
var errorMessage = "CODE_SIGNING_REQUIRED must be set to NO in order to build for device.\nYou can resolve this by running `aemm platform install ios`.";
this.wrapperError(build({ 'options': { 'device' : true }}), done, function(err) {
expect(err.message).toEqual(errorMessage);
expect(platform.isCodeSigningDisabled).toHaveBeenCalled();
expect(cordova.raw.build.calls.argsFor(0)[0].platforms).toEqual(['ios']);
expect(cordova.raw.build.calls.argsFor(0)[0].options.device).toEqual(true);
expect(cordova.raw.build.calls.argsFor(0)[0].options.codeSignIdentity).toEqual("Don't Code Sign");
expect(cordova.raw.build.calls.argsFor(0)[0].options.noSign).toEqual(true);
});
});
});
}); | 49.343284 | 165 | 0.632486 |
96dd5de9293713482b004d48b26747ab721e9da3 | 3,359 | js | JavaScript | client/src/components/NoteForm.js | carlhueffmeier/hootini | a55f01d601c876663a7cce592d67b241402d92c0 | [
"MIT"
] | 1 | 2019-01-03T16:55:03.000Z | 2019-01-03T16:55:03.000Z | client/src/components/NoteForm.js | carlhueffmeier/hootini | a55f01d601c876663a7cce592d67b241402d92c0 | [
"MIT"
] | 1 | 2019-04-03T15:20:16.000Z | 2019-04-03T17:53:26.000Z | client/src/components/NoteForm.js | carlhueffmeier/hootini | a55f01d601c876663a7cce592d67b241402d92c0 | [
"MIT"
] | 1 | 2019-03-07T08:12:52.000Z | 2019-03-07T08:12:52.000Z | import React, { Component, Fragment } from 'react';
import { object, func } from 'prop-types';
import { navigate } from '@reach/router';
import { Form } from 'react-final-form';
import { Button } from './styles/ButtonStyles';
import { EditIcon } from './Icons';
import { IconButton } from './styles/ButtonStyles';
import NotePreviewWithQuery from './NotePreviewWithQuery';
import EditSection from './NoteEditInputs';
import TwoPageLayout from './TwoPageLayout';
import styled from 'react-emotion';
import { OutlinedButton, TextButton } from './styles/ButtonStyles';
import { VisuallyHidden } from '../shared/styleHelper';
const FullPageForm = styled('form')({
height: '100%',
display: 'flex',
flexDirection: 'column'
});
const CancelButton = styled(TextButton)({
marginRight: 'auto'
});
const PreviewButton = styled(OutlinedButton)({
marginRight: '1rem'
});
class NoteForm extends Component {
static propTypes = {
onSubmit: func,
initialValues: object
};
static defaultProps = {
onSubmit: data => console.log('submitting 🧚', data)
};
render() {
const { onSubmit, initialValues, loading } = this.props;
return (
<Form onSubmit={onSubmit} initialValues={initialValues}>
{({ handleSubmit, values, pristine, form }) => (
<FullPageForm
onSubmit={event => {
handleSubmit(event);
form.reset({ deck: values.deck, noteType: values.noteType });
}}
>
<TwoPageLayout>
<TwoPageLayout.Left>{() => <EditSection values={values} />}</TwoPageLayout.Left>
<TwoPageLayout.Right>
{() =>
values.noteType && (
<NotePreviewWithQuery
noteTypeId={values.noteType.id}
values={values}
renderActions={({ activeTab, noteType }) => (
<IconButton
type="button"
onClick={() => {
navigate(`/note-types/${noteType.slug}#tab${activeTab}`);
}}
>
<VisuallyHidden>Edit Template</VisuallyHidden>
<EditIcon />
</IconButton>
)}
/>
)
}
</TwoPageLayout.Right>
<TwoPageLayout.Bottom>
{({ isShiftable, isShifted, toggleShift }) => (
<Fragment>
<CancelButton type="button" onClick={() => navigate('./')}>
Go Back
</CancelButton>
{isShiftable && (
<PreviewButton
type="button"
disabled={!values.noteType}
onClick={toggleShift}
>
{isShifted ? 'Input' : 'Preview'}
</PreviewButton>
)}
<Button disabled={!values.noteType || pristine || loading}>Save</Button>
</Fragment>
)}
</TwoPageLayout.Bottom>
</TwoPageLayout>
</FullPageForm>
)}
</Form>
);
}
}
export default NoteForm;
| 33.257426 | 94 | 0.493599 |
96dda4e80117135da6e45ea58b87af5b183271d0 | 452 | js | JavaScript | src/layout/default/page/Layout.js | jsh1400/react-webpack | 32a1182ae38e7837850ac50e276f1296d8ec6cd3 | [
"MIT"
] | null | null | null | src/layout/default/page/Layout.js | jsh1400/react-webpack | 32a1182ae38e7837850ac50e276f1296d8ec6cd3 | [
"MIT"
] | null | null | null | src/layout/default/page/Layout.js | jsh1400/react-webpack | 32a1182ae38e7837850ac50e276f1296d8ec6cd3 | [
"MIT"
] | null | null | null | import React from 'react';
import { Link } from 'react-router-dom';
import { main, pullRight, h1 } from '../css/Layout.css';
const Layout = ({ children }) => {
return (
<div className={main}>
<Link to="/">
<h1 className={h1}>
React Project
</h1>
</Link>
{children}
<hr />
<p className={pullRight}>
Made with by Javad Shariati
</p>
</div>
);
};
export default Layout;
| 18.833333 | 56 | 0.526549 |
96ddb9526fe11ef9ba0f022b5b6f138760789d86 | 771 | js | JavaScript | packages/ui/src/pages/Exchange/ExchangePage.js | max-vorabhol-zipmex/express-app | 455efc2eaebd64b0a50fba98c19e4e8eda5a13f6 | [
"MIT"
] | null | null | null | packages/ui/src/pages/Exchange/ExchangePage.js | max-vorabhol-zipmex/express-app | 455efc2eaebd64b0a50fba98c19e4e8eda5a13f6 | [
"MIT"
] | 3 | 2021-07-12T02:06:20.000Z | 2021-08-11T01:48:33.000Z | packages/ui/src/pages/Exchange/ExchangePage.js | max-vorabhol-zipmex/express-app | 455efc2eaebd64b0a50fba98c19e4e8eda5a13f6 | [
"MIT"
] | null | null | null | import React from 'react';
import resize from 'hocs/resize';
import 'layouts/TradingLayout/TradingLayout.css';
import PageHeaderLayout from 'layouts/PageHeaderLayout/PageHeaderLayout';
import ExchangePageDesktop from './ExchangePageDesktop';
import ExchangePageMobile from './ExchangePageMobile';
import { breakpoints } from 'design/breakpoints';
class ExchangePage extends React.Component {
render() {
return (
<React.Fragment>
<PageHeaderLayout />
{this.props.width > breakpoints.mobile && (
<ExchangePageDesktop {...this.props} />
)}
{this.props.width < breakpoints.mobile && (
<ExchangePageMobile {...this.props} />
)}
</React.Fragment>
);
}
}
export default resize(ExchangePage);
| 29.653846 | 73 | 0.680934 |
96ddd758901c874b30387c6ce8d36d9e24bbc0ea | 1,805 | js | JavaScript | AllReadyApp/Web-App/AllReady/wwwroot/js/campaignAdmin.js | mk0sojo/allReady | 37833fcf2ea4d1f54d0e846c78ff79b307509809 | [
"MIT"
] | 1,034 | 2015-07-20T17:08:09.000Z | 2022-03-15T08:10:51.000Z | AllReadyApp/Web-App/AllReady/wwwroot/js/campaignAdmin.js | mk0sojo/allReady | 37833fcf2ea4d1f54d0e846c78ff79b307509809 | [
"MIT"
] | 1,853 | 2015-07-30T22:40:20.000Z | 2022-02-25T19:09:29.000Z | AllReadyApp/Web-App/AllReady/wwwroot/js/campaignAdmin.js | mk0sojo/allReady | 37833fcf2ea4d1f54d0e846c78ff79b307509809 | [
"MIT"
] | 946 | 2015-07-20T17:39:36.000Z | 2022-03-23T18:13:05.000Z | $(function() {
$(document).ready(function () {
toggleImpactDisplay();
});
// handle the confirm click
$("#confirmOverwriteContact").click(function ()
{
var id = $("select[id=OrganizationId").val();
var getContactInfo = $.ajax({ url: "/admin/api/organization/" + id + "/Contact", method: "GET", cache: true });
getContactInfo.then(function (data) {
if (data != null) {
$("#PrimaryContactFirstName").val(data.FirstName);
$("#PrimaryContactLastName").val(data.LastName);
$("#PrimaryContactPhoneNumber").val(data.PhoneNumber);
$("#PrimaryContactEmail").val(data.Email);
if (data.Location != null) {
$("#Location_Address1").val(data.Location.Address1);
$("#Location_Address2").val(data.Location.Address2);
$("#Location_City").val(data.Location.City);
$("#Location_State").val(data.Location.State);
$("#Location_PostalCode").val(data.Location.PostalCode);
$("#Location_Country").val(data.Location.Country);
}
}
$('#confirmContactModal').modal('hide');
})
.fail(function (e, t, m) {
alert("Ajax Error:" + e);
});
});
$("#CampaignImpact_ImpactType").on("change", function () {
toggleImpactDisplay();
});
function toggleImpactDisplay() {
console.log($("#CampaignImpact_ImpactType").val());
if ($("#CampaignImpact_ImpactType").val() === "0") {
$("#numericImpactSection").show();
}
else {
$("#numericImpactSection").hide();
}
}
}); | 41.022727 | 120 | 0.503047 |
96dec6a9b795a5ec4f47a49b3b64fb9c781bd005 | 8,193 | js | JavaScript | highmaps/411525.js | lbp0200/highcharts-china-geo | a8342835f3004d257c11aab196272b449aa58899 | [
"MIT"
] | 40 | 2016-06-24T03:14:42.000Z | 2022-01-15T11:17:13.000Z | highmaps/411525.js | lbp0200/highcharts-china-geo | a8342835f3004d257c11aab196272b449aa58899 | [
"MIT"
] | null | null | null | highmaps/411525.js | lbp0200/highcharts-china-geo | a8342835f3004d257c11aab196272b449aa58899 | [
"MIT"
] | 46 | 2016-01-12T16:08:07.000Z | 2022-03-30T17:37:44.000Z | Highcharts.maps["countries/cn/411525"] = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"adcode":411525,"name":"固始县","center":[115.667328,32.183074],"centroid":[115.703153,32.131027],"childrenNum":0,"level":"district","acroutes":[100000,410000,411500],"parent":{"adcode":411500},"longitude":115.703153,"latitude":32.131027},"geometry":{"type":"MultiPolygon","coordinates":[[[[6697,4681],[6697,4680],[6696,4680],[6695,4681],[6694,4681],[6694,4681],[6692,4679],[6691,4678],[6689,4676],[6687,4675],[6687,4674],[6687,4672],[6686,4671],[6686,4671],[6683,4669],[6683,4669],[6682,4667],[6681,4666],[6681,4666],[6683,4666],[6686,4666],[6687,4666],[6687,4665],[6688,4664],[6689,4663],[6688,4661],[6688,4659],[6687,4659],[6687,4659],[6685,4657],[6685,4656],[6685,4656],[6687,4656],[6689,4655],[6689,4654],[6689,4652],[6688,4652],[6689,4651],[6688,4651],[6688,4651],[6688,4650],[6688,4650],[6689,4649],[6690,4648],[6690,4647],[6690,4646],[6691,4644],[6691,4644],[6691,4642],[6692,4641],[6692,4640],[6692,4637],[6692,4637],[6692,4634],[6692,4633],[6692,4632],[6692,4630],[6693,4629],[6693,4626],[6693,4624],[6694,4622],[6693,4622],[6692,4621],[6692,4621],[6692,4620],[6694,4620],[6694,4619],[6695,4618],[6694,4616],[6695,4615],[6696,4614],[6696,4613],[6696,4612],[6696,4612],[6695,4610],[6695,4606],[6695,4604],[6695,4603],[6696,4600],[6697,4598],[6697,4597],[6697,4596],[6697,4595],[6697,4594],[6699,4594],[6699,4593],[6700,4590],[6701,4589],[6700,4588],[6700,4586],[6700,4585],[6700,4583],[6700,4580],[6699,4579],[6699,4577],[6699,4577],[6698,4576],[6698,4575],[6699,4573],[6699,4571],[6699,4571],[6701,4569],[6701,4569],[6701,4567],[6700,4566],[6698,4565],[6698,4564],[6698,4564],[6697,4563],[6698,4563],[6698,4562],[6698,4561],[6698,4561],[6698,4560],[6698,4560],[6698,4559],[6697,4559],[6697,4559],[6697,4558],[6698,4557],[6698,4557],[6698,4557],[6698,4557],[6698,4557],[6698,4556],[6698,4555],[6699,4555],[6699,4554],[6699,4554],[6698,4553],[6699,4553],[6699,4552],[6700,4552],[6700,4551],[6699,4550],[6698,4551],[6698,4551],[6697,4549],[6698,4548],[6697,4547],[6696,4545],[6695,4542],[6695,4542],[6695,4541],[6695,4540],[6695,4539],[6696,4537],[6696,4537],[6696,4536],[6696,4535],[6697,4535],[6697,4534],[6697,4531],[6695,4528],[6694,4525],[6693,4524],[6693,4524],[6693,4523],[6693,4522],[6693,4521],[6693,4520],[6693,4519],[6692,4517],[6692,4515],[6692,4515],[6692,4514],[6693,4513],[6694,4513],[6694,4513],[6695,4512],[6696,4511],[6696,4509],[6696,4508],[6696,4507],[6696,4506],[6696,4505],[6695,4504],[6694,4504],[6693,4504],[6693,4503],[6692,4503],[6692,4502],[6691,4501],[6689,4500],[6688,4501],[6688,4501],[6686,4500],[6685,4500],[6685,4501],[6685,4502],[6684,4503],[6684,4503],[6683,4502],[6682,4501],[6682,4500],[6681,4500],[6681,4501],[6680,4501],[6680,4500],[6679,4499],[6677,4497],[6676,4498],[6676,4499],[6676,4499],[6676,4500],[6676,4500],[6675,4500],[6674,4500],[6673,4500],[6673,4501],[6672,4502],[6671,4502],[6669,4502],[6668,4503],[6668,4503],[6667,4502],[6666,4502],[6665,4502],[6663,4502],[6663,4501],[6663,4500],[6662,4500],[6661,4500],[6662,4499],[6661,4499],[6661,4498],[6662,4498],[6662,4498],[6661,4498],[6659,4498],[6658,4498],[6657,4499],[6656,4499],[6655,4499],[6654,4499],[6653,4499],[6653,4500],[6651,4501],[6650,4501],[6650,4500],[6648,4497],[6647,4497],[6644,4496],[6643,4496],[6642,4498],[6642,4499],[6640,4499],[6639,4500],[6639,4501],[6640,4502],[6640,4502],[6640,4504],[6640,4505],[6639,4506],[6638,4506],[6637,4507],[6636,4506],[6636,4505],[6635,4505],[6634,4504],[6633,4504],[6632,4505],[6631,4505],[6631,4507],[6631,4507],[6631,4508],[6630,4508],[6630,4508],[6630,4509],[6629,4512],[6629,4512],[6630,4513],[6630,4513],[6631,4515],[6631,4516],[6630,4518],[6631,4520],[6630,4521],[6631,4522],[6632,4523],[6632,4524],[6633,4525],[6633,4525],[6632,4527],[6634,4529],[6634,4529],[6635,4530],[6636,4531],[6637,4531],[6637,4532],[6636,4532],[6635,4533],[6634,4534],[6635,4535],[6634,4536],[6632,4537],[6632,4540],[6632,4541],[6632,4542],[6632,4543],[6631,4543],[6631,4543],[6630,4542],[6630,4542],[6629,4542],[6629,4542],[6629,4543],[6629,4544],[6628,4545],[6628,4546],[6628,4546],[6630,4547],[6630,4548],[6630,4549],[6630,4549],[6628,4551],[6627,4551],[6627,4552],[6626,4553],[6626,4554],[6626,4557],[6626,4558],[6625,4559],[6625,4559],[6623,4558],[6622,4558],[6621,4558],[6619,4558],[6617,4559],[6615,4561],[6615,4562],[6615,4563],[6615,4563],[6617,4564],[6617,4565],[6617,4566],[6617,4566],[6616,4566],[6616,4566],[6616,4567],[6616,4568],[6616,4569],[6616,4570],[6615,4569],[6615,4570],[6614,4570],[6613,4570],[6612,4570],[6611,4571],[6610,4571],[6610,4571],[6610,4573],[6610,4573],[6609,4573],[6608,4572],[6607,4572],[6606,4572],[6605,4572],[6603,4571],[6602,4570],[6602,4570],[6602,4568],[6602,4567],[6602,4566],[6601,4565],[6601,4565],[6601,4563],[6601,4561],[6601,4560],[6602,4560],[6602,4559],[6602,4559],[6601,4557],[6601,4556],[6601,4557],[6600,4556],[6600,4557],[6599,4557],[6598,4556],[6598,4556],[6597,4556],[6597,4556],[6597,4557],[6596,4558],[6595,4559],[6594,4560],[6593,4561],[6593,4562],[6593,4562],[6591,4563],[6591,4564],[6591,4565],[6591,4566],[6592,4566],[6592,4567],[6591,4568],[6591,4569],[6591,4570],[6590,4570],[6590,4571],[6590,4572],[6589,4573],[6589,4574],[6588,4574],[6588,4575],[6589,4575],[6589,4575],[6589,4576],[6589,4577],[6589,4578],[6589,4578],[6588,4579],[6588,4580],[6587,4580],[6587,4581],[6587,4581],[6587,4582],[6586,4582],[6586,4583],[6587,4585],[6587,4585],[6587,4586],[6587,4586],[6587,4587],[6587,4587],[6588,4587],[6587,4588],[6587,4588],[6588,4589],[6588,4590],[6589,4590],[6590,4590],[6590,4591],[6590,4591],[6590,4593],[6590,4595],[6590,4595],[6590,4596],[6590,4597],[6589,4597],[6589,4598],[6589,4599],[6589,4599],[6589,4600],[6589,4601],[6590,4602],[6590,4603],[6590,4604],[6590,4604],[6591,4604],[6591,4604],[6592,4605],[6591,4606],[6592,4606],[6591,4607],[6592,4608],[6593,4608],[6594,4608],[6595,4609],[6598,4610],[6601,4611],[6603,4612],[6606,4613],[6607,4613],[6610,4614],[6612,4614],[6615,4614],[6616,4614],[6616,4614],[6617,4615],[6616,4617],[6616,4617],[6617,4618],[6617,4619],[6618,4618],[6618,4618],[6619,4618],[6619,4619],[6619,4619],[6620,4620],[6620,4621],[6620,4621],[6619,4622],[6619,4623],[6619,4624],[6620,4623],[6620,4622],[6621,4623],[6622,4624],[6623,4624],[6623,4624],[6623,4623],[6624,4623],[6625,4623],[6625,4624],[6625,4625],[6626,4624],[6626,4624],[6626,4625],[6626,4625],[6625,4626],[6625,4627],[6624,4627],[6625,4628],[6624,4629],[6624,4630],[6625,4631],[6625,4631],[6625,4630],[6626,4630],[6626,4632],[6626,4632],[6628,4632],[6629,4632],[6629,4633],[6629,4635],[6629,4636],[6629,4638],[6630,4638],[6631,4639],[6631,4639],[6631,4642],[6631,4642],[6633,4646],[6633,4647],[6635,4648],[6635,4648],[6636,4647],[6636,4646],[6638,4644],[6639,4643],[6639,4643],[6639,4643],[6643,4646],[6644,4647],[6645,4649],[6645,4649],[6645,4646],[6645,4645],[6645,4644],[6645,4644],[6647,4644],[6647,4645],[6648,4646],[6648,4647],[6648,4649],[6649,4649],[6650,4651],[6650,4652],[6650,4654],[6649,4655],[6648,4657],[6649,4657],[6649,4657],[6653,4657],[6653,4658],[6653,4658],[6653,4659],[6652,4660],[6652,4661],[6652,4662],[6652,4663],[6653,4664],[6654,4664],[6656,4662],[6657,4662],[6658,4661],[6660,4660],[6661,4660],[6663,4660],[6664,4660],[6665,4661],[6665,4662],[6666,4663],[6666,4665],[6666,4666],[6667,4666],[6667,4666],[6669,4664],[6670,4663],[6670,4662],[6670,4660],[6670,4659],[6669,4658],[6669,4657],[6670,4657],[6670,4658],[6673,4662],[6674,4663],[6676,4664],[6676,4664],[6677,4666],[6677,4666],[6680,4665],[6680,4665],[6680,4665],[6680,4666],[6680,4668],[6680,4670],[6680,4671],[6680,4671],[6681,4672],[6682,4673],[6684,4674],[6685,4674],[6688,4679],[6689,4681],[6690,4683],[6690,4683],[6691,4683],[6692,4683],[6694,4683],[6694,4683],[6695,4682],[6696,4681],[6697,4681]]]]}}],"UTF8Encoding":true,"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG:3415"}},"hc-transform":{"default":{"crs":"+proj=lcc +lat_1=18 +lat_2=24 +lat_0=21 +lon_0=114 +x_0=500000 +y_0=500000 +ellps=WGS72 +towgs84=0,0,1.9,0,0,0.814,-0.38 +units=m +no_defs","scale":0.000129831107685,"jsonres":15.5,"jsonmarginX":-999,"jsonmarginY":9851,"xoffset":-3139937.49309,"yoffset":4358972.7486}}} | 8,193 | 8,193 | 0.670084 |
96e03aae93182138a9309de70b5fbfd54909ea0c | 1,107 | js | JavaScript | javascript/index.js | dush1729/StonksCF | f6010edf5ba7cb918c3d31205f8ccdfdb250a160 | [
"MIT"
] | 31 | 2021-11-25T02:07:15.000Z | 2022-03-23T06:11:31.000Z | javascript/index.js | dush1729/StonksCF | f6010edf5ba7cb918c3d31205f8ccdfdb250a160 | [
"MIT"
] | 4 | 2021-11-25T07:39:06.000Z | 2021-12-20T18:03:08.000Z | javascript/index.js | dush1729/StonksCF | f6010edf5ba7cb918c3d31205f8ccdfdb250a160 | [
"MIT"
] | 5 | 2021-11-26T07:59:48.000Z | 2022-01-15T18:51:03.000Z | function init() {
$.post("./backend/API.php",{"type":1,"num":10},function(res) {
for(var i = 0;i < res.length;++i) {
$("#leaderboard").append("<tr><td>" + (i + 1) + "</td><td>" + nameToCode(res[i]["name"],res[i]["rating"]) + "</td><td>$" + reformNum(res[i]["networth"]) + "</td></tr>")
}
});
$.post("./backend/API.php",{"type":3,"num":5},function(res) {
for(var i = 0;i < res.length;++i) {
$("#hottest").append("<tr><td>" + nameToCode(res[i]["name"],res[i]["rating"]) + "</td><td>$" + reformNum(res[i]["price"]) + "</td><td>" + res[i]["hotness"] + "</td></tr>")
}
});
$.post("./backend/API.php",{"type":2,"num":3},function(res) {
for(var i = 0;i < res.length;++i) {
$("#transactions").append("<tr><td>" + nameToCode(res[i]["buyer"],res[i]["buyerRating"]) + "</td><td>" + nameToCode(res[i]["stock"],res[i]["stockRating"]) + "</td><td>$" + reformNum(res[i]["price"]) + "</td><td>" + Math.abs(res[i]["qty"]) + "</td><td>" + buyOrSell(res[i]["qty"]) + "</td></tr>")
}
});
$.post("./backend/API.php",{"type":4},function(res) {
$("#announcements").append(res[0])
});
}
$(init); | 42.576923 | 298 | 0.514002 |
96e08e25f7faa4cc21551819ea994eaeb95646c6 | 739 | js | JavaScript | cypress/integration/tsp/datesPanel.js | mr337/mymove | 42b08f2c6dcc95d58f0a3d32d63013c9a6a8426d | [
"MIT"
] | null | null | null | cypress/integration/tsp/datesPanel.js | mr337/mymove | 42b08f2c6dcc95d58f0a3d32d63013c9a6a8426d | [
"MIT"
] | null | null | null | cypress/integration/tsp/datesPanel.js | mr337/mymove | 42b08f2c6dcc95d58f0a3d32d63013c9a6a8426d | [
"MIT"
] | null | null | null | import { userEntersDates } from '../../support/datesPanel';
/* global cy */
describe('TSP User Completes Dates Panel', function() {
beforeEach(() => {
cy.signIntoTSP();
});
it('tsp user completes dates panel', function() {
tspUserGoesToDatesPanel('DATESP');
userEntersDates();
});
});
function tspUserGoesToDatesPanel(locator) {
// Open new shipments queue
cy.location().should(loc => {
expect(loc.pathname).to.match(/^\/queues\/new/);
});
// Find shipment and open it
cy.selectQueueItemMoveLocator(locator);
cy.location().should(loc => {
expect(loc.pathname).to.match(/^\/shipments\/[^/]+/);
});
cy
.get('.editable-panel-header')
.contains('Dates')
.siblings()
.click();
}
| 22.393939 | 59 | 0.627876 |
96e0e048dbdb2d1e9bfe1257318d6e4e5aa00cb4 | 655 | js | JavaScript | assets/js/front-end-scripts.js | ruelasal/proyecto | 0e041bff64ab76fd126d5d753d8fecdedfa1b3d9 | [
"MIT"
] | null | null | null | assets/js/front-end-scripts.js | ruelasal/proyecto | 0e041bff64ab76fd126d5d753d8fecdedfa1b3d9 | [
"MIT"
] | null | null | null | assets/js/front-end-scripts.js | ruelasal/proyecto | 0e041bff64ab76fd126d5d753d8fecdedfa1b3d9 | [
"MIT"
] | null | null | null | (function( $ ) {
'use strict';
/* ==========================================================================
When document is ready, do
========================================================================== */
$( document ).ready( function() {
function open_links_in_popup() {
var newwindow = '';
$( 'a[data-class="popup"]' ).on( 'click', function(e) {
e.preventDefault();
newwindow = window.open( $( this ).attr( 'href' ), '', 'height=270,width=500' );
if ( window.focus ) {
newwindow.focus()
}
return false;
} );
}
// execute functions here
open_links_in_popup();
} );
})( window.jQuery ); | 21.129032 | 84 | 0.429008 |
96e26dca44edff2c6ac52e6428edb013f3b031be | 1,844 | js | JavaScript | assets/app/js/helpers/splitter.js | divya814/scancode-workbench | 7997b53e3964731a3ea0cf8e0189f8ba8baa8ac9 | [
"Apache-2.0"
] | 86 | 2019-01-05T18:35:37.000Z | 2022-03-01T23:28:58.000Z | assets/app/js/helpers/splitter.js | divya814/scancode-workbench | 7997b53e3964731a3ea0cf8e0189f8ba8baa8ac9 | [
"Apache-2.0"
] | 281 | 2016-11-08T23:38:18.000Z | 2018-12-21T01:33:12.000Z | assets/app/js/helpers/splitter.js | divya814/scancode-workbench | 7997b53e3964731a3ea0cf8e0189f8ba8baa8ac9 | [
"Apache-2.0"
] | 67 | 2019-02-12T03:25:18.000Z | 2022-03-27T20:22:59.000Z | /*
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# https://nexb.com and https://github.com/nexB/scancode-workbench/
# The ScanCode Workbench software is licensed under the Apache License version 2.0.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
*/
class Splitter {
constructor(leftContainerId, rightContainerId) {
this.handlers = {};
this.splitSizes = [20, 80];
this.splitter = Split(
[leftContainerId, rightContainerId],
{
sizes: this.splitSizes,
minSize: 200,
gutterSize: 5,
elementStyle: function (dimension, size, gutterSize) {
const width = window.outerWidth * (size / 100);
return {'flex-basis': `${width - gutterSize}px`};
},
gutterStyle: (dimension, gutterSize) => {
return {'flex-basis': `${gutterSize}px`};
},
onDragEnd: () => {
this.splitSizes = this.splitter.getSizes();
this.handlers['drag-end']();
}
});
}
show() {
this.splitter.setSizes(this.splitSizes);
$('.gutter-horizontal').removeClass('div-hide').addClass('div-show');
}
hide() {
$('.gutter-horizontal').removeClass('div-show').addClass('div-hide');
this.splitter.collapse(0);
}
on(event, handler) {
this.handlers[event] = handler;
return this;
}
}
module.exports = Splitter;
| 31.254237 | 84 | 0.646963 |
96e32a1474ba2d1cb6e96948ebac686019bf7354 | 350 | js | JavaScript | src/components/figure.js | akankshakutal/springBootBlog | 12be2b0212eac4adaa64c8f3173de71542c33cfd | [
"MIT"
] | null | null | null | src/components/figure.js | akankshakutal/springBootBlog | 12be2b0212eac4adaa64c8f3173de71542c33cfd | [
"MIT"
] | null | null | null | src/components/figure.js | akankshakutal/springBootBlog | 12be2b0212eac4adaa64c8f3173de71542c33cfd | [
"MIT"
] | null | null | null | import PropTypes from "prop-types"
import React from "react"
import "./figure.css"
const Figure = ({ figurePath }) => (
<div className="figureContainer">
<img src={figurePath} alt="springAOP" className="figure"></img>
<h4 className="label">AOP</h4>
</div>
)
Figure.propTypes = {
figurePath: PropTypes.string,
}
export default Figure
| 20.588235 | 67 | 0.685714 |
96e367500f527aa2cf776f0f99f8df9d25740e7f | 3,785 | js | JavaScript | frontend/node_modules/.pnpm/@rsuite+icon-font@4.0.0/node_modules/@rsuite/icon-font/lib/legacy/Braille.js | koenw/fullstack-hello | 6a2317b7e6ace4b97134e7cc2bb5b1159b556d78 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-11-26T00:46:16.000Z | 2021-11-27T06:55:57.000Z | frontend/node_modules/.pnpm/@rsuite+icon-font@4.0.0/node_modules/@rsuite/icon-font/lib/legacy/Braille.js | koenw/fullstack-hello | 6a2317b7e6ace4b97134e7cc2bb5b1159b556d78 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-18T13:54:05.000Z | 2022-03-24T01:18:30.000Z | frontend/node_modules/.pnpm/@rsuite+icon-font@4.0.0/node_modules/@rsuite/icon-font/lib/legacy/Braille.js | koenw/fullstack-hello | 6a2317b7e6ace4b97134e7cc2bb5b1159b556d78 | [
"Apache-2.0",
"MIT"
] | null | null | null | "use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var React = _interopRequireWildcard(require("react"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function Braille(props, svgRef) {
return /*#__PURE__*/React.createElement("svg", _extends({
width: "1em",
height: "1em",
viewBox: "0 0 39 32",
fill: "currentColor",
ref: svgRef
}, props), /*#__PURE__*/React.createElement("path", {
d: "M3.429 21.143C1.858 21.143.572 22.429.572 24s1.286 2.857 2.857 2.857S6.286 25.571 6.286 24 5 21.143 3.429 21.143zm9.142 0C11 21.143 9.714 22.429 9.714 24s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857-1.286-2.857-2.857-2.857zm0-9.143C11 12 9.714 13.286 9.714 14.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857S14.142 12 12.571 12zm13.715 9.143c-1.571 0-2.857 1.286-2.857 2.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857-1.286-2.857-2.857-2.857zm9.143 0c-1.571 0-2.857 1.286-2.857 2.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857-1.286-2.857-2.857-2.857zM26.286 12c-1.571 0-2.857 1.286-2.857 2.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857S27.857 12 26.286 12zm9.143 0c-1.571 0-2.857 1.286-2.857 2.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857S37 12 35.429 12zm0-9.143c-1.571 0-2.857 1.286-2.857 2.857s1.286 2.857 2.857 2.857 2.857-1.286 2.857-2.857S37 2.857 35.429 2.857zM6.857 24a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zM16 24a3.43 3.43 0 01-6.858 0A3.43 3.43 0 0116 24zm-9.143-9.143a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zm9.143 0a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zM6.857 5.714a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zM29.714 24a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zM16 5.714a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zM38.857 24a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zm-9.143-9.143a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zm9.143 0a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zm-9.143-9.143a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0zm9.143 0a3.43 3.43 0 01-6.858 0 3.43 3.43 0 016.858 0z"
}));
}
var ForwardRef = /*#__PURE__*/React.forwardRef(Braille);
var _default = ForwardRef;
exports["default"] = _default; | 118.28125 | 1,576 | 0.683487 |
96e577961f81e7bea20f95322934827cf00374bb | 894 | js | JavaScript | node_modules/paystack-api/resources/customer.js | AduroDaniel/Anytincreative-2.0 | a85895a051202c9826d1736094dd340837932968 | [
"MIT"
] | null | null | null | node_modules/paystack-api/resources/customer.js | AduroDaniel/Anytincreative-2.0 | a85895a051202c9826d1736094dd340837932968 | [
"MIT"
] | 2 | 2021-05-08T03:06:30.000Z | 2022-02-10T15:51:20.000Z | node_modules/paystack-api/resources/customer.js | AduroDaniel/Anytincreative-2.0 | a85895a051202c9826d1736094dd340837932968 | [
"MIT"
] | null | null | null | /*
Paystack API - Customer
*/
const route = "/customer";
module.exports = {
/*
Create customer
*/
create: {
method: "post",
route: route,
params: ["first_name", "last_name", "email*", "phone", "metadata"]
},
/*
List customers
*/
list: {
method: "get",
route: route
},
/*
Get customer
*/
get: {
method: "get",
route: `${route}/{id}`
},
/*
Update customer
*/
update: {
method: "put",
route: `${route}/{id}`,
params: ["first_name", "last_name", "phone", "metadata"]
},
/*
White/Blacklist customer
*/
setRiskAction: {
method: "post",
route: `${route}/set_risk_action`,
params: ["customer*", "risk_action"]
},
/*
Deactivate Authorization for customer
*/
deactivateAuth: {
method: "post",
route: `${route}/deactivate_authorization`,
params: ["authorization_code*"]
}
}; | 15.152542 | 70 | 0.552573 |
b1ce5dbab2696f94045d0fda231f3578d842c561 | 1,522 | js | JavaScript | Prog-Imperativa/mesa18.js | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | Prog-Imperativa/mesa18.js | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | Prog-Imperativa/mesa18.js | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | // Loop de Pares
// Você deve criar uma função chamada loopDePares que receba um número como parâmetro e faça loops de 0 a 100 mostrando cada número do loop no console.
// Caso o número da iteração somado com o número passado pelo parâmetro seja par, aparecerá no console: "O número x é par"
// function loopDePares(number){
// for(var i = 0; i <= 100; i++){
// if((i + number) % 2 === 0){
// return 'o numero é par';
// } else {
// return i;
// }
// }
// }
// console.log(loopDePares(1));
// String.split()
// Você deve criar uma função chamada split que receba uma string e simule o comportamento da função split original. Se você não sabe como funciona, o Google pode ajudá-lo.
// Importante: Você não pode usar o String.split()
// Exemplo:
// split(“olá”) deve retornar [”o”,”l”,”á”]
// split(“tchau”) deve retornar [“t”,“c”,”h”,”a”,”u”]
function split(word) {
for(var init = 0; init < word.length; init++){
var finalArray = [];
return finalArray.push(word[init])
}
return finalArray;
}
// function split(word) {
// for(var init = 0; init < word.length; init++){
// var wordAsArray = [ ];
// return (wordAsArray.push(word.slice[init]));
// }
// return wordAsArray;
// }
console.log(split('issao'));
function split(word) {
word.length;
console.log(word.length);
for(var init = 0; init < word.length; init++){
console.log(word[init]);
}
} | 29.269231 | 172 | 0.588042 |
b1d0b824006b4822785381197c8bb464469ede9e | 3,213 | js | JavaScript | server.js | iomkaragrawal/CatchUpWeb | dc80f1b8f62aea493cab2012636ce3489ecc6aa4 | [
"MIT"
] | null | null | null | server.js | iomkaragrawal/CatchUpWeb | dc80f1b8f62aea493cab2012636ce3489ecc6aa4 | [
"MIT"
] | null | null | null | server.js | iomkaragrawal/CatchUpWeb | dc80f1b8f62aea493cab2012636ce3489ecc6aa4 | [
"MIT"
] | null | null | null | "use strict";
const express = require('express');
const morgan = require('morgan');
const http = require('http');
const https = require('https');
const path = require('path');
const axios = require('axios');
const bodyParser = require('body-parser');
const compression = require('compression');
const helmet = require('helmet');
//------------------------------------------------------------------------------------------------------
// To frequent use constants
//------------------------------------------------------------------------------------------------------
const app = express();
const port = process.env.PORT || 8080;
//------------------------------------------------------------------------------------------------------
// For adding functionalities to express
//------------------------------------------------------------------------------------------------------
if(process.env.NODE_ENV == "production") {
app.set('trust proxy', 1);
}
app.use(morgan('combined'));
app.use(helmet());
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "cdnjs.cloudflare.com"],
"style-src-elem": ["'self'", "cdnjs.cloudflare.com"],
"connect-src": ["'self'", "corsenabled.herokuapp.com", "*.firebaseio.com"]
},
})
);
app.use(bodyParser.json());
app.use(bodyParser.text({type: "text/xml"}));
app.use(express.static(path.join(__dirname, 'assets')));
app.use(compression('BROTLI_MODE_TEXT'));
app.listen(port, () => {console.log(`Our site is hosted on ${port}! If you donot know to open just go to browser and type (localhost:${port})`);
});
//------------------------------------------------------------------------------------------------------
// For routes
//------------------------------------------------------------------------------------------------------
//--------------------For GET Requests------------------------------------------------------------------
app.get('/favicon.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'assets','catchup.png'));
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/hackernews', (req, res) => {
axios.get("https://hnrss.org/newest.jsonfeed", {responseType: 'json'})
.then(resp => {
res.send(resp.data);
})
.catch(err => {
console.log(`\n\n ${err} \n\n`);
res.status(500).send(err);
});
});
app.get('/hackernewsTop', (req, res) => {
axios.get("https://hacker-news.firebaseio.com/v0/topstories.json", {responseType: 'json'})
.then(resp => {
res.send(resp.data);
})
.catch(err => {
console.log(`\n\n ${err} \n\n`);
res.status(500).send(err);
});
});
app.get('/hackerearth', (req, res) => {
axios.get("http://engineering.hackerearth.com/atom.xml", {responseType: 'document'})
.then(resp => {
res.send(resp.data);
})
.catch(err => {
console.log(`\n\n ${err} \n\n`);
res.status(500).send(err);
});
});
| 35.307692 | 144 | 0.438842 |
b1d0fe9b136d30abf730050e9c165494f3ce357e | 782 | js | JavaScript | oxygen-webhelp/app/nav-links/json/topicID1-d46e5189.js | fluxexample/help | a02d0c6e991104744f5ce00e923dfcc86b03f5df | [
"CC-BY-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | null | null | null | oxygen-webhelp/app/nav-links/json/topicID1-d46e5189.js | fluxexample/help | a02d0c6e991104744f5ce00e923dfcc86b03f5df | [
"CC-BY-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | null | null | null | oxygen-webhelp/app/nav-links/json/topicID1-d46e5189.js | fluxexample/help | a02d0c6e991104744f5ce00e923dfcc86b03f5df | [
"CC-BY-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | null | null | null | define({"topics" : [{"title":"About orientation of anisotropic materials","href":"UserGuide\/English\/topics\/AuSujetDeLorientationDesMateriauxAnisotropes.htm","attributes": {"data-id":"topicID1",},"menu": {"hasChildren":false,},"tocID":"topicID1-d46e5197","topics":[]},{"title":"About orientation of magnets","href":"UserGuide\/English\/topics\/AuSujetDeLorientationDesAimants.htm","attributes": {"data-id":"topicID1",},"menu": {"hasChildren":false,},"tocID":"topicID1-d46e5205","topics":[]},{"title":"Orient materials in massive regions: volume (3D) \/ face (2D)","href":"UserGuide\/English\/topics\/OrienterMateriauxDansRegionsMassivesVolumiques3DSurfaciques2D.htm","attributes": {"data-id":"topicID1",},"menu": {"hasChildren":false,},"tocID":"topicID1-d46e5213","topics":[]}]}); | 782 | 782 | 0.730179 |
b1d1800f4c715a57bb02f0f83d21ada6c61a765e | 925 | js | JavaScript | src/redux/slices/authSlice.js | dicka88/todo-daily | 6b09faf4f8d5f39bfe37c16491db0765f9927ce2 | [
"MIT"
] | null | null | null | src/redux/slices/authSlice.js | dicka88/todo-daily | 6b09faf4f8d5f39bfe37c16491db0765f9927ce2 | [
"MIT"
] | null | null | null | src/redux/slices/authSlice.js | dicka88/todo-daily | 6b09faf4f8d5f39bfe37c16491db0765f9927ce2 | [
"MIT"
] | null | null | null | import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import userService from "../../services/userService";
const initialState = {
user: {
uid: '',
displayName: '',
email: '',
preferences: {
language: 'en',
darkMode: false
}
}
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
setUser(state, action) {
state.user = { ...state.user, ...action.payload };
},
setLogout() {
return initialState;
}
}
});
export const fetchUpdateUser = createAsyncThunk(
'auth/fetchUpdateUser',
async ({ uid, data }, { dispatch }) => {
dispatch(setUser(data));
await userService.setUser(uid, data);
}
);
export const { setUser, setLogout } = authSlice.actions;
export const selectUser = (state) => state.auth.user
export const selectPreferences = (state) => state.auth.user.preferences
export default authSlice.reducer; | 22.02381 | 71 | 0.64 |
b1d1926b7c3380d991562859bfe586338bc46921 | 2,278 | js | JavaScript | support/Lab06/b4s/organization/university/b4s_client/routes/users.js | RafaelAPB/university-course | c41786650547800387b94634e7f9cd732080cf11 | [
"Apache-2.0"
] | 125 | 2020-06-29T15:53:45.000Z | 2022-03-26T11:58:44.000Z | support/Lab06/b4s/organization/university/b4s_client/routes/users.js | RafaelAPB/university-course | c41786650547800387b94634e7f9cd732080cf11 | [
"Apache-2.0"
] | 33 | 2020-06-29T16:49:38.000Z | 2022-03-28T10:27:33.000Z | support/Lab06/b4s/organization/university/b4s_client/routes/users.js | RafaelAPB/university-course | c41786650547800387b94634e7f9cd732080cf11 | [
"Apache-2.0"
] | 68 | 2020-06-29T15:54:05.000Z | 2022-03-24T05:45:20.000Z | var express = require('express');
var router = express.Router();
const Student = require('../../../../../chaincode/lib/users/student');
let contractPromise = require('../gateway');
router.post('/createStudent', async function(req, res, next) {
try{
let usersContract = await contractPromise('org2', 'universityTecnicoLisboa','org.b4s.user');
//Parse arguments from CURL/user interface
let studentId = req.body.studentId;
let universityId = req.body.universityId;
let courses = req.body.courses;
const response = await usersContract.submitTransaction('createStudent', studentId, universityId, courses);
const parsedResponse = Student.fromBuffer(response)
console.log('===============')
console.log(parsedResponse)
res.send(parsedResponse)
console.log('Transaction complete.');
} catch (error) {
console.log(`Error processing transaction. ${error}`);
res.status(200)
res.send({message: `Error processing transaction. ${error}`, error: true});
console.log(error.stack);
}
});
router.get('/getAllStudents', async function(req, res, next) {
try{
let usersContract = await contractPromise('org2', 'universityTecnicoLisboa','org.b4s.user');
const response = await usersContract.submitTransaction('getAllStudents');
const parsedResponse = Student.fromBuffer(response)
console.log('===============')
console.log(parsedResponse)
let responseArray = []
for (const element in parsedResponse) {
if (!(element == parseInt(element))) {
continue;
}
const parsedStudent = Student.deserialize(parsedResponse[element]);
responseArray.push(parsedStudent)
console.log('===============')
console.log(`Student ID: ${parsedStudent.studentId}`);
console.log(`Student's University ID: ${parsedStudent.universityId}`);
console.log(`Student courses: ${parsedStudent.enrolledCourses}`);
console.log('===============')
}
res.send(responseArray)
console.log('Transaction complete.');
} catch (error) {
console.log(`Error processing transaction. ${error}`);
res.status(200)
res.send({message: `Error processing transaction. ${error}`, error: true});
console.log(error.stack);
}
});
module.exports = router;
| 33.5 | 110 | 0.666813 |
b1d23e8226bf6e647eb07f4267d4f90878c5f545 | 1,725 | js | JavaScript | wordstream/consumer/sample.js | GeorgeNiece/k8sdemos | 2d97f9400285750f2bd5b2d2ef1ec165e93c38ff | [
"MIT"
] | 7 | 2019-12-07T05:00:23.000Z | 2022-03-19T12:56:27.000Z | wordstream/consumer/sample.js | GeorgeNiece/k8sdemos | 2d97f9400285750f2bd5b2d2ef1ec165e93c38ff | [
"MIT"
] | null | null | null | wordstream/consumer/sample.js | GeorgeNiece/k8sdemos | 2d97f9400285750f2bd5b2d2ef1ec165e93c38ff | [
"MIT"
] | 10 | 2019-10-07T21:53:41.000Z | 2021-12-19T14:42:08.000Z | /*
To get docker up and running in an environment in which Docker is installed:
docker run -d -p 6379:6379 redis
*/
console.log('I am consumer');
const redis = require('redis');
const client1 = redis.createClient();
const client2 = redis.createClient();
const client3 = redis.createClient();
let c = 0;
const timeout = setInterval(function () {
client1.xadd('mystream', '*', 'field1', 'm1', function (err) {
if (err) {
return console.error(err);
}
client1.xgroup('CREATE', 'mystream', 'mygroup', '$', function (err) {
if (err) {
//return console.error(err);
//console.error(err);
}
});
client2.xreadgroup('GROUP', 'mygroup', 'consumer', 'Block', 1000, 'NOACK',
'STREAMS', 'mystream', '>', function (err, stream) {
if (err) {
return console.error(err);
}
console.log('client2 ' + stream);
});
client3.xreadgroup('GROUP', 'mygroup', 'consumer', 'Block', 1000, 'NOACK',
'STREAMS', 'mystream', '>', function (err, stream) {
if (err) {
return console.error(err);
}
console.log('client3 ' + stream);
});
client1.xadd('mystream', '*', 'field1', 'm2', function (err) {
if (err) {
return console.error(err);
}
});
client1.xadd('mystream', '*', 'field1', 'm3', function (err) {
if (err) {
return console.error(err);
}
});
});
c++;
if (c > 100) {
clearInterval(timeout);
}
}, 1000);
| 26.953125 | 82 | 0.478261 |
b1d2ef639ace421c14cc22ebfdf68cb04b42cae7 | 500 | js | JavaScript | src/PhotoStudio.WebApp/wwwroot/core/append-to-body-async.js | QuinntyneBrown/PhotoStudio | afab565df656497cc9cd9eec4ecdac92017d07ff | [
"MIT"
] | null | null | null | src/PhotoStudio.WebApp/wwwroot/core/append-to-body-async.js | QuinntyneBrown/PhotoStudio | afab565df656497cc9cd9eec4ecdac92017d07ff | [
"MIT"
] | null | null | null | src/PhotoStudio.WebApp/wwwroot/core/append-to-body-async.js | QuinntyneBrown/PhotoStudio | afab565df656497cc9cd9eec4ecdac92017d07ff | [
"MIT"
] | null | null | null | "use strict";
var _q_1 = require("./$q");
/**
* @description Append To Body Asynchrously
* @param options
*/
exports.appendToBodyAsync = function (options) {
var deferred = _q_1.$q.defer();
document.body.appendChild(options.nativeElement);
setTimeout(function () { deferred.resolve(); }, options.wait || 100);
return deferred.promise;
};
angular.module("appendToBodyAsync", []).value("appendToBodyAsync", exports.appendToBodyAsync);
//# sourceMappingURL=append-to-body-async.js.map | 35.714286 | 94 | 0.712 |
b1d32ce73470813517fe4daa2715d83fa9f6d68b | 742 | js | JavaScript | src/__tests__/remote.test.js | vigetlabs/foliage | d0539bbfa4a056191cc73c584473b37d84bd75d5 | [
"MIT"
] | 15 | 2015-04-06T13:36:18.000Z | 2020-06-01T16:38:37.000Z | src/__tests__/remote.test.js | vigetlabs/foliage | d0539bbfa4a056191cc73c584473b37d84bd75d5 | [
"MIT"
] | 7 | 2015-04-17T19:18:48.000Z | 2016-01-05T15:18:22.000Z | src/__tests__/remote.test.js | vigetlabs/foliage | d0539bbfa4a056191cc73c584473b37d84bd75d5 | [
"MIT"
] | 1 | 2020-12-18T16:27:12.000Z | 2020-12-18T16:27:12.000Z | let remove = require('../remove')
describe('remove', function() {
it ('supports plain strings', function() {
let sample = { foo: 'bar' }
remove(sample, 'foo', 'bar').should.eql({})
})
it ('properly prunes null values', function() {
let sample = { foo: null }
remove(sample, 'foo').should.eql({})
})
it ('does not modify missing keys', function() {
let sample = { foo: 'bar' }
remove(sample, [ 'missing' ]).should.equal(sample)
})
it ('removes properties', function() {
let sample = { foo: 'bar' }
remove(sample, [ 'foo' ]).should.eql({})
})
it ('prunes empty objects', function() {
let sample = { one: { two: 'three' } }
remove(sample, [ 'one', 'two' ]).should.eql({})
})
})
| 23.935484 | 54 | 0.560647 |
b1d33d8d25cf7a3931be2ec9b1ff8e4897b60c62 | 1,273 | js | JavaScript | utils/mocks/mongoLib.js | luisrdz5/nodejs-EscuelaJavascript | 06f4594703548996848bc8d81ebe9a4e9d2ba074 | [
"MIT"
] | 1 | 2019-09-21T20:31:39.000Z | 2019-09-21T20:31:39.000Z | utils/mocks/mongoLib.js | luisrdz5/nodejs-EscuelaJavascript | 06f4594703548996848bc8d81ebe9a4e9d2ba074 | [
"MIT"
] | 3 | 2020-06-30T06:40:38.000Z | 2021-09-02T13:19:13.000Z | utils/mocks/mongoLib.js | luisrdz5/nodejs-EscuelaJavascript | 06f4594703548996848bc8d81ebe9a4e9d2ba074 | [
"MIT"
] | null | null | null | const sinon = require('sinon');
const { moviesMock, filteredMoviesMock } = require ("./movies");
const getAllStub = sinon.stub();
getAllStub.withArgs('movies').resolves(moviesMock);
const tagQuery = { tags: { $in: ['Drama']}};
getAllStub.withArgs('movies', tagQuery).resolves(filteredMoviesMock('Drama'));
const createStub = sinon.stub().resolves(moviesMock[0].id);
// se crea Stub de getMovie
const getMovieStub = sinon.stub();
getMovieStub.resolves(moviesMock[0]);
// se crea Stub de updateMovie
const updateMovieStub = sinon.stub().resolves(moviesMock[0].id);;
// se crea Stub de deleteMovie
const deleteStub = sinon.stub().resolves(moviesMock[0].id);;
class MongoLibMock {
getAll(collection, query){
return getAllStub(collection, query);
}
get(collection, id){
return getMovieStub(collection, id);
}
create(collection, data){
return createStub(collection, data);
}
update(collection, id, movie){
return updateMovieStub(collection, id, movie )
}
delete( collection, id ) {
return deleteStub( collection, id );
}
}
module.exports = {
getAllStub,
createStub,
MongoLibMock,
getMovieStub,
updateMovieStub,
deleteStub
} | 27.673913 | 79 | 0.657502 |
b1d4a3339f35f6dd96398e6489ecbf316c205052 | 175 | js | JavaScript | src/reducers/index.js | Jaakal/nasa-apod | f572e8210b7f31b0916d803ec99dc6aa8a0ae124 | [
"MIT"
] | 1 | 2020-12-29T02:14:10.000Z | 2020-12-29T02:14:10.000Z | src/reducers/index.js | Jaakal/nasa-apod | f572e8210b7f31b0916d803ec99dc6aa8a0ae124 | [
"MIT"
] | null | null | null | src/reducers/index.js | Jaakal/nasa-apod | f572e8210b7f31b0916d803ec99dc6aa8a0ae124 | [
"MIT"
] | null | null | null | import { combineReducers } from 'redux';
import medias from './medias';
import mediasFilter from './mediasFilter';
export default combineReducers({ medias, mediasFilter });
| 25 | 57 | 0.754286 |
b1d4ac6f4a2cdb56658c1a0bd62a2473d419de4e | 66 | js | JavaScript | next.config.js | gamliela/starter-nextjs-netlify | 7d80ce4eadd6255a7867b9eae3f38ac18026ccea | [
"Apache-2.0"
] | null | null | null | next.config.js | gamliela/starter-nextjs-netlify | 7d80ce4eadd6255a7867b9eae3f38ac18026ccea | [
"Apache-2.0"
] | 5 | 2020-05-25T05:05:33.000Z | 2022-02-12T23:51:27.000Z | next.config.js | gamliela/playground-auth | 4ae616ef5440879dff6dac801dfbf5a1fe0a23a5 | [
"Apache-2.0"
] | null | null | null | module.exports = {
target: "serverless",
distDir: ".next",
};
| 13.2 | 23 | 0.606061 |
b1d54fabdbae0ab6c7e68fd2211aa22a1fc65a13 | 3,256 | js | JavaScript | src/js/pages/product-request/product-request.component.js | actarian/aquafil | 7f2c631dcff7114563f09115c26fc169d3fb23b3 | [
"MIT"
] | null | null | null | src/js/pages/product-request/product-request.component.js | actarian/aquafil | 7f2c631dcff7114563f09115c26fc169d3fb23b3 | [
"MIT"
] | null | null | null | src/js/pages/product-request/product-request.component.js | actarian/aquafil | 7f2c631dcff7114563f09115c26fc169d3fb23b3 | [
"MIT"
] | null | null | null | import { Component, getContext } from 'rxcomp';
import { FormControl, FormGroup, Validators } from 'rxcomp-form';
import { first, takeUntil } from 'rxjs/operators';
import { GtmService } from '../../common/gtm/gtm.service';
import { ModalOutletComponent } from '../../common/modal/modal-outlet.component';
import { ModalService } from '../../common/modal/modal.service';
import { ProductRequestService } from './product-request.service';
export class ProductRequestComponent extends Component {
onInit() {
const { parentInstance } = getContext(this);
if (parentInstance instanceof ModalOutletComponent) {
const data = parentInstance.modal.data;
const id = data.id;
const productName = data.productName;
this.productName = productName ? productName : this.productName;
const recipient = data.recipient;
this.recipient = recipient ? recipient : this.recipient;
const download = data.download;
this.download = download ? download : this.download;
console.log('ProductRequestComponent.onInit', id, productName);
}
this.error = null;
this.success = false;
this.response = '';
this.message = '';
const form = this.form = new FormGroup({
productName: this.productName,
recipient: this.recipient,
download: this.download,
firstName: new FormControl(null, [Validators.RequiredValidator()]),
lastName: new FormControl(null, [Validators.RequiredValidator()]),
company: new FormControl(null),
email: new FormControl(null, [Validators.RequiredValidator(), Validators.EmailValidator()]),
subject: new FormControl(null),
message: new FormControl(null),
privacy: new FormControl(null, [Validators.RequiredTrueValidator()]),
checkRequest: window.antiforgery,
checkField: '',
action: 'save_product_request',
});
const controls = this.controls = form.controls;
form.changes$.pipe(
takeUntil(this.unsubscribe$)
).subscribe((_) => {
this.pushChanges();
});
}
test() {
const form = this.form;
const controls = this.controls;
form.patch({
firstName: 'Jhon',
lastName: 'Appleseed',
company: 'Websolute',
email: 'jhonappleseed@gmail.com',
subject: 'Subject',
message: 'Hi!',
privacy: true,
checkRequest: window.antiforgery,
checkField: ''
});
}
reset() {
const form = this.form;
form.reset();
}
onSubmit(model) {
const form = this.form;
console.log('ProductRequestComponent.onSubmit', form.value);
// console.log('ProductRequestComponent.onSubmit', 'form.valid', valid);
if (form.valid) {
// console.log('ProductRequestComponent.onSubmit', form.value);
form.submitted = true;
ProductRequestService.submit$(form.value).pipe(
first(),
).subscribe(_ => {
if (_.success) {
GtmService.push({ 'event': "Product Request", 'form_name': "Product Request" });
}
this.success = true;
form.reset();
this.response = _.data["response"];
this.message = _.data["message"];
}, error => {
console.log('ProductRequestComponent.error', error);
this.error = error;
this.pushChanges();
});
} else {
form.touched = true;
}
}
onClose() {
ModalService.reject();
}
}
ProductRequestComponent.meta = {
selector: '[product-request]',
inputs: ['productName', 'download'],
};
| 30.148148 | 95 | 0.684582 |
b1d57ceb4e8098bfb940a9c5e62b1ab155f6ee99 | 204 | js | JavaScript | SPA/JavaScript/ModuleTypes/Model/TreeGrouping.js | hpn777/filix | 5edfcc469f79e76bcc4b0af0f235f537cf56e4d1 | [
"MIT"
] | null | null | null | SPA/JavaScript/ModuleTypes/Model/TreeGrouping.js | hpn777/filix | 5edfcc469f79e76bcc4b0af0f235f537cf56e4d1 | [
"MIT"
] | null | null | null | SPA/JavaScript/ModuleTypes/Model/TreeGrouping.js | hpn777/filix | 5edfcc469f79e76bcc4b0af0f235f537cf56e4d1 | [
"MIT"
] | null | null | null | Ext.define('ExtModules.Model.TreeGrouping', {
statics: {
create: function (widgetTitle) {
Ext.define(widgetTitle, {
extend: 'Ext.data.Model',
fields: ['dataIndex','title']
});
}
}
}); | 20.4 | 46 | 0.617647 |
b1d60e3194a27e4bb542e3788d0413dc9ef84fb9 | 6,971 | js | JavaScript | controller/Main.controller.js | Dooobi/odata-util | 3e7fbed60813fc590ce0a81e8f783693d137fde7 | [
"MIT"
] | null | null | null | controller/Main.controller.js | Dooobi/odata-util | 3e7fbed60813fc590ce0a81e8f783693d137fde7 | [
"MIT"
] | null | null | null | controller/Main.controller.js | Dooobi/odata-util | 3e7fbed60813fc590ce0a81e8f783693d137fde7 | [
"MIT"
] | null | null | null | sap.ui.define([
"demindh/odatautils/controller/BaseController",
"demindh/odatautils/model/Constant",
"demindh/odatautils/model/formatter",
"demindh/odatautils/helper/util",
"demindh/odatautils/helper/metadataTransformer",
"sap/ui/model/json/JSONModel",
"sap/ui/layout/SplitterLayoutData",
"demindh/odatautils/controller/BatchRequestDialogController",
], function(BaseController, Constant, formatter, util, metadataTransformer, JSONModel, SplitterLayoutData, BatchRequestDialogController) {
"use strict";
var DIALOG_FRAGMENT = "demindh.odatautils.view.fragment.Dialog";
var delegateOnAfterRendering = function(event) {
console.log("afterRendering");
var table = event.srcControl;
table.removeEventDelegate(delegate);
var columns = table.getColumns();
for (var c = 0; c < columns.length; c++) {
table.autoResizeColumn(c);
}
};
var delegate = {
onAfterRendering: delegateOnAfterRendering
};
return BaseController.extend("demindh.odatautils.controller.Main", {
formatter: formatter,
util: util,
/* =========================================================== */
/* lifecycle methods */
/* =========================================================== */
/**
* Called when the controller is instantiated.
* @public
*/
onInit: function() {
var odata = this.getModel();
this.dataService = {};
this.setModel(this._createViewModel(), "viewModel");
this.eventBus = this.getOwnerComponent().getEventBus();
this.eventBus.subscribe("navigateEvent", this.navigateEvent, this);
this.navContainer = this.byId("navContainer");
odata.metadataLoaded().then(
this.transformMetadata.bind(this)
);
setTimeout(this.onTimer.bind(this), 500);
var pane = this.byId("pane");
pane.setLayoutData(new SplitterLayoutData({
size: "30%"
}));
},
/* =========================================================== */
/* event handlers */
/* =========================================================== */
onHomePress: function() {
},
transformMetadata: function() {
var odata = this.getModel(),
metaModel = metadataTransformer.transformMetadataToModel(odata);
this.eventBus.publish("beforeSettingMetaModel", metaModel);
this.setModel(metaModel, "metaModel");
},
onTimer: function() {
var data = this.dataService;
setTimeout(this.onTimer.bind(this), 500);
},
onTabSelected: function(event) {
this.navigate({
key: event.getParameter("key")
});
},
navigate: function(data) {
var view = this.byId(data.key);
this.navContainer.to(view, data);
},
navigateEvent: function(channel, eventId, data) {
this.navigate(data);
},
sendBatchRequest: function(event) {
var batchRequest = event.getSource().getBindingContext("shared").getObject();
this.getOwnerComponent().getRequestHandler().sendRequest(batchRequest);
},
requestListItemFactory: function(id, context) {
switch (context.getProperty("type")) {
case Constant.REQUEST_CREATE:
case Constant.REQUEST_UPDATE:
case Constant.REQUEST_REMOVE:
var fragment = sap.ui.xmlfragment("demindh.odatautils.view.fragment.CrudRequestListItem", this),
table = fragment.getContent()[0].getContent()[0],
dataValues = context.getProperty("data"),
dataRow = {};
// for (var i = 0; i < dataValues.length; i++) {
// var dataValue = dataValues[i];
// dataRow[dataValue.property.name] = util.transformData(dataValue);
// }
// var dataModel = new JSONModel({
// dataRow: [
// dataRow
// ]
// });
// table.addEventDelegate(delegate);
// table.setModel(dataModel, "dataModel");
return fragment;
case Constant.REQUEST_FUNCTION_IMPORT:
return sap.ui.xmlfragment("demindh.odatautils.view.fragment.FunctionImportRequestListItem", this);
}
},
formElementFactory: function(id, context) {
var property = context.getProperty("property"),
propertyName = property.name,
classification = property.classification,
fields = [];
var inputControl = util.getDisplayControl(property, "shared", "value").setWidth("100%");
if (property.isPrimaryKey) {
fields = [new sap.m.HBox({
renderType: sap.m.FlexRendertype.Bare,
width: "100%",
alignItems: "Center",
items: [
new sap.ui.core.Icon({
src: "sap-icon://primary-key",
color: "#878787"
}).addStyleClass("sapUiTinyMarginEnd"),
inputControl
]
})];
} else {
fields = [inputControl];
}
var formElement = new sap.ui.layout.form.FormElement({
label: new sap.m.Label({
text: propertyName,
required: !property.nullable
}),
fields: fields
});
return formElement;
},
entityTableColumnFactory: function(id, context) {
var propertyName = context.getProperty("name"),
nullable = context.getProperty("nullable") === "true",
columnName = propertyName;
return new sap.ui.table.Column({
label: new sap.m.HBox({
items: [
new sap.ui.core.Icon({
src: "sap-icon://primary-key",
visible: context.getProperty("isPrimaryKey"),
color: "#878787",
size: "0.8em"
}).addStyleClass("sapUiTinyMarginEnd"),
new sap.m.Label({
text: propertyName,
required: !nullable
})
]
}),
autoResizable: true,
template: util.getDisplayControl(context, "dataModel")
});
},
deleteBatchRequest: function(event) {
var pathElements = event.getSource().getBindingContext("shared").getPath(),
index = parseInt(pathElements[pathElements.length - 1], 10),
sharedModel = this.getModel("shared"),
batchRequests = this.getModel("shared").getProperty("/batchRequests");
batchRequests.splice(index, 1);
sharedModel.setProperty("/batchRequests", batchRequests);
},
openAddBatchRequestDialog: function() {
this._getBatchRequestDialogController().openAddDialog();
},
pressHistory: function(event) {
var source = event.getParameter("listItem"),
bindingContext = source.getBindingContext();
var popover = sap.ui.xmlfragment("popover", "demindh.odatautils.view.fragment.Popover", this);
this.getView().addDependent(popover);
popover.setBindingContext(bindingContext);
popover.openBy(source);
},
/* =========================================================== */
/* internal methods */
/* =========================================================== */
_createViewModel: function() {
return new JSONModel({
});
},
_getBatchRequestDialogController: function() {
if (!this.batchRequestDialogController) {
this.batchRequestDialogController = new BatchRequestDialogController(this);
}
return this.batchRequestDialogController;
}
});
}); | 29.045833 | 138 | 0.616411 |
b1d6801ba9dd1a33cf4b7626e43f9d880a1ef1c3 | 1,795 | js | JavaScript | src/cli-table.js | SlimIO/Sync | 98cf7c92e765f79b55a9bd0fef107b479cb78694 | [
"MIT"
] | null | null | null | src/cli-table.js | SlimIO/Sync | 98cf7c92e765f79b55a9bd0fef107b479cb78694 | [
"MIT"
] | 149 | 2019-12-05T04:24:29.000Z | 2021-09-02T22:01:47.000Z | src/cli-table.js | SlimIO/Sync | 98cf7c92e765f79b55a9bd0fef107b479cb78694 | [
"MIT"
] | null | null | null | /* eslint-disable arrow-body-style */
"use strict";
// Require Third-party Dependencies
const ui = require("cliui");
const { gray } = require("kleur");
class CLITable {
static create(text, width = 20, align = "left") {
return { text, width, align };
}
constructor(header, addSeperator = true) {
if (!Array.isArray(header)) {
throw new TypeError("header must be an array");
}
this.ui = ui();
this.headers = header.map((text) => {
return typeof text === "string" ? {
text,
width: 10,
align: "center"
} : text;
});
this.width = this.headers.reduce((prev, curr) => prev + curr.width, 0);
this.ui.div(...this.headers);
this.addSeperator = Boolean(addSeperator);
this.rowCount = 0;
if (this.addSeperator) {
this.ui.div({
text: gray().bold(` ${"-".repeat(this.width)}`),
width: this.width
});
}
console.log("");
}
add(rows) {
if (!Array.isArray(rows)) {
return;
}
this.rowCount++;
this.ui.div(...rows.slice(0, this.headers.length).map((text, index) => {
return typeof text === "string" ? {
width: this.headers[index].width,
align: this.headers[index].align,
text
} : text;
}));
if (this.addSeperator) {
this.ui.div({
text: gray().bold(` ${"-".repeat(this.width)}`),
width: this.width
});
}
}
show() {
if (this.rowCount > 0) {
console.log(this.ui.toString());
}
}
}
module.exports = CLITable;
| 25.642857 | 80 | 0.466852 |
b1d6fc6e9ba2f62474c1f48f5a42b354cff90039 | 1,711 | js | JavaScript | app/components/charts/competency-progress-bar.js | Gooru/ln-Gooru-FE | 682953836798d75dbd17eaa893c5dbd8fdd86fbd | [
"MIT"
] | null | null | null | app/components/charts/competency-progress-bar.js | Gooru/ln-Gooru-FE | 682953836798d75dbd17eaa893c5dbd8fdd86fbd | [
"MIT"
] | null | null | null | app/components/charts/competency-progress-bar.js | Gooru/ln-Gooru-FE | 682953836798d75dbd17eaa893c5dbd8fdd86fbd | [
"MIT"
] | null | null | null | import Ember from 'ember';
import { isCompatibleVW } from 'gooru-web/utils/utils';
import { SCREEN_SIZES } from 'gooru-web/config/config';
export default Ember.Component.extend({
// -------------------------------------------------------------------------
// Attributes
classNames: ['student-comptency-progress'],
/**
* @property {Object} competency
*/
competency: null,
/**
* @property {Boolean}
* Property to store given screen value is compatible
*/
isMobileView: isCompatibleVW(SCREEN_SIZES.LARGE),
didInsertElement() {
this.parseCompetency();
},
didRender() {
this._super(...arguments);
let component = this;
component.$('[data-toggle="tooltip"]').tooltip({
trigger: 'hover'
});
},
/**
* @function parseCompetency
* Method to calculate comptency status count and set height for div
*/
parseCompetency() {
let component = this;
let competency = component.get('competency');
let total =
competency.inprogress + competency.notstarted + competency.completed;
let completed =
competency.completed === 0
? 0
: Math.round((competency.completed / total) * 100);
let inProgress =
competency.inprogress === 0
? 0
: Math.round((competency.inprogress / total) * 100);
let notStarted =
competency.notstarted === 0
? 0
: Math.round((competency.notstarted / total) * 100);
let size = component.get('isMobileView') ? 'width' : 'height';
component.$('.completed').css(`${size}`, `${completed}%`);
component.$('.in-progress').css(`${size}`, `${inProgress}%`);
component.$('.not-started').css(`${size}`, `${notStarted}%`);
}
});
| 28.516667 | 78 | 0.593805 |
b1d7cf4dcf5a37c801f4579176797ffad65e3f80 | 477 | js | JavaScript | src/index.js | frolui/brackets | acd4bda364a1a2169303fde41017cd8058692992 | [
"MIT"
] | null | null | null | src/index.js | frolui/brackets | acd4bda364a1a2169303fde41017cd8058692992 | [
"MIT"
] | null | null | null | src/index.js | frolui/brackets | acd4bda364a1a2169303fde41017cd8058692992 | [
"MIT"
] | null | null | null | module.exports = function check(str, bracketsConfig) {
if(str.length % 2 != 0) {return false}
if(str.length == 0) {return true}
let counter = str.length;
while (str.length > 0){
for (let n = 0; n < bracketsConfig.length; n++){
str = str.replace('' + bracketsConfig[n][0] + bracketsConfig[n][1], '')
};
if (str.length == counter) {return false}
counter = str.length
}
return true
}
| 23.85 | 83 | 0.530398 |
b1d87963e9b23dae6f6f19dc18dade94f8234887 | 237 | js | JavaScript | Gruntfile.js | RetailMeNotSandbox/roux-sass-importer | ea660e7446fe56af72f3b9a241b8036c128e32f3 | [
"MIT"
] | 3 | 2016-10-18T16:42:24.000Z | 2017-04-05T09:05:31.000Z | Gruntfile.js | RetailMeNotSandbox/roux-sass-importer | ea660e7446fe56af72f3b9a241b8036c128e32f3 | [
"MIT"
] | 67 | 2016-10-17T21:04:18.000Z | 2021-06-11T14:26:26.000Z | Gruntfile.js | RetailMeNotSandbox/roux-sass-importer | ea660e7446fe56af72f3b9a241b8036c128e32f3 | [
"MIT"
] | 4 | 2016-10-17T21:02:03.000Z | 2017-10-01T02:34:28.000Z | 'use strict';
module.exports = function (grunt) {
grunt.initConfig({
eslint: {
lint: {
src: ['./']
},
fix: {
options: {
fix: true
},
src: ['./']
}
}
});
grunt.loadNpmTasks('gruntify-eslint');
};
| 11.85 | 39 | 0.481013 |
b1d8b823395d2848a1b18cde3cfa5903e9d870d1 | 1,112 | js | JavaScript | server/dist/lib/db.js | juliobguedes/tormenta | 661c2cd5a7eeb6d83fb89780c8269bb6c9fd5910 | [
"MIT"
] | 1 | 2020-03-19T18:10:48.000Z | 2020-03-19T18:10:48.000Z | server/dist/lib/db.js | juliobguedes/tormenta | 661c2cd5a7eeb6d83fb89780c8269bb6c9fd5910 | [
"MIT"
] | 18 | 2020-03-27T18:23:10.000Z | 2022-02-27T01:24:45.000Z | server/dist/lib/db.js | juliobguedes/tormenta | 661c2cd5a7eeb6d83fb89780c8269bb6c9fd5910 | [
"MIT"
] | 2 | 2020-09-27T13:56:45.000Z | 2020-10-20T20:47:50.000Z | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _mongoose = _interopRequireDefault(require("mongoose"));
var _dotenv = _interopRequireDefault(require("dotenv"));
_dotenv["default"].config();
var MONGO_URL = process.env.MONGO_URL;
var ERROR_CODE = 1;
var db = _mongoose["default"].createConnection(MONGO_URL, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
});
db.on('error', function (error) {
if (error.name === 'MongoNetworkError') {
var fp = 'Not properly connected with MongoDB.';
var sp = 'Check if your .env file is correctly filled and if you have the necessary permissions in MongoDB.';
console.log("".concat(fp, "\n").concat(sp));
} else {
console.log(error);
}
;
process.exit(ERROR_CODE);
});
db.once('open', function () {
console.log('Connection opened with Mongo Atlas');
});
var _default = db;
exports["default"] = _default;
//# sourceMappingURL=db.js.map | 25.860465 | 113 | 0.705036 |
b1daebea1db4ad1c44f3cf672579ac6fb556c447 | 1,681 | js | JavaScript | XilinxProcessorIPLib/drivers/nandps/doc/html/api/xnandps_8c.js | fpgadeveloper/embeddedsw | 23eb39df101391b896adf20fa9d6c5aee27b0adc | [
"BSD-3-Clause"
] | 1 | 2019-01-30T22:39:34.000Z | 2019-01-30T22:39:34.000Z | XilinxProcessorIPLib/drivers/nandps/doc/html/api/xnandps_8c.js | fpgadeveloper/embeddedsw | 23eb39df101391b896adf20fa9d6c5aee27b0adc | [
"BSD-3-Clause"
] | null | null | null | XilinxProcessorIPLib/drivers/nandps/doc/html/api/xnandps_8c.js | fpgadeveloper/embeddedsw | 23eb39df101391b896adf20fa9d6c5aee27b0adc | [
"BSD-3-Clause"
] | 1 | 2020-06-04T18:11:26.000Z | 2020-06-04T18:11:26.000Z | var xnandps_8c =
[
[ "Onfi_CmdReadStatus", "group__nandps__v2__3.html#ga7f3a46694f4b3c4baffca71e6fcfebab", null ],
[ "Onfi_NandInit", "group__nandps__v2__3.html#gacb42515d1fa541b8ac5e785d1fb7eefd", null ],
[ "XNandPs_CfgInitialize", "group__nandps__v2__3.html#gaddb9f847fae34f6d137f591375a7c962", null ],
[ "XNandPs_EraseBlock", "group__nandps__v2__3.html#ga22b4e2bc1af7e4bfecd4428c25a77bb8", null ],
[ "XNandPs_InitBbtDesc", "group__nandps__v2__3.html#ga92acb0aedbfa7e76759062d70a2c4a67", null ],
[ "XNandPs_Read", "group__nandps__v2__3.html#ga8e72425d265074f1c2f8c66edfd22857", null ],
[ "XNandPs_ReadCache", "group__nandps__v2__3.html#ga605bd783f065806f1d1f602f88128f9b", null ],
[ "XNandPs_ReadSpareBytes", "group__nandps__v2__3.html#gaf9857df5e1359875e429f66e46ca5a86", null ],
[ "XNandPs_ScanBbt", "group__nandps__v2__3.html#ga454c0738c0ffe28c49ba8fced47e8d9c", null ],
[ "XNandPs_SendCommand", "group__nandps__v2__3.html#gae2862ccd7e9180b843d9e73e2a8c7e7b", null ],
[ "XNandPs_Write", "group__nandps__v2__3.html#gaebab330d0fd9efef74c26a50b5829d9f", null ],
[ "XNandPs_WriteCache", "group__nandps__v2__3.html#ga8ecd5bb0fc73b3011ee0ba500e0161fe", null ],
[ "XNandPs_WriteSpareBytes", "group__nandps__v2__3.html#gaa987d756af43c965a6439f077a4ce158", null ],
[ "NandOob16", "group__nandps__v2__3.html#gae980af68044391bcf0c94bd2b35c910b", null ],
[ "NandOob32", "group__nandps__v2__3.html#gad8d144dd94afdb026486d7b34e6c58f1", null ],
[ "NandOob64", "group__nandps__v2__3.html#gaed173a3e7bda0d3a84e8f7d55aa4e81d", null ],
[ "OnfiCommands", "group__nandps__v2__3.html#ga6256f01deb0ca40af90a3b6ceb0aef94", null ]
]; | 84.05 | 104 | 0.793575 |
b1db4ca430ef8146d0cf02e121b5496add80fc0b | 75 | js | JavaScript | src/containers/MenuContainer/index.js | alexander-litvinovich/quizgame | 68135893d4ff66e5ec8ed9703e9f84e65b377240 | [
"MIT"
] | null | null | null | src/containers/MenuContainer/index.js | alexander-litvinovich/quizgame | 68135893d4ff66e5ec8ed9703e9f84e65b377240 | [
"MIT"
] | null | null | null | src/containers/MenuContainer/index.js | alexander-litvinovich/quizgame | 68135893d4ff66e5ec8ed9703e9f84e65b377240 | [
"MIT"
] | null | null | null | import MenuContainer from './MenuContainer';
export default MenuContainer;
| 25 | 44 | 0.826667 |
b1db4e25006ba143c2f5b65c1bfc363fdf857422 | 1,256 | js | JavaScript | 6-listas.js | amandagodoy/Front-end | 9d5450ce41c9e5465a85fcde97ecc2ad9afe3b1b | [
"MIT"
] | null | null | null | 6-listas.js | amandagodoy/Front-end | 9d5450ce41c9e5465a85fcde97ecc2ad9afe3b1b | [
"MIT"
] | null | null | null | 6-listas.js | amandagodoy/Front-end | 9d5450ce41c9e5465a85fcde97ecc2ad9afe3b1b | [
"MIT"
] | null | null | null | console.log(`Trabalhando c/ listas`);
// const salvador = `Salvador`;
// const saoPaulo = `São Paulo`;
// const rioDeJaneiro = `Rio de Janeiro`;
const listaDeDestinos = new Array(
`Salvador`,
`São Paulo`,
`Rio de Janeiro`
);// new(nova) Array(lista) essa estrutura de lista, esse novo Array vai imprimir no console a variável em forma de lista.
//let new = 2; Tome cuidado em usar palavras reservadas como variável, pois o IDEL pode informar erro
listaDeDestinos.push(`Curitiba`);// isso possibilita que seja incluso na nova lista uma nova item.
console.log("Destinos possíveis:");
console.log(listaDeDestinos);
listaDeDestinos.splice(1,1); //splice seria um comando para remover um elemento
console.log(listaDeDestinos);//aqui o console vai imprimir somente os itens não solicitados no comando p/ ser splice(removido) da lita, ou seja, ao decretar a posição e quantidade de elementos a serem excluidos, seu console vai mostrar a lista sem o elemento removido.
//console.log(listaDeDestinos[1]); aqui depois de solicitar um comando de removação de elemento, entre couchetes o comando da posição dos elementos novos posicionados é impresso no console e o elemento solicitado é mostrado.
console.log(listaDeDestinos[1], listaDeDestinos[0]); | 62.8 | 268 | 0.76672 |
b1dcc6fdf8245dca9316920e4be9d3208cc4af6c | 4,930 | js | JavaScript | default/RoleRepairer.js | fiher/ScreepsAI | 7ee5018efa3c63954edddf2bd71c73d6a40c4ec2 | [
"MIT"
] | null | null | null | default/RoleRepairer.js | fiher/ScreepsAI | 7ee5018efa3c63954edddf2bd71c73d6a40c4ec2 | [
"MIT"
] | null | null | null | default/RoleRepairer.js | fiher/ScreepsAI | 7ee5018efa3c63954edddf2bd71c73d6a40c4ec2 | [
"MIT"
] | null | null | null | let ServiceCreeps = require('ServiceCreeps')
class RoleRepairer {
constructor() {
this.name = 'Repairer'
this.priority = 6
this.prespawn = 50
}
getPriority(room) {
return this.priority
}
getPrespawn() {
return this.prespawn
}
getName() {
return this.name
}
getMaximum(room) {
const storage = Game.rooms[room.name].storage
if(storage && storage.store.energy < CRITICAL_STORAGE_ENERGY){
return 0
}else if(storage && storage.store.energy < LOW_STORAGE_ENERGY){
return 1
}
if (room.level < 3) {
return 0
}
if (room.underAttack && room.threatLevel > 1) {
return 3
}
return 2
}
getBuild(room) {
if (Game.rooms[room.name].storage && Game.rooms[room.name].storage.store.energy < 30000) {
return [CARRY, CARRY, WORK, WORK, MOVE, MOVE]
}
if (room.energyCapacityAvailable > 4000) {
return [CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, WORK, WORK, MOVE, MOVE, MOVE, MOVE]
}
if (room.energyCapacityAvailable > 750) {
return [CARRY, CARRY, CARRY, CARRY, CARRY, WORK, WORK, WORK, MOVE, MOVE, MOVE, MOVE]
}
if (room.energyCapacityAvailable > 800) {
return [CARRY, CARRY, CARRY, WORK, WORK, MOVE, MOVE]
}
return [CARRY, CARRY, CARRY, WORK, MOVE, MOVE]
}
work(repairer) {
if (!repairer.memory.target || !repairer.memory.destination) {
return false
}
let target = Game.getObjectById(repairer.memory.target)
if (repairer.carry.energy === repairer.carryCapacity) {
repairer.memory.repairing = true
}
if (target && target.hits === target.hitsMax) {
repairer.memory.target = ''
repairer.memory.repairing = false
return false
}
if (repairer.carry.energy === 0 && repairer.memory.repairing) {
repairer.memory.target = ''
repairer.memory.repairing = false
return false
}
let operationResult = ''
let destination = ''
if (repairer.memory.repairing) {
operationResult = repairer.repair(target)
} else {
//Even though the name is `destination` the variable is called `target`
//so that if the repairer is not at its target I can call `repairer.moveTo` for both
//target and destination
//TODO FIX THIS SHIT BECAUSE WHEN NEXT TO TARGET I MOVE RANGE 3, NOT RANGE 1
target = Game.getObjectById(repairer.memory.destination)
if (target && target.structureType) {
operationResult = repairer.withdraw(target, RESOURCE_ENERGY)
} else {
operationResult = repairer.pickup(target)
}
}
if (operationResult === ERR_NOT_IN_RANGE) {
repairer.moveTo(target, {
range: 1
})
return
} else if (operationResult !== OK) {
repairer.memory.destination = ''
}
}
state(repairer) {
let states = {
"repairing": ServiceCreeps.repair,
"moveToTarget": ServiceCreeps.moveToTarget,
"moveToDestination": ServiceCreeps.moveToDestination,
"collecting": ServiceCreeps.collect
}
let stateFunction = states[repairer.memory.state]
if (!stateFunction) {
stateFunction = states['moveToDestination']
}
stateFunction(repairer)
}
repair(repairer) {
if (repairer.repair(Game.getObjectById(repairer.memory.target)) === ERR_NOT_ENOUGH_RESOURCES) {
repairer.memory.state = 'moveToDestination'
}
}
moveToTarget(repairer) {
let target = Game.getObjectById(repairer.memory.target)
if (repairer.repair(target) === ERR_NOT_IN_RANGE) {
repairer.moveTo(target, {
range: 3
})
return
}
repairer.memory.state = 'repair'
}
moveToDestination(repairer) {
let destination = Game.getObjectById(repairer.memory.destination)
if (!repairer.pos.isNearTo(destination)) {
repairer.moveTo(destination)
return
}
repairer.memory.state = 'collect'
}
collect(repairer) {
destination = Game.getObjectById(repairer.memory.destination)
if (destination.structureType) {
repairer.withdraw(destination, RESOURCE_ENERGY)
return
} else {
operationResult = repairer.pickup(destination)
}
if (repairer.carry.energy === repairer.carryCapacity) {
repairer.memory.state = 'moveToTarget'
return
}
}
}
module.exports = new RoleRepairer | 34.236111 | 103 | 0.566734 |
b1dd61b05810ef08a7adb98031db5f336fdc87d4 | 3,920 | js | JavaScript | public/app/ui/images/Learn React _ Codecademy_files/432.3c498f7f99bc449b55af.chunk.js | lwross-sf/iminusler | 5a6e14f41bb72221660b7421e1af451d5f801c27 | [
"MIT"
] | null | null | null | public/app/ui/images/Learn React _ Codecademy_files/432.3c498f7f99bc449b55af.chunk.js | lwross-sf/iminusler | 5a6e14f41bb72221660b7421e1af451d5f801c27 | [
"MIT"
] | null | null | null | public/app/ui/images/Learn React _ Codecademy_files/432.3c498f7f99bc449b55af.chunk.js | lwross-sf/iminusler | 5a6e14f41bb72221660b7421e1af451d5f801c27 | [
"MIT"
] | null | null | null | (window.__LOADABLE_LOADED_CHUNKS__=window.__LOADABLE_LOADED_CHUNKS__||[]).push([[432],{"P/jk":function(e,t,a){"use strict";a.d(t,"a",(function(){return LoginOrRegistration}));var n=a("ODXe"),o=a("kB5q"),r=a("q1tI"),i=a.n(r),s=a("fw5G"),c=a.n(s),u=a("/MKj"),d=a("8+UW"),g=a("Rab/"),m="input__2RCQhdloGqNJ-uu6MtK53P",l="submitButton__lTb3tkVndE_n6Rea4d_WB",_="loginContainer__28l28EdGgx8UWT7wAOlxTG",p="footer__31YdduGeq--HdMwSoUCXn8";const LoginSection=({fromPlatform:e})=>{const t=((e,t)=>t?e.pathname:new c.a("".concat(e.pathname,"?").concat(e.search)).deleteQueryParam("logged_in_via_checkout").addQueryParam("logged_in_via_checkout",!0).toString())(Object(u.useSelector)(g.f),e);return i.a.createElement(d.a,{classNames:{submitButton:l,input:m,loginForm:_,footer:p},compact:!0,redirectUrl:t})};var b=a("1aMd"),f=a("b0K7"),h="input__3XMFApGXqbYNkLB4QIWzDf",O="formGroups__2KjqLsZFWjiN0FjqtWTrK1",N="submitButton__1klbVFD_fqN3yOVdibNj4M";const RegistrationSection=({signupData:e,skipOnboarding:t,ctaText:a})=>{const n=Object(u.useSelector)(g.f),o=Object(r.useCallback)((()=>{const a=e?Object(f.Fb)({skipOnboarding:t,redirectUrl:null==e?void 0:e.redirectUrl,fromSignUpPage:!!e,loggedInViaCheckout:!e}):(e=>new c.a("".concat(e.pathname,"?").concat(e.search)).deleteQueryParam("logged_in_via_checkout").addQueryParam("logged_in_via_checkout",!0).addQueryParam("skipOnboarding",!0).toString())(n);window.location.assign(a)}),[t,e,n]);return i.a.createElement(b.a,{ctaText:a,hideRecaptchaInfo:!0,markValidatedFields:!0,onSuccess:o,submitButtonProps:{theme:"brand-blue",size:"small"},classNames:{input:h,formGroups:O,submitButton:N}})};var v="formContainer__QEg6AK-Ja8ZCQ3Tq9spKD",S="cardShell__eEJOS0NvBvL3BDNUdGe9e",E="form__2sFojCjJNzqM_z9hArMljU",k="formHeader__1GRAk8XPntIqp6M7ARX6Uo",C="accountSection__3rbkrI-IdvK6GS9V4mg67X",P="formFooter__26tAGb9U4geJsuvM4e7ql-",U="formQuestion__1q7aJgyN3bZdFuT5ed3YtO",j="formSuggestion__1mTurqCXSwT9UCQXBs0BOW";const q={login:{heading:"Log In"},register:{heading:"Create Account",cta:"Create Account"}},LoginOrRegistration=({signInFormData:e,signUpFormData:t,loginOrRegistrationCopy:{login:a,register:s}=q,skipOnboarding:c})=>{const u=Object(r.useState)(!1),d=Object(n.a)(u,2),g=d[0],m=d[1],l=g?{formQuestion:"Don't have an account?",formSuggestion:"Create Account",formHeader:a.heading}:{formQuestion:"Already have an account?",formSuggestion:"Log In",formHeader:s.heading},_=g?i.a.createElement(LoginSection,{fromPlatform:!!e}):i.a.createElement(RegistrationSection,{signupData:t,ctaText:s.cta,skipOnboarding:c});return i.a.createElement("div",{className:v,"data-testid":"login-or-registration-v2"},i.a.createElement(o.a,{className:S},i.a.createElement("div",{className:E},i.a.createElement("h1",{className:k,"data-testid":"login-or-registration-header-v2"},l.formHeader),i.a.createElement("div",{className:C},_),i.a.createElement("div",{className:P},i.a.createElement("span",{className:U,"data-testid":"login-or-registration-question-v2"},l.formQuestion),i.a.createElement("button",{type:"button",className:j,"data-testid":"login-or-registration-suggestion-v2",onClick:()=>m(!g)},l.formSuggestion)))))}},izqJ:function(e){e.exports=JSON.parse('{"catalog":"Catalog","community":"Community","business":"For Business","home":"My Home","menu":"Menu","pricing":"Pricing","proPricing":"Pro Pricing","resources":"Resources","signUp":"Sign up","unpauseNow":"Unpause Now","upgradePro":"Upgrade to Pro","upgradeNow":"Upgrade Now","tryProForFree":"Try Pro For Free"}')},yc2H:function(e,t,a){"use strict";a.d(t,"a",(function(){return AdImpression}));var n=a("ODXe"),o=a("q1tI"),r=a.n(o),i=a("aqT/"),s=a.n(i),c=a("z9go");const AdImpression=({children:e,payload:t})=>{const a=Object(o.useState)(!1),i=Object(n.a)(a,2),u=i[0],d=i[1];return r.a.createElement(s.a,{onChange:e=>{e&&!u&&(Object(c.b)("ad","impression",t),d(!0))}},e)}}}]);
//# sourceMappingURL=432.3c498f7f99bc449b55af.chunk.js.map | 1,960 | 3,861 | 0.750765 |
b1dd6493af7bd6f1540038a380a190a6cfb18687 | 357 | js | JavaScript | index.js | thesephist/strat | eb156149f3aa79dac191ad13dd849cb94e226371 | [
"MIT"
] | 3 | 2018-03-27T14:51:12.000Z | 2021-04-20T02:02:36.000Z | index.js | thesephist/strat | eb156149f3aa79dac191ad13dd849cb94e226371 | [
"MIT"
] | null | null | null | index.js | thesephist/strat | eb156149f3aa79dac191ad13dd849cb94e226371 | [
"MIT"
] | null | null | null | const { Portfolio } = require('./src/models/portfolio.js');
(async () => {
// some math
const ptf = new Portfolio({
QQQ: 1,
SPY: 1,
DIA: 1,
});
const start = new Date('2018-01-01');
const end = new Date();
console.log(ptf.toString());
ptf.formattedTx(start, end, 7000).then(v => console.log(v));
})();
| 21 | 64 | 0.529412 |
b1dd67dbc48558a55eed8c4729f797cc04736392 | 269 | js | JavaScript | docs/search/typedefs_1.js | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | 3 | 2018-01-18T07:12:34.000Z | 2018-01-22T10:00:29.000Z | docs/search/typedefs_1.js | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | null | null | null | docs/search/typedefs_1.js | betterchainio/betterchain | 29f82c25ae6812beaf09f8d7069932474bea9f8b | [
"MIT"
] | 2 | 2018-01-30T01:03:10.000Z | 2019-02-28T09:04:06.000Z | var searchData=
[
['base_5ftoken_5ftype',['base_token_type',['../structbetterchain_1_1price.html#a50171d60c92837867ed507a247d8a550',1,'betterchain::price']]],
['bytes',['bytes',['../namespacebetterchain.html#a29af370d237fce6bc6bed2cb98bde53f',1,'betterchain']]]
];
| 44.833333 | 142 | 0.765799 |
b1dd8a7f1b3216a98b869d5d46756b6661f42e51 | 3,461 | js | JavaScript | sugar/modules/KBContents/clients/base/fields/enum-config/enum-config.js | tonyberrynd/SugarDockerized | 65e0f8f99225586641487f24cfb3dc9c0a63449d | [
"Apache-2.0"
] | null | null | null | sugar/modules/KBContents/clients/base/fields/enum-config/enum-config.js | tonyberrynd/SugarDockerized | 65e0f8f99225586641487f24cfb3dc9c0a63449d | [
"Apache-2.0"
] | null | null | null | sugar/modules/KBContents/clients/base/fields/enum-config/enum-config.js | tonyberrynd/SugarDockerized | 65e0f8f99225586641487f24cfb3dc9c0a63449d | [
"Apache-2.0"
] | null | null | null | /*
* Your installation or use of this SugarCRM file is subject to the applicable
* terms available at
* http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.
* If you do not agree to all of the applicable terms or do not have the
* authority to bind the entity as an authorized representative, then do not
* install or use this SugarCRM file.
*
* Copyright (C) SugarCRM Inc. All rights reserved.
*/
({
extendsFrom: 'EnumField',
/**
* @inheritdoc
*/
initialize: function(opts) {
this._super('initialize', [opts]);
if (this.model.isNew() && this.view.action === 'detail') {
this.def.readonly = false;
} else {
this.def.readonly = true;
}
},
/**
* @inheritdoc
*/
loadEnumOptions: function(fetch, callback) {
var module = this.def.module || this.module,
optKey = this.def.key || this.name,
config = app.metadata.getModule(module, 'config') || {};
this._setItems(config[optKey]);
fetch = fetch || false;
if (fetch || !this.items) {
var url = app.api.buildURL(module, 'config', null, {});
app.api.call('read', url, null, {
success: _.bind(function(data) {
this._setItems(data[optKey]);
callback.call(this);
}, this)
});
}
},
/**
* @inheritdoc
*/
_loadTemplate: function() {
this.type = 'enum';
this._super('_loadTemplate');
this.type = this.def.type;
},
/**
* Sets current items.
* @param {Array} values Values to set into items.
*/
_setItems: function(values) {
var result = {},
def = null;
_.each(values, function(val) {
var tmp = _.omit(val, 'primary');
_.extend(result, tmp);
if (val.primary) {
def = _.first(_.keys(tmp));
}
});
this.items = result;
if (def && _.isUndefined(this.model.get(this.name))) {
this.defaultOnUndefined = false;
// call with {silent: true} on, so it won't re-render the field, since we haven't rendered the field yet
this.model.set(this.name, def, {silent: true});
//Forecasting uses backbone model (not bean) for custom enums so we have to check here
if (_.isFunction(this.model.setDefault)) {
this.model.setDefault(this.name, def);
}
}
},
/**
* @inheritdoc
*
* Filters language items for different modes.
* Disable edit mode for editing revision and for creating new revision.
* Displays only available langs for creating localization.
*/
setMode: function(mode) {
if (mode == 'edit') {
if (this.model.has('id')) {
this.setDisabled(true);
} else if (this.model.has('related_languages')) {
if (this.model.has('kbarticle_id')) {
this.setDisabled(true);
} else {
_.each(this.model.get('related_languages'), function(lang) {
delete this.items[lang];
}, this);
this.model.set(this.name, _.first(_.keys(this.items)), {silent: true});
}
}
}
this._super('setMode', [mode]);
}
})
| 32.046296 | 116 | 0.52586 |
b1df377a903d8d7a3405b94aa2b4db2012492fb6 | 820 | js | JavaScript | client/components/LoginScreen.js | MyWebIntelligence/MyWebIntelligence | 783d43cbb6bfd036a81b124aedd84f81d6196114 | [
"MIT"
] | 16 | 2015-01-16T10:26:17.000Z | 2020-12-29T18:32:08.000Z | client/components/LoginScreen.js | MyWebIntelligence/MyWebIntelligence | 783d43cbb6bfd036a81b124aedd84f81d6196114 | [
"MIT"
] | 255 | 2015-01-05T09:05:11.000Z | 2016-09-02T08:19:08.000Z | client/components/LoginScreen.js | MyWebIntelligence/MyWebIntelligence | 783d43cbb6bfd036a81b124aedd84f81d6196114 | [
"MIT"
] | 8 | 2015-01-05T09:06:32.000Z | 2020-12-29T18:34:41.000Z | "use strict";
var React = require('react');
var LoginBox = React.createFactory(require('./LoginBox'));
/*
interface LoginScreenProps{
moveToTerritoiresScreen : () => void
}
*/
module.exports = React.createClass({
displayName: 'LoginScreen',
getInitialState: function() {
return {};
},
render: function() {
var props = this.props;
return React.DOM.section({id: 'sectionConnexion'},
React.DOM.div({id: 'sectionConnexionBox'},
React.DOM.div({id: 'sectionConnexionBoxContent'},
new LoginBox({
onLogin: function(){
props.moveToTerritoiresScreen();
}
})
)
)
)
}
});
| 21.025641 | 65 | 0.487805 |
b1df4cf122bb63d3efd1fbef5add7700b4caefba | 3,823 | js | JavaScript | src/components/features/cockpit/render.js | fernandocamargo/architecture | c60110f0b48e8eb1f5b0ad638114636cd877afbd | [
"MIT"
] | null | null | null | src/components/features/cockpit/render.js | fernandocamargo/architecture | c60110f0b48e8eb1f5b0ad638114636cd877afbd | [
"MIT"
] | null | null | null | src/components/features/cockpit/render.js | fernandocamargo/architecture | c60110f0b48e8eb1f5b0ad638114636cd877afbd | [
"MIT"
] | null | null | null | import last from "lodash/last";
import random from "lodash/random";
import React, { Fragment } from "react";
export const prevent = callback => event =>
event.preventDefault() || callback(event);
export const getStatus = ({ loading, output, error }) => {
switch (true) {
case !!output || (!loading && !error):
return <span style={{ color: "green" }}>success</span>;
case !!error:
return <span style={{ color: "red" }}>fail</span>;
default:
return "loading...";
}
};
export const LoggerItem = ({
path,
params,
start,
finish,
dismiss,
...props
}) => (
<dl
style={{
backgroundColor: "#fff",
border: "dotted 1px #000",
margin: "1rem",
padding: "1rem"
}}
>
<dt>
<h2>
Method: {path.join(".")}
();
</h2>
</dt>
<dt>
<h2>Params:</h2>
<pre>{JSON.stringify(params)}</pre>
</dt>
<dd>
<small>Start: {start.toUTCString()}</small>
</dd>
{!!finish && (
<dd>
<small>Finish: {finish.toUTCString()}</small>
</dd>
)}
<dd>Status: {getStatus(props)}</dd>
{!!dismiss && (
<dd>
<a href="/" title="Dismiss" onClick={prevent(dismiss)}>
Dismiss
</a>
</dd>
)}
</dl>
);
export const Logger = ({ title, log }) =>
!!log.length && (
<div style={{ border: "dotted 1px #000" }}>
<h1>{title}</h1>
{log.map((item, key) => (
<LoggerItem key={key} {...item} />
))}
</div>
);
export const stringify = object =>
typeof object === "string" ? object : JSON.stringify(object, null, 2);
export const Button = ({ onClick, children, loading, output, error }) => (
<Fragment>
<button onClick={onClick} disabled={loading}>
{children} {loading && "(loading...)"}
</button>
{!!output &&
!loading && (
<p style={{ color: "green" }}>
<strong>Success: {stringify(output)}</strong>
</p>
)}
{!!error &&
!loading && (
<p style={{ color: "red" }}>
<strong>Error: {stringify(error)}</strong>
</p>
)}
{!!loading && <p>Loading...</p>}
</Fragment>
);
export default ({
test,
Listen,
a: {
b: {
c: { d, e, f },
g,
h,
i
}
}
}) => (
<Fragment>
<h2>Cockpit (sandbox)</h2>
<Listen to={"a"} params={1} as="log">
<Logger title="Listening to a namespace 'a' with params [1]" />
</Listen>
<Listen to={"a"} params={[1, 2]} as="log">
<Logger title="Listening to a namespace 'a' with params [1, 2]" />
</Listen>
<Listen to={"a"} params={() => [1, 2, 3]} as="log">
<Logger title="Listening to a namespace 'a' with params [1, 2, 3]" />
</Listen>
<Listen to={test} as={status => status} format={last}>
<Button onClick={() => test()}>Testing</Button>
</Listen>
<Listen to={test} as="log">
<Logger title="Listening to test();" />
</Listen>
<Listen to={test} as={status => status} format={last}>
<Button onClick={() => test()}>Testing</Button>
</Listen>
<Listen as="log">
<Logger title="Listening to everything" />
</Listen>
<table>
<tbody>
<tr>
<td>
<button onClick={() => d(1, 2, 3)}>D</button>
</td>
<td>
<button onClick={() => e(2)}>E</button>
</td>
<td>
<button onClick={() => f(3)}>F</button>
</td>
</tr>
<tr>
<td>
<button onClick={() => g(1, 2)}>G</button>
</td>
<td>
<button onClick={() => h(1, 2)}>H</button>
</td>
<td>
<button onClick={() => i(random(1, 10))}>I</button>
</td>
</tr>
</tbody>
</table>
</Fragment>
);
| 23.745342 | 75 | 0.475543 |
b1dfb1f0ac611277e292422745bd26c040eb57dd | 337 | js | JavaScript | src/App.js | superhackerboy/milkbox-kids | dcad40061fbde82b25be750de3abc608ca63bd30 | [
"MIT"
] | null | null | null | src/App.js | superhackerboy/milkbox-kids | dcad40061fbde82b25be750de3abc608ca63bd30 | [
"MIT"
] | null | null | null | src/App.js | superhackerboy/milkbox-kids | dcad40061fbde82b25be750de3abc608ca63bd30 | [
"MIT"
] | null | null | null | import React from "react";
import MissingChildCard from "./components/MissingChildCard";
// https://www.codementor.io/@peterodekwo/create-a-simple-react-npm-package-in-simple-steps-using-cra-w966okagi
function App() {
return (
<MissingChildCard userLocation={"placeholder"} options={"placeholder"} />
);
}
export default App;
| 25.923077 | 111 | 0.744807 |
b1dff133204617370cbd3c445c8d94cc282708b0 | 707 | js | JavaScript | src/components/HomeText/index.js | tniles320/tniles320.github.io | e381a89cd0d4e409fc46d8c2e1afc959af4b86d2 | [
"MIT"
] | null | null | null | src/components/HomeText/index.js | tniles320/tniles320.github.io | e381a89cd0d4e409fc46d8c2e1afc959af4b86d2 | [
"MIT"
] | null | null | null | src/components/HomeText/index.js | tniles320/tniles320.github.io | e381a89cd0d4e409fc46d8c2e1afc959af4b86d2 | [
"MIT"
] | null | null | null | import React from "react";
import "./style.css";
function HomeText() {
return (
<div className="card-body home-text">
<h3 className="card-title">A little about me</h3>
<p className="card-text" id="about-text">
I am a Software Engineer currently working on freelance projects <br />I
have experience with the following:
</p>
<div className="row no-gutters d-flex justify-content-around">
<p className="languages">HTML</p>
<p className="languages">CSS</p>
<p className="languages">Javascript</p>
<p className="languages">Node</p>
<p className="languages">React</p>
</div>
</div>
);
}
export default HomeText;
| 29.458333 | 80 | 0.622348 |
b1e088dca6bcc935c70c60974cad33a9c83674ee | 614 | js | JavaScript | src/35-search-insert-position/index.js | tangweikun/leetcode | 74a5c0be58fe7aa9346132c3eb07007a334017bf | [
"MIT"
] | 174 | 2018-01-30T01:22:48.000Z | 2022-02-03T20:41:54.000Z | src/35-search-insert-position/index.js | tangweikun/long-claw | 74a5c0be58fe7aa9346132c3eb07007a334017bf | [
"MIT"
] | 3 | 2017-11-08T14:09:16.000Z | 2017-12-21T11:51:58.000Z | src/35-search-insert-position/index.js | tangweikun/leetcode | 74a5c0be58fe7aa9346132c3eb07007a334017bf | [
"MIT"
] | 9 | 2018-05-31T16:09:21.000Z | 2020-07-12T20:34:20.000Z | export function searchInsert(nums, target) {
if (target < nums[0]) return 0;
if (target > nums[nums.length - 1]) return nums.length;
return binarySearch(nums, target, 0, nums.length - 1);
}
function binarySearch(nums, target, low, high) {
const mid = low + Math.floor((high - low) / 2);
while (low + 1 < high) {
if (nums[mid] === target) return mid;
if (nums[mid] > target) return binarySearch(nums, target, low, mid);
return binarySearch(nums, target, mid, high);
}
// TODO: bug risk
if (nums[low] === target) return low;
if (nums[high] === target) return high;
return mid + 1;
}
| 32.315789 | 72 | 0.638436 |
b1e0ab5d3b7497899519616f281c7f80e4423ace | 1,360 | js | JavaScript | src/pages/about.js | derrxb/derrxb | e4a6c3608e8334941d1b0684faf4a9cd449bc079 | [
"MIT"
] | 1 | 2019-07-14T03:08:09.000Z | 2019-07-14T03:08:09.000Z | src/pages/about.js | derrxb/derrxb | e4a6c3608e8334941d1b0684faf4a9cd449bc079 | [
"MIT"
] | 2 | 2020-07-26T07:57:20.000Z | 2021-11-22T16:25:32.000Z | src/pages/about.js | derrxb/derrxb | e4a6c3608e8334941d1b0684faf4a9cd449bc079 | [
"MIT"
] | null | null | null | /* eslint-disable react/no-danger */
import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'gatsby';
import Image from 'gatsby-image';
import Layout from '../components/layout';
import SEO from '../components/seo';
import { Hero } from '../components/shared/Hero';
import { MarkdownWrapper, H1 } from '../components/shared';
const About = ({ data }) => (
<Layout>
<SEO
title="About Me"
keywords={['belizean photographer', 'software developer in belize']}
/>
<Hero>
<Image fluid={data.about.frontmatter.heroImage.childImageSharp.fluid} />
</Hero>
<H1 style={{ marginTop: '1em' }}>
Hi! I'm Derrick (施德睿)
<span role="img" aria-label="man using computer and camera">
👨💻📷
</span>
</H1>
<MarkdownWrapper dangerouslySetInnerHTML={{ __html: data.about.html }} />
</Layout>
);
About.propTypes = {
data: PropTypes.shape({
about: PropTypes.object.isRequired,
}).isRequired,
};
export const aboutMeQuery = graphql`
query {
about: markdownRemark(frontmatter: { title: { eq: "about-me" } }) {
html
frontmatter {
heroImage {
childImageSharp {
fluid(maxWidth: 2000, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
export default About;
| 23.859649 | 78 | 0.600735 |
b1e1bb8f8a192d7aaa384b8372a12f7e432b1f44 | 71 | js | JavaScript | src/components/StorySection/index.js | SupratikRulz/watchflix | 7af415ce76c7d176771d5cbca3c1e9a357631c63 | [
"RSA-MD"
] | null | null | null | src/components/StorySection/index.js | SupratikRulz/watchflix | 7af415ce76c7d176771d5cbca3c1e9a357631c63 | [
"RSA-MD"
] | null | null | null | src/components/StorySection/index.js | SupratikRulz/watchflix | 7af415ce76c7d176771d5cbca3c1e9a357631c63 | [
"RSA-MD"
] | null | null | null | import StorySection from './StorySection'
export default StorySection
| 17.75 | 41 | 0.830986 |
b1e338c9359263656d8ad6ab5244c279b779dce7 | 919 | js | JavaScript | src/runtime/visitors/generics/AbsoluteFormVisitor.js | char0n/http-request-in-editor | 30380036dc4bf8a124d4734b3b3051e6641bd631 | [
"Apache-2.0"
] | 32 | 2020-03-20T09:34:38.000Z | 2022-02-22T21:36:36.000Z | src/runtime/visitors/generics/AbsoluteFormVisitor.js | char0n/http-request-in-editor | 30380036dc4bf8a124d4734b3b3051e6641bd631 | [
"Apache-2.0"
] | 60 | 2020-03-11T11:43:37.000Z | 2022-03-26T18:52:02.000Z | src/runtime/visitors/generics/AbsoluteFormVisitor.js | char0n/http-request-in-editor-impl | 534ce1c05ddb70b43270cff655cdf5c2cfd95b8d | [
"Apache-2.0"
] | null | null | null | 'use strict';
const stampit = require('stampit');
const { visit } = require('../../../visitor');
const AbsolutePathVisitor = require('./AbsolutePathVisitor');
const AbsoluteFormVisitor = stampit({
props: {
absoluteForm: '',
},
methods: {
scheme(node) {
this.absoluteForm = `${node.value}://`;
},
'ipv4-or-reg-name': function ipv4OrRegName(node) {
this.absoluteForm += node.value;
},
'ipv6-address': function ipv6Address(node) {
this.absoluteForm += `[${node.value}]`;
},
'absolute-path': function absolutePath(node) {
const visitor = AbsolutePathVisitor();
visit(node, visitor);
this.absoluteForm += visitor.absolutePath;
return false;
},
query(node) {
this.absoluteForm += `?${node.value}`;
},
fragment(node) {
this.absoluteForm += `#${node.value}`;
},
},
});
module.exports = AbsoluteFormVisitor;
| 22.975 | 61 | 0.601741 |
b1e3771cd0a5976927aae7b5e3995540f9656869 | 2,503 | js | JavaScript | static/assets/echarts/js/9a63b2a257d7d76349df2ca38a3c97c5.js | tblxdezhu/STP | db3db2183a70b39e155a0b3a061dc5d3e29e6c9f | [
"MIT"
] | null | null | null | static/assets/echarts/js/9a63b2a257d7d76349df2ca38a3c97c5.js | tblxdezhu/STP | db3db2183a70b39e155a0b3a061dc5d3e29e6c9f | [
"MIT"
] | null | null | null | static/assets/echarts/js/9a63b2a257d7d76349df2ca38a3c97c5.js | tblxdezhu/STP | db3db2183a70b39e155a0b3a061dc5d3e29e6c9f | [
"MIT"
] | null | null | null | (function (root, factory) {if (typeof define === 'function' && define.amd) {define(['exports', 'echarts'], factory);} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {factory(exports, require('echarts'));} else {factory({}, root.echarts);}}(this, function (exports, echarts) {var log = function (msg) {if (typeof console !== 'undefined') {console && console.error && console.error(msg);}};if (!echarts) {log('ECharts is not Loaded');return;}if (!echarts.registerMap) {log('ECharts Map is not loaded');return;}echarts.registerMap('白河县', {"type":"FeatureCollection","features":[{"type":"Feature","id":"610929","properties":{"name":"白河县","cp":[110.112629,32.809026],"childNum":1},"geometry":{"type":"Polygon","coordinates":["@@KIMKUMQGOGMESAA@U@UFOLGJ@@QVGLA@QFMGS@KHKHQH[HYBG@YA_KQGOEWA@@UAS@]DYHSFWDSBWLA@CBMHGFABCDABCDCDAB@BCFABAB@@@B@BA@@@AB@B@B@@@B@@ABA@ABAB@BAB@BCBABABAD@D@B@@A@ABC@ABA@@@A@C@A@ABCBC@@BA@C@CBA@@@A@A@A@@@@B@BABA@@BA@EBC@G@EBA@@@AB@DAB@@ABABABADAB@@@B@@@B@@@B@@ABA@C@C@A@C@@B@@@@@@@B@@AB@@@B@BBDDFBB@@@BABAB@BBBA@@BABABCD@B@B@B@BAB@@ADAB@@@D@BAB@@@B@BBDAB@@@B@B@@@@BD@@@@@BAF@DA@@@@BA@AB@B@@@BBF@D@@AF@B@B@H@B@F@BBD@B@@@BCHABABABED@B@B@BBD@B@B@@AB@@AB@@@@BB@@B@HAB@BA@@D@@@D@BBD@BBBBBBBB@BDD@@DBD@BBB@@@B@@B@DBB@BBDAB@@A@A@@@A@C@A@A@CB@BC@@@@BDDBDBB@@AB@@E@ABA@A@ABAB@@@B@@@@BB@@@B@D@@@D@@@D@@@B@@BB@@H@F@@AD@@@@@@D@B@B@@A@@B@BA@@@ABABC@C@@B@@@BBBBBBB@BDB@@@B@@@B@@AB@@BB@BBF@@@@B@B@D@@BBBBB@@D@F@B@B@@@@ABC@@B@BBH@B@B@BB@@BB@D@@@B@@@@C@IACBA@@@@@@DFF@@BB@B@@@B@B@@@B@B@@@@AB@@CBABCBA@AAA@C@@A@@A@@@@@@B@@@BDB@B@B@B@@@@A@@@ABABAA@@A@ACCA@AA@@@A@A@@@ABAB@BAB@B@@@BD@@D@@@DBB@B@@B@D@@ABBB@@@B@D@B@@@F@B@BADA@@BAB@@@B@B@B@H@B@@@B@BADABAB@BA@@DBB@@@BBDBBBD@BBDBBBF@B@BBBBBBBB@@BB@@BB@@DBB@F@@@DAB@@@DAB@D@@@@@BB@@B@@BB@BBBB@@@@B@B@BB@BD@FA@BB@B@B@B@@AB@B@B@B@BBLA@@D@BABAB@@@FCD@B@B@DBBB@AB@@@BA@@DAB@B@D@@@FA@@@@@@BAAAB@@@B@@@BA@@BADAB@BABA@@B@B@B@@@BB@@D@@@@@@DBB@BDDDBB@B@BA@@B@B@BAB@B@@@B@B@@AB@B@B@@@BBD@B@@@BB@B@D@B@B@BB@B@@@@@@@BB@@@@ABAB@@@@@@@@BB@@A@@@DDBB@@@B@@ABA@C@AB@@ABAB@@ABA@AB@@@F@@@B@@ABA@AB@@ABD@FDDBHHFDFDFBJDH@FBFBH@H@F@@@@BDBBFJTBFDDD@FBFAF@BABAFCLIFCF@D@HBFBJ@P@DAHAB@BAFCFEBCBABCB@DGDADAD@DBD@HAH@DBD@D@JBJAB@PCH@@@F@JBHBH@D@DCBABAFIB@DCHCLCJAF@D@HDF@H@BCBCBEBABCBCFCDAHELEJCD@D@FAB@JAB@NCPEPIHA@AJCHCHEB@HGDEBABCDMBCDABAFAFAJBHBB@D@AEDEEIIMEEEKAE@CFKJGHEN@@@HFFBH@FCBIBAFU@O@M@ICQ@KEM@AGUAODMHEHELKFGLGFQLQJEVMFEACAGGEOGOEQSEKCGKGSAC@MJOPKLQJUDW@G@MAAAIGAOHIBOAMEEACSG"],"encodeOffsets":[[112717,33359]]}}],"UTF8Encoding":true});})); | 2,503 | 2,503 | 0.638833 |
b1e4af3e18e585b4310af358398b96a2faea6c33 | 415 | js | JavaScript | program/WebProject/testApp.js | kolykk/project | bccf50a7b8a88bf3adb466d8d1b483376112fadd | [
"MIT"
] | null | null | null | program/WebProject/testApp.js | kolykk/project | bccf50a7b8a88bf3adb466d8d1b483376112fadd | [
"MIT"
] | null | null | null | program/WebProject/testApp.js | kolykk/project | bccf50a7b8a88bf3adb466d8d1b483376112fadd | [
"MIT"
] | null | null | null | var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/register', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
| 27.666667 | 61 | 0.674699 |
b1e4dda6bb616cb27b5603bfc974012f4804da85 | 436 | js | JavaScript | src/api/communication/server/index.js | Prathameshn/t-customer | 1540b28a2f58b56c6cb3c7fe47bfca2bf224910a | [
"MIT"
] | null | null | null | src/api/communication/server/index.js | Prathameshn/t-customer | 1540b28a2f58b56c6cb3c7fe47bfca2bf224910a | [
"MIT"
] | null | null | null | src/api/communication/server/index.js | Prathameshn/t-customer | 1540b28a2f58b56c6cb3c7fe47bfca2bf224910a | [
"MIT"
] | null | null | null | const grpc = require("@grpc/grpc-js");
const { grpcConfig } = require('@config/vars')
const routes = require('./routes')
const server = new grpc.Server();
for (route of routes) {
server.addService(route.definition, route.methods);
}
server.bindAsync(`${grpcConfig.ip}:${grpcConfig.port}`, grpc.ServerCredentials.createInsecure(), port => {
console.log(`GRPC running on ${grpcConfig.ip}:${grpcConfig.port}`)
server.start();
}); | 36.333333 | 106 | 0.699541 |
b1e572d47ae1843b48d0c7e002f034d2b3c08cf1 | 16,044 | js | JavaScript | resources/js/app.js | yeinerjavier456/laravel | f341aca8b8ffdf66583781bd6eaab760310530e4 | [
"MIT"
] | null | null | null | resources/js/app.js | yeinerjavier456/laravel | f341aca8b8ffdf66583781bd6eaab760310530e4 | [
"MIT"
] | null | null | null | resources/js/app.js | yeinerjavier456/laravel | f341aca8b8ffdf66583781bd6eaab760310530e4 | [
"MIT"
] | null | null | null | require('./bootstrap');
document.getElementById("icon-menu").addEventListener("click", mostrar_menu);
//Buscador de contenido
if(data.length === 0){
$("#singin").removeClass("hidden");
$("#mectrl_body_signOut").addClass("hidden");
$("#userName").empty();
}else{
$("#userName").empty();
$("#userName").append(data.user);
$("#singin").addClass("hidden");
}
// $("#logaut").on("click",function(){
// $.ajax({
// method: "GET",
// url: "http://...../"
// }).done(function(data) {
// alert(data); // imprimimos la respuesta
// }).fail(function() {
// alert("Algo salió mal");
// }).always(function() {
// alert("Siempre se ejecuta")
// });
// })
//Ejecutando funciones
document.getElementById("icon-search").addEventListener("click", mostrar_buscador);
document.getElementById("cover-ctn-search").addEventListener("click", ocultar_buscador);
//Declarando variables
bars_search = document.getElementById("ctn-bars-search");
cover_ctn_search = document.getElementById("cover-ctn-search");
inputSearch = document.getElementById("inputSearch");
box_search = document.getElementById("box-search");
// reemplazar por resultado de la base de datos
const documentos=[
// {
// nombre:"Misión ",
// url:"https://www.ibero.edu.co/documentos/#1600969179236-4c988300-6bd3",
// imagen:"img/document.jpg",
// category:"Institucionales",
// descripcion:"",
// },
// {
// nombre:"Visión " ,
// url:"https://www.ibero.edu.co/documentos/#1600969179267-7424b7c7-bb64",
// imagen:"img/document.jpg",
// category:"Institucionales",
// descripcion:"",
// },
// {
// nombre:"Filosofía Institucional",
// url:"https://www.ibero.edu.co/documentos/#1600969242228-48ec0493-db58",
// imagen:"img/document.jpg",
// category:"Institucionales",
// descripcion:"",
// },
// {
// nombre:"Valores Institucionales",
// url:"https://www.ibero.edu.co/documentos/#1600969276799-de37b446-5382",
// imagen:"img/document.jpg",
// category:"Institucionales",
// descripcion:"",
// },
// {
// nombre:"Principios Institucionales",
// url:"https://www.ibero.edu.co/documentos/#1600969301837-48047705-3ee0",
// imagen:"img/document.jpg",
// category:"Institucionales",
// descripcion:"",
// },
{
nombre:"Reglamento estudiantil",
url:"https://app.box.com/s/xkvms20acdbbgwbw4j23qfzp58x7l5p9",
imagen:"img/document.jpg",
category:"Institucionales",
descripcion:"",
},
{
nombre:"Modelo Pedagógico",
url:"https://www.ibero.edu.co/wp-content/uploads/2020/08/Modelo-Pedag%C3%B3gico_compressed.pdf",
imagen:"img/document.jpg",
category:"Institucionales",
descripcion:"",
},
{
nombre:"Estructura Cursos 2018",
url:"https://aulavirtual.ibero.edu.co/recursosel/Manuales/Manual_estudiante.pdf",
imagen:"img/document.jpg",
category:"Manuales",
descripcion:"",
},
{
nombre:"Estructura Cursos formato 2021",
url:"https://view.genial.ly/6165f559ed4c430d8826ba22",
imagen:"img/document.jpg",
category:"Manuales",
descripcion:"",
},
{
nombre:"Restablecimiento contraseña",
url:"tutorial_password_mrooms.pdf",
imagen:"img/document.jpg",
category:"Manuales",
descripcion:"",
},
{
nombre:"Cómo acceder al aula virtual",
url:"https://player.vimeo.com/video/578554276",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"restablecer contraseña en aula virtual",
url:"https://player.vimeo.com/video/578554109",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Dónde encontrar los cursos en el Aula virtual",
url:"https://player.vimeo.com/video/578554418",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Acta compromiso",
url:"https://player.vimeo.com/video/546711739",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Cómo cargo una actividad?",
url:"https://player.vimeo.com/video/578601821",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Cómo reviso fechas de entrega?",
url:"https://player.vimeo.com/video/578601053",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Qué es un foro de acompañamiento?",
url:"https://player.vimeo.com/video/578601184",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Cómo usar el servicio de mensajeria?",
url:"https://player.vimeo.com/video/578601248",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Cómo accedo a clases a través de teams? ",
url:"https://player.vimeo.com/video/578601348",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Cómo reviso mis calificaciones y retroalimentaciones?",
url:"https://player.vimeo.com/video/578601407",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Qué es el postest y en dónde lo encuentro?",
url:"https://player.vimeo.com/video/578601535",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Qué son los test finales de la unidad",
url:"https://player.vimeo.com/video/578601496",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Qué es la encuesta AVA?",
url:"https://player.vimeo.com/video/578601589",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Acceso a la plataforma MoodleRooms",
url:"https://player.vimeo.com/video/578613094",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Restablecer Contraseña en MoodleRooms",
url:"https://player.vimeo.com/video/578613267",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"¿Dónde encontrar los cursos MoodleRooms?",
url:"https://player.vimeo.com/video/578613424",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Ingreso al ambiente",
url:"https://player.vimeo.com/video/546676722",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Datos acceso",
url:"https://player.vimeo.com/video/546687654",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Generalidades",
url:"https://player.vimeo.com/video/546694773",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Ingresar curso",
url:"https://player.vimeo.com/video/546704624",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Recurso interactivo",
url:"https://player.vimeo.com/video/546708550",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Aspectos generales",
url:"https://player.vimeo.com/video/546709255",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Qué es pretest",
url:"https://player.vimeo.com/video/546717208",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Foros",
url:"https://player.vimeo.com/video/546717469",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Estructura cursos",
url:"https://player.vimeo.com/video/546735408",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Actividad funcionamiento",
url:"https://player.vimeo.com/video/546791038",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Panel de control",
url:"https://player.vimeo.com/video/546791786",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Microsoft Teams",
url:"https://player.vimeo.com/video/546792154",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
{
nombre:"Despedida",
url:"https://player.vimeo.com/video/546791935",
imagen:"img/Mesa de trabajo 1.png",
category:"Capsulas",
descripcion:"",
},
]
const search=document.querySelector("#inputSearch");
const resultado=document.querySelector("#resultado");
var contador=0;
const filtrar= ()=>{
resultado.innerHTML='';
const texto= search.value.toLowerCase();
for(var document of documentos ){
var nombre=document.nombre.toLowerCase();
if(nombre.indexOf(texto) !==-1){
resultado.innerHTML+=`
<div class="card product-item col-md-3 col-sm-6" category="${document.category}" style="text-align: center;max-height: 100%; padding-left: 0;padding-right: 0;">
<img class="card-img-top" src="${document.imagen}" alt="Card image cap" >
<div class="card-body">
<h5 class="card-title">${document.nombre}</h5>
<p class="card-text">${document.descripcion}</p>
<div class=" rateYo"id="rateYo"></div>
</div>
<div class="card-footer bg-transparent"> <button type="button" class="btn btn-lg btn-block ejemplo2" data-toggle="modal" data-target="#exampleModal" data-url="${document.url}">Abrir</button></div>
</div>
`
contador++
}
}
if(resultado.innerHTML===''){
resultado.innerHTML+=` <h2>Documento no encontrado</h2>`
}
}
search.addEventListener('keyup',filtrar);
filtrar();
// AGREGANDO CLASE ACTIVE AL PRIMER ENLACE ====================
$('.category_list .category_item[category="all"]').addClass('ct_item-active');
// FILTRANDO PRODUCTOS ============================================
$('.category_item').click(function(){
var catProduct = $(this).attr('category');
// AGREGANDO CLASE ACTIVE AL ENLACE SELECCIONADO
$('.category_item').removeClass('ct_item-active');
$(this).addClass('ct_item-active');
// OCULTANDO PRODUCTOS =========================
$('.product-item').css('transform', 'scale(0)');
function hideProduct(){
$('.product-item').hide();
} setTimeout(hideProduct,400);
// MOSTRANDO PRODUCTOS =========================
function showProduct(){
$('.product-item[category="'+catProduct+'"]').show();
$('.product-item[category="'+catProduct+'"]').css('transform', 'scale(1)');
} setTimeout(showProduct,400);
});
// MOSTRANDO TODOS LOS PRODUCTOS =======================
$('.category_item[category="all"]').click(function(){
function showAll(){
$('.product-item').show();
$('.product-item').css('transform', 'scale(1)');
} setTimeout(showAll,400);
});
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-body #iframe').attr("src",url)
})
$(".clasificacion").find("input").change(function(){
var valor = $(this).val()
$(".clasificacion").find("input").removeClass("activo")
$(".clasificacion").find("input").each(function(index){
if(index+1<=valor){
$(this).addClass("activo")
}
})
})
$(".clasificacion").find("label").mouseover(function(){
var valor = $(this).prev("input").val()
$(".clasificacion").find("input").removeClass("activo")
$(".clasificacion").find("input").each(function(index){
if(index+1<=valor){
$(this).addClass("activo")
}
})
})
$(document).find(".rateYo").rateYo({
numStars: 5,
starWidth: "30px"
});
//Funcion para mostrar el buscador
function mostrar_buscador(){
bars_search.style.top = "80px";
cover_ctn_search.style.display = "block";
inputSearch.focus();
if (inputSearch.value === ""){
box_search.style.display = "none";
}
}
//Funcion para ocultar el buscador
function ocultar_buscador(){
bars_search.style.top = "-10px";
cover_ctn_search.style.display = "none";
inputSearch.value = "";
box_search.style.display = "none";
}
function mostrar_menu(){
document.getElementById("move-content").classList.toggle('move-container-all');
document.getElementById("show-menu").classList.toggle('show-lateral');
}
| 31.70751 | 218 | 0.509162 |
b1e583f8306d5c54d7a65f8854b422f113000c4f | 1,886 | js | JavaScript | src/index.js | LucasMagnum/tensorflow-js-teachable-image-classifier | a6f83bf4470f37b31511e4f257fc6e7b775b82ce | [
"MIT"
] | null | null | null | src/index.js | LucasMagnum/tensorflow-js-teachable-image-classifier | a6f83bf4470f37b31511e4f257fc6e7b775b82ce | [
"MIT"
] | null | null | null | src/index.js | LucasMagnum/tensorflow-js-teachable-image-classifier | a6f83bf4470f37b31511e4f257fc6e7b775b82ce | [
"MIT"
] | null | null | null | const webcamElement = document.getElementById('webcam');
const classifier = knnClassifier.create();
let net;
async function app() {
console.log('Loading mobilenet..');
// Load the model
net = await mobilenet.load();
console.log('Successfully loaded model');
const webcam = await tf.data.webcam(webcamElement);
// Reads an image from the webcam and associates it with a specific
// class index
const addExample = async classId => {
// Capture an image from the web camera
const img = await webcam.capture();
// Get the intermediate activation of MobileNet `conv_preds`
// and pass that to the KNN classifier
const activation = net.infer(img, true);
// Pass the intermediate activation to the classifier.
classifier.addExample(activation, classId);
// Dispose the tensor to release the memory
img.dispose();
}
// When clicking a button, add an example for that class.
document.getElementById('class-a').addEventListener('click', () => addExample(0));
document.getElementById('class-b').addEventListener('click', () => addExample(1));
document.getElementById('class-c').addEventListener('click', () => addExample(2));
while (true) {
if (classifier.getNumClasses() > 0) {
const img = await webcam.capture();
// Get the activation from mobilenet from the webcam.
const activation = net.infer(img, 'conv_preds');
// Get the most likely class and confidence from the classifier module.
const result = await classifier.predictClass(activation);
const classes = ['Maçã', 'Laranja', 'Kiwi'];
document.getElementById('console').innerText = `
prediction: ${classes[result.label]}\n
probability: ${result.confidences[result.label]}
`;
// Dispose the tensor to release the memory.
img.dispose();
}
await tf.nextFrame();
}
}
app(); | 30.918033 | 84 | 0.677094 |
b1e5b7b2227c6de197b7ef8a2817cb7c95ff0c00 | 441 | js | JavaScript | dirname.js | watilde/universal-dirname | 01fb40738121d14d232a6a8ea460c060c648b8f6 | [
"MIT"
] | null | null | null | dirname.js | watilde/universal-dirname | 01fb40738121d14d232a6a8ea460c060c648b8f6 | [
"MIT"
] | null | null | null | dirname.js | watilde/universal-dirname | 01fb40738121d14d232a6a8ea460c060c648b8f6 | [
"MIT"
] | null | null | null | var path = require('path')
var dirname = (function () {
if (__dirname) return __dirname
if (document.currentScript && document.currentScript.src) {
return path.dirname(String(document.currentScript.src)) + '/'
}
var scripts = document.getElementsByTagName('script')
var script = scripts[scripts.length - 2]
if (script.src) {
return path.dirname(String(script.src)) + '/'
}
return '/'
}())
module.exports = dirname
| 24.5 | 65 | 0.678005 |
b1e6cac38a663bac378888c257f5298a0a514f0b | 2,807 | js | JavaScript | tests/specs/data-each.js | zipang/Temples | dcee38a75c59dae209e0f0f36f5b2a00107eafaf | [
"Unlicense",
"MIT"
] | 1 | 2021-12-01T08:59:46.000Z | 2021-12-01T08:59:46.000Z | tests/specs/data-each.js | zipang/Temples | dcee38a75c59dae209e0f0f36f5b2a00107eafaf | [
"Unlicense",
"MIT"
] | null | null | null | tests/specs/data-each.js | zipang/Temples | dcee38a75c59dae209e0f0f36f5b2a00107eafaf | [
"Unlicense",
"MIT"
] | null | null | null | /**
* Test suite for Temples
* toBe, toNotBe, toEqual, toNotEqual, toMatch, toNotMatch, toBeDefined, toBeUndefined,
* toBeNull, toBeTruthy, toBeFalsy, toHaveBeenCalled, wasCalled, wasNotCalled,
* toHaveBeenCalledWith, wasCalledWith, wasNotCalledWith, toContain, toNotContain,
* toBeLessThan, toBeGreaterThan, toBeCloseTo, toThrow
*/
(function() {
describe('Temples', function() {
afterEach(Temples.destroy);
describe('data-each', function() {
it('a block iterator must contain a child template', function() {
var emptyIterator = "<ul id='articles' data-each='articles'/>",
prepare = function() {
Temples.prepare("articles", emptyIterator)
};
expect(prepare).toThrow();
});
it('data-each=tags iterates over collection items to render blocks', function() {
var template = $("<ul data-each='tags'><li data-bind='tag'/></ul>");
Temples.prepare("tags", template),
Temples.tags.render({tags: ["#1", "#2", "#3"]});
expect(template.children().length).toEqual(3);
expect(template.text()).toEqual("#1#2#3");
});
it('data-iterate=tags iterates over collection items to render blocks', function() {
var template = $("<ul data-iterate='tags'><li data-bind='tag'/></ul>");
Temples.prepare("tags", template),
Temples.tags.render({tags: ["#1", "#2", "#3"]});
expect(template.children().length).toEqual(3);
expect(template.text()).toEqual("#1#2#3");
});
it('data-each=<var> : <collection> iterates over collection items to render blocks', function() {
var template = $("<ul data-iterate='t: tags'><li data-bind='t'/></ul>");
Temples.prepare("tags", template),
Temples.tags.render({tags: ["#1", "#2", "#3"]});
expect(template.children().length).toEqual(3);
expect(template.text()).toEqual("#1#2#3");
});
it('data-each=<var> from <collection> iterates over collection items to render blocks', function() {
var template = $("<ul data-iterate='t from tags'><li data-bind='t'/></ul>");
Temples.prepare("tags", template),
Temples.tags.render({tags: ["#1", "#2", "#3"]});
expect(template.children().length).toEqual(3);
expect(template.text()).toEqual("#1#2#3");
});
it("data-each doesn't render any data if data-render-if is false", function() {
var template = $("<div><ul data-iterate='t from tags' data-render-if='condition'><li data-bind='t'/></ul></div>");
Temples.prepare("tags", template),
Temples.tags.render({tags: ["#1", "#2", "#3"], condition: false});
expect(template.children().length).toEqual(0);
expect(template.text()).toEqual("");
});
});
});
}());
| 40.681159 | 122 | 0.594229 |
b1e730a78e2dc6c64ccd2c2df71411221ed1d4c2 | 3,672 | js | JavaScript | src/components/sections/SignUpForm.js | Goyemon/goyemon.io | 705b3f464c851cd1a260557396f80b81ec746f96 | [
"MIT"
] | null | null | null | src/components/sections/SignUpForm.js | Goyemon/goyemon.io | 705b3f464c851cd1a260557396f80b81ec746f96 | [
"MIT"
] | 8 | 2020-09-19T09:07:45.000Z | 2020-10-01T13:56:17.000Z | src/components/sections/SignUpForm.js | Goyemon/goyemon.io | 705b3f464c851cd1a260557396f80b81ec746f96 | [
"MIT"
] | 1 | 2020-09-21T11:13:20.000Z | 2020-09-21T11:13:20.000Z | import React from 'react';
import addToMailchimp from 'gatsby-plugin-mailchimp';
import { Section, Container } from '@components/global';
import styled from 'styled-components';
export default class SignUpForm extends React.Component {
constructor() {
super();
this.state = { name: null, email: null, device: 'ios', result: '' };
}
_handleSubmit = async (e) => {
e.preventDefault();
const result = await addToMailchimp(this.state.email, {
device: this.state.device,
name: this.state.name
});
this.setState({ result });
};
handleName = (event) => {
this.setState({ name: event.target.value });
};
handleEmail = (event) => {
this.setState({ email: event.target.value });
};
handleDevice = (event) => {
this.setState({ device: event.target.value });
};
renderForm = () => {
if (this.state.result.result === 'success') {
return <p>Thank you for signing up!😄</p>;
} else if (this.state.result.result === 'error') {
return (
<form onSubmit={this._handleSubmit}>
<label>
name
<input type="text" onChange={this.handleName} />
</label>
<label>
email
<input type="email" onChange={this.handleEmail} />
</label>
<label>
device
<select value={this.state.device} onChange={this.handleDevice}>
<option value="ios">iOS</option>
<option value="android">Android</option>
</select>
</label>
<input type="submit" value="Sign Up for Beta" />
<p>Something went wrong 🤷</p>
</form>
);
}
return (
<form onSubmit={this._handleSubmit}>
<label>name</label>
<input type="text" onChange={this.handleName} />
<label>email</label>
<input type="email" onChange={this.handleEmail} />
<label>device</label>
<select value={this.state.device} onChange={this.handleDevice}>
<option value="ios">iOS</option>
<option value="android">Android</option>
</select>
<input type="submit" value="Sign Up for Beta" />
</form>
);
};
render() {
return (
<Section id="sign-up" accent="secondary">
<Container style={{ position: 'relative' }}>
<h1 style={{ marginBottom: 40 }}>Sign Up</h1>
<Wrapper>{this.renderForm()}</Wrapper>
</Container>
</Section>
);
}
}
const Wrapper = styled.div`
form {
background-color: #fff;
${(props) => props.theme.font_size.regular};
padding: 8% 16%;
margin: 0 auto;
}
label {
display: block;
${(props) => props.theme.font_size.small};
text-transform: uppercase;
}
input:focus {
outline: none;
}
select:focus {
outline: none;
}
input[type='text'] {
border: none;
border-bottom: #eeeeee 2px solid;
display: block;
margin-top:8px;
margin-bottom: 40px;
width: 100%;
}
input[type='email'] {
border: none;
border-bottom: #eeeeee 2px solid;
display: block;
margin-top:8px;
margin-bottom: 40px;
width: 100%;
}
select {
border: none;
display: block;
margin-top:8px;
margin-bottom: 40px;
width: 100%;
}
input[type='submit'] {
background-color: #00a3e2;
border: none;
border-radius: 8px;
color: #fff;
${(props) => props.theme.font_size.small};
margin: 0 auto;
margin-top: 24px;
padding: 12px 16px;
width: 100%;
}
p {
color: #e41b13;
${(props) => props.theme.font_size.small};
margin-top: 12px;
text-align: center;
}
`;
| 23.538462 | 75 | 0.563181 |
b1e73bd69cdc55c3fa357173bfce83d248ca7fdf | 1,865 | js | JavaScript | canvas-master/canvas20/js/script.js | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | canvas-master/canvas20/js/script.js | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | canvas-master/canvas20/js/script.js | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | ///////////////////////////////
var config = {
'selector': '#glitch',
'fontSize': 380,
'color': '#fff',
'glitchCount': 5
}
//////////////////////////////
var elements;
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var getRandom = function(min, max) {
return Math.random() * (max - min) + min;
}
var glitch = function(el, count) {
var c = el.getContext('2d');
for (var i = 0; i < count; i++) {
var x = getRandom(0, el.width);
var y = getRandom(0, el.height);
var w = getRandom(0, el.width);
var h = getRandom(0, el.height);
var offsetX = getRandom(config.fontSize / 10 * -1, config.fontSize / 10);
var offsetY = getRandom(config.fontSize / 10 * -1, config.fontSize / 10)
var data = c.getImageData(x, y, w, h);
c.putImageData(data, x + offsetX, y + offsetY);
}
}
var setup = function(el) {
var c = el.getContext('2d');
var letter = el.getAttribute('data-letter');
console.log(letter);
el.height = config.fontSize * 1.3;
el.width = config.fontSize * .6;
c.clearRect(0, 0, el.height, el.width)
c.font = "bold " + config.fontSize + "px 'space mono'";
c.fillStyle = config.color;
c.fillText(letter, 5, el.height - el.height / 4);
}
var init = function() {
$(config.selector).append("<div class='canvas-container' id='canvas-container'></div>")
var text = $(config.selector).text();
for (var i = 0; i < text.length; i++) {
$('#canvas-container').append('<canvas id="c-' + i + '" data-letter="' + text[i] + '"></canvas>')
}
elements = document.getElementsByTagName('canvas');
for (var j = 0; j < elements.length; j++) {
setup(elements[j])
}
}
var loop = function() {
var i = getRandomInt(0, elements.length)
setup(elements[i]);
glitch(elements[i], getRandomInt(config.glitchCount, config.glitchCount * 2))
setTimeout(loop, getRandomInt(10, 500))
}
init();
loop(); | 27.028986 | 99 | 0.612332 |
b1e935b34589cb3a9f7871e8358077180019ef2b | 1,010 | js | JavaScript | demo/BleApp/__tests__/App-test.js | larsthorup/react-native-ble-plx-mock-recorder | 166855d0dd7cac0b1ee75824a873125b49eaf652 | [
"MIT"
] | 7 | 2021-07-04T09:15:22.000Z | 2022-02-01T03:51:13.000Z | demo/App-test.js | larsthorup/react-native-ble-plx-sandbox | 92de0fb99de42c33030ec4f1401fd5d4bc402ccb | [
"MIT"
] | 1 | 2022-01-07T08:58:45.000Z | 2022-01-07T09:35:03.000Z | demo/App-test.js | larsthorup/react-native-ble-plx-sandbox | 92de0fb99de42c33030ec4f1401fd5d4bc402ccb | [
"MIT"
] | 1 | 2022-02-16T23:30:24.000Z | 2022-02-16T23:30:24.000Z | import * as fs from 'fs';
import 'react-native';
import React from 'react';
import { render } from '@testing-library/react-native';
import App from '../App';
import { getBleManager } from '../ble.js';
import { act } from 'react-test-renderer';
const expectedLocalName = 'BeoPlay A1'; // TODO: change to name of your own device
describe('App', () => {
it('should show device names', async () => {
const recording = JSON.parse(fs.readFileSync('../BleAppRecorder/artifact/default.recording.json'));
const { blePlayer } = getBleManager();
blePlayer.mockWith(recording);
// when: render the app
const { queryByText } = render(<App />);
// then: device is NOT shown
expect(queryByText(`- ${expectedLocalName}`)).toBeFalsy();
// when: simulating BLE scan responses
act(() => {
blePlayer.playUntil('scanned'); // Note: causes re-render, so act() is needed
});
// then: device IS shown
expect(queryByText(`- ${expectedLocalName}`)).toBeTruthy();
});
}); | 30.606061 | 103 | 0.648515 |
b1e9cfe042960bda5bb0ff5b4b14a37a3f50f7c3 | 2,406 | js | JavaScript | src/scenes/simpleBox.js | ErykMiszczuk/threejs-sandbox | 2b9d166aea71d57b343e51754f1da5d98f36f813 | [
"BSD-3-Clause"
] | null | null | null | src/scenes/simpleBox.js | ErykMiszczuk/threejs-sandbox | 2b9d166aea71d57b343e51754f1da5d98f36f813 | [
"BSD-3-Clause"
] | 1 | 2022-01-27T16:12:20.000Z | 2022-01-27T16:12:20.000Z | src/scenes/simpleBox.js | ErykMiszczuk/threejs-sandbox | 2b9d166aea71d57b343e51754f1da5d98f36f813 | [
"BSD-3-Clause"
] | null | null | null | import * as THREE from 'three';
const tardisBlue = new THREE.Color("rgb(0, 49, 111)");
const sunYellow = new THREE.Color("rgb(200, 150, 0)");
const snowWhite = new THREE.Color("rgb(255, 255, 255)");
const scene = new THREE.Scene();
scene.background = tardisBlue;
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let INTERSECTED;
const camera = new THREE.PerspectiveCamera(
25,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const cubeGeometry = new THREE.BoxGeometry(2, 3, 4);
const cubeMaterial = new THREE.MeshPhongMaterial({
color: sunYellow,
shininess: 50,
});
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
scene.add(cube);
const pointLight = new THREE.PointLight(snowWhite, 1.5);
pointLight.position.set(-20, -10, 20);
scene.add(pointLight);
const pointLight2 = new THREE.PointLight(snowWhite, 1.5);
pointLight2.position.set(20, 10, 20);
scene.add(pointLight2);
camera.position.z = 25;
window.addEventListener( 'mousemove', event => {
event.preventDefault();
updateMouse(event);
});
function updateMouse(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
}
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.z += 0.05;
findMousePointedObjects();
renderer.render(scene, camera);
}
function findMousePointedObjects() {
camera.lookAt( scene.position );
camera.updateMatrixWorld();
// find intersections
raycaster.setFromCamera( mouse, camera );
let intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 ) {
if ( INTERSECTED != intersects[ 0 ].object ) {
console.log(intersects)
if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.color = snowWhite;
}
} else {
if (INTERSECTED !== null) INTERSECTED.material.color = sunYellow;
INTERSECTED = null;
}
}
animate(); | 25.870968 | 94 | 0.675395 |
b1e9e33b2497d54089ce0f95703454c0478b263e | 1,348 | js | JavaScript | src/components/UI/image.js | chaingraph/chaingraph.io | 7cb8da3f982e14cc2d45d3b4c3def4fbbe2d3d42 | [
"MIT"
] | 3 | 2022-01-14T21:48:56.000Z | 2022-01-18T01:04:33.000Z | src/components/UI/image.js | chaingraph/chaingraph.io | 7cb8da3f982e14cc2d45d3b4c3def4fbbe2d3d42 | [
"MIT"
] | null | null | null | src/components/UI/image.js | chaingraph/chaingraph.io | 7cb8da3f982e14cc2d45d3b4c3def4fbbe2d3d42 | [
"MIT"
] | null | null | null | import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import Img from 'gatsby-image'
import styled from 'utils/styles'
const ImgContainer = styled.div`
width: auto;
height: auto;
max-height: 100%;
max-width: 100%;
z-index: 2;
> img.Regular,
> object.Regular {
width: 100%;
height: 100%;
}
`
export function Image({ img }) {
const { allFile } = useStaticQuery(graphql`
query {
allFile(filter: { name: { ne: null } }) {
edges {
node {
publicURL
name
}
}
}
}
`)
const imgLocalFind = allFile.edges.find(({ node: { name } }) =>
img.match(name),
)
const isSvg =
!imgLocalFind.node.fluid && imgLocalFind.node.publicURL.match(/.svg/g) ? (
<object
id={imgLocalFind.node.name}
aria-label={`${imgLocalFind.node.name}_svg-object`}
type="image/svg+xml"
data={imgLocalFind.node.publicURL}
className="Regular"
/>
) : (
<img
src={imgLocalFind.node.publicURL}
alt={imgLocalFind.node.name}
className="Regular"
/>
)
return imgLocalFind ? (
<ImgContainer>
{imgLocalFind.node.fluid ? (
<Img fluid={imgLocalFind.node.fluid} />
) : (
isSvg
)}
</ImgContainer>
) : (
<></>
)
}
| 20.424242 | 78 | 0.548961 |
b1eae912c8653870222448a2829450be38cc8803 | 2,030 | js | JavaScript | src/reducers/filterReducer.js | Reptarsrage/looking-glass | 985d19f746c3c5f4f86a37f95fef17fee52714dc | [
"Unlicense"
] | 3 | 2019-06-19T14:18:03.000Z | 2021-04-16T10:23:20.000Z | src/reducers/filterReducer.js | Reptarsrage/looking-glass | 985d19f746c3c5f4f86a37f95fef17fee52714dc | [
"Unlicense"
] | 1,260 | 2019-04-19T05:26:11.000Z | 2022-03-31T06:12:22.000Z | src/reducers/filterReducer.js | Reptarsrage/looking-glass | 985d19f746c3c5f4f86a37f95fef17fee52714dc | [
"Unlicense"
] | null | null | null | import produce from 'immer'
import { FETCH_FILTERS_SUCCESS, FETCH_GALLERY_SUCCESS, FETCH_ITEM_FILTERS_SUCCESS } from 'actions/types'
import { generateFilterId, generateFilterSectionId } from './constants'
export const initialState = {
byId: {},
allIds: [],
}
export const initialFilterState = {
id: null,
siteId: null,
filterSectionId: null,
name: null,
}
const addFiltersForSection = (draft, filterSectionId, filter) => {
// generate moduleId
const filterId = generateFilterId(filterSectionId, filter.id)
// add filters
if (!(filterId in draft.byId)) {
draft.allIds.push(filterId)
draft.byId[filterId] = {
...initialFilterState,
...filter,
siteId: filter.id,
id: filterId,
filterSectionId,
}
}
}
export default produce((draft, action) => {
const { type, payload, meta } = action || {}
switch (type) {
case FETCH_FILTERS_SUCCESS: {
// add filters for modules
const filterSectionId = meta
payload.forEach((filter) => addFiltersForSection(draft, filterSectionId, filter))
// TODO: add file system filter options
break
}
case FETCH_ITEM_FILTERS_SUCCESS: {
const { moduleId } = meta
const filters = payload
// add filters for modules
filters.forEach(({ filterSectionId: filterSectionSiteId, ...filter }) => {
const filterSectionId = generateFilterSectionId(moduleId, filterSectionSiteId)
addFiltersForSection(draft, filterSectionId, filter)
})
break
}
case FETCH_GALLERY_SUCCESS: {
const { moduleId } = meta
const gallery = payload
const { items } = gallery
// add item filters
items.forEach((item) => {
item.filters.forEach(({ filterSectionId: filterSectionSiteId, ...filter }) => {
const filterSectionId = generateFilterSectionId(moduleId, filterSectionSiteId)
addFiltersForSection(draft, filterSectionId, filter)
})
})
break
}
// no default
}
}, initialState)
| 26.025641 | 104 | 0.657143 |
b1ebb02b7de68517e4c9713bef8f414dbd897ab8 | 2,940 | js | JavaScript | src/components/App.js | walkeknow/reactnd-project-would-you-rather | abffa9870ec78b484dc7e4469fd18d305be71e44 | [
"MIT"
] | null | null | null | src/components/App.js | walkeknow/reactnd-project-would-you-rather | abffa9870ec78b484dc7e4469fd18d305be71e44 | [
"MIT"
] | 5 | 2020-07-04T13:19:35.000Z | 2022-02-27T05:48:54.000Z | src/components/App.js | walkeknow/reactnd-project-would-you-rather | abffa9870ec78b484dc7e4469fd18d305be71e44 | [
"MIT"
] | null | null | null | import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import { handleInitialData } from '../actions/shared'
import Navbar from '../components/Navbar'
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from 'react-router-dom'
import Login from './Login'
import { setAuthedUser } from '../actions/authedUser'
import Polls from './Polls'
import ViewQuestionPage from './ViewQuestionPage'
import CreateQuestion from './CreateQuestion'
import Leaderboard from './Leaderboard'
import NoMatch from './NoMatch'
export class App extends Component {
state = {
authedUser: null,
pathnameFromLogin: '',
fromLogout: false,
}
componentDidMount() {
this.props.dispatch(handleInitialData())
}
handleSelect = (uid) => {
this.setState(() => ({
authedUser: uid,
}))
}
handleSubmit = (e, pathname) => {
e.preventDefault()
this.setState((currState) => {
// if form is submitted without selecting dropdown
if (currState.authedUser === null) {
this.props.dispatch(setAuthedUser('sarahedo'))
} else {
this.props.dispatch(setAuthedUser(currState.authedUser))
}
return {
authedUser: null,
pathnameFromLogin: pathname,
}
})
}
handleLogout = () => {
this.props.dispatch(setAuthedUser(null))
this.setState(() => ({
fromLogout: true,
}))
}
render() {
return (
<Router>
<div className='container'>
{this.props.autheticated === false ? (
<Fragment>
{this.state.fromLogout === true && <Redirect to='/' />}
<Route
path='/*'
render={({ location }) => {
return (
<Login
handleSelect={this.handleSelect}
handleSubmit={this.handleSubmit}
location={location}
/>
)
}}
></Route>
</Fragment>
) : (
<Fragment>
<Navbar handleLogout={this.handleLogout} />
<Redirect to={this.state.pathnameFromLogin} />
<Switch>
<Route exact path='/' component={Polls}></Route>
<Route
path='/questions/:question_id'
component={ViewQuestionPage}
></Route>
<Route path='/add' component={CreateQuestion}></Route>
<Route path='/leaderboard' component={Leaderboard}></Route>
<Route
render={({ location }) => <NoMatch location={location} />}
></Route>
</Switch>
</Fragment>
)}
</div>
</Router>
)
}
}
const mapStateToProps = ({ authedUser }) => ({
autheticated: authedUser !== null,
})
export default connect(mapStateToProps)(App)
| 28.543689 | 76 | 0.533673 |
b1ebc69914e4a2c00ffc9ad84b3f3b6697c66d0a | 4,696 | js | JavaScript | client/src/components/Nav.js | TaskLab-CS375/TaskLab | 1a43ed4389f3e6cf97b075ba663784e369b2f548 | [
"PostgreSQL"
] | null | null | null | client/src/components/Nav.js | TaskLab-CS375/TaskLab | 1a43ed4389f3e6cf97b075ba663784e369b2f548 | [
"PostgreSQL"
] | null | null | null | client/src/components/Nav.js | TaskLab-CS375/TaskLab | 1a43ed4389f3e6cf97b075ba663784e369b2f548 | [
"PostgreSQL"
] | null | null | null | import React, {Component} from 'react';
import {Link, Route, Switch} from "react-router-dom";
import withAuth from "../utilities/withAuth";
import Home from "./Home";
import Login from "./authentication/Login";
import Register from "./authentication/Register";
import { checkLogin } from "../utilities/auth";
import Dashboard from "./Dashboard";
import Project from "./projects/Project";
import Gantt from "./projects/Gantt";
export default class Nav extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
checkLogin().then(result => this.setState({ isAuthenticated: result }));
}
login = () => {
this.setState({ isAuthenticated: true });
}
async logout(e) {
e.preventDefault();
await fetch('/logout');
this.setState({ isAuthenticated: false });
}
render() {
const { isAuthenticated } = this.state;
return (
<div>
<nav className="navbar navbar-expand-md navbar-light bg-light">
<div className="mx-auto order-0">
<a className="navbar-brand mx-auto" href="#">
<img width="75%" height="75%" src="/logo.png" alt="" />
</a>
<button className="navbar-toggler" type="button" data-toggle="collapse"
data-target=".dual-collapse2">
<span className="navbar-toggler-icon"/>
</button>
</div>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link className="nav-link" to="/">Home</Link>
</li>
{
isAuthenticated &&
<li className="nav-item">
<Link className="nav-link" to="/dashboard">Dashboard</Link>
</li>
}
{isAuthenticated &&
<li className="nav-item">
<Link className="nav-link" to="/project">Projects</Link>
</li>
}
{isAuthenticated &&
<li className="nav-item">
<Link className="nav-link" to="/gantt">Gantt Chart</Link>
</li>
}
</ul>
</div>
<div className="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
{ isAuthenticated
? <p onClick={this.logout.bind(this)}>Logout</p>
: <Link className="nav-link" to="/login">Login</Link>
}
</li>
</ul>
</div>
</nav>
<Switch>
<Route path="/" exact component={Home} />
<Route
path="/dashboard"
component={withAuth(Dashboard)}
render={(props) => (
withAuth(<Dashboard {...props} />)
)}/>
<Route
path="/project"
component={withAuth(Project)}
render={(props) => (
withAuth(<Project {...props} />)
)}/>
<Route
path="/gantt*"
component={withAuth(Gantt)}
render={(props) => (
withAuth(<Gantt {...props} />)
)}/>
<Route
path="/login"
render={(props) => (
<Login login={this.login} {...props} />
)} />
<Route
path="/register"
render={(props) => (
<Register login={this.login} {...props} />
)} />
</Switch>
</div>
);
}
} | 40.834783 | 95 | 0.380111 |
b1ebf5275263e1c036b49e0ab1b5be84f436e176 | 3,943 | js | JavaScript | index.js | zaftzaft/node-vim-colorscheme | 875c71640a06b7ce78e582b6db074ac019dc7368 | [
"MIT"
] | null | null | null | index.js | zaftzaft/node-vim-colorscheme | 875c71640a06b7ce78e582b6db074ac019dc7368 | [
"MIT"
] | null | null | null | index.js | zaftzaft/node-vim-colorscheme | 875c71640a06b7ce78e582b6db074ac019dc7368 | [
"MIT"
] | null | null | null | var fs = require("fs");
var child_process = require("child_process");
var spawn = child_process.spawn;
var spawnSync = child_process.spawnSync;
var temp = require("temp").track();
var colors = {};
var reHi = /^([\w]+)\s+xxx\s+(.+)$/;
var reLink = /^links to ([\w]+)$/;
var buildArgs = function(filePath, options){
var args = ["-e"];
if(options.filetype){
args.push("+e x." + options.filetype);
}
args.push("+redi! > " + filePath, "+hi", "+q!");
return args;
};
var buildOption = function(options){
options = options || {};
options.useCache = options.useCache || false;
options.cachePath = options.cachePath || "./vimcs";
return options;
};
var rediHi = function(args, callback){
var vim = spawn("vim", args, {
stdio: [
process.stdin,
process.stdout,
process.stderr
]
});
vim.on("close", callback);
return vim;
};
var rediHiSync = function(args){
spawnSync("vim", args, {
stdio: [
process.stdin,
process.stdout,
process.stderr
]
});
};
var init = function(options, callback){
options = buildOption(options);
var readCache = function(){
fs.readFile(options.cachePath, "utf8", function(err, data){
parse(data);
callback();
});
};
if(options.useCache){
return fs.exists(options.cachePath, function(exists){
if(exists){
readCache();
}
else{
rediHi(buildArgs(options.cachePath, options), readCache);
}
});
}
temp.open("", function(err, info){
rediHi(buildArgs(info.path, options), function(){
fs.readFile(info.path, "utf8", function(err, data){
parse(data);
temp.cleanup();
callback();
});
});
});
};
var initSync = function(options){
options = buildOption(options);
var readCache = function(){
parse(fs.readFileSync(options.cachePath, "utf8"));
};
if(options.useCache){
if(fs.existsSync(options.cachePath)){
readCache();
}
else{
rediHiSync(buildArgs(options.cachePath, options));
readCache();
}
}
else{
var tempPath = temp.openSync("").path;
rediHiSync(buildArgs(tempPath, options));
parse(fs.readFileSync(tempPath, "utf8"));
temp.cleanupSync();
}
};
var parse = function(data){
var index = {};
var before = null;
data.split("\n").forEach(function(line){
var m;
if(m = line.match(reHi)){
index[before = m[1]] = m[2];
}
else{
before && (index[before] += line);
}
});
var f = function(value){
var m = value.match(reLink);
return m ? f(index[m[1]]) : value;
};
Object.keys(index).forEach(function(key){
colors[key] = {};
f(index[key]).split(" ").filter(function(a){return a;}).forEach(function(a){
var b = a.split("=");
colors[key][b[0]] = b[1] || true;
});
});
};
module.exports = function(colorName, option, attr){
var dummy = function(s){return s;};
var gen = function(c){
return function(s){
return c + s + "\x1b[0m"
};
};
var compose = function(f, g){
return function(s){
return f(g(s));
};
};
var c = colors[colorName];
if(!c){
return dummy;
}
var fg = /^\d+$/.test(c.ctermfg) ? gen("\x1b[38;5;" + c.ctermfg + "m") : dummy;
var bg = /^\d+$/.test(c.ctermbg) ? gen("\x1b[48;5;" + c.ctermbg + "m") : dummy;
if(attr){
[
[/bold/, "\x1b[1m"],
[/underline/, "\x1b[4m"],
[/reverse/, "\x1b[7m"],
[/inverse/, "\x1b[7m"],
[/standout/, "\x1b[1;4m"]
].forEach(function(x){
if(x[0].test(c.cterm)){
var g = gen(x[1]);
fg = compose(fg, g);
bg = compose(bg, g);
}
});
}
if(option === "fg"){
return fg;
}
else if(option === "bg"){
return bg;
}
else{
return compose(fg, bg);
}
};
module.exports.init = init;
module.exports.initSync = initSync;
module.exports.colors = colors;
| 20.752632 | 81 | 0.553639 |
b1ef8f55c65ed9b530e066dca1113dc34d0e3eb7 | 2,311 | js | JavaScript | hostname-is-private.js | FGRibreau/hostname-is-private | ea3decb820d0ef2c54dada6f65ad279c4603ebcd | [
"MIT"
] | 3 | 2015-04-04T16:56:42.000Z | 2020-09-18T01:56:42.000Z | hostname-is-private.js | FGRibreau/hostname-is-private | ea3decb820d0ef2c54dada6f65ad279c4603ebcd | [
"MIT"
] | 10 | 2015-04-05T09:55:35.000Z | 2020-04-27T04:38:23.000Z | hostname-is-private.js | FGRibreau/hostname-is-private | ea3decb820d0ef2c54dada6f65ad279c4603ebcd | [
"MIT"
] | 1 | 2020-07-21T20:54:09.000Z | 2020-07-21T20:54:09.000Z | 'use strict';
var ip = require('ip');
var dns = require('dns');
var publicIp = require('public-ip');
var _ = require('lodash');
var isIP = require('isipaddress');
/**
* Check whether or not an hostname refers to a private IP
* @param {String} hostname
* @param {Function} f(err: {error,null}, isPrivate: {boolean})
*/
var isPrivate = _.curry(function (checker, hostname, f) {
var ipPart = extractIpv4(hostname);
if (isIP.v4(ipPart)) {
// it's an IPV4 and it's private don't go further
return f(null, IPisPrivate(ipPart));
}
try {
dns.lookup(hostname, function (err, addr) {
if (err) {
return setImmediate(f, err);
}
return checker(addr, f);
});
} catch (err) {
setImmediate(f, err);
}
});
function extractIpv4(hostname) {
return String(hostname).split('\\')[0].split(':')[0];
}
function IPisPrivate(ipAddr) {
return ipAddr === '0.0.0.0' || ip.isPrivate(ipAddr);
}
/**
* @param {String} addr array of ip addr
* @param {Function} f(err, isPrivate) isPrivate will be `true` if at least one addr is private
*/
function checkIfAddressesArePrivate(addr, f) {
setImmediate(f, null, IPisPrivate(addr));
}
/**
* @param {String} addr array of ip addr
* @param {Function} f(err, isPrivate) isPrivate will be `true` if at least one addr is private or is the public server IP
*/
function checkIfAddressesArePrivateIncludingPublicIp(addr, f) {
checkIfAddressesArePrivate(addr, function (err, isPrivate) {
if (err) {
return setImmediate(f, err);
}
if (isPrivate === true) {
// no need to check further, the IP is private
return setImmediate(f, null, isPrivate);
}
// retrieve the Public IP
getPublicIP(function (err, publicIp) {
if (err) {
return setImmediate(f, err);
}
f(null, addr === publicIp);
});
});
}
function getPublicIP(f) {
if (getPublicIP.PUBLIC_IP) {
return f(null, getPublicIP.PUBLIC_IP);
}
publicIp(function (err, ip) {
if (err) {
return f(err);
}
getPublicIP.PUBLIC_IP = ip;
f(null, getPublicIP.PUBLIC_IP);
});
}
getPublicIP.PUBLIC_IP = null;
module.exports = {
isPrivate: isPrivate(checkIfAddressesArePrivate),
isPrivateIncludingPublicIp: isPrivate(checkIfAddressesArePrivateIncludingPublicIp)
};
| 23.343434 | 123 | 0.645175 |
b1f0b929bfcb77cc41eb7179dd7bdd2eaf43d507 | 3,367 | js | JavaScript | lego2/lib/xm-cdn-sdk/index.js | ZZsimon/ZZsimon.github.io | d88b8eb458a1ab14aead6a7fe9c1b4b692d752c7 | [
"MIT"
] | null | null | null | lego2/lib/xm-cdn-sdk/index.js | ZZsimon/ZZsimon.github.io | d88b8eb458a1ab14aead6a7fe9c1b4b692d752c7 | [
"MIT"
] | null | null | null | lego2/lib/xm-cdn-sdk/index.js | ZZsimon/ZZsimon.github.io | d88b8eb458a1ab14aead6a7fe9c1b4b692d752c7 | [
"MIT"
] | null | null | null | const fs = require('fs-extra')
const path = require('path')
const axios = require('axios')
const request = require('request')
const chalk = require('chalk')
class XmCdnSDK {
constructor(option) {
if (!option) {
this.logger.error('请传入正确的参数')
}
if (!option.env) {
this.logger.error('请传入环境变量env参数 example:{ env:"production" }')
}
const {
cdnDirName,
bundleDirName,
env,
} = option
this.env = env
this.cdnDirName = cdnDirName
this.bundleDirName = bundleDirName
}
init() {
this.logger.info('开始上传静态文件...')
// this.logger.info('传入的环境变量:' + this.env)
this.fileDisplay(this.bundleDirName)
}
logger = {
error: (log) => {
throw new Error(chalk.redBright(log))
},
info: (log) => {
console.log(chalk.magenta(log))
},
}
setTakaTokenUrl = () => {
if (this.env === 'qa') {
XmCdnSDK.takaTokenUrl = XmCdnSDK.takaTokenUrl.substring(0, 8) + 'qa' + XmCdnSDK.takaTokenUrl.substring(8)
}
}
fileDisplay = (bundleDirName) => {
// 根据文件路径读取文件,返回文件列表
fs.readdir(bundleDirName, (err, files) => this.readdirCallBack({ files, bundleDirName }))
}
readdirCallBack = async ({ files, bundleDirName }) => {
await Promise.all(files.map(filename => {
const suffix = this.getSuffix(filename)
const isSupportFile = XmCdnSDK.supportFiles.includes(suffix)
// 获取当前文件的绝对路径
const filedir = path.join(bundleDirName, filename)
// 根据文件路径获取文件信息,返回一个fs.Stats对象
fs.stat(filedir, (eror, stats) => this.statCallBack({ stats, isSupportFile, filedir }))
}))
}
statCallBack = ({ stats, isSupportFile, filedir }) => {
const isFile = stats.isFile()// 是文件
const isDir = stats.isDirectory()// 是文件夹
if (isFile && isSupportFile) {
const bizType = this.cdnDirName
// 需要上传的文件类型
this.getToken({
filedir,
bizType
})
}
// 递归,如果是文件夹,就继续遍历该文件夹下面的文件
if (isDir) {
this.fileDisplay(filedir)
}
}
getToken = async ({ filedir, bizType }) => {
await axios.post(XmCdnSDK.takaTokenUrl, {
bizType
})
.then(res => {
const response = res.data
const customFilePath = `/${bizType}${filedir.replace(this.bundleDirName, '').replace(/\\/g, '/')}`
this.uploadFile({
filedir,
action: `${response.data.uploadDomain}/v1/file`,
token: response.data.token,
customFilePath
})
})
.catch(error => {
console.error(error)
})
}
uploadFile = async ({ filedir, action, token, customFilePath }) => {
const data = {
customFilePath,
isFullWrite: 1,
};
const params = {
url: action,
formData: {
...data,
file: fs.createReadStream(filedir),
},
headers: {
token,
},
}
request.post(params, (err, resp, body) => {
if (err) {
console.warn('上传失败');
return;
}
const result = JSON.parse(body);
console.log(`${chalk.green('上传成功')} 地址是:${result.data[0].publishUrl}`);
});
}
getSuffix = (url) => {
return url.substring(url.lastIndexOf('.'), url.length)
}
}
XmCdnSDK.takaTokenUrl = 'https://api.xinmai100.com/xinmai-admin-order/taka-token'
XmCdnSDK.supportFiles = ['.js', '.png', '.jpg', '.css', '.xlsx']
module.exports = XmCdnSDK
| 25.126866 | 111 | 0.582715 |
b1f14bd9da43d24573c53bae2a4f148dfe461e73 | 4,019 | js | JavaScript | AppData/Modules/Shell/1.0.456/ClientResources/epi/shell/widget/layout/ComponentTabContainer.js | Romanets/RestImageResize | f9c79924994b6ff05db5caccf8343524629544b3 | [
"MIT"
] | 1 | 2017-07-07T01:21:41.000Z | 2017-07-07T01:21:41.000Z | AppData/Modules/Shell/1.0.456/ClientResources/epi/shell/widget/layout/ComponentTabContainer.js | Romanets/RestImageResize | f9c79924994b6ff05db5caccf8343524629544b3 | [
"MIT"
] | 4 | 2015-08-07T17:10:55.000Z | 2018-01-26T08:38:30.000Z | AppData/Modules/Shell/1.0.456/ClientResources/epi/shell/widget/layout/ComponentTabContainer.js | Romanets/RestImageResize | f9c79924994b6ff05db5caccf8343524629544b3 | [
"MIT"
] | 2 | 2015-08-07T12:24:06.000Z | 2017-04-20T12:18:19.000Z | //>>built
require({cache:{"url:epi/shell/widget/layout/templates/ComponentTabContainer.htm":"<div class=\"dijitTabContainer dojoxDragHandle epi-componentGroup epi-compactTabs\">\r\n <div class=\"dijitTabListWrapper\" data-dojo-attach-point=\"tablistNode\"></div>\r\n <div data-dojo-attach-point=\"tablistSpacer\" class=\"dijitTabSpacer ${baseClass}-spacer\"></div>\r\n <div class=\"dijitTabPaneWrapper ${baseClass}-container\" data-dojo-attach-point=\"containerNode\"></div>\r\n <div data-dojo-attach-point=\"_splitterNode\"></div>\r\n</div>\r\n"}});define("epi/shell/widget/layout/ComponentTabContainer",["dojo/_base/array","dojo/_base/lang","dojo/_base/declare","dojo/dom-style","dojo/dom-construct","dojo/dom-attr","dojo/dom-class","dojo/dom-geometry","dojo/topic","dojo/Evented","dojo/text!./templates/ComponentTabContainer.htm","dijit/layout/TabContainer","dijit/layout/utils","epi/shell/widget/layout/_ComponentTabController","epi/shell/widget/layout/_ComponentResizeMixin","dijit/_WidgetsInTemplateMixin","dijit/form/ToggleButton","epi/shell/widget/ComponentChrome","epi/shell/widget/_FocusableMixin","epi/shell/command/_CommandProviderMixin","epi/shell/widget/command/RemoveGadget"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b,_c,_d,_e,_f,_10,_11,_12,_13,_14,_15){return _3("epi.shell.widget.layout.ComponentTabContainer",[_c,_10,_f,_13,_a,_14],{useMenu:true,doLayout:true,useSlider:false,toggleable:true,templateString:_b,controllerWidget:"epi.shell.widget.layout._ComponentTabController",_removeCommand:null,postMixInProperties:function(){this.inherited(arguments);this._removeCommand=new _15({model:this});},startup:function(){if(this._started){return;}this.inherited(arguments);if(this.maxHeight){_4.set(this.containerNode,"maxHeight",this.maxHeight);}},postCreate:function(){this.inherited(arguments);this.add("commands",this._removeCommand);this.tablist.on("toggle",_2.hitch(this,function(_16){this._started&&this.set("open",_16);}));},addChild:function(_17,_18){var _19=new _12({title:_17.get("heading")||""});_19.addChild(_17);this.inherited(arguments,[_19,_18]);if(this._started&&!_19._started){_19.startup();}},layout:function(){if(!this._contentBox||typeof (this._contentBox.l)=="undefined"){return;}var sc=this.selectedChildWidget;if(this.doLayout){var _1a=this.tabPosition.replace(/-h/,"");this.tablist.layoutAlign=_1a;var _1b=[this.tablist,{domNode:this.tablistSpacer,layoutAlign:_1a},{domNode:this.containerNode,layoutAlign:"client"}];if(this._splitter){_1b.push({domNode:this._splitter.domNode,layoutAlign:"bottom"});}_d.layoutChildren(this.domNode,this._contentBox,_1b);this._containerContentBox=_d.marginBox2contentBox(this.containerNode,_1b[2]);if(sc&&sc.resize){sc.resize(this._containerContentBox);}}else{if(this.tablist.resize){var s=this.tablist.domNode.style;s.width="0";var _1c=_8.getContentBox(this.domNode).w;s.width="";this.tablist.resize({w:_1c});}}},resize:function(_1d){_1d=_2.mixin({},_1d);if(!_1d.h){if(!this.open){_1d.h=this._getClosedHeight();}else{if(this.lastOpenHeight){_1d.h=this.lastOpenHeight;}}}this.inherited(arguments,[_1d]);},getSize:function(){var _1e=_8.getMarginBox(this.domNode);if(!this.open){_1e.h=this._getClosedHeight();}return _1e;},_getClosedHeight:function(){var _1f=_8.getMarginExtents(this.domNode).h,_20=this.tablist?_8.getMarginBox(this.tablist.domNode).h:0,_21=this._splitter?_8.getMarginBox(this._splitter.domNode).h:0;return _20+_21+_1f;},selectChild:function(){this.inherited(arguments);this._removeCommand.set("model",this.selectedChildWidget);},_makeController:function(_22){var _23=this.inherited(arguments);_23.set("title",this.get("heading")||"");return _23;},_setToggleableAttr:function(_24){this._set("toggleable",_24);this.tablist&&this.tablist.set("toggleable",this.toggleable);},_setOpenAttr:function(_25){this.inherited(arguments);this.tablist.setOpen(_25);_4.set(this.containerNode,"display",_25?"":"none");if(this._started){if(!_25){this.lastOpenHeight=_8.getMarginBox(this.domNode).h;}this.emit("toggle",this.open);}}});}); | 2,009.5 | 4,009 | 0.777308 |
b1f18cea34e88ae15d6daa7c12c2c8243e9d0e93 | 2,155 | js | JavaScript | test/ast-node/value.js | smori1983/javascript-smodules | e12212306dfeb38e7c827a7ae3bba43fcaa3273b | [
"MIT"
] | null | null | null | test/ast-node/value.js | smori1983/javascript-smodules | e12212306dfeb38e7c827a7ae3bba43fcaa3273b | [
"MIT"
] | null | null | null | test/ast-node/value.js | smori1983/javascript-smodules | e12212306dfeb38e7c827a7ae3bba43fcaa3273b | [
"MIT"
] | null | null | null | const describe = require('mocha').describe;
const it = require('mocha').it;
const assert = require('assert');
const contextBuilder = require('../../test_lib/parse-context-builder');
describe('ast-node', () => {
describe('value - bool', () => {
describe('read - error', () => {
it('empty string', () => {
const context = contextBuilder.build('');
assert.deepStrictEqual(context.read('value_bool'), false);
});
it('uppercase', () => {
const context = contextBuilder.build('TRUE');
assert.deepStrictEqual(context.read('value_bool'), false);
});
});
describe('read - ok', () => {
it('space', () => {
const context = contextBuilder.build(' true ');
assert.deepStrictEqual(context.read('value_bool'), true);
});
it('operator no space - 1', () => {
const context = contextBuilder.build('true===true');
assert.deepStrictEqual(context.read('value_bool'), true);
});
it('operator no space - 2', () => {
const context = contextBuilder.build('true!==true');
assert.deepStrictEqual(context.read('value_bool'), true);
});
});
});
describe('value - null', () => {
describe('read - error', () => {
it('empty string', () => {
const context = contextBuilder.build('');
assert.deepStrictEqual(context.read('value_null'), false);
});
it('uppercase', () => {
const context = contextBuilder.build('NULL');
assert.deepStrictEqual(context.read('value_null'), false);
});
});
describe('read - ok', () => {
it('space', () => {
const context = contextBuilder.build(' null ');
assert.deepStrictEqual(context.read('value_null'), true);
});
it('operator no space - 1', () => {
const context = contextBuilder.build('null===true');
assert.deepStrictEqual(context.read('value_null'), true);
});
it('operator no space - 2', () => {
const context = contextBuilder.build('null!==true');
assert.deepStrictEqual(context.read('value_null'), true);
});
});
});
});
| 31.231884 | 71 | 0.555916 |
b1f22eed3ca5820916c0881cbb91bde2d8ad2bf9 | 2,462 | js | JavaScript | node_modules/postcss-css-reset/src/index.js | testted123456/vue-element | b3fcc5193a5517c87fca8938d4d9163083de0214 | [
"MIT"
] | 2 | 2020-08-17T10:32:22.000Z | 2020-08-18T03:04:36.000Z | node_modules/postcss-css-reset/src/index.js | testted123456/vue-element | b3fcc5193a5517c87fca8938d4d9163083de0214 | [
"MIT"
] | null | null | null | node_modules/postcss-css-reset/src/index.js | testted123456/vue-element | b3fcc5193a5517c87fca8938d4d9163083de0214 | [
"MIT"
] | 2 | 2020-08-17T10:32:24.000Z | 2020-10-27T10:28:28.000Z | 'use strict';
import postcss from 'postcss';
import resetCore from './resetCore';
const atRules = {
'reset-global' (platefprm) {
return resetCore.resetGlobal(platefprm);
},
'reset-nested' (...tags) {
return resetCore.resetNested(tags);
}
};
// const unwrapAmp = (nodeSelector, node) => {
// if (nodeSelector.indexOf('&:') >= 0 && node.name !== 'media') {
// return node.selectors.map((selector) => {
// return nodeSelector.replace(/&/g, selector);
// }).join(',');
// }
// return nodeSelector;
// };
// const getGlobalSelector = (node) => {
// if (node.parent && node.parent.type === 'atrule') {
// return `${node.parent.name} ${node.parent.params} ${node.selector}`;
// } else if (node.name === 'media') {
// return getGlobalSelector(node.parent);
// }
// return node.selector;
// };
const applyRuleSetToNode = (ruleSet, node, currentAtRule) => {
Object.keys(ruleSet).forEach((prop) => {
let rule = ruleSet[prop];
if (typeof rule === 'object') {
if (node.name !== 'media') {
let extRule = postcss.rule({ selector: unwrapAmp(prop, node) });
applyRuleSetToNode(rule, extRule);
let globalSelector = getGlobalSelector(node);
node.parent.insertAfter(ampInsertedNodes[globalSelector] || node, extRule);
ampInsertedNodes[globalSelector] = extRule;
} else {
let mediaNestedRule = postcss.parse(`${prop} ${JSON.stringify(rule).replace(/"/g, '')}`);
node.append(mediaNestedRule);
}
} else {
if (currentAtRule) {
node.insertBefore(currentAtRule, { prop: prop, value: rule });
} else {
node.append({ prop, value: rule });
}
}
});
};
module.exports = postcss.plugin('postcss-reset', (opts) => {
let options = Object.assign({}, opts);
return (root) => {
let promises = [];
root.walkAtRules(/^reset-/i, (rule) => {
var parser = atRules[rule.name];
if (parser) {
let params = rule.params.trim() ? rule.params.trim().split(' ') : [];
let promise = parser(...params);
promises.push(promise);
promise.then((resetRules) => {
if (typeof resetRules === 'object') {
applyRuleSetToNode(resetRules, rule.parent, rule);
} else {
root.prepend(resetRules);
}
rule.remove();
}).catch(console.error);
}
});
return Promise.all(promises);
};
});
| 28.964706 | 97 | 0.572705 |
b1f2b16d61de955d603f9e38641b356027d7c2d1 | 2,413 | js | JavaScript | sapui5-sdk-1.74.0/test-resources/sap/ca/ui/demokit/explored/views/type/Date.controller.js | juanfelipe82193/opensap | 568c01843a07b8a1be88f8fb8ccb49845fb8110e | [
"Apache-2.0"
] | null | null | null | sapui5-sdk-1.74.0/test-resources/sap/ca/ui/demokit/explored/views/type/Date.controller.js | juanfelipe82193/opensap | 568c01843a07b8a1be88f8fb8ccb49845fb8110e | [
"Apache-2.0"
] | null | null | null | sapui5-sdk-1.74.0/test-resources/sap/ca/ui/demokit/explored/views/type/Date.controller.js | juanfelipe82193/opensap | 568c01843a07b8a1be88f8fb8ccb49845fb8110e | [
"Apache-2.0"
] | null | null | null | jQuery.sap.require("sap.ca.ui.model.type.Date");
jQuery.sap.require("sap.ca.ui.model.type.DateTime");
jQuery.sap.require("sap.ca.ui.model.type.Time");
sap.ui.controller("sap.ca.ui.sample.views.type.Date", {
onInit : function() {
var page = this.getView().byId("page");
util.UiFactory.fillPageHeader(page, this.getView(), util.Title.FORMAT_DATE);
var today = new Date();
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var twoDaysAgo = new Date();
twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
var sixDaysAgo = new Date();
sixDaysAgo.setDate(sixDaysAgo.getDate() - 6);
var sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var yesterdayNight = new Date();
yesterdayNight.setHours(23, 59, 0, 0);
yesterdayNight.setDate(yesterdayNight.getDate() - 1);
var thisMorning = new Date(yesterdayNight);
thisMorning.setHours(0, 1, 0, 0);
thisMorning.setDate(thisMorning.getDate() + 1);
var utcDesc = thisMorning.getTimezoneOffset() > 0 ? "Yesterday Night" : "This Morning";
var utcDate = thisMorning.getTimezoneOffset() > 0 ? yesterdayNight : thisMorning;
var model = new sap.ui.model.json.JSONModel(
{
DaysAgo:
[
{
"Name" : "Today",
"Date" : today
},
{
"Name" : "Yesterday",
"Date" : yesterday
},
{
"Name" : "2 days ago",
"Date" : twoDaysAgo
},
{
"Name" : "6 days ago",
"Date" : sixDaysAgo
},
{
"Name" : "7 days ago",
"Date" : sevenDaysAgo
},
{
"Name" : "Tomorrow",
"Date" : tomorrow
}
],
UTC:
[
{
"Name" : utcDesc,
"Date" : utcDate
}
]
}
);
this.getView().setModel(model);
}
}); | 31.75 | 95 | 0.455035 |
b1f2bd26bd1ae46a29d91266713b00f014ad795a | 962 | js | JavaScript | babel.config.js | ryanspice/game.ryanspice.com | d143c14a6241d99432a9b9c51db0e4978ce44312 | [
"MIT"
] | null | null | null | babel.config.js | ryanspice/game.ryanspice.com | d143c14a6241d99432a9b9c51db0e4978ce44312 | [
"MIT"
] | 6 | 2021-03-09T11:50:10.000Z | 2022-02-26T15:15:21.000Z | babel.config.js | ryanspice/game.ryanspice.com | d143c14a6241d99432a9b9c51db0e4978ce44312 | [
"MIT"
] | null | null | null | module.exports = function (api) {
api.cache(false);
const presets = [
"@babel/preset-flow",
[
"@babel/preset-env",
{
"modules": false,
"useBuiltIns": false,
"shippedProposals":true,
"targets": {
"browsers": "cover 90% in CA"
},
"loose": true
}
]
];
const plugins = [
["@babel/plugin-proposal-decorators", {
"legacy": true
}],
"@babel/plugin-proposal-function-sent",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-throw-expressions",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
["@babel/plugin-proposal-class-properties", {
"loose": false
}],
"@babel/plugin-proposal-json-strings",
["@babel/plugin-transform-runtime"],
"@babel/plugin-transform-flow-strip-types",
"@babel/plugin-syntax-flow"
];
return {
presets,
plugins
};
}
| 22.372093 | 49 | 0.644491 |
b1f3d7ef46951c7856ed549ee9f70922edd4035a | 419 | js | JavaScript | packages/wizzi.proto/mongoose/packi/userActivity.js | stfnbssl/wizzi | d05d2e6b39f6425112942d8de9a4556e0ad99ba7 | [
"MIT"
] | null | null | null | packages/wizzi.proto/mongoose/packi/userActivity.js | stfnbssl/wizzi | d05d2e6b39f6425112942d8de9a4556e0ad99ba7 | [
"MIT"
] | null | null | null | packages/wizzi.proto/mongoose/packi/userActivity.js | stfnbssl/wizzi | d05d2e6b39f6425112942d8de9a4556e0ad99ba7 | [
"MIT"
] | null | null | null | const mongoose = require('mongoose');
const userActivitySchema = new mongoose.Schema({
username: { type: String, unique: true },
openPackies: { type: Array},
openFiles: { type: Array},
});
let UserActivity = null;
module.exports = {
getUserActivity: function() {
if (!UserActivity) { UserActivity = mongoose.model('UserActivity', userActivitySchema); }
return UserActivity;
}
} | 26.1875 | 97 | 0.658711 |
b1f4dfacf847e466267dcfdb8d67915c1c1f1d3f | 599 | js | JavaScript | src/api/admin/project-manage.js | hxulin/site-guide-front | 729366d65b5d925a8c81f6ab658237878a347998 | [
"MIT"
] | null | null | null | src/api/admin/project-manage.js | hxulin/site-guide-front | 729366d65b5d925a8c81f6ab658237878a347998 | [
"MIT"
] | 5 | 2021-03-10T12:44:33.000Z | 2022-02-27T02:05:51.000Z | src/api/admin/project-manage.js | hxulin/site-guide-front | 729366d65b5d925a8c81f6ab658237878a347998 | [
"MIT"
] | null | null | null | import request from '@/utils/request'
/**
* 项目管理页面, 查询最大排序号
*/
export function queryMaxSequence() {
return request({
url: '/project/max_sequence',
method: 'get'
})
}
/**
* 保存项目记录
*/
export function saveProject(data) {
return request({
url: '/auth/project/save',
method: 'post',
data
})
}
/**
* 查询项目列表记录
*/
export function listProject(data) {
return request({
url: '/project/list',
method: 'post',
data
})
}
/**
* 删除项目记录
*/
export function delProject(data) {
return request({
url: '/auth/project/del',
method: 'post',
data
})
}
| 13.311111 | 37 | 0.587646 |
b1f519e60c62ad79fb3ad54cd21306c6b0d51b5b | 94 | js | JavaScript | src/Components/GoogleMap/MapAPI.js | prosany/RiderExpert | 022561616d9f497a82a5371f704f768ee9bcb94b | [
"MIT"
] | null | null | null | src/Components/GoogleMap/MapAPI.js | prosany/RiderExpert | 022561616d9f497a82a5371f704f768ee9bcb94b | [
"MIT"
] | null | null | null | src/Components/GoogleMap/MapAPI.js | prosany/RiderExpert | 022561616d9f497a82a5371f704f768ee9bcb94b | [
"MIT"
] | null | null | null | const MapAPI = {
key: "AIzaSyCYllTGDdyrOuGjVjOY6swftkR6m34N1ek"
};
export default MapAPI; | 18.8 | 50 | 0.765957 |
b1f567e975a3eb54749a363299b14963105b1055 | 2,419 | js | JavaScript | cbfile.js | BrowserSync/browser-sync-client | 8ea3496a7af2f4b4674a5a56b08e206134dd2179 | [
"MIT"
] | 40 | 2015-02-24T13:56:03.000Z | 2020-10-16T07:56:42.000Z | cbfile.js | BrowserSync/browser-sync-client | 8ea3496a7af2f4b4674a5a56b08e206134dd2179 | [
"MIT"
] | 31 | 2015-02-27T18:45:11.000Z | 2018-01-25T08:10:50.000Z | cbfile.js | shakyShane/browser-sync-client | 8ea3496a7af2f4b4674a5a56b08e206134dd2179 | [
"MIT"
] | 48 | 2015-02-21T19:48:23.000Z | 2020-09-14T06:45:07.000Z | var cb = require("crossbow");
var vfs = require("vinyl-fs");
var jshint = require("gulp-jshint");
var uglify = require("gulp-uglify");
var contribs = require("gulp-contribs");
var through2 = require("through2");
var rename = require("gulp-rename");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
cb.task("lint-test", function lintTest() {
return vfs.src(["test/client-new/*.js", "test/middleware/*.js", "cbfile.js"])
.pipe(jshint("test/.jshintrc"))
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"));
});
cb.task("lint-lib", function lintLib() {
return vfs.src(["lib/*", "!lib/browser-sync-client.js", "!lib/events.js", "!lib/client-shims.js"])
.pipe(jshint("lib/.jshintrc"))
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"));
});
cb.task("contribs", function contribs() {
return vfs.src("README.md")
.pipe(contribs())
.pipe(vfs.dest("./"));
});
/**
* Strip debug statements
* @returns {*}
*/
var stripDebug = function () {
var chunks = [];
return through2.obj(function (file, enc, cb) {
chunks.push(file);
var string = file._contents.toString();
var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g;
var stripped = string.replace(regex, "");
file.contents = new Buffer(stripped);
this.push(file);
cb();
});
};
cb.task("bundle", function bundle() {
return browserify("./lib/index.js")
.bundle()
.pipe(source("index.js"))
.pipe(vfs.dest("./dist"));
});
cb.task("minify", function minify() {
return vfs.src(["dist/index.js"])
.pipe(stripDebug())
.pipe(rename("index.min.js"))
.pipe(uglify())
.pipe(vfs.dest("./dist"));
});
cb.task("build-all", ["bundle", "minify"]);
cb.task("dev", {
description: "Build-all & then watch for changes",
tasks: [
"build-all",
function () {
cb.watch(["lib/*.js", "test/client-new/**/*.js"], ["build-all"], {block: true});
}
]
});
cb.task("default", ["lint-lib", "lint-test", "build-all"]);
cb.group("karma", {
watch: "@npm karma start test/karma.conf.js",
unit: "@npm karma start test/karma.conf.ci.js"
});
cb.task("test", [
"default",
"@npm mocha test/middleware",
"karma:unit"
]);
| 27.804598 | 102 | 0.560149 |
b1f5c74c3bfa2c274196dea5f940ee67b792208c | 622 | js | JavaScript | src/downloadonepageallimages.js | masx200/mn5-cc-search-downloader | c6df4e0fa8553b15ae321171b6e77c2919cc6776 | [
"MIT"
] | 3 | 2020-08-24T08:23:15.000Z | 2022-01-16T10:20:08.000Z | src/downloadonepageallimages.js | masx200/mn5-cc-search-downloader | c6df4e0fa8553b15ae321171b6e77c2919cc6776 | [
"MIT"
] | null | null | null | src/downloadonepageallimages.js | masx200/mn5-cc-search-downloader | c6df4e0fa8553b15ae321171b6e77c2919cc6776 | [
"MIT"
] | null | null | null | import { callaria2cdown } from "./callaria2cdown.js";
import { getdirectoryname } from "./getdirectoryname.js";
import { selectimagesfromdom } from "./selectimagesfromdom.js";
import { domtourl } from "./urltodom.js";
//调用aria2c批量下载文件
//选择文档中的所有图片并去重
//下载相册一页中的图片
export async function downloadonepageallimages(document) {
const directoryname = getdirectoryname(document);
let fileurls = selectimagesfromdom(document);
await callaria2cdown(fileurls, directoryname);
console.log(
"one page\xA0images\xA0download\xA0done " + domtourl.get(document)
//
//document.documentURI
);
}
| 32.736842 | 74 | 0.726688 |
b1f636d98d4df81c557642d3c0458ca747fab6c3 | 191 | js | JavaScript | src/canned/Label.js | gaswelder/react-slippy-map | a216d251bfb07ee9dbdf9343c4d38f1ec8121f3b | [
"MIT"
] | 5 | 2018-02-06T09:07:18.000Z | 2020-06-06T10:23:56.000Z | src/canned/Label.js | gaswelder/react-slippy-map | a216d251bfb07ee9dbdf9343c4d38f1ec8121f3b | [
"MIT"
] | 4 | 2020-07-17T00:38:20.000Z | 2021-09-01T04:47:44.000Z | src/canned/Label.js | gaswelder/react-slippy-map | a216d251bfb07ee9dbdf9343c4d38f1ec8121f3b | [
"MIT"
] | null | null | null | import React from "react";
import InfoBox from "./InfoBox";
function Label(props) {
const { text, ...rest } = props;
return <InfoBox {...rest}>{text}</InfoBox>;
}
export default Label;
| 19.1 | 45 | 0.659686 |
b1f6c08b751c83b2178b485a609bdce0169a7261 | 769 | js | JavaScript | sameFrequency/index.js | zkobrinsky/Udemy-JavaScript-Algorithms-and-Data-Structures | 4a46c590291799fdd6f838b0fac5a9b77d32521c | [
"MIT"
] | null | null | null | sameFrequency/index.js | zkobrinsky/Udemy-JavaScript-Algorithms-and-Data-Structures | 4a46c590291799fdd6f838b0fac5a9b77d32521c | [
"MIT"
] | null | null | null | sameFrequency/index.js | zkobrinsky/Udemy-JavaScript-Algorithms-and-Data-Structures | 4a46c590291799fdd6f838b0fac5a9b77d32521c | [
"MIT"
] | null | null | null | function sameFrequency(num1, num2) {
let frequencies1 = {};
let frequencies2 = {};
num1 = num1.toString().split("");
num2 = num2.toString().split("");
for (let i = 0; i < num1.length; i++) {
let num = num1[i];
frequencies1[num] = ++frequencies1[num] || 1;
}
for (let i = 0; i < num2.length; i++) {
let num = num2[i];
frequencies2[num] = ++frequencies2[num] || 1;
}
for (let num in frequencies1) {
if (frequencies1[num] !== frequencies2[num]) {
return false;
}
}
return true;
}
// test inputs:
console.log(
sameFrequency(182, 281), //true
sameFrequency(34, 14), //false
sameFrequency(3589578, 5879385), //true
sameFrequency(22, 222) //false
);
// sameFrequency(182, 281);
| 22.617647 | 51 | 0.570871 |
b1f71580329f1359cc70d48f2aea59efe5f99038 | 602 | js | JavaScript | public/scripts/controllers/dashboard-controller.js | ianemcallister/team-29kettle | 68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a | [
"MIT"
] | 1 | 2022-03-11T01:58:55.000Z | 2022-03-11T01:58:55.000Z | public/scripts/controllers/dashboard-controller.js | ianemcallister/team-29kettle | 68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a | [
"MIT"
] | null | null | null | public/scripts/controllers/dashboard-controller.js | ianemcallister/team-29kettle | 68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a | [
"MIT"
] | null | null | null | ckc
.controller('dashboardController', dashboardController);
dashboardController.$inject = ['$routeParams', '$firebaseObject', 'moment'];
/* @ngInject */
function dashboardController($routeParams, $firebaseObject, moment) {
// NOTIFY PROGRES
console.log('$routeParams', $routeParams)
// LOCAL VARIABLES
var vm = this;
// VIEW MODEL VARIABLES
vm.user = firebase.auth().currentUser;
vm.routeParams = $routeParams;
// VIEW MODEL FUNCTIONS
vm.today = function() {
return moment().format();
}
// EXECUTE
console.log('in the dash controller'); // TODO: TAKE THIS OUT LATER
}
| 21.5 | 77 | 0.696013 |
b1f748a93aaf1785ad4a1ab1d2820f121050c71a | 1,081 | js | JavaScript | src/service/space/image.js | felixyin/ebay-vue-admin | 60c75b8a8e68c907d827b9276e100c6c666f0f11 | [
"MIT"
] | 1 | 2020-11-23T06:30:09.000Z | 2020-11-23T06:30:09.000Z | src/service/space/image.js | NobodiesKZD/sf-vue-admin | 60f1f27c97691fa7515989257bd6e2e9e27bf079 | [
"MIT"
] | null | null | null | src/service/space/image.js | NobodiesKZD/sf-vue-admin | 60f1f27c97691fa7515989257bd6e2e9e27bf079 | [
"MIT"
] | null | null | null | import { Permission } from '@/core/decorator/service'
import request from '@/utils/request'
class ImageSpaceService {
@Permission('space/image/type/list')
type() {
return request({
url: '/space/image/type/list',
method: 'get'
})
}
@Permission('space/image/type/add')
addType(data) {
return request({
url: '/space/image/type/add',
method: 'post',
data
})
}
@Permission('space/image/type/delete')
deleteType(data) {
return request({
url: '/space/image/type/delete',
method: 'post',
data
})
}
@Permission('space/image/page')
page(query) {
return request({
url: '/space/image/page',
method: 'get',
params: query
})
}
@Permission('space/image/delete')
delete(data) {
return request({
url: '/space/image/delete',
method: 'post',
data
})
}
@Permission('space/image/upload')
upload(data) {
return request({
url: '/space/image/upload',
method: 'post',
data
})
}
}
export default ImageSpaceService
| 18.016667 | 53 | 0.575393 |
b1f7abb3983198da41f6c292211e86103d077dc0 | 130,764 | js | JavaScript | dist/officebot-sdk.min.js | OfficeBot/obsdk | e90e5cc763310135da5d1aaa3f88dc22d941ff57 | [
"MIT"
] | null | null | null | dist/officebot-sdk.min.js | OfficeBot/obsdk | e90e5cc763310135da5d1aaa3f88dc22d941ff57 | [
"MIT"
] | null | null | null | dist/officebot-sdk.min.js | OfficeBot/obsdk | e90e5cc763310135da5d1aaa3f88dc22d941ff57 | [
"MIT"
] | null | null | null | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.officebotSdk = f()}})(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){
/**
* This creates a simple package that can be exported
* @namespace OfficeBotSDK.Index
*/
let SDK = (function(Promise) {
let Settings = require('./src/settings.js');
Settings.setPromiseLib(Promise);
let exports = {
API : require('./src/api-config.class'),
Cache : require('./src/cache.class'),
EndpointConfig : require('./src/endpoint-config.class'),
Endpoint : require('./src/endpoint.class'),
HTTPMock : require('./src/http-mock.class'),
Model : require('./src/model.class'),
Request : require('./src/request.class'),
Settings : Settings,
Tranport : require('./src/transport.class'),
URLBuilder : require('./src/url-builder.class'),
Utils : require('./src/utils.class')
};
return exports;
})(Promise);
module.exports = SDK;
},{"./src/api-config.class":15,"./src/cache.class":16,"./src/endpoint-config.class":17,"./src/endpoint.class":18,"./src/http-mock.class":19,"./src/model.class":20,"./src/request.class":21,"./src/settings.js":22,"./src/transport.class":23,"./src/url-builder.class":24,"./src/utils.class":25}],2:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return (b64.length * 3 / 4) - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr((len * 3 / 4) - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0; i < l; i += 4) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],3:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || isArrayBuffer(string)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
function isArrayBuffer (obj) {
return obj instanceof ArrayBuffer ||
(obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
typeof obj.byteLength === 'number')
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"base64-js":2,"ieee754":11}],4:[function(require,module,exports){
(function (Buffer){
var clone = (function() {
'use strict';
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
var nativeMap;
try {
nativeMap = Map;
} catch(_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function() {};
}
var nativeSet;
try {
nativeSet = Set;
} catch(_) {
nativeSet = function() {};
}
var nativePromise;
try {
nativePromise = Promise;
} catch(_) {
nativePromise = function() {};
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (_instanceof(parent, nativeMap)) {
child = new nativeMap();
} else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
} else if (_instanceof(parent, nativePromise)) {
child = new nativePromise(function (resolve, reject) {
parent.then(function(value) {
resolve(_clone(value, depth - 1));
}, function(err) {
reject(_clone(err, depth - 1));
});
});
} else if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
child = new Buffer(parent.length);
parent.copy(child);
return child;
} else if (_instanceof(parent, Error)) {
child = Object.create(parent);
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (_instanceof(parent, nativeMap)) {
parent.forEach(function(value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function(value) {
var entryChild = _clone(value, depth - 1);
child.add(entryChild);
});
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
}).call(this,require("buffer").Buffer)
},{"buffer":3}],5:[function(require,module,exports){
var pSlice = Array.prototype.slice;
var objectKeys = require('./lib/keys.js');
var isArguments = require('./lib/is_arguments.js');
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
},{"./lib/is_arguments.js":6,"./lib/keys.js":7}],6:[function(require,module,exports){
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
},{}],7:[function(require,module,exports){
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
},{}],8:[function(require,module,exports){
var equalsOptions = { strict: true };
var _equals = require('deep-equal');
var areEquals = function (a, b) {
return _equals(a, b, equalsOptions);
};
var helpers_1 = require('./helpers');
exports.JsonPatchError = helpers_1.PatchError;
exports.deepClone = helpers_1._deepClone;
/* We use a Javascript hash to store each
function. Each hash entry (property) uses
the operation identifiers specified in rfc6902.
In this way, we can map each patch operation
to its dedicated function in efficient way.
*/
/* The operations applicable to an object */
var objOps = {
add: function (obj, key, document) {
obj[key] = this.value;
return { newDocument: document };
},
remove: function (obj, key, document) {
var removed = obj[key];
delete obj[key];
return { newDocument: document, removed: removed };
},
replace: function (obj, key, document) {
var removed = obj[key];
obj[key] = this.value;
return { newDocument: document, removed: removed };
},
move: function (obj, key, document) {
/* in case move target overwrites an existing value,
return the removed value, this can be taxing performance-wise,
and is potentially unneeded */
var removed = getValueByPointer(document, this.path);
if (removed) {
removed = helpers_1._deepClone(removed);
}
var originalValue = applyOperation(document, { op: "remove", path: this.from }).removed;
applyOperation(document, { op: "add", path: this.path, value: originalValue });
return { newDocument: document, removed: removed };
},
copy: function (obj, key, document) {
var valueToCopy = getValueByPointer(document, this.from);
// enforce copy by value so further operations don't affect source (see issue #177)
applyOperation(document, { op: "add", path: this.path, value: helpers_1._deepClone(valueToCopy) });
return { newDocument: document };
},
test: function (obj, key, document) {
return { newDocument: document, test: areEquals(obj[key], this.value) };
},
_get: function (obj, key, document) {
this.value = obj[key];
return { newDocument: document };
}
};
/* The operations applicable to an array. Many are the same as for the object */
var arrOps = {
add: function (arr, i, document) {
if (helpers_1.isInteger(i)) {
arr.splice(i, 0, this.value);
}
else {
arr[i] = this.value;
}
// this may be needed when using '-' in an array
return { newDocument: document, index: i };
},
remove: function (arr, i, document) {
var removedList = arr.splice(i, 1);
return { newDocument: document, removed: removedList[0] };
},
replace: function (arr, i, document) {
var removed = arr[i];
arr[i] = this.value;
return { newDocument: document, removed: removed };
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
/**
* Retrieves a value from a JSON document by a JSON pointer.
* Returns the value.
*
* @param document The document to get the value from
* @param pointer an escaped JSON pointer
* @return The retrieved value
*/
function getValueByPointer(document, pointer) {
if (pointer == '') {
return document;
}
var getOriginalDestination = { op: "_get", path: pointer };
applyOperation(document, getOriginalDestination);
return getOriginalDestination.value;
}
exports.getValueByPointer = getValueByPointer;
/**
* Apply a single JSON Patch Operation on a JSON document.
* Returns the {newDocument, result} of the operation.
* It modifies the `document` and `operation` objects - it gets the values by reference.
* If you would like to avoid touching your values, clone them:
* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.
*
* @param document The document to patch
* @param operation The operation to apply
* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
* @param mutateDocument Whether to mutate the original document or clone it before applying
* @return `{newDocument, result}` after the operation
*/
function applyOperation(document, operation, validateOperation, mutateDocument) {
if (validateOperation === void 0) { validateOperation = false; }
if (mutateDocument === void 0) { mutateDocument = true; }
if (validateOperation) {
if (typeof validateOperation == 'function') {
validateOperation(operation, 0, document, operation.path);
}
else {
validator(operation, 0);
}
}
/* ROOT OPERATIONS */
if (operation.path === "") {
var returnValue = { newDocument: document };
if (operation.op === 'add') {
returnValue.newDocument = operation.value;
return returnValue;
}
else if (operation.op === 'replace') {
returnValue.newDocument = operation.value;
returnValue.removed = document; //document we removed
return returnValue;
}
else if (operation.op === 'move' || operation.op === 'copy') {
returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field
if (operation.op === 'move') {
returnValue.removed = document;
}
return returnValue;
}
else if (operation.op === 'test') {
returnValue.test = areEquals(document, operation.value);
if (returnValue.test === false) {
throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', 0, operation, document);
}
returnValue.newDocument = document;
return returnValue;
}
else if (operation.op === 'remove') {
returnValue.removed = document;
returnValue.newDocument = null;
return returnValue;
}
else if (operation.op === '_get') {
operation.value = document;
return returnValue;
}
else {
if (validateOperation) {
throw new exports.JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', 0, operation, document);
}
else {
return returnValue;
}
}
} /* END ROOT OPERATIONS */
else {
if (!mutateDocument) {
document = helpers_1._deepClone(document);
}
var path = operation.path || "";
var keys = path.split('/');
var obj = document;
var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift
var len = keys.length;
var existingPathFragment = undefined;
var key = void 0;
var validateFunction = void 0;
if (typeof validateOperation == 'function') {
validateFunction = validateOperation;
}
else {
validateFunction = validator;
}
while (true) {
key = keys[t];
if (validateOperation) {
if (existingPathFragment === undefined) {
if (obj[key] === undefined) {
existingPathFragment = keys.slice(0, t).join('/');
}
else if (t == len - 1) {
existingPathFragment = operation.path;
}
if (existingPathFragment !== undefined) {
validateFunction(operation, 0, document, existingPathFragment);
}
}
}
t++;
if (Array.isArray(obj)) {
if (key === '-') {
key = obj.length;
}
else {
if (validateOperation && !helpers_1.isInteger(key)) {
throw new exports.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", 0, operation.path, operation);
} // only parse key when it's an integer for `arr.prop` to work
else if (helpers_1.isInteger(key)) {
key = ~~key;
}
}
if (t >= len) {
if (validateOperation && operation.op === "add" && key > obj.length) {
throw new exports.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", 0, operation.path, operation);
}
var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch
if (returnValue.test === false) {
throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', 0, operation, document);
}
return returnValue;
}
}
else {
if (key && key.indexOf('~') != -1) {
key = helpers_1.unescapePathComponent(key);
}
if (t >= len) {
var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch
if (returnValue.test === false) {
throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', 0, operation, document);
}
return returnValue;
}
}
obj = obj[key];
}
}
}
exports.applyOperation = applyOperation;
/**
* Apply a full JSON Patch array on a JSON document.
* Returns the {newDocument, result} of the patch.
* It modifies the `document` object and `patch` - it gets the values by reference.
* If you would like to avoid touching your values, clone them:
* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.
*
* @param document The document to patch
* @param patch The patch to apply
* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
* @return An array of `{newDocument, result}` after the patch
*/
function applyPatch(document, patch, validateOperation) {
if (validateOperation) {
if (!Array.isArray(patch)) {
throw new exports.JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
}
}
var results = new Array(patch.length);
for (var i = 0, length_1 = patch.length; i < length_1; i++) {
results[i] = applyOperation(document, patch[i], validateOperation);
document = results[i].newDocument; // in case root was replaced
}
results.newDocument = document;
return results;
}
exports.applyPatch = applyPatch;
/**
* Apply a single JSON Patch Operation on a JSON document.
* Returns the updated document.
* Suitable as a reducer.
*
* @param document The document to patch
* @param operation The operation to apply
* @return The updated document
*/
function applyReducer(document, operation) {
var operationResult = applyOperation(document, operation);
if (operationResult.test === false) {
throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', 0, operation, document);
}
return operationResult.newDocument;
}
exports.applyReducer = applyReducer;
/**
* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.
* @param {object} operation - operation object (patch)
* @param {number} index - index of operation in the sequence
* @param {object} [document] - object where the operation is supposed to be applied
* @param {string} [existingPathFragment] - comes along with `document`
*/
function validator(operation, index, document, existingPathFragment) {
if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {
throw new exports.JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);
}
else if (!objOps[operation.op]) {
throw new exports.JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
}
else if (typeof operation.path !== 'string') {
throw new exports.JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);
}
else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {
// paths that aren't empty string should start with "/"
throw new exports.JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document);
}
else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {
throw new exports.JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);
}
else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {
throw new exports.JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);
}
else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && helpers_1.hasUndefined(operation.value)) {
throw new exports.JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);
}
else if (document) {
if (operation.op == "add") {
var pathLen = operation.path.split("/").length;
var existingPathLen = existingPathFragment.split("/").length;
if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
throw new exports.JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);
}
}
else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {
if (operation.path !== existingPathFragment) {
throw new exports.JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
}
}
else if (operation.op === 'move' || operation.op === 'copy') {
var existingValue = { op: "_get", path: operation.from, value: undefined };
var error = validate([existingValue], document);
if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {
throw new exports.JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);
}
}
}
}
exports.validator = validator;
/**
* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.
* If error is encountered, returns a JsonPatchError object
* @param sequence
* @param document
* @returns {JsonPatchError|undefined}
*/
function validate(sequence, document, externalValidator) {
try {
if (!Array.isArray(sequence)) {
throw new exports.JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
}
if (document) {
//clone document and sequence so that we can safely try applying operations
applyPatch(helpers_1._deepClone(document), helpers_1._deepClone(sequence), externalValidator || true);
}
else {
externalValidator = externalValidator || validator;
for (var i = 0; i < sequence.length; i++) {
externalValidator(sequence[i], i, document, undefined);
}
}
}
catch (e) {
if (e instanceof exports.JsonPatchError) {
return e;
}
else {
throw e;
}
}
}
exports.validate = validate;
},{"./helpers":10,"deep-equal":5}],9:[function(require,module,exports){
var equalsOptions = { strict: true };
var _equals = require('deep-equal');
var areEquals = function (a, b) {
return _equals(a, b, equalsOptions);
};
var helpers_1 = require('./helpers');
var core_1 = require('./core');
/* export all core functions */
var core_2 = require('./core');
exports.applyOperation = core_2.applyOperation;
exports.applyPatch = core_2.applyPatch;
exports.applyReducer = core_2.applyReducer;
exports.getValueByPointer = core_2.getValueByPointer;
exports.validate = core_2.validate;
exports.validator = core_2.validator;
/* export some helpers */
var helpers_2 = require('./helpers');
exports.JsonPatchError = helpers_2.PatchError;
exports.deepClone = helpers_2._deepClone;
exports.escapePathComponent = helpers_2.escapePathComponent;
exports.unescapePathComponent = helpers_2.unescapePathComponent;
var beforeDict = [];
var Mirror = (function () {
function Mirror(obj) {
this.observers = [];
this.obj = obj;
}
return Mirror;
}());
var ObserverInfo = (function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
}());
function getMirror(obj) {
for (var i = 0, length = beforeDict.length; i < length; i++) {
if (beforeDict[i].obj === obj) {
return beforeDict[i];
}
}
}
function getObserverFromMirror(mirror, callback) {
for (var j = 0, length = mirror.observers.length; j < length; j++) {
if (mirror.observers[j].callback === callback) {
return mirror.observers[j].observer;
}
}
}
function removeObserverFromMirror(mirror, observer) {
for (var j = 0, length = mirror.observers.length; j < length; j++) {
if (mirror.observers[j].observer === observer) {
mirror.observers.splice(j, 1);
return;
}
}
}
/**
* Detach an observer from an object
*/
function unobserve(root, observer) {
observer.unobserve();
}
exports.unobserve = unobserve;
/**
* Observes changes made to an object, which can then be retrieved using generate
*/
function observe(obj, callback) {
var patches = [];
var root = obj;
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.push(mirror);
}
else {
observer = getObserverFromMirror(mirror, callback);
}
if (observer) {
return observer;
}
observer = {};
mirror.value = helpers_1._deepClone(obj);
if (callback) {
observer.callback = callback;
observer.next = null;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(dirtyCheck);
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keyup', fastCheck);
window.addEventListener('mousedown', fastCheck);
window.addEventListener('keydown', fastCheck);
window.addEventListener('change', fastCheck);
}
else {
document.documentElement.attachEvent('onmouseup', fastCheck);
document.documentElement.attachEvent('onkeyup', fastCheck);
document.documentElement.attachEvent('onmousedown', fastCheck);
document.documentElement.attachEvent('onkeydown', fastCheck);
document.documentElement.attachEvent('onchange', fastCheck);
}
}
}
observer.patches = patches;
observer.object = obj;
observer.unobserve = function () {
generate(observer);
clearTimeout(observer.next);
removeObserverFromMirror(mirror, observer);
if (typeof window !== 'undefined') {
if (window.removeEventListener) {
window.removeEventListener('mouseup', fastCheck);
window.removeEventListener('keyup', fastCheck);
window.removeEventListener('mousedown', fastCheck);
window.removeEventListener('keydown', fastCheck);
}
else {
document.documentElement.detachEvent('onmouseup', fastCheck);
document.documentElement.detachEvent('onkeyup', fastCheck);
document.documentElement.detachEvent('onmousedown', fastCheck);
document.documentElement.detachEvent('onkeydown', fastCheck);
}
}
};
mirror.observers.push(new ObserverInfo(callback, observer));
return observer;
}
exports.observe = observe;
/**
* Generate an array of patches from an observer
*/
function generate(observer) {
var mirror;
for (var i = 0, length = beforeDict.length; i < length; i++) {
if (beforeDict[i].obj === observer.object) {
mirror = beforeDict[i];
break;
}
}
_generate(mirror.value, observer.object, observer.patches, "");
if (observer.patches.length) {
core_1.applyPatch(mirror.value, observer.patches);
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
}
exports.generate = generate;
// Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path) {
if (obj === mirror) {
return;
}
if (typeof obj.toJSON === "function") {
obj = obj.toJSON();
}
var newKeys = helpers_1._objectKeys(obj);
var oldKeys = helpers_1._objectKeys(mirror);
var changed = false;
var deleted = false;
//if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (helpers_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {
var newVal = obj[key];
if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null) {
_generate(oldVal, newVal, patches, path + "/" + helpers_1.escapePathComponent(key));
}
else {
if (oldVal !== newVal) {
changed = true;
patches.push({ op: "replace", path: path + "/" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(newVal) });
}
}
}
else {
patches.push({ op: "remove", path: path + "/" + helpers_1.escapePathComponent(key) });
deleted = true; // property has been deleted
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!helpers_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) {
patches.push({ op: "add", path: path + "/" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(obj[key]) });
}
}
}
/**
* Create an array of patches from the differences in two objects
*/
function compare(tree1, tree2) {
var patches = [];
_generate(tree1, tree2, patches, '');
return patches;
}
exports.compare = compare;
},{"./core":8,"./helpers":10,"deep-equal":5}],10:[function(require,module,exports){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017 Joachim Wester
* MIT license
*/
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwnProperty(obj, key) {
return _hasOwnProperty.call(obj, key);
}
exports.hasOwnProperty = hasOwnProperty;
function _objectKeys(obj) {
if (Array.isArray(obj)) {
var keys = new Array(obj.length);
for (var k = 0; k < keys.length; k++) {
keys[k] = "" + k;
}
return keys;
}
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var i in obj) {
if (hasOwnProperty(obj, i)) {
keys.push(i);
}
}
return keys;
}
exports._objectKeys = _objectKeys;
;
/**
* Deeply clone the object.
* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)
* @param {any} obj value to clone
* @return {any} cloned obj
*/
function _deepClone(obj) {
switch (typeof obj) {
case "object":
return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
case "undefined":
return null; //this is how JSON.stringify behaves for array items
default:
return obj; //no need to clone primitives
}
}
exports._deepClone = _deepClone;
//3x faster than cached /^\d+$/.test(str)
function isInteger(str) {
var i = 0;
var len = str.length;
var charCode;
while (i < len) {
charCode = str.charCodeAt(i);
if (charCode >= 48 && charCode <= 57) {
i++;
continue;
}
return false;
}
return true;
}
exports.isInteger = isInteger;
/**
* Escapes a json pointer path
* @param path The raw pointer
* @return the Escaped path
*/
function escapePathComponent(path) {
if (path.indexOf('/') === -1 && path.indexOf('~') === -1)
return path;
return path.replace(/~/g, '~0').replace(/\//g, '~1');
}
exports.escapePathComponent = escapePathComponent;
/**
* Unescapes a json pointer path
* @param path The escaped pointer
* @return The unescaped path
*/
function unescapePathComponent(path) {
return path.replace(/~1/g, '/').replace(/~0/g, '~');
}
exports.unescapePathComponent = unescapePathComponent;
function _getPathRecursive(root, obj) {
var found;
for (var key in root) {
if (hasOwnProperty(root, key)) {
if (root[key] === obj) {
return escapePathComponent(key) + '/';
}
else if (typeof root[key] === 'object') {
found = _getPathRecursive(root[key], obj);
if (found != '') {
return escapePathComponent(key) + '/' + found;
}
}
}
}
return '';
}
exports._getPathRecursive = _getPathRecursive;
function getPath(root, obj) {
if (root === obj) {
return '/';
}
var path = _getPathRecursive(root, obj);
if (path === '') {
throw new Error("Object not found in root");
}
return '/' + path;
}
exports.getPath = getPath;
/**
* Recursively checks whether an object has any undefined values inside.
*/
function hasUndefined(obj) {
if (obj === undefined) {
return true;
}
if (obj) {
if (Array.isArray(obj)) {
for (var i = 0, len = obj.length; i < len; i++) {
if (hasUndefined(obj[i])) {
return true;
}
}
}
else if (typeof obj === "object") {
var objKeys = _objectKeys(obj);
var objKeysLength = objKeys.length;
for (var i = 0; i < objKeysLength; i++) {
if (hasUndefined(obj[objKeys[i]])) {
return true;
}
}
}
}
return false;
}
exports.hasUndefined = hasUndefined;
var PatchError = (function (_super) {
__extends(PatchError, _super);
function PatchError(message, name, index, operation, tree) {
_super.call(this, message);
this.message = message;
this.name = name;
this.index = index;
this.operation = operation;
this.tree = tree;
}
return PatchError;
}(Error));
exports.PatchError = PatchError;
},{}],11:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],12:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],13:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],14:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":12,"./encode":13}],15:[function(require,module,exports){
const EndpointConfig = require('./endpoint-config.class.js');
const Endpoint = require('./endpoint.class.js');
const Cache = require('./cache.class');
const clone = require('./utils.class').clone;
/**
* Defines the base configuration for an API
* @constructor
*/
class APIConfig {
constructor() {
this.config = { headers : {}, url : '' };
this.endpoints = {};
this.cache = new Cache();
}
/**
* Gets / Sets base api url
* @param {string=} url - Base url that this endpoint talks to
* @returns {(this|string)}
*/
baseUrl(url) {
if ('undefined' !== typeof url) {
if ('string' === typeof url) {
this.config.url = url;
}
return this;
}
return this.config.url;
}
/**
* Creates a new endpoint
* @param {string} endpointName - The name that will be used to get this endpoint
* @returns {@link Endpoint} An instance of Endpoint
*/
endpoint(endpointName = '__default__') {
let config = new EndpointConfig().api(this);
this[ endpointName ] = new Endpoint(config);
return this[ endpointName ];
}
/**
* Sets headers that all calls will use. Helpful for authentication
* @param {object=} headers - Key / value pairs of headers
* @returns {this | object}
*/
commonHeaders(headers) {
if ('undefined' !== typeof headers) {
this.config.headers = headers;
return this;
} else {
return clone(this.config.headers);
}
}
}
module.exports = APIConfig;
},{"./cache.class":16,"./endpoint-config.class.js":17,"./endpoint.class.js":18,"./utils.class":25}],16:[function(require,module,exports){
/**
* @constructor
*/
class Cache {
/**
* Create a cache object
*/
constructor() {
this.objects = new Map();
this.config = {
ttl : 60000,
};
}
/**
* Fetches an object from the cache using the object's name (typically the url)
* @param {string} name
* @returns {(object|Array|undefined)} The found object or array if exists, otherwise undefined
*/
get(name) {
let now = Date.now();
let obj = this.objects.get(name);
if ('undefined' !== typeof obj && now - obj[0] < this.config.ttl) {
let cachedObject = obj[1];
Object.defineProperty(cachedObject,'__fromCache', {value : true});
return cachedObject;
} else {
this.objects.delete(name); //in case the object exists but has expired
return undefined;
}
}
/**
* Stores any object or primitive into the cache using it's name
* NOTE: Primitives WILL be converted to objects prior to caching
* @param {string} name
* @param {(string|number|boolean|object)} value
* @returns {boolean} success
*/
put(name, value) {
if ('string' !== typeof name) {
throw new Error('Invalid name attribute');
}
//convert primitive strings to string objects so we can add __fromCached
if ('string' === typeof value) {
value = new String(value); // jshint ignore:line
}
if ('number' === typeof value) {
value = new Number(value); // jshint ignore:line
}
if ('boolean' === typeof value) {
value = new Boolean(value); // jshint ignore:line
}
this.objects.set(name, [Date.now(), value]);
return true;
}
/**
* Removes an object from the cache
* @param {string} name
*/
invalidate(name) {
return this.objects.delete(name);
}
/**
* Changes the default time to live of objects in the cache
* @param {number} newTTL
* @returns {boolean} success
*/
setTTL(newTTL) {
if ('number' !== typeof newTTL) {
throw new Error('Invalid TTL value');
}
this.config.ttl = newTTL;
return true;
}
}
module.exports = Cache;
},{}],17:[function(require,module,exports){
const Model = require('./model.class');
const clone = require('./utils.class').clone;
/**
* @constructor
*/
class EndpointConfig {
constructor(config = {}) {
this.config = { api : {}};
let defaults = {
'url' : '/',
'responseType' : "application/json",
'instantiator' : Model
};
Object.assign(this.config, defaults, clone(config));
}
/**
* Gets or sets the expected media return type. Ultimately, it is up to the transport
* to use this setting to correctly talk to the api
* Note - This is currently unused
* @param {string=} newType - The new media type that this endpoint communicates with
*/
mediaType(newType) {
if ('undefined' !== typeof newType) {
if ('string' === typeof newType) {
this.config.responseType = newType;
}
return this;
}
return this.config.responseType;
}
/**
* Gets / sets the API configuration object. This is needed so each
* endpoint can share common settings
* @param {APIConfig} config - The parent api configuration
* @returns {(this | object)}
*/
api(config) {
if ('undefined' !== typeof config) {
if ('object' === typeof config && config !== null) {
this.config.api = clone(config);
}
return this;
}
return this.config.api;
}
/**
* Gets the base url from the underlying api configuration
* @returns {string} Current root url
*/
baseUrl() {
if (!this.config.api || !this.config.api.baseUrl) {
return '';
}
return this.config.api.baseUrl();
}
/**
* Gets / sets the endpoint's relative url
* @param {string=} newUrl - Url to use for this endpoint
* @returns {(this | string)} This instance or the current url
*/
url(newUrl) {
if ('undefined' !== typeof newUrl) {
if ('string' === typeof newUrl) {
this.config.url = newUrl;
}
return this;
}
return this.config.url;
}
/**
* Gets / sets the instantiator function to use when creating a new model.
* @param {(function|class)=} instantiator - the function or class to use for instantiation
* @returns {(this|function)} This instance or the current insantiation function
*/
model(newFn) {
if ('undefined' !== typeof newFn) {
if ('function' === typeof newFn) {
this.config.instantiator = newFn;
}
return this;
}
return this.config.instantiator;
}
}
module.exports = EndpointConfig;
},{"./model.class":20,"./utils.class":25}],18:[function(require,module,exports){
const URLBuilder = require('./url-builder.class');
const Request = require('./request.class');
const clone = require('./utils.class').clone;
const noop = require('./utils.class').noop;
/**
* Creates an endpoint instance
* @constructor
*/
class Endpoint {
constructor(endpointConfig = {}) {
if (!endpointConfig || 'function' !== typeof endpointConfig.model) {
throw new Error('Invalid endpoint configuration.');
}
this.endpointConfig = clone(endpointConfig);
this.config = {
allowFromCache : true,
method : 'get',
target : '',
query : {}
};
this.cache = this.endpointConfig.api().cache;
}
/**
* Instantiates a new model instance and returns it
* @param {object=} data - Initialization data for the new model instance
* @returns {@link Model} New instance of Model
*/
createNew(data = {}) {
let root = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url()
]);
data['@root'] = root;
let instantiator = this.endpointConfig.model();
let instance = new instantiator(data);
instance.config(this.endpointConfig);
return instance;
}
/**
* Gets / sets instantiator to use when creating a new model instance. Instantiator *should* inherit
* from {@link Model}
* @param {(function|class)=} instantiator - Function or class to use when instantiating model
* @returns {(this|function)} Current instantiator function or this instance
*/
model(instantiator) {
if ('undefined' !== typeof instantiator) {
this.endpointConfig.model(instantiator);
return this;
}
return this.endpointConfig.model();
}
/**
* Gets / sets the endpoint's relative url
* @param {string=} url - The new url value
* @returns {(this|string)} This instance or the current url
*/
url(newUrl) {
if ('undefined' !== typeof newUrl) {
this.endpointConfig.url(newUrl);
return this;
}
return this.endpointConfig.url();
}
/**
* Builds a query to find an object with the specified identifier
* @param {string} id - the unique model identifier
* @returns {this}
*/
findById(id) {
if ('string' !== typeof id) {
throw new Error('Invalid model identifier');
}
this.config.target = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url(),
id
]);
this.config.method = 'get';
return this;
}
/**
* Creates a query to find objects that match the optional query
* @param {object=} query
* @returns {this}
*/
find(query) {
this.config.target = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url()
]);
this.config.method = 'get';
this.config.query.search = JSON.stringify(query);
return this;
}
/**
* At the moment, this behaves exactly the same as .find, but uses the
* SEARCH verb instead
* @param {object} query
* @returns {this}
*/
search(query) {
this.config.target = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url()
]);
this.config.method = 'search';
this.config.query.search = JSON.stringify(query);
return this;
}
/**
* Creates a query to find a unique model with the specified id
* and replaces it's data with the specified body object
* @param {string} id - the unique model identifier
* @param {object} body
* @returns {this}
*/
findByIdAndUpdate(id, body) {
if ('string' !== typeof id) {
throw new Error('Invalid model identifier');
}
if ('object' !== typeof body) {
throw new Error('Invalid body object');
}
this.config.target = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url(),
id
]);
this.config.body = body;
this.config.method = 'put';
return this;
}
/**
* Creates a query that finds a model with the specified id and
* removes it from the database
* @param {string} id - the unique model identifier
* @returns {this}
*/
findByIdAndRemove(id) {
if ('string' !== typeof id) {
throw new Error('Invalid model identifier');
}
this.config.target = new URLBuilder([
this.endpointConfig.baseUrl(),
this.endpointConfig.url(),
id
]);
this.config.method = 'delete';
return this;
}
/**
* Determines if the query request should allow objects from the cache
* or require objects be fresh from the api
* @param {boolean=} allow - Specify if using the cache is allowed
* @returns {(this | boolean)} This instance or the current allow value
*/
allowFromCache(allow) {
if ('undefined' !== typeof allow) {
if ('boolean' === typeof allow) {
this.config.allowFromCache = allow;
}
return this;
}
return this.config.allowFromCache;
}
/**
* Runs the query that has been created using the find/findBy.. calls
* @param {function=} cb - Function to call on completion (success or failure)
* @returns {Promise}
*/
exec(cb = noop) {
let allowFromCache = this.allowFromCache();
let modelConstructor = this.endpointConfig.model();
let endpointConfig = this.endpointConfig;
let headers = {};
try {
headers = this.endpointConfig.api().commonHeaders();
} catch(e) {
// console.error('Unable to get common headers. Something went\'t wrong (unless you are unit testing). ');
}
Object.assign(headers, this.config.headers);
let request = new Request()
.method(this.config.method)
.body(this.config.body || {})
.query(this.config.query || {})
.headers(headers || {})
.url(this.config.target.toString());
let Promise = require('./settings').getPromise();
return new Promise((resolve, reject) => {
if (this.hasCache()) {
let cachedObject = cache.get(request.url());
if (cachedObject && allowFromCache) {
cb(null, cachedObject);
return resolve(cachedObject);
}
}
//do actual 'get'
request.exec().then(response => {
let data = response.data;
let model;
if (Array.isArray(data)) {
model = data.map((item) => {
let entry = new modelConstructor(item);
entry.config(endpointConfig);
Object.defineProperty(entry, '__request', { value : clone(request), enumerable : false });
return entry;
});
} else {
model = new modelConstructor(data);
model.config(endpointConfig);
Object.defineProperty(model, '__request', { value : clone(request), enumerable : false });
}
if (this.hasCache()) {
cache.put(request.url(), model);
}
cb(null, model);
return resolve(model);
}).catch(err => {
if (this.hasCache()) {
cache.invalidate(request.url());
}
cb(err);
reject(err);
throw err;
});
});
}
/**
* Query helper to skip records returned from the api (if supported). Combined
* with the .limit method, this function is great for pagination
* @param {number} skipAmount
* @returns this
*/
skip(skipAmount = 0) {
if ('number' === typeof skipAmount) {
this.config.query.skip = skipAmount;
}
return this;
}
/**
* Query helper to limit the number of results returned (provided the api
* supports it)
* @param {number} limitAmount
* @returns this
*/
limit(limitAmount = 0) {
if ('number' === typeof limitAmount) {
this.config.query.limit = limitAmount;
}
return this;
}
/**
* Sets a list of fields to return from the api (if supported).
* @param {(string|string[])} fields - a list of fields to return from the api
* @returns this
*/
select(fields = '') {
if (Array.isArray(fields)) {
fields = fields.join(' ');
}
if ('string' === typeof fields) {
this.config.query.fields = fields;
}
return this;
}
/**
* Checks to see if the cache object has been set and is valid
* @access private
* @returns {boolean}
*/
hasCache() {
return this.cache && 'function' === typeof this.cache;
}
}
module.exports = Endpoint;
},{"./request.class":21,"./settings":22,"./url-builder.class":24,"./utils.class":25}],19:[function(require,module,exports){
/**
* @constructor
*/
class HTTPMock {
constructor(verbose = false) {
this.listeners = {};
this.verbose = verbose;
}
/**
* Mock representation of the XMLHttpRequest open method
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open}
* @param {string} method
* @param {string} url
* @returns {undefined}
*/
open(method, url) {
this.log(`Opening ${url} using ${method}`);
}
/**
* Mock representation of the XMLHttpRequest send method
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send}
* @param {object} body
* @returns {undefined}
*/
send(body) {
this.log(`Sending with ${body}`);
if ('function' === typeof this.listeners.load) {
let mockResponse = {
response : {'mock_response' : true, 'data' : ['obj1']},
responseText : "{'mock_response' : true}",
status : 200,
statusText : '200',
responseURL : '/mock-call'
};
Object.assign(this, mockResponse);
this.listeners.load();
}
}
/**
* Mock representation of the XMLHttpRequest getAllResponseHeaders method
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders}
* @returns {string} The mock headers
*/
getAllResponseHeaders() {
return "Mock-Headers: true";
}
/**
* Representation of Javascript's addEventListener designed to hook into this
* mock XMLHttpRequest object
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener}
* @param {string} name - The name of the event to listen for
* @param {function} callback - Function to call when event is triggered
*/
addEventListener(name, callback) {
this.log(`${name} listener registered`);
this.listeners[name] = callback;
}
/**
* Just a stub so we have a uniform interface between this and the real thing
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/setRequestHeader}
* @param {string} header
* @param {string} value
*/
setRequestHeader(header, value) {
return true;
}
/**
* Helper function for logging status output based on this object's
* verbosity settings (true/false)
* @param {string} message
*/
log(message) {
if (this.verbose === true) {
console.log(message);
}
}
}
module.exports = HTTPMock;
},{}],20:[function(require,module,exports){
const jsonpatch = require('fast-json-patch');
const clone = require('./utils.class').clone;
const noop = require('./utils.class').noop;
const Request = require('./request.class');
/**
* @constructor
*/
class Model {
constructor(data = {}) {
Object.defineProperty(this, '__config', {enumerable : false, writable : true});
Object.defineProperty(this, '__response', {enumerable : false, writable : true});
Object.defineProperty(this, '__original', {value : jsonpatch.deepClone(data), writable : true});
Object.defineProperty(this, '__revision', {value : Date.now(), writable : true});
Object.assign(this, clone(data));
}
/**
* Persists this model back to the api
* @param {function=} cb - Callback to invoke on completion (failure or success)
* @returns {Request}
*/
save(cb = noop) {
let headers = {};
try {
headers = this.__config.api().commonHeaders();
} catch(e) {
//ignore
}
let method = this._id ? 'put' : 'post';
let instance = this;
let request = new Request()
.url(this.makeHref())
.method(method)
.headers(headers)
.body(this)
.exec()
.then((response) => {
Object.assign(instance, clone(response.data));
instance.__revision = Date.now();
instance.__response = response;
instance.makeClean();
cb();
return instance;
}).catch(err => {
cb(err);
throw err;
});
return request;
}
/**
* Gets a list of changes that have occured since the last get/save
* @returns {Request}
*/
changes() {
let headers = this.__config.api().commonHeaders();
let targetUrl = this['@changes'];
let request = new Request()
.url(targetUrl)
.query({search : {since : this.__revision}})
.method('get')
.headers(headers)
.exec();
return request;
}
/**
* Starts listening for changes and calls onChange whenever they are detected
* @param {function} onChange - Function to call when changes detected
* @param {number} refreshRate - the duration (in milliseconds) between checks
* @returns {this}
*/
subscribe(onChange, ttl = 3000) {
setInterval(() => {
this.changes().then(changeList => {
if (changeList && changeList.length) {
this.__revision = Date.now();
onChange(changeList, Date.now());
}
});
},ttl);
return this;
}
/**
* Puts only the changes (in patch notation) back to the api. The
* server-side endpoint must support PATCH
* @returns {Request}
*/
update() {
//use patch
let headers = this.__config.api().commonHeaders();
let patches = this.getDiffs();
let targetUrl = this.makeHref();
let instance = this;
let request = new Request()
.url(targetUrl)
.method('patch')
.headers(headers)
.body(patches)
.exec()
.then((response) => {
Object.assign(instance, clone(response.data));
instance.__revision = Date.now();
instance.__response = response;
instance.makeClean();
});
return request;
}
/**
* Sets the underlying API config
* @param {EndpointConfig} endpointConfig
*/
config(endpointConfig = {}) {
this.__config = endpointConfig;
}
makeHref() {
let correctHref;
if ('object' === typeof this.__config) {
correctHref = this.__config.baseUrl() + '/' + this.__config.url() + '/';
if ('string' === typeof this._id ) {
correctHref += this._id;
}
} else {
correctHref = '/__unit_test__';
}
return correctHref;
}
/**
* Returns a list of diffs comparing this version to the last
* synced version from the server
* @private
* @returns {object[]} Array of changes
*/
getDiffs() {
return jsonpatch.compare(this.__original, this);
}
/**
* Returns the current status of this model
* @returns {boolean}
*/
isDirty() {
return this.getDiffs().length > 0;
}
/**
* Clears out the change history and syncs the underlying original version
* to the current version
* @returns {undefined}
*/
makeClean() {
this.__original = jsonpatch.deepClone(this);
}
/**
* Removes this modal from the api
* @param {function=} cb - Function to call on completetion (success or failure)
* @returns {Request}
*/
remove(cb = noop) {
let headers = {};
try {
headers = this.__config.api().commonHeaders();
} catch(e) {}
let targetUrl = this.makeHref();
let instance = this;
let request = new Request()
.url(targetUrl)
.method('delete')
.headers(headers)
.exec()
.then((response) => {
instance.__response = response;
return cb();
}).catch(err => {
cb(err);
throw err;
});
return request;
}
}
module.exports = Model;
},{"./request.class":21,"./utils.class":25,"fast-json-patch":9}],21:[function(require,module,exports){
const Transport = require('./transport.class.js');
const clone = require('./utils.class').clone;
/**
* @constructor
* @param {object=} config
*/
class Request {
constructor(config = {}) {
var defaults = {
method: 'GET',
url: '/',
headers: {},
data: undefined,
responseType : 'application/json',
params : {}
};
this.config = {};
Object.assign(this.config, defaults, config);
}
/**
* Executes the current request using the underlying transport mechanism (ie http)
* @returns {Promise}
*/
exec() {
let originalRequest = this;
let Promise = require('./settings').getPromise();
return new Promise((resolve, reject) => {
originalRequest.transport = new Transport(originalRequest);
originalRequest.transport
.exec()
.then(function successCallback(response) {
response.data = clone(response.response);
// originalRequest.response = response;
response.request = originalRequest;
return resolve(response);
}, function errorCallback(response) {
// originalRequest.response = response;
response.request = originalRequest;
return reject(response);
});
});
}
/**
* Gets / sets the query object to use
* @param {object=} newQuery
* @returns {(this | object)}
*/
query(newQuery) {
if ('undefined' !== typeof newQuery) {
if ('object' === typeof newQuery && newQuery !== null) {
newQuery = clone(newQuery);
}
this.config.params = newQuery;
return this;
} else {
return this.config.params;
}
}
/**
* Gets / sets the http verb (method) to use (ie get,put,post, etc)
* @param {string=} newMethod
* @returns {(this | string)}
*/
method(newMethod) {
if ('undefined' !== typeof newMethod) {
if ('string' === typeof newMethod) {
this.config.method = newMethod;
}
return this;
} else {
return this.config.method;
}
}
/**
* Gets / sets the target url to make the request to
* @param {string=} newUrl
* @returns {(this | string)}
*/
url(newUrl) {
if ('undefined' !== typeof newUrl) {
if ('string' === typeof newUrl) {
this.config.url = newUrl;
}
return this;
} else {
return this.config.url;
}
}
/**
* Gets / sets headers (key / value pairs ) to use for the request
* @param {object=} newHeaderObj
* @returns {(this | object)}
*/
headers(newHeaderObj) {
if ('undefined' !== typeof newHeaderObj) {
if ('object' === typeof newHeaderObj && newHeaderObj !== null) {
this.config.headers = clone(newHeaderObj);
}
return this;
} else {
return this.config.headers;
}
}
/**
* Gets / sets the request body
* @param {object=} newBody
* @returns {(this | object | undefined)}
*/
body(newBody) {
if ('undefined' !== typeof newBody) {
if ('object' === typeof newBody && newBody !== null) {
this.config.data = clone(newBody);
}
return this;
} else {
return this.config.data;
}
}
/**
* Gets or sets the response type for the request
* @param {string=} newType
* @returns {(this | string)}
*/
mediaType(newType) {
if ('undefined' !== typeof newType) {
if ('string' === typeof newType) {
this.config.responseType = newType;
}
return this;
}
return this.config.responseType;
}
/**
* Returns a copy of this request's configurations
* @returns {object}
*/
toJSON() {
return JSON.parse( JSON.stringify(this.config) );
}
}
module.exports = Request;
},{"./settings":22,"./transport.class.js":23,"./utils.class":25}],22:[function(require,module,exports){
/**
* Reference point for all of the sdk modules to find common
* settings, such as what promise to use
* @singleton
* @namespace OfficeBotSDK.Settings
*/
let settings = {
_p : Promise,
setPromiseLib : function(p) {
this._p = p;
},
getPromise : function() {
return this._p;
}
};
module.exports = settings;
},{}],23:[function(require,module,exports){
const clone = require('./utils.class').clone;
const querystring = require('querystring');
/**
* @constructor
*/
class Transport {
constructor(request) {
if ('undefined' !== typeof window && window.XMLHttpRequest) {
this.HTTPRequest = window.XMLHttpRequest;
} else {
this.HTTPRequest = require('./http-mock.class.js'); //used for Node based tests
}
this.setRequest(request);
}
/**
* Stores the request object for use later (ie when .exec() gets called). Helpfull
* if building the transport request up instead of passing everything into constructor.
* @param {Request} request
* @returns {this}
*/
setRequest(request) {
this.request = clone(request);
return this;
}
/**
* Makes the actual api call using the Request object that was passed into the constructor
* or added using the setRequest method.
* @returns {Promise}
*/
exec() {
let Promise = require('./settings').getPromise();
let instance = this;
return new Promise((resolve, reject) => {
let httpInstance = new instance.HTTPRequest();
let url = instance.request.url() ;
let query = querystring.stringify(instance.request.query());
if (query && query.length) {
url = url + '?' + query;
}
let body = instance.request.body();
if ('object' === typeof body) {
body = JSON.stringify(body);
}
httpInstance.addEventListener("load", transferComplete);
httpInstance.addEventListener("error", transferFailed);
httpInstance.addEventListener("abort", transferAborted);
httpInstance.open( instance.request.method().toUpperCase(), url );
httpInstance.responseType = 'json';
let headers = instance.request.headers();
httpInstance.setRequestHeader("Content-Type", instance.request.mediaType());
for ( let headerName in headers ) {
httpInstance.setRequestHeader(headerName, headers[headerName]);
}
httpInstance.send( body );
/**
* Handler:Aborted
*/
function transferAborted() {
let failed = new Error('Transfer cancelled.');
reject(failed);
}
/**
* Handler:Failed
*/
function transferFailed(e) {
reject(httpInstance);
}
/**
* Handler:Finished
*/
function transferComplete() {
if (httpInstance.status < 400) {
resolve(httpInstance);
} else {
reject(httpInstance);
}
}
});
}
}
module.exports = Transport;
},{"./http-mock.class.js":19,"./settings":22,"./utils.class":25,"querystring":14}],24:[function(require,module,exports){
/**
* @constructor
* @param {string[]} args
*/
class URLBuilder {
constructor(args = []) {
if (!args || 'function' !== typeof args.join) {
throw new Error('URL Builder requires param 1 to be an array.');
}
this.target = args.filter(item => {
return item !== '/';
}).join('/') || "/";
}
/**
* @returns {string} url
*/
toString() {
return this.target || '';
}
}
module.exports = URLBuilder;
},{}],25:[function(require,module,exports){
var clone_lib = require('clone');
/**
* @constructor
*/
class Utils {
constructor() {
}
/**
* Does nothing
* @returns {undefined}
*/
static noop() {
}
/**
* Creates a deep copy of the passed in object
* @param {object} obj - Object to copy
* @returns {object} Copied object
*/
static clone(obj) {
return obj;
// return clone_lib(obj);
// return privateClone(obj);
}
}
/**
* Allows our static method to call this recursively
* @param {object} obj
* @private
* @returns {object} Copied object
*/
function privateClone(obj) {
if(obj === null || typeof(obj) != 'object') {
return obj;
}
var temp = new obj.constructor();
for(var key in obj) {
temp[key] = privateClone(obj[key]);
}
return temp;
}
module.exports = Utils;
},{"clone":4}]},{},[1])(1)
}); | 29.800365 | 852 | 0.610275 |
b1f8d032576ca1ead0a00b20cf6a90470fae8731 | 47,948 | js | JavaScript | node_modules/@microsoft/sp-webpart-workbench/local-workbench/chunk.8_none.js | maximus-uk/SPFX_React_SPA | 66810c018a082027ba2d47852aa678a770bc58ef | [
"MIT"
] | null | null | null | node_modules/@microsoft/sp-webpart-workbench/local-workbench/chunk.8_none.js | maximus-uk/SPFX_React_SPA | 66810c018a082027ba2d47852aa678a770bc58ef | [
"MIT"
] | null | null | null | node_modules/@microsoft/sp-webpart-workbench/local-workbench/chunk.8_none.js | maximus-uk/SPFX_React_SPA | 66810c018a082027ba2d47852aa678a770bc58ef | [
"MIT"
] | 1 | 2021-11-11T15:12:29.000Z | 2021-11-11T15:12:29.000Z | (window["webpackJsonp_1e2cdec9_1360_4295_b73c_98d6f51866d5_0_1_0"] = window["webpackJsonp_1e2cdec9_1360_4295_b73c_98d6f51866d5_0_1_0"] || []).push([[8],{
/***/ "0zH+":
/*!*****************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroup.js ***!
\*****************************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroup */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroup", function() { return ChoiceGroup; });
/* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Utilities */ "mkpW");
/* harmony import */ var _ChoiceGroup_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ChoiceGroup.base */ "4Qri");
/* harmony import */ var _ChoiceGroup_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ChoiceGroup.styles */ "Abs4");
var ChoiceGroup = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_ChoiceGroup_base__WEBPACK_IMPORTED_MODULE_1__["ChoiceGroupBase"], _ChoiceGroup_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'ChoiceGroup' });
//# sourceMappingURL=ChoiceGroup.js.map
/***/ }),
/***/ "4Qri":
/*!**********************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroup.base.js ***!
\**********************************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroupBase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupBase", function() { return ChoiceGroupBase; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "17wl");
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(tslib__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Label__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Label */ "wMNn");
/* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Utilities */ "mkpW");
/* harmony import */ var _ChoiceGroupOption_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ChoiceGroupOption/index */ "CaTI");
var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["classNamesFunction"])();
/**
* {@docCategory ChoiceGroup}
*/
var ChoiceGroupBase = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ChoiceGroupBase, _super);
function ChoiceGroupBase(props) {
var _this = _super.call(this, props) || this;
_this._focusCallbacks = {};
_this._changeCallbacks = {};
_this._onBlur = function (ev, option) {
_this.setState({
keyFocused: undefined,
});
};
Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["initializeComponentRef"])(_this);
if (true) {
Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["warnDeprecations"])('ChoiceGroup', props, { onChanged: 'onChange' });
Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["warnMutuallyExclusive"])('ChoiceGroup', props, {
selectedKey: 'defaultSelectedKey',
});
}
var defaultSelectedKey = props.defaultSelectedKey, _a = props.options, options = _a === void 0 ? [] : _a;
var validDefaultSelectedKey = !_isControlled(props) &&
defaultSelectedKey !== undefined &&
options.some(function (option) { return option.key === defaultSelectedKey; });
_this.state = {
keyChecked: validDefaultSelectedKey ? defaultSelectedKey : _this._getKeyChecked(props),
};
_this._id = Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["getId"])('ChoiceGroup');
_this._labelId = Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["getId"])('ChoiceGroupLabel');
return _this;
}
Object.defineProperty(ChoiceGroupBase.prototype, "checkedOption", {
/**
* Gets the current checked option.
*/
get: function () {
var _this = this;
var _a = this.props.options, options = _a === void 0 ? [] : _a;
return Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["find"])(options, function (value) { return value.key === _this.state.keyChecked; });
},
enumerable: true,
configurable: true
});
ChoiceGroupBase.prototype.componentDidUpdate = function (prevProps, prevState) {
// Only update if a new props object has been passed in (don't care about state updates)
if (prevProps !== this.props) {
var newKeyChecked = this._getKeyChecked(this.props);
var oldKeyChecked = this._getKeyChecked(prevProps);
if (newKeyChecked !== oldKeyChecked) {
this.setState({
keyChecked: newKeyChecked,
});
}
}
};
ChoiceGroupBase.prototype.render = function () {
var _this = this;
var _a = this.props, className = _a.className, theme = _a.theme, styles = _a.styles, _b = _a.options, options = _b === void 0 ? [] : _b, label = _a.label, required = _a.required, disabled = _a.disabled, name = _a.name;
var _c = this.state, keyChecked = _c.keyChecked, keyFocused = _c.keyFocused;
var divProps = Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["getNativeProps"])(this.props, _Utilities__WEBPACK_IMPORTED_MODULE_3__["divProperties"], [
'onChange',
'className',
'required',
]);
var classNames = getClassNames(styles, {
theme: theme,
className: className,
optionsContainIconOrImage: options.some(function (option) { return !!(option.iconProps || option.imageSrc); }),
});
var labelId = this._id + '-label';
var ariaLabelledBy = this.props.ariaLabelledBy || (label ? labelId : this.props['aria-labelledby']);
// TODO (Fabric 8?) - if possible, move `root` class to the actual root and eliminate
// `applicationRole` class (but the div structure will stay the same by necessity)
return (
// eslint-disable-next-line deprecation/deprecation
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ className: classNames.applicationRole }, divProps),
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ className: classNames.root, role: "radiogroup" }, (ariaLabelledBy && { 'aria-labelledby': ariaLabelledBy })),
label && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Label__WEBPACK_IMPORTED_MODULE_2__["Label"], { className: classNames.label, required: required, id: labelId, disabled: disabled }, label)),
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: classNames.flexContainer }, options.map(function (option) {
var innerOptionProps = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, option), { focused: option.key === keyFocused, checked: option.key === keyChecked, disabled: option.disabled || disabled, id: _this._getOptionId(option), labelId: _this._getOptionLabelId(option), name: name || _this._id, required: required });
return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_ChoiceGroupOption_index__WEBPACK_IMPORTED_MODULE_4__["ChoiceGroupOption"], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ key: option.key, onBlur: _this._onBlur, onFocus: _this._onFocus(option.key), onChange: _this._onChange(option.key) }, innerOptionProps)));
})))));
};
ChoiceGroupBase.prototype.focus = function () {
var _a = this.props.options, options = _a === void 0 ? [] : _a;
var optionToFocus = this.checkedOption || options.filter(function (option) { return !option.disabled; })[0];
var elementToFocus = optionToFocus && document.getElementById(this._getOptionId(optionToFocus));
if (elementToFocus) {
elementToFocus.focus();
}
};
ChoiceGroupBase.prototype._onFocus = function (key) {
var _this = this;
// This extra mess is necessary because React won't pass the `key` prop through to ChoiceGroupOption
if (!this._focusCallbacks[key]) {
this._focusCallbacks[key] = function (ev, option) {
_this.setState({
keyFocused: key,
});
};
}
return this._focusCallbacks[key];
};
ChoiceGroupBase.prototype._onChange = function (key) {
var _this = this;
// This extra mess is necessary because React won't pass the `key` prop through to ChoiceGroupOption
if (!this._changeCallbacks[key]) {
this._changeCallbacks[key] = function (evt, option) {
// eslint-disable-next-line deprecation/deprecation
var _a = _this.props, onChanged = _a.onChanged, onChange = _a.onChange;
// Only manage state in uncontrolled scenarios.
if (!_isControlled(_this.props)) {
_this.setState({
keyChecked: key,
});
}
// Get the original option without the `key` prop removed
var originalOption = Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["find"])(_this.props.options || [], function (value) { return value.key === key; });
// TODO: onChanged deprecated, remove else if after 07/17/2017 when onChanged has been removed.
if (onChange) {
onChange(evt, originalOption);
}
else if (onChanged) {
onChanged(originalOption, evt);
}
};
}
return this._changeCallbacks[key];
};
/**
* Returns `selectedKey` if provided, or the key of the first option with the `checked` prop set.
*/
ChoiceGroupBase.prototype._getKeyChecked = function (props) {
if (props.selectedKey !== undefined) {
return props.selectedKey;
}
var _a = props.options, options = _a === void 0 ? [] : _a;
// eslint-disable-next-line deprecation/deprecation
var optionsChecked = options.filter(function (option) { return option.checked; });
return optionsChecked[0] && optionsChecked[0].key;
};
ChoiceGroupBase.prototype._getOptionId = function (option) {
return option.id || this._id + "-" + option.key;
};
ChoiceGroupBase.prototype._getOptionLabelId = function (option) {
return option.labelId || this._labelId + "-" + option.key;
};
return ChoiceGroupBase;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
function _isControlled(props) {
return Object(_Utilities__WEBPACK_IMPORTED_MODULE_3__["isControlled"])(props, 'selectedKey');
}
//# sourceMappingURL=ChoiceGroup.base.js.map
/***/ }),
/***/ "Abs4":
/*!************************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroup.styles.js ***!
\************************************************************************************************************************************************************************************************************/
/*! exports provided: getStyles */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; });
/* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Styling */ "PL71");
var GlobalClassNames = {
root: 'ms-ChoiceFieldGroup',
flexContainer: 'ms-ChoiceFieldGroup-flexContainer',
};
var getStyles = function (props) {
var className = props.className, optionsContainIconOrImage = props.optionsContainIconOrImage, theme = props.theme;
var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_0__["getGlobalClassNames"])(GlobalClassNames, theme);
return {
// TODO (Fabric 8?) - merge className back into `root` and apply root style to
// the actual root role=application element
applicationRole: className,
root: [
classNames.root,
theme.fonts.medium,
{
display: 'block',
},
],
flexContainer: [
classNames.flexContainer,
optionsContainIconOrImage && {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
},
],
};
};
//# sourceMappingURL=ChoiceGroup.styles.js.map
/***/ }),
/***/ "B3UY":
/*!*****************************************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroupOption/ChoiceGroupOption.js ***!
\*****************************************************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroupOption */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupOption", function() { return ChoiceGroupOption; });
/* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Utilities */ "mkpW");
/* harmony import */ var _ChoiceGroupOption_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ChoiceGroupOption.base */ "Qtdd");
/* harmony import */ var _ChoiceGroupOption_styles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ChoiceGroupOption.styles */ "zJK0");
var ChoiceGroupOption = Object(_Utilities__WEBPACK_IMPORTED_MODULE_0__["styled"])(_ChoiceGroupOption_base__WEBPACK_IMPORTED_MODULE_1__["ChoiceGroupOptionBase"], _ChoiceGroupOption_styles__WEBPACK_IMPORTED_MODULE_2__["getStyles"], undefined, { scope: 'ChoiceGroupOption' });
//# sourceMappingURL=ChoiceGroupOption.js.map
/***/ }),
/***/ "CaTI":
/*!*****************************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroupOption/index.js ***!
\*****************************************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroupOption */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ChoiceGroupOption__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ChoiceGroupOption */ "B3UY");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupOption", function() { return _ChoiceGroupOption__WEBPACK_IMPORTED_MODULE_0__["ChoiceGroupOption"]; });
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "HVOw":
/*!******************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/ChoiceGroup.js ***!
\******************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroup, ChoiceGroupBase, ChoiceGroupOption */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _components_ChoiceGroup_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/ChoiceGroup/index */ "S6rZ");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroup", function() { return _components_ChoiceGroup_index__WEBPACK_IMPORTED_MODULE_0__["ChoiceGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupBase", function() { return _components_ChoiceGroup_index__WEBPACK_IMPORTED_MODULE_0__["ChoiceGroupBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupOption", function() { return _components_ChoiceGroup_index__WEBPACK_IMPORTED_MODULE_0__["ChoiceGroupOption"]; });
//# sourceMappingURL=ChoiceGroup.js.map
/***/ }),
/***/ "Qtdd":
/*!**********************************************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroupOption/ChoiceGroupOption.base.js ***!
\**********************************************************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroupOptionBase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupOptionBase", function() { return ChoiceGroupOptionBase; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "17wl");
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(tslib__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "cDcd");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Image__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Image */ "pw9o");
/* harmony import */ var _Icon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Icon */ "56LG");
/* harmony import */ var _Icon__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_Icon__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Utilities */ "mkpW");
/* harmony import */ var _uifabric_utilities__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @uifabric/utilities */ "P2cQ");
/* harmony import */ var _uifabric_utilities__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_uifabric_utilities__WEBPACK_IMPORTED_MODULE_5__);
var getClassNames = Object(_Utilities__WEBPACK_IMPORTED_MODULE_4__["classNamesFunction"])();
var LARGE_IMAGE_SIZE = 71;
/**
* {@docCategory ChoiceGroup}
*/
var ChoiceGroupOptionBase = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ChoiceGroupOptionBase, _super);
function ChoiceGroupOptionBase(props) {
var _this = _super.call(this, props) || this;
_this._onChange = function (evt) {
var onChange = _this.props.onChange;
if (onChange) {
onChange(evt, _this.props);
}
};
_this._onBlur = function (evt) {
var onBlur = _this.props.onBlur;
if (onBlur) {
onBlur(evt, _this.props);
}
};
_this._onFocus = function (evt) {
var onFocus = _this.props.onFocus;
if (onFocus) {
onFocus(evt, _this.props);
}
};
_this._onRenderField = function (props) {
var id = props.id, imageSrc = props.imageSrc, _a = props.imageAlt, imageAlt = _a === void 0 ? '' : _a, selectedImageSrc = props.selectedImageSrc, iconProps = props.iconProps;
var imageSize = props.imageSize ? props.imageSize : { width: 32, height: 32 };
var onRenderLabel = props.onRenderLabel
? Object(_uifabric_utilities__WEBPACK_IMPORTED_MODULE_5__["composeRenderFunction"])(props.onRenderLabel, _this._onRenderLabel)
: _this._onRenderLabel;
var label = onRenderLabel(props);
return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("label", { htmlFor: id, className: _this._classNames.field },
imageSrc && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.innerField },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.imageWrapper },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Image__WEBPACK_IMPORTED_MODULE_2__["Image"], { src: imageSrc, alt: imageAlt, width: imageSize.width, height: imageSize.height })),
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.selectedImageWrapper },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Image__WEBPACK_IMPORTED_MODULE_2__["Image"], { src: selectedImageSrc, alt: imageAlt, width: imageSize.width, height: imageSize.height })))),
iconProps && (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.innerField },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.iconWrapper },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_Icon__WEBPACK_IMPORTED_MODULE_3__["Icon"], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, iconProps))))),
imageSrc || iconProps ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: _this._classNames.labelWrapper }, label) : label));
};
_this._onRenderLabel = function (props) {
return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { id: props.labelId, className: "ms-ChoiceFieldLabel" }, props.text));
};
Object(_Utilities__WEBPACK_IMPORTED_MODULE_4__["initializeComponentRef"])(_this);
return _this;
}
ChoiceGroupOptionBase.prototype.render = function () {
var _a = this.props, ariaLabel = _a.ariaLabel, focused = _a.focused, required = _a.required, theme = _a.theme, iconProps = _a.iconProps, imageSrc = _a.imageSrc, imageSize = _a.imageSize, disabled = _a.disabled,
// eslint-disable-next-line deprecation/deprecation
checked = _a.checked, id = _a.id, styles = _a.styles, name = _a.name, _b = _a.onRenderField, onRenderField = _b === void 0 ? this._onRenderField : _b, rest = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"])(_a, ["ariaLabel", "focused", "required", "theme", "iconProps", "imageSrc", "imageSize", "disabled", "checked", "id", "styles", "name", "onRenderField"]);
this._classNames = getClassNames(styles, {
theme: theme,
hasIcon: !!iconProps,
hasImage: !!imageSrc,
checked: checked,
disabled: disabled,
imageIsLarge: !!imageSrc && (imageSize.width > LARGE_IMAGE_SIZE || imageSize.height > LARGE_IMAGE_SIZE),
imageSize: imageSize,
focused: focused,
});
var _c = Object(_Utilities__WEBPACK_IMPORTED_MODULE_4__["getNativeProps"])(rest, _Utilities__WEBPACK_IMPORTED_MODULE_4__["inputProperties"]), className = _c.className, nativeProps = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__rest"])(_c, ["className"]);
return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this._classNames.root },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this._classNames.choiceFieldWrapper },
react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("input", Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ "aria-label": ariaLabel, id: id, className: Object(_Utilities__WEBPACK_IMPORTED_MODULE_4__["css"])(this._classNames.input, className), type: "radio", name: name, disabled: disabled, checked: checked, required: required }, nativeProps, { onChange: this._onChange, onFocus: this._onFocus, onBlur: this._onBlur })),
onRenderField(this.props, this._onRenderField))));
};
ChoiceGroupOptionBase.defaultProps = {
// This ensures default imageSize value doesn't mutate. Mutation can cause style re-calcuation.
imageSize: { width: 32, height: 32 },
};
return ChoiceGroupOptionBase;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));
//# sourceMappingURL=ChoiceGroupOption.base.js.map
/***/ }),
/***/ "S6rZ":
/*!***********************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/index.js ***!
\***********************************************************************************************************************************************************************************************/
/*! exports provided: ChoiceGroup, ChoiceGroupBase, ChoiceGroupOption */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ChoiceGroup__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ChoiceGroup */ "0zH+");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroup", function() { return _ChoiceGroup__WEBPACK_IMPORTED_MODULE_0__["ChoiceGroup"]; });
/* harmony import */ var _ChoiceGroup_base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ChoiceGroup.base */ "4Qri");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupBase", function() { return _ChoiceGroup_base__WEBPACK_IMPORTED_MODULE_1__["ChoiceGroupBase"]; });
/* harmony import */ var _ChoiceGroupOption_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ChoiceGroupOption/index */ "CaTI");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChoiceGroupOption", function() { return _ChoiceGroupOption_index__WEBPACK_IMPORTED_MODULE_2__["ChoiceGroupOption"]; });
//# sourceMappingURL=index.js.map
/***/ }),
/***/ "pw9o":
/*!************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/Image.js ***!
\************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _microsoft_office_ui_fabric_react_bundle__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @microsoft/office-ui-fabric-react-bundle */ "KL1q");
/* harmony import */ var _microsoft_office_ui_fabric_react_bundle__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_microsoft_office_ui_fabric_react_bundle__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _microsoft_office_ui_fabric_react_bundle__WEBPACK_IMPORTED_MODULE_0__) if(["default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _microsoft_office_ui_fabric_react_bundle__WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
// Loading office-ui-fabric-react/./lib/Image.js
/***/ }),
/***/ "zJK0":
/*!************************************************************************************************************************************************************************************************************************************!*\
!*** /agent/_work/1/s/common/temp/node_modules/.pnpm/office-ui-fabric-react@7.156.0_baa7aab8a1d5d20fe3858de8537800ba/node_modules/office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroupOption/ChoiceGroupOption.styles.js ***!
\************************************************************************************************************************************************************************************************************************************/
/*! exports provided: getStyles */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStyles", function() { return getStyles; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "17wl");
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(tslib__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Styling__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Styling */ "PL71");
/* harmony import */ var _Utilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Utilities */ "mkpW");
var GlobalClassNames = {
root: 'ms-ChoiceField',
choiceFieldWrapper: 'ms-ChoiceField-wrapper',
input: 'ms-ChoiceField-input',
field: 'ms-ChoiceField-field',
innerField: 'ms-ChoiceField-innerField',
imageWrapper: 'ms-ChoiceField-imageWrapper',
iconWrapper: 'ms-ChoiceField-iconWrapper',
labelWrapper: 'ms-ChoiceField-labelWrapper',
checked: 'is-checked',
};
var labelWrapperLineHeight = 15;
var labelWrapperHeight = labelWrapperLineHeight * 2 + 2; // adding 2px height to ensure text doesn't get cutoff
var iconSize = 32;
var choiceFieldSize = 20;
var choiceFieldTransitionDuration = '200ms';
var choiceFieldTransitionTiming = 'cubic-bezier(.4, 0, .23, 1)';
var radioButtonSpacing = 3;
var radioButtonInnerSize = 5;
function getChoiceGroupFocusStyle(focusBorderColor, hasIconOrImage) {
var _a, _b;
return [
'is-inFocus',
{
selectors: (_a = {},
_a["." + _Utilities__WEBPACK_IMPORTED_MODULE_2__["IsFocusVisibleClassName"] + " &"] = {
position: 'relative',
outline: 'transparent',
selectors: {
'::-moz-focus-inner': {
border: 0,
},
':after': {
content: '""',
top: -2,
right: -2,
bottom: -2,
left: -2,
pointerEvents: 'none',
border: "1px solid " + focusBorderColor,
position: 'absolute',
selectors: (_b = {},
_b[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
borderColor: 'WindowText',
borderWidth: hasIconOrImage ? 1 : 2,
},
_b),
},
},
},
_a),
},
];
}
function getImageWrapperStyle(isSelectedImageWrapper, className, checked) {
return [
className,
{
paddingBottom: 2,
transitionProperty: 'opacity',
transitionDuration: choiceFieldTransitionDuration,
transitionTimingFunction: 'ease',
selectors: {
'.ms-Image': {
display: 'inline-block',
borderStyle: 'none',
},
},
},
(checked ? !isSelectedImageWrapper : isSelectedImageWrapper) && [
'is-hidden',
{
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: '100%',
overflow: 'hidden',
opacity: 0,
},
],
];
}
var getStyles = function (props) {
var _a, _b, _c, _d, _e;
var theme = props.theme, hasIcon = props.hasIcon, hasImage = props.hasImage, checked = props.checked, disabled = props.disabled, imageIsLarge = props.imageIsLarge, focused = props.focused, imageSize = props.imageSize;
var palette = theme.palette, semanticColors = theme.semanticColors, fonts = theme.fonts;
var classNames = Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["getGlobalClassNames"])(GlobalClassNames, theme);
// Tokens
// TODO: after updating the semanticColors slots mapping this needs to be semanticColors.smallInputBorder
var circleBorderColor = palette.neutralPrimary;
var circleHoveredBorderColor = semanticColors.inputBorderHovered;
var circleCheckedBorderColor = semanticColors.inputBackgroundChecked;
// TODO: after updating the semanticColors slots mapping this needs to be semanticColors.inputBackgroundCheckedHovered
var circleCheckedHoveredBorderColor = palette.themeDark;
var circleDisabledBorderColor = semanticColors.disabledBodySubtext;
var circleBackgroundColor = semanticColors.bodyBackground;
var dotUncheckedHoveredColor = palette.neutralSecondary;
var dotCheckedColor = semanticColors.inputBackgroundChecked;
// TODO: after updating the semanticColors slots mapping this needs to be semanticColors.inputBackgroundCheckedHovered
var dotCheckedHoveredColor = palette.themeDark;
var dotDisabledColor = semanticColors.disabledBodySubtext;
// TODO: after updating the semanticColors slots mapping this needs to be semanticColors.bodyTextChecked
var labelHoverFocusColor = palette.neutralDark;
var focusBorderColor = semanticColors.focusBorder;
var iconOrImageChoiceBorderUncheckedHoveredColor = semanticColors.inputBorderHovered;
// TODO: after updating the semanticColors slots mapping this needs to be semanticColors.inputBackgroundCheckedHovered
var iconOrImageChoiceBorderCheckedColor = semanticColors.inputBackgroundChecked;
var iconOrImageChoiceBorderCheckedHoveredColor = palette.themeDark;
var iconOrImageChoiceBackgroundColor = palette.neutralLighter;
var fieldHoverOrFocusProperties = {
selectors: {
'.ms-ChoiceFieldLabel': {
color: labelHoverFocusColor,
},
':before': {
borderColor: checked ? circleCheckedHoveredBorderColor : circleHoveredBorderColor,
},
':after': [
!hasIcon &&
!hasImage &&
!checked && {
content: '""',
transitionProperty: 'background-color',
left: 5,
top: 5,
width: 10,
height: 10,
backgroundColor: dotUncheckedHoveredColor,
},
checked && {
borderColor: dotCheckedHoveredColor,
},
],
},
};
var enabledFieldWithImageHoverOrFocusProperties = {
borderColor: checked ? iconOrImageChoiceBorderCheckedHoveredColor : iconOrImageChoiceBorderUncheckedHoveredColor,
selectors: {
':before': {
opacity: 1,
borderColor: checked ? circleCheckedHoveredBorderColor : circleHoveredBorderColor,
},
},
};
var circleAreaProperties = [
{
content: '""',
display: 'inline-block',
backgroundColor: circleBackgroundColor,
borderWidth: 1,
borderStyle: 'solid',
borderColor: circleBorderColor,
width: choiceFieldSize,
height: choiceFieldSize,
fontWeight: 'normal',
position: 'absolute',
top: 0,
left: 0,
boxSizing: 'border-box',
transitionProperty: 'border-color',
transitionDuration: choiceFieldTransitionDuration,
transitionTimingFunction: choiceFieldTransitionTiming,
borderRadius: '50%',
},
disabled && {
borderColor: circleDisabledBorderColor,
selectors: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])((_a = {}, _a[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
borderColor: 'GrayText',
background: 'Window',
}, _a), Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["getEdgeChromiumNoHighContrastAdjustSelector"])()),
},
checked && {
borderColor: disabled ? circleDisabledBorderColor : circleCheckedBorderColor,
selectors: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])((_b = {}, _b[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
borderColor: 'Highlight',
background: 'Window',
}, _b), Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["getEdgeChromiumNoHighContrastAdjustSelector"])()),
},
(hasIcon || hasImage) && {
top: radioButtonSpacing,
right: radioButtonSpacing,
left: 'auto',
opacity: checked ? 1 : 0,
},
];
var dotAreaProperties = [
{
content: '""',
width: 0,
height: 0,
borderRadius: '50%',
position: 'absolute',
left: choiceFieldSize / 2,
right: 0,
transitionProperty: 'border-width',
transitionDuration: choiceFieldTransitionDuration,
transitionTimingFunction: choiceFieldTransitionTiming,
boxSizing: 'border-box',
},
checked && {
borderWidth: 5,
borderStyle: 'solid',
borderColor: disabled ? dotDisabledColor : dotCheckedColor,
left: 5,
top: 5,
width: 10,
height: 10,
selectors: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])((_c = {}, _c[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
borderColor: 'Highlight',
}, _c), Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["getEdgeChromiumNoHighContrastAdjustSelector"])()),
},
checked &&
(hasIcon || hasImage) && {
top: radioButtonSpacing + radioButtonInnerSize,
right: radioButtonSpacing + radioButtonInnerSize,
left: 'auto',
},
];
return {
root: [
classNames.root,
theme.fonts.medium,
{
display: 'flex',
alignItems: 'center',
boxSizing: 'border-box',
color: semanticColors.bodyText,
minHeight: 26,
border: 'none',
position: 'relative',
marginTop: 8,
selectors: {
'.ms-ChoiceFieldLabel': {
display: 'inline-block',
},
},
},
!hasIcon &&
!hasImage && {
selectors: {
'.ms-ChoiceFieldLabel': {
paddingLeft: '26px',
},
},
},
hasImage && 'ms-ChoiceField--image',
hasIcon && 'ms-ChoiceField--icon',
(hasIcon || hasImage) && {
display: 'inline-flex',
fontSize: 0,
margin: '0 4px 4px 0',
paddingLeft: 0,
backgroundColor: iconOrImageChoiceBackgroundColor,
height: '100%',
},
],
choiceFieldWrapper: [
classNames.choiceFieldWrapper,
focused && getChoiceGroupFocusStyle(focusBorderColor, hasIcon || hasImage),
],
// The hidden input
input: [
classNames.input,
{
position: 'absolute',
opacity: 0,
top: 0,
right: 0,
width: '100%',
height: '100%',
margin: 0,
},
disabled && 'is-disabled',
],
field: [
classNames.field,
checked && classNames.checked,
{
display: 'inline-block',
cursor: 'pointer',
marginTop: 0,
position: 'relative',
verticalAlign: 'top',
userSelect: 'none',
minHeight: 20,
selectors: {
':hover': !disabled && fieldHoverOrFocusProperties,
':focus': !disabled && fieldHoverOrFocusProperties,
// The circle
':before': circleAreaProperties,
// The dot
':after': dotAreaProperties,
},
},
hasIcon && 'ms-ChoiceField--icon',
hasImage && 'ms-ChoiceField-field--image',
(hasIcon || hasImage) && {
boxSizing: 'content-box',
cursor: 'pointer',
paddingTop: 22,
margin: 0,
textAlign: 'center',
transitionProperty: 'all',
transitionDuration: choiceFieldTransitionDuration,
transitionTimingFunction: 'ease',
border: '1px solid transparent',
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
flexDirection: 'column',
},
checked && {
borderColor: iconOrImageChoiceBorderCheckedColor,
},
(hasIcon || hasImage) &&
!disabled && {
selectors: {
':hover': enabledFieldWithImageHoverOrFocusProperties,
':focus': enabledFieldWithImageHoverOrFocusProperties,
},
},
disabled && {
cursor: 'default',
selectors: {
'.ms-ChoiceFieldLabel': {
color: semanticColors.disabledBodyText,
selectors: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])((_d = {}, _d[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
color: 'GrayText',
}, _d), Object(_Styling__WEBPACK_IMPORTED_MODULE_1__["getEdgeChromiumNoHighContrastAdjustSelector"])()),
},
},
},
checked &&
disabled && {
borderColor: iconOrImageChoiceBackgroundColor,
},
],
innerField: [
classNames.innerField,
hasImage && {
// using non-null assertion because we have a default in `ChoiceGroupOptionBase` class.
height: imageSize.height,
width: imageSize.width,
},
(hasIcon || hasImage) && {
position: 'relative',
display: 'inline-block',
paddingLeft: 30,
paddingRight: 30,
},
(hasIcon || hasImage) &&
imageIsLarge && {
paddingLeft: 24,
paddingRight: 24,
},
(hasIcon || hasImage) &&
disabled && {
opacity: 0.25,
selectors: (_e = {},
_e[_Styling__WEBPACK_IMPORTED_MODULE_1__["HighContrastSelector"]] = {
color: 'GrayText',
opacity: 1,
},
_e),
},
],
imageWrapper: getImageWrapperStyle(false, classNames.imageWrapper, checked),
selectedImageWrapper: getImageWrapperStyle(true, classNames.imageWrapper, checked),
iconWrapper: [
classNames.iconWrapper,
{
fontSize: iconSize,
lineHeight: iconSize,
height: iconSize,
},
],
labelWrapper: [
classNames.labelWrapper,
fonts.medium,
(hasIcon || hasImage) && {
display: 'block',
position: 'relative',
margin: '4px 8px 2px 8px',
height: labelWrapperHeight,
lineHeight: labelWrapperLineHeight,
// using non-null assertion because we have a default in `ChoiceGroupOptionBase` class.
maxWidth: imageSize.width * 2,
overflow: 'hidden',
whiteSpace: 'pre-wrap',
},
],
};
};
//# sourceMappingURL=ChoiceGroupOption.styles.js.map
/***/ })
}]);
//# sourceMappingURL=chunk.8_[locale].js.map | 54.860412 | 446 | 0.582047 |
b1f9993552d6ae838404447e99451ce73a05f0eb | 12,886 | js | JavaScript | javascript/pacman.js | alexstaley/pacman-pdx | 81f2cdf89bc13bd6b9aeea3337eb7dfe4e2e2d08 | [
"MIT"
] | null | null | null | javascript/pacman.js | alexstaley/pacman-pdx | 81f2cdf89bc13bd6b9aeea3337eb7dfe4e2e2d08 | [
"MIT"
] | 2 | 2021-05-04T14:17:40.000Z | 2021-05-13T17:12:53.000Z | javascript/pacman.js | alexstaley/pacman-pdx | 81f2cdf89bc13bd6b9aeea3337eb7dfe4e2e2d08 | [
"MIT"
] | null | null | null | import { Character } from "./modules/sprites.js";
import { keyboard } from "./modules/keyboard.js";
import {
MAP_WIDTH,
MAP_HEIGHT,
map1,
map2,
map3,
TileIndices,
TileImages,
drawBackground,
getCoinRegistry,
getCloudsList,
containsWall,
getRandomHeading,
getPacManStartingCoords,
} from "./modules/maps.js";
// import { userName } from "./modules/logon.js";
const COIN_POINTS = 10; // Number of points awarded when Pac-Man picks up a coin
const BEER_POINTS = 50; // ...when Pac-Man picks up a beer
const ROSE_POINTS = 100; // ...when Pac-Man picks up a rose
const CLOUD_POINTS = 200; // ...when Pac-Man eats a cloud
const STARTING_LIVES = 3; // Number of extra lives Pac-Man starts with
const DRUNK_TIME = 420; // Number of ticks Pac-Man spends drunk (60 ticks/second)
let world = document.getElementById("world");
let board = document.getElementById("gameboard");
let playerScore = document.getElementById("scoreFrame");
let playerLives = document.getElementById("livesFrame");
let readyCount = document.getElementById("readyCount");
let endButton = document.getElementById("endButton");
let pauseButton = document.getElementById("pauseButton");
let upButton = document.getElementById("up-arrow-btn");
let downButton = document.getElementById("down-arrow-btn");
let leftButton = document.getElementById("left-arrow-btn");
let rightButton = document.getElementById("right-arrow-btn");
let grid = selectRandomMap();
let database = firebase.database();
function selectRandomMap() {
let min = 1;
let max = 3;
min = Math.ceil(min);
max = Math.floor(max);
switch(Math.floor(Math.random() * (max - min + 1) + min)){
case 1:
return map1;
break;
case 2:
return map2;
break;
case 3:
return map3;
break;
}
}
// Render background (logs, thorns, ground, decor/roses) in DOM
drawBackground(grid);
// Create pixiJS application using 'gameboard' canvas
const app = new PIXI.Application({
view: board,
width: world.offsetWidth,
height: world.offsetHeight,
resolution: window.devicePixelRatio,
autoDensity: true,
transparent: true,
});
// Create sprites and track coins and clouds
let characterList = createSprites(grid, window.innerWidth);
let coinsList = getCoinRegistry(grid);
let cloudsList = getCloudsList(characterList);
// Watch for window resize
window.addEventListener("resize", () => {
// Resize and remeasure canvas
app.renderer.resize(world.offsetWidth, world.offsetHeight);
// Resize and replace sprites. Recalibrate speed.
for (let ch in characterList) {
characterList[ch].resizeSprite(window.innerWidth);
characterList[ch].replaceSprite(app.renderer.screen);
characterList[ch].resetSpeed(window.innerWidth);
}
});
// Declare game variables
let pacman = characterList[getPacManStartingCoords(grid)];
let delta = 0;
let score = 0;
let extraLives = STARTING_LIVES;
let drunkDelta = 0;
let state = ready;
playerScore.innerHTML = "SCORE: " + score.toString();
playerLives.innerHTML = "LIVES: " + extraLives.toString();
// Define and listen for keyboard controls
let upKey = keyboard("ArrowUp");
let downKey = keyboard("ArrowDown");
let leftKey = keyboard("ArrowLeft");
let rightKey = keyboard("ArrowRight");
upKey.press = () => {
if (state == play) {
pacman.turnSprite("up");
}
};
downKey.press = () => {
if (state == play) {
pacman.turnSprite("down");
}
};
leftKey.press = () => {
if (state == play) {
pacman.turnSprite("left");
}
};
rightKey.press = () => {
if (state == play) {
pacman.turnSprite("right");
}
};
// Same for on-screen control buttons
upButton.onclick = () => {
if (state == play) {
pacman.turnSprite("up");
}
};
downButton.onclick = () => {
if (state == play) {
pacman.turnSprite("down");
}
};
leftButton.onclick = () => {
if (state == play) {
pacman.turnSprite("left");
}
};
rightButton.onclick = () => {
if (state == play) {
pacman.turnSprite("right");
}
};
// Listen for pause/end button clicks
pauseButton.onclick = () => {
if (state == play) {
state = pause;
} else if (state == pause) {
state = play;
}
};
endButton.onclick = () => {
state = end;
};
// Open game loop (in 'ready' state)
app.ticker.add(gameLoop);
function gameLoop() {
state();
}
/* Wait for 3 seconds, then transition to 'play' state
*/
function ready() {
++delta;
if (delta > 180) {
state = play;
delta = 0;
readyCount.innerHTML = "";
} else {
readyCount.innerHTML = `${Math.floor((180 - delta) / 60) + 1}`;
}
}
function pause() {
// Do nothing
}
function end(score){
// TODO: Send score to firebase
// database.ref('leaderboard/').set({
// score: score
// });
location.assign("leaderboard.html");
}
/* Move Pac-Man back to starting location
* and transition to 'ready' state
*/
function hit() {
pacman.relocateTo(pacman.origRow, pacman.origCol, app.renderer.screen);
// If a cloud occupies the respawn point, respawn
// pacman at that cloud's original coordinates.
cloudsList.forEach((cloud) => {
if (cloud.isTouching(pacman)) {
pacman.relocateTo(cloud.origRow, cloud.origCol, app.renderer.screen);
}
});
state = ready;
}
/* Move sprites, handle interactions during normal gameplay state
*/
function play() {
// TODO: Turn off "GO!" message after ~2 secs in play state
move();
getCoins();
getRoses();
getBeers();
collideWithCloud();
}
/* Move the character in the direction it's facing
*/
function move() {
// Move Pac-Man forward, update grid coords & drunk status
pacman.moveOn(grid, app.renderer.screen);
pacman.resetGridCoords(app.renderer.screen);
if (pacman.drunk) {
drunkDelta -= 1;
if (drunkDelta <= 0) {
pacman.soberUp();
cloudsList.forEach((cloud) => {
cloud.sprite.texture = PIXI.Texture.from(TileImages.CLOUD);
});
}
}
// Check for walk-thru-walls bug
try {
if (containsWall(grid, pacman.row, pacman.col)) {
pacman.backUp();
}
} catch (error) {
// Watch for out of bounds error from containsWall and hasAClearPath
if (pacman.row > MAP_HEIGHT - 1) {
pacman.relocateTo(0, pacman.col, app.renderer.screen);
}
}
// Move clouds forward and update grid coords
cloudsList.forEach((cloud) => {
cloud.moveOn(grid, app.renderer.screen);
cloud.resetGridCoords(app.renderer.screen);
// Check for walk-thru-walls bug
try {
if (containsWall(grid, cloud.row, cloud.col)) {
cloud.backUp();
cloud.heading = getRandomHeading();
}
if (
!cloud.pathWrapsAround(app.renderer.screen) &&
!cloud.hasAClearPath(grid)
) {
cloud.heading = getRandomHeading();
}
} catch (error) {
// Watch for out of bounds error from containsWall and hasAClearPath
if (cloud.row > MAP_HEIGHT - 1) {
cloud.relocateTo(0, cloud.col, app.renderer.screen);
}
}
});
}
/* Pick up coins. Coins become invisible, and the score and
* coinsList are updated. Check if the level has ended.
*/
function getCoins() {
let cell = `${pacman.row}-${pacman.col}`;
if (coinsList[cell]) {
// Pick up the coin and update ledgers
characterList[cell].sprite.visible = false;
coinsList[cell] = false;
coinsList.totalValue -= 1;
score += COIN_POINTS;
playerScore.innerHTML = "SCORE: " + score.toString();
}
// If all coins have been picked up, transition to 'end' state
if (coinsList.totalValue < 1) {
state = end;
}
}
/* Pick up rose tokens. Roses become invisible, and the score is updated.
*/
function getRoses() {
let cell = `${pacman.row}-${pacman.col}`;
if (
characterList[cell] &&
characterList[cell].sprite.visible &&
(characterList[cell].name == "rose" ||
characterList[cell].name == "rose-yellow" ||
characterList[cell].name == "rose-pink" ||
characterList[cell].name == "rose-gold" ||
characterList[cell].name == "rose-brown" ||
characterList[cell].name == "rose-white")
) {
// Pick up the rose and update score
characterList[cell].sprite.visible = false;
score += ROSE_POINTS;
playerScore.innerHTML = "SCORE: " + score.toString();
}
}
/* Pick up beer tokens. Beers become invisible, Pacman becomes drunk and clouds become edible.
*/
function getBeers() {
let cell = `${pacman.row}-${pacman.col}`;
if (
characterList[cell] &&
characterList[cell].sprite.visible &&
characterList[cell].name == "beer"
) {
characterList[cell].sprite.visible = false;
score += BEER_POINTS;
playerScore.innerHTML = "SCORE: " + score.toString();
drunkDelta = DRUNK_TIME;
pacman.getDrunk();
cloudsList.forEach((cloud) => {
cloud.sprite.texture = PIXI.Texture.from(TileImages.DRUNK_CLOUD);
});
}
}
/* Check the position of each cloud to determine
* if any of them are in contact with Pac-Man
*/
function collideWithCloud() {
cloudsList.forEach((cloud) => {
if (pacman.isTouching(cloud)) {
if (pacman.drunk) {
// Pac-Man eats the cloud
cloud.sprite.visible = false;
score += CLOUD_POINTS * pacman.cloudMultiplier;
playerScore.innerHTML = "SCORE: " + score.toString();
pacman.cloudMultiplier *= 2;
cloud.relocateTo(cloud.origRow, cloud.origCol, app.renderer.screen);
} else {
// The cloud eats Pac-Man
state = hit;
extraLives -= 1;
if (extraLives < 0) {
alert("GAME OVER");
state = end;
}
playerLives.innerHTML = "LIVES: " + extraLives.toString();
}
}
});
}
/* Initialize sprites according to the given map array.
* Returns a container object of characters indexed by "{row}-{col}".
*/
function createSprites(initMap, windowWidth) {
let characters = {};
let canvas = app.renderer.screen;
for (let r = 0; r < MAP_WIDTH; ++r) /*rows*/ {
for (let c = 0; c < MAP_HEIGHT; ++c) /*cols*/ {
switch (initMap[r][c]) {
case TileIndices.PAC_MAN:
let pacman = new Character(
TileImages.PAC_MAN,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(pacman.sprite);
characters[`${r}-${c}`] = pacman;
break;
case TileIndices.COIN:
let coin = new Character(TileImages.COIN, canvas, windowWidth, r, c);
app.stage.addChild(coin.sprite);
characters[`${r}-${c}`] = coin;
break;
case TileIndices.BEER:
let beer = new Character(TileImages.BEER, canvas, windowWidth, r, c);
app.stage.addChild(beer.sprite);
characters[`${r}-${c}`] = beer;
break;
case TileIndices.ROSE_RED:
let roseRed = new Character(
TileImages.ROSE_RED,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(roseRed.sprite);
characters[`${r}-${c}`] = roseRed;
break;
case TileIndices.ROSE_YELLOW:
let roseYellow = new Character(
TileImages.ROSE_YELLOW,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(roseYellow.sprite);
characters[`${r}-${c}`] = roseYellow;
break;
case TileIndices.ROSE_PINK:
let rosePink = new Character(
TileImages.ROSE_PINK,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(rosePink.sprite);
characters[`${r}-${c}`] = rosePink;
break;
case TileIndices.ROSE_GOLD:
let roseGold = new Character(
TileImages.ROSE_GOLD,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(roseGold.sprite);
characters[`${r}-${c}`] = roseGold;
break;
case TileIndices.ROSE_BROWN:
let roseBrown = new Character(
TileImages.ROSE_BROWN,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(roseBrown.sprite);
characters[`${r}-${c}`] = roseBrown;
break;
case TileIndices.ROSE_WHITE:
let roseWhite = new Character(
TileImages.ROSE_WHITE,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(roseWhite.sprite);
characters[`${r}-${c}`] = roseWhite;
break;
case TileIndices.CLOUD:
let cloud = new Character(
TileImages.CLOUD,
canvas,
windowWidth,
r,
c
);
app.stage.addChild(cloud.sprite);
characters[`${r}-${c}`] = cloud;
break;
}
}
}
return characters;
}
| 27.243129 | 94 | 0.608723 |
b1fa193565136bbcc9fb3d35ba73b8177269e9af | 3,244 | js | JavaScript | viewer/src/js/bar.js | hx/doc | 3dfefa94b097cdab7deacb0c45cf0104ac87d191 | [
"Apache-2.0"
] | 2 | 2016-02-29T16:07:46.000Z | 2017-04-10T18:10:13.000Z | viewer/src/js/bar.js | hx/doc | 3dfefa94b097cdab7deacb0c45cf0104ac87d191 | [
"Apache-2.0"
] | null | null | null | viewer/src/js/bar.js | hx/doc | 3dfefa94b097cdab7deacb0c45cf0104ac87d191 | [
"Apache-2.0"
] | null | null | null | var bar = (function(){
var $contents,
$contentsItems,
$searchContainer,
$searchInput,
index = {};
return function(){
var id,
appendToIndex = function() {
index[id].text += $(this).text().replace(/\s\s+/g, ' ').toLowerCase() + "\0";
},
querySplitPattern = /[^\w]+/,
lastCollapsedSet,
performSearch = function(query) {
query = $.trim(query || '');
if(query && !lastCollapsedSet)
lastCollapsedSet = $contentsItems.filter('.collapsed');
else if(!query && lastCollapsedSet) {
lastCollapsedSet
.not('.active, :has(.active)')
.addClass('collapsed')
.children('.listContainer')
.hide();
lastCollapsedSet = null;
}
$contents.toggleClass('searching', !!query);
$contentsItems.removeClass('hit containsHit');
if(query) {
searchTerms = query.toLowerCase().split(querySplitPattern);
$.each(index, searchSingleEntry);
}
},
searchTerms,
searchSingleEntry = function(id, data) {
var i = searchTerms.length;
while(i--)
if(searchTerms[i] && data.text.indexOf(searchTerms[i]) === -1)
return;
data.item
.addClass('hit')
.parents('ul.members > li')
.addClass('containsHit')
.expandMembers(true);
},
clearSearch = function() {
$searchInput.val('').blur();
performSearch();
};
($contents = $('.contents'))
.before('<div class="bar"><div class="persistent"><div class="search blank">' +
'<div><input placeholder="Search"/></div><a href="javascript:" title="Clear">' +
'<div></div></a></div><div class="dropdown"><a href="javascript:" ' +
'title="Show/hide options"><div></div></a></div></div></div>');
$contentsItems = $contents.find('ul.members > li');
$('.page').each(function(){
id = this.id;
index[id] = {
text: '',
item: $('a[href="#' + id + '"]', $contentsItems).parent()
};
$('h2 > .name, > .summary, > .details, > .remarks',
$(this).find('.overload')
.andSelf()
).each(appendToIndex);
});
$searchContainer = $('.bar .search');
$searchInput = $('.bar .search input')
.on('focus', function() {
$searchContainer.removeClass('blank');
})
.on('blur', function() {
$searchContainer.toggleClass('blank', !this.value);
})
.on('keyup', function(e) {
if(e.keyCode === 27)
clearSearch();
else
performSearch(e.target.value);
});
$searchContainer.find('a').on('click', clearSearch);
}
})(); | 30.895238 | 93 | 0.440814 |
b1fa944673cb05166a87f012d29fc8e32749440b | 4,071 | js | JavaScript | __sapper__/export/client/dark-mode.c807b94b.js | resourceldg/rockband | 0786d5d758cc0e87877f3c474d0e0f42f56cf005 | [
"MIT"
] | null | null | null | __sapper__/export/client/dark-mode.c807b94b.js | resourceldg/rockband | 0786d5d758cc0e87877f3c474d0e0f42f56cf005 | [
"MIT"
] | null | null | null | __sapper__/export/client/dark-mode.c807b94b.js | resourceldg/rockband | 0786d5d758cc0e87877f3c474d0e0f42f56cf005 | [
"MIT"
] | null | null | null | import{S as a,i as e,s,e as r,t,h as n,l as o,c as l,a as d,j as i,d as c,k as h,m as k,b as m,f,g,o as u,u as p,p as v,q as w,r as $,T as b,au as y}from"./client.7628e46f.js";import{C as E}from"./Code.4523955d.js";function S(a){let e,s,b,y,S,x,C,P,I,T,N,A,B,M,j,D,q,H,V,z,F,G,J,K,L,O,Q,R,U,W,X,Y,Z,_,aa,ea,sa,ra,ta=a[0]?"dark":"light";return T=new E({props:{code:"<button bind:value={$darkMode}>Toggle dark mode</button>"}}),H=new E({props:{code:'\nbackgroundColor: ["dark", "dark-hover", "hover"],\nborderColor: ["dark", "dark-focus"],\ntextColor: ["dark", "dark-hover", "dark-active"]\n'}}),X=new E({props:{code:'\n<div class="duration-200 ease-in p-10 my-10 bg-black dark:bg-white text-white dark:text-black">\n I am a {$darkMode ? "dark" : "light"} div.\n</div>\n'}}),{c(){e=r("h4"),s=t("Dark mode"),b=n(),y=r("p"),S=t("Smelte uses css pseudo-class variant\n "),x=r("a"),C=t("feature"),P=t("\n of Tailwind to enable dark mode. Basic dark mode switch looks like this:"),I=n(),o(T.$$.fragment),N=n(),A=r("p"),B=t("This will append\n "),M=r("span"),j=t("mode-dark"),D=t('\n class to the document body which will enable all generated classes preceded by\n pseudo-class "dark:". By default smelte generates following variants:'),q=n(),o(H.$$.fragment),V=n(),z=r("p"),F=t("Now you can use dark theme classes like\n "),G=r("span"),J=t("dark:bg-white"),K=t("\n (try using the theme toggle on the top right)."),L=n(),O=r("div"),Q=t("I am a "),R=t(ta),U=t(" div."),W=n(),o(X.$$.fragment),Y=n(),Z=r("p"),_=t("If you don't need dark mode at all, you can pass\n "),aa=r("span"),ea=t("darkMode: false"),sa=t("\n to the smelte-rollup-plugin and it will generate no extra CSS."),this.h()},l(a){e=l(a,"H4",{class:!0});var r=d(e);s=i(r,"Dark mode"),r.forEach(c),b=h(a),y=l(a,"P",{});var t=d(y);S=i(t,"Smelte uses css pseudo-class variant\n "),x=l(t,"A",{class:!0,href:!0});var n=d(x);C=i(n,"feature"),n.forEach(c),P=i(t,"\n of Tailwind to enable dark mode. Basic dark mode switch looks like this:"),t.forEach(c),I=h(a),k(T.$$.fragment,a),N=h(a),A=l(a,"P",{});var o=d(A);B=i(o,"This will append\n "),M=l(o,"SPAN",{class:!0});var m=d(M);j=i(m,"mode-dark"),m.forEach(c),D=i(o,'\n class to the document body which will enable all generated classes preceded by\n pseudo-class "dark:". By default smelte generates following variants:'),o.forEach(c),q=h(a),k(H.$$.fragment,a),V=h(a),z=l(a,"P",{});var f=d(z);F=i(f,"Now you can use dark theme classes like\n "),G=l(f,"SPAN",{class:!0});var g=d(G);J=i(g,"dark:bg-white"),g.forEach(c),K=i(f,"\n (try using the theme toggle on the top right)."),f.forEach(c),L=h(a),O=l(a,"DIV",{class:!0});var u=d(O);Q=i(u,"I am a "),R=i(u,ta),U=i(u," div."),u.forEach(c),W=h(a),k(X.$$.fragment,a),Y=h(a),Z=l(a,"P",{});var p=d(Z);_=i(p,"If you don't need dark mode at all, you can pass\n "),aa=l(p,"SPAN",{class:!0});var v=d(aa);ea=i(v,"darkMode: false"),v.forEach(c),sa=i(p,"\n to the smelte-rollup-plugin and it will generate no extra CSS."),p.forEach(c),this.h()},h(){m(e,"class","pb-8"),m(x,"class","a"),m(x,"href","https://tailwindcss.com/docs/configuring-variants/"),m(M,"class","code-inline"),m(G,"class","code-inline"),m(O,"class","duration-200 ease-in p-10 my-10 bg-black dark:bg-white text-white\n dark:text-black"),m(aa,"class","code-inline")},m(a,r){f(a,e,r),g(e,s),f(a,b,r),f(a,y,r),g(y,S),g(y,x),g(x,C),g(y,P),f(a,I,r),u(T,a,r),f(a,N,r),f(a,A,r),g(A,B),g(A,M),g(M,j),g(A,D),f(a,q,r),u(H,a,r),f(a,V,r),f(a,z,r),g(z,F),g(z,G),g(G,J),g(z,K),f(a,L,r),f(a,O,r),g(O,Q),g(O,R),g(O,U),f(a,W,r),u(X,a,r),f(a,Y,r),f(a,Z,r),g(Z,_),g(Z,aa),g(aa,ea),g(Z,sa),ra=!0},p(a,[e]){(!ra||1&e)&&ta!==(ta=a[0]?"dark":"light")&&p(R,ta)},i(a){ra||(v(T.$$.fragment,a),v(H.$$.fragment,a),v(X.$$.fragment,a),ra=!0)},o(a){w(T.$$.fragment,a),w(H.$$.fragment,a),w(X.$$.fragment,a),ra=!1},d(a){a&&c(e),a&&c(b),a&&c(y),a&&c(I),$(T,a),a&&c(N),a&&c(A),a&&c(q),$(H,a),a&&c(V),a&&c(z),a&&c(L),a&&c(O),a&&c(W),$(X,a),a&&c(Y),a&&c(Z)}}}function x(a,e,s){let r;return b(a,y,(a=>s(0,r=a))),[r]}export default class extends a{constructor(a){super(),e(this,a,x,S,s,{})}}
| 2,035.5 | 4,070 | 0.596659 |
b1fb4f520099ae02a19495b742fa455ec392df39 | 807 | js | JavaScript | src/utils/mediaQueries.js | elevaunt/realsissytalk-cms | f4d036337cdd885517a8f44886c9954fdc240e4a | [
"MIT"
] | null | null | null | src/utils/mediaQueries.js | elevaunt/realsissytalk-cms | f4d036337cdd885517a8f44886c9954fdc240e4a | [
"MIT"
] | null | null | null | src/utils/mediaQueries.js | elevaunt/realsissytalk-cms | f4d036337cdd885517a8f44886c9954fdc240e4a | [
"MIT"
] | null | null | null | import {breakpoints} from './variables'
export const mq = {
min: {
/** sm breakpoint: 640px */
sm: `@media (min-width: ${breakpoints.sm}px)`,
/** md breakpoint: 768px */
md: `@media (min-width: ${breakpoints.md}px)`,
/** lg breakpoint: 992px */
lg: `@media (min-width: ${breakpoints.lg}px)`,
/** xl breakpoint: 1200px */
xl: `@media (min-width: ${breakpoints.xl}px)`,
},
max: {
/** sm breakpoint: 640px - 1 */
sm: `@media (max-width: ${breakpoints.sm - 1}px)`,
/** md breakpoint: 768px - 1 */
md: `@media (max-width: ${breakpoints.md - 1}px)`,
/** lg breakpoint: 992px - 1 */
lg: `@media (max-width: ${breakpoints.lg - 1}px)`,
/** xl breakpoint: 1200px - 1 */
xl: `@media (max-width: ${breakpoints.xl - 1}px)`,
},
}
export default mq; | 32.28 | 54 | 0.557621 |
b1fb545931f6d80278196f2da27e5104c4a308b4 | 93 | js | JavaScript | nccloud/docs/html/search/files_6c.js | codingcai/degradedReadForEC | 4bf9c075d704fc116eda9a7a115ff9a13f1f59c9 | [
"BSD-3-Clause"
] | null | null | null | nccloud/docs/html/search/files_6c.js | codingcai/degradedReadForEC | 4bf9c075d704fc116eda9a7a115ff9a13f1f59c9 | [
"BSD-3-Clause"
] | null | null | null | nccloud/docs/html/search/files_6c.js | codingcai/degradedReadForEC | 4bf9c075d704fc116eda9a7a115ff9a13f1f59c9 | [
"BSD-3-Clause"
] | null | null | null | var searchData=
[
['list_5frepo_2ecc',['list_repo.cc',['../list__repo_8cc.html',1,'']]]
];
| 18.6 | 71 | 0.634409 |
b1fb706d0cb969f168ab8cc418a0ef734824000f | 295 | js | JavaScript | contextapp/src/components/ToggleTheme.js | mostafa1647/reactHooksAndContext | f750fae6e98fe74dc13784942e6626ece8ba3d9c | [
"MIT"
] | null | null | null | contextapp/src/components/ToggleTheme.js | mostafa1647/reactHooksAndContext | f750fae6e98fe74dc13784942e6626ece8ba3d9c | [
"MIT"
] | null | null | null | contextapp/src/components/ToggleTheme.js | mostafa1647/reactHooksAndContext | f750fae6e98fe74dc13784942e6626ece8ba3d9c | [
"MIT"
] | null | null | null | import React, { useContext } from 'react';
import {ThemeContext} from "../contexts/ThemeContext";
const ToggleTheme = () => {
const { toggleTheme } = useContext(ThemeContext);
return(
<button onClick={toggleTheme}>Toggle the Theme</button>
);
};
export default ToggleTheme; | 26.818182 | 63 | 0.677966 |
b1fbf41d68c49f06944e2d7ecd015c0410d9e1f8 | 220 | js | JavaScript | restana.js | PlexusOSS/framework-perf | e575c3753ac397ee191d112369e2e7f394949bcc | [
"MIT"
] | 1 | 2018-11-16T20:23:19.000Z | 2018-11-16T20:23:19.000Z | restana.js | PlexusOSS/framework-perf | e575c3753ac397ee191d112369e2e7f394949bcc | [
"MIT"
] | null | null | null | restana.js | PlexusOSS/framework-perf | e575c3753ac397ee191d112369e2e7f394949bcc | [
"MIT"
] | null | null | null | const service = require('restana')();
service.get('/', (req, res) => {
res.send({
msg: 'Hello Human!'
}, 200);
});
service.start(3000).then(() => {
console.log('Restana server listening on port 3000...')
});
| 18.333333 | 57 | 0.577273 |
b1fdc1273dc4c870a20167f3a9fa6b820e3e6045 | 24,316 | js | JavaScript | packages/page-accounts/build/Accounts/Account.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/page-accounts/build/Accounts/Account.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/page-accounts/build/Accounts/Account.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-2021 @axia-js/app-accounts authors & contributors
// SPDX-License-Identifier: Apache-2.0
import BN from 'bn.js';
import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import styled, { ThemeContext } from 'styled-components';
import { AddressInfo, AddressSmall, Badge, Button, ChainLock, CryptoType, ExpandButton, Forget, Icon, IdentityIcon, LinkExternal, Menu, Popup, StatusContext, Tags } from '@axia-js/react-components';
import { useAccountInfo, useApi, useBalancesAll, useBestNumber, useCall, useLedger, useStakingInfo, useToggle } from '@axia-js/react-hooks';
import { keyring } from '@axia-js/ui-keyring';
import { BN_ZERO, formatBalance, formatNumber, isFunction } from '@axia-js/util';
import Backup from "../modals/Backup.js";
import ChangePass from "../modals/ChangePass.js";
import DelegateModal from "../modals/Delegate.js";
import Derive from "../modals/Derive.js";
import IdentityMain from "../modals/IdentityMain.js";
import IdentitySub from "../modals/IdentitySub.js";
import MultisigApprove from "../modals/MultisigApprove.js";
import ProxyOverview from "../modals/ProxyOverview.js";
import RecoverAccount from "../modals/RecoverAccount.js";
import RecoverSetup from "../modals/RecoverSetup.js";
import Transfer from "../modals/Transfer.js";
import UndelegateModal from "../modals/Undelegate.js";
import { useTranslation } from "../translate.js";
import { createMenuGroup } from "../util.js";
import useMultisigApprovals from "./useMultisigApprovals.js";
import useProxies from "./useProxies.js";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
function calcVisible(filter, name, tags) {
if (filter.length === 0) {
return true;
}
const _filter = filter.toLowerCase();
return tags.reduce((result, tag) => {
return result || tag.toLowerCase().includes(_filter);
}, name.toLowerCase().includes(_filter));
}
function calcUnbonding(stakingInfo) {
if (!(stakingInfo !== null && stakingInfo !== void 0 && stakingInfo.unlocking)) {
return BN_ZERO;
}
const filtered = stakingInfo.unlocking.filter(({
remainingEras,
value
}) => value.gt(BN_ZERO) && remainingEras.gt(BN_ZERO)).map(unlock => unlock.value);
const total = filtered.reduce((total, value) => total.iadd(value), new BN(0));
return total;
}
function createClearDemocracyTx(api, address, unlockableIds) {
return api.tx.utility ? api.tx.utility.batch(unlockableIds.map(id => api.tx.democracy.removeVote(id)).concat(api.tx.democracy.unlock(address))) : null;
}
async function showLedgerAddress(getLedger, meta) {
const ledger = getLedger();
await ledger.getAddress(true, meta.accountOffset || 0, meta.addressOffset || 0);
}
const transformRecovery = {
transform: opt => opt.unwrapOr(null)
};
function Account({
account: {
address,
meta
},
className = '',
delegation,
filter,
isFavorite,
proxy,
setBalance,
toggleFavorite
}) {
var _api$api$derive$democ, _api$api$query$recove, _api$api$tx$balances;
const {
t
} = useTranslation();
const [isExpanded, toggleIsExpanded] = useToggle(false);
const {
theme
} = useContext(ThemeContext);
const {
queueExtrinsic
} = useContext(StatusContext);
const api = useApi();
const {
getLedger
} = useLedger();
const bestNumber = useBestNumber();
const balancesAll = useBalancesAll(address);
const stakingInfo = useStakingInfo(address);
const democracyLocks = useCall((_api$api$derive$democ = api.api.derive.democracy) === null || _api$api$derive$democ === void 0 ? void 0 : _api$api$derive$democ.locks, [address]);
const recoveryInfo = useCall((_api$api$query$recove = api.api.query.recovery) === null || _api$api$query$recove === void 0 ? void 0 : _api$api$query$recove.recoverable, [address], transformRecovery);
const multiInfos = useMultisigApprovals(address);
const proxyInfo = useProxies(address);
const {
flags: {
isDevelopment,
isEditable,
isExternal,
isHardware,
isInjected,
isMultisig,
isProxied
},
genesisHash,
identity,
name: accName,
onSetGenesisHash,
tags
} = useAccountInfo(address);
const [{
democracyUnlockTx
}, setUnlockableIds] = useState({
democracyUnlockTx: null,
ids: []
});
const [vestingVestTx, setVestingTx] = useState(null);
const [isBackupOpen, toggleBackup] = useToggle();
const [isDeriveOpen, toggleDerive] = useToggle();
const [isForgetOpen, toggleForget] = useToggle();
const [isIdentityMainOpen, toggleIdentityMain] = useToggle();
const [isIdentitySubOpen, toggleIdentitySub] = useToggle();
const [isMultisigOpen, toggleMultisig] = useToggle();
const [isProxyOverviewOpen, toggleProxyOverview] = useToggle();
const [isPasswordOpen, togglePassword] = useToggle();
const [isRecoverAccountOpen, toggleRecoverAccount] = useToggle();
const [isRecoverSetupOpen, toggleRecoverSetup] = useToggle();
const [isTransferOpen, toggleTransfer] = useToggle();
const [isDelegateOpen, toggleDelegate] = useToggle();
const [isUndelegateOpen, toggleUndelegate] = useToggle();
useEffect(() => {
if (balancesAll) {
var _stakingInfo$stakingL, _stakingInfo$redeemab, _api$api$tx$vesting;
setBalance(address, {
bonded: (_stakingInfo$stakingL = stakingInfo === null || stakingInfo === void 0 ? void 0 : stakingInfo.stakingLedger.active.unwrap()) !== null && _stakingInfo$stakingL !== void 0 ? _stakingInfo$stakingL : BN_ZERO,
locked: balancesAll.lockedBalance,
redeemable: (_stakingInfo$redeemab = stakingInfo === null || stakingInfo === void 0 ? void 0 : stakingInfo.redeemable) !== null && _stakingInfo$redeemab !== void 0 ? _stakingInfo$redeemab : BN_ZERO,
total: balancesAll.freeBalance.add(balancesAll.reservedBalance),
transferrable: balancesAll.availableBalance,
unbonding: calcUnbonding(stakingInfo)
});
((_api$api$tx$vesting = api.api.tx.vesting) === null || _api$api$tx$vesting === void 0 ? void 0 : _api$api$tx$vesting.vest) && setVestingTx(() => balancesAll.vestingLocked.isZero() ? null : api.api.tx.vesting.vest());
}
}, [address, api, balancesAll, setBalance, stakingInfo]);
useEffect(() => {
bestNumber && democracyLocks && setUnlockableIds(prev => {
const ids = democracyLocks.filter(({
isFinished,
unlockAt
}) => isFinished && bestNumber.gt(unlockAt)).map(({
referendumId
}) => referendumId);
if (JSON.stringify(prev.ids) === JSON.stringify(ids)) {
return prev;
}
return {
democracyUnlockTx: createClearDemocracyTx(api.api, address, ids),
ids
};
});
}, [address, api, bestNumber, democracyLocks]);
const isVisible = useMemo(() => calcVisible(filter, accName, tags), [accName, filter, tags]);
const _onFavorite = useCallback(() => toggleFavorite(address), [address, toggleFavorite]);
const _onForget = useCallback(() => {
if (!address) {
return;
}
const status = {
account: address,
action: 'forget'
};
try {
keyring.forgetAccount(address);
status.status = 'success';
status.message = t('account forgotten');
} catch (error) {
status.status = 'error';
status.message = error.message;
}
}, [address, t]);
const _clearDemocracyLocks = useCallback(() => democracyUnlockTx && queueExtrinsic({
accountId: address,
extrinsic: democracyUnlockTx
}), [address, democracyUnlockTx, queueExtrinsic]);
const _vestingVest = useCallback(() => vestingVestTx && queueExtrinsic({
accountId: address,
extrinsic: vestingVestTx
}), [address, queueExtrinsic, vestingVestTx]);
const _showOnHardware = useCallback( // TODO: we should check the hardwareType from metadata here as well,
// for now we are always assuming hardwareType === 'ledger'
() => {
showLedgerAddress(getLedger, meta).catch(error => {
console.error(`ledger: ${error.message}`);
});
}, [getLedger, meta]);
const menuItems = useMemo(() => {
var _api$api$tx$identity, _api$api$tx$identity2, _api$api$tx$democracy, _api$api$tx$vesting2, _api$api$tx$recovery, _api$api$tx$multisig, _api$api$query$democr, _api$api$query$democr2, _api$api$query$proxy;
return [createMenuGroup('identityGroup', [isFunction((_api$api$tx$identity = api.api.tx.identity) === null || _api$api$tx$identity === void 0 ? void 0 : _api$api$tx$identity.setIdentity) && !isHardware && /*#__PURE__*/_jsx(Menu.Item, {
icon: "link",
onClick: toggleIdentityMain,
children: t('Set on-chain identity')
}, 'identityMain'), isFunction((_api$api$tx$identity2 = api.api.tx.identity) === null || _api$api$tx$identity2 === void 0 ? void 0 : _api$api$tx$identity2.setSubs) && (identity === null || identity === void 0 ? void 0 : identity.display) && !isHardware && /*#__PURE__*/_jsx(Menu.Item, {
icon: "vector-square",
onClick: toggleIdentitySub,
children: t('Set on-chain sub-identities')
}, 'identitySub'), isFunction((_api$api$tx$democracy = api.api.tx.democracy) === null || _api$api$tx$democracy === void 0 ? void 0 : _api$api$tx$democracy.unlock) && democracyUnlockTx && /*#__PURE__*/_jsx(Menu.Item, {
icon: "broom",
onClick: _clearDemocracyLocks,
children: t('Clear expired democracy locks')
}, 'clearDemocracy'), isFunction((_api$api$tx$vesting2 = api.api.tx.vesting) === null || _api$api$tx$vesting2 === void 0 ? void 0 : _api$api$tx$vesting2.vest) && vestingVestTx && /*#__PURE__*/_jsx(Menu.Item, {
icon: "unlock",
onClick: _vestingVest,
children: t('Unlock vested amount')
}, 'vestingVest')], t('Identity')), createMenuGroup('deriveGroup', [!(isExternal || isHardware || isInjected || isMultisig) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "download",
onClick: toggleDerive,
children: t('Derive account via derivation path')
}, 'deriveAccount'), isHardware && /*#__PURE__*/_jsx(Menu.Item, {
icon: "eye",
onClick: _showOnHardware,
children: t('Show address on hardware device')
}, 'showHwAddress')], t('Derive')), createMenuGroup('backupGroup', [!(isExternal || isHardware || isInjected || isMultisig || isDevelopment) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "database",
onClick: toggleBackup,
children: t('Create a backup file for this account')
}, 'backupJson'), !(isExternal || isHardware || isInjected || isMultisig || isDevelopment) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "edit",
onClick: togglePassword,
children: t("Change this account's password")
}, 'changePassword'), !(isInjected || isDevelopment) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "trash-alt",
onClick: toggleForget,
children: t('Forget this account')
}, 'forgetAccount')], t('Backup')), isFunction((_api$api$tx$recovery = api.api.tx.recovery) === null || _api$api$tx$recovery === void 0 ? void 0 : _api$api$tx$recovery.createRecovery) && createMenuGroup('reoveryGroup', [!recoveryInfo && /*#__PURE__*/_jsx(Menu.Item, {
icon: "redo",
onClick: toggleRecoverSetup,
children: t('Make recoverable')
}, 'makeRecoverable'), /*#__PURE__*/_jsx(Menu.Item, {
icon: "screwdriver",
onClick: toggleRecoverAccount,
children: t('Initiate recovery for another')
}, 'initRecovery')], t('Recovery')), isFunction((_api$api$tx$multisig = api.api.tx.multisig) === null || _api$api$tx$multisig === void 0 ? void 0 : _api$api$tx$multisig.asMulti) && isMultisig && createMenuGroup('multisigGroup', [/*#__PURE__*/_jsx(Menu.Item, {
disabled: !multiInfos || !multiInfos.length,
icon: "file-signature",
onClick: toggleMultisig,
children: t('Multisig approvals')
}, 'multisigApprovals')], t('Multisig')), isFunction((_api$api$query$democr = api.api.query.democracy) === null || _api$api$query$democr === void 0 ? void 0 : _api$api$query$democr.votingOf) && (delegation === null || delegation === void 0 ? void 0 : delegation.accountDelegated) && createMenuGroup('undelegateGroup', [/*#__PURE__*/_jsx(Menu.Item, {
icon: "user-edit",
onClick: toggleDelegate,
children: t('Change democracy delegation')
}, 'changeDelegate'), /*#__PURE__*/_jsx(Menu.Item, {
icon: "user-minus",
onClick: toggleUndelegate,
children: t('Undelegate')
}, 'undelegate')], t('Undelegate')), createMenuGroup('delegateGroup', [isFunction((_api$api$query$democr2 = api.api.query.democracy) === null || _api$api$query$democr2 === void 0 ? void 0 : _api$api$query$democr2.votingOf) && !(delegation !== null && delegation !== void 0 && delegation.accountDelegated) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "user-plus",
onClick: toggleDelegate,
children: t('Delegate democracy votes')
}, 'delegate'), isFunction((_api$api$query$proxy = api.api.query.proxy) === null || _api$api$query$proxy === void 0 ? void 0 : _api$api$query$proxy.proxies) && /*#__PURE__*/_jsx(Menu.Item, {
icon: "sitemap",
onClick: toggleProxyOverview,
children: proxy !== null && proxy !== void 0 && proxy[0].length ? t('Manage proxies') : t('Add proxy')
}, 'proxy-overview')], t('Delegate')), isEditable && !api.isDevelopment && createMenuGroup('genesisGroup', [/*#__PURE__*/_jsx(ChainLock, {
className: "accounts--network-toggle",
genesisHash: genesisHash,
onChange: onSetGenesisHash
}, 'chainlock')])].filter(i => i);
}, [_clearDemocracyLocks, _showOnHardware, _vestingVest, api, delegation, democracyUnlockTx, genesisHash, identity, isDevelopment, isEditable, isExternal, isHardware, isInjected, isMultisig, multiInfos, onSetGenesisHash, proxy, recoveryInfo, t, toggleBackup, toggleDelegate, toggleDerive, toggleForget, toggleIdentityMain, toggleIdentitySub, toggleMultisig, togglePassword, toggleProxyOverview, toggleRecoverAccount, toggleRecoverSetup, toggleUndelegate, vestingVestTx]);
if (!isVisible) {
return null;
}
return /*#__PURE__*/_jsxs(_Fragment, {
children: [/*#__PURE__*/_jsxs("tr", {
className: `${className}${isExpanded ? ' noBorder' : ''}`,
children: [/*#__PURE__*/_jsx("td", {
className: "favorite",
children: /*#__PURE__*/_jsx(Icon, {
color: isFavorite ? 'orange' : 'gray',
icon: "star",
onClick: _onFavorite
})
}), /*#__PURE__*/_jsxs("td", {
className: "together",
children: [meta.genesisHash ? /*#__PURE__*/_jsx(Badge, {
color: "transparent"
}) : isDevelopment ? /*#__PURE__*/_jsx(Badge, {
className: "devBadge",
color: "orange",
hover: t('This is a development account derived from the known development seed. Do not use for any funds on a non-development network.'),
icon: "wrench"
}) : /*#__PURE__*/_jsx(Badge, {
color: "orange",
hover: /*#__PURE__*/_jsxs("div", {
children: [/*#__PURE__*/_jsx("p", {
children: t('This account is available on all networks. It is recommended to link to a specific network via the account options ("only this network" option) to limit availability. For accounts from an extension, set the network on the extension.')
}), /*#__PURE__*/_jsx("p", {
children: t('This does not send any transaction, rather is only sets the genesis in the account JSON.')
})]
}),
icon: "exclamation-triangle"
}), recoveryInfo && /*#__PURE__*/_jsx(Badge, {
color: "green",
hover: /*#__PURE__*/_jsxs("div", {
children: [/*#__PURE__*/_jsx("p", {
children: t('This account is recoverable, with the following friends:')
}), /*#__PURE__*/_jsx("div", {
children: recoveryInfo.friends.map((friend, index) => /*#__PURE__*/_jsx(IdentityIcon, {
value: friend
}, index))
}), /*#__PURE__*/_jsx("table", {
children: /*#__PURE__*/_jsxs("tbody", {
children: [/*#__PURE__*/_jsxs("tr", {
children: [/*#__PURE__*/_jsx("td", {
children: t('threshold')
}), /*#__PURE__*/_jsx("td", {
children: formatNumber(recoveryInfo.threshold)
})]
}), /*#__PURE__*/_jsxs("tr", {
children: [/*#__PURE__*/_jsx("td", {
children: t('delay')
}), /*#__PURE__*/_jsx("td", {
children: formatNumber(recoveryInfo.delayPeriod)
})]
}), /*#__PURE__*/_jsxs("tr", {
children: [/*#__PURE__*/_jsx("td", {
children: t('deposit')
}), /*#__PURE__*/_jsx("td", {
children: formatBalance(recoveryInfo.deposit)
})]
})]
})
})]
}),
icon: "shield"
}), multiInfos && multiInfos.length !== 0 && /*#__PURE__*/_jsx(Badge, {
color: "red",
hover: t('Multisig approvals pending'),
info: multiInfos.length
}), isProxied && !proxyInfo.hasOwned && /*#__PURE__*/_jsx(Badge, {
color: "red",
hover: t('Proxied account has no owned proxies'),
info: "0"
}), (delegation === null || delegation === void 0 ? void 0 : delegation.accountDelegated) && /*#__PURE__*/_jsx(Badge, {
color: "blue",
hover: t('This account has a governance delegation'),
icon: "calendar-check",
onClick: toggleDelegate
}), !!(proxy !== null && proxy !== void 0 && proxy[0].length) && api.api.tx.utility && /*#__PURE__*/_jsx(Badge, {
color: "blue",
hover: t('This account has {{proxyNumber}} proxy set.', {
replace: {
proxyNumber: proxy[0].length
}
}),
icon: "arrow-right",
onClick: toggleProxyOverview
})]
}), /*#__PURE__*/_jsxs("td", {
className: "address",
children: [/*#__PURE__*/_jsx(AddressSmall, {
parentAddress: meta.parentAddress,
value: address,
withShortAddress: true
}), isBackupOpen && /*#__PURE__*/_jsx(Backup, {
address: address,
onClose: toggleBackup
}, 'modal-backup-account'), isDelegateOpen && /*#__PURE__*/_jsx(DelegateModal, {
onClose: toggleDelegate,
previousAmount: delegation === null || delegation === void 0 ? void 0 : delegation.amount,
previousConviction: delegation === null || delegation === void 0 ? void 0 : delegation.conviction,
previousDelegatedAccount: delegation === null || delegation === void 0 ? void 0 : delegation.accountDelegated,
previousDelegatingAccount: address
}, 'modal-delegate'), isDeriveOpen && /*#__PURE__*/_jsx(Derive, {
from: address,
onClose: toggleDerive
}, 'modal-derive-account'), isForgetOpen && /*#__PURE__*/_jsx(Forget, {
address: address,
onClose: toggleForget,
onForget: _onForget
}, 'modal-forget-account'), isIdentityMainOpen && /*#__PURE__*/_jsx(IdentityMain, {
address: address,
onClose: toggleIdentityMain
}, 'modal-identity-main'), isIdentitySubOpen && /*#__PURE__*/_jsx(IdentitySub, {
address: address,
onClose: toggleIdentitySub
}, 'modal-identity-sub'), isPasswordOpen && /*#__PURE__*/_jsx(ChangePass, {
address: address,
onClose: togglePassword
}, 'modal-change-pass'), isTransferOpen && /*#__PURE__*/_jsx(Transfer, {
onClose: toggleTransfer,
senderId: address
}, 'modal-transfer'), isProxyOverviewOpen && /*#__PURE__*/_jsx(ProxyOverview, {
onClose: toggleProxyOverview,
previousProxy: proxy,
proxiedAccount: address
}, 'modal-proxy-overview'), isMultisigOpen && multiInfos && /*#__PURE__*/_jsx(MultisigApprove, {
address: address,
onClose: toggleMultisig,
ongoing: multiInfos,
threshold: meta.threshold,
who: meta.who
}, 'multisig-approve'), isRecoverAccountOpen && /*#__PURE__*/_jsx(RecoverAccount, {
address: address,
onClose: toggleRecoverAccount
}, 'recover-account'), isRecoverSetupOpen && /*#__PURE__*/_jsx(RecoverSetup, {
address: address,
onClose: toggleRecoverSetup
}, 'recover-setup'), isUndelegateOpen && /*#__PURE__*/_jsx(UndelegateModal, {
accountDelegating: address,
onClose: toggleUndelegate
}, 'modal-delegate')]
}), /*#__PURE__*/_jsx("td", {
className: "number",
children: /*#__PURE__*/_jsx(CryptoType, {
accountId: address
})
}), /*#__PURE__*/_jsx("td", {
className: "number media--1500",
children: (balancesAll === null || balancesAll === void 0 ? void 0 : balancesAll.accountNonce.gt(BN_ZERO)) && formatNumber(balancesAll.accountNonce)
}), /*#__PURE__*/_jsx("td", {
className: "number",
children: /*#__PURE__*/_jsx(AddressInfo, {
address: address,
balancesAll: balancesAll,
withBalance: {
available: false,
bonded: false,
locked: false,
redeemable: false,
reserved: false,
total: true,
unlocking: false,
vested: false
},
withExtended: false
})
}), /*#__PURE__*/_jsx("td", {
className: "fast-actions",
children: /*#__PURE__*/_jsxs("div", {
className: "fast-actions-row",
children: [/*#__PURE__*/_jsx(LinkExternal, {
className: "ui--AddressCard-exporer-link media--1400",
data: address,
isLogo: true,
type: "address"
}), isFunction((_api$api$tx$balances = api.api.tx.balances) === null || _api$api$tx$balances === void 0 ? void 0 : _api$api$tx$balances.transfer) && /*#__PURE__*/_jsx(Button, {
className: "send-button",
icon: "paper-plane",
label: t('send'),
onClick: toggleTransfer
}), /*#__PURE__*/_jsx(Popup, {
className: `theme--${theme}`,
isDisabled: !menuItems.length,
value: /*#__PURE__*/_jsx(Menu, {
children: menuItems
})
}), /*#__PURE__*/_jsx(ExpandButton, {
expanded: isExpanded,
onClick: toggleIsExpanded
})]
})
})]
}), /*#__PURE__*/_jsxs("tr", {
className: `${className} ${isExpanded ? 'isExpanded' : 'isCollapsed'}`,
children: [/*#__PURE__*/_jsx("td", {
colSpan: 2
}), /*#__PURE__*/_jsx("td", {
children: /*#__PURE__*/_jsx("div", {
className: "tags",
"data-testid": "tags",
children: /*#__PURE__*/_jsx(Tags, {
value: tags,
withTitle: true
})
})
}), /*#__PURE__*/_jsx("td", {
className: "media--1500"
}), /*#__PURE__*/_jsx("td", {}), /*#__PURE__*/_jsx("td", {
children: /*#__PURE__*/_jsx(AddressInfo, {
address: address,
balancesAll: balancesAll,
withBalance: {
available: true,
bonded: true,
locked: true,
redeemable: true,
reserved: true,
total: false,
unlocking: true,
vested: true
},
withExtended: false
})
}), /*#__PURE__*/_jsx("td", {
colSpan: 2
})]
})]
});
}
export default /*#__PURE__*/React.memo(styled(Account).withConfig({
displayName: "Account",
componentId: "sc-1phfxri-0"
})(["&.isCollapsed{visibility:collapse;}&.isExpanded{visibility:visible;}.tags{width:100%;min-height:1.5rem;}.devBadge{opacity:0.65;}&& td.button{padding-bottom:0.5rem;}&& td.fast-actions{padding-left:0.2rem;padding-right:1rem;width:1%;.fast-actions-row{display:flex;align-items:center;justify-content:flex-end;& > * + *{margin-left:0.35rem;}.send-button{min-width:6.5rem;}}}"])); | 46.140417 | 473 | 0.61951 |
b1fe82b77c1926ba20b49bda55807018e7575ade | 289 | js | JavaScript | models/mongodb.js | excalibur233/mind_kafka_customer | 1fdfe9b8e73f7b396bc0cee55f453a33a74ead5c | [
"MIT"
] | null | null | null | models/mongodb.js | excalibur233/mind_kafka_customer | 1fdfe9b8e73f7b396bc0cee55f453a33a74ead5c | [
"MIT"
] | null | null | null | models/mongodb.js | excalibur233/mind_kafka_customer | 1fdfe9b8e73f7b396bc0cee55f453a33a74ead5c | [
"MIT"
] | null | null | null | const config = require('../config/config');
const mongoose = require('mongoose');
module.exports = function () {
const mongodb = mongoose.connect(config.db_uri);
require('./register_log');
require('./authentication_log');
require('./login_log');
return mongodb;
};
| 20.642857 | 52 | 0.6609 |
b1fee60adfbffa21e0dac73bb3a9e403bb35c873 | 267 | js | JavaScript | models/DropModel.js | settlelol/discord-giveaway | 2b6895abaa6cbd496b45e8abaf2b167793b8f797 | [
"MIT"
] | 7 | 2021-04-05T09:43:36.000Z | 2021-09-09T00:40:53.000Z | models/DropModel.js | settlelol/discord-giveaway | 2b6895abaa6cbd496b45e8abaf2b167793b8f797 | [
"MIT"
] | 9 | 2021-03-24T00:03:15.000Z | 2021-12-01T07:13:41.000Z | models/DropModel.js | settlelol/discord-giveaway | 2b6895abaa6cbd496b45e8abaf2b167793b8f797 | [
"MIT"
] | 6 | 2021-05-02T15:05:41.000Z | 2021-09-25T17:06:29.000Z | const mongoose = require('mongoose');
const DropSchema = new mongoose.Schema({
guildId: String,
channelId: String,
prize: String,
createdBy: String,
timeCreated: Date,
position: Number
});
module.exports = mongoose.model('Drop', DropSchema); | 22.25 | 52 | 0.685393 |
b1fee61185a1361bef0fb699d6fcf9aee9c4482c | 94 | js | JavaScript | task-satisfier/src/executors/index.js | ceharris/cloudseam | 12567a63fadab53b718f50973250825c6bc3880f | [
"Apache-2.0"
] | 3 | 2019-02-01T19:45:22.000Z | 2019-11-19T21:32:19.000Z | task-satisfier/src/executors/index.js | ceharris/cloudseam | 12567a63fadab53b718f50973250825c6bc3880f | [
"Apache-2.0"
] | 21 | 2019-02-01T18:14:51.000Z | 2021-04-05T14:03:04.000Z | task-satisfier/src/executors/index.js | ceharris/cloudseam | 12567a63fadab53b718f50973250825c6bc3880f | [
"Apache-2.0"
] | 3 | 2020-08-14T13:46:05.000Z | 2021-04-05T14:04:18.000Z | module.exports = {
terraform: require('./terraform'),
lambda: require('./lambda'),
};
| 18.8 | 38 | 0.606383 |
b1ff7c746df8c1000a11c916704e7d5f0bdc75f2 | 4,446 | js | JavaScript | src/App/App.js | webosose/com.webos.app.volume | 583f9dadaaa96a23d085160f226e9c00afb2e668 | [
"Apache-2.0"
] | null | null | null | src/App/App.js | webosose/com.webos.app.volume | 583f9dadaaa96a23d085160f226e9c00afb2e668 | [
"Apache-2.0"
] | null | null | null | src/App/App.js | webosose/com.webos.app.volume | 583f9dadaaa96a23d085160f226e9c00afb2e668 | [
"Apache-2.0"
] | 1 | 2022-02-26T15:58:52.000Z | 2022-02-26T15:58:52.000Z | import AgateDecorator from '@enact/agate/AgateDecorator';
import ConsumerDecorator from '@enact/agate/data/ConsumerDecorator';
import ProviderDecorator from '@enact/agate/data/ProviderDecorator';
import Transition from '@enact/ui/Transition';
import PropTypes from 'prop-types';
import compose from 'ramda/src/compose';
import React from 'react';
import {
Audio,
cancelAllRequests,
requests,
cancelRequest
} from '../services';
import {getDisplayAffinity} from '../services/utils/displayAffinity';
import VolumeControls from '../views/VolumeControls';
import initialState from './initialState';
import css from './App.module.less';
const
delayTohide = 5000;
let hideTimerId = null;
const
clearHideTime = () => {
if (hideTimerId) {
clearTimeout(hideTimerId);
}
},
setHideTime = (update) => {
clearHideTime();
hideTimerId = setTimeout(() => {
update(state => {
state.app.visible.type = 'fade';
state.app.visible.volumeControl = false;
});
}, delayTohide);
};
const getMasterVolume = (update) => {
const currentDisplayId = getDisplayAffinity();
requests.getMasterVolume = Audio.getMasterVolume({
sessionId: currentDisplayId,
onSuccess: (res) => {
if (Object.prototype.hasOwnProperty.call(res,'volumeStatus') && res.returnValue) {
if (res.volumeStatus && res.volumeStatus.volume) {
update(state => {
state.volume.master = res.volumeStatus.volume;
});
} else {
/* eslint-disable-next-line no-console */
console.warn('check response', res);
}
}
},
onComplete: () => {
cancelRequest('getMasterVolume');
}
});
};
class AppBase extends React.Component {
static propTypes = {
onChangeVolume: PropTypes.func,
onHandleHide: PropTypes.func,
onHideVolumeControl: PropTypes.func,
setMasterVolumeToState: PropTypes.func,
volumeControlRunning: PropTypes.bool,
volumeControlType: PropTypes.string,
volumeControlVisible: PropTypes.bool
};
constructor (props) {
super(props);
this.state = {};
}
componentWillUnmount () {
cancelAllRequests();
}
hideTimerId = null;
resetStatus = () => {
this.setState({});
};
render () {
const {
onChangeVolume,
onHandleHide,
onHideVolumeControl,
volumeControlRunning,
volumeControlType,
volumeControlVisible,
...rest
} = this.props;
delete rest.setMasterVolume;
return (
<div {...rest} className={css.app}>
<Transition css={css} type="fade" visible={volumeControlVisible}>
<div className={css.basement} onClick={onHideVolumeControl} />
</Transition>
<Transition css={css} onHide={onHandleHide} type={volumeControlType} visible={volumeControlVisible}>
{volumeControlRunning ? <VolumeControls onChangeVolume={onChangeVolume} /> : null}
</Transition>
</div>
);
}
}
const AppDecorator = compose(
AgateDecorator({
noAutoFocus: true,
overlay: true
}),
ProviderDecorator({
state: initialState()
}),
ConsumerDecorator({
mount: (props, {update}) => {
const currentDisplayId = getDisplayAffinity();
document.title = `${document.title} - Display ${currentDisplayId}`;
getMasterVolume(update);
document.addEventListener('webOSLocaleChange', () => {
window.location.reload();
});
document.addEventListener('webOSRelaunch', () => {
getMasterVolume(update);
update(state => {
state.app.running = true;
state.app.visible.type = 'slide';
state.app.visible.volumeControl = true;
});
setHideTime(update);
});
update(state => {
state.app.running = true;
});
return () => {
clearHideTime();
};
},
handlers: {
onHandleHide: (ev, props, {update}) => {
update(state => {
state.app.visible.type = 'slide';
state.app.running = false;
});
window.close();
},
onChangeVolume: (ev, props, {update}) => {
setHideTime(update);
},
onHideVolumeControl: (ev, props, {update}) => {
update(state => {
state.app.visible.type = 'fade';
state.app.visible.volumeControl = false;
});
},
setMasterVolumeToState: (volume, props, {state, update}) => {
if (!state.app.touching) {
update(updateState => {
updateState.volume.master = volume;
});
}
}
},
mapStateToProps: ({app}) => ({
volumeControlRunning: app.running,
volumeControlType: app.visible.type,
volumeControlVisible: app.visible.volumeControl
})
})
);
const App = AppDecorator(AppBase);
export default App;
| 23.775401 | 104 | 0.667566 |