text
stringlengths 3
1.05M
|
|---|
"use strict";
(function() {
console.saver = (function() {
var logs = [];
window.addEventListener('load', function getLogs() {
var storedLogs = sessionStorage.getItem('console-log-saver-logs');
if(storedLogs) {
logs = JSON.parse(storedLogs);
}
});
window.addEventListener('unload', function saveLogs() {
try {
sessionStorage.setItem('console-log-saver-logs', JSON.stringify(logs));
} catch(err) {
if(err.code === 22) {
var arrayLength = logs.length;
logs = logs.splice(~~(arrayLength/2), arrayLength);
saveLogs();
}
}
});
return {
add: function(type, log) {
logs.push(type + "\t" + log);
},
save: function(filename) {
var blob = new Blob([logs.join('\r\n')], {type: 'text/json'});
var a = document.createElement('a');
a.download = filename || "console-logs.txt";
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
var e = new MouseEvent('click');
a.dispatchEvent(e);
}
}
})();
var logTypes = ['log', 'info', 'warn', 'error', 'debug'];
var logFn;
function extendLogging(logType) {
logFn = console[logType];
console[logType] = function(msg) {
console.saver.add(logType, msg);
logFn.apply(console, arguments);
};
}
for(var i = 0 ; i < logTypes.length ; i++) {
extendLogging(logTypes[i]);
}
})();
|
import React, { useState } from "react";
import { Link, Redirect } from "react-router-dom";
import { Helmet } from "react-helmet";
import { connect } from "react-redux";
import PropTypes from "prop-types";
// actions components
import { signup } from "../actions/auth"
import { setAlert } from "../actions/alert";
const SignUp = ({ setState, signup, isAuthenticated }) => {
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
password2: "",
});
const { name, email, password, password2 } = formData;
// making changes to the state
const onChange = e =>
setFormData({
...formData,
[e.target.name]: e.target.value
})
// call login action with values from state
const onSubmit = e => {
e.preventDefault();
// perform checks before passing to backend
if (password !== password2 ){
setAlert("Passwords do not match", "error")
}
else
signup({name, email, password, password2});
}
if (isAuthenticated) // no need for brackets for one line
return <Redirect to="/" />
return (
<div className="auth">
<Helmet>
<title>RealState - Sign Up</title>
<meta name="description" content="sign up page" />
</Helmet>
<h1 className="auth__title">Sign Up</h1>
<p className="auth__lead">Create your Account</p>
{/* onSubmit to call the onSubmit func stated above */}
<form onSubmit={(e) => onSubmit(e)}>
<div className="auth__form__group">
<input
className="auth__form__input"
type="text"
name="name"
placeholder="Name"
value={name}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className="auth__form__group">
<input
className="auth__form__input"
type="email"
name="email"
placeholder="email"
value={email}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className="auth__form__group">
<input
className="auth__form__input"
type="password"
name="password"
placeholder="Password"
value={password}
onChange={(e) => onChange(e)}
minLength='6'
/>
</div>
<div className="auth__form__group">
<input
className="auth__form__input"
type="password"
name="password2"
placeholder="Confirm Password"
value={password2}
onChange={(e) => onChange(e)}
minLength='6'
/>
</div>
<button className="auth__form__button">Register</button>
</form>
<p className="auth__authtest">
Already have an account? <Link className="auth__authtext__link" to="/login">Login</Link>
</p>
</div>
);
};
SignUp.propTypes = {
signup: PropTypes.func.isRequired,
setAlert: PropTypes.func,
isAuthenticated: PropTypes.bool,
};
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps, {signup})(SignUp)
|
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from '../components/Layout/Layout';
import SEO from "../components/seo";
const getdata = graphql`
{
wpgraphql {
page(id: "cG9zdDo3MzI5") {
title
content
}
}
}
`
const Terms = () => {
const data = useStaticQuery(getdata);
const common = data.wpgraphql.page;
return (
<>
<Layout>
<SEO title="Law-Firm" />
<section className="mainSpacing">
<div className="container">
<div className="row">
<div className="row">
<div className="col-md-12">
<div dangerouslySetInnerHTML={{ __html: common.content }} />
</div>
</div>
</div>
</div>
</section>
</Layout>
</>
)
}
export default Terms
|
module.exports = (sequelize, DataTypes) => {
var AnswerStatistics = sequelize.define('AnswerStatistics', {
Id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement:true
},
ExtremelySatisfied:{
type: DataTypes.INTEGER,
allowNull:false,
defaultValue:0
},
Satisfied:{
type: DataTypes.INTEGER,
allowNull:false,
defaultValue:0
},
Unsatisfied:{
type: DataTypes.INTEGER,
allowNull:false,
defaultValue:0
},
ExtremelyUnsatisfied:{
type: DataTypes.INTEGER,
allowNull:false,
defaultValue:0
},
},{
updatedAt:'UpdatedAt',
createdAt:'CreatedAt'
})
AnswerStatistics.associate = function(models){
models.AnswerStatistics.belongsTo(models.Faculty,{
onDelete: "CASCADE",
foreignKey: {
name: 'FacultyId',
allowNull: false,
}
});
models.AnswerStatistics.belongsTo(models.Question,{
onDelete: "CASCADE",
foreignKey: {
name: 'QuestionId',
allowNull: false,
unique:'class_question'
}
});
models.AnswerStatistics.belongsTo(models.ClassInfo,{
onDelete: "CASCADE",
foreignKey: {
name: 'ClassId',
allowNull: false,
unique:'class_question'
}
});
};
return AnswerStatistics;
}
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mySuperProject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
|
import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
import Img from "gatsby-image";
const VumbleRedditTV = () => {
const data = useStaticQuery(graphql`
query {
imageSource: file(relativePath: { eq: "vumble/vumble-reddittv.png" }) {
childImageSharp {
fluid(maxWidth: 1400) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return <Img fluid={data.imageSource.childImageSharp.fluid} objectFit="cover" />
}
export default VumbleRedditTV;
|
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
class Renderer {
constructor() {
let c1 = document.getElementById('my_canvas_ipmi');
let c2 = document.getElementById('my_canvas_dbus');
let c3 = document.getElementById('my_canvas_boost_asio_handler');
this.canvas1 = c1;
this.canvas2 = c2;
this.canvas3 = c3;
this.width1 = c1.width; this.height1 = c1.height;
this.width2 = c2.width; this.height2 = c2.height;
this.width3 = c3.width; this.height3 = c3.height;
this.ctx1 = this.canvas1.getContext('2d');
this.ctx2 = this.canvas2.getContext('2d');
this.ctx3 = this.canvas3.getContext('2d');
this.frame_count = 0;
this.addBindings();
this.addListeners();
this.update();
this.run();
}
addBindings() {
this.update = this.update.bind(this);
this.run = this.run.bind(this);
}
addListeners() {
window.addEventListener('resize', this.update);
}
update() {
console.log('update, ' + window.innerWidth + ' x ' + window.innerHeight);
if (false) {
this.width1 = window.innerWidth;
this.height1 = window.innerHeight;
this.canvas1.width = this.width1;
this.canvas1.height = this.height1;
}
}
run() {
draw_timeline(this.ctx1);
draw_timeline_dbus(this.ctx2);
draw_timeline_boost_asio_handler(this.ctx3);
window.requestAnimationFrame(this.run);
}
}
g_renderer = new Renderer();
|
from flask import Flask
app = Flask(__name__) ## Creates the WSGI application
# Decorator
@app.route(rule = "/") # rule tells the URL where we will be running the app
def welcome():
return "Welcome to flask environment :)" # these function is seen in the URL web page
@app.route(rule = "/flask") # rule tells the URL where we will be running the app
def Wel():
return "HI :)" # these function is seen in the URL web page
if __name__ == "__main__" :
app.run(debug = True)
|
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Platform,
} from 'react-native';
import {
InfoService
} from '@bibilgi/services';
import style from '@bibilgi/style/main';
export default class FavoritesTab extends Component {
constructor(props) {
super(props);
this.state = {
favorites: []
};
}
componentWillMount() {
var self = this;
InfoService.getFavs().then(res => {
self.setState({
favorites: res
});
});
}
render() {
return (
<View>
{
this.state.favorites.map((x, i) => (
<View
style={style.favListItem}
key={i}>
<Text
style={style.favListText}>{x.title}</Text>
</View>
))
}
</View>
);
}
}
|
import {Tabs} from 'antd';
import React from 'react';
import {AlcazarConfig} from 'torrents/assets/components/AlcazarConfig';
import {AlcazarInstances} from 'torrents/assets/components/AlcazarInstances';
export class AlcazarSettings extends React.Component {
render() {
return <Tabs>
<Tabs.TabPane tab="Config" key="config"><AlcazarConfig/></Tabs.TabPane>
<Tabs.TabPane tab="Instances" key="instances"><AlcazarInstances/></Tabs.TabPane>
</Tabs>;
}
}
|
/**
* @author Yusuf Al Majid <ajidalmajid6@gmail.com>
* @license MIT
* @version 0.0.1
*/
document.addEventListener("DOMContentLoaded", function(){
var detail = document.getElementsByClassName("detailBtn");
for (var i=0; i < detail.length; i++){
detail[i].onclick = function(){
var id = this.getAttribute('data-id');
var url = baseurl + '/polling/getPollingById';
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
document.getElementById("pollDetail").innerHTML = this.responseText;
}
};
var data = {id:id};
xhr.send(JSON.stringify(data));
};
};
var menu = document.querySelector(".menu-icon");
menu.onclick = function(){
var nav = document.querySelector('nav ul');
nav.classList.toggle('showing');
};
});
|
import React from 'react';
import Helmet from 'react-helmet';
import './all.scss';
import Navbar from './Navbar';
import '../helpers/cursor';
import useSiteMetadata from './SiteMetadata';
const TemplateWrapper = ({ children }) => {
const { title, description } = useSiteMetadata();
return (
<div>
<Helmet>
<html lang="en" />
<title>{title}</title>
<meta name="description" content={description} />
<link
rel="apple-touch-icon-precomposed"
sizes="57x57"
href="/img/apple-touch-icon-57x57.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="114x114"
href="/img/apple-touch-icon-114x114.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="72x72"
href="/img/apple-touch-icon-72x72.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="144x144"
href="/img/apple-touch-icon-144x144.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="60x60"
href="/img/apple-touch-icon-60x60.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="120x120"
href="/img/apple-touch-icon-120x120.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="76x76"
href="/img/apple-touch-icon-76x76.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="152x152"
href="/img/apple-touch-icon-152x152.png"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-196x196.png"
sizes="196x196"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-96x96.png"
sizes="96x96"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-32x32.png"
sizes="32x32"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-16x16.png"
sizes="16x16"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-128.png"
sizes="128x128"
/>
<meta name="application-name" content=" " />
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta
name="msapplication-TileImage"
content="mstile-144x144.png"
/>
<meta
name="msapplication-square70x70logo"
content="mstile-70x70.png"
/>
<meta
name="msapplication-square150x150logo"
content="mstile-150x150.png"
/>
<meta
name="msapplication-wide310x150logo"
content="mstile-310x150.png"
/>
<meta
name="msapplication-square310x310logo"
content="mstile-310x310.png"
/>
<meta name="theme-color" content="#fff" />
<meta property="og:type" content="business.business" />
<meta property="og:title" content={title} />
<meta property="og:url" content="/" />
<meta property="og:image" content="/img/og-image.jpg" />
</Helmet>
<Navbar />
<section className="section">
<div className="container">
<div>{children}</div>
</div>
</section>
<div className="border" />
<div className="grid-lines">
<span />
</div>
</div>
);
};
export default TemplateWrapper;
|
(global["webpackJsonp"]=global["webpackJsonp"]||[]).push([["pages/personal/storesCode/bindingSucceeded"],{"211c":function(t,n,o){"use strict";o.r(n);var e=o("d7b7"),i=o("c614");for(var u in i)"default"!==u&&function(t){o.d(n,t,(function(){return i[t]}))}(u);o("88eb");var c,a=o("f0c5"),r=Object(a["a"])(i["default"],e["b"],e["c"],!1,null,null,null,!1,e["a"],c);n["default"]=r.exports},"21df":function(t,n,o){},"2fb2":function(t,n,o){"use strict";(function(t){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var o={data:function(){return{id:null,isShow:!1,maxBottom:0}},methods:{show:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;this.id=t,this.maxBottom=n,this.isShow=!0},close:function(){this.isShow=!1,this.$emit("closeNotice")},suerScan:function(){t.reLaunch({url:"/pages/personal/tankBottomCode/tankBottomCode?store_id=".concat(this.id,"&maxBottom=").concat(this.maxBottom)})}}};n.default=o}).call(this,o("543d")["default"])},"88eb":function(t,n,o){"use strict";var e=o("21df"),i=o.n(e);i.a},c614:function(t,n,o){"use strict";o.r(n);var e=o("2fb2"),i=o.n(e);for(var u in e)"default"!==u&&function(t){o.d(n,t,(function(){return e[t]}))}(u);n["default"]=i.a},d7b7:function(t,n,o){"use strict";var e;o.d(n,"b",(function(){return i})),o.d(n,"c",(function(){return u})),o.d(n,"a",(function(){return e}));var i=function(){var t=this,n=t.$createElement;t._self._c},u=[]}}]);
;(global["webpackJsonp"] = global["webpackJsonp"] || []).push([
'pages/personal/storesCode/bindingSucceeded-create-component',
{
'pages/personal/storesCode/bindingSucceeded-create-component':(function(module, exports, __webpack_require__){
__webpack_require__('543d')['createComponent'](__webpack_require__("211c"))
})
},
[['pages/personal/storesCode/bindingSucceeded-create-component']]
]);
|
import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableFooter from "@material-ui/core/TableFooter";
import TablePagination from "@material-ui/core/TablePagination";
import TableRow from "@material-ui/core/TableRow";
import IconButton from "@material-ui/core/IconButton";
import "./index.css";
import { connect } from "react-redux";
import {
loadRawMaterials,
onBlurEmptying
} from "../../../../../../actions/RawMaterialsAction";
import MaterialsModal from "./MaterialsModal";
import { withRouter } from "react-router-dom";
const actionsStyles = theme => ({
root: {
flexShrink: 0,
color: theme.palette.text.secondary,
marginLeft: theme.spacing.unit * 2.5
}
});
class TablePaginationActions extends React.Component {
handleFirstPageButtonClick = event => {
this.props.onChangePage(event, 0);
};
handleBackButtonClick = event => {
this.props.onChangePage(event, this.props.page - 1);
};
handleNextButtonClick = event => {
this.props.onChangePage(event, this.props.page + 1);
};
handleLastPageButtonClick = event => {
this.props.onChangePage(
event,
Math.max(0, Math.ceil(this.props.count / this.props.rowsPerPage) - 1)
);
};
render() {
const { classes, count, page, rowsPerPage, theme } = this.props;
return (
<div className={classes.root}>
<IconButton
onClick={this.handleFirstPageButtonClick}
disabled={page === 0}
aria-label="First Page"
>
{theme.direction === "rtl" ? (
<i className="zmdi zmdi-skip-next" />
) : (
<i className="zmdi zmdi-skip-previous" />
)}
</IconButton>
<IconButton
onClick={this.handleBackButtonClick}
disabled={page === 0}
aria-label="Previous Page"
>
{theme.direction === "rtl" ? (
<i className="zmdi zmdi-chevron-right" />
) : (
<i className="zmdi zmdi-chevron-left" />
)}
</IconButton>
<IconButton
onClick={this.handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Next Page"
>
{theme.direction === "rtl" ? (
<i className="zmdi zmdi-chevron-left" />
) : (
<i className="zmdi zmdi-chevron-right" />
)}
</IconButton>
<IconButton
onClick={this.handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="Last Page"
>
{theme.direction === "rtl" ? (
<i className="zmdi zmdi-skip-previous" />
) : (
<i className="zmdi zmdi-skip-next" />
)}
</IconButton>
</div>
);
}
}
TablePaginationActions.propTypes = {
classes: PropTypes.object.isRequired,
count: PropTypes.number.isRequired,
onChangePage: PropTypes.func.isRequired,
page: PropTypes.number.isRequired,
rowsPerPage: PropTypes.number.isRequired,
theme: PropTypes.object.isRequired
};
const TablePaginationActionsWrapped = withStyles(actionsStyles, {
withTheme: true
})(TablePaginationActions);
let counter = 0;
const styles = theme => ({
root: {
width: "100%",
marginTop: theme.spacing.unit * 3
},
table: {
minWidth: 500
},
tableWrapper: {
overflowX: "auto"
}
});
class UsersTable extends React.Component {
componentWillMount() {
this.props.loadRawMaterials();
}
handleChangePage = (event, page) => {
this.setState({ page });
};
handleChangeRowsPerPage = event => {
this.setState({ rowsPerPage: event.target.value });
};
constructor(props, context) {
super(props, context);
this.state = {
page: 0,
rowsPerPage: 8
};
}
render() {
const { classes } = this.props;
const { rowsPerPage, page } = this.state;
const data = this.props.materialItemList;
const emptyRows =
rowsPerPage -
Math.min(rowsPerPage, data ? data.length : 0 - page * rowsPerPage);
return (
<div className={classes.tableWrapper}>
<Table className={classes.table}>
<TableBody
onClick={e => {
e.preventDefault();
this.props.onBlurEmptying();
}}
>
{data
? data
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map(n => {
return (
<TableRow key={n._id}>
<TableCell>{n.materialItem}</TableCell>
<TableCell id="iconsColumn" align="right">
<MaterialsModal edit={{ material: n }} />
</TableCell>
<TableCell id="iconsColumn" align="right">
<MaterialsModal delete={{ material: n }} />
</TableCell>
</TableRow>
);
})
: ""}
{emptyRows > 0 && (
<TableRow style={{ height: 48 * emptyRows }}>
<TableCell colSpan={3} />
</TableRow>
)}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
colSpan={3}
count={data ? data.length : 0}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
ActionsComponent={TablePaginationActionsWrapped}
/>
</TableRow>
</TableFooter>
</Table>
</div>
);
}
}
UsersTable.propTypes = {
classes: PropTypes.object.isRequired
};
const mapStateToProps = ({ user, rawMaterials }) => {
const { materialItemList } = rawMaterials;
const { selected, users, _id } = user;
return { selected, users, _id, materialItemList };
};
export default withRouter(
connect(mapStateToProps, {
loadRawMaterials,
onBlurEmptying
})(withStyles(styles)(UsersTable))
);
|
import { useRouter } from 'next/router'
export default function Post(props) {
const router = useRouter()
if (typeof window === 'undefined') {
if (router.query.post?.startsWith('redir')) {
console.log(router)
throw new Error('render should not occur for redirect')
}
}
if (typeof window !== 'undefined' && !window.initialHref) {
window.initialHref = window.location.href
}
if (router.isFallback) return <p>Loading...</p>
return (
<>
<p id="gsp">getStaticProps</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export const getStaticProps = ({ params }) => {
if (params.post.startsWith('redir')) {
let destination = '/404'
if (params.post.includes('dest-external')) {
destination = 'https://example.com'
} else if (params.post.includes('dest-')) {
destination = params.post.split('dest-').pop().replace(/_/g, '/')
}
let permanent = undefined
let statusCode = undefined
if (params.post.includes('statusCode-')) {
permanent = parseInt(
params.post.split('statusCode-').pop().split('-').shift(),
10
)
}
if (params.post.includes('permanent')) {
permanent = true
} else if (!statusCode) {
permanent = false
}
return {
redirect: {
destination,
permanent,
statusCode,
},
}
}
return {
props: {
params,
},
}
}
export const getStaticPaths = () => {
return {
paths: ['first', 'second'].map((post) => ({ params: { post } })),
fallback: true,
}
}
|
import Snackbar from '@material-ui/core/Snackbar';
import Typography from '@material-ui/core/Typography';
import {withStyles} from '@material-ui/core/styles';
import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import * as React from 'react';
import {Fragment} from 'react';
import Dropzone from 'react-dropzone';
import {convertBytesToMbsOrKbs, createFileFromUrl, readFile} from '../helpers';
import PreviewList from './PreviewList';
import SnackbarContentWrapper from './SnackbarContentWrapper';
const styles = {
'@keyframes progress': {
'0%': {
backgroundPosition: '0 0',
},
'100%': {
backgroundPosition: '-70px 0',
},
},
dropZone: {
position: 'relative',
width: '100%',
minHeight: '250px',
backgroundColor: '#F0F0F0',
border: 'dashed',
borderColor: '#C8C8C8',
cursor: 'pointer',
boxSizing: 'border-box',
},
stripes: {
border: 'solid',
backgroundImage: 'repeating-linear-gradient(-45deg, #F0F0F0, #F0F0F0 25px, #C8C8C8 25px, #C8C8C8 50px)',
animation: 'progress 2s linear infinite !important',
backgroundSize: '150% 100%',
},
rejectStripes: {
backgroundImage: 'repeating-linear-gradient(-45deg, #fc8785, #fc8785 25px, #f4231f 25px, #f4231f 50px)',
},
dropzoneTextStyle: {
textAlign: 'center',
},
uploadIconSize: {
width: 51,
height: 51,
color: '#909090',
},
dropzoneParagraph: {
marginBottom: 20,
marginTop: 20,
},
};
const defaultSnackbarAnchorOrigin = {
horizontal: 'left',
vertical: 'bottom',
};
/**
* This components creates a Material-UI Dropzone, with previews and snackbar notifications.
*/
class DropzoneArea extends React.PureComponent {
state = {
fileObjects: [],
openSnackBar: false,
snackbarMessage: '',
snackbarVariant: 'success',
};
componentDidMount() {
this.filesArray(this.props.initialFiles);
}
componentWillUnmount() {
const {clearOnUnmount, onChange} = this.props;
if (clearOnUnmount) {
this.setState({
fileObjects: [],
});
if (onChange) {
onChange([]);
}
}
}
filesArray = async(urls) => {
try {
const fileObjs = await Promise.all(
urls.map(async(url) => {
const file = await createFileFromUrl(url);
const data = await readFile(file);
return {
file,
data,
};
})
);
this.setState((state) => ({
fileObjects: [].concat(
state.fileObjects,
fileObjs
),
}),
() => {
const {onChange} = this.props;
const {fileObjects} = this.state;
if (onChange) {
onChange(fileObjects.map((fileObject) => fileObject.file));
}
});
} catch (err) {
console.log(err);
}
}
handleDropAccepted = async(acceptedFiles, evt) => {
const {filesLimit, getFileAddedMessage, getFileLimitExceedMessage, onDrop} = this.props;
const {fileObjects} = this.state;
if (filesLimit > 1 && fileObjects.length + acceptedFiles.length > filesLimit) {
this.setState({
openSnackBar: true,
snackbarMessage: getFileLimitExceedMessage(filesLimit),
snackbarVariant: 'error',
});
return;
}
// Notify Drop event
if (onDrop) {
onDrop(acceptedFiles, evt);
}
// Retrieve fileObjects data
const fileObjs = await Promise.all(
acceptedFiles.map(async(file) => {
const data = await readFile(file);
return {
file,
data,
};
})
);
// Display message
const message = fileObjs.reduce((msg, fileObj) => msg + getFileAddedMessage(fileObj.file.name), '');
this.setState({
openSnackBar: true,
snackbarMessage: message,
snackbarVariant: 'success',
});
// Update component state
this.setState((state) => {
// Handle a single file
if (filesLimit <= 1) {
return {
fileObjects: [].concat(fileObjs[0]),
};
}
// Handle multiple files
return {
fileObjects: [].concat(
state.fileObjects,
fileObjs
),
};
},
() => {
const {onChange} = this.props;
const {fileObjects} = this.state;
if (onChange) {
onChange(fileObjects.map((fileObject) => fileObject.file));
}
});
}
handleDropRejected = (rejectedFiles, evt) => {
const {acceptedFiles, getDropRejectMessage, maxFileSize, onDropRejected} = this.props;
let message = '';
rejectedFiles.forEach((rejectedFile) => {
message = getDropRejectMessage(rejectedFile, acceptedFiles, maxFileSize);
});
if (onDropRejected) {
onDropRejected(rejectedFiles, evt);
}
this.setState({
openSnackBar: true,
snackbarMessage: message,
snackbarVariant: 'error',
});
}
handleRemove = (fileIndex) => (event) => {
event.stopPropagation();
const {getFileRemovedMessage, onChange, onDelete} = this.props;
const {fileObjects} = this.state;
// Find removed fileObject
const removedFileObj = fileObjects.filter((fileObject, i) => {
return i === fileIndex;
})[0];
// Calculate remaining fileObjects array
const remainingFileObjs = fileObjects.filter((fileObject, i) => {
return i !== fileIndex;
});
this.setState({fileObjects: remainingFileObjs}, () => {
if (onDelete) {
onDelete(removedFileObj.file);
}
if (onChange) {
onChange(this.state.fileObjects.map((fileObject) => fileObject.file));
}
this.setState({
openSnackBar: true,
snackbarMessage: getFileRemovedMessage(removedFileObj.file.name),
snackbarVariant: 'info',
});
});
};
handleCloseSnackbar = () => {
this.setState({
openSnackBar: false,
});
};
render() {
const {
acceptedFiles,
alertSnackbarProps,
classes,
disableRejectionFeedback,
dropzoneClass,
dropzoneParagraphClass,
dropzoneProps,
dropzoneText,
filesLimit,
inputProps,
maxFileSize,
previewChipProps,
previewGridClasses,
previewGridProps,
previewText,
showAlerts,
showFileNames,
showFileNamesInPreview,
showPreviews,
showPreviewsInDropzone,
useChipsForPreview,
} = this.props;
const {fileObjects, openSnackBar, snackbarMessage, snackbarVariant} = this.state;
const acceptFiles = acceptedFiles?.join(',');
const isMultiple = filesLimit > 1;
const previewsVisible = showPreviews && fileObjects.length > 0;
const previewsInDropzoneVisible = showPreviewsInDropzone && fileObjects.length > 0;
return (
<Fragment>
<Dropzone
{...dropzoneProps}
accept={acceptFiles}
onDropAccepted={this.handleDropAccepted}
onDropRejected={this.handleDropRejected}
maxSize={maxFileSize}
multiple={isMultiple}
>
{({getRootProps, getInputProps, isDragActive, isDragReject}) => (
<div
{...getRootProps()}
className={clsx(
classes.dropZone,
dropzoneClass,
isDragActive && classes.stripes,
(!disableRejectionFeedback && isDragReject) && classes.rejectStripes,
)}
>
<input {...inputProps} {...getInputProps()} />
<div className={classes.dropzoneTextStyle}>
<Typography
variant="h5"
component="p"
className={clsx(classes.dropzoneParagraph, dropzoneParagraphClass)}
>
{dropzoneText}
</Typography>
<CloudUploadIcon className={classes.uploadIconSize} />
</div>
{previewsInDropzoneVisible &&
<PreviewList
fileObjects={fileObjects}
handleRemove={this.handleRemove}
showFileNames={showFileNames}
useChipsForPreview={useChipsForPreview}
previewChipProps={previewChipProps}
previewGridClasses={previewGridClasses}
previewGridProps={previewGridProps}
/>
}
</div>
)}
</Dropzone>
{previewsVisible &&
<Fragment>
<Typography variant="subtitle1" component="span">
{previewText}
</Typography>
<PreviewList
fileObjects={fileObjects}
handleRemove={this.handleRemove}
showFileNames={showFileNamesInPreview}
useChipsForPreview={useChipsForPreview}
previewChipProps={previewChipProps}
previewGridClasses={previewGridClasses}
previewGridProps={previewGridProps}
/>
</Fragment>
}
{showAlerts &&
<Snackbar
anchorOrigin={defaultSnackbarAnchorOrigin}
autoHideDuration={6000}
{...alertSnackbarProps}
open={openSnackBar}
onClose={this.handleCloseSnackbar}
>
<SnackbarContentWrapper
onClose={this.handleCloseSnackbar}
variant={snackbarVariant}
message={snackbarMessage}
/>
</Snackbar>
}
</Fragment>
);
}
}
DropzoneArea.defaultProps = {
acceptedFiles: ['image/*', 'video/*', 'application/*'],
filesLimit: 3,
maxFileSize: 3000000,
dropzoneText: 'Drag and drop a file here or click',
previewText: 'Preview:',
disableRejectionFeedback: false,
showPreviews: false, // By default previews show up under in the dialog and inside in the standalone
showPreviewsInDropzone: true,
showFileNames: false,
showFileNamesInPreview: false,
useChipsForPreview: false,
previewChipProps: {},
previewGridClasses: {},
previewGridProps: {},
showAlerts: true,
alertSnackbarProps: {
anchorOrigin: {
horizontal: 'left',
vertical: 'bottom',
},
autoHideDuration: 6000,
},
clearOnUnmount: true,
initialFiles: [],
getFileLimitExceedMessage: (filesLimit) => (`Maximum allowed number of files exceeded. Only ${filesLimit} allowed`),
getFileAddedMessage: (fileName) => (`File ${fileName} successfully added.`),
getFileRemovedMessage: (fileName) => (`File ${fileName} removed.`),
getDropRejectMessage: (rejectedFile, acceptedFiles, maxFileSize) => {
let message = `File ${rejectedFile.name} was rejected. `;
if (!acceptedFiles.includes(rejectedFile.type)) {
message += 'File type not supported. ';
}
if (rejectedFile.size > maxFileSize) {
message += 'File is too big. Size limit is ' + convertBytesToMbsOrKbs(maxFileSize) + '. ';
}
return message;
},
};
DropzoneArea.propTypes = {
/** @ignore */
classes: PropTypes.object.isRequired,
/** A list of file types to accept.
* @see See [here](https://react-dropzone.js.org/#section-accepting-specific-file-types) for more details.
*/
acceptedFiles: PropTypes.arrayOf(PropTypes.string),
/** Maximum number of files that can be loaded into the dropzone. */
filesLimit: PropTypes.number,
/** Maximum file size (in bytes) that the dropzone will accept. */
maxFileSize: PropTypes.number,
/** Text inside the dropzone. */
dropzoneText: PropTypes.string,
/** Custom CSS class name for dropzone container. */
dropzoneClass: PropTypes.string,
/** Custom CSS class name for text inside the container. */
dropzoneParagraphClass: PropTypes.string,
/** Disable feedback effect when dropping rejected files. */
disableRejectionFeedback: PropTypes.bool,
/** Shows previews **BELOW** the dropzone. */
showPreviews: PropTypes.bool,
/** Shows preview **INSIDE** the dropzone area. */
showPreviewsInDropzone: PropTypes.bool,
/** Shows file name under the dropzone image. */
showFileNames: PropTypes.bool,
/** Shows file name under the image. */
showFileNamesInPreview: PropTypes.bool,
/** Uses deletable Material-UI Chip components to display file names. */
useChipsForPreview: PropTypes.bool,
/**
* Props to pass to the Material-UI Chip components.<br/>Requires `useChipsForPreview` prop to be `true`.
*
* @see See [Material-UI Chip](https://material-ui.com/api/chip/#props) for available values.
*/
previewChipProps: PropTypes.object,
/**
* Custom CSS classNames for preview Grid components.<br/>
* Should be in the form {container: string, item: string, image: string}.
*/
previewGridClasses: PropTypes.object,
/**
* Props to pass to the Material-UI Grid components.<br/>
* Should be in the form {container: GridProps, item: GridProps}.
*
* @see See [Material-UI Grid](https://material-ui.com/api/grid/#props) for available GridProps values.
*/
previewGridProps: PropTypes.object,
/** The label for the file preview section. */
previewText: PropTypes.string,
/** Shows styled Material-UI Snackbar when files are dropped, deleted or rejected. */
showAlerts: PropTypes.bool,
/**
* Props to pass to the Material-UI Snackbar components.<br/>Requires `showAlerts` prop to be `true`.
*
* @see See [Material-UI Snackbar](https://material-ui.com/api/snackbar/#props) for available values.
*/
alertSnackbarProps: PropTypes.object,
/**
* Props to pass to the Dropzone component.
*
* @see See [Dropzone props](https://react-dropzone.js.org/#src) for available values.
*/
dropzoneProps: PropTypes.object,
/**
* Attributes applied to the input element.
*
* @see See [MDN Input File attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Additional_attributes) for available values.
*/
inputProps: PropTypes.object,
/** Clear uploaded files when component is unmounted. */
clearOnUnmount: PropTypes.bool,
/** List of URLs of already uploaded images.<br/>**Note:** Please take care of CORS. */
initialFiles: PropTypes.arrayOf(PropTypes.string),
/**
* Get alert message to display when files limit is exceed.
*
* *Default*: "Maximum allowed number of files exceeded. Only ${filesLimit} allowed"
*
* @param {number} filesLimit The `filesLimit` currently set for the component.
*/
getFileLimitExceedMessage: PropTypes.func,
/**
* Get alert message to display when a new file is added.
*
* *Default*: "File ${fileName} successfully added."
*
* @param {string} fileName The newly added file name.
*/
getFileAddedMessage: PropTypes.func,
/**
* Get alert message to display when a file is removed.
*
* *Default*: "File ${fileName} removed."
*
* @param {string} fileName The name of the removed file.
*/
getFileRemovedMessage: PropTypes.func,
/**
* Get alert message to display when a file is rejected onDrop.
*
* *Default*: "File ${rejectedFile.name} was rejected."
*
* @param {Object} rejectedFile The file that got rejected
* @param {string[]} acceptedFiles The `acceptedFiles` prop currently set for the component
* @param {number} maxFileSize The `maxFileSize` prop currently set for the component
*/
getDropRejectMessage: PropTypes.func,
/**
* Fired when the files inside dropzone change.
*
* @param {File[]} loadedFiles All the files currently loaded into the dropzone.
*/
onChange: PropTypes.func,
/**
* Fired when the user drops files into the dropzone.
*
* @param {File[]} droppedFiles All the files dropped into the dropzone.
*/
onDrop: PropTypes.func,
/**
* Fired when a file is rejected because of wrong file type, size or goes beyond the filesLimit.
*
* @param {File[]} rejectedFiles All the rejected files.
*/
onDropRejected: PropTypes.func,
/**
* Fired when a file is deleted from the previews panel.
*
* @param {File} deletedFile The file that was removed.
*/
onDelete: PropTypes.func,
};
export default withStyles(styles)(DropzoneArea);
|
import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import './footer.css'
const socialURLs = {
twitter: 'https://twitter.com',
github: 'https://github.com',
facebook: 'https://facebook.com',
medium: 'https://medium.com',
linkedin: 'https://linkedin.com/in',
instagram: 'https://instagram.com',
}
const socialIcons = {
twitter: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M23.954 4.569c-.885.389-1.83.654-2.825.775 1.014-.611 1.794-1.574 2.163-2.723-.951.555-2.005.959-3.127 1.184-.896-.959-2.173-1.559-3.591-1.559-2.717 0-4.92 2.203-4.92 4.917 0 .39.045.765.127 1.124C7.691 8.094 4.066 6.13 1.64 3.161c-.427.722-.666 1.561-.666 2.475 0 1.71.87 3.213 2.188 4.096-.807-.026-1.566-.248-2.228-.616v.061c0 2.385 1.693 4.374 3.946 4.827-.413.111-.849.171-1.296.171-.314 0-.615-.03-.916-.086.631 1.953 2.445 3.377 4.604 3.417-1.68 1.319-3.809 2.105-6.102 2.105-.39 0-.779-.023-1.17-.067 2.189 1.394 4.768 2.209 7.557 2.209 9.054 0 13.999-7.496 13.999-13.986 0-.209 0-.42-.015-.63.961-.689 1.8-1.56 2.46-2.548l-.047-.02z" />
</svg>
),
github: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
</svg>
),
facebook: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M22.676 0H1.324C.593 0 0 .593 0 1.324v21.352C0 23.408.593 24 1.324 24h11.494v-9.294H9.689v-3.621h3.129V8.41c0-3.099 1.894-4.785 4.659-4.785 1.325 0 2.464.097 2.796.141v3.24h-1.921c-1.5 0-1.792.721-1.792 1.771v2.311h3.584l-.465 3.63H16.56V24h6.115c.733 0 1.325-.592 1.325-1.324V1.324C24 .593 23.408 0 22.676 0" />
</svg>
),
medium: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0v24h24V0H0zm19.938 5.686L18.651 6.92a.376.376 0 0 0-.143.362v9.067a.376.376 0 0 0 .143.361l1.257 1.234v.271h-6.322v-.27l1.302-1.265c.128-.128.128-.165.128-.36V8.99l-3.62 9.195h-.49L6.69 8.99v6.163a.85.85 0 0 0 .233.707l1.694 2.054v.271H3.815v-.27L5.51 15.86a.82.82 0 0 0 .218-.707V8.027a.624.624 0 0 0-.203-.527L4.019 5.686v-.27h4.674l3.613 7.923 3.176-7.924h4.456v.271z" />
</svg>
),
linkedin: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
</svg>
),
instagram: (
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z" />
</svg>
),
}
function Footer() {
const { site } = useStaticQuery(
graphql`
query FooterQuery {
site {
siteMetadata {
author
bio
social {
twitter
github
facebook
medium
linkedin
instagram
}
}
}
}
`
)
const { social } = site.siteMetadata
return (
<div className="footer-container">
<ul className="horizontal-links" style={{marginBottom: '1.5rem', position: 'relative', 'zIndex': 10 }}>
{Object.keys(social).map(s =>
social[s] ? (
<li key={s}>
<a
aria-label={`${s} profile`}
className="u-no-box-shadow"
href={`${socialURLs[s]}/${social[s]}`}
>
{socialIcons[s]}
</a>
</li>
) : null
)}
</ul>
<div className="direitos-reservados">
<label>Criado e editado por Thais Ribeiro</label>
<label>Todos os direitos reservados ©2021</label>
</div>
<div className="direitos-reservados-blank" style={{height: '10px'}}></div>
</div>
)
}
export default Footer
|
interact(document).on('DOMContentLoaded', function () {
/* global interact, Modernizr */
/*
* This demo is very broken!
*/
let preTransform = Modernizr.prefixed('transform'),
snapTarget = {};
interact('#gallery .thumbnail')
.draggable({
snap: {
targets: [],
relativePoints: [ { x: 0.5, y: 0.5 } ],
endOnly: true,
},
inertia: true,
onstart: function (event) {
snapTarget = {
x: $('#gallery .stage').width() / 2,
y: $('#gallery .stage').height() / 2,
range: Infinity,
};
const thumb = event.target;
thumb.classList.add('dragging');
thumb.dataset.dragX = 0;
thumb.dataset.dragY = 0;
},
onmove: function (event) {
let thumb = event.target,
x = (thumb.dataset.dragX|0) + event.dx,
y = (thumb.dataset.dragY|0) + event.dy;
thumb.style[preTransform] = 'translate(' + x + 'px,' + y + 'px)';
thumb.dataset.dragX = x;
thumb.dataset.dragY = y;
},
onend: function (event) {
const $thumb = $(event.target);
// if the drag was snapped to the stage
if (event.dropzone) {
$('#gallery .stage img').removeClass('active');
$('#gallery .thumbnail').removeClass('expanded')
.not($thumb).css(preTransform, '');
$thumb.addClass('expanded');
$('#gallery [data-image=' + $thumb.data('for') + ']').addClass('active');
}
else {
$thumb.css(preTransform, '');
}
$thumb.removeClass('dragging');
},
})
.origin($('#gallery')[0]);
interact('#gallery .stage')
.dropzone({
accept: ' #gallery .thumbnail',
overlap: 1,
})
.on('dragenter', function (event) {
event.draggable.draggable({
snap: { targets: [snapTarget] },
});
})
.on('dragleave drop', function (event) {
event.draggable.draggable({
snap: { targets: [] },
});
});
}());
|
const StopBox = () => {
return (
<section id="settings" className="popUp">
<p>are you sure you want to reset timer</p>
<button>yes</button>
<button>no</button>
</section>
);
}
export default StopBox;
|
var searchData=
[
['random_5fexponential',['RANDOM_EXPONENTIAL',['../classdrake_1_1symbolic_1_1_variable.html#a1d1cfd8ffb84e947f82999c682b666a7a06dc64955d502a26fe9dc48935c8344a',1,'drake::symbolic::Variable']]],
['random_5fgaussian',['RANDOM_GAUSSIAN',['../classdrake_1_1symbolic_1_1_variable.html#a1d1cfd8ffb84e947f82999c682b666a7acf82fb3fea5e5deb7b1caccda3d2da16',1,'drake::symbolic::Variable']]],
['random_5funiform',['RANDOM_UNIFORM',['../classdrake_1_1symbolic_1_1_variable.html#a1d1cfd8ffb84e947f82999c682b666a7acb3b2e38fa3bb5365b280e686953c5ad',1,'drake::symbolic::Variable']]],
['relative',['relative',['../namespacedrake.html#a487584d4d770172ae2f665bde7462de2a99c483e1d11b1a279a2a1a3960528487',1,'drake']]]
];
|
import time
import gym
import numpy as np
from jaxrl.wrappers.common import TimeStep
class EpisodeMonitor(gym.ActionWrapper):
"""A class that computes episode returns and lengths."""
def __init__(self, env: gym.Env):
super().__init__(env)
self._reset_stats()
self.total_timesteps = 0
def _reset_stats(self):
self.reward_sum = 0.0
self.episode_length = 0
self.start_time = time.time()
def step(self, action: np.ndarray) -> TimeStep:
observation, reward, done, info = self.env.step(action)
self.reward_sum += reward
self.episode_length += 1
self.total_timesteps += 1
info['total'] = {'timesteps': self.total_timesteps}
if done:
info['episode'] = {}
info['episode']['return'] = self.reward_sum
info['episode']['length'] = self.episode_length
info['episode']['duration'] = time.time() - self.start_time
if hasattr(self, 'get_normalized_score'):
info['episode']['return'] = self.get_normalized_score(
info['episode']['return']) * 100.0
return observation, reward, done, info
def reset(self, **kwargs) -> np.ndarray:
self._reset_stats()
return self.env.reset()
|
const skynet = require('@nebulous/skynet');
const database = require('./store.js');
const encryption = require('./encryption')
const fs = require("fs");
const db = new database()
const pgp = new encryption()
class Upload {
async uploadToSkynet(file) {
const skylink = await skynet.UploadFile(
file,
skynet.DefaultUploadOptions
)
return skylink
}
async uploadFile(filePath, data) {
if (data.encryptionType === 'none') {
try {
const skylink = await this.uploadToSkynet(filePath)
db.add('history', { skylink: skylink, encryption: data.encryptionType, type: 'upload' })
return { skylink: skylink, encryption: data.encryptionType }
} catch (e) {
return 'noneUploadFailed'
}
} else if (data.encryptionType === 'symmetric') {
try {
const encryptedFile = await pgp.symmetricEncryption(filePath, data.password)
const skylink = await this.uploadToSkynet(encryptedFile)
fs.unlinkSync(encryptedFile)
db.add('history', { skylink: skylink, encryption: data.encryptionType, type: 'upload' })
return { skylink: skylink, encryption: data.encryptionType };
} catch (e) {
return 'symmetricUploadFailed'
}
} else if (data.encryptionType === 'asymmetric') {
try {
const encryptedFile = await pgp.asymmetricEncryption(filePath, data.publicAddress)
const skylink = await this.uploadToSkynet(encryptedFile)
fs.unlinkSync(encryptedFile)
db.add('history', { skylink: skylink, encryption: data.encryptionType, type: 'upload' })
return { skylink: skylink, encryption: data.encryptionType }
} catch (e) {
//throw e
return 'asymmetricUploadFailed'
}
}
}
}
module.exports = Upload;
|
$(document).ready(function(){$('[data-toggle="popover-custom-content"]').each(function(e,o){$(this).popover({html:!0,placement:"auto",template:'<div class="popover popover-custom" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',content:function(){var e=$(this).attr("popover-id");return $("#popover-content-"+e).html()}})}),setTimeout(function(){$(".vertical-nav-menu").metisMenu()},100),$(".dropdown-menu").on("click",function(e){var o=$._data(document,"events")||{};o=o.click||[];for(var a=0;a<o.length;a++)o[a].selector&&($(e.target).is(o[a].selector)&&o[a].handler.call(e.target,e),$(e.target).parents(o[a].selector).each(function(){o[a].handler.call(this,e)}));e.stopPropagation()}),$('[data-toggle="popover-custom-bg"]').each(function(e,o){var a=$(this).attr("data-bg-class");$(this).popover({trigger:"focus",placement:"top",template:'<div class="popover popover-bg '+a+'" role="tooltip"><h3 class="popover-header"></h3><div class="popover-body"></div></div>'})}),$(function(){$('[data-toggle="popover"]').popover()}),$('[data-toggle="popover-custom"]').each(function(e,o){$(this).popover({html:!0,container:$(this).parent().find(".rm-max-width"),content:function(){return $(this).next(".rm-max-width").find(".popover-custom-content").html()}})}),$("body").on("click",function(e){$('[rel="popover-focus"]').each(function(){$(this).is(e.target)||0!==$(this).has(e.target).length||0!==$(".popover").has(e.target).length||$(this).popover("hide")})}),$(function(){$('[data-toggle="tooltip"]').tooltip()}),$(function(){$('[data-toggle="tooltip-light"]').tooltip({template:'<div class="tooltip tooltip-light"><div class="tooltip-inner"></div></div>'})}),$(".open-right-drawer").click(function(){$(this).addClass("is-active"),$(".app-drawer-wrapper").addClass("drawer-open"),$(".app-drawer-overlay").removeClass("d-none")}),$(".drawer-nav-btn").click(function(){$(".app-drawer-wrapper").removeClass("drawer-open"),$(".app-drawer-overlay").addClass("d-none"),$(".open-right-drawer").removeClass("is-active")}),$(".app-drawer-overlay").click(function(){$(this).addClass("d-none"),$(".app-drawer-wrapper").removeClass("drawer-open"),$(".open-right-drawer").removeClass("is-active")}),$(".mobile-toggle-sidebar-nav").click(function(){$(this).toggleClass("is-active"),$(".app-container").hasClass("sidebar-mobile-open")?($(".app-container").removeClass("sidebar-mobile-open"),$(".app-sidebar-overlay").addClass("d-none")):($(".app-container").addClass("sidebar-mobile-open"),$(".app-sidebar-overlay").removeClass("d-none"))}),$(".app-sidebar-overlay").click(function(){$(this).addClass("d-none"),$(".mobile-toggle-sidebar-nav").click()}),$(".mobile-toggle-header-nav").click(function(){$(this).toggleClass("active"),$(".app-container").hasClass("header-nav-open")?($(".app-container").removeClass("header-nav-open"),$(".app-header-overlay").addClass("d-none")):($(".app-container").addClass("header-nav-open"),$(".app-header-overlay").removeClass("d-none"))}),$(".app-header-overlay").click(function(){$(this).addClass("d-none"),$(".mobile-toggle-header-nav").click()}),$(".show-menu-btn").on("click",function(){$(".app-inner-layout-page").addClass("app-layout-menu-open")}),$(".close-menu-btn").on("click",function(){$(".app-inner-layout-page").removeClass("app-layout-menu-open")}),$(".mobile-app-menu-btn").click(function(){$(".hamburger",this).toggleClass("is-active"),$(".app-inner-layout").toggleClass("open-mobile-menu")}),$(".mobile-toggle-nav").click(function(){$(this).toggleClass("is-active"),$(".app-container").toggleClass("header-mobile-open")}),$(window).on("resize",function(){$(this).width()>991&&($(".app-container").removeClass("header-mobile-open"),$(".mobile-toggle-nav").removeClass("is-active"))});var e=function(){document.body.clientWidth<1250?$(".app-container").addClass("closed-sidebar-mobile"):$(".app-container").removeClass("closed-sidebar-mobile")};$(window).on("resize",function(){e()}),e()});
|
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {getCart, updateCart, removeItem} from '../store/cart'
import history from '../history'
import {CartItem} from './index'
//#region CARD & TABLE
import Card from '@material-ui/core/Card'
import Table from '@material-ui/core/Table'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import TableCell from '@material-ui/core/TableCell'
import TableBody from '@material-ui/core/TableBody'
import CardContent from '@material-ui/core/CardContent'
import CardHeader from '@material-ui/core/CardHeader'
import Button from '@material-ui/core/Button'
//#endregion
/**
//* COMPONENT
*/
export class CartPage extends Component {
componentDidMount() {
this.props.isLoggedIn
? this.props.getCart(this.props.userId)
: this.props.getCart(0)
}
render() {
const {cart} = this.props
if (cart.loading) return <div>loading...</div>
if (cart.masks.length) {
return (
<div>
<Card>
<CardHeader title="Shopping Cart" subheader="Selected items" />
<CardContent>
<Table>
<TableHead>
<TableRow>
<TableCell>Product</TableCell>
<TableCell align="right">Qty</TableCell>
<TableCell align="right">Price ($)</TableCell>
<TableCell align="right">Remove</TableCell>
</TableRow>
</TableHead>
<TableBody>
{cart.masks.map(mask => (
<CartItem
key={mask.id}
mask={mask}
userId={this.props.userId}
updateCart={this.props.updateCart}
removeItem={this.props.removeItem}
/>
))}
<TableRow>
<TableCell rowSpan={3} colSpan={1} />
<TableCell colSpan={1} align="right">
Total
</TableCell>
<TableCell colSpan={1} align="right">
{cart.subtotal}
</TableCell>
<TableCell colSpan={1} align="right" />
</TableRow>
</TableBody>
</Table>
<Button
variant="contained"
color="secondary"
className="checkout"
onClick={() => history.push('/submit')}
>
Checkout
</Button>
</CardContent>
</Card>
</div>
)
} else {
return <div>Sorry, no items in cart</div>
}
}
}
/**
//* CONTAINER
*/
const mapState = state => {
console.log('Mapping State to Props:', state)
return {
userId: state.user.id,
cart: state.cart,
loading: state.cart.loading,
isLoggedIn: !!state.user.id
}
}
const mapDispatch = dispatch => {
console.log('Mapping dispatch to props')
return {
getCart: userId => dispatch(getCart(userId)),
updateCart: (userId, orderId, maskId, update) => {
dispatch(updateCart(userId, orderId, maskId, update))
},
removeItem: (userId, orderId, maskId) => {
dispatch(removeItem(userId, orderId, maskId))
}
}
}
export default connect(mapState, mapDispatch)(CartPage)
|
import React,{useState,useEffect} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder';
import Store from '../../store/store'
import { Typography } from '@material-ui/core';
const useStyles = makeStyles({
root: {
display:"flex",
//flex:1,
width:28,
//width:props => `${props.radius}px`,
//height:props => `${props.radius}px`,
height:28,
//backgroundColor:props=>`${props.color}`,
//[{ backgroundColor:isFavorite ? '#A88663':'black'}, styles.capsuleButtonContainer,]
// backgroundColor:{
// favorites.find(favorite=>favorite.id === props.item) ? "#A88663":"black"
// },
borderRadius:30,
alignItems:"center",
justifyContent:"center",
borderColor:'#A88663',
borderStyle:'solid',
borderWidth:1
}
})
const NumeroTresButton = (props)=>{
console.log(props)
console.log(props.property)
const classes = useStyles(props);
//classes = {...props, {width:props.width}, {height:props.height}}
//classes.root.width = props.radius
//classes.root.height = props.radius
const store = React.useContext(Store)
console.log(store)
const {
state:{favorites=[]},
//state,
dispatch
} = React.useContext(Store)
//const favorites = state.favorites
//console.log(store.state.favorites)
//console.log(favorites)
//const [favorite, setFavorite] = useState(false)
//const isFavorite = favorites.find(favorite=>favorite.id === props.item)
const [isSelected, setIsSelected]=useState(false)
const handleClick = (event)=>{
console.log('selected Any')
//event.stopPropagation();
event.preventDefault();
setIsSelected(!isSelected)
//check if currently favorite
//isFavorite?console.log('iscurrentlyfavorite'):console.log('is not currently favorite')
//isFavorite? dispatch({type: 'TOGGLE_REMOVE_FAVORITE', payload: props.property}) : dispatch({type: 'TOGGLE_ADD_FAVORITE', payload: props.property})
//const isFavorite = favorites.find(propertyID=>propertyID === props.item)
//isFavorite?console.log('newly added favorite'):console.log('nog longer favorite')
}
return (
<div className = {classes.root }
style={ {
backgroundColor:isSelected ? '#A88663':'white',
color:isSelected ? 'white' : '#A88663'
}}
onClick={handleClick}>
<Typography>3</Typography>
</div>
)
}
const styles = {
Active: {
backgroundColor: 'orange'
},
Inactive: {
backgroundColor: 'grey'
},
}
export default NumeroTresButton
|
function msg()
{
}
|
export default normalizeModelName;
import Ember from 'ember';
/**
All modelNames are dasherized internally. Changing this function may
require changes to other normalization hooks (such as typeForRoot).
@method normalizeModelName
@public
@param {String} modelName
@return {String} if the adapter can generate one, an ID
@for DS
*/
function normalizeModelName(modelName) {
return Ember.String.dasherize(modelName);
}
|
import cv2
import numpy
import imutils
#img read and display
img=cv2.imread("rubesh.jpg")
# draw green text on the image
output = img.copy()
cv2.putText(output, "Rubesh", (180, 250),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 250, 0), 2)
cv2.imshow("Text", output)
cv2.waitKey(0)
|
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, 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.
"""
C7N Integration Bindings for Behave testing.
These step definitions create C7N-like CEL expressions from the source policy YAML and the evaluate
those CEL expressions with a given document.
This builds the global objects expected in an activation
- ``resource`` is a CEL representation of the cloud resource
- ``now`` is the current time
- ``event`` is the activation event, if needed.
When the CEL is evaluated, the C7NContext manager is used to provide a filter instance.
This also uses the :py:class:`celpy.c7nlib.C7N_Interpreted_Runner` class to provide
access to C7N caches to the c7nlib functions.
"""
import json
from ast import literal_eval
from types import SimpleNamespace
from unittest.mock import Mock
from behave import *
from dateutil.parser import parse as parse_date
import celpy
import celpy.c7nlib
import celpy.celtypes
from xlate.c7n_to_cel import C7N_Rewriter
@given(u'policy text')
def step_impl(context):
context.cel['policy'] = context.text
@given(u'celtypes.TimestampType configured with TZ_ALIASES {alias_dict}')
def step_impl(context, alias_dict):
aliases = literal_eval(alias_dict)
context.cel["TZ_ALIASES"] = aliases
@given(u'resource value {value}')
def step_impl(context, value):
resource = json.loads(value)
context.cel['activation']["resource"] = celpy.json_to_cel(resource)
@given(u'now value {timestamp}')
def step_impl(context, timestamp):
context.cel['activation']["now"] = celpy.celtypes.TimestampType(parse_date(timestamp))
@given(u'event value {value}')
def step_impl(context, value):
resource = json.loads(value)
context.cel['activation']["event"] = celpy.json_to_cel(resource)
@given(u'url {url} has text')
def step_impl(context, url):
context.value_from_data[url] = context.text
def build_mock_resources(context):
"""
Examine a number of GIVEN caches to gather all of the data required to build mocks.
If there are values provided in GIVEN steps.
"""
if context.cel.get('get_instance_image'):
timestamp = context.cel['get_instance_image'].get("CreateDate", "2020-01-18T19:20:21Z")
name = context.cel['get_instance_image'].get("Name", "RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2")
instance_image={
"VirtualizationType": "hvm",
"Description": "Provided by Red Hat, Inc.",
"PlatformDetails": "Red Hat Enterprise Linux",
"EnaSupport": True,
"Hypervisor": "xen",
"State": "available",
"SriovNetSupport": "simple",
"ImageId": "ami-1234567890EXAMPLE",
"UsageOperation": "RunInstances:0010",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"SnapshotId": "snap-111222333444aaabb",
"DeleteOnTermination": True,
"VolumeType": "gp2",
"VolumeSize": 10,
"Encrypted": False
}
}
],
"Architecture": "x86_64",
"ImageLocation": "123456789012/RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2",
"RootDeviceType": "ebs",
"OwnerId": "123456789012",
"RootDeviceName": "/dev/sda1",
"CreationDate": timestamp,
"Public": True,
"ImageType": "machine",
"Name": name
}
context.cel['filter'].get_instance_image = Mock(
return_value=instance_image
)
@given(u'C7N.filter has get_instance_image result with {field} of {value}')
def step_impl(context, field, value):
"""
Assmble the values to build the filter's :py:meth:`get_instance_image` response.
This method returns the relevant image descruption.
"""
# Save the values for later mock object assembly.
# There are two variants: CreateDate and Name
context.cel.setdefault('get_instance_image', {})[field] = value
@given(u'C7N.filter has get_metric_statistics result with {statistics}')
def step_impl(context, statistics):
"""
The C7N filter ``get_metric_statistics()`` response.
Two API's are reflected here an old-style one that may work with current C7N
The preferred one after CELFilter is refactored.
"""
# Current API.
context.cel['filter'].manager.session_factory = Mock(
name="mock filter session_factory()",
return_value=Mock(
name="mock filter session_factory instance",
client=Mock(
name="mock filter session_factory().client()",
return_value=Mock(
name="mock filter client instance",
get_metric_statistics=Mock(
name="mock filter client get_metric_statistics()",
return_value=json.loads(statistics)
)
)
)
)
)
# Preferred API.
context.cel['filter'].get_resource_statistics = Mock(
return_value=json.loads(statistics)["Datapoints"]
)
@given(u'C7N.filter manager has get_model result of {model}')
def step_impl(context, model):
context.cel['filter'].manager.get_model = Mock(
name="mock filter.manager.get_model()",
return_value=Mock(
name="mock filter.manager.model",
dimension=model
)
)
@given(u'C7N.filter manager has config with {name} = {value}')
def step_impl(context, name, value):
setattr(context.cel['filter'].manager.config, name, value)
@given(u'C7N.filter has resource type of {resource_type}')
def step_impl(context, resource_type):
context.cel['filter'].manager.resource_type = resource_type
@given(u'C7N.filter has get_related result with {sg_document}')
def step_impl(context, sg_document):
context.cel['filter'].get_related = Mock(
name="mock filter.get_related()",
return_value=json.loads(sg_document),
)
@given(u'C7N.filter has flow_logs result with {flow_logs}')
def step_impl(context, flow_logs):
context.cel['filter'].manager.session_factory = Mock(
name="mock filter session_factory()",
return_value=Mock(
name="mock filter session_factory instance",
client=Mock(
name="mock filter session_factory().client()",
return_value=Mock(
name="mock filter client instance",
describe_flow_logs=Mock(
name="mock filter client describe_flow_logs()",
return_value={"FlowLogs": json.loads(flow_logs)}
)
)
)
)
)
# Preferred API.
context.cel['filter'].get_flow_logs=Mock(
return_value={"FlowLogs": json.loads(flow_logs)}
)
@given(u'C7N.filter has get_credential_report result with {credential_report}')
def step_impl(context, credential_report):
context.cel['filter'].get_credential_report=Mock(
return_value=json.loads(credential_report)
)
@given(u'C7N.filter has get_matching_aliases result with {alias_detail}')
def step_impl(context, alias_detail):
context.cel['filter'].get_matching_aliases=Mock(
return_value=json.loads(alias_detail)
)
def evaluate(context):
"""
This does not use the :py:class:`celpy.c7nlib.C7NContext`.
Instead, it provides the context and filter as arguments to :meth:`evaluate`.
"""
decls = {
"resource": celpy.celtypes.MapType,
"now": celpy.celtypes.TimestampType,
}
decls.update(celpy.c7nlib.DECLARATIONS)
context.cel['env'] = celpy.Environment(
annotations=decls,
runner_class=celpy.c7nlib.C7N_Interpreted_Runner
)
context.cel['ast'] = context.cel['env'].compile(context.cel['source'])
context.cel['prgm'] = context.cel['env'].program(context.cel['ast'], functions=celpy.c7nlib.FUNCTIONS)
build_mock_resources(context)
if "TZ_ALIASES" in context.cel:
celpy.celtypes.TimestampType.TZ_ALIASES.update(context.cel["TZ_ALIASES"])
try:
context.cel['result'] = context.cel['prgm'].evaluate(
context=context.cel['activation'],
filter=context.cel['filter'])
except celpy.CELEvalError as ex:
context.cel['result'] = ex
@when(u'CEL filter is built and evaluated')
def step_impl(context):
context.cel['source'] = C7N_Rewriter.c7n_rewrite(context.cel['policy'])
print(f"\nCEL: {context.cel['source']}\n")
evaluate(context)
@when(u'CEL filter {cel_text} is evaluated')
def step_impl(context, cel_text):
context.cel['source'] = cel_text
evaluate(context)
@then(u'result is {result}')
def step_impl(context, result):
error_message = f"{context.cel['source']} evaluated with {context.cel['activation']} is {context.cel['result']}, expected {result!r}"
if result in ("True", "False"):
expected = result == "True"
assert context.cel['result'] == expected, error_message
elif result == "CELEvalError":
assert isinstance(context.cel['result'], celpy.CELEvalError)
else:
raise Exception(f"Invalid THEN step 'result is {result}'")
@then(u'CEL text is {translation}')
def step_impl(context, translation):
assert context.cel['source'] == translation, f"{context.cel['source']!r} != {translation!r}"
|
'''
This is intended to build the feature matrix X that will be fed into the
classifier pipeline.
'''
import os
import sys
import click
import tables
import numpy as np
import pandas as pd
from ipyparallel import Client
from sklearn.pipeline import Pipeline, FeatureUnion
from feature_extractors import *
from src.data.cleaning_functions import WordTokenize
from src.conf import CHUNKSIZE, INTERIM_HDF_PATH, RAW_DATA_FILES,\
INTERIM_DATA_DIR, Q, FEATURES_DIR
question_types = {
'who': 1,
'whos': 2,
'whose': 3,
'what': 4,
'whats': 5,
'where': 6,
'wheres': 7,
'when': 8,
'whens': 9,
'why': 10,
'which': 11,
'is': 12,
'can': 13,
'could': 14,
'do': 15,
'does': 16,
'did': 17,
'will': 18,
'would': 19,
'should': 20,
'has': 21,
'have': 22,
'was': 23,
'how': 24
}
@click.command()
@click.argument('num_rows', type=click.Path(), default=-1)
def main(num_rows):
num_rows = int(num_rows)
# ---------preprocessing----------
get_questions = ExtractCols(['question1', 'question2'])
# ---------question typing---------
sent_tokenizer = SentTokenize()
question_typer = QuestionTypes(question_types=question_types)
question_type_pipe = Pipeline([('sent_tokenizer', sent_tokenizer),
('question_typer', question_typer)])
# --------distance calculation-------
calc_masi_dist = MasiDistance()
# These have tuning parameters and
# could go through cv...
calc_edit_dist1 = EditDistance()
calc_edit_dist2 = EditDistance(sub_cost=2.0)
calc_edit_dist3 = EditDistance(sub_cost=0.5)
calc_edit_dist4 = EditDistance(transpositions=True)
calc_jacc_dist = JaccardDistance()
dist_fu = FeatureUnion(
[('calc_masi_dist', calc_masi_dist),
('calc_edit_dist1', calc_edit_dist1),
('calc_edit_dist2', calc_edit_dist2),
('calc_edit_dist3', calc_edit_dist3),
('calc_edit_dist4', calc_edit_dist4),
('calc_jacc_dist', calc_jacc_dist)],
n_jobs=1)
word_tokenizer = WordTokenize()
dist_pipe = Pipeline([('word_tokenizer', word_tokenizer),
('dist_fu', dist_fu)])
output_fu = FeatureUnion(
[('dist_pipe', dist_pipe),
('question_type_pipe', question_type_pipe)],
n_jobs=1)
# --------final assembly----------
data_pipe = Pipeline([('get_questions', get_questions),
('output_fu', output_fu)]) # output feature union
pool = Client()
pool[:].map(os.chdir, [FEATURES_DIR]*len(pool))
with pool[:].sync_imports():
pass
pool[:].push({'data_pipe': data_pipe})
n_jobs = len(pool)
left_indices = range(0, CHUNKSIZE, CHUNKSIZE // n_jobs)
right_indices = range(CHUNKSIZE // n_jobs, CHUNKSIZE + 1,
CHUNKSIZE // n_jobs)
for f_name in RAW_DATA_FILES:
h5f = tables.open_file(INTERIM_HDF_PATH, 'r')
n_chunks = h5f.get_node_attr('/' + f_name, 'n_chunks')
h5f.close()
for i in range(n_chunks):
print('chunk', i + 1, '/', n_chunks, end='\r')
sys.stdout.flush()
Di = pd.read_hdf(INTERIM_HDF_PATH,
key='/' + f_name + '/' + f_name + str(i))
q1_i = Di.loc[:, Q[0]].values
q2_i = Di.loc[:, Q[1]].values
try:
q1 = np.concatenate((q1, q1_i))
q2 = np.concatenate((q2, q2_i))
except NameError:
q1 = q1_i
q2 = q2_i
results = [] # Send to workers
# It would be much faster to load chunks of data off disk
# as fast as possible and use some kind of switch on the
# pool to send them chunks when they are ready. As is,
# a huge amount of time (probably most) is spent waiting
# for io. Not to mention time used copying data back
# and forth between the processes.
# Maybe the best approach is for each process to load and
# store it's own results to the database independently,
# similar to what I did for the dwglasso application.
for pi, li, ri in zip(pool, left_indices, right_indices):
if len(Di[li:ri]) > 0:
results.append(pi.apply_async(data_pipe.fit_transform,
Di[li:ri]))
for res in results:
Xi = res.get()
try:
X = np.vstack((X, Xi))
except NameError:
X = Xi
X.dump(INTERIM_DATA_DIR + 'X_dist_' + f_name + '.npy')
del X # Free up memory
nrows = len(q1)
assert nrows == len(q2), 'q1 and q2 not equal length!'
q1 = np.append(q1, q2)
del q2
q1.dump(INTERIM_DATA_DIR + 'q_' + f_name + '.npy')
del q1
return
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Models for storing data from Campaign Disclosure Statements (Form 460).
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from calaccess_processed.managers import ProcessedDataManager
from calaccess_processed.models.base import CalAccessBaseModel
from calaccess_processed.models.filings.campaign import CampaignContributionBase
#
# Summaries
#
class Form460ScheduleASummaryBase(CalAccessBaseModel):
"""
Abstract base model with summary data from Schedule A attachments to Form 460 filings.
Includes totals for itemized versus unitemized contributions.
"""
itemized_contributions = models.FloatField(
verbose_name='itemized contributions',
null=True,
help_text="Amount received this period - contributions of $100 or more. (Include all Schedule A subtotals.)",
)
unitemized_contributions = models.FloatField(
verbose_name='unitemized contributions',
null=True,
help_text="Amount received this period - unitemized contributions of less than $100",
)
total_contributions = models.FloatField(
verbose_name='total contributions',
null=True,
help_text="Total monetary contributions received this period. (Add Lines 1 and 2. Enter here and on summary \
Page, Column A, Line 1.)",
)
class Meta:
"""
Model options.
"""
abstract = True
class Form460ScheduleASummary(Form460ScheduleASummaryBase):
"""
The summary data included with the most recent version a Schedule A attachment to a Form 460 filing.
Includes totals for itemized versus unitemized contributions.
"""
filing = models.ForeignKey(
'Form460Filing',
related_name='schedule_a_summaries',
null=True,
on_delete=models.SET_NULL,
help_text='Foreign key referring to the Form 460 on which the summary was reported',
)
objects = ProcessedDataManager()
class Meta:
"""
Model options.
"""
verbose_name = "Form 460 (Campaign Disclosure) Schedule A summary"
verbose_name_plural = "Form 460 (Campaign Disclosure) Schedule A summaries"
def __str__(self):
return '%s' % (self.filing)
class Form460ScheduleASummaryVersion(Form460ScheduleASummaryBase):
"""
The summary data included with each version of a Schedule A attachment to a Form 460 filing.
Includes totals for itemized versus unitemized contributions.
"""
filing_version = models.ForeignKey(
'Form460FilingVersion',
related_name='schedule_a_summaries',
null=True,
on_delete=models.SET_NULL,
help_text='Foreign key referring to the version of the Form 460 that '
'includes the summary'
)
objects = ProcessedDataManager()
class Meta:
"""
Model options.
"""
verbose_name = "Form 460 (Campaign Disclosure) Schedule A summary version"
def __str__(self):
return '%s-%s' % (
self.filing_version.filing_id,
self.filing_version.amend_id,
)
#
# Items
#
class Form460ScheduleAItemBase(CampaignContributionBase):
"""
Abstract base model for items reported on Schedule A of Form 460 filings.
On Schedule A, campaign filers are required to itemize monetary
contributions received during the period covered by the filing.
"""
amount = models.DecimalField(
verbose_name='amount',
decimal_places=2,
max_digits=14,
help_text="Amount received from the contributor in the period covered "
"by the filing (from RCPT_CD.AMOUNT)"
)
class Meta:
"""
Model options.
"""
abstract = True
@python_2_unicode_compatible
class Form460ScheduleAItem(Form460ScheduleAItemBase):
"""
Monetary contributions received by campaign filers.
These transactions are itemized on Schedule A of the most recent version
of each Form 460 filing. For monetary contributions itemized on any version
of any Form 460 filing, see Form460ScheduleAItemVersion.
Also includes contributions transferred to special election commitees,
which were itemized on Schedule A-1 until around 2001.
Derived from RCPT_CD records where FORM_TYPE is 'A' or 'A-1'.
"""
filing = models.ForeignKey(
'Form460Filing',
related_name='schedule_a_items',
null=True,
on_delete=models.SET_NULL,
help_text='Foreign key referring to the Form 460 on which the monetary'
' contribution was reported (from RCPT_CD.FILING_ID)',
)
objects = ProcessedDataManager()
class Meta:
"""
Model options.
"""
unique_together = ((
'filing',
'line_item',
),)
verbose_name = "Form 460 (Campaign Disclosure) Schedule A item"
def __str__(self):
return '%s-%s' % (self.filing, self.line_item)
@python_2_unicode_compatible
class Form460ScheduleAItemVersion(Form460ScheduleAItemBase):
"""
Every version of each monetary contribution received by a campaign filer.
For monetary contributions itemized on Schedule A of the most recent
version of each Form 460 filing, see Form460ScheduleAItem.
Derived from RCPT_CD records where FORM_TYPE is 'A' or 'A-1'.
"""
filing_version = models.ForeignKey(
'Form460FilingVersion',
related_name='schedule_a_items',
null=True,
on_delete=models.SET_NULL,
help_text='Foreign key referring to the version of the Form 460 that '
'includes the received contribution'
)
objects = ProcessedDataManager()
class Meta:
"""
Model options.
"""
unique_together = ((
'filing_version',
'line_item',
),)
index_together = ((
'filing_version',
'line_item',
),)
verbose_name = "Form 460 (Campaign Disclosure) Schedule A item version"
def __str__(self):
return '%s-%s-%s' % (
self.filing_version.filing_id,
self.filing_version.amend_id,
self.line_item
)
|
"""
Provides a test case for issue 283 - "Inheritance breaks".
The issue is outlined here: https://github.com/neo4j-contrib/neomodel/issues/283
More information about the same issue at:
https://github.com/aanastasiou/neomodelInheritanceTest
The following example uses a recursive relationship for economy, but the
idea remains the same: "Instantiate the correct type of node at the end of
a relationship as specified by the model"
"""
import os
import neomodel
import datetime
import pytest
import random
try:
basestring
except NameError:
basestring = str
# Set up a very simple model for the tests
class PersonalRelationship(neomodel.StructuredRel):
"""
A very simple relationship between two basePersons that simply records
the date at which an acquaintance was established.
This relationship should be carried over to anything that inherits from
basePerson without any further effort.
"""
on_date = neomodel.DateProperty(default_now = True)
class BasePerson(neomodel.StructuredNode):
"""
Base class for defining some basic sort of an actor.
"""
name = neomodel.StringProperty(required = True, unique_index = True)
friends_with = neomodel.RelationshipTo("BasePerson", "FRIENDS_WITH",
model = PersonalRelationship)
class TechnicalPerson(BasePerson):
"""
A Technical person specialises BasePerson by adding their expertise.
"""
expertise = neomodel.StringProperty(required = True)
class PilotPerson(BasePerson):
"""
A pilot person specialises BasePerson by adding the type of airplane they
can operate.
"""
airplane = neomodel.StringProperty(required = True)
class BaseOtherPerson(neomodel.StructuredNode):
"""
An obviously "wrong" class of actor to befriend BasePersons with.
"""
car_color = neomodel.StringProperty(required = True)
class SomePerson(BaseOtherPerson):
"""
Concrete class that simply derives from BaseOtherPerson.
"""
pass
# Test cases
def test_automatic_object_resolution():
"""
Node objects at the end of relationships are instantiated to their
corresponding Python object.
"""
# Create a few entities
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
B = TechnicalPerson.get_or_create({"name":"Happy", "expertise":"Unicorns"})[0]
C = TechnicalPerson.get_or_create({"name":"Sleepy", "expertise":"Pillows"})[0]
# Add connections
A.friends_with.connect(B)
B.friends_with.connect(C)
C.friends_with.connect(A)
# If A is friends with B, then A's friends_with objects should be
# TechnicalPerson (!NOT basePerson!)
assert type(A.friends_with[0]) is TechnicalPerson
A.delete()
B.delete()
C.delete()
def test_recursive_automatic_object_resolution():
"""
Node objects are instantiated to native Python objects, both at the top
level of returned results and in the case where they are returned within
lists.
"""
# Create a few entities
A = TechnicalPerson.get_or_create({"name":"Grumpier", "expertise":"Grumpiness"})[0]
B = TechnicalPerson.get_or_create({"name":"Happier", "expertise":"Grumpiness"})[0]
C = TechnicalPerson.get_or_create({"name":"Sleepier", "expertise":"Pillows"})[0]
D = TechnicalPerson.get_or_create({"name":"Sneezier", "expertise":"Pillows"})[0]
# Retrieve mixed results, both at the top level and nested
L, _ = neomodel.db.cypher_query("MATCH (a:TechnicalPerson) "
"WHERE a.expertise='Grumpiness' "
"WITH collect(a) as Alpha "
"MATCH (b:TechnicalPerson) "
"WHERE b.expertise='Pillows' "
"WITH Alpha, collect(b) as Beta "
"RETURN [Alpha, [Beta, [Beta, ['Banana', "
"Alpha]]]]", resolve_objects = True)
# Assert that a Node returned deep in a nested list structure is of the
# correct type
assert type(L[0][0][0][1][0][0][0][0]) is TechnicalPerson
# Assert that primitive data types remain primitive data types
assert issubclass(type(L[0][0][0][1][0][1][0][1][0][0]), basestring)
A.delete()
B.delete()
C.delete()
D.delete()
def test_validation_with_inheritance_from_db():
"""
Objects descending from the specified class of a relationship's end-node are
also perfectly valid to appear as end-node values too
"""
#Create a few entities
# Technical Persons
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
B = TechnicalPerson.get_or_create({"name":"Happy", "expertise":"Unicorns"})[0]
C = TechnicalPerson.get_or_create({"name":"Sleepy", "expertise":"Pillows"})[0]
# Pilot Persons
D = PilotPerson.get_or_create({"name":"Porco Rosso", "airplane":"Savoia-Marchetti"})[0]
E = PilotPerson.get_or_create({"name":"Jack Dalton", "airplane":"Beechcraft Model 18"})[0]
# TechnicalPersons can befriend PilotPersons and vice-versa and that's fine
# TechnicalPersons befriend Technical Persons
A.friends_with.connect(B)
B.friends_with.connect(C)
C.friends_with.connect(A)
# Pilot Persons befriend Pilot Persons
D.friends_with.connect(E)
# Technical Persons befriend Pilot Persons
A.friends_with.connect(D)
E.friends_with.connect(C)
# This now means that friends_with of a TechnicalPerson can
# either be TechnicalPerson or Pilot Person (!NOT basePerson!)
assert (type(A.friends_with[0]) is TechnicalPerson) or (type(A.friends_with[0]) is PilotPerson)
assert (type(A.friends_with[1]) is TechnicalPerson) or (type(A.friends_with[1]) is PilotPerson)
assert type(D.friends_with[0]) is PilotPerson
A.delete()
B.delete()
C.delete()
D.delete()
E.delete()
def test_validation_enforcement_to_db():
"""
If a connection between wrong types is attempted, raise an exception
"""
#Create a few entities
# Technical Persons
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
B = TechnicalPerson.get_or_create({"name":"Happy", "expertise":"Unicorns"})[0]
C = TechnicalPerson.get_or_create({"name":"Sleepy", "expertise":"Pillows"})[0]
# Pilot Persons
D = PilotPerson.get_or_create({"name":"Porco Rosso", "airplane":"Savoia-Marchetti"})[0]
E = PilotPerson.get_or_create({"name":"Jack Dalton", "airplane":"Beechcraft Model 18"})[0]
#Some Person
F = SomePerson(car_color = "Blue").save()
# TechnicalPersons can befriend PilotPersons and vice-versa and that's fine
A.friends_with.connect(B)
B.friends_with.connect(C)
C.friends_with.connect(A)
D.friends_with.connect(E)
A.friends_with.connect(D)
E.friends_with.connect(C)
# Trying to befriend a Technical Person with Some Person should raise an
# exception
with pytest.raises(ValueError):
A.friends_with.connect(F)
A.delete()
B.delete()
C.delete()
D.delete()
E.delete()
F.delete()
def test_failed_object_resolution():
"""
A Neo4j driver node FROM the database contains labels that are unaware to
neomodel's Database class. This condition raises ClassDefinitionNotFound
exception.
"""
class RandomPerson(BasePerson):
randomness = neomodel.FloatProperty(default = random.random)
# A Technical Person...
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
# A Random Person...
B = RandomPerson.get_or_create({"name":"Mad Hatter"})[0]
A.friends_with.connect(B)
# Simulate the condition where the definition of class RandomPerson is not
# known yet.
del neomodel.db._NODE_CLASS_REGISTRY[frozenset(["RandomPerson","BasePerson"])]
# Now try to instantiate a RandomPerson
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
with pytest.raises(neomodel.exceptions.ModelDefinitionMismatch):
for some_friend in A.friends_with:
print(some_friend.name)
A.delete()
B.delete()
def test_node_label_mismatch():
"""
A Neo4j driver node FROM the database contains a superset of the known
labels.
"""
class SuperTechnicalPerson(TechnicalPerson):
superness = neomodel.FloatProperty(default=1.0)
class UltraTechnicalPerson(SuperTechnicalPerson):
ultraness = neomodel.FloatProperty(default=3.1415928)
# Create a TechnicalPerson...
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
# ...that is connected to an UltraTechnicalPerson
F = UltraTechnicalPerson(name = "Chewbaka", expertise="Aarrr wgh ggwaaah").save()
A.friends_with.connect(F)
# Forget about the UltraTechnicalPerson
del neomodel.db._NODE_CLASS_REGISTRY[frozenset(["UltraTechnicalPerson",
"SuperTechnicalPerson",
"TechnicalPerson",
"BasePerson"])]
# Recall a TechnicalPerson and enumerate its friends.
# One of them is UltraTechnicalPerson which would be returned as a valid
# node to a friends_with query but is currently unknown to the node class registry.
A = TechnicalPerson.get_or_create({"name":"Grumpy", "expertise":"Grumpiness"})[0]
with pytest.raises(neomodel.exceptions.ModelDefinitionMismatch):
for some_friend in A.friends_with:
print(some_friend.name)
def test_attempted_class_redefinition():
"""
A neomodel.StructuredNode class is attempted to be redefined.
"""
def redefine_class_locally():
# Since this test has already set up a class hierarchy in its global scope, we will try to redefine
# SomePerson here.
# The internal structure of the SomePerson entity does not matter at all here.
class SomePerson(BaseOtherPerson):
uid = neomodel.UniqueIdProperty()
with pytest.raises(neomodel.exceptions.ClassAlreadyDefined):
redefine_class_locally()
|
(function() {
'use strict';
angular.module('admin').controller('AdminController', AdminController);
AdminController.$inject = ['$state'];
function AdminController($state) {
let vm = this;
vm.state = $state;
}
})();
|
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session');
const passport = require('passport');
const redisStore = require('./helpers/redisStore');
const dotenv = require('dotenv');
dotenv.config();
const indexRouter = require('./routes/index');
const auth = require('./routes/auth');
const chat = require('./routes/chat');
const messages = require('./routes/messages');
const app = express();
//helpers
const db = require('./helpers/db')();
console.log(process.env.DEVELOPER)
//middlewares
const isAuthenticated = require('./middleware/isAuthenticated');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
//express-session
app.use(session({
store: redisStore,
secret: process.env.SESSION_SECRET_KEY,
resave: false,
saveUninitialized: true,
cookie: {maxAge: 14* 24 * 3600000 }
}));
//passport.js
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/auth', auth);
app.use('/chat', isAuthenticated, chat);
app.use('/messages', isAuthenticated, messages);
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
#!/usr/bin/env node
/*
* @Author: etong
* @Date: 2021-10-26 11:28:19
* @LastEditTime: 2021-10-27 18:34:33
* @LastEditors: your name
* @Description:
* @FilePath: \jj-cli\bin\www\index.js
* Think first, Program later
*/
// const testTiny = function(string) {
// if (typeof string !== "string") throw new TypeError("Tiny wants a string!");
// return string.replace(/\s/g, "");
// }
const inquirer = require('inquirer');
const program = require('commander');
const chalk = require('chalk');
const figlet = require('figlet');
figlet.text('@etongduomi/jj-cli!', {
font: 'Ghost',
horizontalLayout: 'default',
verticalLayout: 'default',
whitespaceBreak: true
}, function(err, data) {
if (err) {
console.log('Something went wrong...');
console.dir(err);
return;
}
console.log(data);
});
program
// 定义命令和参数
.command('create <file-name>')
.description('Create a new file project')
// -f or force 强制创建 目录存在则覆盖
.option('-f, --force', 'overwrite target folder if it already exists')
.action((name, options)=>{
require('../lib/create.js')(name, options)
})
program
// 配置版本信息
.version(`v${require('../../package.json').version}`)
.usage('<command> [option]')
// 解析用户执行命令传入参数
program.parse(process.argv);
/*
第一步:询问创建的文件名
第二步:生成对应的文件
*/
// inquirer.prompt({
// type: 'input',
// name: 'fileName',
// message: '请输入需要创建的文件名称',
// default: 'jj-cli-default'
// }).then((answer)=>{
// console.log(answer)
// })
|
'use strict';
module.exports = {
cookie: '',
redis: '',
};
|
#!/usr/bin/env python
# coding: utf-8
import setuptools
import os
import sys
this_directory = os.path.abspath(os.path.dirname(__file__))
sys.path.append(this_directory)
with open(os.path.join(this_directory, 'README.md'), 'r', encoding='utf-8') as fh:
readme = fh.read()
tabugen_version = '0.8.0'
install_requires = [
'et-xmlfile>=1.0.1',
'jdcal>=1.4.1',
'openpyxl>=2.6.3',
'PyMySQL>=0.9.3',
]
setuptools.setup(
name='tabugen',
version=tabugen_version,
license='Apache License 2.0',
author='qchencc',
author_email='ichenq@outlook.com',
url='https://github.com/qchencc/tabugen',
description=u'a spreedsheet export and code generate tool for rapid game development',
long_description=readme,
long_description_content_type='text/markdown',
python_requires='>=3.6',
include_package_data=True,
packages=setuptools.find_packages(),
install_requires=install_requires,
entry_points={
'console_scripts': [
"tabugen = tabugen.cli:main"
]
}
)
|
from os import PathLike
class FrameCapture:
def __init__(self, saveLocation: PathLike = None, snapTime: int = None):
self.saveLocation = saveLocation
self.snapTime = snapTime
def getSaveLocation(self) -> PathLike:
return self.saveLocation
def getSnapTime(self) -> int:
return self.snapTime
|
from functools import partial, wraps
from inspect import getfullargspec
# Modified version of fn.py decorator to support type annotations
def curried(func):
@wraps(func)
def _curried(*args, **kwargs):
f = func
count = 0
while isinstance(f, partial):
if f.args:
count += len(f.args)
f = f.func
spec = getfullargspec(f)
if count == len(spec.args) - len(args):
return func(*args, **kwargs)
return curried(partial(func, *args, **kwargs))
return _curried
|
var searchData=
[
['nb_5fsentinels',['NB_SENTINELS',['../classreactphysics3d_1_1_sweep_and_prune_algorithm.html#ab535d3236b24b716b6260680088b5acb',1,'reactphysics3d::SweepAndPruneAlgorithm']]],
['next',['next',['../structreactphysics3d_1_1_joint_list_element.html#acc8cf193fe5d89c099f45a4f563623ec',1,'reactphysics3d::JointListElement::next()'],['../structreactphysics3d_1_1_contact_manifold_list_element.html#a0facad101aa8bd4b6a07e29ee8d6a454',1,'reactphysics3d::ContactManifoldListElement::next()']]],
['normal',['normal',['../structreactphysics3d_1_1_contact_point_info.html#aa686068afcc156eb2d86c475674986ae',1,'reactphysics3d::ContactPointInfo']]]
];
|
/**
* @file lavas config
* @author my_liao(13723683480@163.com)
*/
'use strict';
const path = require('path');
const BUILD_PATH = path.resolve(__dirname, 'dist');
const isDev = process.env.NODE_ENV === 'development';
const isProd = process.env.NODE_ENV === 'production';
module.exports = {
build: {
ssr: true,
path: BUILD_PATH,
publicPath: '/',
ssrCopy: isDev ? [] : [
{
src: 'server.prod.js'
},
{
src: 'package.json'
}
],
/**
* alias for webpack
*
* @type {Object.<string, Object>}
*/
alias: {
server: {
'iscroll/build/iscroll-lite$': path.join(__dirname, 'core/iscroll-ssr.js')
}
},
/**
* node externals
*
* @type {Array.<string|RegExp>}
*/
nodeExternalsWhitelist: [
/iscroll/
]
},
router: {
mode: 'history',
base: '/',
pageTransition: {
type: 'slide',
transitionClass: 'slide'
}
},
serviceWorker: {
swSrc: path.join(__dirname, 'core/service-worker.js'),
swDest: path.join(BUILD_PATH, 'service-worker.js'),
// swPath: '/custom_path/', // specify custom serveice worker file's path, default is publicPath
globDirectory: BUILD_PATH,
globPatterns: [
'**/*.{html,js,css,eot,svg,ttf,woff}'
],
globIgnores: [
'sw-register.js',
'**/*.map'
],
appshellUrl: '/appshell',
dontCacheBustUrlsMatching: /\.\w{8}\./
}
};
|
// Compiled using marko@4.5.0 - DO NOT EDIT
"use strict";
var marko_template = module.exports = require("marko/src/html").t(__filename),
components_helpers = require("marko/src/components/helpers"),
marko_registerComponent = components_helpers.rc,
marko_componentType = marko_registerComponent("/marko-webpack$1.0.0/src/layouts/default/index.marko", function() {
return module.exports;
}),
marko_renderer = components_helpers.r,
marko_defineComponent = components_helpers.c,
marko_helpers = require("marko/src/runtime/html/helpers"),
marko_loadTag = marko_helpers.t,
include_tag = marko_loadTag(require("marko/src/taglibs/core/include-tag")),
component_globals_tag = marko_loadTag(require("marko/src/components/taglib/component-globals-tag")),
browser_refresh_tag = marko_loadTag(require("browser-refresh-taglib/refresh-tag")),
init_components_tag = marko_loadTag(require("marko/src/components/taglib/init-components-tag")),
await_reorderer_tag = marko_loadTag(require("marko/src/taglibs/async/await-reorderer-tag"));
function render(input, out, __component, component, state) {
var data = input;
out.w("<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>");
include_tag({
_target: data.title
}, out, __component, "4");
out.w("</title>");
include_tag({
_target: data.styles
}, out, __component, "5");
out.w("</head><body>");
component_globals_tag({}, out);
out.w("<div class=\"container\"><h1>");
include_tag({
_target: data.title
}, out, __component, "9");
out.w("</h1><main id=\"main\">");
include_tag({
_target: data.body
}, out, __component, "11");
out.w("</main></div>");
include_tag({
_target: data.scripts
}, out, __component, "12");
browser_refresh_tag({
enabled: true
}, out, __component, "13");
init_components_tag({}, out);
await_reorderer_tag({}, out, __component, "14");
out.w("</body></html>");
}
marko_template._ = marko_renderer(render, {
___implicit: true,
___type: marko_componentType
});
marko_template.Component = marko_defineComponent({}, marko_template._);
marko_template.meta = {
deps: [
"./style.less"
],
tags: [
"marko/src/taglibs/core/include-tag",
"marko/src/components/taglib/component-globals-tag",
"browser-refresh-taglib/refresh-tag",
"marko/src/components/taglib/init-components-tag",
"marko/src/taglibs/async/await-reorderer-tag"
]
};
|
import api from '../api';
class PanoramaController {
constructor (func) {
this._isPanoramas = func;
}
createPanorama (container, state, options) {
this._container = container;
this._coordinates = state.center;
this._options = options;
this._panorama = api.getAPI().panorama;
return this;
}
locate (showService) {
if (this.isSupported()) {
this._panorama.locate(this._coordinates).done(
(panoramas) => {
this._isPanoramas(Boolean(panoramas.length));
if (showService) {
this.show(panoramas);
}
},
(error) => this.error(error)
);
} else {
this.error ({
message: 'Браузер не поддерживается плеером.'
});
}
}
show (panoramas) {
if (panoramas.length > 0) {
const player = new this._panorama.Player(
this._container,
panoramas[0],
this._options
);
player.events.add('destroy', this.destroy.bind(this));
}
}
error (error) {
console.error(error.message);
}
isSupported () {
return this._panorama.isSupported();
}
destroy () {
this._panorama = null;
if (this._options.parentFunct) {
this._options.parentFunct();
}
}
}
export default PanoramaController;
|
# ----------------------------------------------------------------------
# SegmentTopology class
# ----------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python modules
import operator
import logging
import itertools
from collections import defaultdict
# Third-party modules
import cachetools
# NOC modules
from noc.sa.models.managedobject import ManagedObject
from noc.inv.models.interface import Interface
from noc.inv.models.link import Link
from noc.core.log import PrefixLoggerAdapter
from noc.core.ip import IP
from noc.core.graph.nexthop import iter_next_hops
from .base import BaseTopology
logger = logging.getLogger(__name__)
class SegmentTopology(BaseTopology):
def __init__(self, segment, node_hints=None, link_hints=None, force_spring=False):
self.logger = PrefixLoggerAdapter(logger, segment.name)
self.segment = segment
self.segment_siblings = self.segment.get_siblings()
self._uplinks_cache = {}
self.segment_objects = set()
if self.segment.parent:
self.parent_segment = self.segment.parent
self.ancestor_segments = set(self.segment.get_path()[:-1])
else:
self.parent_segment = None
self.ancestor_segments = set()
super().__init__(node_hints, link_hints, force_spring)
def get_role(self, mo):
if mo.segment in self.segment_siblings:
return "segment"
elif self.parent_segment and mo.segment.id in self.ancestor_segments:
return "uplink"
else:
return "downlink"
@cachetools.cachedmethod(operator.attrgetter("_uplinks_cache"))
def get_uplinks(self):
self.logger.info("Searching for uplinks")
if not self.G:
return []
for policy in self.segment.profile.iter_uplink_policy():
uplinks = getattr(self, "get_uplinks_%s" % policy)()
if uplinks:
self.logger.info(
"[%s] %d uplinks found: %s",
policy,
len(uplinks),
", ".join(str(x) for x in uplinks),
)
return uplinks
self.logger.info("[%s] No uplinks found. Skipping", policy)
self.logger.info("Failed to find uplinks")
return []
def get_uplinks_seghier(self):
"""
Find uplinks basing on segment hierarchy. Any object with parent segment
is uplink
:return:
"""
return [i for i in self.G.nodes if self.G.nodes[i].get("role") == "uplink"]
def get_uplinks_molevel(self):
"""
Find uplinks basing on Managed Object's level. Top-leveled objects are returned.
:return:
"""
max_level = max(
self.G.nodes[i].get("level")
for i in self.G.nodes
if self.G.nodes[i].get("type") == "managedobject"
)
return [
i
for i in self.G.nodes
if self.G.nodes[i].get("type") == "managedobject"
and self.G.nodes[i].get("level") == max_level
]
def get_uplinks_seg(self):
"""
All segment objects are uplinks
:return:
"""
return [i for i in self.G.nodes if self.G.nodes[i].get("role") == "segment"]
def get_uplinks_minaddr(self):
"""
Segment's Object with lesser address is uplink
:return:
"""
s = next(
iter(
sorted(
(IP.prefix(self.G.nodes[i].get("address")), i)
for i in self.G.nodes
if self.G.nodes[i].get("role") == "segment"
)
)
)
return [s[1]]
def get_uplinks_maxaddr(self):
"""
Segment's Object with greater address is uplink
:return:
"""
s = next(
reversed(
sorted(
(IP.prefix(self.G.nodes[i].get("address")), i)
for i in self.G.nodes
if self.G.nodes[i].get("role") == "segment"
)
)
)
return [s[1]]
def load(self):
"""
Load all managed objects from segment
"""
def get_bandwidth(if_list):
"""
Calculate bandwidth for list of interfaces
:param if_list:
:return: total in bandwidth, total out bandwidth
"""
in_bw = 0
out_bw = 0
for iface in if_list:
bw = iface.get("bandwidth") or 0
in_speed = iface.get("in_speed") or 0
out_speed = iface.get("out_speed") or 0
in_bw += bandwidth(in_speed, bw)
out_bw += bandwidth(out_speed, bw)
return in_bw, out_bw
def bandwidth(speed, if_bw):
if speed and if_bw:
return min(speed, if_bw)
elif speed and not if_bw:
return speed
elif if_bw:
return if_bw
else:
return 0
# Get all links, belonging to segment
links = list(Link.objects.filter(linked_segments__in=[s.id for s in self.segment_siblings]))
# All linked interfaces from map
all_ifaces = list(itertools.chain.from_iterable(link.interface_ids for link in links))
# Bulk fetch all interfaces data
ifs = {
i["_id"]: i
for i in Interface._get_collection().find(
{"_id": {"$in": all_ifaces}},
{
"_id": 1,
"managed_object": 1,
"name": 1,
"bandwidth": 1,
"in_speed": 1,
"out_speed": 1,
},
)
}
# Bulk fetch all managed objects
segment_mos = set(self.segment.managed_objects.values_list("id", flat=True))
all_mos = list(
set(i["managed_object"] for i in ifs.values() if "managed_object" in i) | segment_mos
)
mos = {mo.id: mo for mo in ManagedObject.objects.filter(id__in=all_mos)}
self.segment_objects = set(
mo_id for mo_id in all_mos if mos[mo_id].segment.id == self.segment.id
)
for mo in mos.values():
self.add_object(mo)
# Process all segment's links
pn = 0
for link in links:
if link.is_loop:
continue # Loops are not shown on map
# Group interfaces by objects
# avoiding non-bulk dereferencing
mo_ifaces = defaultdict(list)
for if_id in link.interface_ids:
iface = ifs[if_id]
mo_ifaces[mos[iface["managed_object"]]] += [iface]
# Pairs of managed objects are pseudo-links
if len(mo_ifaces) == 2:
# ptp link
pseudo_links = [list(mo_ifaces)]
is_pmp = False
else:
# pmp
# Create virtual cloud
self.add_cloud(link)
# Create virtual links to cloud
pseudo_links = [(link, mo) for mo in mo_ifaces]
# Create virtual cloud interface
mo_ifaces[link] = [{"name": "cloud"}]
is_pmp = True
# Link all pairs
for mo0, mo1 in pseudo_links:
mo0_id = str(mo0.id)
mo1_id = str(mo1.id)
# Create virtual ports for mo0
self.G.nodes[mo0_id]["ports"] += [
{"id": pn, "ports": [i["name"] for i in mo_ifaces[mo0]]}
]
# Create virtual ports for mo1
self.G.nodes[mo1_id]["ports"] += [
{"id": pn + 1, "ports": [i["name"] for i in mo_ifaces[mo1]]}
]
# Calculate bandwidth
t_in_bw, t_out_bw = get_bandwidth(mo_ifaces[mo0])
d_in_bw, d_out_bw = get_bandwidth(mo_ifaces[mo1])
in_bw = bandwidth(t_in_bw, d_out_bw) * 1000
out_bw = bandwidth(t_out_bw, d_in_bw) * 1000
# Add link
if is_pmp:
link_id = "%s-%s-%s" % (link.id, pn, pn + 1)
else:
link_id = str(link.id)
self.add_link(
mo0_id,
mo1_id,
{
"id": link_id,
"type": "link",
"method": link.discovery_method,
"ports": [pn, pn + 1],
# Target to source
"in_bw": in_bw,
# Source to target
"out_bw": out_bw,
# Max bandwidth
"bw": max(in_bw, out_bw),
},
)
pn += 2
def iter_uplinks(self):
"""
Yields ObjectUplinks items for segment
:returns: ObjectUplinks items
"""
def get_node_uplinks(node):
role = self.G.nodes[node].get("role", "cloud")
if role == "uplink":
# Only downlinks matter
return []
elif role == "downlink":
# All segment neighbors are uplinks.
# As no inter-downlink segment's links are loaded
# so all neigbors are from current segment
return list(self.G.neighbors(node))
# Segment role and clouds
ups = {}
for u in uplinks:
if u == node:
# skip self
continue
for next_hop, path_len in iter_next_hops(self.G, node, u):
ups[next_hop] = min(path_len, ups.get(next_hop, path_len))
# Shortest path first
return sorted(ups, key=lambda x: ups[x])
from noc.sa.models.objectdata import ObjectUplinks
uplinks = self.get_uplinks()
# @todo: Workaround for empty uplinks
# Get uplinks for cloud nodes
cloud_uplinks = {
o: [int(u) for u in get_node_uplinks(o)]
for o in self.G.nodes
if self.G.nodes[o]["type"] == "cloud"
}
# All objects including neighbors
all_objects = set(o for o in self.G.nodes if self.G.nodes[o]["type"] == "managedobject")
# Get objects uplinks
obj_uplinks = {}
obj_downlinks = defaultdict(set)
for o in all_objects:
mo = int(o)
ups = []
for u in get_node_uplinks(o):
cu = cloud_uplinks.get(u)
if cu is not None:
# Uplink is a cloud. Use cloud's uplinks instead
ups += cu
else:
ups += [int(u)]
obj_uplinks[mo] = ups
for u in ups:
obj_downlinks[u].add(mo)
# Check uplinks with DownlinkMerge settings
dlm_settings = set(
ManagedObject.objects.filter(
id__in=obj_uplinks, object_profile__enable_rca_downlink_merge=True
).values_list("id", flat=True)
)
# Calculate RCA neighbors and yield result
for mo in obj_uplinks:
# Filter out only current segment. Neighbors will be updated by their
# segment's tasks
if mo not in self.segment_objects:
continue
# All uplinks
neighbors = set(obj_uplinks[mo])
# All downlinks
for dmo in obj_downlinks[mo]:
neighbors.add(dmo)
# And uplinks of downlinks
neighbors |= set(obj_uplinks[dmo])
# Downlinks of uplink if MergeDownlinks setting is set
if dlm_settings and dlm_settings.intersection(set(obj_uplinks[mo])):
for dumo in obj_uplinks[mo]:
neighbors |= obj_downlinks[dumo]
# Not including object itself
if mo in neighbors:
neighbors.remove(mo)
#
rca_neighbors = list(sorted(neighbors))
# Recalculated result
yield ObjectUplinks(object_id=mo, uplinks=obj_uplinks[mo], rca_neighbors=rca_neighbors)
def update_uplinks(segment_id):
from noc.inv.models.networksegment import NetworkSegment
segment = NetworkSegment.get_by_id(segment_id)
if not segment:
logger.warning("Segment with id: %s does not exist" % segment_id)
return
st = SegmentTopology(segment)
ManagedObject.update_uplinks(st.iter_uplinks())
|
import { useMeeting, useParticipant } from "@videosdk.live/react-sdk";
import {
Close,
MoreVert,
SearchOutlined,
MicOff as MicOffIcon,
Mic as MicIcon,
VideocamOff as VideocamOffIcon,
Videocam as VideocamIcon,
} from "@material-ui/icons";
import {
Avatar,
Box,
IconButton,
InputAdornment,
TextField,
Typography,
useTheme,
Fade,
Tooltip,
} from "@material-ui/core";
import React, { useEffect, useRef, useMemo, useState } from "react";
import { useMeetingAppContext } from "../../MeetingAppContextDef";
import { Pin, RaiseHand, KickoutUserIcon } from "../../icons";
import { List } from "react-virtualized";
import useWindowSize from "../../utils/useWindowSize";
import useIsTab from "../../utils/useIsTab";
import useIsMobile from "../../utils/useIsMobile";
import ConfirmBox from "../../components/ConfirmBox";
import { nameTructed } from "../../utils/common";
function ParticipantListItem({
raisedHand,
participantId,
participantExpandedId,
setParticipantExpandedId,
}) {
const {
participant,
micOn,
webcamOn,
displayName,
isLocal,
pinState,
pin,
unpin,
enableMic,
disableMic,
enableWebcam,
disableWebcam,
} = useParticipant(participantId);
const {
participantCanToggleOtherMic,
participantCanToggleOtherWebcam,
canRemoveOtherParticipant,
canPin,
} = useMeetingAppContext();
const [isParticipantKickoutVisible, setIsParticipantKickoutVisible] =
useState(false);
const [morePanelWidth, setMorePanelWidth] = useState(0);
const theme = useTheme();
const expanded = participantExpandedId === participantId;
const morePanelRef = useRef();
useEffect(() => {
morePanelRef.current?.offsetWidth &&
setMorePanelWidth(morePanelRef.current.offsetWidth);
}, []);
return (
<Box
mt={1}
p={1}
style={{
backgroundColor: theme.palette.common.sidePanel,
borderRadius: 6,
}}
>
<Box
style={{
display: "flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
position: "relative",
}}
>
<Avatar variant={"rounded"}>{displayName?.charAt(0)}</Avatar>
<Fade in={!expanded}>
<Box ml={1} mr={0.5} style={{ flex: 1, display: "flex" }}>
<Typography
style={{
textOverflow: "ellipsis",
overflow: "hidden",
whiteSpace: "pre-wrap",
}}
variant="body1"
noWrap
>
{isLocal ? "You" : nameTructed(displayName, 15)}
</Typography>
</Box>
</Fade>
<Box
style={{
display: "flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
position: "absolute",
top: 0,
right: 0,
bottom: 0,
}}
>
<Box
style={{
display: "flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
position: "relative",
}}
>
<Box
style={{
display: "flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
transition: "all 200ms",
right: expanded ? morePanelWidth : 0,
position: "absolute",
}}
>
{raisedHand && (
<Box
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
mr={0.5}
p={0.5}
>
<RaiseHand />
</Box>
)}
<Box ml={0.5} mr={0.5}>
<IconButton
disabled={!participantCanToggleOtherMic || isLocal}
style={{ padding: 0 }}
onClick={() => {
if (micOn) {
disableMic();
} else {
enableMic();
}
}}
>
<Box
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: 100,
backgroundColor: micOn ? null : theme.palette.error.main,
}}
p={0.5}
>
{micOn ? (
<MicIcon
fontSize="small"
style={{ color: theme.palette.common.white }}
/>
) : (
<MicOffIcon
fontSize="small"
style={{ color: theme.palette.common.white }}
/>
)}
</Box>
</IconButton>
</Box>
<Box ml={1} mr={0}>
<IconButton
disabled={!participantCanToggleOtherWebcam || isLocal}
style={{ padding: 0 }}
onClick={() => {
if (webcamOn) {
disableWebcam();
} else {
enableWebcam();
}
}}
>
<Box
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: 100,
backgroundColor: webcamOn
? null
: theme.palette.error.main,
}}
p={0.5}
>
{webcamOn ? (
<VideocamIcon
fontSize="small"
style={{ color: theme.palette.common.white }}
/>
) : (
<VideocamOffIcon
fontSize="small"
style={{ color: theme.palette.common.white }}
/>
)}
</Box>
</IconButton>
</Box>
</Box>
<Box
ref={morePanelRef}
style={{
display: "flex",
flex: 1,
justifyContent: "center",
alignItems: "center",
transition: "all 200ms",
right: expanded ? 0 : -morePanelWidth,
position: "absolute",
opacity: expanded ? 1 : 0,
}}
>
{canPin && (
<Box
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
ml={1}
mr={0}
p={0.5}
>
<Tooltip
title={pinState?.share || pinState?.cam ? "Unpin" : `Pin`}
>
<IconButton
disabled={!expanded}
size="small"
onClick={(e) => {
e.stopPropagation();
pinState?.share || pinState?.cam ? unpin() : pin();
}}
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Pin
fill={
pinState?.share || pinState?.cam
? "white"
: "#ffffff80"
}
style={{
width: 20,
height: 20,
}}
/>
</IconButton>
</Tooltip>
</Box>
)}
{!isLocal && canRemoveOtherParticipant && (
<Box ml={1} mr={0}>
<Tooltip title={`Remove`}>
<IconButton
disabled={!expanded}
size="small"
onClick={(e) => {
e.stopPropagation();
setIsParticipantKickoutVisible(true);
// participant.remove();
}}
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<KickoutUserIcon height={18} width={18} />
</IconButton>
</Tooltip>
<ConfirmBox
open={isParticipantKickoutVisible}
title={`Remove ${nameTructed(displayName, 15)} `}
subTitle={`Are you sure want to remove ${nameTructed(
displayName,
15
)} from the call?`}
successText={"Remove"}
rejectText={"Cancel"}
onSuccess={() => {
participant.remove();
}}
onReject={() => {
setIsParticipantKickoutVisible(false);
}}
/>
</Box>
)}
</Box>
</Box>
<Box style={{ transition: "all 200ms" }} ml={expanded ? 1.5 : 1}>
<IconButton
style={{ padding: 0 }}
onClick={(e) => {
if (participantId === participantExpandedId) {
setParticipantExpandedId(null);
} else {
setParticipantExpandedId(participantId);
}
}}
>
<Box
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
borderRadius: 100,
border: `${expanded ? "0" : "0"}px solid ${
expanded
? theme.palette.error.main
: theme.palette.common.secondaryContrastTextLight
}`,
backgroundColor: expanded ? theme.palette.error.main : null,
}}
p={0.5}
>
{expanded ? (
<Close fontSize="small" />
) : (
<MoreVert fontSize="small" />
)}
</Box>
</IconButton>
</Box>
</Box>
</Box>
</Box>
);
}
export default function ParticipantsTabPanel({ panelWidth, panelHeight }) {
const [filterQuery, setFilterQuery] = useState("");
const [participantExpandedId, setParticipantExpandedId] = useState(null);
const { participants } = useMeeting();
const { raisedHandsParticipants } = useMeetingAppContext();
const sortedRaisedHandsParticipants = useMemo(() => {
const participantIds = [...participants.keys()];
const notRaised = participantIds.filter(
(pID) =>
raisedHandsParticipants.findIndex(
({ participantId: rPID }) => rPID === pID
) === -1
);
const raisedSorted = raisedHandsParticipants.sort((a, b) => {
if (a.raisedHandOn > b.raisedHandOn) {
return -1;
}
if (a.raisedHandOn < b.raisedHandOn) {
return 1;
}
return 0;
});
const combined = [
...raisedSorted.map(({ participantId: p }) => ({
raisedHand: true,
participantId: p,
})),
...notRaised.map((p) => ({ raisedHand: false, participantId: p })),
];
return combined;
}, [raisedHandsParticipants, participants]);
const theme = useTheme();
const filterParticipants = (
sortedRaisedHandsParticipants,
participants,
filterQuery
) =>
filterQuery?.length > 3
? sortedRaisedHandsParticipants.filter(({ participantId }) => {
const { displayName } = participants.get(participantId);
const hide = !displayName
?.toLowerCase()
.includes(filterQuery.toLowerCase());
return !hide;
})
: sortedRaisedHandsParticipants;
const part = useMemo(
() =>
filterParticipants(
sortedRaisedHandsParticipants,
participants,
filterQuery
),
[sortedRaisedHandsParticipants, participants, filterQuery]
);
function rowRenderer({ key, index, isScrolling, isVisible, style }) {
const { participantId, raisedHand } = part[index];
return (
<div {...{ key, style }}>
{isVisible ? (
<ParticipantListItem
participantId={participantId}
raisedHand={raisedHand}
participantExpandedId={participantExpandedId}
setParticipantExpandedId={setParticipantExpandedId}
/>
) : (
<Box
mt={1}
style={{
height: 56,
backgroundColor: theme.palette.common.sidePanel,
borderRadius: 6,
}}
></Box>
)}
</div>
);
}
const { width } = useWindowSize();
const isTab = useIsTab();
const isMobile = useIsMobile();
return (
<Box
p={1}
style={{
height: panelHeight - 32,
overflowY: "auto",
overflowX: "hidden",
}}
>
<Box>
<TextField
variant="outlined"
fullWidth
placeholder="Search Participants"
onChange={(e) => setFilterQuery(e.target.value)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchOutlined />
</InputAdornment>
),
}}
/>
</Box>
<Box style={{ overflowY: "auto" }}>
<List
width={isTab || isMobile ? width - 32 : panelWidth - 36}
height={panelHeight - 90}
rowCount={part.length}
rowHeight={64}
rowRenderer={rowRenderer}
/>
</Box>
</Box>
);
}
|
import React from 'react'
import Config from '../Config'
class AppBar extends React.Component {
render ( ) {
return (
<div className="navbar navbar-default appbar-brand navbar-static-top">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href={`${Config.URL.BASE}`}>
<div className="font-brand font-bold">
{Config.App.NAME}
</div>
</a>
</div>
<div className="collapse navbar-collapse">
<ul className="nav navbar-nav navbar-right">
<li className="dropdown">
<a className="dropdown-toggle" data-toggle="dropdown">
<i className="fa fa-fw fa-ellipsis-v"></i>
</a>
<ul className="dropdown-menu">
<li>
<a href="#">
About
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
)
}
}
export default AppBar
|
const { Schema, model } = require('mongoose');
const userSchema = new Schema ( {
username: {
type: String,
unique: true,
required :true,
trim:true
},
email: {
type: String,
unique: true,
required :true,
match: [/.+@.+\..+/]
},
thoughts:
[{ type: Schema.Types.ObjectId, ref: 'Thought'}],
friends:
[{ type: Schema.Types.ObjectId, ref: 'User'}]
},
{
toJSON:{ virtuals: true, getter:true },
id:false
});
userSchema
.virtual('friendCount')
.get(function()
{
return this.friends.length;
});
const User = model('User', userSchema);
module.exports = User;
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("node_modules/codemirror/lib/codemirror.js"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("http", function() {
function failFirstLine(stream, state) {
stream.skipToEnd();
state.cur = header;
return "error";
}
function start(stream, state) {
if (stream.match(/^HTTP\/\d\.\d/)) {
state.cur = responseStatusCode;
return "keyword";
} else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) {
state.cur = requestPath;
return "keyword";
} else {
return failFirstLine(stream, state);
}
}
function responseStatusCode(stream, state) {
var code = stream.match(/^\d+/);
if (!code) return failFirstLine(stream, state);
state.cur = responseStatusText;
var status = Number(code[0]);
if (status >= 100 && status < 200) {
return "positive informational";
} else if (status >= 200 && status < 300) {
return "positive success";
} else if (status >= 300 && status < 400) {
return "positive redirect";
} else if (status >= 400 && status < 500) {
return "negative client-error";
} else if (status >= 500 && status < 600) {
return "negative server-error";
} else {
return "error";
}
}
function responseStatusText(stream, state) {
stream.skipToEnd();
state.cur = header;
return null;
}
function requestPath(stream, state) {
stream.eatWhile(/\S/);
state.cur = requestProtocol;
return "string-2";
}
function requestProtocol(stream, state) {
if (stream.match(/^HTTP\/\d\.\d$/)) {
state.cur = header;
return "keyword";
} else {
return failFirstLine(stream, state);
}
}
function header(stream) {
if (stream.sol() && !stream.eat(/[ \t]/)) {
if (stream.match(/^.*?:/)) {
return "atom";
} else {
stream.skipToEnd();
return "error";
}
} else {
stream.skipToEnd();
return "string";
}
}
function body(stream) {
stream.skipToEnd();
return null;
}
return {
token: function(stream, state) {
var cur = state.cur;
if (cur != header && cur != body && stream.eatSpace()) return null;
return cur(stream, state);
},
blankLine: function(state) {
state.cur = body;
},
startState: function() {
return {cur: start};
}
};
});
CodeMirror.defineMIME("message/http", "http");
});
|
/**
* Kendo UI v2021.2.511 (http://www.telerik.com/kendo-ui)
* Copyright 2021 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(e){"function"==typeof define&&define.amd?define(["kendo.core.min"],e):e()}(function(){!function(e,y){kendo.cultures["en-VC"]={name:"en-VC",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{name:"East Caribbean Dollar",abbr:"XCD",pattern:["-$n","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"$"}},calendars:{standard:{days:{names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],namesAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],namesShort:["Su","Mo","Tu","We","Th","Fr","Sa"]},months:{names:["January","February","March","April","May","June","July","August","September","October","November","December"],namesAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},AM:["am","am","AM"],PM:["pm","pm","PM"],patterns:{d:"dd/MM/yyyy",D:"dddd, d MMMM yyyy",F:"dddd, d MMMM yyyy h:mm:ss tt",g:"dd/MM/yyyy h:mm tt",G:"dd/MM/yyyy h:mm:ss tt",m:"d MMMM",M:"d MMMM",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"h:mm tt",T:"h:mm:ss tt",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM yyyy",Y:"MMMM yyyy"},"/":"/",":":":",firstDay:1}}}}(this)});
//# sourceMappingURL=kendo.culture.en-VC.min.js.map
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
require("dotenv").config();
var Modules = require("./loader");
var stopAll = require("./stopAll");
var _a = require("fs/promises"), readdir = _a.readdir, stat = _a.stat;
var Terminal = require("system-commands");
var chalk = require("chalk");
var path = require("path");
var pm2 = require("pm2");
var fs = require("fs");
module.exports = function a() {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
stopAll
.then(function (data) {
Modules.getDirectories("./".concat(process.env.SECRET_PATH), function (Data) {
console.log(chalk.blue("\u301A\u2261\u301BSyncing Applications, ".concat(Data.length, " in Queue...")));
new Promise(function (res, rej) {
Data.forEach(function (Folder) {
Modules.Start(Folder)
.then(function (data) {
console.log(chalk.green(data));
})
.catch(function (err) {
console.log(chalk.red(err));
});
});
resolve("\u301A\u2714\u301BSuccessfuly Synced");
});
});
})
.catch(function (err) {
reject(err);
});
})];
});
});
};
|
/* eslint-disable class-methods-use-this */
import $ from 'jquery';
import Flash from '../flash';
import FileTemplateTypeSelector from './template_selectors/type_selector';
import BlobCiYamlSelector from './template_selectors/ci_yaml_selector';
import DockerfileSelector from './template_selectors/dockerfile_selector';
import GitignoreSelector from './template_selectors/gitignore_selector';
import LicenseSelector from './template_selectors/license_selector';
export default class FileTemplateMediator {
constructor({ editor, currentAction }) {
this.editor = editor;
this.currentAction = currentAction;
this.initTemplateSelectors();
this.initTemplateTypeSelector();
this.initDomElements();
this.initDropdowns();
this.initPageEvents();
}
initTemplateSelectors() {
// Order dictates template type dropdown item order
this.templateSelectors = [
GitignoreSelector,
BlobCiYamlSelector,
DockerfileSelector,
LicenseSelector,
].map(TemplateSelectorClass => new TemplateSelectorClass({ mediator: this }));
}
initTemplateTypeSelector() {
this.typeSelector = new FileTemplateTypeSelector({
mediator: this,
dropdownData: this.templateSelectors
.map((templateSelector) => {
const cfg = templateSelector.config;
return {
name: cfg.name,
key: cfg.key,
};
}),
});
}
initDomElements() {
const $templatesMenu = $('.template-selectors-menu');
const $undoMenu = $templatesMenu.find('.template-selectors-undo-menu');
const $fileEditor = $('.file-editor');
this.$templatesMenu = $templatesMenu;
this.$undoMenu = $undoMenu;
this.$undoBtn = $undoMenu.find('button');
this.$templateSelectors = $templatesMenu.find('.template-selector-dropdowns-wrap');
this.$filenameInput = $fileEditor.find('.js-file-path-name-input');
this.$fileContent = $fileEditor.find('#file-content');
this.$commitForm = $fileEditor.find('form');
this.$navLinks = $fileEditor.find('.nav-links');
}
initDropdowns() {
if (this.currentAction === 'create') {
this.typeSelector.show();
} else {
this.hideTemplateSelectorMenu();
}
this.displayMatchedTemplateSelector();
}
initPageEvents() {
this.listenForFilenameInput();
this.prepFileContentForSubmit();
this.listenForPreviewMode();
}
listenForFilenameInput() {
this.$filenameInput.on('keyup blur', () => {
this.displayMatchedTemplateSelector();
});
}
prepFileContentForSubmit() {
this.$commitForm.submit(() => {
this.$fileContent.val(this.editor.getValue());
});
}
listenForPreviewMode() {
this.$navLinks.on('click', 'a', (e) => {
const urlPieces = e.target.href.split('#');
const hash = urlPieces[1];
if (hash === 'preview') {
this.hideTemplateSelectorMenu();
} else if (hash === 'editor') {
this.showTemplateSelectorMenu();
}
});
}
selectTemplateType(item, e) {
if (e) {
e.preventDefault();
}
this.templateSelectors.forEach((selector) => {
if (selector.config.key === item.key) {
selector.show();
} else {
selector.hide();
}
});
this.typeSelector.setToggleText(item.name);
this.cacheToggleText();
}
selectTemplateTypeOptions(options) {
this.selectTemplateType(options.selectedObj, options.e);
}
selectTemplateFile(selector, query, data) {
selector.renderLoading();
// in case undo menu is already already there
this.destroyUndoMenu();
this.fetchFileTemplate(selector.config.endpoint, query, data)
.then((file) => {
this.showUndoMenu();
this.setEditorContent(file);
this.setFilename(selector.config.name);
selector.renderLoaded();
})
.catch(err => new Flash(`An error occurred while fetching the template: ${err}`));
}
displayMatchedTemplateSelector() {
const currentInput = this.getFilename();
this.templateSelectors.forEach((selector) => {
const match = selector.config.pattern.test(currentInput);
if (match) {
this.typeSelector.show();
this.selectTemplateType(selector.config);
this.showTemplateSelectorMenu();
}
});
}
fetchFileTemplate(apiCall, query, data) {
return new Promise((resolve) => {
const resolveFile = file => resolve(file);
if (!data) {
apiCall(query, resolveFile);
} else {
apiCall(query, data, resolveFile);
}
});
}
setEditorContent(file) {
if (!file && file !== '') return;
const newValue = file.content || file;
this.editor.setValue(newValue, 1);
this.editor.focus();
this.editor.navigateFileStart();
}
findTemplateSelectorByKey(key) {
return this.templateSelectors.find(selector => selector.config.key === key);
}
showUndoMenu() {
this.$undoMenu.removeClass('hidden');
this.$undoBtn.on('click', () => {
this.restoreFromCache();
this.destroyUndoMenu();
});
}
destroyUndoMenu() {
this.cacheFileContents();
this.cacheToggleText();
this.$undoMenu.addClass('hidden');
this.$undoBtn.off('click');
}
hideTemplateSelectorMenu() {
this.$templatesMenu.hide();
}
showTemplateSelectorMenu() {
this.$templatesMenu.show();
}
cacheToggleText() {
this.cachedToggleText = this.getTemplateSelectorToggleText();
}
cacheFileContents() {
this.cachedContent = this.editor.getValue();
this.cachedFilename = this.getFilename();
}
restoreFromCache() {
this.setEditorContent(this.cachedContent);
this.setFilename(this.cachedFilename);
this.setTemplateSelectorToggleText();
}
getTemplateSelectorToggleText() {
return this.$templateSelectors
.find('.js-template-selector-wrap:visible .dropdown-toggle-text')
.text();
}
setTemplateSelectorToggleText() {
return this.$templateSelectors
.find('.js-template-selector-wrap:visible .dropdown-toggle-text')
.text(this.cachedToggleText);
}
getTypeSelectorToggleText() {
return this.typeSelector.getToggleText();
}
getFilename() {
return this.$filenameInput.val();
}
setFilename(name) {
this.$filenameInput.val(name).trigger('change');
}
getSelected() {
return this.templateSelectors.find(selector => selector.selected);
}
}
|
'use strict';
import UserService from './../../services/user/user.service';
import template from './app-header.template.html';
import './app-header.style.css';
class AppHeaderComponent {
constructor(){
this.controller = AppHeaderComponentController;
this.template = template;
}
static get name() {
return 'appHeader';
}
}
class AppHeaderComponentController{
constructor($state,UserService){
this.$state = $state;
this.UserService = UserService;
}
openMenu($mdMenu, ev) {
$mdMenu.open(ev);
}
isAuthenticated(){
return this.UserService.isAuthenticated();
}
getCurrentUser(){
let user = this.UserService.getCurrentUser();
return user.username;
}
goHome(){
this.$state.go('movies',{});
}
login(){
this.$state.go('login',{});
}
logout(){
this.UserService.logout();
this.$state.go('movies',{});
}
static get $inject(){
return ['$state', UserService.name];
}
}
export default AppHeaderComponent;
|
'''
Created on 01.09.2020
@File: variablen.py
@author: Georg Maubach
'''
def frageNachName():
nname = input("Nachname: ");
vname = input("Vorname: ");
print("Sie heissen {} {}.".format(vname, nname));
print("Sie heissen", vname, nname, "."); # Der Punkt ist dann wegen sep="" abgesetzt.
print("Sie heissen ", vname, " ", nname, ".", sep = "");
print("Sie heissen", vname, nname, "."); # Der Punkt ist wieder abgesetzt.
print("Sie heissen ", vname, " ", nname, ".", sep = "");
print(f"Sie heissen {vname} {nname}."); # f-Strings in print() sind am einfachsten.
def quadriere():
# zahl = int(input("Gebe bitte eine Zahl ein: ")); # input liefert String, nicht Zahl als int() oder float()
# deshalb:
zahl = int(float(input("Gebe bitte eine Zahl ein: "))); # String erst in float() und dann in int() umwandeln
int("Zahl als int", int(5.0));
print("Deine Zahl zum Quadrat ist", zahl**2);
def gebeRestAus():
zahl1 = int(float(input("Gebe Zahl 1 ein: ")));
zahl2 = int(float(input("Gebe Zahl 2 ein: ")));
print(f"Das Ergebnis von {zahl1}/{zahl2} ist {int(zahl1//zahl2)}, Rest {zahl1 % zahl2}."); # Wichtig: Ganzahldivision // verwenden
def gebeRestAus_Musterloesung():
x = int(input("Zahl1: "));
y = int(input("Zahl2: "));
quotient = x // y;
rest = x % y;
print("Das Ergebnis von {0}/{1} ist {2}, Rest {3}.".format(zahl1, zahl2, quotient, rest));
# Mit 0, 1, 2, 3 kann auf die einzelnen Argumente aus .format() zugegriffen werden, z.B.
# um ein Argument mehrfach zu verwenden oder
# um die Reihenfolge zu ändern.
def testGeradeUngerade():
x = int(input("Zahl: "));
if (x % 2 == 0):
print("Zahl ist gerade.");
else:
print("Zahl ist ungerade.");
def FahrenheitInCelsius():
fahrenheit = int(float(input("Grad Fahrenheit: ")));
celsius = round((5/9)*(fahrenheit - 32), 1);
# Python macht eine Fliesskommezahl aus der Division. Andere Sprachen machen daraus denselben
# Datentyp wie die Eingabe. 5/9 ist dann Null. Um das zu vermeiden:
# 1. erst immer im Term multiplizieren.
# 2. erst nach allen Multiplikationen dividieren.
# Deshalb ist das besser:
celsius = round((5 * (fahrenheit - 32) / 9), 1);
print(f"{fahrenheit} Grad Fahrenheit sind {celsius} Grad Celsius.");
# Mathematische Funktionen stehen im "math" Package.
# Mathematische Funktionen:
# round(wert): runden
# round(wert, praezision): runden auf bestimmte Stelle
# floor(wert): abrunden auf nächste ganze Zahl
# ceil(wert): aufrunden auf nächste ganze Zahl
if __name__ == "__main__":
# frageNachName();
# quadriere();
# gebeRestAus();
# testGeradeUngerade();
FahrenheitInCelsius();
# EOF .
|
'use strict'
/*
* Create a `sub` function that takes 2 numbers as arguments and substract them
*
* @notions Primitive and Operators, Functions
*/
// Your code :
function sub(number, number2) {
return number - number2
}
//* Begin of tests
const assert = require('assert')
const rand = Math.random()
assert.strictEqual(typeof sub, 'function')
assert.strictEqual(sub.length, 2)
assert.strictEqual(sub(2, 2), 0)
assert.strictEqual(sub(-2, 2), -4)
assert.strictEqual(sub(rand, rand), rand - rand)
// End of tests */
|
import React, { Component } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Tabs, Button, Table,Modal } from 'antd';
import router from 'umi/router';
const TabPane = Tabs.TabPane;
function callback(key) {
console.log(key);
}
function goRegistration() {
router.push("/casehistory/casesend");
}
@connect(registration => {
return {
registration,
};
})
class Registration extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
data: [],//用户列表
index: 0,
popupsData: [],//弹出层数据
columns:[{
title: '用户名',
dataIndex: 'rid',
}, {
title: '患者姓名',
className: 'keshi',
dataIndex: 'r_uid',
}, {
title: '挂号医生',
dataIndex: 'r_did',
}, {
title: '挂号日期',
dataIndex: 'r_time',
}, {
title: 'Action',
dataIndex: '',
render: (text,record) => {
return (
<div>
<Button type="primary" onClick={() => {
this.showModal(record.rid);
}}>查看详情{record.name}</Button>
<Button style={{ marginLeft: '10px' }} type="primary" onClick={goRegistration}>发布病例</Button>
</div>
)
}
}]
};
}
showPopups = (data) => {
let arr = data.list.map(function (obj, index) {
return (
<div key={index}>
<p>用户名:{obj.rid}</p>
<p>患者姓名:{obj.r_uid}</p>
<p>挂号医生</p>
</div>
)
})
// console.log(arr)
this.setState({
popupsData: arr
})
}
showModal = (data) => {
let popupsIndex;//弹出层对应索引
this.state.data.forEach(function (obj, index) {
if (obj.rid == data) {
popupsIndex = index;
}
});
console.log(popupsIndex);
this.setState({
visible: true,
index: popupsIndex
});
}
handleOk = (e) => {
this.setState({
visible: false,
});
}
handleCancel = (e) => {
this.setState({
visible: false,
});
}
componentDidMount() {
const { dispatch } = this.props;
dispatch({
type: 'registration/gets',
payload: {},
});
}
componentWillReceiveProps() {
console.log(this.props.registration.registration)
this.setState({
data: [...this.props.registration.registration.list]
})
this.showPopups(this.props.registration.registration);
}
render() {
let arr = this.state.data;
return <div>
<PageHeaderWrapper title="挂号列表"></PageHeaderWrapper>
<Tabs defaultActiveKey="1" onChange={callback}>
<TabPane tab="当前挂号" key="1">
<Table
columns={this.state.columns}
dataSource={arr}
bordered
/>
</TabPane>
<TabPane tab="往期挂号" key="2">
<Table
columns={this.state.columns}
dataSource={arr}
bordered
/>
</TabPane>
</Tabs>,
<Modal
title="详情信息"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
{this.state.popupsData[this.state.index]}
</Modal>
</div>;
}
}
export default Registration;
|
var cache_manager = require('cache-manager');
var s3 = new (require('aws-sdk')).S3({params:{Bucket: process.env.S3_BUCKET_NAME}});
module.exports = {
init: function() {
this.cache = cache_manager.caching({
store: s3_cache, ttl: 10/*seconds*/
});
},
beforePhantomRequest: function(req, res, next) {
if(req.method !== 'GET') {
return next();
}
this.cache.get(req.prerender.url, function (err, result) {
if (!err && result) {
console.log('cache hit');
res.send(200, result.Body);
} else {
next();
}
});
},
afterPhantomRequest: function(phantom, context, next) {
this.cache.set(context.request.url, context.response.documentHTML);
next();
}
}
var s3_cache = {
get: function(key, callback) {
if (process.env.S3_PREFIX_KEY) {
key = process.env.S3_PREFIX_KEY + '/' + key;
}
s3.getObject({
Key: key
}, callback);
},
set: function(key, value, callback) {
if (process.env.S3_PREFIX_KEY) {
key = process.env.S3_PREFIX_KEY + '/' + key;
}
var request = s3.putObject({
Key: key,
ContentType: 'text/html;charset=UTF-8',
StorageClass: 'REDUCED_REDUNDANCY',
Body: value
}, callback);
if (!callback) {
request.send();
}
}
}
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateStream = exports.viewStream = exports.createStream = void 0;
const stream_tile_1 = require("@ceramicnetwork/stream-tile");
const http_client_1 = __importDefault(require("@ceramicnetwork/http-client"));
const key_did_provider_ed25519_1 = require("key-did-provider-ed25519");
const _3id_did_resolver_1 = __importDefault(require("@ceramicnetwork/3id-did-resolver"));
const key_did_resolver_1 = __importDefault(require("key-did-resolver"));
const did_resolver_1 = require("did-resolver");
const dids_1 = require("dids");
const utils_1 = require("dids/lib/utils");
// TODO(gabe) allow these to be set from config
const knownCeramicUri = 'https://ceramic-clay.3boxlabs.com';
const knownEncodedSeed = '7Qn5djvQ0KidtdAygpeKjznabVzn6CrRAgASIBevP3o=';
// Connect to the remote Ceramic node
const ceramic = new http_client_1.default(knownCeramicUri);
/**
* Create a stream with a description and uri
*/
function createStream(description, contentUri) {
return __awaiter(this, void 0, void 0, function* () {
// console.debug('creating stream with schema - %s - %s', desc, uri)
yield authenticateCeramic();
// create a tile document stream and pin it
const content = generateCommitData(description, contentUri);
const doc = yield stream_tile_1.TileDocument.create(ceramic, content, undefined, { pin: true });
return doc.id.toString();
});
}
exports.createStream = createStream;
/**
* View a stream
* Able to do three possible things:
* (1) view information about a stream including its controllers and commits
* (2) view a specific commit id for a stream
* (3) view information from the latest commit in a stream
*/
function viewStream(streamId, commitId, latest) {
return __awaiter(this, void 0, void 0, function* () {
// console.debug('viewing stream with id-commitId-latest', streamId, commitId, latest)
yield authenticateCeramic();
if (commitId !== undefined) {
console.log('Viewing commit %s', commitId);
const loaded = yield stream_tile_1.TileDocument.load(ceramic, commitId);
const extracted = extractOracleCommit(loaded);
console.log(extracted);
return;
}
const loaded = yield stream_tile_1.TileDocument.load(ceramic, streamId);
if (latest) {
console.log('Viewing latest commit for stream %s', streamId);
const extracted = extractOracleCommit(loaded);
console.log(extracted);
}
else {
console.log('Viewing stream:', streamId);
console.log('Controllers:', loaded.metadata.controllers);
console.log('Commits:', loaded.allCommitIds.map(c => c.toString()));
}
});
}
exports.viewStream = viewStream;
/**
* Update a stream with a description and uri
*/
function updateStream(streamId, description, contentUri) {
return __awaiter(this, void 0, void 0, function* () {
// console.debug('updating stream %s-%s-%s', streamId, description, contentUri)
if (description === undefined || contentUri === undefined) {
console.log('must have both --description and --contentUri flags set');
return;
}
yield authenticateCeramic();
// load stream, generate new commit data
const loaded = yield stream_tile_1.TileDocument.load(ceramic, streamId);
const content = generateCommitData(description, contentUri);
// update the document with the commit content
yield loaded.update(content);
// load the updated stream and read back the last written record
const updated = yield stream_tile_1.TileDocument.load(ceramic, streamId);
console.log('Updated stream, latest commit: ', updated.content);
});
}
exports.updateStream = updateStream;
// `seed` must be a 32-byte long Uint8Array
function authenticateCeramic() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const seed = (0, utils_1.decodeBase64)(knownEncodedSeed);
// Provide the DID Resolver and Provider to Ceramic
const resolver = new did_resolver_1.Resolver(Object.assign(Object.assign({}, key_did_resolver_1.default.getResolver()), _3id_did_resolver_1.default.getResolver(ceramic)));
const provider = new key_did_provider_ed25519_1.Ed25519Provider(seed);
const did = new dids_1.DID({ provider, resolver });
yield ceramic.setDID(did);
// Authenticate the Ceramic instance with the provider
yield ((_a = ceramic.did) === null || _a === void 0 ? void 0 : _a.authenticate());
});
}
function generateCommitData(desc, uri) {
const timestamp = new Date().toISOString();
return {
createdAt: timestamp,
description: desc,
contentUri: uri
};
}
// from a tile document, pull out our known content structure
function extractOracleCommit(doc) {
const loadedContent = JSON.stringify(doc.content);
const jsonContent = JSON.parse(loadedContent);
return {
createdAt: jsonContent.createdAt,
description: jsonContent.description,
contentUri: jsonContent.contentUri
};
}
|
import typescript from '@rollup/plugin-typescript'
import { terser } from 'rollup-plugin-terser'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import license from 'rollup-plugin-license'
import pkg from './package.json'
function licenseBanner() {
return license({
banner: {
content: { file: './LICENSE' }
}
})
}
const umdExternals = [
...Object.keys(pkg.peerDependencies || {}),
...Object.keys(pkg.optionalDependencies || {})
]
const externals = [...Object.keys(pkg.dependencies || {}), ...umdExternals]
const globals = {
cssesc: 'cssesc',
jspdf: 'jspdf',
svgpath: 'svgpath'
}
const umd = {
input: 'src/svg2pdf.ts',
output: [
{
file: pkg.browser.replace('.es.min.', '.umd.'),
format: 'umd',
name: 'svg2pdf',
exports: 'named',
sourcemap: true,
globals
},
{
file: pkg.browser.replace('.es.', '.umd.'),
format: 'umd',
name: 'svg2pdf',
exports: 'named',
sourcemap: true,
globals,
plugins: [terser({})]
}
],
external: umdExternals,
plugins: [typescript(), commonjs({ extensions: ['.js', '.ts'] }), resolve(), licenseBanner()]
}
const es = {
input: 'src/svg2pdf.ts',
output: [
{
file: pkg.module.replace('.min', ''),
format: 'es',
name: 'svg2pdf',
sourcemap: true,
plugins: []
},
{
file: pkg.module,
format: 'es',
name: 'svg2pdf',
sourcemap: true,
plugins: [terser({})]
}
],
external: externals,
plugins: [typescript(), commonjs({ extensions: ['.js', '.ts'] }), resolve(), licenseBanner()]
}
export default [umd, es]
|
NEWSCHEMA('Settings/TotalAPI', function(schema) {
schema.define('totalapi', 'String(100)', true);
schema.addWorkflow('exec', function($, model) {
if (UNAUTHORIZED($))
return;
TotalAPI(model.totalapi, 'check', EMPTYOBJECT, $.callback);
});
});
|
window.onload = async () => {
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
while (document.querySelector(".container__YPDh") == undefined) {
await delay(1000);
}
document.querySelector(".container__YPDh").style.fontSize = "18px";
};
|
# Copyright 2019 The Forte Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for ag_news_reader.
"""
import os
import unittest
from typing import Dict
from forte.pipeline import Pipeline
from ft.onto.ag_news import Description
from ft.onto.base_ontology import Document, Title
from forte.data.readers import AGNewsReader
from forte.data.data_pack import DataPack
class AGNewsReaderTest(unittest.TestCase):
def setUp(self):
self.pipeline = Pipeline()
self.pipeline.set_reader(AGNewsReader())
self.pipeline.initialize()
self.sample_file: str = os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
*([os.path.pardir] * 4),
"data_samples/ag_news/sample.csv"
)
)
self.expected_content: Dict[int, str] = {}
with open(self.sample_file, "r") as file:
for line_id, line in enumerate(file):
data = line.strip().split(",")
class_id, title, description = (
int(data[0].replace('"', "")),
data[1],
data[2],
)
self.expected_content[line_id] = (class_id, title, description)
self.class_idx_to_name = {
1: "World",
2: "Sports",
3: "Business",
4: "Sci/Tech",
}
def test_ag_news_reader(self):
for data_pack in self.pipeline.process_dataset(self.sample_file):
(
expected_class_id,
expected_title,
expected_desc,
) = self.expected_content[data_pack.pack_name]
self.assertIsInstance(data_pack, DataPack)
# Test Article
doc_entries = list(data_pack.get(Document))
self.assertTrue(len(doc_entries) == 1)
article: Document = doc_entries[0]
self.assertIsInstance(article, Document)
self.assertEqual(
article.text, expected_title + "\n" + expected_desc
)
# Test Document Class
doc_class = article.document_class
self.assertTrue(len(doc_class) == 1)
self.assertEqual(
doc_class[0], self.class_idx_to_name[expected_class_id]
)
# Test Title
title_entries = list(data_pack.get(Title))
self.assertTrue(len(title_entries) == 1)
title: Title = title_entries[0]
self.assertEqual(title.text, expected_title)
# Test Description
desc_entries = list(data_pack.get(Description))
self.assertTrue(len(desc_entries) == 1)
description: Description = desc_entries[0]
self.assertEqual(description.text, expected_desc)
if __name__ == "__main__":
unittest.main()
|
'use strict';
var React = require('react/addons');
var AutomateActions = require('../actions/AutomateActions');
require('styles/AutomatRuleView.less');
var AutomatRuleView = React.createClass({
onMyClick: function() {
AutomateActions.changeRule(this.props.rule.get('id'));
},
render: function () {
var ruleDigits = this.props.rule.get('id').split('');
var ruleItems = ruleDigits.map(function(ruleDigit, i) {
if (ruleDigit === '1') {
return <div className="black-rect-div" key={i}></div>;
} else {
return <div className="white-rect-div" key={i}></div>;
}
});
var ruleResult;
if (this.props.rule.get('result') === '1') {
ruleResult = <div className="black-rect-div"></div>;
} else {
ruleResult = <div className="white-rect-div"></div>;
}
return (
<td className="AutomatRuleView">
<div className="text-nowrap">
{ruleItems}
</div>
<div className="clickable" onClick={this.onMyClick}>
{ruleResult}
</div>
</td>
);
}
});
module.exports = AutomatRuleView;
|
const express = require("express"); // NodeJS Framework
const app = express(); // Init the EXPRESS App
const server = require("http").Server(app); // Init the HTTP Server with the EXPRESS App
const port = process.env.PORT || 8080; // Define the Port
const io = require("socket.io")(server); // Init the Socket.io Library
const { v4: uuidv4 } = require("uuid"); // Unique ID
const { ExpressPeerServer } = require("peer"); // Include PeerJS
const peerServer = ExpressPeerServer(server, {
// Initialize the PeerJS Server
debug: true,
});
server.listen(port); // Port to Launch the Server ON
console.log("Listening on localhost:" + port);
app.set("view engine", "ejs"); // Use EJS
app.use(express.static("public"));
app.use("/peerjs", peerServer); // Use PeerJS
app.get("/", (req, res) => {
// Get the files for App e.i. '/'=root
res.redirect(`/${uuidv4()}`); // Generate Unique ID (uuidv4)
});
app.get("/:room", (req, res) => {
res.render("room", { roomId: req.params.room }); // Get Room ID in URL
});
io.on("connection", (socket) => {
socket.on("join-room", (roomId, userId) => {
socket.join(roomId);
socket.broadcast.to(roomId).emit("user-connected", userId);
socket.on("message", (message) => {
io.to(roomId).emit("createMessage", message);
});
socket.on("disconnect", () => {
socket.broadcast.to(roomId).emit("user-disconnected", userId);
});
});
});
|
# Copyright 2020 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.
# ==============================================================================
# Lint as: python3
"""Gradient-based attribution."""
from typing import cast, List, Text, Optional
from absl import logging
from lit_nlp.api import components as lit_components
from lit_nlp.api import dataset as lit_dataset
from lit_nlp.api import dtypes
from lit_nlp.api import model as lit_model
from lit_nlp.api import types
from lit_nlp.components.citrus import utils as citrus_utils
from lit_nlp.lib import utils
import numpy as np
JsonDict = types.JsonDict
Spec = types.Spec
class GradientNorm(lit_components.Interpreter):
"""Salience map from gradient L2 norm."""
def find_fields(self, output_spec: Spec) -> List[Text]:
# Find TokenGradients fields
grad_fields = utils.find_spec_keys(output_spec, types.TokenGradients)
# Check that these are aligned to Tokens fields
for f in grad_fields:
tokens_field = output_spec[f].align # pytype: disable=attribute-error
assert tokens_field in output_spec
assert isinstance(output_spec[tokens_field], types.Tokens)
return grad_fields
def _interpret(self, grads: np.ndarray, tokens: np.ndarray):
assert grads.shape[0] == len(tokens)
# Norm of dy/d(embs)
grad_norm = np.linalg.norm(grads, axis=1)
grad_norm /= np.sum(grad_norm)
# <float32>[num_tokens]
return grad_norm
def run(self,
inputs: List[JsonDict],
model: lit_model.Model,
dataset: lit_dataset.Dataset,
model_outputs: Optional[List[JsonDict]] = None,
config: Optional[JsonDict] = None) -> Optional[List[JsonDict]]:
"""Run this component, given a model and input(s)."""
# Find gradient fields to interpret
output_spec = model.output_spec()
grad_fields = self.find_fields(output_spec)
logging.info('Found fields for gradient attribution: %s', str(grad_fields))
if len(grad_fields) == 0: # pylint: disable=g-explicit-length-test
return None
# Run model, if needed.
if model_outputs is None:
model_outputs = list(model.predict(inputs))
assert len(model_outputs) == len(inputs)
all_results = []
for o in model_outputs:
# Dict[field name -> interpretations]
result = {}
for grad_field in grad_fields:
token_field = cast(types.TokenGradients, output_spec[grad_field]).align
tokens = o[token_field]
scores = self._interpret(o[grad_field], tokens)
result[grad_field] = dtypes.SalienceMap(tokens, scores)
all_results.append(result)
return all_results
class GradientDotInput(lit_components.Interpreter):
"""Salience map using the values of gradient * input as attribution."""
def find_fields(self, input_spec: Spec, output_spec: Spec) -> List[Text]:
# Find TokenGradients fields
grad_fields = utils.find_spec_keys(output_spec, types.TokenGradients)
# Check that these are aligned to Tokens fields
aligned_fields = []
for f in grad_fields:
tokens_field = output_spec[f].align # pytype: disable=attribute-error
assert tokens_field in output_spec
assert isinstance(output_spec[tokens_field], types.Tokens)
embeddings_field = output_spec[f].grad_for
if embeddings_field is not None:
assert embeddings_field in input_spec
assert isinstance(input_spec[embeddings_field], types.TokenEmbeddings)
assert embeddings_field in output_spec
assert isinstance(output_spec[embeddings_field], types.TokenEmbeddings)
aligned_fields.append(f)
else:
logging.info('Skipping %s since embeddings field not found.', str(f))
return aligned_fields
def _interpret(self, grads: np.ndarray, embs: np.ndarray):
assert grads.shape == embs.shape
# dot product of gradients and embeddings
# <float32>[num_tokens]
grad_dot_input = np.sum(grads * embs, axis=-1)
scores = citrus_utils.normalize_scores(grad_dot_input)
return scores
def run(self,
inputs: List[JsonDict],
model: lit_model.Model,
dataset: lit_dataset.Dataset,
model_outputs: Optional[List[JsonDict]] = None,
config: Optional[JsonDict] = None) -> Optional[List[JsonDict]]:
"""Run this component, given a model and input(s)."""
# Find gradient fields to interpret
input_spec = model.input_spec()
output_spec = model.output_spec()
grad_fields = self.find_fields(input_spec, output_spec)
logging.info('Found fields for gradient attribution: %s', str(grad_fields))
if len(grad_fields) == 0: # pylint: disable=g-explicit-length-test
return None
# Run model, if needed.
if model_outputs is None:
model_outputs = list(model.predict(inputs))
assert len(model_outputs) == len(inputs)
all_results = []
for o in model_outputs:
# Dict[field name -> interpretations]
result = {}
for grad_field in grad_fields:
embeddings_field = cast(types.TokenGradients,
output_spec[grad_field]).grad_for
scores = self._interpret(o[grad_field], o[embeddings_field])
token_field = cast(types.TokenGradients, output_spec[grad_field]).align
tokens = o[token_field]
result[grad_field] = dtypes.SalienceMap(tokens, scores)
all_results.append(result)
return all_results
class IntegratedGradients(lit_components.Interpreter):
"""Salience map from Integrated Gradients.
Integrated Gradients is an attribution method originally proposed in
Sundararajan et al. (https://arxiv.org/abs/1703.01365), which attributes an
importance value for each input feature based on the gradients of the model
output with respect to the input. The feature attribution values are
calculated by taking the integral of gradients along a straight path from a
baseline to the input being analyzed. The original implementation can be
found at: https://github.com/ankurtaly/Integrated-Gradients/blob/master/
BertModel/bert_model_utils.py
This component requires that the following fields in the model spec. Field
names like `embs` are placeholders; you can call them whatever you like,
and as with other LIT components multiple segments are supported.
Output:
- TokenEmbeddings (`embs`) to return the input embeddings
- TokenGradients (`grads`) to return gradients w.r.t. `embs`
- A label field (`target`) to return the label that `grads`
was computed for. This is usually a CategoryLabel, but can be anything
since it will just be fed back into the model.
Input
- TokenEmbeddings (`embs`) to accept the modified input embeddings
- A label field to (`target`) to pin the gradient target to the same
label for all integral steps, since the argmax prediction may change.
"""
def __init__(self, interpolation_steps=30):
# TODO(b/168042999): Make this parameter configurable in the UI.
self.interpolation_steps = interpolation_steps
def find_fields(self, input_spec: Spec, output_spec: Spec) -> List[Text]:
# Find TokenGradients fields
grad_fields = utils.find_spec_keys(output_spec, types.TokenGradients)
# Check that these are aligned to Tokens fields
aligned_fields = []
for f in grad_fields:
tokens_field = output_spec[f].align # pytype: disable=attribute-error
assert tokens_field in output_spec
assert isinstance(output_spec[tokens_field], types.Tokens)
embeddings_field = output_spec[f].grad_for
grad_class_key = output_spec[f].grad_target
if embeddings_field is not None and grad_class_key is not None:
assert embeddings_field in input_spec
assert isinstance(input_spec[embeddings_field], types.TokenEmbeddings)
assert embeddings_field in output_spec
assert isinstance(output_spec[embeddings_field], types.TokenEmbeddings)
assert grad_class_key in input_spec
assert grad_class_key in output_spec
aligned_fields.append(f)
else:
logging.info('Skipping %s since embeddings field not found.', str(f))
return aligned_fields
def get_interpolated_inputs(self, baseline: np.ndarray, target: np.ndarray,
num_steps: int) -> np.ndarray:
"""Gets num_step linearly interpolated inputs from baseline to target."""
if num_steps <= 0: return np.array([])
if num_steps == 1: return np.array([baseline, target])
delta = target - baseline # <float32>[num_tokens, emb_size]
# Creates scale values array of shape [num_steps, num_tokens, emb_dim],
# where the values in scales[i] are the ith step from np.linspace.
# <float32>[num_steps, 1, 1]
scales = np.linspace(0, 1, num_steps + 1,
dtype=np.float32)[:, np.newaxis, np.newaxis]
shape = (num_steps + 1,) + delta.shape
# <float32>[num_steps, num_tokens, emb_size]
deltas = scales * np.broadcast_to(delta, shape)
interpolated_inputs = baseline + deltas
return interpolated_inputs # <float32>[num_steps, num_tokens, emb_size]
def estimate_integral(self, path_gradients: np.ndarray) -> np.ndarray:
"""Estimates the integral of the path_gradients using trapezoid rule."""
path_gradients = (path_gradients[:-1] + path_gradients[1:]) / 2
# There are num_steps elements in the path_gradients. Summing num_steps - 1
# terms and dividing by num_steps - 1 is equivalent to taking
# the average.
return np.average(path_gradients, axis=0)
def get_baseline(self, embeddings: np.ndarray) -> np.ndarray:
"""Returns baseline embeddings to use in Integrated Gradients."""
# Replaces embeddings in the original input with the zero embedding, or
# with the specified token embedding.
baseline = np.zeros_like(embeddings)
# TODO(ellenj): Add option to use a token's embedding as the baseline.
return baseline
def get_salience_result(self, model_input: JsonDict, model: lit_model.Model,
model_output: JsonDict, grad_fields: List[Text]):
result = {}
output_spec = model.output_spec()
# We ensure that the embedding and gradient class fields are present in the
# model's input spec in find_fields().
embeddings_fields = [
cast(types.TokenGradients,
output_spec[grad_field]).grad_for for grad_field in grad_fields]
# The gradient class input is used to specify the target class of the
# gradient calculation (if unspecified, this option defaults to the argmax,
# which could flip between interpolated inputs).
grad_class_key = cast(types.TokenGradients,
output_spec[grad_fields[0]]).grad_target
# TODO(b/168042999): Add option to specify the class to explain in the UI.
grad_class = model_output[grad_class_key]
interpolated_inputs = {}
all_embeddings = []
all_baselines = []
for embed_field in embeddings_fields:
# <float32>[num_tokens, emb_size]
embeddings = np.array(model_output[embed_field])
all_embeddings.append(embeddings)
# Starts with baseline of zeros. <float32>[num_tokens, emb_size]
baseline = self.get_baseline(embeddings)
all_baselines.append(baseline)
# Get interpolated inputs from baseline to original embedding.
# <float32>[interpolation_steps, num_tokens, emb_size]
interpolated_inputs[embed_field] = self.get_interpolated_inputs(
baseline, embeddings, self.interpolation_steps)
# Create model inputs and populate embedding field(s).
inputs_with_embeds = []
for i in range(self.interpolation_steps):
input_copy = model_input.copy()
# Interpolates embeddings for all inputs simultaneously.
for embed_field in embeddings_fields:
# <float32>[num_tokens, emb_size]
input_copy[embed_field] = interpolated_inputs[embed_field][i]
input_copy[grad_class_key] = grad_class
inputs_with_embeds.append(input_copy)
embed_outputs = model.predict(inputs_with_embeds)
# Create list with concatenated gradients for each interpolate input.
gradients = []
for o in embed_outputs:
# <float32>[total_num_tokens, emb_size]
interp_gradients = np.concatenate([o[field] for field in grad_fields])
gradients.append(interp_gradients)
# <float32>[interpolation_steps, total_num_tokens, emb_size]
path_gradients = np.stack(gradients, axis=0)
# Calculate integral
# <float32>[total_num_tokens, emb_size]
integral = self.estimate_integral(path_gradients)
# <float32>[total_num_tokens, emb_size]
concat_embeddings = np.concatenate(all_embeddings)
# <float32>[total_num_tokens, emb_size]
concat_baseline = np.concatenate(all_baselines)
# <float32>[total_num_tokens, emb_size]
integrated_gradients = integral * (np.array(concat_embeddings) -
np.array(concat_baseline))
# Dot product of integral values and (embeddings - baseline).
# <float32>[total_num_tokens]
attributions = np.sum(integrated_gradients, axis=-1)
# TODO(b/168042999): Make normalization customizable in the UI.
# <float32>[total_num_tokens]
scores = citrus_utils.normalize_scores(attributions)
for grad_field in grad_fields:
# Format as salience map result.
token_field = cast(types.TokenGradients, output_spec[grad_field]).align
tokens = model_output[token_field]
# Only use the scores that correspond to the tokens in this grad_field.
# The gradients for all input embeddings were concatenated in the order
# of the grad fields, so they can be sliced out in the same order.
sliced_scores = scores[:len(tokens)] # <float32>[num_tokens in field]
scores = scores[len(tokens):] # <float32>[num_remaining_tokens]
assert len(tokens) == len(sliced_scores)
result[grad_field] = dtypes.SalienceMap(tokens, sliced_scores)
return result
def run(self,
inputs: List[JsonDict],
model: lit_model.Model,
dataset: lit_dataset.Dataset,
model_outputs: Optional[List[JsonDict]] = None,
config: Optional[JsonDict] = None) -> Optional[List[JsonDict]]:
"""Run this component, given a model and input(s)."""
# Find gradient fields to interpret
input_spec = model.input_spec()
output_spec = model.output_spec()
grad_fields = self.find_fields(input_spec, output_spec)
logging.info('Found fields for integrated gradients: %s', str(grad_fields))
if len(grad_fields) == 0: # pylint: disable=g-explicit-length-test
return None
# Run model, if needed.
if model_outputs is None:
model_outputs = list(model.predict(inputs))
all_results = []
for model_output, model_input in zip(model_outputs, inputs):
result = self.get_salience_result(model_input, model, model_output,
grad_fields)
all_results.append(result)
return all_results
|
# Generated by Django 2.0.5 on 2018-05-09 18:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date publised')),
],
),
migrations.AddField(
model_name='choice',
name='question',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
),
]
|
var KoolReport = KoolReport || {};
KoolReport.d3 = KoolReport.d3 || {};
KoolReport.d3.C3Chart = KoolReport.d3.C3Chart ||
function (settings) {
settings.data.onclick = this.onClick.bind(this);
this.settings = settings;
this.events = {};
this.c3chart = c3.generate(settings);
};
KoolReport.d3.C3Chart.prototype = {
settings: null,
c3chart: null,
events:null,
chart: function () {
return this.c3chart;
},
onClick:function(d,element){
var params = {};
// console.log(d);
// return;
switch(this.settings.data.type)
{
case "scatter":
var selectedRow = [
d.x,d.value
];
for(var i in this.settings.cKeys)
{
selectedRow[this.settings.cKeys[i]] = (i==0)?d.x:d.value;
}
params = {
selectedX:d.x,
selectedY:d.value,
selectedRow:selectedRow,
};
break;
case "gauge":
case "pie":
case "donut":
var selectedRow = this.settings.data.columns[d.index];
for(var i in this.settings.cKeys)
{
selectedRow[this.settings.cKeys[i]] = this.settings.data.columns[d.index][i];
}
params = {
selectedRowIndex:d.index,
selectedValue:d.value,
selectedRatio:d.ratio,
selectedRow:selectedRow,
};
break;
default:
var selectedRow = [];
// console.log(this.settings.cKeys);
this.settings.cKeys.forEach(function(v,i){
selectedRow.push(this.settings.data.json[d.index][v]);
selectedRow[v] = this.settings.data.json[d.index][v];
}.bind(this));
params = {
selectedRowIndex:d.index,
columnName:d.name,
selectedValue:d.value,
selectedRow:selectedRow,
};
}
this.fireEvent("itemSelect",params);
},
registerEvent:function(name,handler)
{
if(typeof this.events[name]=='undefined')
{
this.events[name] = [];
}
this.events[name].push(handler);
},
fireEvent:function(name,params)
{
if(typeof this.events[name]!='undefined')
{
for(var i in this.events[name])
{
this.events[name][i](params);
}
}
}
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from 'shared/invariant';
import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags';
import typeof * as ExportsType from './ReactFeatureFlags.test-renderer.www';
export const debugRenderPhaseSideEffectsForStrictMode = false;
export const enableUserTimingAPI = __DEV__;
export const warnAboutDeprecatedLifecycles = true;
export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
export const enableProfilerTimer = __PROFILE__;
export const enableProfilerCommitHooks = false;
export const enableSchedulerTracing = __PROFILE__;
export const enableSuspenseServerRenderer = false;
export const enableSelectiveHydration = false;
export const enableBlocksAPI = false;
export const warnAboutShorthandPropertyCollision = true;
export const enableSchedulerDebugging = false;
export const disableJavaScriptURLs = false;
export const disableInputAttributeSyncing = false;
export const enableDeprecatedFlareAPI = true;
export const enableFundamentalAPI = false;
export const enableScopeAPI = true;
export const enableUseEventAPI = false;
export const warnAboutUnmockedScheduler = true;
export const flushSuspenseFallbacksInTests = true;
export const enableSuspenseCallback = true;
export const warnAboutDefaultPropsOnFunctionComponents = false;
export const warnAboutStringRefs = false;
export const disableLegacyContext = false;
export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
export const enableTrustedTypesIntegration = false;
export const disableTextareaChildren = false;
export const disableMapsAsChildren = false;
export const disableModulePatternComponents = false;
export const warnUnstableRenderSubtreeIntoContainer = false;
export const deferPassiveEffectCleanupDuringUnmount = false;
export const runAllPassiveEffectDestroysBeforeCreates = false;
export const enableModernEventSystem = false;
export const warnAboutSpreadingKeyToJSX = false;
export const enableLegacyFBPrimerSupport = false;
// Internal-only attempt to debug a React Native issue. See D20130868.
export const throwEarlyForMysteriousError = false;
// Only used in www builds.
export function addUserTimingListener() {
invariant(false, 'Not implemented.');
}
// Flow magic to verify the exports of this file match the original version.
// eslint-disable-next-line no-unused-vars
type Check<_X, Y: _X, X: Y = _X> = null;
// eslint-disable-next-line no-unused-expressions
(null: Check<ExportsType, FeatureFlagsType>);
|
define(function(require) {
'use strict';
var CollapseActionView;
var AbstractActionView = require('oroui/js/app/views/jstree/abstract-action-view');
var _ = require('underscore');
var __ = require('orotranslation/js/translator');
CollapseActionView = AbstractActionView.extend({
options: _.extend({}, AbstractActionView.prototype.options, {
icon: 'minus-square-o',
label: __('oro.ui.jstree.actions.collapse')
}),
/**
* @inheritDoc
*/
constructor: function CollapseActionView() {
CollapseActionView.__super__.constructor.apply(this, arguments);
},
onClick: function() {
this.options.$tree.jstree('close_all');
}
});
return CollapseActionView;
});
|
// Generated by CoffeeScript 1.6.3
var SkeletonSync,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
SkeletonSync = (function() {
function SkeletonSync(skeleton, endpoint) {
this.skeleton = skeleton;
this.endpoint = endpoint != null ? endpoint : 'local';
this.onSocketMessage = __bind(this.onSocketMessage, this);
this.onSocketClosed = __bind(this.onSocketClosed, this);
this.onSocketOpened = __bind(this.onSocketOpened, this);
this.onSocketIOMessage = __bind(this.onSocketIOMessage, this);
this.socket = null;
this.reconnecting = false;
this.onUserIn = null;
this.onUserOut = null;
this.onRatio = null;
this.onDataUpdated = null;
}
SkeletonSync.prototype.connect = function() {
var _this = this;
if (this.endpoint === 'local') {
this.socket = new WebSocket('ws://kikko.local:9092');
this.socket.binaryType = 'arraybuffer';
this.socket.onopen = this.onSocketOpened;
this.socket.onclose = this.onSocketClosed;
return this.socket.onmessage = function(msg) {
return _this.onSocketMessage(msg.data);
};
} else {
this.socket = io.connect(this.endpoint);
this.socket.on('connect', this.onSocketOpened);
this.socket.on('message', this.onSocketMessage);
return this.socket.on('skeleton', function(data) {
if (data) {
_this.skeleton.data = data;
if (_this.onDataUpdated) {
return onDataUpdated();
}
}
});
}
};
SkeletonSync.prototype.onSocketIOMessage = function(data) {
return console.log('message');
};
SkeletonSync.prototype.onSocketOpened = function() {
return console.log("websocket connected");
};
SkeletonSync.prototype.onSocketClosed = function() {
var _this = this;
if (!this.reconnecting) {
console.log("websocket disconnected");
}
setTimeout(function() {
return _this.connect();
}, 2000);
return this.reconnecting = true;
};
SkeletonSync.prototype.onSocketMessage = function(data) {
var cmd;
if (data instanceof ArrayBuffer) {
this.skeleton.data = new Float32Array(data);
if (this.onDataUpdated) {
return onDataUpdated();
}
} else {
if (data === '/skeleton') {
} else {
cmd = data.split('/');
cmd.shift();
switch (cmd[0]) {
case 'user':
if (cmd[1] === 'in') {
if (this.onUserIn) {
return this.onUserIn(cmd[2]);
}
} else {
if (this.onUserOut) {
return this.onUserOut(cmd[2]);
}
}
break;
case 'ratio':
if (this.onRatio) {
return this.onRatio(parseFloat(cmd[1]) / parseFloat(cmd[2]));
}
break;
default:
return console.log(data);
}
}
}
};
return SkeletonSync;
})();
|
from datetime import timedelta
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from rules.contrib.views import PermissionRequiredMixin
from . import models
from .signals import invite_accepted
# Create your views here.
def get_invite_view_name_for_object(obj):
"""
Generates a view name from the content object.
NOTE: Must have a corresonding view in appropriate app.
"""
ct = ContentType.objects.get_for_model(obj)
view_name = "{}:{}_invite_list".format(ct.app_label, ct.name.lower())
return view_name
class CreateInvite(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):
"""
Creation view for a given invite.
"""
model = models.Invite
fields = ["label"]
permission_required = "invite.can_create" # Must be set for any related object
template_name = "invites/invite_create.html"
def dispatch(self, request, *args, **kwargs):
ct_pk = kwargs.pop("content_type", None)
obj_slug = kwargs.pop("slug", None)
self.ct = get_object_or_404(ContentType, id=ct_pk)
self.content_object = get_object_or_404(
self.ct.model_class(), slug=obj_slug
)
return super().dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["content_object"] = self.content_object
context["ct"] = self.ct.name.lower()
context[
self.ct.name.lower()
] = self.content_object # for a more friendly reference in template
return context
def get_permission_object(self):
return self.content_object
def form_valid(self, form):
invite = form.save(commit=False)
invite.creator = self.request.user
invite.expires_at = timezone.now() + timedelta(days=30)
invite.content_object = self.content_object
invite.save()
messages.success(self.request, _("Invite created!"))
return HttpResponseRedirect(
reverse_lazy(
get_invite_view_name_for_object(self.content_object),
kwargs={"slug": self.content_object.slug},
)
)
class InviteDeleteView(
LoginRequiredMixin, PermissionRequiredMixin, generic.edit.DeleteView
):
"""
View for deleting an invite object.
"""
model = models.Invite
permission_required = "invite.can_delete"
template_name = "invites/invite_delete.html"
slug_url_kwarg = "invite"
context_object_name = "invite"
def delete(self, request, *args, **kwargs):
messages.success(request, _("Invite deleted."))
obj = self.get_object()
view_name = get_invite_view_name_for_object(obj.content_object)
self.success_url = reverse_lazy(
view_name,
kwargs={"slug": obj.content_object.slug},
)
return super().delete(request, *args, **kwargs)
class InviteAcceptView(LoginRequiredMixin, generic.edit.UpdateView):
"""
View for accepting an invite.
"""
model = models.Invite
slug_url_kwarg = "invite"
context_object_name = "invite"
fields = ["status"]
template_name = "invites/invite_accept.html"
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
if self.object.status != "pending":
if self.object.status == "expired":
messages.error(
self.request, _("Sorry, this invite is already expired.")
)
else:
messages.error(
self.request,
_(
"This invite has already been accepted and cannot be used again."
),
)
return HttpResponseRedirect(reverse_lazy("home"))
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
self.model.objects.filter(
status="pending", expires_at__lte=timezone.now()
).update(status="expired")
return self.model.objects.all()
def get_success_url(self):
return self.object.content_object.get_absolute_url()
def form_valid(self, form):
self.object = form.save(commit=False)
if self.object.status != "accepted":
messages.error(
self.request,
_(
"It looks like someone may have been tampering with the form. Please try again, and no naughty business this time."
),
)
return self.form_invalid(form)
self.object.accepted_by = self.request.user
self.object.save()
invite_accepted.send(
models.Invite, invite=self.object, acceptor=self.request.user
)
return super().form_valid(form)
|
const { merge } = require('webpack-merge')
const common = require('./webpack.common.js')
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
})
|
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('<%= moduleName %>');
|
import React from 'react'
import MainNavbar from 'components/Navbars/MainNavbar.js'
import JobPostingHeader from 'components/Headers/JobPostingHeader'
import MainFooter from 'components/Footers/MainFooter'
import JobsForm from './AddJobs.js'
function JobPostings() {
document.documentElement.classList.remove('nav-open')
React.useEffect(() => {
document.body.classList.add('profile-page')
return function cleanup() {
document.body.classList.remove('profile-page')
}
})
return (
<>
<MainNavbar />
<JobPostingHeader />
<JobsForm />
<MainFooter />
</>
)
}
export default JobPostings
|
import DappLib from "@decentology/dappstarter-dapplib";
import DOM from "../../components/dom";
import { LitElement, html, customElement, property } from "lit-element";
@customElement("composer-page")
export default class ComposerPage extends LitElement {
@property()
get;
@property()
post;
@property()
title;
@property()
category;
@property()
description;
createRenderRoot() {
return this;
}
constructor(args) {
super(args);
this.apiUrl = 'http://localhost:5002/api/composer';
}
getModules() {
return[];
}
updateProject(moduleName, feature, option) {
let self = this;
fetch(`${this.apiUrl}/process/${moduleName}/${feature}/${option}`,
{
method: 'post',
body: JSON.stringify(DappLib.getManifest()),
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: { 'Content-Type': 'application/json' }
})
.then((response) => {
return response.json();
})
.then(function(data) {
console.log(data);
});
}
customizeModule(moduleName) {
let self = this;
let optionsHtml = '';
fetch(`${self.apiUrl}/info/${moduleName}`)
.then(response => response.json())
.then(config => {
let buttons = [];
for(let feature in config) {
let featureInfo = config[feature];
optionsHtml += `<h2 class="font-bold text-xl mb-0 mt-10">${ featureInfo.title } Options</h2>`;
featureInfo.options.forEach((option) => {
optionsHtml += `
<div class="bg-white rounded-lg shadow mt-10 p-10">
<h3 class="font-bold text-l">${ option.title }</h3>
<div class="mt-5 mb-5"><img src="data:image/jpeg;base64, ${option.preview}" alt="Preview" /></div>
<p class="text-gray-700 text-base mb-3">${ option.description }</p>
<button id="button-${option.name}"
@click=${(e) => { e.preventDefault(); self.updateProject(moduleName, feature, option.name); }}
class="self-end text-white font-bold py-2 px-8 rounded bg-green-500 hover:bg-green-700"}"
>
Update Project
</button>
</div>
`
buttons.push({ id: `button-${option.name}`, moduleName, feature, option: option.name })
});
}
document.getElementById('options').innerHTML = optionsHtml;
buttons.forEach((button) => {
document.getElementById(button.id).addEventListener('click', () => {
self.updateProject(button.moduleName, button.feature, button.option);
});
});
});
};
setPageLoader(name) {
let pageLoader = document.getElementById("page-loader");
pageLoader.load(name, this.getModules());
this.requestUpdate();
}
renderModuleView() {
let self = this;
return self.getModules().map(module =>
html`<li class="col-span-1 h-36">
<button
@click=${(e) => { e.preventDefault(); self.customizeModule(module.name.split('-')[1]); }}
class="self-end text-white font-bold py-2 px-8 rounded bg-green-500 hover:bg-green-700"}"
>
Customize ${module.title}
</button>
</li>`);
}
render() {
let content = html`
<div class="container m-auto">
<div class="row fadeIn mt-3 p-2 block">
<p class="mt-3">
Composable modules in your project appear here. Select a module to customize its features.
</p>
</div>
<ul class="mt-3 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
${ this.renderModuleView() }
</ul>
<div id="options" class="mt-3"></div>
</div>
`;
return content;
}
}
|
import { render } from '@testing-library/react'
import { MockedProvider } from '@apollo/client/testing'
jest.mock('@apollo/client', () => ({
__esModule: true,
...jest.requireActual('@apollo/client'),
useQuery: jest.fn()
}))
import { useQuery } from '@apollo/client'
jest.mock('react-i18next', () => ({
...jest.requireActual('react-i18next'),
useTranslation: jest.fn()
}))
import { useTranslation } from 'react-i18next'
jest.mock('./hooks', () => ({
useEditable: jest.fn()
}))
import { useEditable } from './hooks'
import AddReverseRecord from './AddReverseRecord'
import { getQueryName } from '../utils/graphql'
describe('getReverseRecord', () => {
it('should not lookup reverse record information if there is no address', async () => {
const props = {
account: '0xAccount',
currentAddress: null
}
useTranslation.mockImplementation(() => ({ t: () => null }))
useEditable.mockImplementation(() => ({
state: {
editing: null,
txHash: null,
pending: null,
confirmed: null
},
actions: {
startEditing: () => null,
stopEditing: () => null,
startPending: () => null,
setConfirmed: () => null
}
}))
let isSkipped = false
useQuery.mockImplementation((query, options) => {
const operationName = getQueryName(query)
switch (operationName) {
case 'getReverseRecord':
isSkipped = options.skip
return {
refetch: () => null,
data: {
getReverseRecord: 'vitalik.eth '
}
}
case 'getNamesFromSubgraph':
return {
refetch: () => null,
data: {}
}
default:
return {
refetch: () => null,
data: {}
}
}
return {}
})
const { rerender } = render(
<MockedProvider addTypename={false}>
<AddReverseRecord {...props} />
</MockedProvider>
)
expect(isSkipped).toBeTruthy()
props.currentAddress = '0xCurrentAddress'
rerender(
<MockedProvider addTypename={false}>
<AddReverseRecord {...props} />
</MockedProvider>
)
expect(isSkipped).toBeFalsy()
})
})
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __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;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 123);
/******/ })
/************************************************************************/
/******/ ({
/***/ "./resources/admin/metronic/js/pages/features/cards/draggable.js":
/*!***********************************************************************!*\
!*** ./resources/admin/metronic/js/pages/features/cards/draggable.js ***!
\***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar KTCardDraggable = function () {\n return {\n //main function to initiate the module\n init: function init() {\n var containers = document.querySelectorAll('.draggable-zone');\n\n if (containers.length === 0) {\n return false;\n }\n\n var swappable = new Sortable[\"default\"](containers, {\n draggable: '.draggable',\n handle: '.draggable .draggable-handle',\n mirror: {\n //appendTo: selector,\n appendTo: 'body',\n constrainDimensions: true\n }\n });\n }\n };\n}();\n\njQuery(document).ready(function () {\n KTCardDraggable.init();\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvYWRtaW4vbWV0cm9uaWMvanMvcGFnZXMvZmVhdHVyZXMvY2FyZHMvZHJhZ2dhYmxlLmpzP2M4NzQiXSwibmFtZXMiOlsiS1RDYXJkRHJhZ2dhYmxlIiwiaW5pdCIsImNvbnRhaW5lcnMiLCJkb2N1bWVudCIsInF1ZXJ5U2VsZWN0b3JBbGwiLCJsZW5ndGgiLCJzd2FwcGFibGUiLCJTb3J0YWJsZSIsImRyYWdnYWJsZSIsImhhbmRsZSIsIm1pcnJvciIsImFwcGVuZFRvIiwiY29uc3RyYWluRGltZW5zaW9ucyIsImpRdWVyeSIsInJlYWR5Il0sIm1hcHBpbmdzIjoiQUFBYTs7QUFFYixJQUFJQSxlQUFlLEdBQUcsWUFBVztBQUU3QixTQUFPO0FBQ0g7QUFDQUMsUUFBSSxFQUFFLGdCQUFXO0FBQ2IsVUFBSUMsVUFBVSxHQUFHQyxRQUFRLENBQUNDLGdCQUFULENBQTBCLGlCQUExQixDQUFqQjs7QUFFQSxVQUFJRixVQUFVLENBQUNHLE1BQVgsS0FBc0IsQ0FBMUIsRUFBNkI7QUFDekIsZUFBTyxLQUFQO0FBQ0g7O0FBRUQsVUFBSUMsU0FBUyxHQUFHLElBQUlDLFFBQVEsV0FBWixDQUFxQkwsVUFBckIsRUFBaUM7QUFDN0NNLGlCQUFTLEVBQUUsWUFEa0M7QUFFN0NDLGNBQU0sRUFBRSw4QkFGcUM7QUFHN0NDLGNBQU0sRUFBRTtBQUNKO0FBQ0FDLGtCQUFRLEVBQUUsTUFGTjtBQUdKQyw2QkFBbUIsRUFBRTtBQUhqQjtBQUhxQyxPQUFqQyxDQUFoQjtBQVNIO0FBbEJFLEdBQVA7QUFvQkgsQ0F0QnFCLEVBQXRCOztBQXdCQUMsTUFBTSxDQUFDVixRQUFELENBQU4sQ0FBaUJXLEtBQWpCLENBQXVCLFlBQVc7QUFDOUJkLGlCQUFlLENBQUNDLElBQWhCO0FBQ0gsQ0FGRCIsImZpbGUiOiIuL3Jlc291cmNlcy9hZG1pbi9tZXRyb25pYy9qcy9wYWdlcy9mZWF0dXJlcy9jYXJkcy9kcmFnZ2FibGUuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJcInVzZSBzdHJpY3RcIjtcblxudmFyIEtUQ2FyZERyYWdnYWJsZSA9IGZ1bmN0aW9uKCkge1xuXG4gICAgcmV0dXJuIHtcbiAgICAgICAgLy9tYWluIGZ1bmN0aW9uIHRvIGluaXRpYXRlIHRoZSBtb2R1bGVcbiAgICAgICAgaW5pdDogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICB2YXIgY29udGFpbmVycyA9IGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3JBbGwoJy5kcmFnZ2FibGUtem9uZScpO1xuXG4gICAgICAgICAgICBpZiAoY29udGFpbmVycy5sZW5ndGggPT09IDApIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIHZhciBzd2FwcGFibGUgPSBuZXcgU29ydGFibGUuZGVmYXVsdChjb250YWluZXJzLCB7XG4gICAgICAgICAgICAgICAgZHJhZ2dhYmxlOiAnLmRyYWdnYWJsZScsXG4gICAgICAgICAgICAgICAgaGFuZGxlOiAnLmRyYWdnYWJsZSAuZHJhZ2dhYmxlLWhhbmRsZScsXG4gICAgICAgICAgICAgICAgbWlycm9yOiB7XG4gICAgICAgICAgICAgICAgICAgIC8vYXBwZW5kVG86IHNlbGVjdG9yLFxuICAgICAgICAgICAgICAgICAgICBhcHBlbmRUbzogJ2JvZHknLFxuICAgICAgICAgICAgICAgICAgICBjb25zdHJhaW5EaW1lbnNpb25zOiB0cnVlXG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSk7XG4gICAgICAgIH1cbiAgICB9O1xufSgpO1xuXG5qUXVlcnkoZG9jdW1lbnQpLnJlYWR5KGZ1bmN0aW9uKCkge1xuICAgIEtUQ2FyZERyYWdnYWJsZS5pbml0KCk7XG59KTtcbiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/admin/metronic/js/pages/features/cards/draggable.js\n");
/***/ }),
/***/ 123:
/*!*****************************************************************************!*\
!*** multi ./resources/admin/metronic/js/pages/features/cards/draggable.js ***!
\*****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! D:\7.4\htdocs\ci-sia\resources\admin\metronic\js\pages\features\cards\draggable.js */"./resources/admin/metronic/js/pages/features/cards/draggable.js");
/***/ })
/******/ });
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
# We define our externals here instead of directly in WORKSPACE
def register_sorbet_dependencies():
http_archive(
name = "doctest",
urls = _github_public_urls("onqtam/doctest/archive/7d42bd0fab6c44010c8aed9338bd02bea5feba41.zip"),
sha256 = "b33c8e954d15a146bb744ca29f4ca204b955530f52b2f8a895746a99cee4f2df",
build_file = "@com_stripe_ruby_typer//third_party:doctest.BUILD",
strip_prefix = "doctest-7d42bd0fab6c44010c8aed9338bd02bea5feba41",
)
http_archive(
name = "dtl",
urls = _github_public_urls("cubicdaiya/dtl/archive/v1.19.tar.gz"),
sha256 = "f47b99dd11e5d771ad32a8dc960db4ab2fbe349fb0346fa0795f53c846a99c5d",
build_file = "@com_stripe_ruby_typer//third_party:dtl.BUILD",
strip_prefix = "dtl-1.19",
)
http_archive(
name = "yaml_cpp",
urls = _github_public_urls("jbeder/yaml-cpp/archive/yaml-cpp-0.6.3.zip"),
sha256 = "7c0ddc08a99655508ae110ba48726c67e4a10b290c214aed866ce4bbcbe3e84c",
build_file = "@com_stripe_ruby_typer//third_party:yaml_cpp.BUILD",
strip_prefix = "yaml-cpp-yaml-cpp-0.6.3",
)
http_archive(
name = "spdlog",
urls = _github_public_urls("gabime/spdlog/archive/c2b47430fb210c8822177407b9e4b82d4ef7455d.zip"), # v1.3.1
sha256 = "08b7e0f1d7c62a56dfbac5678979967690ccd9e074acd3762a2a49d8731961e6",
build_file = "@com_stripe_ruby_typer//third_party:spdlog.BUILD",
strip_prefix = "spdlog-c2b47430fb210c8822177407b9e4b82d4ef7455d",
)
# proto_library, cc_proto_library, and java_proto_library rules implicitly
# depend on @com_google_protobuf for protoc and proto runtimes.
# This statement defines the @com_google_protobuf repo.
http_archive(
name = "com_google_protobuf",
urls = _github_public_urls("protocolbuffers/protobuf/archive/v3.11.4.zip"),
sha256 = "9748c0d90e54ea09e5e75fb7fac16edce15d2028d4356f32211cfa3c0e956564",
strip_prefix = "protobuf-3.11.4",
)
http_archive(
name = "libprotobuf-mutator",
urls = _github_public_urls("google/libprotobuf-mutator/archive/68e10c13248517c5bcd531d0e02be483da83fc13.zip"),
sha256 = "8684276b996e8d8541ed3703420f9dbcc17702bd7b13c6f3d9c13a4656597c76",
build_file = "@com_stripe_ruby_typer//third_party:libprotobuf-mutator.BUILD",
strip_prefix = "libprotobuf-mutator-68e10c13248517c5bcd531d0e02be483da83fc13",
)
http_archive(
name = "lmdb",
urls = _github_public_urls("DarkDimius/lmdb/archive/75766ec2b663b360be8eea9730a7adc0d252ce7e.zip"),
sha256 = "bd120470d62c6f3433f80bb9841f09f158924081eb0c3236da6e8d1a0976eccc",
build_file = "@com_stripe_ruby_typer//third_party:lmdb.BUILD",
strip_prefix = "lmdb-75766ec2b663b360be8eea9730a7adc0d252ce7e",
)
http_archive(
name = "rapidjson",
urls = _github_public_urls("Tencent/rapidjson/archive/f376690822cbc2d17044e626be5df21f7d91ca8f.zip"),
sha256 = "9425276583dff9020cee6332472b0cf247ae325cb5f26dbe157183f747da3910",
build_file = "@com_stripe_ruby_typer//third_party:rapidjson.BUILD",
strip_prefix = "rapidjson-f376690822cbc2d17044e626be5df21f7d91ca8f",
)
http_archive(
name = "lizard",
urls = _github_public_urls("inikep/lizard/archive/dda3b335e92ecd5caceccc9c577b39dd4e3c9950.zip"),
sha256 = "1d4e8c17d40ec56b7ecad60bcf4a9065df73d7e5997f78e75dbe5fc662ce6aa8",
build_file = "@com_stripe_ruby_typer//third_party:lizard.BUILD",
strip_prefix = "lizard-dda3b335e92ecd5caceccc9c577b39dd4e3c9950",
)
http_archive(
name = "pdqsort",
urls = _github_public_urls("orlp/pdqsort/archive/08879029ab8dcb80a70142acb709e3df02de5d37.zip"),
sha256 = "ad8c9cd3d1abe5d566bad341bcce327a2e897b64236a7f9e74f4b9b0e7e5dc39",
build_file = "@com_stripe_ruby_typer//third_party:pdqsort.BUILD",
strip_prefix = "pdqsort-08879029ab8dcb80a70142acb709e3df02de5d37",
)
http_archive(
name = "jemalloc",
urls = _github_public_urls("jemalloc/jemalloc/archive/ea6b3e973b477b8061e0076bb257dbd7f3faa756.zip"), # 5.2.1
sha256 = "7822c5cb2d06a2665cdbbcd5d949f09b92ef5b891ad8354c6382a3614c9cc9cc",
build_file = "@com_stripe_ruby_typer//third_party:jemalloc.BUILD",
strip_prefix = "jemalloc-ea6b3e973b477b8061e0076bb257dbd7f3faa756",
)
http_archive(
name = "concurrentqueue",
urls = _github_public_urls("cameron314/concurrentqueue/archive/79cec4c3bf1ca23ea4a03adfcd3c2c3659684dd2.zip"),
sha256 = "a78ff232e2996927ad6fbd015d1f15dfb20bf524a87ce2893e64dbbe1f04051e",
build_file = "@com_stripe_ruby_typer//third_party:concurrentqueue.BUILD",
strip_prefix = "concurrentqueue-79cec4c3bf1ca23ea4a03adfcd3c2c3659684dd2",
)
http_archive(
name = "statsd",
urls = _github_public_urls("romanbsd/statsd-c-client/archive/0caa5ef05d6a786bb4695394534a7182a3c94427.zip"),
sha256 = "0c67e994fb809ac9b0fd2216333b0dff5592401f81dc04fb7a0c2179d6b76dca",
build_file = "@com_stripe_ruby_typer//third_party:statsd.BUILD",
strip_prefix = "statsd-c-client-0caa5ef05d6a786bb4695394534a7182a3c94427",
)
http_archive(
name = "cxxopts",
urls = _github_public_urls("jarro2783/cxxopts/archive/b0f67a06de3446aa97a4943ad0ad6086460b2b61.zip"),
sha256 = "8635d7305e6623e7f4c635dae901891eb1151cee3106445d124c696361bb70fc",
build_file = "@com_stripe_ruby_typer//third_party:cxxopts.BUILD",
strip_prefix = "cxxopts-b0f67a06de3446aa97a4943ad0ad6086460b2b61",
)
http_archive(
name = "rang",
urls = _github_public_urls("agauniyal/rang/archive/v3.1.0.zip"),
sha256 = "658adeb8a36d36981d4339fc839f2deedc0e75cb421db1982041d8a0a255835d",
build_file = "@com_stripe_ruby_typer//third_party:rang.BUILD",
strip_prefix = "rang-3.1.0",
)
http_archive(
name = "com_google_absl",
urls = _github_public_urls("abseil/abseil-cpp/archive/62f05b1f57ad660e9c09e02ce7d591dcc4d0ca08.zip"),
sha256 = "afcab9f226ac4ca6b6b7c9ec704a995fe32a6b555d6935b0de247ae6ac6940e0",
strip_prefix = "abseil-cpp-62f05b1f57ad660e9c09e02ce7d591dcc4d0ca08",
)
http_archive(
name = "compdb",
urls = _github_public_urls("grailbio/bazel-compilation-database/archive/0ae6349c52700f060c9a87c5ed2b04b75f94a26f.zip"),
sha256 = "40ad122fedbf2d8b23e70e16b5f49c1a316f02db3ed29ce1af8650dad6ccc1a9",
build_file_content = (
"""
package(default_visibility = ["//visibility:public"])
"""
),
strip_prefix = "bazel-compilation-database-0ae6349c52700f060c9a87c5ed2b04b75f94a26f",
)
# NOTE: using this branch:
# https://github.com/DarkDimius/bazel-toolchain/tree/dp-srb-now
http_archive(
name = "com_grail_bazel_toolchain",
urls = _github_public_urls("DarkDimius/bazel-toolchain/archive/e9d159aa3100905f83415c8a663627e74edaa4fd.zip"),
sha256 = "52d14c50a22de18a818f286a057d1ad5ef082b2980b2ad676f1e7db18edded63",
strip_prefix = "bazel-toolchain-e9d159aa3100905f83415c8a663627e74edaa4fd",
)
http_archive(
name = "io_bazel_rules_go",
urls = _github_public_urls("bazelbuild/rules_go/archive/dd4fb4f8128b83f189f7bdda663e65b915a6d3c4.zip"),
sha256 = "ea702009018b6a5d6665808a4d1f54e2f40a2938e3946e98de00d38b34fd8a27",
strip_prefix = "rules_go-dd4fb4f8128b83f189f7bdda663e65b915a6d3c4",
)
http_archive(
name = "com_github_bazelbuild_buildtools",
urls = _github_public_urls("bazelbuild/buildtools/archive/5bcc31df55ec1de770cb52887f2e989e7068301f.zip"),
sha256 = "875d0c49953e221cfc35d2a3846e502f366dfa4024b271fa266b186ca4664b37",
strip_prefix = "buildtools-5bcc31df55ec1de770cb52887f2e989e7068301f",
)
# optimized version of blake2 hashing algorithm
http_archive(
name = "com_github_blake2_libb2",
urls = _github_public_urls("BLAKE2/libb2/archive/fa83ddbe179912e9a7a57edf0333b33f6ff83056.zip"),
sha256 = "dd25f7ac53371c2a15761fc1689d04de2ff948ac7e213a10d13961e24b0c9ae6",
build_file = "@com_stripe_ruby_typer//third_party:libb2.BUILD",
strip_prefix = "libb2-fa83ddbe179912e9a7a57edf0333b33f6ff83056",
)
# portable reference implementation of blake2
http_archive(
name = "com_github_blake2_blake2",
urls = _github_public_urls("BLAKE2/BLAKE2/archive/997fa5ba1e14b52c554fb03ce39e579e6f27b90c.zip"),
sha256 = "56dafe9512f65728ce7abc78900272f8bf8e95ca04439b362d2dc461927b2a17",
build_file = "@com_stripe_ruby_typer//third_party:blake2.BUILD",
strip_prefix = "BLAKE2-997fa5ba1e14b52c554fb03ce39e579e6f27b90c",
)
http_archive(
name = "com_github_msgpack_msgpack",
urls = _github_public_urls("msgpack/msgpack-c/archive/7893d4d8c9ba8a8699c5c33152deaabf409250b3.zip"),
sha256 = "72dadac3def5180a701a3b251e9f1105c2b126907dc384d933370b7df5b73951",
build_file = "@com_stripe_ruby_typer//third_party:msgpack.BUILD",
strip_prefix = "msgpack-c-7893d4d8c9ba8a8699c5c33152deaabf409250b3",
)
http_archive(
name = "com_github_d_bahr_crcpp",
urls = _github_public_urls("d-bahr/CRCpp/archive/51fbc35ef892e98abe91a51f7320749c929d72bd.zip"),
sha256 = "57c4c127b5aa4451556969d6929cf9465a5d5481b3442ddb878d95296caeee4b",
build_file = "@com_stripe_ruby_typer//third_party:crcpp.BUILD",
strip_prefix = "CRCpp-51fbc35ef892e98abe91a51f7320749c929d72bd",
)
http_archive(
name = "emscripten_toolchain",
urls = _github_public_urls("kripken/emscripten/archive/1.38.25.tar.gz"),
build_file = "@com_stripe_ruby_typer//third_party:emscripten-toolchain.BUILD",
sha256 = "4d6fa350895fabc25b89ce5f9dcb528e719e7c2bf7dacab2a3e3cc818ecd7019",
strip_prefix = "emscripten-1.38.25",
)
http_archive(
name = "emscripten_clang_linux",
url = "https://storage.googleapis.com/webassembly/emscripten-releases-builds/old/linux/emscripten-llvm-e1.38.25.tar.gz",
build_file = "@com_stripe_ruby_typer//third_party:emscripten-clang.BUILD",
sha256 = "0e9a5a114a60c21604f4038b573109bd31424aeba275b4173480485ca0a56ba4",
strip_prefix = "emscripten-llvm-e1.38.25",
)
http_archive(
name = "emscripten_clang_darwin",
url = "https://storage.googleapis.com/webassembly/emscripten-releases-builds/old/mac/emscripten-llvm-e1.38.25.tar.gz",
build_file = "@com_stripe_ruby_typer//third_party:emscripten-clang.BUILD",
sha256 = "01519125c613d0b013193eaf5ac5031e6ec34aac2451c357fd4097874ceee38c",
strip_prefix = "emscripten-llvm-e1.38.25",
)
http_archive(
name = "rules_ragel",
urls = _github_public_urls("jmillikin/rules_ragel/archive/f99f17fcad2e155646745f4827ac636a3b5d4d15.zip"),
sha256 = "f957682c6350b2e4484c433c7f45d427a86de5c8751a0d2a9836f36995fe0320",
strip_prefix = "rules_ragel-f99f17fcad2e155646745f4827ac636a3b5d4d15",
)
http_archive(
name = "rules_bison",
urls = _github_public_urls("jmillikin/rules_bison/releases/download/v0.2/rules_bison-v0.2.tar.xz"),
sha256 = "6ee9b396f450ca9753c3283944f9a6015b61227f8386893fb59d593455141481",
)
http_archive(
name = "rules_m4",
urls = _github_public_urls("jmillikin/rules_m4/releases/download/v0.2/rules_m4-v0.2.tar.xz"),
sha256 = "c67fa9891bb19e9e6c1050003ba648d35383b8cb3c9572f397ad24040fb7f0eb",
)
http_archive(
name = "cpp_subprocess",
urls = _github_public_urls("arun11299/cpp-subprocess/archive/9c624ce4e3423cce9f148bafbae56abfd6437ea0.zip"),
sha256 = "1810d1ec80f3c319dcbb530443b264b9a32a449b5a5d3630076e473648bba8cc",
build_file = "@com_stripe_ruby_typer//third_party:cpp_subprocess.BUILD",
strip_prefix = "cpp-subprocess-9c624ce4e3423cce9f148bafbae56abfd6437ea0",
)
http_file(
name = "bundler_2_1_4",
urls = ["https://rubygems.org/downloads/bundler-2.1.4.gem"],
sha256 = "50014d21d6712079da4d6464de12bb93c278f87c9200d0b60ba99f32c25af489",
)
http_archive(
name = "ruby_2_5",
url = "https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.8.tar.gz",
sha256 = "6c0bdf07876c69811a9e7dc237c43d40b1cb6369f68e0e17953d7279b524ad9a",
strip_prefix = "ruby-2.5.8",
build_file = "@com_stripe_ruby_typer//third_party/ruby:ruby.BUILD",
)
http_archive(
name = "ruby_2_6",
url = "https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.5.tar.gz",
sha256 = "66976b716ecc1fd34f9b7c3c2b07bbd37631815377a2e3e85a5b194cfdcbed7d",
strip_prefix = "ruby-2.6.5",
build_file = "@com_stripe_ruby_typer//third_party/ruby:ruby.BUILD",
)
native.new_local_repository(
name = "system_ssl_darwin",
path = "/usr/local/opt/openssl",
build_file = "@com_stripe_ruby_typer//third_party/openssl:darwin.BUILD",
)
native.new_local_repository(
name = "system_ssl_linux",
path = "/usr",
build_file = "@com_stripe_ruby_typer//third_party/openssl:linux.BUILD",
)
def _github_public_urls(path):
"""
Produce a url list that works both with github, and stripe's internal artifact cache.
"""
return [
"https://github.com/{}".format(path),
"https://artifactory-content.stripe.build/artifactory/github-archives/{}".format(path),
]
|
// Copyright (c) 2019 Magic Leap, Inc. All Rights Reserved
import log, { MessageSeverity } from '../../../util/logger.js';
import { PrismController } from 'lumin';
import { ReactMagicScript } from '../../../react-magic-script/react-magic-script.js';
import { ControlPose3DofInputEventData } from '../types/event-data/control-pose-3dof-Input-event-data.js';
import { ControlPose6DofInputEventData } from '../types/event-data/control-pose-6dof-input-event-data.js';
import { ControlTouchPadInputEventData } from '../types/event-data/control-touch-pad-input-event-data.js';
import { EyeTrackingEventData } from '../types/event-data/eye-tracking-event-data.js';
import { GestureInputEventData } from '../types/event-data/gesture-input-event-data.js';
import { InputEventData } from '../types/event-data/input-event-data.js';
import { KeyInputEventData } from '../types/event-data/key-input-event-data.js';
import { RayCastEventData } from '../types/event-data/ray-cast-event-data.js';
import { SelectionEventData } from '../types/event-data/selection-event-data.js';
import { UiEventData } from '../types/event-data/ui-event-data.js';
import { VideoEventData } from '../types/event-data/video-event-data.js';
import { WorldImageTrackingEventData } from '../types/event-data/world-image-tracking-event-data.js';
export class AppPrismController extends PrismController {
constructor (prismProps) {
super();
this._prismProps = prismProps;
this._containers = new WeakMap();
this._eventHandlers = {
onEvent: [],
onUpdate: []
};
this._eventTypes = [
ControlPose3DofInputEventData,
ControlPose6DofInputEventData,
ControlTouchPadInputEventData,
EyeTrackingEventData,
GestureInputEventData,
InputEventData,
KeyInputEventData,
RayCastEventData,
SelectionEventData,
UiEventData,
VideoEventData,
WorldImageTrackingEventData
];
this._eventTypes.forEach(eventDataConstructor => {
this._eventHandlers[this._getEventTypeName(eventDataConstructor.name)] = [];
});
}
getRootNodeName (componentName) {
return componentName === undefined
? '__root_prism_controller_'
: `__root_prism_controller_${componentName.trim().replace(' ', '_')}`;
}
findChild (nodeName) {
const root = this.getRoot();
return root.getName() === nodeName ? root : root.findChild(nodeName);
}
getContainer (nodeName) {
const parent = nodeName === undefined
? this.getRoot()
: this.findChild(nodeName);
let container = this._containers[parent];
if (container === undefined) {
container = { parent: parent, controller: this };
this._containers[parent] = container;
}
return container;
}
onAttachPrism (prism) {
const rootNodeName = this.getRootNodeName(this._prismProps.name);
this.getRoot().setName(rootNodeName);
try {
ReactMagicScript.render(this._prismProps.children, this.getContainer());
} catch (error) {
log(`${error.name} - ${error.message}\n${error.stack}`, MessageSeverity.exception);
throw error;
}
}
onDetachPrism (prism) {
this.deleteSceneGraph();
}
addListener (nodeId, event, eventHandlerCallback) {
const handlers = this._eventHandlers[event];
if (handlers !== undefined) {
handlers.push({ id: nodeId, handler: eventHandlerCallback });
} else {
throw TypeError(`Event ${event} is not supported by the controller`);
}
}
removeListener (nodeId, event, eventHandlerCallback) {
const handlers = this._eventHandlers[event];
if (handlers !== undefined) {
const index = handlers.findIndex(subscriber => subscriber.id === nodeId && subscriber.handler === eventHandlerCallback);
if (index !== -1) {
handlers.splice(index, 1);
}
} else {
throw TypeError(`Event ${event} is not supported by the controller`);
}
}
onEvent (event) {
const eventData = this._getEventDataByEventType(event);
let handlers = this._eventHandlers[this._getEventTypeName(eventData.constructor.name)];
if (!Array.isArray(handlers) || handlers.length === 0) {
handlers = this._eventHandlers.onEvent;
}
let eventIsConsumed = false;
for (let subscriber of handlers) {
if (eventIsConsumed === true) {
break;
}
if (typeof event.getAffectedNodeId === 'function') {
if (subscriber.id === event.getAffectedNodeId()) {
eventIsConsumed = subscriber.handler(eventData);
}
} else {
eventIsConsumed = subscriber.handler(eventData);
}
}
return eventIsConsumed;
}
onUpdate (delta) {
this._eventHandlers.onUpdate
.forEach(subscriber => subscriber.handler(delta));
}
_getEventDataByEventType (eventData) {
const eventConstructor = this._eventTypes
.find(eventType => eventType.isSupported(eventData));
return eventConstructor === undefined
? eventData
: new eventConstructor(eventData);
}
_getEventTypeName (eventDataTypeName) {
// Remove suffix 'Data' from the event data type name
return `on${eventDataTypeName.slice(0, -4)}`;
}
}
|
import argparse
import os
from nst import neural_style_transfer
if __name__ == "__main__":
#
# fixed args - don't change these unless you have a good reason
#
default_resource_dir = os.path.join(os.path.dirname(__file__), "data")
content_images_dir = os.path.join(default_resource_dir, "content-images")
style_images_dir = os.path.join(default_resource_dir, "style-images")
output_img_dir = os.path.join(default_resource_dir, "output-images")
img_format = (4, ".jpg") # saves images in the format: %04d.jpg
#
# modifiable args - feel free to play with these (only small subset is exposed by design to avoid cluttering)
# sorted so that the ones on the top are more likely to be changed than the ones on the bottom
#
parser = argparse.ArgumentParser()
parser.add_argument(
"--content_img_name", type=str, help="content image name", default="figures.jpg"
)
parser.add_argument(
"--style_img_name",
type=str,
help="style image name",
default="vg_starry_night.jpg",
)
parser.add_argument(
"--height", type=int, help="height of content and style images", default=400
)
parser.add_argument(
"--content_weight",
type=float,
help="weight factor for content loss",
default=1e5,
)
parser.add_argument(
"--style_weight", type=float, help="weight factor for style loss", default=3e4
)
parser.add_argument(
"--tv_weight",
type=float,
help="weight factor for total variation loss",
default=1e0,
)
parser.add_argument(
"--optimizer", type=str, choices=["lbfgs", "adam"], default="lbfgs"
)
parser.add_argument("--iterations", type=int, default=1000)
parser.add_argument(
"--model", type=str, choices=["vgg16", "vgg19"], default="vgg19"
)
parser.add_argument(
"--init_method",
type=str,
choices=["random", "content", "style"],
default="content",
)
parser.add_argument(
"--saving_freq",
type=int,
help="saving frequency for intermediate images (-1 means only final)",
default=-1,
)
args = parser.parse_args()
# some values of weights that worked for figures.jpg, vg_starry_night.jpg (starting point for finding good images)
# once you understand what each one does it gets really easy -> also see README.md
# lbfgs, content init -> (cw, sw, tv) = (1e5, 3e4, 1e0)
# lbfgs, style init -> (cw, sw, tv) = (1e5, 1e1, 1e-1)
# lbfgs, random init -> (cw, sw, tv) = (1e5, 1e3, 1e0)
# adam, content init -> (cw, sw, tv, lr) = (1e5, 1e5, 1e-1, 1e1)
# adam, style init -> (cw, sw, tv, lr) = (1e5, 1e2, 1e-1, 1e1)
# adam, random init -> (cw, sw, tv, lr) = (1e5, 1e2, 1e-1, 1e1)
# just wrapping settings into a dictionary
args_as_dict = {var: getattr(args, var) for var in vars(args)}
optimization_config = neural_style_transfer.Config(**args_as_dict)
optimization_config.content_images_dir = content_images_dir
optimization_config.style_images_dir = style_images_dir
optimization_config.output_img_dir = output_img_dir
optimization_config.img_format = img_format
# original NST (Neural Style Transfer) algorithm (Gatys et al.)
results_path = neural_style_transfer.transfer_style(optimization_config)
# uncomment this if you want to create a video from images dumped during the optimization procedure
# create_video_from_intermediate_results(results_path, img_format)
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TableOfContents from 'rsg-components/TableOfContents';
import StyleGuideRenderer from 'rsg-components/StyleGuide/StyleGuideRenderer';
import Sections from 'rsg-components/Sections';
import Welcome from 'rsg-components/Welcome';
import Error from 'rsg-components/Error';
import NotFound from 'rsg-components/NotFound';
import { HOMEPAGE } from '../../../scripts/consts';
import { DisplayModes } from '../../consts';
/**
* This function will return true, if the sidebar should be visible and false otherwise.
*
* These sorted conditions (highest precedence first) define the visibility
* state of the sidebar.
*
* - Sidebar is hidden for isolated example views
* - Sidebar is always visible when pagePerSection
* - Sidebar is hidden when showSidebar is set to false
* - Sidebar is visible when showSidebar is set to true for non-isolated views
*
* @param {boolean} displayMode
* @param {boolean} showSidebar
* @param {boolean} pagePerSection
* @returns {boolean}
*/
function hasSidebar(displayMode, showSidebar) {
return displayMode === DisplayModes.notFound || (showSidebar && displayMode === DisplayModes.all);
}
export default class StyleGuide extends Component {
static propTypes = {
codeRevision: PropTypes.number.isRequired,
config: PropTypes.object.isRequired,
slots: PropTypes.object.isRequired,
sections: PropTypes.array.isRequired,
welcomeScreen: PropTypes.bool,
patterns: PropTypes.array,
displayMode: PropTypes.string,
allSections: PropTypes.array.isRequired,
pagePerSection: PropTypes.bool,
};
static childContextTypes = {
codeRevision: PropTypes.number.isRequired,
config: PropTypes.object.isRequired,
slots: PropTypes.object.isRequired,
displayMode: PropTypes.string,
};
static defaultProps = {
displayMode: DisplayModes.all,
};
state = {
error: false,
info: null,
};
getChildContext() {
return {
codeRevision: this.props.codeRevision,
config: this.props.config,
slots: this.props.slots,
displayMode: this.props.displayMode,
};
}
componentDidCatch(error, info) {
this.setState({
error,
info,
});
}
render() {
const {
config,
sections,
welcomeScreen,
patterns,
displayMode,
allSections,
pagePerSection,
} = this.props;
if (this.state.error) {
return <Error error={this.state.error} info={this.state.info} />;
}
if (welcomeScreen) {
return <Welcome patterns={patterns} />;
}
return (
<StyleGuideRenderer
title={config.title}
homepageUrl={HOMEPAGE}
toc={<TableOfContents sections={allSections} useRouterLinks={pagePerSection} />}
hasSidebar={hasSidebar(displayMode, config.showSidebar)}
>
{sections.length ? <Sections sections={sections} depth={1} /> : <NotFound />}
</StyleGuideRenderer>
);
}
}
|
const WebhooksController = require('./src/features/webhooks/controller')
const WalletController = require('./src/features/wallet/controller')
const PricesController = require('./src/features/prices/controller')
const TransactionController = require('./src/features/transaction/controller')
const StakingController = require('./src/features/staking/controller')
const SwapController = require('./src/features/swap/controller')
const InfoController = require('./src/features/info/controller')
const { Protocol } = require('./src/services/blockchain/constants')
const { GenericException } = require('./errors')
/**
* @typedef {object} Config
* @property {string} environment
* @property {string} apiKey
*/
class CryptumSDK {
/**
*
* @param {Config} config
*/
constructor(config) {
this.config = config
}
/**
* Method to get an controller to create, get and delete webhooks
*
* @returns an WebhooksController instance class to manipulate
*/
getWebhooksController() {
return new WebhooksController(this.config)
}
/**
* Method to get a controller to manipulate wallets
*
* @returns WalletController instance
*/
getWalletController() {
return new WalletController(this.config)
}
/**
* Method to get a controller to manipulate transactions
*
* @returns TransactionController instance
*/
getTransactionController() {
return new TransactionController(this.config)
}
/**
* Method to get a controller to manipulate transactions
* @param {Object} args
* @param {Protocol} args.protocol
* @returns TransactionController instance
*/
getStakingController({ protocol }) {
const controller = new StakingController(this.config)
switch (protocol) {
case Protocol.CELO:
return controller.celo()
default:
throw new GenericException('Invalid protocol')
}
}
/**
* Method to get a controller to manipulate prices
*
* @returns PricesController instance
*/
getPricesController() {
return new PricesController(this.config)
}
/**
* Method to get a controller to manipulate swap
*
* @returns SwapController instance
*/
getSwapController() {
return new SwapController(this.config)
}
/**
* Method to get a controller to manipulate swap
*
* @returns InfoController instance
*/
getInfoController() {
return new InfoController(this.config)
}
}
module.exports = CryptumSDK
|
var assert = require('assert');
var httpHelper = require('./helpers/httpHelper.js');
var appHelper = require('./helpers/appHelper');
describe('router :: ', function() {
describe('View routes', function() {
var appName = 'testApp';
before(function(done) {
this.timeout(5000);
appHelper.build(done);
});
beforeEach(function(done) {
appHelper.lift({verbose: false}, function(err, sails) {
if (err) {throw new Error(err);}
sailsprocess = sails;
setTimeout(done, 100);
});
});
afterEach(function(done) {
sailsprocess.kill();
done();
});
after(function() {
// console.log('before `chdir ../`' + ', cwd was :: ' + process.cwd());
process.chdir('../');
// console.log('after `chdir ../`' + ', cwd was :: ' + process.cwd());
appHelper.teardown();
});
describe('with default routing', function() {
it('should respond to a get request to localhost:1342 with welcome page', function(done) {
httpHelper.testRoute('get', '', function(err, response) {
if (err) return done(new Error(err));
assert(response.body.indexOf('not found') < 0);
done();
});
});
});
describe('with no specified routing', function() {
before(function() {
httpHelper.writeRoutes({});
});
it('should respond to get request to :controller with the template at views/:controller/index.ejs', function(done) {
// Empty router file
httpHelper.testRoute('get', 'viewTest', function(err, response) {
if (err) return done(new Error(err));
assert(response.body.indexOf('indexView') !== -1, response.body);
done();
});
});
it('should respond to get request to :controller/:action with the template at views/:controller/:action.ejs', function(done) {
httpHelper.testRoute('get', 'viewTest/create', function(err, response) {
if (err) return done(new Error(err));
assert(response.body.indexOf('createView') !== -1);
done();
});
});
it('should merge config.views.locals into the view locals', function(done) {
httpHelper.testRoute('get', 'viewTest/viewOptions', function(err, response) {
if (err) return done(new Error(err));
assert(response.body.indexOf('!bar!') !== -1);
done();
});
});
it('should allow config.views.locals to be overridden', function(done) {
httpHelper.testRoute('get', 'viewTest/viewOptionsOverride', function(err, response) {
if (err) return done(new Error(err));
assert(response.body.indexOf('!baz!') !== -1);
done();
});
});
});
});
});
|
from typing import List, Optional
import discord
import member
from discord_utils import find_guild_in, find_channel_id_in, get_guild_members_as_string_from, choose_member_from, \
find_role
from emoji_wrapper import get_count_for_emoji, BALLOT_BOX
from model.topic import Topic
def get_vote_count(msg):
return get_count_for_emoji(msg, BALLOT_BOX)
class TopicService:
def __init__(self):
self.ctx = None
self.topics: List[Topic] = []
def add(self, topic_title):
self.topics.append(Topic(topic_title, "", "", "", ""))
return self.topics
def all(self):
return self.topics
def clear(self):
return self.topics.clear()
def find(self, title):
found_topics = [t for t in self.topics if t.title == title]
return found_topics[0]
def get_topic_by_display_id(self, display_id):
found_topics = [t for t in self.topics if t.display_id == int(display_id)]
return found_topics[0]
def get_next_topic(self, topic) -> Optional[Topic]:
next_topic_id = int(topic.display_id) + 1
if len(self.topics) <= next_topic_id:
return self.get_topic_by_display_id()
return None
|
'use strict';
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, BadRequest, InsufficientFunds, InvalidAddress, BadSymbol, InvalidOrder } = require ('./base/errors');
const Precise = require ('./base/Precise');
module.exports = class xena extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'xena',
'name': 'Xena Exchange',
'countries': [ 'VC', 'UK' ],
'rateLimit': 100,
'has': {
'CORS': false,
'cancelAllOrders': true,
'cancelOrder': true,
'createDepositAddress': true,
'createOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchLedger': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrderBook': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchWithdrawals': true,
'withdraw': true,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/51840849/87489843-bb469280-c64c-11ea-91aa-69c6326506af.jpg',
'test': {
'public': 'https://trading.demo.xena.io/api',
'private': 'https://api.demo.xena.io',
},
'api': {
'public': 'https://trading.xena.exchange/api',
'private': 'https://api.xena.exchange',
},
'www': 'https://xena.exchange',
'doc': 'https://support.xena.exchange/support/solutions/44000808700',
'fees': 'https://trading.xena.exchange/en/platform-specification/fee-schedule',
},
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'4h': '4h',
'12h': '12h',
'1d': '1d',
'1w': '1w',
},
'api': {
'public': {
'get': [
'common/currencies',
'common/instruments',
'common/features',
'common/commissions',
'common/news',
'market-data/candles/{marketId}/{timeframe}',
'market-data/market-watch',
'market-data/dom/{symbol}',
'market-data/candles/{symbol}/{timeframe}',
'market-data/trades/{symbol}',
'market-data/server-time',
'market-data/v2/candles/{symbol}/{timeframe}',
'market-data/v2/trades/{symbol}',
'market-data/v2/dom/{symbol}/',
'market-data/v2/server-time',
],
},
'private': {
'get': [
'trading/accounts/{accountId}/order',
'trading/accounts/{accountId}/active-orders',
'trading/accounts/{accountId}/last-order-statuses',
'trading/accounts/{accountId}/positions',
'trading/accounts/{accountId}/positions-history',
'trading/accounts/{accountId}/margin-requirements',
'trading/accounts',
'trading/accounts/{accountId}/balance',
'trading/accounts/{accountId}/trade-history',
// 'trading/accounts/{accountId}/trade-history?symbol=BTC/USDT&client_order_id=EMBB8Veke&trade_id=220143254',
'transfers/accounts',
'transfers/accounts/{accountId}',
'transfers/accounts/{accountId}/deposit-address/{currency}',
'transfers/accounts/{accountId}/deposits',
'transfers/accounts/{accountId}/trusted-addresses',
'transfers/accounts/{accountId}/withdrawals',
'transfers/accounts/{accountId}/balance-history',
// 'transfers/accounts/{accountId}/balance-history?currency={currency}&from={time}&to={time}&kind={kind}&kind={kind}',
// 'transfers/accounts/{accountId}/balance-history?page={page}&limit={limit}',
// 'transfers/accounts/{accountId}/balance-history?txid=3e1db982c4eed2d6355e276c5bae01a52a27c9cef61574b0e8c67ee05fc26ccf',
],
'post': [
'trading/order/new',
'trading/order/heartbeat',
'trading/order/cancel',
'trading/order/mass-cancel',
'trading/order/replace',
'trading/position/maintenance',
'transfers/accounts/{accountId}/withdrawals',
'transfers/accounts/{accountId}/deposit-address/{currency}',
],
},
},
'fees': {
'trading': {
'maker': 0.0005,
'taker': 0.001,
'tierBased': true,
'percentage': true,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {},
'deposit': {},
},
},
'exceptions': {
'exact': {
'Validation failed': BadRequest,
'Unknown derivative symbol': BadSymbol, // {"error":"Unknown derivative symbol"}
'Unknown account': BadRequest, // {"error":"Unknown account"}
'Wrong TransactTime': BadRequest, // {"error":"Wrong TransactTime"}
'ClOrdId is empty': BadRequest, // {"error":"ClOrdId is empty"}
},
'broad': {
'Invalid aggregation ratio or depth': BadRequest,
'address': InvalidAddress,
'Money not enough': InsufficientFunds,
'parse error': BadRequest,
'Not enough': InsufficientFunds, // {"error":"Not enough free margin"}
},
},
'options': {
'defaultType': 'margin', // 'margin',
'accountId': undefined, // '1012838157',
},
});
}
async fetchTime (params = {}) {
const response = await this.publicGetMarketDataV2ServerTime (params);
//
// {
// "msgType":"0",
// "transactTime":1594774454112817637
// }
//
const transactTime = this.safeInteger (response, 'transactTime');
return parseInt (transactTime / 1000000);
}
async fetchMarkets (params = {}) {
const response = await this.publicGetCommonInstruments (params);
//
// [
// {
// "id":"ETHUSD_3M_250920",
// "type":"Margin",
// "marginType":"XenaFuture",
// "symbol":"ETHUSD_3M_250920",
// "baseCurrency":"ETH",
// "quoteCurrency":"USD",
// "settlCurrency":"BTC",
// "tickSize":2,
// "minOrderQuantity":"1",
// "orderQtyStep":"1",
// "limitOrderMaxDistance":"10",
// "priceInputMask":"0000.00",
// "enabled":true,
// "liquidationMaxDistance":"0.01",
// "contractValue":"1",
// "contractCurrency":"BTC",
// "lotSize":"1",
// "tickValue":"0.00000001", // linear contracts only
// "maxOrderQty":"175000",
// "maxPosVolume":"1750000",
// "mark":".ETHUSD_3M_250920",
// "underlying":".ETHUSD_TWAP",
// "openInterest":".ETHUSD_3M_250920_OpenInterest",
// "floatingPL":"BidAsk", // perpetual contracts only
// "addUvmToFreeMargin":"ProfitAndLoss",
// "margin":{
// "netting":"PositionsAndOrders",
// "rates":[
// {"maxVolume":"175000","initialRate":"0.05","maintenanceRate":"0.0125"},
// {"maxVolume":"350000","initialRate":"0.1","maintenanceRate":"0.025"},
// {"maxVolume":"500000","initialRate":"0.2","maintenanceRate":"0.05"},
// {"maxVolume":"750000","initialRate":"0.3","maintenanceRate":"0.075"},
// {"maxVolume":"1050000","initialRate":"0.4","maintenanceRate":"0.1"},
// {"maxVolume":"1400000","initialRate":"0.5","maintenanceRate":"0.125"},
// {"maxVolume":"1750000","initialRate":"1","maintenanceRate":"0.25"}
// ],
// "rateMultipliers":{
// "LimitBuy":"1",
// "LimitSell":"1",
// "Long":"1",
// "MarketBuy":"1",
// "MarketSell":"1",
// "Short":"1",
// "StopBuy":"0",
// "StopSell":"0"
// }
// },
// "clearing":{"enabled":true,"index":".ETHUSD_3M_250920"},
// "premium":{"enabled":true,"index":".XBTUSD_Premium_IR_Corrected"}, // perpetual contracts only
// "riskAdjustment":{"enabled":true,"index":".RiskAdjustment_IR"},
// "expiration":{"enabled":true,"index":".ETHUSD_TWAP"}, // futures only
// "pricePrecision":3,
// "priceRange":{
// "enabled":true,
// "distance":"0.03",
// "movingBoundary":"0",
// "lowIndex":".ETHUSD_3M_250920_LOWRANGE",
// "highIndex":".ETHUSD_3M_250920_HIGHRANGE"
// },
// "priceLimits":{
// "enabled":true,
// "distance":"0.5",
// "movingBoundary":"0",
// "lowIndex":".ETHUSD_3M_250920_LOWLIMIT",
// "highIndex":".ETHUSD_3M_250920_HIGHLIMIT"
// },
// "inverse":true, // inverse contracts only
// "serie":"ETHUSD", // futures only
// "tradingStartDate":"2020-03-27 07:00:00",
// "expiryDate":"2020-09-25 08:00:00" // futures only
// },
// {
// "type":"Index",
// "symbol":".ETHUSD_Premium_IR_Corrected",
// "tickSize":6,
// "enabled":true,
// "basis":365
// },
// ]
//
const result = [];
for (let i = 0; i < response.length; i++) {
const market = response[i];
let type = this.safeStringLower (market, 'type');
const id = this.safeString (market, 'symbol');
const numericId = this.safeString (market, 'id');
const marginType = this.safeString (market, 'marginType');
const baseId = this.safeString (market, 'baseCurrency');
const quoteId = this.safeString (market, 'quoteCurrency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
let symbol = id;
if (type === 'margin') {
if (marginType === 'XenaFuture') {
type = 'future';
} else if (marginType === 'XenaListedPerpetual') {
type = 'swap';
symbol = base + '/' + quote;
}
}
const future = (type === 'future');
const swap = (type === 'swap');
const pricePrecision = this.safeInteger2 (market, 'tickSize', 'pricePrecision');
const precision = {
'price': pricePrecision,
'amount': 0,
};
const maxCost = this.safeNumber (market, 'maxOrderQty');
const minCost = this.safeNumber (market, 'minOrderQuantity');
const limits = {
'amount': {
'min': undefined,
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': minCost,
'max': maxCost,
},
};
const active = this.safeValue (market, 'enabled', false);
const inverse = this.safeValue (market, 'inverse', false);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'numericId': numericId,
'active': active,
'type': type,
'spot': false,
'future': future,
'swap': swap,
'inverse': inverse,
'precision': precision,
'limits': limits,
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetCommonCurrencies (params);
//
// {
// "BAB": {
// "name":"BAB",
// "title":"Bitcoin ABC",
// "blockchain":{
// "name":"BAB",
// "title":"Bitcoin ABC",
// "deposit":{"confirmations":6},
// "withdraw":{"confirmations":1},
// "addressReuseAllowed":false,
// "view":{
// "uriTemplate":"bitcoinabc:%s?message=Xena Exchange",
// "recommendedFee":"0.00001",
// "transactionUrl":"https://blockchair.com/bitcoin-cash/transaction/${txId}",
// "walletUrl":"https://blockchair.com/bitcoin-cash/address/${walletId}"
// }
// },
// "precision":5,
// "withdraw":{"minAmount":"0.01","commission":"0.001"},
// "view":{
// "color":"#DC7C08",
// "site":"https://www.bitcoinabc.org"
// },
// "enabled":true
// },
// }
const ids = Object.keys (response);
const result = {};
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const currency = response[id];
const code = this.safeCurrencyCode (id);
const name = this.safeString (currency, 'title');
const precision = this.safeInteger (currency, 'precision');
const enabled = this.safeValue (currency, 'enabled');
const active = (enabled === true);
const withdraw = this.safeValue (currency, 'withdraw', {});
result[code] = {
'id': id,
'code': code,
'info': currency,
'name': name,
'active': active,
'fee': this.safeNumber (withdraw, 'commission'),
'precision': precision,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': this.safeNumber (withdraw, 'minAmount'),
'max': undefined,
},
},
};
}
return result;
}
parseTicker (ticker, market = undefined) {
//
// fetchTicker, fetchTickers
//
// {
// "symbol":".XBTUSD_3M_250920_MID",
// "firstPx":"9337.49",
// "lastPx":"9355.81",
// "highPx":"9579.42",
// "lowPx":"9157.63",
// "buyVolume":"0",
// "sellVolume":"0",
// "bid":"0",
// "ask":"0"
// }
//
const timestamp = this.milliseconds ();
const marketId = this.safeString (ticker, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const last = this.safeNumber (ticker, 'lastPx');
const open = this.safeNumber (ticker, 'firstPx');
const buyVolume = this.safeNumber (ticker, 'buyVolume');
const sellVolume = this.safeNumber (ticker, 'sellVolume');
const baseVolume = this.sum (buyVolume, sellVolume);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'highPx'),
'low': this.safeNumber (ticker, 'lowPx'),
'bid': this.safeNumber (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'ask'),
'askVolume': undefined,
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': undefined,
'info': ticker,
}, market);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const tickers = await this.fetchTickers (undefined, params);
if (symbol in tickers) {
return tickers[symbol];
}
throw new BadSymbol (this.id + ' fetchTicker could not find a ticker with symbol ' + symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const tickers = await this.publicGetMarketDataMarketWatch (params);
//
// [
// {
// "symbol":".XBTUSD_3M_250920_MID",
// "firstPx":"9337.49",
// "lastPx":"9355.81",
// "highPx":"9579.42",
// "lowPx":"9157.63",
// "buyVolume":"0",
// "sellVolume":"0",
// "bid":"0",
// "ask":"0"
// }
// ]
//
const result = {};
for (let i = 0; i < tickers.length; i++) {
const ticker = this.parseTicker (tickers[i]);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'symbol': this.marketId (symbol),
};
if (limit !== undefined) {
request['depth'] = limit;
}
const response = await this.publicGetMarketDataV2DomSymbol (this.extend (request, params));
//
// {
// "msgType":"W",
// "mdStreamId":"DOM:XBTUSD:aggregated",
// "lastUpdateTime":1594772683037691997,
// "mdBookType":"2",
// "symbol":"XBTUSD",
// "lowRangePx":"9132.24",
// "highRangePx":"9410.36",
// "lowLimitPx":"9132.24",
// "highLimitPx":"9410.36",
// "clearingPx":"9253.4",
// "bestBid":"9269.8",
// "bestAsk":"9275.9",
// "mdEntry":[
// {"mdEntryType":"1","mdEntryPx":"9275.9","mdEntrySize":"3000","numberOfOrders":1},
// {"mdEntryType":"1","mdEntryPx":"9277.7","mdEntrySize":"50000","numberOfOrders":1},
// {"mdEntryType":"1","mdEntryPx":"9277.8","mdEntrySize":"2000","numberOfOrders":1},
// {"mdEntryType":"0","mdEntryPx":"9269.8","mdEntrySize":"2000","numberOfOrders":1},
// {"mdEntryType":"0","mdEntryPx":"9267.9","mdEntrySize":"3000","numberOfOrders":1},
// {"mdEntryType":"0","mdEntryPx":"9267.8","mdEntrySize":"50000","numberOfOrders":1},
// ]
// }
//
const mdEntry = this.safeValue (response, 'mdEntry', []);
const mdEntriesByType = this.groupBy (mdEntry, 'mdEntryType');
const lastUpdateTime = this.safeInteger (response, 'lastUpdateTime');
const timestamp = parseInt (lastUpdateTime / 1000000);
return this.parseOrderBook (mdEntriesByType, symbol, timestamp, '0', '1', 'mdEntryPx', 'mdEntrySize');
}
async fetchAccounts (params = {}) {
const response = await this.privateGetTradingAccounts (params);
//
// {
// "accounts": [
// { "id":8273231, "kind": "Spot" },
// { "id":10012833469, "kind": "Margin", "currency": "BTC" }
// ]
// }
//
const accounts = this.safeValue (response, 'accounts');
const result = [];
for (let i = 0; i < accounts.length; i++) {
const account = accounts[i];
const accountId = this.safeString (account, 'id');
const currencyId = this.safeString (account, 'currency');
const code = this.safeCurrencyCode (currencyId);
const type = this.safeStringLower (account, 'kind');
result.push ({
'id': accountId,
'type': type,
'currency': code,
'info': account,
});
}
return result;
}
async findAccountByType (type) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountsByType = this.groupBy (this.accounts, 'type');
const accounts = this.safeValue (accountsByType, type);
if (accounts === undefined) {
throw new ExchangeError (this.id + " findAccountByType() could not find an accountId with type '" + type + "', specify the 'accountId' parameter instead"); // eslint-disable-line quotes
}
const numAccounts = accounts.length;
if (numAccounts > 1) {
throw new ExchangeError (this.id + " findAccountByType() found more than one accountId with type '" + type + "', specify the 'accountId' parameter instead"); // eslint-disable-line quotes
}
return accounts[0];
}
async getAccountId (params) {
await this.loadMarkets ();
await this.loadAccounts ();
const defaultAccountId = this.safeString (this.options, 'accountId');
const accountId = this.safeString (params, 'accountId', defaultAccountId);
if (accountId !== undefined) {
return accountId;
}
const defaultType = this.safeString (this.options, 'defaultType', 'margin');
const type = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
if (type === undefined) {
throw new ArgumentsRequired (this.id + " requires an 'accountId' parameter or a 'type' parameter ('spot' or 'margin')");
}
const account = await this.findAccountByType (type);
return account['id'];
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'accountId': accountId,
};
const response = await this.privateGetTradingAccountsAccountIdBalance (this.extend (request, params));
//
// {
// "msgType":"XAR",
// "balances":[
// {
// "currency":"BTC",
// "lastUpdateTime":1619384111905916598,
// "available":"0.00549964",
// "onHold":"0",
// "settled":"0.00549964",
// "equity":"0.00549964"
// }
// ]
// }
//
const result = { 'info': response };
let timestamp = undefined;
const balances = this.safeValue (response, 'balances', []);
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const lastUpdateTime = this.safeString (balance, 'lastUpdateTime');
const lastUpdated = lastUpdateTime.slice (0, 13);
const currentTimestamp = parseInt (lastUpdated);
timestamp = (timestamp === undefined) ? currentTimestamp : Math.max (timestamp, currentTimestamp);
const currencyId = this.safeString (balance, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'available');
account['used'] = this.safeString (balance, 'onHold');
result[code] = account;
}
result['timestamp'] = timestamp;
result['datetime'] = this.iso8601 (timestamp);
return this.parseBalance (result);
}
parseTrade (trade, market = undefined) {
//
// {
// "mdUpdateAction":"0",
// "mdEntryType":"2",
// "mdEntryPx":"9225.16",
// "mdEntrySize":"10000",
// "transactTime":1594728504524977655,
// "tradeId":"6ac51bb7-7505-4f35-85ef-61eb738cb4d9",
// "aggressorSide":"1"
// }
//
// fetchMyTrades
//
// {
// "msgType":"8",
// "account":1012838158,
// "clOrdId":"xXWKLQVl3",
// "orderId":"89eee8bd-98ae-4d06-97dc-ee2d12997fe7",
// "symbol":"ETHUSD",
// "transactTime":1595143349089739000,
// "execId":"c4bd0ee2330930924e0f6fdde4630e56751692a4",
// "tradeId":"30a394b2-6d53-4bc4-b276-d8e19f470ba1",
// "side":"2",
// "lastQty":"1",
// "lastPx":"234.58",
// "avgPx":"234.58",
// "calculatedCcyLastQty":"0",
// "netMoney":"0",
// "lastLiquidityInd":"2",
// "commission":"0.00000011",
// "commRate":"0.00045",
// "commCurrency":"BTC",
// "positionId":132162662,
// "positionEffect":"C"
// }
//
const id = this.safeString (trade, 'tradeId');
let timestamp = this.safeInteger (trade, 'transactTime');
if (timestamp !== undefined) {
timestamp = parseInt (timestamp / 1000000);
}
let side = this.safeStringLower2 (trade, 'side', 'aggressorSide');
if (side === '1') {
side = 'buy';
} else if (side === '2') {
side = 'sell';
}
const orderId = this.safeString (trade, 'orderId');
const marketId = this.safeString (trade, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const priceString = this.safeString2 (trade, 'lastPx', 'mdEntryPx');
const amountString = this.safeString2 (trade, 'lastQty', 'mdEntrySize');
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
let fee = undefined;
const feeCost = this.safeNumber (trade, 'commission');
if (feeCost !== undefined) {
const feeCurrencyId = this.safeString (trade, 'commCurrency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId);
const feeRate = this.safeNumber (trade, 'commRate');
fee = {
'cost': feeCost,
'rate': feeRate,
'currency': feeCurrencyCode,
};
}
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'order': orderId,
'side': side,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'accountId': accountId,
// 'page': 1,
// 'limit': integer,
// 'from': time,
// 'to': time,
// 'symbol': currency['id'],
// 'trade_id': id,
// 'client_order_id': id,
};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = since * 1000000;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetTradingAccountsAccountIdTradeHistory (this.extend (request, params));
//
// [
// {
// "msgType":"8",
// "account":1012838158,
// "clOrdId":"xXWKLQVl3",
// "orderId":"89eee8bd-98ae-4d06-97dc-ee2d12997fe7",
// "symbol":"ETHUSD",
// "transactTime":1595143349089739000,
// "execId":"c4bd0ee2330930924e0f6fdde4630e56751692a4",
// "tradeId":"30a394b2-6d53-4bc4-b276-d8e19f470ba1",
// "side":"2",
// "lastQty":"1",
// "lastPx":"234.58",
// "avgPx":"234.58",
// "calculatedCcyLastQty":"0",
// "netMoney":"0",
// "lastLiquidityInd":"2",
// "commission":"0.00000011",
// "commRate":"0.00045",
// "commCurrency":"BTC",
// "positionId":132162662,
// "positionEffect":"C"
// },
// {
// "msgType":"8",
// "account":1012838158,
// "clOrdId":"3ce8c305-9936-4e97-9206-71ae3ff40305",
// "orderId":"a93c686d-990e-44d9-9cbe-61107744b990",
// "symbol":"ETHUSD",
// "transactTime":1595143315369226000,
// "execId":"1c745881722ad966a4ce71600cd058d59da0d1c3",
// "tradeId":"77f75bd8-27c4-4b1a-a5e8-0d59239ce216",
// "side":"1",
// "lastQty":"1",
// "lastPx":"234.72",
// "avgPx":"234.72",
// "calculatedCcyLastQty":"0",
// "netMoney":"0",
// "lastLiquidityInd":"2",
// "commission":"0.00000011",
// "commRate":"0.00045",
// "commCurrency":"BTC",
// "positionId":132162662,
// "positionEffect":"O"
// }
// ]
//
return this.parseTrades (response, market, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "transactTime":1594784700000000000,
// "firstPx":"9246.3",
// "lastPx":"9232.8",
// "highPx":"9246.3",
// "lowPx":"9232.8",
// "buyVolume":"0",
// "sellVolume":"0"
// }
//
const transactTime = this.safeInteger (ohlcv, 'transactTime');
const timestamp = parseInt (transactTime / 1000000);
const buyVolume = this.safeNumber (ohlcv, 'buyVolume');
const sellVolume = this.safeNumber (ohlcv, 'sellVolume');
const volume = this.sum (buyVolume, sellVolume);
return [
timestamp,
this.safeNumber (ohlcv, 'firstPx'),
this.safeNumber (ohlcv, 'highPx'),
this.safeNumber (ohlcv, 'lowPx'),
this.safeNumber (ohlcv, 'lastPx'),
volume,
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'timeframe': this.timeframes[timeframe],
};
const durationInSeconds = this.parseTimeframe (timeframe);
const duration = durationInSeconds * 1000;
if (since !== undefined) {
request['from'] = since * 1000000;
if (limit !== undefined) {
request['to'] = this.sum (since, limit * duration) * 1000000;
}
} else {
const now = this.milliseconds ();
// max limit is 1000
if (limit !== undefined) {
request['from'] = (now - limit * duration) * 1000000;
}
}
const response = await this.publicGetMarketDataV2CandlesSymbolTimeframe (this.extend (request, params));
//
// {
// "mdEntry":[
// {"transactTime":1594784700000000000,"firstPx":"9246.3","lastPx":"9232.8","highPx":"9246.3","lowPx":"9232.8","buyVolume":"0","sellVolume":"0"},
// {"transactTime":1594785600000000000,"firstPx":"9231.8","lastPx":"9227.3","highPx":"9232.8","lowPx":"9227.3","buyVolume":"0","sellVolume":"0"},
// {"transactTime":1594786500000000000,"firstPx":"9226.3","lastPx":"9230.3","highPx":"9230.3","lowPx":"9220.6","buyVolume":"0","sellVolume":"0"}
// ]
// }
//
const mdEntry = this.safeValue (response, 'mdEntry', []);
return this.parseOHLCVs (mdEntry, market, timeframe, since, limit);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
// 'from': this.iso8601 (since),
// 'to': this.iso8601 (this.milliseconds ()),
// 'page': 1,
// 'limit': limit,
};
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetMarketDataV2TradesSymbol (this.extend (request, params));
//
// {
// "msgType":"W",
// "lastUpdateTime":1594737830902223803,
// "symbol":"XBTUSD",
// "mdEntry":[
// {
// "mdUpdateAction":"0",
// "mdEntryType":"2",
// "mdEntryPx":"9225.16",
// "mdEntrySize":"10000",
// "transactTime":1594728504524977655,
// "tradeId":"6ac51bb7-7505-4f35-85ef-61eb738cb4d9",
// "aggressorSide":"1"
// },
// ]
// }
//
const mdEntry = this.safeValue (response, 'mdEntry', []);
return this.parseTrades (mdEntry, market, since, limit);
}
parseOrderStatus (status) {
const statuses = {
'A': 'open', // PendingNew
'0': 'open', // New
'1': 'open', // PartiallyFilled
'2': 'closed', // Filled
'6': 'canceled', // PendingCancel
'4': 'canceled', // Cancelled
'E': 'open', // PendingReplace
'8': 'rejected', // Rejected
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// createOrder
//
// {
// "msgType":"8",
// "account":1012838720,
// "clOrdId":"XAq0pRQ1g",
// "orderId":"64d7a06a-27e5-422e-99d9-3cadc04f5a35",
// "symbol":"XBTUSD",
// "ordType":"2",
// "price":"9000",
// "transactTime":1593778763271127920,
// "execId":"ff5fb8153652f0516bf07b6979255bed053c84b9",
// "execType":"I",
// "ordStatus":"0",
// "side":"1",
// "orderQty":"1",
// "leavesQty":"1",
// "cumQty":"0",
// "positionEffect":"O",
// "marginAmt":"0.00000556",
// "marginAmtType":"11"
// }
//
const id = this.safeString (order, 'orderId');
const clientOrderId = this.safeString (order, 'clOrdId');
const transactTime = this.safeInteger (order, 'transactTime');
const timestamp = parseInt (transactTime / 1000000);
const status = this.parseOrderStatus (this.safeString (order, 'ordStatus'));
const marketId = this.safeString (order, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const price = this.safeNumber (order, 'price');
const amount = this.safeNumber (order, 'orderQty');
const filled = this.safeNumber (order, 'cumQty');
const remaining = this.safeNumber (order, 'leavesQty');
let side = this.safeStringLower (order, 'side');
if (side === '1') {
side = 'buy';
} else if (side === '1') {
side = 'sell';
}
let type = this.safeStringLower (order, 'ordType');
if (type === '1') {
type = 'market';
} else if (type === '2') {
type = 'limit';
} else if (type === '3') {
type = 'stop';
} else if (type === '4') {
type = 'stop-limit';
}
return this.safeOrder ({
'id': id,
'clientOrderId': clientOrderId,
'info': order,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'amount': amount,
'cost': undefined,
'average': undefined,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': undefined,
'trades': undefined,
});
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const orderTypes = {
'market': '1',
'limit': '2',
'stop': '3',
'stop-limit': '4',
};
const orderType = this.safeString (orderTypes, type);
if (orderType === undefined) {
throw new InvalidOrder (this.id + ' createOrder does not support order type ' + type + ', supported order types are market, limit, stop, stop-limit');
}
const orderSides = {
'buy': '1',
'sell': '2',
};
const orderSide = this.safeString (orderSides, side);
if (orderSide === undefined) {
throw new InvalidOrder (this.id + ' createOrder does not support order side ' + side + ', supported order sides are buy, sell');
}
const market = this.market (symbol);
const request = {
'account': parseInt (accountId),
'symbol': market['id'],
'ordType': orderType,
'side': orderSide,
'orderQty': this.amountToPrecision (symbol, amount),
'transactTime': this.milliseconds () * 1000000,
// 'clOrdId': this.uuid (), // required
// 'price': this.priceToPrecision (symbol, price), // required for limit and stop-limit orders
// 'stopPx': this.priceToPrecision (symbol, stopPx), // required for stop and stop-limit orders
// 'timeInForce': '1', // default '1' = GoodTillCancelled, '3' = ImmediateOrCancel, '4' = FillOrKill
// 'execInst': '0',
// '0' = StayOnOfferSide, maker only, reject instead of aggressive execution
// '9' = PegToOfferSide, maker only, best available level instead of aggressive execution
// 'o' = CancelOnConnectionLoss
// 'positionID': 1013838923, // required when positionEffect == 'C' with hedged accounting
// 'positionEffect': 'O', // 'C' = Close, 'O' = Open, send C along with the positionID if the order must close a position with hedged accounting mode
// 'text': 'comment', // optional
// 'grpID': 'group-identifier', // group identifier for cancel on disconnect orders
};
if ((type === 'limit') || (type === 'stop-limit')) {
if (price === undefined) {
throw new InvalidOrder (this.id + ' createOrder() requires a price argument for order type ' + type);
}
request['price'] = this.priceToPrecision (symbol, price);
}
if ((type === 'stop') || (type === 'stop-limit')) {
const stopPx = this.safeNumber (params, 'stopPx');
if (stopPx === undefined) {
throw new InvalidOrder (this.id + ' createOrder() requires a stopPx param for order type ' + type);
}
request['stopPx'] = this.priceToPrecision (symbol, stopPx);
params = this.omit (params, 'stopPx');
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'clOrdId', this.uuid ());
if (clientOrderId !== undefined) {
request['clOrdId'] = clientOrderId;
params = this.omit (params, [ 'clientOrderId', 'clOrdId' ]);
}
const response = await this.privatePostTradingOrderNew (this.extend (request, params));
//
// {
// "msgType":"8",
// "account":1012838720,
// "clOrdId":"XAq0pRQ1g",
// "orderId":"64d7a06a-27e5-422e-99d9-3cadc04f5a35",
// "symbol":"XBTUSD",
// "ordType":"2",
// "price":"9000",
// "transactTime":1593778763271127920,
// "execId":"ff5fb8153652f0516bf07b6979255bed053c84b9",
// "execType":"I",
// "ordStatus":"0",
// "side":"1",
// "orderQty":"1",
// "leavesQty":"1",
// "cumQty":"0",
// "positionEffect":"O",
// "marginAmt":"0.00000556",
// "marginAmtType":"11"
// }
//
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const market = this.market (symbol);
const request = {
'account': parseInt (accountId),
'clOrdId': this.uuid (),
'symbol': market['id'],
'transactTime': this.milliseconds () * 1000000,
// 'origClOrdId': this.uuid (), // one of orderId or origClOrdId is required
// 'orderId': id,
// 'side': '1', // 1 = buy, 2 = sell
// 'execInst': '0',
// '0' = StayOnOfferSide, maker only, reject instead of aggressive execution
// '9' = PegToOfferSide, maker only, best available level instead of aggressive execution
// 'o' = CancelOnConnectionLoss
// 'orderQty': 38 M decimal
// 'price': this.priceToPrecision (symbol, price), // required for limit and stop-limit orders
// 'stopPx': this.priceToPrecision (symbol, stopPx), // required for stop and stop-limit orders
// 'capPrice': this.priceToPrecision (symbol, capPrice), // the price beyond which the order will not move for trailing stop and attempt-zero-loss
// 'pegPriceType': '8', // '8' = TrailingStopPeg, identifies a trailing stop or an attempt-zero-loss order
// 'pegOffsetType': '2', // '2' = BasisPoints, the unit of the distance to the stop price for a trailing stop or an attempt-zero-loss order
// 'pegOffsetValue': 123, // distance to the trailing stop or attempt-zero-loss
};
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'origClOrdId');
if (clientOrderId !== undefined) {
request['origClOrdId'] = clientOrderId;
params = this.omit (params, [ 'clientOrderId', 'origClOrdId' ]);
} else {
request['orderId'] = id;
}
if (amount !== undefined) {
request['orderQty'] = this.amountToPrecision (symbol, amount);
}
if (price !== undefined) {
request['price'] = this.priceToPrecision (symbol, price);
}
const stopPx = this.safeNumber (params, 'stopPx');
if (stopPx !== undefined) {
request['stopPx'] = this.priceToPrecision (symbol, stopPx);
params = this.omit (params, 'stopPx');
}
const capPrice = this.safeNumber (params, 'capPrice');
if (capPrice !== undefined) {
request['capPrice'] = this.priceToPrecision (symbol, capPrice);
params = this.omit (params, 'capPrice');
}
const response = await this.privatePostTradingOrderReplace (this.extend (request, params));
return this.parseOrder (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'origClOrdId');
params = this.omit (params, [ 'clientOrderId', 'origClOrdId' ]);
const market = this.market (symbol);
const request = {
'account': parseInt (accountId),
'symbol': market['id'],
'clOrdId': this.uuid (),
'transactTime': this.milliseconds () * 1000000,
};
if (clientOrderId !== undefined) {
request['origClOrdId'] = clientOrderId;
} else {
request['orderId'] = id;
}
const response = await this.privatePostTradingOrderCancel (this.extend (request, params));
//
// {
// "msgType":"8",
// "account":1012838158,
// "clOrdId":"0fa3fb55-9dc0-4cfc-a1db-6aa8b7dd2d98",
// "origClOrdId":"3b2878bb-24d8-4922-9d2a-5b8009416677",
// "orderId":"665b418e-9d09-4461-b733-d317f6bff43f",
// "symbol":"ETHUSD",
// "ordType":"2",
// "price":"640",
// "transactTime":1595060080941618739,
// "execId":"c541c0ca437c0e6501c3a50a9d4dc8f575f49972",
// "execType":"6",
// "ordStatus":"6",
// "side":"2",
// "orderQty":"1",
// "leavesQty":"0",
// "cumQty":"0",
// "positionEffect":"O",
// "marginAmt":"0.000032",
// "marginAmtType":"11"
// }
//
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'account': parseInt (accountId),
'clOrdId': this.uuid (),
// 'side': '1', // 1 = buy, 2 = sell, optional filter, cancel only orders with the given side
// 'positionEffect': 'C', // C = Close, O = Open, optional filter, cancel only orders with the given positionEffect, applicable only for accounts with hedged accounting
};
if (symbol !== undefined) {
const market = this.market (symbol);
request['symbol'] = market['id'];
request['massCancelRequestType'] = '1'; // CancelOrdersForASecurity
} else {
request['massCancelRequestType'] = '7'; // CancelAllOrders
}
const response = await this.privatePostTradingOrderMassCancel (this.extend (request, params));
//
// {
// "msgType":"r",
// "clOrdId":"b3e95759-e43e-4b3a-b664-a4d213e281a7",
// "massActionReportID":"e915b6f4-a7ca-4c5c-b8d6-e39862530248",
// "massCancelResponse":"1",
// "symbol":"ETHUSD",
// "transactTime":1595065630133756426,
// "totalAffectedOrders":2,
// "account":1012838158
// }
//
return response;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'accountId': accountId,
// 'symbol': market['id'],
};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateGetTradingAccountsAccountIdActiveOrders (this.extend (request, params));
//
// [
// {
// "msgType":"8",
// "account":1012838720,
// "clOrdId":"XAq0pRQ1g",
// "orderId":"64d7a06a-27e5-422e-99d9-3cadc04f5a35",
// "symbol":"XBTUSD",
// "ordType":"2",
// "price":"9000",
// "transactTime":1593778763271127920,
// "execId":"ff5fb8153652f0516bf07b6979255bed053c84b9",
// "execType":"I",
// "ordStatus":"0",
// "side":"1",
// "orderQty":"1",
// "leavesQty":"1",
// "cumQty":"0",
// "positionEffect":"O",
// "marginAmt":"0.00000556",
// "marginAmtType":"11"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'accountId': accountId,
// 'from': this.iso8601 (since) * 1000000,
// 'to': this.iso8601 (this.milliseconds ()) * 1000000, // max range is 7 days
// 'symbol': market['id'],
// 'limit': 100,
};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since) * 1000000;
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetTradingAccountsAccountIdLastOrderStatuses (this.extend (request, params));
//
// [
// {
// "msgType":"8",
// "account":1012838720,
// "clOrdId":"XAq0pRQ1g",
// "orderId":"64d7a06a-27e5-422e-99d9-3cadc04f5a35",
// "symbol":"XBTUSD",
// "ordType":"2",
// "price":"9000",
// "transactTime":1593778763271127920,
// "execId":"ff5fb8153652f0516bf07b6979255bed053c84b9",
// "execType":"I",
// "ordStatus":"0",
// "side":"1",
// "orderQty":"1",
// "leavesQty":"1",
// "cumQty":"0",
// "positionEffect":"O",
// "marginAmt":"0.00000556",
// "marginAmtType":"11"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async createDepositAddress (code, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const currency = this.currency (code);
const request = {
'accountId': accountId,
'currency': currency['id'],
};
const response = await this.privatePostTransfersAccountsAccountIdDepositAddressCurrency (this.extend (request, params));
//
// {
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "uri": "bitcoin:mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9?message=Xena Exchange",
// "allowsRenewal": true
// }
//
const address = this.safeValue (response, 'address');
const tag = undefined;
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'info': response,
};
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const currency = this.currency (code);
const request = {
'accountId': accountId,
'currency': currency['id'],
};
const response = await this.privateGetTransfersAccountsAccountIdDepositAddressCurrency (this.extend (request, params));
//
// {
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "uri": "bitcoin:mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9?message=Xena Exchange",
// "allowsRenewal": true
// }
//
const address = this.safeValue (response, 'address');
const tag = undefined;
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'info': response,
};
}
async fetchTransactionsByType (type, code = undefined, since = undefined, limit = undefined, params = {}) {
if (code === undefined) {
throw new ArgumentsRequired (this.id + ' fetchTransactions() requires a currency `code` argument');
}
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
'accountId': accountId,
};
if (since !== undefined) {
request['since'] = parseInt (since / 1000);
}
const method = 'privateGetTransfersAccountsAccountId' + this.capitalize (type);
const response = await this[method] (this.extend (request, params));
//
// {
// "withdrawals": [
// {
// "withdrawalRequestId": 47383243,
// "externalId": "...", // external ID submitted by the client when creating the request
// "status": 1,
// "statusMessage": "Pending confirmation",
// "amount": "10.2",
// "currency": "BTC",
// "lastUpdated": <UNIX nanoseconds>,
// "blockchain": "Bitcoin",
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "txId": "0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98"
// }
// ]
// }
//
// {
// "deposits": [
// {
// "currency": "BTC",
// "amount": "1.2",
// "status": 1,
// "statusMessage": "Processing",
// "blockchain": "Bitcoin",
// "txId": "0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98",
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "lastUpdated": <UNIX nanoseconds>
// "confirmations": 2,
// "requiredConfirmations": 6
// }
// ]
// }
//
//
const transactions = this.safeValue (response, type, []);
return this.parseTransactions (transactions, currency, since, limit);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('withdrawals', code, since, limit, params);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('deposits', code, since, limit, params);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw()
//
// {
// "withdrawalRequestId": 47383243,
// "status": 1,
// "statusMessage": "Pending confirmation"
// }
//
// fetchWithdrawals
//
// {
// "withdrawalRequestId": 47383243,
// "externalId": "...", // external ID submitted by the client when creating the request
// "status": 1,
// "statusMessage": "Pending confirmation",
// "amount": "10.2",
// "currency": "BTC",
// "lastUpdated": <UNIX nanoseconds>,
// "blockchain": "Bitcoin",
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "txId": "0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98"
// }
//
// fetchDeposits
//
// {
// "currency": "BTC",
// "amount": "1.2",
// "status": 1,
// "statusMessage": "Processing",
// "blockchain": "Bitcoin",
// "txId": "0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98",
// "address": "mu5GceHFAG38mGRYCFqafe5ZiNKLX3rKk9",
// "lastUpdated": <UNIX nanoseconds>
// "confirmations": 2,
// "requiredConfirmations": 6
// }
//
const id = this.safeString (transaction, 'withdrawalRequestId');
const type = (id === undefined) ? 'deposit' : 'withdrawal';
let updated = this.safeInteger (transaction, 'lastUpdated');
if (updated !== undefined) {
updated = parseInt (updated / 1000000);
}
const timestamp = undefined;
const txid = this.safeString (transaction, 'txId');
const currencyId = this.safeString (transaction, 'currency');
const code = this.safeCurrencyCode (currencyId, currency);
const address = this.safeString (transaction, 'address');
const addressFrom = undefined;
const addressTo = address;
const amount = this.safeNumber (transaction, 'amount');
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const fee = undefined;
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'addressFrom': addressFrom,
'addressTo': addressTo,
'address': address,
'tagFrom': undefined,
'tagTo': undefined,
'tag': undefined,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
parseTransactionStatus (status) {
const statuses = {
'1': 'pending', // new
'2': 'ok', // completed
'3': 'failed', // duplicate
'4': 'failed', // not enough money
'5': 'pending', // waiting for manual approval from XENA
'100': 'pending', // request is being processed
'101': 'pending', // request is being processed
'102': 'pending', // request is being processed
'103': 'pending', // request is being processed
};
return this.safeString (statuses, status, status);
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
this.checkAddress (address);
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const currency = this.currency (code);
let uuid = this.uuid ();
uuid = uuid.split ('-');
uuid = uuid.join ('');
const request = {
'currency': currency['id'],
'accountId': accountId,
'amount': this.currencyToPrecision (code, amount),
'address': address,
'id': uuid, // mandatory external ID (string), used by the client to identify his request
};
const response = await this.privatePostTransfersAccountsAccountIdWithdrawals (this.extend (request, params));
//
// {
// "withdrawalRequestId": 47383243,
// "status": 1,
// "statusMessage": "Pending confirmation"
// }
//
return this.parseTransaction (response, currency);
}
parseLedgerEntryType (type) {
const types = {
'deposit': 'transaction',
'withdrawal': 'transaction',
'internal deposit': 'transfer',
'internal withdrawal': 'transfer',
'rebate': 'rebate',
'reward': 'reward',
};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
// {
// "accountId":8263118,
// "ts":1551974415000000000,
// "amount":"-1",
// "currency":"BTC",
// "kind":"internal withdrawal",
// "commission":"0",
// "id":96
// }
//
const id = this.safeString (item, 'id');
let direction = undefined;
const account = this.safeString (item, 'accountId');
const referenceId = undefined;
const referenceAccount = undefined;
const type = this.parseLedgerEntryType (this.safeString (item, 'kind'));
const code = this.safeCurrencyCode (this.safeString (item, 'currency'), currency);
let amount = this.safeNumber (item, 'amount');
if (amount < 0) {
direction = 'out';
amount = Math.abs (amount);
} else {
direction = 'in';
}
let timestamp = this.safeInteger (item, 'ts');
if (timestamp !== undefined) {
timestamp = parseInt (timestamp / 1000000);
}
const fee = {
'cost': this.safeNumber (item, 'commission'),
'currency': code,
};
const before = undefined;
const after = this.safeNumber (item, 'balance');
const status = 'ok';
return {
'info': item,
'id': id,
'direction': direction,
'account': account,
'referenceId': referenceId,
'referenceAccount': referenceAccount,
'type': type,
'currency': code,
'amount': amount,
'before': before,
'after': after,
'status': status,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const accountId = await this.getAccountId (params);
const request = {
'accountId': accountId,
// 'page': 1,
// 'limit': 5000, // max 5000
// 'from': time,
// 'to': time,
// 'symbol': currency['id'],
// 'trade_id': id,
// 'client_order_id': id,
// 'txid': txid,
// 'kind': 'deposit', // 'withdrawal, 'internal deposit', 'internal withdrawal', 'rebate', 'reward'
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['symbol'] = currency['id'];
}
if (since !== undefined) {
request['from'] = since * 1000000;
}
if (limit !== undefined) {
request['limit'] = limit; // max 5000
}
const response = await this.privateGetTransfersAccountsAccountIdBalanceHistory (this.extend (request, params));
//
// [
// {
// "accountId":8263118,
// "ts":1551974415000000000,
// "amount":"-1",
// "currency":"BTC",
// "kind":"internal withdrawal",
// "commission":"0",
// "id":96
// },
// {
// "accountId":8263118,
// "ts":1551964677000000000,
// "amount":"-1",
// "currency":"BTC",
// "kind":"internal deposit",
// "commission":"0",
// "id":95
// }
// ]
//
return this.parseLedger (response, currency, since, limit);
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
const query = this.omit (params, this.extractParams (path));
if (api === 'public') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (api === 'private') {
this.checkRequiredCredentials ();
let nonce = this.nonce ();
// php does not format it properly
// therefore we use string concatenation here
// nonce *= 1000000;
nonce = nonce.toString ();
nonce = nonce + '000000'; // see the comment a few lines above
const payload = 'AUTH' + nonce;
const secret = this.secret.slice (14, 78);
const ecdsa = this.ecdsa (payload, secret, 'p256', 'sha256');
const signature = ecdsa['r'] + ecdsa['s'];
headers = {
'X-AUTH-API-KEY': this.apiKey,
'X-AUTH-API-PAYLOAD': payload,
'X-AUTH-API-SIGNATURE': signature,
'X-AUTH-API-NONCE': nonce,
};
if (method === 'GET') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (method === 'POST') {
body = this.json (query);
headers['Content-Type'] = 'application/json';
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return;
}
//
// {"error":"Validation failed","fields":["address"]}
// {"error":"Money not enough. You have only: 0 ETH","fields":["amount"]}
//
if (code >= 400) {
const feedback = this.id + ' ' + this.json (response);
const message = this.safeString (response, 'error');
const exact = this.exceptions['exact'];
if (message in exact) {
throw new exact[message] (feedback);
}
const broad = this.exceptions['broad'];
const broadKey = this.findBroadlyMatchedKey (broad, body);
if (broadKey !== undefined) {
throw new broad[broadKey] (feedback);
}
throw new ExchangeError (feedback); // unknown message
}
}
};
|
import csv
import datetime as dt
from django.core.management import BaseCommand
from scheduler.models import Course, Attendance
class Command(BaseCommand):
help = "Exports a CSV of all attendances for all students in the given course to stdout."
def add_arguments(self, parser):
parser.add_argument("course", type=str, help="the name of the course")
def _get_time(self, time):
return dt.datetime.combine(dt.date.min, time)
def handle(self, *args, **options):
course = Course.objects.get(name=options["course"])
attendances = Attendance.objects.filter(
student__section__course=course,
student__active=True
).order_by(
"date",
"student__section__spacetime__day_of_week",
"student__section__spacetime__start_time",
"student__section__mentor",
)
# write columns
cols = (
"Student Name",
"Student Email",
"Week Start",
"Attendance",
"Mentor Name",
"Mentor Email",
"Section Day",
"Section Time",
)
self._write(cols)
for attendance in attendances:
student = attendance.student
section = student.section
mentor = section.mentor
spacetime = section.spacetime
row = (
student.user.get_full_name(),
student.user.email,
str(attendance.week_start),
attendance.presence,
mentor.user.get_full_name(),
mentor.user.email,
spacetime.day_of_week,
str(spacetime.start_time),
)
self._write(row)
def _write(self, row):
self.stdout.write(",".join(row))
|
/*
Реализуйте (с использованием рекурсивного процесса) функцию sequenceSum,
которая находит сумму последовательности целых чисел.
Последовательность задается двумя значениями: begin - начало последовательности,
end - конец последовательности. Например: begin = 2 и end = 6 дают нам такую последовательность 2, 3, 4, 5, 6.
Сумма такой последовательности будет: 20.
import sequenceSum from './sequenceSum';
sequenceSum(1, 5); // 1 + 2 + 3 + 4 + 5 = 15
sequenceSum(4, 10); // 4 + 5 + 6 + 7 + 8 + 9 + 10 = 49
sequenceSum(-3, 2); // (-3) + (-2) + (-1) + 0 + 1 + 2 = -3
*/
function sequenceSum(begin, end) {
if (begin > end) {
return NaN;
}
if (begin === end) {
return begin;
}
return begin + sequenceSum(++begin, end);
}
console.log(sequenceSum(0, 0));//toBe(0);
console.log(sequenceSum(1, 1));//toBe(1);
console.log(sequenceSum(1, 5));//toBe(15);
console.log(sequenceSum(2, 6));//toBe(20);
console.log(sequenceSum(-1, -1));//toBe(-1);
console.log(sequenceSum(-5, 4));//toBe(-5);
console.log(Number.isNaN(sequenceSum(2, 1)));//toBe(true);
console.log(Number.isNaN(sequenceSum(1, -5)));//toBe(true);
|
/**
* @category saltcorn-cli
* @module commands/configuration-check
*/
const { Command, flags } = require("@oclif/command");
const { cli } = require("cli-ux");
const { maybe_as_tenant } = require("../common");
/**
* ConfigurationCheckCommand Class
* @extends oclif.Command
* @category saltcorn-cli
*/
class ConfigurationCheckCommand extends Command {
/**
* @returns {Promise<void>}
*/
async run() {
const User = require("@saltcorn/data/models/user");
const { flags } = this.parse(ConfigurationCheckCommand);
const { loadAllPlugins } = require("@saltcorn/server/load_plugins");
const { init_multi_tenant } = require("@saltcorn/data/db/state");
const { getAllTenants } = require("@saltcorn/admin-models/models/tenant");
const {
runConfigurationCheck,
} = require("@saltcorn/admin-models/models/config-check");
const { mockReqRes } = require("@saltcorn/data/tests/mocks");
await loadAllPlugins();
const tenants = await getAllTenants();
await init_multi_tenant(loadAllPlugins, undefined, tenants);
const that = this;
await maybe_as_tenant(flags.tenant, async () => {
const { passes, errors, pass } = await runConfigurationCheck(
mockReqRes.req
);
if (!pass) {
errors.forEach((s) => console.log(s + "\n"));
console.log(`FAIL - ${errors.length} checks failed`);
that.exit(1);
} else {
passes.forEach((s) => console.log(s));
console.log("Success - all checks pass");
}
});
this.exit(0);
}
}
/**
* @type {string}
*/
ConfigurationCheckCommand.description = `Check configuration`;
/**
* @type {object}
*/
ConfigurationCheckCommand.flags = {
tenant: flags.string({
char: "t",
description: "tenant",
}),
};
module.exports = ConfigurationCheckCommand;
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOverseasTaxAdvancedCreateModel(object):
def __init__(self):
self._doc_id = None
self._extend_param = None
self._identify_account_no = None
self._identify_account_type = None
self._nationality = None
self._out_merchant_id = None
self._out_tax_refund_no = None
self._passport_name = None
self._passport_no = None
self._pay_timeout = None
self._tax_refund_amount = None
self._tax_refund_country = None
self._tax_refund_currency = None
self._tax_refund_scene_type = None
self._user_received_amount = None
self._user_received_currency = None
@property
def doc_id(self):
return self._doc_id
@doc_id.setter
def doc_id(self, value):
self._doc_id = value
@property
def extend_param(self):
return self._extend_param
@extend_param.setter
def extend_param(self, value):
self._extend_param = value
@property
def identify_account_no(self):
return self._identify_account_no
@identify_account_no.setter
def identify_account_no(self, value):
self._identify_account_no = value
@property
def identify_account_type(self):
return self._identify_account_type
@identify_account_type.setter
def identify_account_type(self, value):
self._identify_account_type = value
@property
def nationality(self):
return self._nationality
@nationality.setter
def nationality(self, value):
self._nationality = value
@property
def out_merchant_id(self):
return self._out_merchant_id
@out_merchant_id.setter
def out_merchant_id(self, value):
self._out_merchant_id = value
@property
def out_tax_refund_no(self):
return self._out_tax_refund_no
@out_tax_refund_no.setter
def out_tax_refund_no(self, value):
self._out_tax_refund_no = value
@property
def passport_name(self):
return self._passport_name
@passport_name.setter
def passport_name(self, value):
self._passport_name = value
@property
def passport_no(self):
return self._passport_no
@passport_no.setter
def passport_no(self, value):
self._passport_no = value
@property
def pay_timeout(self):
return self._pay_timeout
@pay_timeout.setter
def pay_timeout(self, value):
self._pay_timeout = value
@property
def tax_refund_amount(self):
return self._tax_refund_amount
@tax_refund_amount.setter
def tax_refund_amount(self, value):
self._tax_refund_amount = value
@property
def tax_refund_country(self):
return self._tax_refund_country
@tax_refund_country.setter
def tax_refund_country(self, value):
self._tax_refund_country = value
@property
def tax_refund_currency(self):
return self._tax_refund_currency
@tax_refund_currency.setter
def tax_refund_currency(self, value):
self._tax_refund_currency = value
@property
def tax_refund_scene_type(self):
return self._tax_refund_scene_type
@tax_refund_scene_type.setter
def tax_refund_scene_type(self, value):
self._tax_refund_scene_type = value
@property
def user_received_amount(self):
return self._user_received_amount
@user_received_amount.setter
def user_received_amount(self, value):
self._user_received_amount = value
@property
def user_received_currency(self):
return self._user_received_currency
@user_received_currency.setter
def user_received_currency(self, value):
self._user_received_currency = value
def to_alipay_dict(self):
params = dict()
if self.doc_id:
if hasattr(self.doc_id, 'to_alipay_dict'):
params['doc_id'] = self.doc_id.to_alipay_dict()
else:
params['doc_id'] = self.doc_id
if self.extend_param:
if hasattr(self.extend_param, 'to_alipay_dict'):
params['extend_param'] = self.extend_param.to_alipay_dict()
else:
params['extend_param'] = self.extend_param
if self.identify_account_no:
if hasattr(self.identify_account_no, 'to_alipay_dict'):
params['identify_account_no'] = self.identify_account_no.to_alipay_dict()
else:
params['identify_account_no'] = self.identify_account_no
if self.identify_account_type:
if hasattr(self.identify_account_type, 'to_alipay_dict'):
params['identify_account_type'] = self.identify_account_type.to_alipay_dict()
else:
params['identify_account_type'] = self.identify_account_type
if self.nationality:
if hasattr(self.nationality, 'to_alipay_dict'):
params['nationality'] = self.nationality.to_alipay_dict()
else:
params['nationality'] = self.nationality
if self.out_merchant_id:
if hasattr(self.out_merchant_id, 'to_alipay_dict'):
params['out_merchant_id'] = self.out_merchant_id.to_alipay_dict()
else:
params['out_merchant_id'] = self.out_merchant_id
if self.out_tax_refund_no:
if hasattr(self.out_tax_refund_no, 'to_alipay_dict'):
params['out_tax_refund_no'] = self.out_tax_refund_no.to_alipay_dict()
else:
params['out_tax_refund_no'] = self.out_tax_refund_no
if self.passport_name:
if hasattr(self.passport_name, 'to_alipay_dict'):
params['passport_name'] = self.passport_name.to_alipay_dict()
else:
params['passport_name'] = self.passport_name
if self.passport_no:
if hasattr(self.passport_no, 'to_alipay_dict'):
params['passport_no'] = self.passport_no.to_alipay_dict()
else:
params['passport_no'] = self.passport_no
if self.pay_timeout:
if hasattr(self.pay_timeout, 'to_alipay_dict'):
params['pay_timeout'] = self.pay_timeout.to_alipay_dict()
else:
params['pay_timeout'] = self.pay_timeout
if self.tax_refund_amount:
if hasattr(self.tax_refund_amount, 'to_alipay_dict'):
params['tax_refund_amount'] = self.tax_refund_amount.to_alipay_dict()
else:
params['tax_refund_amount'] = self.tax_refund_amount
if self.tax_refund_country:
if hasattr(self.tax_refund_country, 'to_alipay_dict'):
params['tax_refund_country'] = self.tax_refund_country.to_alipay_dict()
else:
params['tax_refund_country'] = self.tax_refund_country
if self.tax_refund_currency:
if hasattr(self.tax_refund_currency, 'to_alipay_dict'):
params['tax_refund_currency'] = self.tax_refund_currency.to_alipay_dict()
else:
params['tax_refund_currency'] = self.tax_refund_currency
if self.tax_refund_scene_type:
if hasattr(self.tax_refund_scene_type, 'to_alipay_dict'):
params['tax_refund_scene_type'] = self.tax_refund_scene_type.to_alipay_dict()
else:
params['tax_refund_scene_type'] = self.tax_refund_scene_type
if self.user_received_amount:
if hasattr(self.user_received_amount, 'to_alipay_dict'):
params['user_received_amount'] = self.user_received_amount.to_alipay_dict()
else:
params['user_received_amount'] = self.user_received_amount
if self.user_received_currency:
if hasattr(self.user_received_currency, 'to_alipay_dict'):
params['user_received_currency'] = self.user_received_currency.to_alipay_dict()
else:
params['user_received_currency'] = self.user_received_currency
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayOverseasTaxAdvancedCreateModel()
if 'doc_id' in d:
o.doc_id = d['doc_id']
if 'extend_param' in d:
o.extend_param = d['extend_param']
if 'identify_account_no' in d:
o.identify_account_no = d['identify_account_no']
if 'identify_account_type' in d:
o.identify_account_type = d['identify_account_type']
if 'nationality' in d:
o.nationality = d['nationality']
if 'out_merchant_id' in d:
o.out_merchant_id = d['out_merchant_id']
if 'out_tax_refund_no' in d:
o.out_tax_refund_no = d['out_tax_refund_no']
if 'passport_name' in d:
o.passport_name = d['passport_name']
if 'passport_no' in d:
o.passport_no = d['passport_no']
if 'pay_timeout' in d:
o.pay_timeout = d['pay_timeout']
if 'tax_refund_amount' in d:
o.tax_refund_amount = d['tax_refund_amount']
if 'tax_refund_country' in d:
o.tax_refund_country = d['tax_refund_country']
if 'tax_refund_currency' in d:
o.tax_refund_currency = d['tax_refund_currency']
if 'tax_refund_scene_type' in d:
o.tax_refund_scene_type = d['tax_refund_scene_type']
if 'user_received_amount' in d:
o.user_received_amount = d['user_received_amount']
if 'user_received_currency' in d:
o.user_received_currency = d['user_received_currency']
return o
|
/* @flow */
import React from 'react'
import Helmet from 'react-helmet'
function About () {
return (
<div style={{ textAlign: 'center' }}>
<Helmet title="About" />
Produced with ❤️
by
 
<a href="https://twitter.com/controlplusb" target="_blank" rel="noopener noreferrer">
Sean Matheson
</a>
</div>
)
}
export default About
|
const strif = require('../strif');
strif.template();
let formatter = strif.create({
transformers: {
date: s => new Date(s),
lds: d => d.toLocaleDateString(),
upper: d => d.toUpperCase(),
}
});
let template = formatter.template(`Hi {name}!`, {
props: {
name: {},
}
});
let result = template.compile({
name: 'John'
});
console.log('result', result);
|
import gulp from 'gulp';
import path from 'path';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.dev.config.js';
import webpackProductionConfig from './webpack.prod.config.js';
gulp.task('wp.dev', done => {
webpack(webpackConfig).run((err, stats) => {
if (err) {
console.log('Error', err);
} else {
console.log(stats.toString());
}
if (done) done();
});
});
gulp.task('wp.prod', done => {
webpack(webpackProductionConfig).run((err, stats) => {
if (err) {
console.log('Error', err);
} else {
console.log(stats.toString());
}
if (done) done();
});
});
gulp.task('server', () => {
const server = new WebpackDevServer(webpack(webpackConfig), {
contentBase: webpackConfig.contentBase,
hot: true,
historyApiFallback: true,
stats: { colors: true },
});
server.listen(webpackConfig.port, "localhost", (err, result) => {
if (err) {
console.log(err);
}
console.log('Listening at http://localhost:' + webpackConfig.port);
});
});
gulp.task('dev', ['wp.dev', 'server']);
gulp.task('prod', ['wp.prod']);
gulp.task('default', ['dev']);
|
"""add is_dead, is_web_archive columns
Revision ID: c41abb284c8f
Revises:
Create Date: 2021-10-20 16:38:27.128115
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "c41abb284c8f"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"weblinks",
sa.Column("is_dead", sa.Integer(), server_default="0", nullable=False),
)
op.add_column(
"weblinks",
sa.Column("is_web_archive", sa.Integer(), server_default="0", nullable=False),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("weblinks", "is_web_archive")
op.drop_column("weblinks", "is_dead")
# ### end Alembic commands ###
|
const mongoose = require('mongoose')
const Product = new mongoose.Schema({
id: { type: Number },
brand: { type: String, default: '' },
description: { type: String, default: '' },
image: { type: String, default: '' },
price: { type: Number, default: 0 },
})
module.exports = mongoose.model('Product', Product)
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/cdk/portal'), require('@angular/common'), require('rxjs'), require('@angular/animations'), require('@angular/cdk/a11y'), require('@angular/material/core'), require('@angular/cdk/coercion'), require('@angular/cdk/keycodes'), require('rxjs/operators'), require('@angular/cdk/bidi'), require('@angular/cdk/overlay')) :
typeof define === 'function' && define.amd ? define('@angular/material/menu', ['exports', '@angular/core', '@angular/cdk/portal', '@angular/common', 'rxjs', '@angular/animations', '@angular/cdk/a11y', '@angular/material/core', '@angular/cdk/coercion', '@angular/cdk/keycodes', 'rxjs/operators', '@angular/cdk/bidi', '@angular/cdk/overlay'], factory) :
(factory((global.ng = global.ng || {}, global.ng.material = global.ng.material || {}, global.ng.material.menu = {}),global.ng.core,global.ng.cdk.portal,global.ng.common,global.rxjs,global.ng.animations,global.ng.cdk.a11y,global.ng.material.core,global.ng.cdk.coercion,global.ng.cdk.keycodes,global.rxjs.operators,global.ng.cdk.bidi,global.ng.cdk.overlay));
}(this, (function (exports,core,portal,common,rxjs,animations,a11y,core$1,coercion,keycodes,operators,bidi,overlay) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Menu content that will be rendered lazily once the menu is opened.
*/
var MatMenuContent = /** @class */ (function () {
function MatMenuContent(_template, _componentFactoryResolver, _appRef, _injector, _viewContainerRef, _document) {
this._template = _template;
this._componentFactoryResolver = _componentFactoryResolver;
this._appRef = _appRef;
this._injector = _injector;
this._viewContainerRef = _viewContainerRef;
this._document = _document;
/**
* Emits when the menu content has been attached.
*/
this._attached = new rxjs.Subject();
}
/**
* Attaches the content with a particular context.
* @docs-private
*/
/**
* Attaches the content with a particular context.
* \@docs-private
* @param {?=} context
* @return {?}
*/
MatMenuContent.prototype.attach = /**
* Attaches the content with a particular context.
* \@docs-private
* @param {?=} context
* @return {?}
*/
function (context) {
if (context === void 0) { context = {}; }
if (!this._portal) {
this._portal = new portal.TemplatePortal(this._template, this._viewContainerRef);
}
this.detach();
if (!this._outlet) {
this._outlet = new portal.DomPortalOutlet(this._document.createElement('div'), this._componentFactoryResolver, this._appRef, this._injector);
}
/** @type {?} */
var element = this._template.elementRef.nativeElement; /** @type {?} */
((
// Because we support opening the same menu from different triggers (which in turn have their
// own `OverlayRef` panel), we have to re-insert the host element every time, otherwise we
// risk it staying attached to a pane that's no longer in the DOM.
element.parentNode)).insertBefore(this._outlet.outletElement, element);
this._portal.attach(this._outlet, context);
this._attached.next();
};
/**
* Detaches the content.
* @docs-private
*/
/**
* Detaches the content.
* \@docs-private
* @return {?}
*/
MatMenuContent.prototype.detach = /**
* Detaches the content.
* \@docs-private
* @return {?}
*/
function () {
if (this._portal.isAttached) {
this._portal.detach();
}
};
/**
* @return {?}
*/
MatMenuContent.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
if (this._outlet) {
this._outlet.dispose();
}
};
MatMenuContent.decorators = [
{ type: core.Directive, args: [{
selector: 'ng-template[matMenuContent]'
},] },
];
/** @nocollapse */
MatMenuContent.ctorParameters = function () { return [
{ type: core.TemplateRef },
{ type: core.ComponentFactoryResolver },
{ type: core.ApplicationRef },
{ type: core.Injector },
{ type: core.ViewContainerRef },
{ type: undefined, decorators: [{ type: core.Inject, args: [common.DOCUMENT,] }] }
]; };
return MatMenuContent;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** *
* Animations used by the mat-menu component.
* Animation duration and timing values are based on:
* https://material.io/guidelines/components/menus.html#menus-usage
* \@docs-private
@type {?} */
var matMenuAnimations = {
/**
* This animation controls the menu panel's entry and exit from the page.
*
* When the menu panel is added to the DOM, it scales in and fades in its border.
*
* When the menu panel is removed from the DOM, it simply fades out after a brief
* delay to display the ripple.
*/
transformMenu: animations.trigger('transformMenu', [
animations.state('void', animations.style({
opacity: 0,
transform: 'scale(0.8)'
})),
animations.transition('void => enter', animations.group([
animations.query('.mat-menu-content', animations.animate('100ms linear', animations.style({ opacity: 1 }))),
animations.animate('120ms cubic-bezier(0, 0, 0.2, 1)', animations.style({ transform: 'scale(1)' })),
])),
animations.transition('* => void', animations.animate('100ms 25ms linear', animations.style({ opacity: 0 })))
]),
/**
* This animation fades in the background color and content of the menu panel
* after its containing element is scaled in.
*/
fadeInItems: animations.trigger('fadeInItems', [
// TODO(crisbeto): this is inside the `transformMenu`
// now. Remove next time we do breaking changes.
animations.state('showing', animations.style({ opacity: 1 })),
animations.transition('void => *', [
animations.style({ opacity: 0 }),
animations.animate('400ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)')
])
])
};
/** *
* @deprecated
* \@breaking-change 8.0.0
* \@docs-private
@type {?} */
var fadeInItems = matMenuAnimations.fadeInItems;
/** *
* @deprecated
* \@breaking-change 8.0.0
* \@docs-private
@type {?} */
var transformMenu = matMenuAnimations.transformMenu;
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* Throws an exception for the case when menu trigger doesn't have a valid mat-menu instance
* \@docs-private
* @return {?}
*/
function throwMatMenuMissingError() {
throw Error("matMenuTriggerFor: must pass in an mat-menu instance.\n\n Example:\n <mat-menu #menu=\"matMenu\"></mat-menu>\n <button [matMenuTriggerFor]=\"menu\"></button>");
}
/**
* Throws an exception for the case when menu's x-position value isn't valid.
* In other words, it doesn't match 'before' or 'after'.
* \@docs-private
* @return {?}
*/
function throwMatMenuInvalidPositionX() {
throw Error("xPosition value must be either 'before' or after'.\n Example: <mat-menu xPosition=\"before\" #menu=\"matMenu\"></mat-menu>");
}
/**
* Throws an exception for the case when menu's y-position value isn't valid.
* In other words, it doesn't match 'above' or 'below'.
* \@docs-private
* @return {?}
*/
function throwMatMenuInvalidPositionY() {
throw Error("yPosition value must be either 'above' or below'.\n Example: <mat-menu yPosition=\"above\" #menu=\"matMenu\"></mat-menu>");
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** *
* Injection token used to provide the parent menu to menu-specific components.
* \@docs-private
@type {?} */
var MAT_MENU_PANEL = new core.InjectionToken('MAT_MENU_PANEL');
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/**
* \@docs-private
*/
var /**
* \@docs-private
*/
MatMenuItemBase = /** @class */ (function () {
function MatMenuItemBase() {
}
return MatMenuItemBase;
}());
/** @type {?} */
var _MatMenuItemMixinBase = core$1.mixinDisableRipple(core$1.mixinDisabled(MatMenuItemBase));
/**
* This directive is intended to be used inside an mat-menu tag.
* It exists mostly to set the role attribute.
*/
var MatMenuItem = /** @class */ (function (_super) {
__extends(MatMenuItem, _super);
function MatMenuItem(_elementRef, document, _focusMonitor, _parentMenu) {
var _this =
// @breaking-change 8.0.0 make `_focusMonitor` and `document` required params.
_super.call(this) || this;
_this._elementRef = _elementRef;
_this._focusMonitor = _focusMonitor;
_this._parentMenu = _parentMenu;
/**
* Stream that emits when the menu item is hovered.
*/
_this._hovered = new rxjs.Subject();
/**
* Whether the menu item is highlighted.
*/
_this._highlighted = false;
/**
* Whether the menu item acts as a trigger for a sub-menu.
*/
_this._triggersSubmenu = false;
if (_focusMonitor) {
// Start monitoring the element so it gets the appropriate focused classes. We want
// to show the focus style for menu items only when the focus was not caused by a
// mouse or touch interaction.
_focusMonitor.monitor(_this._elementRef, false);
}
if (_parentMenu && _parentMenu.addItem) {
_parentMenu.addItem(_this);
}
_this._document = document;
return _this;
}
/** Focuses the menu item. */
/**
* Focuses the menu item.
* @param {?=} origin
* @return {?}
*/
MatMenuItem.prototype.focus = /**
* Focuses the menu item.
* @param {?=} origin
* @return {?}
*/
function (origin) {
if (origin === void 0) { origin = 'program'; }
if (this._focusMonitor) {
this._focusMonitor.focusVia(this._getHostElement(), origin);
}
else {
this._getHostElement().focus();
}
};
/**
* @return {?}
*/
MatMenuItem.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
if (this._focusMonitor) {
this._focusMonitor.stopMonitoring(this._elementRef);
}
if (this._parentMenu && this._parentMenu.removeItem) {
this._parentMenu.removeItem(this);
}
this._hovered.complete();
};
/** Used to set the `tabindex`. */
/**
* Used to set the `tabindex`.
* @return {?}
*/
MatMenuItem.prototype._getTabIndex = /**
* Used to set the `tabindex`.
* @return {?}
*/
function () {
return this.disabled ? '-1' : '0';
};
/** Returns the host DOM element. */
/**
* Returns the host DOM element.
* @return {?}
*/
MatMenuItem.prototype._getHostElement = /**
* Returns the host DOM element.
* @return {?}
*/
function () {
return this._elementRef.nativeElement;
};
/** Prevents the default element actions if it is disabled. */
/**
* Prevents the default element actions if it is disabled.
* @param {?} event
* @return {?}
*/
MatMenuItem.prototype._checkDisabled = /**
* Prevents the default element actions if it is disabled.
* @param {?} event
* @return {?}
*/
function (event) {
if (this.disabled) {
event.preventDefault();
event.stopPropagation();
}
};
/** Emits to the hover stream. */
/**
* Emits to the hover stream.
* @return {?}
*/
MatMenuItem.prototype._handleMouseEnter = /**
* Emits to the hover stream.
* @return {?}
*/
function () {
this._hovered.next(this);
};
/** Gets the label to be used when determining whether the option should be focused. */
/**
* Gets the label to be used when determining whether the option should be focused.
* @return {?}
*/
MatMenuItem.prototype.getLabel = /**
* Gets the label to be used when determining whether the option should be focused.
* @return {?}
*/
function () {
/** @type {?} */
var element = this._elementRef.nativeElement;
/** @type {?} */
var textNodeType = this._document ? this._document.TEXT_NODE : 3;
/** @type {?} */
var output = '';
if (element.childNodes) {
/** @type {?} */
var length_1 = element.childNodes.length;
// Go through all the top-level text nodes and extract their text.
// We skip anything that's not a text node to prevent the text from
// being thrown off by something like an icon.
for (var i = 0; i < length_1; i++) {
if (element.childNodes[i].nodeType === textNodeType) {
output += element.childNodes[i].textContent;
}
}
}
return output.trim();
};
MatMenuItem.decorators = [
{ type: core.Component, args: [{selector: '[mat-menu-item]',
exportAs: 'matMenuItem',
inputs: ['disabled', 'disableRipple'],
host: {
'role': 'menuitem',
'class': 'mat-menu-item',
'[class.mat-menu-item-highlighted]': '_highlighted',
'[class.mat-menu-item-submenu-trigger]': '_triggersSubmenu',
'[attr.tabindex]': '_getTabIndex()',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.disabled]': 'disabled || null',
'(click)': '_checkDisabled($event)',
'(mouseenter)': '_handleMouseEnter()',
},
changeDetection: core.ChangeDetectionStrategy.OnPush,
encapsulation: core.ViewEncapsulation.None,
template: "<ng-content></ng-content><div class=\"mat-menu-ripple\" matRipple [matRippleDisabled]=\"disableRipple || disabled\" [matRippleTrigger]=\"_getHostElement()\"></div>",
},] },
];
/** @nocollapse */
MatMenuItem.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: undefined, decorators: [{ type: core.Inject, args: [common.DOCUMENT,] }] },
{ type: a11y.FocusMonitor },
{ type: undefined, decorators: [{ type: core.Inject, args: [MAT_MENU_PANEL,] }, { type: core.Optional }] }
]; };
return MatMenuItem;
}(_MatMenuItemMixinBase));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** *
* Injection token to be used to override the default options for `mat-menu`.
@type {?} */
var MAT_MENU_DEFAULT_OPTIONS = new core.InjectionToken('mat-menu-default-options', {
providedIn: 'root',
factory: MAT_MENU_DEFAULT_OPTIONS_FACTORY
});
/**
* \@docs-private
* @return {?}
*/
function MAT_MENU_DEFAULT_OPTIONS_FACTORY() {
return {
overlapTrigger: false,
xPosition: 'after',
yPosition: 'below',
backdropClass: 'cdk-overlay-transparent-backdrop',
};
}
/** *
* Start elevation for the menu panel.
* \@docs-private
@type {?} */
var MAT_MENU_BASE_ELEVATION = 4;
var MatMenu = /** @class */ (function () {
function MatMenu(_elementRef, _ngZone, _defaultOptions) {
this._elementRef = _elementRef;
this._ngZone = _ngZone;
this._defaultOptions = _defaultOptions;
this._xPosition = this._defaultOptions.xPosition;
this._yPosition = this._defaultOptions.yPosition;
/**
* Menu items inside the current menu.
*/
this._items = [];
/**
* Emits whenever the amount of menu items changes.
*/
this._itemChanges = new rxjs.Subject();
/**
* Subscription to tab events on the menu panel
*/
this._tabSubscription = rxjs.Subscription.EMPTY;
/**
* Config object to be passed into the menu's ngClass
*/
this._classList = {};
/**
* Current state of the panel animation.
*/
this._panelAnimationState = 'void';
/**
* Emits whenever an animation on the menu completes.
*/
this._animationDone = new rxjs.Subject();
/**
* Class to be added to the backdrop element.
*/
this.backdropClass = this._defaultOptions.backdropClass;
this._overlapTrigger = this._defaultOptions.overlapTrigger;
this._hasBackdrop = this._defaultOptions.hasBackdrop;
/**
* Event emitted when the menu is closed.
*/
this.closed = new core.EventEmitter();
/**
* Event emitted when the menu is closed.
* @deprecated Switch to `closed` instead
* \@breaking-change 8.0.0
*/
this.close = this.closed;
}
Object.defineProperty(MatMenu.prototype, "xPosition", {
/** Position of the menu in the X axis. */
get: /**
* Position of the menu in the X axis.
* @return {?}
*/
function () { return this._xPosition; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
if (value !== 'before' && value !== 'after') {
throwMatMenuInvalidPositionX();
}
this._xPosition = value;
this.setPositionClasses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenu.prototype, "yPosition", {
/** Position of the menu in the Y axis. */
get: /**
* Position of the menu in the Y axis.
* @return {?}
*/
function () { return this._yPosition; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
if (value !== 'above' && value !== 'below') {
throwMatMenuInvalidPositionY();
}
this._yPosition = value;
this.setPositionClasses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenu.prototype, "overlapTrigger", {
/** Whether the menu should overlap its trigger. */
get: /**
* Whether the menu should overlap its trigger.
* @return {?}
*/
function () { return this._overlapTrigger; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
this._overlapTrigger = coercion.coerceBooleanProperty(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenu.prototype, "hasBackdrop", {
/** Whether the menu has a backdrop. */
get: /**
* Whether the menu has a backdrop.
* @return {?}
*/
function () { return this._hasBackdrop; },
set: /**
* @param {?} value
* @return {?}
*/
function (value) {
this._hasBackdrop = coercion.coerceBooleanProperty(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenu.prototype, "panelClass", {
/**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @param classes list of class names
*/
set: /**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @param {?} classes list of class names
* @return {?}
*/
function (classes) {
if (classes && classes.length) {
this._classList = classes.split(' ').reduce(function (obj, className) {
obj[className] = true;
return obj;
}, {});
this._elementRef.nativeElement.className = '';
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenu.prototype, "classList", {
/**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @deprecated Use `panelClass` instead.
* @breaking-change 8.0.0
*/
get: /**
* This method takes classes set on the host mat-menu element and applies them on the
* menu template that displays in the overlay container. Otherwise, it's difficult
* to style the containing menu from outside the component.
* @deprecated Use `panelClass` instead.
* \@breaking-change 8.0.0
* @return {?}
*/
function () { return this.panelClass; },
set: /**
* @param {?} classes
* @return {?}
*/
function (classes) { this.panelClass = classes; },
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
MatMenu.prototype.ngOnInit = /**
* @return {?}
*/
function () {
this.setPositionClasses();
};
/**
* @return {?}
*/
MatMenu.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
var _this = this;
this._keyManager = new a11y.FocusKeyManager(this._items).withWrap().withTypeAhead();
this._tabSubscription = this._keyManager.tabOut.subscribe(function () { return _this.closed.emit('tab'); });
};
/**
* @return {?}
*/
MatMenu.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
this._tabSubscription.unsubscribe();
this.closed.complete();
};
/** Stream that emits whenever the hovered menu item changes. */
/**
* Stream that emits whenever the hovered menu item changes.
* @return {?}
*/
MatMenu.prototype._hovered = /**
* Stream that emits whenever the hovered menu item changes.
* @return {?}
*/
function () {
return this._itemChanges.pipe(operators.startWith(this._items), operators.switchMap(function (items) { return rxjs.merge.apply(void 0, items.map(function (item) { return item._hovered; })); }));
};
/** Handle a keyboard event from the menu, delegating to the appropriate action. */
/**
* Handle a keyboard event from the menu, delegating to the appropriate action.
* @param {?} event
* @return {?}
*/
MatMenu.prototype._handleKeydown = /**
* Handle a keyboard event from the menu, delegating to the appropriate action.
* @param {?} event
* @return {?}
*/
function (event) {
/** @type {?} */
var keyCode = event.keyCode;
switch (keyCode) {
case keycodes.ESCAPE:
this.closed.emit('keydown');
break;
case keycodes.LEFT_ARROW:
if (this.parentMenu && this.direction === 'ltr') {
this.closed.emit('keydown');
}
break;
case keycodes.RIGHT_ARROW:
if (this.parentMenu && this.direction === 'rtl') {
this.closed.emit('keydown');
}
break;
default:
if (keyCode === keycodes.UP_ARROW || keyCode === keycodes.DOWN_ARROW) {
this._keyManager.setFocusOrigin('keyboard');
}
this._keyManager.onKeydown(event);
}
};
/**
* Focus the first item in the menu.
* @param origin Action from which the focus originated. Used to set the correct styling.
*/
/**
* Focus the first item in the menu.
* @param {?=} origin Action from which the focus originated. Used to set the correct styling.
* @return {?}
*/
MatMenu.prototype.focusFirstItem = /**
* Focus the first item in the menu.
* @param {?=} origin Action from which the focus originated. Used to set the correct styling.
* @return {?}
*/
function (origin) {
var _this = this;
if (origin === void 0) { origin = 'program'; }
// When the content is rendered lazily, it takes a bit before the items are inside the DOM.
if (this.lazyContent) {
this._ngZone.onStable.asObservable()
.pipe(operators.take(1))
.subscribe(function () { return _this._keyManager.setFocusOrigin(origin).setFirstItemActive(); });
}
else {
this._keyManager.setFocusOrigin(origin).setFirstItemActive();
}
};
/**
* Resets the active item in the menu. This is used when the menu is opened, allowing
* the user to start from the first option when pressing the down arrow.
*/
/**
* Resets the active item in the menu. This is used when the menu is opened, allowing
* the user to start from the first option when pressing the down arrow.
* @return {?}
*/
MatMenu.prototype.resetActiveItem = /**
* Resets the active item in the menu. This is used when the menu is opened, allowing
* the user to start from the first option when pressing the down arrow.
* @return {?}
*/
function () {
this._keyManager.setActiveItem(-1);
};
/**
* Sets the menu panel elevation.
* @param depth Number of parent menus that come before the menu.
*/
/**
* Sets the menu panel elevation.
* @param {?} depth Number of parent menus that come before the menu.
* @return {?}
*/
MatMenu.prototype.setElevation = /**
* Sets the menu panel elevation.
* @param {?} depth Number of parent menus that come before the menu.
* @return {?}
*/
function (depth) {
/** @type {?} */
var newElevation = "mat-elevation-z" + (MAT_MENU_BASE_ELEVATION + depth);
/** @type {?} */
var customElevation = Object.keys(this._classList).find(function (c) { return c.startsWith('mat-elevation-z'); });
if (!customElevation || customElevation === this._previousElevation) {
if (this._previousElevation) {
this._classList[this._previousElevation] = false;
}
this._classList[newElevation] = true;
this._previousElevation = newElevation;
}
};
/**
* Registers a menu item with the menu.
* @docs-private
*/
/**
* Registers a menu item with the menu.
* \@docs-private
* @param {?} item
* @return {?}
*/
MatMenu.prototype.addItem = /**
* Registers a menu item with the menu.
* \@docs-private
* @param {?} item
* @return {?}
*/
function (item) {
// We register the items through this method, rather than picking them up through
// `ContentChildren`, because we need the items to be picked up by their closest
// `mat-menu` ancestor. If we used `@ContentChildren(MatMenuItem, {descendants: true})`,
// all descendant items will bleed into the top-level menu in the case where the consumer
// has `mat-menu` instances nested inside each other.
if (this._items.indexOf(item) === -1) {
this._items.push(item);
this._itemChanges.next(this._items);
}
};
/**
* Removes an item from the menu.
* @docs-private
*/
/**
* Removes an item from the menu.
* \@docs-private
* @param {?} item
* @return {?}
*/
MatMenu.prototype.removeItem = /**
* Removes an item from the menu.
* \@docs-private
* @param {?} item
* @return {?}
*/
function (item) {
/** @type {?} */
var index = this._items.indexOf(item);
if (this._items.indexOf(item) > -1) {
this._items.splice(index, 1);
this._itemChanges.next(this._items);
}
};
/**
* Adds classes to the menu panel based on its position. Can be used by
* consumers to add specific styling based on the position.
* @param posX Position of the menu along the x axis.
* @param posY Position of the menu along the y axis.
* @docs-private
*/
/**
* Adds classes to the menu panel based on its position. Can be used by
* consumers to add specific styling based on the position.
* \@docs-private
* @param {?=} posX Position of the menu along the x axis.
* @param {?=} posY Position of the menu along the y axis.
* @return {?}
*/
MatMenu.prototype.setPositionClasses = /**
* Adds classes to the menu panel based on its position. Can be used by
* consumers to add specific styling based on the position.
* \@docs-private
* @param {?=} posX Position of the menu along the x axis.
* @param {?=} posY Position of the menu along the y axis.
* @return {?}
*/
function (posX, posY) {
if (posX === void 0) { posX = this.xPosition; }
if (posY === void 0) { posY = this.yPosition; }
/** @type {?} */
var classes = this._classList;
classes['mat-menu-before'] = posX === 'before';
classes['mat-menu-after'] = posX === 'after';
classes['mat-menu-above'] = posY === 'above';
classes['mat-menu-below'] = posY === 'below';
};
/** Starts the enter animation. */
/**
* Starts the enter animation.
* @return {?}
*/
MatMenu.prototype._startAnimation = /**
* Starts the enter animation.
* @return {?}
*/
function () {
// @breaking-change 8.0.0 Combine with _resetAnimation.
this._panelAnimationState = 'enter';
};
/** Resets the panel animation to its initial state. */
/**
* Resets the panel animation to its initial state.
* @return {?}
*/
MatMenu.prototype._resetAnimation = /**
* Resets the panel animation to its initial state.
* @return {?}
*/
function () {
// @breaking-change 8.0.0 Combine with _startAnimation.
this._panelAnimationState = 'void';
};
/** Callback that is invoked when the panel animation completes. */
/**
* Callback that is invoked when the panel animation completes.
* @param {?} event
* @return {?}
*/
MatMenu.prototype._onAnimationDone = /**
* Callback that is invoked when the panel animation completes.
* @param {?} event
* @return {?}
*/
function (event) {
this._animationDone.next(event);
this._isAnimating = false;
// Scroll the content element to the top once the animation is done. This is necessary, because
// we move focus to the first item while it's still being animated, which can throw the browser
// off when it determines the scroll position. Alternatively we can move focus when the
// animation is done, however moving focus asynchronously will interrupt screen readers
// which are in the process of reading out the menu already. We take the `element` from
// the `event` since we can't use a `ViewChild` to access the pane.
if (event.toState === 'enter' && this._keyManager.activeItemIndex === 0) {
event.element.scrollTop = 0;
}
};
MatMenu.decorators = [
{ type: core.Component, args: [{selector: 'mat-menu',
template: "<ng-template><div class=\"mat-menu-panel\" [ngClass]=\"_classList\" (keydown)=\"_handleKeydown($event)\" (click)=\"closed.emit('click')\" [@transformMenu]=\"_panelAnimationState\" (@transformMenu.start)=\"_isAnimating = true\" (@transformMenu.done)=\"_onAnimationDone($event)\" tabindex=\"-1\" role=\"menu\"><div class=\"mat-menu-content\"><ng-content></ng-content></div></div></ng-template>",
styles: [".mat-menu-panel{min-width:112px;max-width:280px;overflow:auto;-webkit-overflow-scrolling:touch;max-height:calc(100vh - 48px);border-radius:4px;outline:0}@media screen and (-ms-high-contrast:active){.mat-menu-panel{outline:solid 1px}}.mat-menu-content:not(:empty){padding-top:8px;padding-bottom:8px}.mat-menu-item{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;line-height:48px;height:48px;padding:0 16px;text-align:left;text-decoration:none;max-width:100%;position:relative}.mat-menu-item::-moz-focus-inner{border:0}.mat-menu-item[disabled]{cursor:default}[dir=rtl] .mat-menu-item{text-align:right}.mat-menu-item .mat-icon{margin-right:16px;vertical-align:middle}.mat-menu-item .mat-icon svg{vertical-align:top}[dir=rtl] .mat-menu-item .mat-icon{margin-left:16px;margin-right:0}@media screen and (-ms-high-contrast:active){.mat-menu-item-highlighted,.mat-menu-item.cdk-keyboard-focused,.mat-menu-item.cdk-program-focused{outline:dotted 1px}}.mat-menu-item-submenu-trigger{padding-right:32px}.mat-menu-item-submenu-trigger::after{width:0;height:0;border-style:solid;border-width:5px 0 5px 5px;border-color:transparent transparent transparent currentColor;content:'';display:inline-block;position:absolute;top:50%;right:16px;transform:translateY(-50%)}[dir=rtl] .mat-menu-item-submenu-trigger{padding-right:16px;padding-left:32px}[dir=rtl] .mat-menu-item-submenu-trigger::after{right:auto;left:16px;transform:rotateY(180deg) translateY(-50%)}.mat-menu-panel.ng-animating .mat-menu-item-submenu-trigger{pointer-events:none}button.mat-menu-item{width:100%}.mat-menu-item .mat-menu-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}"],
changeDetection: core.ChangeDetectionStrategy.OnPush,
encapsulation: core.ViewEncapsulation.None,
exportAs: 'matMenu',
animations: [
matMenuAnimations.transformMenu,
matMenuAnimations.fadeInItems
],
providers: [
{ provide: MAT_MENU_PANEL, useExisting: MatMenu }
]
},] },
];
/** @nocollapse */
MatMenu.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: core.NgZone },
{ type: undefined, decorators: [{ type: core.Inject, args: [MAT_MENU_DEFAULT_OPTIONS,] }] }
]; };
MatMenu.propDecorators = {
backdropClass: [{ type: core.Input }],
xPosition: [{ type: core.Input }],
yPosition: [{ type: core.Input }],
templateRef: [{ type: core.ViewChild, args: [core.TemplateRef,] }],
items: [{ type: core.ContentChildren, args: [MatMenuItem,] }],
lazyContent: [{ type: core.ContentChild, args: [MatMenuContent,] }],
overlapTrigger: [{ type: core.Input }],
hasBackdrop: [{ type: core.Input }],
panelClass: [{ type: core.Input, args: ['class',] }],
classList: [{ type: core.Input }],
closed: [{ type: core.Output }],
close: [{ type: core.Output }]
};
return MatMenu;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
/** *
* Injection token that determines the scroll handling while the menu is open.
@type {?} */
var MAT_MENU_SCROLL_STRATEGY = new core.InjectionToken('mat-menu-scroll-strategy');
/**
* \@docs-private
* @param {?} overlay
* @return {?}
*/
function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay$$1) {
return function () { return overlay$$1.scrollStrategies.reposition(); };
}
/** *
* \@docs-private
@type {?} */
var MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [overlay.Overlay],
useFactory: MAT_MENU_SCROLL_STRATEGY_FACTORY,
};
/** *
* Default top padding of the menu panel.
@type {?} */
var MENU_PANEL_TOP_PADDING = 8;
/**
* This directive is intended to be used in conjunction with an mat-menu tag. It is
* responsible for toggling the display of the provided menu instance.
*/
var MatMenuTrigger = /** @class */ (function () {
function MatMenuTrigger(_overlay, _element, _viewContainerRef, scrollStrategy, _parentMenu, _menuItemInstance, _dir, _focusMonitor) {
this._overlay = _overlay;
this._element = _element;
this._viewContainerRef = _viewContainerRef;
this._parentMenu = _parentMenu;
this._menuItemInstance = _menuItemInstance;
this._dir = _dir;
this._focusMonitor = _focusMonitor;
this._overlayRef = null;
this._menuOpen = false;
this._closeSubscription = rxjs.Subscription.EMPTY;
this._hoverSubscription = rxjs.Subscription.EMPTY;
// Tracking input type is necessary so it's possible to only auto-focus
// the first item of the list when the menu is opened via the keyboard
this._openedBy = null;
/**
* Event emitted when the associated menu is opened.
*/
this.menuOpened = new core.EventEmitter();
/**
* Event emitted when the associated menu is opened.
* @deprecated Switch to `menuOpened` instead
* \@breaking-change 8.0.0
*/
this.onMenuOpen = this.menuOpened;
/**
* Event emitted when the associated menu is closed.
*/
this.menuClosed = new core.EventEmitter();
/**
* Event emitted when the associated menu is closed.
* @deprecated Switch to `menuClosed` instead
* \@breaking-change 8.0.0
*/
this.onMenuClose = this.menuClosed;
if (_menuItemInstance) {
_menuItemInstance._triggersSubmenu = this.triggersSubmenu();
}
this._scrollStrategy = scrollStrategy;
}
Object.defineProperty(MatMenuTrigger.prototype, "_deprecatedMatMenuTriggerFor", {
/**
* @deprecated
* @breaking-change 8.0.0
*/
get: /**
* @deprecated
* \@breaking-change 8.0.0
* @return {?}
*/
function () {
return this.menu;
},
set: /**
* @param {?} v
* @return {?}
*/
function (v) {
this.menu = v;
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
MatMenuTrigger.prototype.ngAfterContentInit = /**
* @return {?}
*/
function () {
var _this = this;
this._checkMenu();
this.menu.close.asObservable().subscribe(function (reason) {
_this._destroyMenu();
// If a click closed the menu, we should close the entire chain of nested menus.
if ((reason === 'click' || reason === 'tab') && _this._parentMenu) {
_this._parentMenu.closed.emit(reason);
}
});
this._handleHover();
};
/**
* @return {?}
*/
MatMenuTrigger.prototype.ngOnDestroy = /**
* @return {?}
*/
function () {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._cleanUpSubscriptions();
};
Object.defineProperty(MatMenuTrigger.prototype, "menuOpen", {
/** Whether the menu is open. */
get: /**
* Whether the menu is open.
* @return {?}
*/
function () {
return this._menuOpen;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MatMenuTrigger.prototype, "dir", {
/** The text direction of the containing app. */
get: /**
* The text direction of the containing app.
* @return {?}
*/
function () {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
},
enumerable: true,
configurable: true
});
/** Whether the menu triggers a sub-menu or a top-level one. */
/**
* Whether the menu triggers a sub-menu or a top-level one.
* @return {?}
*/
MatMenuTrigger.prototype.triggersSubmenu = /**
* Whether the menu triggers a sub-menu or a top-level one.
* @return {?}
*/
function () {
return !!(this._menuItemInstance && this._parentMenu);
};
/** Toggles the menu between the open and closed states. */
/**
* Toggles the menu between the open and closed states.
* @return {?}
*/
MatMenuTrigger.prototype.toggleMenu = /**
* Toggles the menu between the open and closed states.
* @return {?}
*/
function () {
return this._menuOpen ? this.closeMenu() : this.openMenu();
};
/** Opens the menu. */
/**
* Opens the menu.
* @return {?}
*/
MatMenuTrigger.prototype.openMenu = /**
* Opens the menu.
* @return {?}
*/
function () {
var _this = this;
if (this._menuOpen) {
return;
}
this._checkMenu();
/** @type {?} */
var overlayRef = this._createOverlay();
this._setPosition(/** @type {?} */ (overlayRef.getConfig().positionStrategy));
overlayRef.attach(this._portal);
if (this.menu.lazyContent) {
this.menu.lazyContent.attach(this.menuData);
}
this._closeSubscription = this._menuClosingActions().subscribe(function () { return _this.closeMenu(); });
this._initMenu();
if (this.menu instanceof MatMenu) {
this.menu._startAnimation();
}
};
/** Closes the menu. */
/**
* Closes the menu.
* @return {?}
*/
MatMenuTrigger.prototype.closeMenu = /**
* Closes the menu.
* @return {?}
*/
function () {
this.menu.close.emit();
};
/**
* Focuses the menu trigger.
* @param origin Source of the menu trigger's focus.
*/
/**
* Focuses the menu trigger.
* @param {?=} origin Source of the menu trigger's focus.
* @return {?}
*/
MatMenuTrigger.prototype.focus = /**
* Focuses the menu trigger.
* @param {?=} origin Source of the menu trigger's focus.
* @return {?}
*/
function (origin) {
if (origin === void 0) { origin = 'program'; }
if (this._focusMonitor) {
this._focusMonitor.focusVia(this._element, origin);
}
else {
this._element.nativeElement.focus();
}
};
/**
* Closes the menu and does the necessary cleanup.
* @return {?}
*/
MatMenuTrigger.prototype._destroyMenu = /**
* Closes the menu and does the necessary cleanup.
* @return {?}
*/
function () {
var _this = this;
if (!this._overlayRef || !this.menuOpen) {
return;
}
/** @type {?} */
var menu = this.menu;
this._closeSubscription.unsubscribe();
this._overlayRef.detach();
if (menu instanceof MatMenu) {
menu._resetAnimation();
if (menu.lazyContent) {
// Wait for the exit animation to finish before detaching the content.
menu._animationDone
.pipe(operators.filter(function (event) { return event.toState === 'void'; }), operators.take(1),
// Interrupt if the content got re-attached.
operators.takeUntil(menu.lazyContent._attached))
.subscribe(function () { return ((menu.lazyContent)).detach(); }, undefined, function () {
// No matter whether the content got re-attached, reset the menu.
_this._resetMenu();
});
}
else {
this._resetMenu();
}
}
else {
this._resetMenu();
if (menu.lazyContent) {
menu.lazyContent.detach();
}
}
};
/**
* This method sets the menu state to open and focuses the first item if
* the menu was opened via the keyboard.
* @return {?}
*/
MatMenuTrigger.prototype._initMenu = /**
* This method sets the menu state to open and focuses the first item if
* the menu was opened via the keyboard.
* @return {?}
*/
function () {
this.menu.parentMenu = this.triggersSubmenu() ? this._parentMenu : undefined;
this.menu.direction = this.dir;
this._setMenuElevation();
this._setIsMenuOpen(true);
this.menu.focusFirstItem(this._openedBy || 'program');
};
/**
* Updates the menu elevation based on the amount of parent menus that it has.
* @return {?}
*/
MatMenuTrigger.prototype._setMenuElevation = /**
* Updates the menu elevation based on the amount of parent menus that it has.
* @return {?}
*/
function () {
if (this.menu.setElevation) {
/** @type {?} */
var depth = 0;
/** @type {?} */
var parentMenu = this.menu.parentMenu;
while (parentMenu) {
depth++;
parentMenu = parentMenu.parentMenu;
}
this.menu.setElevation(depth);
}
};
/**
* This method resets the menu when it's closed, most importantly restoring
* focus to the menu trigger if the menu was opened via the keyboard.
* @return {?}
*/
MatMenuTrigger.prototype._resetMenu = /**
* This method resets the menu when it's closed, most importantly restoring
* focus to the menu trigger if the menu was opened via the keyboard.
* @return {?}
*/
function () {
this._setIsMenuOpen(false);
// We should reset focus if the user is navigating using a keyboard or
// if we have a top-level trigger which might cause focus to be lost
// when clicking on the backdrop.
if (!this._openedBy) {
// Note that the focus style will show up both for `program` and
// `keyboard` so we don't have to specify which one it is.
this.focus();
}
else if (!this.triggersSubmenu()) {
this.focus(this._openedBy);
}
this._openedBy = null;
};
/**
* @param {?} isOpen
* @return {?}
*/
MatMenuTrigger.prototype._setIsMenuOpen = /**
* @param {?} isOpen
* @return {?}
*/
function (isOpen) {
this._menuOpen = isOpen;
this._menuOpen ? this.menuOpened.emit() : this.menuClosed.emit();
if (this.triggersSubmenu()) {
this._menuItemInstance._highlighted = isOpen;
}
};
/**
* This method checks that a valid instance of MatMenu has been passed into
* matMenuTriggerFor. If not, an exception is thrown.
* @return {?}
*/
MatMenuTrigger.prototype._checkMenu = /**
* This method checks that a valid instance of MatMenu has been passed into
* matMenuTriggerFor. If not, an exception is thrown.
* @return {?}
*/
function () {
if (!this.menu) {
throwMatMenuMissingError();
}
};
/**
* This method creates the overlay from the provided menu's template and saves its
* OverlayRef so that it can be attached to the DOM when openMenu is called.
* @return {?}
*/
MatMenuTrigger.prototype._createOverlay = /**
* This method creates the overlay from the provided menu's template and saves its
* OverlayRef so that it can be attached to the DOM when openMenu is called.
* @return {?}
*/
function () {
if (!this._overlayRef) {
this._portal = new portal.TemplatePortal(this.menu.templateRef, this._viewContainerRef);
/** @type {?} */
var config = this._getOverlayConfig();
this._subscribeToPositions(/** @type {?} */ (config.positionStrategy));
this._overlayRef = this._overlay.create(config);
// Consume the `keydownEvents` in order to prevent them from going to another overlay.
// Ideally we'd also have our keyboard event logic in here, however doing so will
// break anybody that may have implemented the `MatMenuPanel` themselves.
this._overlayRef.keydownEvents().subscribe();
}
return this._overlayRef;
};
/**
* This method builds the configuration object needed to create the overlay, the OverlayState.
* @return {?} OverlayConfig
*/
MatMenuTrigger.prototype._getOverlayConfig = /**
* This method builds the configuration object needed to create the overlay, the OverlayState.
* @return {?} OverlayConfig
*/
function () {
return new overlay.OverlayConfig({
positionStrategy: this._overlay.position()
.flexibleConnectedTo(this._element)
.withLockedPosition()
.withTransformOriginOn('.mat-menu-panel'),
hasBackdrop: this.menu.hasBackdrop == null ? !this.triggersSubmenu() : this.menu.hasBackdrop,
backdropClass: this.menu.backdropClass || 'cdk-overlay-transparent-backdrop',
scrollStrategy: this._scrollStrategy(),
direction: this._dir
});
};
/**
* Listens to changes in the position of the overlay and sets the correct classes
* on the menu based on the new position. This ensures the animation origin is always
* correct, even if a fallback position is used for the overlay.
* @param {?} position
* @return {?}
*/
MatMenuTrigger.prototype._subscribeToPositions = /**
* Listens to changes in the position of the overlay and sets the correct classes
* on the menu based on the new position. This ensures the animation origin is always
* correct, even if a fallback position is used for the overlay.
* @param {?} position
* @return {?}
*/
function (position) {
var _this = this;
if (this.menu.setPositionClasses) {
position.positionChanges.subscribe(function (change) {
/** @type {?} */
var posX = change.connectionPair.overlayX === 'start' ? 'after' : 'before';
/** @type {?} */
var posY = change.connectionPair.overlayY === 'top' ? 'below' : 'above'; /** @type {?} */
((_this.menu.setPositionClasses))(posX, posY);
});
}
};
/**
* Sets the appropriate positions on a position strategy
* so the overlay connects with the trigger correctly.
* @param {?} positionStrategy Strategy whose position to update.
* @return {?}
*/
MatMenuTrigger.prototype._setPosition = /**
* Sets the appropriate positions on a position strategy
* so the overlay connects with the trigger correctly.
* @param {?} positionStrategy Strategy whose position to update.
* @return {?}
*/
function (positionStrategy) {
var _a = this.menu.xPosition === 'before' ? ['end', 'start'] : ['start', 'end'], originX = _a[0], originFallbackX = _a[1];
var _b = this.menu.yPosition === 'above' ? ['bottom', 'top'] : ['top', 'bottom'], overlayY = _b[0], overlayFallbackY = _b[1];
var _c = [overlayY, overlayFallbackY], originY = _c[0], originFallbackY = _c[1];
var _d = [originX, originFallbackX], overlayX = _d[0], overlayFallbackX = _d[1];
/** @type {?} */
var offsetY = 0;
if (this.triggersSubmenu()) {
// When the menu is a sub-menu, it should always align itself
// to the edges of the trigger, instead of overlapping it.
overlayFallbackX = originX = this.menu.xPosition === 'before' ? 'start' : 'end';
originFallbackX = overlayX = originX === 'end' ? 'start' : 'end';
offsetY = overlayY === 'bottom' ? MENU_PANEL_TOP_PADDING : -MENU_PANEL_TOP_PADDING;
}
else if (!this.menu.overlapTrigger) {
originY = overlayY === 'top' ? 'bottom' : 'top';
originFallbackY = overlayFallbackY === 'top' ? 'bottom' : 'top';
}
positionStrategy.withPositions([
{ originX: originX, originY: originY, overlayX: overlayX, overlayY: overlayY, offsetY: offsetY },
{ originX: originFallbackX, originY: originY, overlayX: overlayFallbackX, overlayY: overlayY, offsetY: offsetY },
{
originX: originX,
originY: originFallbackY,
overlayX: overlayX,
overlayY: overlayFallbackY,
offsetY: -offsetY
},
{
originX: originFallbackX,
originY: originFallbackY,
overlayX: overlayFallbackX,
overlayY: overlayFallbackY,
offsetY: -offsetY
}
]);
};
/**
* Cleans up the active subscriptions.
* @return {?}
*/
MatMenuTrigger.prototype._cleanUpSubscriptions = /**
* Cleans up the active subscriptions.
* @return {?}
*/
function () {
this._closeSubscription.unsubscribe();
this._hoverSubscription.unsubscribe();
};
/**
* Returns a stream that emits whenever an action that should close the menu occurs.
* @return {?}
*/
MatMenuTrigger.prototype._menuClosingActions = /**
* Returns a stream that emits whenever an action that should close the menu occurs.
* @return {?}
*/
function () {
var _this = this;
/** @type {?} */
var backdrop = /** @type {?} */ ((this._overlayRef)).backdropClick();
/** @type {?} */
var detachments = /** @type {?} */ ((this._overlayRef)).detachments();
/** @type {?} */
var parentClose = this._parentMenu ? this._parentMenu.closed : rxjs.of();
/** @type {?} */
var hover = this._parentMenu ? this._parentMenu._hovered().pipe(operators.filter(function (active) { return active !== _this._menuItemInstance; }), operators.filter(function () { return _this._menuOpen; })) : rxjs.of();
return rxjs.merge(backdrop, parentClose, hover, detachments);
};
/** Handles mouse presses on the trigger. */
/**
* Handles mouse presses on the trigger.
* @param {?} event
* @return {?}
*/
MatMenuTrigger.prototype._handleMousedown = /**
* Handles mouse presses on the trigger.
* @param {?} event
* @return {?}
*/
function (event) {
if (!a11y.isFakeMousedownFromScreenReader(event)) {
// Since right or middle button clicks won't trigger the `click` event,
// we shouldn't consider the menu as opened by mouse in those cases.
this._openedBy = event.button === 0 ? 'mouse' : null;
// Since clicking on the trigger won't close the menu if it opens a sub-menu,
// we should prevent focus from moving onto it via click to avoid the
// highlight from lingering on the menu item.
if (this.triggersSubmenu()) {
event.preventDefault();
}
}
};
/** Handles key presses on the trigger. */
/**
* Handles key presses on the trigger.
* @param {?} event
* @return {?}
*/
MatMenuTrigger.prototype._handleKeydown = /**
* Handles key presses on the trigger.
* @param {?} event
* @return {?}
*/
function (event) {
/** @type {?} */
var keyCode = event.keyCode;
if (this.triggersSubmenu() && ((keyCode === keycodes.RIGHT_ARROW && this.dir === 'ltr') ||
(keyCode === keycodes.LEFT_ARROW && this.dir === 'rtl'))) {
this.openMenu();
}
};
/** Handles click events on the trigger. */
/**
* Handles click events on the trigger.
* @param {?} event
* @return {?}
*/
MatMenuTrigger.prototype._handleClick = /**
* Handles click events on the trigger.
* @param {?} event
* @return {?}
*/
function (event) {
if (this.triggersSubmenu()) {
// Stop event propagation to avoid closing the parent menu.
event.stopPropagation();
this.openMenu();
}
else {
this.toggleMenu();
}
};
/**
* Handles the cases where the user hovers over the trigger.
* @return {?}
*/
MatMenuTrigger.prototype._handleHover = /**
* Handles the cases where the user hovers over the trigger.
* @return {?}
*/
function () {
var _this = this;
// Subscribe to changes in the hovered item in order to toggle the panel.
if (!this.triggersSubmenu()) {
return;
}
this._hoverSubscription = this._parentMenu._hovered()
// Since we might have multiple competing triggers for the same menu (e.g. a sub-menu
// with different data and triggers), we have to delay it by a tick to ensure that
// it won't be closed immediately after it is opened.
.pipe(operators.filter(function (active) { return active === _this._menuItemInstance && !active.disabled; }), operators.delay(0, rxjs.asapScheduler))
.subscribe(function () {
_this._openedBy = 'mouse';
// If the same menu is used between multiple triggers, it might still be animating
// while the new trigger tries to re-open it. Wait for the animation to finish
// before doing so. Also interrupt if the user moves to another item.
if (_this.menu instanceof MatMenu && _this.menu._isAnimating) {
// We need the `delay(0)` here in order to avoid
// 'changed after checked' errors in some cases. See #12194.
_this.menu._animationDone
.pipe(operators.take(1), operators.delay(0, rxjs.asapScheduler), operators.takeUntil(_this._parentMenu._hovered()))
.subscribe(function () { return _this.openMenu(); });
}
else {
_this.openMenu();
}
});
};
MatMenuTrigger.decorators = [
{ type: core.Directive, args: [{
selector: "[mat-menu-trigger-for], [matMenuTriggerFor]",
host: {
'aria-haspopup': 'true',
'[attr.aria-expanded]': 'menuOpen || null',
'(mousedown)': '_handleMousedown($event)',
'(touchstart)': '_openedBy = "touch"',
'(keydown)': '_handleKeydown($event)',
'(click)': '_handleClick($event)',
},
exportAs: 'matMenuTrigger'
},] },
];
/** @nocollapse */
MatMenuTrigger.ctorParameters = function () { return [
{ type: overlay.Overlay },
{ type: core.ElementRef },
{ type: core.ViewContainerRef },
{ type: undefined, decorators: [{ type: core.Inject, args: [MAT_MENU_SCROLL_STRATEGY,] }] },
{ type: MatMenu, decorators: [{ type: core.Optional }] },
{ type: MatMenuItem, decorators: [{ type: core.Optional }, { type: core.Self }] },
{ type: bidi.Directionality, decorators: [{ type: core.Optional }] },
{ type: a11y.FocusMonitor }
]; };
MatMenuTrigger.propDecorators = {
_deprecatedMatMenuTriggerFor: [{ type: core.Input, args: ['mat-menu-trigger-for',] }],
menu: [{ type: core.Input, args: ['matMenuTriggerFor',] }],
menuData: [{ type: core.Input, args: ['matMenuTriggerData',] }],
menuOpened: [{ type: core.Output }],
onMenuOpen: [{ type: core.Output }],
menuClosed: [{ type: core.Output }],
onMenuClose: [{ type: core.Output }]
};
return MatMenuTrigger;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
var MatMenuModule = /** @class */ (function () {
function MatMenuModule() {
}
MatMenuModule.decorators = [
{ type: core.NgModule, args: [{
imports: [
common.CommonModule,
core$1.MatCommonModule,
core$1.MatRippleModule,
overlay.OverlayModule,
],
exports: [MatMenu, MatMenuItem, MatMenuTrigger, MatMenuContent, core$1.MatCommonModule],
declarations: [MatMenu, MatMenuItem, MatMenuTrigger, MatMenuContent],
providers: [MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER]
},] },
];
return MatMenuModule;
}());
exports.MAT_MENU_SCROLL_STRATEGY = MAT_MENU_SCROLL_STRATEGY;
exports.MatMenuModule = MatMenuModule;
exports.MatMenu = MatMenu;
exports.MAT_MENU_DEFAULT_OPTIONS = MAT_MENU_DEFAULT_OPTIONS;
exports.MatMenuItem = MatMenuItem;
exports.MatMenuTrigger = MatMenuTrigger;
exports.matMenuAnimations = matMenuAnimations;
exports.fadeInItems = fadeInItems;
exports.transformMenu = transformMenu;
exports.MatMenuContent = MatMenuContent;
exports.ɵa19 = MAT_MENU_DEFAULT_OPTIONS_FACTORY;
exports.ɵb19 = MatMenuItemBase;
exports.ɵc19 = _MatMenuItemMixinBase;
exports.ɵf19 = MAT_MENU_PANEL;
exports.ɵd19 = MAT_MENU_SCROLL_STRATEGY_FACTORY;
exports.ɵe19 = MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=material-menu.umd.js.map
|
const { slash } = require( `gatsby-core-utils` );
const singlePageTemplate = require.resolve(`../src/templates/blog-post-archive.js`);
const createPaginatedPages = require('gatsby-paginate');
// Get all the posts.
const GET_POSTS = `
query WpAllCategories {
allWpCategory {
categories: edges {
node {
name
slug
uri
id
posts {
nodes {
excerpt
title
categories {
nodes {
name
}
}
uri
date(formatString: "DD MMM, 'YY")
author {
node {
name
}
}
featuredImage {
node {
localFile {
childImageSharp {
gatsbyImageData(
width: 750
placeholder: BLURRED
blurredOptions: {toFormat: NO_CHANGE}
formats: [AUTO, WEBP, AVIF]
)
}
}
altText
}
}
acfPosts {
readingTime
}
}
}
}
}
}
}
`
module.exports = async ( { actions, graphql } ) => {
const { createPage } = actions;
const fetchPosts = async () => {
// Do query to get all posts and posts, this will return the posts and posts.
return await graphql( GET_POSTS )
.then( ( { data } ) => {
const { allWpCategory: { categories } } = data;
return { categories: categories };
} );
};
// When the above fetchPosts is resolved, then loop through the results i.e posts to create posts.
await fetchPosts().then( ( { categories } ) => {
// 2. Create Single PAGE: Loop through all categories and create single archive page for posts.
categories &&
categories.map( ( category ) => {
/**
* Create Archive Pages with Pagination.
* This will create a each paginaion page in this loop at different URLs ( category.node.uri ) e.g. /category/adventure/
* And category ( which contains posts that belong to that category will be available )
*
* Paginated pages will be available at e.g. ( /category/adventure/ /category/adventure/2, /category/adventure/3 ) etc.
*/
createPaginatedPages({
edges: category.node.posts.nodes,
createPage: createPage,
pageTemplate: singlePageTemplate,
pageLength: 10, // This is optional and defaults to 10 if not used
pathPrefix: `${ category.node.uri.replace(/^\/|\/$/g, '') }`, // This is optional and defaults to an empty string if not used ( replaced the begining and trailing slash ),
context: { ...category, ...categories }, // This is optional and defaults to an empty object if not used
});
})
} )
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5l3.5-4.36V14.5z" /><path d="M15.5 14.5c0-.23.04-.46.07-.68-.92-.43-2.14-.82-3.57-.82-3 0-5.1 1.7-5.3 1.9l5.3 6.6 3.5-4.36V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /></g></React.Fragment>
, 'SignalWifi1BarLockTwoTone');
|
"gpsd client functions"
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
#
# This code run compatibly under Python 2 and 3.x for x >= 2.
# Preserve this property!
from __future__ import absolute_import, print_function, division
import json
import select
import socket
import sys
import time
from .misc import polystr, polybytes
from .watch_options import *
GPSD_PORT = "2947"
class gpscommon(object):
"Isolate socket handling and buffering from the protocol interpretation."
host = "127.0.0.1"
port = GPSD_PORT
def __init__(self, host="127.0.0.1", port=GPSD_PORT, verbose=0,
should_reconnect=False):
self.stream_command = b''
self.linebuffer = b''
self.received = time.time()
self.reconnect = should_reconnect
self.verbose = verbose
self.sock = None # in case we blow up in connect
# Provide the response in both 'str' and 'bytes' form
self.bresponse = b''
self.response = polystr(self.bresponse)
if host is not None:
self.host = host
if port is not None:
self.port = port
self.connect(self.host, self.port)
def connect(self, host, port):
"""Connect to a host on a given port.
If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.
"""
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
raise socket.error("nonnumeric port")
# if self.verbose > 0:
# print 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
# if self.debuglevel > 0: print 'connect:', (host, port)
self.sock.connect(sa)
if self.verbose > 0:
print('connected to tcp://{}:{}'.format(host, port))
break
# do not use except ConnectionRefusedError
# # Python 2.7 doc does have this exception
except socket.error as e:
if self.verbose > 1:
msg = str(e) + ' (to {}:{})'.format(host, port)
sys.stderr.write("error: {}\n".format(msg.strip()))
self.close()
raise # propogate error to caller
def close(self):
"Close the gpsd socket"
if self.sock:
self.sock.close()
self.sock = None
def __del__(self):
"Close the gpsd socket"
self.close()
def waiting(self, timeout=0):
"Return True if data is ready for the client."
if self.linebuffer:
return True
if self.sock is None:
return False
(winput, _woutput, _wexceptions) = select.select(
(self.sock,), (), (), timeout)
return winput != []
def read(self):
"Wait for and read data being streamed from the daemon."
if None is self.sock:
self.connect(self.host, self.port)
if None is self.sock:
return -1
self.stream()
eol = self.linebuffer.find(b'\n')
if eol == -1:
# RTCM3 JSON can be over 4.4k long, so go big
frag = self.sock.recv(8192)
self.linebuffer += frag
if not self.linebuffer:
if self.verbose > 1:
sys.stderr.write(
"poll: no available data: returning -1.\n")
# Read failed
return -1
eol = self.linebuffer.find(b'\n')
if eol == -1:
if self.verbose > 1:
sys.stderr.write("poll: partial message: returning 0.\n")
# Read succeeded, but only got a fragment
self.response = '' # Don't duplicate last response
return 0
else:
if self.verbose > 1:
sys.stderr.write("poll: fetching from buffer.\n")
# We got a line
eol += 1
# Provide the response in both 'str' and 'bytes' form
self.bresponse = self.linebuffer[:eol]
self.response = polystr(self.bresponse)
self.linebuffer = self.linebuffer[eol:]
# Can happen if daemon terminates while we're reading.
if not self.response:
return -1
if 1 < self.verbose:
sys.stderr.write("poll: data is %s\n" % repr(self.response))
self.received = time.time()
# We got a \n-terminated line
return len(self.response)
# Note that the 'data' method is sometimes shadowed by a name
# collision, rendering it unusable. The documentation recommends
# accessing 'response' directly. Consequently, no accessor method
# for 'bresponse' is currently provided.
def data(self):
"Return the client data buffer."
return self.response
def send(self, commands):
"Ship commands to the daemon."
lineend = "\n"
if isinstance(commands, bytes):
lineend = polybytes("\n")
if not commands.endswith(lineend):
commands += lineend
if self.sock is None:
self.stream_command = commands
else:
self.sock.send(polybytes(commands))
class json_error(BaseException):
"Class for JSON errors"
def __init__(self, data, explanation):
BaseException.__init__(self)
self.data = data
self.explanation = explanation
class gpsjson(object):
"Basic JSON decoding."
def __init__(self):
self.data = None
self.stream_command = None
self.verbose = -1
def __iter__(self):
"Broken __iter__"
return self
def unpack(self, buf):
"Unpack a JSON string"
try:
self.data = dictwrapper(json.loads(buf.strip(), encoding="ascii"))
except ValueError as e:
raise json_error(buf, e.args[0])
# Should be done for any other array-valued subobjects, too.
# This particular logic can fire on SKY or RTCM2 objects.
if hasattr(self.data, "satellites"):
self.data.satellites = [dictwrapper(x)
for x in self.data.satellites]
def stream(self, flags=0, devpath=None):
"Control streaming reports from the daemon,"
if 0 < flags:
self.stream_command = self.generate_stream_command(flags, devpath)
else:
self.stream_command = self.enqueued
if self.stream_command:
if self.verbose > 1:
sys.stderr.write("send: stream as:"
" {}\n".format(self.stream_command))
self.send(self.stream_command)
else:
raise TypeError("Invalid streaming command!! : " + str(flags))
def generate_stream_command(self, flags=0, devpath=None):
"Generate stream command"
if flags & WATCH_OLDSTYLE:
return self.generate_stream_command_old_style(flags)
return self.generate_stream_command_new_style(flags, devpath)
@staticmethod
def generate_stream_command_old_style(flags=0):
"Generate stream command, old style"
if flags & WATCH_DISABLE:
arg = "w-"
if flags & WATCH_NMEA:
arg += 'r-'
elif flags & WATCH_ENABLE:
arg = 'w+'
if flags & WATCH_NMEA:
arg += 'r+'
return arg
@staticmethod
def generate_stream_command_new_style(flags=0, devpath=None):
"Generate stream command, new style"
if (flags & (WATCH_JSON | WATCH_OLDSTYLE | WATCH_NMEA |
WATCH_RAW)) == 0:
flags |= WATCH_JSON
if flags & WATCH_DISABLE:
arg = '?WATCH={"enable":false'
if flags & WATCH_JSON:
arg += ',"json":false'
if flags & WATCH_NMEA:
arg += ',"nmea":false'
if flags & WATCH_RARE:
arg += ',"raw":1'
if flags & WATCH_RAW:
arg += ',"raw":2'
if flags & WATCH_SCALED:
arg += ',"scaled":false'
if flags & WATCH_TIMING:
arg += ',"timing":false'
if flags & WATCH_SPLIT24:
arg += ',"split24":false'
if flags & WATCH_PPS:
arg += ',"pps":false'
else: # flags & WATCH_ENABLE:
arg = '?WATCH={"enable":true'
if flags & WATCH_JSON:
arg += ',"json":true'
if flags & WATCH_NMEA:
arg += ',"nmea":true'
if flags & WATCH_RARE:
arg += ',"raw":1'
if flags & WATCH_RAW:
arg += ',"raw":2'
if flags & WATCH_SCALED:
arg += ',"scaled":true'
if flags & WATCH_TIMING:
arg += ',"timing":true'
if flags & WATCH_SPLIT24:
arg += ',"split24":true'
if flags & WATCH_PPS:
arg += ',"pps":true'
if flags & WATCH_DEVICE:
arg += ',"device":"%s"' % devpath
arg += "}"
return arg
class dictwrapper(object):
"Wrapper that yields both class and dictionary behavior,"
def __init__(self, ddict):
"Init class dictwrapper"
self.__dict__ = ddict
def get(self, k, d=None):
"Get dictwrapper"
return self.__dict__.get(k, d)
def keys(self):
"Keys dictwrapper"
return self.__dict__.keys()
def __getitem__(self, key):
"Emulate dictionary, for new-style interface."
return self.__dict__[key]
def __iter__(self):
"Iterate dictwrapper"
return self.__dict__.__iter__()
def __setitem__(self, key, val):
"Emulate dictionary, for new-style interface."
self.__dict__[key] = val
def __contains__(self, key):
"Find key in dictwrapper"
return key in self.__dict__
def __str__(self):
"dictwrapper to string"
return "<dictwrapper: " + str(self.__dict__) + ">"
__repr__ = __str__
def __len__(self):
"length of dictwrapper"
return len(self.__dict__)
#
# Someday a cleaner Python interface using this machinery will live here
#
# End
|
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, InsufficientFunds, InvalidOrder, OrderNotFound, AuthenticationError, BadSymbol } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class indodax extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'indodax',
'name': 'INDODAX',
'countries': [ 'ID' ], // Indonesia
'has': {
'cancelOrder': true,
'CORS': undefined,
'createMarketOrder': undefined,
'createOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchMarkets': true,
'fetchMyTrades': undefined,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': undefined,
'fetchTicker': true,
'fetchTickers': undefined,
'fetchTime': true,
'fetchTrades': true,
'withdraw': true,
},
'version': '2.0', // as of 9 April 2018
'urls': {
'logo': 'https://user-images.githubusercontent.com/51840849/87070508-9358c880-c221-11ea-8dc5-5391afbbb422.jpg',
'api': {
'public': 'https://indodax.com/api',
'private': 'https://indodax.com/tapi',
},
'www': 'https://www.indodax.com',
'doc': 'https://github.com/btcid/indodax-official-api-docs',
'referral': 'https://indodax.com/ref/testbitcoincoid/1',
},
'api': {
'public': {
'get': [
'server_time',
'pairs',
'{pair}/ticker',
'{pair}/trades',
'{pair}/depth',
],
},
'private': {
'post': [
'getInfo',
'transHistory',
'trade',
'tradeHistory',
'getOrder',
'openOrders',
'cancelOrder',
'orderHistory',
'withdrawCoin',
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'maker': 0,
'taker': 0.003,
},
},
'exceptions': {
'exact': {
'invalid_pair': BadSymbol, // {"error":"invalid_pair","error_description":"Invalid Pair"}
'Insufficient balance.': InsufficientFunds,
'invalid order.': OrderNotFound,
'Invalid credentials. API not found or session has expired.': AuthenticationError,
'Invalid credentials. Bad sign.': AuthenticationError,
},
'broad': {
'Minimum price': InvalidOrder,
'Minimum order': InvalidOrder,
},
},
// exchange-specific options
'options': {
'recvWindow': 5 * 1000, // default 5 sec
'timeDifference': 0, // the difference between system clock and exchange clock
'adjustForTimeDifference': false, // controls the adjustment logic upon instantiation
},
'commonCurrencies': {
'STR': 'XLM',
'BCHABC': 'BCH',
'BCHSV': 'BSV',
'DRK': 'DASH',
'NEM': 'XEM',
},
});
}
nonce () {
return this.milliseconds () - this.options['timeDifference'];
}
async fetchTime (params = {}) {
const response = await this.publicGetServerTime (params);
//
// {
// "timezone": "UTC",
// "server_time": 1571205969552
// }
//
return this.safeInteger (response, 'server_time');
}
async loadTimeDifference (params = {}) {
const serverTime = await this.fetchTime (params);
const after = this.milliseconds ();
this.options['timeDifference'] = after - serverTime;
return this.options['timeDifference'];
}
async fetchMarkets (params = {}) {
const response = await this.publicGetPairs (params);
//
// [
// {
// "id": "btcidr",
// "symbol": "BTCIDR",
// "base_currency": "idr",
// "traded_currency": "btc",
// "traded_currency_unit": "BTC",
// "description": "BTC/IDR",
// "ticker_id": "btc_idr",
// "volume_precision": 0,
// "price_precision": 1000,
// "price_round": 8,
// "pricescale": 1000,
// "trade_min_base_currency": 10000,
// "trade_min_traded_currency": 0.00007457,
// "has_memo": false,
// "memo_name": false,
// "has_payment_id": false,
// "trade_fee_percent": 0.3,
// "url_logo": "https://indodax.com/v2/logo/svg/color/btc.svg",
// "url_logo_png": "https://indodax.com/v2/logo/png/color/btc.png",
// "is_maintenance": 0
// }
// ]
//
const result = [];
for (let i = 0; i < response.length; i++) {
const market = response[i];
const id = this.safeString (market, 'ticker_id');
const baseId = this.safeString (market, 'traded_currency');
const quoteId = this.safeString (market, 'base_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const taker = this.safeNumber (market, 'trade_fee_percent');
const isMaintenance = this.safeInteger (market, 'is_maintenance');
const active = (isMaintenance) ? false : true;
const pricePrecision = this.safeInteger (market, 'price_round');
const precision = {
'amount': 8,
'price': pricePrecision,
};
const limits = {
'amount': {
'min': this.safeNumber (market, 'trade_min_traded_currency'),
'max': undefined,
},
'price': {
'min': this.safeNumber (market, 'trade_min_base_currency'),
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
};
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'type': 'spot',
'spot': true,
'active': active,
'taker': taker,
'percentage': true,
'precision': precision,
'limits': limits,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.privatePostGetInfo (params);
//
// {
// "success":1,
// "return":{
// "server_time":1619562628,
// "balance":{
// "idr":167,
// "btc":"0.00000000",
// "1inch":"0.00000000",
// },
// "balance_hold":{
// "idr":0,
// "btc":"0.00000000",
// "1inch":"0.00000000",
// },
// "address":{
// "btc":"1KMntgzvU7iTSgMBWc11nVuJjAyfW3qJyk",
// "1inch":"0x1106c8bb3172625e1f411c221be49161dac19355",
// "xrp":"rwWr7KUZ3ZFwzgaDGjKBysADByzxvohQ3C",
// "zrx":"0x1106c8bb3172625e1f411c221be49161dac19355"
// },
// "user_id":"276011",
// "name":"",
// "email":"testbitcoincoid@mailforspam.com",
// "profile_picture":null,
// "verification_status":"unverified",
// "gauth_enable":true
// }
// }
//
const balances = this.safeValue (response, 'return', {});
const free = this.safeValue (balances, 'balance', {});
const used = this.safeValue (balances, 'balance_hold', {});
const timestamp = this.safeTimestamp (balances, 'server_time');
const result = {
'info': response,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
};
const currencyIds = Object.keys (free);
for (let i = 0; i < currencyIds.length; i++) {
const currencyId = currencyIds[i];
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (free, currencyId);
account['used'] = this.safeString (used, currencyId);
result[code] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'pair': this.marketId (symbol),
};
const orderbook = await this.publicGetPairDepth (this.extend (request, params));
return this.parseOrderBook (orderbook, symbol, undefined, 'buy', 'sell');
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'pair': market['id'],
};
const response = await this.publicGetPairTicker (this.extend (request, params));
//
// {
// "ticker": {
// "high":"0.01951",
// "low":"0.01877",
// "vol_eth":"39.38839319",
// "vol_btc":"0.75320886",
// "last":"0.01896",
// "buy":"0.01896",
// "sell":"0.019",
// "server_time":1565248908
// }
// }
//
const ticker = response['ticker'];
const timestamp = this.safeTimestamp (ticker, 'server_time');
const baseVolume = 'vol_' + market['baseId'].toLowerCase ();
const quoteVolume = 'vol_' + market['quoteId'].toLowerCase ();
const last = this.safeNumber (ticker, 'last');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': this.safeNumber (ticker, 'buy'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'sell'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeNumber (ticker, baseVolume),
'quoteVolume': this.safeNumber (ticker, quoteVolume),
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
const timestamp = this.safeTimestamp (trade, 'date');
const id = this.safeString (trade, 'tid');
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
const type = undefined;
const side = this.safeString (trade, 'type');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': type,
'side': side,
'order': undefined,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': undefined,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'pair': market['id'],
};
const response = await this.publicGetPairTrades (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
parseOrderStatus (status) {
const statuses = {
'open': 'open',
'filled': 'closed',
'cancelled': 'canceled',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// {
// "order_id": "12345",
// "submit_time": "1392228122",
// "price": "8000000",
// "type": "sell",
// "order_ltc": "100000000",
// "remain_ltc": "100000000"
// }
//
// market closed orders - note that the price is very high
// and does not reflect actual price the order executed at
//
// {
// "order_id": "49326856",
// "type": "sell",
// "price": "1000000000",
// "submit_time": "1618314671",
// "finish_time": "1618314671",
// "status": "filled",
// "order_xrp": "30.45000000",
// "remain_xrp": "0.00000000"
// }
let side = undefined;
if ('type' in order) {
side = order['type'];
}
const status = this.parseOrderStatus (this.safeString (order, 'status', 'open'));
let symbol = undefined;
let cost = undefined;
const price = this.safeString (order, 'price');
let amount = undefined;
let remaining = undefined;
if (market !== undefined) {
symbol = market['symbol'];
let quoteId = market['quoteId'];
let baseId = market['baseId'];
if ((market['quoteId'] === 'idr') && ('order_rp' in order)) {
quoteId = 'rp';
}
if ((market['baseId'] === 'idr') && ('remain_rp' in order)) {
baseId = 'rp';
}
cost = this.safeString (order, 'order_' + quoteId);
if (!cost) {
amount = this.safeString (order, 'order_' + baseId);
remaining = this.safeString (order, 'remain_' + baseId);
}
}
const timestamp = this.safeInteger (order, 'submit_time');
const fee = undefined;
const id = this.safeString (order, 'order_id');
return this.safeOrder2 ({
'info': order,
'id': id,
'clientOrderId': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': 'limit',
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'cost': cost,
'average': undefined,
'amount': amount,
'filled': undefined,
'remaining': remaining,
'status': status,
'fee': fee,
'trades': undefined,
});
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'pair': market['id'],
'order_id': id,
};
const response = await this.privatePostGetOrder (this.extend (request, params));
const orders = response['return'];
const order = this.parseOrder (this.extend ({ 'id': id }, orders['order']), market);
return this.extend ({ 'info': response }, order);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['pair'] = market['id'];
}
const response = await this.privatePostOpenOrders (this.extend (request, params));
const rawOrders = response['return']['orders'];
// { success: 1, return: { orders: null }} if no orders
if (!rawOrders) {
return [];
}
// { success: 1, return: { orders: [ ... objects ] }} for orders fetched by symbol
if (symbol !== undefined) {
return this.parseOrders (rawOrders, market, since, limit);
}
// { success: 1, return: { orders: { marketid: [ ... objects ] }}} if all orders are fetched
const marketIds = Object.keys (rawOrders);
let exchangeOrders = [];
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const marketOrders = rawOrders[marketId];
market = this.markets_by_id[marketId];
const parsedOrders = this.parseOrders (marketOrders, market, since, limit);
exchangeOrders = this.arrayConcat (exchangeOrders, parsedOrders);
}
return exchangeOrders;
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const request = {};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['pair'] = market['id'];
}
const response = await this.privatePostOrderHistory (this.extend (request, params));
let orders = this.parseOrders (response['return']['orders'], market);
orders = this.filterBy (orders, 'status', 'closed');
return this.filterBySymbolSinceLimit (orders, symbol, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type !== 'limit') {
throw new ExchangeError (this.id + ' allows limit orders only');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'pair': market['id'],
'type': side,
'price': price,
};
const currency = market['baseId'];
if (side === 'buy') {
request[market['quoteId']] = amount * price;
} else {
request[market['baseId']] = amount;
}
request[currency] = amount;
const result = await this.privatePostTrade (this.extend (request, params));
const data = this.safeValue (result, 'return', {});
const id = this.safeString (data, 'order_id');
return {
'info': result,
'id': id,
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
const side = this.safeValue (params, 'side');
if (side === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires an extra "side" param');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'order_id': id,
'pair': market['id'],
'type': side,
};
return await this.privatePostCancelOrder (this.extend (request, params));
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
// Custom string you need to provide to identify each withdrawal.
// Will be passed to callback URL (assigned via website to the API key)
// so your system can identify the request and confirm it.
// Alphanumeric, max length 255.
const requestId = this.milliseconds ();
// Alternatively:
// let requestId = this.uuid ();
const request = {
'currency': currency['id'],
'withdraw_amount': amount,
'withdraw_address': address,
'request_id': requestId.toString (),
};
if (tag) {
request['withdraw_memo'] = tag;
}
const response = await this.privatePostWithdrawCoin (this.extend (request, params));
//
// {
// "success": 1,
// "status": "approved",
// "withdraw_currency": "xrp",
// "withdraw_address": "rwWr7KUZ3ZFwzgaDGjKBysADByzxvohQ3C",
// "withdraw_amount": "10000.00000000",
// "fee": "2.00000000",
// "amount_after_fee": "9998.00000000",
// "submit_time": "1509469200",
// "withdraw_id": "xrp-12345",
// "txid": "",
// "withdraw_memo": "123123"
// }
//
let id = undefined;
if (('txid' in response) && (response['txid'].length > 0)) {
id = response['txid'];
}
return {
'info': response,
'id': id,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'][api];
if (api === 'public') {
url += '/' + this.implodeParams (path, params);
} else {
this.checkRequiredCredentials ();
body = this.urlencode (this.extend ({
'method': path,
'timestamp': this.nonce (),
'recvWindow': this.options['recvWindow'],
}, params));
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': this.apiKey,
'Sign': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (response === undefined) {
return;
}
// { success: 0, error: "invalid order." }
// or
// [{ data, ... }, { ... }, ... ]
if (Array.isArray (response)) {
return; // public endpoints may return []-arrays
}
const error = this.safeValue (response, 'error', '');
if (!('success' in response) && error === '') {
return; // no 'success' property on public responses
}
if (this.safeInteger (response, 'success', 0) === 1) {
// { success: 1, return: { orders: [] }}
if (!('return' in response)) {
throw new ExchangeError (this.id + ': malformed response: ' + this.json (response));
} else {
return;
}
}
const feedback = this.id + ' ' + body;
this.throwExactlyMatchedException (this.exceptions['exact'], error, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], error, feedback);
throw new ExchangeError (feedback); // unknown message
}
};
|
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var ViewAgenda = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z", key: "k0" }),
React.createElement("path", { d: "M21 13H2v8h19v-8zm0-10H2v8h19V3z", key: "k1" })));
});
ViewAgenda.displayName = 'ViewAgenda';
export var ViewAgendaDimensions = { height: 24, width: 24 };
|
import React, { Component, PropTypes } from 'react';
import HeaderBar from './HeaderBar';
import Board from './Board';
class Project extends Component {
static propTypes = {
projectName: PropTypes.string.isRequired,
entries: PropTypes.array.isRequired,
};
state = {
sidebarVisible: false
};
toggleSidebar = () => (
this.setState({ sidebarVisible: !this.state.sidebarVisible })
);
render() {
const { entries, projectName } = this.props;
const { sidebarVisible } = this.state;
return (
<div>
<HeaderBar
projectName={projectName}
sidebarVisible={sidebarVisible}
onToggleSidebar={this.toggleSidebar} />
<Board entries={entries} sidebarVisible={sidebarVisible} />
</div>
);
}
}
export default Project;
|