text
stringlengths 3
1.05M
|
|---|
"use strict";
// Copyright 2019 Google LLC
// 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.
Object.defineProperty(exports, "__esModule", { value: true });
/*! THIS FILE IS AUTO-GENERATED */
const googleapis_common_1 = require("googleapis-common");
const v1_1 = require("./v1");
exports.VERSIONS = {
'v1': v1_1.acceleratedmobilepageurl_v1.Acceleratedmobilepageurl,
};
function acceleratedmobilepageurl(versionOrOptions) {
return googleapis_common_1.getAPI('acceleratedmobilepageurl', versionOrOptions, exports.VERSIONS, this);
}
exports.acceleratedmobilepageurl = acceleratedmobilepageurl;
const auth = new googleapis_common_1.AuthPlus();
exports.auth = auth;
//# sourceMappingURL=index.js.map
|
import React from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import * as Yup from 'yup';
import { Formik } from 'formik';
import {
Box,
Button,
Container,
Grid,
Link,
TextField,
Typography,
makeStyles
} from '@material-ui/core';
import FacebookIcon from 'src/icons/Facebook';
import GoogleIcon from 'src/icons/Google';
import Page from 'src/components/Page';
import Firebase from 'c:/Users/GCBµ/Documents/node code/dashboardNext/src/config/firebase';
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: theme.palette.background.dark,
height: '100%',
paddingBottom: theme.spacing(3),
paddingTop: theme.spacing(3)
}
}));
const LoginView = () => {
const classes = useStyles();
const navigate = useNavigate();
const OnLoginButtonPressed = async (values) => {
const { email, password } = values;
try {
const response = await Firebase.loginWithEmail(email, password);
if (response.user) {
navigate('/app/dashboard', { replace: true });
}
} catch (error) {
console.error(error);
}
};
return (
<Page
className={classes.root}
title="Login"
>
<Box
display="flex"
flexDirection="column"
height="100%"
justifyContent="center"
>
<Container maxWidth="sm">
<Formik
initialValues={{
email: '',
password: ''
}}
validationSchema={Yup.object().shape({
email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
password: Yup.string().max(255).required('Password is required')
})}
onSubmit={(values) => {
OnLoginButtonPressed(values);
}}
>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
touched,
values
}) => (
<form onSubmit={handleSubmit}>
<Box mb={3}>
<Typography
color="textPrimary"
variant="h2"
>
Sign in
</Typography>
<Typography
color="textSecondary"
gutterBottom
variant="body2"
>
Sign in on the internal platform
</Typography>
</Box>
<Grid
container
spacing={3}
>
<Grid
item
xs={12}
md={6}
>
<Button
color="primary"
fullWidth
startIcon={<FacebookIcon />}
onClick={handleSubmit}
size="large"
variant="contained"
>
Login with Facebook
</Button>
</Grid>
<Grid
item
xs={12}
md={6}
>
<Button
fullWidth
startIcon={<GoogleIcon />}
onClick={handleSubmit}
size="large"
variant="contained"
>
Login with Google
</Button>
</Grid>
</Grid>
<Box
mt={3}
mb={1}
>
<Typography
align="center"
color="textSecondary"
variant="body1"
>
or login with email address
</Typography>
</Box>
<TextField
error={Boolean(touched.email && errors.email)}
fullWidth
helperText={touched.email && errors.email}
label="Email Address"
margin="normal"
name="email"
onBlur={handleBlur}
onChange={handleChange}
type="email"
value={values.email}
variant="outlined"
/>
<TextField
error={Boolean(touched.password && errors.password)}
fullWidth
helperText={touched.password && errors.password}
label="Password"
margin="normal"
name="password"
onBlur={handleBlur}
onChange={handleChange}
type="password"
value={values.password}
variant="outlined"
/>
<Box my={2}>
<Button
color="primary"
disabled={isSubmitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Sign in now
</Button>
</Box>
<Typography
color="textSecondary"
variant="body1"
>
Don't have an account?
{' '}
<Link
component={RouterLink}
to="/register"
variant="h6"
>
Sign up
</Link>
</Typography>
</form>
)}
</Formik>
</Container>
</Box>
</Page>
);
};
export default LoginView;
|
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2017, Battelle Memorial Institute.
#
# 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.
#
# This material was prepared as an account of work sponsored by an agency of
# the United States Government. Neither the United States Government nor the
# United States Department of Energy, nor Battelle, nor any of their
# employees, nor any jurisdiction or organization that has cooperated in the
# development of these materials, makes any warranty, express or
# implied, or assumes any legal liability or responsibility for the accuracy,
# completeness, or usefulness or any information, apparatus, product,
# software, or process disclosed, or represents that its use would not infringe
# privately owned rights. Reference herein to any specific commercial product,
# process, or service by trade name, trademark, manufacturer, or otherwise
# does not necessarily constitute or imply its endorsement, recommendation, or
# favoring by the United States Government or any agency thereof, or
# Battelle Memorial Institute. The views and opinions of authors expressed
# herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
#
# PACIFIC NORTHWEST NATIONAL LABORATORY operated by
# BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
# }}}
import pytest
from volttron.platform.agent.base_market_agent.point import Point
from volttron.platform.agent.base_market_agent.poly_line import PolyLine
from volttron.platform.agent.base_market_agent.buy_sell import BUYER, SELLER
from market_service.offer_manager import OfferManager
@pytest.mark.market
def test_offer_settle_no_intersection():
demand1 = create_demand_curve()
demand2 = create_demand_curve()
offer_manager = OfferManager()
offer_manager.make_offer(BUYER, demand1)
offer_manager.make_offer(SELLER, demand2)
quantity, price, aux = offer_manager.settle()
assert len(aux) == 4
def create_demand_curve():
demand_curve = PolyLine()
price = 0
quantity = 1000
demand_curve.add(Point(price,quantity))
price = 1000
quantity = 0
demand_curve.add(Point(price,quantity))
return demand_curve
|
import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
// import Utils from "@televisadigital/nxtv-utilities";
import { HeaderDropDown, LoginProfile, LogOut } from "../../items";
import { Anchor, Button, Icons, Form, Modal } from "../../accessories";
import Animate from "../../helpers/animate";
import navigation from "./navigation.json";
import {
HeaderStyles,
HeaderMobile,
HeaderGrid,
HeaderLogo,
HeaderLink,
HeaderSubLink,
HeaderLiveLink,
HeaderLinkContainer,
HeaderNavigation,
HeaderDinamic,
InnerSearch,
InnerSearchContainer,
InnerSearchBox,
InnerSearchInput,
HeaderLinkBox,
HeaderSocial,
OpenSearch,
SocialText,
LogoAnchor,
SearchStyles,
ArrowStyles,
} from "./styles";
const HeaderTUDN = ({ breadcrumbs, uri, logged }) => {
const [search, handleSearch] = useState(false);
const [menu, handleMenu] = useState(false);
const [modal, setModal] = useState(false);
return (
<HeaderStyles as="header" id="Header">
<Animate
animation={modal ? "FadeIn" : "FadeOut"}
duration="0.8s"
playState={modal ? "running" : "paused"}
style={{ zIndex: "10", position: "fixed" }}
>
<Modal active={modal} closebtn={false}>
<LogOut handleClose={() => setModal(!modal)} />
</Modal>
</Animate>
<HeaderMobile variant="Transparent" as="section">
<LogoAnchor>
<Icons color="#079F70" name="Deportes" size={120} variant="Transparent" />
</LogoAnchor>
<Animate
animation={menu ? "FadeIn" : "FadeOut"}
duration="0.8s"
playState={menu ? "running" : "paused"}
>
<Button
aria-label="Menu"
variant="Transparent"
onClick={() => {
handleMenu(true);
handleSearch(!search);
}}
>
<Icons color="#079F70" name="Menu" variant="Transparent" />
</Button>
</Animate>
</HeaderMobile>
<Animate
animation={menu ? "FadeIn" : "FadeOut"}
duration="0.8s"
playState={menu ? "running" : "paused"}
>
<HeaderGrid variant="Transparent" id="Navigation" active={menu}>
<HeaderLogo as="section" variant="Transparent" color={menu ? "gray" : null}>
<LogoAnchor href="/">
<Icons
color="#079F70"
name="Deportes"
size={120}
variant="Transparent"
/>
</LogoAnchor>
<Button
variant="Transparent"
onClick={() => {
handleMenu(false);
handleSearch(!search);
}}
m="0"
>
<Icons color="#079F70" name="Close" variant="Transparent" />
</Button>
</HeaderLogo>
<HeaderNavigation variant="Transparent" as="section">
<HeaderLinkContainer variant="Transparent" as="nav">
<HeaderLinkBox variant="Transparent">
{navigation.map(nav => {
let LinkTag;
if (nav.live) {
LinkTag = HeaderLiveLink;
} else if (nav.subnav) {
LinkTag = HeaderSubLink;
} else {
LinkTag = HeaderLink;
}
return (
<LinkTag
href={nav.path}
key={nav.name}
// active={breadcrumbs[0].uri === nav.path}
>
{nav.name}
</LinkTag>
);
})}
</HeaderLinkBox>
</HeaderLinkContainer>
<InnerSearch variant="Transparent" as="section">
<InnerSearchContainer variant="Transparent">
<InnerSearchBox variant="Transparent">
<Form>
<InnerSearchInput
placeholder="Buscar"
inputWidth="100%"
autoFocus
/>
</Form>
</InnerSearchBox>
{/* <Button variant="Transparent" aria-label="hamburger">
<Icons color="#079F70" name="Search" variant="Transparent" />
</Button> */}
</InnerSearchContainer>
{logged && <LoginProfile handleSession={setModal} />}
</InnerSearch>
</HeaderNavigation>
<HeaderDinamic variant="Transparent">
<HeaderDropDown
logged={logged}
active={search}
handleModal={() => handleSearch(!search)}
handleLoggedOut={() => setModal(!modal)}
/>
<SocialText>¿Ya nos sigues?</SocialText>
<HeaderSocial variant="Transparent" as="nav">
<Anchor href="./">
<Icons color="#fff" name="Facebook" variant="Transparent" />
</Anchor>
<Anchor href="./">
<Icons color="#fff" name="Twitter" variant="Transparent" />
</Anchor>
<Anchor href="./">
<Icons color="#fff" name="YouTube" variant="Transparent" />
</Anchor>
<Anchor href="./">
<Icons color="#fff" name="Instagram" variant="Transparent" />
</Anchor>
</HeaderSocial>
<OpenSearch variant="Flex">
<SearchStyles placeholder="Buscar" />
<Button variant="Transparent" onClick={() => handleSearch(!search)}>
<Icons
color="#464646"
name="Profile"
size={30}
variant="Transparent"
/>
</Button>
<ArrowStyles
color="#079F70"
name="Next"
size={15}
variant="Transparent"
/>
</OpenSearch>
</HeaderDinamic>
</HeaderGrid>
</Animate>
</HeaderStyles>
);
};
HeaderTUDN.propTypes = {
// breadcrumbs: PropTypes.arrayOf(
// PropTypes.shape({
// uri: PropTypes.string.isRequired,
// }),
// ).isRequired,
// uri: PropTypes.string.isRequired,
logged: PropTypes.bool,
};
HeaderTUDN.defaultProps = {
logged: true,
};
export default HeaderTUDN;
|
const express = require('express');
var bodyParser = require('body-parser');
const redis = require("redis");
const redisClient = redis.createClient(
15827,
"redis-15827.c264.ap-south-1-1.ec2.cloud.redislabs.com",
{ no_ready_check: true }
);
const route = require('./routes/route.js');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const mongoose = require('mongoose');
const { response } = require('express');
mongoose.connect("mongodb+srv://user-open-to-all:hiPassword123@cluster0.xgk0k.mongodb.net/group1PDAM-DB?retryWrites=true&w=majority")
.then(() => console.log('mongodb running on 27017'))
.catch(err => console.log(err))
app.use('/', route);
app.listen(process.env.PORT || 3000, function () {
console.log('Express app running on port ' + (process.env.PORT || 3000))
});
redisClient.auth("B319nmG7lHoNE5u3sDgBsQGsnWLYPzOk", function (err) {
if (err) throw err;
});
redisClient.on("connect", async function () {
console.log("Connected to Redis..");
});
|
// Copyright 2018 Jonah Snider
const { Command } = require('discord.js-commando');
const config = require('../../config');
const rp = require('request-promise-native');
const diceAPI = require('../../providers/diceAPI');
module.exports = class RefundTransactionCommand extends Command {
constructor(client) {
super(client, {
name: 'refund-transaction',
group: 'economy',
memberName: 'refund-transaction',
description: 'Refund a transaction on Discoin.',
aliases: ['refund', 'revert-transaction', 'revert'],
examples: ['refund-transaction e03f7f5b048414d8eadf9fd6e1245803b3c2da9a'],
clientPermissions: ['EMBED_LINKS'],
args: [{
key: 'receipt',
prompt: 'What is the receipt for the transaction you want to revert?',
type: 'string',
label: 'transaction receipt',
min: 40,
max: 40
}],
throttling: {
usages: 1,
duration: 30
},
ownerOnly: true
});
}
run(msg, { receipt }) {
try {
msg.channel.startTyping();
rp({
json: true,
method: 'POST',
url: 'http://discoin.sidetrip.xyz/transaction/reverse',
headers: { authorization: config.discoinToken },
resolveWithFullResponse: true,
body: { receipt: receipt }
})
.then(response => {
rp({
json: true,
method: 'GET',
url: `http://discoin.sidetrip.xyz/transaction/${receipt}`,
headers: { authorization: config.discoinToken },
resolveWithFullResponse: true,
body: { receipt: receipt }
})
.then(async transactionResponse => {
await diceAPI.increaseBalance(transactionResponse.body.user, response.body.refundAmount);
msg.replyEmbed({
title: '💱 Refund Successful',
color: 0x4caf50,
timestamp: new Date(transactionResponse.body.processTime),
fields: [{
name: '💰 Refunded Amount',
value: `${response.body.refundAmount} oats refunded`
}]
});
})
.catch(transactionResponse => {
switch(transactionResponse.statusCode) {
case 503:
return msg.reply('Discoin is currently unavailable. Try again later.');
case 404:
return msg.reply('Transaction not found.');
default:
return msg.reply('An unknown error occured. Try again later.');
}
});
})
.catch(response => {
switch(response.statusCode) {
case 503:
return msg.reply('Discoin is currently unavailable. Try again later.');
case 400:
switch(response.body.reason) {
case 'cannot refund a refund':
return msg.reply('You can\t refund a refund.');
case 'transaction already reversed':
return msg.reply('Transaction has already been reversed.');
}
break;
case 403:
return msg.reply('Transaction must be to this bot');
case 404:
return msg.reply('Transaction not found');
default:
return msg.reply('An unknown error occured. Try again later.');
}
return null;
});
return null;
} finally {
msg.channel.stopTyping();
}
}
};
|
from django.db import models
class Item(models.Model):
"""To do item to show"""
title = models.CharField(max_length=255, unique=True)
done = models.BooleanField(default=False)
def __str__(self):
return self.title
|
'use strict';
exports = module.exports = function (ourDb, theirDb, count) {
function callback0() {
global.gc();
ourTest(ourDb, count, callback1);
}
function callback1() {
global.gc();
theirTest(theirDb, count, callback2);
}
function callback2() {
var closedCount = 0;
ourDb.on('close', closed).close();
theirDb.close(closed);
function closed() {
++closedCount === 2 && process.exit();
}
}
setTimeout(callback0, 100);
};
exports.data = undefined;
function ourTest(db, count, done) {
var t0 = process.hrtime();
for (var i=0; i<count; ++i) {
exports.data = db.prepare('SELECT * FROM entries');
}
var td = process.hrtime(t0);
report('better-sqlite3', count, td);
done();
}
function theirTest(db, count, done) {
var completed = 0;
var t0 = process.hrtime();
for (var i=0; i<count; ++i) {
db.prepare('SELECT * FROM entries', callback);
}
function callback(err, data) {
exports.data = data;
if (err) {throw err;}
if (++completed === count) {
var td = process.hrtime(t0);
report('node-sqlite3', count, td);
done();
}
}
}
function report(name, count, time) {
var ms = time[0] * 1000 + Math.round(time[1] / 1000000);
console.log(name + '\t' + count + ' prepared statements in ' + ms + 'ms');
}
|
(function(factory){if(typeof module==="object"&&typeof module.exports!=="undefined"){module.exports=factory}else{factory(FusionCharts)}})(function(FusionCharts){(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{configurable:false,enumerable:true,get:getter})}};__webpack_require__.r=function(exports){Object.defineProperty(exports,"__esModule",{value:true})};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s=382)})({382:function(module,exports,__webpack_require__){"use strict";var _fusioncharts=__webpack_require__(383);var _fusioncharts2=_interopRequireDefault(_fusioncharts);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}FusionCharts.addDep(_fusioncharts2["default"])},383:function(module,exports,__webpack_require__){"use strict";exports.__esModule=true;
/**!
* @license FusionCharts JavaScript Library
* Copyright FusionCharts Technologies LLP
* License Information at <http://www.fusioncharts.com/license>
*
* @author FusionCharts Technologies LLP
* @meta package_map_pack
* @id fusionmaps.EastSouthCentralDMA.17.10-28-2015 06:54:51
*/var M="M",L="L",Z="Z",Q="Q",LFT="left",RGT="right",CEN="center",MID="middle",TOP="top",BTM="bottom",geodefinitions=[{name:"EastSouthCentralDMA",revision:17,standaloneInit:true,baseWidth:527,baseHeight:600,baseScaleFactor:10,entities:{515:{outlines:[[M,3836,198,Q,3801,198,3753,191,3702,184,3680,184,3665,183,3656,162,3648,136,3645,129,3617,98,3591,70,3565,42,3542,37,3518,32,3452,26,L,3388,26,3349,33,Q,3345,33,3342,34,3339,34,3337,35,3321,53,3323,90,3325,113,3330,162,3328,227,3328,282,3328,289,3328,296,3326,296,3325,296,3323,306,3319,319,3323,330,3315,337,3307,344,3297,342,3266,335,3265,361,3264,376,3272,403,L,3272,441,Q,3321,450,3332,490,3335,502,3336,557,L,3407,557,Q,3429,556,3464,503,3465,503,3498,477,3518,462,3528,448,3555,413,3578,400,L,3926,400,Q,3963,402,3983,395,3984,395,4009,384,4015,381,4026,381,L,4026,257,Q,3984,258,3960,258,3937,258,3909,228,Q,3881,197,3836,198,Z]],label:"Cincinnati",shortLabel:"CIN-OH",labelPosition:[364.5,29.1],labelAlignment:[CEN,MID]},522:{outlines:[[M,3580,3950,Q,3579,3948,3577,3946,3574,3940,3571,3933,L,3380,3933,3380,4260,Q,3386,4263,3447,4267,3494,4270,3509,4298,3523,4325,3523,4465,3523,4470,3523,4530,3524,4593,3519,4619,3518,4625,3503,4632,3484,4640,3478,4647,3451,4673,3439,4699,3422,4739,3432,4831,3437,4873,3425,4889,3451,4891,3468,4882,3480,4877,3504,4861,3509,4858,3542,4846,3572,4835,3586,4825,3631,4795,3657,4784,3696,4768,3739,4773,3737,4762,3737,4747,3740,4627,3740,4569,3740,4541,3754,4530,3763,4522,3790,4509,3808,4498,3812,4482,3814,4473,3814,4445,3814,4358,3771,4306,3708,4249,3669,4203,3655,4186,3640,4142,3626,4094,3620,4077,3619,4074,3603,4006,Q,3594,3965,3580,3950,Z]],label:"Columbus-Ga",shortLabel:"COL-GA",labelPosition:[416.9,440.6],labelAlignment:[LFT,MID],labelConnectors:[[M,4169,4406,L,3653,4406]]},524:{outlines:[[M,3320,3486,Q,3297,3507,3292,3530,3287,3549,3293,3584,3266,3600,3250,3611,3219,3633,3219,3652,3220,3666,3237,3669,3248,3671,3276,3671,3332,3675,3331,3734,L,3331,3933,3571,3933,Q,3547,3871,3519,3763,3468,3566,3467,3562,L,3409,3368,Q,3385,3307,3382,3275,3382,3275,3382,3274,3373,3292,3359,3389,Q,3348,3462,3320,3486,Z]],label:"Atlanta",shortLabel:"ATL-GA",labelPosition:[399.7,359.7],labelAlignment:[LFT,MID],labelConnectors:[[M,3997,3597,L,3361,3597]]},529:{outlines:[[M,3325,296,Q,3291,296,3251,303,3209,310,3174,310,3181,354,3134,360,3073,360,3048,367,3048,482,3046,540,3005,557,2974,562,2955,565,2955,590,2955,604,2958,630,2958,671,2917,668,2894,667,2851,690,2825,704,2830,761,2833,792,2837,852,L,2684,852,Q,2675,811,2668,788,2656,747,2627,740,L,2558,740,Q,2558,846,2556,857,2555,863,2535,873,2514,883,2512,887,2509,893,2509,917,2510,938,2501,945,L,2440,945,Q,2440,960,2438,988,2438,1004,2453,1017,2462,1024,2477,1035,2486,1043,2486,1069,2486,1084,2484,1118,2484,1148,2477,1221,2477,1240,2472,1270,2467,1299,2466,1319,2489,1317,2517,1314,2533,1314,2664,1321,2669,1321,2748,1321,2763,1322,2774,1314,2780,1309,2792,1296,2814,1275,2810,1236,2808,1223,2814,1219,2822,1213,2847,1212,2856,1213,2923,1214,2953,1214,2964,1219,2983,1228,2982,1301,L,2978,1401,3129,1401,3130,1502,Q,3133,1501,3137,1500,L,3271,1500,Q,3266,1490,3266,1477,3266,1462,3269,1455,3273,1447,3274,1426,3276,1386,3283,1378,3297,1362,3334,1362,3360,1361,3360,1332,3360,1305,3320,1277,3281,1250,3281,1228,3281,1201,3342,1168,L,3342,854,3270,854,3270,716,Q,3320,731,3331,687,3336,672,3336,589,3336,571,3335,556,3335,502,3331,490,3321,450,3272,441,L,3272,403,Q,3264,376,3265,361,3266,335,3296,341,3307,344,3315,337,3323,330,3318,319,Q,3323,306,3325,296,Z]],label:"Louisville",shortLabel:"LOU-KY",labelPosition:[289.9,100.7],labelAlignment:[CEN,MID]},531:{outlines:[[M,4642,1094,Q,4607,1096,4578,1100,4556,1103,4537,1107,4521,1112,4456,1165,4446,1175,4426,1208,4413,1228,4390,1227,4365,1228,4360,1219,4345,1194,4322,1174,4301,1144,4287,1141,4235,1140,4206,1138,L,4189,1138,Q,4189,1237,4180,1391,4202,1387,4232,1384,4259,1377,4308,1338,4314,1335,4352,1309,4376,1293,4392,1290,4440,1281,4485,1281,4535,1281,4546,1291,4551,1289,4557,1287,4569,1284,4594,1279,4609,1270,4636,1242,L,4635,1174,Q,4633,1162,4658,1158,4688,1151,4698,1142,4708,1133,4734,1109,4742,1102,4749,1094,Z],[M,5073,1500,Q,5009,1500,5003,1500,4952,1500,4915,1496,4879,1492,4852,1492,4833,1492,4765,1520,4699,1547,4617,1547,4564,1547,4544,1536,4524,1525,4490,1525,4478,1525,4479,1557,4479,1591,4470,1593,4459,1597,4436,1597,L,4435,1666,Q,4435,1698,4439,1707,4443,1716,4466,1755,L,4488,1793,Q,4496,1809,4496,1836,4504,1848,4516,1870,4533,1887,4552,1896,4559,1900,4597,1925,4619,1939,4636,1942,4638,1931,4643,1928,4646,1925,4660,1909,4670,1898,4679,1896,4709,1893,4736,1893,4738,1893,4787,1902,4796,1904,4807,1911,4814,1915,4827,1916,4829,1916,4831,1916,4857,1913,4875,1884,4886,1866,4900,1834,4917,1809,4948,1808,5004,1807,5005,1807,5039,1798,5100,1749,5131,1732,5138,1704,5141,1667,5144,1642,5212,1642,5237,1640,L,5237,1440,5204,1440,Q,5146,1459,5120,1481,Q,5097,1501,5073,1500,Z]],label:"Tri-Cities-Tn-Va",shortLabel:"TRI-TN",labelPosition:[477.8,166.9],labelAlignment:[CEN,MID]},541:{outlines:[[M,4047,382,Q,4035,380,4026,380,4015,381,4009,384,3984,395,3983,395,3963,402,3926,400,L,3578,400,Q,3555,413,3528,448,3518,462,3498,477,3465,503,3464,503,3429,556,3407,556,L,3335,556,Q,3336,571,3336,589,3336,672,3331,687,3320,731,3270,716,L,3270,854,3342,854,3342,1168,Q,3281,1201,3281,1228,3281,1250,3320,1277,3360,1305,3360,1332,3360,1361,3334,1362,3297,1362,3283,1378,3276,1386,3274,1426,3273,1447,3269,1455,3266,1462,3266,1477,3266,1490,3271,1500,3284,1526,3334,1527,3344,1528,3364,1525,3380,1525,3382,1543,L,3384,1597,Q,3384,1609,3384,1622,L,3437,1622,3437,1669,Q,3501,1669,3509,1670,3513,1671,3517,1677,3521,1684,3528,1687,3532,1688,3556,1688,3582,1688,3589,1674,3592,1666,3592,1638,3592,1619,3577,1619,3562,1618,3562,1605,3562,1590,3590,1558,3605,1542,3625,1521,3631,1514,3634,1497,3636,1480,3643,1470,3652,1458,3667,1429,L,3775,1429,Q,3777,1433,3775,1447,3774,1459,3780,1459,3784,1507,3785,1623,L,3881,1625,Q,3916,1625,3930,1619,3940,1614,3967,1597,3971,1595,4010,1588,4035,1583,4036,1566,4035,1544,4048,1523,4053,1516,4068,1478,4109,1414,4131,1403,4145,1396,4180,1391,4189,1237,4189,1138,L,4206,1138,Q,4235,1140,4287,1141,4301,1144,4322,1174,4345,1194,4360,1219,4365,1228,4390,1227,4413,1228,4426,1208,4446,1175,4456,1165,4521,1112,4537,1107,4556,1103,4578,1100,L,4578,981,4577,980,4573,980,Q,4504,979,4502,978,4497,975,4497,932,4497,883,4476,851,4467,837,4431,805,4403,778,4393,752,4378,714,4388,651,L,4369,651,Q,4357,668,4343,671,4339,672,4304,672,4260,672,4249,659,4244,654,4229,609,4202,549,4192,509,4187,486,4144,431,4098,372,4076,372,4067,372,4061,376,Q,4055,381,4047,382,Z]],label:"Lexington",shortLabel:"LEX-KY",labelPosition:[382,103],labelAlignment:[CEN,MID]},557:{outlines:[[M,4485,1281,Q,4440,1281,4392,1290,4376,1293,4352,1310,4314,1335,4308,1338,4259,1377,4232,1384,4202,1387,4180,1391,4145,1396,4131,1403,4109,1414,4068,1479,4053,1516,4048,1524,4035,1544,4036,1566,4035,1583,4011,1588,3971,1595,3967,1597,3940,1614,3931,1619,3916,1625,3881,1625,L,3786,1624,Q,3784,1507,3780,1459,3774,1459,3775,1447,3777,1433,3776,1430,L,3668,1430,Q,3652,1458,3643,1470,3636,1480,3634,1497,3631,1514,3625,1521,3605,1542,3590,1558,3562,1590,3562,1605,3562,1618,3577,1619,3592,1619,3593,1638,3592,1666,3589,1674,3582,1688,3556,1688,3532,1688,3528,1687,3521,1684,3517,1677,3513,1671,3510,1671,3501,1669,3438,1669,L,3438,1622,3384,1622,Q,3384,1694,3380,1832,3380,1870,3383,1874,3387,1878,3428,1877,L,3428,1961,Q,3394,1969,3380,2024,3372,2055,3358,2121,3354,2132,3355,2178,3425,2178,3584,2172,3657,2171,3703,2198,3739,2219,3790,2280,3823,2320,3843,2391,3848,2412,3851,2453,3857,2484,3883,2490,3942,2490,3951,2491,4010,2495,4046,2453,4085,2406,4074,2340,4103,2328,4123,2303,4133,2289,4153,2258,4181,2223,4195,2220,4206,2218,4255,2223,4279,2223,4332,2204,4387,2186,4400,2173,4408,2165,4457,2118,4472,2100,4491,2095,4500,2092,4520,2086,4526,2083,4552,2073,4576,2062,4580,2053,4594,2026,4617,2015,L,4618,2015,Q,4638,2004,4636,1971,4634,1953,4636,1942,4619,1939,4597,1925,4559,1900,4552,1897,4533,1887,4516,1870,4504,1848,4496,1837,4496,1809,4488,1793,L,4466,1755,Q,4443,1716,4439,1708,4435,1698,4435,1666,L,4436,1598,Q,4430,1598,4422,1598,4389,1596,4386,1596,4282,1590,4228,1590,L,4228,1566,Q,4237,1559,4269,1511,4290,1478,4326,1481,4346,1483,4400,1454,4446,1440,4462,1418,4472,1405,4491,1394,4501,1388,4520,1378,4550,1359,4542,1314,4537,1298,4547,1291,Q,4535,1281,4485,1281,Z]],label:"Knoxville",shortLabel:"KNO-TX",labelPosition:[399.5,188.6],labelAlignment:[CEN,MID]},564:{outlines:[[M,4449,258,Q,4440,251,4421,220,4403,194,4394,190,4379,183,4321,186,4274,189,4269,187,L,4277,186,Q,4202,184,4178,189,4140,196,4151,252,4076,255,4026,257,L,4026,380,Q,4035,380,4047,382,4055,381,4061,376,4067,372,4076,372,4098,372,4144,431,4187,486,4192,509,4202,549,4229,609,4244,654,4249,659,4260,672,4304,672,4339,672,4343,671,4357,668,4369,651,L,4388,651,Q,4378,714,4393,752,4403,778,4431,805,4467,837,4476,851,4497,883,4497,932,4497,975,4502,978,4504,979,4573,980,L,4577,980,4578,981,4578,1100,Q,4607,1096,4642,1094,L,4749,1094,Q,4750,1094,4751,1093,4765,1078,4777,1064,4794,1043,4820,1024,4836,1013,4875,985,4881,981,4936,953,4966,938,4966,916,4966,897,4952,883,4933,866,4924,857,4903,834,4851,835,4821,837,4781,796,4753,768,4733,734,4710,691,4695,667,4669,622,4632,586,4593,547,4581,524,4567,497,4566,450,4567,420,4571,411,4574,403,4574,372,4574,315,4539,302,4515,295,4500,289,Q,4472,278,4449,258,Z]],label:"Charleston/Huntington",shortLabel:"CHA-WV",labelPosition:[427.6,32.6],labelAlignment:[CEN,MID]},575:{outlines:[[M,3584,2172,Q,3425,2178,3355,2178,3355,2198,3356,2223,3358,2288,3323,2308,3301,2321,3241,2376,3205,2408,3154,2407,3057,2405,3042,2423,3034,2432,3034,2454,3034,2468,3035,2509,3035,2514,3035,2574,3035,2591,3061,2618,3064,2625,3062,2648,3061,2670,3066,2678,3087,2715,3089,2728,L,3089,2727,3232,2727,3232,2726,3464,2726,Q,3550,2725,3557,2720,3569,2712,3579,2684,3590,2669,3616,2677,3625,2676,3775,2684,3781,2684,3877,2684,3893,2685,3906,2670,3914,2662,3932,2642,3951,2623,3951,2575,3948,2518,3951,2491,3942,2490,3883,2490,3857,2484,3851,2453,3848,2412,3843,2391,3823,2320,3790,2280,3739,2219,3703,2198,Q,3657,2171,3584,2172,Z]],label:"Chattanooga",shortLabel:"CHA-TN",labelPosition:[349.2,245],labelAlignment:[CEN,MID]},606:{outlines:[[M,3787,4888,Q,3787,4845,3762,4823,3744,4807,3739,4774,3696,4768,3657,4785,3631,4795,3586,4825,3572,4835,3542,4846,3509,4858,3504,4861,3480,4877,3468,4883,3451,4891,3425,4889,3423,4893,3420,4895,3406,4905,3352,4905,3297,4902,3270,4901,3222,4900,3194,4907,3118,4924,3129,5013,3136,5071,3125,5168,3111,5282,3111,5306,3114,5306,3116,5306,3168,5314,3233,5287,3307,5256,3335,5255,3409,5251,3872,5252,L,3872,5218,Q,3817,5217,3799,5183,3784,5155,3790,5095,3793,5060,3791,4992,Q,3787,4900,3787,4888,Z]],label:"Dothan",shortLabel:"DOT-AL",labelPosition:[349.2,504],labelAlignment:[CEN,MID]},622:{outlines:[[M,1111,5455,Q,1110,5459,1110,5469,L,1111,5469,Q,1114,5511,1114,5604,1116,5622,1111,5670,1112,5711,1138,5721,1203,5746,1218,5824,1227,5869,1232,5968,L,1283,5968,Q,1289,5963,1350,5924,1386,5902,1376,5866,L,1354,5866,1354,5482,Q,1356,5479,1358,5476,L,1359,5476,Q,1357,5461,1352,5455,Z]],label:"New Orleans",shortLabel:"NEW-LA",labelPosition:[89.9,571.4],labelAlignment:[RGT,MID],labelConnectors:[[M,899,5714,L,1261,5714]]},630:{outlines:[[M,3297,3051,Q,3296,3074,3281,3075,3263,3075,3257,3079,3246,3086,3244,3109,3243,3117,3245,3137,3241,3153,3219,3161,3178,3187,3158,3197,3070,3236,3028,3256,2951,3290,2921,3326,L,2870,3326,Q,2872,3313,2861,3303,2847,3292,2845,3276,2841,3252,2819,3239,2805,3229,2792,3229,2622,3226,2616,3226,2515,3228,2465,3226,2439,3225,2412,3251,2386,3280,2375,3287,L,1842,3287,1842,3401,Q,1845,3407,1847,3424,1877,3424,1915,3431,1951,3438,1984,3438,L,1984,3779,1903,3779,Q,1875,3776,1842,3777,1841,3800,1842,3994,1842,4098,1836,4162,1863,4157,1884,4165,1898,4187,1919,4206,1940,4225,1964,4259,1987,4293,1999,4315,2011,4336,2031,4364,2051,4391,2074,4403,2077,4405,2081,4407,2103,4416,2146,4417,2195,4418,2245,4418,2295,4417,2303,4414,2310,4410,2327,4365,2343,4320,2342,4260,2338,4194,2339,4167,2402,4165,2564,4163,2567,4163,2576,4200,2586,4237,2586,4250,2585,4275,2588,4280,2592,4287,2615,4290,2639,4292,2693,4290,2768,4290,2773,4286,2778,4281,2781,4265,2785,4239,2789,4218,2813,4216,2876,4221,2930,4223,2945,4203,2965,4174,3022,4174,3053,4173,3122,4174,3128,4150,3126,4107,3122,4058,3122,4035,3120,3951,3169,3934,L,3332,3933,3332,3734,Q,3332,3675,3276,3671,3248,3671,3237,3670,3220,3666,3220,3652,3219,3633,3250,3612,3266,3600,3293,3585,3287,3549,3292,3530,3297,3507,3321,3486,3348,3462,3359,3389,3373,3292,3382,3274,3387,3195,3377,3169,L,3322,3169,Q,3319,3152,3322,3122,3326,3089,3327,3073,3330,3021,3294,3021,Q,3295,3031,3297,3051,Z]],label:"Birmingham",shortLabel:"BIR-AL",labelPosition:[261,371.9],labelAlignment:[CEN,MID]},632:{outlines:[[M,1702,1259,Q,1693,1297,1650,1299,1626,1298,1614,1298,1594,1299,1582,1306,1543,1328,1537,1332,1502,1358,1502,1387,1502,1407,1523,1429,1557,1463,1560,1467,L,1560,1538,1450,1538,Q,1431,1513,1418,1507,1403,1500,1363,1502,1258,1500,1251,1500,1217,1500,1187,1513,1152,1530,1152,1556,1152,1566,1169,1588,1189,1614,1193,1628,1202,1653,1202,1732,1202,1813,1200,1817,1197,1822,1136,1872,L,1338,1872,Q,1356,1872,1374,1879,1392,1885,1420,1885,L,1544,1885,Q,1574,1887,1639,1886,1699,1887,1711,1885,1737,1882,1750,1866,1758,1857,1771,1833,1782,1821,1789,1817,1790,1815,1790,1797,1790,1771,1779,1757,1762,1738,1747,1716,L,1747,1636,1830,1636,Q,1848,1636,1861,1622,1870,1614,1888,1594,1908,1577,1914,1535,1953,1495,1953,1480,1950,1476,1949,1472,1949,1450,1937,1438,1917,1418,1914,1412,1874,1325,1840,1279,1804,1229,1707,1236,Q,1705,1249,1702,1259,Z]],label:"Paducah/Cape Girardeau/Harrisburg/Mt Vernon",shortLabel:"PAD-KY",labelPosition:[147.3,168.7],labelAlignment:[CEN,MID]},639:{outlines:[[M,1544,1885,L,1420,1885,Q,1392,1885,1374,1879,1356,1872,1338,1872,L,1136,1872,Q,1126,1881,1095,1885,1067,1889,1057,1902,1025,1944,1016,1965,1015,1967,1015,1969,1008,1996,958,2016,L,958,2037,Q,969,2060,969,2077,969,2101,960,2118,L,960,2153,Q,973,2155,1004,2155,1025,2155,1036,2152,1048,2149,1078,2148,1100,2149,1120,2142,1140,2135,1148,2135,1164,2135,1168,2137,1172,2139,1193,2150,1204,2156,1204,2194,1204,2211,1198,2235,1193,2259,1193,2277,1193,2309,1211,2320,1261,2350,1261,2351,1269,2358,1316,2368,1353,2377,1353,2398,1353,2402,1337,2410,1312,2425,1302,2432,1250,2469,1250,2522,1250,2550,1256,2560,1261,2569,1287,2588,1310,2604,1362,2618,1368,2622,1400,2632,1420,2638,1428,2651,1438,2667,1444,2688,1452,2702,1477,2702,1494,2702,1499,2692,1511,2672,1527,2658,1530,2656,1556,2649,1582,2643,1592,2632,L,1643,2632,Q,1650,2719,1639,2810,1642,2837,1659,2847,1671,2854,1696,2857,1709,2858,1726,2858,1756,2858,1841,2846,1841,2846,1841,2846,1875,2841,1908,2838,1909,2807,1902,2758,1895,2706,1894,2682,1895,2648,1892,2642,1889,2633,1877,2634,1862,2635,1859,2633,1848,2628,1834,2613,1819,2598,1810,2593,1807,2591,1773,2591,1746,2592,1746,2573,L,1746,2473,Q,1748,2289,1748,2284,1748,2185,1728,2162,1720,2150,1715,2144,1706,2134,1693,2136,1623,2138,1618,2138,1547,2138,1544,2133,1547,2103,1544,2054,Z]],label:"Jackson-Tn",shortLabel:"JAC-TN",labelPosition:[152.3,230.9],labelAlignment:[CEN,MID]},640:{outlines:[[M,1204,2194,Q,1204,2156,1193,2150,1172,2139,1168,2137,1164,2135,1148,2135,1140,2135,1120,2142,1100,2149,1078,2148,1048,2149,1036,2152,1025,2155,1004,2155,973,2155,960,2153,L,960,2118,Q,969,2101,969,2077,969,2060,958,2037,L,958,2016,Q,938,2024,912,2031,815,2033,772,2034,772,2081,769,2102,L,769,2269,906,2269,906,2386,Q,912,2415,889,2444,881,2454,843,2492,804,2530,791,2616,755,2635,740,2640,717,2649,717,2668,717,2697,740,2723,763,2750,763,2775,763,2808,752,2881,752,2900,730,2917,710,2933,690,2934,689,2934,689,2935,657,2973,584,3046,526,3116,526,3183,526,3243,514,3268,501,3295,458,3317,416,3338,414,3377,413,3392,414,3421,413,3446,400,3456,386,3468,354,3491,L,409,3491,Q,418,3493,431,3501,443,3508,455,3507,473,3506,493,3534,514,3561,531,3561,547,3562,569,3554,589,3554,594,3550,601,3546,612,3536,628,3535,656,3533,679,3529,695,3513,712,3496,749,3469,753,3467,756,3464,763,3460,762,3447,L,760,3424,Q,761,3416,797,3416,822,3416,898,3422,900,3422,902,3422,L,913,3422,Q,917,3432,950,3431,987,3431,992,3435,1e3,3439,1093,3439,1181,3439,1209,3432,1222,3429,1246,3411,1272,3392,1271,3385,1272,3377,1245,3329,1221,3285,1209,3268,L,1209,3126,1492,3126,Q,1491,3100,1492,3084,1494,3055,1517,3048,1526,3045,1547,3030,1555,3025,1589,3024,1628,3018,1678,3014,1710,3006,1710,2960,1710,2947,1705,2932,1697,2910,1696,2904,L,1696,2857,Q,1671,2854,1659,2847,1642,2837,1639,2810,1650,2719,1643,2632,L,1592,2632,Q,1582,2643,1556,2649,1530,2656,1527,2658,1511,2672,1499,2692,1494,2702,1477,2702,1452,2702,1444,2688,1438,2667,1428,2651,1420,2638,1400,2632,1368,2622,1362,2618,1310,2604,1287,2588,1261,2569,1256,2560,1250,2550,1250,2522,1250,2469,1302,2432,1312,2425,1337,2410,1353,2402,1353,2398,1353,2377,1316,2368,1269,2358,1261,2351,1261,2350,1211,2320,1193,2309,1193,2277,1193,2259,1198,2235,Q,1204,2211,1204,2194,Z]],label:"Memphis",shortLabel:"MEM-TN",labelPosition:[108.6,278.9],labelAlignment:[CEN,MID]},647:{outlines:[[M,749,3469,Q,712,3496,695,3513,679,3529,656,3533,628,3535,612,3536,601,3546,594,3550,589,3554,569,3554,547,3562,531,3561,514,3561,493,3534,473,3506,455,3507,443,3508,431,3501,418,3493,409,3491,L,354,3491,Q,346,3498,337,3504,297,3537,285,3565,277,3585,275,3652,274,3705,247,3727,228,3744,225,3746,215,3760,214,3785,214,3823,213,3830,208,3857,187,3861,133,3863,102,3866,50,3871,40,3897,40,3900,39,3902,L,39,3932,Q,62,3964,60,4043,59,4089,56,4186,56,4205,85,4220,103,4228,140,4244,163,4256,191,4277,214,4291,243,4288,253,4287,269,4286,281,4285,292,4274,299,4266,356,4254,377,4249,379,4211,377,4169,379,4156,L,421,4156,Q,422,4159,425,4169,L,441,4169,Q,442,4165,443,4123,444,4093,459,4080,488,4056,492,4053,511,4040,534,4040,565,4040,626,3996,651,3978,717,3978,765,3978,775,3982,779,3984,821,4011,846,4023,932,4023,L,990,4023,Q,1006,4023,1037,4011,1041,4011,1046,4010,1055,3998,1055,3982,1055,3965,1005,3921,955,3878,955,3839,955,3795,1031,3768,1073,3753,1083,3748,1107,3736,1107,3717,1107,3705,1094,3699,1079,3692,1075,3680,1074,3675,1074,3620,848,3620,845,3616,838,3608,839,3582,841,3550,839,3541,836,3491,831,3469,Z]],label:"Greenwood/Greenville",shortLabel:"GRE-MS",labelPosition:[57.3,382.3],labelAlignment:[CEN,MID]},649:{outlines:[[M,2438,945,Q,2418,904,2351,904,2303,904,2278,950,2253,996,2196,997,2139,997,2115,964,2079,955,2068,941,2057,926,2053,928,2050,930,2032,923,2014,917,1990,931,1979,935,1972,938,1958,944,1957,953,1965,982,1942,991,1926,998,1888,997,1885,998,1851,996,1813,993,1804,991,L,1713,991,Q,1713,992,1714,1133,1714,1194,1707,1236,1804,1229,1840,1279,1874,1325,1915,1412,1917,1418,1937,1438,1949,1450,1950,1472,1950,1476,1954,1480,1968,1494,2034,1494,L,2279,1494,Q,2280,1494,2281,1494,2354,1495,2366,1486,2372,1480,2385,1478,2384,1448,2378,1434,L,2378,1326,Q,2394,1326,2467,1319,2467,1299,2472,1270,2477,1240,2478,1221,2484,1148,2484,1118,2486,1084,2486,1070,2486,1043,2478,1035,2462,1024,2454,1017,2438,1004,2438,989,2440,960,2440,945,Z]],label:"Evansville",shortLabel:"EVA-IN",labelPosition:[209.6,119.9],labelAlignment:[CEN,MID]},659:{outlines:[[M,3046,1528,Q,3022,1529,3017,1538,3010,1546,3008,1567,3006,1586,3001,1591,2998,1594,2966,1594,2927,1595,2915,1595,2910,1594,2910,1594,2847,1594,2823,1592,L,2823,1530,2782,1530,Q,2779,1531,2714,1530,2678,1530,2672,1552,2665,1577,2654,1580,2648,1581,2589,1581,2526,1581,2520,1579,2508,1573,2515,1536,L,2515,1486,Q,2462,1486,2455,1484,2444,1475,2437,1476,2413,1476,2411,1476,2396,1475,2385,1478,2372,1480,2366,1486,2354,1495,2281,1494,2280,1494,2279,1494,L,2034,1494,Q,1968,1494,1954,1480,1953,1495,1915,1535,1908,1577,1888,1594,1870,1614,1861,1622,1848,1636,1830,1636,L,1747,1636,1747,1716,Q,1762,1738,1779,1757,1790,1771,1790,1797,1790,1815,1789,1817,1782,1821,1771,1833,1758,1857,1750,1866,1737,1882,1711,1885,1699,1887,1639,1887,1574,1887,1544,1885,L,1544,2054,Q,1547,2103,1545,2133,1547,2138,1618,2138,1623,2138,1693,2136,1706,2134,1715,2144,1720,2150,1728,2163,1748,2185,1748,2284,1748,2289,1746,2473,L,1746,2573,Q,1746,2592,1773,2592,1807,2591,1811,2593,1819,2598,1834,2614,1848,2628,1859,2633,1862,2635,1878,2634,1889,2633,1893,2642,1895,2648,1895,2682,1895,2706,1903,2759,1909,2807,1908,2839,1960,2834,2010,2834,L,2188,2838,Q,2293,2838,2319,2824,2357,2804,2489,2792,2521,2789,2527,2742,2528,2687,2531,2671,2532,2660,2532,2655,2533,2645,2540,2641,2545,2636,2573,2630,2587,2619,2599,2600,2604,2590,2627,2591,2704,2590,2731,2621,2745,2638,2775,2668,2798,2694,2797,2716,2793,2757,2806,2767,2818,2777,2867,2775,2942,2771,3014,2782,3068,2781,3093,2775,L,3093,2755,Q,3091,2742,3089,2738,L,3089,2728,Q,3087,2715,3066,2678,3061,2670,3062,2648,3064,2625,3061,2618,3035,2591,3035,2574,3035,2514,3035,2509,3034,2468,3034,2454,3034,2432,3042,2423,3057,2405,3154,2407,3205,2408,3241,2376,3301,2321,3323,2308,3358,2288,3356,2223,3355,2198,3355,2178,3354,2132,3358,2121,3372,2055,3380,2024,3394,1969,3428,1961,L,3428,1877,Q,3387,1878,3383,1874,3380,1870,3380,1832,3384,1694,3384,1622,3384,1609,3384,1598,L,3382,1543,Q,3380,1525,3364,1525,3344,1528,3334,1528,3284,1526,3271,1500,L,3137,1500,Q,3133,1501,3130,1503,3088,1519,3078,1524,Q,3073,1526,3046,1528,Z]],label:"Nashville",shortLabel:"NAS-TN",labelPosition:[248.6,215.7],labelAlignment:[CEN,MID]},673:{outlines:[[M,1841,2846,Q,1756,2858,1726,2858,1709,2858,1696,2857,L,1696,2904,Q,1697,2910,1705,2932,1710,2947,1710,2960,1710,3006,1678,3014,1628,3018,1589,3024,1555,3025,1547,3030,1526,3045,1517,3048,1494,3055,1492,3084,1491,3100,1492,3126,L,1209,3126,1209,3268,Q,1221,3285,1245,3329,1272,3377,1271,3385,1272,3392,1246,3411,1222,3429,1209,3432,1181,3439,1093,3439,1e3,3439,992,3435,987,3431,950,3431,917,3432,913,3422,L,902,3422,Q,900,3422,898,3422,822,3416,797,3416,761,3416,760,3424,L,762,3447,Q,763,3460,756,3464,753,3467,749,3469,L,831,3469,Q,836,3491,839,3541,841,3550,839,3582,838,3608,845,3616,848,3620,1074,3620,1074,3675,1075,3680,1079,3692,1094,3699,1107,3705,1107,3717,1107,3736,1083,3748,1073,3753,1031,3768,955,3795,955,3839,955,3878,1005,3921,1055,3965,1055,3982,1055,3998,1046,4010,1063,4009,1100,4011,1129,4013,1137,4012,1142,4012,1142,4011,L,1226,4011,Q,1241,4012,1240,4037,1240,4077,1240,4078,1245,4103,1257,4143,1263,4170,1266,4216,L,1707,4216,Q,1729,4209,1789,4176,1814,4165,1836,4162,1842,4098,1841,3994,1841,3800,1841,3776,1875,3776,1903,3779,L,1984,3779,1984,3438,Q,1951,3438,1914,3431,1877,3424,1847,3424,1845,3407,1841,3401,L,1841,2846,Q,1841,2846,1841,2846,Z]],label:"Columbus/Tupelo/West Point",shortLabel:"COL-MS",labelPosition:[143.9,363.9],labelAlignment:[CEN,MID]},686:{outlines:[[M,2245,4797,Q,2217,4766,2137,4766,2088,4774,2054,4782,2035,4801,2038,4816,2042,4832,2044,4872,2046,4913,2036,4919,2034,4922,1992,4930,1954,4953,1950,4955,1935,4963,1906,4962,1871,4961,1850,4961,1850,5029,1846,5130,1845,5167,1844,5208,1844,5248,1877,5288,1911,5329,1911,5386,1911,5412,1905,5430,1900,5448,1900,5482,1900,5520,1894,5532,1889,5545,1889,5566,1889,5590,1920,5620,1950,5650,1950,5689,1950,5696,1947,5771,L,1974,5771,Q,1976,5773,1984,5775,1993,5777,2026,5796,2060,5814,2065,5814,2096,5815,2096,5658,2094,5606,2097,5576,2102,5522,2134,5522,2196,5522,2208,5683,2206,5704,2224,5730,2245,5760,2247,5771,2254,5815,2255,5818,2264,5850,2284,5850,2315,5850,2326,5845,2331,5842,2338,5832,2351,5812,2425,5811,2466,5811,2469,5811,2493,5808,2501,5793,2509,5780,2507,5753,2504,5722,2503,5707,2500,5697,2499,5643,2498,5588,2493,5560,2434,5572,2393,5534,2360,5492,2342,5471,L,2343,5337,2360,5337,Q,2394,5352,2406,5358,2418,5364,2558,5364,2698,5364,2729,5361,2757,5358,2829,5367,2877,5374,2867,5303,2867,5303,2867,5302,2869,5223,2858,5198,2832,5189,2813,5172,2801,5159,2776,5159,2698,5159,2607,5184,2516,5209,2483,5209,2461,5209,2454,5204,2449,5200,2449,5183,2449,5153,2506,5078,2548,5022,2574,4997,2639,4936,2658,4903,2680,4862,2685,4858,2699,4848,2722,4825,L,2722,4820,Q,2533,4820,2376,4822,Q,2270,4824,2245,4797,Z]],label:"Mobile/Pensacola/Fort Walton Beach",shortLabel:"MOB-AL",labelPosition:[217.6,520],labelAlignment:[CEN,MID]},691:{outlines:[[M,2806,2767,Q,2793,2757,2797,2716,2798,2694,2775,2668,2745,2638,2730,2621,2704,2590,2627,2590,2604,2590,2598,2600,2587,2619,2572,2629,2545,2636,2539,2640,2533,2645,2532,2655,2532,2660,2531,2671,2528,2687,2527,2742,2521,2789,2489,2792,2357,2804,2319,2824,2293,2838,2188,2838,L,2010,2834,Q,1960,2834,1908,2838,1875,2841,1841,2846,L,1841,3287,2375,3287,Q,2386,3280,2412,3250,2439,3225,2464,3226,2515,3228,2616,3226,2622,3226,2791,3228,2805,3229,2819,3239,2841,3252,2845,3275,2847,3292,2860,3303,2872,3313,2870,3326,L,2920,3326,Q,2951,3290,3027,3256,3070,3236,3158,3197,3178,3187,3219,3161,3241,3153,3244,3137,3243,3117,3244,3108,3246,3086,3257,3079,3263,3075,3280,3075,3296,3074,3296,3051,3295,3031,3294,3021,3294,3018,3294,3016,3291,2923,3281,2906,3279,2903,3247,2867,3229,2847,3229,2818,3231,2757,3231,2726,L,3089,2726,3089,2737,Q,3091,2742,3093,2755,L,3093,2774,Q,3068,2781,3014,2781,2942,2771,2867,2774,Q,2818,2777,2806,2767,Z]],label:"Huntsville/Decatur/Florence",shortLabel:"HUN-AL",labelPosition:[256.9,299.4],labelAlignment:[CEN,MID]},698:{outlines:[[M,3122,4035,Q,3122,4058,3126,4107,3128,4150,3122,4174,3053,4173,3022,4174,2965,4174,2945,4203,2930,4223,2876,4221,2813,4216,2789,4218,2785,4239,2781,4265,2778,4281,2773,4286,2768,4290,2693,4290,2639,4292,2615,4290,2592,4287,2588,4280,2585,4275,2586,4250,2586,4237,2576,4200,2567,4163,2564,4163,2402,4165,2339,4167,2338,4194,2342,4260,2343,4320,2327,4365,2310,4410,2303,4414,2295,4417,2245,4418,2195,4418,2146,4417,2103,4416,2081,4407,2076,4436,2064,4484,2056,4528,2059,4569,2062,4624,2062,4752,2063,4761,2054,4783,2088,4774,2137,4766,2217,4766,2245,4797,2270,4824,2376,4823,2533,4820,2722,4820,L,2722,4825,Q,2699,4848,2686,4858,2680,4862,2658,4904,2639,4936,2575,4997,2548,5022,2506,5078,2449,5153,2449,5183,2449,5200,2455,5204,2461,5209,2483,5209,2516,5209,2607,5184,2698,5159,2777,5159,2801,5159,2814,5172,2832,5189,2858,5198,2869,5223,2867,5303,L,2997,5320,Q,3019,5320,3062,5312,3095,5305,3111,5306,3111,5282,3125,5168,3136,5071,3129,5013,3118,4924,3194,4907,3222,4900,3270,4901,3297,4902,3352,4905,3406,4905,3420,4895,3423,4893,3425,4889,3437,4873,3432,4832,3422,4739,3439,4699,3451,4673,3478,4647,3485,4640,3503,4632,3518,4625,3520,4619,3524,4593,3524,4530,3523,4470,3523,4465,3523,4325,3509,4298,3494,4270,3447,4267,3386,4263,3380,4260,L,3380,3933,3169,3934,Q,3120,3951,3122,4035,Z]],label:"Montgomery/Selma",shortLabel:"MON-AL",labelPosition:[278.9,462.6],labelAlignment:[CEN,MID]},710:{outlines:[[M,1588,4878,Q,1537,4878,1535,4874,1538,4847,1535,4802,L,1535,4670,Q,1383,4668,1306,4667,1306,4732,1308,4778,1309,4826,1309,4861,1309,4884,1310,4907,1310,4920,1303,4922,1270,4917,1215,4922,1212,4948,1211,4969,1209,4976,1184,4975,1169,4975,1147,4964,L,1045,4964,1045,5011,Q,1052,5019,1114,5065,1172,5113,1172,5134,1172,5150,1121,5157,1079,5173,1049,5181,975,5202,908,5202,L,908,5305,Q,1019,5385,1026,5462,1039,5464,1063,5467,1092,5472,1110,5470,1110,5459,1111,5455,L,1352,5455,Q,1357,5461,1359,5476,L,1359,5476,Q,1387,5479,1401,5500,1407,5510,1427,5509,1437,5509,1451,5507,L,1489,5507,Q,1499,5507,1505,5500,1511,5492,1515,5487,1532,5468,1540,5466,1559,5462,1576,5454,1633,5459,1648,5448,1661,5438,1659,5422,1659,5411,1663,5407,1666,5403,1666,5393,1666,5368,1658,5358,1654,5353,1652,5343,1651,5333,1648,5328,1626,5307,1616,5288,1597,5269,1597,5264,1599,5245,1597,5235,1589,5200,1589,5169,1589,5141,1591,5133,1594,5124,1604,5124,1611,5125,1635,5128,1663,5132,1693,5130,L,1846,5130,Q,1850,5029,1850,4961,1810,4924,1797,4903,1785,4881,1765,4876,1755,4874,1711,4874,Q,1628,4878,1588,4878,Z]],label:"Hattiesburg/Laurel",shortLabel:"HAT-MS",labelPosition:[137.9,504.2],labelAlignment:[CEN,MID]},711:{outlines:[[M,1919,4206,Q,1898,4187,1884,4165,1882,4164,1880,4164,1860,4158,1836,4162,1814,4165,1789,4177,1729,4209,1707,4216,L,1275,4216,1275,4224,Q,1287,4247,1306,4377,1306,4378,1307,4379,1307,4593,1307,4661,1306,4664,1307,4668,1383,4668,1536,4670,L,1536,4802,Q,1538,4847,1535,4874,1537,4878,1588,4879,1628,4878,1712,4874,1755,4874,1765,4876,1785,4881,1798,4904,1810,4924,1850,4961,1871,4961,1907,4963,1935,4963,1950,4956,1954,4953,1992,4931,2034,4922,2037,4920,2046,4913,2044,4872,2042,4832,2038,4816,2035,4801,2054,4783,2063,4761,2062,4752,2062,4624,2059,4569,2056,4528,2064,4484,2076,4436,2081,4407,2077,4405,2074,4403,2051,4391,2031,4364,2011,4336,1999,4315,1987,4293,1964,4259,Q,1940,4225,1919,4206,Z]],label:"Meridian",shortLabel:"MER-MS",labelPosition:[167.8,456.1],labelAlignment:[CEN,MID]},716:{outlines:[[M,544,5245,Q,315,5247,87,5247,81,5278,54,5333,27,5387,31,5426,31,5427,31,5428,L,31,5497,Q,70,5505,85,5516,93,5522,130,5522,243,5522,258,5508,275,5494,405,5494,408,5494,452,5490,499,5487,524,5494,560,5504,580,5517,589,5522,619,5522,623,5522,627,5522,627,5374,625,5350,613,5298,610,5278,608,5266,608,5258,605,5245,599,5245,Z]],label:"Baton Rouge",shortLabel:"BAT-LA",labelPosition:[32.9,538.3],labelAlignment:[CEN,MID]},718:{outlines:[[M,1142,4011,Q,1142,4012,1138,4012,1129,4013,1100,4011,1063,4009,1046,4010,1041,4011,1037,4011,1006,4023,990,4023,L,933,4023,Q,846,4023,821,4011,779,3984,775,3983,765,3978,717,3978,651,3978,626,3996,565,4040,534,4041,511,4040,493,4053,488,4056,459,4081,444,4093,444,4124,442,4165,441,4169,L,425,4169,Q,422,4159,421,4156,L,379,4156,Q,377,4169,379,4212,377,4249,357,4254,299,4266,292,4274,281,4285,269,4286,253,4287,243,4288,244,4288,244,4288,238,4322,254,4346,279,4385,283,4397,290,4420,296,4457,302,4480,324,4512,325,4517,324,4583,322,4633,340,4638,362,4644,366,4649,370,4654,370,4677,371,4692,376,4707,381,4722,381,4741,381,4779,377,4783,341,4812,333,4821,313,4842,275,4896,251,4926,157,5040,125,5082,121,5131,120,5146,106,5182,90,5218,88,5238,88,5242,87,5247,315,5247,544,5245,L,599,5245,Q,605,5245,608,5258,608,5266,610,5278,613,5298,625,5350,627,5374,627,5522,657,5520,680,5504,718,5476,750,5464,796,5448,896,5461,898,5462,899,5462,L,1016,5462,Q,1020,5462,1026,5463,1019,5385,908,5305,L,908,5202,Q,975,5202,1049,5182,1079,5173,1121,5157,1172,5150,1173,5135,1172,5113,1114,5065,1052,5019,1045,5012,L,1045,4964,1148,4964,Q,1169,4975,1185,4976,1209,4976,1212,4969,1212,4948,1215,4922,1270,4917,1304,4922,1310,4920,1310,4907,1309,4884,1309,4861,1309,4826,1308,4778,1306,4732,1307,4668,1306,4664,1307,4661,1307,4593,1307,4379,1306,4378,1306,4377,1287,4247,1275,4224,L,1275,4216,1267,4216,Q,1263,4170,1258,4143,1245,4103,1240,4078,1240,4077,1240,4037,1241,4012,1226,4011,Z]],label:"Jackson-Ms",shortLabel:"JAC-MS",labelPosition:[69.8,475],labelAlignment:[CEN,MID]},736:{outlines:[[M,2810,1236,Q,2814,1275,2792,1296,2780,1309,2774,1314,2763,1322,2748,1321,2669,1321,2664,1321,2533,1314,2517,1314,2489,1317,2466,1319,2394,1326,2378,1326,L,2378,1434,Q,2384,1448,2384,1478,2396,1475,2411,1475,2413,1476,2437,1475,2444,1475,2454,1484,2462,1486,2514,1486,L,2514,1536,Q,2508,1573,2520,1579,2526,1581,2589,1581,2648,1581,2654,1580,2665,1577,2672,1551,2678,1530,2714,1530,2779,1531,2782,1530,L,2823,1530,2823,1592,Q,2847,1594,2910,1594,2910,1594,2915,1594,2927,1595,2966,1594,2998,1594,3001,1591,3006,1586,3008,1567,3010,1546,3016,1537,3022,1529,3046,1527,3073,1526,3078,1523,3088,1519,3130,1502,L,3129,1401,2978,1401,2982,1301,Q,2983,1228,2964,1219,2953,1214,2923,1214,2856,1213,2847,1212,2822,1213,2814,1219,Q,2808,1223,2810,1236,Z]],label:"Bowling Green",shortLabel:"BOW-OH",labelPosition:[270,140.4],labelAlignment:[CEN,MID]},746:{outlines:[[M,1658,5358,Q,1666,5368,1666,5393,1666,5403,1663,5407,1659,5411,1659,5422,1661,5438,1648,5448,1633,5459,1576,5454,1559,5462,1540,5466,1532,5468,1515,5487,1511,5492,1505,5500,1499,5507,1489,5507,L,1451,5507,Q,1437,5509,1427,5509,1407,5510,1401,5500,1387,5479,1359,5476,L,1358,5476,Q,1356,5479,1354,5482,L,1354,5866,1376,5866,Q,1445,5862,1446,5862,1487,5857,1499,5836,1514,5815,1553,5814,1576,5814,1620,5817,L,1911,5817,Q,1911,5790,1913,5771,L,1947,5771,Q,1950,5696,1950,5689,1950,5650,1920,5620,1889,5590,1889,5566,1889,5545,1894,5532,1900,5520,1900,5482,1900,5448,1905,5430,1911,5412,1911,5386,1911,5329,1877,5288,1844,5248,1844,5208,1845,5167,1846,5130,L,1693,5130,Q,1663,5132,1635,5128,1611,5125,1604,5124,1594,5124,1591,5133,1589,5141,1589,5169,1589,5200,1597,5235,1599,5245,1597,5264,1597,5269,1616,5288,1626,5307,1648,5328,1651,5333,1652,5343,Q,1654,5353,1658,5358,Z]],label:"Biloxi/Gulfport",shortLabel:"BIL-MS",labelPosition:[165.2,562.1],labelAlignment:[CEN,MID]}}}];exports["default"]={extension:geodefinitions,name:"eastsouthcentraldma",type:"maps"}}})});
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
var Base = require('azure-iot-mqtt-base').Mqtt;
var results = require('azure-iot-common').results;
var errors = require('azure-iot-common').errors;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
/**
* @class module:azure-iot-device-mqtt.Mqtt
* @classdesc Provides MQTT transport for the device [client]{@link module:azure-iot-device.Client} class.
*
* @param {Object} config Configuration object derived from the connection string by the client.
*/
/*
Codes_SRS_NODE_DEVICE_HTTP_12_001: [The Mqtt shall accept the transport configuration structure
Codes_SRS_NODE_DEVICE_HTTP_12_002: [The Mqtt shall store the configuration structure in a member variable
Codes_SRS_NODE_DEVICE_HTTP_12_003: [The Mqtt shall create an MqttTransport object and store it in a member variable
*/
function Mqtt(config) {
EventEmitter.call(this);
this._config = config;
this._mqtt = new Base(config);
}
util.inherits(Mqtt, EventEmitter);
/**
* @method module:azure-iot-device-mqtt.Mqtt#connect
* @description Establishes the connection to the Azure IoT Hub instance using the MQTT protocol.
*
* @param {Function} done callback that shall be called when the connection is established.
*/
/* Codes_SRS_NODE_DEVICE_HTTP_12_004: [The connect method shall call the connect method on MqttTransport */
Mqtt.prototype.connect = function (done) {
this._mqtt.connect(function (err, result) {
if (err) {
if (done) done(err);
} else {
this._mqtt.client.on('disconnect', function (err) {
this.emit('disconnect', err);
}.bind(this));
if (done) done(null, result);
}
}.bind(this));
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#disconnect
* @description Terminates the connection to the IoT Hub instance.
*
* @param {Function} done Callback that shall be called when the connection is terminated.
*/
/* Codes_SRS_NODE_DEVICE_HTTP_16_001: [The disconnect method should call the disconnect method on MqttTransport.] */
Mqtt.prototype.disconnect = function (done) {
this._mqtt.disconnect(function (err, result) {
if (done) done(err, result);
});
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#sendEvent
* @description Sends an event to the server.
*
* @param {Message} message Message used for the content of the event sent to the server.
*/
/* Codes_SRS_NODE_DEVICE_HTTP_12_005: [The sendEvent method shall call the publish method on MqttTransport */
Mqtt.prototype.sendEvent = function (message, done) {
this._mqtt.publish(message, done);
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#getReceiver
* @description Gets a receiver object that is used to receive and settle messages.
*
* @param {Function} done callback that shall be called with a receiver object instance.
*/
Mqtt.prototype.getReceiver = function (done) {
this._mqtt.getReceiver(done);
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#complete
* @description Settles the message as complete and calls the done callback with the result.
*
* @param {Message} message The message to settle as complete.
* @param {Function} done The callback that shall be called with the error or result object.
*/
/*Codes_SRS_NODE_DEVICE_MQTT_16_005: [The ‘complete’ method shall call the callback given as argument immediately since all messages are automatically completed.]*/
Mqtt.prototype.complete = function (message, done) {
done(null, new results.MessageCompleted());
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#reject
* @description Settles the message as rejected and calls the done callback with the result.
*
* @throws {Error} The MQTT transport does not support rejecting messages.
*/
/*Codes_SRS_NODE_DEVICE_MQTT_16_006: [The ‘reject’ method shall throw because MQTT doesn’t support rejecting messages.] */
Mqtt.prototype.reject = function () {
throw new errors.NotImplementedError('the MQTT transport does not support rejecting messages.');
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#abandon
* @description Settles the message as abandoned and calls the done callback with the result.
*
* @throws {Error} The MQTT transport does not support rejecting messages.
*/
/*Codes_SRS_NODE_DEVICE_MQTT_16_004: [The ‘abandon’ method shall throw because MQTT doesn’t support abandoning messages.] */
Mqtt.prototype.abandon = function () {
throw new errors.NotImplementedError('The MQTT transport does not support abandoning messages.');
};
/**
* @method module:azure-iot-device-mqtt.Mqtt#updateSharedAccessSignature
* @description This methods sets the SAS token used to authenticate with the IoT Hub service.
*
* @param {String} sharedAccessSignature The new SAS token.
* @param {Function} done The callback to be invoked when `updateSharedAccessSignature` completes.
*/
Mqtt.prototype.updateSharedAccessSignature = function (sharedAccessSignature, done) {
/*Codes_SRS_NODE_DEVICE_MQTT_16_008: [The updateSharedAccessSignature method shall disconnect the current connection operating with the deprecated token, and re-iniialize the transport object with the new connection parameters.]*/
this._mqtt.disconnect(function (err) {
if (err) {
/*Codes_SRS_NODE_DEVICE_MQTT_16_009: [The updateSharedAccessSignature method shall call the `done` method with an Error object if updating the configuration or re-initializing the transport object.]*/
if (done) done(err);
} else {
/*Codes_SRS_NODE_DEVICE_MQTT_16_007: [The updateSharedAccessSignature method shall save the new shared access signature given as a parameter to its configuration.]*/
this._config.sharedAccessSignature = sharedAccessSignature;
this._mqtt = new Base(this._config);
/*Codes_SRS_NODE_DEVICE_MQTT_16_010: [The updateSharedAccessSignature method shall call the `done` callback with a null error object and a SharedAccessSignatureUpdated object as a result, indicating hat the client needs to reestablish the transport connection when ready.]*/
done(null, new results.SharedAccessSignatureUpdated(true));
}
}.bind(this));
};
module.exports = Mqtt;
|
export { default } from 'rsg-components/Markdown/Checkbox/CheckboxRenderer';
|
import aiohttp
from typing import Callable, Dict, Iterable, List, Mapping, Any, Set
import json
import logging
import pkg_resources
import re
import os
import pathlib
import requests
from datetime import datetime, timedelta
from bs4 import BeautifulSoup # type: ignore
from typing import Union, Optional
logger = logging.getLogger(name="python-Wappalyzer")
class WappalyzerError(Exception):
"""
Raised for fatal Wappalyzer errors.
"""
pass
class WebPage:
"""
Simple representation of a web page, decoupled
from any particular HTTP library's API.
Well, except for the class methods that use `requests`
or `aiohttp` to create the WebPage.
This object is designed to be created for each website scanned
by python-Wappalyzer.
It will parse the HTML with BeautifulSoup to find <script> and <meta> tags.
You can create it from manually from HTML with the `WebPage()` method
or from the class methods.
"""
def __init__(self, url:str, html:str, headers:Mapping[str, Any]):
"""
Initialize a new WebPage object manually.
>>> from Wappalyzer import WebPage
>>> w = WebPage('exemple.com', html='<strong>Hello World</strong>', headers={'Server': 'Apache', })
:param url: The web page URL.
:param html: The web page content (HTML)
:param headers: The HTTP response headers
"""
self.url = url
self.html = html
self.headers = headers
self.scripts :List[str] = []
try:
list(self.headers.keys())
except AttributeError:
raise ValueError("Headers must be a dictionary-like object")
self._parse_html()
def _parse_html(self):
"""
Parse the HTML with BeautifulSoup to find <script> and <meta> tags.
"""
self.parsed_html = soup = BeautifulSoup(self.html, 'lxml')
self.scripts.extend(script['src'] for script in
soup.findAll('script', src=True))
self.meta = {
meta['name'].lower():
meta['content'] for meta in soup.findAll(
'meta', attrs=dict(name=True, content=True))
}
@classmethod
def new_from_url(cls, url: str, **kwargs:Any) -> 'WebPage':
"""
Constructs a new WebPage object for the URL,
using the `requests` module to fetch the HTML.
>>> from Wappalyzer import WebPage
>>> page = WebPage.new_from_url('exemple.com', timeout=5)
:param url: URL
:param headers: (optional) Dictionary of HTTP Headers to send.
:param cookies: (optional) Dict or CookieJar object to send.
:param timeout: (optional) How many seconds to wait for the server to send data before giving up.
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Boolean, it controls whether we verify the SSL certificate validity.
:param \*\*kwargs: Any other arguments are passed to `requests.get` method as well.
"""
response = requests.get(url, **kwargs)
return cls.new_from_response(response)
@classmethod
def new_from_response(cls, response:requests.Response) -> 'WebPage':
"""
Constructs a new WebPage object for the response,
using the `BeautifulSoup` module to parse the HTML.
:param response: `requests.Response` object
"""
return cls(response.url, html=response.text, headers=response.headers)
@classmethod
async def new_from_url_async(cls, url: str, verify: bool = True,
aiohttp_client_session: aiohttp.ClientSession = None, **kwargs:Any) -> 'WebPage':
"""
Same as new_from_url only Async.
Constructs a new WebPage object for the URL,
using the `aiohttp` module to fetch the HTML.
>>> from Wappalyzer import WebPage
>>> from aiohttp import ClientSession
>>> async with ClientSession() as session:
... page = await WebPage.new_from_url_async(aiohttp_client_session=session)
:param url: URL
:param aiohttp_client_session: `aiohttp.ClientSession` instance to use, optional.
:param verify: (optional) Boolean, it controls whether we verify the SSL certificate validity.
:param headers: Dict. HTTP Headers to send with the request (optional).
:param cookies: Dict. HTTP Cookies to send with the request (optional).
:param timeout: Int. override the session's timeout (optional)
:param proxy: Proxy URL, `str` or `yarl.URL` (optional).
:param \*\*kwargs: Any other arguments are passed to `aiohttp.ClientSession.get` method as well.
"""
if not aiohttp_client_session:
connector = aiohttp.TCPConnector(ssl=verify)
aiohttp_client_session = aiohttp.ClientSession(connector=connector)
async with aiohttp_client_session.get(url, **kwargs) as response:
return await cls.new_from_response_async(response)
@classmethod
async def new_from_response_async(cls, response:aiohttp.ClientResponse) -> 'WebPage':
"""
Constructs a new WebPage object for the response,
using the `BeautifulSoup` module to parse the HTML.
>>> from aiohttp import ClientSession
>>> wappalyzer = Wappalyzer.latest()
>>> async with ClientSession() as session:
... page = await session.get("http://example.com")
...
>>> webpage = await WebPage.new_from_response_async(page)
:param response: `aiohttp.ClientResponse` object
"""
html = await response.text()
return cls(str(response.url), html=html, headers=response.headers)
class Wappalyzer:
"""
Python Wappalyzer driver.
Consider the following exemples.
Here is how you can use the latest technologies file from AliasIO/wappalyzer repository.
.. python::
from Wappalyzer import Wappalyzer
wappalyzer=Wappalyzer.latest(update=True)
# Create webpage
webpage=WebPage.new_from_url('http://example.com')
# analyze
results = wappalyzer.analyze_with_categories(webpage)
Here is how you can custom request and headers arguments:
.. python::
import requests
from Wappalyzer import Wappalyzer, WebPage
wappalyzer = Wappalyzer.latest()
webpage = WebPage.new_from_url('http://exemple.com', headers={'User-Agent': 'Custom user agent'})
wappalyzer.analyze_with_categories(webpage)
"""
def __init__(self, categories:Dict[str, Any], technologies:Dict[str, Any]):
"""
Manually initialize a new Wappalyzer instance.
You might want to use the factory method: `latest`
:param categories: Map of category ids to names, as in ``technologies.json``.
:param technologies: Map of technology names to technology dicts, as in ``technologies.json``.
"""
self.categories = categories
self.technologies = technologies
self._confidence_regexp = re.compile(r"(.+)\\;confidence:(\d+)")
# TODO
for name, technology in list(self.technologies.items()):
self._prepare_technology(technology)
@classmethod
def latest(cls, technologies_file:str=None, update:bool=False) -> 'Wappalyzer':
"""
Construct a Wappalyzer instance.
Use ``update=True`` to download the very latest file from internet.
Do not update if the file has already been updated in the last 24 hours.
*New in version 0.4.0*
Use ``technologies_file=/some/path/technologies.json`` to load a
custom technologies file.
If no arguments is passed, load the default ``data/technologies.json`` file
inside the package ressource.
:param technologies_file: File path
:param update: Download and use the latest ``technologies.json`` file
from `AliasIO/wappalyzer <https://github.com/AliasIO/wappalyzer>`_ repository.
"""
default=pkg_resources.resource_string(__name__, "data/technologies.json")
defaultobj = json.loads(default)
if technologies_file:
with open(technologies_file, 'r', encoding='utf-8') as fd:
obj = json.load(fd)
elif update:
should_update = True
_technologies_file: pathlib.Path
_files = cls._find_files(['HOME', 'APPDATA',], ['.python-Wappalyzer/technologies.json'])
if _files:
_technologies_file = pathlib.Path(_files[0])
last_modification_time = datetime.fromtimestamp(_technologies_file.stat().st_mtime)
if datetime.now() - last_modification_time < timedelta(hours=24):
should_update = False
# Get the lastest file
if should_update:
try:
lastest_technologies_file=requests.get('https://raw.githubusercontent.com/AliasIO/wappalyzer/master/src/technologies.json')
obj = lastest_technologies_file.json()
_technologies_file = pathlib.Path(cls._find_files(
['HOME', 'APPDATA',],
['.python-Wappalyzer/technologies.json'],
create = True
).pop())
if obj != defaultobj:
with _technologies_file.open('w', encoding='utf-8') as tfile:
tfile.write(lastest_technologies_file.text)
logger.info("python-Wappalyzer technologies.json file updated")
except Exception as err: # Or loads default
logger.error("Could not download latest Wappalyzer technologies.json file because of error : '{}'. Using default. ".format(err))
obj = defaultobj
else:
logger.debug("python-Wappalyzer technologies.json file not updated because already updated in the last 24h")
with _technologies_file.open('r', encoding='utf-8') as tfile:
obj = json.load(tfile)
logger.info("Using technologies.json file at {}".format(_technologies_file.as_posix()))
else:
obj = defaultobj
return cls(categories=obj['categories'], technologies=obj['technologies'])
@staticmethod
def _find_files(
env_location: List[str],
potential_files: List[str],
default_content: str = "",
create: bool = False,
) -> List[str]:
"""Find existent files based on folders name and file names.
Arguments:
- `env_location`: list of environment variable to use as a base path. Exemple: ['HOME', 'XDG_CONFIG_HOME', 'APPDATA', 'PWD']
- `potential_files`: list of filenames. Exemple: ['.myapp/conf.ini',]
- `default_content`: Write default content if the file does not exist
- `create`: Create the file in the first existing env_location with default content if the file does not exist
"""
potential_paths = []
existent_files = []
env_loc_exists = False
# build potential_paths of config file
for env_var in env_location:
if env_var in os.environ:
env_loc_exists = True
for file_path in potential_files:
potential_paths.append(os.path.join(os.environ[env_var], file_path))
if not env_loc_exists and create:
raise RuntimeError(f"Cannot find any of the env locations {env_location}. ")
# If file exist, add to list
for p in potential_paths:
if os.path.isfile(p):
existent_files.append(p)
# If no file foud and create=True, init new file
if len(existent_files) == 0 and create:
os.makedirs(os.path.dirname(potential_paths[0]), exist_ok=True)
with open(potential_paths[0], "w", encoding='utf-8') as config_file:
config_file.write(default_content)
existent_files.append(potential_paths[0])
return existent_files
def _prepare_technology(self, technology: Dict[str, Any]) -> None:
"""
Normalize technology data, preparing it for the detection phase.
"""
# Ensure these keys' values are lists
for key in ['url', 'html', 'scripts', 'implies']:
try:
value = technology[key]
except KeyError:
technology[key] = []
else:
if not isinstance(value, list):
technology[key] = [value]
# Ensure these keys exist
for key in ['headers', 'meta']:
try:
value = technology[key]
except KeyError:
technology[key] = {}
# Ensure the 'meta' key is a dict
obj = technology['meta']
if not isinstance(obj, dict):
technology['meta'] = {'generator': obj}
# Ensure keys are lowercase
for key in ['headers', 'meta']:
obj = technology[key]
technology[key] = {k.lower(): v for k, v in list(obj.items())}
# Prepare regular expression patterns
for key in ['url', 'html', 'scripts']:
patterns = []
for pattern in technology[key]:
patterns.extend(self._prepare_pattern(pattern))
technology[key] = patterns
for key in ['headers', 'meta']:
obj = technology[key]
for name, pattern in list(obj.items()):
obj[name] = self._prepare_pattern(obj[name])
def _prepare_pattern(self, pattern:Union[str, List[str]]) -> List[Dict[str, Any]]:
"""
Strip out key:value pairs from the pattern and compile the regular
expression.
"""
prep_patterns = []
if isinstance(pattern, list):
for p in pattern:
prep_patterns.extend(self._prepare_pattern(p))
else:
attrs = {}
patterns = pattern.split('\\;')
for index, expression in enumerate(patterns):
if index == 0:
attrs['string'] = expression
try:
attrs['regex'] = re.compile(expression, re.I) # type: ignore
except re.error as err:
# Wappalyzer is a JavaScript application therefore some of the regex wont compile in Python.
logger.debug(
"Caught '{error}' compiling regex: {regex}".format(
error=err, regex=patterns)
)
# regex that never matches:
# http://stackoverflow.com/a/1845097/413622
attrs['regex'] = re.compile(r'(?!x)x') # type: ignore
else:
attr = expression.split(':')
if len(attr) > 1:
key = attr.pop(0)
attrs[str(key)] = ':'.join(attr)
prep_patterns.append(attrs)
return prep_patterns
def _has_technology(self, technology: Dict[str, Any], webpage: WebPage) -> bool:
"""
Determine whether the web page matches the technology signature.
"""
app = technology
has_app = False
# Search the easiest things first and save the full-text search of the
# HTML for last
for pattern in app['url']:
if pattern['regex'].search(webpage.url):
self._set_detected_app(app, 'url', pattern, webpage.url)
for name, patterns in list(app['headers'].items()):
if name in webpage.headers:
content = webpage.headers[name]
for pattern in patterns:
if pattern['regex'].search(content):
self._set_detected_app(app, 'headers', pattern, content, name)
has_app = True
for pattern in technology['scripts']:
for script in webpage.scripts:
if pattern['regex'].search(script):
self._set_detected_app(app, 'scripts', pattern, script)
has_app = True
for name, patterns in list(technology['meta'].items()):
if name in webpage.meta:
content = webpage.meta[name]
for pattern in patterns:
if pattern['regex'].search(content):
self._set_detected_app(app, 'meta', pattern, content, name)
has_app = True
for pattern in app['html']:
if pattern['regex'].search(webpage.html):
self._set_detected_app(app, 'html', pattern, webpage.html)
has_app = True
# Set total confidence
if has_app:
total = 0
for index in app['confidence']:
total += app['confidence'][index]
app['confidenceTotal'] = total
return has_app
def _set_detected_app(self, app: Dict[str, Any], app_type:str, pattern: Dict[str, Any], value:str, key='') -> None:
"""
Store detected app.
"""
app['detected'] = True
# Set confidence level
if key != '':
key += ' '
if 'confidence' not in app:
app['confidence'] = {}
if 'confidence' not in pattern:
pattern['confidence'] = 100
else:
# Convert to int for easy adding later
pattern['confidence'] = int(pattern['confidence'])
app['confidence'][app_type + ' ' + key + pattern['string']] = pattern['confidence']
# Dectect version number
if 'version' in pattern:
allmatches = re.findall(pattern['regex'], value)
for i, matches in enumerate(allmatches):
version = pattern['version']
# Check for a string to avoid enumerating the string
if isinstance(matches, str):
matches = [(matches)]
for index, match in enumerate(matches):
# Parse ternary operator
ternary = re.search(re.compile('\\\\' + str(index + 1) + '\\?([^:]+):(.*)$', re.I), version)
if ternary and len(ternary.groups()) == 2 and ternary.group(1) is not None and ternary.group(2) is not None:
version = version.replace(ternary.group(0), ternary.group(1) if match != ''
else ternary.group(2))
# Replace back references
version = version.replace('\\' + str(index + 1), match)
if version != '':
if 'versions' not in app:
app['versions'] = [version]
elif version not in app['versions']:
app['versions'].append(version)
self._set_app_version(app)
def _set_app_version(self, app: Dict[str, Any]) -> None:
"""
Resolve version number (find the longest version number that *is supposed to* contains all shorter detected version numbers).
TODO: think if it's the right wat to handled version detection.
"""
if 'versions' not in app:
return
app['versions'] = sorted(app['versions'], key=self._cmp_to_key(self._sort_app_versions))
def _get_implied_technologies(self, detected_technologies:Iterable[str]) -> Iterable[str]:
"""
Get the set of technologies implied by `detected_technologies`.
"""
def __get_implied_technologies(technologies:Iterable[str]) -> Iterable[str] :
_implied_technologies = set()
for tech in technologies:
try:
for implie in self.technologies[tech]['implies']:
# If we have no doubts just add technology
if 'confidence' not in implie:
_implied_technologies.add(implie)
# Case when we have "confidence" (some doubts)
else:
try:
# Use more strict regexp (cause we have already checked the entry of "confidence")
# Also, better way to compile regexp one time, instead of every time
app_name, confidence = self._confidence_regexp.search(implie).groups() # type: ignore
if int(confidence) >= 50:
_implied_technologies.add(app_name)
except (ValueError, AttributeError):
pass
except KeyError:
pass
return _implied_technologies
implied_technologies = __get_implied_technologies(detected_technologies)
all_implied_technologies : Set[str] = set()
# Descend recursively until we've found all implied technologies
while not all_implied_technologies.issuperset(implied_technologies):
all_implied_technologies.update(implied_technologies)
implied_technologies = __get_implied_technologies(all_implied_technologies)
return all_implied_technologies
def get_categories(self, tech_name:str) -> List[str]:
"""
Returns a list of the categories for an technology name.
:param tech_name: Tech name
"""
cat_nums = self.technologies.get(tech_name, {}).get("cats", [])
cat_names = [self.categories.get(str(cat_num), "").get("name", "")
for cat_num in cat_nums]
return cat_names
def get_versions(self, app_name:str) -> List[str]:
"""
Retuns a list of the discovered versions for an app name.
:param app_name: App name
"""
return [] if 'versions' not in self.technologies[app_name] else self.technologies[app_name]['versions']
def get_confidence(self, app_name:str) -> Optional[int]:
"""
Returns the total confidence for an app name.
:param app_name: App name
"""
return None if 'confidenceTotal' not in self.technologies[app_name] else self.technologies[app_name]['confidenceTotal']
def analyze(self, webpage:WebPage) -> Set[str]:
"""
Return a set of technology that can be detected on the web page.
:param webpage: The Webpage to analyze
"""
detected_technologies = set()
for tech_name, technology in list(self.technologies.items()):
if self._has_technology(technology, webpage):
detected_technologies.add(tech_name)
detected_technologies.update(self._get_implied_technologies(detected_technologies))
return detected_technologies
def analyze_with_versions(self, webpage:WebPage) -> Dict[str, Dict[str, Any]]:
"""
Return a dict of applications and versions that can be detected on the web page.
:param webpage: The Webpage to analyze
"""
detected_apps = self.analyze(webpage)
versioned_apps = {}
for app_name in detected_apps:
versions = self.get_versions(app_name)
versioned_apps[app_name] = {"versions": versions}
return versioned_apps
def analyze_with_categories(self, webpage:WebPage) -> Dict[str, Dict[str, Any]]:
"""
Return a dict of technologies and categories that can be detected on the web page.
:param webpage: The Webpage to analyze
>>> wappalyzer.analyze_with_categories(webpage)
{'Amazon ECS': {'categories': ['IaaS']},
'Amazon Web Services': {'categories': ['PaaS']},
'Azure CDN': {'categories': ['CDN']},
'Docker': {'categories': ['Containers']}}
"""
detected_technologies = self.analyze(webpage)
categorised_technologies = {}
for tech_name in detected_technologies:
cat_names = self.get_categories(tech_name)
categorised_technologies[tech_name] = {"categories": cat_names}
return categorised_technologies
def analyze_with_versions_and_categories(self, webpage:WebPage) -> Dict[str, Dict[str, Any]]:
"""
Return a dict of applications and versions and categories that can be detected on the web page.
:param webpage: The Webpage to analyze
>>> wappalyzer.analyze_with_versions_and_categories(webpage)
{'Font Awesome': {'categories': ['Font scripts'], 'versions': ['5.4.2']},
'Google Font API': {'categories': ['Font scripts'], 'versions': []},
'MySQL': {'categories': ['Databases'], 'versions': []},
'Nginx': {'categories': ['Web servers', 'Reverse proxies'], 'versions': []},
'PHP': {'categories': ['Programming languages'], 'versions': ['5.6.40']},
'WordPress': {'categories': ['CMS', 'Blogs'], 'versions': ['5.4.2']},
'Yoast SEO': {'categories': ['SEO'], 'versions': ['14.6.1']}}
"""
versioned_apps = self.analyze_with_versions(webpage)
versioned_and_categorised_apps = versioned_apps
for app_name in versioned_apps:
cat_names = self.get_categories(app_name)
versioned_and_categorised_apps[app_name]["categories"] = cat_names
return versioned_and_categorised_apps
def _sort_app_versions(self, version_a: str, version_b: str) -> int:
return len(version_a) - len(version_b)
def _cmp_to_key(self, mycmp: Callable[..., Any]):
"""
Convert a cmp= function into a key= function
"""
# https://docs.python.org/3/howto/sorting.html
class CmpToKey:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return CmpToKey
def analyze(url:str,
update:bool=False,
useragent:str=None,
timeout:int=10,
verify:bool=True) -> Dict[str, Dict[str, Any]]:
"""
Quick utility method to analyze a website with minimal configurable options.
:See: `WebPage` and `Wappalyzer`.
:Parameters:
- `url`: URL
- `update`: Update the technologies file from the internet
- `useragent`: Request user agent
- `timeout`: Request timeout
- `verify`: SSL cert verify
:Return:
`dict`. Just as `Wappalyzer.analyze_with_versions_and_categories`.
:Note: More information might be added to the returned values in the future
"""
# Create Wappalyzer
wappalyzer=Wappalyzer.latest(update=update)
# Create WebPage
headers={}
if useragent:
headers['User-Agent'] = useragent
webpage=WebPage.new_from_url(url,
headers=headers,
timeout=timeout,
verify=verify)
# Analyze
results = wappalyzer.analyze_with_versions_and_categories(webpage)
return results
|
mycallback( {"CONTRIBUTOR OCCUPATION": "Diagnostic Radiologist", "CONTRIBUTION AMOUNT (F3L Bundled)": "150.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "Radiological Assoc. of Sacramento", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "1501 Chalupa Pl", "CONTRIBUTOR MIDDLE NAME": "", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "CA", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Bahram", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20101231", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00343459", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Varjavand", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "956186757", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "Davis", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "38220433", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727350.fec_2.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "Dr.", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "600.00", "FORM TYPE": "SA11ai"});
|
import game_2048 from "./game_2048.js";
const {left, right, up, down} = game_2048;
const print_boards = function (b1, b2) {
const string_rows_1 = b1.map(String);
const string_rows_2 = b2.map(String);
const padding = [" ", " --\\ ", " --/ ", " "];
const output = padding.map(
(p, k) => string_rows_1[k] + p + string_rows_2[k] + "\n"
).reduce(
(a, x) => a + x
);
console.log(output);
};
const board = [
[1, 1, 2, 2],
[1, 0, 0, 1],
[0, 0, 1, 1],
[0, 2, 2, 3]
];
print_boards(board, right(board));
print_boards(right(board), left(right(board)));
print_boards(left(right(board)), up(left(right(board))));
print_boards(up(left(right(board))), down(up(left(right(board)))));
|
from abc import ABC, abstractmethod
class Clothes(ABC):
@abstractmethod
def calculate(self):
pass
class Coat(Clothes):
def __init__(self, size: float):
self.size = size
@property
def calculate(self):
return round(self.size / 6.5 + 0.5, 2)
class Costume(Clothes):
def __init__(self, height: float):
self.height = height
@property
def calculate(self):
return round(2 * self.height + 0.3, 2)
if __name__ == '__main__':
coat = Coat(45.0)
costume = Costume(3)
print(coat.calculate)
print(costume.calculate)
|
/*************
**** <config>
**/
stepIn = 20; // delay when fading in
stepOut = 20; // delay when fading out
/*
** set to true or false; true will
** cause all links to fade automatically
***/
autoFade = true;
/*
** set to true or false; true will cause all CSS
** classes with "fade" in them to fade onmouseover
***/
sloppyClass = true;
/**
**** </config>
**************/
/*************
**** <install>
**
**
**** </install>
**************/
hexa = new makearray(16);
for(var i = 0; i < 10; i++)
hexa[i] = i;
hexa[10]="a"; hexa[11]="b"; hexa[12]="c";
hexa[13]="d"; hexa[14]="e"; hexa[15]="f";
document.onmouseover = domouseover;
document.onmouseout = domouseout;
startColor = dehexize(startColor.toLowerCase());
endColor = dehexize(endColor.toLowerCase());
var fadeId = new Array();
function dehexize(Color){
var colorArr = new makearray(3);
for (i=1; i<7; i++){
for (j=0; j<16; j++){
if (Color.charAt(i) == hexa[j]){
if (i%2 !=0)
colorArr[Math.floor((i-1)/2)]=eval(j)*16;
else
colorArr[Math.floor((i-1)/2)]+=eval(j);
}
}
}
return colorArr;
}
function domouseover() {
if(document.all){
var srcElement = event.srcElement;
if ((srcElement.tagName == "A" && autoFade && srcElement.className.indexOf("admincolor") == -1 && srcElement.className.indexOf("modcolor") == -1) || srcElement.className == "fade" || (sloppyClass && srcElement.className.indexOf("fade") != -1))
fade(startColor,endColor,srcElement.uniqueID,stepIn);
}
}
function domouseout() {
if (document.all){
var srcElement = event.srcElement;
if ((srcElement.tagName == "A" && autoFade && srcElement.className.indexOf("admincolor") == -1 && srcElement.className.indexOf("modcolor") == -1) || srcElement.className == "fade" || (sloppyClass && srcElement.className.indexOf("fade") != -1))
fade(endColor,startColor,srcElement.uniqueID,stepOut);
}
}
function makearray(n) {
this.length = n;
for(var i = 1; i <= n; i++)
this[i] = 0;
return this;
}
function hex(i) {
if (i < 0)
return "00";
else if (i > 255)
return "ff";
else
return "" + hexa[Math.floor(i/16)] + hexa[i%16];}
function setColor(r, g, b, element) {
var hr = hex(r); var hg = hex(g); var hb = hex(b);
element.style.color = "#"+hr+hg+hb;
}
function fade(s,e, element,step){
var sr = s[0]; var sg = s[1]; var sb = s[2];
var er = e[0]; var eg = e[1]; var eb = e[2];
if (fadeId[0] != null && fade[0] != element){
setColor(sr,sg,sb,eval(fadeId[0]));
var i = 1;
while(i < fadeId.length){
clearTimeout(fadeId[i]);
i++;
}
}
for(var i = 0; i <= step; i++) {
fadeId[i+1] = setTimeout("setColor(Math.floor(" +sr+ " *(( " +step+ " - " +i+ " )/ " +step+ " ) + " +er+ " * (" +i+ "/" +
step+ ")),Math.floor(" +sg+ " * (( " +step+ " - " +i+ " )/ " +step+ " ) + " +eg+ " * (" +i+ "/" +step+
")),Math.floor(" +sb+ " * ((" +step+ "-" +i+ ")/" +step+ ") + " +eb+ " * (" +i+ "/" +step+ ")),"+element+");",i*step);
}
fadeId[0] = element;
}
|
'use strict';
// /**
// * Synchronize zooming through the setExtremes event handler.
// */
// function syncExtremes(e) {
// var thisChart = this.chart;
//
// if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
// window.charts.forEach( function (chart) {
// if (chart !== thisChart) {
// if (chart.xAxis[0].setExtremes) { // It is null while updating
// chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
// }
// }
// });
// }
// }
/**
* Custom Axis extension to allow emulation of negative values on a logarithmic
* Y axis. Note that the scale is not mathematically correct, as a true
* logarithmic axis never reaches or crosses zero.
*/
(function (H) {
// Pass error messages
H.Axis.prototype.allowNegativeLog = true;
// Override conversions
H.Axis.prototype.log2lin = function (num) {
var isNegative = num < 0,
adjustedNum = Math.abs(num),
result;
if (adjustedNum < 10) {
adjustedNum += (10 - adjustedNum) / 10;
}
result = Math.log(adjustedNum) / Math.LN10;
return isNegative ? -result : result;
};
H.Axis.prototype.lin2log = function (num) {
var isNegative = num < 0,
absNum = Math.abs(num),
result = Math.pow(10, absNum);
if (result < 10) {
result = (10 * (result - 1)) / (10 - 1);
}
return isNegative ? -result : result;
};
}(Highcharts));
$(document).ready(function () {
if (job.complete && !job.failed) {
initializeGraphs();
} else {
pollUntilDone(5000, 0).then(function(bases) {
job.result = {bases: bases};
$.get(window.location.pathname + "/content", function(fragment) {
$("#job-view-content").replaceWith(fragment); // update snippet of page
initializeGraphs();
});
}).catch(function(err) {
console.error(err);
});
}
});
// create a promise that resolves after a short delay
function delay(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
}
function pollUntilDone(interval, timeout) {
let start = Date.now();
function run() {
return $.get(window.location.pathname + "/bases").then(function(bases) {
if ( bases.length > 0 ) {
// done
return bases;
} else {
if (timeout !== 0 && Date.now() - start > timeout) {
throw new Error("timeout error on pollUntilDone");
} else {
// run again with a short delay
return delay(interval).then(run);
}
}
});
}
return run();
}
function updateBinaryCutoff() {
window.heatmapChart.colorAxis[0].update({
stops: [[0, '#a1dab4'],
[window.heatmapChart.heatmapCutoff, '#a1dab4'],
[window.heatmapChart.heatmapCutoff, '#253494'],
[1, '#253494']],
tickPositions: [0, window.heatmapChart.heatmapCutoff, 1]
});
}
function resetCutoff() {
window.heatmapChart.heatmapCutoff = 0.88;
$('#cutoff').val(window.heatmapChart.heatmapCutoff);
$('#cutoff-value').html(parseFloat(window.heatmapChart.heatmapCutoff).toFixed(2));
if ($('#binary-radio').prop("checked", true)) {
updateBinaryCutoff();
}
}
function initializeGraphs() {
$('#job-graphs').bind('mouseleave', function(e) {
window.charts.forEach(function (chart) {
chart.tooltip.hide();
chart.xAxis[0].removePlotLine('plot-line-sync');
});
});
const $cutoffContainer = $('#cutoff-container');
const $gradRad = $('#grad-radio');
$gradRad.bind('change', function () {
$cutoffContainer.hide();
window.heatmapChart.colorAxis[0].update(window.heatmapChart.gradientColorAxis);
});
const $binRad = $('#binary-radio');
$binRad.bind('change', function () {
$cutoffContainer.show();
updateBinaryCutoff();
});
const $cutoff = $('#cutoff');
const $cutoffVal = $('#cutoff-value');
$cutoff.bind('input', function () {
window.heatmapChart.heatmapCutoff = this.value;
$cutoffVal.html(parseFloat(this.value).toFixed(2));
});
$cutoff.bind('mouseup touchend', function () {
if ($binRad.prop("checked", true)) {
updateBinaryCutoff();
}
});
let data = [];
let categories = [];
let depth = [];
let iupData = [];
let espritzData = [];
let conservation = [];
job.result.bases.forEach(function (base, x) {
// if (x < 100) {
categories.push(base.reference);
depth.push(base.depth);
iupData.push(base.iupred);
espritzData.push(base.espritz);
conservation.push(base.conservation);
if (base.list.length === 0) {
base.list = new Array(20).fill(0);
}
base.list.forEach(function (val, y) {
// if (y < 5) {
data.push([x+1, y, val]);
// }
});
// }
});
// let predictionData = [{name: "IUPred -l", type: "area", data: iupData},{name: "ESpritz -D", type: "line", color: "red", data: espritzData}];
let conservationData = [{name: "Conservation", type: "area", data: conservation}];
let depthData = [{name:"Depth", type: "area", data:depth}];
window.charts = [];
if (data.length !== 0) {
window.heatmapChart = new Highcharts.Chart(
document.getElementById('heatmap-container'),
createHeatMap( "Position Conservation Matrix", data, categories)
);
window.heatmapChart.heatmapCutoff = 0.88;
window.heatmapChart.gradientColorAxis = {
stops: window.heatmapChart.colorAxis[0].stops,
tickPositions: window.heatmapChart.colorAxis[0].tickPositions
};
$("#heatmap-axis-toggle").show();
charts.push( window.heatmapChart );
}
if (conservationData.every(function(v) {return v.data.length !== 0})) {
window.conservationChart = new Highcharts.Chart(
document.getElementById('conservation-container'),
createChart( "Conservation", conservationData, true, false, "linear")
);
charts.push( window.conservationChart );
}
if (depthData.every(function(v) {return v.data.length !== 0})) {
window.depthChart = new Highcharts.Chart(
document.getElementById('depth-container'),
createChart( "Alignment Depth", depthData, true, true, "linear")
);
charts.push( window.depthChart );
}
// if (predictionData.every(function(v) {return v.data.length !== 0})) {
// window.predictionChart = new Highcharts.Chart(
// document.getElementById('prediction-container'),
// createHeatMap( "Depth", predictionData, true, true, "linear")
// );
// charts.push( window.predictionChart );
// }
}
function createHeatMap(title,
data,
categories) {
return {
chart: {
type: 'heatmap',
zoomType: 'x',
resetZoomButton: {
position: {
// align: 'right', // by default
// verticalAlign: 'top', // by default
x: 0,
y: -40
}
},
height: 300,
marginLeft: 60,
marginRight: 75,
marginTop: 40,
// marginBottom: 80,
plotBorderWidth: 1,
events : {
load: function() {
console.log( "loading chart", this );
},
selection: function (event) {
if (event.resetSelection) {
window.charts.forEach(function (chart) {
// Chosen instead of zoomOut as is doesn't trigger selection
chart.zoom();
});
// window.heatmapChart.zoom();
return false;
}
var extremesObject = event.xAxis[0],
min = Math.round(extremesObject.min),
max = Math.round(extremesObject.max);
// Smooth hacks
window.charts.forEach(function (chart) {
chart.xAxis[0].setExtremes(min - 0.5, max + 0.5);
});
window.heatmapChart.xAxis[0].setExtremes(min, max);
if (!heatmapChart.resetZoomButton) {
window.heatmapChart.showResetZoom();
}
return false;
}
}
},
boost: {
useGPUTranslations: true
},
credits: false,
title: {
text: title,
align: 'left',
margin: 0,
x: 70,
style: {
fontSize: '1.8em',
},
},
plotOptions: {
series: {
point: {
events: {
mouseOver: function (e) {
var p = this;
window.charts.forEach(function (chart) {
try {
chart.xAxis[0].removePlotLine('plot-line-sync');
chart.xAxis[0].addPlotLine({
value: p.x,
color: "#525252",
width: 1,
zIndex: 5,
id: 'plot-line-sync'
});
// Synchronized Labels
if (p.series.chart !== chart && chart.series[0].type !== "heatmap" ) {
let pps = [];
chart.series.forEach(function (s) {
let pp = {};
if (chart.isBoosting) {
pp = s.getPoint({i: p.x - 1});
pp.plotX = s.xAxis.toPixels(pp.x) - chart.plotLeft;
pp.plotY = s.yAxis.toPixels(pp.y) - chart.plotTop;
} else {
pp = s.data[p.x - 1];
}
pps.push(pp);
});
chart.tooltip.refresh(pps); // Show the tooltip
}
} catch (e) {
console.log(e);
}
});
}
}
}
}
},
xAxis: [{
minPadding: 0,
maxPadding: 0,
startOnTick: false,
endOnTick: false,
allowDecimals: false,
tickWidth: 0,
labels: {
style: {
fontSize: '1.5em',
color: '#000000',
},
}
}, {
// visible: this.props.data.length <= 100,
linkedTo: 0,
allowDecimals: false,
minPadding: 0,
maxPadding: 0,
startOnTick: false,
endOnTick: false,
tickInterval: 1,
tickWidth: 0,
tickLength: 0,
opposite: false,
lineWidth: 0,
offset:-9,
labels: {
step: 1,
formatter: function (e) {
if (this.axis.max - this.axis.min < 100) {
return categories[this.value - 1];
} else {
return "";
}
},
style: {
fontSize: '0.95em',
color: '#000000',
},
}
}],
yAxis: {
categories: ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'],
title: null,
tickInterval: 1,
startOnTick: true,
endOnTick: false,
min: 0,
max: 19,
padding: 1,
step: 1,
tickWidth: 0,
labels: {
align: 'center',
step: 1,
style: {
fontSize: '1em',
color: '#000000',
},
},
},
colorAxis: {
min: 0,
max: 1,
stops: [[0, '#ffffff'],
[0.1, '#ffffcc'],
[0.6, '#a1dab4'],
[0.8, '#41b6c4'],
[0.9, '#2c7fb8'],
[0.95, '#253494']],
labels: {
x: 5,
style: {
fontSize: '1.5em',
color: '#000000',
}
},
tickPositions: [0, 0.5, 1],
// minColor: '#FFFFFF',
// maxColor: '#000099' //Highcharts.getOptions().colors[0]
},
legend: {
align: 'right',
layout: 'vertical',
margin: 0,
verticalAlign: 'middle',
// y: 0,
// symbolHeight: 217,
navigation: {
enabled: false,
arrowSize: 0,
}
},
tooltip: {
formatter: function () {
return 'Mutation: <b>' + categories[this.point.x - 1] + ' ' + this.point.x + ' ' +
this.series.yAxis.categories[this.point.y] + '<br></b>Effect: <b>' + this.point.value + '</b>';
},
shared: false
},
series: [{
boostThreshold: 100,
name: 'LIST',
borderWidth: 0,
data: data,
dataLabels: {
enabled: false,
color: '#000000'
},
turboThreshold: 1000,
}],
exporting: {
filename: job.label,
sourceWidth: 1200,
sourceHeight: 500,
chartOptions: {
chart : {
marginTop: 60,
},
title: {
style: {
fontSize: '3em'
}
},
xAxis: {
tickPixelInterval: 150,
labels: {
style: {
fontSize: '3em'
}
},
tickWidth: null,
},
yAxis: {
labels: {
style: {
fontSize: '1.5em'
}
}
},
legend: {
symbolHeight: 350,
},
colorAxis: {
labels: {
style: {
fontSize: '1.5em'
}
}
}
}
}
};
}
function createChart(title,
data,
xAxisVisible,
enableCredit,
yAxisType) {
const options = {
title: {
text: title,
align: 'left',
margin: 0,
x: 70,
style: {
fontSize: '1.8em',
},
},
credits: enableCredit,
chart: {
height: 200,
marginLeft: 60,
marginRight: 75,
spacingTop: 20,
spacingBottom: 20,
zoomType: 'x',
resetZoomButton: {
position: {
// align: 'right', // by default
// verticalAlign: 'top', // by default
x: 0,
y: -40
}
},
events : {
load: function() {
console.log( "loading chart", this );
},
selection: function (event) {
if (event.resetSelection) {
window.charts.forEach(function (chart) {
// Chosen instead of zoomOut as is doesn't trigger selection
chart.zoom();
});
// window.heatmapChart.zoom();
return false;
}
var extremesObject = event.xAxis[0],
min = Math.round(extremesObject.min),
max = Math.round(extremesObject.max);
// Smooth hacks
window.charts.forEach(function (chart) {
chart.xAxis[0].setExtremes(min - 0.5, max + 0.5);
});
window.heatmapChart.xAxis[0].setExtremes(min, max);
if (!heatmapChart.resetZoomButton) {
window.heatmapChart.showResetZoom();
}
return false;
}
}
},
boost: {
usePreallocated: false,
useGPUTranslations: true,
},
plotOptions: {
series: {
pointStart: 1,
point: {
events: {
mouseOver: function (e) {
var p = this;
window.charts.forEach(function (chart) {
try {
chart.xAxis[0].removePlotLine('plot-line-sync');
chart.xAxis[0].addPlotLine({
value: p.x,
color: "#525252",
width: 1,
zIndex: 5,
id: 'plot-line-sync'
});
// Synchronized Labels
if (p.series.chart !== chart && chart.series[0].type !== "heatmap") {
let pps = [];
chart.series.forEach(function(s) {
let pp = {};
if (chart.isBoosting) {
pp = s.getPoint({i: p.x - 1});
pp.plotX = s.xAxis.toPixels(pp.x) - chart.plotLeft;
pp.plotY = s.yAxis.toPixels(pp.y) - chart.plotTop;
} else {
pp = s.data[p.x - 1];
}
pps.push(pp);
});
chart.tooltip.refresh(pps); // Show the tooltip
}
} catch (e) {
console.log(e);
}
});
}
}
}
}
},
xAxis: {
min: 0.5,
max: data[0].data.length + 0.5,
minTickInterval: 1,
allowDecimals: false,
crosshair: true,
minPadding: 0,
maxPadding: 0,
startOnTick: false,
endOnTick: false,
visible: xAxisVisible,
labels: {
style: {
fontSize: '1.5em',
color: '#000000',
},
}
},
yAxis: {
title: null,
type: yAxisType,
maxPadding: 0,
minPadding:0,
labels: {
style: {
fontSize: '1.5em',
color: '#000000',
},
}
},
legend: {
enabled: data.length > 1,
align: 'right',
verticalAlign: 'top',
x: -60,
y: -5,
floating: true,
itemStyle: {
fontSize: '1.2em',
},
itemDistance: 50,
},
tooltip: {
shared: true,
},
series: [],
exporting: {
filename: job.label + "-" + title,
sourceWidth: 1200,
sourceHeight: 500,
chartOptions: {
chart : {
marginTop: 60,
marginRight: 20,
marginLeft: 80,
events: {
load: function() {
this.xAxis[0].removePlotLine('plot-line-sync');
}
}
},
title: {
style: {
fontSize: '3em',
},
},
legend: {
itemStyle: {
fontSize: '2.5em',
},
symbolPadding: 10,
},
xAxis: {
tickPixelInterval: 150,
labels: {
style: {
fontSize: '3em'
}
}
},
yAxis: {
labels: {
style: {
fontSize: '3em'
}
}
},
}
}
};
data.forEach(function(series) {
options.series.push({
boostThreshold: 1000,
name: series.name,
type: series.type,
data: series.data,
color: series.color,
marker: {
enabled: false,
states: {
hover: {
enabled: false,
}
}
}
})
});
return options;
}
|
'use strict';
const lowkie = require('lowkie');
const Schema = lowkie.Schema;
const ObjectId = Schema.ObjectId;
const scheme = {
id: ObjectId,
entitytype: String,
email: {
type: String,
unique: true,
},
password: String,
first_name: String,
last_name: String,
phone: String,
status: {
email_verified: {
type: Boolean,
default: false,
},
active: {
type: Boolean,
default: false,
},
mfa: {
type: Boolean,
default: false,
},
},
primaryasset: {
type: ObjectId,
ref: 'Asset',
},
association: {
organization: {
type: ObjectId,
ref: 'Organization',
},
},
userroles: [{
type: ObjectId,
ref: 'Userrole',
},
],
};
module.exports = {
scheme,
options: {},
coreDataOptions: {
docid: ['_id', 'name', ],
sort: { createdat: -1, },
search: ['first_name', 'last_name', 'email', ],
population: 'association.organization primaryasset userroles',
},
};
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version__ = "1.3.1"
|
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class LearningAssignmentAggregateParam(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
LearningAssignmentAggregateParam - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'interval': 'str',
'metrics': 'list[str]',
'group_by': 'list[str]',
'filter': 'LearningAssignmentAggregateQueryRequestFilter'
}
self.attribute_map = {
'interval': 'interval',
'metrics': 'metrics',
'group_by': 'groupBy',
'filter': 'filter'
}
self._interval = None
self._metrics = None
self._group_by = None
self._filter = None
@property
def interval(self):
"""
Gets the interval of this LearningAssignmentAggregateParam.
Specifies the range of due dates to be used for filtering. Milliseconds will be truncated. A maximum of 1 year can be specified in the range. End date is not inclusive. Intervals are represented as an ISO-8601 string. For example: YYYY-MM-DDThh:mm:ss/YYYY-MM-DDThh:mm:ss
:return: The interval of this LearningAssignmentAggregateParam.
:rtype: str
"""
return self._interval
@interval.setter
def interval(self, interval):
"""
Sets the interval of this LearningAssignmentAggregateParam.
Specifies the range of due dates to be used for filtering. Milliseconds will be truncated. A maximum of 1 year can be specified in the range. End date is not inclusive. Intervals are represented as an ISO-8601 string. For example: YYYY-MM-DDThh:mm:ss/YYYY-MM-DDThh:mm:ss
:param interval: The interval of this LearningAssignmentAggregateParam.
:type: str
"""
self._interval = interval
@property
def metrics(self):
"""
Gets the metrics of this LearningAssignmentAggregateParam.
The list of metrics to be returned. If omitted, all metrics are returned.
:return: The metrics of this LearningAssignmentAggregateParam.
:rtype: list[str]
"""
return self._metrics
@metrics.setter
def metrics(self, metrics):
"""
Sets the metrics of this LearningAssignmentAggregateParam.
The list of metrics to be returned. If omitted, all metrics are returned.
:param metrics: The metrics of this LearningAssignmentAggregateParam.
:type: list[str]
"""
self._metrics = metrics
@property
def group_by(self):
"""
Gets the group_by of this LearningAssignmentAggregateParam.
Specifies if the aggregated data is combined into a single set of metrics (groupBy is empty or not specified), or contains an element per attendeeId (groupBy is \"attendeeId\")
:return: The group_by of this LearningAssignmentAggregateParam.
:rtype: list[str]
"""
return self._group_by
@group_by.setter
def group_by(self, group_by):
"""
Sets the group_by of this LearningAssignmentAggregateParam.
Specifies if the aggregated data is combined into a single set of metrics (groupBy is empty or not specified), or contains an element per attendeeId (groupBy is \"attendeeId\")
:param group_by: The group_by of this LearningAssignmentAggregateParam.
:type: list[str]
"""
self._group_by = group_by
@property
def filter(self):
"""
Gets the filter of this LearningAssignmentAggregateParam.
The filter applied to the data. This is ANDed with the interval parameter.
:return: The filter of this LearningAssignmentAggregateParam.
:rtype: LearningAssignmentAggregateQueryRequestFilter
"""
return self._filter
@filter.setter
def filter(self, filter):
"""
Sets the filter of this LearningAssignmentAggregateParam.
The filter applied to the data. This is ANDed with the interval parameter.
:param filter: The filter of this LearningAssignmentAggregateParam.
:type: LearningAssignmentAggregateQueryRequestFilter
"""
self._filter = filter
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_json(self):
"""
Returns the model as raw JSON
"""
return json.dumps(sanitize_for_serialization(self.to_dict()))
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var testProps = [
'testConfigBoolean',
'testConfigBooleanFalse',
'testConfigMissing',
'testConfigString',
'testConfigStringEquals',
'testConfigStringNotEquals',
'testConfigIntEquals',
'testConfigIntNotEquals',
'testConfigIntGreater',
'testConfigIntLess',
'testTrue',
'testFalse',
'testAll',
'testAsyncTrue',
'testAsyncFalse',
'executableTrue',
'executableFalse'
];
var tests = {
setUp: function( done ) {
// setup here if necessary
done();
}
};
testProps.forEach( function( prop ) {
tests[ prop ] = function( test ) {
test.expect( 1 );
var actual = grunt.file.readJSON( 'tmp/results.json' )[prop];
var expected = grunt.file.readJSON( 'test/expected/results.json' )[prop];
//var expected = grunt.file.readJSON( 'test/expected/results.json' )[prop];
test.equal( actual, expected, prop + ' result not expected ' );
test.done();
};
} );
exports.if = tests;
|
// https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
// Runtime: 72 ms, faster than 90.78% of JavaScript online submissions for Binary Tree Level Order Traversal II.
// Memory Usage: 38.7 MB, less than 7.45% of JavaScript online submissions for Binary Tree Level Order Traversal II.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/*
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function (root) {
let map = {}
let traverse = (node, lv) => {
if (!node) return;
if (map[lv] === undefined) map[lv] = [];
map[lv].push(node.val);
node.left && traverse(node.left, lv + 1);
node.right && traverse(node.right, lv + 1);
}
traverse(root, 1);
let result = [];
for (let i in map) {
result.unshift(map[i]);
}
return result;
};
|
"use strict";
///////////////////////////////////////////////////////////
// Constants
///////////////////////////////////////////////////////////
var CARD_SLIDE_DURATION_MS = 450;
var DONATION_LINK_VARIETIES = 6;
var DONATION_PAGE_VARIETIES = 5;
var BUG_REPORT_MAX_SIZE = 0.74 * 1024 * 1024;
var OPTIONS_INIT_RETRY_DELAY_MS = 1500;
///////////////////////////////////////////////////////////
// Globals
///////////////////////////////////////////////////////////
var bg;
var settings;
var currentCardId;
var donationLinkNumber;
var donationPageNumber;
///////////////////////////////////////////////////////////
// Initialization
///////////////////////////////////////////////////////////
function initOptionsPage(onComplete) {
bg = chrome.extension.getBackgroundPage();
if (!bg) {
// background page not ready yet, try again in a bit
retriggerInitOptionsPage(onComplete);
return;
}
settings = bg.settings;
if (!settings) {
// settings object not ready yet, try again in a bit
retriggerInitOptionsPage(onComplete);
return;
}
var delayMsg = $('#initDelayed');
if (delayMsg.length > 0) {
delayMsg.remove();
}
setI18NText();
transformInputElements();
initDonateElements();
loadSettings();
setCloudPlayState();
$.fx.off = !settings.get('animationEnabled');
$(document)
.on('change', 'input[type=text], select', onSettingModified)
.on('click', 'input[type=checkbox]', onSettingModified)
.on('click', 'a', onLinkClick)
.on('click', '.slideCard', onSlideCardClick);
setTimeout(function() {
// delay to avoid F5 (reload) spuriously triggering keyup
$(document).on('keyup', 'input[type=text]', onSettingModified);
}, 250);
if (onComplete) onComplete();
}
function retriggerInitOptionsPage(onComplete) {
if ($('#initDelayed').length == 0) {
$('body').append($('<div id="initDelayed">').text('Just a moment...'));
}
setTimeout(function() { initOptionsPage(onComplete); }, OPTIONS_INIT_RETRY_DELAY_MS);
}
function onDonateLinkClick(evt) {
reportEvent('donate', 'donate_link_clicked', 'donate_link_' + donationLinkNumber);
reportEvent('donate', 'donate_page_viewed', 'donate_page_' + donationPageNumber);
}
function initDonateElements() {
// var whichPage = Math.floor(1 + Math.random() * DONATION_PAGE_VARIETIES);
var whichPage = 1;
var whichLink;
if (location.pathname == '/options_install.html') {
whichLink = 'install';
}
else {
whichLink = Math.floor(1 + Math.random() * DONATION_LINK_VARIETIES);
}
$('#donateLink').html(getMessage('donateLink_' + whichLink));
var iframeUrl = 'http://www.sidewise.info/pay/?embed=1&which=' + whichPage + '&whichLink=' + whichLink;
$('#donatePage').attr('src', iframeUrl);
donationLinkNumber = whichLink;
donationPageNumber = whichPage;
reportEvent('donate', 'donate_link_shown', 'donate_link_' + donationLinkNumber, null, true);
reportEvent('donate', 'donate_page_chosen', 'donate_page_' + donationPageNumber, null, true);
}
function initGooglePlusElement() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
}
function transformInputElements() {
var elems = $('input, select');
elems.each(function(i, e) {
var $e = $(e);
var name = e.attributes.name.value;
var type = $e.attr('type') || e.tagName.toLowerCase();
var msgName = 'option_' + name;
var label = getMessage(msgName);
var labelElem = $('<div class="optionsLabel">')
.append($('<label/>', { for: name }).text(label));
var units = getMessage(msgName + '_units');
if (units) {
var unitsElem = $('<span class="optionsUnits"/>').text(units);
}
else {
var unitsElem = $('');
}
var hint = getMessage(msgName + '_hint');
if (hint) {
var hintClass = 'hintIcon';
if (hint[0] == '!') {
hint = hint.slice(1);
hintClass = 'warningIcon';
}
var hintElem = $('<div/>', { class: hintClass, title: hint })
.tooltip({ position: 'top right', delay: 50, offset: [8, 0] }).dynamic();
}
else {
var hintElem = $('');
}
var inputElem = $e.clone();
inputElem.attr('id', name);
var inputBox = $('<div class="optionsInputBox"/>');
var rep = $('<div class="optionsRow"/>');
switch (type) {
case 'text':
inputBox.append(inputElem).append(unitsElem);
rep.append(labelElem).append(inputBox).append(hintElem);
break;
case 'checkbox':
labelElem.addClass('optionsWideLabel').append(hintElem);
inputBox.append(inputElem).append(labelElem);
rep.append(inputBox);
break;
case 'button':
inputElem.val(label);
if (! $e.hasClass('toolButton')) {
rep.append(inputElem);
}
else {
rep = inputElem;
}
break;
case 'select':
inputBox.append(inputElem).append(hintElem);
rep.append(labelElem).append(inputBox);
break;
default:
throw new Error('Unsupported input element type, cannot transform: ' + type);
}
$e.replaceWith(rep);
});
}
function setCloudPlayState() {
$('#clouds > div').css('-webkit-animation-play-state', settings.get('animationEnabled') ? 'running' : 'paused');
}
///////////////////////////////////////////////////////////
// Event handlers
///////////////////////////////////////////////////////////
function onSettingModified(evt) {
var target = evt.target;
var $target = $(target);
var $gp = $target.parent().parent();
if ($gp.is('[role=row]')) {
// pane picker checkbox clicked
var id = parseInt($gp.attr('id'));
var data = $('#panePicker').jqGrid('getRowData', id);
var enabled = (data.enabled == 'Yes');
var pane = getPaneByPickerRowId(id);
if (enabled && !pane.enabled) {
// user enabled a disabled pane
pane.enabled = true;
bg.paneCatalog.saveState();
if (bg.sidebarHandler.sidebarExists()) {
var manager = bg.sidebarHandler.sidebarPanes.sidebarHost.manager;
manager.enableSidebarPane(pane.id);
}
}
else if (!enabled && pane.enabled) {
// user disabled an enabled pane
pane.enabled = false;
bg.paneCatalog.saveState();
if (bg.sidebarHandler.sidebarExists()) {
var manager = bg.sidebarHandler.sidebarPanes.sidebarHost.manager;
manager.disableSidebarPane(pane.id);
}
}
}
if ($target.is('[type=checkbox]')) {
updateExpansionGroup($target.attr('id'), false);
}
if (saveOneSetting(target)) {
$target.removeClass('invalid');
showStatusMessage(getMessage('optionsSuccessSavingSetting'));
settings.updateStateFromSettings($target.attr('id'));
setCloudPlayState();
$.fx.off = !settings.get('animationEnabled');
return;
}
$target.addClass('invalid');
showErrorMessage(getMessage('optionsErrorSavingSetting'));
}
function onCloseButtonClick() {
window.close();
}
function onSlideCardClick(evt) {
var newCardId = $(this).attr('to');
slideCard(newCardId);
}
function onLinkClick(evt) {
var $this = $(this);
if ($this.attr('href').match(/^chrome:\/\/.*settings/)) {
chrome.tabs.create({ url: 'chrome://settings', active: true });
return;
}
if ($this.attr('href') == '#') {
return true;
}
$this.attr('target', '_blank');
// alert(evt);
}
///////////////////////////////////////////////////////////
// Pane picker
///////////////////////////////////////////////////////////
function initPaneGrid() {
// configure pane picker
var $picker = $('#panePicker');
$picker.jqGrid({
datatype: "local",
colModel: [
{name:'paneid', hidden: true },
{sortable: false, name:'enabled', index:'enabled', width: 40, formatter: 'checkbox', formatoptions: { disabled: false }, align: 'center' },
{sortable: false, name:'label', index:'label', width: 200}
],
onSelectRow: onPanePickerSelectRow
});
$picker.jqGrid('sortableRows', {
update: onPanePickerReorderedRow
});
// remove picker's column header
$picker.parents("div.ui-jqgrid-view").children("div.ui-jqgrid-hdiv").remove();
// populate grid with panes data
var panes = bg.paneCatalog.items.map(function(e) {
return {
paneid: e.id,
enabled: e.enabled,
label: '<img class="panePickerRowIcon" width="16" height="16" src="' + e.icon + '"> ' + e.label
};
});
for(var i=0; i <= panes.length; i++) {
$picker.jqGrid('addRowData', i+1, panes[i]);
}
// remove 'title' attributes from all pane picker grid cells, since it is redundant
$picker.find('[role=gridcell]').attr('title', '');
}
function showPanePicker(evt) {
$(evt.target).hide();
initPaneGrid();
$('#panePickerContainer').slideDown();
}
function onPanePickerReorderedRow(evt, ui) {
var $row = $(ui.item);
var newIndex = $row.index() - 1;
var pane = getPaneByPickerRowId($row.attr('id'));
bg.paneCatalog.reorderPane(pane.id, newIndex);
if (!bg.sidebarHandler.sidebarExists()) {
return;
}
var manager = bg.sidebarHandler.sidebarPanes.sidebarHost.manager;
manager.reorderSidebarPane(pane.id, newIndex);
bg.paneCatalog.saveState();
}
function onPanePickerSelectRow(rowid, status, e) {
if (!bg.sidebarHandler.sidebarExists()) {
return;
}
var pane = getPaneByPickerRowId(rowid);
log('select pane ' + rowid + ' ' + pane.id);
if (!pane.enabled) {
return;
}
var manager = bg.sidebarHandler.sidebarPanes.sidebarHost.manager;
manager.showSidebarPane(pane.id);
}
function getPaneByPickerRowId(rowid) {
var data = $('#panePicker').jqGrid('getRowData', rowid);
var pane = bg.paneCatalog.getPane(data.paneid);
if (pane) {
return pane;
}
throw new Error('Unable to find correct pane in catalog by id');
}
///////////////////////////////////////////////////////////
// Card display
///////////////////////////////////////////////////////////
function showCard(id, pageTitle) {
$('#' + id).show();
currentCardId = id;
if (pageTitle) {
window.document.title = pageTitle;
}
}
function slideCard(newCardId) {
var docWidth = $(document).width();
var currentCard = $('#' + currentCardId);
var currentCardLeft = currentCard.position().left;
var currentCardIndex = currentCard.index();
var newCard = $('#' + newCardId);
var newCardIndex = newCard.index();
var cardWidth = currentCard.width();
var padding = 100;
// ensure left property is actually set on current card prior to sliding it
currentCard.css('left', currentCardLeft);
if (currentCardIndex < newCardIndex) {
// current card is to the left of the new card, so slide cards to the left
currentCard.animate({ left: -cardWidth - padding }, CARD_SLIDE_DURATION_MS, function() {
currentCard.hide();
});
newCard.css('left', docWidth + padding);
newCard.show();
newCard.animate({ left: currentCardLeft }, CARD_SLIDE_DURATION_MS);
}
else {
// current card is to the right of the new card, so slide cards to the right
currentCard.animate({ left: docWidth + padding }, CARD_SLIDE_DURATION_MS, function() {
currentCard.hide();
});
newCard.css('left', -cardWidth - padding);
newCard.show();
newCard.animate({ left: currentCardLeft }, CARD_SLIDE_DURATION_MS);
}
currentCardId = newCardId;
}
///////////////////////////////////////////////////////////
// Settings loading and saving
///////////////////////////////////////////////////////////
function loadSettings() {
var elems = $('input, select');
elems.each(function(i, e) {
var $e = $(e);
var type = $e.attr('type') || e.tagName.toLowerCase();
var name = $e.attr('name');
var value = settings.get(name);
switch (type) {
case 'button':
return;
break;
case 'checkbox':
e.checked = value;
updateExpansionGroup($e.attr('id'), true);
break;
default:
$e.val(value);
break;
}
});
}
function saveOneSetting(e) {
var $e = $(e);
var name = $e.attr('name');
var value = e.value;
var type = $e.attr('type') || e.tagName.toLowerCase();
var datatype = $e.attr('datatype');
var storeValue;
// validate
var valid = true;
switch (type) {
case 'button':
// ignore for purposes of saving settings
return;
break;
case 'text':
switch (datatype) {
case 'int':
storeValue = parseInt(value);
if (storeValue.toString() != value) {
valid = false;
break;
}
break;
default:
storeValue = value;
break;
}
break;
case 'checkbox':
storeValue = e.checked;
break;
default:
storeValue = value;
break;
}
if (!valid) {
return false;
}
settings.set(name, storeValue);
reportEvent('set_option', name, storeValue.toString(), undefined, true);
return true;
}
function resetAllSettings(evt) {
if (!confirm(getMessage('prompt_confirmResetOptions'))) {
return;
}
settings.initializeDefaults(true);
loadSettings();
settings.updateStateFromSettings();
showStatusMessage(getMessage('optionsResetAllSettings'));
}
///////////////////////////////////////////////////////////
// Status bar
///////////////////////////////////////////////////////////
function showStatusMessage(msg) {
$('#statusBar').addClass('statusOK').removeClass('statusError')
.highlight({ start_color: '#c2d2e3', end_color: '#e7edf4', delay: 2000 });
$('#statusMessage')
// .stop().animate({opacity:'100'})
.text(msg)
.show(); //.fadeOut(2000);
}
function showErrorMessage(msg) {
$('#statusBar').removeClass('statusOK').addClass('statusError')
.highlight({ start_color: '#edd', end_color: '#fee', delay: 2000 });
// $('#statusMessage').stop().animate({opacity:'100'});
$('#statusMessage').text(msg).show();
}
///////////////////////////////////////////////////////////
// Monitor detection
///////////////////////////////////////////////////////////
function detectMonitors() {
bg.monitorInfo.retrieveMonitorMetrics(function() {
bg.monitorInfo.saveToSettings();
settings.updateStateFromSettings();
setMonitorCountInfo(bg.monitorInfo.monitors.length, true);
showStatusMessage(getMessage('prompt_detectMonitors_complete'));
});
}
function setMonitorCountInfo(count, highlight) {
var elem = $('#infoMonitorsOnYourSystem');
elem.html(
getMessage('optionsInfoMonitorsOnYourSystem',
[count,
(count == 1 ? getMessage('text_monitor') : getMessage('text_monitors'))
]
)
);
if (highlight) {
elem.highlight({ start_color: 'yellow', end_color: '#fff', delay: 2000 });
}
}
///////////////////////////////////////////////////////////
// Option revealers
///////////////////////////////////////////////////////////
function showAdvancedOptions(revealing) {
var $advOpts = $('.advancedOptions');
if (revealing) {
$('#advancedOptionsExpander').slideUp();
$advOpts.slideDown(400, function() {
$advOpts.css('background-color', 'hsl(60, 60%, 88%)');
});
}
else {
$('#advancedOptionsExpander').hide();
$advOpts.show();
}
}
function updateExpansionGroup(forId, instant) {
var isTrue = $('#' + forId).is(':checked');
var $group = $('.trueExpansionGroup[for=' + forId + ']');
if ($group.length == 0) {
return;
}
if (isTrue) {
if (instant) {
$group.show();
return;
}
$group.slideDown(150);
return;
}
if (instant) {
$group.hide();
return;
}
$group.slideUp(150);
}
///////////////////////////////////////////////////////////
// Bug submitter
///////////////////////////////////////////////////////////
var BUG_REPORT_SIDEBARHANDLER_PROPS = ['creatingSidebar', 'currentDockWindowMetrics',
'currentSidebarMetrics', 'dockState', 'dockWindowId', 'lastDockWindowMetrics',
'matchingMinimizedStates', 'maximizedOffset', 'monitorMetrics',
'removeInProgress', 'resetResizingDockWindowTimeout', 'resizingDockWindow',
'resizingSidebar', 'sidebarUrl', 'tabId', 'targetWidth', 'windowId'
];
async function submitBugReport() {
var desc = prompt('This sends a log of Sidewise\'s recent activity to the author for diagnostic purposes. It is best used immediately after you experience a problem.\n\nPlease clearly describe the problem below. Include row IDs from the tree when pertinent.\n\nNote that this report includes a list of everything in your sidebar panes/trees.');
if (!desc) {
alert('Diagnostic report cancelled.');
return;
}
bg.log('--- tree ---');
bg.log(bg.tree.dump());
bg.log(bg.tree.dumpTabIndexes());
bg.log('--- stored tree ---');
bg.log(localStorage['pageTree']);
bg.log('--- sidebarHandler ---');
bg.log(BUG_REPORT_SIDEBARHANDLER_PROPS.map(function(e) {
return e + ':' + JSON.stringify(bg.sidebarHandler[e]);
}).join(', '));
bg.log('--- monitorInfo ---');
bg.log(JSON.stringify(bg.monitorInfo.monitors));
bg.log('--- Settings ---');
bg.log(settings.dump(400));
bg.log('--- Versions ---');
bg.log([
'Sidewise: ' + getVersion(),
'Chrome: ' + navigator.userAgent,
'OS: ' + navigator.platform,
].join('\n'));
var data = (getVersion() + ' - ' + Date() + '\n' + desc + '\n\n' + bg.runningLog);
// htmlencode the data
data = $('<div/>').text(data).html();
// turn call stacks into classed divs
data = data.replace(/((^\s{4}.+\n)+)/mg, '<div class="stack">$1</div>');
// trim data length to something that won't throw an exception on the server
data = data.substr(data.length > BUG_REPORT_MAX_SIZE ? data.length - BUG_REPORT_MAX_SIZE : 0);
// add JS/CSS for stacks
data =
'<style>* { font-family: Lucida Console; font-size: 12px; } .stack { font-size: 11px; color: #bbb; }</style>'
+ data;
$.post('http://www.sidewise.info/submit_error/index.php', { 'desc': desc, 'data': data, 'type': 'log' }, function(data, textStatus, jqXHR) {
bg.settings.toJSON().then(function(json) {
$.post('http://www.sidewise.info/submit_error/index.php', { 'desc': desc, 'data': json, 'type': 'state' }, function(data, textStatus, jqXHR) {
alert('Diagnostic report sent. Thank you for the report.\n\nServer response:\n' + data);
});
});
});
}
///////////////////////////////////////////////////////////
// Emergency restore
///////////////////////////////////////////////////////////
async function restoreFromPreviousSessionBackup() {
var backup = await settings.loadData('backupPageTreeLastSession', []);
var when;
if (backup.length > 0) {
when = 'during your PREVIOUS browser session';
}
else {
backup = await settings.lodaData('backupPageTree', []);
if (backup.length > 0) {
when = 'earlier THIS browser session';
}
}
if (backup.length == 0) {
alert('Sorry, but there are no automatic backups to restore from! :(');
return;
}
if (!confirm('If your page tree has gotten wiped out or corrupted, Sidewise can try restoring the tree from a recent automatic backup.\n\n' +
'The best backup we have was saved ' + when + '.\n\n' +
'Proceed with restore?')) {
return;
}
alert('Sidewise will now restart to complete the restore operation.');
await settings.saveData('pageTree', backup);
bg.setTimeout(bg.restartSidewise, 100);
setTimeout(function() { window.close(); }, 10);
}
///////////////////////////////////////////////////////////
// Import/export
///////////////////////////////////////////////////////////
async function exportState() {
await bg.savePageTree(bg.tree, 'pageTree', true);
var head = '/* Sidewise Data Export: v' + getVersion() + ' exported on ' + Date().toString() + ' */ ';
var tail = ' /* End Sidewise Data */';
copyTextToClipboard(head + await bg.settings.toJSON() + tail);
alert('Sidewise\'s configuration and state data has been exported and copied to your clipboard.\n\nPaste this into a text file to save it.');
}
function importState() {
var html = 'Paste the previously exported Sidewise data into the box below:<br/><textarea rows="10" cols="34" id="importBox" name="data" spellcheck="false"></textarea>';
var importPrompt = $.prompt(html, { prefix: 'cleanblue', buttons: { 'OK': true, 'Cancel': false }, callback: doImportState });
importPrompt.bind('promptloaded', () => $('#importBox').focus());
}
function doImportState(e,v,m,f) {
if (!v) {
// user hit Cancel
return;
}
let data = f.data;
if (!data) {
alert('No data pasted. Import aborted.');
return;
}
// Drop leading/trailing comments
data = data.replace(/^\/\*.+?\*\/\s*/, '');
data = data.replace(/\/\*.+?\*\/\s*$/, '');
try {
bg.settings.importFromJSON(data);
}
catch (ex) {
alert(`There was a problem importing the data.\n\n${ex.message}\n\n${ex.stack}`);
return;
}
alert('Import successful!\nSidewise will now be restarted.');
bg.restartSidewise();
setTimeout(function() { document.location.reload(); }, 3000);
}
|
import Vue from "vue";
import Cloudbase from "@cloudbase/vue-provider";
export default async () => {
const envId = await fetch("/nuxt-ssr-echo/")
.then(response => response.json())
.then(data => data.envId);
Vue.use(Cloudbase, {
env: envId
});
};
|
(function ($) {
angular.module('designer').requires.push('expander', 'sfSelectors');
angular.module('designer').controller('SimpleCtrl', ['$scope', 'propertyService', function ($scope, propertyService) {
var emptyGuid = '00000000-0000-0000-0000-000000000000';
var sortOptions = ['PublicationDate DESC', 'LastModified DESC', 'Title ASC', 'Title DESC', 'EventStart ASC', 'EventStart DESC', 'AsSetManually'];
$scope.eventSelector = {
selectedItemsIds: []
};
$scope.feedback.showLoadingIndicator = true;
$scope.changeFilteredSelectionMode = function (filteredSelectionMode) {
if ($scope.properties) {
$scope.properties.SelectionMode.PropertyValue = 'FilteredItems';
$scope.properties.FilteredSelectionMode.PropertyValue = filteredSelectionMode;
}
};
$scope.isFilteredSelectionModeChecked = function (filteredSelectionMode) {
if ($scope.properties && $scope.properties.SelectionMode.PropertyValue == "FilteredItems") {
return $scope.properties.FilteredSelectionMode.PropertyValue === filteredSelectionMode;
}
};
$scope.$watch(
'eventSelector.selectedItemsIds',
function (newVal, oldVal) {
if (newVal !== oldVal) {
if (newVal) {
$scope.properties.SerializedSelectedItemsIds.PropertyValue = JSON.stringify(newVal);
if (newVal.length === 1) {
$scope.properties.ContentViewDisplayMode.PropertyValue = 'Detail';
}
}
}
},
true
);
$scope.$watch(
'properties.SelectionMode.PropertyValue',
function (newVal, oldVal) {
if (newVal !== oldVal) {
if (newVal == 'SelectedItems') {
$scope.selectedSortOption = 'AsSetManually';
}
else {
$scope.selectedSortOption = 'EventStart ASC';
}
}
},
true
);
$scope.additionalFilters = {};
$scope.$watch(
'additionalFilters.value',
function (newAdditionalFilters, oldAdditionalFilters) {
if (newAdditionalFilters !== oldAdditionalFilters) {
$scope.properties.SerializedAdditionalFilters.PropertyValue = JSON.stringify(newAdditionalFilters);
}
},
true
);
$scope.narrowFilters = {};
$scope.$watch(
'narrowFilters.value',
function (newNarrowFilters, oldNarrowFilters) {
if (newNarrowFilters !== oldNarrowFilters) {
$scope.properties.SerializedNarrowSelectionFilters.PropertyValue = JSON.stringify(newNarrowFilters);
}
},
true
);
$scope.updateSortOption = function (newSortOption) {
if (newSortOption !== "Custom") {
$scope.selectedSortOption = newSortOption;
$scope.properties.SortExpression.PropertyValue = newSortOption;
}
};
propertyService.get()
.then(function (data) {
if (data) {
$scope.properties = propertyService.toAssociativeArray(data.Items);
var additionalFilters = $.parseJSON($scope.properties.SerializedAdditionalFilters.PropertyValue || null);
$scope.additionalFilters.value = additionalFilters;
var narrowFilters = $.parseJSON($scope.properties.SerializedNarrowSelectionFilters.PropertyValue || null);
$scope.narrowFilters.value = narrowFilters;
var selectedItemsIds = $.parseJSON($scope.properties.SerializedSelectedItemsIds.PropertyValue || null);
if (selectedItemsIds) {
$scope.eventSelector.selectedItemsIds = selectedItemsIds;
}
if ($scope.properties.SortExpression.PropertyValue === '') {
if ($scope.properties.SelectionMode.PropertyValue === 'SelectedItems') {
$scope.selectedSortOption = 'AsSetManually';
}
else {
$scope.selectedSortOption = 'EventStart ASC';
}
}
else if (sortOptions.indexOf($scope.properties.SortExpression.PropertyValue) >= 0) {
$scope.selectedSortOption = $scope.properties.SortExpression.PropertyValue;
}
else {
$scope.selectedSortOption = 'Custom';
}
}
},
function (data) {
$scope.feedback.showError = true;
if (data)
$scope.feedback.errorMessage = data.Detail;
})
.then(function () {
$scope.feedback.savingHandlers.push(function () {
if ($scope.properties.OpenInSamePage.PropertyValue && $scope.properties.OpenInSamePage.PropertyValue.toLowerCase() === 'true') {
$scope.properties.DetailsPageId.PropertyValue = emptyGuid;
}
else if (!$scope.properties.DetailsPageId.PropertyValue || $scope.properties.DetailsPageId.PropertyValue === emptyGuid) {
$scope.properties.OpenInSamePage.PropertyValue = true;
}
if ($scope.properties.SelectionMode.PropertyValue !== 'SelectedItems') {
$scope.properties.SerializedSelectedItemsIds.PropertyValue = null;
// If the sorting expression is AsSetManually but the selection mode is AllItems or FilteredItems, this is not a valid combination.
// So set the sort expression to the default value: PublicationDate DESC
if ($scope.properties.SortExpression.PropertyValue === 'AsSetManually') {
$scope.properties.SortExpression.PropertyValue = 'EventStart ASC';
$scope.selectedSortOption = 'EventStart ASC';
}
}
else {
$scope.properties.SerializedAdditionalFilters.PropertyValue = null;
$scope.properties.SerializedNarrowSelectionFilters.PropertyValue = null;
}
if ($scope.properties.ContentViewDisplayMode.PropertyValue === 'Detail' &&
($scope.properties.SelectionMode.PropertyValue !== 'SelectedItems' || $scope.eventSelector.selectedItemsIds.length !== 1)) {
$scope.properties.ContentViewDisplayMode.PropertyValue = 'Automatic';
}
$scope.properties.SortExpression.PropertyValue = $scope.selectedSortOption;
});
})
.finally(function () {
$scope.feedback.showLoadingIndicator = false;
});
}]);
})(jQuery);
|
(function () {
'use strict';
angular
.module('app')
.directive('straboNestingTabDirective', straboNestingTabDirective);
function straboNestingTabDirective() {
return {
'restrict': 'AE',
'replace': true,
'templateUrl': 'app/spot/nesting/nesting-tab.directive.html'
};
}
}());
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[569],{hcM1:function(e,o,t){var n,p,i;!function(c){if("object"==typeof e.exports){var s=c(0,o);void 0!==s&&(e.exports=s)}else p=[t,o],void 0===(i="function"==typeof(n=c)?n.apply(o,p):n)||(e.exports=i)}((function(e,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.default=[]}))}}]);
|
$(document).ready(function(){
SIS.validacionGeneral('form-general'); //form general porq con ese id lo creamos al form
});
var f=new Date();
var a=f.getFullYear();
var m=f.getMonth()+1;
var d=f.getDate();
m=(m<10)?"0"+m:m;
d=(d<10)?"0"+d:d;
var fechaactual=a+"-"+m+"-"+d;
$('#fecha_esp').flatpickr({
dateFormat: "Y-m-d",
minDate: 1990-01-01,
maxDate: fechaactual,
});
$('#fecha_ini').flatpickr({
dateFormat: "Y-m-d",
minDate: 1990-01-01,
maxDate: fechaactual
});
$('#fecha_fin').flatpickr({
dateFormat: "Y-m-d",
maxDate: fechaactual,
});
var $div_t_paciente = document.getElementById("div_t_paciente")
var $div_t_consulta = document.getElementById("div_t_consulta")
var $div_t_enfermeria = document.getElementById("div_t_enfermeria")
var $div_t_internacion = document.getElementById("div_t_internacion")
$('#informe').change(function(){
if ($('#informe').val()=="") {
$div_t_paciente.style.display='none';
$div_t_consulta.style.display='none';
$div_t_enfermeria.style.display='none';
$div_t_internacion.style.display='none';
} else {
$('#fecha_esp').val("")
$('#fecha_ini').val("")
$('#fecha_fin').val("")
if ($('#informe').val()=="paciente") {
$div_t_paciente.style.display='block';
$div_t_consulta.style.display='none';
$div_t_enfermeria.style.display='none';
$div_t_internacion.style.display='none';
$('#t_paciente').prop('required', true);
$('#t_consulta').prop('required', false);
$('#t_enfermeria').prop('required', false);
$('#t_internacion').prop('required', false);
} else {
if ($('#informe').val()=="consulta") {
$div_t_paciente.style.display='none';
$div_t_consulta.style.display='block';
$div_t_enfermeria.style.display='none';
$div_t_internacion.style.display='none';
$('#t_paciente').prop('required', false);
$('#t_consulta').prop('required', true);
$('#t_enfermeria').prop('required', false);
$('#t_internacion').prop('required', false);
} else {
if ($('#informe').val()=="enfermeria"){
$div_t_paciente.style.display='none';
$div_t_consulta.style.display='none';
$div_t_enfermeria.style.display='block';
$div_t_internacion.style.display='none';
$('#t_paciente').prop('required', false);
$('#t_consulta').prop('required', false);
$('#t_enfermeria').prop('required', true);
$('#t_internacion').prop('required', false);
}
else{
$div_t_paciente.style.display='none';
$div_t_consulta.style.display='none';
$div_t_enfermeria.style.display='none';
$div_t_internacion.style.display='block';
$('#t_paciente').prop('required', false);
$('#t_consulta').prop('required', false);
$('#t_enfermeria').prop('required', false);
$('#t_internacion').prop('required', true);
}
}
}
}
});
var $div_fecha_esp = document.getElementById("div_fecha_esp")
var $div_rango = document.getElementById("div_rango")
$('#t_fecha').change(function(){
if ($('#t_fecha').val()=="") {
$div_fecha_esp.style.display='none';
$div_rango.style.display='none';
} else {
$('#fecha_esp').val("")
$('#fecha_ini').val("")
$('#fecha_fin').val("")
if ($('#t_fecha').val()=="especifico") {
$div_fecha_esp.style.display='block';
$div_rango.style.display='none';
$('#fecha_esp').prop('required', true);
$('#fecha_ini').prop('required', false);
$('#fecha_fin').prop('required', false);
} else {
$div_fecha_esp.style.display='none';
$div_rango.style.display='block';
$('#fecha_esp').prop('required', false);
$('#fecha_ini').prop('required', true);
$('#fecha_fin').prop('required', true);
}
}
});
$('#fecha_ini').change(function(){
if ($('#fecha_ini').val()!="") {
$('#fecha_fin').flatpickr({
dateFormat: "Y-m-d",
minDate: $('#fecha_ini').val(),
maxDate: fechaactual,
});
}
});
|
const Discord = require('discord.js');
module.exports = {
name: "unlock",
category: "mod",
aliases: ['unlock', 'destravar'],
async run(client, message, args) {
if (!message.member.hasPermission("MANAGE_CHANNELS")) return message.reply("<a:no:792088988785311754> | Você não tem a permissão `MANAGE_CHANNELS` para executar esse comando.");
if(!message.guild.me.permissions.has("MANAGE_CHANNELS")) {
return message.reply("<a:no:792088988785311754> | Eu não tenho a permissão `MANAGE_CHANNELS`!")
}
let card = new Discord.MessageEmbed()
.setColor('RED')
.setTitle(`Certeza ${message.author.username}?`)
.setDescription('Você deseja realmente dar unlock neste canal?')
message.channel.send(card).then(msg => {
msg.react('🔓')
const filtro = (reacao, usuario) => reacao.emoji.name === '🔓' && usuario.id === message.author.id;
const coletor = msg.createReactionCollector(filtro);
//abc
coletor.on('collect', () => {
let card2 = new Discord.MessageEmbed()
.setTitle('🔓 | Aberto Novamente!')
.setDescription('Canal aberto com sucesso!')
.setColor('RED')
msg.edit(card2);
if (!client.lockit) client.lockit = [];
message.channel.createOverwrite(message.guild.id, {
SEND_MESSAGES: null
})
})
}
)}};
|
from dataclasses import dataclass
from broadcaster import Broadcast
broadcast = None
async def get_broadcast():
global broadcast
if not broadcast:
broadcast = Broadcast("memory://")
await broadcast.connect()
return broadcast
@dataclass
class Context:
broadcast: Broadcast
|
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
import * as tslib_1 from "tslib";
import ControllerInterface from './controller-interface';
import Errors from '../models/errors';
import WorkerPageMessage from '../models/worker-page-message';
import DefaultSW from '../models/default-sw';
import NOTIFICATION_PERMISSION from '../models/notification-permission';
import FCMDetails from '../models/fcm-details';
import base64ToArrayBuffer from '../helpers/base64-to-array-buffer';
import { createSubscribe } from '@firebase/util';
var WindowController = /** @class */ (function (_super) {
tslib_1.__extends(WindowController, _super);
/**
* A service that provides a MessagingService instance.
* @param {!firebase.app.App} app
*/
function WindowController(app) {
var _this = _super.call(this, app) || this;
_this.messageObserver_ = null;
_this.onMessage_ = createSubscribe(function (observer) {
_this.messageObserver_ = observer;
});
_this.tokenRefreshObserver_ = null;
_this.onTokenRefresh_ = createSubscribe(function (observer) {
_this.tokenRefreshObserver_ = observer;
});
/**
* @private
* @type {ServiceWorkerRegistration}
*/
_this.registrationToUse_;
/**
* @private
* @type {Promise}
*/
_this.manifestCheckPromise_;
/**
* @private
* @type {firebase.Observer}
*/
_this.messageObserver_ = null;
/**
* @private {!firebase.Subscribe} The subscribe function to the onMessage
* observer.
*/
_this.onMessage_ = createSubscribe(function (observer) {
_this.messageObserver_ = observer;
});
/**
* @private
* @type {firebase.Observer}
*/
_this.tokenRefreshObserver_ = null;
_this.onTokenRefresh_ = createSubscribe(function (observer) {
_this.tokenRefreshObserver_ = observer;
});
_this.setupSWMessageListener_();
return _this;
}
/**
* This method returns an FCM token if it can be generated.
* The return promise will reject if the browser doesn't support
* FCM, if permission is denied for notifications or it's not
* possible to generate a token.
* @export
* @return {Promise<string> | Promise<null>} Returns a promise the
* resolves to an FCM token or null if permission isn't granted.
*/
WindowController.prototype.getToken = function () {
var _this = this;
// Check that the required API's are available
if (!this.isSupported_()) {
return Promise.reject(this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER));
}
return this.manifestCheck_().then(function () {
return _super.prototype.getToken.call(_this);
});
};
/**
* The method checks that a manifest is defined and has the correct GCM
* sender ID.
* @private
* @return {Promise} Returns a promise that resolves if the manifest matches
* our required sender ID
*/
WindowController.prototype.manifestCheck_ = function () {
var _this = this;
if (this.manifestCheckPromise_) {
return this.manifestCheckPromise_;
}
var manifestTag = document.querySelector('link[rel="manifest"]');
if (!manifestTag) {
this.manifestCheckPromise_ = Promise.resolve();
}
else {
this.manifestCheckPromise_ = fetch(manifestTag.href)
.then(function (response) {
return response.json();
})
.catch(function () {
// If the download or parsing fails allow check.
// We only want to error if we KNOW that the gcm_sender_id is incorrect.
})
.then(function (manifestContent) {
if (!manifestContent) {
return;
}
if (!manifestContent['gcm_sender_id']) {
return;
}
if (manifestContent['gcm_sender_id'] !== '103953800507') {
throw _this.errorFactory_.create(Errors.codes.INCORRECT_GCM_SENDER_ID);
}
});
}
return this.manifestCheckPromise_;
};
/**
* Request permission if it is not currently granted
* @export
* @returns {Promise} Resolves if the permission was granted, otherwise
* rejects
*/
WindowController.prototype.requestPermission = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var _this = this;
return tslib_1.__generator(this, function (_a) {
if (Notification.permission === NOTIFICATION_PERMISSION.granted) {
return [2 /*return*/];
}
return [2 /*return*/, new Promise(function (resolve, reject) {
var managePermissionResult = function (result) {
if (result === NOTIFICATION_PERMISSION.granted) {
return resolve();
}
else if (result === NOTIFICATION_PERMISSION.denied) {
return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED));
}
else {
return reject(_this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT));
}
};
// The Notification.requestPermission API was changed to
// return a promise so now have to handle both in case
// browsers stop support callbacks for promised version
var permissionPromise = Notification.requestPermission(managePermissionResult);
if (permissionPromise) {
// Prefer the promise version as it's the future API.
permissionPromise.then(managePermissionResult);
}
})];
});
});
};
/**
* This method allows a developer to override the default service worker and
* instead use a custom service worker.
* @export
* @param {!ServiceWorkerRegistration} registration The service worker
* registration that should be used to receive the push messages.
*/
WindowController.prototype.useServiceWorker = function (registration) {
if (!(registration instanceof ServiceWorkerRegistration)) {
throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);
}
if (typeof this.registrationToUse_ !== 'undefined') {
throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);
}
this.registrationToUse_ = registration;
};
/**
* This method allows a developer to override the default vapid key
* and instead use a custom VAPID public key.
* @export
* @param {!string} publicKey A URL safe base64 encoded string.
*/
WindowController.prototype.usePublicVapidKey = function (publicKey) {
if (typeof publicKey !== 'string') {
throw this.errorFactory_.create(Errors.codes.INVALID_PUBLIC_VAPID_KEY);
}
if (typeof this.publicVapidKeyToUse_ !== 'undefined') {
throw this.errorFactory_.create(Errors.codes.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);
}
var parsedKey = base64ToArrayBuffer(publicKey);
if (parsedKey.length !== 65) {
throw this.errorFactory_.create(Errors.codes.PUBLIC_KEY_DECRYPTION_FAILED);
}
this.publicVapidKeyToUse_ = parsedKey;
};
/**
* @export
* @param {!firebase.Observer|function(*)} nextOrObserver An observer object
* or a function triggered on message.
* @param {function(!Error)=} optError Optional A function triggered on
* message error.
* @param {function()=} optCompleted Optional function triggered when the
* observer is removed.
* @return {!function()} The unsubscribe function for the observer.
*/
WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {
return this.onMessage_(nextOrObserver, optError, optCompleted);
};
/**
* @export
* @param {!firebase.Observer|function()} nextOrObserver An observer object
* or a function triggered on token refresh.
* @param {function(!Error)=} optError Optional A function
* triggered on token refresh error.
* @param {function()=} optCompleted Optional function triggered when the
* observer is removed.
* @return {!function()} The unsubscribe function for the observer.
*/
WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {
return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);
};
/**
* Given a registration, wait for the service worker it relates to
* become activer
* @private
* @param {ServiceWorkerRegistration} registration Registration to wait
* for service worker to become active
* @return {Promise<!ServiceWorkerRegistration>} Wait for service worker
* registration to become active
*/
WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {
var _this = this;
var serviceWorker = registration.installing || registration.waiting || registration.active;
return new Promise(function (resolve, reject) {
if (!serviceWorker) {
// This is a rare scenario but has occured in firefox
reject(_this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));
return;
}
// Because the Promise function is called on next tick there is a
// small chance that the worker became active or redundant already.
if (serviceWorker.state === 'activated') {
resolve(registration);
return;
}
if (serviceWorker.state === 'redundant') {
reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));
return;
}
var stateChangeListener = function () {
if (serviceWorker.state === 'activated') {
resolve(registration);
}
else if (serviceWorker.state === 'redundant') {
reject(_this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));
}
else {
// Return early and wait to next state change
return;
}
serviceWorker.removeEventListener('statechange', stateChangeListener);
};
serviceWorker.addEventListener('statechange', stateChangeListener);
});
};
/**
* This will regiater the default service worker and return the registration
* @private
* @return {Promise<!ServiceWorkerRegistration>} The service worker
* registration to be used for the push service.
*/
WindowController.prototype.getSWRegistration_ = function () {
var _this = this;
if (this.registrationToUse_) {
return this.waitForRegistrationToActivate_(this.registrationToUse_);
}
// Make the registration null so we know useServiceWorker will not
// use a new service worker as registrationToUse_ is no longer undefined
this.registrationToUse_ = null;
return navigator.serviceWorker
.register(DefaultSW.path, {
scope: DefaultSW.scope
})
.catch(function (err) {
throw _this.errorFactory_.create(Errors.codes.FAILED_DEFAULT_REGISTRATION, {
browserErrorMessage: err.message
});
})
.then(function (registration) {
return _this.waitForRegistrationToActivate_(registration).then(function () {
_this.registrationToUse_ = registration;
// We update after activation due to an issue with Firefox v49 where
// a race condition occassionally causes the service work to not
// install
registration.update();
return registration;
});
});
};
/**
* This will return the default VAPID key or the uint8array version of the public VAPID key
* provided by the developer.
* @private
*/
WindowController.prototype.getPublicVapidKey_ = function () {
if (this.publicVapidKeyToUse_) {
return Promise.resolve(this.publicVapidKeyToUse_);
}
return Promise.resolve(FCMDetails.DEFAULT_PUBLIC_VAPID_KEY);
};
/**
* This method will set up a message listener to handle
* events from the service worker that should trigger
* events in the page.
*
* @private
*/
WindowController.prototype.setupSWMessageListener_ = function () {
var _this = this;
if (!('serviceWorker' in navigator)) {
return;
}
navigator.serviceWorker.addEventListener('message', function (event) {
if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {
// Not a message from FCM
return;
}
var workerPageMessage = event.data;
switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {
case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:
case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:
var pushMessage = workerPageMessage[WorkerPageMessage.PARAMS.DATA];
if (_this.messageObserver_) {
_this.messageObserver_.next(pushMessage);
}
break;
default:
// Noop.
break;
}
}, false);
};
/**
* Checks to see if the required API's are valid or not.
* @private
* @return {boolean} Returns true if the desired APIs are available.
*/
WindowController.prototype.isSupported_ = function () {
return ('serviceWorker' in navigator &&
'PushManager' in window &&
'Notification' in window &&
'fetch' in window &&
ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
PushSubscription.prototype.hasOwnProperty('getKey'));
};
return WindowController;
}(ControllerInterface));
export default WindowController;
//# sourceMappingURL=window-controller.js.map
|
module.exports = {
User: require('./User')
}
|
function original() {
function f(n){return n==0?1:n*f(n-1)}a=arguments[0];return f(2*a)/((a+1)*f(a)*4)
}
function solve() {
function fact(num) {
return num == 0 ? 1 : num * fact(num - 1);
}
input = arguments[0];
var answer = fact(2 * input) / (fact(1 + input) * fact(input) * 2);
return answer
}
(function(a){return[1,1,2,5,14,42,132,429,1430,4862,16796,58786][a[0]]/2})
|
// Copyright (c) 2016, Dataent Technologies and contributors
// For license information, please see license.txt
dataent.ui.form.on('Workflow Action', {
refresh: function(frm) {
}
});
|
"""
Serializers to convert API data to and from the database
"""
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer
from .models import Profile, UserPhoto
class UserSerializer(ModelSerializer):
"""
A serializer for the default auth.User model
"""
class Meta:
model = User
fields = (
"id",
"username",
"email",
"password",
"last_login",
"date_joined",
"profile",
)
read_only_fields = ("id", "date_joined", "profile")
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
user = User.objects.create(
email=validated_data["email"],
username=validated_data["username"],
password=make_password(validated_data["password"]),
)
user.save()
return user
class ProfileSerializer(ModelSerializer):
"""
A serializer for the users.Profile model
"""
class Meta:
model = Profile
fields = (
"id",
"user",
"name",
"alt",
"display_name",
"age",
"image",
"bio",
"location",
"external_url",
"facebook_url",
"twitter_user",
"instagram_user",
"show_email",
"searchable",
"email_confirmed",
"birth_date",
"photos",
)
read_only_fields = ("id", "user", "display_name", "age", "photos")
class PublicProfileSerializer(ModelSerializer):
"""
A serializer for a user's public profile
"""
class Meta:
model = Profile
fields = (
"id",
"display_name",
"age",
"image",
"bio",
"location",
"external_url",
"facebook_url",
"twitter_user",
"instagram_user",
"photos",
)
class UserPhotoSerializer(ModelSerializer):
"""
A serializer for the users.UserPhoto model
"""
class Meta:
model = UserPhoto
fields = ("id", "profile", "image", "description", "created")
read_only_fields = ("id", "profile", "image", "created")
|
module.exports = {
siteMetadata: {
title: `Nick EATS`,
description: `New Restaurant Site built with gatsbyjs.`,
author: `Nicholas Wease`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
`gatsby-plugin-sass`,
{
resolve: `gatsby-plugin-styled-components`,
options: {
// Add any options here
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
import webpack from 'webpack'
import path from 'path'
import HtmlWebpackPlguin from 'html-webpack-plugin'
export default {
entry: {
app: process.env.NODE_ENV === 'production' ? [
'./src/js/app.js',
] : [
'webpack-dev-server/client?http://localhost:8080',
'./src/js/app.js',
],
},
resolve: {
modules: [
'node_modules',
path.join(__dirname, 'src'),
],
extensions: ['', '.js', '.jsx'],
},
output: {
path: path.join(__dirname, 'docs'),
filename: 'js/[name].js',
publicPath: '/',
},
resolve: {
modules: [
'node_modules',
path.join(__dirname, 'src'),
],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
include: [
path.resolve(__dirname, 'src/js'),
],
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: false,
},
},
{
loader: 'eslint-loader',
options: {
},
},
],
},
{
test: /\.scss$/,
include: path.resolve(__dirname, 'src/scss/'),
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
plugins: (loader) => [
require('postcss-normalize')(),
require('autoprefixer')(),
require('cssnano')(),
],
}
},
{
loader: 'sass-loader',
},
],
},
],
},
devServer: {
contentBase: './docs',
publicPath: '/',
port: 8080,
},
plugins: [
new HtmlWebpackPlguin({
filename: 'index.html',
inject: false,
template: './src/templates/index.ejs',
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
require('autoprefixer')(),
require('cssnano')(),
],
},
}),
],
}
|
/**
* Copyright 2019, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import withTests from '../../util/withTests';
import CreditCardDetails, {
CardNumberInput,
ExpiryDateInput,
SecurityCodeInput,
NameOnCardInput,
cardSchemeIcons,
schemes
} from '.';
import Button from '../Button';
import Text from '../Text';
const { SCHEMES } = schemes;
const acceptedCardSchemes = {
[SCHEMES.VISA]: cardSchemeIcons[SCHEMES.VISA],
[SCHEMES.MASTERCARD]: cardSchemeIcons[SCHEMES.MASTERCARD],
[SCHEMES.JCB]: cardSchemeIcons[SCHEMES.JCB]
};
class YourFavoriteFormLibrary extends Component {
static propTypes = {
children: PropTypes.func.isRequired
};
state = {
values: {
name: '',
cardNumber: '',
expiryDate: '',
securityCode: ''
}
};
handleChange = (field, parse) => ({ target: { value } }) => {
this.setState(prevState => ({
values: {
...prevState.values,
[field]: parse ? parse(value) : value
}
}));
};
render() {
return this.props.children({
values: this.state.values,
handleChange: this.handleChange
});
}
}
storiesOf('CreditCardDetails', module)
.addDecorator(withTests('CreditCardDetails'))
.add(
'Default CreditCardDetails',
withInfo()(() => (
<YourFavoriteFormLibrary>
{({ values, handleChange }) => (
<div style={{ width: '95vw', maxWidth: '600px', margin: '0 auto' }}>
<CreditCardDetails
nameOnCard={
<NameOnCardInput
value={values.name}
onChange={handleChange('name')}
/>
}
cardNumber={
<CardNumberInput
{...{ acceptedCardSchemes }}
value={values.cardNumber}
onChange={handleChange('cardNumber')}
/>
}
expiryDate={
<ExpiryDateInput
value={values.expiryDate}
onChange={handleChange('expiryDate')}
/>
}
renderSecurityCodeInput={() => (
<SecurityCodeInput
value={values.securityCode}
onChange={handleChange('securityCode')}
/>
)}
/>
</div>
)}
</YourFavoriteFormLibrary>
))
)
.add(
'CreditCardDetails with security code info',
withInfo()(() => (
<YourFavoriteFormLibrary>
{({ values, handleChange }) => (
<div style={{ width: '95vw', maxWidth: '600px', margin: '0 auto' }}>
<CreditCardDetails
nameOnCard={
<NameOnCardInput
value={values.name}
onChange={handleChange('name')}
/>
}
cardNumber={
<CardNumberInput
{...{ acceptedCardSchemes }}
value={values.cardNumber}
onChange={handleChange('cardNumber')}
/>
}
expiryDate={
<ExpiryDateInput
value={values.expiryDate}
onChange={handleChange('expiryDate')}
/>
}
renderSecurityCodeInput={({ onShowInfo }) => (
<SecurityCodeInput
value={values.securityCode}
onChange={handleChange('securityCode')}
onShowInfo={onShowInfo}
/>
)}
renderSecurityCodeInfo={({ isShowingInfo, onHideInfo }) =>
isShowingInfo && (
<Fragment>
<Text>
Display some information regarding security codes. We do
this with a Modal.
</Text>
<Button onClick={onHideInfo} type="button">
Hide
</Button>
</Fragment>
)
}
/>
</div>
)}
</YourFavoriteFormLibrary>
))
);
|
// @flow
const eventListenerList = require('./eventListenerList.js'),
SublimeObject = require('./SublimeObject.js')
/**
* Note that many of these events are triggered by the buffer underlying the view, and thus the method is only called once, with the first view as the parameter.
*
* [sublime_plugin.EventListener Class](https://www.sublimetext.com/docs/3/api_reference.html#sublime_plugin.EventListener).
*/
class EventListener extends SublimeObject {
constructor () {
super(null, null, true)
eventListenerList[this.constructor.name] = this
}
/**
* Called when a new buffer is created.
*/
async on_new (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a new buffer is created. Runs in a separate thread, and does not block the application.
*/
async on_new_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view is cloned from an existing one.
*/
async on_clone (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view is cloned from an existing one. Runs in a separate thread, and does not block the application.
*/
async on_clone_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when the file is finished loading.
*/
async on_load (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when the file is finished loading. Runs in a separate thread, and does not block the application.
*/
async on_load_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view is about to be closed. The view will still be in the window at this point.
*/
async on_pre_close (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view is closed (note, there may still be other views into the same buffer).
*/
async on_close (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called just before a view is saved.
*/
async on_pre_save (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called just before a view is saved. Runs in a separate thread, and does not block the application.
*/
async on_pre_save_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after a view has been saved.
*/
async on_post_save (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after a view has been saved. Runs in a separate thread, and does not block the application.
*/
async on_post_save_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after changes have been made to a view.
*/
async on_modified (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after changes have been made to a view. Runs in a separate thread, and does not block the application.
*/
async on_modified_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after the selection has been modified in a view.
*/
async on_selection_modified (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after the selection has been modified in a view. Runs in a separate thread, and does not block the application.
*/
async on_selection_modified_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view gains input focus.
*/
async on_activated (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view gains input focus. Runs in a separate thread, and does not block the application.
*/
async on_activated_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view loses input focus.
*/
async on_deactivated (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when a view loses input focus. Runs in a separate thread, and does not block the application.
*/
async on_deactivated_async (view /*: View*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when the user's mouse hovers over a view for a short period.
*
* ```point``` is the closest point in the view to the mouse location. The mouse may not actually be located adjacent based on the value of ```hover_zone```:
* - ```sublime.HOVER_TEXT```: When the mouse is hovered over text.
* - ```sublime.HOVER_GUTTER```: When the mouse is hovered over the gutter.
* - ```sublime.HOVER_MARGIN```: When the mouse is hovered in whitespace to the right of a line.
*/
async on_hover (view /*: View*/, point /*: number*/, hover_zone /*: number*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called when determining to trigger a key binding with the given context ```key```. If the plugin knows how to respond to the context, it should return either ```true``` of ```false```. If the context is unknown, it should return ```null```.
*
* ```operator``` is one of:
* - ```sublime.OP_EQUAL```: Is the value of the context equal to the operand?
* - ```sublime.OP_NOT_EQUAL```: Is the value of the context not equal to the operand?
* - ```sublime.OP_REGEX_MATCH```: Does the value of the context match the regex given in operand?
* - ```sublime.OP_NOT_REGEX_MATCH```: Does the value of the context not match the regex given in operand?
* - ```sublime.OP_REGEX_CONTAINS```: Does the value of the context contain a substring matching the regex given in operand?
* - ```sublime.OP_NOT_REGEX_CONTAINS```: Does the value of the context not contain a substring matching the regex given in operand?
*
* ```match_all``` should be used if the context relates to the selections: does every selection have to match (```match_all == true```), or is at least one matching enough (```match_all == false```)?
*/
async on_query_context (view /*: View*/, key /*: string*/, operator /*: number*/, operand /*: boolean*/, match_all /*: boolean*/, step /*: StepObject*/) /*: Promise<boolean | void>*/ {
}
/**
* Called whenever completions are to be presented to the user. The ```prefix``` is a unicode string of the text to complete.
*
* ```locations``` is a list of points. Since this method is called for all completions no matter the syntax, ```self.view.match_selector(point, relevant_scope)``` should be called to determine if the point is relevant.
*
* The return value must be one of the following formats:
* - ```null```: no completions are provided
*
* ```
* return null
* ```
*
* - A list of 2-element lists/tuples. The first element is a unicode string of the completion trigger, the second is the unicode replacement text.
*
* ```
* return [["me1", "method1()"], ["me2", "method2()"]]
* ```
*
* The trigger may contain a tab character (```\t```) followed by a hint to display in the right-hand side of the completion box.
*
* ```
* return [
* ["me1\tmethod", "method1()"],
* ["me2\tmethod", "method2()"]
* ]
* ```
*
* The replacement text may contain dollar-numeric fields such as a snippet does, e.g. ```$0```, ```$1```.
*
* ```
* return [
* ["fn", "def ${1:name}($2) { $0 }"],
* ["for", "for ($1; $2; $3) { $0 }"]
* ]
* ```
*
* - A 2-element tuple with the first element being the list format documented above, and the second element being bit flags from the following list:
* - ```sublime.INHIBIT_WORD_COMPLETIONS```: prevent Sublime Text from showing completions based on the contents of the view
* - ```sublime.INHIBIT_EXPLICIT_COMPLETIONS```: prevent Sublime Text from showing completions based on ```.sublime-completions``` files
*
* ```
* return [
* [
* ["me1", "method1()"],
* ["me2", "method2()"]
* ],
* sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
* ]
* ```
*/
async on_query_completions (view /*: View*/, prefix /*: string*/, locations /*: Array<number>*/, step /*: StepObject*/) /*: Promise<Array<[Array<[string, string]>, number]> | Array<[string, string]> | void>*/ {
}
/**
* Called when a text command is issued. The listener may return a ```(command, arguments)``` tuple to rewrite the command, or ```null``` to run the command unmodified.
*/
async on_text_command (view /*: View*/, command_name /*: string*/, args /*: Object*/, step /*: StepObject*/) /*: Promise<[string, Object] | void>*/ {
}
/**
* Called when a window command is issued. The listener may return a ```(command, arguments)``` tuple to rewrite the command, or ```null``` to run the command unmodified.
*/
async on_window_command (view /*: View*/, command_name /*: string*/, args /*: Object*/, step /*: StepObject*/) /*: Promise<[string, Object] | void>*/ {
}
/**
* Called after a text command has been executed.
*/
async on_post_text_command (view /*: View*/, command_name /*: string*/, args /*: Object*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
/**
* Called after a window command has been executed.
*/
async on_post_window_command (view /*: View*/, command_name /*: string*/, args /*: Object*/, step /*: StepObject*/) /*: Promise<void>*/ {
}
}
module.exports = EventListener
|
function formatDate(date) {
return new Intl.DateTimeFormat().format(new Date(date));
}
export const formatDateTime = (date) => {
if(!date){
return null
}
return new Intl.DateTimeFormat('en-us', { weekday: "short", year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "numeric", hour12: true, timeZone: 'Australia/Sydney' }).format(new Date(date))
}
export default formatDate;
|
// @flow
import type {TypedState} from '../reducer'
export type NodeCB = (err: ?any, result: ?any) => void
export type SagaGenerator<Yield, Actions> = Generator<Yield, void, Actions>
export type Buffer<T> = {
isEmpty: () => boolean,
put: (msg: T) => void,
take: () => T,
}
export type Channel<T> = {
take: (cb: (msg: T) => void) => void,
put: (msg: T) => void,
close: () => void,
}
// TODO (mm) it might be possible to type these better instead of just key: string
export type ChannelConfig<T> = {
[key: string]: () => Buffer<T>,
}
export type ChannelMap<T> = {
[key: string]: Channel<T>,
}
export type SagaMap = {
// $FlowIssue with returning Generators from functions
[key: string]: Generator<*, *, *>,
}
type _AfterSelect<Out, SelectorFn: (state: TypedState) => Out> = Out // eslint-disable-line
export type AfterSelect<SelectorFn: (state: TypedState) => *> = _AfterSelect<*, SelectorFn>
|
'use strict';
const common = require('../common');
const assert = require('assert');
const tick = require('./tick');
const initHooks = require('./init-hooks');
const { checkInvocations } = require('./hook-checks');
const binding = process.binding('http_parser');
const HTTPParser = binding.HTTPParser;
const CRLF = '\r\n';
const RESPONSE = HTTPParser.RESPONSE;
const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0;
const kOnBody = HTTPParser.kOnBody | 0;
const hooks = initHooks();
hooks.enable();
const request = Buffer.from(
'HTTP/1.1 200 OK' + CRLF +
'Content-types: text/plain' + CRLF +
'Content-Length: 4' + CRLF +
CRLF +
'pong'
);
const parser = new HTTPParser(RESPONSE);
const as = hooks.activitiesOfTypes('HTTPPARSER');
const httpparser = as[0];
assert.strictEqual(
as.length, 1,
'1 httpparser created synchronously when creating new httpparser');
assert.strictEqual(typeof httpparser.uid, 'number', 'uid is a number');
assert.strictEqual(typeof httpparser.triggerId,
'number', 'triggerId is a number');
checkInvocations(httpparser, { init: 1 }, 'when created new Httphttpparser');
parser[kOnHeadersComplete] = common.mustCall(onheadersComplete);
parser[kOnBody] = common.mustCall(onbody);
parser.execute(request, 0, request.length);
function onheadersComplete() {
checkInvocations(httpparser, { init: 1, before: 1 },
'when onheadersComplete called');
}
function onbody(buf, start, len) {
checkInvocations(httpparser, { init: 1, before: 2, after: 1 },
'when onbody called');
tick(1, common.mustCall(tick1));
}
function tick1() {
parser.close();
tick(1);
}
process.on('exit', onexit);
function onexit() {
hooks.disable();
hooks.sanityCheck('HTTPPARSER');
checkInvocations(httpparser, { init: 1, before: 2, after: 2, destroy: 1 },
'when process exits');
}
|
const pkg = require('../template/package.json');
const fs = require('fs-extra');
module.exports = (targetPkg, name, program) => new Promise((resolve, reject) => {
const customContent = {
author: program.author || '',
version: '0.0.0',
name: name,
license: program.license || ''
};
if (fs.existsSync(targetPkg)) {
const genPkg = JSON.stringify({
...pkg,
...customContent
}, null, '\t');
fs.writeFile(targetPkg, genPkg, { encoding: 'utf8' }, function (err) {
if (err) reject(err);
resolve(true);
});
}
});
|
# -*- coding: utf-8 -*-
###############################################################################
#
# AllExercises
# Retrieves a list of all exercises in the Khan Academy library.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class AllExercises(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the AllExercises Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(AllExercises, self).__init__(temboo_session, '/Library/KhanAcademy/Exercises/AllExercises')
def new_input_set(self):
return AllExercisesInputSet()
def _make_result_set(self, result, path):
return AllExercisesResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return AllExercisesChoreographyExecution(session, exec_id, path)
class AllExercisesInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the AllExercises
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
pass
class AllExercisesResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the AllExercises Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Khan Academy.)
"""
return self._output.get('Response', None)
class AllExercisesChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return AllExercisesResultSet(response, path)
|
var nnet_to_raw_nnet_8cc =
[
[ "main", "nnet-to-raw-nnet_8cc.html#a0ddf1224851353fc92bfbff6f499fa97", null ]
];
|
Ext.define('KitchenSink.view.binding.Formula', {
extend: 'Ext.form.Panel',
// <example>
otherContent: [{
type: 'ViewModel',
path: 'modern/src/view/binding/FormulaModel.js'
}],
// </example>
viewModel: 'binding-formula',
shadow: true,
cls: 'demo-solid-background',
items: {
xtype: 'fieldset',
instructions: 'As the field changes, the formula calculates the 2x and 4x values.',
items: [{
xtype: 'spinnerfield',
label: 'Number',
stepValue: 1,
bind: '{x}'
}, {
xtype: 'textfield',
readOnly: true,
label: 'Times 2',
bind: '{x} * 2 = {twice}'
}, {
xtype: 'textfield',
readOnly: true,
label: 'Times 4',
bind: '{x} * 4 = {quad}'
}]
}
});
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import bisect
import collections
import ctypes
import heapq
import inspect
import multiprocessing
import random
import re
import string
import sys
import time
from six import moves
from rally.common import logging
from rally import exceptions
LOG = logging.getLogger(__name__)
class ImmutableMixin(object):
_inited = False
def __init__(self):
self._inited = True
def __setattr__(self, key, value):
if self._inited:
raise exceptions.ImmutableException()
super(ImmutableMixin, self).__setattr__(key, value)
class EnumMixin(object):
def __iter__(self):
for k, v in moves.map(lambda x: (x, getattr(self, x)), dir(self)):
if not k.startswith("_"):
yield v
class StdOutCapture(object):
def __init__(self):
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = moves.StringIO()
return sys.stdout
def __exit__(self, type, value, traceback):
sys.stdout = self.stdout
class StdErrCapture(object):
def __init__(self):
self.stderr = sys.stderr
def __enter__(self):
sys.stderr = moves.StringIO()
return sys.stderr
def __exit__(self, type, value, traceback):
sys.stderr = self.stderr
class Timer(object):
def __enter__(self):
self.error = None
self.start = time.time()
return self
def timestamp(self):
return self.start
def __exit__(self, type, value, tb):
self.finish = time.time()
if type:
self.error = (type, value, tb)
def duration(self):
return self.finish - self.start
class Struct(object):
def __init__(self, **entries):
self.__dict__.update(entries)
class RAMInt(object):
"""Share RAM integer, for IPC.
This class represents iterable which refers directly to an integer value
stored in RAM. Being a true system-level singletone, this allows safely
share integer among processes and threads.
"""
def __init__(self, base_value=0):
self.__int = multiprocessing.Value("I", base_value)
def __int__(self):
return self.__int.value
def __str__(self):
return str(self.__int.value)
def __iter__(self):
return self
def __next__(self):
with self.__int._lock:
value = self.__int.value
self.__int.value += 1
if self.__int.value > value:
return value
raise StopIteration
def next(self):
return self.__next__()
def reset(self):
with self.__int._lock:
self.__int.value = 0
def get_method_class(func):
"""Return the class that defined the given method.
:param func: function to get the class for.
:returns: class object or None if func is not an instance method.
"""
if hasattr(func, "im_class"):
# this check works in Python 2
for cls in inspect.getmro(func.im_class):
if func.__name__ in cls.__dict__:
return cls
elif hasattr(func, "__qualname__") and inspect.isfunction(func):
# this check works in Python 3
cls = getattr(
inspect.getmodule(func),
func.__qualname__.split(".<locals>.", 1)[0].rsplit(".", 1)[0])
if isinstance(cls, type):
return cls
else:
return None
def first_index(lst, predicate):
"""Return the index of the first element that matches a predicate.
:param lst: list to find the matching element in.
:param predicate: predicate object.
:returns: the index of the first matching element or None if no element
matches the predicate.
"""
for i, e in enumerate(lst):
if predicate(e):
return i
return None
def distance(s1, s2):
"""Computes the edit distance between two strings.
The edit distance is the Levenshtein distance. The larger the return value,
the more edits are required to transform one string into the other.
:param s1: First string to compare
:param s2: Second string to compare
:returns: Integer distance between two strings
"""
n = range(0, len(s1) + 1)
for y in range(1, len(s2) + 1):
l, n = n, [y]
for x in moves.range(1, len(s1) + 1):
n.append(min(l[x] + 1, n[-1] + 1,
l[x - 1] + (s2[y - 1] != s1[x - 1])))
return n[-1]
def retry(times, func, *args, **kwargs):
"""Try to execute multiple times function mitigating exceptions.
:param times: Amount of attempts to execute function
:param func: Function that should be executed
:param args: *args that are passed to func
:param kwargs: **kwargs that are passed to func
:raises Exception: Raise any exception that can raise func
:returns: Result of func(*args, **kwargs)
"""
for i in range(times):
try:
return func(*args, **kwargs)
except Exception:
if i == times - 1:
raise
def iterate_per_tenants(users):
"""Iterate of a single arbitrary user from each tenant
:type users: list of users
:return: iterator of a single user from each tenant
"""
processed_tenants = set()
for user in users:
if user["tenant_id"] not in processed_tenants:
processed_tenants.add(user["tenant_id"])
yield (user, user["tenant_id"])
class RandomNameGeneratorMixin(object):
"""Mixin for objects that need to generate random names.
This mixin provides one method,
``generate_random_name()``. Classes that include it must provide a
``self.task`` attribute that references a task dict or a
``self.verification`` attribute that references a verification dict.
Classes that use this mixin may set two class variables to alter the
behavior of ``generate_random_name()``:
* ``RESOURCE_NAME_FORMAT``: A mktemp(1)-like format string that
will be used to pattern the generated random string. It must
contain two separate segments of at least three 'X's; the first
one will be replaced by a portion of the task ID, and the second
will be replaced with a random string.
* ``RESOURCE_NAME_ALLOWED_CHARACTERS``: A string consisting of the
characters allowed in the random portions of the name.
"""
_resource_name_placeholder_re = re.compile(
"^(?P<prefix>.*?)(?P<task>X{3,})(?P<sep>[^X]+?)(?P<rand>X{3,})"
"(?P<suffix>.*)$")
RESOURCE_NAME_FORMAT = "rally_XXXXXXXX_XXXXXXXX"
RESOURCE_NAME_ALLOWED_CHARACTERS = string.ascii_letters + string.digits
@classmethod
def _generate_random_part(cls, length):
"""Generate a random string.
:param length: The length of the random string.
:returns: string, randomly-generated string of the specified length
containing only characters from
cls.RESOURCE_NAME_ALLOWED_CHARACTERS
"""
return "".join(random.choice(cls.RESOURCE_NAME_ALLOWED_CHARACTERS)
for i in range(length))
@classmethod
def _generate_task_id_part(cls, task_id, length):
# NOTE(stpierre): the first part of the random name is a
# subset of the task ID
task_id_part = task_id.replace("-", "")[0:length]
if len(task_id_part) < length:
LOG.debug("Task ID %(task_id)s cannot be included in a random "
"name because it is too short. Format: %(format)s" %
{"task_id": task_id,
"format": cls.RESOURCE_NAME_FORMAT})
elif any(char not in cls.RESOURCE_NAME_ALLOWED_CHARACTERS
for char in task_id_part):
LOG.debug("Task ID %(task_id)s cannot be included in a random "
"name because it includes disallowed characters. "
"Allowed characters are: %(chars)s" %
{"task_id": task_id,
"chars": cls.RESOURCE_NAME_ALLOWED_CHARACTERS})
else:
return task_id_part
# NOTE(stpierre): either the task UUID is shorter than the
# task portion; or the portion of the task ID that we
# would use contains only characters in
# resource_name_allowed_characters.
try:
# NOTE(stpierre): seed pRNG with task ID so that all random
# names with the same task ID have the same task ID part
random.seed(task_id)
return cls._generate_random_part(length)
finally:
random.seed()
def generate_random_name(self):
"""Generate pseudo-random resource name for scenarios.
The name follows a deterministic pattern, which helps support
out-of-band cleanup of Rally-created resources.
If possible, a portion of the task ID will be used in the
random name. If the task ID contains characters that are not
allowed by the 'RESOURCE_NAME_ALLOWED_CHARACTERS' class
variable, then a random string, seeded with the task ID, will
be generated for the task portion of the random name.
:returns: str, pseudo-random name
"""
if hasattr(self, "task"):
task_id = self.task["uuid"]
elif hasattr(self, "verification"):
task_id = self.verification["uuid"]
match = self._resource_name_placeholder_re.match(
self.RESOURCE_NAME_FORMAT)
if match is None:
raise ValueError("%s is not a valid resource name format" %
self.RESOURCE_NAME_FORMAT)
parts = match.groupdict()
return "".join([
parts["prefix"],
self._generate_task_id_part(task_id, len(parts["task"])),
parts["sep"],
self._generate_random_part(len(parts["rand"])),
parts["suffix"]])
@classmethod
def name_matches_object(cls, name, task_id=None):
"""Determine if a resource name could have been created by this class.
:param name: The resource name to check against this class's
RESOURCE_NAME_FORMAT.
:param task_id: The task ID that must match the task portion of
the random name
:returns: bool
"""
match = cls._resource_name_placeholder_re.match(
cls.RESOURCE_NAME_FORMAT)
parts = match.groupdict()
subst = {
"prefix": re.escape(parts["prefix"]),
"sep": re.escape(parts["sep"]),
"suffix": re.escape(parts["suffix"]),
"chars": re.escape(cls.RESOURCE_NAME_ALLOWED_CHARACTERS),
"rand_length": len(parts["rand"])}
if task_id:
subst["task_id"] = cls._generate_task_id_part(task_id,
len(parts["task"]))
else:
subst["task_id"] = "[%s]{%s}" % (subst["chars"],
len(parts["task"]))
name_re = re.compile(
"%(prefix)s%(task_id)s%(sep)s"
"[%(chars)s]{%(rand_length)s}%(suffix)s$" % subst)
return bool(name_re.match(name))
def name_matches_object(name, *objects, **kwargs):
"""Determine if a resource name could have been created by given objects.
The object(s) must implement RandomNameGeneratorMixin.
It will often be more efficient to pass a list of classes to
name_matches_object() than to perform multiple
name_matches_object() calls, since this function will deduplicate
identical name generation options.
:param name: The resource name to check against the object's
RESOURCE_NAME_FORMAT.
:param *objects: Classes or objects to fetch random name
generation parameters from.
:param **kwargs: Additional keyword args. Only 'task_id' is
recognized, but the function signature must
accept **kwargs because Python can be wierd about
mixing *-magic and non-magic. The optional
'task_id' kwarg can be used to specify the task
ID that must match the task portion of the random
name.
:returns: bool
"""
task_id = kwargs.get("task_id")
unique_rng_options = {}
for obj in objects:
key = (obj.RESOURCE_NAME_FORMAT, obj.RESOURCE_NAME_ALLOWED_CHARACTERS)
if key not in unique_rng_options:
unique_rng_options[key] = obj
return any(obj.name_matches_object(name, task_id=task_id)
for obj in unique_rng_options.values())
def merge(length, *sources):
"""Merge lists of lists.
Each source produces (or contains) lists of ordered items.
Items of each list must be greater or equal to all items of
the previous list (that implies that items must be comparable).
The function merges the sources into lists with the length
equal to given one, except the last list which can be shorter.
Example:
it1 = iter([[1, 3, 5], [5, 7, 9, 14], [17, 21, 36, 41]])
it2 = iter([[2, 2, 4], [9, 10], [16, 19, 23, 26, 91]])
it3 = iter([[5], [5, 7, 11, 14, 14, 19, 23]])
it = merge(10, it1, it2, it3)
for i in it:
print i
prints out:
[1, 2, 2, 3, 4, 5, 5, 5, 5, 7, 7, 9, 9, 10]
[11, 14, 14, 14, 16, 17, 19, 19, 21, 23, 23]
[26, 36, 41, 91]
:param: length, length of generated lists, except the last one.
:param: sources, generators that produce lists of items to merge
"""
streams = [
{"data": [], "gen": src}
for src in sources]
out_chunk = []
while True:
while len(out_chunk) < length:
# Least right item among streams
lri = None
# Refresh data if needed
for s in streams:
if s["gen"] and not s["data"]:
try:
while not s["data"]:
s["data"] = next(s["gen"])
except StopIteration:
s["gen"] = None
# ... and define least right item
if s["data"]:
rightmost_item = s["data"][-1]
if (lri is None) or (rightmost_item < lri):
lri = rightmost_item
# No more data to merge
if lri is None:
break
to_merge = []
for s in streams:
if s["data"]:
pos = bisect.bisect_right(s["data"], lri)
to_merge.append(s["data"][:pos])
s["data"] = s["data"][pos:]
out_chunk += heapq.merge(*to_merge)
if out_chunk:
if len(out_chunk) > length:
yield out_chunk[:length]
out_chunk = out_chunk[length:]
else:
yield out_chunk
out_chunk = []
else:
return
def interruptable_sleep(sleep_time, atomic_delay=0.1):
"""Return after sleep_time seconds.
Divide sleep_time by atomic_delay, and call time.sleep N times.
This should give a chance to interrupt current thread.
:param sleep_time: idle time of method (in seconds).
:param atomic_delay: parameter with which time.sleep would be called
int(sleep_time / atomic_delay) times.
"""
if atomic_delay <= 0:
raise ValueError("atomic_delay should be > 0")
if sleep_time >= 0:
if sleep_time < 1:
return time.sleep(sleep_time)
for x in moves.xrange(int(sleep_time / atomic_delay)):
time.sleep(atomic_delay)
left = sleep_time - (int(sleep_time / atomic_delay)) * atomic_delay
if left:
time.sleep(left)
else:
raise ValueError("sleep_time should be >= 0")
def terminate_thread(thread_ident, exc_type=exceptions.ThreadTimeoutException):
"""Terminate a python thread.
Use PyThreadState_SetAsyncExc to terminate thread.
:param thread_ident: threading.Thread.ident value
:param exc_type: an Exception type to be raised
"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread_ident), ctypes.py_object(exc_type))
def timeout_thread(queue):
"""Terminate threads by timeout.
Function need to be run in separate thread. Its designed to terminate
threads which are running longer then timeout.
Parent thread will put tuples (thread_ident, deadline) in the queue,
where `thread_ident` is Thread.ident value of thread to watch, and
`deadline` is timestamp when thread should be terminated. Also tuple
(None, None) should be put when all threads are exited and no more
threads to watch.
:param queue: Queue object to communicate with parent thread.
"""
all_threads = collections.deque()
while True:
if not all_threads:
timeout = None
else:
thread_ident, deadline = all_threads[0]
timeout = deadline - time.time()
try:
next_thread = queue.get(timeout=timeout)
all_threads.append(next_thread)
except (moves.queue.Empty, ValueError):
# NOTE(rvasilets) Empty means that timeout was occurred.
# ValueError means that timeout lower then 0.
LOG.info("Thread %s is timed out. Terminating." % thread_ident)
terminate_thread(thread_ident)
all_threads.popleft()
if next_thread == (None, None,):
return
|
from math import inf
# Input Arguments for Ranking & Crowding Distance calculation
# F : The list of objective functions
# X_in : The sample population in the form of 2D list of dimension X_in[pop_size][num_of_params]
# Rest are self-explanatory
class Individual:
def __init__(self, idx, X, F):
self.id = idx
self.X = X # Coefficient matrix of the individual vector
self.F = F # Solution Matrix of the Individual (for all objectives)
self.sp = [] # Set of individuals dominated by this individual
self.np = 0 # Number of individuals that dominate this individual
self.rank = 0
self.crowding_distance = 0
def __repr__(self):
return repr(())
def ranking(F, X_in):
# F is a 2D list, with elements as [Objective][Individual]
# F[i][j] implies the value of the (i)th objective for the (j)th individual
front = 1
Fronts = dict(
[(front, [])]
)
num_objectives = len(F[0])
pop_size = len(X_in)
individuals = []
for i in range(0, pop_size, 1):
individuals.append(Individual(i, X_in[i], F[i]))
individuals[i].sp = []
individuals[i].np = 0
for i in range(0, pop_size, 1):
for j in range(0, pop_size, 1):
less_d = 0
equal_d = 0
more_d = 0
for k in range(0, num_objectives, 1):
if F[i][k] > F[j][k]:
less_d = less_d + 1
elif F[i][k] == F[j][k]:
equal_d = equal_d + 1
else:
more_d = more_d + 1
if (less_d == 0) & (equal_d != num_objectives):
individuals[i].sp.append(j)
elif (more_d == 0) & (equal_d != num_objectives):
individuals[i].np = individuals[i].np + 1
if individuals[i].np == 0:
individuals[i].rank = 1
Fronts[front].append(i)
front_mem = Fronts[front]
dat = dict(
[(front, front_mem)]
)
Fronts.update(dat)
while Fronts[front]:
buff = []
for i in range(0, len(Fronts[front])):
if individuals[Fronts[front][i]].sp:
for j in range(0, len(individuals[Fronts[front][i]].sp), 1):
individuals[individuals[Fronts[front][i]].sp[j]].np = \
individuals[individuals[Fronts[front][i]].sp[j]].np - 1
if individuals[individuals[Fronts[front][i]].sp[j]].np == 0:
individuals[individuals[Fronts[front][i]].sp[j]].rank = front + 1
buff.append(individuals[Fronts[front][i]].sp[j])
front = front + 1
Fronts[front] = buff
individuals = crowding_distance(Fronts, individuals, num_objectives)
return [Fronts, individuals]
def crowding_distance(fronts, individuals, num_objectives):
for front in fronts:
for objective in range(0, num_objectives, 1):
front_indivs_unsorted = fronts[front]
sorter_dict = {}
for i in front_indivs_unsorted:
sorter_dict[i] = individuals[i].F[objective]
front_indivs_sorted = sorted(sorter_dict, key=sorter_dict.__getitem__, \
reverse=False)
len_front_indiv = len(front_indivs_sorted)
if len_front_indiv > 2:
individuals[front_indivs_sorted[0]].crowding_distance = \
individuals[front_indivs_sorted[len_front_indiv - 1]].crowding_distance = inf
f_max = individuals[front_indivs_sorted[len_front_indiv - 1]].F[objective]
f_min = individuals[front_indivs_sorted[0]].F[objective]
for i in range(1, len_front_indiv - 1, 1):
prev_indiv_val = individuals[front_indivs_sorted[i - 1]].F[objective]
next_indiv_val = individuals[front_indivs_sorted[i + 1]].F[objective]
if f_max != f_min:
individuals[front_indivs_sorted[i]].crowding_distance = \
individuals[front_indivs_sorted[i]].crowding_distance + \
((next_indiv_val - prev_indiv_val) / (f_max - f_min))
else:
individuals[front_indivs_sorted[i]].crowding_distance = inf
return individuals
|
from gi.repository import Gtk, GdkPixbuf
from typing import Any
from pkg_resources import resource_filename
from ocrd_browser import __version__
from ocrd_browser.model import Document
@Gtk.Template(filename=resource_filename(__name__, '../resources/about-dialog.ui'))
class AboutDialog(Gtk.AboutDialog):
__gtype_name__ = "AboutDialog"
def __init__(self, **kwargs: Any):
Gtk.AboutDialog.__init__(self, **kwargs)
# noinspection PyCallByClass,PyArgumentList
self.set_logo(GdkPixbuf.Pixbuf.new_from_resource('/org/readmachine/ocrd-browser/icons/logo.png'))
self.set_version(__version__)
@Gtk.Template(filename=resource_filename(__name__, '../resources/open-dialog.ui'))
class OpenDialog(Gtk.FileChooserDialog):
__gtype_name__ = "OpenDialog"
def __init__(self, **kwargs: Any):
# noinspection PyCallByClass
Gtk.FileChooserDialog.__init__(self, **kwargs)
filter_mets = Gtk.FileFilter()
filter_mets.set_name("METS files")
filter_mets.add_mime_type("application/mets+xml")
filter_mets.add_pattern("*.xml")
self.add_filter(filter_mets)
filter_any = Gtk.FileFilter()
filter_any.set_name("Any files")
filter_any.add_pattern("*")
self.add_filter(filter_any)
@Gtk.Template(filename=resource_filename(__name__, '../resources/save-dialog.ui'))
class SaveDialog(Gtk.FileChooserDialog):
__gtype_name__ = "SaveDialog"
def __init__(self, **kwargs: Any):
# noinspection PyCallByClass
Gtk.FileChooserDialog.__init__(self, **kwargs)
filter_text = Gtk.FileFilter()
filter_text.set_name("METS files")
filter_text.add_mime_type("text/xml")
self.add_filter(filter_text)
filter_any = Gtk.FileFilter()
filter_any.set_name("Any files")
filter_any.add_pattern("*")
self.add_filter(filter_any)
class SaveChangesDialog(Gtk.MessageDialog):
def __init__(self, document: Document, **kwargs: Any):
Gtk.MessageDialog.__init__(self, **kwargs)
name = document.workspace.mets.unique_identifier if document.workspace.mets.unique_identifier else '<unnamed>'
self.props.text = 'Save changes to document "{}" before closing?'.format(name)
self.props.secondary_text = 'If you don’t save, changes to {} will be permanently lost.'.format(
document.original_url if document.original_url else 'this file')
self.props.message_type = Gtk.MessageType.QUESTION
# Close Button
close_button: Gtk.Button = self.add_button('Close without saving', Gtk.ResponseType.NO)
close_button.get_style_context().add_class('destructive-action')
# Cancel Button
self.add_button('_Cancel', Gtk.ResponseType.CANCEL)
# Save Button
save_text = '_Save' if document.original_url else '_Save as ...'
save_button: Gtk.Button = self.add_button(save_text, Gtk.ResponseType.YES)
self.set_default(save_button)
|
import Sequelize, { Model } from 'sequelize';
class Recipient extends Model {
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
street: Sequelize.STRING,
number: Sequelize.STRING,
complement: Sequelize.STRING,
state: Sequelize.STRING,
city: Sequelize.STRING,
zip_code: Sequelize.STRING,
},
{
sequelize,
}
);
}
}
export default Recipient;
|
'use strict';
// FIXME not really a unit test
// FIXME npm should be stubbed
// TODO Test for local module... what does it even mean?
const os = require('os');
const path = require('path');
const fs = require('fs');
const test = require('tap').test;
const mkdirp = require('mkdirp');
const rimraf = require('rimraf');
const grabProject = require('../lib/grab-project');
const sandbox = path.join(os.tmpdir(), `citgm-${Date.now()}`);
const fixtures = path.join(__dirname, 'fixtures');
test('grab-project: setup', (t) => {
mkdirp(sandbox, (err) => {
t.error(err);
t.end();
});
});
test('grab-project: npm module', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
raw: 'omg-i-pass'
},
meta: {},
options: {}
};
grabProject(context, (err) => {
t.error(err);
fs.stat(context.unpack, (err, stats) => {
t.error(err);
t.ok(stats.isFile(), 'The tar ball should exist on the system');
t.end();
});
});
});
test('grab-project: local', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
raw: './test/fixtures/omg-i-pass',
type: 'directory'
},
meta: {},
options: {}
};
grabProject(context, (err) => {
t.error(err);
fs.stat(context.unpack, (err, stats) => {
t.error(err);
t.ok(stats.isFile(), 'The tar ball should exist on the system');
t.end();
});
});
});
test('grab-project: lookup table', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
raw: 'lodash'
},
meta: {},
options: {}
};
grabProject(context, (err) => {
t.error(err);
fs.stat(context.unpack, (err, stats) => {
t.error(err);
t.ok(stats.isFile(), 'The tar ball should exist on the system');
t.end();
});
});
});
test('grab-project: local', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
raw: 'omg-i-pass',
type: 'directory'
},
options: {}
};
process.chdir(fixtures);
grabProject(context, (err) => {
t.error(err);
fs.stat(context.unpack, (err, stats) => {
t.error(err);
t.ok(stats.isFile(), 'The tar ball should exist on the system');
process.chdir(__dirname);
t.end();
});
});
});
test('grab-project: module does not exist', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
raw: 'I-DO-NOT-EXIST'
},
options: {}
};
grabProject(context, (err) => {
t.equals(err && err.message, 'Failure getting project from npm');
t.end();
});
});
test('grab-project: timeout', (t) => {
const context = {
emit: function() {},
path: sandbox,
module: {
name: 'omg-i-pass'
},
meta: {},
options: {
npmLevel: 'silly',
timeoutLength: 10
}
};
grabProject(context, (err) => {
t.equals(err && err.message, 'Download Timed Out');
t.end();
});
});
test('grab-project: teardown', (t) => {
rimraf(sandbox, (err) => {
t.error(err);
t.end();
});
});
|
"use strict";var KTPortletDraggable={init:function(){$("#kt_sortable_portlets").sortable({connectWith:".kt-portlet__head",items:".kt-portlet",opacity:.8,handle:".kt-portlet__head",coneHelperSize:!0,placeholder:"kt-portlet--sortable-placeholder",forcePlaceholderSize:!0,tolerance:"pointer",helper:"clone",cancel:".kt-portlet--sortable-empty",revert:250,update:function(e,t){t.item.prev().hasClass("kt-portlet--sortable-empty")&&t.item.prev().before(t.item)}})}};jQuery(document).ready(function(){KTPortletDraggable.init()});
|
from .activity import ActivityCount
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const wrapIcon_1 = require("../utils/wrapIcon");
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 20, height: 20, viewBox: "0 0 20 20", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M3.5 5.5a1 1 0 011.84-.56.75.75 0 101.24-.83A2.5 2.5 0 104.6 8h10.67a.75.75 0 000-1.5H4.5a1 1 0 01-1-1z", fill: primaryFill }),
React.createElement("path", { d: "M9.75 4a.75.75 0 000 1.5h7.5a.75.75 0 000-1.5h-7.5z", fill: primaryFill }),
React.createElement("path", { d: "M5.75 9a.75.75 0 000 1.5h4.98A5.48 5.48 0 0114.5 9H5.75z", fill: primaryFill }),
React.createElement("path", { d: "M2.75 11.5h7.14c-.3.46-.53.96-.68 1.5H2.75a.75.75 0 010-1.5z", fill: primaryFill }),
React.createElement("path", { d: "M5.75 14h3.27a5.57 5.57 0 00.07 1.5H5.75a.75.75 0 010-1.5z", fill: primaryFill }),
React.createElement("path", { d: "M19 14.5a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0zm-4-2a.5.5 0 00-1 0V14h-1.5a.5.5 0 000 1H14v1.5a.5.5 0 101 0V15h1.5a.5.5 0 100-1H15v-1.5z", fill: primaryFill }));
};
const ReadingListAdd20Filled = wrapIcon_1.default(rawSvg({}), 'ReadingListAdd20Filled');
exports.default = ReadingListAdd20Filled;
|
'''
This is the input node that receives spikes and converts to Baxter joint angles.
'''
import argparse
from brian_multiprocess_udp import BrianConnectUDP
def from_spikes_to_baxter(spikes_pipe_in, spikes_pipe_out):
"""
This function substitutes the run_brian_simulation and converts the received spikes into Baxter joint angles.
"""
import numpy
import select
import time
import rospy
import baxter_interface
# Initialization of the ROS node.
print("Initializing Baxter node... ")
rospy.init_node("spikes_to_joint_position", disable_signals=True) # This node name must be UNIQUE!
# the option "disable_signals=True" is important to make ROS ignore the signals from my program.
print("Getting robot state... ")
rs = baxter_interface.RobotEnable()
init_state = rs.state().enabled
# def clean_shutdown():
# print("\nExiting example...")
# if not init_state:
# print("Disabling robot...")
# rs.disable()
# rospy.on_shutdown(clean_shutdown)
if not init_state:
print("Enabling robot... ")
rs.enable()
# Initializes the left arm
left = baxter_interface.Limb('left')
time.sleep(1) #gives some time to ROS...
# Gets the joint names used inside the joint_command
lj = left.joint_names()
# lj[0] => s0
# lj[1] => s1
# lj[2] => e0
# lj[3] => e1
# lj[4] => w0
# lj[5] => w1
# lj[6] => w2
joint_weights = [0.1,0.1,1,0.1,1,1,1] #these numbers will be multiplicated by the steps each joint is going to do
joint_weights = [1,1,0,1,0,1,0] #these numbers will be multiplicated by the steps each joint is going to do
# ['left_s0','left_s1','left_e0','left_e1','left_w0','left_w1','left_w2']
def converts_spikes_into_joints(spike_numpy_array, limb, step_up, step_down):
"""
Receives a numpy.array with 7 elements. If an element has an 1, increases the value of that joint. If is a 0, decreases.
spike_numpy_array => the numpy array received directly from my system (a numpy array with 1's and 0's) and the
same length as NumOfNeuronsInput.
joint_angles => list of the angles following the same order as joint_names
step_up => amount to be increased at the angle if a spike is received
step_down => amount to be decreased at the angle if a spike is received
returns a dict with all the joint angles values
"""
joint_angles = limb.joint_angles() #gets the actual joint angles
joint_names = ['left_s0','left_s1','left_e0','left_e1','left_w0','left_w1','left_w2']
movement = spike_numpy_array*step_up - (spike_numpy_array*(-1)+1)*step_down
# Creates a dictionary with the joint names and the necessary steps (up or down)
final_step = dict(zip(joint_names, movement*joint_weights))
# Returns the actual joint angles summed by the steps according to the spike_numpy_array received
return {key:value+final_step[key] for key,value in joint_angles.iteritems()}
print "Node started!"
while True:
if select.select([spikes_pipe_in],[],[]):
# Receives the spike train from the pipe, converts according to the converts_spikes_into_joints function
# and them apply the dictionary with the joint names and angles to Baxter using the set_joint_positions method
# from the limb object (left).
#print "spikes in!"
cmd = converts_spikes_into_joints(spikes_pipe_in.recv(), left, 0.005, 0.005)
#print "set joints!",
left.set_joint_positions( cmd )
#print "Done!"
# Prints the current endpoint position.
print "Baxter Input Node"
print cmd
if __name__=="__main__":
#my_randseed=int(''.join(map(str,numpy.random.randint(0,9,15)))) # creates a long integer converted random seed, but it is a crazy dumb code :)
# Process the information received from the command line arguments.
parser = argparse.ArgumentParser(description="Sets up and launch the Baxter OUTPUT node.")
parser.add_argument("--input_neurons", help="The total number of INPUT neurons.", type=int, default=7)
parser.add_argument("--input_addr", help="Input addresses as a tuple with (\"IP\", PORT).", type=list, default=("192.168.1.123", 33333))
parser.add_argument("--input_clock", help="An integer number used as the INPUT clock (mS)", type=int, default=100)
parser.add_argument("--brian_addr", help="A number from 0 to 255 used to identify the node.", type=int, default=200)
parser.add_argument("--ttime", help="Total time of the simulation.", type=int, required=True)
args=parser.parse_args()
my_inputclock_dt = args.input_clock
Number_of_Neurons_Input = args.input_neurons
my_simulation = BrianConnectUDP(main_NeuronGroup=None, NumOfNeuronsInput=Number_of_Neurons_Input,
input_addresses=[(args.input_addr[0], args.input_addr[1], Number_of_Neurons_Input)],
inputclock_dt=my_inputclock_dt, TotalSimulationTime=args.ttime, brian_bypass=from_spikes_to_baxter, brian_address=args.brian_addr)
|
/*!
* Copyright 2013 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-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 ContentConstants = module.exports.ContentConstants = {};
ContentConstants.roles = {
// Determines not only all known roles, but the ordered priority they take as the "effective" role. (e.g., if
// you are both a viewer and a manager, your effective role is "manager", so it must be later in the list)
'ALL_PRIORITY': ['viewer', 'manager'],
'MANAGER': 'manager',
'VIEWER': 'viewer'
};
ContentConstants.resourceSubTypes = ['collabdoc', 'link', 'file'];
ContentConstants.events = {
'CREATED_COMMENT': 'createdComment',
'CREATED_CONTENT': 'createdContent',
'DELETED_CONTENT': 'deletedContent',
'RESTORED_REVISION': 'restoredContent',
'UPDATED_CONTENT': 'updatedContent',
'UPDATED_CONTENT_BODY': 'updatedContentBody',
'UPDATED_CONTENT_MEMBERS': 'updatedContentMembers',
'UPDATED_CONTENT_PREVIEW': 'updatedContentPreview'
};
ContentConstants.previews = {
'DONE': 'done',
'ERROR': 'error',
'IGNORED': 'ignored',
'PENDING': 'pending'
};
ContentConstants.activity = {
'ACTIVITY_CONTENT_CREATE': 'content-create',
'ACTIVITY_CONTENT_UPDATE': 'content-update',
'ACTIVITY_CONTENT_UPDATE_VISIBILITY': 'content-update-visibility',
'ACTIVITY_CONTENT_REVISION': 'content-revision',
'ACTIVITY_CONTENT_RESTORED_REVISION': 'content-restored-revision',
'ACTIVITY_CONTENT_SHARE': 'content-share',
'ACTIVITY_CONTENT_ADD_TO_LIBRARY': 'content-add-to-library',
'ACTIVITY_CONTENT_COMMENT': 'content-comment',
'PROP_OAE_CONTENT_ID': 'oae:contentId',
'PROP_OAE_CONTENT_TYPE': 'oae:resourceSubType',
'PROP_OAE_CONTENT_MIMETYPE': 'oae:mimeType',
'PROP_OAE_PREVIEWS': 'oae:previews',
'PROP_OAE_REVISION_ID': 'oae:revisionId',
'PROP_OAE_WIDE_IMAGE': 'oae:wideImage'
};
ContentConstants.library = {
'CONTENT_LIBRARY_INDEX_NAME': 'content:content'
};
ContentConstants.backend = {
'DOWNLOAD_STRATEGY_DIRECT': 'direct',
'DOWNLOAD_STRATEGY_INTERNAL': 'internal',
'DOWNLOAD_STRATEGY_REDIRECT': 'redirect',
'DOWNLOAD_STRATEGY_TEST': 'test'
};
|
const Alexa = require('ask-sdk-core');
const util = require('./util');
const ScheduleTripApiHandler = {
canHandle(handlerInput) {
return util.isApiRequest(
handlerInput, 'com.ubertravel.scheduleTrip');
},
handle(handlerInput) {
const destination = util.getApiArguments(handlerInput).destination;
const startDate = util.getApiArguments(handlerInput).startDate;
const tripLength = util.getApiArguments(handlerInput).tripLength;
const reservationNumber =
scheduleTrip(destination, startDate, tripLength);
const response = {
apiResponse: {
reservationNumber: reservationNumber,
destination: destination,
departureDate: startDate,
returnDate: tripLength
}
};
return response;
}
};
function scheduleTrip(destination, departureDate, returnDate) {
console.log("HANDLING A SCHEDULE TRIP REQUEST::::: ");
console.log(` - ${destination}`);
console.log(` - ${departureDate}`);
console.log(` - ${returnDate}`);
//
// TODO: Invoke travel booking API
//
return 12345; // <-- Fake reservation number
}
const LaunchRequestHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
},
handle(handlerInput) {
const speakOutput = 'Welcome, you can say Hello or Help. Which would you like to try?';
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'SessionEndedRequest';
},
handle(handlerInput) {
// Any cleanup logic goes here.
return handlerInput.responseBuilder.getResponse();
}
};
// The intent reflector is used for interaction model testing and debugging.
// It will simply repeat the intent the user said. You can create custom handlers
// for your intents by defining them above, then also adding them to the request
// handler chain below.
const IntentReflectorHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest';
},
handle(handlerInput) {
const intentName = Alexa.getIntentName(handlerInput.requestEnvelope);
const speakOutput = `You just triggered ${intentName}`;
return handlerInput.responseBuilder
.speak(speakOutput)
//.reprompt('add a reprompt if you want to keep the session open for the user to respond')
.getResponse();
}
};
// Generic error handling to capture any syntax or routing errors. If you receive an error
// stating the request handler chain is not found, you have not implemented a handler for
// the intent being invoked or included it in the skill builder below.
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`~~~~ Error handled: ${error.stack}`);
const speakOutput = `Sorry, I had trouble doing what you asked. Please try again.`;
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
// The SkillBuilder acts as the entry point for your skill, routing all request and response
// payloads to the handlers above. Make sure any new handlers or interceptors you've
// defined are included below. The order matters - they're processed top to bottom.
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
ScheduleTripApiHandler,
SessionEndedRequestHandler,
IntentReflectorHandler,
)
.addErrorHandlers(
ErrorHandler,
)
.lambda();
|
import React, { Component } from 'react';
import './ActorPage.scss';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import getActorPageData from '../../actions/pages/getActorPageData';
import Slider from '../Slider'
import PreviewItem from '../PreviewItem'
import noPoster from '../../images/no-poster.jpg'
import noPhoto from '../../images/no-photo.png';
class ActorPage extends Component {
goToPage = (event) => {
this.props.changeSearchInput('');
}
componentDidMount() {
const pageID = this.props.location.pathname.split('/')[2];
this.props.getActorPageData(pageID)
}
render() {
const { base_url, profile_sizes, poster_sizes } = this.props.settings.images;
const { profile_path, name, biography, gender, birthday, place_of_birth, homepage, also_known_as, known_for_department, movie_credits } = this.props.pageData;
const { genres } = this.props.genres;
const actorGender = gender == 1 ? "Female" : "Male";
const imageSrc = !!profile_path && !!profile_sizes
? base_url + profile_sizes[2] + profile_path
: noPoster;
const actorKnownAs = also_known_as
? also_known_as.map(item => <li key={item}>{item}</li>)
: null
const popularMovies = movie_credits && movie_credits.cast && base_url
? (
movie_credits.cast.sort(function (a, b) {
return b.popularity - a.popularity;
})
.slice(0, 40)
.map(item => {
const movieGenres = genres.filter((genreItem) => {
return item.genre_ids.some((arrival) => genreItem.id === arrival)
} )
const src = !!poster_sizes && item.poster_path
? base_url + poster_sizes[1] + item.poster_path
: noPoster;
return (
<PreviewItem
genres={movieGenres}
key={item.id}
id={item.id}
title={item.title}
imageSrc={src}
goToPage={this.goToPage}
voteAverage={item.vote_average}
previewType="movie"
/>
)
})
)
: null
const unpopularMovies = movie_credits && movie_credits.cast && base_url
? (
movie_credits.cast.sort(function (a, b) {
return a.popularity - b.popularity;
})
.slice(0, 40)
.map(item => {
const src = !!poster_sizes && item.poster_path
? base_url + poster_sizes[1] + item.poster_path
: noPoster;
return (
<PreviewItem
genres={item.genres}
key={item.id}
id={item.id}
title={item.title}
imageSrc={src}
goToPage={this.goToPage}
voteAverage={item.vote_average}
previewType="movie"
/>
)
})
)
: null
return (
<div className="actor-page">
<div className="info-container container">
<img className="poster" src={imageSrc} alt={`${name}`}
/>
<div className="info-content">
<h1 className="title">{name}</h1>
<h3>Biography</h3>
<div className="biography">{biography}</div>
</div>
</div>
<div className="more-info container">
<div className="additional-info">
<h2>Personal Info</h2>
{ known_for_department
? (<div className="gender"><h3>Known For:</h3><span>{known_for_department}</span></div>)
: null
}
{ gender
? (<div className="gender"><h3>Gender:</h3><span>{actorGender}</span></div>)
: null
}
{ birthday
? (<div className="gender"><h3>Birthday:</h3><span>{birthday}</span></div>)
: null
}
{ place_of_birth
? (<div className="gender"><h3>Place of Birth:</h3><span>{place_of_birth}</span></div>)
: null
}
{ homepage
? (<div className="gender"><h3>Official Site:</h3><a href={homepage}>{homepage}</a></div>)
: null
}
{ also_known_as && also_known_as.length
? (<div className="gender"><h3>Also Known Ass:</h3><ul>{actorKnownAs}</ul></div>)
: null
}
</div>
<div className="movies slider">
{
popularMovies
? (<div className="popularMovies"><h3>Popular movies:</h3><Slider previewItems={popularMovies}/></div>)
: null
}
{
unpopularMovies
? (<div className="unpopularMovies"><h3>Unpopular movies:</h3><Slider previewItems={unpopularMovies}/></div>)
: null
}
</div>
</div>
</div>
)
}
}
const mapStateToProps = (store) => {
return {
settings: store.settings,
pageData: store.actorPageData,
genres: store.genres
}
}
const mapDispatchToProps = dispatch => {
return {
getActorPageData: input => dispatch(getActorPageData(input))
}
}
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)
(ActorPage)
);
|
const multer = require('multer')
const { v1: uuid } = require('uuid')
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/jpg': 'jpg'
}
const fileUpload = multer({
limits: 500000,
storage: multer.diskStorage({
destination : (req, file, cb) => {
cb(null, 'uploads/images')
},
filename: (req, file, cb) => {
const ext = MIME_TYPE_MAP[file.mimetype]
cb(null, uuid() + '.' + ext)
}
}),
fileFilter: (req, file, cb) => {
const isValid = !!MIME_TYPE_MAP[file.mimetype]
let error = isValid ? null : new Error('Invalid mime type')
cb(error, isValid)
}
})
module.exports = fileUpload
|
var producto_table = $('#producto-table').DataTable({
"ajax": APP_URL+"/producto/getJson",
"responsive": true,
"processing": true,
"info": true,
"showNEntries": true,
"dom": 'Bfrtip',
lengthMenu: [
[ 10, 25, 50, -1 ],
[ '10 filas', '25 filas', '50 filas', 'Mostrar todo' ]
],
"buttons": [
'pageLength',
'excelHtml5',
'csvHtml5'
],
"paging": true,
"language": {
"sdecimal": ".",
"sthousands": ",",
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
},
},
"order": [0, 'desc'],
"columns": [ {
"title": "No.",
"data": "id",
"width" : "5%",
"responsivePriority": 1,
"render": function( data, type, full, meta ) {
return (data);},
},
{
"title": "Nombre",
"data": "nombre",
"width" : "10%",
"responsivePriority": 2,
"render": function( data, type, full, meta ) {
return ("<a href='/producto/show/"+ full.id +"' class='ver-producto'>"
+data +
"</a>");},
},
{
"title": "Acciones",
"orderable": false,
"width" : "20%",
"render": function(data, type, full, meta) {
return "<div id='" + full.id + "' class='text-center'>" +
"<div class='float-left col-lg-6'>" +
"<a href='/producto/edit/"+ full.id +"' class='edit-producto'>" +
"<i class='fa fa-btn fa-edit' title='Editar Producto'></i>" +
"</a>" + "</div>" +
"<div class='float-right col-lg-6'>" +
"<a href='#' class='remove-producto' onclick='confirmacion("+ full.id +")'>" +
"<i class='fa fa-btn fa-trash' title='Eliminar Producto'></i>" +
"</a>" + "</div>";
},
"responsivePriority": 5
}]
});
function confirmacion(id) {
if (window.confirm("Eliminar el producto")) {
window.CSRF_TOKEN = '{{ csrf_token() }}';
var url = "/productos/delete/"+id;
$.ajax({
method: "DELETE",
url: url,
headers: {'X-CSRF-TOKEN': window.CSRF_TOKEN },
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
contentType: "application/json",
}).done(function (data){
alert("Producto eliminado exitosamente!");
location.reload();
}).fail(function(errors) {
var errors = JSON.parse(errors.responseText);
console.log(errors);
});
return false;
}
}
|
# Copyright 2020 Box Robotics, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Driver for for the PTPDump node"""
import argparse
import json
import sys
import rclpy
from ouster_ptp.ros_node.ptp import PTPDump
def get_args():
parser = argparse.ArgumentParser(
description="Dump the JSON being published by the pmc_node",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-t", "--topic", required=False,
default="/ouster_ptp/ptp", type=str,
help="Topic to subscribe to")
parser.add_argument("-p", "--pretty", required=False,
action='store_true', default=False,
help="Pretty print the json output")
parser.add_argument("-1", "--one", required=False,
action='store_true', default=False,
help="Dump one message and exit")
args, _ = parser.parse_known_args(sys.argv[1:])
return args
def main() -> int:
args = get_args()
count = 0
def cb(json_str):
nonlocal count
count += 1
if args.pretty:
print(json.dumps(json.loads(json_str),
sort_keys=True, indent=2, separators=(',', ': ')),
flush=True)
else:
print(json_str, flush=True)
try:
rclpy.init(args=sys.argv[1:])
node = PTPDump(topic=args.topic, cb=cb)
while rclpy.ok():
if args.one and count > 0:
break
rclpy.spin_once(node)
except KeyboardInterrupt:
pass
except:
print(sys.exc_info()[0], ": ", sys.exc_info()[1])
raise
finally:
node.destroy_node()
rclpy.shutdown()
return 0
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/src/core/di';
import { ListWrapper, Map } from 'angular2/src/facade/collection';
import { Serializer } from "angular2/src/web_workers/shared/serializer";
import { isPresent, FunctionWrapper } from "angular2/src/facade/lang";
import { MessageBus } from "angular2/src/web_workers/shared/message_bus";
import { PromiseWrapper, ObservableWrapper } from 'angular2/src/facade/async';
export class ServiceMessageBrokerFactory {
}
export let ServiceMessageBrokerFactory_ = class ServiceMessageBrokerFactory_ extends ServiceMessageBrokerFactory {
constructor(_messageBus, _serializer) {
super();
this._messageBus = _messageBus;
this._serializer = _serializer;
}
createMessageBroker(channel, runInZone = true) {
this._messageBus.initChannel(channel, runInZone);
return new ServiceMessageBroker_(this._messageBus, this._serializer, channel);
}
};
ServiceMessageBrokerFactory_ = __decorate([
Injectable(),
__metadata('design:paramtypes', [MessageBus, Serializer])
], ServiceMessageBrokerFactory_);
export class ServiceMessageBroker {
}
/**
* Helper class for UIComponents that allows components to register methods.
* If a registered method message is received from the broker on the worker,
* the UIMessageBroker deserializes its arguments and calls the registered method.
* If that method returns a promise, the UIMessageBroker returns the result to the worker.
*/
export class ServiceMessageBroker_ extends ServiceMessageBroker {
constructor(messageBus, _serializer, channel) {
super();
this._serializer = _serializer;
this.channel = channel;
this._methods = new Map();
this._sink = messageBus.to(channel);
var source = messageBus.from(channel);
ObservableWrapper.subscribe(source, (message) => this._handleMessage(message));
}
registerMethod(methodName, signature, method, returnType) {
this._methods.set(methodName, (message) => {
var serializedArgs = message.args;
let numArgs = signature === null ? 0 : signature.length;
var deserializedArgs = ListWrapper.createFixedSize(numArgs);
for (var i = 0; i < numArgs; i++) {
var serializedArg = serializedArgs[i];
deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature[i]);
}
var promise = FunctionWrapper.apply(method, deserializedArgs);
if (isPresent(returnType) && isPresent(promise)) {
this._wrapWebWorkerPromise(message.id, promise, returnType);
}
});
}
_handleMessage(map) {
var message = new ReceivedMessage(map);
if (this._methods.has(message.method)) {
this._methods.get(message.method)(message);
}
}
_wrapWebWorkerPromise(id, promise, type) {
PromiseWrapper.then(promise, (result) => {
ObservableWrapper.callEmit(this._sink, { 'type': 'result', 'value': this._serializer.serialize(result, type), 'id': id });
});
}
}
export class ReceivedMessage {
constructor(data) {
this.method = data['method'];
this.args = data['args'];
this.id = data['id'];
this.type = data['type'];
}
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VydmljZV9tZXNzYWdlX2Jyb2tlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImRpZmZpbmdfcGx1Z2luX3dyYXBwZXItb3V0cHV0X3BhdGgtOUQxaUdRVkcudG1wL2FuZ3VsYXIyL3NyYy93ZWJfd29ya2Vycy9zaGFyZWQvc2VydmljZV9tZXNzYWdlX2Jyb2tlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7T0FBTyxFQUFDLFVBQVUsRUFBQyxNQUFNLHNCQUFzQjtPQUN4QyxFQUFDLFdBQVcsRUFBRSxHQUFHLEVBQWEsTUFBTSxnQ0FBZ0M7T0FDcEUsRUFBQyxVQUFVLEVBQUMsTUFBTSw0Q0FBNEM7T0FDOUQsRUFBQyxTQUFTLEVBQVEsZUFBZSxFQUFDLE1BQU0sMEJBQTBCO09BQ2xFLEVBQUMsVUFBVSxFQUFDLE1BQU0sNkNBQTZDO09BQy9ELEVBQWUsY0FBYyxFQUFFLGlCQUFpQixFQUFDLE1BQU0sMkJBQTJCO0FBRXpGO0FBS0EsQ0FBQztBQUdELHFGQUFrRCwyQkFBMkI7SUFJM0UsWUFBb0IsV0FBdUIsRUFBRSxXQUF1QjtRQUNsRSxPQUFPLENBQUM7UUFEVSxnQkFBVyxHQUFYLFdBQVcsQ0FBWTtRQUV6QyxJQUFJLENBQUMsV0FBVyxHQUFHLFdBQVcsQ0FBQztJQUNqQyxDQUFDO0lBRUQsbUJBQW1CLENBQUMsT0FBZSxFQUFFLFNBQVMsR0FBWSxJQUFJO1FBQzVELElBQUksQ0FBQyxXQUFXLENBQUMsV0FBVyxDQUFDLE9BQU8sRUFBRSxTQUFTLENBQUMsQ0FBQztRQUNqRCxNQUFNLENBQUMsSUFBSSxxQkFBcUIsQ0FBQyxJQUFJLENBQUMsV0FBVyxFQUFFLElBQUksQ0FBQyxXQUFXLEVBQUUsT0FBTyxDQUFDLENBQUM7SUFDaEYsQ0FBQztBQUNILENBQUM7QUFkRDtJQUFDLFVBQVUsRUFBRTs7Z0NBQUE7QUFnQmI7QUFHQSxDQUFDO0FBRUQ7Ozs7O0dBS0c7QUFDSCwyQ0FBMkMsb0JBQW9CO0lBSTdELFlBQVksVUFBc0IsRUFBVSxXQUF1QixFQUFTLE9BQU87UUFDakYsT0FBTyxDQUFDO1FBRGtDLGdCQUFXLEdBQVgsV0FBVyxDQUFZO1FBQVMsWUFBTyxHQUFQLE9BQU8sQ0FBQTtRQUYzRSxhQUFRLEdBQTBCLElBQUksR0FBRyxFQUFvQixDQUFDO1FBSXBFLElBQUksQ0FBQyxLQUFLLEdBQUcsVUFBVSxDQUFDLEVBQUUsQ0FBQyxPQUFPLENBQUMsQ0FBQztRQUNwQyxJQUFJLE1BQU0sR0FBRyxVQUFVLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ3RDLGlCQUFpQixDQUFDLFNBQVMsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxPQUFPLEtBQUssSUFBSSxDQUFDLGNBQWMsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDO0lBQ2pGLENBQUM7SUFFRCxjQUFjLENBQUMsVUFBa0IsRUFBRSxTQUFpQixFQUFFLE1BQTJDLEVBQ2xGLFVBQWlCO1FBQzlCLElBQUksQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLFVBQVUsRUFBRSxDQUFDLE9BQXdCO1lBQ3JELElBQUksY0FBYyxHQUFHLE9BQU8sQ0FBQyxJQUFJLENBQUM7WUFDbEMsSUFBSSxPQUFPLEdBQUcsU0FBUyxLQUFLLElBQUksR0FBRyxDQUFDLEdBQUcsU0FBUyxDQUFDLE1BQU0sQ0FBQztZQUN4RCxJQUFJLGdCQUFnQixHQUFVLFdBQVcsQ0FBQyxlQUFlLENBQUMsT0FBTyxDQUFDLENBQUM7WUFDbkUsR0FBRyxDQUFDLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxPQUFPLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztnQkFDakMsSUFBSSxhQUFhLEdBQUcsY0FBYyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUN0QyxnQkFBZ0IsQ0FBQyxDQUFDLENBQUMsR0FBRyxJQUFJLENBQUMsV0FBVyxDQUFDLFdBQVcsQ0FBQyxhQUFhLEVBQUUsU0FBUyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDbEYsQ0FBQztZQUVELElBQUksT0FBTyxHQUFHLGVBQWUsQ0FBQyxLQUFLLENBQUMsTUFBTSxFQUFFLGdCQUFnQixDQUFDLENBQUM7WUFDOUQsRUFBRSxDQUFDLENBQUMsU0FBUyxDQUFDLFVBQVUsQ0FBQyxJQUFJLFNBQVMsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUM7Z0JBQ2hELElBQUksQ0FBQyxxQkFBcUIsQ0FBQyxPQUFPLENBQUMsRUFBRSxFQUFFLE9BQU8sRUFBRSxVQUFVLENBQUMsQ0FBQztZQUM5RCxDQUFDO1FBQ0gsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDO0lBRU8sY0FBYyxDQUFDLEdBQXlCO1FBQzlDLElBQUksT0FBTyxHQUFHLElBQUksZUFBZSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ3ZDLEVBQUUsQ0FBQyxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDdEMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsT0FBTyxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQzdDLENBQUM7SUFDSCxDQUFDO0lBRU8scUJBQXFCLENBQUMsRUFBVSxFQUFFLE9BQXFCLEVBQUUsSUFBVTtRQUN6RSxjQUFjLENBQUMsSUFBSSxDQUFDLE9BQU8sRUFBRSxDQUFDLE1BQVc7WUFDdkMsaUJBQWlCLENBQUMsUUFBUSxDQUN0QixJQUFJLENBQUMsS0FBSyxFQUNWLEVBQUMsTUFBTSxFQUFFLFFBQVEsRUFBRSxPQUFPLEVBQUUsSUFBSSxDQUFDLFdBQVcsQ0FBQyxTQUFTLENBQUMsTUFBTSxFQUFFLElBQUksQ0FBQyxFQUFFLElBQUksRUFBRSxFQUFFLEVBQUMsQ0FBQyxDQUFDO1FBQ3ZGLENBQUMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQztBQUNILENBQUM7QUFFRDtJQU1FLFlBQVksSUFBMEI7UUFDcEMsSUFBSSxDQUFDLE1BQU0sR0FBRyxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUM7UUFDN0IsSUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDekIsSUFBSSxDQUFDLEVBQUUsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDckIsSUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDM0IsQ0FBQztBQUNILENBQUM7QUFBQSIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7SW5qZWN0YWJsZX0gZnJvbSAnYW5ndWxhcjIvc3JjL2NvcmUvZGknO1xuaW1wb3J0IHtMaXN0V3JhcHBlciwgTWFwLCBNYXBXcmFwcGVyfSBmcm9tICdhbmd1bGFyMi9zcmMvZmFjYWRlL2NvbGxlY3Rpb24nO1xuaW1wb3J0IHtTZXJpYWxpemVyfSBmcm9tIFwiYW5ndWxhcjIvc3JjL3dlYl93b3JrZXJzL3NoYXJlZC9zZXJpYWxpemVyXCI7XG5pbXBvcnQge2lzUHJlc2VudCwgVHlwZSwgRnVuY3Rpb25XcmFwcGVyfSBmcm9tIFwiYW5ndWxhcjIvc3JjL2ZhY2FkZS9sYW5nXCI7XG5pbXBvcnQge01lc3NhZ2VCdXN9IGZyb20gXCJhbmd1bGFyMi9zcmMvd2ViX3dvcmtlcnMvc2hhcmVkL21lc3NhZ2VfYnVzXCI7XG5pbXBvcnQge0V2ZW50RW1pdHRlciwgUHJvbWlzZVdyYXBwZXIsIE9ic2VydmFibGVXcmFwcGVyfSBmcm9tICdhbmd1bGFyMi9zcmMvZmFjYWRlL2FzeW5jJztcblxuZXhwb3J0IGFic3RyYWN0IGNsYXNzIFNlcnZpY2VNZXNzYWdlQnJva2VyRmFjdG9yeSB7XG4gIC8qKlxuICAgKiBJbml0aWFsaXplcyB0aGUgZ2l2ZW4gY2hhbm5lbCBhbmQgYXR0YWNoZXMgYSBuZXcge0BsaW5rIFNlcnZpY2VNZXNzYWdlQnJva2VyfSB0byBpdC5cbiAgICovXG4gIGFic3RyYWN0IGNyZWF0ZU1lc3NhZ2VCcm9rZXIoY2hhbm5lbDogc3RyaW5nLCBydW5JblpvbmU/OiBib29sZWFuKTogU2VydmljZU1lc3NhZ2VCcm9rZXI7XG59XG5cbkBJbmplY3RhYmxlKClcbmV4cG9ydCBjbGFzcyBTZXJ2aWNlTWVzc2FnZUJyb2tlckZhY3RvcnlfIGV4dGVuZHMgU2VydmljZU1lc3NhZ2VCcm9rZXJGYWN0b3J5IHtcbiAgLyoqIEBpbnRlcm5hbCAqL1xuICBwdWJsaWMgX3NlcmlhbGl6ZXI6IFNlcmlhbGl6ZXI7XG5cbiAgY29uc3RydWN0b3IocHJpdmF0ZSBfbWVzc2FnZUJ1czogTWVzc2FnZUJ1cywgX3NlcmlhbGl6ZXI6IFNlcmlhbGl6ZXIpIHtcbiAgICBzdXBlcigpO1xuICAgIHRoaXMuX3NlcmlhbGl6ZXIgPSBfc2VyaWFsaXplcjtcbiAgfVxuXG4gIGNyZWF0ZU1lc3NhZ2VCcm9rZXIoY2hhbm5lbDogc3RyaW5nLCBydW5JblpvbmU6IGJvb2xlYW4gPSB0cnVlKTogU2VydmljZU1lc3NhZ2VCcm9rZXIge1xuICAgIHRoaXMuX21lc3NhZ2VCdXMuaW5pdENoYW5uZWwoY2hhbm5lbCwgcnVuSW5ab25lKTtcbiAgICByZXR1cm4gbmV3IFNlcnZpY2VNZXNzYWdlQnJva2VyXyh0aGlzLl9tZXNzYWdlQnVzLCB0aGlzLl9zZXJpYWxpemVyLCBjaGFubmVsKTtcbiAgfVxufVxuXG5leHBvcnQgYWJzdHJhY3QgY2xhc3MgU2VydmljZU1lc3NhZ2VCcm9rZXIge1xuICBhYnN0cmFjdCByZWdpc3Rlck1ldGhvZChtZXRob2ROYW1lOiBzdHJpbmcsIHNpZ25hdHVyZTogVHlwZVtdLCBtZXRob2Q6IEZ1bmN0aW9uLFxuICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm5UeXBlPzogVHlwZSk6IHZvaWQ7XG59XG5cbi8qKlxuICogSGVscGVyIGNsYXNzIGZvciBVSUNvbXBvbmVudHMgdGhhdCBhbGxvd3MgY29tcG9uZW50cyB0byByZWdpc3RlciBtZXRob2RzLlxuICogSWYgYSByZWdpc3RlcmVkIG1ldGhvZCBtZXNzYWdlIGlzIHJlY2VpdmVkIGZyb20gdGhlIGJyb2tlciBvbiB0aGUgd29ya2VyLFxuICogdGhlIFVJTWVzc2FnZUJyb2tlciBkZXNlcmlhbGl6ZXMgaXRzIGFyZ3VtZW50cyBhbmQgY2FsbHMgdGhlIHJlZ2lzdGVyZWQgbWV0aG9kLlxuICogSWYgdGhhdCBtZXRob2QgcmV0dXJucyBhIHByb21pc2UsIHRoZSBVSU1lc3NhZ2VCcm9rZXIgcmV0dXJucyB0aGUgcmVzdWx0IHRvIHRoZSB3b3JrZXIuXG4gKi9cbmV4cG9ydCBjbGFzcyBTZXJ2aWNlTWVzc2FnZUJyb2tlcl8gZXh0ZW5kcyBTZXJ2aWNlTWVzc2FnZUJyb2tlciB7XG4gIHByaXZhdGUgX3Npbms6IEV2ZW50RW1pdHRlcjxhbnk+O1xuICBwcml2YXRlIF9tZXRob2RzOiBNYXA8c3RyaW5nLCBGdW5jdGlvbj4gPSBuZXcgTWFwPHN0cmluZywgRnVuY3Rpb24+KCk7XG5cbiAgY29uc3RydWN0b3IobWVzc2FnZUJ1czogTWVzc2FnZUJ1cywgcHJpdmF0ZSBfc2VyaWFsaXplcjogU2VyaWFsaXplciwgcHVibGljIGNoYW5uZWwpIHtcbiAgICBzdXBlcigpO1xuICAgIHRoaXMuX3NpbmsgPSBtZXNzYWdlQnVzLnRvKGNoYW5uZWwpO1xuICAgIHZhciBzb3VyY2UgPSBtZXNzYWdlQnVzLmZyb20oY2hhbm5lbCk7XG4gICAgT2JzZXJ2YWJsZVdyYXBwZXIuc3Vic2NyaWJlKHNvdXJjZSwgKG1lc3NhZ2UpID0+IHRoaXMuX2hhbmRsZU1lc3NhZ2UobWVzc2FnZSkpO1xuICB9XG5cbiAgcmVnaXN0ZXJNZXRob2QobWV0aG9kTmFtZTogc3RyaW5nLCBzaWduYXR1cmU6IFR5cGVbXSwgbWV0aG9kOiAoLi4uXzogYW55W10pID0+IFByb21pc2U8YW55Pnwgdm9pZCxcbiAgICAgICAgICAgICAgICAgcmV0dXJuVHlwZT86IFR5cGUpOiB2b2lkIHtcbiAgICB0aGlzLl9tZXRob2RzLnNldChtZXRob2ROYW1lLCAobWVzc2FnZTogUmVjZWl2ZWRNZXNzYWdlKSA9PiB7XG4gICAgICB2YXIgc2VyaWFsaXplZEFyZ3MgPSBtZXNzYWdlLmFyZ3M7XG4gICAgICBsZXQgbnVtQXJncyA9IHNpZ25hdHVyZSA9PT0gbnVsbCA/IDAgOiBzaWduYXR1cmUubGVuZ3RoO1xuICAgICAgdmFyIGRlc2VyaWFsaXplZEFyZ3M6IGFueVtdID0gTGlzdFdyYXBwZXIuY3JlYXRlRml4ZWRTaXplKG51bUFyZ3MpO1xuICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCBudW1BcmdzOyBpKyspIHtcbiAgICAgICAgdmFyIHNlcmlhbGl6ZWRBcmcgPSBzZXJpYWxpemVkQXJnc1tpXTtcbiAgICAgICAgZGVzZXJpYWxpemVkQXJnc1tpXSA9IHRoaXMuX3NlcmlhbGl6ZXIuZGVzZXJpYWxpemUoc2VyaWFsaXplZEFyZywgc2lnbmF0dXJlW2ldKTtcbiAgICAgIH1cblxuICAgICAgdmFyIHByb21pc2UgPSBGdW5jdGlvbldyYXBwZXIuYXBwbHkobWV0aG9kLCBkZXNlcmlhbGl6ZWRBcmdzKTtcbiAgICAgIGlmIChpc1ByZXNlbnQocmV0dXJuVHlwZSkgJiYgaXNQcmVzZW50KHByb21pc2UpKSB7XG4gICAgICAgIHRoaXMuX3dyYXBXZWJXb3JrZXJQcm9taXNlKG1lc3NhZ2UuaWQsIHByb21pc2UsIHJldHVyblR5cGUpO1xuICAgICAgfVxuICAgIH0pO1xuICB9XG5cbiAgcHJpdmF0ZSBfaGFuZGxlTWVzc2FnZShtYXA6IHtba2V5OiBzdHJpbmddOiBhbnl9KTogdm9pZCB7XG4gICAgdmFyIG1lc3NhZ2UgPSBuZXcgUmVjZWl2ZWRNZXNzYWdlKG1hcCk7XG4gICAgaWYgKHRoaXMuX21ldGhvZHMuaGFzKG1lc3NhZ2UubWV0aG9kKSkge1xuICAgICAgdGhpcy5fbWV0aG9kcy5nZXQobWVzc2FnZS5tZXRob2QpKG1lc3NhZ2UpO1xuICAgIH1cbiAgfVxuXG4gIHByaXZhdGUgX3dyYXBXZWJXb3JrZXJQcm9taXNlKGlkOiBzdHJpbmcsIHByb21pc2U6IFByb21pc2U8YW55PiwgdHlwZTogVHlwZSk6IHZvaWQge1xuICAgIFByb21pc2VXcmFwcGVyLnRoZW4ocHJvbWlzZSwgKHJlc3VsdDogYW55KSA9PiB7XG4gICAgICBPYnNlcnZhYmxlV3JhcHBlci5jYWxsRW1pdChcbiAgICAgICAgICB0aGlzLl9zaW5rLFxuICAgICAgICAgIHsndHlwZSc6ICdyZXN1bHQnLCAndmFsdWUnOiB0aGlzLl9zZXJpYWxpemVyLnNlcmlhbGl6ZShyZXN1bHQsIHR5cGUpLCAnaWQnOiBpZH0pO1xuICAgIH0pO1xuICB9XG59XG5cbmV4cG9ydCBjbGFzcyBSZWNlaXZlZE1lc3NhZ2Uge1xuICBtZXRob2Q6IHN0cmluZztcbiAgYXJnczogYW55W107XG4gIGlkOiBzdHJpbmc7XG4gIHR5cGU6IHN0cmluZztcblxuICBjb25zdHJ1Y3RvcihkYXRhOiB7W2tleTogc3RyaW5nXTogYW55fSkge1xuICAgIHRoaXMubWV0aG9kID0gZGF0YVsnbWV0aG9kJ107XG4gICAgdGhpcy5hcmdzID0gZGF0YVsnYXJncyddO1xuICAgIHRoaXMuaWQgPSBkYXRhWydpZCddO1xuICAgIHRoaXMudHlwZSA9IGRhdGFbJ3R5cGUnXTtcbiAgfVxufVxuIl19
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
/**
* Determine if a given value is an object that implements the `RelayEnvironment`
* interface.
*/
function isClassicRelayEnvironment(environment: mixed): boolean {
return (
typeof environment === 'object' &&
environment !== null &&
typeof environment.applyMutation === 'function' &&
typeof environment.sendMutation === 'function' &&
typeof environment.forceFetch === 'function' &&
typeof environment.getFragmentResolver === 'function' &&
typeof environment.getStoreData === 'function' &&
typeof environment.primeCache === 'function'
);
}
module.exports = isClassicRelayEnvironment;
|
window.onload = function () {
const lf = new LogicFlow({
container: document.querySelector('#app'),
edgeTextDraggable: true,
nodeTextDraggable: true,
metaKeyMultipleSelected: true,
grid: {
type: 'dot',
size: 20,
},
keyboard: {
enabled: true,
},
snapline: true,
});
let lfData = window.sessionStorage.getItem('lf-data');
if (lfData) {
renderXml(lfData);
} else {
lfData = window.sessionStorage.getItem('lf-json-data');
if (!lfData) {
lfData = {};
} else {
lfData = JSON.parse(lfData);
}
lf.render(lfData);
}
document.querySelector('#selection-node-pattern').addEventListener('mousedown', () => {
lf.updateEditConfig({
stopMoveGraph: true,
extraConf: {
openSelectionMode: true,
}
});
});
lf.on('selection:selected', () => {
lf.updateEditConfig({
stopMoveGraph: false,
extraConf: {
openSelectionMode: false,
}
});
});
document.querySelector('#start-node-pattern').addEventListener('mousedown', () => {
lf.dnd.startDrag({
type: 'bpmn:startEvent',
text: '开始'
});
});
document.querySelector('#end-node-pattern').addEventListener('mousedown', () => {
lf.dnd.startDrag({
type: 'bpmn:endEvent',
text: '结束'
});
});
document.querySelector('#condition-node-pattern').addEventListener('mousedown', () => {
lf.dnd.startDrag({
type: 'bpmn:exclusiveGateway',
});
});
document.querySelector('#user-node-pattern').addEventListener('mousedown', () => {
lf.dnd.startDrag({
type: 'bpmn:userTask',
});
});
document.querySelector('#system-node-pattern').addEventListener('mousedown', () => {
lf.dnd.startDrag({
type: 'bpmn:serviceTask',
});
});
document.querySelector('#download').addEventListener('click', () => {
const data = lf.getGraphData();
const xml = json2xml(data, '\n');
this.download('logic-flow.xml', xml);
window.sessionStorage.setItem('lf-data', xml);
});
document.querySelector('#download-img').addEventListener('click', () => {
lf.getSnapshot('logic-flow.png');
});
this.document.querySelector('#upload').addEventListener('change', function (ev) {
const file = ev.target.files[0];
const reader = new FileReader()
reader.onload = (event) => {
const xml = event.target.result;
renderXml(xml);
}
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
});
function renderXml(xml) {
const json = new XML.ObjTree().parseXML(xml);
lf.render(json);
}
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
|
(function() {
var output = PUBNUB.$('output'),
input = PUBNUB.$('input'),
button = PUBNUB.$('button'),
avatar = PUBNUB.$('avatar'),
presence = PUBNUB.$('presence');
var channel = 'mchat';
// Assign a random avatar in random color
avatar.className = 'face-' + ((Math.random() * 13 + 1) >>> 0) + ' color-' + ((Math.random() * 10 + 1) >>> 0);
var p = PUBNUB.init({
subscribe_key: 'sub-c-f762fb78-2724-11e4-a4df-02ee2ddab7fe',
publish_key: 'pub-c-156a6d5f-22bd-4a13-848d-b5b4d4b36695'
});
p.subscribe({
channel : channel,
callback : function(m) {
output.innerHTML = '<p><i class="' + m.avatar + '"></i><span>' + m.text.replace( /[<>]/ig, '' ) + '</span></p>' + output.innerHTML;
},
presence: function(m){
if(m.occupancy > 1) {
presence.textContent = m.occupancy + ' people online';
} else {
presence.textContent = 'Nobody else is online';
}
}
});
p.bind('keyup', input, function(e) {
(e.keyCode || e.charCode) === 13 && publish()
});
p.bind('click', button, publish);
function publish() {
p.publish({
channel : channel,
message : {avatar: avatar.className, text: input.value},
x : (input.value='')
});
}
})();
|
pbjsChunk([40],{100:function(e,r,a){a(101),e.exports=a(102)},101:function(e,r,a){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.spec=void 0;var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var a=arguments[r];for(var t in a)Object.prototype.hasOwnProperty.call(a,t)&&(e[t]=a[t])}return e},i=a(20),n=(function(e){{if(e&&e.__esModule)return e;var r={};if(null!=e)for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&(r[a]=e[a]);return r.default=e,r}})(a(0)),d=a(6),o=a(13);var p=["id","mimes","minduration","maxduration","startdelay","skippable","playback_method","frameworks"],u=["age","external_uid","segments","gender","dnt","language"],c={body:"description",cta:"ctatext",image:{serverName:"main_image",requiredParams:{required:!0},minimumParams:{sizes:[{}]}},icon:{serverName:"icon",requiredParams:{required:!0},minimumParams:{sizes:[{}]}},sponsoredBy:"sponsored_by"},m=r.spec={code:"appnexusAst",supportedMediaTypes:[o.BANNER,o.VIDEO,o.NATIVE],isBidRequestValid:function(e){return!!(e.params.placementId||e.params.member&&e.params.invCode)},buildRequests:function(e,r){var a=e.map(l),t=e.find(y),s=void 0;t&&(s={},Object.keys(t.params.user).filter((function(e){return u.includes(e)})).forEach((function(e){return s[e]=t.params.user[e]})));var i=e.find(f),n=i?parseInt(i.params.member,10):0,d={tags:[].concat(function(e){if(Array.isArray(e)){for(var r=0,a=Array(e.length);r<e.length;r++)a[r]=e[r];return a}return Array.from(e)}(a)),user:s,sdk:{source:"pbjs",version:"0.34.0"}};return n>0&&(d.member_id=n),{method:"POST",url:"//ib.adnxs.com/ut/v3/prebid",data:JSON.stringify(d),bidderRequest:r}},interpretResponse:function(e,r){var a=this,t=r.bidderRequest;e=e.body;var d=[];if(!e||e.error){var p="in response for "+t.bidderCode+" adapter";return e&&e.error&&(p+=": "+e.error),n.logError(p),d}return e.tags&&e.tags.forEach((function(e){var r,t,p=(r=e)&&r.ads&&r.ads.length&&r.ads.find((function(e){return e.rtb}));if(p&&0!==p.cpm&&a.supportedMediaTypes.includes(p.ad_type)){var u=(function(e,r){var a={requestId:e.uuid,cpm:r.cpm,creativeId:r.creative_id,dealId:r.deal_id,currency:"USD",netRevenue:!0,ttl:300};if(r.rtb.video)s(a,{width:r.rtb.video.player_width,height:r.rtb.video.player_height,vastUrl:r.rtb.video.asset_url,descriptionUrl:r.rtb.video.asset_url,ttl:3600}),r.renderer_url&&(s(a,{adResponse:e,renderer:(function(e,r){var a=i.Renderer.install({id:r.renderer_id,url:r.renderer_url,config:{adText:"AppNexus Outstream Video Ad via Prebid.js"},loaded:!1});try{a.setRender(v)}catch(e){n.logWarn("Prebid Error calling setRender on renderer",e)}return a.setEventHandlers({impression:function(){return n.logMessage("AppNexus outstream video impression event")},loaded:function(){return n.logMessage("AppNexus outstream video loaded event")},ended:function(){n.logMessage("AppNexus outstream renderer video event"),document.querySelector("#"+e).style.display="none"}}),a})(a.adUnitCode,r)}),a.adResponse.ad=a.adResponse.ads[0],a.adResponse.ad.video=a.adResponse.ad.rtb.video);else if(r.rtb[o.NATIVE]){var t=r.rtb[o.NATIVE];a[o.NATIVE]={title:t.title,body:t.desc,cta:t.ctatext,sponsoredBy:t.sponsored,image:t.main_img&&t.main_img.url,icon:t.icon&&t.icon.url,clickUrl:t.link.url,clickTrackers:t.link.click_trackers,impressionTrackers:t.impression_trackers}}else{s(a,{width:r.rtb.banner.width,height:r.rtb.banner.height,ad:r.rtb.banner.content});try{var d=r.rtb.trackers[0].impression_urls[0],p=n.createTrackPixelHtml(d);a.ad+=p}catch(e){n.logError("Error appending tracking pixel",e)}}return a})(e,p);u.mediaType=(t=p.ad_type)===o.VIDEO?o.VIDEO:t===o.NATIVE?o.NATIVE:o.BANNER,d.push(u)}})),d},getUserSyncs:function(e){if(e.iframeEnabled)return[{type:"iframe",url:"//acdn.adnxs.com/ib/static/usersync/v3/async_usersync.html"}]}};function l(e){var r,a,i,d,u={};if(u.sizes=(function(e){var r=[],a={};if(n.isArray(e)&&2===e.length&&!n.isArray(e[0]))a.width=parseInt(e[0],10),a.height=parseInt(e[1],10),r.push(a);else if("object"===(void 0===e?"undefined":t(e)))for(var s=0;s<e.length;s++){var i=e[s];(a={}).width=parseInt(i[0],10),a.height=parseInt(i[1],10),r.push(a)}return r})(e.sizes),u.primary_size=u.sizes[0],u.ad_types=[],u.uuid=e.bidId,e.params.placementId?u.id=parseInt(e.params.placementId,10):u.code=e.params.invCode,u.allow_smaller_sizes=e.params.allowSmallerSizes||!1,u.use_pmt_rule=e.params.usePaymentRule||!1,u.prebid=!0,u.disable_psa=!0,e.params.reserve&&(u.reserve=e.params.reserve),e.params.position&&(u.position={above:1,below:2}[e.params.position]||0),e.params.trafficSourceCode&&(u.traffic_source_code=e.params.trafficSourceCode),e.params.privateSizes&&(u.private_sizes=getSizes(e.params.privateSizes)),e.params.supplyType&&(u.supply_type=e.params.supplyType),e.params.pubClick&&(u.pubclick=e.params.pubClick),e.params.extInvCode&&(u.ext_inv_code=e.params.extInvCode),e.params.externalImpId&&(u.external_imp_id=e.params.externalImpId),n.isEmpty(e.params.keywords)||(u.keywords=(r=e.params.keywords,a=[],n._each(r,(function(e,r){if(n.isArray(e)){var t=[];n._each(e,(function(e){(e=n.getValueString("keywords."+r,e))&&t.push(e)})),e=t}else{if(e=n.getValueString("keywords."+r,e),!n.isStr(e))return;e=[e]}a.push({key:r,value:e})})),a)),(e.mediaType===o.NATIVE||n.deepAccess(e,"mediaTypes.native"))&&(u.ad_types.push(o.NATIVE),e.nativeParams)){var m=(i=e.nativeParams,d={},Object.keys(i).forEach((function(e){var r=c[e]&&c[e].serverName||c[e]||e,a=c[e]&&c[e].requiredParams;d[r]=s({},a,i[e]);var t=c[e]&&c[e].minimumParams;if(a&&t){var n=Object.keys(i[e]),o=Object.keys(a);0===n.filter((function(e){return!o.includes(e)})).length&&(d[r]=s({},d[r],t))}})),d);u[o.NATIVE]={layouts:[m]}}var l=n.deepAccess(e,"mediaTypes.video"),y=n.deepAccess(e,"mediaTypes.video.context");return(e.mediaType===o.VIDEO||l)&&u.ad_types.push(o.VIDEO),(e.mediaType===o.VIDEO||l&&"outstream"!==y)&&(u.require_asset_url=!0),e.params.video&&(u.video={},Object.keys(e.params.video).filter((function(e){return p.includes(e)})).forEach((function(r){return u.video[r]=e.params.video[r]}))),(n.isEmpty(e.mediaType)&&n.isEmpty(e.mediaTypes)||e.mediaType===o.BANNER||e.mediaTypes&&e.mediaTypes[o.BANNER])&&u.ad_types.push(o.BANNER),u}function y(e){return!!e.params.user}function f(e){return!!parseInt(e.params.member,10)}function v(e){e.renderer.push((function(){window.ANOutstreamVideo.renderAd({tagId:e.adResponse.tag_id,sizes:[e.getSize().split("x")],targetId:e.adUnitCode,uuid:e.adResponse.uuid,adResponse:e.adResponse,rendererOptions:e.renderer.getConfig()},function(e,r,a){e.renderer.handleVideoEvent({id:r,eventName:a})}.bind(null,e))}))}(0,d.registerBidder)(m)},102:function(e,r){}},[100]);
|
const themes = {
default: {
title_color: "2f80ed",
icon_color: "4c71f2",
text_color: "333",
bg_color: "ffffff00",
border_color: "e4e2e2",
},
default_repocard: {
title_color: "2f80ed",
icon_color: "586069", // icon color is different
text_color: "333",
bg_color: "fffefe",
},
dark: {
title_color: "fff",
icon_color: "79ff97",
text_color: "9f9f9f",
bg_color: "151515",
},
radical: {
title_color: "fe428e",
icon_color: "f8d847",
text_color: "a9fef7",
bg_color: "141321",
},
merko: {
title_color: "abd200",
icon_color: "b7d364",
text_color: "68b587",
bg_color: "0a0f0b",
},
gruvbox: {
title_color: "fabd2f",
icon_color: "fe8019",
text_color: "8ec07c",
bg_color: "282828",
},
gruvbox_light: {
title_color: "b57614",
icon_color: "af3a03",
text_color: "427b58",
bg_color: "fbf1c7",
},
tokyonight: {
title_color: "70a5fd",
icon_color: "bf91f3",
text_color: "38bdae",
bg_color: "1a1b27",
},
onedark: {
title_color: "e4bf7a",
icon_color: "8eb573",
text_color: "df6d74",
bg_color: "282c34",
},
cobalt: {
title_color: "e683d9",
icon_color: "0480ef",
text_color: "75eeb2",
bg_color: "193549",
},
synthwave: {
title_color: "e2e9ec",
icon_color: "ef8539",
text_color: "e5289e",
bg_color: "2b213a",
},
highcontrast: {
title_color: "e7f216",
icon_color: "00ffff",
text_color: "fff",
bg_color: "000",
},
dracula: {
title_color: "ff6e96",
icon_color: "79dafa",
text_color: "f8f8f2",
bg_color: "282a36",
},
prussian: {
title_color: "bddfff",
icon_color: "38a0ff",
text_color: "6e93b5",
bg_color: "172f45",
},
monokai: {
title_color: "eb1f6a",
icon_color: "e28905",
text_color: "f1f1eb",
bg_color: "272822",
},
vue: {
title_color: "41b883",
icon_color: "41b883",
text_color: "273849",
bg_color: "fffefe",
},
"vue-dark": {
title_color: "41b883",
icon_color: "41b883",
text_color: "fffefe",
bg_color: "273849",
},
"shades-of-purple": {
title_color: "fad000",
icon_color: "b362ff",
text_color: "a599e9",
bg_color: "2d2b55",
},
nightowl: {
title_color: "c792ea",
icon_color: "ffeb95",
text_color: "7fdbca",
bg_color: "011627",
},
buefy: {
title_color: "7957d5",
icon_color: "ff3860",
text_color: "363636",
bg_color: "ffffff",
},
"blue-green": {
title_color: "2f97c1",
icon_color: "f5b700",
text_color: "0cf574",
bg_color: "040f0f",
},
algolia: {
title_color: "00AEFF",
icon_color: "2DDE98",
text_color: "FFFFFF",
bg_color: "050F2C",
},
"great-gatsby": {
title_color: "ffa726",
icon_color: "ffb74d",
text_color: "ffd95b",
bg_color: "000000",
},
darcula: {
title_color: "BA5F17",
icon_color: "84628F",
text_color: "BEBEBE",
bg_color: "242424",
},
bear: {
title_color: "e03c8a",
icon_color: "00AEFF",
text_color: "bcb28d",
bg_color: "1f2023",
},
"solarized-dark": {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "002b36",
},
"solarized-light": {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "fdf6e3",
},
"chartreuse-dark": {
title_color: "7fff00",
icon_color: "00AEFF",
text_color: "fff",
bg_color: "000",
},
nord: {
title_color: "81a1c1",
text_color: "d8dee9",
icon_color: "88c0d0",
bg_color: "2e3440",
},
gotham: {
title_color: "2aa889",
icon_color: "599cab",
text_color: "99d1ce",
bg_color: "0c1014",
},
"material-palenight": {
title_color: "c792ea",
icon_color: "89ddff",
text_color: "a6accd",
bg_color: "292d3e",
},
graywhite: {
title_color: "24292e",
icon_color: "24292e",
text_color: "24292e",
bg_color: "ffffff",
},
"vision-friendly-dark": {
title_color: "ffb000",
icon_color: "785ef0",
text_color: "ffffff",
bg_color: "000000",
},
"ayu-mirage": {
title_color: "f4cd7c",
icon_color: "73d0ff",
text_color: "c7c8c2",
bg_color: "1f2430",
},
"midnight-purple": {
title_color: "9745f5",
icon_color: "9f4bff",
text_color: "ffffff",
bg_color: "000000",
},
calm: {
title_color: "e07a5f",
icon_color: "edae49",
text_color: "ebcfb2",
bg_color: "373f51",
},
"flag-india": {
title_color: "ff8f1c",
icon_color: "250E62",
text_color: "509E2F",
bg_color: "ffffff",
},
omni: {
title_color: "FF79C6",
icon_color: "e7de79",
text_color: "E1E1E6",
bg_color: "191622",
},
react: {
title_color: "61dafb",
icon_color: "61dafb",
text_color: "ffffff",
bg_color: "20232a",
},
jolly: {
title_color: "ff64da",
icon_color: "a960ff",
text_color: "ffffff",
bg_color: "291B3E",
},
maroongold: {
title_color: "F7EF8A",
icon_color: "F7EF8A",
text_color: "E0AA3E",
bg_color: "260000",
},
yeblu: {
title_color: "ffff00",
icon_color: "ffff00",
text_color: "ffffff",
bg_color: "002046",
},
blueberry: {
title_color: "82aaff",
icon_color: "89ddff",
text_color: "27e8a7",
bg_color: "242938",
},
slateorange: {
title_color: "faa627",
icon_color: "faa627",
text_color: "ffffff",
bg_color: "36393f",
},
kacho_ga: {
title_color: "bf4a3f",
icon_color: "a64833",
text_color: "d9c8a9",
bg_color: "402b23",
},
outrun: {
title_color: "ffcc00",
icon_color: "ff1aff",
text_color: "8080ff",
bg_color: "141439",
},
ocean_dark: {
title_color: "8957B2",
icon_color: "FFFFFF",
text_color: "92D534",
bg_color: "151A28",
},
city_lights: {
title_color: "5D8CB3",
icon_color: "4798FF",
text_color: "718CA1",
bg_color: "1D252C",
},
github_dark: {
title_color: "58A6FF",
icon_color: "1F6FEB",
text_color: "C3D1D9",
bg_color: "0D1117",
},
discord_old_blurple: {
title_color: "7289DA",
icon_color: "7289DA",
text_color: "FFFFFF",
bg_color: "2C2F33",
},
aura_dark: {
title_color: "ff7372",
icon_color: "6cffd0",
text_color: "dbdbdb",
bg_color: "252334",
},
panda: {
title_color: "19f9d899",
icon_color: "19f9d899",
text_color: "FF75B5",
bg_color: "31353a",
},
noctis_minimus: {
title_color: "d3b692",
icon_color: "72b7c0",
text_color: "c5cdd3",
bg_color: "1b2932",
},
cobalt2: {
title_color: "ffc600",
icon_color: "ffffff",
text_color: "0088ff",
bg_color: "193549",
},
swift: {
title_color: "000000",
icon_color: "f05237",
text_color: "000000",
bg_color: "f7f7f7",
},
aura: {
title_color: "a277ff",
icon_color: "ffca85",
text_color: "61ffca",
bg_color: "15141b",
},
apprentice: {
title_color: "ffffff",
icon_color: "ffffaf",
text_color: "bcbcbc",
bg_color: "262626",
},
trans_bg: {
title_color: "2f80ed",
icon_color: "4c71f2",
text_color: "333",
bg_color: "yellow",
border_color: "e4e2e2",
},
};
module.exports = themes;
|
import {analyser, audio} from './audio';
mapboxgl.accessToken = 'pk.eyJ1IjoiY3R3aGl0ZSIsImEiOiItb0dqdUlZIn0.4Zb1DGESXnx0ePxMVLihZQ';
export const map = new mapboxgl.Map({
style: 'mapbox://styles/mapbox/dark-v9',
// center: [-78.9002, 35.9939],
center: {
lng: -74.00649562332922,
lat: 40.70811328605049
},
zoom: 15,
pitch: 55,
bearing: -17.6,
hash: false,
container: 'map'
});
map.addControl(new mapboxgl.FullscreenControl());
// The 'building' layer in the mapbox-streets vector source contains building-height
// data from OpenStreetMap.
map.on('load', function() {
var bins =20;
var maxHeight = 80;
var binWidth = maxHeight / bins;
// Divide the buildings into 16 bins based on their true height, using a layer filter.
for (var i = 0; i < bins; i++) {
map.addLayer({
'id': '3d-buildings-' + i,
'source': 'composite',
'source-layer': 'building',
'filter': ['all', ['==', 'extrude', 'true'], ['>', 'height', i * binWidth], ['<=', 'height', (i + 1) * binWidth]],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa',
'fill-extrusion-height-transition': {
duration: 0,
delay: 0
},
'fill-extrusion-opacity': .6
}
});
}
var frequencyData = new Uint8Array(bins); //was 200
var avg = 0;
function funkyTown() {
analyser.getByteFrequencyData(frequencyData);
for (var i = 0; i < bins; i++) {
avg += frequencyData[i];
map.setPaintProperty('3d-buildings-' + i, 'fill-extrusion-color', getRandomColor(frequencyData[i]));
map.setPaintProperty('3d-buildings-' + i, 'fill-extrusion-height', frequencyData[i]);
// map.setPaintProperty('3d-buildings-' + i, 'fill-extrusion-base', frequencyData[bins.length - i]);
}
requestAnimationFrame(funkyTown);
}
requestAnimationFrame(funkyTown);
});
function generateFrequencies(n) {
var freq = [];
var i = 0;
for (i; i < n; i++) {
freq.push(Math.floor((Math.random() * 100) + 1));
}
return freq;
}
function getRandomColor(freq) {
var letters = '0123456789ABCDEF0123456789ABCDEF';
var color = '#98F';
for (var i = 0; i < 3; i++) {
color += letters[Math.floor(Math.floor(freq /8))];
}
return color;
}
|
import React from "react";
// nodejs library that concatenates classes
import classNames from "classnames";
// nodejs library to set properties for components
import PropTypes from "prop-types";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
// @material-ui/icons
// core components
import styles from "./cardAvatarStyle";
const useStyles = makeStyles(styles);
export default function CardAvatar(props) {
const classes = useStyles();
const {
children,
className,
plain,
profile,
testimonial,
testimonialFooter,
...rest
} = props;
const cardAvatarClasses = classNames({
[classes.cardAvatar]: true,
[classes.cardAvatarProfile]: profile,
[classes.cardAvatarPlain]: plain,
[classes.cardAvatarTestimonial]: testimonial,
[classes.cardAvatarTestimonialFooter]: testimonialFooter,
[className]: className !== undefined
});
return (
<div className={cardAvatarClasses} {...rest}>
{children}
</div>
);
}
CardAvatar.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string,
profile: PropTypes.bool,
plain: PropTypes.bool,
testimonial: PropTypes.bool,
testimonialFooter: PropTypes.bool
};
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
runserver
~~~~~~~~~
develop server execute module for local test
:copyright: (c) 2014 by geeksaga.
:license: MIT LICENSE 2.0, see license for more details.
"""
from flask import redirect, url_for
from geeksaga.archive import create_app
app = create_app()
from geeksaga.archive.controller import ArchiveAPI
archive_view = ArchiveAPI.ArchiveAPI.as_view('archive_api')
app.add_url_rule('/archive', view_func=archive_view, methods=['GET',])
#app.add_url_rule('/archive', view_func=archive_view, methods=['GET'])
#app.add_url_rule('/archive/<path:page>', view_func=archive_view, methods=['PUT'])
@app.route('/')
def index():
#redirect to the about page
return redirect('/archive')
def register_api(view, endpoint, url, pk='id', pk_type='int'):
view_func = view.as_view(endpoint)
app.add_url_rule(url, defaults={pk: None},
view_func=view_func, methods=['GET',])
app.add_url_rule(url, view_func=view_func, methods=['POST',])
app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func,
methods=['GET', 'PUT', 'DELETE'])
#register_api(UserAPI, 'user_api', '/users/', pk='user_id')
if __name__ == '__main__':
try:
app.run(host='0.0.0.0', port=5000, debug=True)
except KeyboardInterrupt as e:
pass
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
//serviceWorkerRegistration.register();
serviceWorkerRegistration.register();
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
/*
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import register from "./registerServiceWorker";
ReactDOM.render(<App />, document.getElementById("root"));
register(); */
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 19c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" /></g></React.Fragment>
, 'DialpadSharp');
|
describe('Bramble Lynx', function () {
describe("Bramble Lynx's constant ability", function () {
beforeEach(function () {
this.setupTest({
player1: {
house: 'untamed',
inPlay: ['flaxia'],
hand: ['bramble-lynx']
},
player2: {
inPlay: ['troll']
}
});
});
it('should not enter ready since no creature reaped this turn', function () {
this.player1.playCreature(this.brambleLynx);
expect(this.brambleLynx.exhausted).toBe(true);
});
it('should enter play read if a creature reaps', function () {
this.player1.reap(this.flaxia);
this.player1.playCreature(this.brambleLynx);
expect(this.brambleLynx.exhausted).toBe(false);
});
it('should be valid only for one turn', function () {
this.player1.reap(this.flaxia);
this.player1.endTurn();
this.player2.clickPrompt('brobnar');
this.player2.reap(this.troll);
this.player2.endTurn();
this.player1.clickPrompt('untamed');
this.player1.playCreature(this.brambleLynx);
expect(this.brambleLynx.exhausted).toBe(true);
});
});
});
|
module.exports = function (req,res) {
var url = require("url");
var mongoose = require('mongoose');
var moment = require('moment');
var request = require("request");
var historyLength = 10;
var number = 5; // set a default number of search items to be returned
var regex = new RegExp(/([?])([a-z]{6})[=][0-9]+/); // regex that searches for this pattern: '?offset='
// Get the search parameter value (e.g. what you are searching for -example: 'cats') from the url entered
var param = url.parse(req.url).pathname.split("").slice(1).join(''); //returns path e.g api/imagesearch/'searchterm parameter'
param = param.substr(param.lastIndexOf('/') + 1); // strip the path - get only the searchterm from the last '/' onwards
// format param to create a human readable version (for 'recent history'), and a version for the Custom Search Engine
var searchTerm = param.replace('%20',' '); // replace %20 with a space - for use in recording recent search terms
param = param.replace("%20", "+"); // replace spaces with a plus symbol - for use in Google Custom Search Engine
// Check if the request url contains pagination - e.g it contains '?offset=10' (or whatever number);
if (regex.test(url.parse(req.url).search)) { // use node's 'url' module to parse out a search term (starts with a '?') and test using regex for correct pattern
console.log('includes pagination');
// strip out the number from the end of the pagination request
number = url.parse(req.url).search;
number = number.substr(number.lastIndexOf('=') + 1).split('');
var numLength = number.length;
number = number.slice(0,numLength-1).join(''); // remove the '&' character which seems to come along for the ride at the end of the string
}
else {
console.log('no pagination');
}
// CONNECT TO DB, INSERT SEARCH INTO RECENT HISTORY
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var collection = db.collection("history");
collection.find({},{ _id : 0, term: 1, when: 1}).toArray(function (err,docs) {
if (err) console.error('find error');
console.log('Recent History:\n', docs);
// Remove Oldest Record
if (docs.length === historyLength) {
// delete oldest record
}
// add newest record
var date = moment().format('MMMM Do YYYY, h:mm:ss a');
collection.insertOne({term:searchTerm, when:date}, function (err,result) { // callback function will return error or object if successful
if (err) console.error('insert err');
collection.find({},{ _id: 0, term: 1, when: 1}).toArray(function (err,docs) {
if (err) console.error('find error');
console.log("After Insert: \n", docs);
});
});
});
// GOOGLE CUSTOM SEARCH ENGINE. DEVELOPER TOOL. SEE: https://developers.google.com/apis-explorer/#p/customsearch/v1/search.cse.list?q=monkey+mice&cx=005534600515625453000%253Aejzuuniklui&fileType=+bmp%252C+gif%252C+png%252C+jpg&num=5&fields=items(link%252Cpagemap%252Csnippet)&_h=11&
// Google Custom Search Engine API & Custom Search key. The API key is safe for embedding in URLs, it doesn't need any encoding.
var cseid = "AIzaSyBhq-DFox5DCEAkQTBq77bGWphV-8mc5cs"; // API key
var cx = "005534600515625453000:ejzuuniklui"; // Custom Search key
var path = 'https://www.googleapis.com/customsearch/v1?q=' + param + '&cx=' + cx + '&fileType=+bmp%2C+gif%2C+png%2C+jpg&num=' + number + '&fields=items(link%2Cpagemap%2Csnippet)' +'&key=' + cseid;
console.log('path: ',path);
// use the request module to make an http get request to Google's Custom search engine
request( path, function(error, response, body) {
if (error) console.error('error with request');
// MUST parse the JSON that the Google API returns to remove "" from everything and access it via JS
var result = JSON.parse(body);
var arr = [];
var url,snippet,thumbnail,context;
// MAKE SURE that the returned results have the key/value's that you are looking for
for (var i = 0; i < result.items.length; i++) {
if(result.items[i].hasOwnProperty("pagemap")) {
if(result.items[i].pagemap.hasOwnProperty("cse_image")) {url = result.items[i].pagemap.cse_image[0].src;}
else { url = ''}
}
else { url = ''}
if(result.items[i].hasOwnProperty("snippet")) {snippet = result.items[i].snippet;}
else { snippet = ''}
if(result.items[i].hasOwnProperty("pagemap")) {
if(result.items[i].pagemap.hasOwnProperty("cse_thumbnail")) {thumbnail = result.items[i].pagemap.cse_thumbnail[0].src;}
else { thumbnail = ''}
}
else { thumbnail = ''}
if(result.items[i].hasOwnProperty("link")) {context = result.items[i].link;}
else { context = ''}
var obj = {
url: url,
snippet: snippet,
thumbnail: thumbnail,
context: context
};
arr.push(obj);
}
console.log(arr);
res.json(arr); // Express has built in JSON formatting
});
};
|
import styled, { css } from '@xstyled/styled-components'
import React from 'react'
export const FlexContainer = styled.div(
({ align, direction, flex, justify }) => css`
display: flex;
align-items: center;
justify-content: flex-start;
flex: ${flex};
flex-direction: ${direction};
${direction === 'column'} {
align-items: flex-start;
}
${align} {
align-items: ${align};
}
${justify} {
justify-content: ${justify};
}
`
)
export const RowContainer = styled(({ direction, flex, ...rest }) => (
<FlexContainer {...rest} direction="row" />
))
export const StackContainer = styled(({ direction, ...rest }) => (
<FlexContainer {...rest} direction="column" />
))
|
require('toml-require').install();
var options = {
redis: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT
}
};
if (process.env.NODE_ENV === 'development') {
options = require('./config.toml');
}
module.exports = options;
|
module.exports = function(text) {
return text.toLowerCase().replace(/[^\w]+/g, '-');
}
|
import { combineReducers } from "redux";
import { connectRouter } from 'connected-react-router'
//list the imports for the reducers to combine
import {reducer as notifications} from 'react-notification-system-redux'
export default (history) => combineReducers({
router: connectRouter(history),
notifications,
//list here the reducers files to combine
});
|
this.NesDb = this.NesDb || {};
NesDb[ '185189551A395701FDDDB9FBD7F270B48A8FDD50' ] = {
"$": {
"name": "Power Soccer",
"altname": "パワーサッカー",
"class": "Licensed",
"catalog": "GTS-FT",
"publisher": "Tokuma Shoten",
"developer": "",
"region": "Japan",
"players": "2",
"date": "1990-03-30"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "7080D1F8",
"sha1": "185189551A395701FDDDB9FBD7F270B48A8FDD50",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2009-11-01"
},
"board": [
{
"$": {
"type": "HVC-CNROM",
"pcb": "CN-04B",
"mapper": "3"
},
"prg": [
{
"$": {
"size": "32k",
"crc": "9160A87A",
"sha1": "AD13847DCD773EA36A74B3AA6F719B5F8095BFC6"
}
}
],
"chr": [
{
"$": {
"size": "32k",
"crc": "9E4A8716",
"sha1": "A25E4F93B490D412219A0BD5A2E8F1166E87577C"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
}
],
"pad": [
{
"$": {
"h": "0",
"v": "1"
}
}
]
}
]
}
]
};
|
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* TodoStore
*/
var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var TodoConstants = require('../constants/TodoConstants');
var assign = require('object-assign');
var CHANGE_EVENT = 'change';
var _schemi = {
primo: {
id: 123,
complete: false,
text: "blablabla"
},
secondo: {
id: 1234,
complete: false,
text: "Secondo schema"
}
};
var SchemiStore = assign({}, EventEmitter.prototype, {
/**
* Tests whether all the remaining TODO items are marked as completed.
* @return {boolean}
*/
areAllComplete: function() {
for (var id in _schemi) {
if (!_schemi[id].complete) {
return false;
}
}
return true;
},
/**
* Get the entire collection of TODOs.
* @return {object}
*/
getAll: function() {
return _schemi;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
/**
* @param {function} callback
*/
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
/**
* @param {function} callback
*/
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
}
});
// Register callback to handle all updates
AppDispatcher.register(function(action) {
var text;
switch(action.actionType) {
case TodoConstants.TODO_CREATE:
text = action.text.trim();
if (text !== '') {
create(text);
TodoStore.emitChange();
}
break;
case TodoConstants.TODO_TOGGLE_COMPLETE_ALL:
if (TodoStore.areAllComplete()) {
updateAll({complete: false});
} else {
updateAll({complete: true});
}
TodoStore.emitChange();
break;
case TodoConstants.TODO_UNDO_COMPLETE:
update(action.id, {complete: false});
TodoStore.emitChange();
break;
case TodoConstants.TODO_COMPLETE:
update(action.id, {complete: true});
TodoStore.emitChange();
break;
case TodoConstants.TODO_UPDATE_TEXT:
text = action.text.trim();
if (text !== '') {
update(action.id, {text: text});
TodoStore.emitChange();
}
break;
case TodoConstants.TODO_DESTROY:
destroy(action.id);
TodoStore.emitChange();
break;
case TodoConstants.TODO_DESTROY_COMPLETED:
destroyCompleted();
TodoStore.emitChange();
break;
default:
// no op
}
});
module.exports = SchemiStore;
|
"""Generates a JSON schema to handle Reaction protos.
See:
* https://json-schema.org/
* https://json-schema.org/understanding-json-schema/index.html
Inspired by https://github.com/GoogleCloudPlatform/protoc-gen-bq-schema.
"""
import json
from absl import app
from absl import flags
from ord_schema.proto import reaction_pb2
FLAGS = flags.FLAGS
flags.DEFINE_string('output', None, 'Output filename (*.json).')
def get_schema(message_descriptor):
"""Builds the JSON schema for a Message.
Args:
message_descriptor: google.protobuf.descriptor.Descriptor.
Returns:
Dict of dicts; a JSON schema.
Raises:
NotImplementedError: If a FieldDescriptor type is not supported.
"""
schema = {
# NOTE(kearnes): Setting additionalProperties to False here ensures
# that only the listed properties are allowed. See
# https://json-schema.org/understanding-json-schema/reference/object.html#properties.
'additionalProperties': False,
'type': 'object',
'properties': {},
'title': message_descriptor.name,
}
for field in message_descriptor.fields:
field_properties = {}
if field.type == field.TYPE_BOOL:
field_properties.update({'type': 'boolean'})
elif field.type == field.TYPE_FLOAT:
field_properties.update({'type': 'number'})
elif field.type in [field.TYPE_INT32, field.TYPE_INT64]:
# NOTE(kearnes): We avoid 'integer' since its implementation differs
# between validators; see
# https://json-schema.org/understanding-json-schema/reference/numeric.html#integer.
field_properties.update({'type': 'number', 'multipleOf': 1.0})
elif field.type in [field.TYPE_STRING, field.TYPE_BYTES]:
field_properties.update({'type': 'string'})
elif field.type == field.TYPE_ENUM:
enum_descriptor = field.enum_type
enum_names = enum_descriptor.values_by_name.keys()
field_properties.update({'type': 'string', 'enum': enum_names})
elif field.type == field.TYPE_MESSAGE:
field_properties.update(get_schema(field.message_type))
else:
raise NotImplementedError(f'unsupported type: {field.type}')
if field.label == field.LABEL_REPEATED:
schema['properties'][field.name] = {
'type': 'array',
'items': field_properties,
}
else:
schema['properties'][field.name] = field_properties
return schema
def main(argv):
del argv # Only used by app.run().
schema = get_schema(reaction_pb2.Reaction.DESCRIPTOR)
with open(FLAGS.output, 'w') as f:
json.dump(schema, f, indent=2)
if __name__ == '__main__':
flags.mark_flag_as_required('output')
app.run(main)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("@styled-icons/material/Portrait"), exports);
|
/*
* Copyright (c) 2015-2016 PointSource, LLC.
* MIT Licensed
*/
//uses async init to set initialized to true
var initialized = false;
exports.init = function(service15) {
initialized = true;
};
exports.isInitialized = function() {
return initialized;
};
|
import request from '@/utils/request'
export function fetchList(query) {
return request({
url: '/article/list',
method: 'get',
params: query
})
}
export function fetchArticle(id) {
return request({
url: '/article/detail',
method: 'get',
params: { id }
})
}
export function createArticle(data) {
return request({
url: '/article/create',
method: 'post',
data
})
}
export function updateArticle(data) {
return request({
url: '/article/update',
method: 'post',
data
})
}
export function deleteArticle(data) {
return request({
url: '/article/delete',
method: 'post',
data
})
}
|
import aiotools
import asyncio
async def mytick(interval):
print('tick')
async def run():
t = aiotools.create_timer(mytick, 1.0)
await asyncio.sleep(4)
t.cancel()
await t
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(run())
finally:
loop.stop()
|
import withBreakpointManager from './withBreakpointManager.js';
import withBreakpointObserver from './withBreakpointObserver.js';
import withExtraConfig from './withExtraConfig.js';
import withIntersectionObserver from './withIntersectionObserver.js';
import withMountWhenInView from './withMountWhenInView.js';
export {
withBreakpointManager,
withBreakpointObserver,
withExtraConfig,
withIntersectionObserver,
withMountWhenInView,
};
|
// Sign up form handler
async function signupFormHandler(event) {
console.log("Hello!");
event.preventDefault();
// get the information from the sign up form
const name = document.querySelector('#username-signup').value.trim();
const email = document.querySelector('#email-signup').value.trim();
const password = document.querySelector('#password-signup').value.trim();
// if all three fields have content
if (name && email && password) {
// POST the new user to the user table in the database
const response = await fetch('/api/user', {
method: 'post',
body: JSON.stringify({
name,
email,
password
}),
headers: {'Content-Type': 'application/json'}
});
// when the fetch promise is fufilled, check the response status and convey the results
if (response.ok) {
alert('Account created! Logging you in now.');
document.location.replace('/dashboard');
} else {
alert(response.statusText)
}
}
}
document.querySelector('.signup-form').addEventListener('submit', signupFormHandler);
|
import Ember from 'ember';
import DS from 'ember-data';
var locale = new Globalize( navigator.language );
export default DS.Model.extend( {
account_id: DS.attr(),
company_id: DS.attr(),
amount: DS.attr( 'number' ),
currency_id: DS.attr(),
type: DS.attr( 'number' ),
status: DS.attr( 'number' ),
start_date: DS.attr( 'date' ),
title: DS.attr(),
notes: DS.attr(),
frequency: DS.attr( 'number' ),
frequency_type: DS.attr(),
next_payment_date: DS.attr( 'date' ),
fee_counter: DS.attr( 'number' ),
created_at: DS.attr(),
updated_at: DS.attr(),
currency: DS.belongsTo( 'currency', { async: true } ),
account: DS.belongsTo( 'account', { async: true } ),
canCancel: function(){
return this.get( 'status' ) !== 2;
}.property( 'status' ),
str_created_at_date: function(){
return moment( this.get( 'created_at' ) ).utc().format( 'MM/DD/YYYY' );
}.property( 'created_at' ),
str_next_payment_date: function(){
return moment( this.get( 'next_payment_date' ) ).utc().format( 'MM/DD/YYYY' );
}.property( 'created_at' ),
str_start_date: function(){
return moment( this.get( 'start_date' ) ).utc().format( 'MM/DD/YYYY' );
}.property( 'created_at' ),
str_amount: function(){
return locale.format( Number( this.get( 'amount' ) ), 'n2' );
}.property( 'amount' ),
str_fee_counter: function(){
return locale.format( Number( this.get( 'fee_counter' ) ), 'n2' );
}.property( 'fee_counter' ),
isOneTime: function(){
return ( this.get( 'type' ) === 0 );
}.property( 'type' )
} );
|
import numpy
import six
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
def _check_indices(indices):
if len(indices) == 0:
return
# TODO(unno): Check indices without cpu
indices = cuda.to_cpu(indices)
for i in indices:
if 0 <= i < len(indices):
continue
raise ValueError('Out of bounds index: {}'.format(i))
sort = numpy.sort(indices)
for s, t in six.moves.zip(sort, sort[1:]):
if s == t:
raise ValueError('indices contains duplicate value: {}'.format(s))
def _inverse_indices(indices):
xp = backend.get_array_module(indices)
r = xp.empty_like(indices)
if xp is numpy:
r[indices] = numpy.arange(len(indices))
else:
cuda.elementwise(
'S ind', 'raw S r',
'r[ind] = i',
'inverse_indices'
)(indices, r)
return r
class Permutate(function_node.FunctionNode):
"""Permutate function."""
def __init__(self, indices, axis, inv):
self.indices = indices
self.axis = axis
self.inv = inv
def check_type_forward(self, in_types):
type_check.argname(in_types, ('x',))
x_type, = in_types
if self.axis < 0:
type_check.expect(x_type.ndim >= -self.axis)
else:
type_check.expect(x_type.ndim > self.axis)
def _permutate(self, x, indices, inv):
if inv:
indices = _inverse_indices(indices)
return x[((slice(None),) * self.axis) + (indices,)]
def forward(self, inputs):
x, = inputs
inds = self.indices
if chainer.is_debug():
_check_indices(inds)
return self._permutate(x, inds, self.inv),
def backward(self, indexes, grad_outputs):
g, = grad_outputs
inds = self.indices
gx, = Permutate(inds, self.axis, not self.inv).apply((g,))
return gx,
def permutate(x, indices, axis=0, inv=False):
"""Permutates a given variable along an axis.
This function permutate ``x`` with given ``indices``.
That means ``y[i] = x[indices[i]]`` for all ``i``.
Note that this result is same as ``y = x.take(indices)``.
``indices`` must be a permutation of ``[0, 1, ..., len(x) - 1]``.
When ``inv`` is ``True``, ``indices`` is treated as its inverse.
That means ``y[indices[i]] = x[i]``.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Variable to permutate.
A :math:`(s_1, s_2, ..., s_N)` -shaped float array.
indices (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Indices to extract from the variable. A one-dimensional int array.
axis (int): Axis that the input array is permutate along.
inv (bool): If ``True``, ``indices`` is treated as its inverse.
Returns:
~chainer.Variable: Output variable.
.. admonition:: Example
>>> x = np.arange(6).reshape((3, 2)).astype(np.float32)
>>> x
array([[0., 1.],
[2., 3.],
[4., 5.]], dtype=float32)
>>> indices = np.array([2, 0, 1], np.int32)
>>> y = F.permutate(x, indices)
>>> y.data
array([[4., 5.],
[0., 1.],
[2., 3.]], dtype=float32)
>>> y = F.permutate(x, indices, inv=True)
>>> y.data
array([[2., 3.],
[4., 5.],
[0., 1.]], dtype=float32)
>>> indices = np.array([1, 0], np.int32)
>>> y = F.permutate(x, indices, axis=1)
>>> y.data
array([[1., 0.],
[3., 2.],
[5., 4.]], dtype=float32)
"""
if indices.dtype.kind != 'i' or indices.ndim != 1:
raise ValueError(
'indices should be a one-dimensional int array')
if isinstance(indices, chainer.Variable):
indices = indices.array
y, = Permutate(indices, axis, inv).apply((x,))
return y
|
console.log('Here I am');
console.log('It works');
for(let i=1;i<=5;i++) {
document.write('hello<br/>');
}
|
console.log('Cheers!');
|
$('#login-button').click(function (event) {
var userName=document.getElementById("userName").value;
var pwd=document.getElementById("pwd").value;
if(userName=="唐小月" && pwd=="0810"){
event.preventDefault();
$('form').fadeOut(500);
$('.wrapper').addClass('form-success');
requestFullScreen();
setTimeout(function(){location.href="index1.html";},2000);
//auto_link_html("index1.html");
}
else{
alert("密码是你的生日哦!(密码为4位数)");
}
});
function requestFullScreen(element) {
var element=document.documentElement;
// 判断各种浏览器,找到正确的方法
//alert(element.webkitRequestFullScreen);
var requestMethod = element.requestFullScreen || //W3C
element.webkitRequestFullScreen || //Chrome等
element.mozRequestFullScreen || //FireFox
element.msRequestFullScreen; //IE11
if (requestMethod) {
requestMethod.call(element);
}
else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function changeFrameHeight(){
var ifm= document.getElementById("iframepage");
ifm.height=document.documentElement.clientHeight;
}
window.onresize=function(){
changeFrameHeight();
}
// function auto_link_html(url){
// var ifm = document.getElementById("frame_content");
// ifm.setAttribute("src", url);
// }
|
/**-----------------------------------------------------------------------------------------
* Copyright © 2020 Progress Software Corporation. All rights reserved.
* Licensed under commercial license. See LICENSE.md in the project root for more information
*-------------------------------------------------------------------------------------------*/
import * as tslib_1 from "tslib";
import { Input } from '@angular/core';
import { ComponentMessages } from '@progress/kendo-angular-l10n';
/**
* @hidden
*/
var CalendarMessages = /** @class */ (function (_super) {
tslib_1.__extends(CalendarMessages, _super);
function CalendarMessages() {
return _super !== null && _super.apply(this, arguments) || this;
}
CalendarMessages.propDecorators = {
today: [{ type: Input }]
};
return CalendarMessages;
}(ComponentMessages));
export { CalendarMessages };
|
import Firebase from 'firebase/app'
import { firebaseApp } from './firebase'
import 'firebase/auth'
export const auth = firebaseApp.auth()
const providersConfig = [
{
name: 'facebook',
obj: new Firebase.auth.FacebookAuthProvider(),
scopes: ['email'],
},
{
name: 'github',
obj: new Firebase.auth.GithubAuthProvider(),
scopes: ['user:email'],
},
{
name: 'google',
obj: new Firebase.auth.GoogleAuthProvider(),
scopes: [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
],
},
{
name: 'twitter',
obj: new Firebase.auth.TwitterAuthProvider(),
scopes: [],
},
]
const providersWithScope = {}
providersConfig.forEach((provider) => {
provider.scopes.forEach((scope) => {
provider.obj.addScope(scope)
})
providersWithScope[provider.name] = provider.obj
})
export const providers = providersWithScope
|
import './assets/styles.css';
import Vue from 'vue';
import App from './App.vue';
import VueMeta from 'vue-meta';
import createRouter from './router';
import createStore from './store';
Vue.config.productionTip = false;
Vue.use(VueMeta, {
keyName: 'head',
});
import TestCase from './components/TestCase.vue';
Vue.component('test-case', TestCase);
export default () => {
const router = createRouter();
const store = createStore();
return new Vue({
router,
store,
render: h => h(App),
});
};
|
exports = module.exports;
exports.sendError = function(code, res, next, msg) {
return next({'message': msg, 'status': code});
};
exports.send400 = function(res, next, msg) {
return exports.sendError(400, res, next, msg);
};
exports.coerceDate = function(targetObject) {
var stringRep = JSON.stringify(targetObject);
stringRep = stringRep.replace(/(\d\d\d\d-\d\d-\d\d[Tt]\d\d:\d\d:\d\d)\.\d\d\d[Zz]/g, "$1Z");
return JSON.parse(stringRep);
};
exports.getPort = function () {
return process.env.PORT || 3000;
}
exports.toPascalCase = function(input) {
return '' + input.charAt(0).toUpperCase() + input.slice(1);
}
|
from __future__ import absolute_import
import json
import os
import six
from flask import Flask, redirect, url_for, request, session
from flask_oauth import OAuth
BASE_URL = os.environ.get("BASE_URL", "http://dev.getsentry.net:8000")
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
REDIRECT_URI = "/authorized"
SECRET_KEY = "development key"
DEBUG = True
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()
sentry = oauth.remote_app(
"sentry",
base_url=BASE_URL,
authorize_url="{}/oauth/authorize/".format(BASE_URL),
request_token_url=None,
request_token_params={
"scope": "project:releases event:read org:read org:write",
"response_type": "code",
},
access_token_url="{}/oauth/token/".format(BASE_URL),
access_token_method="POST",
access_token_params={"grant_type": "authorization_code"},
consumer_key=CLIENT_ID,
consumer_secret=CLIENT_SECRET,
)
@app.route("/")
def index():
access_token = session.get("access_token")
if access_token is None:
return ("<h1>Who are you?</h1>" '<p><a href="{}">Login with Sentry</a></p>').format(
url_for("login")
)
from urllib2 import Request, urlopen, URLError
headers = {"Authorization": "Bearer {}".format(access_token)}
req = Request("{}/api/0/organizations/".format(BASE_URL), None, headers)
try:
res = urlopen(req)
except URLError as e:
if e.code == 401:
# Unauthorized - bad token
session.pop("access_token", None)
return redirect(url_for("login"))
return "{}\n{}".format(six.text_type(e), e.read())
return ("<h1>Hi, {}!</h1>" "<pre>{}</pre>").format(
json.loads(session["user"])["email"], json.dumps(json.loads(res.read()), indent=2)
)
@app.route("/login")
def login():
callback = url_for("authorized", _external=True)
return sentry.authorize(callback=callback)
@app.route(REDIRECT_URI)
@sentry.authorized_handler
def authorized(resp):
if "error" in request.args:
return ("<h1>Error</h1>" "<p>{}</p>" '<p><a href="{}">Try again</a></p>').format(
request.args["error"], url_for("login")
)
access_token = resp["access_token"]
session["access_token"] = access_token
session["user"] = json.dumps(resp["user"])
return redirect(url_for("index"))
@sentry.tokengetter
def get_access_token():
return session.get("access_token")
def main():
app.run()
if __name__ == "__main__":
main()
|
'use strict';
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Copyright (c) 2015 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Purpose: include this in your module to avoids adding dependencies on
// micro modules like 'global' and 'is-browser';
/* global process, window, global, document, navigator */
var isBrowser = (typeof process === 'undefined' ? 'undefined' : (0, _typeof3.default)(process)) !== 'object' || String(process) !== '[object process]' || process.browser;
var userAgent = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase() : '';
module.exports = {
window: typeof window !== 'undefined' ? window : global,
global: typeof global !== 'undefined' ? global : window,
document: typeof document !== 'undefined' ? document : {},
isBrowser: isBrowser,
userAgent: userAgent
};
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tam9sbmlyLmpzL3NyYy91dGlscy9nbG9iYWxzLmpzIl0sIm5hbWVzIjpbImlzQnJvd3NlciIsInByb2Nlc3MiLCJTdHJpbmciLCJicm93c2VyIiwidXNlckFnZW50IiwibmF2aWdhdG9yIiwidG9Mb3dlckNhc2UiLCJtb2R1bGUiLCJleHBvcnRzIiwid2luZG93IiwiZ2xvYmFsIiwiZG9jdW1lbnQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBLElBQU1BLFlBQ0osUUFBT0MsT0FBUCx1REFBT0EsT0FBUCxPQUFtQixRQUFuQixJQUNBQyxPQUFPRCxPQUFQLE1BQW9CLGtCQURwQixJQUVBQSxRQUFRRSxPQUhWOztBQUtBLElBQU1DLFlBQVksT0FBT0MsU0FBUCxLQUFxQixXQUFyQixHQUNoQkEsVUFBVUQsU0FBVixDQUFvQkUsV0FBcEIsRUFEZ0IsR0FDb0IsRUFEdEM7O0FBR0FDLE9BQU9DLE9BQVAsR0FBaUI7QUFDZkMsVUFBUSxPQUFPQSxNQUFQLEtBQWtCLFdBQWxCLEdBQWdDQSxNQUFoQyxHQUF5Q0MsTUFEbEM7QUFFZkEsVUFBUSxPQUFPQSxNQUFQLEtBQWtCLFdBQWxCLEdBQWdDQSxNQUFoQyxHQUF5Q0QsTUFGbEM7QUFHZkUsWUFBVSxPQUFPQSxRQUFQLEtBQW9CLFdBQXBCLEdBQWtDQSxRQUFsQyxHQUE2QyxFQUh4QztBQUlmWCxzQkFKZTtBQUtmSTtBQUxlLENBQWpCIiwiZmlsZSI6Imdsb2JhbHMuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBDb3B5cmlnaHQgKGMpIDIwMTcgVWJlciBUZWNobm9sb2dpZXMsIEluYy5cbi8vXG4vLyBQZXJtaXNzaW9uIGlzIGhlcmVieSBncmFudGVkLCBmcmVlIG9mIGNoYXJnZSwgdG8gYW55IHBlcnNvbiBvYnRhaW5pbmcgYSBjb3B5XG4vLyBvZiB0aGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmlsZXMgKHRoZSBcIlNvZnR3YXJlXCIpLCB0byBkZWFsXG4vLyBpbiB0aGUgU29mdHdhcmUgd2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRhdGlvbiB0aGUgcmlnaHRzXG4vLyB0byB1c2UsIGNvcHksIG1vZGlmeSwgbWVyZ2UsIHB1Ymxpc2gsIGRpc3RyaWJ1dGUsIHN1YmxpY2Vuc2UsIGFuZC9vciBzZWxsXG4vLyBjb3BpZXMgb2YgdGhlIFNvZnR3YXJlLCBhbmQgdG8gcGVybWl0IHBlcnNvbnMgdG8gd2hvbSB0aGUgU29mdHdhcmUgaXNcbi8vIGZ1cm5pc2hlZCB0byBkbyBzbywgc3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6XG4vL1xuLy8gVGhlIGFib3ZlIGNvcHlyaWdodCBub3RpY2UgYW5kIHRoaXMgcGVybWlzc2lvbiBub3RpY2Ugc2hhbGwgYmUgaW5jbHVkZWQgaW5cbi8vIGFsbCBjb3BpZXMgb3Igc3Vic3RhbnRpYWwgcG9ydGlvbnMgb2YgdGhlIFNvZnR3YXJlLlxuLy9cbi8vIFRIRSBTT0ZUV0FSRSBJUyBQUk9WSURFRCBcIkFTIElTXCIsIFdJVEhPVVQgV0FSUkFOVFkgT0YgQU5ZIEtJTkQsIEVYUFJFU1MgT1Jcbi8vIElNUExJRUQsIElOQ0xVRElORyBCVVQgTk9UIExJTUlURUQgVE8gVEhFIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZLFxuLy8gRklUTkVTUyBGT1IgQSBQQVJUSUNVTEFSIFBVUlBPU0UgQU5EIE5PTklORlJJTkdFTUVOVC4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFXG4vLyBBVVRIT1JTIE9SIENPUFlSSUdIVCBIT0xERVJTIEJFIExJQUJMRSBGT1IgQU5ZIENMQUlNLCBEQU1BR0VTIE9SIE9USEVSXG4vLyBMSUFCSUxJVFksIFdIRVRIRVIgSU4gQU4gQUNUSU9OIE9GIENPTlRSQUNULCBUT1JUIE9SIE9USEVSV0lTRSwgQVJJU0lORyBGUk9NLFxuLy8gT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgU09GVFdBUkUgT1IgVEhFIFVTRSBPUiBPVEhFUiBERUFMSU5HUyBJTlxuLy8gVEhFIFNPRlRXQVJFLlxuXG4vLyBDb3B5cmlnaHQgKGMpIDIwMTUgLSAyMDE3IFViZXIgVGVjaG5vbG9naWVzLCBJbmMuXG4vL1xuLy8gUGVybWlzc2lvbiBpcyBoZXJlYnkgZ3JhbnRlZCwgZnJlZSBvZiBjaGFyZ2UsIHRvIGFueSBwZXJzb24gb2J0YWluaW5nIGEgY29weVxuLy8gb2YgdGhpcyBzb2Z0d2FyZSBhbmQgYXNzb2NpYXRlZCBkb2N1bWVudGF0aW9uIGZpbGVzICh0aGUgXCJTb2Z0d2FyZVwiKSwgdG8gZGVhbFxuLy8gaW4gdGhlIFNvZnR3YXJlIHdpdGhvdXQgcmVzdHJpY3Rpb24sIGluY2x1ZGluZyB3aXRob3V0IGxpbWl0YXRpb24gdGhlIHJpZ2h0c1xuLy8gdG8gdXNlLCBjb3B5LCBtb2RpZnksIG1lcmdlLCBwdWJsaXNoLCBkaXN0cmlidXRlLCBzdWJsaWNlbnNlLCBhbmQvb3Igc2VsbFxuLy8gY29waWVzIG9mIHRoZSBTb2Z0d2FyZSwgYW5kIHRvIHBlcm1pdCBwZXJzb25zIHRvIHdob20gdGhlIFNvZnR3YXJlIGlzXG4vLyBmdXJuaXNoZWQgdG8gZG8gc28sIHN1YmplY3QgdG8gdGhlIGZvbGxvd2luZyBjb25kaXRpb25zOlxuLy9cbi8vIFRoZSBhYm92ZSBjb3B5cmlnaHQgbm90aWNlIGFuZCB0aGlzIHBlcm1pc3Npb24gbm90aWNlIHNoYWxsIGJlIGluY2x1ZGVkIGluXG4vLyBhbGwgY29waWVzIG9yIHN1YnN0YW50aWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS5cbi8vXG4vLyBUSEUgU09GVFdBUkUgSVMgUFJPVklERUQgXCJBUyBJU1wiLCBXSVRIT1VUIFdBUlJBTlRZIE9GIEFOWSBLSU5ELCBFWFBSRVNTIE9SXG4vLyBJTVBMSUVELCBJTkNMVURJTkcgQlVUIE5PVCBMSU1JVEVEIFRPIFRIRSBXQVJSQU5USUVTIE9GIE1FUkNIQU5UQUJJTElUWSxcbi8vIEZJVE5FU1MgRk9SIEEgUEFSVElDVUxBUiBQVVJQT1NFIEFORCBOT05JTkZSSU5HRU1FTlQuIElOIE5PIEVWRU5UIFNIQUxMIFRIRVxuLy8gQVVUSE9SUyBPUiBDT1BZUklHSFQgSE9MREVSUyBCRSBMSUFCTEUgRk9SIEFOWSBDTEFJTSwgREFNQUdFUyBPUiBPVEhFUlxuLy8gTElBQklMSVRZLCBXSEVUSEVSIElOIEFOIEFDVElPTiBPRiBDT05UUkFDVCwgVE9SVCBPUiBPVEhFUldJU0UsIEFSSVNJTkcgRlJPTSxcbi8vIE9VVCBPRiBPUiBJTiBDT05ORUNUSU9OIFdJVEggVEhFIFNPRlRXQVJFIE9SIFRIRSBVU0UgT1IgT1RIRVIgREVBTElOR1MgSU5cbi8vIFRIRSBTT0ZUV0FSRS5cblxuLy8gUHVycG9zZTogaW5jbHVkZSB0aGlzIGluIHlvdXIgbW9kdWxlIHRvIGF2b2lkcyBhZGRpbmcgZGVwZW5kZW5jaWVzIG9uXG4vLyBtaWNybyBtb2R1bGVzIGxpa2UgJ2dsb2JhbCcgYW5kICdpcy1icm93c2VyJztcblxuLyogZ2xvYmFsIHByb2Nlc3MsIHdpbmRvdywgZ2xvYmFsLCBkb2N1bWVudCwgbmF2aWdhdG9yICovXG5jb25zdCBpc0Jyb3dzZXIgPVxuICB0eXBlb2YgcHJvY2VzcyAhPT0gJ29iamVjdCcgfHxcbiAgU3RyaW5nKHByb2Nlc3MpICE9PSAnW29iamVjdCBwcm9jZXNzXScgfHxcbiAgcHJvY2Vzcy5icm93c2VyO1xuXG5jb25zdCB1c2VyQWdlbnQgPSB0eXBlb2YgbmF2aWdhdG9yICE9PSAndW5kZWZpbmVkJyA/XG4gIG5hdmlnYXRvci51c2VyQWdlbnQudG9Mb3dlckNhc2UoKSA6ICcnO1xuXG5tb2R1bGUuZXhwb3J0cyA9IHtcbiAgd2luZG93OiB0eXBlb2Ygd2luZG93ICE9PSAndW5kZWZpbmVkJyA/IHdpbmRvdyA6IGdsb2JhbCxcbiAgZ2xvYmFsOiB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6IHdpbmRvdyxcbiAgZG9jdW1lbnQ6IHR5cGVvZiBkb2N1bWVudCAhPT0gJ3VuZGVmaW5lZCcgPyBkb2N1bWVudCA6IHt9LFxuICBpc0Jyb3dzZXIsXG4gIHVzZXJBZ2VudFxufTtcbiJdfQ==
|
/**
* Kendo UI v2020.1.114 (http://www.telerik.com/kendo-ui)
* Copyright 2020 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(n){"function"==typeof define&&define.amd?define(["kendo.core.min"],n):n()}(function(){!function(n,y){kendo.cultures["gu-IN"]={name:"gu-IN",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3,2],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3,2],symbol:"%"},currency:{name:"Indian Rupee",abbr:"INR",pattern:["$ -n","$n"],decimals:2,",":",",".":".",groupSize:[3,2],symbol:"₹"}},calendars:{standard:{days:{names:["રવિવાર","સોમવાર","મંગળવાર","બુધવાર","ગુરુવાર","શુક્રવાર","શનિવાર"],namesAbbr:["રવિ","સોમ","મંગળ","બુધ","ગુરુ","શુક્ર","શનિ"],namesShort:["ર","સો","મં","બુ","ગુ","શુ","શ"]},months:{names:["જાન્યુઆરી","ફેબ્રુઆરી","માર્ચ","એપ્રિલ","મે","જૂન","જુલાઈ","ઑગસ્ટ","સપ્ટેમ્બર","ઑક્ટોબર","નવેમ્બર","ડિસેમ્બર"],namesAbbr:["જાન્યુ","ફેબ્રુ","માર્ચ","એપ્રિલ","મે","જૂન","જુલાઈ","ઑગ","સપ્ટે","ઑક્ટો","નવે","ડિસે"]},AM:["પૂર્વ મધ્યાહ્ન","પૂર્વ મધ્યાહ્ન","પૂર્વ મધ્યાહ્ન"],PM:["ઉત્તર મધ્યાહ્ન","ઉત્તર મધ્યાહ્ન","ઉત્તર મધ્યાહ્ન"],patterns:{d:"dd-MM-yy",D:"dd MMMM yyyy",F:"dd MMMM yyyy HH:mm:ss",g:"dd-MM-yy HH:mm",G:"dd-MM-yy HH:mm:ss",m:"dd MMMM",M:"dd MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH:mm",T:"HH:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM, yyyy",Y:"MMMM, yyyy"},"/":"-",":":":",firstDay:1}}}}(this)});
//# sourceMappingURL=kendo.culture.gu-IN.min.js.map
|
# coding=utf-8
from OTLMOW.PostenMapping.StandaardPost import StandaardPost
from OTLMOW.PostenMapping.StandaardPostMapping import StandaardPostMapping
# Generated with PostenCreator. To modify: extend, do not edit
class Post050404312(StandaardPost):
def __init__(self):
super().__init__(
nummer='0504.04312',
beschrijving='Steenslagfundering met continue korrelverdeling met toevoegsel, type IB volgens 5-4.4, dikte 12 cm',
meetstaateenheid='M2',
mappings=[StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#Onderbouw',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#Onderbouw.type',
dotnotatie='type',
defaultWaarde='met-toevoegsel-behandelde-steenslag-met-continue-korrelverdeling---type-IB',
range='',
usagenote='',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0504.04312')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#Onderbouw',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.laagRol',
dotnotatie='laagRol',
defaultWaarde='fundering',
range='',
usagenote='',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0504.04312')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#Onderbouw',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#LaagDikte.dikte',
dotnotatie='dikte',
defaultWaarde='12',
range='',
usagenote='cm^^cdt:ucumunit',
isMeetstaatAttr=0,
isAltijdInTeVullen=0,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0504.04312')
, StandaardPostMapping(
typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#Onderbouw',
attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.oppervlakte',
dotnotatie='oppervlakte',
defaultWaarde='',
range='',
usagenote='m2^^cdt:ucumunit',
isMeetstaatAttr=1,
isAltijdInTeVullen=1,
isBasisMapping=1,
mappingStatus='gemapt 2.0',
mappingOpmerking='',
standaardpostnummer='0504.04312')])
|