hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
9116585c753882b470b901df8c25de3fd519c327
841
js
JavaScript
source/utility/parseDate.test.js
catamphetamine/react-responsive-ui
fb08eb0ecc9091b7fba2ff55c0837009055f1ea7
[ "MIT" ]
57
2017-07-29T12:09:07.000Z
2020-04-03T20:37:33.000Z
source/utility/parseDate.test.js
catamphetamine/react-responsive-ui
fb08eb0ecc9091b7fba2ff55c0837009055f1ea7
[ "MIT" ]
7
2017-08-11T18:34:33.000Z
2022-03-29T14:31:40.000Z
source/utility/parseDate.test.js
catamphetamine/react-responsive-ui
fb08eb0ecc9091b7fba2ff55c0837009055f1ea7
[ "MIT" ]
9
2017-08-11T16:03:32.000Z
2020-09-08T09:31:18.000Z
import parseDate, { correspondsToTemplate } from './parseDate' describe('parseDate', () => { it('should parse dates', () => { expect(parseDate('fadsfasd', 'dd.mm.yyyy', true)).to.be.undefined expect(parseDate('28.02.2017', 'dd.mm.yyyy', true).toISOString()).to.equal('2017-02-28T00:00:00.000Z') expect(parseDate('12/02/2017', 'mm/dd/yyyy', true).toISOString()).to.equal('2017-12-02T00:00:00.000Z') expect(parseDate('99/99/2017', 'mm/dd/yyyy', true).toISOString()).to.equal('2025-06-07T00:00:00.000Z') expect(parseDate('02/03/17', 'mm/dd/yy', true).toISOString()).to.equal('2017-02-03T00:00:00.000Z') }) it('should detect if a string corresponds to template', () => { expect(correspondsToTemplate('1231231234', 'dd.mm.yyyy')).to.equal(false) expect(correspondsToTemplate('12.12.1234', 'dd.mm.yyyy')).to.equal(true) }) })
44.263158
104
0.678954
9116a7770c70c83329ede28a90b0888e37e8f60a
6,333
js
JavaScript
src/components/anchor-navigation/anchor-navigation.stories.js
arturodrigues/carbon
3416303d82758d60957d26da0fa5cd878e84b875
[ "Apache-2.0" ]
null
null
null
src/components/anchor-navigation/anchor-navigation.stories.js
arturodrigues/carbon
3416303d82758d60957d26da0fa5cd878e84b875
[ "Apache-2.0" ]
null
null
null
src/components/anchor-navigation/anchor-navigation.stories.js
arturodrigues/carbon
3416303d82758d60957d26da0fa5cd878e84b875
[ "Apache-2.0" ]
13
2020-05-05T06:26:37.000Z
2020-05-08T05:43:07.000Z
import React, { useRef } from 'react'; import { State, Store } from '@sambego/storybook-state'; import { dlsThemeSelector } from '../../../.storybook/theme-selectors'; import Textbox from '../../__experimental__/components/textbox'; import Button from '../button'; import DialogFullScreen from '../dialog-full-screen'; import { AnchorNavigation, AnchorSectionDivider, AnchorNavigationItem } from '.'; // eslint-disable-next-line react/prop-types const Content = ({ title, noTextbox }) => ( <> <div> <h2> {title} </h2> {!noTextbox && <Textbox label={ title } />} <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> <p style={ { marginTop: 30, marginBottom: 30 } }>Content</p> </div> </> ); export default { title: 'Test/AnchorNavigation', component: AnchorNavigation, parameters: { themeSelector: dlsThemeSelector, info: { disable: true } } }; export const Basic = () => { const ref1 = useRef(); const ref2 = useRef(); const ref3 = useRef(); const ref4 = useRef(); const ref5 = useRef(); return ( <AnchorNavigation stickyNavigation={ ( <> <AnchorNavigationItem target={ ref1 }> First </AnchorNavigationItem> <AnchorNavigationItem target={ ref2 }> Second </AnchorNavigationItem> <AnchorNavigationItem target={ ref3 }> Third </AnchorNavigationItem> <AnchorNavigationItem target={ ref4 }> Navigation item with very long label </AnchorNavigationItem> <AnchorNavigationItem target={ ref5 }> Fifth </AnchorNavigationItem> </> ) } > <div ref={ ref1 }> <Content title='First section' /> </div> <AnchorSectionDivider /> <div ref={ ref2 }> <Content title='Second section' /> </div> <AnchorSectionDivider /> <div ref={ ref3 }> <Content noTextbox title='Third section' /> </div> <AnchorSectionDivider /> <div ref={ ref4 }> <Content title='Fourth section' /> </div> <AnchorSectionDivider /> <div ref={ ref5 }> <Content title='Fifth section' /> </div> </AnchorNavigation> ); }; const store = new Store({ open: false }); const handleOpen = () => { store.set({ open: true }); }; const handleClose = () => { store.set({ open: false }); }; export const InFullScreenDialog = () => { const ref1 = useRef(); const ref2 = useRef(); const ref3 = useRef(); const ref4 = useRef(); const ref5 = useRef(); return ( <> <Button onClick={ handleOpen }>Open AnchorNavigation</Button> <State store={ store }> <DialogFullScreen open={ store.get('open') } onCancel={ handleClose } title='Title' subtitle='Subtitle' > <AnchorNavigation stickyNavigation={ ( <> <AnchorNavigationItem target={ ref1 }> First </AnchorNavigationItem> <AnchorNavigationItem target={ ref2 }> Second </AnchorNavigationItem> <AnchorNavigationItem target={ ref3 }> Third </AnchorNavigationItem> <AnchorNavigationItem target={ ref4 }> Navigation item with very long label </AnchorNavigationItem> <AnchorNavigationItem target={ ref5 }> Fifth </AnchorNavigationItem> </> ) } > <div ref={ ref1 }> <Content title='First section' /> </div> <AnchorSectionDivider /> <div ref={ ref2 }> <Content title='Second section' /> </div> <AnchorSectionDivider /> <div ref={ ref3 }> <Content noTextbox title='Third section' /> </div> <AnchorSectionDivider /> <div ref={ ref4 }> <Content title='Fourth section' /> </div> <AnchorSectionDivider /> <div ref={ ref5 }> <Content title='Fifth section' /> </div> </AnchorNavigation> </DialogFullScreen> </State> </> ); }; export const WithOverridenStyles = () => { const ref1 = useRef(); const ref2 = useRef(); const ref3 = useRef(); const ref4 = useRef(); const ref5 = useRef(); return ( <AnchorNavigation styleOverride={ { root: { backgroundColor: '#F2F5F6' }, content: { marginLeft: 96, marginRight: 96 }, navigation: { maxWidth: 450, top: 100, marginTop: 24 } } } stickyNavigation={ ( <> <AnchorNavigationItem target={ ref1 }> First </AnchorNavigationItem> <AnchorNavigationItem target={ ref2 }> Second </AnchorNavigationItem> <AnchorNavigationItem target={ ref3 }> Third </AnchorNavigationItem> <AnchorNavigationItem target={ ref4 }> Navigation item with very long label </AnchorNavigationItem> <AnchorNavigationItem target={ ref5 } styleOverride={ { textDecoration: 'underline' } }> Fifth </AnchorNavigationItem> </> ) } > <div ref={ ref1 }> <Content title='First section' /> </div> <AnchorSectionDivider styleOverride={ { backgroundColor: 'white' } } /> <div ref={ ref2 }> <Content title='Second section' /> </div> <AnchorSectionDivider /> <div ref={ ref3 }> <Content noTextbox title='Third section' /> </div> <AnchorSectionDivider /> <div ref={ ref4 }> <Content title='Fourth section' /> </div> <AnchorSectionDivider /> <div ref={ ref5 }> <Content title='Fifth section' /> </div> </AnchorNavigation> ); };
28.146667
98
0.532923
91173327b532f2678524d665f672cf5c3452bba4
515
js
JavaScript
src/components/spinner/Spinner.js
ABONEMR/goit-react-hw-08-phonebook
51468ad65ff1fd2d3a63ae55dc6c551896f44492
[ "MIT" ]
null
null
null
src/components/spinner/Spinner.js
ABONEMR/goit-react-hw-08-phonebook
51468ad65ff1fd2d3a63ae55dc6c551896f44492
[ "MIT" ]
null
null
null
src/components/spinner/Spinner.js
ABONEMR/goit-react-hw-08-phonebook
51468ad65ff1fd2d3a63ae55dc6c551896f44492
[ "MIT" ]
1
2022-02-06T10:57:48.000Z
2022-02-06T10:57:48.000Z
import React from 'react'; import { Bars } from 'react-loader-spinner'; import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css'; import styled from 'styled-components'; export default function Spinner() { return ( <SpinnerWrapper> <Bars heigth="100" width="100" color="#f6f4f3" ariaLabel="loading" /> </SpinnerWrapper> ); } const SpinnerWrapper = styled.div` display: flex; align-items: center; justify-content: center; width: 100%; height: auto; margin-top: 10px; `;
23.409091
75
0.695146
911743d8d9a6e3f030b561c0df10f20dfb116245
312
js
JavaScript
config.js
wwddesigns/Cakemonbot
06f4678ce71e9b6832cf293e73240c1a656e11b1
[ "MIT" ]
null
null
null
config.js
wwddesigns/Cakemonbot
06f4678ce71e9b6832cf293e73240c1a656e11b1
[ "MIT" ]
null
null
null
config.js
wwddesigns/Cakemonbot
06f4678ce71e9b6832cf293e73240c1a656e11b1
[ "MIT" ]
null
null
null
module.exports = { subdomain: "api", consumer_key: "KD0yHQFWMeIQ3vjMmRefWdRm3", consumer_secret: "ix3QESATJIanzw2vxaTkmbgrckgdsxjnPMGeDGVBe5K6PxRZRX", access_token_key: "2321203640-3TqFo5k03lQ36H3FrOctCtCyJk5T35wE46o5BBn", access_token_secret: "SCSByd6uk2GfPVfvX5pz7oa38BWtUMBORi19LOHDbVkGh" };
39
74
0.820513
9118454235124b92cf260f7b051531b920bb4e81
1,200
js
JavaScript
src/server/game/entities/attributes.js
macbury/codequest
621c5c6f8820dfb006eac15248a3bdf5a695d86a
[ "MIT" ]
null
null
null
src/server/game/entities/attributes.js
macbury/codequest
621c5c6f8820dfb006eac15248a3bdf5a695d86a
[ "MIT" ]
null
null
null
src/server/game/entities/attributes.js
macbury/codequest
621c5c6f8820dfb006eac15248a3bdf5a695d86a
[ "MIT" ]
null
null
null
export default class Attributes { constructor(data) { this.data = data this.dirty = !this.isEmpty() } getEnum(key, EnumType, defaultVal) { if (this.isPresent(key)) { return EnumType.get(this.get(key)) } return defaultVal } setEnum(key, enumVal) { this.set(key, enumVal.value) } get(key, defaultValue) { return this.data[key] || defaultValue } set(key, value, quiet) { if (value == null) { throw `Use remove to clear value for ${key}` } this.data[key] = value if (!this.dirty) { this.dirty = !quiet } } updateAll(newState) { this.data = newState this.dirty = true } isEqual(key, value) { return this.get(key) == value } getUpdatePacket() { return {...this.data} } remove(key, quiet) { delete this.data[key] if (!this.dirty) { this.dirty = !quiet } } isNull(key) { return this.data[key] == null } isPresent(key) { return !this.isNull(key) } isEmpty() { return Object.keys(this.data).length == 0 } isDirty() { return this.dirty } markAsDirty() { this.dirty = true } markAsClean() { this.dirty = false } }
15.789474
50
0.5725
9119291acf913d24add17974c31b2f38e7a14e8f
3,156
js
JavaScript
Briefly/frontend/src/components/pages/landing_page_properties/LandingPageAbout.js
q815101630/Briefly2.0
d92ba52308ef8c644fe8fb453169d0bee1a7f47e
[ "MIT" ]
null
null
null
Briefly/frontend/src/components/pages/landing_page_properties/LandingPageAbout.js
q815101630/Briefly2.0
d92ba52308ef8c644fe8fb453169d0bee1a7f47e
[ "MIT" ]
null
null
null
Briefly/frontend/src/components/pages/landing_page_properties/LandingPageAbout.js
q815101630/Briefly2.0
d92ba52308ef8c644fe8fb453169d0bee1a7f47e
[ "MIT" ]
1
2021-10-06T03:50:19.000Z
2021-10-06T03:50:19.000Z
import { makeStyles } from "@material-ui/styles"; import React from "react"; import { Grid, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ captionMargins: { marginTop: "100px", marginBottom: "50px", fontSize: "45px", }, emphasizedBody1: { ...theme.typography.emphasizedBody1, fontFamily: "Roboto", fontWeight: 400, fontSize: "1.3rem", color: "#2c3e50", lineHeight: 2, }, })); export const AboutSection = () => { const classes = useStyles(); return ( <Grid justify="center" alignItems="center" container direction="column" id="about-us" style={{ marginBottom: "3rem" }} > <Typography className={classes.captionMargins} variant="h2" align="center"> About Us </Typography> <Grid item style={{ width: "80%" }}> <Typography className={classes.emphasizedBody1} variant="h5"> We are a group of dedicated college students who try to use AI technology to improve online learning effciency by building a powerful content management platform - Briefly. As online learning is gaining momentum globally due to the covid-19, students are experiencing dramatic changes in their learning environments and methods; many international students are not able to attend online live lectures due to time zone differences. Thus, finding new and useful methods for all remote learning students becomes unspeakably important. As Zoom is becoming the most popular online class platform, many students reported difficulties in following along with the online lecture contents, especially among international students or those with language barriers. As a study posted in the journal of Clinical and Diagnostic Research, almost 40% of students could not keep themselves up-to-date along with the teaching in flipped class sessions taken in online mode, and the study further shows that 40 minutes is an optimized zoom lecture duration for the best student feedback. Due to the nature of online lecturing form, class interaction, one of the most important class components, is usually missing; therefore, many students are having a hard time fully absorbing lecture contents. Also with the remote learning setting, professors may not be able to guarantee all students’ level of understanding during the lecture. Thus, it becomes students’ responsibility to rewatch lecture videos or to read the supported text to achieve academic advancement. However, it is usually difficult to comprehend all important messages given in long video, audio, or text sources without knowing what to look for. In fact, not only students find it difficult, but many businesses or people with hearing disorders also need an efficient method to collect important insights from video or text data. A solution is urgently needed to accommodate these problems. </Typography> </Grid> </Grid> ); };
48.553846
100
0.694867
911a123ee4e2d562dfcf04a53fe0cebf32932041
609
js
JavaScript
Public/banter.min.js
Davidde94/BanterURL
7b94fad8bf12607c01ac605534f58b10fd369766
[ "MIT" ]
1
2020-06-14T00:24:42.000Z
2020-06-14T00:24:42.000Z
Public/banter.min.js
Davidde94/BanterURL
7b94fad8bf12607c01ac605534f58b10fd369766
[ "MIT" ]
null
null
null
Public/banter.min.js
Davidde94/BanterURL
7b94fad8bf12607c01ac605534f58b10fd369766
[ "MIT" ]
1
2020-06-14T00:24:43.000Z
2020-06-14T00:24:43.000Z
$(document).ready(function(){$("#mainForm").submit(function(b){b.preventDefault();var c=$(this).serializeArray();var a={};$.each(c,function(){a[this.name]=this.value||""});a=JSON.stringify(a);$.ajax({type:"POST",url:$("#mainForm").attr("action"),dataType:"json",contentType:"application/json",data:a}).done(function(e){var d=e.url;$("#resultBox").show();$("#link").text(d)}).fail(function(d){console.log(d)})});$("#link").click(function(){var a=$("<input>");$("body").append(a);a.val($("#link").text()).select();document.execCommand("copy");a.remove();console.log("copied to clipboard! "+$(this).text())})});
304.5
608
0.646962
911a1fe1463edd61df978742fcfe2119acbdfa4c
1,281
js
JavaScript
src/store/types.js
vinsol-spree-contrib/spree-on-vue
8ba733a5cc4ce6f84e4aa158e3107990c81d6baa
[ "MIT" ]
10
2018-12-20T05:05:27.000Z
2021-05-18T12:56:15.000Z
src/store/types.js
vinsol-spree-contrib/spree-on-vue
8ba733a5cc4ce6f84e4aa158e3107990c81d6baa
[ "MIT" ]
null
null
null
src/store/types.js
vinsol-spree-contrib/spree-on-vue
8ba733a5cc4ce6f84e4aa158e3107990c81d6baa
[ "MIT" ]
8
2019-01-20T07:02:29.000Z
2020-11-24T14:26:25.000Z
// Getters export const GET_TAXONS = 'taxons/GET_TAXONS'; export const GET_PRODUCTS = 'products/GET_PRODUCTS'; export const GET_PRODUCT = 'products/GET_PRODUCT'; export const GET_USER = 'users/GET_USER'; export const GET_LOGIN_USER = 'session/GET_LOGIN_USER' export const GET_SEARCH_RESULTS = 'products/GET_SEARCH_RESULTS'; export const GET_TAXON_PRODUCTS = 'products/GET_TAXON_PRODUCTS'; // Mutations export const MUTATE_SET_TAXONS = 'taxons/MUTATE_SET_TAXONS'; export const MUTATE_SET_PRODUCTS = 'products/MUTATE_SET_PRODUCTS'; export const MUTATE_SET_PRODUCT = 'products/MUTATE_SET_PRODUCT'; export const MUTATE_SET_USER = 'users/MUTATE_SET_USER'; export const MUTATE_SET_LOGIN_USER = 'session/MUTATE_SET_LOGIN_USER'; export const MUTATE_SEARCH_RESULTS = 'products/MUTATE_SEARCH_RESULTS'; export const MUTATE_TAXON_PRODUCTS = 'products/SET_TAXON_PRODUCTS'; // Actions export const FETCH_TAXONS = 'taxons/FETCH_TAXONS'; export const FETCH_PRODUCTS = 'products/FETCH_PRODUCTS'; export const FETCH_PRODUCT = 'products/FETCH_PRODUCT'; export const FETCH_USER = 'users/FETCH_USER'; export const LOGIN = "session/FETCH_LOGGED_IN_USER"; export const SIGNUP = "session/FETCH_NEW_USER"; export const SEARCH = 'products/SEARCH'; export const TAXON_PRODUCTS = 'products/TAXON_PRODUCTS';
45.75
70
0.818111
911b462b8812529a1f79d71d326769a3961298ef
1,374
js
JavaScript
widget/util/JUpload.js
jinxiaonb/basicFE
7e5c223a1a9994ea8bc03180644ee1a6cdee5a02
[ "MIT" ]
null
null
null
widget/util/JUpload.js
jinxiaonb/basicFE
7e5c223a1a9994ea8bc03180644ee1a6cdee5a02
[ "MIT" ]
null
null
null
widget/util/JUpload.js
jinxiaonb/basicFE
7e5c223a1a9994ea8bc03180644ee1a6cdee5a02
[ "MIT" ]
null
null
null
define([], function() { var imgUpload = { init: function(ele, userava, pattern, uploadurl) { //ele:input file id,userava:上传后返回的图片地址 $("#" + ele).change(function(e) { var _this = $(this); var _fileInput = _this[0]; //console.log(_fileInput); var byteSize = _fileInput.files[0].size; //console.log(_fileInput.files[0]); //console.log(byteSize); if (!(_this.val().match(/.*(.jpg|.gif|.png|.txt|.doc|.docx|.pdf)$/))) { //tip.setErrorText($(".error"),"上传的图片类型必须是jpg,gif或png格式!"); return false; } imgUpload.ajaxFileUpload(ele, userava, pattern, uploadurl); }); }, ajaxFileUpload: function(element, userava, pattern, uploadurl) { var formData = new FormData(); formData.append('uploadFile', document.getElementById(element).files[0]); $.ajax({ url: uploadurl, type: 'post', data: formData, cache: false, contentType: false, processData: false, success: function(data) { console.log(data); if (data.result) { if (pattern == "a") { $(userava).attr("href", data.fileUrl); } else if (pattern == "img") { $(userava).attr("src", data.imageUrl); } else if (pattern == "file") { $(userava).val(data.fileUrl); } } }, error: function(msg) { console.log(msg); } }); return false; } }; return imgUpload; });
26.941176
91
0.585881
911c922d913579c1783bee73a94182f0dfe8ac55
500
js
JavaScript
routes/main_database.js
geo-c/OCT
727da1290ae6b867aeb64ba816d439152779d93a
[ "MIT" ]
null
null
null
routes/main_database.js
geo-c/OCT
727da1290ae6b867aeb64ba816d439152779d93a
[ "MIT" ]
null
null
null
routes/main_database.js
geo-c/OCT
727da1290ae6b867aeb64ba816d439152779d93a
[ "MIT" ]
1
2016-11-29T09:39:48.000Z
2016-11-29T09:39:48.000Z
var express = require('express'); var router = express.Router(); var list = require('../controllers/main_database/list'); var listAll = require('../controllers/main_database/listAll'); var listAllUser = require('../controllers/main_database/listAllUser'); // LIST router.get('/main_database', list.request); router.get('/database_all', listAll.request); router.get('/database_all/:username', listAllUser.request); // TODO: // POST // DELETE ALL // GET // PUT // DELETE module.exports = router;
21.73913
70
0.718
911cac7e4881e1e9891b2f701f19a58f1f14c9f3
16,156
js
JavaScript
pages/share/share.js
KateJun/MiniGame24
9460cc2b760c18bef3b6d1b32fcbdd46e9f7b556
[ "Apache-2.0" ]
8
2018-04-04T10:18:17.000Z
2021-04-05T02:23:20.000Z
pages/share/share.js
KateJun/MiniGame24
9460cc2b760c18bef3b6d1b32fcbdd46e9f7b556
[ "Apache-2.0" ]
1
2019-02-26T08:59:38.000Z
2019-02-26T08:59:38.000Z
pages/share/share.js
KateJun/MiniGame24
9460cc2b760c18bef3b6d1b32fcbdd46e9f7b556
[ "Apache-2.0" ]
1
2019-03-11T07:19:16.000Z
2019-03-11T07:19:16.000Z
// pages/share/share.js var app = getApp(); var req = require("../../utils/request.js") Page({ /** * 页面的初始数据 */ data: { CANVAS_ID: 'canvas_id', PIC_BG: '../../images/score_bg.jpg', PIC_LOGO: '../../images/score_logo_top.png', PIC_SEAL: '../../images/score_seal.png', PIC_SQURE: '../../images/score_square.png', PIC_QR: '../../images/score_qr_new.jpg', screenWH: [], allPicInfo: {}, baseWidth: 750, radio: 1, xyLogo: [0, 10], xyNums: [20, 235], xyPhoto: [100, 375], whPhoto: [160, 160], xyScore: [280, 405], xyEvaluationBg: [20, 565], xyEvaluationPercent: [155, 620], xyEvaluationTitle: [500, 620], xyEvaluationResult: [320, 660], xyEvaluationSum: [0, 770], xyShareBg: [0, -340], xyShareText: [75, -340 + 55], xyShareQR: [750 - 20 - 300, -340 + 20], margin20: 20, font26: 26, font32: 32, font36: 36, font48: 48, font40: 40, font60: 60, font80: 80, colorTextBlack: '#3e4a53', colorTextBlue: '#61ada8', colorTextGreen: '#317e50', colorTextWhite: '#ffffff', result: ['1', '2', '7', '7'], resultText: ['通过加减乘除', '得出24!'], resultScoreTitle: '我的最终算力评分', resultScore: '321', resultEvaluation: ['98%', '算力堪比', 'intel i7 7790k', '无敌是种怎样的体验?', 48], resultShareText: ['这里是24点算力测评', '据说', '只有智力', '不同于普通人', '的', '才喜欢玩', '长按识别立即体验'], userInfo: {}, userImg: '', userNickName: '', hasUserInfo: false, discuss: [ { minScore: -1, maxScore: 0, desc: '没有什么可以对比的', dis: '可以尝试着换颗脑袋', per: '0.1%', fontSize: 36 }, { minScore: 1, maxScore: 120, desc: '赛扬D 365 ', dis: '勉勉强强能算个1+1', per: '38%', fontSize: 48 }, //<=120 { minScore: 121, maxScore: 254, desc: '酷睿2 E6600', dis: '加油已经可以运算加减乘除', per: '58%', fontSize: 48 }, { minScore: 255, maxScore: 405, desc: '酷睿i3 7300', dis: '有点厉害', per: '68%', fontSize: 48 }, { minScore: 406, maxScore: 630, desc: '酷睿i5 7640X', dis: '跪求一败', per: '78%', fontSize: 48 }, { minScore: 631, maxScore: 800, desc: '酷睿i7 7820X', dis: '人形计算机', per: '88%', fontSize: 48 }, { minScore: 801, maxScore: 1000, desc: '酷睿i9 7980XE ', dis: '无敌是多么寂寞', per: '98%', fontSize: 48 }, { minScore: 1001, maxScore: 10000, desc: '未知生物', dis: '作弊是种怎样的体验?', per: '1%', fontSize: 48 } ], }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; that.initPhoto() that.loadHeader(function () { if (that.getScreenWH()) { // that.data.radio = that.data.screenWH[2] ; that.data.radio = that.data.screenWH[0] / that.data.baseWidth; that.getAllPicInfo(function (result) { if (result) { that.drawPage(that); } }); } }) }, loadHeader(c) { var context = this wx.downloadFile({ url: context.data.userImg, success(res) { console.log('tempimage', res) if (res.statusCode == 200) { context.data.userImg = res.tempFilePath } else { context.data.userImg = "../../images/avatar_default.png" } c() }, fail(res) { context.data.userImg = "../../images/avatar_default.png" c() } }) }, initPhoto: function () { var that = this; that.data.userInfo = app.globalData.userInfo; that.data.userImg = app.globalData.userInfo.avatarUrl; try { var ls = wx.getStorageSync("lastScore") if (ls == '') { ls = 0 } } catch (e) { ls = 0 } that.data.resultScore = ls for (var i = 0; i < that.data.discuss.length; i++) { if (ls <= that.data.discuss[i].maxScore && ls >= that.data.discuss[i].minScore) { var cur = that.data.discuss[i] that.data.resultEvaluation[0] = cur.per that.data.resultEvaluation[2] = cur.desc that.data.resultEvaluation[3] = cur.dis that.data.resultEvaluation[4] = cur.fontSize break } } }, getScreenWH: function (call) { try { var res = wx.getSystemInfoSync(); this.data.screenWH.push(res.windowWidth); this.data.screenWH.push(res.windowHeight); this.data.screenWH.push(res.pixelRatio); return true; } catch (e) { wx.getSystemInfo({ success: function (res) { this.data.screenWH.push(res.windowWidth); this.data.screenWH.push(res.windowHeight); this.data.screenWH.push(res.pixelRatio); return (true) }, }) console.log('Get System info error!'); return false; } }, getAllPicInfo: function (callback) { var allPicRelativePath = [this.data.PIC_BG, this.data.PIC_LOGO, this.data.PIC_SEAL, this.data.PIC_SQURE, this.data.PIC_QR]; this.getOnePicInfo(this, allPicRelativePath, this.data.allPicInfo, function (result) { if (result) { if (callback) { callback(true); } } else { console.log('获取图片信息失败'); if (callback) { callback(false); } } }); }, getOnePicInfo: function (context, allPicRelativePath, allPicInfo, callback) { if (allPicRelativePath.length < 1) { if (callback) { callback(true); } return; } var path = allPicRelativePath[0]; allPicRelativePath.splice(0, 1); wx.getImageInfo({ src: path, success: function (res) { allPicInfo[path] = res; context.getOnePicInfo(context, allPicRelativePath, allPicInfo, callback); }, fail: function (res) { console.log('获取图片path=' + path + '失败'); if (callback) { callback(false); } } }) }, drawPage: function (context) { const canvas = wx.createCanvasContext(context.data.CANVAS_ID); context.drawBg(context, canvas); context.drawLogo(context, canvas); context.drawAnswer(context, canvas); context.drawPhoto(context, canvas); context.drawScore(context, canvas); context.drawEvaluation(context, canvas); context.drawShare(context, canvas); canvas.draw(); }, drawBg: function (context, canvas) { canvas.save(); canvas.drawImage(context.data.PIC_BG, 0, 0, context.data.screenWH[0], context.data.screenWH[1]); canvas.restore(); }, drawLogo: function (context, canvas) { var xyLogo = context.data.xyLogo; canvas.save(); var width = context.scale(context.data.allPicInfo[context.data.PIC_LOGO].width); var height = context.scale(context.data.allPicInfo[context.data.PIC_LOGO].height); canvas.drawImage(context.data.PIC_LOGO, context.scale(xyLogo[0]), context.scale(xyLogo[1]), width, height); canvas.restore(); }, drawAnswer: function (context, canvas) { canvas.save(); var xyNums = context.data.xyNums; var width = context.scale(context.data.allPicInfo[context.data.PIC_SQURE].width); var height = context.scale(context.data.allPicInfo[context.data.PIC_SQURE].height); var leftMargin = context.scale(context.data.margin20); canvas.setFillStyle(context.data.colorTextBlack); var fontSize = context.scale(context.data.font80); canvas.setFontSize(fontSize); //4个结果数字 for (var i = 0; i < 4; i++) { var x = context.scale(xyNums[0]) + (leftMargin * i) + (width * i); var y = context.scale(xyNums[1]); canvas.drawImage(context.data.PIC_SQURE, x, y, width, height); canvas.fillText(context.data.result[i], x + (width - fontSize / 2) / 2, y + fontSize); } canvas.restore(); canvas.save(); //右侧文字 var x = context.scale(xyNums[0]) + (leftMargin * 4) + (width * 4); var fontSize = context.scale(context.data.font36); canvas.setFillStyle(context.data.colorTextBlack); canvas.setFontSize(fontSize); canvas.fillText(context.data.resultText[0], x, y + fontSize - context.scale(4)); var fontSizeNew = context.scale(context.data.font48); canvas.setFillStyle(context.data.colorTextBlack); canvas.setFontSize(fontSizeNew); // canvas.setShadow(1, 1, 0, context.data.colorTextBlack); // canvas.setShadow(-1, -1, 0, context.data.colorTextBlack); canvas.fillText(context.data.resultText[1], x, y + fontSize + fontSizeNew + context.scale(4)); canvas.restore(); }, drawPhoto: function (context, canvas) { var x = context.scale(context.data.xyPhoto[0]); var y = context.scale(context.data.xyPhoto[1]); var width = context.scale(context.data.whPhoto[0]); var height = context.scale(context.data.whPhoto[1]); canvas.save(); canvas.arc(x + width / 2, y + height / 2, width / 2, 0, 2 * Math.PI); canvas.clip(); canvas.drawImage(context.data.userImg, x, y, width, height); canvas.restore(); }, drawScore: function (context, canvas) { //title canvas.save(); var x = context.scale(context.data.xyScore[0]); var y = context.scale(context.data.xyScore[1]); var fontSize = context.scale(context.data.font32); canvas.setFillStyle(context.data.colorTextBlack); canvas.setFontSize(fontSize); canvas.fillText(context.data.resultScoreTitle, x, y + fontSize - context.scale(4)); canvas.restore(); canvas.save(); //score var newFontSize = context.scale(context.data.font80); canvas.setFontSize(newFontSize); canvas.setFillStyle(context.data.colorTextBlue); var newY = y + context.scale(fontSize + context.data.margin20); // canvas.setShadow(1, 1, 0, context.data.colorTextBlue); // canvas.setShadow(-1, -1, 0, context.data.colorTextBlue); canvas.fillText(context.data.resultScore, x, newY + newFontSize - context.scale(4)); canvas.restore(); }, drawEvaluation: function (context, canvas) { canvas.save(); //bg var x = context.scale(context.data.xyEvaluationBg[0]); var y = context.scale(context.data.xyEvaluationBg[1]); var width = context.scale(context.data.allPicInfo[context.data.PIC_SEAL].width); var height = context.scale(context.data.allPicInfo[context.data.PIC_SEAL].height); canvas.drawImage(context.data.PIC_SEAL, x, y, width, height); canvas.restore(); canvas.save(); //percent var percent = context.data.resultEvaluation[0]; var xP = context.scale(context.data.xyEvaluationPercent[0]); var yP = context.scale(context.data.xyEvaluationPercent[1]); var fontSize = context.scale(context.data.font60); canvas.setFillStyle(context.data.colorTextGreen); canvas.setFontSize(fontSize); canvas.rotate(-15 * Math.PI / 180); // canvas.setShadow(1, 1, 0, context.data.colorTextGreen); // canvas.setShadow(-1, -1, 0, context.data.colorTextGreen); canvas.fillText(percent, xP - context.scale(190), yP + fontSize + context.scale(35)); canvas.restore(); canvas.save(); //title var title = context.data.resultEvaluation[1]; var x = context.scale(context.data.xyEvaluationTitle[0]); var y = context.scale(context.data.xyEvaluationTitle[1]); var fontSize = context.scale(context.data.font32); canvas.setFillStyle(context.data.colorTextGreen); canvas.setFontSize(fontSize); canvas.fillText(title, x, y + fontSize - context.scale(4)); canvas.restore(); canvas.save(); //evaluation var evaluation = context.data.resultEvaluation[2]; var x = context.scale(context.data.xyEvaluationResult[0]); var y = context.scale(context.data.xyEvaluationResult[1]); var fontSize = context.scale(context.data.resultEvaluation[4]); canvas.setFillStyle(context.data.colorTextWhite); canvas.setFontSize(fontSize); // canvas.setShadow(1, 1, 0, context.data.colorTextWhite); // canvas.setShadow(-1, -1, 0, context.data.colorTextWhite); canvas.fillText(evaluation, x, y + fontSize - context.scale(4)); canvas.restore(); canvas.save(); //sum var sum = context.data.resultEvaluation[3]; var x = context.scale(context.data.xyEvaluationSum[0]); var y = context.scale(context.data.xyEvaluationSum[1]); var fontSize = context.scale(context.data.font40); canvas.setFillStyle(context.data.colorTextBlack); canvas.setFontSize(fontSize); // canvas.setTextAlign('center'); canvas.fillText(sum, context.data.screenWH[0] / 2 - x - (fontSize*sum.length)/2, y + fontSize - context.scale(4)); canvas.restore(); }, // draw二维码+左边文字 drawShare: function (context, canvas) { canvas.save(); //bg canvas.setFillStyle(context.data.colorTextWhite); var x = context.scale(context.data.xyShareBg[0]); var y = context.data.screenWH[1] + context.scale(context.data.xyShareBg[1]); canvas.fillRect(x, y, context.data.screenWH[0], -context.scale(context.data.xyShareBg[1])); canvas.restore(); canvas.save(); //text var text = context.data.resultShareText; var xText = context.scale(context.data.xyShareText[0]); var yText = context.data.screenWH[1] + context.scale(context.data.xyShareText[1]); var lineSpace = context.scale(context.data.margin20); var fontSize = context.scale(context.data.font26); var fontSizeBold = context.scale(context.data.font32); canvas.setFillStyle(context.data.colorTextBlack); canvas.setFontSize(fontSize); canvas.fillText(text[0], xText, yText + fontSize - context.scale(4)); canvas.fillText(text[1], xText, yText + fontSize - context.scale(4) + lineSpace + fontSize * 1); canvas.fillText(text[2], xText, yText + fontSize - context.scale(4) + lineSpace * 2 + fontSize * 2); canvas.restore(); canvas.save(); canvas.setFontSize(fontSizeBold); // canvas.setShadow(1, 1, 0, context.data.colorTextBlack); // canvas.setShadow(-1, -1, 0, context.data.colorTextBlack); canvas.fillText(text[3], xText + fontSize * text[2].length, yText + fontSize - context.scale(4) + lineSpace * 2 + fontSize * 2); canvas.restore(); canvas.save(); canvas.setFontSize(fontSize); canvas.fillText(text[4], xText + fontSize * text[2].length + fontSizeBold * text[3].length, yText + fontSize - context.scale(4) + lineSpace * 2 + fontSize * 2); canvas.restore(); canvas.save(); canvas.setFontSize(fontSizeBold); // canvas.setShadow(1, 1, 0, context.data.colorTextBlack); // canvas.setShadow(-1, -1, 0, context.data.colorTextBlack); canvas.fillText(text[5], xText, yText + fontSizeBold - context.scale(4) + lineSpace * 3 + fontSize * 2 + fontSizeBold * 1); canvas.restore(); canvas.save(); canvas.setFontSize(fontSize); canvas.fillText(text[6], xText, yText + fontSizeBold - context.scale(4) + lineSpace * 4 + fontSize * 2 + fontSizeBold * 2); canvas.restore(); canvas.save(); //qr var x = context.scale(context.data.xyShareQR[0]); var y = context.data.screenWH[1] + context.scale(context.data.xyShareQR[1]); var width = context.scale(context.data.allPicInfo[context.data.PIC_QR].width); var height = context.scale(context.data.allPicInfo[context.data.PIC_QR].height); canvas.drawImage(context.data.PIC_QR, x, y, width, height); canvas.restore(); }, scale: function (source) { return source * this.data.radio; }, /** * 用户点击右上角分享 */ onShareAppMessage: function (e) { return { title: '', path: '/pages/index/index', imageUrl: e, // imageUrl: 'http://mj-img.mjmobi.com/dsp/3f7876bb-489d-455d-9cfc-e3d187310687.jpg', success: function (res) { // 转发成功 wx.showToast({ title: '分享成功', }) // wx.redirectTo({ // url: '/pages/index/index', // }) req.share(app.globalData.userid) }, fail: function (res) { // 转发失败 wx.showToast({ title: '分享取消', }) } } }, save() { var me = this wx.canvasToTempFilePath({ canvasId: me.data.CANVAS_ID, // x: 0, // y: 0, // width: me.data.screenWH[0], // height: me.data.screenWH[1], // destWidth: me.data.screenWH[0], // destHeight: me.data.screenWH[1], success(res) { var image = res.tempFilePath console.log(image) wx.previewImage({ urls: [image], current: image }) } }) }, })
34.301486
164
0.627197
911d1d3dbea4486186e773d3a097e54ca753ff6c
454
js
JavaScript
docs/classfmt_1_1v5_1_1system__error.js
bj-winhye/Livox-SDK
95d4c63d00cc9bbc610233364fce372f8bde8e6f
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
docs/classfmt_1_1v5_1_1system__error.js
bj-winhye/Livox-SDK
95d4c63d00cc9bbc610233364fce372f8bde8e6f
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
docs/classfmt_1_1v5_1_1system__error.js
bj-winhye/Livox-SDK
95d4c63d00cc9bbc610233364fce372f8bde8e6f
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
var classfmt_1_1v5_1_1system__error = [ [ "system_error", "classfmt_1_1v5_1_1system__error.html#afab23543db82d4cebb222ac5582c29f4", null ], [ "system_error", "classfmt_1_1v5_1_1system__error.html#adb8fd39cacc13537bdf0265602df3b76", null ], [ "error_code", "classfmt_1_1v5_1_1system__error.html#a663469e2ea1f8c0993909cf90c669270", null ], [ "error_code_", "classfmt_1_1v5_1_1system__error.html#ac761354e3eb707044395fd140020e796", null ] ];
64.857143
103
0.80837
911e700f5bb815e8215a9124ee3ce98ae22e9d02
3,798
js
JavaScript
src/core/request.js
tOgg1/pseudo-fetch
d33c5244c9d3d7c6bc0a5b379c0e8780fbc07c9e
[ "MIT" ]
1
2017-02-06T07:38:11.000Z
2017-02-06T07:38:11.000Z
src/core/request.js
tOgg1/pseudo-fetch
d33c5244c9d3d7c6bc0a5b379c0e8780fbc07c9e
[ "MIT" ]
null
null
null
src/core/request.js
tOgg1/pseudo-fetch
d33c5244c9d3d7c6bc0a5b379c0e8780fbc07c9e
[ "MIT" ]
null
null
null
import Headers from './headers'; /** * This class represents a request object. */ class Request { /** * Construct a new Request. * * @param {String} url The url that the request should go to. * @param {Object} init An init object taking all regular configurations of a fetch-request. */ constructor(url, init = {}) { this._url = url || ''; this._method = init.method || 'GET'; this._headers = new Headers(init.headers); this._body = init.body || ''; this._mode = init.mode || 'cors'; this._credentials = init.credentials || 'omit'; this._cache = init.cache || 'default'; this._redirect = init.redirect || 'follow'; this._referrer = init.referrer || 'client'; this._integrity = init.integrity || null; this._bodyUsed = false; } /** * The method of the Request. * @return {String} Typically something like GET, POST, etc. */ get method() { return this._method; } /** * The headers of the Request. * @return {Headers} The headers. */ get headers() { return this._headers; } /** * The cache policy of the Request. * @return {String} The cache policy. */ get cache() { return this._cache; } /** * Returns whether or not the body has been read yet. * @return {Boolean} True or false */ get bodyUsed() { return this._bodyUsed; } /** * Context is not supported, and will always return the empty string. * @return {String} '' */ get context() { return ''; } /** * The mode of the Request. * @return {String} The mode. */ get mode() { return this._mode; } /** * The cache policy of the Request. * @return {String} The referrer. */ get referrer() { return this._referrer; } /** * The referrerPolicy of the Request. Note that this is the Http Referrer header. * @return {String} The referrerPolicy value: */ get referrerPolicy() { return this.headers.get('Referrer') || ''; } /** * The url of the Request. * @return {String} The url. */ get url() { return this._url; } /** * Returns an arrayBuffer representation of the body, if possible. * * Currently not implemented. */ arrayBuffer() { throw new Error('arrayBuffer not implemented'); } /** * Returns a blob-representation of the body, if possible. * * Currently not implemented. */ blob() { throw new Error('arrayBuffer not implemented'); } /** * Returns a formData-representation of the body, if possible. * * Currently not implemented. */ formData() { throw new Error('arrayBuffer not implemented'); } /** * Returns a json-representation of the body, wrapped in a Promise, if possible. * @return {Promise} A promise which resolves with a json representation of the body. */ json() { return new Promise((resolve, reject) => { try { // Resolve with an empty object is body is not truthy if (!this.body) { resolve({}); } // If we already have a parsed json-object, return it if (this.body.constructor === Object) { resolve(this.body); } else if(this.body) { let parsed = JSON.parse(this.body || ''); resolve(parsed); } else { reject('Body is empty'); } } catch (e) { reject(e); } }); } /** * Returns a text-representation of the body, wrapped in a Promise, if possible. * @return {Promise} A promise which resolves with a text-representation of the body. */ text() { return new Promise((resolve, reject) => { try { resolve((this.body || '').toString()); } catch (e) { reject(e); } }); } } export default Request;
22.607143
95
0.584255
911eee308a2c64398b69d5cb3c183f1036c0c124
4,174
js
JavaScript
static/js/itemList.js
nikvas0/b2b_shop
04783a9525d394d962ba006df57c3c150eeaa9ed
[ "MIT" ]
5
2018-02-17T21:04:40.000Z
2021-02-01T07:18:07.000Z
static/js/itemList.js
tortuc/Django-B2B-MarketPlace-Platform.
9b9d375f67871deccca7a89a566946bb62fc0aaf
[ "MIT" ]
1
2021-08-16T11:27:28.000Z
2021-08-16T11:27:28.000Z
static/js/itemList.js
tortuc/Django-B2B-MarketPlace-Platform.
9b9d375f67871deccca7a89a566946bb62fc0aaf
[ "MIT" ]
3
2019-03-24T16:01:29.000Z
2021-03-22T05:20:08.000Z
function updatePricelist(product, tag) { var obj = ".item-price[data-product=" + product + "][data-tag=" + tag + "]"; var item = $(".variant-selector[data-product=" + product + "][data-tag=" + tag + "] :selected").val(); var fill = "<div><table class='table table-striped'><thead><tr><th>кол-во (" + items[item].measure + ")</th><th>цена (руб)</th></tr></thead><tbody>"; var keys = Object.keys(priceList[item]).map(function (num) { return parseInt(num); }); keys.sort(function (a, b) { return a - b; }); console.log(keys); keys.forEach(function (val, index, array) { fill += "<tr>"; fill += "<th> от " + val + "</th>"; fill += "<th>" + normalize(priceList[item][val]) + "</th>"; fill += "</tr>"; }); fill += "</tbody></table></div>" $(obj).attr("data-content", fill); $(".item-multiplicity[data-product=" + product + "][data-tag=" + tag + "]").text(items[item]["multiplicity"]); } function notify(text) { console.log(text); notifyCart(text); } function update(product, tag) { var q = +($(".quantity-selector[data-product=" + product + "][data-tag=" + tag + "]").val()); var item = $(".variant-selector[data-product=" + product + "][data-tag=" + tag + "] :selected").val(); console.log(item, q, getQuantityInCart(item), getItemPrice(item, q + getQuantityInCart(item))); $(".item-price[data-product=" + product + "][data-tag=" + tag + "]").text(normalize(getItemPrice(item, q + getQuantityInCart(item))) + "\u202Fр"); $(".item-count[data-product=" + product + "][data-tag=" + tag + "]").text(items[item].quantity); $(".product-sum[data-product=" + product + "][data-tag=" + tag + "]").text( normalize(getItemPrice(item, q + getQuantityInCart(item)) * q) + "\u202Fр"); $(".item-multiplicity[data-product=" + product + "][data-tag=" + tag + "]").text(items[item]["multiplicity"]); //updatePricelist(product, tag); //console.log(stored[item], item) } $(document).ready(function () { $(".btn-add-cart").click(function () { var tag = $(this).attr("data-tag"); var product = $(this).attr("data-product"); update(product, tag); var q = +($(".quantity-selector[data-product=" + product + "][data-tag=" + tag + "]").val()); var item = $(".variant-selector[data-product=" + product + "][data-tag=" + tag + "] :selected").val(); console.log(item, q, tag, product); addToCart(item, q, function (data, status) { if (data == 'error') { notifyId('#btn_' + product + '_' + tag, 'ошибка'); } else if (data == 'not authenticated') { notifyId('#btn_' + product + '_' + tag, 'Для добавления товаров в корзину, пожалуйста, войдите или зарегистрируйтесь.'); } else if (data == 'must be divisible by multiplicity') { notifyId('#btn_' + product + '_' + tag, 'Количество должно делиться на кратность.'); } else { notifyId('#btn_' + product + '_' + tag, 'добавлено ' + q.toString() + ' ' + items[item].measure); } $(".quantity-selector[data-product=" + product + "][data-tag=" + tag + "]").val(0); update(product, tag); }); }); $(".variant-selector").change(function () { var tag = $(this).attr("data-tag"); var product = $(this).attr("data-product"); update(product, tag); updatePricelist(product, tag); }); $(".quantity-selector").on('change keyup paste mouseover', function () { var tag = $(this).attr("data-tag"); var product = $(this).attr("data-product"); update(product, tag); }); $(".btn-add-cart").each(function () { var tag = $(this).attr("data-tag"); var product = $(this).attr("data-product"); update(product, tag); }); $(".variant-selector").each(function () { var product = $(this).attr("data-product"); var tag = $(this).attr("data-tag"); //console.log(cart); updatePricelist(product, tag); }); $('[data-toggle="popover"]').popover({ trigger: "hover" }); // });
43.479167
153
0.546718
911f933a537e8d8611b638037001782d83f9f12d
40
js
JavaScript
src/components/SocialMenu/index.js
slushman/slushman.github.io
4a477c4e57197c6691020086250257067df17b81
[ "MIT" ]
null
null
null
src/components/SocialMenu/index.js
slushman/slushman.github.io
4a477c4e57197c6691020086250257067df17b81
[ "MIT" ]
1
2022-02-15T05:21:11.000Z
2022-02-15T05:21:11.000Z
src/components/SocialMenu/index.js
slushman/slushman.github.io
4a477c4e57197c6691020086250257067df17b81
[ "MIT" ]
null
null
null
export { default } from './SocialMenu';
20
39
0.675
9121947f4a76783344791eb8d32d2c95a9ab162f
626
js
JavaScript
src/firebase.js
vieee/react_chat_app
1ac1f2c620d8801f1e66137495ccbe11dbf6e789
[ "MIT" ]
1
2021-08-15T14:35:59.000Z
2021-08-15T14:35:59.000Z
src/firebase.js
vieee/react_chat_app
1ac1f2c620d8801f1e66137495ccbe11dbf6e789
[ "MIT" ]
null
null
null
src/firebase.js
vieee/react_chat_app
1ac1f2c620d8801f1e66137495ccbe11dbf6e789
[ "MIT" ]
null
null
null
import firebase from "firebase/app"; import "firebase/auth"; import "firebase/database"; import "firebase/storage"; var firebaseConfig = { apiKey: "AIzaSyA4WP26sTCkNOsPHfTWYV1yypQ-6JrUFhk", authDomain: "react-slack-clone-e6b28.firebaseapp.com", databaseURL: "https://react-slack-clone-e6b28.firebaseio.com", projectId: "react-slack-clone-e6b28", storageBucket: "react-slack-clone-e6b28.appspot.com", messagingSenderId: "921343697113", appId: "1:921343697113:web:9c0b06f3a2e6c3c5df5ec8", measurementId: "G-N684Y9HDVP" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
31.3
64
0.776358
9121ed968f4bde04c620a2775653d55a37fcb7d1
563
js
JavaScript
www/frontend/controller/overview.js
ifoundthetao/FuzzFlow
86559ac7f85fc89510c0d9647e02880edb95aa2a
[ "MIT" ]
53
2016-08-26T02:51:45.000Z
2021-05-24T21:05:44.000Z
static/frontend/controller/overview.js
FingerLeakers/FuzzFlow
3f2de617c3658904f9640f53a05d5e4e90634e32
[ "MIT" ]
null
null
null
static/frontend/controller/overview.js
FingerLeakers/FuzzFlow
3f2de617c3658904f9640f53a05d5e4e90634e32
[ "MIT" ]
31
2016-08-26T04:08:31.000Z
2021-05-24T21:05:54.000Z
'use strict'; angular.module('frontApp') .controller('OverviewCtrl', function ($scope, $rootScope, $interval, $location, StatusAPI, config) { $scope.initOverview = function() { StatusAPI.read().then(function(data){ $scope.status = data; console.log($scope.status); }) }; $scope.formatDateTime = function(timeString){ return moment(timeString).format('YYYY-MM-DD h:mm:ss A'); }; $scope.initOverview(); $rootScope.overviewTimer = $interval($scope.initOverview, config.refreshTime); });
28.15
82
0.630551
912221d6e4e0d67d79f1458f76f0fb224330db14
828
js
JavaScript
src/SDK/types.js
angxuejian/moto.js
9c2d9a258acaa62934dc2aac68a4d6ecb3d6c264
[ "MIT" ]
null
null
null
src/SDK/types.js
angxuejian/moto.js
9c2d9a258acaa62934dc2aac68a4d6ecb3d6c264
[ "MIT" ]
null
null
null
src/SDK/types.js
angxuejian/moto.js
9c2d9a258acaa62934dc2aac68a4d6ecb3d6c264
[ "MIT" ]
null
null
null
/** * 判断类型是否一致 * @param {any} value 需要判断的类型的 值 * @param {string} type 期望类型 * @returns {boolean} true / false * @example * * const value = 'yuhua' * isTypeOf(value, 'string') * // => true */ export function isTypeOf(value, type) { if (!value) throw new TypeError(`"value" cannot be empty`) if (!type) throw new TypeError(`"type" cannot be empty`) if (typeof type !== 'string') throw new TypeError(`${type} is not a string`) const arr = type.split('') arr.splice(0, 1, arr[0].toUpperCase()) const vv = Object.prototype.toString.call(value) const tt = `[object ${arr.join('')}]` if (vv === tt) return true else return false // [object Null] // [object Array] // [object String] // [object Number] // [object Object] // [object Boolean] // [object Function] // [object Undefined] }
24.352941
78
0.619565
912425eabec78f92b2b5fd9958db8899e917fe53
1,168
js
JavaScript
src/reducers/statsReducer.js
ZeeshanTamboli/Redux-Saga
3a086a6e1c02dcd41ea6c0adf1821aaea2356166
[ "MIT" ]
null
null
null
src/reducers/statsReducer.js
ZeeshanTamboli/Redux-Saga
3a086a6e1c02dcd41ea6c0adf1821aaea2356166
[ "MIT" ]
null
null
null
src/reducers/statsReducer.js
ZeeshanTamboli/Redux-Saga
3a086a6e1c02dcd41ea6c0adf1821aaea2356166
[ "MIT" ]
null
null
null
import { STATS_LOAD, STATS_LOAD_SUCCESS, STATS_LOAD_FAILURE } from '../types'; const initialState = { isLoading: false, error: false, id: null, }; export default function(state = initialState, action) { switch (action.type) { case STATS_LOAD: return { ...state, [action.payload]: { isLoading: true, error: false, id: action.payload, }, }; case STATS_LOAD_SUCCESS: return { ...state, [action.payload.id]: { isLoading: false, downloads: action.payload.downloads, id: action.payload.id, error: false, }, }; case STATS_LOAD_FAILURE: return { ...state, [action.payload]: { isLoading: false, downloads: 0, error: true, id: action.payload, }, }; default: return state; } }
26.545455
78
0.407534
9126015e3410f12b069f4299cbdd08bc80e25460
335
js
JavaScript
lib/ghostbin.js
LasDrak/ElainaXyzV2
dce5e86a172ddcac8c331d31debaddd5f3c22695
[ "MIT" ]
3
2021-12-20T05:09:00.000Z
2021-12-29T08:49:38.000Z
lib/ghostbin.js
LasDrak/ElainaXyzV2
dce5e86a172ddcac8c331d31debaddd5f3c22695
[ "MIT" ]
null
null
null
lib/ghostbin.js
LasDrak/ElainaXyzV2
dce5e86a172ddcac8c331d31debaddd5f3c22695
[ "MIT" ]
10
2021-12-20T11:50:38.000Z
2022-02-10T01:41:03.000Z
const axios = require("axios") function ghostbin(text, title, password) { return new Promise ((resolve, reject) => { axios({ method: "post", url: "https://ghostbin.com/paste/new", data: `text=${text}&title=${title}&password=${password}`}) .then(res=>resolve('https://ghostbin.com'+ res.request.path)) }) }; module.exports = ghostbin;
25.769231
61
0.683582
912775a698490147c8a5c7b8432d230c1745bcfd
801
js
JavaScript
src/app/controllers/sessions.js
sonnym/bughouse
b333894ef3ce43a610df95b287104d634356a74d
[ "MIT" ]
1
2015-06-05T18:53:00.000Z
2015-06-05T18:53:00.000Z
src/app/controllers/sessions.js
sonnym/bughouse
b333894ef3ce43a610df95b287104d634356a74d
[ "MIT" ]
4
2020-04-25T03:20:47.000Z
2022-02-27T12:42:16.000Z
src/app/controllers/sessions.js
sonnym/bughouse
b333894ef3ce43a610df95b287104d634356a74d
[ "MIT" ]
null
null
null
import User from "~/app/models/user" export const create = async (req, res, next) => { const { email, password } = req.body if (!email || !password) { res.status(400).end() return } const loadedUser = await User.query(builder => { builder .innerJoin('emails', 'emails.user_id', 'users.id') .where('emails.value', '=', email) .limit(1) }).fetch({ require: false, withRelated: ["profile", "rating"] }) const user = loadedUser || new User() if (await user.isValidPassword(password)) { req.login(user, (err) => { if (err) next(err) res.status(201).send(user.serialize()) }) } else { res.status(401).end() } } export const destroy = async (req, res, next) => { await req.session.destroy() res.status(205).end() }
21.078947
56
0.588015
912796f4f3f12d38f2dbccdcb7c21f7f4f393e71
4,611
js
JavaScript
index.js
haidaoge/pages
baa0b71324d78e6bef7b7fa0a5a47df5d93c3db4
[ "MIT" ]
null
null
null
index.js
haidaoge/pages
baa0b71324d78e6bef7b7fa0a5a47df5d93c3db4
[ "MIT" ]
null
null
null
index.js
haidaoge/pages
baa0b71324d78e6bef7b7fa0a5a47df5d93c3db4
[ "MIT" ]
null
null
null
(function($) { var methods = { init: function(options) { $(this).empty(); $(this).off("click", "#hpage a"); // 默认选项 var defaults = { elem: $(this), counts: 0, curr: 1, offset: 15, }; // 使用settings合并拓展选项 var obj = $.extend({}, defaults, options); // 计算分页 obj.pages = Math.ceil(obj.counts / obj.offset); // 小于一页不分页 if(obj.pages < 2) { return this; } obj.limit = obj.pages > 9 ? 9 : obj.pages; // 生成分页元素 var html = '<ul id="hpage" class="pagination">'+ '<li class="disabled"><a href="javascript:;" data-index="first">首页</a></li>'+ '<li class="disabled"><a href="javascript:;" data-index="prev">«</a></li>'+ '<li class="active"><a href="javascript:;" data-index="1">1</a></li>'; for(var i = 2; i <= obj.limit; i++) { html += '<li><a href="javascript:;" data-index="'+ i +'">'+ i +'</a></li>'; } html += '<li><a href="javascript:;" data-index="next">»</a></li>'+ '<li><a href="javascript:;" data-index="last">尾页</a></li></ul>'; // 分页元素视图化 obj.elem.html(html); obj.elem.hPage("method", obj); }, method: function(obj) { $(this).on("click", "#hpage a", function() { var curr = $(this).attr("data-index"); obj.index = $("#hpage a").index($(this)); $("#hpage li").removeClass("active disabled"); switch (curr) { case "first": if(obj.curr != 1){ obj.curr = 1; obj.callback(obj); } obj.elem.hPage("update", obj); break; case "prev": if(obj.curr > 1) { obj.curr --; obj.callback(obj); } obj.elem.hPage("update", obj); break; case "next": if(obj.curr < obj.pages) { obj.curr ++; obj.callback(obj); } obj.elem.hPage("update", obj); break; case "last": if(obj.curr != obj.pages) { obj.curr = obj.pages; obj.callback(obj); } obj.elem.hPage("update", obj); break; default: obj.curr = curr * 1; obj.callback(obj); obj.elem.hPage("update", obj); } }); }, update: function(obj) { var curr = obj.curr, index = obj.index, start = 1, end = obj.pages, html = ''; if (obj.pages > 9) { start = curr - 5 > 0 ? curr - 4 : 1; end = curr + 4 > obj.pages ? obj.pages : curr + 4; // 首页 if(index == 0) { start = 1; end = 9; } //尾页 if(index == 12) { start = obj.pages - 8; end = obj.pages; } // 点击区域在数字1-5 或者 最后4页之前 或者 前5页 if((index > 1 && index < 7) || (index == 11 && curr <= obj.pages - 5) || curr <= 5) { index = curr - start + 2; end = start + 8; //点击区域在数字6-9 或者 最后4页之前 或者 最后4页 }else if((index >= 7 && index < 11) || (index == 1 && curr <= obj.pages - 5) || curr > obj.pages - 5) { index = curr - end + 10; start = end - 8; } } else { start = 1; end = obj.pages; if((index == 1 && curr != 1) || (index == obj.limit + 2 && curr != obj.pages)) { index = curr + 1; } } html += '<ul id="hpage" class="pagination">'+ '<li ><a href="javascript:;" data-index="first">首页</a></li>'+ '<li ><a href="javascript:;" data-index="prev">«</a></li>'; for(var i = start; i <= end; i++) { html += '<li><a href="javascript:;" data-index="'+ i +'">'+ i +'</a></li>'; } html += '<li><a href="javascript:;" data-index="next">»</a></li>'+ '<li><a href="javascript:;" data-index="last">尾页</a></li></ul>'; obj.elem.html(html); if (index > 1 && index <= obj.pages) { $("#hpage li").eq(index).addClass("active"); } if (curr == 1 || index == 0) { $("#hpage li").eq(2).addClass("active"); $("#hpage li").eq(0).addClass("disabled"); $("#hpage li").eq(1).addClass("disabled"); } if (curr == obj.pages || index == obj.limit + 2) { $("#hpage li").eq(obj.limit + 1).addClass("active"); $("#hpage li").eq(obj.limit + 2).addClass("disabled"); $("#hpage li").eq(obj.limit + 3).addClass("disabled"); } } }; $.fn.hPage = function() { // 获取传入的方法,切勿用function(method){}来实现,否则会毁掉一切 var method = arguments[0]; // 方法调用 if(methods[method]) { // 如果存在,获取方法名 method = methods[method]; arguments = Array.prototype.slice.call(arguments, 1); } else if (typeof method === 'object' || !method) { //如果没有传入方法名,则默认调用init方法,参数为arguments method = methods.init; } else { // 否则提示错误 $.error('Method' + method + 'does not exist no jQuery.hPage'); } // 用apply方法调用方法,并传入参数 return method.apply(this, arguments); }; })(jQuery);
29
107
0.505313
9127b6fe0933c6d8ce776ab821c1038cc1aa825c
2,142
js
JavaScript
app/containers/AddBookPage/sagas.js
kevinnorris/bookTrading
2e4d82ef7cc5c0e0e93723a9e7f89ad9bcbae27c
[ "MIT" ]
null
null
null
app/containers/AddBookPage/sagas.js
kevinnorris/bookTrading
2e4d82ef7cc5c0e0e93723a9e7f89ad9bcbae27c
[ "MIT" ]
null
null
null
app/containers/AddBookPage/sagas.js
kevinnorris/bookTrading
2e4d82ef7cc5c0e0e93723a9e7f89ad9bcbae27c
[ "MIT" ]
null
null
null
import { takeLatest, call, select, put, take, cancel } from 'redux-saga/effects'; import { push, LOCATION_CHANGE } from 'react-router-redux'; import request from 'utils/request'; import { appUrl } from 'utils/constants'; import { makeSelectToken, makeSelectUserId } from 'containers/App/selectors'; import { unselectBook } from 'containers/App/actions'; import { SEARCH_REQUEST, ADD_BOOK_REQUEST, } from './constants'; import { searchSuccess, searchError, addBookSuccess, addBookError, } from './actions'; export function* searchSaga(action) { const token = yield select(makeSelectToken()); const userId = yield select(makeSelectUserId()); const requestUrl = `${appUrl}/api/search?searchTerm=${action.payload.searchTerm}&&token=${token}&&userId=${userId}`; try { const books = yield call(request, requestUrl); if (books.success) { yield put(searchSuccess({ books: books.data })); } else { yield put(searchError({ error: books.error })); } } catch (error) { yield put(searchError({ error: error.response })); } } export function* searchData() { const watcher = yield takeLatest(SEARCH_REQUEST, searchSaga); yield take(LOCATION_CHANGE); yield cancel(watcher); } export function* addBookSaga(action) { const token = yield select(makeSelectToken()); const userId = yield select(makeSelectUserId()); try { const bookAdded = yield call(request, `${appUrl}/api/addBook`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token, userId, googleData: action.payload.book }), }); if (bookAdded.success) { yield put(unselectBook()); yield put(addBookSuccess()); yield put(push('/mybooks')); } else { yield put(addBookError({ error: bookAdded.error })); } } catch (error) { yield put(addBookError({ error: error.response })); } } export function* addBookWatcher() { const watcher = yield takeLatest(ADD_BOOK_REQUEST, addBookSaga); yield take(LOCATION_CHANGE); yield cancel(watcher); } // All sagas to be loaded export default [ searchData, addBookWatcher, ];
28.56
118
0.683473
91284a7b5f15ac6457e03e85ff4b9bc1141fbe62
1,051
js
JavaScript
src/components/Nav/ModalContainer/index.js
jyunakaike/kuka_corp
bf76460113972baf14ce2c72ca4cf1f2afbd1910
[ "MIT" ]
null
null
null
src/components/Nav/ModalContainer/index.js
jyunakaike/kuka_corp
bf76460113972baf14ce2c72ca4cf1f2afbd1910
[ "MIT" ]
null
null
null
src/components/Nav/ModalContainer/index.js
jyunakaike/kuka_corp
bf76460113972baf14ce2c72ca4cf1f2afbd1910
[ "MIT" ]
null
null
null
import React, { useEffect } from 'react' import './styles.css' import {IoMdCloseCircle} from 'react-icons/io'; import Qr from '../../../../assets/image/qr.jpeg' export const ModalContainer = ({ setOpenModal }) => { useEffect(() => { document.body.style.overflow = 'hidden'; }, []) const closeModal = () => { document.body.style.overflow = 'unset'; setOpenModal(false) } return ( <React.Fragment> <div className='ModalContainer-overlay' > <div className='ModalContainer-overlay-container '> <div className='ModalContainer-right'> <div className='ModalContainer-Close' onClick={closeModal} > <IoMdCloseCircle /> </div> </div> <div className='ModalContainer-element'> <h2>CHAT WHATSAPP</h2> <img src={Qr} alt={'Whatsapp-Qr'}></img> </div> </div> </div> </React.Fragment> ) }
30.028571
112
0.511893
9129e6cf68748695a9c8174f7f421fe5b1333be7
720
js
JavaScript
fast-cheap-good/script.js
coding-bootcamps-eu/katas
8fac5cf46118978ede3412b2deef420a8338a742
[ "MIT" ]
null
null
null
fast-cheap-good/script.js
coding-bootcamps-eu/katas
8fac5cf46118978ede3412b2deef420a8338a742
[ "MIT" ]
null
null
null
fast-cheap-good/script.js
coding-bootcamps-eu/katas
8fac5cf46118978ede3412b2deef420a8338a742
[ "MIT" ]
null
null
null
const fastCheck = document.querySelector("#fast"); const cheapCheck = document.querySelector("#cheap"); const goodCheck = document.querySelector("#good"); lastCheckbox = null; function toggle(clickedCheckbox, otherCheckbox1, otherCheckbox2) { if ( clickedCheckbox.checked && otherCheckbox1.checked && otherCheckbox2.checked ) { lastCheckbox.checked = false; } lastCheckbox = clickedCheckbox; } fastCheck.addEventListener("change", function () { toggle(fastCheck, cheapCheck, goodCheck); }); cheapCheck.addEventListener("change", function () { toggle(cheapCheck, fastCheck, goodCheck); }); goodCheck.addEventListener("change", function () { toggle(goodCheck, cheapCheck, fastCheck); });
25.714286
66
0.734722
912b6718a72be55c9df31bf092c1ca35e2d109e5
1,559
js
JavaScript
entities/admin/admin.js
zer0eXploit/poosuu-api
adc2dd2eb7f5d979be0185c5e8f06e9d99c6d623
[ "MIT" ]
null
null
null
entities/admin/admin.js
zer0eXploit/poosuu-api
adc2dd2eb7f5d979be0185c5e8f06e9d99c6d623
[ "MIT" ]
null
null
null
entities/admin/admin.js
zer0eXploit/poosuu-api
adc2dd2eb7f5d979be0185c5e8f06e9d99c6d623
[ "MIT" ]
null
null
null
import { isString, isEmptyString, isValidEmail, isValidPassword, isValidUsername, } from "../../helpers/validation.js"; import { hashPassword } from "../../helpers/auth.js"; import requiredParam from "../../helpers/required-param.js"; import { InvalidPropertyError } from "../../helpers/errors.js"; const makeAdmin = (adminData = requiredParam("AdminData")) => { const validateName = (name) => { if (!isString(name)) throw new InvalidPropertyError("Admin name is not valid."); if (isEmptyString(name)) throw new InvalidPropertyError("Admin name must not be empty."); }; const validateEmail = (email) => { if (!isValidEmail(email)) throw new InvalidPropertyError("Email must be valid."); }; const validatePassword = (password) => { if (!isValidPassword(password)) throw new InvalidPropertyError("Password must be valid."); }; const validateUsername = (username) => { if (!isValidUsername(username)) throw new InvalidPropertyError("Username must be valid."); }; const validate = ({ name = requiredParam("name"), username = requiredParam("username"), email = requiredParam("email"), password = requiredParam("password"), }) => { validateName(name); validateUsername(username); validatePassword(password); validateEmail(email); return { name, username, email, password: hashPassword(password), }; }; const validAdmin = validate(adminData); return Object.freeze(validAdmin); }; export default makeAdmin;
25.557377
70
0.661963
912b952bf1281cd25290e47f08eff8d2fb9fd44a
61
js
JavaScript
src/core/modules/utils/index.js
rutkat/mousekyc-admin
8f27dc0e277d582db753c30728c0f370cd05ff7a
[ "MIT" ]
17
2018-07-26T21:16:54.000Z
2021-08-17T05:30:59.000Z
src/core/modules/utils/index.js
rutkat/mousekyc-admin
8f27dc0e277d582db753c30728c0f370cd05ff7a
[ "MIT" ]
56
2018-11-30T05:03:02.000Z
2019-02-14T11:40:19.000Z
src/core/modules/utils/index.js
rutkat/mousekyc-admin
8f27dc0e277d582db753c30728c0f370cd05ff7a
[ "MIT" ]
16
2018-07-26T21:10:23.000Z
2021-04-04T08:10:42.000Z
export { createPromiseAction } from './createPromiseAction';
30.5
60
0.786885
912c576d00a908ed5de4e5c9efec1ee653d34ce6
349
js
JavaScript
backend/src/services/jwtService.js
alescrocaro/projeto-integrador
2341de090aee5256ddd004acd1c82dd91a4d8dcf
[ "MIT" ]
null
null
null
backend/src/services/jwtService.js
alescrocaro/projeto-integrador
2341de090aee5256ddd004acd1c82dd91a4d8dcf
[ "MIT" ]
null
null
null
backend/src/services/jwtService.js
alescrocaro/projeto-integrador
2341de090aee5256ddd004acd1c82dd91a4d8dcf
[ "MIT" ]
null
null
null
const jwt = require('jsonwebtoken') module.exports = { generateJwt(id, firstName, lastName, email) { const jwtSecret = process.env.JWT_SECRET const token = jwt.sign({ id:id, firstName:firstName, lastName:lastName, email:email }, jwtSecret); return token } }
24.928571
49
0.555874
912d4c6539f6ff126d9d084a96718b6177563121
178
js
JavaScript
gulpfile.js
crstffr/cloud9-electron-launcher
638270c40c64f7ceca6d9d2bc7a989dec925ca2c
[ "CC0-1.0" ]
null
null
null
gulpfile.js
crstffr/cloud9-electron-launcher
638270c40c64f7ceca6d9d2bc7a989dec925ca2c
[ "CC0-1.0" ]
null
null
null
gulpfile.js
crstffr/cloud9-electron-launcher
638270c40c64f7ceca6d9d2bc7a989dec925ca2c
[ "CC0-1.0" ]
null
null
null
// Gulp tasks are broken out and defined in the ./gulp/tasks folder, // and are loaded at runtime by the ./gulp/tasks.js loader. require('./gulp/tasks')(require('gulp'));
29.666667
69
0.679775
912da2abc57d03a2701b1595cc2ffb3dc7bd94db
627
js
JavaScript
gulpfile.js
kristianroebuck/snow
3cb6d1f516cb42f16e34c068fc1574724dbcaaf3
[ "MIT" ]
6
2015-02-08T10:37:30.000Z
2016-05-01T01:38:09.000Z
gulpfile.js
kristianroebuck/snow
3cb6d1f516cb42f16e34c068fc1574724dbcaaf3
[ "MIT" ]
null
null
null
gulpfile.js
kristianroebuck/snow
3cb6d1f516cb42f16e34c068fc1574724dbcaaf3
[ "MIT" ]
null
null
null
var gulp = require('gulp'), to5 = require('gulp-6to5'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), plumber = require('gulp-plumber'), sourcemaps = require('gulp-sourcemaps'), jsFiles = './js/snow.js'; gulp.task('js', function() { return gulp.src(jsFiles) .pipe(plumber()) .pipe(rename({suffix:'.min'})) .pipe(sourcemaps.init()) .pipe(to5()) .pipe(uglify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('js')); }); gulp.task('watch', function() { gulp.watch(jsFiles, ['js']); }); gulp.task('default', ['watch']);
24.115385
44
0.555024
912dcfa0bbce04946fcd9f3ea49d4155418aaad5
1,048
js
JavaScript
notifyQueue.js
shiva-sc/x-notify
5c77f0402509a7e41fc7b6faf0a0e6f6ee059284
[ "MIT" ]
null
null
null
notifyQueue.js
shiva-sc/x-notify
5c77f0402509a7e41fc7b6faf0a0e6f6ee059284
[ "MIT" ]
null
null
null
notifyQueue.js
shiva-sc/x-notify
5c77f0402509a7e41fc7b6faf0a0e6f6ee059284
[ "MIT" ]
null
null
null
const Queue = require('bull'); const { setQueues } = require('bull-board'); const { UI } = require('bull-board'); const redisUri = process.env.REDIS_URI || 'x-notify-redis'; const redisPort = process.env.REDIS_PORT || '6379'; const redisSentinel1Uri = process.env.REDIS_SENTINEL_1_URI || '127.0.0.1'; const redisSentinel1Port = process.env.REDIS_SENTINEL_1_PORT || '26379'; const redisSentinel2Uri = process.env.REDIS_SENTINEL_2_URI || '127.0.0.1'; const redisSentinel2Port = process.env.REDIS_SENTINEL_2_PORT || '26379'; const redisMasterName = process.env.REDIS_MASTER_NAME || 'x-notify-master'; let redisConf = {}; if (process.env.NODE_ENV === 'prod') { redisConf = { redis: { sentinels: [ { host: redisSentinel1Uri, port: redisSentinel1Port }, { host: redisSentinel2Uri, port: redisSentinel2Port } ], name: redisMasterName, } } } else { redisConf = { redis: { host: redisUri, port: redisPort, } } } const notifyQueue = new Queue('sendMail', redisConf); setQueues([notifyQueue]); module.exports.UI = UI;
26.871795
75
0.701336
912de0e0a752c28d7945574413645709e57cc86d
1,629
js
JavaScript
test/annexB/built-ins/RegExp/legacy-accessors/input/this-cross-realm-constructor.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
1,849
2015-01-15T12:42:53.000Z
2022-03-30T21:23:59.000Z
test/annexB/built-ins/RegExp/legacy-accessors/input/this-cross-realm-constructor.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
2,157
2015-01-06T05:01:55.000Z
2022-03-31T17:18:08.000Z
test/annexB/built-ins/RegExp/legacy-accessors/input/this-cross-realm-constructor.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
411
2015-01-22T01:40:04.000Z
2022-03-28T19:19:16.000Z
// Copyright (C) 2020 ExE Boss. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: pending description: RegExp.input throws a TypeError for cross-realm receiver info: | get RegExp.input 1. Return ? GetLegacyRegExpStaticProperty(%RegExp%, this value, [[RegExpInput]]). set RegExp.input = val 1. Return ? SetLegacyRegExpStaticProperty(%RegExp%, this value, [[RegExpInput]], val). GetLegacyRegExpStaticProperty( C, thisValue, internalSlotName ). 1. Assert C is an object that has an internal slot named internalSlotName. 2. If SameValue(C, thisValue) is false, throw a TypeError exception. 3. ... SetLegacyRegExpStaticProperty( C, thisValue, internalSlotName, val ). 1. Assert C is an object that has an internal slot named internalSlotName. 2. If SameValue(C, thisValue) is false, throw a TypeError exception. 3. ... features: [legacy-regexp,cross-realm,Reflect,Reflect.set] ---*/ const other = $262.createRealm().global; assert.throws( TypeError, function () { Reflect.get(RegExp, "input", other.RegExp); }, "RegExp.input getter throws for cross-realm receiver" ); assert.throws( TypeError, function () { Reflect.set(RegExp, "input", "", other.RegExp); }, "RegExp.input setter throws for cross-realm receiver" ); assert.throws( TypeError, function () { Reflect.get(RegExp, "$_", other.RegExp); }, "RegExp.$_ getter throws for cross-realm receiver" ); assert.throws( TypeError, function () { Reflect.set(RegExp, "$_", "", other.RegExp); }, "RegExp.$_ setter throws for cross-realm receiver" );
26.274194
88
0.703499
912e30f812b834a6a005de95c2151eeeff1ad5cb
2,458
js
JavaScript
src/components/card.js
theianjones/illustrated-dev
2dd50e4d237dac434443ad1ab5c1e5b707c3025b
[ "MIT" ]
null
null
null
src/components/card.js
theianjones/illustrated-dev
2dd50e4d237dac434443ad1ab5c1e5b707c3025b
[ "MIT" ]
null
null
null
src/components/card.js
theianjones/illustrated-dev
2dd50e4d237dac434443ad1ab5c1e5b707c3025b
[ "MIT" ]
null
null
null
import React from 'react' import { css } from '@emotion/core' import Img from 'gatsby-image' import { bpMinSM, bpMinMD } from '../utils/breakpoints' const Card = ({ title, image = [], description, date, tags = [], featured, children }) => ( <div css={css({ [bpMinSM]: { height: "380px", flexDirection: featured ? "row" : "column" }, background: "white", boxShadow: "0px 1px 2px rgba(52, 61, 68, 0.05)", display: "flex", flexDirection: "column", justifyContent: "space-between", ".gatsby-image-wrapper": { [bpMinSM]: { width: featured ? "330px" : "100%", height: featured ? "330px" : "100%" }, width: "100%", height: "100%" }, h1: { [bpMinSM]: { fontSize: featured ? "40px" : "23px" }, fontWeight: "300", height: featured ? "auto" : "60px", lineHeight: "1.2" }, ".description": { [bpMinMD]: { display: "block" }, fontFamily: "ff-tisa-web-pro, serif", fontWeight: "100", fontSize: "20px", lineHeight: 1.4, opacity: 0.9, display: "none", margin: 0 }, ":hover": { boxShadow: "0 10px 30px -10px rgba(0,0,0,0.15)", transition: "all 250ms ease", h1: { color: "inherit" }, ".tags": { display: "block" } }, transition: "all 250ms ease", ".tags": { display: featured ? "block" : "none" } })} > <div css={css({ padding: featured ? "50px 40px 50px 50px" : "50px 50px 0 50px", display: featured && "flex", flexDirection: featured && "column", justifyContent: "space-between" })} > <h1>{title}</h1> {featured && <p className="description">{description}</p>} {/* {tags && ( <div className="tags"> {tags.map(tag => ( <span css={css({ marginRight: '10px', fontFamily: 'brandon-grotesque, sans-serif', })}> {tag} </span> ))} </div> )} */} </div> <div css={css({ display: "flex", justifyContent: "flex-end", alignItems: "flex-end" })} > <Img fluid={image} /> {children} </div> </div> ); export default Card
23.188679
71
0.458096
912fe5961f7a2a5ca6d3df3a8f43cc168f782e60
1,944
js
JavaScript
src/containers/pages/dashboard/right-container/topbar.js
vFujin/HearthLounge
c4c39e26d333c7a858cc0a646a80cd07e56113c5
[ "Apache-2.0" ]
28
2017-06-05T11:23:13.000Z
2018-05-28T09:37:22.000Z
src/containers/pages/dashboard/right-container/topbar.js
sbsrnt/HearthLounge
c4c39e26d333c7a858cc0a646a80cd07e56113c5
[ "BSD-3-Clause" ]
83
2017-05-20T14:29:00.000Z
2018-05-09T20:59:38.000Z
src/containers/pages/dashboard/right-container/topbar.js
xNehel/clownfiesta-collector-react
c4c39e26d333c7a858cc0a646a80cd07e56113c5
[ "BSD-3-Clause" ]
4
2017-08-28T14:41:24.000Z
2018-03-04T13:10:49.000Z
import React from 'react'; import {connect} from 'react-redux'; import Icon from "../../../../components/icon"; const Topbar = ({activeUser, handleUserDecksClick, handleFetchAllUsers}) =>{ const {role} = activeUser; return ( <ul className="topbar has-icons"> {/*<li className="home-grid">*/} {/*<span className="hs-icon icon-grid"></span>*/} {/*<div className="tooltip">*/} {/*<div className="caret-up"></div>*/} {/*<p>Homepage block scheme</p>*/} {/*</div>*/} {/*</li>*/} <li className="deck" onClick={handleUserDecksClick}> <Icon name="deck" title="Your decks" tooltip={true}/> </li> { role < 3 && <li className="deck" onClick={handleFetchAllUsers}> <Icon name="login" title="Users" tooltip={true}/> </li> } {/*<li className="tournaments">*/} {/*<span className="hs-icon icon-trophy"></span>*/} {/*<div className="tooltip">*/} {/*<div className="caret-up"></div>*/} {/*<p>Tournaments</p>*/} {/*</div>*/} {/*</li>*/} {/*<li className="streams">*/} {/*<span className="hs-icon icon-twitch"></span>*/} {/*<div className="tooltip">*/} {/*<div className="caret-up"></div>*/} {/*<p>Streams</p>*/} {/*</div>*/} {/*</li>*/} {/*<Tooltip title="stats" placement="bottom">*/} {/*<li className="stats">*/} {/*<span className="hs-icon icon-stats-dots"></span>*/} {/*</li>*/} {/*</Tooltip>*/} </ul> ) }; const mapStateToProps = state =>{ const {activeUser} = state.users; return {activeUser}; }; export default connect(mapStateToProps, null)(Topbar);
36
76
0.458333
912fea4267cf69be2210ca725e9d8f7328871e3e
1,948
js
JavaScript
src/main/webapp/scripts/app/entities/transactions_bak/transactions.controller.js
nezuvian/Library-webapp
72e6f328e584e47aa97556c94b605a36f3249ae1
[ "Unlicense" ]
null
null
null
src/main/webapp/scripts/app/entities/transactions_bak/transactions.controller.js
nezuvian/Library-webapp
72e6f328e584e47aa97556c94b605a36f3249ae1
[ "Unlicense" ]
null
null
null
src/main/webapp/scripts/app/entities/transactions_bak/transactions.controller.js
nezuvian/Library-webapp
72e6f328e584e47aa97556c94b605a36f3249ae1
[ "Unlicense" ]
null
null
null
'use strict'; angular.module('libappApp') .controller('TransactionsController', function ($scope, Transactions, User, Book, ParseLinks) { $scope.transactionss = []; $scope.users = User.query(); $scope.transactions = Book.query(); $scope.page = 1; $scope.loadAll = function() { Transactions.query({page: $scope.page, per_page: 20}, function(result, headers) { $scope.links = ParseLinks.parse(headers('link')); $scope.transactionss = result; }); }; $scope.loadPage = function(page) { $scope.page = page; $scope.loadAll(); }; $scope.loadAll(); $scope.create = function () { Transactions.update($scope.transactions, function () { $scope.loadAll(); $('#saveTransactionsModal').modal('hide'); $scope.clear(); }); }; $scope.update = function (id) { Transactions.get({id: id}, function(result) { $scope.transactions = result; $('#saveTransactionsModal').modal('show'); }); }; $scope.delete = function (id) { Transactions.get({id: id}, function(result) { $scope.transactions = result; $('#deleteTransactionsConfirmation').modal('show'); }); }; $scope.confirmDelete = function (id) { Transactions.delete({id: id}, function () { $scope.loadAll(); $('#deleteTransactionsConfirmation').modal('hide'); $scope.clear(); }); }; $scope.clear = function () { $scope.transactions = {id: null}; $scope.editForm.$setPristine(); $scope.editForm.$setUntouched(); }; });
33.016949
99
0.476386
9131422f77b0b8c84947bd8dacead7adf61898cd
3,851
js
JavaScript
node_modules/cesium/Build/Cesium/Workers/createCircleGeometry.js
Ldthovn/Cesium
6fc0e25a0d98bbbaf6c0e1abe3ab4adbd1cfccca
[ "Zlib", "Apache-2.0" ]
null
null
null
node_modules/cesium/Build/Cesium/Workers/createCircleGeometry.js
Ldthovn/Cesium
6fc0e25a0d98bbbaf6c0e1abe3ab4adbd1cfccca
[ "Zlib", "Apache-2.0" ]
null
null
null
node_modules/cesium/Build/Cesium/Workers/createCircleGeometry.js
Ldthovn/Cesium
6fc0e25a0d98bbbaf6c0e1abe3ab4adbd1cfccca
[ "Zlib", "Apache-2.0" ]
1
2021-04-14T07:05:18.000Z
2021-04-14T07:05:18.000Z
/** * Cesium - https://github.com/AnalyticalGraphicsInc/cesium * * Copyright 2011-2020 Cesium Contributors * * 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. * * Columbus View (Pat. Pend.) * * Portions licensed separately. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details. */ define(["./when-0488ac89","./Check-78ca6843","./Math-8a4c9da1","./Cartesian2-cc1e6450","./defineProperties-c6a70625","./Transforms-fa4f10bc","./RuntimeError-4d6e0952","./WebGLConstants-66e14a3b","./ComponentDatatype-9252f28f","./GeometryAttribute-3345e440","./GeometryAttributes-3227db5b","./AttributeCompression-fe1560e2","./GeometryPipeline-587f449d","./EncodedCartesian3-97ac8d01","./IndexDatatype-8575c917","./IntersectionTests-12255a09","./Plane-466db411","./GeometryOffsetAttribute-22febf92","./VertexFormat-7996cb24","./EllipseGeometryLibrary-ff71c40e","./GeometryInstance-2a7fafaf","./EllipseGeometry-e762155f"],function(o,e,t,a,i,r,n,s,l,m,d,c,u,p,y,_,h,G,f,x,g,v){"use strict";function E(e){var t=(e=o.defaultValue(e,o.defaultValue.EMPTY_OBJECT)).radius,i={center:e.center,semiMajorAxis:t,semiMinorAxis:t,ellipsoid:e.ellipsoid,height:e.height,extrudedHeight:e.extrudedHeight,granularity:e.granularity,vertexFormat:e.vertexFormat,stRotation:e.stRotation,shadowVolume:e.shadowVolume};this._ellipseGeometry=new v.EllipseGeometry(i),this._workerName="createCircleGeometry"}E.packedLength=v.EllipseGeometry.packedLength,E.pack=function(e,t,i){return v.EllipseGeometry.pack(e._ellipseGeometry,t,i)};var w=new v.EllipseGeometry({center:new a.Cartesian3,semiMajorAxis:1,semiMinorAxis:1}),A={center:new a.Cartesian3,radius:void 0,ellipsoid:a.Ellipsoid.clone(a.Ellipsoid.UNIT_SPHERE),height:void 0,extrudedHeight:void 0,granularity:void 0,vertexFormat:new f.VertexFormat,stRotation:void 0,semiMajorAxis:void 0,semiMinorAxis:void 0,shadowVolume:void 0};return E.unpack=function(e,t,i){var r=v.EllipseGeometry.unpack(e,t,w);return A.center=a.Cartesian3.clone(r._center,A.center),A.ellipsoid=a.Ellipsoid.clone(r._ellipsoid,A.ellipsoid),A.height=r._height,A.extrudedHeight=r._extrudedHeight,A.granularity=r._granularity,A.vertexFormat=f.VertexFormat.clone(r._vertexFormat,A.vertexFormat),A.stRotation=r._stRotation,A.shadowVolume=r._shadowVolume,o.defined(i)?(A.semiMajorAxis=r._semiMajorAxis,A.semiMinorAxis=r._semiMinorAxis,i._ellipseGeometry=new v.EllipseGeometry(A),i):(A.radius=r._semiMajorAxis,new E(A))},E.createGeometry=function(e){return v.EllipseGeometry.createGeometry(e._ellipseGeometry)},E.createShadowVolume=function(e,t,i){var r=e._ellipseGeometry._granularity,o=e._ellipseGeometry._ellipsoid,a=t(r,o),n=i(r,o);return new E({center:e._ellipseGeometry._center,radius:e._ellipseGeometry._semiMajorAxis,ellipsoid:o,stRotation:e._ellipseGeometry._stRotation,granularity:r,extrudedHeight:a,height:n,vertexFormat:f.VertexFormat.POSITION_ONLY,shadowVolume:!0})},i.defineProperties(E.prototype,{rectangle:{get:function(){return this._ellipseGeometry.rectangle}},textureCoordinateRotationPoints:{get:function(){return this._ellipseGeometry.textureCoordinateRotationPoints}}}),function(e,t){return o.defined(t)&&(e=E.unpack(e,t)),e._ellipseGeometry._center=a.Cartesian3.clone(e._ellipseGeometry._center),e._ellipseGeometry._ellipsoid=a.Ellipsoid.clone(e._ellipseGeometry._ellipsoid),E.createGeometry(e)}});
160.458333
3,007
0.800312
91335804dd4647339e7ea03aaf65fac9ef9325d4
6,951
js
JavaScript
src/javascripts/main.js
rajveersinghsaini-code/dictionary
8f181fed9c08f27e6cfff6d5185f20cc4b6ba5c6
[ "MIT" ]
null
null
null
src/javascripts/main.js
rajveersinghsaini-code/dictionary
8f181fed9c08f27e6cfff6d5185f20cc4b6ba5c6
[ "MIT" ]
null
null
null
src/javascripts/main.js
rajveersinghsaini-code/dictionary
8f181fed9c08f27e6cfff6d5185f20cc4b6ba5c6
[ "MIT" ]
null
null
null
const DICTIONARY_API_URL = "https://api.dictionaryapi.dev/api/v2/entries/en_US/"; const search_result = document.querySelector("div#search_result"); //Clear the previous screen if it has child controls const clearSearchResult = () => { while (search_result.firstChild) { search_result.removeChild(search_result.firstChild); } }; //Method do display no result if API return any error const displayNoResult = () => { clearSearchResult(); let divNoResultFound = document.createElement("div"); divNoResultFound.className = ""; divNoResultFound.append("No definitions found for this word."); search_result.appendChild(divNoResultFound); }; //Main method to render dynamic search result const createDefinitionCard = (resultJson) => { if (resultJson === null || resultJson === undefined) { displayNoResult(); return; } //Definition Card let divDefCard = document.createElement("div"); divDefCard.className = "result-card"; //Search Word let searchWord = document.createElement("p"); searchWord.className = "font-bold"; searchWord.appendChild(document.createTextNode(resultJson.word)); divDefCard.append(searchWord); //phonetic text and audio control if ( resultJson.phonetics !== null && resultJson.phonetics !== undefined && resultJson.phonetics.length > 0 ) { const phonetics = resultJson.phonetics[0]; if (phonetics && Object.keys(phonetics).length > 0) { let phoneticText = document.createElement("p"); //phonetic audio buttton let phoneticAudioButton = document.createElement("button"); phoneticAudioButton.className = "audio-button"; phoneticAudioButton.innerHTML = '<i class="bi bi-volume-up-fill"></i>'; phoneticAudioButton.addEventListener("click", function () { const music = new Audio("https:" + phonetics.audio); music.play(); }); phoneticText.appendChild(phoneticAudioButton); phoneticText.appendChild(document.createTextNode(phonetics.text)); divDefCard.append(phoneticText); } } //Add Origin if (resultJson.origin !== undefined) { let originWord = document.createElement("p"); originWord.appendChild( document.createTextNode("Origin: " + resultJson.origin) ); divDefCard.append(originWord); } //Append Meaning to main result container if (resultJson.meanings !== undefined) { resultJson.meanings.forEach((meaning) => divDefCard.appendChild(createMeaningsCard(meaning)) ); } //Append to main result section search_result.appendChild(divDefCard); }; const createMeaningsCard = (meaningJson) => { let divMeaningCard = document.createElement("div"); if (meaningJson !== null && meaningJson != undefined) { //Part of Speach Word if (meaningJson.partOfSpeech !== undefined) { let partOfSpeechText = document.createElement("p"); partOfSpeechText.className = "font-bold"; partOfSpeechText.appendChild( document.createTextNode(meaningJson.partOfSpeech) ); divMeaningCard.append(partOfSpeechText); } const definitions = meaningJson.definitions; let meaningCount = 1; if (definitions !== undefined) { definitions.forEach((item) => { //Definition Paragraph if (item.definition !== undefined) { let definitionPara = document.createElement("p"); definitionPara.className = "definition-paragraph"; definitionPara.appendChild( document.createTextNode( meaningCount.toString() + ". " + item.definition ) ); divMeaningCard.append(definitionPara); } //Example Paragraph if (item.example !== undefined) { let examplePara = document.createElement("p"); examplePara.className = "definition-example"; examplePara.appendChild(document.createTextNode("- " + item.example)); divMeaningCard.append(examplePara); } //Synonyms if (item.synonyms !== undefined && item.synonyms.length > 0) { let synonymsHeader = document.createElement("span"); synonymsHeader.append("synonyms: "); divMeaningCard.append(synonymsHeader); item.synonyms.forEach((synonyms) => { let synonymsText = document.createElement("span"); synonymsText.className = "badge"; synonymsText.append(document.createTextNode(synonyms)); synonymsText.addEventListener("click", function () { synonymsAntonymsClick(synonyms); }); divMeaningCard.append(synonymsText); }); } //Antonyms if (item.antonyms !== undefined && item.antonyms.length > 0) { divMeaningCard.append(document.createElement("br")); let antonymsHeader = document.createElement("span"); antonymsHeader.append("antonyms: "); divMeaningCard.append(antonymsHeader); item.antonyms.forEach((antonyms) => { let antonymsText = document.createElement("span"); antonymsText.className = "badge"; antonymsText.append(document.createTextNode(antonyms)); antonymsText.addEventListener("click", function () { synonymsAntonymsClick(antonyms); }); divMeaningCard.append(antonymsText); }); } //Increase Meaning counter meaningCount++; }); } } return divMeaningCard; }; const synonymsAntonymsClick = (searchText) =>{ document.querySelector("#search_input").value = searchText; fetchDefinition(); }; //Make Dictionary API Call and generate dynamic result const fetchDefinition = () => { const search_input = document.querySelector("#search_input").value; if (search_input !== undefined && search_input !== "") { fetch(DICTIONARY_API_URL + search_input) .then(function (response) { if (response.status !== 200) { console.log("There was a problem. Status Code: " + response.status); displayNoResult(); return; } // Examine the text in the response response.json().then(function (data) { clearSearchResult(); if (data !== undefined && data !== null) { data.forEach((jsonData) => { createDefinitionCard(jsonData); }); } }); }) .catch(function (err) { console.log("Fetch Error: ", err); }); } }; //Add event on textbox and search button (function () { const search_submit = document.querySelector("#search_submit"); search_submit.addEventListener("click", function () { fetchDefinition(); }); // Get the input field const search_input = document.querySelector("#search_input"); search_input.addEventListener("keyup", function (event) { if (event.keyCode === 13) { event.preventDefault(); search_submit.click(); } }); })();
34.929648
80
0.644512
913377b9932932b3aeae6a02a5d45f88c2a76af7
735
js
JavaScript
src/logger.js
jucrouzet/icecast.js
03b2e389a8b99a34110371be33ef36ce3638cc1c
[ "MIT" ]
14
2017-01-09T01:48:24.000Z
2021-06-18T17:05:19.000Z
src/logger.js
jucrouzet/icecast.js
03b2e389a8b99a34110371be33ef36ce3638cc1c
[ "MIT" ]
4
2016-09-02T11:27:44.000Z
2020-05-05T22:19:49.000Z
src/logger.js
jucrouzet/icecast.js
03b2e389a8b99a34110371be33ef36ce3638cc1c
[ "MIT" ]
6
2016-09-02T11:24:38.000Z
2020-12-29T22:01:51.000Z
"use strict"; exports.__esModule = true; var Utils = require("./utils"); var LogLevel = require("loglevel"); LogLevel.setLevel(__LOG_LEVEL__); var prefix = require('loglevel-plugin-prefix'); //tslint:disable-line: no-any no-var-requires prefix.apply(LogLevel, { template: '%n', nameFormatter: function (name) { if (Utils.isUndefined(name)) { return ''; } return "[" + name + "]: "; } }); /** * Get a named logger instance. */ function logger(instanceName) { var name = (Utils.isUndefined(instanceName)) ? 'Icecast.js' : "Icecast.js/" + instanceName; var instance = LogLevel.getLogger(name); instance.setLevel(__LOG_LEVEL__); return instance; } exports.logger = logger;
28.269231
95
0.646259
9134a7ce52ee84cffc314a9b260aaa9b385af386
2,029
js
JavaScript
prod.server.js
qirenji/music-vue
3600e8e8e7d5fb0166c35b3443f1768f59c1b5c8
[ "MIT" ]
4
2017-09-07T01:22:05.000Z
2017-12-22T00:21:37.000Z
prod.server.js
qirenji/music-vue
3600e8e8e7d5fb0166c35b3443f1768f59c1b5c8
[ "MIT" ]
1
2018-07-26T23:47:00.000Z
2018-07-26T23:47:00.000Z
prod.server.js
qirenji/music-vue
3600e8e8e7d5fb0166c35b3443f1768f59c1b5c8
[ "MIT" ]
null
null
null
var express = require('express'); var http = require('http'); var port = process.env.PORT || 18003; var app = express(); var router = express.Router(); app.use(express.static('./dist')); var data = require('./music-data.json'); router.get("/",function(req,res){ res.render('index.html',{}) }) router.get('/music-data',(req, res) => { res.json({ errno: 0, musicData: data.musicData }); }); router.get('/hot', (req, res) => { // 热门关键词 let hotKeywords = ['张杰', '赵雷', '李健', '林志炫', '张碧晨', '梁博', '周笔畅', '张靓颖', '陈奕迅', '周杰伦', '王力宏', 'TFBoys', '李玉刚', '魏晨', '薛之谦']; let rHot = new Array(6); for(let i=0; i<rHot.length;i++){ let length = hotKeywords.length; let random = Math.floor(length * Math.random()); rHot[i] = hotKeywords[random]; hotKeywords.splice(random,1); } res.json(rHot); }); function searchUrl(url) { return new Promise((resolve, reject) => { let searchResult = ''; // 参考至https://blog.csdn.net/jamin2018/article/details/79157213 http.get(url, response => { response.on('data', data => { searchResult += data; }); response.on('end', () => { resolve(searchResult); }) }) }) } // 获取搜索信息 router.get('/search', (req, res) => { let keywords = req.query.keywords; let url = encodeURI('http://songsearch.kugou.com/song_search_v2?page=1&pagesize=20&platform=WebFilter&userid=-1&iscorrection=1&privilege_filter=0&filter=2&keyword='+ keywords); searchUrl(url) .then(searchResult => { let result = JSON.parse(searchResult) res.json(result); }) }); // 获取播放信息 router.get('/play', (req, res) => { let hash = req.query.hash; // 获取歌曲信息 let url = encodeURI('http://www.kugou.com/yy/index.php?r=play/getdata&hash='+ hash); searchUrl(url) .then(result => { res.json(JSON.parse(result)); }) }); app.use('/api', router); module.exports = app.listen(port, function (err) { if (err) { console.log(err); return } console.log('Listening at http://localhost:' + port + '\n') });
24.154762
178
0.601281
91354ca248a7d459ed3d79696161bca7dd903e91
687
js
JavaScript
template/src/router/routes.js
gdefenser/gns-admin-frontend
e94458970ebe30a332672d0b4de67b64b33bc7a2
[ "MIT" ]
null
null
null
template/src/router/routes.js
gdefenser/gns-admin-frontend
e94458970ebe30a332672d0b4de67b64b33bc7a2
[ "MIT" ]
null
null
null
template/src/router/routes.js
gdefenser/gns-admin-frontend
e94458970ebe30a332672d0b4de67b64b33bc7a2
[ "MIT" ]
null
null
null
//const NotFound = () => import(/* webpackChunkName: "group-pub" */'../components/page/NotFound.vue') //const App = () => import(/* webpackChunkName: "group-pub" */'../App.vue') //const Dashboard = () => import(/* webpackChunkName: "group-pub" */'../pages/Dashboard.vue') import NotFound from '../components/page/NotFound' import App from '../App' import Dashboard from '../pages/Dashboard' // Routes const routes = [ { path: '', component: App, children: [ { path: '/dashboard', name: 'Dashboard', component: Dashboard }, { path: '/', name: 'MainPage', component: Dashboard }, ] }, { path: '*', component: NotFound } ] export default routes
26.423077
101
0.612809
9135501e090e95e0b510e7a2e8533d267382e74b
2,673
js
JavaScript
public_html/js/modules/CartServicesForm.js
AlexeyProt/quick_step
ce4424cb58e029f673dd9093679af429c92a31fc
[ "MIT" ]
null
null
null
public_html/js/modules/CartServicesForm.js
AlexeyProt/quick_step
ce4424cb58e029f673dd9093679af429c92a31fc
[ "MIT" ]
null
null
null
public_html/js/modules/CartServicesForm.js
AlexeyProt/quick_step
ce4424cb58e029f673dd9093679af429c92a31fc
[ "MIT" ]
null
null
null
"use strict"; class CartServicesForm extends CartForm { constructor(args) { super(args); console.log('CartServicesForm'); } /** * Устанавливает сумму за услуги * @param array sumPrices */ _setServiceSum(sumPrices) { let sum = 0; for (let i = 0; i < sumPrices.length; i++) { sum += sumPrices[i]; } if (sum && sum < 5000) sum = 5000; this.nodes.service_sum.innerHTML = sum; } // Вычисляет и устанавливает общую сумму // Устанавливает массив this._postProductsData с данными выбранных товаров // Устанавливает массив this._postServicesData с данными выбранных услуг _totalAmount() { this._inputs = this._elem.querySelectorAll('[name="select"]'); this._postProductsData = []; this._postServicesData = []; this._resetTotalAmount(); this.nodes.service_sum.innerHTML = 0; let sumPrices = []; for ( var i = 0; i < this._inputs.length; i++ ) { if ( this._inputs[i].checked ) { var target = this._inputs[i]; while ( target != this._elem ) { if ( target.dataset.id ) { var sum = target.querySelector('[data-cart-window="sum"]'), quantity = target.querySelector('[data-cart-window="quantity"]'), serviceName = target.querySelector('[data-cart-window="service name"]'); if (serviceName) { sumPrices.push( Number(sum.innerHTML) ); this._postServicesData[this._postServicesData.length] = {id: +target.dataset.id, quantity: +quantity.innerHTML}; break; } this._setTotalAmount(sum.innerHTML); this._postProductsData[this._postProductsData.length] = {id: +target.dataset.id, quantity: +quantity.innerHTML}; break; } target = target.parentNode; } } } this._setServiceSum(sumPrices); this._setTotalAmount(this.nodes.service_sum.innerHTML); } // Выполняет запрос добавления выбранных товаров и услуг для оформления заказа _addToOrderAjax() { let order = { order_products: this._postProductsData, order_services: this._postServicesData } $.ajax({ url: "/cart/add-to-order", type: "POST", data: JSON.stringify(order), processData: false, contentType: 'application/json', success: this._redirect.bind(this), error: this._showError.bind(this) }); } // Если не выбран ни один товар, выводит сообщение об ошибке // Выполняет запрос добавления выбранных товаров для оформления заказа _checkSelected() { if (!this._postProductsData.length && !this._postServicesData) { this._notice.innerHTML = ''; this.addWarning('Не выбран ни один товар.<br> Отметьте товары, которые хотите купить.'); return; } this._addToOrderAjax(); } }
29.373626
119
0.668163
913597d6e9d23518e6305fb750ef7ca4ac5b2d94
603
js
JavaScript
components/header/index.js
dogdogbrother/my-github
7ced73351405d7002b62b551589cdb0ac7af1975
[ "Apache-2.0" ]
null
null
null
components/header/index.js
dogdogbrother/my-github
7ced73351405d7002b62b551589cdb0ac7af1975
[ "Apache-2.0" ]
1
2021-12-09T02:08:57.000Z
2021-12-09T02:08:57.000Z
components/header/index.js
dogdogbrother/my-github
7ced73351405d7002b62b551589cdb0ac7af1975
[ "Apache-2.0" ]
null
null
null
import GithubLinkIcon from './github-link-icon' import BannerSearch from './banner-search' const Header = () => { return ( <> <header className="banner df sb"> <div className="df fs"> <GithubLinkIcon /> <BannerSearch /> </div> </header> <style jsx> {` .banner { color: hsla(0,0%,100%,.7); padding: 16px; background-color: #24292e; } svg{ color:#fff; } `} </style> </> ) } export default Header
20.1
48
0.432836
91377b7afcc0d9b3d800d51824ab974f7f011e2b
101
js
JavaScript
index.js
OrKoN/fa
e14de8d3590600a4784640135c9d001cb0e7f843
[ "MIT" ]
null
null
null
index.js
OrKoN/fa
e14de8d3590600a4784640135c9d001cb0e7f843
[ "MIT" ]
null
null
null
index.js
OrKoN/fa
e14de8d3590600a4784640135c9d001cb0e7f843
[ "MIT" ]
null
null
null
module.exports = { StateMachine: require('./fa'), DetermenisticStateMachine: require('./dfa') };
20.2
45
0.683168
9137d2d2232721751e1a7291ed24376192f8e40b
3,079
js
JavaScript
src/screens/discovery/catalog-detail/store.js
ekibun/BangumiTinygrailPlugin
21cf8a4c21df97d494e2730d6f3e915966bd8ee2
[ "MIT" ]
4
2020-08-01T01:59:54.000Z
2022-01-16T01:25:38.000Z
src/screens/discovery/catalog-detail/store.js
ekibun/BangumiTinygrailPlugin
21cf8a4c21df97d494e2730d6f3e915966bd8ee2
[ "MIT" ]
null
null
null
src/screens/discovery/catalog-detail/store.js
ekibun/BangumiTinygrailPlugin
21cf8a4c21df97d494e2730d6f3e915966bd8ee2
[ "MIT" ]
null
null
null
/* * @Author: czy0729 * @Date: 2020-01-05 22:24:28 * @Last Modified by: czy0729 * @Last Modified time: 2020-11-10 23:12:29 */ import { observable, computed } from 'mobx' import { discoveryStore, collectionStore, subjectStore } from '@stores' import store from '@utils/store' import { info, feedback } from '@utils/ui' import { t, fetchHTML } from '@utils/fetch' import { HOST } from '@constants' import rateData from '@constants/json/rate.json' const namespace = 'ScreenCatalogDetail' export default class ScreenCatalogDetail extends store { state = observable({ sort: 0, _loaded: false }) init = async () => { const res = this.getStorage(undefined, namespace) const state = await res this.setState({ ...state, _loaded: true }) return this.fetchCatalogDetail() } // -------------------- fetch -------------------- fetchCatalogDetail = () => discoveryStore.fetchCatalogDetail({ id: this.catalogId }) // -------------------- get -------------------- @computed get catalogId() { const { catalogId = '' } = this.params return catalogId } @computed get catalogDetail() { const { sort } = this.state const catalogDetail = discoveryStore.catalogDetail(this.catalogId) let list = catalogDetail.list.map(item => ({ ...item, score: subjectStore.subject(item.id)?.rating?.score || rateData[item.id] || 0 })) if (sort === 1) { // 时间 list = list.sort((a, b) => b.info.localeCompare(a.info)) } else if (sort === 2) { // 分数 list = list.sort((a, b) => b.score - a.score) } return { ...catalogDetail, list } } @computed get isCollect() { const { byeUrl } = this.catalogDetail return !!byeUrl } @computed get userCollectionsMap() { return collectionStore.userCollectionsMap } // -------------------- page -------------------- /** * 收藏或取消目录 */ toggleCollect = () => { const { byeUrl } = this.catalogDetail if (byeUrl) { this.doErase() return } this.doCollect() } sort = title => { const sort = title === '评分' ? 2 : title === '时间' ? 1 : 0 t('目录详情.排序', { sort }) this.setState({ sort }) this.setStorage(undefined, undefined, namespace) } // -------------------- action -------------------- /** * 收藏目录 */ doCollect = async () => { const { joinUrl } = this.catalogDetail if (!joinUrl) { return false } t('目录详情.收藏', { catalogId: this.catalogId }) await fetchHTML({ method: 'POST', url: `${HOST}${joinUrl}` }) feedback() info('已收藏') return this.fetchCatalogDetail() } /** * 取消收藏目录 */ doErase = async () => { const { byeUrl } = this.catalogDetail if (!byeUrl) { return false } t('目录详情.取消收藏', { catalogId: this.catalogId }) await fetchHTML({ method: 'POST', url: `${HOST}${byeUrl}` }) feedback() info('已取消收藏') return this.fetchCatalogDetail() } }
20.526667
78
0.54141
913823dc1c42d6fcd00b09358fa67a53a4c1087a
2,675
js
JavaScript
tests/browser/spa/interaction.test.js
martinkuba/newrelic-browser-agent
e68c0a77a94e8bfa280b00214f7c6866f6ab7d2f
[ "Apache-2.0" ]
18
2021-04-29T17:15:50.000Z
2022-02-24T10:05:40.000Z
tests/browser/spa/interaction.test.js
martinkuba/newrelic-browser-agent
e68c0a77a94e8bfa280b00214f7c6866f6ab7d2f
[ "Apache-2.0" ]
96
2021-04-29T23:37:49.000Z
2022-03-30T15:54:04.000Z
tests/browser/spa/interaction.test.js
metal-messiah/newrelic-browser-agent
62a32238d2d0e213a12ed59d84a7196900e936d5
[ "Apache-2.0" ]
12
2021-04-28T22:42:58.000Z
2022-03-18T16:18:44.000Z
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ const jil = require('jil') jil.browserTest('checkFinish', function (t) { var loader = require('loader') loader.info = {} var clearTimeoutCalls = 0 NREUM.o.CT = function() { clearTimeoutCalls++ } var setTimeoutCalls = 0 var executeTimeoutCallback = true NREUM.o.ST = function(cb) { setTimeoutCalls++ if (executeTimeoutCallback) cb() return setTimeoutCalls } var Interaction = require('../../../feature/spa/aggregate/Interaction') t.test('checkFinish sets timers', function(t) { var interaction = new Interaction() var setTimeoutCallsStart = setTimeoutCalls interaction.checkFinish() t.ok(setTimeoutCalls === setTimeoutCallsStart + 2, 'setTimeout has been called twice') t.end() }) t.test('checkFinish does not set timers when there is work in progress', function(t) { var interaction = new Interaction() var setTimeoutCallsStart = setTimeoutCalls interaction.remaining = 1 interaction.checkFinish() t.equals(setTimeoutCallsStart, setTimeoutCalls) t.end() }) t.test('assigns url and routename to attributes', function(t) { var interaction = new Interaction() t.ok(interaction.root.attrs.newURL === undefined, 'url is undefined initially') t.ok(interaction.root.attrs.newRoute === undefined, 'route name is undefined initially') interaction.checkFinish('some url', 'some route name') t.ok(interaction.root.attrs.newURL === 'some url', 'url has been set') t.ok(interaction.root.attrs.newRoute === 'some route name', 'route name has been set') t.end() }) t.test('does not reset finishTimer if it has already been set', function(t) { var setTimeoutCallsStart = setTimeoutCalls executeTimeoutCallback = false var interaction = new Interaction() interaction.checkFinish() t.equals(setTimeoutCallsStart + 1, setTimeoutCalls, 'setTimeout has been called once') interaction.checkFinish() t.equals(setTimeoutCallsStart + 1, setTimeoutCalls, 'setTimeout has not been called again') executeTimeoutCallback = true t.end() }) t.test('if timer is in progress and there is work remaining, timer should be cancelled', function(t) { var clearTimeoutCallsStart = clearTimeoutCalls executeTimeoutCallback = false var interaction = new Interaction() interaction.checkFinish() interaction.remaining = 1 interaction.checkFinish() t.equals(clearTimeoutCallsStart + 1, clearTimeoutCalls, 'clearTimeout has been called once') executeTimeoutCallback = true t.end() }) })
28.763441
104
0.706168
91383eeb66106993cde64911f385071fea54f2ed
593
js
JavaScript
app/javascript/dashboard/modules/widget-preview/stories/Widget.stories.js
Devyani606/chatwoot
1b5eae5b7ec06d1a067847c46b39611e5214737f
[ "MIT" ]
12,874
2019-08-14T07:21:35.000Z
2022-03-31T19:40:46.000Z
app/javascript/dashboard/modules/widget-preview/stories/Widget.stories.js
Devyani606/chatwoot
1b5eae5b7ec06d1a067847c46b39611e5214737f
[ "MIT" ]
2,629
2019-08-19T08:21:08.000Z
2022-03-31T18:28:04.000Z
app/javascript/dashboard/modules/widget-preview/stories/Widget.stories.js
Devyani606/chatwoot
1b5eae5b7ec06d1a067847c46b39611e5214737f
[ "MIT" ]
1,774
2019-08-19T01:36:44.000Z
2022-03-31T08:37:55.000Z
import Widget from '../components/Widget'; const ReplyTime = { 'In a few minutes': 'in_a_few_minutes', 'In a few hours': 'in_a_few_hours', 'In a few day': 'in_a_day', }; export default { title: 'components/Widget', component: Widget, argTypes: { replyTime: { control: { type: 'select', options: ReplyTime, }, }, }, }; const Template = (args, { argTypes }) => ({ props: Object.keys(argTypes), components: { Widget }, template: '<Widget v-bind="$props" />', }); export const DefaultWidget = Template.bind({}); DefaultWidget.args = {};
19.766667
47
0.602024
9139381b38840003f803d11ff5bc1acd385bee67
3,277
js
JavaScript
lib/gallery_detail/gd-1/index.js
thanhtam282/Museum
ed91602166b2a1e87666db6a4efb5a872ebcf72c
[ "Unlicense" ]
null
null
null
lib/gallery_detail/gd-1/index.js
thanhtam282/Museum
ed91602166b2a1e87666db6a4efb5a872ebcf72c
[ "Unlicense" ]
null
null
null
lib/gallery_detail/gd-1/index.js
thanhtam282/Museum
ed91602166b2a1e87666db6a4efb5a872ebcf72c
[ "Unlicense" ]
null
null
null
function ProductDetailShop1() { $('.canhcam-gallery-details-1 .product-details .slider-for').not('.slick-initialized').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: false, infinite: true, autoplay: false, asNavFor: '.slider-nav' }); $('.canhcam-gallery-details-1 .product-details .slider-nav').not('.slick-initialized').slick({ autoplay: false, slidesToShow: 5, slidesToScroll: 1, asNavFor: '.slider-for', dots: false, arrows: true, centerMode: false, focusOnSelect: true, prevArrow: $('.top-arrow'), nextArrow: $('.bottom-arrow'), vertical: true, variableWidth: false, verticalSwiping: false, infinite: true, responsive: [{ breakpoint: 992, settings: { slidesToShow: 6, vertical: false, verticalSwiping: false, variableWidth: false }}, { breakpoint: 768, settings: { vertical: false, slidesToShow: 4, verticalSwiping: false, variableWidth: false } }] }).on('init', function (event, slick, direction) { if (!$('.canhcam-gallery-details-1 .product-details .slider-nav .top-arrow').is(':visible')) { $('.canhcam-gallery-details-1 .product-details .slider-control').css({ 'padding-top': '0px' }) } }).on('afterChange', function (event, slick, currentSlide, nextSlide) { var getcs = slick.$slides.length - 1 if (currentSlide == 0) { $('.canhcam-gallery-details-1 .product-details .top-arrow').attr('disabled', 'disabled') } else { $('.canhcam-gallery-details-1 .product-details .top-arrow').removeAttr('disabled') } if (getcs == currentSlide) { $('.canhcam-gallery-details-1 .product-details .bottom-arrow').attr('disabled', 'disabled') } else { $('.canhcam-gallery-details-1 .product-details .bottom-arrow').removeAttr('disabled') } }); }; function Gallerydetail() { $(".canhcam-gallery-details-1 .slider-for ").lightGallery({ thumbnail: true, animateThumb: false, showThumbByDefault: false, selector: 'a' }); } $(document).ready(function() { Gallerydetail() }); $(document).ready(function () { ProductDetailShop1(); $('.canhcam-gallery-details-1 #quantity input').TouchSpin({ min: 0, max: 100, buttondown_class: "btn btn-default", buttonup_class: "btn btn-default" }); }); $(function () { }) $(window).resize(function () {}) $(function () { if ($('.canhcam-gallery-details-1 .list-items').length) { $(".canhcam-gallery-details-1 .list-items").not('.slick-initialized').slick({ // autoplay: true, // slickPlay: true, // slickPause: true, autoplaySpeed: 1600, dots: false, infinite: true, speed: 300, arrows: true, slidesToShow: 3, slidesToScroll: 1, // customPaging: function(slider, i) { // var thumb = $(slider.$slides[i]).data('thumb'); // return '<a><p> ' + thumb + '</p></a>'; // }, }); } if ($('.canhcam-gallery-details-1 .owl-carousel').length) { $(' .canhcam-gallery-details-1 .owl-carousel').owlCarousel({ loop: true, margin: 30, nav: true, dots: false, navText: ["<span class='lnr lnr-chevron-left'></span>","<span class='lnr lnr-chevron-right'></span>"], responsive: { 0: { items: 1 }, 768: { items: 2 }, 992: { items: 3 } } }) } });
21.993289
105
0.6213
9139869a818676795aa665a04a8322dbe618179a
3,071
js
JavaScript
test/interactors/findAgreement.js
folio-org/ui-plugin-find-agreement
30086dde89667fc82381cba0b7edeee598f8bc8c
[ "Apache-2.0" ]
null
null
null
test/interactors/findAgreement.js
folio-org/ui-plugin-find-agreement
30086dde89667fc82381cba0b7edeee598f8bc8c
[ "Apache-2.0" ]
72
2020-02-10T23:08:20.000Z
2022-03-18T14:39:28.000Z
test/interactors/findAgreement.js
folio-org/ui-plugin-find-agreement
30086dde89667fc82381cba0b7edeee598f8bc8c
[ "Apache-2.0" ]
null
null
null
import { interactor, scoped, collection, clickable, fillable, is, isPresent, text } from '@bigtest/interactor'; import css from '../../src/AgreementSearch.css'; @interactor class SearchField { static defaultScope = '[data-test-agreement-search-input]'; fill = fillable(); } @interactor class PluginModalInteractor { isStatusFilterPresent = isPresent('#accordion-toggle-button-filter-accordion-agreementStatus') isRenewalPriorityFilterPresent = isPresent('#accordion-toggle-button-filter-accordion-renewalPriority') isIsPerpetualFilterPresent = isPresent('#accordion-toggle-button-filter-accordion-isPerpetual'); isOrgsFilterPresent = isPresent('#accordion-toggle-button-organizations-filter'); isOrgsRoleFilterPresent = isPresent('#accordion-toggle-button-organization-role-filter'); isInternalContactsFilterPresent = isPresent('#accordion-toggle-button-internal-contacts-filter'); isInternalContactRoleFilterPresent = isPresent('#accordion-toggle-button-internal-contacts-role-filter'); isTagsFilterPresent = isPresent('#accordion-toggle-button-clickable-tags-filter'); isSupplementaryPropertiesFilterPresent = isPresent('#accordion-toggle-button-clickable-custprop-filter'); clickClosedFilter = clickable('#clickable-filter-agreementStatus-closed'); clickDraftFilter = clickable('#clickable-filter-agreementStatus-draft'); clickRequestedFilter = clickable('#clickable-filter-agreementStatus-requested'); clickInNegotiationFilter = clickable('#clickable-filter-agreementStatus-in-negotiation'); clickActiveFilter = clickable('#clickable-filter-agreementStatus-active'); clickDefinitelyRenewFilter = clickable('#clickable-filter-renewalPriority-definitely-renew'); clickForReviewFilter = clickable('#clickable-filter-renewalPriority-for-review'); clickDefinitelyCancelFilter = clickable('#clickable-filter-renewalPriority-definitely-cancel'); clickisPerpetualYesFilter = clickable('#clickable-filter-isPerpetual-yes'); clickisPerpetualNoFilter = clickable('#clickable-filter-isPerpetual-no'); instances = collection('[role="rowgroup"] [role="row"]', { click: clickable('[role=gridcell]'), startDate: text('[data-test-start-date]'), endDate: text('[data-test-end-date]'), cancellationDeadline: text('[data-test-cancellation-deadline]'), }); resetButton = scoped('#clickable-reset-all', { isEnabled: is(':not([disabled])'), click: clickable() }); searchField = scoped('[data-test-agreement-search-input]', SearchField); searchButton = scoped('#clickable-search-agreements', { click: clickable(), isEnabled: is(':not([disabled])'), }); } @interactor class FindAgreementInteractor { button = scoped('[data-test-plugin-agreement-button]', { click: clickable(), }); closeButton = scoped('#plugin-find-agreement-modal-close-button', { click: clickable(), }); clearButton = scoped('[data-test-clear-button]', { click: clickable(), }); modal = new PluginModalInteractor(`.${css.modalContent}`); } export default FindAgreementInteractor;
39.371795
107
0.753826
9139d28e0eba4afc59395ad15a29b3f22e185ff5
128
js
JavaScript
src/pipe/map.js
ytiurin/import-export-merger
a25e47666b8968c7bd1c00165c97e06289d21f3a
[ "0BSD" ]
6
2020-05-13T12:57:04.000Z
2020-05-28T02:26:43.000Z
src/pipe/map.js
ytiurin/import-export-merger
a25e47666b8968c7bd1c00165c97e06289d21f3a
[ "0BSD" ]
8
2020-08-18T20:20:03.000Z
2021-04-01T19:44:27.000Z
src/pipe/map.js
ytiurin/import-export-merger
a25e47666b8968c7bd1c00165c97e06289d21f3a
[ "0BSD" ]
null
null
null
const { pipe } = require("./pipe"); const map = (...funcs) => (array) => array.map(pipe(...funcs)); module.exports = { map };
21.333333
63
0.554688
d5b78c5a3ef12667ef5b2f130d089d3078ab977a
400
js
JavaScript
api/areas/index.js
jessechoward/mono-mud
ddc21b0078f9f2e9cbb2903c9211dc5e19a18d3e
[ "MIT" ]
null
null
null
api/areas/index.js
jessechoward/mono-mud
ddc21b0078f9f2e9cbb2903c9211dc5e19a18d3e
[ "MIT" ]
null
null
null
api/areas/index.js
jessechoward/mono-mud
ddc21b0078f9f2e9cbb2903c9211dc5e19a18d3e
[ "MIT" ]
null
null
null
const router = require('express').Router(); router.param('areaId', paramLookup('areas')); router.route('/') .get() .post(); router.route('/:areaId') .get() .post() .patch() .put() .delete(); router.use('/rooms', require('./rooms')); router.use('/items', require('./items')); router.use('/npcs', require('./npcs')); router.use('/instances', require('./instances')); module.exports = router;
20
49
0.6225
d5b83378e0ded3adfdb2e5284f605675f8a52e13
5,811
js
JavaScript
src/createInterceptor.js
lovelybooks/flying-squirrel
6171871ba02b16a20f8b59feb2c1fe0e0e6f517a
[ "MIT" ]
4
2015-10-16T09:33:40.000Z
2017-06-05T14:46:02.000Z
src/createInterceptor.js
lovelybooks/flying-squirrel
6171871ba02b16a20f8b59feb2c1fe0e0e6f517a
[ "MIT" ]
null
null
null
src/createInterceptor.js
lovelybooks/flying-squirrel
6171871ba02b16a20f8b59feb2c1fe0e0e6f517a
[ "MIT" ]
null
null
null
/*jshint jasmine: true */ 'use strict'; require('es6-promise').polyfill(); var _ = require('lodash'); var determineType = require('./schemaUtils').determineType; // A constructor for our objects (this name will show up in the debugger) function Interceptor() {} // The newRefCallback will be called whenever a new ref is accessed. // When inside IO(), this callback would get the needed data and put it to store. function createInterceptor(schema, store, newRefCallback) { console.assert(_.isObject(schema)); console.assert(_.isObject(store)); console.assert(_.isFunction(newRefCallback)); function createSubInterceptorForReference(subSchema, subStore, path) { console.assert(subSchema.__isRef); console.assert(!subStore || _.isNumber(subStore) || _.isString(subStore)); return returnValueForGetter( subSchema.get(schema)[0], // UGLY // TODO: write test for traversing to entries.123 when store.entries is undefined subStore ? (subSchema.get(store) || {})[subStore] : undefined, path ); } function createSubInterceptorForCollection(subSchema, subStore, path) { console.assert(_.isArray(subSchema)); console.assert(subSchema.length === 1); var collectionObj = { keys: function () { if (_.isObject(subStore)) { var keys = subStore.__keys; console.assert(_.isUndefined(keys) || _.isArray(keys)); // TODO: support for criteria using e.g. keys[JSON.stringify(criteria)] if (keys) { return _.clone(keys); } } newRefCallback(path + '.*', subSchema[0]); return ['*']; // hacky: the getter on this key should return item from schema }, getAll: function () { return _.map(this.keys(), this.get, this); }, get: function (id) { console.assert(id !== '__keys'); if (id == null) { throw new Error(id + ' id requested in ' + path); } var isReference = subSchema[0].__isRef; if (isReference) { return returnValueForGetter( subSchema[0], id, // For references, the stored value is just the referenced id // And if we don't reference *, we jump to the referenced path. (id !== '*' ? subSchema[0].ref : path) + '.' + id ); } else { return returnValueForGetter( subSchema[0], _.isObject(subStore) ? subStore[id] : undefined, path + '.' + id ); } }, toJSON: function() { var keys = this.keys(); return JSON.stringify(_.zipObject(keys, _.map(keys, this.get.bind(this)))); }, }; Object.defineProperty(collectionObj, 'length', { get: function () { throw new Error(path + '.length is not supported, use ' + path + '.getAll().length instead.'); }, }); return collectionObj; } function createSubInterceptorForObject(subSchema, subStore, path) { if (path) { path += '.'; } else { path = ''; // Special case for the root path. } var subInterceptor = new Interceptor(); _.each(_.keys(subSchema), function (fieldName) { // TODO: expose referenced objects in toJSON or sth so that _.isEqual can work. // Putting primitives directly to object. This way JSON.stringify may work. if (_.has(subStore, fieldName) && determineType(subSchema[fieldName]) === 'primitive') { subInterceptor[fieldName] = subStore[fieldName]; return; } // For each field in subInterceptor, we define a getter that calls the newRefCallback // whenever we need to use data from schema (i.e. we don't have the data in the store). Object.defineProperty(subInterceptor, fieldName, { get: function () { return returnValueForGetter( subSchema[fieldName], subStore && subStore[fieldName], path + fieldName ); }, }); }); Object.defineProperty(subInterceptor, '_isMocked', { get: function () { return !subStore; }, }); return subInterceptor; } function returnValueForGetter(valueFromSchema, valueFromStore, path) { if (_.isUndefined(valueFromStore)) { // If we don't have a valueFromStore, we'll need to get it. newRefCallback(path, valueFromSchema); } var type = determineType(valueFromSchema); if (type === 'reference') { if (valueFromStore === null) { return null; } return createSubInterceptorForReference(valueFromSchema, valueFromStore, path); } else if (type === 'collection') { return createSubInterceptorForCollection(valueFromSchema, valueFromStore, path); } else if (type === 'object') { return createSubInterceptorForObject(valueFromSchema, valueFromStore, path); } else { return valueFromStore || valueFromSchema; // primitive value } } return createSubInterceptorForObject(schema, store, null); } module.exports = createInterceptor;
40.075862
110
0.538634
d5b8744c5b903b70cb19dcbfb53152106e9b0955
13,538
js
JavaScript
test/convex/convex-tests.js
defisaver/defisaver-v3-contracts
a98fb0df9ba2695d45bfec6f579a08505a8efd2e
[ "MIT" ]
15
2022-02-17T11:09:51.000Z
2022-03-26T09:47:25.000Z
test/convex/convex-tests.js
defisaver/defisaver-v3-contracts
a98fb0df9ba2695d45bfec6f579a08505a8efd2e
[ "MIT" ]
null
null
null
test/convex/convex-tests.js
defisaver/defisaver-v3-contracts
a98fb0df9ba2695d45bfec6f579a08505a8efd2e
[ "MIT" ]
1
2022-03-31T11:22:10.000Z
2022-03-31T11:22:10.000Z
/* eslint-disable no-continue */ /* eslint-disable no-await-in-loop */ /* eslint-disable no-param-reassign */ const { expect } = require('chai'); const hre = require('hardhat'); const { convexDeposit, convexWithdraw, convexClaim } = require('../actions'); const { getProxy, redeploy, Float2BN, balanceOf, setBalance, resetForkToBlock, takeSnapshot, revertToSnapshot, timeTravel, } = require('../utils'); const { noTest: _noTest, poolInfo: _poolInfo, DepositOptions, getRewards, WithdrawOptions, } = require('../utils-convex'); let noTest = _noTest; let poolInfo = _poolInfo; const convexDepositTest = (testLength) => { if (testLength === undefined) { testLength = poolInfo.length; } else { testLength = testLength > poolInfo.length ? poolInfo.length : testLength; } describe('Convex-Deposit', function () { this.timeout(1000000); const amount = Float2BN('10000'); let senderAcc; let senderAddr; let proxy; let snapshot; before(async () => { await resetForkToBlock(14500000); senderAcc = (await hre.ethers.getSigners())[0]; senderAddr = senderAcc.address; proxy = await getProxy(senderAddr); await redeploy('ConvexDeposit'); }); beforeEach(async () => { snapshot = await takeSnapshot(); }); afterEach(async () => { await revertToSnapshot(snapshot); }); it('... should wrap curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, amount, DepositOptions.WRAP, ); expect(await balanceOf(pool.token, senderAddr)).to.be.eq(amount); })); }); it('... should stake wrapped curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.token, senderAddr, amount); await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, amount, DepositOptions.STAKE, ); expect(await balanceOf(pool.crvRewards, senderAddr)).to.be.eq(amount); })); }); it('... should wrap and stake curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, amount, DepositOptions.WRAP_AND_STAKE, ); expect(await balanceOf(pool.crvRewards, senderAddr)).to.be.eq(amount); })); }); after(() => { console.log(`tested ${testLength}/${poolInfo.length} pools, skipped ${noTest}`); }); }); }; const convexWithdrawTest = (testLength) => { if (testLength === undefined) { testLength = poolInfo.length; } else { testLength = testLength > poolInfo.length ? poolInfo.length : testLength; } describe('Convex-Withdraw', function () { this.timeout(1000000); const amount = Float2BN('10000'); let senderAcc; let senderAddr; let proxy; let proxyAddr; let snapshot; before(async () => { await resetForkToBlock(14500000); senderAcc = (await hre.ethers.getSigners())[0]; senderAddr = senderAcc.address; proxy = await getProxy(senderAddr); proxyAddr = proxy.address; await redeploy('ConvexDeposit'); await redeploy('ConvexWithdraw'); await redeploy('ConvexView'); }); beforeEach(async () => { snapshot = await takeSnapshot(); }); afterEach(async () => { await revertToSnapshot(snapshot); }); it('... should unwrap curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, amount, DepositOptions.WRAP, ); expect(await balanceOf(pool.token, senderAddr)).to.be.eq(amount); await convexWithdraw( proxy, senderAddr, senderAddr, pool.lpToken, amount, WithdrawOptions.UNWRAP, ); expect(await balanceOf(pool.lpToken, senderAddr)).to.be.eq(amount); })); }); it('... should unstake wrapped curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, proxyAddr, pool.lpToken, amount, DepositOptions.WRAP_AND_STAKE, ); expect(await balanceOf(pool.crvRewards, proxyAddr)).to.be.eq(amount); await convexWithdraw( proxy, proxyAddr, senderAddr, pool.lpToken, amount, WithdrawOptions.UNSTAKE, ); expect(await balanceOf(pool.token, senderAddr)).to.be.eq(amount); })); }); it('... should unstake and unwrap curve lp', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, proxyAddr, pool.lpToken, amount, DepositOptions.WRAP_AND_STAKE, ); expect(await balanceOf(pool.crvRewards, proxyAddr)).to.be.eq(amount); await convexWithdraw( proxy, proxyAddr, senderAddr, pool.lpToken, amount, WithdrawOptions.UNSTAKE_AND_UNWRAP, ); expect(await balanceOf(pool.lpToken, senderAddr)).to.be.eq(amount); })); }); after(() => { console.log(`tested ${testLength}/${poolInfo.length} pools, skipped ${noTest}`); }); }); }; const convexClaimTest = (testLength) => { if (testLength === undefined) { testLength = poolInfo.length; } else { testLength = testLength > poolInfo.length ? poolInfo.length : testLength; } describe('Convex-Claim', function () { this.timeout(1000000); const amount = Float2BN('10000'); let senderAcc; let senderAddr; let proxy; let proxyAddr; let snapshot; before(async () => { await resetForkToBlock(14500000); senderAcc = (await hre.ethers.getSigners())[0]; senderAddr = senderAcc.address; proxy = await getProxy(senderAddr); proxyAddr = proxy.address; await redeploy('ConvexDeposit'); await redeploy('ConvexWithdraw'); await redeploy('ConvexClaim'); await redeploy('ConvexView'); }); beforeEach(async () => { snapshot = await takeSnapshot(); }); afterEach(async () => { await revertToSnapshot(snapshot); }); it('... should claim rewards for user and send to proxy', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount.add('1')); await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, amount, DepositOptions.WRAP_AND_STAKE, ); expect(await balanceOf(pool.crvRewards, senderAddr)).to.be.eq(amount); })); await timeTravel(60 * 60 * 24 * 7); for (let i = 0; i < poolInfo.length; i++) { const pool = poolInfo[i]; if (noTest.includes(pool.pid) || i >= testLength) { continue; } // need to bump state await convexDeposit( proxy, senderAddr, senderAddr, pool.lpToken, Float2BN('1', 0), DepositOptions.WRAP_AND_STAKE, ); const rewards = await getRewards(senderAddr, pool.crvRewards); const balancesB4 = await Promise.all( rewards.map(async (e) => balanceOf(e.token, senderAddr)), ); await convexClaim( proxy, senderAddr, proxyAddr, pool.lpToken, ); await Promise.all(rewards.map(async (e, j) => expect( (await balanceOf(e.token, proxyAddr)).sub(balancesB4[j]), ).to.be.gte(e.earned))); } }); it('... should claim rewards for proxy and send to user', async () => { await Promise.all(poolInfo.map(async (pool, i) => { if (noTest.includes(pool.pid) || i >= testLength) { return; } await setBalance(pool.lpToken, senderAddr, amount); await convexDeposit( proxy, senderAddr, proxyAddr, pool.lpToken, amount, DepositOptions.WRAP_AND_STAKE, ); expect(await balanceOf(pool.crvRewards, proxyAddr)).to.be.eq(amount); })); await timeTravel(60 * 60 * 24 * 7); for (let i = 0; i < poolInfo.length; i++) { const pool = poolInfo[i]; if (noTest.includes(pool.pid) || i >= testLength) { continue; } await convexWithdraw( proxy, proxyAddr, senderAddr, pool.lpToken, amount, WithdrawOptions.UNSTAKE_AND_UNWRAP, ); expect(await balanceOf(pool.lpToken, senderAddr)).to.be.eq(amount); const rewards = await getRewards(proxyAddr, pool.crvRewards); const balancesB4 = await Promise.all( rewards.map(async (e) => balanceOf(e.token, senderAddr)), ); await convexClaim( proxy, proxyAddr, senderAddr, pool.lpToken, ); await Promise.all(rewards.map(async (e, j) => expect( (await balanceOf(e.token, senderAddr)).sub(balancesB4[j]), ).to.be.gte(e.earned))); } }); after(() => { console.log(`tested ${testLength}/${poolInfo.length} pools, skipped ${noTest}`); }); }); }; const convexFullTest = (testLength, single) => { if (single !== undefined) { poolInfo = [_poolInfo[single]]; testLength = 1; noTest = []; } describe('Convex full test', () => { it('... should do full Convex test', async () => { convexDepositTest(testLength); convexWithdrawTest(testLength); convexClaimTest(testLength); }); }); }; module.exports = { convexDepositTest, convexWithdrawTest, convexClaimTest, convexFullTest, };
31.193548
92
0.466391
d5b8d7eba76fc876ca0ca97b993aba2347f45ed7
398,373
js
JavaScript
jawfish/static/script/brython.js
NeolithEra/jawfish
22fe222e607f0ad275860c75d81ab41114a18eb3
[ "MIT" ]
52
2016-08-08T15:08:19.000Z
2022-03-23T09:48:53.000Z
jawfish/static/script/brython.js
NeolithEra/jawfish
22fe222e607f0ad275860c75d81ab41114a18eb3
[ "MIT" ]
6
2016-10-09T19:50:49.000Z
2019-08-17T15:34:21.000Z
jawfish/static/script/brython.js
NeolithEra/jawfish
22fe222e607f0ad275860c75d81ab41114a18eb3
[ "MIT" ]
15
2017-02-03T03:08:57.000Z
2021-08-04T06:11:15.000Z
// brython.js brython.info // version [3, 3, 0, 'alpha', 0] // implementation [3, 1, 3, 'final', 0] // version compiled from commented, indented source files at github.com/brython-dev/brython var __BRYTHON__=__BRYTHON__ ||{} ;(function($B){ var scripts=document.getElementsByTagName('script') var this_url=scripts[scripts.length-1].src var elts=this_url.split('/') elts.pop() var $path=$B.brython_path=elts.join('/')+'/' var $href=$B.script_path=window.location.href var $href_elts=$href.split('/') $href_elts.pop() var $script_dir=$B.script_dir=$href_elts.join('/') $B.$py_module_path={} $B.path=[$path+'Lib',$script_dir,$path+'Lib/site-packages'] $B.bound={} $B.async_enabled=false if($B.async_enabled)$B.block={} $B.modules={} $B.imported={__main__:{__class__:$B.$ModuleDict,__name__:'__main__'}} $B.vars={} $B.globals={} $B.frames_stack=[] $B.builtins={__repr__:function(){return "<module 'builtins>'"},__str__:function(){return "<module 'builtins'>"},} $B.builtin_funcs={} $B.__getattr__=function(attr){return this[attr]} $B.__setattr__=function(attr,value){ if(['debug','stdout','stderr'].indexOf(attr)>-1){$B[attr]=value} else{throw $B.builtins.AttributeError('__BRYTHON__ object has no attribute '+attr)}} $B.language=window.navigator.userLanguage ||window.navigator.language $B.charset=document.characterSet ||document.inputEncoding ||"utf-8" var has_storage=typeof(Storage)!=="undefined" if(has_storage){$B.has_local_storage=false try{ if(localStorage){$B.local_storage=localStorage $B.has_local_storage=true }}catch(err){} $B.has_session_storage=false try{ if(sessionStorage){$B.session_storage=sessionStorage $B.has_session_storage=true }}catch(err){}}else{ $B.has_local_storage=false $B.has_session_storage=false } $B._indexedDB=window.indexedDB ||window.webkitIndexedDB ||window.mozIndexedDB ||window.msIndexedDB $B.IDBTransaction=window.IDBTransaction ||window.webkitIDBTransaction $B.IDBKeyRange=window.IDBKeyRange ||window.webkitIDBKeyRange $B.has_indexedDB=typeof($B._indexedDB)!=="undefined" if($B.has_indexedDB){$B.indexedDB=function(){return $B.JSObject($B._indexedDB)}} $B.re=function(pattern,flags){return $B.JSObject(new RegExp(pattern,flags))} $B.has_json=typeof(JSON)!=="undefined" $B.has_websocket=window.WebSocket!==undefined })(__BRYTHON__) __BRYTHON__.implementation=[3,1,3,'final',0] __BRYTHON__.__MAGIC__="3.1.3" __BRYTHON__.version_info=[3,3,0,'alpha',0] __BRYTHON__.compiled_date="2015-05-14 09:53:42.559000" __BRYTHON__.builtin_module_names=["posix","sys","errno","time","_ajax","_browser","_html","_jsre","_multiprocessing","_posixsubprocess","_svg","_sys","builtins","dis","hashlib","javascript","json","long_int","math","modulefinder","_codecs","_collections","_csv","_dummy_thread","_functools","_imp","_io","_markupbase","_random","_socket","_sre","_string","_struct","_sysconfigdata","_testcapi","_thread","_warnings","_weakref"] __BRYTHON__.re_XID_Start=/[a-zA-Z_\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u01BA\u01BB\u01BC-\u01BF\u01C0-\u01C3\u01C4-\u0241\u0250-\u02AF\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EE\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03F5\u03F7-\u0481\u048A-\u04CE\u04D0-\u04F9\u0500-\u050F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0640\u0641-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u06FC\u06FF]/ __BRYTHON__.re_XID_Continue=/[a-zA-Z_\u0030-\u0039\u0041-\u005A\u005F\u0061-\u007A\u00AA\u00B5\u00B7\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u01BA\u01BB\u01BC-\u01BF\u01C0-\u01C3\u01C4-\u0241\u0250-\u02AF\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EE\u0300-\u036F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03F5\u03F7-\u0481\u0483-\u0486\u048A-\u04CE\u04D0-\u04F9\u0500-\u050F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05B9\u05BB-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u0615\u0621-\u063A\u0640\u0641-\u064A\u064B-\u065E\u0660-\u0669\u066E-\u066F\u0670\u0671-\u06D3\u06D5\u06D6-\u06DC\u06DF-\u06E4\u06E5-\u06E6\u06E7-\u06E8\u06EA-\u06ED\u06EE-\u06EF\u06F0-\u06F9\u06FA-\u06FC\u06FF]/ ;(function($B){var js,$pos,res,$op var keys=$B.keys=function(obj){var res=[],pos=0 for(var attr in obj){res[pos++]=attr} res.sort() return res } var clone=$B.clone=function(obj){var res={} for(var attr in obj){res[attr]=obj[attr]} return res } $B.last=function(table){return table[table.length-1]} $B.list2obj=function(list,value){var res={},i=list.length if(value===undefined){value=true} while(i-->0){res[list[i]]=value} return res } var $operators={"//=":"ifloordiv",">>=":"irshift","<<=":"ilshift","**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv","%=":"imod","&=":"iand","|=":"ior","^=":"ixor","+":"add","-":"sub","*":"mul","/":"truediv","%":"mod","&":"and","|":"or","~":"invert","^":"xor","<":"lt",">":"gt","<=":"le",">=":"ge","==":"eq","!=":"ne","or":"or","and":"and","in":"in","is":"is","not_in":"not_in","is_not":"is_not" } var $augmented_assigns={"//=":"ifloordiv",">>=":"irshift","<<=":"ilshift","**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv","%=":"imod","&=":"iand","|=":"ior","^=":"ixor" } var noassign=$B.list2obj(['True','False','None','__debug__']) var $op_order=[['or'],['and'],['in','not_in'],['<','<=','>','>=','!=','==','is','is_not'],['|','^','&'],['>>','<<'],['+'],['-'],['*'],['/','//','%'],['unary_neg','unary_inv'],['**'] ] var $op_weight={} var $weight=1 for(var $i=0;$i<$op_order.length;$i++){var _tmp=$op_order[$i] for(var $j=0;$j<_tmp.length;$j++){$op_weight[_tmp[$j]]=$weight } $weight++ } var $loop_num=0 $B.func_magic=Math.random().toString(36).substr(2,8) function $_SyntaxError(C,msg,indent){ var ctx_node=C while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var module=tree_node.module var line_num=tree_node.line_num $B.line_info=line_num+','+module if(indent===undefined){if(Array.isArray(msg)){$B.$SyntaxError(module,msg[0],$pos)} if(msg==="Triple string end not found"){ $B.$SyntaxError(module,'invalid syntax : triple string end not found',$pos) } $B.$SyntaxError(module,'invalid syntax',$pos) }else{throw $B.$IndentationError(module,msg,$pos)}} function $Node(type){this.type=type this.children=[] this.yield_atoms=[] this.add=function(child){ this.children[this.children.length]=child child.parent=this child.module=this.module } this.insert=function(pos,child){ this.children.splice(pos,0,child) child.parent=this child.module=this.module } this.toString=function(){return "<object 'Node'>"} this.show=function(indent){ var res='' if(this.type==='module'){for(var i=0;i<this.children.length;i++){res +=this.children[i].show(indent) } return res } indent=indent ||0 res +=' '.repeat(indent) res +=this.C if(this.children.length>0)res +='{' res +='\n' for(var i=0;i<this.children.length;i++){res +='['+i+'] '+this.children[i].show(indent+4) } if(this.children.length>0){res +=' '.repeat(indent) res+='}\n' } return res } this.to_js=function(indent){ if(this.js!==undefined)return this.js this.res=[] var pos=0 this.unbound=[] if(this.type==='module'){for(var i=0;i<this.children.length;i++){this.res[pos++]=this.children[i].to_js() this.children[i].js_index=pos } this.js=this.res.join('') return this.js } indent=indent ||0 var ctx_js=this.C.to_js() if(ctx_js){ this.res[pos++]=' '.repeat(indent) this.res[pos++]=ctx_js this.js_index=pos if(this.children.length>0)this.res[pos++]='{' this.res[pos++]='\n' for(var i=0;i<this.children.length;i++){this.res[pos++]=this.children[i].to_js(indent+4) this.children[i].js_index=pos } if(this.children.length>0){this.res[pos++]=' '.repeat(indent) this.res[pos++]='}\n' }} this.js=this.res.join('') return this.js } this.transform=function(rank){ if(this.yield_atoms.length>0){ this.parent.children.splice(rank,1) var offset=0 for(var i=0;i<this.yield_atoms.length;i++){ var temp_node=new $Node() var js='$yield_value'+$loop_num js +='='+(this.yield_atoms[i].to_js()||'None') new $NodeJSCtx(temp_node,js) this.parent.insert(rank+offset,temp_node) var yield_node=new $Node() this.parent.insert(rank+offset+1,yield_node) var yield_expr=new $YieldCtx(new $NodeCtx(yield_node)) new $StringCtx(yield_expr,'$yield_value'+$loop_num) var set_yield=new $Node() set_yield.is_set_yield_value=true js=$loop_num new $NodeJSCtx(set_yield,js) this.parent.insert(rank+offset+2,set_yield) this.yield_atoms[i].to_js=(function(x){return function(){return '$yield_value'+x}})($loop_num) $loop_num++ offset +=3 } this.parent.insert(rank+offset,this) this.yield_atoms=[] return offset+1 } if(this.type==='module'){ this.doc_string=$get_docstring(this) var i=0 while(i<this.children.length){var offset=this.children[i].transform(i) if(offset===undefined){offset=1} i +=offset }}else{var elt=this.C.tree[0],ctx_offset if(elt.transform !==undefined){ctx_offset=elt.transform(this,rank) } var i=0 while(i<this.children.length){var offset=this.children[i].transform(i) if(offset===undefined){offset=1} i +=offset } if(ctx_offset===undefined){ctx_offset=1} return ctx_offset }} this.clone=function(){var res=new $Node(this.type) for(var attr in this){res[attr]=this[attr]} return res }} function $AbstractExprCtx(C,with_commas){this.type='abstract_expr' this.with_commas=with_commas this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(abstract_expr '+with_commas+') '+this.tree} this.to_js=function(){this.js_processed=true if(this.type==='list')return '['+$to_js(this.tree)+']' return $to_js(this.tree) }} function $AssertCtx(C){ this.type='assert' this.toString=function(){return '(assert) '+this.tree} this.parent=C this.tree=[] C.tree[C.tree.length]=this this.transform=function(node,rank){if(this.tree[0].type==='list_or_tuple'){ var condition=this.tree[0].tree[0] var message=this.tree[0].tree[1] }else{var condition=this.tree[0] var message=null } var new_ctx=new $ConditionCtx(node.C,'if') var not_ctx=new $NotCtx(new_ctx) not_ctx.tree=[condition] node.C=new_ctx var new_node=new $Node() var js='throw AssertionError("AssertionError")' if(message !==null){js='throw AssertionError(str('+message.to_js()+'))' } new $NodeJSCtx(new_node,js) node.add(new_node) }} function $AssignCtx(C,check_unbound){ check_unbound=check_unbound===undefined this.type='assign' C.parent.tree.pop() C.parent.tree[C.parent.tree.length]=this this.parent=C.parent this.tree=[C] var scope=$get_scope(this) if(C.type=='expr' && C.tree[0].type=='call'){$_SyntaxError(C,["can't assign to function call "]) }else if(C.type=='list_or_tuple' || (C.type=='expr' && C.tree[0].type=='list_or_tuple')){if(C.type=='expr'){C=C.tree[0]} for(var i=0;i<C.tree.length;i++){var assigned=C.tree[i].tree[0] if(assigned.type=='id' && check_unbound){$B.bound[scope.id][assigned.value]=true var scope=$get_scope(this) if(scope.ntype=='def' ||scope.ntype=='generator'){$check_unbound(assigned,scope,assigned.value) }}else if(assigned.type=='call'){$_SyntaxError(C,["can't assign to function call"]) }}}else if(C.type=='assign'){for(var i=0;i<C.tree.length;i++){var assigned=C.tree[i].tree[0] if(assigned.type=='id'){if(scope.ntype=='def' ||scope.ntype=='generator'){$check_unbound(assigned,scope,assigned.value) } $B.bound[scope.id][assigned.value]=true }}}else{var assigned=C.tree[0] if(assigned && assigned.type=='id'){if(noassign[assigned.value]===true){$_SyntaxError(C,["can't assign to keyword"]) } if(!$B.globals[scope.id]|| $B.globals[scope.id][assigned.value]===undefined){ var node=$get_node(this) node.bound_before=$B.keys($B.bound[scope.id]) $B.bound[scope.id][assigned.value]=true assigned.bound=true } if(scope.ntype=='def' ||scope.ntype=='generator'){$check_unbound(assigned,scope,assigned.value) }}} this.toString=function(){return '(assign) '+this.tree[0]+'='+this.tree[1]} this.transform=function(node,rank){ var scope=$get_scope(this) var left=this.tree[0] while(left.type==='assign'){ var new_node=new $Node() var node_ctx=new $NodeCtx(new_node) node_ctx.tree=[left] node.parent.insert(rank+1,new_node) this.tree[0]=left.tree[1] left=this.tree[0] } var left_items=null switch(left.type){case 'expr': if(left.tree.length>1){left_items=left.tree }else if(left.tree[0].type==='list_or_tuple'||left.tree[0].type==='target_list'){left_items=left.tree[0].tree }else if(left.tree[0].type=='id'){ var name=left.tree[0].value if($B.globals && $B.globals[scope.id] && $B.globals[scope.id][name]){void(0) }else{left.tree[0].bound=true }} break case 'target_list': case 'list_or_tuple': left_items=left.tree } if(left_items===null){return} var right=this.tree[1] var right_items=null if(right.type==='list'||right.type==='tuple'|| (right.type==='expr' && right.tree.length>1)){right_items=right.tree } if(right_items!==null){ if(right_items.length>left_items.length){throw Error('ValueError : too many values to unpack (expected '+left_items.length+')') }else if(right_items.length<left_items.length){throw Error('ValueError : need more than '+right_items.length+' to unpack') } var new_nodes=[],pos=0 var new_node=new $Node() new $NodeJSCtx(new_node,'void(0)') new_nodes[pos++]=new_node var $var='$temp'+$loop_num var new_node=new $Node() new $NodeJSCtx(new_node,'var '+$var+'=[], $pos=0') new_nodes[pos++]=new_node for(var i=0;i<right_items.length;i++){var js=$var+'[$pos++]='+right_items[i].to_js() var new_node=new $Node() new $NodeJSCtx(new_node,js) new_nodes[pos++]=new_node } for(var i=0;i<left_items.length;i++){var new_node=new $Node() new_node.id=$get_node(this).module var C=new $NodeCtx(new_node) left_items[i].parent=C var assign=new $AssignCtx(left_items[i],false) assign.tree[1]=new $JSCode($var+'['+i+']') new_nodes[pos++]=new_node } node.parent.children.splice(rank,1) for(var i=new_nodes.length-1;i>=0;i--){node.parent.insert(rank,new_nodes[i]) } $loop_num++ }else{ var new_node=new $Node() new_node.line_num=node.line_num var js='var $right'+$loop_num+'=getattr' js +='(iter('+right.to_js()+'),"__next__");' new $NodeJSCtx(new_node,js) var new_nodes=[new_node],pos=1 var rlist_node=new $Node() var $var='$rlist'+$loop_num js='var '+$var+'=[], $pos=0;' js +='while(1){try{'+$var+'[$pos++]=$right' js +=$loop_num+'()}catch(err){$B.$pop_exc();break}};' new $NodeJSCtx(rlist_node,js) new_nodes[pos++]=rlist_node var packed=null for(var i=0;i<left_items.length;i++){var expr=left_items[i] if(expr.type=='expr' && expr.tree[0].type=='packed'){packed=i break }} var check_node=new $Node() var min_length=left_items.length if(packed!==null){min_length--} js='if($rlist'+$loop_num+'.length<'+min_length+')' js +='{throw ValueError("need more than "+$rlist'+$loop_num js +='.length+" value" + ($rlist'+$loop_num+'.length>1 ?' js +=' "s" : "")+" to unpack")}' new $NodeJSCtx(check_node,js) new_nodes[pos++]=check_node if(packed==null){var check_node=new $Node() var min_length=left_items.length js='if($rlist'+$loop_num+'.length>'+min_length+')' js +='{throw ValueError("too many values to unpack ' js +='(expected '+left_items.length+')")}' new $NodeJSCtx(check_node,js) new_nodes[pos++]=check_node } var j=0 for(var i=0;i<left_items.length;i++){var new_node=new $Node() new_node.id=scope.id var C=new $NodeCtx(new_node) left_items[i].parent=C var assign=new $AssignCtx(left_items[i],false) var js='$rlist'+$loop_num if(packed==null ||i<packed){js +='['+i+']' }else if(i==packed){js +='.slice('+i+',$rlist'+$loop_num+'.length-' js +=(left_items.length-i-1)+')' }else{js +='[$rlist'+$loop_num+'.length-'+(left_items.length-i)+']' } assign.tree[1]=new $JSCode(js) new_nodes[pos++]=new_node } node.parent.children.splice(rank,1) for(var i=new_nodes.length-1;i>=0;i--){node.parent.insert(rank,new_nodes[i]) } $loop_num++ }} this.to_js=function(){this.js_processed=true if(this.parent.type==='call'){ return '{$nat:"kw",name:'+this.tree[0].to_js()+',value:'+this.tree[1].to_js()+'}' } var left=this.tree[0] if(left.type==='expr')left=left.tree[0] var right=this.tree[1] if(left.type=='attribute' ||left.type=='sub'){ var node=$get_node(this) var res='',rvar='',$var='$temp'+$loop_num if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='call' && ('eval'==right.tree[0].func.value || 'exec'==right.tree[0].func.value)){res +='var '+$var+'='+right.to_js()+';\n' rvar=$var $loop_num++ }else if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='sub'){res +='var '+$var+'='+right.to_js()+';\n' rvar=$var }else{rvar=right.to_js() } if(left.type==='attribute'){ left.func='setattr' res +=left.to_js() left.func='getattr' res=res.substr(0,res.length-1) return res + ','+rvar+');None;' } if(left.type==='sub'){ if(Array.isArray){ function is_simple(elt){return(elt.type=='expr' && ['int','id'].indexOf(elt.tree[0].type)>-1) } var exprs=[] if(left.tree.length==1){var left_seq=left,args=[],pos=0,ix=0 while(left_seq.value.type=='sub' && left_seq.tree.length==1){if(is_simple(left_seq.tree[0])){args[pos++]='['+left_seq.tree[0].to_js()+']' }else{var $var='$temp_ix'+$loop_num exprs.push('var '+$var+'_'+ix+'='+left_seq.tree[0].to_js()) args[pos++]='['+$var+'_'+ix+']' left_seq.tree[0]={type:'id',to_js:(function(rank){return function(){return $var+'_'+rank}})(ix) } ix++ } left_seq=left_seq.value } if(is_simple(left_seq.tree[0])){args.unshift('['+left_seq.tree[0].to_js()+']') }else{exprs.push('var $temp_ix'+$loop_num+'_'+ix+'='+left_seq.tree[0].to_js()) args.unshift('[$temp_ix'+$loop_num+'_'+ix+']') ix++ } if(left_seq.value.type!=='id'){var val='$temp_ix'+$loop_num+'_'+ix exprs.push('var '+val+'='+left_seq.value.to_js()) }else{var val=left_seq.value.to_js() } res +=exprs.join(';\n')+';\n' res +='Array.isArray('+val+') && ' res +=val+args.join('')+'!==undefined ? ' res +=val+args.join('')+'='+rvar res +=' : ' res +='$B.$setitem('+left.value.to_js() res +=','+left.tree[0].to_js()+','+rvar+');None;' return res }} left.func='setitem' res +=left.to_js() res=res.substr(0,res.length-1) left.func='getitem' return res + ','+rvar+');None;' }} return left.to_js()+'='+right.to_js() }} function $AttrCtx(C){ this.type='attribute' this.value=C.tree[0] this.parent=C C.tree.pop() C.tree[C.tree.length]=this this.tree=[] this.func='getattr' this.toString=function(){return '(attr) '+this.value+'.'+this.name} this.to_js=function(){this.js_processed=true return this.func+'('+this.value.to_js()+',"'+this.name+'")' }} function $AugmentedAssignCtx(C,op){ this.type='augm_assign' this.parent=C.parent C.parent.tree.pop() C.parent.tree[C.parent.tree.length]=this this.op=op this.tree=[C] if(C.type=='expr' && C.tree[0].type=='id' && noassign[C.tree[0].value]===true){$_SyntaxError(C,["can't assign to keyword"]) } var scope=$get_scope(this) $get_node(this).bound_before=$B.keys($B.bound[scope.id]) this.module=scope.module this.toString=function(){return '(augm assign) '+this.tree} this.transform=function(node,rank){var func='__'+$operators[op]+'__' var offset=0,parent=node.parent var line_num=node.line_num,lnum_set=false parent.children.splice(rank,1) var left_is_id=(this.tree[0].type=='expr' && this.tree[0].tree[0].type=='id') var right_is_int=(this.tree[1].type=='expr' && this.tree[1].tree[0].type=='int') var right=right_is_int ? this.tree[1].tree[0].value : '$temp' if(!right_is_int){ var new_node=new $Node() new_node.line_num=line_num lnum_set=true new $NodeJSCtx(new_node,'var $temp,$left;') parent.insert(rank,new_node) offset++ var new_node=new $Node() new_node.id=this.module var new_ctx=new $NodeCtx(new_node) var new_expr=new $ExprCtx(new_ctx,'js',false) var _id=new $RawJSCtx(new_expr,'$temp') var assign=new $AssignCtx(new_expr) assign.tree[1]=this.tree[1] _id.parent=assign parent.insert(rank+offset,new_node) offset++ } var prefix='',in_class=false switch(op){case '+=': case '-=': case '*=': case '/=': if(left_is_id){var scope=$get_scope(C),local_ns='$local_'+scope.id.replace(/\./g,'_'),global_ns='$local_'+scope.module.replace(/\./g,'_'),prefix switch(scope.ntype){case 'module': prefix=global_ns break case 'def': case 'generator': if(scope.globals && scope.globals.indexOf(C.tree[0].value)>-1){prefix=global_ns }else{prefix='$locals'} break case 'class': var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} new $NodeJSCtx(new_node,'var $left='+C.to_js()) parent.insert(rank+offset,new_node) in_class=true offset++ }}} var left=C.tree[0].to_js() prefix=prefix && !C.tree[0].unknown_binding if(prefix){var left1=in_class ? '$left' : left var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} js=right_is_int ? 'if(' : 'if(typeof $temp.valueOf()=="number" && ' js +='typeof '+left1+'.valueOf()=="number"){' js +=right_is_int ? '(' : '(typeof $temp=="number" && ' js +='typeof '+left1+'=="number") ? ' js +=left+op+right js +=' : (typeof '+left1+'=="number" ? '+left+op js +=right_is_int ? right : right+'.valueOf()' js +=' : '+left + '.value ' +op js +=right_is_int ? right : right+'.valueOf()' js +=');' js +='}' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset++ } var aaops={'+=':'add','-=':'sub','*=':'mul'} if(C.tree[0].type=='sub' && ('+='==op ||'-='==op ||'*='==op)&& C.tree[0].tree.length==1){var js1='$B.augm_item_'+aaops[op]+'(' js1 +=C.tree[0].value.to_js() js1 +=','+C.tree[0].tree[0].to_js()+',' js1 +=right+');None;' var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} new $NodeJSCtx(new_node,js1) parent.insert(rank+offset,new_node) offset++ return } var new_node=new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} var js='' if(prefix){js +='else '} js +='if(!hasattr('+C.to_js()+',"'+func+'"))' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset ++ var aa1=new $Node() aa1.id=this.module var ctx1=new $NodeCtx(aa1) var expr1=new $ExprCtx(ctx1,'clone',false) expr1.tree=C.tree for(var i=0;i<expr1.tree.length;i++){expr1.tree[i].parent=expr1 } var assign1=new $AssignCtx(expr1) var new_op=new $OpCtx(expr1,op.substr(0,op.length-1)) new_op.parent=assign1 new $RawJSCtx(new_op,right) assign1.tree.push(new_op) expr1.parent.tree.pop() expr1.parent.tree.push(assign1) new_node.add(aa1) var aa2=new $Node() new $NodeJSCtx(aa2,'else') parent.insert(rank+offset,aa2) var aa3=new $Node() var js3=C.to_js() if(prefix){if(scope.ntype=='class'){js3='$left'} else{js3 +='='+prefix+'["'+C.tree[0].value+'"]'}} js3 +='=getattr('+C.to_js() js3 +=',"'+func+'")('+right+')' new $NodeJSCtx(aa3,js3) aa2.add(aa3) return offset } this.to_js=function(){return '' if(this.tree[0].type=='expr' && this.tree[0].length==1 && this.tree[0].tree[0].type=='id'){return this.tree[0].to_js()+op+this.tree[1].to_js()+';' }else{return this.tree[0].to_js()+op+this.tree[1].to_js()+';' }}} function $BodyCtx(C){ var ctx_node=C.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var body_node=new $Node() tree_node.insert(0,body_node) return new $NodeCtx(body_node) } function $BreakCtx(C){ this.type='break' this.toString=function(){return 'break '} this.parent=C C.tree[C.tree.length]=this var ctx_node=C while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var loop_node=tree_node.parent var break_flag=false while(1){if(loop_node.type==='module'){ $_SyntaxError(C,'break outside of a loop') }else{var ctx=loop_node.C.tree[0] if(ctx.type==='condition' && ctx.token==='while'){this.loop_ctx=ctx ctx.has_break=true break } switch(ctx.type){case 'for': this.loop_ctx=ctx ctx.has_break=true break_flag=true break case 'def': case 'generator': case 'class': $_SyntaxError(C,'break outside of a loop') default: loop_node=loop_node.parent } if(break_flag)break } } this.to_js=function(){this.js_processed=true var scope=$get_scope(this) var res=';$locals_'+scope.id.replace(/\./g,'_') return res + '["$no_break'+this.loop_ctx.loop_num+'"]=false;break;' }} function $CallArgCtx(C){ this.type='call_arg' this.toString=function(){return 'call_arg '+this.tree} this.parent=C this.start=$pos this.tree=[] C.tree[C.tree.length]=this this.expect='id' this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $CallCtx(C){ this.type='call' this.func=C.tree[0] if(this.func!==undefined){ this.func.parent=this } this.parent=C if(C.type!='class'){C.tree.pop() C.tree[C.tree.length]=this }else{ C.args=this } this.expect='id' this.tree=[] this.start=$pos this.toString=function(){return '(call) '+this.func+'('+this.tree+')'} this.to_js=function(){this.js_processed=true if(this.tree.length>0){if(this.tree[this.tree.length-1].tree.length==0){ this.tree.pop() }} var func_js=this.func.to_js() var ctx=this.func.found if(ctx && ctx.type=='def'){var flag=(ctx.default_list.length==0 && !ctx.other_args && !ctx.other_kw && ctx.after_star.length==0) if(flag){var args=[] if(this.tree.length==ctx.positional_list.length){for(var i=0;i<this.tree.length;i++){if(this.tree[i].type!='call_arg' || this.tree[i].tree[0].type !=='expr'){flag=false break }else{args.push(ctx.positional_list[i]+':'+ this.tree[i].to_js()) }}} if(flag){args='{$nat:"args"},{'+args.join(',')+'}' }}} if(this.func!==undefined){switch(this.func.value){case 'classmethod': return 'classmethod('+$to_js(this.tree)+')' case '$$super': if(this.tree.length==0){ var scope=$get_scope(this) if(scope.ntype=='def' ||scope.ntype=='generator'){var def_scope=$get_scope(scope.C.tree[0]) if(def_scope.ntype=='class'){new $IdCtx(this,def_scope.C.tree[0].name) }}} if(this.tree.length==1){ var scope=$get_scope(this) if(scope.ntype=='def' ||scope.ntype=='generator'){var args=scope.C.tree[0].args if(args.length>0){new $IdCtx(this,args[0]) }}} break default: if(this.func.type=='unary'){ switch(this.func.op){case '+': return $to_js(this.tree) case '-': return 'getattr('+$to_js(this.tree)+',"__neg__")()' case '~': return 'getattr('+$to_js(this.tree)+',"__invert__")()' } } } var _block=false if($B.async_enabled){var scope=$get_scope(this.func) if($B.block[scope.id]===undefined){ } else if($B.block[scope.id][this.func.value])_block=true } var pos_args=[],kw_args=[],star_args=null,dstar_args=null for(var i=0;i<this.tree.length;i++){var arg=this.tree[i],type switch(arg.type){case 'star_arg': star_args=arg.tree[0].tree[0].to_js() break case 'double_star_arg': dstar_args=arg.tree[0].tree[0].to_js() break case 'id': pos_args.push(arg.to_js()) break default: if(arg.tree[0]===undefined){console.log('bizarre',arg)} else{type=arg.tree[0].type} switch(type){case 'expr': pos_args.push(arg.to_js()) break case 'kwarg': kw_args.push(arg.tree[0].tree[0].value+':'+arg.tree[0].tree[1].to_js()) break case 'list_or_tuple': case 'op': pos_args.push(arg.to_js()) break case 'star_arg': star_args=arg.tree[0].tree[0].to_js() break case 'double_star_arg': dstar_args=arg.tree[0].tree[0].to_js() break default: pos_args.push(arg.to_js()) break } break }} var args_str=pos_args.join(', ') if(star_args){args_str='$B.extend_list('+args_str if(pos_args.length>0){args_str +=','} args_str +='_b_.list('+star_args+'))' } kw_args_str='{'+kw_args.join(', ')+'}' if(dstar_args){kw_args_str='{$nat:"kw",kw:$B.extend("'+this.func.value+'",'+kw_args_str kw_args_str +=','+dstar_args+')}' }else if(kw_args_str!=='{}'){kw_args_str='{$nat:"kw",kw:'+kw_args_str+'}' }else{kw_args_str='' } if(star_args && kw_args_str){args_str +='.concat(['+kw_args_str+'])' }else{if(args_str && kw_args_str){args_str +=','+kw_args_str} else if(!args_str){args_str=kw_args_str}} if(star_args){ args_str='.apply(null,'+args_str+')' }else{args_str='('+args_str+')' } if($B.debug>0){ var res="" if(_block){ res="@@;$B.execution_object.$append($jscode, 10); " res+="$B.execution_object.$execute_next_segment(); " res+="$jscode=@@" } res +='getattr('+func_js+',"__call__")' return res+args_str } if(this.tree.length>-1){if(this.func.type=='id'){if(this.func.is_builtin){ if($B.builtin_funcs[this.func.value]!==undefined){return func_js+args_str }}else{var bound_obj=this.func.found if(bound_obj &&(bound_obj.type=='class' || bound_obj.type=='def')){return func_js+args_str }} var res='('+func_js+'.$is_func ? ' res +=func_js+' : ' res +='getattr('+func_js+',"__call__"))'+args_str }else{var res='getattr('+func_js+',"__call__")'+args_str } return res } return 'getattr('+func_js+',"__call__")()' }}} function $ClassCtx(C){ this.type='class' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.expect='id' this.toString=function(){return '(class) '+this.name+' '+this.tree+' args '+this.args} var scope=this.scope=$get_scope(this) this.parent.node.parent_block=scope this.parent.node.bound={} this.set_name=function(name){this.random=$B.UUID() this.name=name this.id=C.node.module+'_'+name+'_'+this.random $B.bound[this.id]={} if($B.async_enabled)$B.block[this.id]={} $B.modules[this.id]=this.parent.node this.parent.node.id=this.id var parent_block=scope while(parent_block.C && parent_block.C.tree[0].type=='class'){parent_block=parent_block.parent } while(parent_block.C && 'def' !=parent_block.C.tree[0].type && 'generator' !=parent_block.C.tree[0].type){parent_block=parent_block.parent } this.parent.node.parent_block=parent_block $B.bound[this.scope.id][name]=this if(scope.is_function){if(scope.C.tree[0].locals.indexOf(name)==-1){scope.C.tree[0].locals.push(name) }}} this.transform=function(node,rank){ this.doc_string=$get_docstring(node) var instance_decl=new $Node() var local_ns='$locals_'+this.id.replace(/\./g,'_') var js=';var '+local_ns+'=' if($B.debug>0){js +='{$def_line:$B.line_info}'} else{js +='{}'} js +=', $locals = '+local_ns+';' new $NodeJSCtx(instance_decl,js) node.insert(0,instance_decl) var ret_obj=new $Node() new $NodeJSCtx(ret_obj,'return '+local_ns+';') node.insert(node.children.length,ret_obj) var run_func=new $Node() new $NodeJSCtx(run_func,')();') node.parent.insert(rank+1,run_func) var scope=$get_scope(this) var name_ref=';$locals_'+scope.id.replace(/\./g,'_') name_ref +='["'+this.name+'"]' if(this.name=="FF"){ var js=[name_ref +'=$B.$class_constructor1("'+this.name],pos=1 }else{var js=[name_ref +'=$B.$class_constructor("'+this.name],pos=1 } js[pos++]='",$'+this.name+'_'+this.random if(this.args!==undefined){ var arg_tree=this.args.tree,args=[],kw=[] for(var i=0;i<arg_tree.length;i++){var _tmp=arg_tree[i] if(_tmp.tree[0].type=='kwarg'){kw.push(_tmp.tree[0])} else{args.push(_tmp.to_js())}} js[pos++]=',tuple(['+args.join(',')+']),[' var _re=new RegExp('"','g') var _r=[],rpos=0 for(var i=0;i<args.length;i++){_r[rpos++]='"'+args[i].replace(_re,'\\"')+'"' } js[pos++]=_r.join(',')+ ']' _r=[],rpos=0 for(var i=0;i<kw.length;i++){var _tmp=kw[i] _r[rpos++]='["'+_tmp.tree[0].value+'",'+_tmp.tree[1].to_js()+']' } js[pos++]=',[' + _r.join(',')+ ']' }else{ js[pos++]=',tuple([]),[],[]' } js[pos++]=')' var cl_cons=new $Node() new $NodeJSCtx(cl_cons,js.join('')) rank++ node.parent.insert(rank+1,cl_cons) rank++ var ds_node=new $Node() js=name_ref+'.$dict.__doc__=' js +=(this.doc_string ||'None')+';' new $NodeJSCtx(ds_node,js) node.parent.insert(rank+1,ds_node) rank++ js=name_ref+'.$dict.__module__="'+$get_module(this).module+'"' var mod_node=new $Node() new $NodeJSCtx(mod_node,js) node.parent.insert(rank+1,mod_node) if(scope.ntype==='module'){var w_decl=new $Node() new $NodeJSCtx(w_decl,'$locals["'+ this.name+'"]='+this.name) } var end_node=new $Node() new $NodeJSCtx(end_node,'None;') node.parent.insert(rank+2,end_node) this.transformed=true } this.to_js=function(){this.js_processed=true return 'var $'+this.name+'_'+this.random+'=(function()' }} function $CompIfCtx(C){ this.type='comp_if' C.parent.intervals.push($pos) this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(comp if) '+this.tree} this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $ComprehensionCtx(C){ this.type='comprehension' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(comprehension) '+this.tree} this.to_js=function(){this.js_processed=true var _i=[],pos=0 for(var j=0;j<this.tree.length;j++)_i[pos++]=this.tree[j].start return _i }} function $CompForCtx(C){ this.type='comp_for' C.parent.intervals.push($pos) this.parent=C this.tree=[] this.expect='in' C.tree[C.tree.length]=this this.toString=function(){return '(comp for) '+this.tree} this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $CompIterableCtx(C){ this.type='comp_iterable' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(comp iter) '+this.tree} this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $ConditionCtx(C,token){ this.type='condition' this.token=token this.parent=C this.tree=[] if(token==='while'){this.loop_num=$loop_num++} C.tree[C.tree.length]=this this.toString=function(){return this.token+' '+this.tree} this.transform=function(node,rank){var scope=$get_scope(this) if(this.token=="while"){if(scope.ntype=='generator'){this.parent.node.loop_start=this.loop_num } var new_node=new $Node() var js='$locals["$no_break'+this.loop_num+'"]=true' new $NodeJSCtx(new_node,js) node.parent.insert(rank,new_node) return 2 }} this.to_js=function(){this.js_processed=true var tok=this.token if(tok==='elif'){tok='else if'} var res=[tok+'(bool('],pos=1 if(tok=='while'){res[pos++]='$locals["$no_break'+this.loop_num+'"] && ' } if(this.tree.length==1){res[pos++]=$to_js(this.tree)+'))' }else{ res[pos++]=this.tree[0].to_js()+'))' if(this.tree[1].tree.length>0){res[pos++]='{'+this.tree[1].to_js()+'}' }} return res.join('') }} function $ContinueCtx(C){ this.type='continue' this.parent=C C.tree[C.tree.length]=this this.toString=function(){return '(continue)'} this.to_js=function(){this.js_processed=true return 'continue' }} function $DecoratorCtx(C){ this.type='decorator' this.parent=C C.tree[C.tree.length]=this this.tree=[] this.toString=function(){return '(decorator) '+this.tree} this.transform=function(node,rank){var func_rank=rank+1,children=node.parent.children var decorators=[this.tree] while(1){if(func_rank>=children.length){$_SyntaxError(C)} else if(children[func_rank].C.type=='node_js'){func_rank++} else if(children[func_rank].C.tree[0].type==='decorator'){decorators.push(children[func_rank].C.tree[0].tree) children.splice(func_rank,1) }else{break}} this.dec_ids=[] var pos=0 for(var i=0;i<decorators.length;i++){this.dec_ids[pos++]='$id'+ $B.UUID() } if($B.async_enabled){var _block_async_flag=false for(var i=0;i<decorators.length;i++){try{ var name=decorators[i][0].tree[0].value if(name=="brython_block" ||name=="brython_async")_block_async_flag=true }catch(err){console.log(i);console.log(decorators[i][0])}}} var obj=children[func_rank].C.tree[0] var callable=children[func_rank].C var tail='' var scope=$get_scope(this) var ref='$locals["'+obj.name+'"]' var res=ref+'=' for(var i=0;i<decorators.length;i++){ res +=this.dec_ids[i]+'(' tail +=')' } res +=ref+tail+';' $B.bound[scope.id][obj.name]=true var decor_node=new $Node() new $NodeJSCtx(decor_node,res) node.parent.insert(func_rank+1,decor_node) this.decorators=decorators if($B.async_enabled && _block_async_flag){ if($B.block[scope.id]===undefined)$B.block[scope.id]={} $B.block[scope.id][obj.name]=true }} this.to_js=function(){if($B.async_enabled){if(this.processing !==undefined)return "" } this.js_processed=true var res=[],pos=0 for(var i=0;i<this.decorators.length;i++){res[pos++]='var '+this.dec_ids[i]+'='+$to_js(this.decorators[i])+';' } return res.join('') }} function $DefCtx(C){this.type='def' this.name=null this.parent=C this.tree=[] this.locals=[] this.yields=[] C.tree[C.tree.length]=this this.enclosing=[] var scope=this.scope=$get_scope(this) var parent_block=scope while(parent_block.C && parent_block.C.tree[0].type=='class'){parent_block=parent_block.parent } while(parent_block.C && 'def' !=parent_block.C.tree[0].type && 'generator' !=parent_block.C.tree[0].type){parent_block=parent_block.parent } this.parent.node.parent_block=parent_block var pb=parent_block while(pb && pb.C){if(pb.C.tree[0].type=='def'){this.inside_function=true break } pb=pb.parent_block } this.module=scope.module this.positional_list=[] this.default_list=[] this.other_args=null this.other_kw=null this.after_star=[] this.set_name=function(name){var id_ctx=new $IdCtx(this,name) this.name=name this.id=this.scope.id+'_'+name this.id=this.id.replace(/\./g,'_') this.id +='_'+ $B.UUID() this.parent.node.id=this.id this.parent.node.module=this.module $B.modules[this.id]=this.parent.node $B.bound[this.id]={} $B.bound[this.scope.id][name]=this id_ctx.bound=true if(scope.is_function){if(scope.C.tree[0].locals.indexOf(name)==-1){scope.C.tree[0].locals.push(name) }}} this.toString=function(){return 'def '+this.name+'('+this.tree+')'} this.transform=function(node,rank){ if(this.transformed!==undefined)return var scope=this.scope var pb=this.parent.node var flag=this.name.substr(0,4)=='func' while(pb && pb.C){if(pb.C.tree[0].type=='def'){this.inside_function=true break } pb=pb.parent } this.doc_string=$get_docstring(node) this.rank=rank var fglobs=this.parent.node.globals var indent=node.indent+16 var header=$ws(indent) if(this.name.substr(0,15)=='lambda_'+$B.lambda_magic){var pblock=$B.modules[scope.id].parent_block if(pblock.C && pblock.C.tree[0].type=="def"){this.enclosing.push(pblock) }} var pnode=this.parent.node while(pnode.parent && pnode.parent.is_def_func){this.enclosing.push(pnode.parent.parent) pnode=pnode.parent.parent } var defaults=[],apos=0,dpos=0,defs1=[],dpos1=0 this.argcount=0 this.kwonlyargcount=0 this.varnames={} this.args=[] this.__defaults__=[] this.slots=[] var slot_list=[] var func_args=this.tree[1].tree for(var i=0;i<func_args.length;i++){var arg=func_args[i] this.args[apos++]=arg.name this.varnames[arg.name]=true if(arg.type==='func_arg_id'){if(this.star_arg){this.kwonlyargcount++} else{this.argcount++} this.slots.push(arg.name+':null') slot_list.push('"'+arg.name+'"') if(arg.tree.length>0){defaults[dpos++]='"'+arg.name+'"' defs1[dpos1++]=arg.name+':'+$to_js(arg.tree) this.__defaults__.push($to_js(arg.tree)) }}else if(arg.type=='func_star_arg'){if(arg.op=='*'){this.star_arg=arg.name} else if(arg.op=='**'){this.kw_arg=arg.name}}} var flags=67 if(this.star_arg){flags |=4} if(this.kw_arg){flags |=8} if(this.type=='generator'){flags |=32} var positional_str=[],positional_obj=[],pos=0 for(var i=0,_len=this.positional_list.length;i<_len;i++){positional_str[pos]='"'+this.positional_list[i]+'"' positional_obj[pos++]=this.positional_list[i]+':null' } positional_str=positional_str.join(',') positional_obj='{'+positional_obj.join(',')+'}' var dobj=[],pos=0 for(var i=0;i<this.default_list.length;i++){dobj[pos++]=this.default_list[i]+':null' } dobj='{'+dobj.join(',')+'}' var nodes=[],js var global_scope=scope if(global_scope.parent_block===undefined){alert('undef ')} while(global_scope.parent_block.id !=='__builtins__'){global_scope=global_scope.parent_block } var global_ns='$locals_'+global_scope.id.replace(/\./g,'_') var local_ns='$locals_'+this.id js='var '+local_ns+'={}, ' js +='$local_name="'+this.id+'",$locals='+local_ns+';' var new_node=new $Node() new_node.locals_def=true new $NodeJSCtx(new_node,js) nodes.push(new_node) var new_node=new $Node() var js=';$B.enter_frame([$local_name, $locals,' js +='"'+global_scope.id+'", '+global_ns+']);' new_node.enter_frame=true new $NodeJSCtx(new_node,js) nodes.push(new_node) this.env=[] var make_args_nodes=[] var func_ref='$locals_'+scope.id.replace(/\./g,'_')+'["'+this.name+'"]' var js='var $ns = $B.$MakeArgs1("'+this.name+'", ' js +=this.argcount+', {'+this.slots.join(', ')+'}, ' js +='['+slot_list.join(', ')+'], ' js +='arguments, ' if(defs1.length){js +='$defaults, '} else{js +='{}, '} js +=this.other_args+', '+this.other_kw+');' var new_node=new $Node() new $NodeJSCtx(new_node,js) make_args_nodes.push(new_node) var new_node=new $Node() new $NodeJSCtx(new_node,'for(var $var in $ns){$locals[$var]=$ns[$var]};') make_args_nodes.push(new_node) var only_positional=false if(defaults.length==0 && this.other_args===null && this.other_kw===null && this.after_star.length==0){ only_positional=true var pos_nodes=[] if($B.debug>0 ||this.positional_list.length>0){ var new_node=new $Node() var js='if(arguments.length>0 && arguments[arguments.length-1].$nat)' new $NodeJSCtx(new_node,js) nodes.push(new_node) new_node.add(make_args_nodes[0]) new_node.add(make_args_nodes[1]) var else_node=new $Node() new $NodeJSCtx(else_node,'else') nodes.push(else_node) } if($B.debug>0){ var pos_len=this.positional_list.length js='if(arguments.length!='+pos_len+')' var wrong_nb_node=new $Node() new $NodeJSCtx(wrong_nb_node,js) else_node.add(wrong_nb_node) if(pos_len>0){ js='if(arguments.length<'+pos_len+')' js +='{var $missing='+pos_len+'-arguments.length;' js +='throw TypeError("'+this.name+'() missing "+$missing+' js +='" positional argument"+($missing>1 ? "s" : "")+": "' js +='+new Array('+positional_str+').slice(arguments.length))}' new_node=new $Node() new $NodeJSCtx(new_node,js) wrong_nb_node.add(new_node) js='else if' }else{js='if' } js +='(arguments.length>'+pos_len+')' js +='{throw TypeError("'+this.name+'() takes '+pos_len js +=' positional argument' js +=(pos_len>1 ? "s" : "") js +=' but more were given")}' new_node=new $Node() new $NodeJSCtx(new_node,js) wrong_nb_node.add(new_node) } for(var i=0;i<this.positional_list.length;i++){var arg=this.positional_list[i] var new_node=new $Node() var js='$locals["'+arg+'"]='+arg+';' new $NodeJSCtx(new_node,js) else_node.add(new_node) }}else{nodes.push(make_args_nodes[0]) nodes.push(make_args_nodes[1]) } for(var i=nodes.length-1;i>=0;i--){node.children.splice(0,0,nodes[i]) } var def_func_node=new $Node() if(only_positional){var params=Object.keys(this.varnames).concat(['$extra']).join(', ') new $NodeJSCtx(def_func_node,'return function('+params+')') }else{new $NodeJSCtx(def_func_node,'return function()') } def_func_node.is_def_func=true def_func_node.module=this.module for(var i=0;i<node.children.length;i++){def_func_node.add(node.children[i]) } var last_instr=node.children[node.children.length-1].C.tree[0] if(last_instr.type!=='return' && this.type!='generator'){new_node=new $Node() new $NodeJSCtx(new_node,';$B.leave_frame();return None;') def_func_node.add(new_node) } node.children=[] var default_node=new $Node() var js=';None;' if(defs1.length>0){js='var $defaults = {'+defs1.join(',')+'}'} new $NodeJSCtx(default_node,js) node.insert(0,default_node) node.add(def_func_node) var ret_node=new $Node() new $NodeJSCtx(ret_node,')();') node.parent.insert(rank+1,ret_node) var offset=2 if(this.type==='generator' && !this.declared){var sc=scope var env=[],pos=0 while(sc && sc.id!=='__builtins__'){var sc_id=sc.id.replace(/\./g,'_') if(sc===scope){env[pos++]='["'+sc_id+'",$locals]' }else{env[pos++]='["'+sc_id+'",$locals_'+sc_id+']' } sc=sc.parent_block } var env_string='['+env.join(', ')+']' js='$B.$BRgenerator('+env_string+',"'+this.name+'","'+this.id+'")' var gen_node=new $Node() gen_node.id=this.module var ctx=new $NodeCtx(gen_node) var expr=new $ExprCtx(ctx,'id',false) var name_ctx=new $IdCtx(expr,this.name) var assign=new $AssignCtx(expr) var expr1=new $ExprCtx(assign,'id',false) var js_ctx=new $NodeJSCtx(assign,js) expr1.tree.push(js_ctx) node.parent.insert(rank+offset,gen_node) this.declared=true offset++ } var prefix=this.tree[0].to_js() var indent=node.indent js=prefix+'.$infos = {' var name_decl=new $Node() new $NodeJSCtx(name_decl,js) node.parent.insert(rank+offset,name_decl) offset++ js=' __name__:"' if(this.scope.ntype=='class'){js+=this.scope.C.tree[0].name+'.'} js +=this.name+'",' var name_decl=new $Node() new $NodeJSCtx(name_decl,js) node.parent.insert(rank+offset,name_decl) offset++ var module=$get_module(this) new_node=new $Node() new $NodeJSCtx(new_node,' __defaults__ : ['+this.__defaults__.join(', ')+'],') node.parent.insert(rank+offset,new_node) offset++ var module=$get_module(this) new_node=new $Node() new $NodeJSCtx(new_node,' __module__ : "'+module.module+'",') node.parent.insert(rank+offset,new_node) offset++ js=' __doc__: '+(this.doc_string ||'None')+',' new_node=new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank+offset,new_node) offset++ for(var attr in $B.bound[this.id]){this.varnames[attr]=true} var co_varnames=[] for(var attr in this.varnames){co_varnames.push('"'+attr+'"')} var h='\n'+' '.repeat(indent+8) js=' __code__:{'+h+'__class__:$B.$CodeDict' h=','+h js +=h+'co_argcount:'+this.argcount js +=h+'co_filename:$locals_'+scope.module.replace(/\./g,'_')+'["__file__"]' js +=h+'co_firstlineno:'+node.line_num js +=h+'co_flags:'+flags js +=h+'co_kwonlyargcount:'+this.kwonlyargcount js +=h+'co_name: "'+this.name+'"' js +=h+'co_nlocals: '+co_varnames.length js +=h+'co_varnames: ['+co_varnames.join(', ')+']' js +='}\n};' js +='None;' new_node=new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank+offset,new_node) this.transformed=true return offset } this.to_js=function(func_name){this.js_processed=true func_name=func_name ||this.tree[0].to_js() return func_name+'=(function()' }} function $DelCtx(C){ this.type='del' this.parent=C C.tree[C.tree.length]=this this.tree=[] this.toString=function(){return 'del '+this.tree} this.to_js=function(){this.js_processed=true if(this.tree[0].type=='list_or_tuple'){ var res=[],pos=0 for(var i=0;i<this.tree[0].tree.length;i++){var subdel=new $DelCtx(C) subdel.tree=[this.tree[0].tree[i]] res[pos++]=subdel.to_js() C.tree.pop() } this.tree=[] return res.join(';') }else{var expr=this.tree[0].tree[0] var scope=$get_scope(this) switch(expr.type){case 'id': return 'delete '+expr.to_js()+';' case 'list_or_tuple': var res=[],pos=0 for(var i=0;i<expr.tree.length;i++){res[pos++]='delete '+expr.tree[i].to_js() } return res.join(';') case 'sub': expr.func='delitem' js=expr.to_js() expr.func='getitem' return js case 'op': $_SyntaxError(this,["can't delete operator"]) case 'call': $_SyntaxError(this,["can't delete function call"]) case 'attribute': return 'delattr('+expr.value.to_js()+',"'+expr.name+'")' default: $_SyntaxError(this,["can't delete "+expr.type]) }}}} function $DictOrSetCtx(C){ this.type='dict_or_set' this.real='dict_or_set' this.expect='id' this.closed=false this.start=$pos this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){switch(this.real){case 'dict': return '(dict) {'+this.items+'}' case 'set': return '(set) {'+this.tree+'}' } return '(dict_or_set) {'+this.tree+'}' } this.to_js=function(){this.js_processed=true switch(this.real){case 'dict': var res=[],pos=0 for(var i=0;i<this.items.length;i+=2){res[pos++]='['+this.items[i].to_js()+','+this.items[i+1].to_js()+']' } return 'dict(['+res.join(',')+'])'+$to_js(this.tree) case 'set_comp': return 'set('+$to_js(this.items)+')'+$to_js(this.tree) case 'dict_comp': return 'dict('+$to_js(this.items)+')'+$to_js(this.tree) } return 'set(['+$to_js(this.items)+'])'+$to_js(this.tree) }} function $DoubleStarArgCtx(C){ this.type='double_star_arg' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '**'+this.tree} this.to_js=function(){this.js_processed=true return '{$nat:"pdict",arg:'+$to_js(this.tree)+'}' }} function $EllipsisCtx(C){ this.type='ellipsis' this.parent=C this.nbdots=1 C.tree[C.tree.length]=this this.toString=function(){return 'ellipsis'} this.to_js=function(){this.js_processed=true return '$B.builtins["Ellipsis"]' }} function $ExceptCtx(C){ this.type='except' this.parent=C C.tree[C.tree.length]=this this.tree=[] this.expect='id' this.toString=function(){return '(except) '} this.set_alias=function(alias){this.tree[0].alias=alias $B.bound[$get_scope(this).id][alias]=true } this.to_js=function(){ this.js_processed=true switch(this.tree.length){case 0: return 'else' case 1: if(this.tree[0].name==='Exception')return 'else if(1)' } var res=[],pos=0 for(var i=0;i<this.tree.length;i++){res[pos++]=this.tree[i].to_js() } return 'else if($B.is_exc('+this.error_name+',['+res.join(',')+']))' }} function $ExprCtx(C,name,with_commas){ this.type='expr' this.name=name this.with_commas=with_commas this.expect=',' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(expr '+with_commas+') '+this.tree} this.to_js=function(arg){this.js_processed=true if(this.type==='list')return '['+$to_js(this.tree)+']' if(this.tree.length===1)return this.tree[0].to_js(arg) return 'tuple('+$to_js(this.tree)+')' }} function $ExprNot(C){ this.type='expr_not' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(expr_not)'}} function $FloatCtx(C,value){ this.type='float' this.value=value this.toString=function(){return 'float '+this.value} this.parent=C this.tree=[] C.tree[C.tree.length]=this this.to_js=function(){this.js_processed=true return 'float('+this.value+')' }} function $ForExpr(C){ this.type='for' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.loop_num=$loop_num this.module=$get_scope(this).module $loop_num++ this.toString=function(){return '(for) '+this.tree} this.transform=function(node,rank){var scope=$get_scope(this) var mod_name=scope.module var target=this.tree[0] var iterable=this.tree[1] var num=this.loop_num var local_ns='$locals_'+scope.id.replace(/\./g,'_') var $range=false if(target.tree.length==1 && iterable.type=='expr' && iterable.tree[0].type=='expr' && iterable.tree[0].tree[0].type=='call'){var call=iterable.tree[0].tree[0] if(call.func.type=='id'){var func_name=call.func.value if(func_name=='range' && call.tree.length<3){$range=call }}} var new_nodes=[],pos=0 var children=node.children var offset=1 if($range && scope.ntype!='generator'){if(this.has_break){ new_node=new $Node() new $NodeJSCtx(new_node,local_ns+'["$no_break'+num+'"]=true') new_nodes[pos++]=new_node } var range_is_builtin=false if(!scope.blurred){var _scope=$get_scope(this),found=[],fpos=0 while(1){if($B.bound[_scope.id]['range']){found[fpos++]=_scope.id} if(_scope.parent_block){_scope=_scope.parent_block} else{break}} range_is_builtin=found.length==1 && found[0]=="__builtins__" if(found==['__builtins__']){range_is_builtin=true}} var test_range_node=new $Node() if(range_is_builtin){new $NodeJSCtx(test_range_node,'if(1)') }else{new $NodeJSCtx(test_range_node,'if('+call.func.to_js()+'===$B.builtins.range)') } new_nodes[pos++]=test_range_node var idt=target.to_js() if($range.tree.length==1){var start=0,stop=$range.tree[0].to_js() }else{var start=$range.tree[0].to_js(),stop=$range.tree[1].to_js() } var js=idt+'=('+start+')-1, $stop_'+num js +='='+stop+'-1;while('+idt+'++ < $stop_'+num+')' var for_node=new $Node() new $NodeJSCtx(for_node,js) for(var i=0;i<children.length;i++){for_node.add(children[i].clone()) } var in_loop=false if(scope.ntype=='module'){var pnode=node.parent while(pnode){if(pnode.for_wrapper){in_loop=true;break} pnode=pnode.parent }} if(scope.ntype=='module' && !in_loop){var func_node=new $Node() func_node.for_wrapper=true js='function $f'+num+'(' if(this.has_break){js +='$no_break'+num} js +=')' new $NodeJSCtx(func_node,js) test_range_node.add(func_node) func_node.add(for_node) if(this.has_break){new_node=new $Node() new $NodeJSCtx(new_node,'return $no_break'+num) func_node.add(new_node) } var end_func_node=new $Node() new $NodeJSCtx(end_func_node,'var $res'+num+'=$f'+num+'();') test_range_node.add(end_func_node) if(this.has_break){var no_break=new $Node() new $NodeJSCtx(no_break,'$no_break'+num+'=$res'+num) test_range_node.add(no_break) }}else{ test_range_node.add(for_node) } if(range_is_builtin){node.parent.children.splice(rank,1) var k=0 if(this.has_break){node.parent.insert(rank,new_nodes[0]) k++ } for(var i=new_nodes[k].children.length-1;i>=0;i--){node.parent.insert(rank+k,new_nodes[k].children[i]) } node.children=[] return 0 } var else_node=new $Node() new $NodeJSCtx(else_node,'else') new_nodes[pos++]=else_node for(var i=new_nodes.length-1;i>=0;i--){node.parent.insert(rank+1,new_nodes[i]) } this.test_range=true new_nodes=[],pos=0 } var new_node=new $Node() var js='$locals["$next'+num+'"]' js +='=getattr(iter('+iterable.to_js()+'),"__next__");\n' new $NodeJSCtx(new_node,js) new_nodes[pos++]=new_node if(this.has_break){ new_node=new $Node() new $NodeJSCtx(new_node,local_ns+'["$no_break'+num+'"]=true;') new_nodes[pos++]=new_node } var while_node=new $Node() if(this.has_break){js='while('+local_ns+'["$no_break'+num+'"])'} else{js='while(1)'} new $NodeJSCtx(while_node,js) while_node.C.loop_num=num if(scope.ntype=='generator'){ while_node.loop_start=num } new_nodes[pos++]=while_node node.parent.children.splice(rank,1) if(this.test_range){for(var i=new_nodes.length-1;i>=0;i--){else_node.insert(0,new_nodes[i]) }}else{for(var i=new_nodes.length-1;i>=0;i--){node.parent.insert(rank,new_nodes[i]) offset +=new_nodes.length }} var try_node=new $Node() new $NodeJSCtx(try_node,'try') while_node.add(try_node) var iter_node=new $Node() iter_node.parent=$get_node(this).parent iter_node.id=this.module var C=new $NodeCtx(iter_node) var target_expr=new $ExprCtx(C,'left',true) target_expr.tree=target.tree var assign=new $AssignCtx(target_expr) assign.tree[1]=new $JSCode('$locals["$next'+num+'"]()') try_node.add(iter_node) var catch_node=new $Node() var js='catch($err){if($B.is_exc($err,[StopIteration]))' js +='{$B.$pop_exc();' js +='delete $locals["$next'+num+'"];break;}' js +='else{throw($err)}}' new $NodeJSCtx(catch_node,js) while_node.add(catch_node) for(var i=0;i<children.length;i++){while_node.add(children[i].clone()) } node.children=[] return 0 } this.to_js=function(){this.js_processed=true var iterable=this.tree.pop() return 'for '+$to_js(this.tree)+' in '+iterable.to_js() }} function $FromCtx(C){ this.type='from' this.parent=C this.module='' this.names=[] this.aliases={} C.tree[C.tree.length]=this this.expect='module' this.scope=$get_scope(this) this.add_name=function(name){this.names[this.names.length]=name if(name=='*'){this.scope.blurred=true}} this.bind_names=function(){ var scope=$get_scope(this) for(var i=0;i<this.names.length;i++){var name=this.aliases[this.names[i]]||this.names[i] $B.bound[scope.id][name]=true }} this.toString=function(){return '(from) '+this.module+' (import) '+this.names+'(as)'+this.aliases } this.to_js=function(){this.js_processed=true var scope=$get_scope(this) var mod=$get_module(this).module var res='' var indent=$get_node(this).indent var head=' '.repeat(indent) var _mod=this.module.replace(/\$/g,''),package,packages=[] while(_mod.length>0){if(_mod.charAt(0)=='.'){if(package===undefined){package=$B.imported[mod].__package__ if(package==''){console.log('package vide 1 pour $B.imported['+mod+']')}}else{package=$B.imported[package] if(package==''){console.log('package vide 3 pour $B.imported['+package+']')}} if(package===undefined){return 'throw SystemError("Parent module \'\' not loaded, cannot perform relative import")' }else{packages.push(package) } _mod=_mod.substr(1) }else{break }} if(_mod){packages.push(_mod)} this.module=packages.join('.') if(this.names[0]=='*'){res +='$B.$import("'+this.module+'","'+mod+'")\n' res +=head+'var $mod=$B.imported["'+this.module+'"]\n' res +=head+'for(var $attr in $mod){\n' res +="if($attr.substr(0,1)!=='_'){\n"+head res +='$locals_'+scope.id.replace(/\./g,'_')+'[$attr]' res +='=$mod[$attr]\n'+head+'}}' scope.blurred=true }else{res +='$B.$import_from("'+this.module+'",[' res +='"' + this.names.join('","')+ '"' res +='],"'+mod+'");\n' var _is_module=scope.ntype==='module' for(var i=0;i<this.names.length;i++){var name=this.names[i] var alias=this.aliases[name]||name res +=head+'try{$locals_'+scope.id.replace(/\./g,'_')+'["'+ alias+'"]' res +='=getattr($B.imported["'+this.module+'"],"'+name+'")}\n' res +='catch($err'+$loop_num+'){if($err'+$loop_num+'.__class__' res +='===AttributeError.$dict){$err'+$loop_num+'.__class__' res +='=ImportError.$dict};throw $err'+$loop_num+'};' }} return res + '\n'+head+'None;' }} function $FuncArgs(C){ this.type='func_args' this.parent=C this.tree=[] this.names=[] C.tree[C.tree.length]=this this.toString=function(){return 'func args '+this.tree} this.expect='id' this.has_default=false this.has_star_arg=false this.has_kw_arg=false this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $FuncArgIdCtx(C,name){ this.type='func_arg_id' this.name=name this.parent=C if(C.has_star_arg){C.parent.after_star.push('"'+name+'"') }else{C.parent.positional_list.push(name) } var node=$get_node(this) if($B.bound[node.id][name]){$_SyntaxError(C,["duplicate argument '"+name+"' in function definition"]) } $B.bound[node.id][name]='arg' this.tree=[] C.tree[C.tree.length]=this var ctx=C while(ctx.parent!==undefined){if(ctx.type==='def'){ctx.locals.push(name) break } ctx=ctx.parent } this.expect='=' this.toString=function(){return 'func arg id '+this.name +'='+this.tree} this.to_js=function(){this.js_processed=true return this.name+$to_js(this.tree) }} function $FuncStarArgCtx(C,op){ this.type='func_star_arg' this.op=op this.parent=C this.node=$get_node(this) C.has_star_arg=op=='*' C.has_kw_arg=op=='**' C.tree[C.tree.length]=this this.toString=function(){return '(func star arg '+this.op+') '+this.name} this.set_name=function(name){this.name=name if(name=='$dummy'){return} if($B.bound[this.node.id][name]){$_SyntaxError(C,["duplicate argument '"+name+"' in function definition"]) } $B.bound[this.node.id][name]='arg' var ctx=C while(ctx.parent!==undefined){if(ctx.type==='def'){ctx.locals.push(name) break } ctx=ctx.parent } if(op=='*'){ctx.other_args='"'+name+'"'} else{ctx.other_kw='"'+name+'"'}}} function $GlobalCtx(C){ this.type='global' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.expect='id' this.toString=function(){return 'global '+this.tree} this.scope=$get_scope(this) $B.globals=$B.globals ||{} $B.globals[this.scope.id]=$B.globals[this.scope.id]||{} this.add=function(name){$B.globals[this.scope.id][name]=true } this.to_js=function(){this.js_processed=true return '' }} function $check_unbound(assigned,scope,varname){ if(scope.var2node && scope.var2node[varname]){if(scope.C.tree[0].locals.indexOf(varname)>-1)return for(var i=0;i<scope.var2node[varname].length;i++){var ctx=scope.var2node[varname][i] if(ctx==assigned){delete scope.var2node[varname] break }else{while(ctx.parent){ctx=ctx.parent} var ctx_node=ctx.node var pnode=ctx_node.parent for(var rank=0;rank<pnode.children.length;rank++){if(pnode.children[rank]===ctx_node){break}} var new_node=new $Node() var js='throw UnboundLocalError("local variable '+"'" js +=varname+"'"+' referenced before assignment")' if(ctx.tree[0].type=='condition' && ctx.tree[0].token=='elif'){js='else if(1){'+js+'}' } new $NodeJSCtx(new_node,js) pnode.insert(rank,new_node) }}} if(scope.C.tree[0].locals.indexOf(varname)==-1){scope.C.tree[0].locals.push(varname) }} function $IdCtx(C,value){ this.type='id' this.toString=function(){return '(id) '+this.value+':'+(this.tree||'')} this.value=value this.parent=C this.tree=[] C.tree[C.tree.length]=this if(C.parent.type==='call_arg')this.call_arg=true this.scope=$get_scope(this) this.blurred_scope=this.scope.blurred this.env=clone($B.bound[this.scope.id]) var ctx=C while(ctx.parent!==undefined){switch(ctx.type){case 'list_or_tuple': case 'dict_or_set': case 'call_arg': case 'def': case 'lambda': if(ctx.vars===undefined){ctx.vars=[value]} else if(ctx.vars.indexOf(value)===-1){ctx.vars.push(value)} if(this.call_arg&&ctx.type==='lambda'){if(ctx.locals===undefined){ctx.locals=[value]} else{ctx.locals.push(value)}}} ctx=ctx.parent } var scope=$get_scope(this) if(C.type=='target_list'){ $B.bound[scope.id][value]=true this.bound=true } if(scope.ntype=='def' ||scope.ntype=='generator'){ var _ctx=this.parent while(_ctx){if(_ctx.type=='list_or_tuple' && _ctx.is_comp())return _ctx=_ctx.parent } if(C.type=='target_list'){if(C.parent.type=='for'){ $check_unbound(this,scope,value) }else if(C.parent.type=='comp_for'){ var comprehension=C.parent.parent.parent if(comprehension.parent && comprehension.parent.type=='call_arg'){ comprehension=comprehension.parent } var remove=[],pos=0 if(scope.var2node && scope.var2node[value]){for(var i=0;i<scope.var2node[value].length;i++){var ctx=scope.var2node[value][i] while(ctx.parent){if(ctx===comprehension.parent){remove[pos++]=i break } ctx=ctx.parent }}} while(i-->0){ scope.var2node[value].splice(i,1) }}}else if(C.type=='expr' && C.parent.type=='comp_if'){ return }else if(C.type=='global'){if(scope.globals===undefined){scope.globals=[value] }else if(scope.globals.indexOf(value)==-1){scope.globals.push(value) }}else if(scope.globals===undefined ||scope.globals.indexOf(value)==-1){ if(scope.var2node===undefined){scope.var2node={} scope.var2node[value]=[this] }else if(scope.var2node[value]===undefined){scope.var2node[value]=[this] }else{scope.var2node[value].push(this) }}} this.to_js=function(arg){this.js_processed=true var val=this.value if(val=='eval')val='$eval' else if(val=='__BRYTHON__' ||val=='$B'){return val} var innermost=$get_scope(this) var scope=innermost,found=[],module=scope.module var gs=innermost while(gs.parent_block && gs.parent_block.id!=='__builtins__'){gs=gs.parent_block } var global_ns='$locals_'+gs.id.replace(/\./g,'_') while(1){if($B.bound[scope.id]===undefined){console.log('name '+val+' undef '+scope.id)} if($B.globals[scope.id]!==undefined && $B.globals[scope.id][val]!==undefined){found=[gs] break } if(scope===innermost){ var bound_before=$get_node(this).bound_before if(bound_before && !this.bound){if(bound_before.indexOf(val)>-1){found.push(scope)} else if(scope.C && scope.C.tree[0].type=='def' && scope.C.tree[0].env.indexOf(val)>-1){found.push(scope) }}else{if($B.bound[scope.id][val]){found.push(scope)}}}else{if($B.bound[scope.id][val]){found.push(scope)}} if(scope.parent_block){scope=scope.parent_block} else{break}} this.found=found if(found.length>0){if(found.length>1 && found[0].C){if(found[0].C.tree[0].type=='class' && !this.bound){var bound_before=$get_node(this).bound_before,res var ns0='$locals_'+found[0].id.replace(/\./g,'_'),ns1='$locals_'+found[1].id.replace(/\./g,'_') if(bound_before){if(bound_before.indexOf(val)>-1){this.found=$B.bound[found[0].id][val] res=ns0 }else{this.found=$B.bound[found[1].id][val] res=ns1 } return res+'["'+val+'"]' }else{this.found=false var res=ns0 + '["'+val+'"]!==undefined ? ' res +=ns0 + '["'+val+'"] : ' return res + ns1 + '["'+val+'"]' }}} var scope=found[0] this.found=$B.bound[scope.id][val] var scope_ns='$locals_'+scope.id.replace(/\./g,'_') if(scope.C===undefined){ if(scope.id=='__builtins__'){if(gs.blurred){var val1='('+global_ns+'["'+val+'"]' val1 +='|| $B.builtins["'+val+'"])' val=val1 }else{val='$B.builtins["'+val+'"]' this.is_builtin=true }}else if(scope.id==scope.module){if(!this.bound && scope===innermost && this.env[val]===undefined){return '$B.$search("'+val+'", $locals_'+scope.id.replace(/\./g,'_')+')' } val=scope_ns+'["'+val+'"]' }else{val=scope_ns+'["'+val+'"]' }}else if(scope===innermost){if($B.globals[scope.id]&& $B.globals[scope.id][val]){val=global_ns+'["'+val+'"]' }else{val='$locals["'+val+'"]' }}else{ val=scope_ns+'["'+val+'"]' } return val+$to_js(this.tree,'') }else{ this.unknown_binding=true return '$B.$search("'+val+'", '+global_ns+')' }}} function $ImaginaryCtx(C,value){ this.type='imaginary' this.value=value this.toString=function(){return 'imaginary '+this.value} this.parent=C this.tree=[] C.tree[C.tree.length]=this this.to_js=function(){this.js_processed=true return 'complex(0,'+this.value+')' }} function $ImportCtx(C){ this.type='import' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.expect='id' this.toString=function(){return 'import '+this.tree} this.bind_names=function(){ var scope=$get_scope(this) for(var i=0;i<this.tree.length;i++){if(this.tree[i].name==this.tree[i].alias){var name=this.tree[i].name var parts=name.split('.') if(parts.length==1){$B.bound[scope.id][name]=true} else{$B.bound[scope.id][parts[0]]=true}}else{$B.bound[scope.id][this.tree[i].alias]=true }}} this.to_js=function(){this.js_processed=true var scope=$get_scope(this) var mod=scope.module var res=[],pos=0 for(var i=0;i<this.tree.length;i++){res[pos++]='$B.$import('+this.tree[i].to_js()+',"'+mod+'");' if(this.tree[i].name==this.tree[i].alias){var parts=this.tree[i].name.split('.') for(var j=0;j<parts.length;j++){var imp_key=parts.slice(0,j+1).join('.') var obj_attr='' for(var k=0;k<j+1;k++){obj_attr+='["'+parts[k]+'"]'} res[pos++]='$locals'+obj_attr+'=$B.imported["'+imp_key+'"];' }}else{res[pos++]='$locals_'+scope.id.replace(/\./g,'_') res[pos++]='["'+this.tree[i].alias res[pos++]='"]=$B.imported["'+this.tree[i].name+'"];' }} return res.join('')+ 'None;' }} function $ImportedModuleCtx(C,name){this.type='imported module' this.toString=function(){return ' (imported module) '+this.name} this.parent=C this.name=name this.alias=name C.tree[C.tree.length]=this this.to_js=function(){this.js_processed=true return '"'+this.name+'"' }} function $IntCtx(C,value){ this.type='int' this.value=value this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return 'int '+this.value} this.to_js=function(){this.js_processed=true return this.value }} function $JSCode(js){this.js=js this.toString=function(){return this.js} this.to_js=function(){this.js_processed=true return this.js }} function $KwArgCtx(C){ this.type='kwarg' this.parent=C.parent this.tree=[C.tree[0]] C.parent.tree.pop() C.parent.tree.push(this) var value=this.tree[0].value var ctx=C.parent.parent if(ctx.kwargs===undefined){ctx.kwargs=[value]} else if(ctx.kwargs.indexOf(value)===-1){ctx.kwargs.push(value)} else{$_SyntaxError(C,['keyword argument repeated'])} var scope=$get_scope(this) switch(scope.ntype){case 'def': case 'generator': var ix=null,varname=C.tree[0].value if(scope.var2node[varname]!==undefined){for(var i=0;i<scope.var2node[varname].length;i++){if(scope.var2node[varname][i]==C.tree[0]){ix=i break }} scope.var2node[varname].splice(ix,1) }} this.toString=function(){return 'kwarg '+this.tree[0]+'='+this.tree[1]} this.to_js=function(){this.js_processed=true var key=this.tree[0].value if(key.substr(0,2)=='$$'){key=key.substr(2)} var res='{$nat:"kw",name:"'+key+'",' return res + 'value:'+$to_js(this.tree.slice(1,this.tree.length))+'}' }} function $LambdaCtx(C){ this.type='lambda' this.parent=C C.tree[C.tree.length]=this this.tree=[] this.args_start=$pos+6 this.vars=[] this.locals=[] this.toString=function(){return '(lambda) '+this.args_start+' '+this.body_start} this.to_js=function(){this.js_processed=true var module=$get_module(this) var src=$B.$py_src[module.id] var qesc=new RegExp('"',"g") var args=src.substring(this.args_start,this.body_start).replace(qesc,'\\"') var body=src.substring(this.body_start+1,this.body_end).replace(qesc,'\\"') body=body.replace(/\n/g,' ') var scope=$get_scope(this) var sc=scope var env=[],pos=0 while(sc && sc.id!=='__builtins__'){env[pos++]='["'+sc.id+'",$locals_'+sc.id.replace(/\./g,'_')+']' sc=sc.parent_block } var env_string='['+env.join(', ')+']' return '$B.$lambda('+env_string+',"'+args+'","'+body+'")' }} function $ListOrTupleCtx(C,real){ this.type='list_or_tuple' this.start=$pos this.real=real this.expect='id' this.closed=false this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){switch(this.real){case 'list': return '(list) ['+this.tree+']' case 'list_comp': case 'gen_expr': return '('+this.real+') ['+this.intervals+'-'+this.tree+']' default: return '(tuple) ('+this.tree+')' }} this.is_comp=function(){switch(this.real){case 'list_comp': case 'gen_expr': case 'dict_or_set_comp': return true } return false } this.get_src=function(){ var scope=$get_scope(this) var ident=scope.id while($B.$py_src[ident]===undefined && $B.modules[ident].parent_block){ident=$B.modules[ident].parent_block.id } if($B.$py_src[ident]===undefined){ return $B.$py_src[scope.module] } return $B.$py_src[ident] } this.to_js=function(){this.js_processed=true var scope=$get_scope(this) var sc=scope var env=[],pos=0 while(sc && sc.id!=='__builtins__'){if(sc===scope){env[pos++]='["'+sc.id+'",$locals]' }else{env[pos++]='["'+sc.id+'",$locals_'+sc.id.replace(/\./g,'_')+']' } sc=sc.parent_block } var env_string='['+env.join(', ')+']' switch(this.real){case 'list': return '['+$to_js(this.tree)+']' case 'list_comp': case 'gen_expr': case 'dict_or_set_comp': var src=this.get_src() var res1=[] var qesc=new RegExp('"',"g") for(var i=1;i<this.intervals.length;i++){var txt=src.substring(this.intervals[i-1],this.intervals[i]) var lines=txt.split('\n') var res2=[],pos=0 for(var j=0;j<lines.length;j++){var txt=lines[j] if(txt.replace(/ /g,'').length==0){continue} txt=txt.replace(/\n/g,' ') txt=txt.replace(/\\/g,'\\\\') txt=txt.replace(qesc,'\\"') res2[pos++]='"'+txt+'"' } res1.push('['+res2.join(',')+']') } switch(this.real){case 'list_comp': return '$B.$list_comp('+env_string+','+res1+')' case 'dict_or_set_comp': if(this.expression.length===1){return '$B.$gen_expr('+env_string+','+res1+')' } return '$B.$dict_comp('+env_string+','+res1+')' } return '$B.$gen_expr('+env_string+','+res1+')' case 'tuple': if(this.tree.length===1 && this.has_comma===undefined){return this.tree[0].to_js() } return 'tuple(['+$to_js(this.tree)+'])' }}} function $NodeCtx(node){ this.node=node node.C=this this.tree=[] this.type='node' var scope=null var tree_node=node while(tree_node.parent && tree_node.parent.type!=='module'){var ntype=tree_node.parent.C.tree[0].type var _break_flag=false switch(ntype){case 'def': case 'class': case 'generator': scope=tree_node.parent _break_flag=true } if(_break_flag)break tree_node=tree_node.parent } if(scope==null){scope=tree_node.parent ||tree_node } this.toString=function(){return 'node '+this.tree} this.to_js=function(){this.js_processed=true if(this.tree.length>1){var new_node=new $Node() var ctx=new $NodeCtx(new_node) ctx.tree=[this.tree[1]] new_node.indent=node.indent+4 this.tree.pop() node.add(new_node) } if(node.children.length==0){return $to_js(this.tree)+';'} return $to_js(this.tree) }} function $NodeJSCtx(node,js){ this.node=node node.C=this this.type='node_js' this.tree=[js] this.toString=function(){return 'js '+js} this.to_js=function(){this.js_processed=true return js }} function $NonlocalCtx(C){ this.type='global' this.parent=C this.tree=[] this.names={} C.tree[C.tree.length]=this this.expect='id' this.scope=$get_scope(this) if(this.scope.C===undefined){$_SyntaxError(C,["nonlocal declaration not allowed at module level"]) } this.toString=function(){return 'global '+this.tree} this.add=function(name){if($B.bound[this.scope.id][name]=='arg'){$_SyntaxError(C,["name '"+name+"' is parameter and nonlocal"]) } this.names[name]=[false,$pos] } this.transform=function(node,rank){var pscope=this.scope.parent_block if(pscope.C===undefined){$_SyntaxError(C,["no binding for nonlocal '"+name+"' found"]) }else{while(pscope!==undefined && pscope.C!==undefined){for(var name in this.names){if($B.bound[pscope.id][name]!==undefined){this.names[name]=[true] }} pscope=pscope.parent_block } for(var name in this.names){if(!this.names[name][0]){console.log('nonlocal error, C '+C) $pos=this.names[name][1] $_SyntaxError(C,["no binding for nonlocal '"+name+"' found"]) }} }} this.to_js=function(){this.js_processed=true return '' }} function $NotCtx(C){ this.type='not' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return 'not ('+this.tree+')'} this.to_js=function(){this.js_processed=true return '!bool('+$to_js(this.tree)+')' }} function $OpCtx(C,op){ this.type='op' this.op=op this.parent=C.parent this.tree=[C] C.parent.tree.pop() C.parent.tree.push(this) this.toString=function(){return '(op '+this.op+') ['+this.tree+']'} this.to_js=function(){this.js_processed=true var comps={'==':'eq','!=':'ne','>=':'ge','<=':'le','<':'lt','>':'gt'} if(comps[this.op]!==undefined){var method=comps[this.op] if(this.tree[0].type=='expr' && this.tree[1].type=='expr'){var t0=this.tree[0].tree[0],t1=this.tree[1].tree[0] switch(t1.type){case 'int': switch(t0.type){case 'int': return t0.to_js()+this.op+t1.to_js() case 'str': return '$B.$TypeError("unorderable types: int() < str()")' case 'id': var res='typeof '+t0.to_js()+'=="number" ? ' res +=t0.to_js()+this.op+t1.to_js()+' : ' res +='getattr('+this.tree[0].to_js() res +=',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break case 'str': switch(t0.type){case 'str': return t0.to_js()+this.op+t1.to_js() case 'int': return '$B.$TypeError("unorderable types: str() < int()")' case 'id': var res='typeof '+t0.to_js()+'=="string" ? ' res +=t0.to_js()+this.op+t1.to_js()+' : ' res +='getattr('+this.tree[0].to_js() res +=',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break case 'id': if(t0.type=='id'){var res='typeof '+t0.to_js()+'!="object" && ' res +='typeof '+t0.to_js()+'==typeof '+t1.to_js() res +=' ? '+t0.to_js()+this.op+t1.to_js()+' : ' res +='getattr('+this.tree[0].to_js() res +=',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break } }} switch(this.op){case 'and': var res='$B.$test_expr($B.$test_item('+this.tree[0].to_js()+')&&' return res + '$B.$test_item('+this.tree[1].to_js()+'))' case 'or': var res='$B.$test_expr($B.$test_item('+this.tree[0].to_js()+')||' return res + '$B.$test_item('+this.tree[1].to_js()+'))' case 'in': return '$B.$is_member('+$to_js(this.tree)+')' case 'not_in': return '!$B.$is_member('+$to_js(this.tree)+')' case 'unary_neg': case 'unary_inv': if(this.op=='unary_neg'){op='-'}else{op='~'} if(this.tree[1].type=="expr"){var x=this.tree[1].tree[0] switch(x.type){case 'int': return op+x.value case 'float': return 'float('+op+x.value+')' case 'imaginary': return 'complex(0,'+op+x.value+')' }} if(op=='-')return 'getattr('+this.tree[1].to_js()+',"__neg__")()' return 'getattr('+this.tree[1].to_js()+',"__invert__")()' case 'is': return this.tree[0].to_js()+ '===' + this.tree[1].to_js() case 'is_not': return this.tree[0].to_js()+ '!==' + this.tree[1].to_js() case '*': case '+': case '-': var op=this.op var vars=[] var has_float_lit=false function is_simple(elt){if(elt.type=='expr' && elt.tree[0].type=='int'){return true} else if(elt.type=='expr' && elt.tree[0].type=='float'){has_float_lit=true return true }else if(elt.type=='expr' && elt.tree[0].type=='list_or_tuple' && elt.tree[0].real=='tuple' && elt.tree[0].tree.length==1 && elt.tree[0].tree[0].type=='expr'){return is_simple(elt.tree[0].tree[0].tree[0]) }else if(elt.type=='expr' && elt.tree[0].type=='id'){var _var=elt.tree[0].to_js() if(vars.indexOf(_var)==-1){vars.push(_var)} return true }else if(elt.type=='op' &&['*','+','-'].indexOf(elt.op)>-1){for(var i=0;i<elt.tree.length;i++){if(!is_simple(elt.tree[i])){return false}} return true } return false } var e0=this.tree[0],e1=this.tree[1] if(is_simple(this)){var v0=this.tree[0].tree[0] var v1=this.tree[1].tree[0] if(vars.length==0 && !has_float_lit){ return this.simple_js() }else if(vars.length==0){ return 'new $B.$FloatClass('+this.simple_js()+')' }else{ var tests=[],tests1=[],pos=0 for(var i=0;i<vars.length;i++){ tests[pos]='typeof '+vars[i]+'.valueOf() == "number"' tests1[pos++]='typeof '+vars[i]+' == "number"' } var res=[tests.join(' && ')+' ? '],pos=1 res[pos++]='('+tests1.join(' && ')+' ? ' res[pos++]=this.simple_js() res[pos++]=' : new $B.$FloatClass('+this.simple_js()+')' res[pos++]=')' if(this.op=='+'){res[pos++]=' : (typeof '+this.tree[0].to_js()+'=="string"' res[pos++]=' && typeof '+this.tree[1].to_js() res[pos++]='=="string") ? '+this.tree[0].to_js() res[pos++]='+'+this.tree[1].to_js() } res[pos++]=': getattr('+this.tree[0].to_js()+',"__' res[pos++]=$operators[this.op]+'__")'+'('+this.tree[1].to_js()+')' return '('+res.join('')+')' }} var res='getattr('+e0.to_js()+',"__' return res + $operators[this.op]+'__")'+'('+e1.to_js()+')' default: var res='getattr('+this.tree[0].to_js()+',"__' return res + $operators[this.op]+'__")'+'('+this.tree[1].to_js()+')' }} this.simple_js=function(){function sjs(elt){if(elt.type=='op'){return elt.simple_js()} else if(elt.type=='expr' && elt.tree[0].type=='list_or_tuple' && elt.tree[0].real=='tuple' && elt.tree[0].tree.length==1 && elt.tree[0].tree[0].type=='expr'){return '('+elt.tree[0].tree[0].tree[0].simple_js()+')' }else{return elt.tree[0].to_js()}} return sjs(this.tree[0])+op+sjs(this.tree[1]) }} function $PackedCtx(C){ this.type='packed' if(C.parent.type=='list_or_tuple'){for(var i=0;i<C.parent.tree.length;i++){var child=C.parent.tree[i] if(child.type=='expr' && child.tree.length>0 && child.tree[0].type=='packed'){$_SyntaxError(C,["two starred expressions in assignment"]) }}} this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(packed) '+this.tree} this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $PassCtx(C){ this.type='pass' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(pass)'} this.to_js=function(){this.js_processed=true return 'void(0)' }} function $RaiseCtx(C){ this.type='raise' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return ' (raise) '+this.tree} this.to_js=function(){this.js_processed=true var res=';$B.leave_frame();' if(this.tree.length===0)return res+'$B.$raise()' var exc=this.tree[0],exc_js=exc.to_js() if(exc.type==='id' || (exc.type==='expr' && exc.tree[0].type==='id')){res +='if(isinstance('+exc_js+',type)){throw '+exc_js+'()}' return res + 'else{throw '+exc_js+'}' } while(this.tree.length>1)this.tree.pop() return res+'throw '+$to_js(this.tree) }} function $RawJSCtx(C,js){this.type="raw_js" C.tree[C.tree.length]=this this.parent=C this.toString=function(){return '(js) '+js} this.to_js=function(){this.js_processed=true return js }} function $ReturnCtx(C){ this.type='return' this.parent=C this.tree=[] C.tree[C.tree.length]=this var node=$get_node(this) while(node.parent){if(node.parent.C && node.parent.C.tree[0].type=='for'){node.parent.C.tree[0].has_return=true break } node=node.parent } this.toString=function(){return 'return '+this.tree} this.to_js=function(){this.js_processed=true if(this.tree.length==1 && this.tree[0].type=='abstract_expr'){ this.tree.pop() new $IdCtx(new $ExprCtx(this,'rvalue',false),'None') } var scope=$get_scope(this) if(scope.ntype=='generator'){return 'return [$B.generator_return(' + $to_js(this.tree)+')]' } var js='' js +='if($B.frames_stack.length>1){$B.frames_stack.pop()}' return js +';return '+$to_js(this.tree) }} function $SingleKwCtx(C,token){ this.type='single_kw' this.token=token this.parent=C this.tree=[] C.tree[C.tree.length]=this if(token=="else"){var node=C.node var pnode=node.parent for(var rank=0;rank<pnode.children.length;rank++){if(pnode.children[rank]===node)break } var pctx=pnode.children[rank-1].C if(pctx.tree.length>0){var elt=pctx.tree[0] if(elt.type=='for' || (elt.type=='condition' && elt.token=='while')){elt.has_break=true this.loop_num=elt.loop_num }}} this.toString=function(){return this.token} this.to_js=function(){this.js_processed=true if(this.token=='finally')return this.token if(this.loop_num!==undefined){var scope=$get_scope(this) var res='if($locals_'+scope.id.replace(/\./g,'_') return res +'["$no_break'+this.loop_num+'"])' } return this.token }} function $StarArgCtx(C){ this.type='star_arg' this.parent=C this.tree=[] C.tree[C.tree.length]=this this.toString=function(){return '(star arg) '+this.tree} this.to_js=function(){this.js_processed=true return '{$nat:"ptuple",arg:'+$to_js(this.tree)+'}' }} function $StringCtx(C,value){ this.type='str' this.parent=C this.tree=[value] this.raw=false C.tree[C.tree.length]=this this.toString=function(){return 'string '+(this.tree||'')} this.to_js=function(){this.js_processed=true var res='',type=null for(var i=0;i<this.tree.length;i++){var value=this.tree[i],is_bytes=value.charAt(0)=='b' if(type==null){type=is_bytes if(is_bytes){res+='bytes('}}else if(type!=is_bytes){return '$B.$TypeError("can\'t concat bytes to str")' } if(!is_bytes){res +=value.replace(/\n/g,'\\n\\\n') }else{res +=value.substr(1).replace(/\n/g,'\\n\\\n') } if(i<this.tree.length-1){res+='+'}} if(is_bytes){res +=',"ISO-8859-1")'} return res }} function $SubCtx(C){ this.type='sub' this.func='getitem' this.value=C.tree[0] C.tree.pop() C.tree[C.tree.length]=this this.parent=C this.tree=[] this.toString=function(){return '(sub) (value) '+this.value+' (tree) '+this.tree } this.to_js=function(){this.js_processed=true if(this.marked){var val=this.value.to_js() var res='getattr('+val+',"__'+this.func+'__")(' if(this.tree.length===1)return res+this.tree[0].to_js()+')' var res1=[],pos=0 for(var i=0;i<this.tree.length;i++){if(this.tree[i].type==='abstract_expr'){res1[pos++]='null'} else{res1[pos++]=this.tree[i].to_js()} } return res+'slice(' + res1.join(',')+ '))' }else{if(this.func=='getitem' && this.tree.length==1){return '$B.$getitem('+this.value.to_js()+',' + this.tree[0].to_js()+')' } var res='',shortcut=false if(this.func!=='delitem' && Array.isArray && this.tree.length==1 && !this.in_sub){var expr='',x=this shortcut=true while(x.value.type=='sub'){expr +='['+x.tree[0].to_js()+']' x.value.in_sub=true x=x.value } var subs=x.value.to_js()+'['+x.tree[0].to_js()+']' res +='((Array.isArray('+x.value.to_js()+') || ' res +='typeof '+x.value.to_js()+'=="string")' res +=' && '+subs+'!==undefined ?' res +=subs+expr+ ' : ' } var val=this.value.to_js() res +='getattr('+val+',"__'+this.func+'__")(' if(this.tree.length===1){res +=this.tree[0].to_js()+')' }else{ var res1=[],pos=0 for(var i=0;i<this.tree.length;i++){if(this.tree[i].type==='abstract_expr'){res1[pos++]='null'} else{res1[pos++]=this.tree[i].to_js()} } res +='slice(' + res1.join(',')+ '))' } return shortcut ? res+')' : res }}} function $TargetListCtx(C){ this.type='target_list' this.parent=C this.tree=[] this.expect='id' C.tree[C.tree.length]=this this.toString=function(){return '(target list) '+this.tree} this.to_js=function(){this.js_processed=true return $to_js(this.tree) }} function $TernaryCtx(C){ this.type='ternary' this.parent=C.parent C.parent.tree.pop() C.parent.tree.push(this) C.parent=this this.tree=[C] this.toString=function(){return '(ternary) '+this.tree} this.to_js=function(){this.js_processed=true var res='bool('+this.tree[1].to_js()+') ? ' res +=this.tree[0].to_js()+' : ' return res + this.tree[2].to_js() }} function $TryCtx(C){ this.type='try' this.parent=C C.tree[C.tree.length]=this this.toString=function(){return '(try) '} this.transform=function(node,rank){if(node.parent.children.length===rank+1){$_SyntaxError(C,"missing clause after 'try' 1") }else{var next_ctx=node.parent.children[rank+1].C.tree[0] switch(next_ctx.type){case 'except': case 'finally': case 'single_kw': break default: $_SyntaxError(C,"missing clause after 'try' 2") }} var scope=$get_scope(this) var $var='$B.$failed'+$loop_num var js=$var+'=false;' js +='$locals["$frame'+$loop_num+'"]=$B.frames_stack.slice();' js +='try' new $NodeJSCtx(node,js) node.is_try=true var catch_node=new $Node() new $NodeJSCtx(catch_node,'catch($err'+$loop_num+')') catch_node.is_catch=true node.parent.insert(rank+1,catch_node) var new_node=new $Node() new $NodeJSCtx(new_node,$var+'=true;if(0){}') catch_node.insert(0,new_node) var pos=rank+2 var has_default=false var has_else=false while(1){if(pos===node.parent.children.length){break} var ctx=node.parent.children[pos].C.tree[0] if(ctx.type==='except'){ if(has_else){$_SyntaxError(C,"'except' or 'finally' after 'else'")} ctx.error_name='$err'+$loop_num if(ctx.tree.length>0 && ctx.tree[0].alias!==null && ctx.tree[0].alias!==undefined){ var new_node=new $Node() var alias=ctx.tree[0].alias var js='$locals["'+alias+'"]' js +='=$B.exception($err'+$loop_num+')' new $NodeJSCtx(new_node,js) node.parent.children[pos].insert(0,new_node) } catch_node.insert(catch_node.children.length,node.parent.children[pos]) if(ctx.tree.length===0){if(has_default){$_SyntaxError(C,'more than one except: line')} has_default=true } node.parent.children.splice(pos,1) }else if(ctx.type==='single_kw' && ctx.token==='finally'){if(has_else){$_SyntaxError(C,"'finally' after 'else'")} pos++ }else if(ctx.type==='single_kw' && ctx.token==='else'){if(has_else){$_SyntaxError(C,"more than one 'else'")} has_else=true var else_body=node.parent.children[pos] node.parent.children.splice(pos,1) }else{break}} if(!has_default){ var new_node=new $Node() new $NodeJSCtx(new_node,'else{throw $err'+$loop_num+'}') catch_node.insert(catch_node.children.length,new_node) } if(has_else){var else_node=new $Node() new $NodeJSCtx(else_node,'if(!$B.$failed'+$loop_num+')') for(var i=0;i<else_body.children.length;i++){else_node.add(else_body.children[i]) } node.parent.insert(pos,else_node) pos++ } var frame_node=new $Node() var js=';$B.frames_stack = $locals["$frame'+$loop_num+'"];' js +='delete $locals["$frame'+$loop_num+'"];' new $NodeJSCtx(frame_node,js) node.parent.insert(pos,frame_node) $loop_num++ } this.to_js=function(){this.js_processed=true return 'try' }} function $UnaryCtx(C,op){ this.type='unary' this.op=op this.parent=C C.tree[C.tree.length]=this this.toString=function(){return '(unary) '+this.op} this.to_js=function(){this.js_processed=true return this.op }} function $WithCtx(C){ this.type='with' this.parent=C C.tree[C.tree.length]=this this.tree=[] this.expect='as' this.toString=function(){return '(with) '+this.tree} this.set_alias=function(arg){var scope=$get_scope(this) this.tree[this.tree.length-1].alias=arg if(scope.ntype !=='module'){ scope.C.tree[0].locals.push(arg) }} this.transform=function(node,rank){if(this.transformed)return node.is_try=true if(this.tree[0].alias===null){this.tree[0].alias='$temp'} if(this.tree[0].type=='expr' && this.tree[0].tree[0].type=='list_or_tuple'){if(this.tree[1].type!='expr' || this.tree[1].tree[0].type!='list_or_tuple'){$_SyntaxError(C) } if(this.tree[0].tree[0].tree.length!=this.tree[1].tree[0].tree.length){$_SyntaxError(C,['wrong number of alias']) } var ids=this.tree[0].tree[0].tree var alias=this.tree[1].tree[0].tree this.tree.shift() this.tree.shift() for(var i=ids.length-1;i>=0;i--){ids[i].alias=alias[i].value this.tree.splice(0,0,ids[i]) }} var catch_node=new $Node() catch_node.is_catch=true new $NodeJSCtx(catch_node,'catch($err'+$loop_num+')') var fbody=new $Node() var js='if(!$ctx_manager_exit($err'+$loop_num+'.type,' js +='$err'+$loop_num+'.value,$err'+$loop_num+'.traceback))' js +='{throw $err'+$loop_num+'}' new $NodeJSCtx(fbody,js) catch_node.add(fbody) node.parent.insert(rank+1,catch_node) $loop_num++ var finally_node=new $Node() new $NodeJSCtx(finally_node,'finally') finally_node.C.type='single_kw' finally_node.C.token='finally' var fbody=new $Node() new $NodeJSCtx(fbody,'$ctx_manager_exit(None,None,None)') finally_node.add(fbody) node.parent.insert(rank+2,finally_node) if(this.tree.length>1){var nw=new $Node() var ctx=new $NodeCtx(nw) nw.parent=node var wc=new $WithCtx(ctx) wc.tree=this.tree.slice(1) for(var i=0;i<node.children.length;i++){nw.add(node.children[i]) } node.children=[nw] } this.transformed=true } this.to_js=function(){this.js_processed=true var res='var $ctx_manager='+this.tree[0].to_js() var scope=$get_scope(this) res +='\nvar $ctx_manager_exit = getattr($ctx_manager,"__exit__")\n' if(this.tree[0].alias){var alias=this.tree[0].alias res +=';$locals_'+scope.id.replace(/\./g,'_') res +='["'+alias+'"]=' } return res + 'getattr($ctx_manager,"__enter__")()\ntry' }} function $YieldCtx(C){ this.type='yield' this.toString=function(){return '(yield) '+this.tree} this.parent=C this.tree=[] C.tree[C.tree.length]=this switch(C.type){case 'node': break case 'assign': case 'tuple': case 'list_or_tuple': var ctx=C while(ctx.parent)ctx=ctx.parent ctx.node.yield_atoms.push(this) break default: $_SyntaxError(C,'yield atom must be inside ()') } var scope=$get_scope(this) if(!scope.is_function){$_SyntaxError(C,["'yield' outside function"]) }else if(scope.has_return_with_arguments){$_SyntaxError(C,["'return' with argument inside generator"]) } var def=scope.C.tree[0] def.type='generator' def.yields.push(this) this.toString=function(){return '(yield) '+(this.from ? '(from) ' : '')+this.tree} this.transform=function(node,rank){if(this.from===true){ var new_node=new $Node() node.parent.children.splice(rank,1) node.parent.insert(rank,new_node) var for_ctx=new $ForExpr(new $NodeCtx(new_node)) new $IdCtx(new $ExprCtx(for_ctx,'id',false),'$temp'+$loop_num) for_ctx.tree[1]=this.tree[0] this.tree[0].parent=for_ctx var yield_node=new $Node() new_node.add(yield_node) new $IdCtx(new $YieldCtx(new $NodeCtx(yield_node)),'$temp'+$loop_num) var ph_node=new $Node() new $NodeJSCtx(ph_node,'// placeholder for generator sent value') ph_node.set_yield_value=true new_node.add(ph_node) for_ctx.transform(new_node,rank) $loop_num++ }else{var new_node=new $Node() new $NodeJSCtx(new_node,'// placeholder for generator sent value') new_node.set_yield_value=true node.parent.insert(rank+1,new_node) }} this.to_js=function(){this.js_processed=true if(this.from===undefined)return $to_js(this.tree)||'None' return $to_js(this.tree) }} function $add_line_num(node,rank){if(node.type==='module'){var i=0 while(i<node.children.length){i +=$add_line_num(node.children[i],i) }}else{var elt=node.C.tree[0],offset=1 var flag=true var pnode=node while(pnode.parent!==undefined){pnode=pnode.parent} var mod_id=pnode.id if(node.line_num===undefined){flag=false} if(elt.type==='condition' && elt.token==='elif'){flag=false} else if(elt.type==='except'){flag=false} else if(elt.type==='single_kw'){flag=false} if(flag){ var js=';$B.line_info="'+node.line_num+','+mod_id+'";' var new_node=new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank,new_node) offset=2 } var i=0 while(i<node.children.length)i+=$add_line_num(node.children[i],i) return offset }} function $clear_ns(ctx){ var scope=$get_scope(ctx) if(scope.is_function){if(scope.var2node){for(var name in scope.var2node){var remove=[],pos=0 for(var j=0;j<scope.var2node[name].length;j++){var elt=scope.var2node[name][j].parent while(elt.parent){if(elt===ctx){remove[pos++]=j;break} elt=elt.parent }} for(var k=remove.length-1;k>=0;k--){scope.var2node[name].splice(remove[k],1) }}}}} function $get_docstring(node){var doc_string='' if(node.children.length>0){var firstchild=node.children[0] if(firstchild.C.tree && firstchild.C.tree[0].type=='expr'){if(firstchild.C.tree[0].tree[0].type=='str') doc_string=firstchild.C.tree[0].tree[0].to_js() }} return doc_string } function $get_scope(C){ var ctx_node=C.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var scope=null while(tree_node.parent && tree_node.parent.type!=='module'){var ntype=tree_node.parent.C.tree[0].type switch(ntype){case 'def': case 'class': case 'generator': var scope=tree_node.parent scope.ntype=ntype scope.elt=scope.C.tree[0] scope.is_function=ntype!='class' return scope } tree_node=tree_node.parent } var scope=tree_node.parent ||tree_node scope.ntype="module" scope.elt=scope.module return scope } function $get_module(C){ var ctx_node=C.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node=ctx_node.node var scope=null while(tree_node.parent.type!=='module'){tree_node=tree_node.parent } var scope=tree_node.parent scope.ntype="module" return scope } function $get_node(C){var ctx=C while(ctx.parent){ctx=ctx.parent} return ctx.node } function $ws(n){return ' '.repeat(n) } function $to_js_map(tree_element){if(tree_element.to_js !==undefined)return tree_element.to_js() throw Error('no to_js() for '+tree_element) } function $to_js(tree,sep){if(sep===undefined){sep=','} return tree.map($to_js_map).join(sep) } var $expr_starters=['id','imaginary','int','float','str','bytes','[','(','{','not','lambda'] function $arbo(ctx){while(ctx.parent!=undefined){ctx=ctx.parent} return ctx } function $transition(C,token){ switch(C.type){case 'abstract_expr': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': case 'yield': C.parent.tree.pop() var commas=C.with_commas C=C.parent } switch(token){case 'id': return new $IdCtx(new $ExprCtx(C,'id',commas),arguments[2]) case 'str': return new $StringCtx(new $ExprCtx(C,'str',commas),arguments[2]) case 'bytes': return new $StringCtx(new $ExprCtx(C,'bytes',commas),arguments[2]) case 'int': return new $IntCtx(new $ExprCtx(C,'int',commas),arguments[2]) case 'float': return new $FloatCtx(new $ExprCtx(C,'float',commas),arguments[2]) case 'imaginary': return new $ImaginaryCtx(new $ExprCtx(C,'imaginary',commas),arguments[2]) case '(': return new $ListOrTupleCtx(new $ExprCtx(C,'tuple',commas),'tuple') case '[': return new $ListOrTupleCtx(new $ExprCtx(C,'list',commas),'list') case '{': return new $DictOrSetCtx(new $ExprCtx(C,'dict_or_set',commas)) case '.': return new $EllipsisCtx(new $ExprCtx(C,'ellipsis',commas)) case 'not': if(C.type==='op'&&C.op==='is'){ C.op='is_not' return C } return new $NotCtx(new $ExprCtx(C,'not',commas)) case 'lambda': return new $LambdaCtx(new $ExprCtx(C,'lambda',commas)) case 'op': var tg=arguments[2] switch(tg){case '+': return C case '*': C.parent.tree.pop() var commas=C.with_commas C=C.parent return new $PackedCtx(new $ExprCtx(C,'expr',commas)) case '-': case '~': C.parent.tree.pop() var left=new $UnaryCtx(C.parent,tg) if(tg=='-'){var op_expr=new $OpCtx(left,'unary_neg')} else{var op_expr=new $OpCtx(left,'unary_inv')} return new $AbstractExprCtx(op_expr,false) } $_SyntaxError(C,'token '+token+' after '+C) case '=': $_SyntaxError(C,token) case 'yield': return new $AbstractExprCtx(new $YieldCtx(C),false) case ':': return $transition(C.parent,token,arguments[2]) case ')': case ',': switch(C.parent.type){case 'list_or_tuple': case 'call_arg': case 'op': case 'yield': break default: $_SyntaxError(C,token) } } return $transition(C.parent,token,arguments[2]) case 'assert': if(token==='eol')return $transition(C.parent,token) $_SyntaxError(C,token) case 'assign': if(token==='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+C) } return $transition(C.parent,'eol') } $_SyntaxError(C,'token '+token+' after '+C) case 'attribute': if(token==='id'){var name=arguments[2] if(noassign[name]===true){$_SyntaxError(C,["cannot assign to "+name])} C.name=name return C.parent } $_SyntaxError(C,token) case 'augm_assign': if(token==='eol'){if(C.tree[1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+C) } return $transition(C.parent,'eol') } $_SyntaxError(C,'token '+token+' after '+C) case 'break': if(token==='eol')return $transition(C.parent,'eol') $_SyntaxError(C,token) case 'call': switch(token){case ',': if(C.expect=='id'){$_SyntaxError(C,token)} return C case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': if(C.has_dstar)$_SyntaxError(C,token) C.expect=',' return $transition(new $CallArgCtx(C),token,arguments[2]) case ')': C.end=$pos return C.parent case 'op': C.expect=',' switch(arguments[2]){case '-': case '~': C.expect=',' return $transition(new $CallArgCtx(C),token,arguments[2]) case '+': return C case '*': C.has_star=true return new $StarArgCtx(C) case '**': C.has_dstar=true return new $DoubleStarArgCtx(C) } throw Error('SyntaxError') } return $transition(C.parent,token,arguments[2]) case 'call_arg': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': if(C.expect==='id'){C.expect=',' var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) } break case '=': if(C.expect===','){return new $ExprCtx(new $KwArgCtx(C),'kw_value',false) } break case 'for': $clear_ns(C) var lst=new $ListOrTupleCtx(C,'gen_expr') lst.vars=C.vars lst.locals=C.locals lst.intervals=[C.start] C.tree.pop() lst.expression=C.tree C.tree=[lst] lst.tree=[] var comp=new $ComprehensionCtx(lst) return new $TargetListCtx(new $CompForCtx(comp)) case 'op': if(C.expect==='id'){var op=arguments[2] C.expect=',' switch(op){case '+': case '-': return $transition(new $AbstractExprCtx(C,false),token,op) case '*': return new $StarArgCtx(C) case '**': return new $DoubleStarArgCtx(C) } } $_SyntaxError(C,'token '+token+' after '+C) case ')': if(C.parent.kwargs && $B.last(C.parent.tree).tree[0]&& ['kwarg','double_star_arg'].indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword arg after keyword arg']) } if(C.tree.length>0){var son=C.tree[C.tree.length-1] if(son.type==='list_or_tuple'&&son.real==='gen_expr'){son.intervals.push($pos) }} return $transition(C.parent,token) case ':': if(C.expect===',' && C.parent.parent.type==='lambda'){return $transition(C.parent.parent,token) } break case ',': if(C.expect===','){if(C.parent.kwargs && ['kwarg','double_star_arg'].indexOf($B.last(C.parent.tree).tree[0].type)==-1){$_SyntaxError(C,['non-keyword arg after keyword arg']) } return new $CallArgCtx(C.parent) } console.log('C '+C+'token '+token+' expect '+C.expect) } $_SyntaxError(C,'token '+token+' after '+C) case 'class': switch(token){case 'id': if(C.expect==='id'){C.set_name(arguments[2]) C.expect='(:' return C } break case '(': return new $CallCtx(C) case ':': return $BodyCtx(C) } $_SyntaxError(C,'token '+token+' after '+C) case 'comp_if': return $transition(C.parent,token,arguments[2]) case 'comp_for': if(token==='in' && C.expect==='in'){C.expect=null return new $AbstractExprCtx(new $CompIterableCtx(C),true) } if(C.expect===null){ return $transition(C.parent,token,arguments[2]) } $_SyntaxError(C,'token '+token+' after '+C) case 'comp_iterable': return $transition(C.parent,token,arguments[2]) case 'comprehension': switch(token){case 'if': return new $AbstractExprCtx(new $CompIfCtx(C),false) case 'for': return new $TargetListCtx(new $CompForCtx(C)) } return $transition(C.parent,token,arguments[2]) case 'condition': if(token===':')return $BodyCtx(C) $_SyntaxError(C,'token '+token+' after '+C) case 'continue': if(token=='eol')return C.parent $_SyntaxError(C,'token '+token+' after '+C) case 'decorator': if(token==='id' && C.tree.length===0){return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) } if(token==='eol')return $transition(C.parent,token) $_SyntaxError(C,'token '+token+' after '+C) case 'def': switch(token){case 'id': if(C.name){$_SyntaxError(C,'token '+token+' after '+C) } C.set_name(arguments[2]) return C case '(': if(C.name===null){$_SyntaxError(C,'token '+token+' after '+C) } C.has_args=true return new $FuncArgs(C) case ':': if(C.has_args)return $BodyCtx(C) } $_SyntaxError(C,'token '+token+' after '+C) case 'del': if(token==='eol')return $transition(C.parent,token) $_SyntaxError(C,'token '+token+' after '+C) case 'dict_or_set': if(C.closed){switch(token){case '[': return new $SubCtx(C.parent) case '(': return new $CallArgCtx(new $CallCtx(C)) case 'op': return new $AbstractExprCtx(new $OpCtx(C,arguments[2]),false) } return $transition(C.parent,token,arguments[2]) }else{if(C.expect===','){switch(token){case '}': switch(C.real){case 'dict_or_set': if(C.tree.length !==1)break C.real='set' case 'set': case 'set_comp': case 'dict_comp': C.items=C.tree C.tree=[] C.closed=true return C case 'dict': if(C.tree.length%2===0){C.items=C.tree C.tree=[] C.closed=true return C }} $_SyntaxError(C,'token '+token+' after '+C) case ',': if(C.real==='dict_or_set'){C.real='set'} if(C.real==='dict' && C.tree.length%2){$_SyntaxError(C,'token '+token+' after '+C) } C.expect='id' return C case ':': if(C.real==='dict_or_set'){C.real='dict'} if(C.real==='dict'){C.expect=',' return new $AbstractExprCtx(C,false) }else{$_SyntaxError(C,'token '+token+' after '+C)} case 'for': $clear_ns(C) if(C.real==='dict_or_set'){C.real='set_comp'} else{C.real='dict_comp'} var lst=new $ListOrTupleCtx(C,'dict_or_set_comp') lst.intervals=[C.start+1] lst.vars=C.vars C.tree.pop() lst.expression=C.tree C.tree=[lst] lst.tree=[] var comp=new $ComprehensionCtx(lst) return new $TargetListCtx(new $CompForCtx(comp)) } $_SyntaxError(C,'token '+token+' after '+C) }else if(C.expect==='id'){switch(token){case '}': if(C.tree.length==0){ C.items=[] C.real='dict' }else{ C.items=C.tree } C.tree=[] C.closed=true return C case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': C.expect=',' var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) case 'op': switch(arguments[2]){case '+': return C case '-': case '~': C.expect=',' var left=new $UnaryCtx(C,arguments[2]) if(arguments[2]=='-'){var op_expr=new $OpCtx(left,'unary_neg')} else{var op_expr=new $OpCtx(left,'unary_inv')} return new $AbstractExprCtx(op_expr,false) } $_SyntaxError(C,'token '+token+' after '+C) } $_SyntaxError(C,'token '+token+' after '+C) } return $transition(C.parent,token,arguments[2]) } break case 'double_star_arg': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) case ',': return C.parent case ')': return $transition(C.parent,token) case ':': if(C.parent.parent.type==='lambda'){return $transition(C.parent.parent,token) }} $_SyntaxError(C,'token '+token+' after '+C) case 'ellipsis': if(token=='.'){C.nbdots++;return C} else{if(C.nbdots!=3){$pos--;$_SyntaxError(C,'token '+token+' after '+C) }else{return $transition(C.parent,token,arguments[2]) }} case 'except': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': if(C.expect==='id'){C.expect='as' return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) } case 'as': if(C.expect==='as' && C.has_alias===undefined){C.expect='alias' C.has_alias=true return C } case 'id': if(C.expect==='alias'){C.expect=':' C.set_alias(arguments[2]) return C } break case ':': var _ce=C.expect if(_ce=='id' ||_ce=='as' ||_ce==':'){return $BodyCtx(C) } break case '(': if(C.expect==='id' && C.tree.length===0){C.parenth=true return C } break case ')': if(C.expect==',' ||C.expect=='as'){C.expect='as' return C } case ',': if(C.parenth!==undefined && C.has_alias===undefined && (C.expect=='as' ||C.expect==',')){C.expect='id' return C }} $_SyntaxError(C,'token '+token+' after '+C.expect) case 'expr': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': if(C.expect==='expr'){C.expect=',' return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) }} switch(token){case 'not': if(C.expect===',')return new $ExprNot(C) break case 'in': if(C.expect===',')return $transition(C,'op','in') break case ',': if(C.expect===','){if(C.with_commas){ C.parent.tree.pop() var tuple=new $ListOrTupleCtx(C.parent,'tuple') tuple.implicit=true tuple.has_comma=true tuple.tree=[C] C.parent=tuple return tuple }} return $transition(C.parent,token) case '.': return new $AttrCtx(C) case '[': return new $AbstractExprCtx(new $SubCtx(C),true) case '(': return new $CallCtx(C) case 'op': var op_parent=C.parent,op=arguments[2] if(op_parent.type=='ternary' && op_parent.in_else){var new_op=new $OpCtx(C,op) return new $AbstractExprCtx(new_op,false) } var op1=C.parent,repl=null while(1){if(op1.type==='expr'){op1=op1.parent} else if(op1.type==='op'&&$op_weight[op1.op]>=$op_weight[op]){repl=op1;op1=op1.parent} else{break}} if(repl===null){if(op==='and' ||op==='or'){while(C.parent.type==='not'|| (C.parent.type==='expr'&&C.parent.parent.type==='not')){ C=C.parent op_parent=C.parent }}else{while(1){if(C.parent!==op1){C=C.parent op_parent=C.parent }else{break }}} C.parent.tree.pop() var expr=new $ExprCtx(op_parent,'operand',C.with_commas) expr.expect=',' C.parent=expr var new_op=new $OpCtx(C,op) return new $AbstractExprCtx(new_op,false) } if(repl.type==='op'){var _flag=false switch(repl.op){case '<': case '<=': case '==': case '!=': case 'is': case '>=': case '>': _flag=true } if(_flag){switch(op){case '<': case '<=': case '==': case '!=': case 'is': case '>=': case '>': var c2=repl.tree[1] var c2_clone=new Object() for(var attr in c2){c2_clone[attr]=c2[attr]} while(repl.parent && repl.parent.type=='op'){if($op_weight[repl.parent.op]<$op_weight[repl.op]){repl=repl.parent }else{break}} repl.parent.tree.pop() var and_expr=new $OpCtx(repl,'and') c2_clone.parent=and_expr and_expr.tree.push('xxx') var new_op=new $OpCtx(c2_clone,op) return new $AbstractExprCtx(new_op,false) } } } repl.parent.tree.pop() var expr=new $ExprCtx(repl.parent,'operand',false) expr.tree=[op1] repl.parent=expr var new_op=new $OpCtx(repl,op) return new $AbstractExprCtx(new_op,false) case 'augm_assign': if(C.expect===','){return new $AbstractExprCtx(new $AugmentedAssignCtx(C,arguments[2])) } break case '=': if(C.expect===','){if(C.parent.type==="call_arg"){return new $AbstractExprCtx(new $KwArgCtx(C),true) } while(C.parent!==undefined)C=C.parent C=C.tree[0] return new $AbstractExprCtx(new $AssignCtx(C),true) } break case 'if': if(C.parent.type!=='comp_iterable'){ var ctx=C while(ctx.parent && ctx.parent.type=='op'){ctx=ctx.parent if(ctx.type=='expr' && ctx.parent && ctx.parent.type=='op'){ctx=ctx.parent }} return new $AbstractExprCtx(new $TernaryCtx(ctx),false) }} return $transition(C.parent,token) case 'expr_not': if(token==='in'){ C.parent.tree.pop() return new $AbstractExprCtx(new $OpCtx(C.parent,'not_in'),false) } $_SyntaxError(C,'token '+token+' after '+C) case 'for': switch(token){case 'in': return new $AbstractExprCtx(new $ExprCtx(C,'target list',true),false) case ':': return $BodyCtx(C) } $_SyntaxError(C,'token '+token+' after '+C) case 'from': switch(token){case 'id': if(C.expect==='id'){C.add_name(arguments[2]) C.expect=',' return C } if(C.expect==='alias'){C.aliases[C.names[C.names.length-1]]=arguments[2] C.expect=',' return C } case '.': if(C.expect==='module'){if(token==='id'){C.module +=arguments[2]} else{C.module +='.'} return C } case 'import': if(C.expect==='module'){C.expect='id' return C } case 'op': if(arguments[2]==='*' && C.expect==='id' && C.names.length===0){if($get_scope(C).ntype!=='module'){$_SyntaxError(C,["import * only allowed at module level"]) } C.add_name('*') C.expect='eol' return C } case ',': if(C.expect===','){C.expect='id' return C } case 'eol': switch(C.expect){case ',': case 'eol': C.bind_names() return $transition(C.parent,token) } case 'as': if(C.expect===',' ||C.expect==='eol'){C.expect='alias' return C } case '(': if(C.expect==='id'){C.expect='id' return C } case ')': if(C.expect===','){C.expect='eol' return C }} $_SyntaxError(C,'token '+token+' after '+C) case 'func_arg_id': switch(token){case '=': if(C.expect==='='){C.parent.has_default=true var def_ctx=C.parent.parent if(C.parent.has_star_arg){def_ctx.default_list.push(def_ctx.after_star.pop()) }else{def_ctx.default_list.push(def_ctx.positional_list.pop()) } return new $AbstractExprCtx(C,false) } break case ',': case ')': if(C.parent.has_default && C.tree.length==0 && C.parent.has_star_arg===undefined){console.log('parent '+C.parent,C.parent) $pos -=C.name.length $_SyntaxError(C,['non-default argument follows default argument']) }else{return $transition(C.parent,token) }} $_SyntaxError(C,'token '+token+' after '+C) case 'func_args': switch(token){case 'id': if(C.expect==='id'){C.expect=',' if(C.names.indexOf(arguments[2])>-1){$_SyntaxError(C,['duplicate argument '+arguments[2]+' in function definition']) }} return new $FuncArgIdCtx(C,arguments[2]) case ',': if(C.has_kw_arg)$_SyntaxError(C,'duplicate kw arg') if(C.expect===','){C.expect='id' return C } $_SyntaxError(C,'token '+token+' after '+C) case ')': return C.parent case 'op': var op=arguments[2] C.expect=',' if(op=='*'){if(C.has_star_arg){$_SyntaxError(C,'duplicate star arg')} return new $FuncStarArgCtx(C,'*') } if(op=='**')return new $FuncStarArgCtx(C,'**') $_SyntaxError(C,'token '+op+' after '+C) } $_SyntaxError(C,'token '+token+' after '+C) case 'func_star_arg': switch(token){case 'id': if(C.name===undefined){if(C.parent.names.indexOf(arguments[2])>-1){$_SyntaxError(C,['duplicate argument '+arguments[2]+' in function definition']) }} C.set_name(arguments[2]) C.parent.names.push(arguments[2]) return C.parent case ',': if(C.name===undefined){ C.set_name('$dummy') C.parent.names.push('$dummy') return $transition(C.parent,token) } break case ')': C.set_name('$dummy') C.parent.names.push('$dummy') return $transition(C.parent,token) } $_SyntaxError(C,'token '+token+' after '+C) case 'global': switch(token){case 'id': if(C.expect==='id'){new $IdCtx(C,arguments[2]) C.add(arguments[2]) C.expect=',' return C } break case ',': if(C.expect===','){C.expect='id' return C } break case 'eol': if(C.expect===','){return $transition(C.parent,token) } break } $_SyntaxError(C,'token '+token+' after '+C) case 'id': switch(token){case '=': if(C.parent.type==='expr' && C.parent.parent !==undefined && C.parent.parent.type==='call_arg'){return new $AbstractExprCtx(new $KwArgCtx(C.parent),false) } return $transition(C.parent,token,arguments[2]) case 'op': return $transition(C.parent,token,arguments[2]) case 'id': case 'str': case 'int': case 'float': case 'imaginary': $_SyntaxError(C,'token '+token+' after '+C) } return $transition(C.parent,token,arguments[2]) case 'import': switch(token){case 'id': if(C.expect==='id'){new $ImportedModuleCtx(C,arguments[2]) C.expect=',' return C } if(C.expect==='qual'){C.expect=',' C.tree[C.tree.length-1].name +='.'+arguments[2] C.tree[C.tree.length-1].alias +='.'+arguments[2] return C } if(C.expect==='alias'){C.expect=',' C.tree[C.tree.length-1].alias=arguments[2] return C } break case '.': if(C.expect===','){C.expect='qual' return C } break case ',': if(C.expect===','){C.expect='id' return C } break case 'as': if(C.expect===','){C.expect='alias' return C } break case 'eol': if(C.expect===','){C.bind_names() return $transition(C.parent,token) } break } $_SyntaxError(C,'token '+token+' after '+C) case 'imaginary': case 'int': case 'float': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': $_SyntaxError(C,'token '+token+' after '+C) } return $transition(C.parent,token,arguments[2]) case 'kwarg': if(token===',')return new $CallArgCtx(C.parent.parent) return $transition(C.parent,token) case 'lambda': if(token===':' && C.args===undefined){C.args=C.tree C.tree=[] C.body_start=$pos return new $AbstractExprCtx(C,false) } if(C.args!==undefined){ C.body_end=$pos return $transition(C.parent,token) } if(C.args===undefined){return $transition(new $CallCtx(C),token,arguments[2]) } $_SyntaxError(C,'token '+token+' after '+C) case 'list_or_tuple': if(C.closed){if(token==='[')return new $SubCtx(C.parent) if(token==='(')return new $CallCtx(C) return $transition(C.parent,token,arguments[2]) }else{if(C.expect===','){switch(C.real){case 'tuple': case 'gen_expr': if(token===')'){C.closed=true if(C.real==='gen_expr'){C.intervals.push($pos)} return C.parent } break case 'list': case 'list_comp': if(token===']'){C.closed=true if(C.real==='list_comp'){C.intervals.push($pos)} return C } break case 'dict_or_set_comp': if(token==='}'){C.intervals.push($pos) return $transition(C.parent,token) } break } switch(token){case ',': if(C.real==='tuple'){C.has_comma=true} C.expect='id' return C case 'for': if(C.real==='list'){C.real='list_comp'} else{C.real='gen_expr'} $clear_ns(C) C.intervals=[C.start+1] C.expression=C.tree C.tree=[] var comp=new $ComprehensionCtx(C) return new $TargetListCtx(new $CompForCtx(comp)) } return $transition(C.parent,token,arguments[2]) }else if(C.expect==='id'){switch(C.real){case 'tuple': if(token===')'){C.closed=true return C.parent } if(token=='eol' && C.implicit===true){C.closed=true return $transition(C.parent,token) } break case 'gen_expr': if(token===')'){C.closed=true return $transition(C.parent,token) } break case 'list': if(token===']'){C.closed=true return C } break } switch(token){case '=': if(C.real=='tuple' && C.implicit===true){C.closed=true C.parent.tree.pop() var expr=new $ExprCtx(C.parent,'tuple',false) expr.tree=[C] C.parent=expr return $transition(C.parent,token) } break case ')': case ']': break case ',': $_SyntaxError(C,'unexpected comma inside list') default: C.expect=',' var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) } }else{return $transition(C.parent,token,arguments[2])}} case 'list_comp': switch(token){case ']': return C.parent case 'in': return new $ExprCtx(C,'iterable',true) case 'if': return new $ExprCtx(C,'condition',true) } $_SyntaxError(C,'token '+token+' after '+C) case 'node': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': case '.': var expr=new $AbstractExprCtx(C,true) return $transition(expr,token,arguments[2]) case 'op': switch(arguments[2]){case '*': case '+': case '-': case '~': var expr=new $AbstractExprCtx(C,true) return $transition(expr,token,arguments[2]) } break case 'class': return new $ClassCtx(C) case 'continue': return new $ContinueCtx(C) case 'break': return new $BreakCtx(C) case 'def': return new $DefCtx(C) case 'for': return new $TargetListCtx(new $ForExpr(C)) case 'if': case 'elif': case 'while': return new $AbstractExprCtx(new $ConditionCtx(C,token),false) case 'else': case 'finally': return new $SingleKwCtx(C,token) case 'try': return new $TryCtx(C) case 'except': return new $ExceptCtx(C) case 'assert': return new $AbstractExprCtx(new $AssertCtx(C),'assert',true) case 'from': return new $FromCtx(C) case 'import': return new $ImportCtx(C) case 'global': return new $GlobalCtx(C) case 'nonlocal': return new $NonlocalCtx(C) case 'lambda': return new $LambdaCtx(C) case 'pass': return new $PassCtx(C) case 'raise': return new $RaiseCtx(C) case 'return': return new $AbstractExprCtx(new $ReturnCtx(C),true) case 'with': return new $AbstractExprCtx(new $WithCtx(C),false) case 'yield': return new $AbstractExprCtx(new $YieldCtx(C),true) case 'del': return new $AbstractExprCtx(new $DelCtx(C),true) case '@': return new $DecoratorCtx(C) case 'eol': if(C.tree.length===0){ C.node.parent.children.pop() return C.node.parent.C } return C } $_SyntaxError(C,'token '+token+' after '+C) case 'not': switch(token){case 'in': C.parent.parent.tree.pop() return new $ExprCtx(new $OpCtx(C.parent,'not_in'),'op',false) case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) case 'op': var a=arguments[2] if('+'==a ||'-'==a ||'~'==a){var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) }} return $transition(C.parent,token) case 'op': if(C.op===undefined){$_SyntaxError(C,['C op undefined '+C]) } if(C.op.substr(0,5)=='unary'){if(C.parent.type=='assign' ||C.parent.type=='return'){ C.parent.tree.pop() var t=new $ListOrTupleCtx(C.parent,'tuple') t.tree.push(C) C.parent=t return t }} switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) case 'op': switch(arguments[2]){case '+': case '-': case '~': return new $UnaryCtx(C,arguments[2]) } default: if(C.tree[C.tree.length-1].type=='abstract_expr'){$_SyntaxError(C,'token '+token+' after '+C) }} return $transition(C.parent,token) case 'packed': if(token==='id')new $IdCtx(C,arguments[2]);return C.parent $_SyntaxError(C,'token '+token+' after '+C) case 'pass': if(token==='eol')return C.parent $_SyntaxError(C,'token '+token+' after '+C) case 'raise': switch(token){case 'id': if(C.tree.length===0){return new $IdCtx(new $ExprCtx(C,'exc',false),arguments[2]) } break case 'from': if(C.tree.length>0){return new $AbstractExprCtx(C,false) } break case 'eol': return $transition(C.parent,token) } $_SyntaxError(C,'token '+token+' after '+C) case 'return': var no_args=C.tree[0].type=='abstract_expr' if(!no_args){var scope=$get_scope(C) if(scope.ntype=='generator'){$_SyntaxError(C,["'return' with argument inside generator"]) } scope.has_return_with_arguments=true } return $transition(C.parent,token) case 'single_kw': if(token===':')return $BodyCtx(C) $_SyntaxError(C,'token '+token+' after '+C) case 'star_arg': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) case ',': return $transition(C.parent,token) case ')': return $transition(C.parent,token) case ':': if(C.parent.parent.type==='lambda'){return $transition(C.parent.parent,token) }} $_SyntaxError(C,'token '+token+' after '+C) case 'str': switch(token){case '[': return new $AbstractExprCtx(new $SubCtx(C.parent),false) case '(': return new $CallCtx(C) case 'str': C.tree.push(arguments[2]) return C } return $transition(C.parent,token,arguments[2]) case 'sub': switch(token){case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': var expr=new $AbstractExprCtx(C,false) return $transition(expr,token,arguments[2]) case ']': return C.parent case ':': if(C.tree.length==0){new $AbstractExprCtx(C,false) } return new $AbstractExprCtx(C,false) } $_SyntaxError(C,'token '+token+' after '+C) case 'target_list': switch(token){case 'id': if(C.expect==='id'){C.expect=',' new $IdCtx(C,arguments[2]) return C } case '(': case '[': if(C.expect==='id'){C.expect=',' return new $TargetListCtx(C) } case ')': case ']': if(C.expect===',')return C.parent case ',': if(C.expect==','){C.expect='id' return C }} if(C.expect===',')return $transition(C.parent,token,arguments[2]) $_SyntaxError(C,'token '+token+' after '+C) case 'ternary': if(token==='else'){C.in_else=true return new $AbstractExprCtx(C,false) } return $transition(C.parent,token,arguments[2]) case 'try': if(token===':')return $BodyCtx(C) $_SyntaxError(C,'token '+token+' after '+C) case 'unary': switch(token){case 'int': case 'float': case 'imaginary': var expr=C.parent C.parent.parent.tree.pop() var value=arguments[2] if(C.op==='-'){value="-"+value} else if(C.op==='~'){value=~value} return $transition(C.parent.parent,token,value) case 'id': C.parent.parent.tree.pop() var expr=new $ExprCtx(C.parent.parent,'call',false) var expr1=new $ExprCtx(expr,'id',false) new $IdCtx(expr1,arguments[2]) if(C.op !=='+'){var repl=new $AttrCtx(expr) if(C.op==='-'){repl.name='__neg__'} else{repl.name='__invert__'} var call=new $CallCtx(expr) return expr1 } return C.parent case 'op': if('+'==arguments[2]||'-'==arguments[2]){var op=arguments[2] if(C.op===op){C.op='+'}else{C.op='-'} return C }} return $transition(C.parent,token,arguments[2]) case 'with': switch(token){case 'id': if(C.expect==='id'){C.expect='as' return $transition(new $AbstractExprCtx(C,false),token,arguments[2]) } if(C.expect==='alias'){if(C.parenth!==undefined){C.expect=','} else{C.expect=':'} C.set_alias(arguments[2]) return C } break case 'as': if(C.expect==='as'){ C.expect='alias' C.has_alias=true return C } break case ':': switch(C.expect){case 'id': case 'as': case ':': return $BodyCtx(C) } break case '(': if(C.expect==='id' && C.tree.length===0){C.parenth=true return C }else if(C.expect=='alias'){C.expect=':' return $transition(new $AbstractExprCtx(C,false),token) } break case ')': if(C.expect==',' ||C.expect=='as'){C.expect=':' return C } break case ',': if(C.parenth!==undefined && C.has_alias===undefined && (C.expect==',' ||C.expect=='as')){C.expect='id' return C }else if(C.expect==':'){C.expect='id' return C } break } $_SyntaxError(C,'token '+token+' after '+C.expect) case 'yield': if(token=='from'){ if(C.tree[0].type!='abstract_expr'){ $_SyntaxError(C,"'from' must follow 'yield'") } C.from=true C.tree=[] return new $AbstractExprCtx(C,true) } return $transition(C.parent,token) } } $B.forbidden=['super','case','catch','constructor','Date','delete','default','Error','history','function','location','Math','new','null','Number','RegExp','this','throw','var','toString'] var s_escaped='abfnrtvxuU"'+"'"+'\\',is_escaped={} for(var i=0;i<s_escaped.length;i++){is_escaped[s_escaped.charAt(i)]=true} function $tokenize(src,module,locals_id,parent_block_id,line_info){var delimiters=[["#","\n","comment"],['"""','"""',"triple_string"],["'","'","string"],['"','"',"string"],["r'","'","raw_string"],['r"','"',"raw_string"]] var br_open={"(":0,"[":0,"{":0} var br_close={")":"(","]":"[","}":"{"} var br_stack="" var br_pos=[] var kwdict=["class","return","break","for","lambda","try","finally","raise","def","from","nonlocal","while","del","global","with","as","elif","else","if","yield","assert","import","except","raise","in","not","pass","with","continue" ] var unsupported=[] var $indented=['class','def','for','condition','single_kw','try','except','with'] var punctuation={',':0,':':0} var int_pattern=new RegExp("^\\d+(j|J)?") var float_pattern1=new RegExp("^\\d+\\.\\d*([eE][+-]?\\d+)?(j|J)?") var float_pattern2=new RegExp("^\\d+([eE][+-]?\\d+)(j|J)?") var hex_pattern=new RegExp("^0[xX]([0-9a-fA-F]+)") var octal_pattern=new RegExp("^0[oO]([0-7]+)") var binary_pattern=new RegExp("^0[bB]([01]+)") var id_pattern=new RegExp("[\\$_a-zA-Z]\\w*") var qesc=new RegExp('"',"g") var sqesc=new RegExp("'","g") var C=null var root=new $Node('module') root.module=module root.id=locals_id $B.modules[root.id]=root $B.$py_src[locals_id]=src if(locals_id==parent_block_id){root.parent_block=$B.modules[parent_block_id].parent_block ||$B.modules['__builtins__'] }else{root.parent_block=$B.modules[parent_block_id] } root.line_info=line_info root.indent=-1 if(locals_id!==module){$B.bound[locals_id]={}} var new_node=new $Node() var current=root var name="" var _type=null var pos=0 indent=null var lnum=1 while(pos<src.length){var flag=false var car=src.charAt(pos) if(indent===null){var indent=0 while(pos<src.length){var _s=src.charAt(pos) if(_s==" "){indent++;pos++} else if(_s=="\t"){ indent++;pos++ if(indent%8>0)indent+=8-indent%8 }else{break}} var _s=src.charAt(pos) if(_s=='\n'){pos++;lnum++;indent=null;continue} else if(_s==='#'){ var offset=src.substr(pos).search(/\n/) if(offset===-1){break} pos+=offset+1;lnum++;indent=null;continue } new_node.indent=indent new_node.line_num=lnum new_node.module=module if(indent>current.indent){ if(C!==null){if($indented.indexOf(C.tree[0].type)==-1){$pos=pos $_SyntaxError(C,'unexpected indent1',pos) }} current.add(new_node) }else if(indent<=current.indent && $indented.indexOf(C.tree[0].type)>-1 && C.tree.length<2){$pos=pos $_SyntaxError(C,'expected an indented block',pos) }else{ while(indent!==current.indent){current=current.parent if(current===undefined ||indent>current.indent){$pos=pos $_SyntaxError(C,'unexpected indent2',pos) }} current.parent.add(new_node) } current=new_node C=new $NodeCtx(new_node) continue } if(car=="#"){var end=src.substr(pos+1).search('\n') if(end==-1){end=src.length-1} pos +=end+1;continue } if(car=='"' ||car=="'"){var raw=C.type=='str' && C.raw,bytes=false ,end=null if(name.length>0){switch(name.toLowerCase()){case 'r': raw=true;name='' break case 'u': name='' break case 'b': bytes=true;name='' break case 'rb': case 'br': bytes=true;raw=true;name='' break }} if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3} else{_type="string";end=pos+1} var escaped=false var zone=car var found=false while(end<src.length){if(escaped){zone+=src.charAt(end) if(raw && src.charAt(end)=='\\'){zone+='\\'} escaped=false;end+=1 }else if(src.charAt(end)=="\\"){if(raw){if(end<src.length-1 && src.charAt(end+1)==car){zone +='\\\\'+car end +=2 }else{zone +='\\\\' end++ } escaped=true }else{ if(src.charAt(end+1)=='\n'){ end +=2 lnum++ }else{ if(end < src.length-1 && is_escaped[src.charAt(end+1)]==undefined){zone +='\\' } zone+='\\' escaped=true;end+=1 }}}else if(src.charAt(end)==car){if(_type=="triple_string" && src.substr(end,3)!=car+car+car){zone +=src.charAt(end) end++ }else{ found=true $pos=pos var $string=zone.substr(1),string='' for(var i=0;i<$string.length;i++){var $car=$string.charAt(i) if($car==car && (raw ||(i==0 ||$string.charAt(i-1)!=='\\'))){string +='\\' } string +=$car } if(bytes){C=$transition(C,'str','b'+car+string+car) }else{C=$transition(C,'str',car+string+car) } C.raw=raw pos=end+1 if(_type=="triple_string"){pos=end+3} break }}else{ zone +=src.charAt(end) if(src.charAt(end)=='\n'){lnum++} end++ }} if(!found){if(_type==="triple_string"){$_SyntaxError(C,"Triple string end not found") }else{$_SyntaxError(C,"String end not found") }} continue } if(name==""){if($B.re_XID_Start.exec(car)){name=car pos++;continue }}else{ if($B.re_XID_Continue.exec(car)){name+=car pos++;continue }else{if(kwdict.indexOf(name)>-1){$pos=pos-name.length if(unsupported.indexOf(name)>-1){$_SyntaxError(C,"Unsupported Python keyword '"+name+"'") } if(name=='not'){var re=/^\s+in\s+/ var res=re.exec(src.substr(pos)) if(res!==null){pos +=res[0].length C=$transition(C,'op','not_in') }else{C=$transition(C,name) }}else{C=$transition(C,name) }}else if($operators[name]!==undefined && $B.forbidden.indexOf(name)==-1){ $pos=pos-name.length C=$transition(C,'op',name) }else{ if($B.forbidden.indexOf(name)>-1){name='$$'+name} $pos=pos-name.length C=$transition(C,'id',name) } name="" continue }} switch(car){case ' ': case '\t': pos++ break case '.': if(pos<src.length-1 && /^\d$/.test(src.charAt(pos+1))){ var j=pos+1 while(j<src.length && src.charAt(j).search(/\d/)>-1){j++} C=$transition(C,'float','0'+src.substr(pos,j-pos)) pos=j break } $pos=pos C=$transition(C,'.') pos++ break case '0': var res=hex_pattern.exec(src.substr(pos)) if(res){C=$transition(C,'int',parseInt(res[1],16)) pos +=res[0].length break } var res=octal_pattern.exec(src.substr(pos)) if(res){C=$transition(C,'int',parseInt(res[1],8)) pos +=res[0].length break } var res=binary_pattern.exec(src.substr(pos)) if(res){C=$transition(C,'int',parseInt(res[1],2)) pos +=res[0].length break } if(src.charAt(pos+1).search(/\d/)>-1){$_SyntaxError(C,('invalid literal starting with 0')) } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': var res=float_pattern1.exec(src.substr(pos)) if(res){$pos=pos if(res[2]!==undefined){C=$transition(C,'imaginary',res[0].substr(0,res[0].length-1)) }else{C=$transition(C,'float',res[0])}}else{res=float_pattern2.exec(src.substr(pos)) if(res){$pos=pos if(res[2]!==undefined){C=$transition(C,'imaginary',res[0].substr(0,res[0].length-1)) }else{C=$transition(C,'float',res[0])}}else{res=int_pattern.exec(src.substr(pos)) $pos=pos if(res[1]!==undefined){C=$transition(C,'imaginary',res[0].substr(0,res[0].length-1)) }else{C=$transition(C,'int',res[0])}}} pos +=res[0].length break case '\n': lnum++ if(br_stack.length>0){ pos++; }else{ if(current.C.tree.length>0){$pos=pos C=$transition(C,'eol') indent=null new_node=new $Node() }else{new_node.line_num=lnum } pos++ } break case '(': case '[': case '{': br_stack +=car br_pos[br_stack.length-1]=[C,pos] $pos=pos C=$transition(C,car) pos++ break case ')': case ']': case '}': if(br_stack==""){$_SyntaxError(C,"Unexpected closing bracket") }else if(br_close[car]!=br_stack.charAt(br_stack.length-1)){$_SyntaxError(C,"Unbalanced bracket") }else{ br_stack=br_stack.substr(0,br_stack.length-1) $pos=pos C=$transition(C,car) pos++ } break case '=': if(src.charAt(pos+1)!="="){$pos=pos C=$transition(C,'=') pos++; }else{ $pos=pos C=$transition(C,'op','==') pos+=2 } break case ',': case ':': $pos=pos C=$transition(C,car) pos++ break case ';': $transition(C,'eol') if(current.C.tree.length===0){ $pos=pos $_SyntaxError(C,'invalid syntax') } var pos1=pos+1 var ends_line=false while(pos1<src.length){var _s=src.charAt(pos1) if(_s=='\n' ||_s=='#'){ends_line=true;break }else if(_s==' '){pos1++} else{break}} if(ends_line){pos++;break} new_node=new $Node() new_node.indent=current.indent new_node.line_num=lnum new_node.module=module current.parent.add(new_node) current=new_node C=new $NodeCtx(new_node) pos++ break case '/': case '%': case '&': case '>': case '<': case '-': case '+': case '*': case '/': case '^': case '=': case '|': case '~': case '!': case 'i': case 'n': var op_match="" for(var op_sign in $operators){if(op_sign==src.substr(pos,op_sign.length) && op_sign.length>op_match.length){op_match=op_sign }} $pos=pos if(op_match.length>0){if(op_match in $augmented_assigns){C=$transition(C,'augm_assign',op_match) }else{C=$transition(C,'op',op_match) } pos +=op_match.length } break case '\\': if(src.charAt(pos+1)=='\n'){lnum++ pos+=2 break } case '@': $pos=pos C=$transition(C,car) pos++ break default: $pos=pos;$_SyntaxError(C,'unknown token ['+car+']') } } if(br_stack.length!=0){var br_err=br_pos[0] $pos=br_err[1] $_SyntaxError(br_err[0],["Unbalanced bracket "+br_stack.charAt(br_stack.length-1)]) } if(C!==null && $indented.indexOf(C.tree[0].type)>-1){$pos=pos-1 $_SyntaxError(C,'expected an indented block',pos) } return root } $B.py2js=function(src,module,locals_id,parent_block_id,line_info){ var t0=new Date().getTime() var src=src.replace(/\r\n/gm,'\n') var $n=0 var _src=src.charAt(0) var _src_length=src.length while(_src_length>$n &&(_src=="\n" ||_src=="\r")){$n++ _src=src.charAt($n) } src=src.substr($n) if(src.charAt(src.length-1)!="\n"){src+='\n'} var locals_is_module=Array.isArray(locals_id) if(locals_is_module){locals_id=locals_id[0] } var local_ns='$locals_'+locals_id.replace(/\./g,'_') var global_ns='$locals_'+module.replace(/\./g,'_') $B.bound[module]={} $B.bound[module]['__doc__']=true $B.bound[module]['__name__']=true $B.bound[module]['__file__']=true $B.$py_src[locals_id]=src var root=$tokenize(src,module,locals_id,parent_block_id,line_info) root.transform() var js=['var $B=__BRYTHON__;\n'],pos=1 js[pos++]='var __builtins__=_b_=$B.builtins;\n' if(locals_is_module){js[pos++]='var '+local_ns+'=$locals_'+module+';' }else{js[pos++]='var '+local_ns+'={};' } js[pos++]='var $locals='+local_ns+';\n' js[pos++]='$B.enter_frame(["'+locals_id+'", '+local_ns+',' js[pos++]='"'+module+'", '+global_ns+']);\n' js[pos++]='eval($B.InjectBuiltins());\n' var new_node=new $Node() new $NodeJSCtx(new_node,js.join('')) root.insert(0,new_node) var ds_node=new $Node() new $NodeJSCtx(ds_node,local_ns+'["__doc__"]='+(root.doc_string||'None')+';') root.insert(1,ds_node) var name_node=new $Node() var lib_module=module try{if(module.substr(0,9)=='__main__,'){lib_module='__main__;'}}catch(err){alert(module) throw err } new $NodeJSCtx(name_node,local_ns+'["__name__"]="'+locals_id+'";') root.insert(2,name_node) var file_node=new $Node() new $NodeJSCtx(file_node,local_ns+'["__file__"]="'+$B.$py_module_path[module]+'";None;\n') root.insert(3,file_node) if($B.debug>0){$add_line_num(root,null,module)} if($B.debug>=2){var t1=new Date().getTime() console.log('module '+module+' translated in '+(t1 - t0)+' ms') } var new_node=new $Node() new $NodeJSCtx(new_node,';$B.leave_frame("'+module+'");\n') root.add(new_node) $B.exception_stack=[] return root } function brython(options){var _b_=$B.builtins $B.$py_src={} $B.meta_path=[] $B.$options={} $B.$py_next_hash=-Math.pow(2,53) $B.$py_UUID=0 $B.lambda_magic=Math.random().toString(36).substr(2,8) $B.callbacks={} if(options===undefined)options={'debug':0} if(typeof options==='number')options={'debug':options} $B.debug=options.debug _b_.__debug__=$B.debug>0 if(options.static_stdlib_import===undefined){options.static_stdlib_import=true} $B.static_stdlib_import=options.static_stdlib_import if(options.open !==undefined)_b_.open=options.open $B.$CORS=false if(options.CORS !==undefined)$B.$CORS=options.CORS $B.$options=options $B.exception_stack=[] $B.call_stack=[] if(options.ipy_id!==undefined){var $elts=[] for(var $i=0;$i<options.ipy_id.length;$i++){$elts.push(document.getElementById(options.ipy_id[$i])) }}else{var $elts=document.getElementsByTagName('script') } var $href=$B.script_path=window.location.href var $href_elts=$href.split('/') $href_elts.pop() if(options.pythonpath!==undefined)$B.path=options.pythonpath if(options.re_module !==undefined){if(options.re_module=='pyre' ||options.re_module=='jsre'){$B.$options.re=options.re }} var kk=Object.keys(window) var first_script=true,module_name for(var $i=0;$i<$elts.length;$i++){var $elt=$elts[$i] if($elt.type=="text/python"||$elt.type==="text/python3"){if($elt.id){module_name=$elt.id} else if(first_script){module_name='__main__';first_script=false} else{module_name='__main__'+$B.UUID()} var $src=null if($elt.src){ if(window.XMLHttpRequest){ var $xmlhttp=new XMLHttpRequest() }else{ var $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") } $xmlhttp.onreadystatechange=function(){var state=this.readyState if(state===4){$src=$xmlhttp.responseText }} $xmlhttp.open('GET',$elt.src,false) $xmlhttp.send() if($xmlhttp.status !=200){var msg="can't open file '"+$elt.src msg +="': No such file or directory" console.log(msg) return } $B.$py_module_path[module_name]=$elt.src var $src_elts=$elt.src.split('/') $src_elts.pop() var $src_path=$src_elts.join('/') if($B.path.indexOf($src_path)==-1){ $B.path.splice(0,0,$src_path) }}else{ var $src=($elt.innerHTML ||$elt.textContent) $B.$py_module_path[module_name]=$href } try{ var $root=$B.py2js($src,module_name,module_name,'__builtins__') var $js=$root.to_js() if($B.debug>1)console.log($js) if($B.async_enabled){$js=$B.execution_object.source_conversion($js) eval($js) }else{ eval($js) }}catch($err){if($B.debug>1){console.log($err) for(var attr in $err){console.log(attr+' : ',$err[attr]) } console.log('line info '+$B.line_info) } if($err.$py_error===undefined){console.log('Javascript error',$err) $err=_b_.RuntimeError($err+'') } var $trace=$err.__name__+': ' +$err.args +'\n'+_b_.getattr($err,'info') try{_b_.getattr($B.stderr,'write')($trace) }catch(print_exc_err){console.log($trace) } throw $err }}} } $B.$operators=$operators $B.$Node=$Node $B.$NodeJSCtx=$NodeJSCtx $B.brython=brython })(__BRYTHON__) var brython=__BRYTHON__.brython __BRYTHON__.$__new__=function(factory){return function(cls){ var res=factory.apply(null,[]) res.__class__=cls.$dict var init_func=null try{init_func=__BRYTHON__.builtins.getattr(res,'__init__')} catch(err){__BRYTHON__.$pop_exc()} if(init_func!==null){var args=[],pos=0 for(var i=1,_len_i=arguments.length;i < _len_i;i++){args[pos++]=arguments[i]} init_func.apply(null,args) res.__initialized__=true } return res }} __BRYTHON__.builtins.object=(function($B){var _b_=$B.builtins var $ObjectDict={ __name__:'object',$native:true } var $ObjectNI=function(name,op){return function(other){throw _b_.TypeError('unorderable types: object() '+op+ ' '+ _b_.str($B.get_class(other).__name__)+'()') }} var opnames=['add','sub','mul','truediv','floordiv','mod','pow','lshift','rshift','and','xor','or'] var opsigns=['+','-','*','/','//','%','**','<<','>>','&','^','|'] $ObjectDict.__delattr__=function(self,attr){delete self[attr]} $ObjectDict.__dir__=function(self){var objects=[self],pos=1 var mro=$B.get_class(self).__mro__ for(var i=0,_len_i=mro.length;i < _len_i;i++){objects[pos++]=mro[i] } var res=[],pos=0 for(var i=0,_len_i=objects.length;i < _len_i;i++){for(var attr in objects[i]){ if(attr.charAt(0)=='$' && attr.charAt(1)!='$'){ continue } if(!isNaN(parseInt(attr.charAt(0)))){ continue } res[pos++]=attr }} res=_b_.list(_b_.set(res)) _b_.list.$dict.sort(res) return res } $ObjectDict.__eq__=function(self,other){ var _class=$B.get_class(self) if(_class.$native ||_class.__name__=='function'){var _class1=$B.get_class(other) if(!_class1.$native && _class1.__name__ !='function'){return _b_.getattr(other,'__eq__')(self) }} return self===other } $ObjectDict.__ge__=$ObjectNI('__ge__','>=') $ObjectDict.__getattribute__=function(obj,attr){var klass=$B.get_class(obj) if(attr==='__class__'){return klass.$factory } var res=obj[attr],args=[] if(res===undefined){ var mro=klass.__mro__ for(var i=0,_len_i=mro.length;i < _len_i;i++){if(mro[i].$methods){var method=mro[i].$methods[attr] if(method!==undefined){return method(obj) }} var v=mro[i][attr] if(v!==undefined){res=v break }else if(attr=='__str__' && mro[i]['__repr__']!==undefined){ res=mro[i]['repr'] break }}}else{if(res.__set__===undefined){ return res }} if(res!==undefined){var get_func=res.__get__ if(get_func===undefined &&(typeof res=='object')){var __get__=_b_.getattr(res,'__get__',null) if(__get__ &&(typeof __get__=='function')){get_func=function(x,y){return __get__.apply(x,[y,klass])}}} if(get_func===undefined &&(typeof res=='function')){get_func=function(x){return x}} if(get_func!==undefined){ res.__name__=attr if(attr=='__new__'){res.$type='staticmethod'} var res1=get_func.apply(null,[res,obj,klass]) if(typeof res1=='function'){ if(res1.__class__===$B.$factory)return res else if(res1.__class__===$B.$MethodDict)return res return $B.make_method(attr,klass,res,res1)(obj) }else{ return res1 }} return res }else{ var _ga=obj['__getattr__'] if(_ga===undefined){var mro=klass.__mro__ if(mro===undefined){console.log('in getattr mro undefined for '+obj)} for(var i=0,_len_i=mro.length;i < _len_i;i++){var v=mro[i]['__getattr__'] if(v!==undefined){_ga=v break }}} if(_ga!==undefined){try{return _ga(obj,attr)} catch(err){$B.$pop_exc()}} if(attr.substr(0,2)=='__' && attr.substr(attr.length-2)=='__'){var attr1=attr.substr(2,attr.length-4) var rank=opnames.indexOf(attr1) if(rank > -1){var rop='__r'+opnames[rank]+'__' return function(){try{ if($B.$get_class(arguments[0])===klass){throw Error('')} return _b_.getattr(arguments[0],rop)(obj) }catch(err){var msg="unsupported operand types for "+opsigns[rank]+": '" msg +=klass.__name__+"' and '" throw _b_.TypeError(msg) }}}} }} $ObjectDict.__gt__=$ObjectNI('__gt__','>') $ObjectDict.__hash__=function(self){$B.$py_next_hash+=1; return $B.$py_next_hash } $ObjectDict.__init__=function(){} $ObjectDict.__le__=$ObjectNI('__le__','<=') $ObjectDict.__lt__=$ObjectNI('__lt__','<') $ObjectDict.__mro__=[$ObjectDict] $ObjectDict.__new__=function(cls){if(cls===undefined){throw _b_.TypeError('object.__new__(): not enough arguments')} return{__class__ : cls.$dict}} $ObjectDict.__ne__=function(self,other){return !$ObjectDict.__eq__(self,other)} $ObjectDict.__or__=function(self,other){if(_b_.bool(self))return self return other } $ObjectDict.__repr__=function(self){if(self===object)return "<class 'object'>" if(self.__class__===$B.$factory)return "<class '"+self.$dict.__name__+"'>" if(self.__class__.__module__!==undefined){return "<"+self.__class__.__module__+"."+self.__class__.__name__+" object>" }else{return "<"+self.__class__.__name__+" object>" }} $ObjectDict.__setattr__=function(self,attr,val){if(val===undefined){ throw _b_.TypeError("can't set attributes of built-in/extension type 'object'") }else if(self.__class__===$ObjectDict){ if($ObjectDict[attr]===undefined){throw _b_.AttributeError("'object' object has no attribute '"+attr+"'") }else{throw _b_.AttributeError("'object' object attribute '"+attr+"' is read-only") }} self[attr]=val } $ObjectDict.__setattr__.__str__=function(){return 'method object.setattr'} $ObjectDict.__str__=$ObjectDict.__repr__ $ObjectDict.__subclasshook__=function(){return _b_.NotImplemented} function object(){return{__class__:$ObjectDict}} object.$dict=$ObjectDict $ObjectDict.$factory=object object.__repr__=object.__str__=function(){return "<class 'object'>"} return object })(__BRYTHON__) ;(function($B){var _b_=$B.builtins $B.$class_constructor=function(class_name,class_obj,parents,parents_names,kwargs){var cl_dict=_b_.dict(),bases=null var setitem=_b_.dict.$dict.__setitem__ for(var attr in class_obj){setitem(cl_dict,attr,class_obj[attr]) } if(parents!==undefined){for(var i=0;i<parents.length;i++){if(parents[i]===undefined){ $B.line_info=class_obj.$def_line throw _b_.NameError("name '"+parents_names[i]+"' is not defined") }}} bases=parents var metaclass=_b_.type for(var i=0;i<kwargs.length;i++){var key=kwargs[i][0],val=kwargs[i][1] if(key=='metaclass'){metaclass=val}} var class_dict={__name__ : class_name.replace('$$',''),__bases__ : bases,__dict__ : cl_dict } var items=_b_.list(_b_.dict.$dict.items(cl_dict)) for(var i=0;i<items.length;i++){class_dict[items[i][0]]=items[i][1] } class_dict.__mro__=[class_dict].concat(make_mro(bases,cl_dict)) for(var i=1;i<class_dict.__mro__.length;i++){if(class_dict.__mro__[i].__class__ !==$B.$type){metaclass=class_dict.__mro__[i].__class__.$factory }} class_dict.__class__=metaclass.$dict var meta_new=$B.$type.__getattribute__(metaclass.$dict,'__new__') if(meta_new.__func__===$B.$type.__new__){var factory=_b_.type.$dict.__new__(_b_.type,class_name,bases,cl_dict) }else{var factory=meta_new(metaclass,class_name,bases,cl_dict) } for(var i=0;i<parents.length;i++){parents[i].$dict.$subclasses=parents[i].$dict.$subclasses ||[] parents[i].$dict.$subclasses.push(factory) } if(metaclass===_b_.type)return factory for(var attr in class_dict){factory.$dict[attr]=class_dict[attr]} factory.$dict.$factory=factory for(var member in metaclass.$dict){if(typeof metaclass.$dict[member]=='function' && member !='__new__'){metaclass.$dict[member].$type='classmethod' }} factory.$is_func=true return factory } $B.$class_constructor1=function(class_name,class_obj){if(class_obj.__init__===undefined){var creator=function(){this.__class__=class_obj }}else{var creator=function(args){this.__class__=class_obj class_obj.__init__.apply(null,[this].concat(Array.prototype.slice.call(args))) }} var factory=function(){return new creator(arguments)} factory.__class__=$B.$factory factory.__name__=class_name factory.$dict=class_obj class_obj.__class__=$B.$type class_obj.__name__=class_name class_obj.__mro__=[class_obj,_b_.object.$dict] for(var attr in class_obj){factory.prototype[attr]=class_obj[attr] } class_obj.$factory=factory return factory } $B.make_method=function(attr,klass,func,func1){ var __self__,__func__=func,__repr__,__str__,method switch(func.$type){case undefined: case 'function': method=function(instance){ var instance_method=function(){var local_args=[instance] var pos=local_args.length for(var i=0,_len_i=arguments.length;i < _len_i;i++){local_args[pos++]=arguments[i] } return func.apply(null,local_args) } instance_method.__class__=$B.$MethodDict instance_method.$infos={__class__:klass.$factory,__func__:func,__name__:attr,__self__:instance } return instance_method } break case 'instancemethod': return func case 'classmethod': method=function(){ var class_method=function(){var local_args=[klass] var pos=local_args.length for(var i=0,_len_i=arguments.length;i < _len_i;i++){local_args[pos++]=arguments[i] } return func.apply(null,local_args) } class_method.__class__=$B.$MethodDict class_method.$infos={__class__:klass.$factory,__func__:func,__name__:attr } return class_method } break case 'staticmethod': method=function(){var static_method=function(){return func.apply(null,arguments) } static_method.$infos={__func__:func,__name__:klass.__name__+'.'+attr } return static_method } break } return method } function make_mro(bases,cl_dict){ var seqs=[],pos1=0 for(var i=0;i<bases.length;i++){ if(bases[i]===_b_.str)bases[i]=$B.$StringSubclassFactory else if(bases[i]===_b_.list)bases[i]=$B.$ListSubclassFactory var bmro=[],pos=0 var _tmp=bases[i].$dict.__mro__ for(var k=0;k<_tmp.length;k++){bmro[pos++]=_tmp[k] } seqs[pos1++]=bmro } if(bases.indexOf(_b_.object)==-1){bases=bases.concat(_b_.tuple([_b_.object])) } for(var i=0;i<bases.length;i++)seqs[pos1++]=bases[i].$dict var mro=[],mpos=0 while(1){var non_empty=[],pos=0 for(var i=0;i<seqs.length;i++){if(seqs[i].length>0)non_empty[pos++]=seqs[i] } if(non_empty.length==0)break for(var i=0;i<non_empty.length;i++){var seq=non_empty[i],candidate=seq[0],not_head=[],pos=0 for(var j=0;j<non_empty.length;j++){var s=non_empty[j] if(s.slice(1).indexOf(candidate)>-1){not_head[pos++]=s}} if(not_head.length>0){candidate=null} else{break}} if(candidate===null){throw _b_.TypeError("inconsistent hierarchy, no C3 MRO is possible") } mro[mpos++]=candidate for(var i=0;i<seqs.length;i++){var seq=seqs[i] if(seq[0]===candidate){ seqs[i].shift() }}} if(mro[mro.length-1]!==_b_.object.$dict){mro[mpos++]=_b_.object.$dict } return mro } _b_.type=function(obj,bases,cl_dict){if(arguments.length==1){if(obj.__class__===$B.$factory){ return obj.$dict.__class__.$factory } return $B.get_class(obj).$factory } return $B.$type.__new__(_b_.type,obj,bases,cl_dict) } _b_.type.__class__=$B.$factory $B.$type={$factory: _b_.type,__name__:'type'} $B.$type.__class__=$B.$type $B.$type.__mro__=[$B.$type,_b_.object.$dict] _b_.type.$dict=$B.$type $B.$type.__new__=function(cls,name,bases,cl_dict){ var class_dict={__class__ : $B.$type,__name__ : name.replace('$$',''),__bases__ : bases,__dict__ : cl_dict,$methods :{}} var items=_b_.list(_b_.dict.$dict.items(cl_dict)) for(var i=0;i<items.length;i++){var name=items[i][0],v=items[i][1] class_dict[name]=v if(typeof v=='function' && v.__class__!==$B.$factory && v.__class__!==$B.$MethodDict){class_dict.$methods[name]=$B.make_method(name,class_dict,v,v) }} class_dict.__mro__=[class_dict].concat(make_mro(bases,cl_dict)) class_dict.__class__=class_dict.__mro__[1].__class__ var creator=$instance_creator(class_dict) var factory=function(){return creator.apply(null,arguments) } factory.__class__=$B.$factory factory.$dict=class_dict factory.$is_func=true factory.__eq__=function(other){return other===factory.__class__} class_dict.$factory=factory return factory } $B.$factory={__class__:$B.$type,$factory:_b_.type,is_class:true } $B.$factory.__mro__=[$B.$factory,$B.$type,_b_.object.$dict] _b_.type.__class__=$B.$factory _b_.object.$dict.__class__=$B.$type _b_.object.__class__=$B.$factory $B.$type.__getattribute__=function(klass,attr){ switch(attr){case '__call__': return $instance_creator(klass) case '__eq__': return function(other){return klass.$factory===other} case '__ne__': return function(other){return klass.$factory!==other} case '__class__': return klass.__class__.$factory case '__doc__': return klass.__doc__ ||_b_.None case '__setattr__': if(klass['__setattr__']!==undefined)return klass['__setattr__'] return function(key,value){klass[key]=value} case '__delattr__': if(klass['__delattr__']!==undefined)return klass['__delattr__'] return function(key){delete klass[key]} case '__hash__': return function(){if(arguments.length==0)return klass.__hashvalue__ ||$B.$py_next_hash-- }} var res=klass[attr],is_class=true if(res===undefined){ var mro=klass.__mro__ if(mro===undefined){console.log('attr '+attr+' mro undefined for class '+klass+' name '+klass.__name__)} for(var i=0;i<mro.length;i++){var v=mro[i][attr] if(v!==undefined){res=v break }} var cl_mro=klass.__class__.__mro__ if(res===undefined){ var cl_mro=klass.__class__.__mro__ if(cl_mro!==undefined){for(var i=0;i<cl_mro.length;i++){var v=cl_mro[i][attr] if(v!==undefined){res=v break }}}} if(res===undefined){ var getattr=null for(var i=0;i<cl_mro.length;i++){if(cl_mro[i].__getattr__!==undefined){getattr=cl_mro[i].__getattr__ break }} if(getattr!==null){if(getattr.$type=='classmethod'){return getattr(klass.$factory,attr) } return getattr(attr) }}} if(res!==undefined){ if(res.__class__===$B.$PropertyDict)return res var get_func=res.__get__ if(get_func===undefined &&(typeof res=='function')){get_func=function(x){return x}} if(get_func===undefined)return res if(attr=='__new__'){res.$type='staticmethod'} var res1=get_func.apply(null,[res,$B.builtins.None,klass]) var args if(typeof res1=='function'){res.__name__=attr var __self__,__func__=res1,__repr__,__str__ switch(res.$type){case undefined: case 'function': case 'instancemethod': args=[] __repr__=__str__=function(attr){return function(){return '<function '+klass.__name__+'.'+attr+'>' }}(attr) break case 'classmethod': args=[klass.$factory] __self__=klass __repr__=__str__=function(){var x='<bound method '+klass.__name__+'.'+attr x +=' of '+klass.__name__+'>' return x } break case 'staticmethod': args=[] __repr__=__str__=function(attr){return function(){return '<function '+klass.__name__+'.'+attr+'>' }}(attr) break } var method=(function(initial_args){return function(){ var local_args=initial_args.slice() var pos=local_args.length for(var i=0;i < arguments.length;i++){local_args[pos++]=arguments[i] } return res.apply(null,local_args) }})(args) method.__class__=$B.$FunctionDict method.__eq__=function(other){return other.__func__===__func__ } for(var attr in res){method[attr]=res[attr]} method.__func__=__func__ method.__repr__=__repr__ method.__self__=__self__ method.__str__=__str__ method.__code__={'__class__': $B.CodeDict} method.__doc__=res.__doc__ ||'' method.im_class=klass return method }}} function $instance_creator(klass){ var new_func=null try{new_func=_b_.getattr(klass,'__new__')} catch(err){$B.$pop_exc()} var init_func=null try{init_func=_b_.getattr(klass,'__init__')} catch(err){$B.$pop_exc()} var simple=false if(klass.__bases__.length==0){simple=true} else if(klass.__bases__.length==1){switch(klass.__bases__[0]){case _b_.object: case _b_.type: simple=true break default: simple=false break }} if(simple && klass.__new__==undefined && init_func!==null){ return function(){var obj={__class__:klass} init_func.apply(null,[obj].concat(Array.prototype.slice.call(arguments))) return obj }} return function(){var obj var _args=Array.prototype.slice.call(arguments) if(simple && klass.__new__==undefined){obj={__class__:klass}}else{if(new_func!==null){obj=new_func.apply(null,[klass.$factory].concat(_args)) }} if(!obj.__initialized__){if(init_func!==null){init_func.apply(null,[obj].concat(_args)) }} return obj }} function $MethodFactory(){} $MethodFactory.__class__=$B.$factory $B.$MethodDict={__class__:$B.$type,__name__:'method',$factory:$MethodFactory } $B.$MethodDict.__eq__=function(self,other){return self.__func__===other.__func__ } $B.$MethodDict.__getattribute__=function(self,attr){ var infos=self.$infos.__func__.$infos if(infos && infos[attr]){if(attr=='__code__'){var res={__class__:$B.$CodeDict} for(var attr in infos.__code__){res[attr]=infos.__code__[attr] } return res }else{return infos[attr] }}else{return _b_.object.$dict.__getattribute__(self,attr) }} $B.$MethodDict.__mro__=[$B.$MethodDict,_b_.object.$dict] $B.$MethodDict.__repr__=$B.$MethodDict.__str__=function(self){var res='<bound method '+self.$infos.__class__.$dict.__name__+'.' res +=self.$infos.__name__+' of ' return res+_b_.str(self.$infos.__self__)+'>' } $MethodFactory.$dict=$B.$MethodDict $B.$InstanceMethodDict={__class__:$B.$type,__name__:'instancemethod',__mro__:[_b_.object.$dict],$factory:$MethodFactory }})(__BRYTHON__) ;(function($B){var _b_=$B.builtins $B.$MakeArgs=function($fname,$args,$required,$defaults,$other_args,$other_kw,$after_star){ var has_kw_args=false,nb_pos=$args.length if(nb_pos>0 && $args[nb_pos-1]&& $args[nb_pos-1].$nat=='kw'){has_kw_args=true nb_pos-- var kw_args=$args[nb_pos].kw } var $ns={},$arg var $robj={} for(var i=0;i<$required.length;i++){$robj[$required[i]]=null} var $dobj={} for(var i=0;i<$defaults.length;i++){$dobj[$defaults[i]]=null} if($other_args !=null){$ns[$other_args]=[]} if($other_kw !=null){var $dict_keys=[],key_pos=0,$dict_values=[],value_pos=0} var upargs=[],pos=0 for(var i=0,_len_i=nb_pos;i < _len_i;i++){$arg=$args[i] if($arg===undefined){console.log('arg '+i+' undef in '+$fname)} else if($arg===null){upargs[pos++]=null} else{ switch($arg.$nat){case 'ptuple': var _arg=$arg.arg for(var j=0,_len_j=_arg.length;j < _len_j;j++)upargs[pos++]=_arg[j] break default: upargs[pos++]=$arg } } } var nbreqset=0 for(var $i=0,_len_$i=upargs.length;$i < _len_$i;$i++){var $arg=upargs[$i] var $PyVar=$B.$JS2Py($arg) if($i<$required.length){$ns[$required[$i]]=$PyVar nbreqset++ }else if($other_args!==null){$ns[$other_args].push($PyVar) }else if($i<$required.length+$defaults.length){$ns[$defaults[$i-$required.length]]=$PyVar }else{ console.log(''+$B.line_info) msg=$fname+"() takes "+$required.length+' positional argument' msg +=$required.length==1 ? '' : 's' msg +=' but more were given' throw _b_.TypeError(msg) }} if(has_kw_args){ for(var key in kw_args){$PyVar=kw_args[key] if($ns[key]!==undefined){throw _b_.TypeError($fname+"() got multiple values for argument '"+key+"'") }else if($robj[key]===null){$ns[key]=$PyVar nbreqset++ }else if($other_args!==null && $after_star!==undefined && $after_star.indexOf(key)>-1){var ix=$after_star.indexOf(key) $ns[$after_star[ix]]=$PyVar }else if($dobj[key]===null){$ns[key]=$PyVar var pos_def=$defaults.indexOf(key) $defaults.splice(pos_def,1) delete $dobj[key] }else if($other_kw!=null){$dict_keys.push(key) $dict_values.push($PyVar) }else{ throw _b_.TypeError($fname+"() got an unexpected keyword argument '"+key+"'") }}} if(nbreqset!==$required.length){ var missing=[],pos=0 for(var i=0,_len_i=$required.length;i < _len_i;i++){if($ns[$required[i]]===undefined)missing[pos++]=$required[i] } if(missing.length==1){throw _b_.TypeError($fname+" missing 1 positional argument: '"+missing[0]+"'") }else if(missing.length>1){var msg=$fname+" missing "+missing.length+" positional arguments: " for(var i=0,_len_i=missing.length-1;i < _len_i;i++){msg +="'"+missing[i]+"', "} msg +="and '"+missing.pop()+"'" throw _b_.TypeError(msg) }} if($other_kw!=null){$ns[$other_kw]=_b_.dict() var si=_b_.dict.$dict.__setitem__ var i=$dict_keys.length while(i--){ si($ns[$other_kw],$dict_keys[i],$dict_values[i]) }} if($other_args!=null){$ns[$other_args]=_b_.tuple($ns[$other_args])} return $ns } $B.$MakeArgs1=function($fname,argcount,slots,var_names,$args,$dobj,extra_pos_args,extra_kw_args){ var has_kw_args=false,nb_pos=$args.length,$ns if(nb_pos>0 && $args[nb_pos-1].$nat=='kw'){has_kw_args=true nb_pos-- var kw_args=$args[nb_pos].kw } if(extra_pos_args){slots[extra_pos_args]=[]} if(extra_kw_args){slots[extra_kw_args]=_b_.dict()} if(nb_pos>argcount){ if(extra_pos_args===null){ msg=$fname+"() takes "+argcount+' positional argument' msg +=argcount> 1 ? '' : 's' msg +=' but more were given' throw _b_.TypeError(msg) }else{ slots[extra_pos_args]=Array.prototype.slice.call($args,argcount,nb_pos) nb_pos=argcount }} for(var i=0;i<nb_pos;i++){slots[var_names[i]]=$args[i]} if(has_kw_args){for(var key in kw_args){if(slots[key]===undefined){ if(extra_kw_args){ slots[extra_kw_args].$string_dict[key]=kw_args[key] }else{throw _b_.TypeError($fname+"() got an unexpected keyword argument '"+key+"'") }}else if(slots[key]!==null){ throw _b_.TypeError($fname+"() got multiple values for argument '"+key+"'") }else{ slots[key]=kw_args[key] }}} var missing=[],attr for(var i=nb_pos,_len=var_names.length;i<_len;i++){attr=var_names[i] if(slots[attr]===null){if($dobj[attr]!==undefined){slots[attr]=$dobj[attr]} else{missing.push("'"+attr+"'")}}} if(missing.length>0){var msg=$fname+" missing "+missing.length+" positional arguments: " msg +=missing.join(' and ') throw _b_.TypeError(msg) if(missing.length==1){throw _b_.TypeError($fname+" missing 1 positional argument: '"+missing[0]+"'") }else if(missing.length>1){}} if(extra_pos_args){slots[extra_pos_args].__class__=_b_.tuple.$dict} return slots } $B.get_class=function(obj){ if(obj===null){return $B.$NoneDict} var klass=obj.__class__ if(klass===undefined){switch(typeof obj){case 'number': obj.__class__=_b_.int.$dict return _b_.int.$dict case 'string': obj.__class__=_b_.str.$dict return _b_.str.$dict case 'boolean': obj.__class__=$B.$BoolDict return $B.$BoolDict case 'function': obj.__class__=$B.$FunctionDict return $B.$FunctionDict case 'object': if(obj.constructor===Array){obj.__class__=_b_.list.$dict return _b_.list.$dict } break }} return klass } $B.$mkdict=function(glob,loc){var res={} for(var arg in glob)res[arg]=glob[arg] for(var arg in loc)res[arg]=loc[arg] return res } function clear(ns){ delete $B.vars[ns],$B.bound[ns],$B.modules[ns],$B.imported[ns] } $B.$list_comp=function(env){ var $ix=$B.UUID() var $py="x"+$ix+"=[]\n",indent=0 for(var $i=2,_len_$i=arguments.length;$i < _len_$i;$i++){$py +=' '.repeat(indent) $py +=arguments[$i]+':\n' indent +=4 } $py +=' '.repeat(indent) $py +='x'+$ix+'.append('+arguments[1].join('\n')+')\n' for(var i=0;i<env.length;i++){var sc_id='$locals_'+env[i][0].replace(/\./,'_') eval('var '+sc_id+'=env[i][1]') } var local_name=env[0][0] var module_env=env[env.length-1] var module_name=module_env[0] var listcomp_name='lc'+$ix var $root=$B.py2js($py,module_name,listcomp_name,local_name,$B.line_info) $root.caller=$B.line_info var $js=$root.to_js() $B.call_stack[$B.call_stack.length]=$B.line_info try{eval($js) var res=eval('$locals_'+listcomp_name+'["x"+$ix]') } catch(err){throw $B.exception(err)} finally{clear(listcomp_name) $B.call_stack.pop() } return res } $B.$dict_comp=function(env){ var $ix=$B.UUID() var $res='res'+$ix var $py=$res+"={}\n" var indent=0 for(var $i=2,_len_$i=arguments.length;$i < _len_$i;$i++){$py+=' '.repeat(indent) $py +=arguments[$i]+':\n' indent +=4 } $py+=' '.repeat(indent) $py +=$res+'.update({'+arguments[1].join('\n')+'})' for(var i=0;i<env.length;i++){var sc_id='$locals_'+env[i][0].replace(/\./,'_') eval('var '+sc_id+'=env[i][1]') } var local_name=env[0][0] var module_env=env[env.length-1] var module_name=module_env[0] var dictcomp_name='dc'+$ix var $root=$B.py2js($py,module_name,dictcomp_name,local_name,$B.line_info) $root.caller=$B.line_info var $js=$root.to_js() eval($js) var res=eval('$locals_'+dictcomp_name+'["'+$res+'"]') return res } $B.$gen_expr=function(env){ var $ix=$B.UUID() var $res='res'+$ix var $py=$res+"=[]\n" var indent=0 for(var $i=2,_len_$i=arguments.length;$i < _len_$i;$i++){$py+=' '.repeat(indent) $py +=arguments[$i].join(' ')+':\n' indent +=4 } $py+=' '.repeat(indent) $py +=$res+'.append('+arguments[1].join('\n')+')' for(var i=0;i<env.length;i++){var sc_id='$locals_'+env[i][0].replace(/\./,'_') eval('var '+sc_id+'=env[i][1]') } var local_name=env[0][0] var module_env=env[env.length-1] var module_name=module_env[0] var genexpr_name='ge'+$ix var $root=$B.py2js($py,module_name,genexpr_name,local_name,$B.line_info) var $js=$root.to_js() eval($js) var $res1=eval('$locals_ge'+$ix)["res"+$ix] var $GenExprDict={__class__:$B.$type,__name__:'generator',toString:function(){return '(generator)'}} $GenExprDict.__mro__=[$GenExprDict,_b_.object.$dict] $GenExprDict.__iter__=function(self){return self} $GenExprDict.__next__=function(self){self.$counter +=1 if(self.$counter==self.value.length){throw _b_.StopIteration('') } return self.value[self.$counter] } $GenExprDict.$factory={__class__:$B.$factory,$dict:$GenExprDict} var $res2={value:$res1,__class__:$GenExprDict,$counter:-1} $res2.toString=function(){return 'ge object'} return $res2 } $B.$lambda=function(env,args,body){ var rand=$B.UUID() var $res='lambda_'+$B.lambda_magic+'_'+rand var $py='def '+$res+'('+args+'):\n' $py +=' return '+body for(var i=0;i<env.length;i++){var sc_id='$locals_'+env[i][0].replace(/\./,'_') eval('var '+sc_id+'=env[i][1]') } var local_name=env[0][0] var module_env=env[env.length-1] var module_name=module_env[0] var lambda_name='lambda'+rand var $js=$B.py2js($py,module_name,lambda_name,local_name).to_js() eval($js) var $res=eval('$locals_'+lambda_name+'["'+$res+'"]') $res.__module__=module_name $res.__name__='<lambda>' return $res } $B.$search=function(name,global_ns){var res=global_ns[name] return res !==undefined ? res : $B.$NameError(name) } $B.$JS2Py=function(src){if(typeof src==='number'){if(src%1===0)return src return _b_.float(src) } if(src===null||src===undefined)return _b_.None var klass=$B.get_class(src) if(klass!==undefined){if(klass===_b_.list.$dict){for(var i=0,_len_i=src.length;i< _len_i;i++)src[i]=$B.$JS2Py(src[i]) } return src } if(typeof src=="object"){if($B.$isNode(src))return $B.DOMNode(src) if($B.$isEvent(src))return $B.DOMEvent(src) if(src.constructor===Array||$B.$isNodeList(src)){var res=[],pos=0 for(var i=0,_len_i=src.length;i<_len_i;i++)res[pos++]=$B.$JS2Py(src[i]) return res }} return $B.JSObject(src) } function index_error(obj){var type=typeof obj=='string' ? 'string' : 'list' throw _b_.IndexError(type+" index out of range") } $B.$getitem=function(obj,item){if(typeof item=='number'){if(Array.isArray(obj)||typeof obj=='string'){item=item >=0 ? item : obj.length+item if(obj[item]!==undefined){return $B.$JS2Py(obj[item])} else{index_error(obj)}}} item=$B.$GetInt(item) if((Array.isArray(obj)||typeof obj=='string') && typeof item=='number'){item=item >=0 ? item : obj.length+item if(obj[item]!==undefined){return obj[item]} else{index_error(obj)}} return _b_.getattr(obj,'__getitem__')(item) } $B.$setitem=function(obj,item,value){if(Array.isArray(obj)&& typeof item=='number'){if(item<0){item+=obj.length} if(obj[item]===undefined){throw _b_.IndexError("list assignment index out of range")} obj[item]=value return }else if(obj.__class__===_b_.dict.$dict){obj.__class__.__setitem__(obj,item,value) return } _b_.getattr(obj,'__setitem__')(item,value) } $B.augm_item_add=function(obj,item,incr){if(Array.isArray(obj)&& typeof item=="number" && obj[item]!==undefined){obj[item]+=incr return } var ga=_b_.getattr try{var augm_func=ga(ga(obj,'__getitem__')(item),'__iadd__') console.log('has augmfunc') }catch(err){ga(obj,'__setitem__')(item,ga(ga(obj,'__getitem__')(item),'__add__')(incr)) return } augm_func(value) } var augm_item_src=''+$B.augm_item_add var augm_ops=[['-=','sub'],['*=','mul']] for(var i=0,_len_i=augm_ops.length;i < _len_i;i++){var augm_code=augm_item_src.replace(/add/g,augm_ops[i][1]) augm_code=augm_code.replace(/\+=/g,augm_ops[i][0]) eval('$B.augm_item_'+augm_ops[i][1]+'='+augm_code) } $B.$raise=function(){ var es=$B.exception_stack if(es.length>0){throw es[es.length-1] } throw _b_.RuntimeError('No active exception to reraise') } $B.$syntax_err_line=function(exc,module,pos){ var pos2line={} var lnum=1 var src=$B.$py_src[module] var line_pos={1:0} for(var i=0,_len_i=src.length;i < _len_i;i++){pos2line[i]=lnum if(src.charAt(i)=='\n'){line_pos[++lnum]=i}} var line_num=pos2line[pos] exc.$line_info=line_num+','+module var lines=src.split('\n') var line=lines[line_num-1] var lpos=pos-line_pos[line_num] var len=line.length line=line.replace(/^\s*/,'') lpos-=len-line.length exc.args=_b_.tuple([$B.$getitem(exc.args,0),_b_.tuple([module,line_num,lpos,line])]) } $B.$SyntaxError=function(module,msg,pos){var exc=_b_.SyntaxError(msg) $B.$syntax_err_line(exc,module,pos) throw exc } $B.$IndentationError=function(module,msg,pos){var exc=_b_.IndentationError(msg) $B.$syntax_err_line(exc,module,pos) throw exc } $B.$pop_exc=function(){$B.exception_stack.pop()} $B.extend=function(fname,arg,mapping){var it=_b_.iter(mapping),getter=_b_.getattr(mapping,'__getitem__') while(true){try{var key=_b_.next(it) if(typeof key!=='string'){throw _b_.TypeError(fname+"() keywords must be strings") } if(arg[key]!==undefined){throw _b_.TypeError( fname+"() got multiple values for argument '"+key+"'") } arg[key]=getter(key) }catch(err){if(_b_.isinstance(err,[_b_.StopIteration])){$B.$pop_exc();break} throw err }} return arg } $B.extend_list=function(){ var res=Array.prototype.slice.call(arguments,0,arguments.length-1),last=$B.last(arguments) var it=_b_.iter(last) while(true){try{res.push(_b_.next(it)) }catch(err){if(_b_.isinstance(err,[_b_.StopIteration])){$B.$pop_exc();break} throw err }} return res } $B.$test_item=function(expr){ $B.$test_result=expr return _b_.bool(expr) } $B.$test_expr=function(){ return $B.$test_result } $B.$is_member=function(item,_set){ var f,_iter try{f=_b_.getattr(_set,"__contains__")} catch(err){$B.$pop_exc()} if(f)return f(item) try{_iter=_b_.iter(_set)} catch(err){$B.$pop_exc()} if(_iter){while(1){try{var elt=_b_.next(_iter) if(_b_.getattr(elt,"__eq__")(item))return true }catch(err){if(err.__name__=="StopIteration"){$B.$pop_exc() return false } throw err }}} try{f=_b_.getattr(_set,"__getitem__")} catch(err){$B.$pop_exc() throw _b_.TypeError("'"+$B.get_class(_set).__name__+"' object is not iterable") } if(f){var i=-1 while(1){i++ try{var elt=f(i) if(_b_.getattr(elt,"__eq__")(item))return true }catch(err){if(err.__name__=='IndexError')return false throw err }}}} var $io={__class__:$B.$type,__name__:'io'} $io.__mro__=[$io,_b_.object.$dict] $B.stderr={__class__:$io,write:function(data){console.log(data)},flush:function(){}} $B.stderr_buff='' $B.stdout={__class__:$io,write: function(data){console.log(data)},flush:function(){}} $B.stdin={__class__:$io, read: function(size){return ''}} $B.jsobject2pyobject=function(obj){switch(obj){case null: return _b_.None case true: return _b_.True case false: return _b_.False } if(_b_.isinstance(obj,_b_.list)){var res=[],pos=0 for(var i=0,_len_i=obj.length;i < _len_i;i++){res[pos++]=$B.jsobject2pyobject(obj[i]) } return res } if(obj.__class__!==undefined){if(obj.__class__===_b_.list){for(var i=0,_len_i=obj.length;i < _len_i;i++){obj[i]=$B.jsobject2pyobject(obj[i]) } return obj } return obj } if(obj._type_==='iter'){ return _b_.iter(obj.data) } if(typeof obj==='object' && obj.__class__===undefined){ var res=_b_.dict() var si=_b_.dict.$dict.__setitem__ for(var attr in obj){si(res,attr,$B.jsobject2pyobject(obj[attr])) } return res } return $B.JSObject(obj) } $B.pyobject2jsobject=function(obj){ switch(obj){case _b_.None: return null case _b_.True: return true case _b_.False: return false } if(_b_.isinstance(obj,[_b_.int,_b_.str]))return obj if(_b_.isinstance(obj,_b_.float))return obj.value if(_b_.isinstance(obj,[_b_.list,_b_.tuple])){var res=[],pos=0 for(var i=0,_len_i=obj.length;i < _len_i;i++){res[pos++]=$B.pyobject2jsobject(obj[i]) } return res } if(_b_.isinstance(obj,_b_.dict)){var res={} var items=_b_.list(_b_.dict.$dict.items(obj)) for(var i=0,_len_i=items.length;i < _len_i;i++){res[$B.pyobject2jsobject(items[i][0])]=$B.pyobject2jsobject(items[i][1]) } return res } if(_b_.hasattr(obj,'__iter__')){ var _a=[],pos=0 while(1){try{ _a[pos++]=$B.pyobject2jsobject(_b_.next(obj)) }catch(err){if(err.__name__ !=="StopIteration")throw err $B.$pop_exc();break }} return{'_type_': 'iter',data: _a}} if(_b_.hasattr(obj,'__getstate__')){return _b_.getattr(obj,'__getstate__')() } if(_b_.hasattr(obj,'__dict__')){return $B.pyobject2jsobject(_b_.getattr(obj,'__dict__')) } throw _b_.TypeError(str(obj)+' is not JSON serializable') } if(window.IDBObjectStore !==undefined){window.IDBObjectStore.prototype._put=window.IDBObjectStore.prototype.put window.IDBObjectStore.prototype.put=function(obj,key){var myobj=$B.pyobject2jsobject(obj) return window.IDBObjectStore.prototype._put.apply(this,[myobj,key]) } window.IDBObjectStore.prototype._add=window.IDBObjectStore.prototype.add window.IDBObjectStore.prototype.add=function(obj,key){var myobj=$B.pyobject2jsobject(obj) return window.IDBObjectStore.prototype._add.apply(this,[myobj,key]) }} if(window.IDBRequest !==undefined){window.IDBRequest.prototype.pyresult=function(){return $B.jsobject2pyobject(this.result) }} $B.set_line=function(line_num,module_name){$B.line_info=line_num+','+module_name return _b_.None } $B.$iterator=function(items,klass){var res={__class__:klass,__iter__:function(){return res},__len__:function(){return items.length},__next__:function(){res.counter++ if(res.counter<items.length)return items[res.counter] throw _b_.StopIteration("StopIteration") },__repr__:function(){return "<"+klass.__name__+" object>"},counter:-1 } res.__str__=res.toString=res.__repr__ return res } $B.$iterator_class=function(name){var res={__class__:$B.$type,__name__:name,} res.__mro__=[res,_b_.object.$dict] function as_array(s){var _a=[],pos=0 var _it=_b_.iter(s) while(1){try{ _a[pos++]=_b_.next(_it) }catch(err){if(err.__name__=='StopIteration'){$B.$pop_exc();break}}} return _a } function as_list(s){return _b_.list(as_array(s))} function as_set(s){return _b_.set(as_array(s))} res.__eq__=function(self,other){if(_b_.isinstance(other,[_b_.tuple,_b_.set,_b_.list])){return _b_.getattr(as_list(self),'__eq__')(other) } if(_b_.hasattr(other,'__iter__')){return _b_.getattr(as_list(self),'__eq__')(as_list(other)) } _b_.NotImplementedError("__eq__ not implemented yet for list and " + _b_.type(other)) } var _ops=['eq','ne'] var _f=res.__eq__+'' for(var i=0;i < _ops.length;i++){var _op='__'+_ops[i]+'__' eval('res.'+_op+'='+_f.replace(new RegExp('__eq__','g'),_op)) } res.__or__=function(self,other){if(_b_.isinstance(other,[_b_.tuple,_b_.set,_b_.list])){return _b_.getattr(as_set(self),'__or__')(other) } if(_b_.hasattr(other,'__iter__')){return _b_.getattr(as_set(self),'__or__')(as_set(other)) } _b_.NotImplementedError("__or__ not implemented yet for set and " + _b_.type(other)) } var _ops=['sub','and','xor','gt','ge','lt','le'] var _f=res.__or__+'' for(var i=0;i < _ops.length;i++){var _op='__'+_ops[i]+'__' eval('res.'+_op+'='+_f.replace(new RegExp('__or__','g'),_op)) } res.$factory={__class__:$B.$factory,$dict:res} return res } $B.$CodeDict={__class__:$B.$type,__name__:'code'} $B.$CodeDict.__mro__=[$B.$CodeDict,_b_.object.$dict] function _code(){} _code.__class__=$B.$factory _code.$dict=$B.$CodeDict $B.$CodeDict.$factory=_code function $err(op,klass,other){var msg="unsupported operand type(s) for "+op msg +=": '"+klass.__name__+"' and '"+$B.get_class(other).__name__+"'" throw _b_.TypeError(msg) } var ropnames=['add','sub','mul','truediv','floordiv','mod','pow','lshift','rshift','and','xor','or'] var ropsigns=['+','-','*','/','//','%','**','<<','>>','&','^','|'] $B.make_rmethods=function(klass){for(var j=0,_len_j=ropnames.length;j < _len_j;j++){if(klass['__'+ropnames[j]+'__']===undefined){ klass['__'+ropnames[j]+'__']=(function(name,sign){return function(self,other){try{return _b_.getattr(other,'__r'+name+'__')(self)} catch(err){$err(sign,klass,other)}}})(ropnames[j],ropsigns[j]) }}} $B.set_func_names=function(klass){var name=klass.__name__ for(var attr in klass){if(typeof klass[attr]=='function'){klass[attr].__name__=name+'.'+attr }}} $B.UUID=function(){return $B.$py_UUID++} $B.InjectBuiltins=function(){var _str=["var _b_=$B.builtins"],pos=1 for(var $b in $B.builtins)_str[pos++]='var ' + $b +'=_b_["'+$b+'"]' return _str.join(';') } $B.$GetInt=function(value){ if(typeof value=="number"){return value} else if(typeof value==="boolean"){return value ? 1 : 0} else if(_b_.isinstance(value,_b_.int)){return value} try{var v=_b_.getattr(value,'__int__')();return v}catch(e){$B.$pop_exc()} try{var v=_b_.getattr(value,'__index__')();return v}catch(e){$B.$pop_exc()} return value } $B.enter_frame=function(frame){$B.frames_stack[$B.frames_stack.length]=frame } $B.leave_frame=function(){ if($B.frames_stack.length>1){$B.frames_stack.pop() }}})(__BRYTHON__) if(!Array.indexOf){Array.prototype.indexOf=function(obj){for(var i=0,_len_i=this.length;i < _len_i;i++)if(this[i]==obj)return i return -1 }} if(!String.prototype.repeat){String.prototype.repeat=function(count){if(count < 1)return '' var result='',pattern=this.valueOf() while(count > 1){if(count & 1)result +=pattern count >>=1,pattern +=pattern } return result + pattern }} ;(function($B){eval($B.InjectBuiltins()) _b_.__debug__=false var $ObjectDict=_b_.object.$dict $B.$comps={'>':'gt','>=':'ge','<':'lt','<=':'le'} function abs(obj){if(isinstance(obj,_b_.int))return _b_.int(Math.abs(obj)) if(isinstance(obj,_b_.float))return _b_.float(Math.abs(obj.value)) if(hasattr(obj,'__abs__'))return getattr(obj,'__abs__')() throw _b_.TypeError("Bad operand type for abs(): '"+$B.get_class(obj)+"'") } function _alert(src){alert(_b_.str(src))} function all(obj){var iterable=iter(obj) while(1){try{var elt=next(iterable) if(!bool(elt))return false }catch(err){return true}}} function any(obj){var iterable=iter(obj) while(1){try{var elt=next(iterable) if(bool(elt))return true }catch(err){return false}}} function ascii(obj){ function padWithLeadingZeros(string,pad){return new Array(pad+1-string.length).join("0")+ string } function charEscape(charCode){if(charCode>255)return "\\u"+padWithLeadingZeros(charCode.toString(16),4) return "\\x" + padWithLeadingZeros(charCode.toString(16),2) } return obj.split("").map(function(char){var charCode=char.charCodeAt(0) return charCode > 127 ? charEscape(charCode): char }) .join("") } function $builtin_base_convert_helper(obj,base){var value=$B.$GetInt(obj) if(value===undefined){ throw _b_.TypeError('Error, argument must be an integer or contains an __index__ function') return } var prefix="" switch(base){case 2: prefix='0b';break case 8: prefix='0o';break case 16: prefix='0x';break default: console.log('invalid base:' + base) } if(value >=0)return prefix + value.toString(base) return '-' + prefix +(-value).toString(base) } function bin(obj){if(isinstance(obj,_b_.int)){return $builtin_base_convert_helper(obj,2) } return getattr(obj,'__index__')() } function bool(obj){ if(obj===null ||obj===undefined )return false switch(typeof obj){case 'boolean': return obj case 'number': case 'string': if(obj)return true return false default: try{return getattr(obj,'__bool__')()} catch(err){$B.$pop_exc() try{return getattr(obj,'__len__')()>0} catch(err){$B.$pop_exc();return true}}} } bool.__class__=$B.$type bool.__mro__=[bool,object] bool.__name__='bool' bool.__repr__=bool.__str__=function(){return "<class 'bool'>"} bool.toString=bool.__str__ bool.__hash__=function(){if(this.valueOf())return 1 return 0 } function callable(obj){return hasattr(obj,'__call__')} function chr(i){if(i < 0 ||i > 1114111)_b_.ValueError('Outside valid range') return String.fromCharCode(i) } var $ClassmethodDict={__class__:$B.$type,__name__:'classmethod'} $ClassmethodDict.__mro__=[$ClassmethodDict,$ObjectDict] function classmethod(func){func.$type='classmethod' return func } classmethod.__class__=$B.$factory classmethod.$dict=$ClassmethodDict $ClassmethodDict.$factory=classmethod function $class(obj,info){this.obj=obj this.__name__=info this.__class__=$B.$type this.__mro__=[this,$ObjectDict] } $B.$CodeObjectDict={__class__:$B.$type,__name__:'code',__repr__:function(self){return '<code object '+self.name+', file '+self.filename+'>'},} $B.$CodeObjectDict.__str__=$B.$CodeObjectDict.__repr__ $B.$CodeObjectDict.__mro__=[$B.$CodeObjectDict,$ObjectDict] function compile(source,filename,mode){ var current_frame=$B.frames_stack[$B.frames_stack.length-1] if(current_frame===undefined){alert('current frame undef pour '+src.substr(0,30))} var current_locals_id=current_frame[0] var current_locals_name=current_locals_id.replace(/\./,'_') var current_globals_id=current_frame[2] var current_globals_name=current_globals_id.replace(/\./,'_') var module_name=current_globals_name var local_name=current_locals_name var root=$B.py2js(source,module_name,[module_name],local_name) root.children.pop() var js=root.to_js() return{__class__:$B.$CodeObjectDict,src:js,name:source.__name__ ||'<module>',filename:filename,mode:mode}} compile.__class__=$B.factory $B.$CodeObjectDict.$factory=compile compile.$dict=$B.$CodeObjectDict var __debug__=$B.debug>0 function delattr(obj,attr){ var klass=$B.get_class(obj) var res=obj[attr] if(res===undefined){var mro=klass.__mro__ for(var i=0;i<mro.length;i++){var res=mro[i][attr] if(res!==undefined){break}}} if(res!==undefined && res.__delete__!==undefined){return res.__delete__(res,obj,attr) } getattr(obj,'__delattr__')(attr) } function dir(obj){if(obj===undefined){ var frame=$B.last($B.frames_stack),globals_obj=frame[1][1],res=_b_.list(),pos=0 for(var attr in globals_obj){if(attr.charAt(0)=='$' && attr.charAt(1)!='$'){ continue } res[pos++]=attr } _b_.list.$dict.sort(res) return res } if(isinstance(obj,$B.JSObject))obj=obj.js else if($B.get_class(obj).is_class){obj=obj.$dict} else{ try{ var res=getattr(obj,'__dir__')() res=_b_.list(res) res.sort() return res }catch(err){$B.$pop_exc()}} var res=[],pos=0 for(var attr in obj){if(attr.charAt(0)!=='$' && attr!=='__class__'){res[pos++]=attr }} res.sort() return res } function divmod(x,y){var klass=$B.get_class(x) return[klass.__floordiv__(x,y),klass.__mod__(x,y)] } var $EnumerateDict={__class__:$B.$type,__name__:'enumerate'} $EnumerateDict.__mro__=[$EnumerateDict,$ObjectDict] function enumerate(){var _start=0 var $ns=$B.$MakeArgs("enumerate",arguments,["iterable"],["start"],null,null) var _iter=iter($ns["iterable"]) var _start=$ns["start"]||_start var res={__class__:$EnumerateDict,__getattr__:function(attr){return res[attr]},__iter__:function(){return res},__name__:'enumerate iterator',__next__:function(){res.counter++ return _b_.tuple([res.counter,next(_iter)]) },__repr__:function(){return "<enumerate object>"},__str__:function(){return "<enumerate object>"},counter:_start-1 } for(var attr in res){if(typeof res[attr]==='function' && attr!=="__class__"){res[attr].__str__=(function(x){return function(){return "<method wrapper '"+x+"' of enumerate object>"}})(attr) }} return res } enumerate.__class__=$B.$factory enumerate.$dict=$EnumerateDict $EnumerateDict.$factory=enumerate function $eval(src,_globals,_locals){var current_frame=$B.frames_stack[$B.frames_stack.length-1] if(current_frame===undefined){alert('current frame undef pour '+src.substr(0,30))} var current_locals_id=current_frame[0] var current_locals_name=current_locals_id.replace(/\./,'_') var current_globals_id=current_frame[2] var current_globals_name=current_globals_id.replace(/\./,'_') if(src.__class__===$B.$CodeObjectDict){module_name=current_globals_name eval('var $locals_'+module_name+'=current_frame[3]') return eval(src.src) } var is_exec=arguments[3]=='exec',module_name,leave=false if(_globals===undefined){module_name='exec_'+$B.UUID() $B.$py_module_path[module_name]=$B.$py_module_path[current_globals_id] eval('var $locals_'+module_name+'=current_frame[3]') }else{if(_globals.id===undefined){_globals.id='exec_'+$B.UUID()} module_name=_globals.id $B.$py_module_path[module_name]=$B.$py_module_path[current_globals_id] eval('var $locals_'+module_name+'={}') var items=_b_.dict.$dict.items(_globals),item while(1){try{item=next(items) eval('$locals_'+module_name+'["'+item[0]+'"] = item[1]') }catch(err){break }}} if(_locals===undefined){local_name=module_name }else{if(_locals.id===undefined){_locals.id='exec_'+$B.UUID()} local_name=_locals.id } try{var root=$B.py2js(src,module_name,[module_name],local_name) if(!is_exec){ root.children.pop() leave=true var instr=root.children[root.children.length-1] var type=instr.C.tree[0].type if(!('expr'==type ||'list_or_tuple'==type)){ $B.line_info="1,"+module_name throw _b_.SyntaxError("eval() argument must be an expression") }} var js=root.to_js() if($B.async_enabled)js=$B.execution_object.source_conversion(js) var res=eval(js) if(_globals!==undefined){ var ns=eval('$locals_'+module_name) var setitem=getattr(_globals,'__setitem__') for(var attr in ns){setitem(attr,ns[attr]) }} if(res===undefined)return _b_.None return res }catch(err){if(err.$py_error===undefined){throw $B.exception(err)} throw err }finally{if(leave){$B.leave_frame()}}} $eval.$is_func=true function show_frames(){ var ch='' for(var i=0;i<$B.frames_stack.length;i++){var frame=$B.frames_stack[i] ch +='['+frame[0][0] if($B.debug>0){ch +=' line '+frame[0][2]} ch +=', '+frame[1][0]+'] ' } return ch } function exec(src,globals,locals){return $eval(src,globals,locals,'exec')||_b_.None } exec.$is_func=true var $FilterDict={__class__:$B.$type,__name__:'filter'} $FilterDict.__iter__=function(self){return self} $FilterDict.__repr__=$FilterDict.__str__=function(){return "<filter object>"},$FilterDict.__mro__=[$FilterDict,$ObjectDict] function filter(){if(arguments.length!=2){throw _b_.TypeError( "filter expected 2 arguments, got "+arguments.length)} var func=arguments[0],iterable=iter(arguments[1]) if(func===_b_.None)func=bool var __next__=function(){while(true){try{ var _item=next(iterable) if(func(_item)){return _item}}catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();throw _b_.StopIteration('')} else{throw err}}}} return{ __class__: $FilterDict,__next__: __next__ }} function format(value,format_spec){if(hasattr(value,'__format__'))return getattr(value,'__format__')(format_spec) throw _b_.NotImplementedError("__format__ is not implemented for object '" + _b_.str(value)+ "'") } function getattr(obj,attr,_default){var klass=$B.get_class(obj) if(klass===undefined){ if(obj[attr]!==undefined)return obj[attr] if(_default!==undefined)return _default throw _b_.AttributeError('object has no attribute '+attr) } switch(attr){case '__call__': if(typeof obj=='function'){if(obj.$blocking){console.log('calling blocking function '+obj.__name__) } if($B.debug>0){ return function(){$B.call_stack[$B.call_stack.length]=$B.line_info var res=obj.apply(null,arguments) $B.line_info=$B.call_stack.pop() return res }}else{return obj }}else if(klass===$B.JSObject.$dict && typeof obj.js=='function'){return function(){var res=obj.js.apply(null,arguments) if(res===undefined)return _b_.None return $B.JSObject(res) }} break case '__class__': return klass.$factory case '__dict__': return $B.obj_dict(obj) case '__doc__': for(var i=0;i<builtin_names.length;i++){if(obj===_b_[builtin_names[i]]){_get_builtins_doc() return $B.builtins_doc[builtin_names[i]] }} break case '__mro__': if(klass===$B.$factory){ var res=[],pos=0 for(var i=0;i<obj.$dict.__mro__.length;i++){res[pos++]=obj.$dict.__mro__[i].$factory } return res } break case '__subclasses__': if(klass===$B.$factory){var subclasses=obj.$dict.$subclasses ||[] return function(){return subclasses}} break } if(typeof obj=='function'){if(attr !==undefined && obj[attr]!==undefined){if(attr=='__module__'){ return obj[attr] }}} if(klass.$native){if(klass[attr]===undefined){if(_default===undefined)throw _b_.AttributeError(klass.__name__+" object has no attribute '"+attr+"'") return _default } if(typeof klass[attr]=='function'){ if(attr=='__new__')return klass[attr].apply(null,arguments) if(klass.descriptors && klass.descriptors[attr]!==undefined){return klass[attr].apply(null,[obj]) } var method=function(){var args=[obj],pos=1 for(var i=0;i<arguments.length;i++){args[pos++]=arguments[i]} return klass[attr].apply(null,args) } method.__name__='method '+attr+' of built-in '+klass.__name__ return method } return klass[attr] } var is_class=klass.is_class,mro,attr_func if(is_class){attr_func=$B.$type.__getattribute__ if(obj.$dict===undefined){console.log('obj '+obj+' $dict undefined')} obj=obj.$dict }else{var mro=klass.__mro__ if(mro===undefined){console.log('in getattr '+attr+' mro undefined for '+obj+' dir '+dir(obj)+' class '+obj.__class__) for(var _attr in obj){console.log('obj attr '+_attr+' : '+obj[_attr]) } console.log('obj class '+dir(klass)+' str '+klass) } for(var i=0;i<mro.length;i++){attr_func=mro[i]['__getattribute__'] if(attr_func!==undefined){break}}} if(typeof attr_func!=='function'){console.log(attr+' is not a function '+attr_func) } try{var res=attr_func(obj,attr)} catch(err){$B.$pop_exc() if(_default!==undefined)return _default throw err } if(res!==undefined)return res if(_default !==undefined)return _default var cname=klass.__name__ if(is_class)cname=obj.__name__ throw _b_.AttributeError("'"+cname+"' object has no attribute '"+attr+"'") } function globals(){ var globals_obj=$B.last($B.frames_stack)[3] return $B.obj_dict(globals_obj) } function hasattr(obj,attr){try{getattr(obj,attr);return true} catch(err){$B.$pop_exc();return false}} function hash(obj){if(arguments.length!=1){throw _b_.TypeError("hash() takes exactly one argument ("+ arguments.length+" given)") } if(obj.__hashvalue__ !==undefined)return obj.__hashvalue__ if(isinstance(obj,_b_.int))return obj.valueOf() if(isinstance(obj,bool))return _b_.int(obj) if(obj.__hash__ !==undefined){return obj.__hashvalue__=obj.__hash__() } var hashfunc=getattr(obj,'__hash__',_b_.None) if(hashfunc==_b_.None)return $B.$py_next_hash++ if(hashfunc.__func__===_b_.object.$dict.__hash__ && getattr(obj,'__eq__').__func__!==_b_.object.$dict.__eq__){throw _b_.TypeError("unhashable type: '"+ $B.get_class(obj).__name__+"'") }else{return obj.__hashvalue__=hashfunc() }} function _get_builtins_doc(){if($B.builtins_doc===undefined){ var url=$B.brython_path if(url.charAt(url.length-1)=='/'){url=url.substr(0,url.length-1)} url +='/builtins_docstrings.js' var f=_b_.open(url) eval(f.$content) $B.builtins_doc=docs }} function help(obj){if(obj===undefined)obj='help' if(typeof obj=='string' && _b_[obj]!==undefined){_get_builtins_doc() var _doc=$B.builtins_doc[obj] if(_doc !==undefined && _doc !=''){_b_.print(_doc) return }} for(var i=0;i<builtin_names.length;i++){if(obj===_b_[builtin_names[i]]){_get_builtins_doc() _b_.print(_doc=$B.builtins_doc[builtin_names[i]]) }} if(typeof obj=='string'){$B.$import("pydoc") var pydoc=$B.imported["pydoc"] getattr(getattr(pydoc,"help"),"__call__")(obj) return } try{return getattr(obj,'__doc__')} catch(err){console.log('help err '+err);return ''}} function hex(x){return $builtin_base_convert_helper(x,16)} function id(obj){if(obj.__hashvalue__ !==undefined)return obj.__hashvalue__ if(typeof obj=='string')return getattr(_b_.str(obj),'__hash__')() if(obj.__hash__===undefined ||isinstance(obj,[_b_.set,_b_.list,_b_.dict])){return obj.__hashvalue__=$B.$py_next_hash++ } if(obj.__hash__ !==undefined)return obj.__hash__() return null } function __import__(mod_name){ var current_frame=$B.frames_stack[$B.frames_stack.length-1] var origin=current_frame[3].__name__ try{$B.$import(mod_name,origin)} catch(err){$B.imported[mod_name]=undefined} if($B.imported[mod_name]===undefined)throw _b_.ImportError(mod_name) return $B.imported[mod_name] } function input(src){return prompt(src)} function isinstance(obj,arg){if(obj===null)return arg===None if(obj===undefined)return false if(arg.constructor===Array){for(var i=0;i<arg.length;i++){if(isinstance(obj,arg[i]))return true } return false } if(arg===_b_.int &&(obj===True ||obj===False)){return True} var klass=$B.get_class(obj) if(klass===undefined){switch(arg){case _b_.int: return((typeof obj)=="number"||obj.constructor===Number)&&(obj.valueOf()%1===0) case _b_.float: return((typeof obj=="number" && obj.valueOf()%1!==0))|| (klass===_b_.float.$dict) case _b_.str: return(typeof obj=="string"||klass===_b_.str.$dict) case _b_.list: return(obj.constructor===Array) default: return false }} if(arg.$dict===undefined){return false} if(klass==$B.$factory){klass=obj.$dict.__class__} for(var i=0;i<klass.__mro__.length;i++){var kl=klass.__mro__[i] if(kl===arg.$dict){return true} else if(arg===_b_.str && kl===$B.$StringSubclassFactory.$dict){return true} else if(arg===_b_.list && kl===$B.$ListSubclassFactory.$dict){return true}} var hook=getattr(arg,'__instancecheck__',null) if(hook!==null){return hook(obj)} return false } function issubclass(klass,classinfo){if(arguments.length!==2){throw _b_.TypeError("issubclass expected 2 arguments, got "+arguments.length) } if(!klass.__class__ ||!klass.__class__.is_class){throw _b_.TypeError("issubclass() arg 1 must be a class") } if(isinstance(classinfo,_b_.tuple)){for(var i=0;i<classinfo.length;i++){if(issubclass(klass,classinfo[i]))return true } return false } if(classinfo.__class__.is_class){if(klass.$dict.__mro__.indexOf(classinfo.$dict)>-1){return true}} var hook=getattr(classinfo,'__subclasscheck__',null) if(hook!==null){return hook(klass)} return false } function iter(obj){try{return getattr(obj,'__iter__')()} catch(err){$B.$pop_exc() throw _b_.TypeError("'"+$B.get_class(obj).__name__+"' object is not iterable") }} function len(obj){try{return getattr(obj,'__len__')()} catch(err){throw _b_.TypeError("object of type '"+$B.get_class(obj).__name__+"' has no len()") }} function locals(){ var locals_obj=$B.last($B.frames_stack)[1] return $B.obj_dict(locals_obj) } var $MapDict={__class__:$B.$type,__name__:'map'} $MapDict.__mro__=[$MapDict,$ObjectDict] $MapDict.__iter__=function(self){return self} function map(){var func=getattr(arguments[0],'__call__') var iter_args=[],pos=0 for(var i=1;i<arguments.length;i++){iter_args[pos++]=iter(arguments[i])} var __next__=function(){var args=[],pos=0 for(var i=0;i<iter_args.length;i++){try{args[pos++]=next(iter_args[i]) }catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();throw _b_.StopIteration('') }else{throw err}}} return func.apply(null,args) } var obj={__class__:$MapDict,__repr__:function(){return "<map object>"},__str__:function(){return "<map object>"},__next__: __next__ } return obj } function $extreme(args,op){ var $op_name='min' if(op==='__gt__')$op_name="max" if(args.length==0){throw _b_.TypeError($op_name+" expected 1 arguments, got 0")} var last_arg=args[args.length-1] var nb_args=args.length var has_kw_args=false var has_default=false var func=false if(last_arg.$nat=='kw'){nb_args-- last_arg=last_arg.kw for(var attr in last_arg){switch(attr){case 'key': var func=last_arg[attr] has_key=true break case '$$default': var default_value=last_arg[attr] has_default=true break default: throw _b_.TypeError("'"+attr+"' is an invalid keyword argument for this function") break }}} if(!func){func=function(x){return x}} if(nb_args==0){throw _b_.TypeError($op_name+" expected 1 arguments, got 0") }else if(nb_args==1){ var $iter=iter(args[0]),res=null while(true){try{var x=next($iter) if(res===null ||bool(getattr(func(x),op)(func(res)))){res=x}}catch(err){if(err.__name__=="StopIteration"){$B.$pop_exc() if(res===null){if(has_default){return default_value} else{throw _b_.ValueError($op_name+"() arg is an empty sequence")}}else{return res}} throw err }}}else{if(has_default){throw _b_.TypeError("Cannot specify a default for "+$op_name+"() with multiple positional arguments") } var res=null for(var i=0;i<nb_args;i++){var x=args[i] if(res===null ||bool(getattr(func(x),op)(func(res)))){res=x}} return res }} function max(){var args=[],pos=0 for(var i=0;i<arguments.length;i++){args[pos++]=arguments[i]} return $extreme(args,'__gt__') } function memoryview(obj){throw NotImplementedError('memoryview is not implemented') } function min(){var args=[],pos=0 for(var i=0;i<arguments.length;i++){args[pos++]=arguments[i]} return $extreme(args,'__lt__') } function next(obj){var ga=getattr(obj,'__next__') if(ga!==undefined)return ga() throw _b_.TypeError("'"+$B.get_class(obj).__name__+"' object is not an iterator") } var $NotImplementedDict={__class__:$B.$type,__name__:'NotImplementedType'} $NotImplementedDict.__mro__=[$NotImplementedDict,$ObjectDict] $NotImplementedDict.__repr__=$NotImplementedDict.__str__=function(){return 'NotImplemented'} var NotImplemented={__class__ : $NotImplementedDict,} function $not(obj){return !bool(obj)} function oct(x){return $builtin_base_convert_helper(x,8)} function ord(c){ return c.charCodeAt(0) } function pow(){var $ns=$B.$MakeArgs('pow',arguments,[],[],'args','kw') var args=$ns['args'] if(args.length<2){throw _b_.TypeError( "pow expected at least 2 arguments, got "+args.length) } if(args.length>3){throw _b_.TypeError( "pow expected at most 3 arguments, got "+args.length) } if(args.length===2){var x=args[0] var y=args[1] var a,b if(isinstance(x,_b_.float)){a=x.value }else if(isinstance(x,_b_.int)){a=x }else{throw _b_.TypeError("unsupported operand type(s) for ** or pow()") } if(isinstance(y,_b_.float)){b=y.value }else if(isinstance(y,_b_.int)){b=y }else{ throw _b_.TypeError("unsupported operand type(s) for ** or pow()") } return Math.pow(a,b) } if(args.length===3){var x=args[0] var y=args[1] var z=args[2] var _err="pow() 3rd argument not allowed unless all arguments are integers" if(!isinstance(x,_b_.int))throw _b_.TypeError(_err) if(!isinstance(y,_b_.int))throw _b_.TypeError(_err) if(!isinstance(z,_b_.int))throw _b_.TypeError(_err) return Math.pow(x,y)%z }} function $print(){var end='\n',sep=' ',file=$B.stdout var $ns=$B.$MakeArgs('print',arguments,[],['end','sep','file'],'args',null) for(var attr in $ns){eval('var '+attr+'=$ns[attr]')} getattr(file,'write')(args.map(_b_.str).join(sep)+end) } $print.__name__='print' function $prompt(text,fill){return prompt(text,fill ||'')} var $PropertyDict={__class__ : $B.$type,__name__ : 'property',__repr__ : function(){return "<property object>"},__str__ : function(){return "<property object>"},toString : function(){return "property"}} $PropertyDict.__mro__=[$PropertyDict,$ObjectDict] $B.$PropertyDict=$PropertyDict function property(fget,fset,fdel,doc){var p={__class__ : $PropertyDict,__doc__ : doc ||"",$type:fget.$type,fget:fget,fset:fset,fdel:fdel,toString:function(){return '<property>'}} p.__get__=function(self,obj,objtype){if(obj===undefined)return self if(self.fget===undefined)throw _b_.AttributeError("unreadable attribute") return getattr(self.fget,'__call__')(obj) } if(fset!==undefined){p.__set__=function(self,obj,value){if(self.fset===undefined)throw _b_.AttributeError("can't set attribute") getattr(self.fset,'__call__')(obj,value) }} p.__delete__=fdel p.getter=function(fget){return property(fget,p.fset,p.fdel,p.__doc__)} p.setter=function(fset){return property(p.fget,fset,p.fdel,p.__doc__)} p.deleter=function(fdel){return property(p.fget,p.fset,fdel,p.__doc__)} return p } property.__class__=$B.$factory property.$dict=$PropertyDict var $RangeDict={__class__:$B.$type,__dir__:$ObjectDict.__dir__,__name__:'range',$native:true } $RangeDict.__contains__=function(self,other){var x=iter(self) while(1){try{var y=$RangeDict.__next__(x) if(getattr(y,'__eq__')(other)){return true}}catch(err){return false}} return false } $RangeDict.__getitem__=function(self,rank){if(typeof rank !="number"){rank=$B.$GetInt(rank) } var res=self.start + rank*self.step if((self.step>0 && res >=self.stop)|| (self.step<0 && res < self.stop)){throw _b_.IndexError('range object index out of range') } return res } $RangeDict.__getitems__=function(self){var t=[],rank=0 while(1){var res=self.start + rank*self.step if((self.step>0 && res >=self.stop)|| (self.step<0 && res < self.stop)){break } t[rank++]=res } return t } $RangeDict.__iter__=function(self){return{ __class__ : $RangeDict,start:self.start,stop:self.stop,step:self.step,$counter:self.start-self.step }} $RangeDict.__len__=function(self){if(self.step>0)return 1+_b_.int((self.stop-1-self.start)/self.step) return 1+_b_.int((self.start-1-self.stop)/-self.step) } $RangeDict.__next__=function(self){self.$counter +=self.step if((self.step>0 && self.$counter >=self.stop) ||(self.step<0 && self.$counter <=self.stop)){throw _b_.StopIteration('') } return self.$counter } $RangeDict.__mro__=[$RangeDict,$ObjectDict] $RangeDict.__reversed__=function(self){return range(self.stop-1,self.start-1,-self.step) } $RangeDict.__repr__=$RangeDict.__str__=function(self){var res='range('+self.start+', '+self.stop if(self.step!=1)res +=', '+self.step return res+')' } function range(){var $ns=$B.$MakeArgs('range',arguments,[],[],'args',null) var args=$ns['args'] if(args.length>3){throw _b_.TypeError( "range expected at most 3 arguments, got "+args.length) } var start=0 var stop=0 var step=1 if(args.length==1){stop=args[0]} else if(args.length>=2){start=args[0] stop=args[1] } if(args.length>=3)step=args[2] if(step==0){throw ValueError("range() arg 3 must not be zero")} var res={__class__ : $RangeDict,start:start,stop:stop,step:step,$is_range:true } res.__repr__=res.__str__=function(){return 'range('+start+','+stop+(args.length>=3 ? ','+step : '')+')' } return res } range.__class__=$B.$factory range.$dict=$RangeDict $RangeDict.$factory=range function repr(obj){if(obj.__class__===$B.$factory){ var func=$B.$type.__getattribute__(obj.$dict.__class__,'__repr__') return func(obj) } var func=getattr(obj,'__repr__') if(func!==undefined)return func() throw _b_.AttributeError("object has no attribute __repr__") } var $ReversedDict={__class__:$B.$type,__name__:'reversed'} $ReversedDict.__mro__=[$ReversedDict,$ObjectDict] $ReversedDict.__iter__=function(self){return self} $ReversedDict.__next__=function(self){self.$counter-- if(self.$counter<0)throw _b_.StopIteration('') return self.getter(self.$counter) } function reversed(seq){ try{return getattr(seq,'__reversed__')()} catch(err){if(err.__name__=='AttributeError'){$B.$pop_exc()} else{throw err}} try{var res={__class__:$ReversedDict,$counter : getattr(seq,'__len__')(),getter:getattr(seq,'__getitem__') } return res }catch(err){throw _b_.TypeError("argument to reversed() must be a sequence") }} reversed.__class__=$B.$factory reversed.$dict=$ReversedDict $ReversedDict.$factory=reversed function round(arg,n){if(!isinstance(arg,[_b_.int,_b_.float])){throw _b_.TypeError("type "+arg.__class__+" doesn't define __round__ method") } if(isinstance(arg,_b_.float)&&(arg.value===Infinity ||arg.value===-Infinity)){throw _b_.OverflowError("cannot convert float infinity to integer") } if(n===undefined)return _b_.int(Math.round(arg)) if(!isinstance(n,_b_.int)){throw _b_.TypeError( "'"+n.__class__+"' object cannot be interpreted as an integer")} var mult=Math.pow(10,n) return _b_.int.$dict.__truediv__(Number(Math.round(arg.valueOf()*mult)),mult) } function setattr(obj,attr,value){if(!isinstance(attr,_b_.str)){throw _b_.TypeError("setattr(): attribute name must be string") } switch(attr){case 'alert': case 'case': case 'catch': case 'constructor': case 'Date': case 'delete': case 'default': case 'document': case 'Error': case 'history': case 'function': case 'location': case 'Math': case 'new': case 'Number': case 'RegExp': case 'this': case 'throw': case 'var': case 'super': case 'window': attr='$$'+attr break case '__class__': obj.__class__=value.$dict;return break } if(obj.__class__===$B.$factory){ if(obj.$dict.$methods && typeof value=='function'){ obj.$dict.$methods[attr]=$B.make_method(attr,obj.$dict,value,value) return }else{obj.$dict[attr]=value;return}} var res=obj[attr],klass=$B.get_class(obj) if(res===undefined){var mro=klass.__mro__,_len=mro.length for(var i=0;i<_len;i++){res=mro[i][attr] if(res!==undefined)break }} if(res!==undefined){ if(res.__set__!==undefined)return res.__set__(res,obj,value) var __set__=getattr(res,'__set__',null) if(__set__ &&(typeof __set__=='function')){return __set__.apply(res,[obj,value]) }} var setattr=false if(klass!==undefined){for(var i=0,_len=klass.__mro__.length;i<_len;i++){setattr=klass.__mro__[i].__setattr__ if(setattr){break}}} if(!setattr){obj[attr]=value;return} setattr(obj,attr,value) } var $SliceDict={__class__:$B.$type,__name__:'slice'} $SliceDict.__mro__=[$SliceDict,$ObjectDict] $SliceDict.indices=function(self,length){var len=$B.$GetInt(length) if(len < 0)_b_.ValueError('length should not be negative') if(self.step > 0){var _len=min(len,self.stop) return _b_.tuple([self.start,_len,self.step]) }else if(self.step==_b_.None){var _len=min(len,self.stop) var _start=self.start if(_start==_b_.None)_start=0 return _b_.tuple([_start,_len,1]) } _b_.NotImplementedError("Error! negative step indices not implemented yet") } function slice(){var $ns=$B.$MakeArgs('slice',arguments,[],[],'args',null) var args=$ns['args'] if(args.length>3){throw _b_.TypeError( "slice expected at most 3 arguments, got "+args.length) }else if(args.length==0){throw _b_.TypeError('slice expected at least 1 arguments, got 0') } var start=0,stop=0,step=1 switch(args.length){case 1: step=start=None stop=$B.$GetInt(args[0]) break case 2: start=$B.$GetInt(args[0]) stop=$B.$GetInt(args[1]) break case 3: start=$B.$GetInt(args[0]) stop=$B.$GetInt(args[1]) step=$B.$GetInt(args[2]) } if(step==0)throw ValueError("slice step must not be zero") var res={__class__ : $SliceDict,start:start,stop:stop,step:step } res.__repr__=res.__str__=function(){return 'slice('+start+','+stop+','+step+')' } return res } slice.__class__=$B.$factory slice.$dict=$SliceDict $SliceDict.$factory=slice function sorted(){var $ns=$B.$MakeArgs('sorted',arguments,['iterable'],[],null,'kw') if($ns['iterable']===undefined)throw _b_.TypeError("sorted expected 1 positional argument, got 0") var iterable=$ns['iterable'] var key=_b_.dict.$dict.get($ns['kw'],'key',None) var reverse=_b_.dict.$dict.get($ns['kw'],'reverse',false) var obj=_b_.list(iterable) var args=[obj],pos=1 if(key !==None)args[pos++]={$nat:'kw',kw:{key:key}} if(reverse)args[pos++]={$nat:'kw',kw:{reverse:true}} _b_.list.$dict.sort.apply(null,args) return obj } var $StaticmethodDict={__class__:$B.$type,__name__:'staticmethod'} $StaticmethodDict.__mro__=[$StaticmethodDict,$ObjectDict] function staticmethod(func){func.$type='staticmethod' return func } staticmethod.__class__=$B.$factory staticmethod.$dict=$StaticmethodDict $StaticmethodDict.$factory=staticmethod function sum(iterable,start){if(start===undefined)start=0 var res=start var iterable=iter(iterable) while(1){try{var _item=next(iterable) res=getattr(res,'__add__')(_item) }catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();break} else{throw err}}} return res } var $SuperDict={__class__:$B.$type,__name__:'super'} $SuperDict.__getattribute__=function(self,attr){var mro=self.__thisclass__.$dict.__mro__,res for(var i=1;i<mro.length;i++){ res=mro[i][attr] if(res!==undefined){ if(self.__self_class__!==None){var _args=[self.__self_class__] if(attr=='__new__'){_args=[]} var method=(function(initial_args){return function(){ var local_args=initial_args.slice() var pos=initial_args.length for(var i=0;i<arguments.length;i++){local_args[pos++]=arguments[i] } var x=res.apply(null,local_args) if(x===undefined)return None return x }})(_args) method.__class__={__class__:$B.$type,__name__:'method',__mro__:[$ObjectDict] } method.__func__=res method.__self__=self return method } return res }} throw _b_.AttributeError("object 'super' has no attribute '"+attr+"'") } $SuperDict.__mro__=[$SuperDict,$ObjectDict] $SuperDict.__repr__=$SuperDict.__str__=function(self){return "<object 'super'>"} function $$super(_type1,_type2){return{__class__:$SuperDict,__thisclass__:_type1,__self_class__:(_type2 ||None) }} $$super.$dict=$SuperDict $$super.__class__=$B.$factory $SuperDict.$factory=$$super $$super.$is_func=true var $Reader={__class__:$B.$type,__name__:'reader'} $Reader.__enter__=function(self){return self} $Reader.__exit__=function(self){return false} $Reader.__iter__=function(self){return iter(self.$lines)} $Reader.__len__=function(self){return self.lines.length} $Reader.__mro__=[$Reader,$ObjectDict] $Reader.close=function(self){self.closed=true} $Reader.read=function(self,nb){if(self.closed===true)throw _b_.ValueError('I/O operation on closed file') if(nb===undefined)return self.$content self.$counter+=nb return self.$content.substr(self.$counter-nb,nb) } $Reader.readable=function(self){return true} $Reader.readline=function(self,limit){if(self.closed===true)throw _b_.ValueError('I/O operation on closed file') var line='' if(limit===undefined||limit===-1)limit=null while(1){if(self.$counter>=self.$content.length-1)break var car=self.$content.charAt(self.$counter) if(car=='\n'){self.$counter++;return line} line +=car if(limit!==null && line.length>=limit)return line self.$counter++ } return '0' } $Reader.readlines=function(self,hint){if(self.closed===true)throw _b_.ValueError('I/O operation on closed file') var x=self.$content.substr(self.$counter).split('\n') if(hint && hint!==-1){var y=[],size=0,pos=0 while(1){var z=x.shift() size +=z.length y[pos++]=z if(size>hint ||x.length==0)return y }} return x } $Reader.seek=function(self,offset,whence){if(self.closed===True)throw _b_.ValueError('I/O operation on closed file') if(whence===undefined)whence=0 if(whence===0){self.$counter=offset} else if(whence===1){self.$counter +=offset} else if(whence===2){self.$counter=self.$content.length+offset}} $Reader.seekable=function(self){return true} $Reader.tell=function(self){return self.$counter} $Reader.writable=function(self){return false} var $BufferedReader={__class__:$B.$type,__name__:'_io.BufferedReader'} $BufferedReader.__mro__=[$BufferedReader,$Reader,$ObjectDict] var $TextIOWrapper={__class__:$B.$type,__name__:'_io.TextIOWrapper'} $TextIOWrapper.__mro__=[$TextIOWrapper,$Reader,$ObjectDict] function $url_open(){ var mode='r',encoding='utf-8' var $ns=$B.$MakeArgs('open',arguments,['file'],['mode','encoding'],'args','kw') for(var attr in $ns){eval('var '+attr+'=$ns["'+attr+'"]')} if(args.length>0)var mode=args[0] if(args.length>1)var encoding=args[1] if(isinstance(file,$B.JSObject))return new $OpenFile(file.js,mode,encoding) if(isinstance(file,_b_.str)){ if(window.XMLHttpRequest){ var req=new XMLHttpRequest() }else{ var req=new ActiveXObject("Microsoft.XMLHTTP") } req.onreadystatechange=function(){var status=req.status if(status===404){$res=_b_.IOError('File '+file+' not found') }else if(status!==200){$res=_b_.IOError('Could not open file '+file+' : status '+status) }else{$res=req.responseText }} var fake_qs='?foo='+$B.UUID() req.open('GET',file+fake_qs,false) var is_binary=mode.search('b')>-1 if(is_binary){req.overrideMimeType('text/plain; charset=iso-8859-1') } req.send() if($res.constructor===Error)throw $res var lines=$res.split('\n') var res={$content:$res,$counter:0,$lines:lines,closed:False,encoding:encoding,mode:mode,name:file } res.__class__=is_binary ? $BufferedReader : $TextIOWrapper return res }} var $ZipDict={__class__:$B.$type,__name__:'zip'} var $zip_iterator=$B.$iterator_class('zip_iterator') $ZipDict.__iter__=function(self){return $B.$iterator(self.items,$zip_iterator) } $ZipDict.__mro__=[$ZipDict,$ObjectDict] function zip(){var res={__class__:$ZipDict,items:[]} if(arguments.length==0)return res var $ns=$B.$MakeArgs('zip',arguments,[],[],'args','kw') var _args=$ns['args'] var args=[],pos=0 for(var i=0;i<_args.length;i++){args[pos++]=iter(_args[i])} var kw=$ns['kw'] var rank=0,items=[] while(1){var line=[],flag=true,pos=0 for(var i=0;i<args.length;i++){try{line[pos++]=next(args[i]) }catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();flag=false;break} else{throw err}}} if(!flag)break items[rank++]=_b_.tuple(line) } res.items=items return res } zip.__class__=$B.$factory zip.$dict=$ZipDict $ZipDict.$factory=zip function no_set_attr(klass,attr){if(klass[attr]!==undefined){throw _b_.AttributeError("'"+klass.__name__+"' object attribute '"+ attr+"' is read-only") }else{throw _b_.AttributeError("'"+klass.__name__+ "' object has no attribute '"+attr+"'") }} var $BoolDict=$B.$BoolDict={__class__:$B.$type,__dir__:$ObjectDict.__dir__,__name__:'bool',$native:true } $BoolDict.__mro__=[$BoolDict,$ObjectDict] bool.__class__=$B.$factory bool.$dict=$BoolDict $BoolDict.$factory=bool $BoolDict.__add__=function(self,other){if(self.valueOf())return other + 1 return other } var True=true var False=false $BoolDict.__eq__=function(self,other){if(self.valueOf())return !!other return !other } $BoolDict.__ne__=function(self,other){if(self.valueOf())return !other return !!other } $BoolDict.__ge__=function(self,other){return _b_.int.$dict.__ge__($BoolDict.__hash__(self),other) } $BoolDict.__gt__=function(self,other){return _b_.int.$dict.__gt__($BoolDict.__hash__(self),other) } $BoolDict.__hash__=$BoolDict.__index__=$BoolDict.__int__=function(self){if(self.valueOf())return 1 return 0 } $BoolDict.__le__=function(self,other){return !$BoolDict.__gt__(self,other)} $BoolDict.__lt__=function(self,other){return !$BoolDict.__ge__(self,other)} $BoolDict.__mul__=function(self,other){if(self.valueOf())return other return 0 } $BoolDict.__repr__=$BoolDict.__str__=function(self){if(self.valueOf())return "True" return "False" } $BoolDict.__setattr__=function(self,attr){return no_set_attr($BoolDict,attr) } $BoolDict.__sub__=function(self,other){if(self.valueOf())return 1-other return -other } $BoolDict.__xor__=function(self,other){return self.valueOf()!=other.valueOf() } var $EllipsisDict={__class__:$B.$type,__name__:'Ellipsis',} $EllipsisDict.__mro__=[$ObjectDict] $EllipsisDict.$factory=$EllipsisDict var Ellipsis={__bool__ : function(){return True},__class__ : $EllipsisDict,__repr__ : function(){return 'Ellipsis'},__str__ : function(){return 'Ellipsis'},toString : function(){return 'Ellipsis'}} for(var $key in $B.$comps){ switch($B.$comps[$key]){case 'ge': case 'gt': case 'le': case 'lt': Ellipsis['__'+$B.$comps[$key]+'__']=(function(k){return function(other){throw _b_.TypeError("unorderable types: ellipsis() "+k+" "+ $B.get_class(other).__name__)}})($key) }} for(var $func in Ellipsis){if(typeof Ellipsis[$func]==='function'){Ellipsis[$func].__str__=(function(f){return function(){return "<method-wrapper "+f+" of Ellipsis object>"}})($func) }} var $NoneDict={__class__:$B.$type,__name__:'NoneType'} $NoneDict.__mro__=[$NoneDict,$ObjectDict] $NoneDict.__setattr__=function(self,attr){return no_set_attr($NoneDict,attr) } var None={__bool__ : function(){return False},__class__ : $NoneDict,__hash__ : function(){return 0},__repr__ : function(){return 'None'},__str__ : function(){return 'None'},toString : function(){return 'None'}} $NoneDict.$factory=function(){return None} $NoneDict.$factory.__class__=$B.$factory $NoneDict.$factory.$dict=$NoneDict for(var $op in $B.$comps){ var key=$B.$comps[$op] switch(key){case 'ge': case 'gt': case 'le': case 'lt': $NoneDict['__'+key+'__']=(function(op){return function(other){throw _b_.TypeError("unorderable types: NoneType() "+op+" "+ $B.get_class(other).__name__+"()")}})($op) }} for(var $func in None){if(typeof None[$func]==='function'){None[$func].__str__=(function(f){return function(){return "<method-wrapper "+f+" of NoneType object>"}})($func) }} var $FunctionCodeDict={__class__:$B.$type,__name__:'function code'} $FunctionCodeDict.__mro__=[$FunctionCodeDict,$ObjectDict] $FunctionCodeDict.$factory={__class__:$B.$factory,$dict:$FunctionCodeDict} var $FunctionGlobalsDict={__class:$B.$type,__name__:'function globals'} $FunctionGlobalsDict.__mro__=[$FunctionGlobalsDict,$ObjectDict] $FunctionGlobalsDict.$factory={__class__:$B.$factory,$dict:$FunctionGlobalsDict} var $FunctionDict=$B.$FunctionDict={__class__:$B.$type,__code__:{__class__:$FunctionCodeDict,__name__:'function code'},__globals__:{__class__:$FunctionGlobalsDict,__name__:'function globals'},__name__:'function' } $FunctionDict.__getattribute__=function(self,attr){ if(self.$infos && self.$infos[attr]!==undefined){if(attr=='__code__'){var res={__class__:$B.$CodeDict} for(var attr in self.$infos.__code__){res[attr]=self.$infos.__code__[attr] } return res }else{return self.$infos[attr] }}else{return _b_.object.$dict.__getattribute__(self,attr) }} $FunctionDict.__repr__=$FunctionDict.__str__=function(self){return '<function '+self.$infos.__name__+'>' } $FunctionDict.__mro__=[$FunctionDict,$ObjectDict] var $Function=function(){} $Function.__class__=$B.$factory $FunctionDict.$factory=$Function $Function.$dict=$FunctionDict var $BaseExceptionDict={__class__:$B.$type,__bases__ :[_b_.object],__module__:'builtins',__name__:'BaseException' } $BaseExceptionDict.__init__=function(self){self.args=_b_.tuple([arguments[1]]) } $BaseExceptionDict.__repr__=function(self){if(self.$message===None){return $B.get_class(self).__name__+'()'} return self.$message } $BaseExceptionDict.__str__=$BaseExceptionDict.__repr__ $BaseExceptionDict.__mro__=[$BaseExceptionDict,$ObjectDict] $BaseExceptionDict.__new__=function(cls){var err=_b_.BaseException() err.__name__=cls.$dict.__name__ err.__class__=cls.$dict return err } $BaseExceptionDict.__getattr__=function(self,attr){if(attr=='info'){var info='Traceback (most recent call last):' if(self.$js_exc!==undefined){for(var attr in self.$js_exc){if(attr==='message')continue try{info +='\n '+attr+' : '+self.$js_exc[attr]} catch(_err){}} info+='\n' } var last_info,tb=null for(var i=0;i<self.$call_stack.length;i++){var call_info=self.$call_stack[i].split(',') var lib_module=call_info[1] var caller=$B.modules[lib_module].line_info if(caller!==undefined){call_info=caller.split(',') lib_module=caller[1] } var lines=$B.$py_src[call_info[1]].split('\n') info +='\n module '+lib_module+' line '+call_info[0] var line=lines[call_info[0]-1] if(line)line=line.replace(/^[]+/g,'') info +='\n '+line last_info=call_info } if(self.$line_info!=last_info){var err_info=self.$line_info.split(',') var line=$B.$py_src[err_info[1]].split('\n')[parseInt(err_info[0])-1] if(line)line=line.replace(/^[]+/g,'') self.$last_info=err_info self.$line=line info +='\n module '+err_info[1]+' line '+err_info[0] info +='\n '+line } return info }else if(attr=='traceback'){ if($B.debug==0){ return traceback({tb_frame:frame(self.$frames_stack),tb_lineno:0,tb_lasti:-1,tb_next: None }) } $BaseExceptionDict.__getattr__(self,'info') return traceback({tb_frame:frame(self.$frames_stack),tb_lineno:parseInt(self.$last_info[0]),tb_lasti:self.$line,tb_next: None }) }else{throw AttributeError(self.__class__.__name__+ "has no attribute '"+attr+"'") }} var $TracebackDict={__class__:$B.$type,__name__:'traceback' } $TracebackDict.__mro__=[$TracebackDict,$ObjectDict] function traceback(tb){tb.__class__=$TracebackDict return tb } traceback.__class__=$B.$factory traceback.$dict=$TracebackDict $TracebackDict.$factory=traceback var $FrameDict={__class__:$B.$type,__name__:'frame' } $FrameDict.__mro__=[$FrameDict,$ObjectDict] function to_dict(obj){var res=_b_.dict() var setitem=_b_.dict.$dict.__setitem__ for(var attr in obj){if(attr.charAt(0)=='$'){continue} setitem(res,attr,obj[attr]) } return res } function frame(stack,pos){var mod_name=stack[2] var fs=stack var res={__class__:$FrameDict,f_builtins :{} } if(pos===undefined){pos=fs.length-1} if(fs.length){var _frame=fs[pos] if(_frame[1]===undefined){alert('frame undef '+stack+' '+Array.isArray(stack)+' is frames stack '+(stack===$B.frames_stack))} var locals_id=_frame[0] try{res.f_locals=$B.obj_dict(_frame[1]) }catch(err){console.log('err '+err) throw err } res.f_globals=$B.obj_dict(_frame[3]) if($B.debug>0){res.f_lineno=parseInt($B.line_info.split(',')[0]) }else{res.f_lineno=-1 } if(pos>0){res.f_back=frame(stack,pos-1)} else{res.f_back=None} res.f_code={__class__:$B.$CodeDict,co_code:None, co_name: locals_id, co_filename: "<unknown>" }} return res } frame.__class__=$B.$factory frame.$dict=$FrameDict $FrameDict.$factory=frame $B._frame=frame var BaseException=function(msg,js_exc){var err=Error() err.__name__='BaseException' err.$line_info=$B.line_info err.$call_stack=$B.call_stack.slice() err.$frames_stack=$B.frames_stack.slice() err.$js_exc=js_exc if(msg===undefined)msg='BaseException' err.args=_b_.tuple([msg]) err.$message=msg err.__class__=$BaseExceptionDict err.$py_error=true $B.exception_stack[$B.exception_stack.length]=err return err } BaseException.__name__='BaseException' BaseException.__class__=$B.$factory BaseException.$dict=$BaseExceptionDict _b_.BaseException=BaseException $B.exception=function(js_exc){ if(!js_exc.$py_error){ console.log(js_exc) if($B.debug>0 && js_exc.info===undefined){if($B.line_info!==undefined){var line_info=$B.line_info.split(',') var mod_name=line_info[1] var module=$B.modules[mod_name] if(module){if(module.caller!==undefined){ $B.line_info=module.caller var mod_name=line_info[1] } var lib_module=mod_name if(lib_module.substr(0,13)==='__main__,exec'){lib_module='__main__'} var line_num=parseInt(line_info[0]) if($B.$py_src[mod_name]===undefined){console.log('pas de py_src pour '+mod_name) } var lines=$B.$py_src[mod_name].split('\n') js_exc.message +="\n module '"+lib_module+"' line "+line_num js_exc.message +='\n'+lines[line_num-1] js_exc.info_in_msg=true }}else{console.log('error '+js_exc) }} var exc=Error() exc.__name__='Internal Javascript error: '+(js_exc.__name__ ||js_exc.name) exc.__class__=_b_.Exception.$dict if(js_exc.name=='ReferenceError'){exc.__name__='NameError' exc.__class__=_b_.NameError.$dict js_exc.message=js_exc.message.replace('$$','') } exc.$message=js_exc.message ||'<'+js_exc+'>' exc.args=_b_.tuple([exc.$message]) exc.info='' exc.$py_error=true exc.traceback=traceback({tb_frame:frame($B.frames_stack),tb_lineno:-1,tb_lasti:'',tb_next: None }) }else{var exc=js_exc } $B.exception_stack[$B.exception_stack.length]=exc return exc } $B.is_exc=function(exc,exc_list){ if(exc.__class__===undefined)exc=$B.exception(exc) var exc_class=exc.__class__.$factory for(var i=0;i<exc_list.length;i++){if(issubclass(exc_class,exc_list[i]))return true } return false } $B.builtins_block={id:'__builtins__',module:'__builtins__'} $B.modules['__builtins__']=$B.builtins_block $B.bound['__builtins__']={'__BRYTHON__':true,'$eval':true,'$open': true} $B.bound['__builtins__']['BaseException']=true _b_.__BRYTHON__=__BRYTHON__ function $make_exc(names,parent){ var _str=[],pos=0 for(var i=0;i<names.length;i++){var name=names[i] $B.bound['__builtins__'][name]=true var $exc=(BaseException+'').replace(/BaseException/g,name) _str[pos++]='var $'+name+'Dict={__class__:$B.$type,__name__:"'+name+'"}' _str[pos++]='$'+name+'Dict.__bases__ = [parent]' _str[pos++]='$'+name+'Dict.__module__ = "builtins"' _str[pos++]='$'+name+'Dict.__mro__=[$'+name+'Dict].concat(parent.$dict.__mro__)' _str[pos++]='_b_.'+name+'='+$exc _str[pos++]='_b_.'+name+'.__repr__ = function(){return "<class '+"'"+name+"'"+'>"}' _str[pos++]='_b_.'+name+'.__str__ = function(){return "<class '+"'"+name+"'"+'>"}' _str[pos++]='_b_.'+name+'.__class__=$B.$factory' _str[pos++]='$'+name+'Dict.$factory=_b_.'+name _str[pos++]='_b_.'+name+'.$dict=$'+name+'Dict' } eval(_str.join(';')) } $make_exc(['SystemExit','KeyboardInterrupt','GeneratorExit','Exception'],BaseException) $make_exc(['StopIteration','ArithmeticError','AssertionError','AttributeError','BufferError','EOFError','ImportError','LookupError','MemoryError','NameError','OSError','ReferenceError','RuntimeError','SyntaxError','SystemError','TypeError','ValueError','Warning'],_b_.Exception) $make_exc(['FloatingPointError','OverflowError','ZeroDivisionError'],_b_.ArithmeticError) $make_exc(['IndexError','KeyError'],_b_.LookupError) $make_exc(['UnboundLocalError'],_b_.NameError) $make_exc(['BlockingIOError','ChildProcessError','ConnectionError','FileExistsError','FileNotFoundError','InterruptedError','IsADirectoryError','NotADirectoryError','PermissionError','ProcessLookupError','TimeoutError'],_b_.OSError) $make_exc(['BrokenPipeError','ConnectionAbortedError','ConnectionRefusedError','ConnectionResetError'],_b_.ConnectionError) $make_exc(['NotImplementedError'],_b_.RuntimeError) $make_exc(['IndentationError'],_b_.SyntaxError) $make_exc(['TabError'],_b_.IndentationError) $make_exc(['UnicodeError'],_b_.ValueError) $make_exc(['UnicodeDecodeError','UnicodeEncodeError','UnicodeTranslateError'],_b_.UnicodeError) $make_exc(['DeprecationWarning','PendingDeprecationWarning','RuntimeWarning','SyntaxWarning','UserWarning','FutureWarning','ImportWarning','UnicodeWarning','BytesWarning','ResourceWarning'],_b_.Warning) $make_exc(['EnvironmentError','IOError','VMSError','WindowsError'],_b_.OSError) $B.$NameError=function(name){ throw _b_.NameError(name) } $B.$TypeError=function(msg){throw _b_.TypeError(msg) } var builtin_funcs=['abs','all','any','ascii','bin','bool','bytearray','bytes','callable','chr','classmethod','compile','complex','delattr','dict','dir','divmod','enumerate','eval','exec','exit','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','$$super','tuple','type','vars','zip'] for(var i=0;i<builtin_funcs.length;i++){var name=builtin_funcs[i] if(name=='open'){name1='$url_open'} if(name=='super'){name='$$super'} if(name=='eval'){name='$eval'} $B.builtin_funcs[name]=true } $B.builtin_funcs['$eval']=true var other_builtins=['Ellipsis','False','None','True','__build_class__','__debug__','__doc__','__import__','__name__','__package__','copyright','credits','license','NotImplemented','type'] var builtin_names=builtin_funcs.concat(other_builtins) for(var i=0;i<builtin_names.length;i++){var name=builtin_names[i] var orig_name=name var name1=name if(name=='open'){name1='$url_open'} if(name=='super'){name='$$super'} if(name=='eval'){name=name1='$eval'} if(name=='print'){name1='$print'} $B.bound['__builtins__'][name]=true try{_b_[name]=eval(name1) if($B.builtin_funcs[name]!==undefined){ if(_b_[name].__repr__===undefined){ _b_[name].__repr__=_b_[name].__str__=(function(x){return function(){return '<built-in function '+x+'>'}})(orig_name) } _b_[name].__module__='builtins' _b_[name].__name__=name _b_[name].__defaults__=_b_[name].__defaults__ ||[] _b_[name].__kwdefaults__=_b_[name].__kwdefaults__ ||{} _b_[name].__annotations__=_b_[name].__annotations__ ||{}} _b_[name].__doc__=_b_[name].__doc__ ||'' } catch(err){}} $B._alert=_alert _b_['$eval']=$eval _b_['open']=$url_open _b_['print']=$print _b_['$$super']=$$super })(__BRYTHON__) ;(function($B){var _b_=$B.builtins var $ObjectDict=_b_.object.$dict var isinstance=_b_.isinstance,getattr=_b_.getattr,None=_b_.None var from_unicode={},to_unicode={} var $BytearrayDict={__class__:$B.$type,__name__:'bytearray'} var mutable_methods=['__delitem__','clear','copy','count','index','pop','remove','reverse','sort'] for(var i=0,_len_i=mutable_methods.length;i < _len_i;i++){var method=mutable_methods[i] $BytearrayDict[method]=(function(m){return function(self){var args=[self.source],pos=1 for(var i=1,_len_i=arguments.length;i < _len_i;i++)args[pos++]=arguments[i] return _b_.list.$dict[m].apply(null,args) }})(method) } var $bytearray_iterator=$B.$iterator_class('bytearray_iterator') $BytearrayDict.__iter__=function(self){return $B.$iterator(self.source,$bytearray_iterator) } $BytearrayDict.__mro__=[$BytearrayDict,$ObjectDict] $BytearrayDict.__repr__=$BytearrayDict.__str__=function(self){return 'bytearray('+$BytesDict.__repr__(self)+")" } $BytearrayDict.__setitem__=function(self,arg,value){if(isinstance(arg,_b_.int)){if(!isinstance(value,_b_.int)){throw _b_.TypeError('an integer is required') }else if(value>255){throw _b_.ValueError("byte must be in range(0, 256)") } var pos=arg if(arg<0)pos=self.source.length+pos if(pos>=0 && pos<self.source.length){self.source[pos]=value} else{throw _b_.IndexError('list index out of range')}}else if(isinstance(arg,_b_.slice)){var start=arg.start===None ? 0 : arg.start var stop=arg.stop===None ? self.source.length : arg.stop var step=arg.step===None ? 1 : arg.step if(start<0)start=self.source.length+start if(stop<0)stop=self.source.length+stop self.source.splice(start,stop-start) if(_b_.hasattr(value,'__iter__')){var $temp=_b_.list(value) for(var i=$temp.length-1;i>=0;i--){if(!isinstance($temp[i],_b_.int)){throw _b_.TypeError('an integer is required') }else if($temp[i]>255){throw ValueError("byte must be in range(0, 256)") } self.source.splice(start,0,$temp[i]) }}else{throw _b_.TypeError("can only assign an iterable") }}else{ throw _b_.TypeError('list indices must be integer, not '+$B.get_class(arg).__name__) }} $BytearrayDict.append=function(self,b){if(arguments.length!=2){throw _b_.TypeError( "append takes exactly one argument ("+(arguments.length-1)+" given)") } if(!isinstance(b,_b_.int))throw _b_.TypeError("an integer is required") if(b>255)throw ValueError("byte must be in range(0, 256)") self.source[self.source.length]=b } $BytearrayDict.insert=function(self,pos,b){if(arguments.length!=3){throw _b_.TypeError( "insert takes exactly 2 arguments ("+(arguments.length-1)+" given)") } if(!isinstance(b,_b_.int))throw _b_.TypeError("an integer is required") if(b>255)throw ValueError("byte must be in range(0, 256)") _b_.list.$dict.insert(self.source,pos,b) } function bytearray(source,encoding,errors){var _bytes=bytes(source,encoding,errors) var obj={__class__:$BytearrayDict} $BytearrayDict.__init__(obj,source,encoding,errors) return obj } bytearray.__class__=$B.$factory bytearray.$dict=$BytearrayDict $BytearrayDict.$factory=bytearray bytearray.__code__={} bytearray.__code__.co_argcount=1 bytearray.__code__.co_consts=[] bytearray.__code__.co_varnames=['i'] var $BytesDict={__class__ : $B.$type,__name__ : 'bytes'} $BytesDict.__add__=function(self,other){if(!isinstance(other,bytes)){throw _b_.TypeError("can't concat bytes to " + _b_.str(other)) } self.source=self.source.concat(other.source) return self } var $bytes_iterator=$B.$iterator_class('bytes_iterator') $BytesDict.__iter__=function(self){return $B.$iterator(self.source,$bytes_iterator) } $BytesDict.__eq__=function(self,other){return getattr(self.source,'__eq__')(other.source) } $BytesDict.__ge__=function(self,other){return _b_.list.$dict.__ge__(self.source,other.source) } $BytesDict.__getitem__=function(self,arg){var i if(isinstance(arg,_b_.int)){var pos=arg if(arg<0)pos=self.source.length+pos if(pos>=0 && pos<self.source.length)return self.source[pos] throw _b_.IndexError('index out of range') }else if(isinstance(arg,_b_.slice)){var step=arg.step===None ? 1 : arg.step if(step>0){var start=arg.start===None ? 0 : arg.start var stop=arg.stop===None ? getattr(self.source,'__len__')(): arg.stop }else{var start=arg.start===None ? getattr(self.source,'__len__')()-1 : arg.start var stop=arg.stop===None ? 0 : arg.stop } if(start<0)start=self.source.length+start if(stop<0)stop=self.source.length+stop var res=[],i=null,pos=0 if(step>0){if(stop<=start)return '' for(i=start;i<stop;i+=step)res[pos++]=self.source[i] }else{ if(stop>=start)return '' for(i=start;i>=stop;i+=step)res[pos++]=self.source[i] } return bytes(res) }else if(isinstance(arg,bool)){return self.source.__getitem__(_b_.int(arg)) }} $BytesDict.__gt__=function(self,other){return _b_.list.$dict.__gt__(self.source,other.source) } $BytesDict.__hash__=function(self){if(self===undefined){return $BytesDict.__hashvalue__ ||$B.$py_next_hash-- } var hash=1 for(var i=0,_len_i=self.length;i < _len_i;i++){hash=(101*hash + self.source[i])& 0xFFFFFFFF } return hash } $BytesDict.__init__=function(self,source,encoding,errors){var int_list=[],pos=0 if(source===undefined){ }else if(isinstance(source,_b_.int)){var i=source while(i--)int_list[pos++]=0 }else{if(isinstance(source,_b_.str)){if(encoding===undefined) throw _b_.TypeError("string argument without an encoding") int_list=encode(source,encoding) }else{ int_list=_b_.list(source) }} self.source=int_list self.encoding=encoding self.errors=errors } $BytesDict.__le__=function(self,other){return _b_.list.$dict.__le__(self.source,other.source) } $BytesDict.__len__=function(self){return self.source.length} $BytesDict.__lt__=function(self,other){return _b_.list.$dict.__lt__(self.source,other.source) } $BytesDict.__mro__=[$BytesDict,$ObjectDict] $BytesDict.__ne__=function(self,other){return !$BytesDict.__eq__(self,other)} $BytesDict.__repr__=$BytesDict.__str__=function(self){var res="b'" for(var i=0,_len_i=self.source.length;i < _len_i;i++){var s=self.source[i] if(s<32 ||s>=128){var hx=s.toString(16) hx=(hx.length==1 ? '0' : '')+ hx res +='\\x'+hx }else{res +=String.fromCharCode(s) }} return res+"'" } $BytesDict.__reduce_ex__=function(self){return $BytesDict.__repr__(self)} $BytesDict.decode=function(self,encoding,errors){if(encoding===undefined)encoding='utf-8' if(errors===undefined)errors='strict' switch(errors){case 'strict': case 'ignore': case 'replace': case 'surrogateescape': case 'xmlcharrefreplace': case 'backslashreplace': return decode(self.source,encoding,errors) default: }} $BytesDict.maketrans=function(from,to){var _t=[] for(var i=0;i < 256;i++)_t[i]=i for(var i=0,_len_i=from.source.length;i < _len_i;i++){var _ndx=from.source[i] _t[_ndx]=to.source[i] } return bytes(_t) } function _strip(self,cars,lr){if(cars===undefined){cars=[],pos=0 var ws='\r\n \t' for(var i=0,_len_i=ws.length;i < _len_i;i++)cars[pos++]=ws.charCodeAt(i) }else if(isinstance(cars,bytes)){cars=cars.source }else{throw _b_.TypeError("Type str doesn't support the buffer API") } if(lr=='l'){for(var i=0,_len_i=self.source.length;i < _len_i;i++){if(cars.indexOf(self.source[i])==-1)break } return bytes(self.source.slice(i)) } for(var i=self.source.length-1;i>=0;i--){if(cars.indexOf(self.source[i])==-1)break } return bytes(self.source.slice(0,i+1)) } $BytesDict.lstrip=function(self,cars){return _strip(self,cars,'l')} $BytesDict.rstrip=function(self,cars){return _strip(self,cars,'r')} $BytesDict.strip=function(self,cars){var res=$BytesDict.lstrip(self,cars) return $BytesDict.rstrip(res,cars) } $BytesDict.translate=function(self,table,_delete){if(_delete===undefined){_delete=[]} else if(isinstance(_delete,bytes)){_delete=_delete.source} else{throw _b_.TypeError("Type "+$B.get_class(_delete).__name+" doesn't support the buffer API") } var res=[],pos=0 if(isinstance(table,bytes)&& table.source.length==256){for(var i=0,_len_i=self.source.length;i < _len_i;i++){if(_delete.indexOf(self.source[i])>-1)continue res[pos++]=table.source[self.source[i]] }} return bytes(res) } $BytesDict.upper=function(self){var _res=[],pos=0 for(var i=0,_len_i=self.source.length;i < _len_i;i++)_res[pos++]=self.source[i].toUpperCase() return bytes(_res) } function $UnicodeEncodeError(encoding,position){throw _b_.UnicodeEncodeError("'"+encoding+ "' codec can't encode character in position "+position) } function $UnicodeDecodeError(encoding,position){throw _b_.UnicodeDecodeError("'"+encoding+ "' codec can't decode bytes in position "+position) } function _hex(int){return int.toString(16)} function _int(hex){return parseInt(hex,16)} function load_decoder(enc){ if(to_unicode[enc]===undefined){load_encoder(enc) to_unicode[enc]={} for(var attr in from_unicode[enc]){to_unicode[enc][from_unicode[enc][attr]]=attr }}} function load_encoder(enc){ if(from_unicode[enc]===undefined){var url=$B.brython_path if(url.charAt(url.length-1)=='/'){url=url.substr(0,url.length-1)} url +='/encodings/'+enc+'.js' var f=_b_.open(url) eval(f.$content) }} function decode(b,encoding,errors){var s='' switch(encoding.toLowerCase()){case 'utf-8': case 'utf8': var i=0,cp var _int_800=_int('800'),_int_c2=_int('c2'),_int_1000=_int('1000') var _int_e0=_int('e0'),_int_e1=_int('e1'),_int_e3=_int('e3') var _int_a0=_int('a0'),_int_80=_int('80'),_int_2000=_int('2000') while(i<b.length){if(b[i]<=127){s +=String.fromCharCode(b[i]) i +=1 }else if(b[i]<_int_e0){if(i<b.length-1){cp=b[i+1]+ 64*(b[i]-_int_c2) s +=String.fromCharCode(cp) i +=2 }else{$UnicodeDecodeError(encoding,i)}}else if(b[i]==_int_e0){if(i<b.length-2){var zone=b[i+1]-_int_a0 cp=b[i+2]-_int_80+_int_800+64*zone s +=String.fromCharCode(cp) i +=3 }else{$UnicodeDecodeError(encoding,i)}}else if(b[i]<_int_e3){if(i<b.length-2){var zone=b[i+1]-_int_80 cp=b[i+2]-_int_80+_int_1000+64*zone s +=String.fromCharCode(cp) i +=3 }else{$UnicodeDecodeError(encoding,i)}}else{if(i<b.length-2){var zone1=b[i]-_int_e1-1 var zone=b[i+1]-_int_80+64*zone1 cp=b[i+2]-_int_80+_int_2000+64*zone s +=String.fromCharCode(cp) i +=3 }else{if(errors=='surrogateescape'){s+='\\udc' + _hex(b[i]) i+=1 }else{ $UnicodeDecodeError(encoding,i) }}}} break case 'latin-1': case 'iso-8859-1': case 'windows-1252': for(var i=0,_len_i=b.length;i < _len_i;i++)s +=String.fromCharCode(b[i]) break case 'cp1250': case 'windows-1250': load_decoder('cp1250') for(var i=0,_len_i=b.length;i < _len_i;i++){var u=to_unicode['cp1250'][b[i]] if(u!==undefined){s+=String.fromCharCode(u)} else{s +=String.fromCharCode(b[i])}} break case 'ascii': for(var i=0,_len_i=b.length;i < _len_i;i++){var cp=b[i] if(cp<=127){s +=String.fromCharCode(cp)} else{var msg="'ascii' codec can't decode byte 0x"+cp.toString(16) msg +=" in position "+i+": ordinal not in range(128)" throw _b_.UnicodeDecodeError(msg) }} break default: throw _b_.LookupError("unknown encoding: "+encoding) } return s } function encode(s,encoding){var t=[],pos=0 switch(encoding.toLowerCase()){case 'utf-8': case 'utf8': var _int_800=_int('800'),_int_c2=_int('c2'),_int_1000=_int('1000') var _int_e0=_int('e0'),_int_e1=_int('e1'),_int_a0=_int('a0'),_int_80=_int('80') var _int_2000=_int('2000'),_int_D000=_int('D000') for(var i=0,_len_i=s.length;i < _len_i;i++){var cp=s.charCodeAt(i) if(cp<=127){t[pos++]=cp }else if(cp<_int_800){var zone=Math.floor((cp-128)/64) t[pos++]=_int_c2+zone t[pos++]=cp -64*zone }else if(cp<_int_1000){var zone=Math.floor((cp-_int_800)/64) t[pos++]=_int_e0 t[pos++]=_int_a0+zone t[pos++]=_int_80 + cp - _int_800 - 64 * zone }else if(cp<_int_2000){var zone=Math.floor((cp-_int_1000)/64) t[pos++]=_int_e1+Math.floor((cp-_int_1000)/_int_1000) t[pos++]=_int_80+zone t[pos++]=_int_80 + cp - _int_1000 -64*zone }else if(cp<_int_D000){var zone=Math.floor((cp-_int_2000)/64) var zone1=Math.floor((cp-_int_2000)/_int_1000) t[pos++]=_int_e1+Math.floor((cp-_int_1000)/_int_1000) t[pos++]=_int_80+zone-zone1*64 t[pos++]=_int_80 + cp - _int_2000 - 64 * zone }} break case 'latin-1': case 'iso-8859-1': case 'windows-1252': for(var i=0,_len_i=s.length;i < _len_i;i++){var cp=s.charCodeAt(i) if(cp<=255){t[pos++]=cp} else{$UnicodeEncodeError(encoding,i)}} break case 'cp1250': case 'windows-1250': for(var i=0,_len_i=s.length;i < _len_i;i++){var cp=s.charCodeAt(i) if(cp<=255){t[pos++]=cp} else{ load_encoder('cp1250') var res=from_unicode['cp1250'][cp] if(res!==undefined){t[pos++]=res} else{$UnicodeEncodeError(encoding,i)}}} break case 'ascii': for(var i=0,_len_i=s.length;i < _len_i;i++){var cp=s.charCodeAt(i) if(cp<=127){t[pos++]=cp} else{$UnicodeEncodeError(encoding,i)}} break default: throw _b_.LookupError("unknown encoding: "+ encoding.toLowerCase()) } return t } function bytes(source,encoding,errors){ var obj={__class__:$BytesDict} $BytesDict.__init__(obj,source,encoding,errors) return obj } bytes.__class__=$B.$factory bytes.$dict=$BytesDict $BytesDict.$factory=bytes bytes.__code__={} bytes.__code__.co_argcount=1 bytes.__code__.co_consts=[] bytes.__code__.co_varnames=['i'] for(var $attr in $BytesDict){if($BytearrayDict[$attr]===undefined){$BytearrayDict[$attr]=(function(attr){return function(){return $BytesDict[attr].apply(null,arguments)}})($attr) }} $B.set_func_names($BytesDict) $B.set_func_names($BytearrayDict) _b_.bytes=bytes _b_.bytearray=bytearray })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict var $LocationDict={__class__:$B.$type,__name__:'Location'} $LocationDict.__mro__=[$LocationDict,$ObjectDict] function $Location(){ var obj={} for(var x in window.location){if(typeof window.location[x]==='function'){obj[x]=(function(f){return function(){return f.apply(window.location,arguments) }})(window.location[x]) }else{obj[x]=window.location[x] }} if(obj['replace']===undefined){ obj['replace']=function(url){window.location=url}} obj.__class__=$LocationDict obj.toString=function(){return window.location.toString()} obj.__repr__=obj.__str__=obj.toString return obj } $LocationDict.$factory=$Location $Location.$dict=$LocationDict var $JSConstructorDict={__class__:$B.$type,__name__:'JSConstructor'} $JSConstructorDict.__call__=function(self){ var args=[null] for(var i=1,_len_i=arguments.length;i < _len_i;i++){args.push(pyobj2jsobj(arguments[i])) } var factory=self.func.bind.apply(self.func,args) var res=new factory() return $B.$JS2Py(res) } $JSConstructorDict.__mro__=[$JSConstructorDict,$ObjectDict] function JSConstructor(obj){ return{ __class__:$JSConstructorDict,func:obj.js_func }} JSConstructor.__class__=$B.$factory JSConstructor.$dict=$JSConstructorDict $JSConstructorDict.$factory=JSConstructor var jsobj2pyobj=$B.jsobj2pyobj=function(jsobj){switch(jsobj){case true: case false: return jsobj case null: return _b_.None } if(typeof jsobj==='object'){if('length' in jsobj)return _b_.list(jsobj) var d=_b_.dict() for(var $a in jsobj)_b_.dict.$dict.__setitem__(d,$a,jsobj[$a]) return d } if(typeof jsobj==='number'){if(jsobj.toString().indexOf('.')==-1)return _b_.int(jsobj) return _b_.float(jsobj) } return $B.JSObject(jsobj) } var pyobj2jsobj=$B.pyobj2jsobj=function(pyobj){ if(pyobj===true ||pyobj===false)return pyobj if(pyobj===_b_.None)return null var klass=$B.get_class(pyobj) if(klass===$JSObjectDict ||klass===$JSConstructorDict){ return pyobj.js }else if(klass.__mro__.indexOf($B.DOMNodeDict)>-1){ return pyobj.elt }else if([_b_.list.$dict,_b_.tuple.$dict].indexOf(klass)>-1){ var res=[] for(var i=0,_len_i=pyobj.length;i < _len_i;i++){res.push(pyobj2jsobj(pyobj[i]))} return res }else if(klass===_b_.dict.$dict){ var jsobj={} var items=_b_.list(_b_.dict.$dict.items(pyobj)) for(var j=0,_len_j=items.length;j < _len_j;j++){jsobj[items[j][0]]=pyobj2jsobj(items[j][1]) } return jsobj }else if(klass===$B.builtins.float.$dict){ return pyobj.value }else{ return pyobj }} var $JSObjectDict={__class__:$B.$type,__name__:'JSObject',toString:function(){return '(JSObject)'}} $JSObjectDict.__bool__=function(self){return(new Boolean(self.js)).valueOf() } $JSObjectDict.__getattribute__=function(obj,attr){if(attr.substr(0,2)=='$$')attr=attr.substr(2) if(obj.js===null)return $ObjectDict.__getattribute__(None,attr) if(attr==='__class__')return $JSObjectDict if(attr=="bind" && obj.js[attr]===undefined && obj.js['addEventListener']!==undefined){attr='addEventListener'} var js_attr=obj.js[attr] if(obj.js_func && obj.js_func[attr]!==undefined){js_attr=obj.js_func[attr] } if(js_attr !==undefined){if(typeof js_attr=='function'){ var res=function(){var args=[],arg for(var i=0,_len_i=arguments.length;i < _len_i;i++){if(arguments[i].$nat=='ptuple'){ var ptuple=_b_.iter(arguments[i].arg) while(true){try{var item=_b_.next(ptuple) args.push(pyobj2jsobj(item)) }catch(err){$B.$pop_exc() break }}}else{args.push(pyobj2jsobj(arguments[i])) }} if(attr==='replace' && obj.js===location){location.replace(args[0]) return } var res=js_attr.apply(obj.js,args) if(typeof res=='object')return JSObject(res) if(res===undefined)return None return $B.$JS2Py(res) } res.__repr__=function(){return '<function '+attr+'>'} res.__str__=function(){return '<function '+attr+'>'} return{__class__:$JSObjectDict,js:res,js_func:js_attr}}else{if(Array.isArray(obj.js[attr])){return obj.js[attr]} return $B.$JS2Py(obj.js[attr]) }}else if(obj.js===window && attr==='$$location'){ return $Location() } var res var mro=[$JSObjectDict,$ObjectDict] for(var i=0,_len_i=mro.length;i < _len_i;i++){var v=mro[i][attr] if(v!==undefined){res=v break }} if(res!==undefined){if(typeof res==='function'){ return function(){var args=[obj],arg for(var i=0,_len_i=arguments.length;i < _len_i;i++){arg=arguments[i] if(arg &&(arg.__class__===$JSObjectDict ||arg.__class__===$JSConstructorDict)){args.push(arg.js) }else{args.push(arg) }} return res.apply(obj,args) }} return $B.$JS2Py(res) }else{ throw _b_.AttributeError("no attribute "+attr+' for '+this) }} $JSObjectDict.__getitem__=function(self,rank){console.log('get item '+rank+' of',self) try{return getattr(self.js,'__getitem__')(rank)} catch(err){if(self.js[rank]!==undefined)return JSObject(self.js[rank]) throw _b_.AttributeError(self+' has no attribute __getitem__') }} var $JSObject_iterator=$B.$iterator_class('JS object iterator') $JSObjectDict.__iter__=function(self){return $B.$iterator(self.js,$JSObject_iterator) } $JSObjectDict.__len__=function(self){try{return getattr(self.js,'__len__')()} catch(err){console.log('err in JSObject.__len__ : '+err) throw _b_.AttributeError(this+' has no attribute __len__') }} $JSObjectDict.__mro__=[$JSObjectDict,$ObjectDict] $JSObjectDict.__repr__=function(self){return "<JSObject wraps "+self.js+">"} $JSObjectDict.__setattr__=function(self,attr,value){if(isinstance(value,JSObject)){self.js[attr]=value.js }else{self.js[attr]=value }} $JSObjectDict.__setitem__=$JSObjectDict.__setattr__ $JSObjectDict.__str__=$JSObjectDict.__repr__ var no_dict={'string':true,'function':true,'number':true,'boolean':true} $JSObjectDict.to_dict=function(self){ var res=_b_.dict() for(var key in self.js){var value=self.js[key] if(typeof value=='object' && !Array.isArray(value)){_b_.dict.$dict.__setitem__(res,key,$JSObjectDict.to_dict(JSObject(value))) }else{_b_.dict.$dict.__setitem__(res,key,value) }} return res } function JSObject(obj){ if(obj===null){return _b_.None} if(typeof obj=='function'){return{__class__:$JSObjectDict,js:obj}} var klass=$B.get_class(obj) if(klass===_b_.list.$dict){ if(obj.__brython__)return obj return{__class__:$JSObjectDict,js:obj}} if(klass!==undefined)return obj return{__class__:$JSObjectDict,js:obj} } JSObject.__class__=$B.$factory JSObject.$dict=$JSObjectDict $JSObjectDict.$factory=JSObject $B.JSObject=JSObject $B.JSConstructor=JSConstructor })(__BRYTHON__) ;(function($B){$B.stdlib={} var js=['_ajax','_browser','_html','_jsre','_multiprocessing','_posixsubprocess','_svg','_sys','aes','builtins','dis','hashlib','hmac-md5','hmac-ripemd160','hmac-sha1','hmac-sha224','hmac-sha256','hmac-sha3','hmac-sha384','hmac-sha512','javascript','json','long_int','math','md5','modulefinder','pbkdf2','rabbit','rabbit-legacy','rc4','ripemd160','sha1','sha224','sha256','sha3','sha384','sha512','tripledes'] for(var i=0;i<js.length;i++)$B.stdlib[js[i]]=['js'] var pylist=['VFS_import','_abcoll','_codecs','_collections','_csv','_dummy_thread','_functools','_imp','_io','_markupbase','_random','_socket','_sre','_string','_strptime','_struct','_sysconfigdata','_testcapi','_thread','_threading_local','_warnings','_weakref','_weakrefset','abc','antigravity','atexit','base64','binascii','bisect','browser.ajax','browser.html','browser.indexed_db','browser.local_storage','browser.markdown','browser.object_storage','browser.session_storage','browser.svg','browser.timer','browser.websocket','calendar','codecs','collections.abc','colorsys','configparser','Clib','copy','copyreg','csv','datetime','decimal','difflib','encodings.aliases','encodings.utf_8','errno','external_import','fnmatch','formatter','fractions','functools','gc','genericpath','getopt','heapq','html.entities','html.parser','http.cookies','imp','importlib._bootstrap','importlib.abc','importlib.basehook','importlib.machinery','importlib.util','inspect','io','itertools','keyword','linecache','locale','logging.config','logging.handlers','markdown2','marshal','multiprocessing.dummy.connection','multiprocessing.pool','multiprocessing.process','multiprocessing.util','numbers','opcode','operator','optparse','os','pickle','platform','posix','posixpath','pprint','pwd','pydoc','pydoc_data.topics','queue','random','re','reprlib','select','shutil','signal','site','site-packages.docs','site-packages.header','site-packages.highlight','site-packages.pygame.SDL','site-packages.pygame.base','site-packages.pygame.color','site-packages.pygame.colordict','site-packages.pygame.compat','site-packages.pygame.constants','site-packages.pygame.display','site-packages.pygame.draw','site-packages.pygame.event','site-packages.pygame.font','site-packages.pygame.image','site-packages.pygame.locals','site-packages.pygame.mixer','site-packages.pygame.mouse','site-packages.pygame.pkgdata','site-packages.pygame.rect','site-packages.pygame.sprite','site-packages.pygame.surface','site-packages.pygame.time','site-packages.pygame.transform','site-packages.pygame.version','site-packages.test_sp','site-packages.turtle','socket','sre_compile','sre_constants','sre_parse','stat','string','struct','subprocess','sys','sysconfig','tarfile','tempfile','test.pystone','test.re_tests','test.regrtest','test.support','test.test_int','test.test_re','textwrap','this','threading','time','timeit','token','tokenize','traceback','types','ui.dialog','ui.progressbar','ui.slider','ui.widget','unittest.__main__','unittest.case','unittest.loader','unittest.main','unittest.mock','unittest.result','unittest.runner','unittest.signals','unittest.suite','unittest.test._test_warnings','unittest.test.dummy','unittest.test.support','unittest.test.test_assertions','unittest.test.test_break','unittest.test.test_case','unittest.test.test_discovery','unittest.test.test_functiontestcase','unittest.test.test_loader','unittest.test.test_program','unittest.test.test_result','unittest.test.test_runner','unittest.test.test_setups','unittest.test.test_skipping','unittest.test.test_suite','unittest.test.testmock.support','unittest.test.testmock.testcallable','unittest.test.testmock.testhelpers','unittest.test.testmock.testmagicmethods','unittest.test.testmock.testmock','unittest.test.testmock.testpatch','unittest.test.testmock.testsentinel','unittest.test.testmock.testwith','unittest.util','urllib.parse','urllib.request','warnings','weakref','webbrowser','xml.dom.NodeFilter','xml.dom.domreg','xml.dom.expatbuilder','xml.dom.minicompat','xml.dom.minidom','xml.dom.pulldom','xml.dom.xmlbuilder','xml.etree.ElementInclude','xml.etree.ElementPath','xml.etree.ElementTree','xml.etree.cElementTree','xml.parsers.expat','xml.sax._exceptions','xml.sax.expatreader','xml.sax.handler','xml.sax.saxutils','xml.sax.xmlreader','zipfile','zlib'] for(var i=0;i<pylist.length;i++)$B.stdlib[pylist[i]]=['py'] var pkglist=['browser','collections','encodings','html','http','importlib','jqueryui','logging','long_int1','multiprocessing','multiprocessing.dummy','pydoc_data','site-packages.pygame','test','ui','unittest','unittest.test','unittest.test.testmock','urllib','xml','xml.dom','xml.etree','xml.parsers','xml.sax'] for(var i=0;i<pkglist.length;i++)$B.stdlib[pkglist[i]]=['py',true] })(__BRYTHON__) ;(function($B){var _b_=$B.builtins $B.$ModuleDict={__class__ : $B.$type,__name__ : 'module' } $B.$ModuleDict.__repr__=$B.$ModuleDict.__str__=function(self){return '<module '+self.__name__+'>' } $B.$ModuleDict.__mro__=[$B.$ModuleDict,_b_.object.$dict] function module(name,doc,package){return{__class__:$B.$ModuleDict,__name__:name,__doc__:doc||_b_.None,__package__:package||_b_.None }} module.__class__=$B.$factory module.$dict=$B.$ModuleDict $B.$ModuleDict.$factory=module function $importer(){ var $xmlhttp=new XMLHttpRequest() if($B.$CORS && "withCredentials" in $xmlhttp){ }else if($B.$CORS && typeof window.XDomainRequest !="undefined"){ $xmlhttp=new window.XDomainRequest() }else if(window.XMLHttpRequest){ }else{ $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") } var fake_qs switch($B.$options.cache){case 'version': fake_qs="?v="+$B.version_info[2] break case 'browser': fake_qs='' break default: fake_qs="?v="+$B.UUID() } var timer=setTimeout(function(){$xmlhttp.abort() throw _b_.ImportError("No module named '"+module+"'")},5000) return[$xmlhttp,fake_qs,timer] } function $download_module(module,url){var imp=$importer() var $xmlhttp=imp[0],fake_qs=imp[1],timer=imp[2],res=null $xmlhttp.open('GET',url+fake_qs,false) if($B.$CORS){$xmlhttp.onload=function(){if($xmlhttp.status==200 ||$xmlhttp.status==0){res=$xmlhttp.responseText }else{ res=_b_.FileNotFoundError("No module named '"+module+"'") }} $xmlhttp.onerror=function(){res=_b_.FileNotFoundError("No module named '"+module+"'") }}else{ $xmlhttp.onreadystatechange=function(){if($xmlhttp.readyState==4){window.clearTimeout(timer) if($xmlhttp.status==200 ||$xmlhttp.status==0){res=$xmlhttp.responseText} else{ console.log('Error '+$xmlhttp.status+' means that Python module '+module+' was not found at url '+url) res=_b_.FileNotFoundError("No module named '"+module+"'") }}}} if('overrideMimeType' in $xmlhttp){$xmlhttp.overrideMimeType("text/plain")} $xmlhttp.send() if(res==null)throw _b_.FileNotFoundError("No module named '"+module+"' (res is null)") if(res.constructor===Error){throw res} return res } $B.$download_module=$download_module function import_js(module,path){try{var module_contents=$download_module(module.name,path)} catch(err){$B.$pop_exc();return null} run_js(module,path,module_contents) return true } function run_js(module,path,module_contents){eval(module_contents) try{$module} catch(err){throw _b_.ImportError("name '$module' is not defined in module") } $module.__class__=$B.$ModuleDict $module.__name__=module.name $module.__repr__=$module.__str__=function(){if($B.builtin_module_names.indexOf(module.name)> -1){return "<module '"+module.name+"' (built-in)>" } return "<module '"+module.name+"' from "+path+" >" } $module.toString=function(){return "<module '"+module.name+"' from "+path+" >"} if(module.name !='builtins'){ $module.__file__=path } $B.imported[module.name]=$B.modules[module.name]=$module return true } function show_ns(){var kk=Object.keys(window) for(var i=0,_len_i=kk.length;i < _len_i;i++){console.log(kk[i]) if(kk[i].charAt(0)=='$'){console.log(eval(kk[i]))}} console.log('---') } function import_py(module,path,package){ try{var module_contents=$download_module(module.name,path) }catch(err){$B.$pop_exc() return null } $B.imported[module.name].$is_package=module.$is_package if(path.substr(path.length-12)=='/__init__.py'){ $B.imported[module.name].__package__=module.name $B.imported[module.name].$is_package=module.$is_package=true }else if(package){$B.imported[module.name].__package__=package }else{var mod_elts=module.name.split('.') mod_elts.pop() $B.imported[module.name].__package__=mod_elts.join('.') } $B.imported[module.name].__file__=path return run_py(module,path,module_contents) } $B.run_py=run_py=function(module,path,module_contents){var $Node=$B.$Node,$NodeJSCtx=$B.$NodeJSCtx $B.$py_module_path[module.name]=path var root=$B.py2js(module_contents,module.name,module.name,'__builtins__') var body=root.children root.children=[] var mod_node=new $Node('expression') new $NodeJSCtx(mod_node,'var $module=(function()') root.insert(0,mod_node) for(var i=0,_len_i=body.length;i < _len_i;i++){mod_node.add(body[i])} var ret_node=new $Node('expression') new $NodeJSCtx(ret_node,'return $locals_'+module.name.replace(/\./g,'_')) mod_node.add(ret_node) var ex_node=new $Node('expression') new $NodeJSCtx(ex_node,')(__BRYTHON__)') root.add(ex_node) try{var js=root.to_js() if($B.$options.debug==10){console.log('code for module '+module.name) console.log(js) } eval(js) }catch(err){console.log(err+' for module '+module.name) console.log('message: '+err.$message) console.log('filename: '+err.fileName) console.log('linenum: '+err.lineNumber) if($B.debug>0){console.log('line info '+ $B.line_info)} throw err } try{ var mod=eval('$module') mod.__class__=$B.$ModuleDict mod.__name__=module.name mod.__repr__=mod.__str__=function(){if($B.builtin_module_names.indexOf(module.name)> -1){return "<module '"+module.name+"' (built-in)>" } return "<module '"+module.name+"' from "+path+" >" } mod.__initializing__=false mod.$is_package=module.$is_package $B.imported[module.name]=$B.modules[module.name]=mod return true }catch(err){console.log(''+err+' '+' for module '+module.name) for(var attr in err)console.log(attr+' '+err[attr]) if($B.debug>0){console.log('line info '+__BRYTHON__.line_info)} throw err }} function import_from_VFS(mod_name,origin,package){var stored=$B.VFS[mod_name] if(stored===undefined && package){stored=$B.VFS[package+'.'+mod_name] } if(stored!==undefined){var ext=stored[0] var module_contents=stored[1] var $is_package=stored[2] var path='py_VFS' var module={name:mod_name,__class__:$B.$ModuleDict,$is_package:$is_package} if($is_package){var package=mod_name} else{var elts=mod_name.split('.') elts.pop() var package=elts.join('.') } $B.modules[mod_name].$is_package=$is_package $B.modules[mod_name].__package__=package if(ext=='.js'){run_js(module,path,module_contents)} else{run_py(module,path,module_contents)} console.log('import '+mod_name+' from VFS') return true } return null } function import_from_stdlib_static(mod_name,origin,package){var address=$B.stdlib[mod_name] if(address!==undefined){var ext=address[0] var $is_package=address[1]!==undefined var path=$B.brython_path if(ext=='py'){path+='Lib/'} else{path+='libs/'} path +=mod_name.replace(/\./g,'/') if($is_package){path+='/__init__.py'} else if(ext=='py'){path+='.py'} else{path+='.js'} if(ext=='py'){return import_py({name:mod_name,__class__:$B.$ModuleDict,$is_package:$is_package},path,package) }else{return import_js({name:mod_name,__class__:$B.$ModuleDict},path) }} return null } function import_from_stdlib(mod_name,origin,package){var module={name:mod_name,__class__:$B.$ModuleDict} var js_path=$B.brython_path+'libs/'+mod_name+'.js' var js_mod=import_js(module,js_path) if(js_mod!==null)return true mod_path=mod_name.replace(/\./g,'/') var py_paths=[$B.brython_path+'Lib/'+mod_path+'.py',$B.brython_path+'Lib/'+mod_path+'/__init__.py'] for(var i=0,_len_i=py_paths.length;i < _len_i;i++){var py_mod=import_py(module,py_paths[i],package) if(py_mod!==null)return true } return null } function import_from_site_packages(mod_name,origin,package){var module={name:mod_name} mod_path=mod_name.replace(/\./g,'/') var py_paths=[$B.brython_path+'Lib/site-packages/'+mod_path+'.py',$B.brython_path+'Lib/site-packages/'+mod_path+'/__init__.py'] for(var i=0,_len_i=py_paths.length;i < _len_i;i++){var py_mod=import_py(module,py_paths[i],package) if(py_mod!==null){ if(py_paths[i].substr(py_paths[i].length-12)=='/__init__.py'){ $B.imported[mod_name].$is_package=true py_mod.__package__=mod_name } return py_mod }} return null } function import_from_caller_folder(mod_name,origin,package){var module={name:mod_name} var origin_path=$B.$py_module_path[origin] var origin_dir_elts=origin_path.split('/') origin_dir_elts.pop() origin_dir=origin_dir_elts.join('/') var mod_elts=mod_name.split('.') var origin_elts=origin.split('.') while(mod_elts[0]==origin_elts[0]){mod_elts.shift();origin_elts.shift()} mod_path=mod_elts.join('/') var py_paths=[origin_dir+'/'+mod_path+'.py',origin_dir+'/'+mod_path+'/__init__.py'] for(var i=0,_len_i=$B.path.length;i < _len_i;i++){if($B.path[i].substring(0,4)=='http')continue var _path=origin_dir+'/'+ $B.path[i]+'/' py_paths.push(_path+ mod_path + ".py") py_paths.push(_path+ mod_path + "/__init__.py") } for(var i=0,_len_i=py_paths.length;i < _len_i;i++){ var py_mod=import_py(module,py_paths[i],package) if(py_mod!==null){return py_mod }} return null } function import_from_package(mod_name,origin,package){var mod_elts=mod_name.split('.'),package_elts=package.split('.') for(var i=0;i<package_elts.length;i++){mod_elts.shift()} var package_path=$B.imported[package].__file__ if(package_path===undefined){console.log('__file__ indefini pour package '+package)} var py_path=package_path.split('/') py_path.pop() py_path=py_path.concat(mod_elts) py_path=py_path.join('/') py_paths=[py_path+'.py',py_path+'/__init__.py'] for(var i=0;i<2;i++){var module={name:mod_name} var py_mod=import_py(module,py_paths[i],package) if(py_mod!==null)return py_mod } return null } $B.$import=function(mod_name,origin){ var parts=mod_name.split('.') var norm_parts=[] for(var i=0,_len_i=parts.length;i < _len_i;i++){norm_parts.push(parts[i].substr(0,2)=='$$' ? parts[i].substr(2): parts[i]) } mod_name=norm_parts.join('.') if($B.imported[origin]===undefined){var package=''} else{var package=$B.imported[origin].__package__} if($B.$options.debug==10){console.log('$import '+mod_name+' origin '+origin) console.log('use VFS ? '+$B.use_VFS) console.log('use static stdlib paths ? '+$B.static_stdlib_import) } if($B.imported[mod_name]!==undefined){return} var mod,funcs=[] if($B.use_VFS){funcs=[import_from_VFS,import_from_stdlib_static] }else if($B.static_stdlib_import){funcs=[import_from_stdlib_static] }else{funcs=[import_from_stdlib] } if($B.$options['custom_import_funcs']!==undefined){funcs=funcs.concat($B.$options['custom_import_funcs']) } funcs=funcs.concat([import_from_site_packages,import_from_caller_folder]) var mod_elts=mod_name.split('.') if(mod_elts[0]==package && mod_elts.length==2){ if($B.imported[package]===undefined){console.log('mod_elts ['+mod_elts+']','package',package,'undef') } var res=$B.imported[package][mod_elts[1]] if(res!==undefined){return res}} for(var i=0,_len_i=mod_elts.length;i < _len_i;i++){ var elt_name=mod_elts.slice(0,i+1).join('.') if($B.imported[elt_name]!==undefined){ if(!$B.use_VFS && $B.imported[elt_name].$is_package){ package=elt_name package_path=$B.imported[elt_name].__file__ funcs=[import_from_package ] } continue } $B.modules[elt_name]=$B.imported[elt_name]={__class__:$B.$ModuleDict,toString:function(){return '<module '+elt_name+'>'}} var flag=false for(var j=0,_len_j=funcs.length;j < _len_j;j++){var res=funcs[j](elt_name,origin,package) if(res!==null){flag=true if(i>0){var pmod=mod_elts.slice(0,i).join('.') $B.modules[pmod][mod_elts[i]]=$B.modules[elt_name] } break }} if(!flag){ $B.modules[elt_name]=undefined $B.imported[elt_name]=undefined throw _b_.ImportError("cannot import "+elt_name) } if(!($B.use_VFS && j==0) && i<mod_elts.length-1 && $B.imported[elt_name].$is_package){ package=elt_name package_path=$B.modules[elt_name].__file__ funcs=[import_from_package ] }}} $B.$import_from=function(mod_name,names,origin){ if($B.$options.debug==10){ } if(mod_name.substr(0,2)=='$$'){mod_name=mod_name.substr(2)} mod_name=mod_name.replace(/\$/g,'') var mod=$B.imported[mod_name] if(mod===undefined){$B.$import(mod_name,origin) mod=$B.imported[mod_name] } for(var i=0,_len_i=names.length;i < _len_i;i++){if(mod[names[i]]===undefined){if(mod.$is_package){var sub_mod=mod_name+'.'+names[i].replace(/\$/g,'') $B.$import(sub_mod,origin) mod[names[i]]=$B.modules[sub_mod] }else{throw _b_.ImportError("cannot import name "+names[i]) }}} return mod }})(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict function $err(op,other){var msg="unsupported operand type(s) for "+op msg +=": 'float' and '"+$.get_class(other).__name__+"'" throw _b_.TypeError(msg) } var $FloatDict={__class__:$B.$type,__dir__:$ObjectDict.__dir__,__name__:'float',$native:true} $FloatDict.as_integer_ratio=function(self){if(Math.round(self.value)==self.value)return _b_.tuple([_b_.int(self.value),_b_.int(1)]) var _temp=self.value var i=10 while(!(Math.round(_temp/i)==_temp/i))i*=10 return _b_.tuple([_b_.int(_temp*i),_b_.int(i)]) } $FloatDict.__bool__=function(self){return _b_.bool(self.value)} $FloatDict.__class__=$B.$type $FloatDict.__eq__=function(self,other){ if(other===undefined)return self===float if(isinstance(other,_b_.int))return self.value==other if(isinstance(other,float)){ return self.value==other.value } if(isinstance(other,_b_.complex)){if(other.imag !=0)return false return self.value==other.real } return self.value===other } $FloatDict.__floordiv__=function(self,other){if(isinstance(other,_b_.int)){if(other===0)throw ZeroDivisionError('division by zero') return float(Math.floor(self.value/other)) } if(isinstance(other,float)){if(!other.value)throw ZeroDivisionError('division by zero') return float(Math.floor(self.value/other.value)) } if(hasattr(other,'__rfloordiv__')){return getattr(other,'__rfloordiv__')(self) } $err('//',other) } $FloatDict.fromhex=function(arg){ if(!isinstance(arg,_b_.str)){throw _b_.ValueError('argument must be a string') } var value=arg.trim() switch(value.toLowerCase()){case '+inf': case 'inf': case '+infinity': case 'infinity': return new $FloatClass(Infinity) case '-inf': case '-infinity': return new $FloatClass(-Infinity) case '+nan': case 'nan': return new $FloatClass(Number.NaN) case '-nan': return new $FloatClass(-Number.NaN) case '': throw _b_.ValueError('count not convert string to float') } var _m=/^(\d*\.?\d*)$/.exec(value) if(_m !==null)return new $FloatClass(parseFloat(_m[1])) var _m=/^(\+|-)?(0x)?([0-9A-F]+\.?)?(\.[0-9A-F]+)?(p(\+|-)?\d+)?$/i.exec(value) if(_m==null)throw _b_.ValueError('invalid hexadecimal floating-point string') var _sign=_m[1] var _int=parseInt(_m[3]||'0',16) var _fraction=_m[4]||'.0' var _exponent=_m[5]||'p0' if(_sign=='-'){_sign=-1}else{_sign=1} var _sum=_int for(var i=1,_len_i=_fraction.length;i < _len_i;i++)_sum+=parseInt(_fraction.charAt(i),16)/Math.pow(16,i) return float(_sign * _sum * Math.pow(2,parseInt(_exponent.substring(1)))) } $FloatDict.__getformat__=function(arg){if(arg=='double' ||arg=='float')return 'IEEE, little-endian' throw _b_.ValueError("__getformat__() argument 1 must be 'double' or 'float'") } $FloatDict.__getitem__=function(){throw _b_.TypeError("'float' object is not subscriptable") } $FloatDict.__format__=function(self,format_spec){ if(format_spec=='')format_spec='f' if(format_spec=='.4')format_spec='.4G' return _b_.str.$dict.__mod__('%'+format_spec,self) } $FloatDict.__hash__=function(self){if(self===undefined){return $FloatDict.__hashvalue__ ||$B.$py_next_hash-- } var _v=self.value if(_v===Infinity)return 314159 if(_v===-Infinity)return -271828 if(isNaN(_v))return 0 if(_v==Math.round(_v))return Math.round(_v) var r=_b_.$frexp(_v) r[0]*=Math.pow(2,31) var hipart=_b_.int(r[0]) r[0]=(r[0]- hipart)* Math.pow(2,31) var x=hipart + _b_.int(r[0])+(r[1]<< 15) return x & 0xFFFFFFFF } _b_.$isninf=function(x){var x1=x if(x.value !==undefined && isinstance(x,float))x1=x.value return x1==-Infinity ||x1==Number.NEGATIVE_INFINITY } _b_.$isinf=function(x){var x1=x if(x.value !==undefined && isinstance(x,float))x1=x.value return x1==Infinity ||x1==-Infinity ||x1==Number.POSITIVE_INFINITY ||x1==Number.NEGATIVE_INFINITY } _b_.$fabs=function(x){return x>0?float(x):float(-x)} _b_.$frexp=function(x){var x1=x if(x.value !==undefined && isinstance(x,float))x1=x.value if(isNaN(x1)||_b_.$isinf(x1)){return[x1,-1]} if(x1==0)return[0,0] var sign=1,ex=0,man=x1 if(man < 0.){sign=-sign man=-man } while(man < 0.5){man *=2.0 ex-- } while(man >=1.0){man *=0.5 ex++ } man *=sign return[man ,ex] } _b_.$ldexp=function(x,i){if(_b_.$isninf(x))return float('-inf') if(_b_.$isinf(x))return float('inf') var y=x if(x.value !==undefined && isinstance(x,float))y=x.value if(y==0)return y var j=i if(i.value !==undefined && isinstance(i,float))j=i.value return y * Math.pow(2,j) } $FloatDict.hex=function(self){ var DBL_MANT_DIG=53 var TOHEX_NBITS=DBL_MANT_DIG + 3 -(DBL_MANT_DIG+2)%4 switch(self.value){case Infinity: case -Infinity: case Number.NaN: case -Number.NaN: return self case -0: return '-0x0.0p0' case 0: return '0x0.0p0' } var _a=_b_.$frexp(_b_.$fabs(self.value)) var _m=_a[0],_e=_a[1] var _shift=1 - Math.max(-1021 - _e,0) _m=_b_.$ldexp(_m,_shift) _e -=_shift var _int2hex='0123456789ABCDEF'.split('') var _s=_int2hex[Math.floor(_m)] _s+='.' _m -=Math.floor(_m) for(var i=0;i <(TOHEX_NBITS-1)/4;i++){_m*=16.0 _s+=_int2hex[Math.floor(_m)] _m-=Math.floor(_m) } var _esign='+' if(_e < 0){_esign='-' _e=-_e } if(self.value < 0)return "-0x" + _s + 'p' + _esign + _e return "0x" + _s + 'p' + _esign + _e } $FloatDict.__init__=function(self,value){self.value=value} $FloatDict.is_integer=function(self){return _b_.int(self.value)==self.value} $FloatDict.__mod__=function(self,other){ if(isinstance(other,_b_.int))return float((self.value%other+other)%other) if(isinstance(other,float)){return float(((self.value%other.value)+other.value)%other.value) } if(isinstance(other,_b_.bool)){var bool_value=0; if(other.valueOf())bool_value=1 return float((self.value%bool_value+bool_value)%bool_value) } if(hasattr(other,'__rmod__'))return getattr(other,'__rmod__')(self) $err('%',other) } $FloatDict.__mro__=[$FloatDict,$ObjectDict] $FloatDict.__mul__=function(self,other){if(isinstance(other,_b_.int))return float(self.value*other) if(isinstance(other,float))return float(self.value*other.value) if(isinstance(other,_b_.bool)){var bool_value=0; if(other.valueOf())bool_value=1 return float(self.value*bool_value) } if(isinstance(other,_b_.complex)){return _b_.complex(self.value*other.real,self.value*other.imag) } if(hasattr(other,'__rmul__'))return getattr(other,'__rmul__')(self) $err('*',other) } $FloatDict.__ne__=function(self,other){return !$FloatDict.__eq__(self,other)} $FloatDict.__neg__=function(self,other){return float(-self.value)} $FloatDict.__pow__=function(self,other){if(isinstance(other,_b_.int))return float(Math.pow(self,other)) if(isinstance(other,float))return float(Math.pow(self.value,other.value)) if(hasattr(other,'__rpow__'))return getattr(other,'__rpow__')(self) $err("** or pow()",other) } $FloatDict.__repr__=$FloatDict.__str__=function(self){if(self===float)return "<class 'float'>" if(self.value==Infinity)return 'inf' if(self.value==-Infinity)return '-inf' if(isNaN(self.value))return 'nan' var res=self.value+'' if(res.indexOf('.')==-1)res+='.0' return _b_.str(res) } $FloatDict.__truediv__=function(self,other){if(isinstance(other,_b_.int)){if(other===0)throw ZeroDivisionError('division by zero') return float(self.value/other) } if(isinstance(other,float)){if(!other.value)throw ZeroDivisionError('division by zero') return float(self.value/other.value) } if(isinstance(other,_b_.complex)){var cmod=other.real*other.real+other.imag*other.imag if(cmod==0)throw ZeroDivisionError('division by zero') return _b_.complex(float(self.value*other.real/cmod),float(-self.value*other.imag/cmod)) } if(hasattr(other,'__rtruediv__'))return getattr(other,'__rtruediv__')(self) $err('/',other) } var $op_func=function(self,other){if(isinstance(other,_b_.int))return float(self.value-other) if(isinstance(other,float))return float(self.value-other.value) if(isinstance(other,_b_.bool)){var bool_value=0; if(other.valueOf())bool_value=1 return float(self.value-bool_value) } if(isinstance(other,_b_.complex)){return _b_.complex(self.value - other.real,-other.imag) } if(hasattr(other,'__rsub__'))return getattr(other,'__rsub__')(self) $err('-',other) } $op_func +='' var $ops={'+':'add','-':'sub'} for(var $op in $ops){var $opf=$op_func.replace(/-/gm,$op) $opf=$opf.replace(/__rsub__/gm,'__r'+$ops[$op]+'__') eval('$FloatDict.__'+$ops[$op]+'__ = '+$opf) } var $comp_func=function(self,other){if(isinstance(other,_b_.int))return self.value > other.valueOf() if(isinstance(other,float))return self.value > other.value throw _b_.TypeError( "unorderable types: "+self.__class__.__name__+'() > '+$B.get_class(other).__name__+"()") } $comp_func +='' var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le'} for(var $op in $comps){eval("$FloatDict.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op)) } $B.make_rmethods($FloatDict) var $notimplemented=function(self,other){throw _b_.TypeError( "unsupported operand types for OPERATOR: '"+self.__class__.__name__+ "' and '"+$B.get_class(other).__name__+"'") } $notimplemented +='' for(var $op in $B.$operators){ switch($op){case '+=': case '-=': case '*=': case '/=': case '%=': break default: var $opfunc='__'+$B.$operators[$op]+'__' if($FloatDict[$opfunc]===undefined){eval('$FloatDict.'+$opfunc+"="+$notimplemented.replace(/OPERATOR/gm,$op)) }} } function $FloatClass(value){this.value=value this.__class__=$FloatDict this.toString=function(){return this.value} this.valueOf=function(){return this.value}} var float=function(value){switch(value){case undefined: return new $FloatClass(0.0) case Number.MAX_VALUE: return new $FloatClass(Infinity) case -Number.MAX_VALUE: return new $FloatClass(-Infinity) } if(typeof value=="number"){return new $FloatClass(value) } if(isinstance(value,float))return value if(isinstance(value,_b_.bytes)){return new $FloatClass(parseFloat(getattr(value,'decode')('latin-1'))) } if(hasattr(value,'__float__')){return new $FloatClass(getattr(value,'__float__')()) } if(typeof value=='string'){value=value.trim() switch(value.toLowerCase()){case '+inf': case 'inf': case '+infinity': case 'infinity': return new $FloatClass(Infinity) case '-inf': case '-infinity': return new $FloatClass(-Infinity) case '+nan': case 'nan': return new $FloatClass(Number.NaN) case '-nan': return new $FloatClass(-Number.NaN) case '': throw _b_.ValueError('count not convert string to float') default: if(isFinite(value))return new $FloatClass(eval(value)) }} throw _b_.ValueError("Could not convert to float(): '"+_b_.str(value)+"'") } float.__class__=$B.$factory float.$dict=$FloatDict $FloatDict.$factory=float $FloatDict.__new__=$B.$__new__(float) $B.$FloatClass=$FloatClass _b_.float=float })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict function $err(op,other){var msg="unsupported operand type(s) for "+op msg +=": 'int' and '"+$B.get_class(other).__name__+"'" throw _b_.TypeError(msg) } var $IntDict={__class__:$B.$type,__name__:'int',__dir__:$ObjectDict.__dir__,toString:function(){return '$IntDict'},$native:true } $IntDict.from_bytes=function(){var $ns=$B.$MakeArgs("from_bytes",arguments,['x','byteorder'],'signed','args','kw') var x=$ns['x'] var byteorder=$ns['byteorder'] var signed=$ns['signed']||_b_.dict.$dict.get($ns['kw'],'signed',False) var _bytes,_len if(isinstance(x,[_b_.list,_b_.tuple])){_bytes=x _len=len(x) }else if(isinstance(x,[_b_.bytes,_b_.bytearray])){_bytes=x.source _len=x.source.length }else{ _b_.TypeError("Error! " + _b_.type(x)+ " is not supported in int.from_bytes. fix me!") } switch(byteorder){case 'big': var num=_bytes[_len - 1] var _mult=256 for(var i=(_len - 2);i >=0;i--){num=_mult * _bytes[i]+ num _mult*=256 } if(!signed)return num if(_bytes[0]< 128)return num return num - _mult case 'little': var num=_bytes[0] if(num >=128)num=num - 256 var _mult=256 for(var i=1;i < _len;i++){num=_mult * _bytes[i]+ num _mult *=256 } if(!signed)return num if(_bytes[_len - 1]< 128)return num return num - _mult } throw _b_.ValueError("byteorder must be either 'little' or 'big'") } $IntDict.to_bytes=function(length,byteorder,star){ throw _b_.NotImplementedError("int.to_bytes is not implemented yet") } $IntDict.__abs__=function(self){return abs(self)} $IntDict.__bool__=function(self){return new Boolean(self.valueOf())} $IntDict.__ceil__=function(self){return Math.ceil(self)} $IntDict.__class__=$B.$type $IntDict.__divmod__=function(self,other){return divmod(self,other)} $IntDict.__eq__=function(self,other){ if(other===undefined)return self===int if(isinstance(other,int))return self.valueOf()==other.valueOf() if(isinstance(other,_b_.float))return self.valueOf()==other.value if(isinstance(other,_b_.complex)){if(other.imag !=0)return False return self.valueOf()==other.real } if(hasattr(other,'__eq__'))return getattr(other,'__eq__')(self) return self.valueOf()===other } $IntDict.__format__=function(self,format_spec){if(format_spec=='')format_spec='d' return _b_.str.$dict.__mod__('%'+format_spec,self) } $IntDict.__floordiv__=function(self,other){if(isinstance(other,int)){if(other==0)throw ZeroDivisionError('division by zero') return Math.floor(self/other) } if(isinstance(other,_b_.float)){if(!other.value)throw ZeroDivisionError('division by zero') return _b_.float(Math.floor(self/other.value)) } if(hasattr(other,'__rfloordiv__')){return getattr(other,'__rfloordiv__')(self) } $err("//",other) } $IntDict.__getitem__=function(){throw _b_.TypeError("'int' object is not subscriptable") } $IntDict.__hash__=function(self){if(self===undefined){return $IntDict.__hashvalue__ ||$B.$py_next_hash-- } return self.valueOf() } $IntDict.__index__=function(self){return self} $IntDict.__init__=function(self,value){if(value===undefined){value=0} self.toString=function(){return value} } $IntDict.__int__=function(self){return self} $IntDict.__invert__=function(self){return ~self} $IntDict.__mod__=function(self,other){ if(isinstance(other,_b_.tuple)&& other.length==1)other=other[0] if(isinstance(other,int))return(self%other+other)%other if(isinstance(other,_b_.float))return((self%other)+other)%other if(isinstance(other,bool)){var bool_value=0; if(other.valueOf())bool_value=1 return(self%bool_value+bool_value)%bool_value } if(hasattr(other,'__rmod__'))return getattr(other,'__rmod__')(self) $err('%',other) } $IntDict.__mro__=[$IntDict,$ObjectDict] $IntDict.__mul__=function(self,other){var val=self.valueOf() if(typeof other==="string"){return other.repeat(val) } other=$B.$GetInt(other) if(isinstance(other,int))return self*other if(isinstance(other,_b_.float))return _b_.float(self*other.value) if(isinstance(other,_b_.bool)){ if(other.valueOf())return self return int(0) } if(isinstance(other,_b_.complex)){return _b_.complex(self.valueOf()*other.real,self.valueOf()*other.imag) } if(isinstance(other,[_b_.list,_b_.tuple])){var res=[] var $temp=other.slice(0,other.length) for(var i=0;i<val;i++)res=res.concat($temp) if(isinstance(other,_b_.tuple))res=_b_.tuple(res) return res } if(hasattr(other,'__rmul__'))return getattr(other,'__rmul__')(self) $err("*",other) } $IntDict.__name__='int' $IntDict.__ne__=function(self,other){return !$IntDict.__eq__(self,other)} $IntDict.__neg__=function(self){return -self} $IntDict.__new__=function(cls){if(cls===undefined){throw _b_.TypeError('int.__new__(): not enough arguments')} return{__class__:cls.$dict}} $IntDict.__pow__=function(self,other){if(isinstance(other,int)){switch(other.valueOf()){case 0: return int(1) case 1: return int(self.valueOf()) } return Math.pow(self.valueOf(),other.valueOf()) } if(isinstance(other,_b_.float)){return _b_.float(Math.pow(self.valueOf(),other.valueOf())) } if(hasattr(other,'__rpow__'))return getattr(other,'__rpow__')(self) $err("**",other) } $IntDict.__repr__=function(self){if(self===int)return "<class 'int'>" return self.toString() } $IntDict.__setattr__=function(self,attr,value){if(self.__class__===$IntDict){throw _b_.AttributeError("'int' object has no attribute "+attr+"'") } self[attr]=value } $IntDict.__str__=$IntDict.__repr__ $IntDict.__truediv__=function(self,other){if(isinstance(other,int)){if(other==0)throw ZeroDivisionError('division by zero') return _b_.float(self/other) } if(isinstance(other,_b_.float)){if(!other.value)throw ZeroDivisionError('division by zero') return _b_.float(self/other.value) } if(isinstance(other,_b_.complex)){var cmod=other.real*other.real+other.imag*other.imag if(cmod==0)throw ZeroDivisionError('division by zero') return _b_.complex(self*other.real/cmod,-self*other.imag/cmod) } if(hasattr(other,'__rtruediv__'))return getattr(other,'__rtruediv__')(self) $err("/",other) } $IntDict.bit_length=function(self){s=bin(self) s=getattr(s,'lstrip')('-0b') return s.length } $IntDict.numerator=function(self){return self} $IntDict.denominator=function(self){return int(1)} var $op_func=function(self,other){if(isinstance(other,int))return self-other if(isinstance(other,_b_.bool))return self-other if(hasattr(other,'__rsub__'))return getattr(other,'__rsub__')(self) $err("-",other) } $op_func +='' var $ops={'&':'and','|':'or','<<':'lshift','>>':'rshift','^':'xor'} for(var $op in $ops){var opf=$op_func.replace(/-/gm,$op) opf=opf.replace(new RegExp('sub','gm'),$ops[$op]) eval('$IntDict.__'+$ops[$op]+'__ = '+opf) } var $op_func=function(self,other){if(isinstance(other,int)){var res=self.valueOf()-other.valueOf() if(isinstance(res,int))return res return _b_.float(res) } if(isinstance(other,_b_.float)){return _b_.float(self.valueOf()-other.value) } if(isinstance(other,_b_.complex)){return _b_.complex(self-other.real,-other.imag) } if(isinstance(other,_b_.bool)){var bool_value=0 if(other.valueOf())bool_value=1 return self.valueOf()-bool_value } if(isinstance(other,_b_.complex)){return _b_.complex(self.valueOf()- other.real,other.imag) } if(hasattr(other,'__rsub__'))return getattr(other,'__rsub__')(self) throw $err('-',other) } $op_func +='' var $ops={'+':'add','-':'sub'} for(var $op in $ops){var opf=$op_func.replace(/-/gm,$op) opf=opf.replace(new RegExp('sub','gm'),$ops[$op]) eval('$IntDict.__'+$ops[$op]+'__ = '+opf) } var $comp_func=function(self,other){if(isinstance(other,int))return self.valueOf()> other.valueOf() if(isinstance(other,_b_.float))return self.valueOf()> other.value if(isinstance(other,_b_.bool)){return self.valueOf()> _b_.bool.$dict.__hash__(other) } if(hasattr(other,'__int__')||hasattr(other,'__index__')){return $IntDict.__gt__(self,$B.$GetInt(other)) } throw _b_.TypeError( "unorderable types: int() > "+$B.get_class(other).__name__+"()") } $comp_func +='' for(var $op in $B.$comps){eval("$IntDict.__"+$B.$comps[$op]+'__ = '+ $comp_func.replace(/>/gm,$op).replace(/__gt__/gm,'__'+$B.$comps[$op]+'__')) } $B.make_rmethods($IntDict) var $valid_digits=function(base){var digits='' if(base===0)return '0' if(base < 10){for(var i=0;i < base;i++)digits+=String.fromCharCode(i+48) return digits } var digits='0123456789' for(var i=10;i < base;i++)digits+=String.fromCharCode(i+55) return digits } var int=function(value,base){ if(typeof value=='number' && base===undefined){return parseInt(value)} if(base!==undefined){if(!isinstance(value,[_b_.str,_b_.bytes,_b_.bytearray])){throw TypeError("int() can't convert non-string with explicit base") }} if(isinstance(value,_b_.float)){var v=value.value return v >=0 ? Math.floor(v): Math.ceil(v) } if(isinstance(value,_b_.complex)){throw TypeError("can't convert complex to int") } var $ns=$B.$MakeArgs('int',arguments,[],[],'args','kw') var value=$ns['args'][0] var base=$ns['args'][1] if(value===undefined)value=_b_.dict.$dict.get($ns['kw'],'x',0) if(base===undefined)base=_b_.dict.$dict.get($ns['kw'],'base',10) if(!(base >=2 && base <=36)){ if(base !=0)throw _b_.ValueError("invalid base") } if(typeof value=='number'){if(base==10){return value} else if(value.toString().search('e')>-1){ throw _b_.OverflowError("can't convert to base "+base) }else{return parseInt(value,base) }} if(value===true)return Number(1) if(value===false)return Number(0) base=$B.$GetInt(base) if(isinstance(value,_b_.str))value=value.valueOf() if(typeof value=="string"){value=value.trim() if(value.length==2 && base==0 &&(value=='0b' ||value=='0o' ||value=='0x')){throw _b_.ValueError('invalid value') } if(value.length >2){var _pre=value.substr(0,2).toUpperCase() if(base==0){if(_pre=='0B')base=2 if(_pre=='0O')base=8 if(_pre=='0X')base=16 } if(_pre=='0B' ||_pre=='0O' ||_pre=='0X'){value=value.substr(2) }} var _digits=$valid_digits(base) var _re=new RegExp('^[+-]?['+_digits+']+$','i') if(!_re.test(value)){throw _b_.ValueError( "Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'") } if(base <=10 && !isFinite(value)){throw _b_.ValueError( "Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'") } return Number(parseInt(value,base)) } if(isinstance(value,[_b_.bytes,_b_.bytearray]))return Number(parseInt(getattr(value,'decode')('latin-1'),base)) if(hasattr(value,'__int__'))return Number(getattr(value,'__int__')()) if(hasattr(value,'__index__'))return Number(getattr(value,'__index__')()) if(hasattr(value,'__trunc__'))return Number(getattr(value,'__trunc__')()) throw _b_.ValueError( "Invalid literal for int() with base "+base +": '"+_b_.str(value)+"'") } int.$dict=$IntDict int.__class__=$B.$factory $IntDict.$factory=int _b_.int=int })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict function $UnsupportedOpType(op,class1,class2){throw _b_.TypeError("unsupported operand type(s) for "+op+": '"+class1+"' and '"+class2+"'") } var $ComplexDict={__class__:$B.$type,__dir__:$ObjectDict.__dir__,__name__:'complex',$native:true } $ComplexDict.__abs__=function(self,other){return complex(abs(self.real),abs(self.imag))} $ComplexDict.__bool__=function(self){return new Boolean(self.real ||self.imag)} $ComplexDict.__class__=$B.$type $ComplexDict.__eq__=function(self,other){if(isinstance(other,complex))return self.real==other.real && self.imag==other.imag if(isinstance(other,_b_.int)){if(self.imag !=0)return False return self.real==other.valueOf() } if(isinstance(other,_b_.float)){if(self.imag !=0)return False return self.real==other.value } $UnsupportedOpType("==","complex",$B.get_class(other)) } $ComplexDict.__floordiv__=function(self,other){$UnsupportedOpType("//","complex",$B.get_class(other)) } $ComplexDict.__hash__=function(self){ if(self===undefined){return $ComplexDict.__hashvalue__ ||$B.$py_next_hash-- } return self.imag*1000003+self.real } $ComplexDict.__init__=function(self,real,imag){self.toString=function(){return '('+real+'+'+imag+'j)'}} $ComplexDict.__invert__=function(self){return ~self} $ComplexDict.__mod__=function(self,other){throw _b_.TypeError("TypeError: can't mod complex numbers.") } $ComplexDict.__mro__=[$ComplexDict,$ObjectDict] $ComplexDict.__mul__=function(self,other){if(isinstance(other,complex)) return complex(self.real*other.real-self.imag*other.imag,self.imag*other.real + self.real*other.imag) if(isinstance(other,_b_.int)) return complex(self.real*other.valueOf(),self.imag*other.valueOf()) if(isinstance(other,_b_.float)) return complex(self.real*other.value,self.imag*other.value) if(isinstance(other,_b_.bool)){if(other.valueOf())return self return complex(0) } $UnsupportedOpType("*",complex,other) } $ComplexDict.__name__='complex' $ComplexDict.__ne__=function(self,other){return !$ComplexDict.__eq__(self,other)} $ComplexDict.__neg__=function(self){return complex(-self.real,-self.imag)} $ComplexDict.__new__=function(cls){if(cls===undefined)throw _b_.TypeError('complex.__new__(): not enough arguments') return{__class__:cls.$dict}} $ComplexDict.__pow__=function(self,other){$UnsupportedOpType("**",complex,$B.get_class(other)) } $ComplexDict.__str__=$ComplexDict.__repr__=function(self){if(self.real==0)return self.imag+'j' if(self.imag>=0)return '('+self.real+'+'+self.imag+'j)' return '('+self.real+'-'+(-self.imag)+'j)' } $ComplexDict.__sqrt__=function(self){if(self.imag==0)return complex(Math.sqrt(self.real)) var r=self.real,i=self.imag var _sqrt=Math.sqrt(r*r+i*i) var _a=Math.sqrt((r + sqrt)/2) var _b=Number.sign(i)* Math.sqrt((-r + sqrt)/2) return complex(_a,_b) } $ComplexDict.__truediv__=function(self,other){if(isinstance(other,complex)){if(other.real==0 && other.imag==0){throw ZeroDivisionError('division by zero') } var _num=self.real*other.real + self.imag*other.imag var _div=other.real*other.real + other.imag*other.imag var _num2=self.imag*other.real - self.real*other.imag return complex(_num/_div,_num2/_div) } if(isinstance(other,_b_.int)){if(!other.valueOf())throw ZeroDivisionError('division by zero') return $ComplexDict.__truediv__(self,complex(other.valueOf())) } if(isinstance(other,_b_.float)){if(!other.value)throw ZeroDivisionError('division by zero') return $ComplexDict.__truediv__(self,complex(other.value)) } $UnsupportedOpType("//","complex",other.__class__) } var $op_func=function(self,other){throw _b_.TypeError("TypeError: unsupported operand type(s) for -: 'complex' and '" + $B.get_class(other).__name__+"'") } $op_func +='' var $ops={'&':'and','|':'ior','<<':'lshift','>>':'rshift','^':'xor'} for(var $op in $ops){eval('$ComplexDict.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op)) } $ComplexDict.__ior__=$ComplexDict.__or__ var $op_func=function(self,other){if(isinstance(other,complex))return complex(self.real-other.real,self.imag-other.imag) if(isinstance(other,_b_.int))return complex(self.real-other.valueOf(),self.imag) if(isinstance(other,_b_.float))return complex(self.real - other.value,self.imag) if(isinstance(other,_b_.bool)){var bool_value=0 if(other.valueOf())bool_value=1 return complex(self.real - bool_value,self.imag) } throw _b_.TypeError("unsupported operand type(s) for -: "+self.__repr__()+ " and '"+$B.get_class(other).__name__+"'") } $op_func +='' var $ops={'+':'add','-':'sub'} for(var $op in $ops){eval('$ComplexDict.__'+$ops[$op]+'__ = '+$op_func.replace(/-/gm,$op)) } var $comp_func=function(self,other){throw _b_.TypeError("TypeError: unorderable types: complex() > " + $B.get_class(other).__name__ + "()") } $comp_func +='' for(var $op in $B.$comps){eval("$ComplexDict.__"+$B.$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op)) } $B.make_rmethods($ComplexDict) var complex=function(real,imag){var res={__class__:$ComplexDict,real:real ||0,imag:imag ||0 } res.__repr__=res.__str__=function(){if(real==0)return imag + 'j' return '('+real+'+'+imag+'j)' } return res } complex.$dict=$ComplexDict complex.__class__=$B.$factory $ComplexDict.$factory=complex $B.set_func_names($ComplexDict) _b_.complex=complex })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict function $list(){ var args=[],pos=0 for(var i=0,_len_i=arguments.length;i < _len_i;i++){args[pos++]=arguments[i]} return new $ListDict(args) } var $ListDict={__class__:$B.$type,__name__:'list',$native:true,__dir__:$ObjectDict.__dir__} $ListDict.__add__=function(self,other){var res=self.valueOf().concat(other.valueOf()) if(isinstance(self,tuple))res=tuple(res) return res } $ListDict.__contains__=function(self,item){var _eq=getattr(item,'__eq__') var i=self.length while(i--){try{if(_eq(self[i]))return true }catch(err){$B.$pop_exc();void(0)}} return false } $ListDict.__delitem__=function(self,arg){if(isinstance(arg,_b_.int)){var pos=arg if(arg<0)pos=self.length+pos if(pos>=0 && pos<self.length){self.splice(pos,1) return } throw _b_.IndexError('list index out of range') } if(isinstance(arg,_b_.slice)){var start=arg.start;if(start===None){start=0} var stop=arg.stop;if(stop===None){stop=self.length} var step=arg.step ||1 if(start<0)start=self.length+start if(stop<0)stop=self.length+stop var res=[],i=null,pos=0 if(step>0){if(stop>start){for(var i=start;i<stop;i+=step){if(self[i]!==undefined){res[pos++]=i}}}}else{ if(stop<start){for(var i=start;i>stop;i+=step.value){if(self[i]!==undefined){res[pos++]=i}} res.reverse() }} var i=res.length while(i--){ self.splice(res[i],1) } return } if(hasattr(arg,'__int__')||hasattr(arg,'__index__')){$ListDict.__delitem__(self,_b_.int(arg)) return } throw _b_.TypeError('list indices must be integer, not '+_b_.str(arg.__class__)) } $ListDict.__eq__=function(self,other){ if(other===undefined)return self===list if($B.get_class(other)===$B.get_class(self)){if(other.length==self.length){var i=self.length while(i--){if(!getattr(self[i],'__eq__')(other[i]))return false } return true }} if(isinstance(other,[_b_.set,_b_.tuple,_b_.list])){if(self.length !=getattr(other,'__len__')())return false var i=self.length while(i--){if(!getattr(other,'__contains__')(self[i]))return false } return true } return false } $ListDict.__getitem__=function(self,arg){if(isinstance(arg,_b_.int)){var items=self.valueOf() var pos=arg if(arg<0)pos=items.length+pos if(pos>=0 && pos<items.length)return items[pos] throw _b_.IndexError('list index out of range') } if(isinstance(arg,_b_.slice)){ var step=arg.step===None ? 1 : arg.step if(step==0){throw Error('ValueError : slice step cannot be zero') } var length=self.length var start,end if(arg.start===None){start=step<0 ? length-1 : 0 }else{ start=arg.start if(start < 0)start +=length if(start < 0)start=step<0 ? -1 : 0 if(start >=length)start=step<0 ? length-1 : length } if(arg.stop===None){stop=step<0 ? -1 : length }else{ stop=arg.stop if(stop < 0)stop +=length if(stop < 0)stop=step<0 ? -1 : 0 if(stop >=length)stop=step<0 ? length-1 : length } var res=[],i=null,items=self.valueOf(),pos=0 if(step > 0){if(stop <=start)return res for(var i=start;i<stop;i+=step){res[pos++]=items[i] } return res }else{ if(stop > start)return res for(var i=start;i>stop;i+=step){res[pos++]=items[i] } return res }} if(hasattr(arg,'__int__')||hasattr(arg,'__index__')){return $ListDict.__getitem__(self,_b_.int(arg)) } throw _b_.TypeError('list indices must be integer, not '+arg.__class__.__name__) } $ListDict.__getitems__=function(self){return self} $ListDict.__ge__=function(self,other){if(!isinstance(other,[list,_b_.tuple])){throw _b_.TypeError("unorderable types: list() >= "+ $B.get_class(other).__name__+'()') } var i=0 while(i<self.length){if(i>=other.length)return true if(getattr(self[i],'__eq__')(other[i])){i++} else return(getattr(self[i],"__ge__")(other[i])) } return other.length==self.length } $ListDict.__gt__=function(self,other){if(!isinstance(other,[list,_b_.tuple])){throw _b_.TypeError("unorderable types: list() > "+ $B.get_class(other).__name__+'()') } var i=0 while(i<self.length){if(i>=other.length)return true if(getattr(self[i],'__eq__')(other[i])){i++} else return(getattr(self[i],'__gt__')(other[i])) } return false } $ListDict.__hash__=None $ListDict.__init__=function(self,arg){var len_func=getattr(self,'__len__'),pop_func=getattr(self,'pop') while(len_func())pop_func() if(arg===undefined)return var arg=iter(arg) var next_func=getattr(arg,'__next__') var pos=self.length while(1){try{self[pos++]=next_func()} catch(err){if(err.__name__=='StopIteration'){$B.$pop_exc();break} else{throw err}}}} var $list_iterator=$B.$iterator_class('list_iterator') $ListDict.__iter__=function(self){return $B.$iterator(self,$list_iterator) } $ListDict.__le__=function(self,other){return !$ListDict.__gt__(self,other) } $ListDict.__len__=function(self){return self.length} $ListDict.__lt__=function(self,other){return !$ListDict.__ge__(self,other) } $ListDict.__mro__=[$ListDict,$ObjectDict] $ListDict.__mul__=function(self,other){if(isinstance(other,_b_.int)){ var res=[] var $temp=self.slice(0,self.length) for(var i=0;i<other;i++)res=res.concat($temp) return _b_.list(res) } if(hasattr(other,'__int__')||hasattr(other,'__index__')){return $ListDict.__mul__(self,_b_.int(other)) } throw _b_.TypeError("can't multiply sequence by non-int of type '"+ $B.get_class(other).__name__+"'") } $ListDict.__ne__=function(self,other){return !$ListDict.__eq__(self,other)} $ListDict.__repr__=function(self){if(self===undefined)return "<class 'list'>" var _r=self.map(_b_.repr) if(self.__class__===$TupleDict){if(self.length==1){return '('+_r[0]+',)'} return '('+_r.join(', ')+')' } return '['+_r.join(', ')+']' } $ListDict.__setitem__=function(self,arg,value){if(isinstance(arg,_b_.int)){var pos=arg if(arg<0)pos=self.length+pos if(pos>=0 && pos<self.length){self[pos]=value} else{throw _b_.IndexError('list index out of range')} return } if(isinstance(arg,slice)){var start=arg.start===None ? 0 : arg.start var stop=arg.stop===None ? self.length : arg.stop var step=arg.step===None ? 1 : arg.step if(start<0)start=self.length+start if(stop<0)stop=self.length+stop self.splice(start,stop-start) var $temp if(Array.isArray(value)){$temp=Array.prototype.slice.call(value)} else if(hasattr(value,'__iter__')){$temp=list(value)} if($temp!==undefined){for(var i=$temp.length-1;i>=0;i--){self.splice(start,0,$temp[i]) } return } throw _b_.TypeError("can only assign an iterable") } if(hasattr(arg,'__int__')||hasattr(arg,'__index__')){$ListDict.__setitem__(self,_b_.int(arg),value) return } throw _b_.TypeError('list indices must be integer, not '+arg.__class__.__name__) } $ListDict.__str__=$ListDict.__repr__ $B.make_rmethods($ListDict) var _ops=['add','sub'] $ListDict.__imul__=function(self,value){self=$ListDict.__mul__(self,value)} $ListDict.append=function(self,other){self[self.length]=other} $ListDict.clear=function(self){while(self.length)self.pop()} $ListDict.copy=function(self){return self.slice(0,self.length)} $ListDict.count=function(self,elt){var res=0 _eq=getattr(elt,'__eq__') var i=self.length while(i--)if(_eq(self[i]))res++ return res } $ListDict.extend=function(self,other){if(arguments.length!=2){throw _b_.TypeError( "extend() takes exactly one argument ("+arguments.length+" given)")} other=iter(other) var pos=self.length while(1){try{self[pos++]=next(other)} catch(err){if(err.__name__=='StopIteration'){$B.$pop_exc();break} else{throw err}}}} $ListDict.index=function(self,elt){var _eq=getattr(elt,'__eq__') for(var i=0,_len_i=self.length;i < _len_i;i++){if(_eq(self[i]))return i } throw _b_.ValueError(_b_.str(elt)+" is not in list") } $ListDict.insert=function(self,i,item){self.splice(i,0,item)} $ListDict.remove=function(self,elt){var _eq=getattr(elt,'__eq__') for(var i=0,_len_i=self.length;i < _len_i;i++){if(_eq(self[i])){self.splice(i,1) return }} throw _b_.ValueError(_b_.str(elt)+" is not in list") } $ListDict.pop=function(self,pos){if(pos===undefined){ return self.splice(self.length-1,1)[0] } if(arguments.length==2){if(isinstance(pos,_b_.int)){var res=self[pos] self.splice(pos,1) return res } throw _b_.TypeError(pos.__class__+" object cannot be interpreted as an integer") } throw _b_.TypeError("pop() takes at most 1 argument ("+(arguments.length-1)+' given)') } $ListDict.reverse=function(self){var _len=self.length-1 var i=parseInt(self.length/2) while(i--){var buf=self[i] self[i]=self[_len-i] self[_len-i]=buf }} function $partition(arg,array,begin,end,pivot) {var piv=array[pivot] array=swap(array,pivot,end-1) var store=begin if(arg===null){if(array.$cl!==false){ var le_func=array.$cl.__le__ for(var ix=begin;ix<end-1;++ix){if(le_func(array[ix],piv)){array=swap(array,store,ix) ++store }}}else{for(var ix=begin;ix<end-1;++ix){if(getattr(array[ix],'__le__')(piv)){array=swap(array,store,ix) ++store }}}}else{for(var ix=begin;ix<end-1;++ix){if(getattr(arg(array[ix]),'__le__')(arg(piv))){array=swap(array,store,ix) ++store }}} array=swap(array,end-1,store) return store } function swap(_array,a,b){var tmp=_array[a] _array[a]=_array[b] _array[b]=tmp return _array } function $qsort(arg,array,begin,end) {if(end-1>begin){var pivot=begin+Math.floor(Math.random()*(end-begin)) pivot=$partition(arg,array,begin,end,pivot) $qsort(arg,array,begin,pivot) $qsort(arg,array,pivot+1,end) }} function $elts_class(self){ if(self.length==0){return null} var cl=$B.get_class(self[0]),i=self.length while(i--){ if($B.get_class(self[i])!==cl)return false } return cl } $ListDict.sort=function(self){var func=null var reverse=false for(var i=1,_len_i=arguments.length;i < _len_i;i++){var arg=arguments[i] if(arg.$nat=='kw'){var kw_args=arg.kw for(var key in kw_args){if(key=='key'){func=getattr(kw_args[key],'__call__')} else if(key=='reverse'){reverse=kw_args[key]}}}} if(self.length==0)return self.$cl=$elts_class(self) if(func===null && self.$cl===_b_.str.$dict){self.sort()} else if(func===null && self.$cl===_b_.int.$dict){self.sort(function(a,b){return a-b}) } else{$qsort(func,self,0,self.length)} if(reverse)$ListDict.reverse(self) if(!self.__brython__)return self } $B.set_func_names($ListDict) function list(obj){if(arguments.length===0)return[] if(arguments.length>1){throw _b_.TypeError("list() takes at most 1 argument ("+arguments.length+" given)") } if(Array.isArray(obj)){ obj.__brython__=true if(obj.__class__==$TupleDict){var res=obj.slice() res.__class__=$ListDict return res } return obj } var res=[],pos=0 var arg=iter(obj) var next_func=getattr(arg,'__next__') while(1){try{res[pos++]=next_func()} catch(err){if(err.__name__=='StopIteration'){$B.$pop_exc() }else{throw err } break }} res.__brython__=true return res } list.__class__=$B.$factory list.$dict=$ListDict $ListDict.$factory=list list.$is_func=true list.__module__='builtins' list.__bases__=[] var $ListSubclassDict={__class__:$B.$type,__name__:'list' } for(var $attr in $ListDict){if(typeof $ListDict[$attr]=='function'){$ListSubclassDict[$attr]=(function(attr){return function(){var args=[] if(arguments.length>0){var args=[arguments[0].valueOf()] var pos=1 for(var i=1,_len_i=arguments.length;i < _len_i;i++){args[pos++]=arguments[i] }} return $ListDict[attr].apply(null,args) }})($attr) }} $ListSubclassDict.__init__=function(self){var res=[],args=[res],pos=1 for(var i=1;i<arguments.length;i++){args[pos++]=arguments[i]} $ListDict.__init__.apply(null,args) self.valueOf=function(){return res}} $ListSubclassDict.__mro__=[$ListSubclassDict,$ObjectDict] $B.$ListSubclassFactory={__class__:$B.$factory,$dict:$ListSubclassDict } function $tuple(arg){return arg} var $TupleDict={__class__:$B.$type,__name__:'tuple',$native:true} $TupleDict.__iter__=function(self){return $B.$iterator(self,$tuple_iterator) } var $tuple_iterator=$B.$iterator_class('tuple_iterator') function tuple(){var obj=list.apply(null,arguments) obj.__class__=$TupleDict return obj } tuple.__class__=$B.$factory tuple.$dict=$TupleDict tuple.$is_func=true $TupleDict.$factory=tuple $TupleDict.__new__=$B.$__new__(tuple) tuple.__module__='builtins' for(var attr in $ListDict){switch(attr){case '__delitem__': case '__setitem__': case 'append': case 'extend': case 'insert': case 'remove': case 'pop': case 'reverse': case 'sort': break default: if($TupleDict[attr]===undefined){if(typeof $ListDict[attr]=='function'){$TupleDict[attr]=(function(x){return function(){return $ListDict[x].apply(null,arguments)}})(attr) }else{$TupleDict[attr]=$ListDict[attr] }}} } $TupleDict.__delitem__=function(){throw _b_.TypeError("'tuple' object doesn't support item deletion") } $TupleDict.__setitem__=function(){throw _b_.TypeError("'tuple' object does not support item assignment") } $TupleDict.__eq__=function(self,other){ if(other===undefined)return self===tuple return $ListDict.__eq__(self,other) } $TupleDict.__hash__=function(self){ var x=0x345678 for(var i=0,_len_i=self.length;i < _len_i;i++){var y=_b_.hash(self[i]) x=(1000003 * x)^ y & 0xFFFFFFFF } return x } $TupleDict.__mro__=[$TupleDict,$ObjectDict] $TupleDict.__name__='tuple' $B.set_func_names($TupleDict) _b_.list=list _b_.tuple=tuple _b_.object.$dict.__bases__=tuple() })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=object.$dict var $StringDict={__class__:$B.$type,__dir__:$ObjectDict.__dir__,__name__:'str',$native:true } $StringDict.__add__=function(self,other){if(!(typeof other==="string")){try{return getattr(other,'__radd__')(self)} catch(err){throw _b_.TypeError( "Can't convert "+$B.get_class(other).__name__+" to str implicitely")}} return self+other } $StringDict.__contains__=function(self,item){if(!(typeof item==="string")){throw _b_.TypeError( "'in <string>' requires string as left operand, not "+item.__class__)} var nbcar=item.length if(nbcar==0)return true if(self.length==0)return nbcar==0 for(var i=0,_len_i=self.length;i < _len_i;i++){if(self.substr(i,nbcar)==item)return true } return false } $StringDict.__delitem__=function(){throw _b_.TypeError("'str' object doesn't support item deletion") } $StringDict.__dir__=$ObjectDict.__dir__ $StringDict.__eq__=function(self,other){if(other===undefined){ return self===str } if(_b_.isinstance(other,_b_.str)){return other.valueOf()==self.valueOf() } return other===self.valueOf() } $StringDict.__format__=function(self,arg){var _fs=$FormattableString(self.valueOf()) var args=[],pos=0 for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} return _fs.strformat(arg) } $StringDict.__getitem__=function(self,arg){if(isinstance(arg,_b_.int)){var pos=arg if(arg<0)pos+=self.length if(pos>=0 && pos<self.length)return self.charAt(pos) throw _b_.IndexError('string index out of range') } if(isinstance(arg,slice)){var step=arg.step===None ? 1 : arg.step if(step>0){var start=arg.start===None ? 0 : arg.start var stop=arg.stop===None ? getattr(self,'__len__')(): arg.stop }else{var start=arg.start===None ? getattr(self,'__len__')()-1 : arg.start var stop=arg.stop===None ? 0 : arg.stop } if(start<0)start+=self.length if(stop<0)stop+=self.length var res='',i=null if(step>0){if(stop<=start)return '' for(var i=start;i<stop;i+=step)res +=self.charAt(i) }else{ if(stop>=start)return '' for(var i=start;i>=stop;i+=step)res +=self.charAt(i) } return res } if(isinstance(arg,bool))return self.__getitem__(_b_.int(arg)) } $StringDict.__getitems__=function(self){return self.split('')} $StringDict.__hash__=function(self){if(self===undefined){return $StringDict.__hashvalue__ ||$B.$py_next_hash-- } var hash=1 for(var i=0,_len_i=self.length;i < _len_i;i++){hash=(101*hash + self.charCodeAt(i))& 0xFFFFFFFF } return hash } $StringDict.__init__=function(self,arg){self.valueOf=function(){return arg} self.toString=function(){return arg}} var $str_iterator=$B.$iterator_class('str_iterator') $StringDict.__iter__=function(self){var items=self.split('') return $B.$iterator(items,$str_iterator) } $StringDict.__len__=function(self){return self.length} var kwarg_key=new RegExp('([^\\)]*)\\)') var NotANumber=function(){this.name='NotANumber' } var number_check=function(s){if(!isinstance(s,[_b_.int,_b_.float])){throw new NotANumber() }} var get_char_array=function(size,char){if(size <=0) return '' return new Array(size + 1).join(char) } var format_padding=function(s,flags,minus_one){var padding=flags.padding if(!padding){ return s } s=s.toString() padding=parseInt(padding,10) if(minus_one){ padding -=1 } if(!flags.left){return get_char_array(padding - s.length,flags.pad_char)+ s }else{ return s + get_char_array(padding - s.length,flags.pad_char) }} var format_int_precision=function(val,flags){var precision=flags.precision if(!precision){return val.toString() } precision=parseInt(precision,10) var s=val.toString() var sign=s[0] if(s[0]==='-'){return '-' + get_char_array(precision - s.length + 1,'0')+ s.slice(1) } return get_char_array(precision - s.length,'0')+ s } var format_float_precision=function(val,upper,flags,modifier){var precision=flags.precision if(isFinite(val)){val=modifier(val,precision,flags,upper) return val } if(val===Infinity){val='inf' }else if(val===-Infinity){val='-inf' }else{ val='nan' } if(upper){return val.toUpperCase() } return val } var format_sign=function(val,flags){if(flags.sign){if(val >=0){return "+" }}else if(flags.space){if(val >=0){return " " }} return "" } var str_format=function(val,flags){ flags.pad_char=" " return format_padding(str(val),flags) } var num_format=function(val,flags){number_check(val) val=parseInt(val) var s=format_int_precision(val,flags) if(flags.pad_char==='0'){if(val < 0){s=s.substring(1) return '-' + format_padding(s,flags,true) } var sign=format_sign(val,flags) if(sign !==''){return sign + format_padding(s,flags,true) }} return format_padding(format_sign(val,flags)+ s,flags) } var repr_format=function(val,flags){flags.pad_char=" " return format_padding(repr(val),flags) } var ascii_format=function(val,flags){flags.pad_char=" " return format_padding(ascii(val),flags) } var _float_helper=function(val,flags){number_check(val) if(!flags.precision){if(!flags.decimal_point){flags.precision=6 }else{ flags.precision=0 }}else{ flags.precision=parseInt(flags.precision,10) validate_precision(flags.precision) } return parseFloat(val) } var trailing_zeros=/(.*?)(0+)([eE].*)/ var leading_zeros=/\.(0*)/ var trailing_dot=/\.$/ var validate_precision=function(precision){ if(precision > 20){throw _b_.ValueError("precision too big") }} var floating_point_format=function(val,upper,flags){val=_float_helper(val,flags) var v=val.toString() var v_len=v.length var dot_idx=v.indexOf('.') if(dot_idx < 0){dot_idx=v_len } if(val < 1 && val > -1){var zeros=leading_zeros.exec(v) var numzeros if(zeros){numzeros=zeros[1].length }else{ numzeros=0 } if(numzeros >=4){val=format_sign(val,flags)+ format_float_precision(val,upper,flags,_floating_g_exp_helper) if(!flags.alternate){var trl=trailing_zeros.exec(val) if(trl){val=trl[1].replace(trailing_dot,'')+ trl[3] }}else{ if(flags.precision <=1){val=val[0]+ '.' + val.substring(1) }} return format_padding(val,flags) } flags.precision +=numzeros return format_padding(format_sign(val,flags)+ format_float_precision(val,upper,flags,function(val,precision){val=val.toFixed(min(precision,v_len - dot_idx)+ numzeros) }),flags) } if(dot_idx > flags.precision){val=format_sign(val,flags)+ format_float_precision(val,upper,flags,_floating_g_exp_helper) if(!flags.alternate){var trl=trailing_zeros.exec(val) if(trl){val=trl[1].replace(trailing_dot,'')+ trl[3] }}else{ if(flags.precision <=1){val=val[0]+ '.' + val.substring(1) }} return format_padding(val,flags) } return format_padding(format_sign(val,flags)+ format_float_precision(val,upper,flags,function(val,precision){if(!flags.decimal_point){precision=min(v_len - 1,6) }else if(precision > v_len){if(!flags.alternate){precision=v_len }} if(precision < dot_idx){precision=dot_idx } return val.toFixed(precision - dot_idx) }),flags) } var _floating_g_exp_helper=function(val,precision,flags,upper){if(precision){--precision } val=val.toExponential(precision) var e_idx=val.lastIndexOf('e') if(e_idx > val.length - 4){val=val.substring(0,e_idx + 2)+ '0' + val.substring(e_idx + 2) } if(upper){return val.toUpperCase() } return val } var floating_point_decimal_format=function(val,upper,flags){val=_float_helper(val,flags) return format_padding(format_sign(val,flags)+ format_float_precision(val,upper,flags,function(val,precision,flags){val=val.toFixed(precision) if(precision===0 && flags.alternate){val +='.' } return val }),flags) } var _floating_exp_helper=function(val,precision,flags,upper){val=val.toExponential(precision) var e_idx=val.lastIndexOf('e') if(e_idx > val.length - 4){val=val.substring(0,e_idx + 2)+ '0' + val.substring(e_idx + 2) } if(upper){return val.toUpperCase() } return val } var floating_point_exponential_format=function(val,upper,flags){val=_float_helper(val,flags) return format_padding(format_sign(val,flags)+ format_float_precision(val,upper,flags,_floating_exp_helper),flags) } var signed_hex_format=function(val,upper,flags){number_check(val) var ret=parseInt(val) ret=ret.toString(16) ret=format_int_precision(ret,flags) if(upper){ret=ret.toUpperCase() } if(flags.pad_char==='0'){if(val < 0){ret=ret.substring(1) ret='-' + format_padding(ret,flags,true) } var sign=format_sign(val,flags) if(sign !==''){ret=sign + format_padding(ret,flags,true) }} if(flags.alternate){if(ret.charAt(0)==='-'){if(upper){ret="-0X" + ret.slice(1) }else{ ret="-0x" + ret.slice(1) }}else{ if(upper){ret="0X" + ret }else{ ret="0x" + ret }}} return format_padding(format_sign(val,flags)+ ret,flags) } var octal_format=function(val,flags){number_check(val) var ret=parseInt(val) ret=ret.toString(8) ret=format_int_precision(ret,flags) if(flags.pad_char==='0'){if(val < 0){ret=ret.substring(1) ret='-' + format_padding(ret,flags,true) } var sign=format_sign(val,flags) if(sign !==''){ret=sign + format_padding(ret,flags,true) }} if(flags.alternate){if(ret.charAt(0)==='-'){ret="-0o" + ret.slice(1) }else{ ret="0o" + ret }} return format_padding(ret,flags) } var single_char_format=function(val,flags){if(isinstance(val,str)&& val.length==1)return val try{ val=_b_.int(val) }catch(err){throw _b_.TypeError('%c requires int or char') } return format_padding(chr(val),flags) } var num_flag=function(c,flags){if(c==='0' && !flags.padding && !flags.decimal_point && !flags.left){flags.pad_char='0' return } if(!flags.decimal_point){flags.padding=(flags.padding ||"")+ c }else{ flags.precision=(flags.precision ||"")+ c }} var decimal_point_flag=function(val,flags){if(flags.decimal_point){ throw new UnsupportedChar() } flags.decimal_point=true } var neg_flag=function(val,flags){flags.pad_char=' ' flags.left=true } var space_flag=function(val,flags){flags.space=true } var sign_flag=function(val,flags){flags.sign=true } var alternate_flag=function(val,flags){flags.alternate=true } var char_to_func_mapping={'s': str_format,'d': num_format,'i': num_format,'u': num_format,'o': octal_format,'r': repr_format,'a': ascii_format,'g': function(val,flags){return floating_point_format(val,false,flags)},'G': function(val,flags){return floating_point_format(val,true,flags)},'f': function(val,flags){return floating_point_decimal_format(val,false,flags)},'F': function(val,flags){return floating_point_decimal_format(val,true,flags)},'e': function(val,flags){return floating_point_exponential_format(val,false,flags)},'E': function(val,flags){return floating_point_exponential_format(val,true,flags)},'x': function(val,flags){return signed_hex_format(val,false,flags)},'X': function(val,flags){return signed_hex_format(val,true,flags)},'c': single_char_format,'0': function(val,flags){return num_flag('0',flags)},'1': function(val,flags){return num_flag('1',flags)},'2': function(val,flags){return num_flag('2',flags)},'3': function(val,flags){return num_flag('3',flags)},'4': function(val,flags){return num_flag('4',flags)},'5': function(val,flags){return num_flag('5',flags)},'6': function(val,flags){return num_flag('6',flags)},'7': function(val,flags){return num_flag('7',flags)},'8': function(val,flags){return num_flag('8',flags)},'9': function(val,flags){return num_flag('9',flags)},'-': neg_flag,' ': space_flag,'+': sign_flag,'.': decimal_point_flag,'#': alternate_flag } var UnsupportedChar=function(){this.name="UnsupportedChar" } $StringDict.__mod__=function(val,args){return $legacy_format(val,args,char_to_func_mapping) } var $legacy_format=function(val,args,char_mapping){var length=val.length var pos=0 |0 var argpos=null if(args && _b_.isinstance(args,_b_.tuple)){argpos=0 |0 } var ret='' var $get_kwarg_string=function(s){ ++pos var rslt=kwarg_key.exec(s.substring(newpos)) if(!rslt){throw _b_.ValueError("incomplete format key") } var key=rslt[1] newpos +=rslt[0].length try{ var val=_b_.getattr(args.__class__,'__getitem__')(args,key) }catch(err){if(err.name==="KeyError"){throw err } throw _b_.TypeError("format requires a mapping") } return get_string_value(s,val) } var $get_arg_string=function(s){ var val if(argpos===null){ val=args }else{ try{ val=args[argpos++] } catch(err){if(err.name==="IndexError"){throw _b_.TypeError("not enough arguments for format string") }else{ throw err }}} return get_string_value(s,val) } var get_string_value=function(s,val){ var flags={'pad_char': ' '} do{ var func=char_mapping[s[newpos]] try{ if(func===undefined){throw new UnsupportedChar() }else{ var ret=func(val,flags) if(ret !==undefined){return ret } ++newpos }}catch(err){if(err.name==="UnsupportedChar"){invalid_char=s[newpos] if(invalid_char===undefined){throw _b_.ValueError("incomplete format") } throw _b_.ValueError("unsupported format character '" + invalid_char + "' (0x" + invalid_char.charCodeAt(0).toString(16)+ ") at index " + newpos) }else if(err.name==="NotANumber"){var try_char=s[newpos] var cls=val.__class__ if(!cls){if(typeof(val)==='string'){cls='str' }else{ cls=typeof(val) }}else{ cls=cls.__name__ } throw _b_.TypeError("%" + try_char + " format: a number is required, not " + cls) }else{ throw err }}}while(true) } do{ var newpos=val.indexOf('%',pos) if(newpos < 0){ret +=val.substring(pos) break } ret +=val.substring(pos,newpos) ++newpos if(newpos < length){if(val[newpos]==='%'){ret +='%' }else{ var tmp if(val[newpos]==='('){++newpos ret +=$get_kwarg_string(val) }else{ ret +=$get_arg_string(val) }}}else{ throw _b_.ValueError("incomplete format") } pos=newpos + 1 }while(pos < length) return ret } var char_to_new_format_mapping={'b': function(val,flags){number_check(val) val=val.toString(2) if(flags.alternate){val="0b" + val } return val },'n': function(val,flags){return floating_point_format(val,false,flags)},'N': function(val,flags){return floating_point_format(val,true,flags)}} for(k in char_to_func_mapping){char_to_new_format_mapping[k]=char_to_func_mapping[k] } $format_to_legacy=function(val,args){return $legacy_format(val,args,char_to_new_format_mapping) } $StringDict.__mro__=[$StringDict,$ObjectDict] $StringDict.__mul__=function(self,other){if(!isinstance(other,_b_.int)){throw _b_.TypeError( "Can't multiply sequence by non-int of type '"+ $B.get_class(other).__name__+"'")} $res='' for(var i=0;i<other;i++){$res+=self.valueOf()} return $res } $StringDict.__ne__=function(self,other){return other!==self.valueOf()} $StringDict.__repr__=function(self){if(self===undefined){return "<class 'str'>"} var qesc=new RegExp("'","g") var res=self.replace(/\n/g,'\\\\n') res="'"+res.replace(qesc,"\\'")+"'" return res } $StringDict.__setattr__=function(self,attr,value){setattr(self,attr,value)} $StringDict.__setitem__=function(self,attr,value){throw _b_.TypeError("'str' object does not support item assignment") } $StringDict.__str__=function(self){if(self===undefined)return "<class 'str'>" return self.toString() } $StringDict.toString=function(){return 'string!'} var $comp_func=function(self,other){if(typeof other !=="string"){throw _b_.TypeError( "unorderable types: 'str' > "+$B.get_class(other).__name__+"()")} return self > other } $comp_func +='' var $comps={'>':'gt','>=':'ge','<':'lt','<=':'le'} for(var $op in $comps){eval("$StringDict.__"+$comps[$op]+'__ = '+$comp_func.replace(/>/gm,$op)) } $B.make_rmethods($StringDict) var $notimplemented=function(self,other){throw NotImplementedError("OPERATOR not implemented for class str") } $StringDict.capitalize=function(self){if(self.length==0)return '' return self.charAt(0).toUpperCase()+self.substr(1).toLowerCase() } $StringDict.casefold=function(self){throw _b_.NotImplementedError("function casefold not implemented yet") } $StringDict.center=function(self,width,fillchar){if(fillchar===undefined){fillchar=' '}else{fillchar=fillchar} if(width<=self.length)return self var pad=parseInt((width-self.length)/2) var res=Array(pad+1).join(fillchar) res +=self + res if(res.length<width){res +=fillchar} return res } $StringDict.count=function(self,elt){if(!(typeof elt==="string")){throw _b_.TypeError( "Can't convert '"+elt.__class__.__name__+"' object to str implicitly")} var n=0,pos=0 while(1){pos=self.indexOf(elt,pos) if(pos>=0){n++;pos+=elt.length}else break } return n } $StringDict.encode=function(self,encoding){if(encoding===undefined)encoding='utf-8' if(encoding=='rot13' ||encoding=='rot_13'){ var res='' for(var i=0,_len=self.length;i<_len ;i++){var char=self.charAt(i) if(('a'<=char && char<='m')||('A'<=char && char<='M')){res +=String.fromCharCode(String.charCodeAt(char)+13) }else if(('m'<char && char<='z')||('M'<char && char<='Z')){res +=String.fromCharCode(String.charCodeAt(char)-13) }else{res +=char}} return res } return _b_.bytes(self,encoding) } $StringDict.endswith=function(self){ var args=[],pos=0 for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} var start=null,end=null var $ns=$B.$MakeArgs("$StringDict.endswith",args,['suffix'],['start','end'],null,null) var suffixes=$ns['suffix'] if(!isinstance(suffixes,_b_.tuple)){suffixes=[suffixes]} start=$ns['start']||start end=$ns['end']||self.length-1 var s=self.substr(start,end+1) for(var i=0,_len_i=suffixes.length;i < _len_i;i++){suffix=suffixes[i] if(suffix.length<=s.length && s.substr(s.length-suffix.length)==suffix)return true } return false } $StringDict.expandtabs=function(self,tabsize){tabsize=tabsize ||8 var _str='' for(var i=0;i < tabsize;i++)_str+=' ' return self.valueOf().replace(/\t/g,_str) } $StringDict.find=function(self){ var start=0,end=self.length var $ns=$B.$MakeArgs("$StringDict.find",arguments,['self','sub'],['start','end'],null,null) for(var attr in $ns){eval('var '+attr+'=$ns[attr]')} if(!isinstance(sub,str)){throw _b_.TypeError( "Can't convert '"+sub.__class__.__name__+"' object to str implicitly")} if(!isinstance(start,_b_.int)||!isinstance(end,_b_.int)){throw _b_.TypeError( "slice indices must be integers or None or have an __index__ method")} var s=self.substring(start,end) var esc_sub='' for(var i=0,_len_i=sub.length;i < _len_i;i++){switch(sub.charAt(i)){case '[': case '.': case '*': case '+': case '?': case '|': case '(': case ')': case '$': case '^': esc_sub +='\\' } esc_sub +=sub.charAt(i) } var res=s.search(esc_sub) if(res==-1)return -1 return start+res } var $FormattableString=function(format_string){ this.format_string=format_string this._prepare=function(){ var match=arguments[0] var p1='' + arguments[2] if(match=='%')return '%%' if(match.substring(0,1)==match.substring(match.length-1)){ return match.substring(0,Math.floor(match.length/2)) } if(p1.charAt(0)=='{' && p1.charAt(match.length-1)=='}'){p1=match.substring(1,p1.length-1) } var _repl if(match.length >=2){_repl='' }else{ _repl=match.substring(1) } var _i=p1.indexOf(':') var _out if(_i > -1){_out=[p1.slice(0,_i),p1.slice(_i+1)] }else{_out=[p1]} var _field=_out[0]||'' var _format_spec=_out[1]||'' _out=_field.split('!') var _literal=_out[0]||'' var _sep=_field.indexOf('!')> -1?'!': undefined var _conv=_out[1] if(_sep && _conv===undefined){throw _b_.ValueError("end of format while looking for conversion specifier") } if(_conv !==undefined && _conv.length > 1){throw _b_.ValueError("expected ':' after format specifier") } if(_conv !==undefined && 'rsa'.indexOf(_conv)==-1){throw _b_.ValueError("Unknown conversion specifier " + _conv) } _name_parts=this.field_part.apply(null,[_literal]) var _start=_literal.charAt(0) var _name='' if(_start=='' ||_start=='.' ||_start=='['){ if(this._index===undefined){throw _b_.ValueError("cannot switch from manual field specification to automatic field numbering") } _name=self._index.toString() this._index+=1 if(! _literal ){_name_parts.shift() }}else{ _name=_name_parts.shift()[1] if(this._index !==undefined && !isNaN(_name)){ if(this._index){throw _b_.ValueError("cannot switch from automatic field " + "numbering to manual field specification") this._index=undefined }}} var _empty_attribute=false var _k for(var i=0,_len_i=_name_parts.length;i < _len_i;i++){_k=_name_parts[i][0] var _v=_name_parts[i][1] var _tail=_name_parts[i][2] if(_v===''){_empty_attribute=true} if(_tail !==''){throw _b_.ValueError("Only '.' or '[' may follow ']' " + "in format field specifier") }} if(_name_parts && _k=='[' && ! _literal.charAt(_literal.length)==']'){throw _b_.ValueError("Missing ']' in format string") } if(_empty_attribute){throw _b_.ValueError("Empty attribute in format string") } var _rv='' if(_format_spec.indexOf('{')!=-1){_format_spec=_format_spec.replace(this.format_sub_re,this._prepare) _rv=[_name_parts,_conv,_format_spec] if(this._nested[_name]===undefined){this._nested[_name]=[] this._nested_array.push(_name) } this._nested[_name].push(_rv) }else{ _rv=[_name_parts,_conv,_format_spec] if(this._kwords[_name]===undefined){this._kwords[_name]=[] this._kwords_array.push(_name) } this._kwords[_name].push(_rv) } return '%(' + id(_rv)+ ')s' } this.format=function(){ var $ns=$B.$MakeArgs('format',arguments,[],[],'args','kwargs') var args=$ns['args'] var kwargs=$ns['kwargs'] if(args.length>0){for(var i=0,_len_i=args.length;i < _len_i;i++){ getattr(kwargs,'__setitem__')(str(i),args[i]) }} var _want_bytes=isinstance(this._string,str) var _params=_b_.dict() for(var i=0,_len_i=this._kwords_array.length;i < _len_i;i++){var _name=this._kwords_array[i] var _items=this._kwords[_name] var _var=getattr(kwargs,'__getitem__')(_name) var _value if(hasattr(_var,'value')){_value=getattr(_var,'value') }else{ _value=_var } for(var j=0,_len_j=_items.length;j < _len_j;j++){var _parts=_items[j][0] var _conv=_items[j][1] var _spec=_items[j][2] var _f=this.format_field.apply(null,[_value,_parts,_conv,_spec,_want_bytes]) getattr(_params,'__setitem__')(id(_items[j]).toString(),_f) }} for(var i=0,_len_i=this._nested_array.length;i < _len_i;i++){var _name=this._nested_array[i] var _items=this._nested[i] var _var=getattr(kwargs,'__getitem__')(_name) var _value if(hasattr(_var,'value')){_value=getattr(getattr(kwargs,'__getitem__')(_name),'value') }else{ _value=_var } for(var j=0,_len_j=_items.length;j < _len_j;j++){var _parts=_items[j][0] var _conv=_items[j][1] var _spec=_items[j][2] _spec=$format_to_legacy(_spec,_params) var _f=this.format_field.apply(null,[_value,_parts,_conv,_spec,_want_bytes]) getattr(_params,'__setitem__')(id(_items[j]).toString(),_f) }} return $format_to_legacy(this._string,_params) } this.format_field=function(value,parts,conv,spec,want_bytes){if(want_bytes===undefined)want_bytes=false for(var i=0,_len_i=parts.length;i < _len_i;i++){var _k=parts[i][0] var _part=parts[i][1] if(_k){if(!isNaN(_part)){value=value[parseInt(_part)] }else{ value=getattr(value,_part) }}else{ value=value[_part] }} if(conv){ value=$format_to_legacy((conv=='r')&& '%r' ||'%s',value) } value=this.strformat(value,spec) if(want_bytes){return value.toString()} return value } this.strformat=function(value,format_spec){if(format_spec===undefined)format_spec='' if(!isinstance(value,[str,_b_.int])&& hasattr(value,'__format__')){return getattr(value,'__format__')(format_spec) } var _m=this.format_spec_re.test(format_spec) if(!_m)throw _b_.ValueError('Invalid conversion specification') var _match=this.format_spec_re.exec(format_spec) var _align=_match[1] var _sign=_match[2] var _prefix=_match[3] var _width=_match[4] var _comma=_match[5] var _precision=_match[6] var _conversion=_match[7] var _is_float=isinstance(value,_b_.float) var _is_integer=isinstance(value,_b_.int) var _is_numeric=_is_float ||_is_integer if(_prefix !='' && ! _is_numeric){if(_is_numeric){throw _b_.ValueError('Alternate form (#) not allowed in float format specifier') }else{ throw _b_.ValueError('Alternate form (#) not allowed in string format specification') }} if(_is_numeric && _conversion=='n'){_conversion=_is_integer && 'd' ||'g' }else{ if(_sign){if(! _is_numeric){throw _b_.ValueError('Sign not allowed in string format specification') } if(_conversion=='c'){throw("Sign not allowed with integer format specifier 'c'") }}} if(_comma !==''){value +='' var x=value.split('.') var x1=x[0] var x2=x.length > 1 ? '.' + x[1]: '' var rgx=/(\d+)(\d{3})/ while(rgx.test(x1)){x1=x1.replace(rgx,'$1' + ',' + '$2') } value=x1+x2 } var _rv if(_conversion !='' &&((_is_numeric && _conversion=='s')|| (! _is_integer && 'coxX'.indexOf(_conversion)!=-1))){console.log(_conversion) throw _b_.ValueError('Fix me') } if(_conversion=='c')_conversion='s' _rv='%' + _prefix + _precision +(_conversion ||'s') _rv=$format_to_legacy(_rv,value) if(_sign !='-' && value >=0)_rv=_sign + _rv var _zero=false if(_width){_zero=_width.charAt(0)=='0' _width=parseInt(_width) }else{ _width=0 } if(_width <=_rv.length){if(! _is_float &&(_align=='=' ||(_zero && ! _align))){throw _b_.ValueError("'=' alignment not allowed in string format specifier") } return _rv } _fill=_align.substr(0,_align.length-1) _align=_align.substr(_align.length-1) if(! _fill){_fill=_zero && '0' ||' '} if(_align=='^'){_rv=getattr(_rv,'center')(_width,_fill) }else if(_align=='=' ||(_zero && ! _align)){if(! _is_numeric){throw _b_.ValueError("'=' alignment not allowed in string format specifier") } if(_value < 0 ||_sign !='-'){_rv=_rv.substring(0,1)+ getattr(_rv.substring(1),'rjust')(_width - 1,_fill) }else{ _rv=getattr(_rv,'rjust')(_width,_fill) }}else if((_align=='>' ||_align=='=')||(_is_numeric && ! _aligned)){_rv=getattr(_rv,'rjust')(_width,_fill) }else if(_align=='<'){_rv=getattr(_rv,'ljust')(_width,_fill) }else{ throw _b_.ValueError("'" + _align + "' alignment not valid") } return _rv } this.field_part=function(literal){if(literal.length==0)return[['','','']] var _matches=[] var _pos=0 var _start='',_middle='',_end='' var arg_name='' if(literal===undefined)console.log(literal) var _lit=literal.charAt(_pos) while(_pos < literal.length && _lit !=='[' && _lit !=='.'){arg_name +=_lit _pos++ _lit=literal.charAt(_pos) } if(arg_name !='')_matches.push(['',arg_name,'']) var attribute_name='' var element_index='' while(_pos < literal.length){var car=literal.charAt(_pos) if(car=='['){ _start=_middle=_end='' _pos++ car=literal.charAt(_pos) while(_pos < literal.length && car !==']'){_middle +=car _pos++ car=literal.charAt(_pos) } _pos++ if(car==']'){while(_pos < literal.length){_end+=literal.charAt(_pos) _pos++ }} _matches.push([_start,_middle,_end]) }else if(car=='.'){ _middle='' _pos++ car=literal.charAt(_pos) while(_pos < literal.length && car !=='[' && car !=='.'){ _middle +=car _pos++ car=literal.charAt(_pos) } _matches.push(['.',_middle,'']) }} return _matches } this.format_str_re=new RegExp( '(%)' + '|((?!{)(?:{{)+' + '|(?:}})+(?!})' + '|{(?:[^{}](?:[^{}]+|{[^{}]*})*)?})','g' ) this.format_sub_re=new RegExp('({[^{}]*})') this.format_spec_re=new RegExp( '((?:[^{}]?[<>=^])?)' + '([\\-\\+ ]?)' + '(#?)' + '(\\d*)' + '(,?)' + '((?:\.\\d+)?)' + '(.?)$' ) this._index=0 this._kwords={} this._kwords_array=[] this._nested={} this._nested_array=[] this._string=format_string.replace(this.format_str_re,this._prepare) return this } $StringDict.format=function(self){var _fs=$FormattableString(self.valueOf()) var args=[],pos=0 for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} return _fs.format.apply(null,args) } $StringDict.format_map=function(self){throw NotImplementedError("function format_map not implemented yet") } $StringDict.index=function(self){ var res=$StringDict.find.apply(self,arguments) if(res===-1)throw _b_.ValueError("substring not found") return res } $StringDict.isalnum=function(self){return /^[a-z0-9]+$/i.test(self)} $StringDict.isalpha=function(self){return /^[a-z]+$/i.test(self)} $StringDict.isdecimal=function(self){ return /^[0-9]+$/.test(self) } $StringDict.isdigit=function(self){return /^[0-9]+$/.test(self)} $StringDict.isidentifier=function(self){switch(self){case 'False': case 'None': case 'True': case 'and': case 'as': case 'assert': case 'break': case 'class': case 'continue': case 'def': case 'del': case 'elif': case 'else': case 'except': case 'finally': case 'for': case 'from': case 'global': case 'if': case 'import': case 'in': case 'is': case 'lambda': case 'nonlocal': case 'not': case 'or': case 'pass': case 'raise': case 'return': case 'try': case 'while': case 'with': case 'yield': return true } return /^[a-z][0-9a-z_]+$/i.test(self) } $StringDict.islower=function(self){return /^[a-z]+$/.test(self)} $StringDict.isnumeric=function(self){return /^[0-9]+$/.test(self)} $StringDict.isprintable=function(self){return !/[^ -~]/.test(self)} $StringDict.isspace=function(self){return /^\s+$/i.test(self)} $StringDict.istitle=function(self){return /^([A-Z][a-z]+)(\s[A-Z][a-z]+)$/i.test(self)} $StringDict.isupper=function(self){return /^[A-Z]+$/.test(self)} $StringDict.join=function(self,obj){var iterable=iter(obj) var res='',count=0 while(1){try{var obj2=next(iterable) if(!isinstance(obj2,str)){throw _b_.TypeError( "sequence item "+count+": expected str instance, "+$B.get_class(obj2).__name__+" found")} res +=obj2+self count++ }catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();break} else{throw err}}} if(count==0)return '' return res.substr(0,res.length-self.length) } $StringDict.ljust=function(self,width,fillchar){if(width <=self.length)return self if(fillchar===undefined)fillchar=' ' return self + Array(width - self.length + 1).join(fillchar) } $StringDict.lower=function(self){return self.toLowerCase()} $StringDict.lstrip=function(self,x){var pattern=null if(x==undefined){pattern="\\s*"} else{pattern="["+x+"]*"} var sp=new RegExp("^"+pattern) return self.replace(sp,"") } $StringDict.maketrans=function(from,to){var _t=[] for(var i=0;i < 256;i++)_t[i]=String.fromCharCode(i) for(var i=0,_len_i=from.source.length;i < _len_i;i++){var _ndx=from.source[i].charCodeAt(0) _t[_ndx]=to.source[i] } var _d=dict() for(var i=0;i < 256;i++){_b_.dict.$dict.__setitem__(_d,i,_t[i]) } return _d } $StringDict.partition=function(self,sep){if(sep===undefined){throw Error("sep argument is required") return } var i=self.indexOf(sep) if(i==-1)return _b_.tuple([self,'','']) return _b_.tuple([self.substring(0,i),sep,self.substring(i+sep.length)]) } function $re_escape(str) {var specials="[.*+?|()$^" for(var i=0,_len_i=specials.length;i < _len_i;i++){var re=new RegExp('\\'+specials.charAt(i),'g') str=str.replace(re,"\\"+specials.charAt(i)) } return str } $StringDict.replace=function(self,old,_new,count){ if(count===undefined){count=-1 }else{ if(!isinstance(count,[_b_.int,_b_.float])){throw _b_.TypeError("'" + str(count.__class__)+ "' object cannot be interpreted as an integer") }else if(isinstance(count,_b_.float)){throw _b_.TypeError("integer argument expected, got float") }} var res=self.valueOf() var pos=-1 if(count < 0)count=res.length while(count > 0){pos=res.indexOf(old,pos) if(pos < 0) break res=res.substr(0,pos)+ _new + res.substr(pos + old.length) pos=pos + _new.length count-- } return res } $StringDict.rfind=function(self){ var start=0,end=self.length var $ns=$B.$MakeArgs("$StringDict.find",arguments,['self','sub'],['start','end'],null,null) for(var attr in $ns){eval('var '+attr+'=$ns[attr]')} if(!isinstance(sub,str)){throw _b_.TypeError( "Can't convert '"+sub.__class__.__name__+"' object to str implicitly")} if(!isinstance(start,_b_.int)||!isinstance(end,_b_.int)){throw _b_.TypeError( "slice indices must be integers or None or have an __index__ method")} var s=self.substring(start,end) return self.lastIndexOf(sub) } $StringDict.rindex=function(){ var res=$StringDict.rfind.apply(this,arguments) if(res==-1){throw _b_.ValueError("substring not found")} return res } $StringDict.rjust=function(self){var fillchar=' ' var $ns=$B.$MakeArgs("$StringDict.rjust",arguments,['self','width'],['fillchar'],null,null) for(var attr in $ns){eval('var '+attr+'=$ns[attr]')} if(width <=self.length)return self return Array(width - self.length + 1).join(fillchar)+ self } $StringDict.rpartition=function(self,sep){if(sep===undefined){throw Error("sep argument is required") return } var pos=self.length-sep.length while(1){if(self.substr(pos,sep.length)==sep){return _b_.tuple([self.substr(0,pos),sep,self.substr(pos+sep.length)]) }else{pos-- if(pos<0){return _b_.tuple(['','',self])}}}} $StringDict.rsplit=function(self){var args=[],pos=0 for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} var $ns=$B.$MakeArgs("$StringDict.rsplit",args,[],[],'args','kw') var sep=None,maxsplit=-1 if($ns['args'].length>=1){sep=$ns['args'][0]} if($ns['args'].length==2){maxsplit=$ns['args'][1]} maxsplit=_b_.dict.$dict.get($ns['kw'],'maxsplit',maxsplit) var array=$StringDict.split(self,sep) if(array.length <=maxsplit ||maxsplit==-1)return array var s=[] s=array.splice(array.length - maxsplit,array.length) s.splice(0,0,array.join(sep)) return s } $StringDict.rstrip=function(self,x){if(x==undefined){var pattern="\\s*"} else{var pattern="["+x+"]*"} sp=new RegExp(pattern+'$') return str(self.replace(sp,"")) } $StringDict.split=function(self){var args=[],pos=0 for(var i=1,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} var $ns=$B.$MakeArgs("$StringDict.split",args,[],[],'args','kw') var sep=None,maxsplit=-1 if($ns['args'].length>=1){sep=$ns['args'][0]} if($ns['args'].length==2){maxsplit=$ns['args'][1]} maxsplit=_b_.dict.$dict.get($ns['kw'],'maxsplit',maxsplit) if(sep=='')throw _b_.ValueError('empty separator') if(sep===None){var res=[] var pos=0 while(pos<self.length&&self.charAt(pos).search(/\s/)>-1){pos++} if(pos===self.length-1){return[]} var name='' while(1){if(self.charAt(pos).search(/\s/)===-1){if(name===''){name=self.charAt(pos)} else{name+=self.charAt(pos)}}else{if(name!==''){res.push(name) if(maxsplit!==-1&&res.length===maxsplit+1){res.pop() res.push(name+self.substr(pos)) return res } name='' }} pos++ if(pos>self.length-1){if(name){res.push(name)} break }} return res }else{var esc_sep='' for(var i=0,_len_i=sep.length;i < _len_i;i++){switch(sep.charAt(i)){case '*': case '+': case '.': case '[': case ']': case '(': case ')': case '|': case '$': case '^': esc_sep +='\\' } esc_sep +=sep.charAt(i) } var re=new RegExp(esc_sep) if(maxsplit==-1){ return self.valueOf().split(re,maxsplit) } var l=self.valueOf().split(re,-1) var a=l.slice(0,maxsplit) var b=l.slice(maxsplit,l.length) if(b.length > 0)a.push(b.join(sep)) return a }} $StringDict.splitlines=function(self){return $StringDict.split(self,'\n')} $StringDict.startswith=function(self){ var $ns=$B.$MakeArgs("$StringDict.startswith",arguments,['self','prefix'],['start','end'],null,null) var prefixes=$ns['prefix'] if(!isinstance(prefixes,_b_.tuple)){prefixes=[prefixes]} var start=$ns['start']||0 var end=$ns['end']||self.length-1 var s=self.substr(start,end+1) for(var i=0,_len_i=prefixes.length;i < _len_i;i++){if(s.indexOf(prefixes[i])==0)return true } return false } $StringDict.strip=function(self,x){if(x==undefined){x="\\s"} return $StringDict.rstrip($StringDict.lstrip(self,x),x) } $StringDict.swapcase=function(self){ return self.replace(/([a-z])|([A-Z])/g,function($0,$1,$2) {return($1)? $0.toUpperCase(): $0.toLowerCase() }) } $StringDict.title=function(self){ return self.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+ txt.substr(1).toLowerCase();}) } $StringDict.translate=function(self,table){var res=[],pos=0 if(isinstance(table,_b_.dict)){for(var i=0,_len_i=self.length;i < _len_i;i++){var repl=_b_.dict.$dict.get(table,self.charCodeAt(i),-1) if(repl==-1){res[pos++]=self.charAt(i)} else if(repl!==None){res[pos++]=repl}}} return res.join('') } $StringDict.upper=function(self){return self.toUpperCase()} $StringDict.zfill=function(self,width){if(width===undefined ||width <=self.length ||!self.isnumeric()){return self } return Array(width - self.length +1).join('0') } function str(arg){if(arg===undefined)return '' switch(typeof arg){case 'string': return arg case 'number': return arg.toString() } try{if(arg.__class__===$B.$factory){ var func=$B.$type.__getattribute__(arg.$dict.__class__,'__str__') if(func.__func__===_b_.object.$dict.__str__){return func(arg)} return func() } var f=getattr(arg,'__str__') return f() } catch(err){ $B.$pop_exc() try{ var f=getattr(arg,'__repr__') return getattr(f,'__call__')() }catch(err){$B.$pop_exc() console.log(err+'\ndefault to toString '+arg);return arg.toString() }}} str.__class__=$B.$factory str.$dict=$StringDict $StringDict.$factory=str $StringDict.__new__=function(cls){if(cls===undefined){throw _b_.TypeError('str.__new__(): not enough arguments') } return{__class__:cls.$dict}} $B.set_func_names($StringDict) var $StringSubclassDict={__class__:$B.$type,__name__:'str' } for(var $attr in $StringDict){if(typeof $StringDict[$attr]=='function'){$StringSubclassDict[$attr]=(function(attr){return function(){var args=[],pos=0 if(arguments.length>0){var args=[arguments[0].valueOf()],pos=1 for(var i=1,_len_i=arguments.length;i < _len_i;i++){args[pos++]=arguments[i] }} return $StringDict[attr].apply(null,args) }})($attr) }} $StringSubclassDict.__mro__=[$StringSubclassDict,$ObjectDict] $B.$StringSubclassFactory={__class__:$B.$factory,$dict:$StringSubclassDict } _b_.str=str })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict var str_hash=_b_.str.$dict.__hash__ function $DictClass($keys,$values){this.iter=null this.__class__=$DictDict $DictDict.clear(this) var setitem=$DictDict.__setitem__ var i=$keys.length while(i--)setitem($keys[i],$values[i]) } var $DictDict={__class__:$B.$type,__name__ : 'dict',$native:true,__dir__:$ObjectDict.__dir__ } var $key_iterator=function(d){this.d=d this.current=0 this.iter=new $item_generator(d) } $key_iterator.prototype.length=function(){return this.iter.length } $key_iterator.prototype.next=function(){return this.iter.next()[0]} var $value_iterator=function(d){this.d=d this.current=0 this.iter=new $item_generator(d) } $value_iterator.prototype.length=function(){return this.iter.length } $value_iterator.prototype.next=function(){return this.iter.next()[1]} var $item_generator=function(d){this.i=0 if(d.$jsobj){this.items=[] for(var attr in d.$jsobj){this.items.push([attr,d.$jsobj[attr]])} this.length=this.items.length return } var items=[] var pos=0 for(var k in d.$numeric_dict){items[pos++]=[parseFloat(k),d.$numeric_dict[k]] } for(var k in d.$string_dict){items[pos++]=[k,d.$string_dict[k]] } for(var k in d.$object_dict){var i=d.$object_dict[k].length while(i--)items[pos++]=d.$object_dict[k][i] } this.items=items this.length=items.length } $item_generator.prototype.next=function(){if(this.i < this.items.length){return this.items[this.i++] } throw _b_.StopIteration("StopIteration") } $item_generator.prototype.as_list=function(){return this.items } var $item_iterator=function(d){this.d=d this.current=0 this.iter=new $item_generator(d) } $item_iterator.prototype.length=function(){return this.iter.items.length } $item_iterator.prototype.next=function(){return _b_.tuple(this.iter.next())} var $copy_dict=function(left,right){var _l=new $item_generator(right).as_list() var si=$DictDict.__setitem__ var i=_l.length while(i--)si(left,_l[i][0],_l[i][1]) } $iterator_wrapper=function(items,klass){var res={__class__:klass,__iter__:function(){items.iter.i=0;return res},__len__:function(){return items.length()},__next__:function(){ return items.next() },__repr__:function(){return "<"+klass.__name__+" object>"}, } res.__str__=res.toString=res.__repr__ return res } var $dict_keysDict=$B.$iterator_class('dict_keys') $DictDict.keys=function(self){if(arguments.length > 1){var _len=arguments.length - 1 var _msg="keys() takes no arguments ("+_len+" given)" throw _b_.TypeError(_msg) } return $iterator_wrapper(new $key_iterator(self),$dict_keysDict) } var $dict_valuesDict=$B.$iterator_class('dict_values') $DictDict.values=function(self){if(arguments.length > 1){var _len=arguments.length - 1 var _msg="values() takes no arguments ("+_len+" given)" throw _b_.TypeError(_msg) } return $iterator_wrapper(new $value_iterator(self),$dict_valuesDict) } $DictDict.__bool__=function(self){return $DictDict.__len__(self)> 0} $DictDict.__contains__=function(self,item){if(self.$jsobj)return self.$jsobj[item]!==undefined switch(typeof item){case 'string': return self.$string_dict[item]!==undefined case 'number': return self.$numeric_dict[item]!==undefined } var _key=hash(item) if(self.$str_hash[_key]!==undefined && _b_.getattr(item,'__eq__')(self.$str_hash[_key])){return true} if(self.$numeric_dict[_key]!==undefined && _b_.getattr(item,'__eq__')(_key)){return true} if(self.$object_dict[_key]!==undefined){var _eq=getattr(item,'__eq__') var i=self.$object_dict[_key].length while(i--){if(_eq(self.$object_dict[_key][i][0]))return true }} return false } $DictDict.__delitem__=function(self,arg){if(self.$jsobj){if(self.$jsobj[arg]===undefined){throw KeyError(arg)} delete self.$jsobj[arg] return } switch(typeof arg){case 'string': if(self.$string_dict[arg]===undefined)throw KeyError(_b_.str(arg)) delete self.$string_dict[arg] delete self.$str_hash[str_hash(arg)] return case 'number': if(self.$numeric_dict[arg]===undefined)throw KeyError(_b_.str(arg)) delete self.$numeric_dict[arg] return } var _key=hash(arg) if(self.$object_dict[_key]!==undefined){var _eq=getattr(arg,'__eq__') var i=self.$object_dict[_key].length while(i--){if(_eq(self.$object_dict[_key][i][0])){delete self.$object_dict[_key][i] break }}} if(self.$jsobj)delete self.$jsobj[arg] } $DictDict.__eq__=function(self,other){if(other===undefined){ return self===dict } if(!isinstance(other,dict))return false if($DictDict.__len__(self)!=$DictDict.__len__(other)){return false} var _l=new $item_generator(self).as_list() var i=_l.length while(i--){var key=_l[i][0] if(!$DictDict.__contains__(other,key)){return false} var v1=_l[i][1] var v2=$DictDict.__getitem__(other,key) if(!getattr(v1,'__eq__')(v2)){return false}} return true } $DictDict.__getitem__=function(self,arg){if(self.$jsobj){if(self.$jsobj[arg]===undefined){return None} return self.$jsobj[arg] } switch(typeof arg){case 'string': if(self.$string_dict[arg]!==undefined)return self.$string_dict[arg] break case 'number': if(self.$numeric_dict[arg]!==undefined)return self.$numeric_dict[arg] } var _key=hash(arg) var sk=self.$str_hash[_key] if(sk!==undefined && _b_.getattr(arg,'__eq__')(sk)){return self.$string_dict[sk] } if(self.$numeric_dict[_key]!==undefined && _b_.getattr(arg,'__eq__')(_key)){return self.$numeric_dict[_key] } if(self.$object_dict[_key]!==undefined){var _eq=getattr(arg,'__eq__') var i=self.$object_dict[_key].length while(i--){if(_eq(self.$object_dict[_key][i][0])){return self.$object_dict[_key][i][1] }}} if(hasattr(self,'__missing__'))return getattr(self,'__missing__')(arg) throw KeyError(_b_.str(arg)) } $DictDict.__hash__=function(self){if(self===undefined){return $DictDict.__hashvalue__ ||$B.$py_next_hash-- } throw _b_.TypeError("unhashable type: 'dict'") } $DictDict.__init__=function(self){var args=[],pos=0 for(var i=1;i<arguments.length;i++){args[pos++]=arguments[i]} $DictDict.clear(self) switch(args.length){case 0: return case 1: var obj=args[0] if(Array.isArray(obj)){var i=obj.length var si=$DictDict.__setitem__ while(i--)si(self,obj[i][0],obj[i][1]) return }else if(isinstance(obj,dict)){$copy_dict(self,obj) return } if(obj.__class__===$B.JSObject.$dict){ var si=$DictDict.__setitem__ for(var attr in obj.js)si(self,attr,obj.js[attr]) self.$jsobj=obj.js return }} var $ns=$B.$MakeArgs('dict',args,[],[],'args','kw') var args=$ns['args'] var kw=$ns['kw'] if(args.length>0){if(isinstance(args[0],dict)){$B.$copy_dict(self,args[0]) return } if(Array.isArray(args[0])){var src=args[0] var i=src.length var si=$DictDict.__setitem__ while(i--)si(self,src[i][0],src[i][1]) }else{var iterable=iter(args[0]) while(1){try{var elt=next(iterable) var key=getattr(elt,'__getitem__')(0) var value=getattr(elt,'__getitem__')(1) $DictDict.__setitem__(self,key,value) }catch(err){if(err.__name__==='StopIteration'){$B.$pop_exc();break} throw err }}}} if($DictDict.__len__(kw)> 0)$copy_dict(self,kw) } var $dict_iterator=$B.$iterator_class('dict iterator') $DictDict.__iter__=function(self){return $DictDict.keys(self) } $DictDict.__len__=function(self){var _count=0 if(self.$jsobj){for(var attr in self.$jsobj){_count++} return _count } for(var k in self.$numeric_dict)_count++ for(var k in self.$string_dict)_count++ for(var k in self.$object_dict)_count+=self.$object_dict[k].length return _count } $DictDict.__mro__=[$DictDict,$ObjectDict] $DictDict.__ne__=function(self,other){return !$DictDict.__eq__(self,other)} $DictDict.__next__=function(self){if(self.$iter==null){self.$iter=new $item_generator(self) } try{ return self.$iter.next() }catch(err){if(err.__name__ !=="StopIteration"){throw err }else{$B.$pop_exc()}}} $DictDict.__repr__=function(self){if(self===undefined)return "<class 'dict'>" if(self.$jsobj){ var res=[] for(var attr in self.$jsobj){if(attr.charAt(0)=='$' ||attr=='__class__'){continue} else{res.push(attr+': '+_b_.repr(self.$jsobj[attr]))}} return '{'+res.join(', ')+'}' } var _objs=[self] var res=[],pos=0 var items=new $item_generator(self).as_list() for(var i=0;i < items.length;i++){var itm=items[i] if(_objs.indexOf(itm[1])> -1 && _b_.isinstance(itm[1],[_b_.dict,_b_.list,_b_.set,_b_.tuple])){var value='?'+_b_.type(itm[1]) if(isinstance(itm[1],dict))value='{...}' res[pos++]=repr(itm[0])+': '+ value }else{ if(_objs.indexOf(itm[1])==-1)_objs.push(itm[1]) res[pos++]=repr(itm[0])+': '+repr(itm[1]) }} return '{'+ res.join(', ')+'}' } $DictDict.__setitem__=function(self,key,value){if(self.$jsobj){self.$jsobj[key]=value;return} switch(typeof key){case 'string': self.$string_dict[key]=value self.$str_hash[str_hash(key)]=key return case 'number': self.$numeric_dict[key]=value return } var _key=hash(key) var _eq=getattr(key,'__eq__') if(self.$numeric_dict[_key]!==undefined && _eq(_key)){self.$numeric_dict[_key]=value return } var sk=self.$str_hash[_key] if(sk!==undefined && _eq(sk)){self.$string_dict[sk]=value return } if(self.$object_dict[_key]!=undefined){var i=self.$object_dict[_key].length while(i--){if(_eq(self.$object_dict[_key][i][0])){self.$object_dict[_key][i]=[key,value] return }} self.$object_dict[_key].push([key,value]) }else{ self.$object_dict[_key]=[[key,value]] }} $DictDict.__str__=$DictDict.__repr__ $B.make_rmethods($DictDict) $DictDict.clear=function(self){ self.$numeric_dict={} self.$string_dict={} self.$str_hash={} self.$object_dict={} if(self.$jsobj)self.$jsobj={}} $DictDict.copy=function(self){ var res=_b_.dict() $copy_dict(res,self) return res } $DictDict.get=function(self,key,_default){if(_default===undefined)_default=None switch(typeof key){case 'string': return self.$string_dict[key]||_default case 'number': return self.$numeric_dict[key]||_default } var _key=hash(key) if(self.$object_dict[_key]!=undefined){var _eq=getattr(key,'__eq__') var i=self.$object_dict[_key].length while(i--){if(_eq(self.$object_dict[_key][i][0])) return self.$object_dict[_key][i][1] }} if(_default!==undefined)return _default return None } var $dict_itemsDict=$B.$iterator_class('dict_items') $DictDict.items=function(self){if(arguments.length > 1){var _len=arguments.length - 1 var _msg="items() takes no arguments ("+_len+" given)" throw _b_.TypeError(_msg) } return $iterator_wrapper(new $item_iterator(self),$dict_itemsDict) } $DictDict.fromkeys=function(keys,value){ if(value===undefined)value=None var res=dict() var keys_iter=_b_.iter(keys) while(1){try{var key=_b_.next(keys_iter) $DictDict.__setitem__(res,key,value) }catch(err){if($B.is_exc(err,[_b_.StopIteration])){$B.$pop_exc() return res } throw err }}} $DictDict.pop=function(self,key,_default){try{var res=$DictDict.__getitem__(self,key) $DictDict.__delitem__(self,key) return res }catch(err){$B.$pop_exc() if(err.__name__==='KeyError'){if(_default!==undefined)return _default throw err } throw err }} $DictDict.popitem=function(self){try{var itm=new $item_iterator(self).next() $DictDict.__delitem__(self,itm[0]) return _b_.tuple(itm) }catch(err){if(err.__name__=="StopIteration"){$B.$pop_exc() throw KeyError("'popitem(): dictionary is empty'") }}} $DictDict.setdefault=function(self,key,_default){try{return $DictDict.__getitem__(self,key)} catch(err){if(_default===undefined)_default=None $DictDict.__setitem__(self,key,_default) return _default }} $DictDict.update=function(self){var params=[],pos=0 for(var i=1;i<arguments.length;i++){params[pos++]=arguments[i]} var $ns=$B.$MakeArgs('$DictDict.update',params,[],[],'args','kw') var args=$ns['args'] if(args.length>0){var o=args[0] if(isinstance(o,dict)){$copy_dict(self,o) }else if(hasattr(o,'__getitem__')&& hasattr(o,'keys')){var _keys=_b_.list(getattr(o,'keys')()) var si=$DictDict.__setitem__ var i=_keys.length while(i--){ var _value=getattr(o,'__getitem__')(_keys[i]) si(self,_keys[i],_value) }}} var kw=$ns['kw'] $copy_dict(self,kw) } function dict(args,second){if(second===undefined && Array.isArray(args)){ var res={__class__:$DictDict,$numeric_dict :{},$object_dict :{},$string_dict :{},$str_hash:{},length: 0 } var i=-1,stop=args.length-1 var si=$DictDict.__setitem__ while(i++<stop){var item=args[i] switch(typeof item[0]){case 'string': res.$string_dict[item[0]]=item[1] res.$str_hash[str_hash(item[0])]=item[0] break case 'number': res.$numeric_dict[item[0]]=item[1] break default: si(res,item[0],item[1]) break }} return res } var res={__class__:$DictDict} $DictDict.clear(res) var _args=[res],pos=1 for(var i=0,_len_i=arguments.length;i < _len_i;i++){_args[pos++]=arguments[i]} $DictDict.__init__.apply(null,_args) return res } dict.__class__=$B.$factory dict.$dict=$DictDict $DictDict.$factory=dict $DictDict.__new__=$B.$__new__(dict) _b_.dict=dict $B.$dict_iterator=function(d){return new $item_generator(d)} $B.$dict_length=$DictDict.__len__ $B.$dict_getitem=$DictDict.__getitem__ $B.$dict_get=$DictDict.get $B.$dict_set=$DictDict.__setitem__ $B.$dict_contains=$DictDict.__contains__ $B.$dict_items=function(d){return new $item_generator(d).as_list()} $B.$copy_dict=$copy_dict $B.$dict_get_copy=$DictDict.copy var mappingproxyDict={__class__ : $B.$type,__name__ : "mappingproxy" } mappingproxyDict.__mro__=[mappingproxyDict,_b_.object.$dict] mappingproxyDict.__setitem__=function(){throw _b_.TypeError("'mappingproxy' object does not support item assignment") } function mappingproxy(obj){var res=obj_dict(obj) res.__class__=mappingproxyDict return res } mappingproxy.__class__=$B.$factory mappingproxy.$dict=mappingproxyDict mappingproxyDict.$factory=mappingproxy $B.mappingproxy=mappingproxy $B.obj_dict=function(obj){var res=dict() res.$jsobj=obj return res }})(__BRYTHON__) ;(function($B){var _=$B.builtins var $SetDict={__class__:$B.$type,__dir__:_.object.$dict.__dir__,__name__:'set',$native:true } $SetDict.__add__=function(self,other){return set(self.$items.concat(other.$items)) } $SetDict.__and__=function(self,other,accept_iter){$test(accept_iter,other) var res=set() for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(_.getattr(other,'__contains__')(self.$items[i])){$SetDict.add(res,self.$items[i]) }} return res } $SetDict.__contains__=function(self,item){if(self.$num &&(typeof item=='number')){return self.$items.indexOf(item)>-1} if(self.$str &&(typeof item=='string')){return self.$items.indexOf(item)>-1} for(var i=0,_len_i=self.$items.length;i < _len_i;i++){try{if(_.getattr(self.$items[i],'__eq__')(item))return true }catch(err){void(0)}} return false } $SetDict.__eq__=function(self,other){ if(other===undefined)return self===set if(_.isinstance(other,_.set)){if(other.$items.length==self.$items.length){for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if($SetDict.__contains__(self,other.$items[i])===false)return false } return true } return false } if(_.isinstance(other,[_.list])){if(_.len(other)!=self.$items.length)return false for(var i=0,_len_i=_.len(other);i < _len_i;i++){var _value=getattr(other,'__getitem__')(i) if($SetDict.__contains__(self,_value)===false)return false } return true } if(_.hasattr(other,'__iter__')){ if(_.len(other)!=self.$items.length)return false var _it=_.iter(other) while(1){try{ var e=_.next(_it) if(!$SetDict.__contains__(self,e))return false }catch(err){if(err.__name__=="StopIteration"){$B.$pop_exc();break } console.log(err) throw err }} return true } return false } $SetDict.__ge__=function(self,other){return !$SetDict.__lt__(self,other)} $SetDict.__getitems__=function(self){return self.$items} $SetDict.__gt__=function(self,other,accept_iter){$test(accept_iter,other) return !$SetDict.__le__(self,other) } $SetDict.__hash__=function(self){if(self===undefined){return $SetDict.__hashvalue__ ||$B.$py_next_hash-- } throw _.TypeError("unhashable type: 'set'") } $SetDict.__init__=function(self){var args=[] for(var i=1,_len_i=arguments.length;i < _len_i;i++){args.push(arguments[i]) } if(args.length==0)return if(args.length==1){ var arg=args[0] if(_.isinstance(arg,[set,frozenset])){self.$items=arg.$items return } try{var iterable=_.iter(arg) var obj={$items:[],$str:true,$num:true} while(1){try{$SetDict.add(obj,_.next(iterable))} catch(err){if(err.__name__=='StopIteration'){$B.$pop_exc();break} throw err }} self.$items=obj.$items }catch(err){console.log(''+err) throw _.TypeError("'"+arg.__class__.__name__+"' object is not iterable") }}else{ throw _.TypeError("set expected at most 1 argument, got "+args.length) }} var $set_iterator=$B.$iterator_class('set iterator') $SetDict.__iter__=function(self){return $B.$iterator(self.$items,$set_iterator) } $SetDict.__le__=function(self,other,accept_iter){$test(accept_iter,other) var cfunc=_.getattr(other,'__contains__') for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(!cfunc(self.$items[i]))return false } return true } $SetDict.__len__=function(self){return self.$items.length} $SetDict.__lt__=function(self,other){return($SetDict.__le__(self,other)&& $SetDict.__len__(self)<_.getattr(other,'__len__')()) } $SetDict.__mro__=[$SetDict,_.object.$dict] $SetDict.__ne__=function(self,other){return !$SetDict.__eq__(self,other)} $SetDict.__or__=function(self,other,accept_iter){ var res=$SetDict.copy(self) var func=_.getattr(_.iter(other),'__next__') while(1){try{$SetDict.add(res,func())} catch(err){if(_.isinstance(err,_.StopIteration)){$B.$pop_exc();break} throw err }} return res } $SetDict.__str__=$SetDict.toString=$SetDict.__repr__=function(self){if(self===undefined)return "<class 'set'>" var head='',tail='' frozen=self.$real==='frozen' if(self.$items.length===0){if(frozen)return 'frozenset()' return 'set()' } if(self.__class__===$SetDict && frozen){head='frozenset(' tail=')' }else if(self.__class__!==$SetDict){ head=self.__class__.__name__+'(' tail=')' } var res=[] for(var i=0,_len_i=self.$items.length;i < _len_i;i++){res.push(_.repr(self.$items[i])) } res='{' + res.join(', ')+'}' return head+res+tail } $SetDict.__sub__=function(self,other,accept_iter){ $test(accept_iter,other) var res=set() var cfunc=_.getattr(other,'__contains__') for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(!cfunc(self.$items[i])){res.$items.push(self.$items[i]) }} return res } $SetDict.__xor__=function(self,other,accept_iter){ $test(accept_iter,other) var res=set() var cfunc=_.getattr(other,'__contains__') for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(!cfunc(self.$items[i])){$SetDict.add(res,self.$items[i]) }} for(var i=0,_len_i=other.$items.length;i < _len_i;i++){if(!$SetDict.__contains__(self,other.$items[i])){$SetDict.add(res,other.$items[i]) }} return res } function $test(accept_iter,other){if(accept_iter===undefined && !_.isinstance(other,[set,frozenset])){throw TypeError("unsupported operand type(s) for |: 'set' and '"+ $B.get_class(other).__name__+"'") }} $B.make_rmethods($SetDict) $SetDict.add=function(self,item){if(self.$str && !(typeof item=='string')){self.$str=false} if(self.$num && !(typeof item=='number')){self.$num=false} if(self.$num||self.$str){if(self.$items.indexOf(item)==-1){self.$items.push(item)} return } var cfunc=_.getattr(item,'__eq__') for(var i=0,_len_i=self.$items.length;i < _len_i;i++){try{if(cfunc(self.$items[i]))return} catch(err){void(0)} } self.$items.push(item) } $SetDict.clear=function(self){self.$items=[]} $SetDict.copy=function(self){var res=set() for(var i=0,_len_i=self.$items.length;i < _len_i;i++)res.$items[i]=self.$items[i] return res } $SetDict.difference_update=function(self,s){if(_.isinstance(s,set)){for(var i=0;i < s.$items.length;i++){var _type=typeof s.$items[i] if(_type=='string' ||_type=="number"){var _index=self.$items.indexOf(s.$items[i]) if(_index > -1){self.$items.splice(_index,1) break }}else{ for(var j=0;j < self.$items.length;j++){if(getattr(self.$items[j],'__eq__')(s.$items[i])){self.$items.splice(j,1) break }}}} return }} $SetDict.intersection_update=function(self,s){if(_.isinstance(s,set)){var _res=[] for(var i=0;i < s.$items.length;i++){var _item=s.$items[i] var _type=typeof _item if(_type=='string' ||_type=="number"){if(self.$items.indexOf(_item)> -1)_res.push(_item) }else{ for(var j=0;j < self.$items.length;j++){if(getattr(self.$items[j],'__eq__')(_item)){_res.push(_item) break }}}} self=set(_res) }} $SetDict.discard=function(self,item){try{$SetDict.remove(self,item)} catch(err){if(err.__name__!=='LookupError'){throw err}}} $SetDict.isdisjoint=function(self,other){for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(_.getattr(other,'__contains__')(self.$items[i]))return false } return true } $SetDict.pop=function(self){if(self.$items.length===0)throw _.KeyError('pop from an empty set') return self.$items.pop() } $SetDict.remove=function(self,item){if(typeof item=='string' ||typeof item=='number'){var _i=self.$items.indexOf(item) if(_i==-1)throw _.LookupError('missing item ' + _.repr(item)) self.$items.splice(_i,1) return } for(var i=0,_len_i=self.$items.length;i < _len_i;i++){if(_.getattr(self.$items[i],'__eq__')(item)){self.$items.splice(i,1) return _.None }} throw _.KeyError(item) } $SetDict.update=function(self,other){if(other===undefined ||other.$items===undefined)return for(var i=0,_len_i=other.$items.length;i < _len_i;i++){$SetDict.add(self,other.$items[i]) }} $SetDict.symmetric_difference=function(self,other){return $SetDict.__xor__(self,other,1) } $SetDict.difference=function(self,other){$SetDict.__sub__(self,other,1) } $SetDict.intersection=function(self,other){return $SetDict.__and__(self,other,1) } $SetDict.issubset=function(self,other){return $SetDict.__le__(self,other,1) } $SetDict.issuperset=function(self,other){return $SetDict.__ge__(self,other,1) } $SetDict.union=function(self,other){return $SetDict.__or__(self,other,1) } function set(){ var res={__class__:$SetDict,$str:true,$num:true,$items:[]} var args=[res].concat(Array.prototype.slice.call(arguments)) $SetDict.__init__.apply(null,args) return res } set.__class__=$B.$factory set.$dict=$SetDict $SetDict.$factory=set $SetDict.__new__=$B.$__new__(set) $B.set_func_names($SetDict) var $FrozensetDict={__class__:$B.$type,__name__:'frozenset'} $FrozensetDict.__mro__=[$FrozensetDict,_.object.$dict] $FrozensetDict.__str__=$FrozensetDict.toString=$FrozensetDict.__repr__=function(self){if(self===undefined)return "<class 'frozenset'>" if(self.$items.length===0)return 'frozenset()' var res=[] for(var i=0,_len_i=self.$items.length;i < _len_i;i++){res.push(_.repr(self.$items[i])) } return 'frozenset({'+res.join(', ')+'})' } for(var attr in $SetDict){switch(attr){case 'add': case 'clear': case 'discard': case 'pop': case 'remove': case 'update': break default: if($FrozensetDict[attr]==undefined){if(typeof $SetDict[attr]=='function'){$FrozensetDict[attr]=(function(x){return function(){return $SetDict[x].apply(null,arguments)}})(attr) }else{$FrozensetDict[attr]=$SetDict[attr] }}}} $FrozensetDict.__hash__=function(self){if(self===undefined){return $FrozensetDict.__hashvalue__ ||$B.$py_next_hash-- } if(self.__hashvalue__ !==undefined)return self.__hashvalue__ var _hash=1927868237 _hash *=self.$items.length for(var i=0,_len_i=self.$items.length;i < _len_i;i++){var _h=_.hash(self.$items[i]) _hash ^=((_h ^ 89869747)^(_h << 16))* 3644798167 } _hash=_hash * 69069 + 907133923 if(_hash==-1)_hash=590923713 return self.__hashvalue__=_hash } function frozenset(){var res=set.apply(null,arguments) res.__class__=$FrozensetDict return res } frozenset.__class__=$B.$factory frozenset.$dict=$FrozensetDict $FrozensetDict.__new__=$B.$__new__(frozenset) $FrozensetDict.$factory=frozenset $B.set_func_names($FrozensetDict) _.set=set _.frozenset=frozenset })(__BRYTHON__) ;(function($B){eval($B.InjectBuiltins()) var $ObjectDict=_b_.object.$dict var JSObject=$B.JSObject $B.events=_b_.dict() function $getMouseOffset(target,ev){ev=ev ||window.event var docPos=$getPosition(target) var mousePos=$mouseCoords(ev) return{x:mousePos.x - docPos.x,y:mousePos.y - docPos.y} } function $getPosition(e){var left=0 var top=0 var width=e.width ||e.offsetWidth var height=e.height ||e.offsetHeight while(e.offsetParent){left +=e.offsetLeft top +=e.offsetTop e=e.offsetParent } left +=e.offsetLeft top +=e.offsetTop return{left:left,top:top,width:width,height:height} } function $mouseCoords(ev){var posx=0 var posy=0 if(!ev)var ev=window.event if(ev.pageX ||ev.pageY){posx=ev.pageX posy=ev.pageY }else if(ev.clientX ||ev.clientY){posx=ev.clientX + document.body.scrollLeft + document.documentElement.scrollLeft posy=ev.clientY + document.body.scrollTop + document.documentElement.scrollTop } var res={} res.x=_b_.int(posx) res.y=_b_.int(posy) res.__getattr__=function(attr){return this[attr]} res.__class__="MouseCoords" return res } var $DOMNodeAttrs=['nodeName','nodeValue','nodeType','parentNode','childNodes','firstChild','lastChild','previousSibling','nextSibling','attributes','ownerDocument'] $B.$isNode=function(obj){for(var i=0;i<$DOMNodeAttrs.length;i++){if(obj[$DOMNodeAttrs[i]]===undefined)return false } return true } $B.$isNodeList=function(nodes){ try{var result=Object.prototype.toString.call(nodes) var re=new RegExp("^\\[object (HTMLCollection|NodeList|Object)\\]$") return(typeof nodes==='object' && re.exec(result)!==null && nodes.hasOwnProperty('length') &&(nodes.length==0 ||(typeof nodes[0]==="object" && nodes[0].nodeType > 0)) ) }catch(err){return false }} var $DOMEventAttrs_W3C=['NONE','CAPTURING_PHASE','AT_TARGET','BUBBLING_PHASE','type','target','currentTarget','eventPhase','bubbles','cancelable','timeStamp','stopPropagation','preventDefault','initEvent'] var $DOMEventAttrs_IE=['altKey','altLeft','button','cancelBubble','clientX','clientY','contentOverflow','ctrlKey','ctrlLeft','data','dataFld','dataTransfer','fromElement','keyCode','nextPage','offsetX','offsetY','origin','propertyName','reason','recordset','repeat','screenX','screenY','shiftKey','shiftLeft','source','srcElement','srcFilter','srcUrn','toElement','type','url','wheelDelta','x','y'] $B.$isEvent=function(obj){flag=true for(var i=0;i<$DOMEventAttrs_W3C.length;i++){if(obj[$DOMEventAttrs_W3C[i]]===undefined){flag=false;break}} if(flag)return true for(var i=0;i<$DOMEventAttrs_IE.length;i++){if(obj[$DOMEventAttrs_IE[i]]===undefined)return false } return true } var $NodeTypes={1:"ELEMENT",2:"ATTRIBUTE",3:"TEXT",4:"CDATA_SECTION",5:"ENTITY_REFERENCE",6:"ENTITY",7:"PROCESSING_INSTRUCTION",8:"COMMENT",9:"DOCUMENT",10:"DOCUMENT_TYPE",11:"DOCUMENT_FRAGMENT",12:"NOTATION" } var $DOMEventDict={__class__:$B.$type,__name__:'DOMEvent'} $DOMEventDict.__mro__=[$DOMEventDict,$ObjectDict] $DOMEventDict.__getattribute__=function(self,attr){switch(attr){case 'x': return $mouseCoords(self).x case 'y': return $mouseCoords(self).y case 'data': if(self.dataTransfer!==undefined)return $Clipboard(self.dataTransfer) return self['data'] case 'target': if(self.target===undefined)return DOMNode(self.srcElement) return DOMNode(self.target) case 'char': return String.fromCharCode(self.which) } var res=self[attr] if(res!==undefined){if(typeof res=='function'){var func=function(){return res.apply(self,arguments)} func.$infos={__name__:res.toString().substr(9,res.toString().search('{'))} return func } return $B.$JS2Py(res) } throw _b_.AttributeError("object DOMEvent has no attribute '"+attr+"'") } function $DOMEvent(ev){ev.__class__=$DOMEventDict if(ev.preventDefault===undefined){ev.preventDefault=function(){ev.returnValue=false}} if(ev.stopPropagation===undefined){ev.stopPropagation=function(){ev.cancelBubble=true}} ev.__repr__=function(){return '<DOMEvent object>'} ev.toString=ev.__str__=ev.__repr__ return ev } $B.DOMEvent=function(evt_name){ return $DOMEvent(new Event(evt_name)) } $B.DOMEvent.__class__=$B.$factory $B.DOMEvent.$dict=$DOMEventDict $DOMEventDict.$factory=$B.DOMEvent var $ClipboardDict={__class__:$B.$type,__name__:'Clipboard'} $ClipboardDict.__getitem__=function(self,name){return self.data.getData(name)} $ClipboardDict.__mro__=[$ClipboardDict,$ObjectDict] $ClipboardDict.__setitem__=function(self,name,value){self.data.setData(name,value)} function $Clipboard(data){ return{ data : data,__class__ : $ClipboardDict,}} function $EventsList(elt,evt,arg){ this.elt=elt this.evt=evt if(isintance(arg,list)){this.callbacks=arg} else{this.callbacks=[arg]} this.remove=function(callback){var found=false for(var i=0;i<this.callbacks.length;i++){if(this.callbacks[i]===callback){found=true this.callback.splice(i,1) this.elt.removeEventListener(this.evt,callback,false) break }} if(!found){throw KeyError("not found")}}} function $OpenFile(file,mode,encoding){this.reader=new FileReader() if(mode==='r'){this.reader.readAsText(file,encoding)} else if(mode==='rb'){this.reader.readAsBinaryString(file)} this.file=file this.__class__=dom.FileReader this.__getattr__=function(attr){if(this['get_'+attr]!==undefined)return this['get_'+attr] return this.reader[attr] } this.__setattr__=(function(obj){return function(attr,value){if(attr.substr(0,2)=='on'){ if(window.addEventListener){var callback=function(ev){return value($DOMEvent(ev))} obj.addEventListener(attr.substr(2),callback) }else if(window.attachEvent){var callback=function(ev){return value($DOMEvent(window.event))} obj.attachEvent(attr,callback) }}else if('set_'+attr in obj){return obj['set_'+attr](value)} else if(attr in obj){obj[attr]=value} else{setattr(obj,attr,value)}}})(this.reader) } var dom={File : function(){},FileReader : function(){}} dom.File.__class__=$B.$type dom.File.__str__=function(){return "<class 'File'>"} dom.FileReader.__class__=$B.$type dom.FileReader.__str__=function(){return "<class 'FileReader'>"} function $Options(parent){return{ __class__:$OptionsDict,parent:parent }} var $OptionsDict={__class__:$B.$type,__name__:'Options'} $OptionsDict.__delitem__=function(self,arg){self.parent.options.remove(arg.elt) } $OptionsDict.__getitem__=function(self,key){return DOMNode(self.parent.options[key]) } $OptionsDict.__len__=function(self){return self.parent.options.length} $OptionsDict.__mro__=[$OptionsDict,$ObjectDict] $OptionsDict.__setattr__=function(self,attr,value){self.parent.options[attr]=value } $OptionsDict.__setitem__=function(self,attr,value){self.parent.options[attr]=$B.$JS2Py(value) } $OptionsDict.__str__=function(self){return "<object Options wraps "+self.parent.options+">" } $OptionsDict.append=function(self,element){self.parent.options.add(element.elt) } $OptionsDict.insert=function(self,index,element){if(index===undefined){self.parent.options.add(element.elt)} else{self.parent.options.add(element.elt,index)}} $OptionsDict.item=function(self,index){return self.parent.options.item(index) } $OptionsDict.namedItem=function(self,name){return self.parent.options.namedItem(name) } $OptionsDict.remove=function(self,arg){self.parent.options.remove(arg.elt)} var $StyleDict={__class__:$B.$type,__name__:'CSSProperty'} $StyleDict.__mro__=[$StyleDict,$ObjectDict] $StyleDict.__getattr__=function(self,attr){return $ObjectDict.__getattribute__(self.js,attr) } $StyleDict.__setattr__=function(self,attr,value){if(attr.toLowerCase()==='float'){self.js.cssFloat=value self.js.styleFloat=value }else{switch(attr){case 'top': case 'left': case 'height': case 'width': case 'borderWidth': if(isinstance(value,_b_.int))value=value+'px' } self.js[attr]=value }} function $Style(style){ return{__class__:$StyleDict,js:style}} $Style.__class__=$B.$factory $Style.$dict=$StyleDict $StyleDict.$factory=$Style var DOMNode=$B.DOMNode=function(elt){ var res={} res.$dict={} res.elt=elt if(elt['$brython_id']===undefined||elt.nodeType===9){ elt.$brython_id='DOM-'+$B.UUID() res.__repr__=res.__str__=res.toString=function(){var res="<DOMNode object type '" return res+$NodeTypes[elt.nodeType]+"' name '"+elt.nodeName+"'>" }} res.__class__=DOMNodeDict return res } DOMNodeDict={__class__ : $B.$type,__name__ : 'DOMNode' } DOMNode.__class__=$B.$factory DOMNode.$dict=DOMNodeDict DOMNodeDict.$factory=DOMNode DOMNodeDict.__mro__=[DOMNodeDict,_b_.object.$dict] DOMNodeDict.__add__=function(self,other){ var res=$TagSum() res.children=[self],pos=1 if(isinstance(other,$TagSum)){for(var $i=0;$i<other.children.length;$i++){res.children[pos++]=other.children[$i]}}else if(isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.list,_b_.dict,_b_.set,_b_.tuple])){res.children[pos++]=DOMNode(document.createTextNode(_b_.str(other))) }else{res.children[pos++]=other} return res } DOMNodeDict.__bool__=function(self){return true} DOMNodeDict.__class__=$B.$type DOMNodeDict.__contains__=function(self,key){try{self.__getitem__(key);return True} catch(err){return False}} DOMNodeDict.__del__=function(self){ if(!self.elt.parentNode){throw _b_.ValueError("can't delete "+str(elt)) } self.elt.parentNode.removeChild(self.elt) } DOMNodeDict.__delitem__=function(self,key){if(self.elt.nodeType===9){ var res=self.elt.getElementById(key) if(res){res.parentNode.removeChild(res)} else{throw KeyError(key)}}else{ self.elt.removeChild(self.elt.childNodes[key]) }} DOMNodeDict.__eq__=function(self,other){return self.elt==other.elt } DOMNodeDict.__getattribute__=function(self,attr){switch(attr){case 'class_name': case 'children': case 'html': case 'id': case 'left': case 'parent': case 'query': case 'text': case 'top': case 'value': case 'height': case 'width': return DOMNodeDict[attr](self) case 'clear': case 'remove': return function(){DOMNodeDict[attr](self,arguments[0])} case 'headers': if(self.elt.nodeType==9){ var req=new XMLHttpRequest() req.open('GET',document.location,false) req.send(null) var headers=req.getAllResponseHeaders() headers=headers.split('\r\n') var res=_b_.dict() for(var i=0;i<headers.length;i++){var header=headers[i] if(header.strip().length==0){continue} var pos=header.search(':') res.__setitem__(header.substr(0,pos),header.substr(pos+1).lstrip()) } return res } break case '$$location': attr='location' break } if(self.elt.getAttribute!==undefined){res=self.elt.getAttribute(attr) if(res!==undefined&&res!==null&&self.elt[attr]===undefined){ return res }} if(self.elt[attr]!==undefined){res=self.elt[attr] if(typeof res==="function"){var func=(function(f,elt){return function(){var args=[],pos=0 for(var i=0;i<arguments.length;i++){var arg=arguments[i] if(isinstance(arg,JSObject)){args[pos++]=arg.js }else if(isinstance(arg,DOMNodeDict)){args[pos++]=arg.elt }else if(arg===_b_.None){args[pos++]=null }else{args[pos++]=arg }} var result=f.apply(elt,args) return $B.$JS2Py(result) }})(res,self.elt) func.__name__=attr return func } if(attr=='options')return $Options(self.elt) if(attr=='style')return $Style(self.elt[attr]) return $B.$JS2Py(self.elt[attr]) } return $ObjectDict.__getattribute__(self,attr) } DOMNodeDict.__getitem__=function(self,key){if(self.elt.nodeType===9){ if(typeof key==="string"){var res=self.elt.getElementById(key) if(res)return DOMNode(res) throw KeyError(key) }else{try{var elts=self.elt.getElementsByTagName(key.$dict.__name__),res=[],pos=0 for(var $i=0;$i<elts.length;$i++)res[pos++]=DOMNode(elts[$i]) return res }catch(err){throw KeyError(str(key)) }}}else{throw _b_.TypeError('DOMNode object is not subscriptable') }} DOMNodeDict.__iter__=function(self){ self.$counter=-1 return self } DOMNodeDict.__le__=function(self,other){ var elt=self.elt if(self.elt.nodeType===9){elt=self.elt.body} if(isinstance(other,$TagSum)){var $i=0 for($i=0;$i<other.children.length;$i++){elt.appendChild(other.children[$i].elt) }}else if(typeof other==="string" ||typeof other==="number"){var $txt=document.createTextNode(other.toString()) elt.appendChild($txt) }else{ elt.appendChild(other.elt) }} DOMNodeDict.__len__=function(self){return self.elt.childNodes.length} DOMNodeDict.__mul__=function(self,other){if(isinstance(other,_b_.int)&& other.valueOf()>0){var res=$TagSum() var pos=res.children.length for(var i=0;i<other.valueOf();i++){res.children[pos++]=DOMNodeDict.clone(self)() } return res } throw _b_.ValueError("can't multiply "+self.__class__+"by "+other) } DOMNodeDict.__ne__=function(self,other){return !DOMNodeDict.__eq__(self,other)} DOMNodeDict.__next__=function(self){self.$counter++ if(self.$counter<self.elt.childNodes.length){return DOMNode(self.elt.childNodes[self.$counter]) } throw _b_.StopIteration('StopIteration') } DOMNodeDict.__radd__=function(self,other){ var res=$TagSum() var txt=DOMNode(document.createTextNode(other)) res.children=[txt,self] return res } DOMNodeDict.__str__=DOMNodeDict.__repr__=function(self){if(self===undefined)return "<class 'DOMNode'>" var res="<DOMNode object type '" return res+$NodeTypes[self.elt.nodeType]+"' name '"+self.elt.nodeName+"'>" } DOMNodeDict.__setattr__=function(self,attr,value){if(attr.substr(0,2)=='on'){ if(!_b_.bool(value)){ DOMNodeDict.unbind(self,attr.substr(2)) }else{ DOMNodeDict.bind(self,attr.substr(2),value) }}else{if(DOMNodeDict['set_'+attr]!==undefined){return DOMNodeDict['set_'+attr](self,value) } var attr1=attr.replace('_','-').toLowerCase() if(self.elt[attr1]!==undefined){self.elt[attr1]=value;return} var res=self.elt.getAttribute(attr1) if(res!==undefined&&res!==null){self.elt.setAttribute(attr1,value)} else{self.elt[attr]=value }}} DOMNodeDict.__setitem__=function(self,key,value){self.elt.childNodes[key]=value} DOMNodeDict.bind=function(self,event){ var _id if(self.elt.nodeType===9){_id=0} else{_id=self.elt.$brython_id} var _d=_b_.dict.$dict if(!_d.__contains__($B.events,_id)){_d.__setitem__($B.events,_id,dict()) } var item=_d.__getitem__($B.events,_id) if(!_d.__contains__(item,event)){_d.__setitem__(item,event,[]) } var evlist=_d.__getitem__(item,event) var pos=evlist.length for(var i=2;i<arguments.length;i++){var func=arguments[i] var callback=(function(f){return function(ev){try{return f($DOMEvent(ev)) }catch(err){getattr($B.stderr,"write")(err.__name__+': '+ err.$message+'\n'+_b_.getattr(err,"info")) }}} )(func) if(window.addEventListener){self.elt.addEventListener(event,callback,false) }else if(window.attachEvent){self.elt.attachEvent("on"+event,callback) } evlist[pos++]=[func,callback] }} DOMNodeDict.children=function(self){var res=[],pos=0 for(var i=0;i<self.elt.childNodes.length;i++){res[pos++]=DOMNode(self.elt.childNodes[i]) } return res } DOMNodeDict.clear=function(self){ var elt=self.elt if(elt.nodeType==9){elt=elt.body} for(var i=elt.childNodes.length-1;i>=0;i--){elt.removeChild(elt.childNodes[i]) }} DOMNodeDict.Class=function(self){if(self.elt.className !==undefined)return self.elt.className return None } DOMNodeDict.class_name=function(self){return DOMNodeDict.Class(self)} DOMNodeDict.clone=function(self){res=DOMNode(self.elt.cloneNode(true)) res.elt.$brython_id='DOM-' + $B.UUID() var _d=_b_.dict.$dict if(_d.__contains__($B.events,self.elt.$brython_id)){var events=_d.__getitem__($B.events,self.elt.$brython_id) var items=_b_.list(_d.items(events)) for(var i=0;i<items.length;i++){var event=items[i][0] for(var j=0;j<items[i][1].length;j++){DOMNodeDict.bind(res,event,items[i][1][j][0]) }}} return res } DOMNodeDict.focus=function(self){return(function(obj){return function(){ setTimeout(function(){obj.focus();},10) }})(self.elt) } DOMNodeDict.get=function(self){ var obj=self.elt var args=[],pos=0 for(var i=1;i<arguments.length;i++){args[pos++]=arguments[i]} var $ns=$B.$MakeArgs('get',args,[],[],null,'kw') var $dict={} var items=_b_.list(_b_.dict.$dict.items($ns['kw'])) for(var i=0;i<items.length;i++){$dict[items[i][0]]=items[i][1] } if($dict['name']!==undefined){if(obj.getElementsByName===undefined){throw _b_.TypeError("DOMNode object doesn't support selection by name") } var res=[],pos=0 var node_list=document.getElementsByName($dict['name']) if(node_list.length===0)return[] for(var i=0;i<node_list.length;i++)res[pos++]=DOMNode(node_list[i]) } if($dict['tag']!==undefined){if(obj.getElementsByTagName===undefined){throw _b_.TypeError("DOMNode object doesn't support selection by tag name") } var res=[],pos=0 var node_list=document.getElementsByTagName($dict['tag']) if(node_list.length===0)return[] for(var i=0;i<node_list.length;i++)res[pos++]=DOMNode(node_list[i]) } if($dict['classname']!==undefined){if(obj.getElementsByClassName===undefined){throw _b_.TypeError("DOMNode object doesn't support selection by class name") } var res=[],pos=0 var node_list=document.getElementsByClassName($dict['classname']) if(node_list.length===0)return[] for(var i=0;i<node_list.length;i++)res[pos++]=DOMNode(node_list[i]) } if($dict['id']!==undefined){if(obj.getElementById===undefined){throw _b_.TypeError("DOMNode object doesn't support selection by id") } var id_res=obj.getElementById($dict['id']) if(!id_res)return[] return[DOMNode(id_res)] } if($dict['selector']!==undefined){if(obj.querySelectorAll===undefined){throw _b_.TypeError("DOMNode object doesn't support selection by selector") } var node_list=obj.querySelectorAll($dict['selector']) var sel_res=[],pos=0 if(node_list.length===0)return[] for(var i=0;i<node_list.length;i++)sel_res[pos++]=DOMNode(node_list[i]) if(res===undefined)return sel_res var to_delete=[],pos=0 for(var i=0;i<res.length;i++){var elt=res[i] flag=false for(var j=0;j<sel_res.length;j++){if(elt.__eq__(sel_res[j])){flag=true;break}} if(!flag){to_delete[pos++]=i}} for(var i=to_delete.length-1;i>=0;i--)res.splice(to_delete[i],1) } return res } DOMNodeDict.getContext=function(self){ if(!('getContext' in self.elt)){throw _b_.AttributeError("object has no attribute 'getContext'") } var obj=self.elt return function(ctx){return JSObject(obj.getContext(ctx))}} DOMNodeDict.getSelectionRange=function(self){ if(self.elt['getSelectionRange']!==undefined){return self.elt.getSelectionRange.apply(null,arguments) }} DOMNodeDict.height=function(self){return _b_.int($getPosition(self.elt)["height"]) } DOMNodeDict.html=function(self){return self.elt.innerHTML} DOMNodeDict.left=function(self){return _b_.int($getPosition(self.elt)["left"]) } DOMNodeDict.id=function(self){if(self.elt.id !==undefined)return self.elt.id return None } DOMNodeDict.options=function(self){ return new $OptionsClass(self.elt) } DOMNodeDict.parent=function(self){if(self.elt.parentElement)return DOMNode(self.elt.parentElement) return None } DOMNodeDict.remove=function(self,child){ var elt=self.elt,flag=false,ch_elt=child.elt if(self.elt.nodeType==9){elt=self.elt.body} while(ch_elt.parentElement){if(ch_elt.parentElement===elt){elt.removeChild(ch_elt) flag=true break }else{ch_elt=ch_elt.parentElement}} if(!flag){throw _b_.ValueError('element '+child+' is not inside '+self)}} DOMNodeDict.top=function(self){return _b_.int($getPosition(self.elt)["top"]) } DOMNodeDict.reset=function(self){ return function(){self.elt.reset()}} DOMNodeDict.style=function(self){ self.elt.style.float=self.elt.style.cssFloat ||self.style.styleFloat return $B.JSObject(self.elt.style) } DOMNodeDict.setSelectionRange=function(self){ if(this['setSelectionRange']!==undefined){return(function(obj){return function(){return obj.setSelectionRange.apply(obj,arguments) }})(this) }else if(this['createTextRange']!==undefined){return(function(obj){return function(start_pos,end_pos){if(end_pos==undefined){end_pos=start_pos} var range=obj.createTextRange() range.collapse(true) range.moveEnd('character',start_pos) range.moveStart('character',end_pos) range.select() }})(this) }} DOMNodeDict.set_class_name=function(self,arg){self.elt.setAttribute('class',arg) } DOMNodeDict.set_html=function(self,value){self.elt.innerHTML=str(value) } DOMNodeDict.set_left=function(self,value){console.log('set left') self.elt.style.left=value } DOMNodeDict.set_style=function(self,style){ if(!_b_.isinstance(style,_b_.dict)){throw TypeError('style must be dict, not '+$B.get_class(style).__name__) } var items=_b_.list(_b_.dict.$dict.items(style)) for(var i=0;i<items.length;i++){var key=items[i][0],value=items[i][1] if(key.toLowerCase()==='float'){self.elt.style.cssFloat=value self.elt.style.styleFloat=value }else{switch(key){case 'top': case 'left': case 'width': case 'borderWidth': if(isinstance(value,_b_.int)){value=value+'px'}} self.elt.style[key]=value }}} DOMNodeDict.set_text=function(self,value){self.elt.innerText=str(value) self.elt.textContent=str(value) } DOMNodeDict.set_value=function(self,value){self.elt.value=str(value)} DOMNodeDict.submit=function(self){ return function(){self.elt.submit()}} DOMNodeDict.text=function(self){return self.elt.innerText ||self.elt.textContent} DOMNodeDict.toString=function(self){if(self===undefined)return 'DOMNode' return self.elt.nodeName } DOMNodeDict.trigger=function(self,etype){ if(self.elt.fireEvent){self.elt.fireEvent('on' + etype) }else{ var evObj=document.createEvent('Events') evObj.initEvent(etype,true,false) self.elt.dispatchEvent(evObj) }} DOMNodeDict.unbind=function(self,event){ var _id if(self.elt.nodeType==9){_id=0}else{_id=self.elt.$brython_id} if(!_b_.dict.$dict.__contains__($B.events,_id))return var item=_b_.dict.$dict.__getitem__($B.events,_id) if(!_b_.dict.$dict.__contains__(item,event))return var events=_b_.dict.$dict.__getitem__(item,event) if(arguments.length===2){for(var i=0;i<events.length;i++){var callback=events[i][1] if(window.removeEventListener){self.elt.removeEventListener(event,callback,false) }else if(window.detachEvent){self.elt.detachEvent(event,callback,false) }} events=[] return } for(var i=2;i<arguments.length;i++){var func=arguments[i],flag=false for(var j=0;j<events.length;j++){if(getattr(func,'__eq__')(events[j][0])){var callback=events[j][1] if(window.removeEventListener){self.elt.removeEventListener(event,callback,false) }else if(window.detachEvent){self.elt.detachEvent(event,callback,false) } events.splice(j,1) flag=true break }} if(!flag){throw KeyError('missing callback for event '+event)}}} DOMNodeDict.value=function(self){return self.elt.value} DOMNodeDict.width=function(self){return _b_.int($getPosition(self.elt)["width"]) } var $QueryDict={__class__:$B.$type,__name__:'query'} $QueryDict.__contains__=function(self,key){return self._keys.indexOf(key)>-1 } $QueryDict.__getitem__=function(self,key){ var result=self._values[key] if(result===undefined)throw KeyError(key) if(result.length==1)return result[0] return result } var $QueryDict_iterator=$B.$iterator_class('query string iterator') $QueryDict.__iter__=function(self){return $B.$iterator(self._keys,$QueryDict_iterator) } $QueryDict.__mro__=[$QueryDict,$ObjectDict] $QueryDict.getfirst=function(self,key,_default){ var result=self._values[key] if(result===undefined){if(_default===undefined)return None return _default } return result[0] } $QueryDict.getlist=function(self,key){ var result=self._values[key] if(result===undefined)return[] return result } $QueryDict.getvalue=function(self,key,_default){try{return self.__getitem__(key)} catch(err){$B.$pop_exc() if(_default===undefined)return None return _default }} $QueryDict.keys=function(self){return self._keys} DOMNodeDict.query=function(self){var res={__class__:$QueryDict,_keys :[],_values :{}} var qs=location.search.substr(1).split('&') for(var i=0;i<qs.length;i++){var pos=qs[i].search('=') var elts=[qs[i].substr(0,pos),qs[i].substr(pos+1)] var key=decodeURIComponent(elts[0]) var value=decodeURIComponent(elts[1]) if(res._keys.indexOf(key)>-1){res._values[key].push(value)} else{res._keys.push(key) res._values[key]=[value] }} return res } var $TagSumDict={__class__ : $B.$type,__name__:'TagSum'} $TagSumDict.appendChild=function(self,child){self.children.push(child) } $TagSumDict.__add__=function(self,other){if($B.get_class(other)===$TagSumDict){self.children=self.children.concat(other.children) }else if(isinstance(other,[_b_.str,_b_.int,_b_.float,_b_.dict,_b_.set,_b_.list])){self.children=self.children.concat(DOMNode(document.createTextNode(other))) }else{self.children.push(other)} return self } $TagSumDict.__mro__=[$TagSumDict,$ObjectDict] $TagSumDict.__radd__=function(self,other){var res=$TagSum() res.children=self.children.concat(DOMNode(document.createTextNode(other))) return res } $TagSumDict.__repr__=function(self){var res='<object TagSum> ' for(var i=0;i<self.children.length;i++){res+=self.children[i] if(self.children[i].toString()=='[object Text]'){res +=' ['+self.children[i].textContent+']\n'}} return res } $TagSumDict.__str__=$TagSumDict.toString=$TagSumDict.__repr__ $TagSumDict.clone=function(self){var res=$TagSum(),$i=0 for($i=0;$i<self.children.length;$i++){res.children.push(self.children[$i].cloneNode(true)) } return res } function $TagSum(){return{__class__:$TagSumDict,children:[],toString:function(){return '(TagSum)'}}} $TagSum.__class__=$B.$factory $TagSum.$dict=$TagSumDict $B.$TagSum=$TagSum var $WinDict={__class__:$B.$type,__name__:'window'} $WinDict.__getattribute__=function(self,attr){if(window[attr]!==undefined){return JSObject(window[attr])} throw _b_.AttributeError("'window' object has no attribute '"+attr+"'") } $WinDict.__setattr__=function(self,attr,value){ window[attr]=value } $WinDict.__mro__=[$WinDict,$ObjectDict] var win=JSObject(window) win.get_postMessage=function(msg,targetOrigin){if(isinstance(msg,dict)){var temp={__class__:'dict'} var items=_b_.list(_b_.dict.$dict.items(msg)) for(var i=0;i<items.length;i++)temp[items[i][0]]=items[i][1] msg=temp } return window.postMessage(msg,targetOrigin) } $B.DOMNodeDict=DOMNodeDict $B.win=win })(__BRYTHON__) ;(function($B){ var _b_=$B.builtins eval($B.InjectBuiltins()) $B.make_node=function(top_node,node){ var ctx_js=node.C.to_js() var is_cond=false,is_except=false,is_else=false if(node.locals_def){ var iter_name=top_node.iter_id ctx_js='var $locals_'+iter_name+' = $B.vars["'+iter_name+'"] || {}' ctx_js +=', $local_name = "'+iter_name ctx_js +='", $locals = $locals_'+iter_name+';' ctx_js +='$B.vars["'+iter_name+'"] = $locals;' } if(node.is_catch){is_except=true;is_cond=true} if(node.C.type=='node'){var ctx=node.C.tree[0] var ctype=ctx.type switch(ctx.type){case 'except': is_except=true is_cond=true break case 'single_kw': is_cond=true if(ctx.token=='else')is_else=true if(ctx.token=='finally')is_except=true break case 'condition': if(ctx.token=='elif'){is_else=true;is_cond=true} if(ctx.token=='if')is_cond=true } } if(ctx_js){ var new_node=new $B.genNode(ctx_js) if(ctype=='yield'){ var yield_node_id=top_node.yields.length while(ctx_js.charAt(ctx_js.length-1)==';'){ctx_js=ctx_js.substr(0,ctx_js.length-1) } var res='return ['+ctx_js+', '+yield_node_id+']' new_node.data=res top_node.yields.push(new_node) }else if(node.is_set_yield_value){ var js='$sent'+ctx_js+'=$B.modules["' js +=top_node.iter_id+'"].sent_value || None;' js +='if($sent'+ctx_js+'.__class__===$B.$GeneratorSendError)' js +='{throw $sent'+ctx_js+'.err};' js +='$yield_value'+ctx_js+'=$sent'+ctx_js+';' js +='$B.modules["'+top_node.iter_id+'"].sent_value=None' new_node.data=js }else if(ctype=='break'){ new_node.is_break=true new_node.loop_num=node.C.tree[0].loop_ctx.loop_num } new_node.is_cond=is_cond new_node.is_except=is_except new_node.is_if=ctype=='condition' && ctx.token=="if" new_node.is_try=node.is_try new_node.is_else=is_else new_node.loop_start=node.loop_start new_node.is_set_yield_value=node.is_set_yield_value for(var i=0,_len_i=node.children.length;i < _len_i;i++){new_node.addChild($B.make_node(top_node,node.children[i])) }} return new_node } $B.genNode=function(data,parent){_indent=4 this.data=data this.parent=parent this.children=[] this.has_child=false if(parent===undefined){this.nodes={} this.num=0 } this.addChild=function(child){if(child===undefined){console.log('child of '+this+' undefined')} this.children[this.children.length]=child this.has_child=true child.parent=this child.rank=this.children.length-1 } this.clone=function(){var res=new $B.genNode(this.data) res.has_child=this.has_child res.is_cond=this.is_cond res.is_except=this.is_except res.is_if=this.is_if res.is_try=this.is_try res.is_else=this.is_else res.loop_num=this.loop_num res.loop_start=this.loop_start return res } this.clone_tree=function(exit_node,head){ var res=new $B.genNode(this.data) if(this.replaced && !in_loop(this)){ res.data='void(0)' } if(this===exit_node &&(this.parent.is_cond ||!in_loop(this))){ if(!exit_node.replaced){ res=new $B.genNode('void(0)') }else{res=new $B.genNode(exit_node.data) } exit_node.replaced=true } if(head && this.is_break){res.data='$locals["$no_break'+this.loop_num+'"]=false;' res.data +='var err = new Error("break");' res.data +='err.__class__=$B.GeneratorBreak;throw err;' res.is_break=true } res.has_child=this.has_child res.is_cond=this.is_cond res.is_except=this.is_except res.is_try=this.is_try res.is_else=this.is_else res.loop_num=this.loop_num res.loop_start=this.loop_start res.no_break=true for(var i=0,_len_i=this.children.length;i < _len_i;i++){res.addChild(this.children[i].clone_tree(exit_node,head)) if(this.children[i].is_break){res.no_break=false}} return res } this.has_break=function(){if(this.is_break){return true} else{for(var i=0,_len_i=this.children.length;i < _len_i;i++){if(this.children[i].has_break()){return true}}} return false } this.indent_src=function(indent){return ' '.repeat(indent*indent) } this.src=function(indent){ indent=indent ||0 var res=[this.indent_src(indent)+this.data],pos=1 if(this.has_child)res[pos++]='{' res[pos++]='\n' for(var i=0,_len_i=this.children.length;i < _len_i;i++){res[pos++]=this.children[i].src(indent+1) } if(this.has_child)res[pos++]='\n'+this.indent_src(indent)+'}\n' return res.join('') } this.toString=function(){return '<Node '+this.data+'>'}} $B.GeneratorBreak={} $B.$GeneratorSendError={} var $GeneratorReturn={} $B.generator_return=function(){return{__class__:$GeneratorReturn}} function in_loop(node){ while(node){if(node.loop_start!==undefined)return node node=node.parent } return false } function in_try(node){ var tries=[],pnode=node.parent,pos=0 while(pnode){if(pnode.is_try){tries[pos++]=pnode} pnode=pnode.parent } return tries } var $BRGeneratorDict={__class__:$B.$type,__name__:'generator'} $BRGeneratorDict.__iter__=function(self){return self} $BRGeneratorDict.__enter__=function(self){console.log("generator.__enter__ called")} $BRGeneratorDict.__exit__=function(self){console.log("generator.__exit__ called")} function clear_ns(iter_id){delete $B.vars[iter_id] delete $B.modules[iter_id] delete $B.bound[iter_id] delete $B.generators[iter_id] delete $B.$generators[iter_id] } $BRGeneratorDict.__next__=function(self){ var scope_id=self.func_root.scope.id if(self._next===undefined){ var src=self.func_root.src()+'\n)()' try{eval(src)} catch(err){console.log("cant eval\n"+src+'\n'+err) clear_ns(self.iter_id) throw err } self._next=$B.$generators[self.iter_id] } if(self.gi_running){throw _b_.ValueError("ValueError: generator already executing") } self.gi_running=true for(var i=0;i<self.env.length;i++){eval('var $locals_'+self.env[i][0]+'=self.env[i][1]') } try{var res=self._next.apply(null,self.args) }catch(err){self._next=function(){var _err=StopIteration('after exception') _err.caught=true throw _err } clear_ns(self.iter_id) throw err }finally{self.gi_running=false $B.leave_frame() } if(res===undefined){throw StopIteration("")} if(res[0].__class__==$GeneratorReturn){ self._next=function(){throw StopIteration("after generator return")} clear_ns(self.iter_id) throw StopIteration('') } var yielded_value=res[0],yield_node_id=res[1] if(yield_node_id==self.yield_node_id){return yielded_value} self.yield_node_id=yield_node_id var exit_node=self.func_root.yields[yield_node_id] exit_node.replaced=false var root=new $B.genNode(self.def_ctx.to_js('__BRYTHON__.generators["'+self.iter_id+'"]')) root.addChild(self.func_root.children[0].clone()) var fnode=self.func_root.children[1].clone() root.addChild(fnode) func_node=self.func_root.children[1] var js='var $locals = $B.vars["'+self.iter_id+'"];' fnode.addChild(new $B.genNode(js)) while(1){ var exit_parent=exit_node.parent var rest=[],pos=0 var has_break=false var start=exit_node.rank+1 if(exit_node.loop_start){ start=exit_node.rank }else if(exit_node.is_cond){ while(start<exit_parent.children.length && (exit_parent.children[start].is_except || exit_parent.children[start].is_else)){start++}}else if(exit_node.is_try ||exit_node.is_except){ while(start<exit_parent.children.length && (exit_parent.children[start].is_except || exit_parent.children[start].is_else)){start++}} for(var i=start,_len_i=exit_parent.children.length;i < _len_i;i++){var clone=exit_parent.children[i].clone_tree(null,true) rest[pos++]=clone if(clone.has_break()){has_break=true}} if(has_break){ var rest_try=new $B.genNode('try') for(var i=0,_len_i=rest.length;i < _len_i;i++){rest_try.addChild(rest[i])} var catch_test='catch(err)' catch_test +='{if(err.__class__!==$B.GeneratorBreak)' catch_test +='{throw err}}' catch_test=new $B.genNode(catch_test) rest=[rest_try,catch_test] } var tries=in_try(exit_node) if(tries.length==0){ for(var i=0;i<rest.length;i++){fnode.addChild(rest[i])}}else{ var tree=[],pos=0 for(var i=0;i<tries.length;i++){var try_node=tries[i],try_clone=try_node.clone() if(i==0){for(var j=0;j<rest.length;j++){try_clone.addChild(rest[j])}} var children=[try_clone],cpos=1 for(var j=try_node.rank+1;j<try_node.parent.children.length;j++){if(try_node.parent.children[j].is_except){children[cpos++]=try_node.parent.children[j].clone_tree(null,true) }else{break }} tree[pos++]=children } var parent=fnode while(tree.length){children=tree.pop() for(var i=0;i<children.length;i++){parent.addChild(children[i])} parent=children[0] }} exit_node=exit_parent if(exit_node===self.func_root){break}} self.next_root=root var next_src=root.src()+'\n)()' try{eval(next_src)} catch(err){console.log('error '+err+'\n'+next_src);throw err} self._next=$B.generators[self.iter_id] return yielded_value } $BRGeneratorDict.__mro__=[$BRGeneratorDict,_b_.object.$dict] $BRGeneratorDict.$factory={__class__:$B.$factory,$dict: $BRGeneratorDict} $BRGeneratorDict.__repr__=$BRGeneratorDict.__str__=function(self){return '<generator '+self.func_name+' '+self.iter_id+'>' } $BRGeneratorDict.close=function(self,value){self.sent_value=_b_.GeneratorExit() try{var res=$BRGeneratorDict.__next__(self) if(res!==_b_.None){throw _b_.RuntimeError("closed generator returned a value") }}catch(err){if($B.is_exc(err,[_b_.StopIteration,_b_.GeneratorExit])){$B.$pop_exc();return _b_.None } throw err }} $BRGeneratorDict.send=function(self,value){self.sent_value=value return $BRGeneratorDict.__next__(self) } $BRGeneratorDict.$$throw=function(self,value){if(_b_.isinstance(value,_b_.type))value=value() self.sent_value={__class__:$B.$GeneratorSendError,err:value} return $BRGeneratorDict.__next__(self) } $B.$BRgenerator=function(env,func_name,def_id){ var def_node=$B.modules[def_id] var def_ctx=def_node.C.tree[0] var counter=0 var func=env[0][1][func_name] $B.generators=$B.generators ||{} $B.$generators=$B.$generators ||{} var module=def_node.module var res=function(){var args=[],pos=0 for(var i=0,_len_i=arguments.length;i<_len_i;i++){args[pos++]=arguments[i]} var iter_id=def_id+'_'+counter++ $B.bound[iter_id]={} for(var attr in $B.bound[def_id]){$B.bound[iter_id][attr]=true} var func_root=new $B.genNode(def_ctx.to_js('$B.$generators["'+iter_id+'"]')) func_root.scope=env[0][1] func_root.module=module func_root.yields=[] func_root.loop_ends={} func_root.def_id=def_id func_root.iter_id=iter_id for(var i=0,_len_i=def_node.children.length;i < _len_i;i++){func_root.addChild($B.make_node(func_root,def_node.children[i])) } var func_node=func_root.children[1].children[0] var obj={__class__ : $BRGeneratorDict,args:args,def_id:def_id,def_ctx:def_ctx,def_node:def_node,env:env,func:func,func_name:func_name,func_root:func_root,module:module,func_node:func_node,next_root:func_root,gi_running:false,iter_id:iter_id,id:iter_id,num:0 } $B.modules[iter_id]=obj obj.parent_block=def_node.parent_block return obj } res.__call__=function(){console.log('call generator');return res.apply(null,arguments)} res.__repr__=function(){return "<function "+func.__name__+">"} return res } $B.$BRgenerator.__repr__=function(){return "<class 'generator'>"} $B.$BRgenerator.__str__=function(){return "<class 'generator'>"} $B.$BRgenerator.__class__=$B.$type })(__BRYTHON__) ;(function($B){var _b_=$B.builtins function import_hooks(mod_name,origin,package){var module={name:mod_name,__class__:$B.$ModuleDict} $B.$import('sys','__main__') var $globals=$B.vars['__main__'] var sys=$globals['sys'] var _meta_path=_b_.getattr(sys,'meta_path') var _path=_b_.getattr(sys,'path') for(var i=0,_len_i=_meta_path.length;i < _len_i;i++){var _mp=_meta_path[i] for(var j=0,_len_j=_path.length;j < _len_j;j++){try{ var _finder=_b_.getattr(_mp,'__call__')(mod_name,_path[j]) var _loader=_b_.getattr(_b_.getattr(_finder,'find_module'),'__call__')() }catch(e){if(e.__name__=='ImportError'){ continue }else{ throw e }} if(_loader==_b_.None)continue return _b_.getattr(_b_.getattr(_loader,'load_module'),'__call__')(mod_name) } } return null } window.import_hooks=import_hooks })(__BRYTHON__) ;(function($B){var modules={} modules['browser']={$package: true,$is_package: true,__package__:'browser',__file__:$B.brython_path+'/Lib/browser/__init__.py',alert:function(message){window.alert($B.builtins.str(message))},confirm: $B.JSObject(window.confirm),console:$B.JSObject(window.console),document:$B.DOMNode(document),doc: $B.DOMNode(document), DOMEvent:$B.DOMEvent,DOMNode:$B.DOMNode,mouseCoords: function(ev){return $B.JSObject($mouseCoords(ev))},prompt: function(message,default_value){return $B.JSObject(window.prompt(message,default_value||'')) },win: $B.win,window: $B.win,URLParameter:function(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]") var regex=new RegExp("[\\?&]" + name + "=([^&#]*)"),results=regex.exec(location.search) results=results===null ? "" : decodeURIComponent(results[1].replace(/\+/g," ")) return $B.builtins.str(results) }} modules['browser.html']=(function($B){var _b_=$B.builtins var $TagSumDict=$B.$TagSum.$dict function makeTagDict(tagName){ var dict={__class__:$B.$type,__name__:tagName } dict.__init__=function(){var $ns=$B.$MakeArgs('pow',arguments,['self'],[],'args','kw') var self=$ns['self'] var args=$ns['args'] if(args.length==1){var first=args[0] if(_b_.isinstance(first,[_b_.str,_b_.int,_b_.float])){self.elt.appendChild(document.createTextNode(_b_.str(first))) }else if(first.__class__===$TagSumDict){for(var i=0,_len_i=first.children.length;i < _len_i;i++){self.elt.appendChild(first.children[i].elt) }}else{ try{self.elt.appendChild(first.elt)} catch(err){throw _b_.ValueError('wrong element '+first)}}} var items=_b_.list(_b_.dict.$dict.items($ns['kw'])) for(var i=0,_len_i=items.length;i < _len_i;i++){ var arg=items[i][0] var value=items[i][1] if(arg.toLowerCase().substr(0,2)==="on"){ var js='$B.DOMNodeDict.bind(self,"' js +=arg.toLowerCase().substr(2) eval(js+'",function(){'+value+'})') }else if(arg.toLowerCase()=="style"){$B.DOMNodeDict.set_style(self,value) }else{ if(value!==false){ try{arg=arg.toLowerCase().replace('_','-') self.elt.setAttribute(arg,value) }catch(err){throw _b_.ValueError("can't set attribute "+arg) }}}}} dict.__mro__=[dict,$B.DOMNodeDict,$B.builtins.object.$dict] dict.__new__=function(cls){ var res=$B.DOMNode(document.createElement(tagName)) res.__class__=cls.$dict return res } return dict } function makeFactory(tagName){var factory=function(){var res=$B.DOMNode(document.createElement(tagName)) res.__class__=dicts[tagName] var args=[res].concat(Array.prototype.slice.call(arguments)) dicts[tagName].__init__.apply(null,args) return res } factory.__class__=$B.$factory factory.$dict=dicts[tagName] return factory } var $tags=['A','ABBR','ACRONYM','ADDRESS','APPLET','AREA','B','BASE','BASEFONT','BDO','BIG','BLOCKQUOTE','BODY','BR','BUTTON','CAPTION','CENTER','CITE','CODE','COL','COLGROUP','DD','DEL','DFN','DIR','DIV','DL','DT','EM','FIELDSET','FONT','FORM','FRAME','FRAMESET','H1','H2','H3','H4','H5','H6','HEAD','HR','HTML','I','IFRAME','IMG','INPUT','INS','ISINDEX','KBD','LABEL','LEGEND','LI','LINK','MAP','MENU','META','NOFRAMES','NOSCRIPT','OBJECT','OL','OPTGROUP','OPTION','P','PARAM','PRE','Q','S','SAMP','SCRIPT','SELECT','SMALL','SPAN','STRIKE','STRONG','STYLE','SUB','SUP','TABLE','TBODY','TD','TEXTAREA','TFOOT','TH','THEAD','TITLE','TR','TT','U','UL','VAR', 'ARTICLE','ASIDE','AUDIO','BDI','CANVAS','COMMAND','DATA','DATALIST','EMBED','FIGCAPTION','FIGURE','FOOTER','HEADER','KEYGEN','MAIN','MARK','MATH','METER','NAV','OUTPUT','PROGRESS','RB','RP','RT','RTC','RUBY','SECTION','SOURCE','TEMPLATE','TIME','TRACK','VIDEO','WBR', 'DETAILS','DIALOG','MENUITEM','PICTURE','SUMMARY'] var obj=new Object() var dicts={} for(var i=0,_len_i=$tags.length;i < _len_i;i++){var tag=$tags[i] dicts[tag]=makeTagDict(tag) obj[tag]=makeFactory(tag) dicts[tag].$factory=obj[tag] } $B.tag_classes=dicts return obj })(__BRYTHON__) modules['javascript']={__file__:$B.brython_path+'/libs/javascript.js',JSObject: $B.JSObject,JSConstructor: $B.JSConstructor,console: $B.JSObject(window.console),load:function(script_url,names){ var file_obj=$B.builtins.open(script_url) var content=$B.builtins.getattr(file_obj,'read')() eval(content) if(names!==undefined){if(!Array.isArray(names)){throw $B.builtins.TypeError("argument 'names' should be a list, not '"+$B.get_class(names).__name__) }else{for(var i=0;i<names.length;i++){try{window[names[i]]=eval(names[i])} catch(err){throw $B.builtins.NameError("name '"+names[i]+"' not found in script "+script_url)}}}}},py2js: function(src){return $B.py2js(src).to_js()},pyobj2jsobj:function(obj){return $B.pyobj2jsobj(obj)},jsobj2pyobj:function(obj){return $B.jsobj2pyobj(obj)}} function load(name,module_obj){ module_obj.__class__=$B.$ModuleDict module_obj.__name__=name module_obj.__repr__=module_obj.__str__=function(){return "<module '"+name+"' (built-in)>" } $B.imported[name]=$B.modules[name]=module_obj } for(var attr in modules){load(attr,modules[attr])}})(__BRYTHON__) ;(function($B){_b_=$B.builtins $B.execution_object={} $B.execution_object.queue=[] $B.execution_object.start_flag=true $B.execution_object.$execute_next_segment=function(){if($B.execution_object.queue.length==0){return } $B.execution_object.start_flag=false var element=$B.execution_object.queue.shift() var code=element[0] var delay=10 if(element.length==2)delay=element[1] setTimeout(function(){ console.log(code) try{eval(code)}catch(e){console.log(e)} $B.execution_object.start_flag=$B.execution_object.queue.length==0 },delay) } $B.execution_object.$append=function(code,delay){$B.execution_object.queue.push([code,delay]) if($B.execution_object.start_flag)$B.execution_object.$execute_next_segment() } $B.execution_object.source_conversion=function(js){js=js.replace("\n","",'g') js=js.replace("'","\\'",'g') js=js.replace('"','\\"','g') js=js.replace("@@","\'",'g') js+="';$B.execution_object.$append($jscode, 10); " js+="$B.execution_object.$execute_next_segment(); " return "var $jscode='" + js } _b_['brython_block']=function(f,sec){if(sec===undefined ||sec==_b_.None)sec=1 return f } $B.builtin_funcs['brython_block']=true $B.bound['__builtins__']['brython_block']=true _b_['brython_async']=function(f){return f} $B.builtin_funcs['brython_async']=true $B.bound['__builtins__']['brython_async']=true })(__BRYTHON__)
34.224485
3,807
0.718846
d5b990e3ce3518c0f19c876431788002397d4ef7
661
js
JavaScript
src/components/Header/styles.js
hyerdev/csgo-hyer
f866d7a8befe15d11afd76fc84a921df680ce53f
[ "MIT" ]
null
null
null
src/components/Header/styles.js
hyerdev/csgo-hyer
f866d7a8befe15d11afd76fc84a921df680ce53f
[ "MIT" ]
2
2020-04-08T00:03:20.000Z
2021-03-10T13:50:03.000Z
src/components/Header/styles.js
hyerdev/csgo-hyer
f866d7a8befe15d11afd76fc84a921df680ce53f
[ "MIT" ]
null
null
null
import styled from 'styled-components'; export const Container = styled.header` width: 100%; margin: 0 auto; `; export const Wrapper = styled.div` width: 100%; max-width: 1200px; margin: 0 auto; z-index: 1; position: fixed; left: 0; right: 0; padding: 20px 0px; display: flex; justify-content: space-between; align-items: center; img { width: 100%; max-width: 100px; } ul { display: flex; list-style: none; text-transform: uppercase; font-weight: bold; li { &:hover { color: #c83232; cursor: pointer; } & + li { margin-left: 20px; } } } `;
14.688889
39
0.565809
d5b9bff3a27cd9a1c65717377349b38a2eca0c21
234
js
JavaScript
web/components/screens/onboarding/HowToPlay/index.fixture.js
EdwinMontero88/Flatris-LAB
01f0f5940e65d288f8bc28f61b93c371c3d91a21
[ "MIT" ]
14
2020-04-09T17:35:20.000Z
2021-02-01T13:32:51.000Z
web/components/screens/onboarding/HowToPlay/index.fixture.js
EdwinMontero88/Flatris-LAB
01f0f5940e65d288f8bc28f61b93c371c3d91a21
[ "MIT" ]
12
2019-11-04T08:48:44.000Z
2022-02-18T14:11:10.000Z
web/components/screens/onboarding/HowToPlay/index.fixture.js
EdwinMontero88/Flatris-LAB
01f0f5940e65d288f8bc28f61b93c371c3d91a21
[ "MIT" ]
1,657
2020-07-17T12:41:30.000Z
2022-03-31T17:40:17.000Z
// @flow import React from 'react'; import HowToPlay from '.'; export default { enabled: <HowToPlay disabled={false} onNext={() => console.log('Next')} />, disabled: <HowToPlay disabled onNext={() => console.log('Next')} /> };
21.272727
77
0.641026
d5b9eeb4cefdc9f5bbf98b62c8b5ddfe505aef7f
977
js
JavaScript
js/geolocation.js
ktavo/HTML5_CSS3_Javascript
8fabc53fec5519867598faf36327386d373fe1a4
[ "MIT" ]
null
null
null
js/geolocation.js
ktavo/HTML5_CSS3_Javascript
8fabc53fec5519867598faf36327386d373fe1a4
[ "MIT" ]
null
null
null
js/geolocation.js
ktavo/HTML5_CSS3_Javascript
8fabc53fec5519867598faf36327386d373fe1a4
[ "MIT" ]
null
null
null
console.log('Hi from geolocation.js'); function iniciar(){ var boton = document.getElementById('obtener'); boton.addEventListener('click', obtener, false); } function obtener(){ var geoConfig = { enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 }; navigator.geolocation.getCurrentPosition(mostrar, errores, geoConfig); //watchPosition se usa para evaluar cambios en la ubicación, sirve en dispositívos móviles //var controlUbicacion = navigator.geolocation.watchPosition(mostrar, errores, geoConfig); } function mostrar(posicion){ var ubicacion = document.getElementById('ubicacion'); var datos = ''; datos += 'Latitud: ' + posicion.coords.latitude + '<br>'; datos += 'Longitud: ' + posicion.coords.longitude + '<br>'; datos += 'Exactitud: ' + posicion.coords.accuracy + 'm.<br>'; ubicacion.innerHTML = datos; } function errores(error){ alert('Error: ' + error.code + ' ' + error.message); } window.addEventListener('load', iniciar, false);
29.606061
91
0.721597
d5bbdc4555a68aae9638f0bb9fc37829842a5622
109
js
JavaScript
src/config/constants.js
mrnav90/vue-boilerplate
6825ce7ab8f843831ee41c80bf6b17b2d6b4375f
[ "MIT" ]
null
null
null
src/config/constants.js
mrnav90/vue-boilerplate
6825ce7ab8f843831ee41c80bf6b17b2d6b4375f
[ "MIT" ]
null
null
null
src/config/constants.js
mrnav90/vue-boilerplate
6825ce7ab8f843831ee41c80bf6b17b2d6b4375f
[ "MIT" ]
null
null
null
export const GOOGLE_WEB_FONT_STATUS = { inactive: 'inactive', active: 'active', loading: 'loading', };
18.166667
39
0.688073
d5bbee1c6325c2c29c2e4333746f61d3db67ca73
3,148
js
JavaScript
src/index.js
EvgeniiShumeiko/megahack2018_frontend
a0b106e04c62a2090de4001d58def380cc48a9af
[ "MIT" ]
null
null
null
src/index.js
EvgeniiShumeiko/megahack2018_frontend
a0b106e04c62a2090de4001d58def380cc48a9af
[ "MIT" ]
null
null
null
src/index.js
EvgeniiShumeiko/megahack2018_frontend
a0b106e04c62a2090de4001d58def380cc48a9af
[ "MIT" ]
null
null
null
// @flow import socketIOClient from "socket.io-client"; import { default as App } from "@app"; import axios from "axios"; import environment from "@core/environment.json"; import { default as Chat } from "./modules/chat"; import { default as Login } from "./modules/login"; import { default as Mentor } from "./modules/Mentor"; const url = environment.API.HOST; const soketUrl = environment.API.SOCKET; axios .get(`${url}/account/role`, { headers: { authorization: localStorage.getItem("secretKey") } }) .then(res => { console.log(res); console.log(url); axios .get(`${url}/account/info`, { headers: { authorization: localStorage.getItem("secretKey") } }) .then(data => { if (window.location.pathname.indexOf("chat") === -1) { if (res.data === "developer") // App({ name: "Example Name ", email: "username@example.com" }); else if (res.data === "reporter") Mentor({ name: "Example Name ", email: "username@example.com" }); else if (res.data === "reporter") Login({ name: "Name ", email: "username@example.com" }); } else Chat(data); window.socket = socketIOClient(soketUrl); window.socket.on("connect", () => { window.socket.emit( "authorize", JSON.stringify({ login: data.data.login, session: localStorage.getItem("secretKey") }) ); console.info( "[Socket] Connected", JSON.stringify({ login: data.data.login, session: localStorage.getItem("secretKey") }) ); }); window.socket.on("up", ddd => { const d = JSON.parse(ddd); console.log(ddd); if (window.location.pathname.indexOf("chat") === -1 && window.location.pathname.indexOf(d.user.login) === -1) { if (window.confirm(`${d.user.name} ${d.user.surname} (${d.user.login}) хочет связаться с вами, принять?`)) { window.location.href = `https://nammm.ru/chat/?room=${d.room}`; } } }); function SendPush(user, login, room) { console.log("send push:", user, login, room); window.socket.emit( "up", JSON.stringify({ user, login, room }) ); } window.SendPush = SendPush; }) .catch(() => {}); }) .catch(() => { console.log("login"); Login({ name: "Name ", email: "username@example.com" }); });
40.358974
132
0.435197
d5bc52589f4aaf265c6121eaf3342a44ec31a529
2,491
js
JavaScript
index.js
jonschlinkert/parser-csv
d01b0306d56266fcc077e70638f48e44f05e527a
[ "MIT" ]
3
2016-09-24T06:53:18.000Z
2021-05-15T15:47:33.000Z
index.js
jonschlinkert/parser-csv
d01b0306d56266fcc077e70638f48e44f05e527a
[ "MIT" ]
null
null
null
index.js
jonschlinkert/parser-csv
d01b0306d56266fcc077e70638f48e44f05e527a
[ "MIT" ]
null
null
null
'use strict'; /** * Module dependencies. */ var fs = require('fs'); var extend = require('extend-shallow'); /** * Requires cache */ var requires = {}; /** * Expose `parser` */ var parser = module.exports; /** * Parse the given `str` of CSV and callback `cb(err, json)`. * * @name .parse * @param {String|Object} `str` The object or string to parse. * @param {Object|Function} `options` or `cb` callback function. * @param {Function} `cb` callback function. * @api public */ parser.parse = function(str, options, cb) { var csv = requires.csv || (requires.csv = require('parse-csv')); if (typeof options === 'function') { cb = options; options = {}; } var opts = extend({headers: {included: true}}, options); try { opts.jsonType = opts.jsonType || 'jsonDict'; cb(null, JSON.parse(csv.to(opts.csv, stripBOM(str), opts))); } catch (err) { cb(err); return; } }; /** * Parse the given `str` of CSV and return an object. * * @param {String|Object} `str` The object or string to parse. * @return {Object} * @api public */ parser.parseSync = function(str, options) { var csv = requires.csv || (requires.csv = require('parse-csv')); var opts = extend({headers: {included: true}}, options); try { opts.jsonType = opts.jsonType || 'jsonDict'; return JSON.parse(csv.to(opts.csv, stripBOM(str), opts)); } catch (err) { return err; } }; /** * CSV file support. Parse the given `str` of CSV and callback `cb(err, data)`. * * @param {String|Object} `str` The object or string to parse. * @return {Object} * @api public */ parser.parseFile = function(fp, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } var opts = extend({}, options); try { fs.readFile(fp, 'utf8', function(err, str) { parser.parse(str, opts, cb); }); } catch (err) { cb(err); return; } }; /** * CSV file support. Parse a file at the given `fp`. * * ```js * parser.parseFile('foo/bar/baz.csv'); * ``` * * @param {String} `fp` * @param {Object} `options` Options to pass to [parse-csv] * @api public */ parser.parseFileSync = function(fp, options) { try { var str = fs.readFileSync(fp, 'utf8'); return parser.parseSync(str, options); } catch (err) { return err; } }; /** * Strip byte-order marks * * @api private */ function stripBOM(str) { if (str[0] === '\uFEFF') { return str.substring(1); } else { return str; } }
19.769841
79
0.596146
d5bc6b16a3c0453bfe89db6ee6c73b917538484c
271
js
JavaScript
client/components/basic/avatar/UserAvatar.js
eugeniumegherea/Rocket.Chat
2c41b942843733938d37bb52aa1af676a0bf4c38
[ "MIT" ]
2
2020-06-01T13:54:03.000Z
2020-09-09T12:00:40.000Z
client/components/basic/avatar/UserAvatar.js
eugeniumegherea/Rocket.Chat
2c41b942843733938d37bb52aa1af676a0bf4c38
[ "MIT" ]
5
2018-07-19T21:36:12.000Z
2019-12-03T13:29:29.000Z
client/components/basic/avatar/UserAvatar.js
eugeniumegherea/Rocket.Chat
2c41b942843733938d37bb52aa1af676a0bf4c38
[ "MIT" ]
1
2021-02-03T02:09:58.000Z
2021-02-03T02:09:58.000Z
import React from 'react'; import { Avatar } from '@rocket.chat/fuselage'; function UserAvatar({ url, username, ...props }) { const avatarUrl = url || `/avatar/${ username }`; return <Avatar url={avatarUrl} title={username} {...props}/>; } export default UserAvatar;
27.1
62
0.678967
d5be1981da254a9d17e3bfc533ef559b356180d6
289
js
JavaScript
Array/Manipulation/sparseArray.js
vipuljain08/data-structure-algorithms
7de444883a9fcb5959b0829309ab5de278abe0e0
[ "MIT" ]
null
null
null
Array/Manipulation/sparseArray.js
vipuljain08/data-structure-algorithms
7de444883a9fcb5959b0829309ab5de278abe0e0
[ "MIT" ]
null
null
null
Array/Manipulation/sparseArray.js
vipuljain08/data-structure-algorithms
7de444883a9fcb5959b0829309ab5de278abe0e0
[ "MIT" ]
1
2020-10-08T15:27:45.000Z
2020-10-08T15:27:45.000Z
const sparseArray = (strings, queries) => { let finalArray = [] for(let i=0; i<queries.length; i++) { finalArray.push(strings.filter(st => st==queries[i]).length) } return finalArray } console.log(sparseArray(['ab', 'ab', 'abc'], ['ab', 'abc', 'bc'])) // [2, 1, 0]
32.111111
79
0.570934
d5bf14a026080a2b451e190a0f98a137a48e3862
1,068
js
JavaScript
src/redux/articleReducer.js
young0810/yyblog
753196f2e39b4228c4afbd1d4b00ff76effd6ad2
[ "MIT" ]
null
null
null
src/redux/articleReducer.js
young0810/yyblog
753196f2e39b4228c4afbd1d4b00ff76effd6ad2
[ "MIT" ]
null
null
null
src/redux/articleReducer.js
young0810/yyblog
753196f2e39b4228c4afbd1d4b00ff76effd6ad2
[ "MIT" ]
null
null
null
import axios from "axios"; const GET_ARTICLE_LIST = "get_artical_list"; const GET_ARTICLE = "get_article"; const initialState = { articles: [], article: {} }; export function articleReducer(state = initialState, action) { switch (action.type) { case GET_ARTICLE_LIST: return { ...state, articles: action.payload }; case GET_ARTICLE: return { ...state, article: action.payload }; default: return state; } } function getArticleList(articles) { return { type: GET_ARTICLE_LIST, payload: articles }; } function getArticle(article) { return { type: GET_ARTICLE, payload: article }; } export function fetchArticleList() { return dispatch => { return axios.get("/api/article").then(res => { if (res.status === 200) { dispatch(getArticleList(res.data)); } }); }; } export function fetchArticle(id) { return dispatch => { return axios.get("/api/article/" + id).then(res => { if (res.status === 200) { dispatch(getArticle(res.data)); } }); }; }
19.418182
62
0.61985
d5c0cff68bbeacc165b02fb3f8b71418bbcd7a91
320
js
JavaScript
src/utils/parseToken/index.js
mattcarlotta/SJSITAPP-SSR
194f03988a7dc1a5e1df534500f397ac0001179a
[ "MIT" ]
1
2021-03-31T06:42:59.000Z
2021-03-31T06:42:59.000Z
src/utils/parseToken/index.js
mattcarlotta/SJSITAPP-SSR
194f03988a7dc1a5e1df534500f397ac0001179a
[ "MIT" ]
2
2020-03-26T20:21:32.000Z
2020-03-26T20:21:39.000Z
src/utils/parseToken/index.js
mattcarlotta/SJSITAPP-SSR
194f03988a7dc1a5e1df534500f397ac0001179a
[ "MIT" ]
2
2020-05-08T04:31:08.000Z
2020-10-05T12:09:18.000Z
import qs from "qs"; /** * Helper function to parse a token from a search string. * * @function * @param {string} search - a URL string. * @returns {string} - a parsed token string from search. */ export default search => { const { token } = qs.parse(search, { ignoreQueryPrefix: true, }); return token; };
18.823529
57
0.65
d5c106d387f8961ba1c5effa2ac3bfdfbf3ece63
842
js
JavaScript
src/signUp/components/ModalContent/SignUpForm/BirthdayField.js
DoorTwoDoor/web
126e032170fe337b017c8594cf1a400a1204dc8f
[ "Apache-2.0" ]
null
null
null
src/signUp/components/ModalContent/SignUpForm/BirthdayField.js
DoorTwoDoor/web
126e032170fe337b017c8594cf1a400a1204dc8f
[ "Apache-2.0" ]
null
null
null
src/signUp/components/ModalContent/SignUpForm/BirthdayField.js
DoorTwoDoor/web
126e032170fe337b017c8594cf1a400a1204dc8f
[ "Apache-2.0" ]
null
null
null
import React, { Component } from 'react'; import { Form } from 'semantic-ui-react'; import { getDayOptions, getMonthOptions, getYearOptions, } from '../../../utilities/Helper'; class BirthdayField extends Component { render() { const dayOptions = getDayOptions(2017, 2); const monthOptions = getMonthOptions(); const yearOptions = getYearOptions(); return ( <Form.Group widths={'equal'}> <Form.Select name={'month'} placeholder={'Month'} options={monthOptions} /> <Form.Select name={'day'} placeholder={'Day'} options={dayOptions} /> <Form.Select name={'year'} placeholder={'Year'} options={yearOptions} /> </Form.Group> ); } } export default BirthdayField;
21.589744
46
0.562945
d5c122a99b8a1283f7d7940c562994e5b030d77e
1,545
js
JavaScript
src/components/footer/footer.js
williamkwao/yap
0b4254fba260692e27482a6bd8d904223d1442cd
[ "MIT" ]
null
null
null
src/components/footer/footer.js
williamkwao/yap
0b4254fba260692e27482a6bd8d904223d1442cd
[ "MIT" ]
null
null
null
src/components/footer/footer.js
williamkwao/yap
0b4254fba260692e27482a6bd8d904223d1442cd
[ "MIT" ]
null
null
null
import React from 'react' import styled from 'styled-components' import { library } from '@fortawesome/fontawesome-svg-core' import { faEnvelope } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { SocialMediaIcons } from '../' const YapFooter = styled.footer` background-color: #fcbc19; margin-bottom: 0px; padding: 20px 15px; text-align: center; section { margin: 12px 0px; } a { color: #fff; text-decoration: none; } p { color: #fff; font-weight: bold; margin-bottom: 0px; } .fa-envelope { color: #fff; } .social-icons { .logo-div { svg { path { fill: #fff !important; } width: 26px !important; :hover path { fill: #fff !important; } } } } @media (min-width: 992px) { padding: 20px 35px; display: grid; grid-template-columns: repeat(3, 1fr); section { margin: 1px 0px; } } ` const Footer = () => { library.add(faEnvelope) return ( <YapFooter> <section className="contact"> <a href="mailto:info@yapdc.org"> <p> <FontAwesomeIcon icon="envelope" /> info@yapdc.org </p> </a> </section> <section> <SocialMediaIcons /> </section> <section className="copyright"> <p> {new Date().getFullYear()} {String.fromCharCode(169)} YAP DC </p> </section> </YapFooter> ) } export default Footer
20.328947
70
0.564401
d5c2e2bf4200560efe14600a6c1f2c6f85ee4356
752
js
JavaScript
lib/gateways/models/createModelFromSnapshot.js
LBHackney-IT/housing-needs-vulnerabilities
91548c066b6f9d805587542c26cf29223ab6d6d5
[ "MIT" ]
null
null
null
lib/gateways/models/createModelFromSnapshot.js
LBHackney-IT/housing-needs-vulnerabilities
91548c066b6f9d805587542c26cf29223ab6d6d5
[ "MIT" ]
3
2020-06-22T10:50:58.000Z
2020-08-12T08:06:49.000Z
lib/gateways/models/createModelFromSnapshot.js
LBHackney-IT/housing-needs-vulnerabilities
91548c066b6f9d805587542c26cf29223ab6d6d5
[ "MIT" ]
null
null
null
import { Snapshot } from 'lib/domain'; import { normalise } from 'lib/utils/normalise'; function nullifyEmptyStrings(object) { if (!object) { return object; } Object.keys(object).forEach(key => { if (typeof object[key] === 'object') { object[key] = nullifyEmptyStrings(object[key]); } else if (object[key] === '') { object[key] = null; } }); return object; } export function createSnapshotModel(snapshot) { if (!(snapshot instanceof Snapshot)) { throw new TypeError( `expected type Snapshot, but got ${snapshot?.constructor.name}` ); } return nullifyEmptyStrings({ ...snapshot, queryFirstName: normalise(snapshot.firstName), queryLastName: normalise(snapshot.lastName) }); }
22.787879
69
0.648936
d5c34341602db1d767c78bf91349d0ee81ca1747
275
js
JavaScript
node_modules/@tensorflow/tfjs-core/dist-es6/version_test.js
syiin/nnLibconv
416993e9a7b165e419a3ee980dc973e911bffc8a
[ "Apache-2.0" ]
14
2018-03-17T13:55:55.000Z
2020-10-10T12:23:49.000Z
node_modules/@tensorflow/tfjs-core/dist-es6/version_test.js
syiin/nnLibconv
416993e9a7b165e419a3ee980dc973e911bffc8a
[ "Apache-2.0" ]
null
null
null
node_modules/@tensorflow/tfjs-core/dist-es6/version_test.js
syiin/nnLibconv
416993e9a7b165e419a3ee980dc973e911bffc8a
[ "Apache-2.0" ]
1
2021-12-21T10:33:11.000Z
2021-12-21T10:33:11.000Z
import { version_core } from './index'; describe('version', function () { it('version is contained', function () { var expected = require('../package.json').version; expect(version_core).toBe(expected); }); }); //# sourceMappingURL=version_test.js.map
34.375
58
0.643636
d5c37d12862c286adafe8e8234f494d76147a33a
4,645
js
JavaScript
packages/hzero-front-hadm/src/routes/RuleConfig/index.js
open-hand/hzero-front
9a2797242671ea7dfd2cd0cd1d55e3479048da2b
[ "Apache-2.0" ]
14
2020-09-23T03:07:03.000Z
2022-03-25T09:40:01.000Z
packages/hzero-front-hadm/src/routes/RuleConfig/index.js
open-hand/hzero-front
9a2797242671ea7dfd2cd0cd1d55e3479048da2b
[ "Apache-2.0" ]
7
2020-09-24T08:09:43.000Z
2022-02-28T03:18:30.000Z
packages/hzero-front-hadm/src/routes/RuleConfig/index.js
open-hand/hzero-front
9a2797242671ea7dfd2cd0cd1d55e3479048da2b
[ "Apache-2.0" ]
25
2020-09-23T04:14:06.000Z
2021-12-06T07:17:21.000Z
/** * ruleConfig 规则配置 * @date: 2020-4-30 * @author: jmy <mingyang.jin@hand-china.com> * @copyright Copyright (c) 2020, Hand */ import React from 'react'; import { Table, ModalContainer, DataSet } from 'choerodon-ui/pro'; import { Bind } from 'lodash-decorators'; import { Header, Content } from 'components/Page'; import { Button as ButtonPermission } from 'components/Permission'; import formatterCollections from 'utils/intl/formatterCollections'; import { operatorRender } from 'utils/renderer'; import intl from 'utils/intl'; import { initDS } from '../../stores/ruleConfigDS'; @formatterCollections({ code: ['hadm.ruleConfig'] }) export default class ruleConfig extends React.Component { initDs = new DataSet(initDS()); get columns() { return [ { name: 'index', width: 100, renderer: ({ record }) => { return record.index + 1; }, }, // { // name: 'dsUrl', // }, { name: 'datasourceGroupName', // width: 200, }, { name: 'proxySchemaName', width: 200, }, // { // name: 'proxyDsUrl', // width: 200, // }, { name: 'action', width: 160, renderer: ({ record }) => { const operators = []; operators.push({ key: 'edit', ele: ( <ButtonPermission type="text" permissionList={[ { code: `${this.props.match.path}.button.edit`, type: 'button', meaning: '规则配置-编辑', }, ]} onClick={() => this.handleUpdate(false, record)} > {intl.get('hzero.common.button.edit').d('编辑')} </ButtonPermission> ), len: 2, title: intl.get('hzero.common.button.edit').d('编辑'), }); operators.push({ key: 'delete', ele: ( <ButtonPermission type="text" permissionList={[ { code: `${this.props.match.path}.button.delete`, type: 'button', meaning: '规则配置-删除', }, ]} onClick={() => this.handleDelete(record)} > {intl.get('hzero.common.button.delete').d('删除')} </ButtonPermission> ), len: 2, title: intl.get('hzero.common.button.delete').d('删除'), }); return operatorRender(operators); }, }, ]; } /** * 新建/编辑 * @param {boolean} isCreate * @memberof ruleConfig */ @Bind() handleUpdate(isCreate, record) { const { history } = this.props; if (isCreate) { history.push('/hadm/rule-config/detail/create'); } else { history.push(`/hadm/rule-config/detail/${record.get('ruleHeaderId')}`); } } /** * 删除 * @param {object} [record={}] * @memberof ruleConfig */ @Bind() async handleDelete(record = {}) { await this.initDs.delete(record); // if(res){ // await this.initDs.query(); // } } render() { const { location, match } = this.props; return ( <> <Header title={intl.get('hadm.ruleConfig.view.message.title.ruleConfig').d('Proxy规则配置')} > <ButtonPermission type="c7n-pro" permissionList={[ { code: `${match.path}.button.create`, type: 'button', meaning: '规则配置-新建', }, ]} color="primary" icon="add" onClick={() => this.handleUpdate(true)} > {intl.get('hzero.common.button.create').d('新建')} </ButtonPermission> <ButtonPermission type="c7n-pro" permissionList={[ { code: `${match.path}.button.refresh`, type: 'button', meaning: '规则配置-刷新', }, ]} icon="sync" onClick={() => this.initDs.query()} > {intl.get('hzero.common.button.refresh').d('刷新')} </ButtonPermission> </Header> <Content> <Table dataSet={this.initDs} highLightRow={false} columns={this.columns} queryFieldsLimit={3} /> <ModalContainer location={location} /> </Content> </> ); } }
26.095506
90
0.46028
d5c5583cff8a087b5a7dff4bfde492729cc84d96
2,149
js
JavaScript
build/translations/nb.js
connerts/ckeditor5-build-alignment-font
3ae9d62ac5c1325679075b160b1b9cae7834075f
[ "MIT" ]
null
null
null
build/translations/nb.js
connerts/ckeditor5-build-alignment-font
3ae9d62ac5c1325679075b160b1b9cae7834075f
[ "MIT" ]
null
null
null
build/translations/nb.js
connerts/ckeditor5-build-alignment-font
3ae9d62ac5c1325679075b160b1b9cae7834075f
[ "MIT" ]
null
null
null
(function(d){d['nb']=Object.assign(d['nb']||{},{a:"Image toolbar",b:"Table toolbar",c:"Venstrejuster",d:"Høyrejuster",e:"Midstill",f:"Blokkjuster",g:"Tekstjustering",h:"Text alignment toolbar",i:"Kursiv",j:"Fet",k:"Blokksitat",l:"Velg overskrift",m:"Overskrift",n:"Bilde i full størrelse",o:"Sidebilde",p:"Venstrejustert bilde",q:"Midtstilt bilde",r:"Høyrejustert bilde",s:"Horizontal line",t:"Skriv inn bildetekst",u:"Nummerert liste",v:"Punktmerket liste",w:"media widget",x:"Insert media",y:"The URL must not be empty.",z:"This media URL is not supported.",aa:"Sett inn bilde",ab:"Lenke",ac:"Opplasting feilet",ad:"Sett inn tabell",ae:"Overskriftkolonne",af:"Insert column left",ag:"Insert column right",ah:"Slett kolonne",ai:"Kolonne",aj:"Overskriftrad",ak:"Sett inn rad under",al:"Sett inn rad over",am:"Slett rad",an:"Rad",ao:"Slå sammen celle opp",ap:"Slå sammen celle til høyre",aq:"Slå sammen celle ned",ar:"Slå sammen celle til venstre",as:"Del celle vertikalt",at:"Del celle horisontalt",au:"Slå sammen celler",av:"Bilde-widget",aw:"Opplasting pågår",ax:"Widget toolbar",ay:"Skrifttype",az:"Standard",ba:"Skriftstørrelse",bb:"Veldig liten",bc:"Liten",bd:"Stor",be:"Veldig stor",bf:"Font Color",bg:"Font Background Color",bh:"Endre tekstalternativ for bilde",bi:"Rikteksteditor",bj:"Dropdown toolbar",bk:"Rikteksteditor, %0",bl:"Editor toolbar",bm:"%0 of %1",bn:"Previous",bo:"Next",bp:"Black",bq:"Dim grey",br:"Grey",bs:"Light grey",bt:"White",bu:"Red",bv:"Orange",bw:"Yellow",bx:"Light green",by:"Green",bz:"Aquamarine",ca:"Turquoise",cb:"Light blue",cc:"Blue",cd:"Purple",ce:"Remove color",cf:"Document colors",cg:"Lagre",ch:"Avbryt",ci:"Tekstalternativ for bilde",cj:"Angre",ck:"Gjør om",cl:"Open in a new tab",cm:"Downloadable",cn:"Fjern lenke",co:"Rediger lenke",cp:"Åpne lenke i ny fane",cq:"Denne lenken har ingen URL",cr:"URL for lenke",cs:"Paste the media URL in the input.",ct:"Tip: Paste the URL into the content to embed faster.",cu:"Media URL",cv:"Avsnitt",cw:"Overskrift 1",cx:"Overskrift 2",cy:"Overskrift 3",cz:"Heading 4",da:"Heading 5",db:"Heading 6"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
2,149
2,149
0.722196
d5c5d70a16461c28f4d9fae9e94130285641ab4f
579
js
JavaScript
public/admin/js/script.js
thang240699/WEB4012-Assignment
b8b46c34a89b376ddcdf0f814ef683a1ebd00ed8
[ "MIT" ]
null
null
null
public/admin/js/script.js
thang240699/WEB4012-Assignment
b8b46c34a89b376ddcdf0f814ef683a1ebd00ed8
[ "MIT" ]
2
2019-10-07T09:01:22.000Z
2019-10-07T09:02:08.000Z
public/admin/js/script.js
thang240699/WEB4012-Assignment
b8b46c34a89b376ddcdf0f814ef683a1ebd00ed8
[ "MIT" ]
null
null
null
//config message messUpdate = "Đang cập nhật"; //htmlUpdate = html(messUpdate); //customer $(document).ready(function () { $("#form-customer").submit(function (e) { e.preventDefault(); form_data_customer = $(this).serialize(); btn_customer_submit = $("button#btn_customer_submit").htmlUpdate; $.ajax({ url: 'main.php', type: 'POST', data: btn_customer_submit, dataType: 'json' }).done(function (data) { }) }) });
23.16
74
0.495682
d5c6152b23c8518ccd1e1122d1e7cf0244752395
10,983
js
JavaScript
docs/docs/html/search/all_8.js
wild-ducklings/digital-owl
a851a94d40c6f8b2ed55f59e7592d7f1e174648f
[ "MIT" ]
1
2021-02-22T13:05:27.000Z
2021-02-22T13:05:27.000Z
docs/docs/html/search/all_8.js
wild-ducklings/digital-owl
a851a94d40c6f8b2ed55f59e7592d7f1e174648f
[ "MIT" ]
null
null
null
docs/docs/html/search/all_8.js
wild-ducklings/digital-owl
a851a94d40c6f8b2ed55f59e7592d7f1e174648f
[ "MIT" ]
null
null
null
var searchData= [ ['id',['Id',['../class_digital_owl_1_1_api_1_1_model_1_1_user_1_1_view_user.html#a49ceb6c3c9d5adb597d1c743c52d130e',1,'DigitalOwl.Api.Model.User.ViewUser.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_group.html#aef2aa662ac1ea9150709678b4dafce47',1,'DigitalOwl.Repository.Entity.Group.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_group_member.html#af8460349f56ccc60676d44930602fe2d',1,'DigitalOwl.Repository.Entity.GroupMember.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_group_message.html#a50b9b7d0bcf6f5b2b76c64c215499ed4',1,'DigitalOwl.Repository.Entity.GroupMessage.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_group_police.html#a50e62cec218bc808e90fcc25fe1c3b10',1,'DigitalOwl.Repository.Entity.GroupPolice.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_group_role.html#aa54f7e9475e5e190919e80901d6cb038',1,'DigitalOwl.Repository.Entity.GroupRole.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_poll.html#a8e40af3caf0c96814c6bf024e9d34a5a',1,'DigitalOwl.Repository.Entity.Poll.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_poll_answer.html#aafc643c7718be33ed050a4cb824cbc74',1,'DigitalOwl.Repository.Entity.PollAnswer.Id()'],['../class_digital_owl_1_1_repository_1_1_entity_1_1_poll_question.html#a574e3d4a3def09c660c254d917322dde',1,'DigitalOwl.Repository.Entity.PollQuestion.Id()'],['../interface_digital_owl_1_1_repository_1_1_interface_1_1_entity_1_1_i_entity.html#ad183eb94c9773a7ac582095a4460ba02',1,'DigitalOwl.Repository.Interface.Entity.IEntity.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_group.html#a768b271d5f67d1c38071836ceee8038b',1,'DigitalOwl.Service.Dto.DtoGroup.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_group_member.html#a782194a5851e41dc6c89f8e06ab9cda4',1,'DigitalOwl.Service.Dto.DtoGroupMember.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_group_message.html#a8083a8cb0ca053709ad574b8644865de',1,'DigitalOwl.Service.Dto.DtoGroupMessage.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_group_police.html#ac297c4be5778a1585d5e75b9ccf02531',1,'DigitalOwl.Service.Dto.DtoGroupPolice.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_group_role.html#a67b07298b2ea3cabd39ee6284f7333a3',1,'DigitalOwl.Service.Dto.DtoGroupRole.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_poll.html#ab7c16f324852dbd4f649706c5d4ad892',1,'DigitalOwl.Service.Dto.DtoPoll.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_poll_answer.html#ab0106b15b64a4523505818a5b21afcf0',1,'DigitalOwl.Service.Dto.DtoPollAnswer.Id()'],['../class_digital_owl_1_1_service_1_1_dto_1_1_dto_poll_question.html#a07a40b109a154e79ffc1e3c7d6586bba',1,'DigitalOwl.Service.Dto.DtoPollQuestion.Id()']]], ['idbcontext',['IDbContext',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_db_context.html',1,'DigitalOwl::Repository::Interface::Base']]], ['idbcontext_2ecs',['IDbContext.cs',['../_i_db_context_8cs.html',1,'']]], ['ientity',['IEntity',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_entity_1_1_i_entity.html',1,'DigitalOwl::Repository::Interface::Entity']]], ['ientity_2ecs',['IEntity.cs',['../_i_entity_8cs.html',1,'']]], ['igenericrepository',['IGenericRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_2ecs',['IGenericRepository.cs',['../_i_generic_repository_8cs.html',1,'']]], ['igenericrepository_3c_20group_20_3e',['IGenericRepository&lt; Group &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20groupmember_20_3e',['IGenericRepository&lt; GroupMember &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20groupmessage_20_3e',['IGenericRepository&lt; GroupMessage &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20grouppolice_20_3e',['IGenericRepository&lt; GroupPolice &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20grouprole_20_3e',['IGenericRepository&lt; GroupRole &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20poll_20_3e',['IGenericRepository&lt; Poll &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20pollanswer_20_3e',['IGenericRepository&lt; PollAnswer &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igenericrepository_3c_20pollquestion_20_3e',['IGenericRepository&lt; PollQuestion &gt;',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_generic_repository.html',1,'DigitalOwl::Repository::Interface::Base']]], ['igroupmemberrepository',['IGroupMemberRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_group_member_repository.html',1,'DigitalOwl::Repository::Interface']]], ['igroupmemberrepository_2ecs',['IGroupMemberRepository.cs',['../_i_group_member_repository_8cs.html',1,'']]], ['igroupmemberservice',['IGroupMemberService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_group_member_service.html',1,'DigitalOwl::Service::Interface']]], ['igroupmemberservice_2ecs',['IGroupMemberService.cs',['../_i_group_member_service_8cs.html',1,'']]], ['igroupmessagerepository',['IGroupMessageRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_group_message_repository.html',1,'DigitalOwl::Repository::Interface']]], ['igroupmessagerepository_2ecs',['IGroupMessageRepository.cs',['../_i_group_message_repository_8cs.html',1,'']]], ['igroupmessageservice',['IGroupMessageService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_group_message_service.html',1,'DigitalOwl::Service::Interface']]], ['igroupmessageservice_2ecs',['IGroupMessageService.cs',['../_i_group_message_service_8cs.html',1,'']]], ['igrouppolicerepository',['IGroupPoliceRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_group_police_repository.html',1,'DigitalOwl::Repository::Interface']]], ['igrouppolicerepository_2ecs',['IGroupPoliceRepository.cs',['../_i_group_police_repository_8cs.html',1,'']]], ['igrouppoliceservice',['IGroupPoliceService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_group_police_service.html',1,'DigitalOwl::Service::Interface']]], ['igrouppoliceservice_2ecs',['IGroupPoliceService.cs',['../_i_group_police_service_8cs.html',1,'']]], ['igrouprepository',['IGroupRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_group_repository.html',1,'DigitalOwl::Repository::Interface']]], ['igrouprepository_2ecs',['IGroupRepository.cs',['../_i_group_repository_8cs.html',1,'']]], ['igrouprolerepository',['IGroupRoleRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_group_role_repository.html',1,'DigitalOwl::Repository::Interface']]], ['igrouprolerepository_2ecs',['IGroupRoleRepository.cs',['../_i_group_role_repository_8cs.html',1,'']]], ['igrouproleservice',['IGroupRoleService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_group_role_service.html',1,'DigitalOwl::Service::Interface']]], ['igrouproleservice_2ecs',['IGroupRoleService.cs',['../_i_group_role_service_8cs.html',1,'']]], ['igroupservice',['IGroupService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_group_service.html',1,'DigitalOwl::Service::Interface']]], ['igroupservice_2ecs',['IGroupService.cs',['../_i_group_service_8cs.html',1,'']]], ['ijwtfactory',['IJwtFactory',['../interface_digital_owl_1_1_api_1_1_infrastructure_1_1_auth_1_1_i_jwt_factory.html',1,'DigitalOwl::Api::Infrastructure::Auth']]], ['ijwtfactory_2ecs',['IJwtFactory.cs',['../_i_jwt_factory_8cs.html',1,'']]], ['ipollanswerrepository',['IPollAnswerRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_poll_answer_repository.html',1,'DigitalOwl::Repository::Interface']]], ['ipollanswerrepository_2ecs',['IPollAnswerRepository.cs',['../_i_poll_answer_repository_8cs.html',1,'']]], ['ipollanswerservice',['IPollAnswerService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_poll_answer_service.html',1,'DigitalOwl::Service::Interface']]], ['ipollanswerservice_2ecs',['IPollAnswerService.cs',['../_i_poll_answer_service_8cs.html',1,'']]], ['ipollquestionrepository',['IPollQuestionRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_poll_question_repository.html',1,'DigitalOwl::Repository::Interface']]], ['ipollquestionrepository_2ecs',['IPollQuestionRepository.cs',['../_i_poll_question_repository_8cs.html',1,'']]], ['ipollquestionservice',['IPollQuestionService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_poll_question_service.html',1,'DigitalOwl::Service::Interface']]], ['ipollquestionservice_2ecs',['IPollQuestionService.cs',['../_i_poll_question_service_8cs.html',1,'']]], ['ipollrepository',['IPollRepository',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_i_poll_repository.html',1,'DigitalOwl::Repository::Interface']]], ['ipollrepository_2ecs',['IPollRepository.cs',['../_i_poll_repository_8cs.html',1,'']]], ['ipollservice',['IPollService',['../interface_digital_owl_1_1_service_1_1_interface_1_1_i_poll_service.html',1,'DigitalOwl::Service::Interface']]], ['ipollservice_2ecs',['IPollService.cs',['../_i_poll_service_8cs.html',1,'']]], ['issuedat',['IssuedAt',['../class_digital_owl_1_1_api_1_1_infrastructure_1_1_auth_1_1_jwt_issuer_options.html#acd9c79f1b76942c0bd67140fdb17c33d',1,'DigitalOwl::Api::Infrastructure::Auth::JwtIssuerOptions']]], ['issuer',['Issuer',['../class_digital_owl_1_1_api_1_1_infrastructure_1_1_auth_1_1_jwt_issuer_options.html#afef5b8df3ee9ae97f66b65f0f2b67713',1,'DigitalOwl::Api::Infrastructure::Auth::JwtIssuerOptions']]], ['itimestamp',['ITimestamp',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_entity_1_1_i_timestamp.html',1,'DigitalOwl::Repository::Interface::Entity']]], ['itimestamp_2ecs',['ITimestamp.cs',['../_i_timestamp_8cs.html',1,'']]], ['iunitofwork',['IUnitOfWork',['../interface_digital_owl_1_1_repository_1_1_interface_1_1_base_1_1_i_unit_of_work.html',1,'DigitalOwl::Repository::Interface::Base']]], ['iunitofwork_2ecs',['IUnitOfWork.cs',['../_i_unit_of_work_8cs.html',1,'']]] ];
186.152542
2,754
0.815897
d5c6c3e189d3cbfb06d60e0970dedf45a89e189c
2,782
js
JavaScript
_node_modules/projen/lib/cdk8s-construct.js
vtarabcakova/dssp
de777627a6065ce0f2ab461e9c4b7543d5ba35cb
[ "Apache-2.0" ]
null
null
null
_node_modules/projen/lib/cdk8s-construct.js
vtarabcakova/dssp
de777627a6065ce0f2ab461e9c4b7543d5ba35cb
[ "Apache-2.0" ]
null
null
null
_node_modules/projen/lib/cdk8s-construct.js
vtarabcakova/dssp
de777627a6065ce0f2ab461e9c4b7543d5ba35cb
[ "Apache-2.0" ]
null
null
null
"use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConstructLibraryCdk8s = void 0; const JSII_RTTI_SYMBOL_1 = Symbol.for("jsii.rtti"); const construct_lib_1 = require("./construct-lib"); /** * (experimental) CDK8s construct library project. * * A multi-language (jsii) construct library which vends constructs designed to * use within the CDK for Kubernetes (CDK8s), with a friendly workflow and * automatic publishing to the construct catalog. * * @experimental * @pjid cdk8s-construct */ class ConstructLibraryCdk8s extends construct_lib_1.ConstructLibrary { /** * @experimental */ constructor(options) { super(options); const ver = options.cdk8sVersion; this.addPeerDeps('constructs@^3.2.34', `cdk8s@^${ver}`, `cdk8s-plus-17@^${ver}`); } } exports.ConstructLibraryCdk8s = ConstructLibraryCdk8s; _a = JSII_RTTI_SYMBOL_1; ConstructLibraryCdk8s[_a] = { fqn: "projen.ConstructLibraryCdk8s", version: "0.17.1" }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2RrOHMtY29uc3RydWN0LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NkazhzLWNvbnN0cnVjdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLG1EQUE0RTs7Ozs7Ozs7Ozs7QUFvQjVFLE1BQWEscUJBQXNCLFNBQVEsZ0NBQWdCOzs7O0lBQ3pELFlBQVksT0FBcUM7UUFDL0MsS0FBSyxDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBRWYsTUFBTSxHQUFHLEdBQUcsT0FBTyxDQUFDLFlBQVksQ0FBQztRQUVqQyxJQUFJLENBQUMsV0FBVyxDQUNkLG9CQUFvQixFQUNwQixVQUFVLEdBQUcsRUFBRSxFQUNmLGtCQUFrQixHQUFHLEVBQUUsQ0FDeEIsQ0FBQztJQUNKLENBQUM7O0FBWEgsc0RBWUMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBDb25zdHJ1Y3RMaWJyYXJ5LCBDb25zdHJ1Y3RMaWJyYXJ5T3B0aW9ucyB9IGZyb20gJy4vY29uc3RydWN0LWxpYic7XG5cbmV4cG9ydCBpbnRlcmZhY2UgQ29uc3RydWN0TGlicmFyeUNkazhzT3B0aW9ucyBleHRlbmRzIENvbnN0cnVjdExpYnJhcnlPcHRpb25zIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFxuICByZWFkb25seSBjZGs4c1ZlcnNpb246IHN0cmluZztcbn1cblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcbmV4cG9ydCBjbGFzcyBDb25zdHJ1Y3RMaWJyYXJ5Q2RrOHMgZXh0ZW5kcyBDb25zdHJ1Y3RMaWJyYXJ5IHtcbiAgY29uc3RydWN0b3Iob3B0aW9uczogQ29uc3RydWN0TGlicmFyeUNkazhzT3B0aW9ucykge1xuICAgIHN1cGVyKG9wdGlvbnMpO1xuXG4gICAgY29uc3QgdmVyID0gb3B0aW9ucy5jZGs4c1ZlcnNpb247XG5cbiAgICB0aGlzLmFkZFBlZXJEZXBzKFxuICAgICAgJ2NvbnN0cnVjdHNAXjMuMi4zNCcsXG4gICAgICBgY2RrOHNAXiR7dmVyfWAsXG4gICAgICBgY2RrOHMtcGx1cy0xN0BeJHt2ZXJ9YCxcbiAgICApO1xuICB9XG59Il19
92.733333
1,774
0.893242
d5c6eced01c454b4c003060bd6ed4a010f0c5357
618
js
JavaScript
ingest/gql/updatePersonSemanticScholarIds.js
share-research/pace-admin
33b46da1d7e1da282dc81d1cbdcd9dcc5dd918c0
[ "Apache-2.0" ]
1
2021-04-09T22:04:08.000Z
2021-04-09T22:04:08.000Z
ingest/gql/updatePersonSemanticScholarIds.js
share-research/pace-admin
33b46da1d7e1da282dc81d1cbdcd9dcc5dd918c0
[ "Apache-2.0" ]
113
2020-02-07T19:34:42.000Z
2022-03-09T16:08:19.000Z
ingest/gql/updatePersonSemanticScholarIds.js
share-research/pace-admin
33b46da1d7e1da282dc81d1cbdcd9dcc5dd918c0
[ "Apache-2.0" ]
4
2020-10-27T15:52:11.000Z
2021-12-07T14:54:02.000Z
import gql from 'graphql-tag' export default function updatePersonSemanticScholarIds (id, semanticScholarIds) { return { mutation: gql` mutation MyMutation($id: Int!, $semantic_scholar_ids: String!) { update_persons(where: {id: {_eq: $id}}, _set: {semantic_scholar_ids: $semantic_scholar_ids}) { returning { id given_name family_name start_date end_date, semantic_scholar_ids } } } `, variables: { id, semantic_scholar_ids: JSON.stringify(semanticScholarIds) } } }
24.72
102
0.585761
d5c77d5c73ac42551e99d446d170df6600f64e1b
427
js
JavaScript
shared/reducers/lib/form-validation/roles.js
Proyecto-de-Software/2017_grupo74
ffccd1ea1e9a3e084151014417df5e83bc1fb7e0
[ "MIT" ]
1
2018-07-15T22:51:34.000Z
2018-07-15T22:51:34.000Z
shared/reducers/lib/form-validation/roles.js
hnrg/hnrg
ffccd1ea1e9a3e084151014417df5e83bc1fb7e0
[ "MIT" ]
6
2020-07-17T18:52:14.000Z
2022-02-12T17:05:32.000Z
shared/reducers/lib/form-validation/roles.js
Proyecto-de-Software/2017_grupo74
ffccd1ea1e9a3e084151014417df5e83bc1fb7e0
[ "MIT" ]
1
2018-07-15T22:51:37.000Z
2018-07-15T22:51:37.000Z
import _ from 'lodash'; export default function formValidation(state) { const isValid = ( state.fields.name !== '' && !state.fields.nameHasError && !state.fields.permissionsHasError && (state.fields.name !== state.originalRol.name || !_.isEqual( state.fields.permissions, Array.from(state.originalRol.permissions || []).map(p => p.name), )) ); return { ...state, isValid, }; }
22.473684
71
0.620609
d5c7edb14736721086d80aa787dfcd898cb30667
1,348
js
JavaScript
lib/getCatKeyPath.js
trasherdk/catkeys
ec968bc1fff964d0d6bf56f32341118fbe25593b
[ "MIT" ]
5
2021-03-04T21:43:14.000Z
2021-04-19T13:25:25.000Z
lib/getCatKeyPath.js
93million/catkeys
ec968bc1fff964d0d6bf56f32341118fbe25593b
[ "MIT" ]
1
2021-04-25T11:24:06.000Z
2021-04-25T11:34:25.000Z
lib/getCatKeyPath.js
trasherdk/catkeys
ec968bc1fff964d0d6bf56f32341118fbe25593b
[ "MIT" ]
3
2021-03-06T15:06:21.000Z
2021-05-24T19:19:19.000Z
const fs = require('fs') const util = require('util') const locateKeysDir = require('./locateKeysDir') const path = require('path') const getCatKeyFileName = require('./getCatKeyFilename') const readdir = util.promisify(fs.readdir) module.exports = async (catKey, { catKeysDir } = {}) => { const keyDir = catKeysDir || process.env.CAT_KEYS_DIR || await locateKeysDir() if (keyDir === undefined) { throw new Error('catkeys directory could not be found') } if (catKey !== undefined) { return getCatKeyFileName(keyDir, catKey) } else if (process.env.CAT_KEY_NAME !== undefined) { return getCatKeyFileName(keyDir, process.env.CAT_KEY_NAME) } else { const files = await readdir(keyDir) const keys = files.filter(filename => { const excludeKeyNames = ['server'] const [ext, basename] = filename.split('.').reverse() const keyExts = ['catkey', 'cahkey'] return (keyExts.includes(ext) && !excludeKeyNames.includes(basename)) }) if (keys.length !== 1) { const msg = keys.length > 1 ? [ 'Too many client catkeys!', 'Specify which one to use in env CAT_KEY_NAME or `catKey` option' ].join(' ') : `Unable to find catkey in directory ${keyDir}` throw new Error(msg) } else { return path.resolve(keyDir, keys[0]) } } }
30.636364
80
0.638724
d5c8787508b8c684508543b9ddf374c2afec77d7
22,464
js
JavaScript
src/components/content/article/Article.js
thaisonnguyenbt/afn-contentful
11749435f41f21e65339fe2d5a636c959556a01e
[ "MIT" ]
null
null
null
src/components/content/article/Article.js
thaisonnguyenbt/afn-contentful
11749435f41f21e65339fe2d5a636c959556a01e
[ "MIT" ]
null
null
null
src/components/content/article/Article.js
thaisonnguyenbt/afn-contentful
11749435f41f21e65339fe2d5a636c959556a01e
[ "MIT" ]
null
null
null
import React from 'react'; import LazyLoad from 'react-lazyload' import lowRes from '../../../images/common/afn-1920x1280-lowres.jpg'; import {Link} from 'gatsby'; import facebook from '../../../images/common/social-media/facebook-default.svg'; import pinterest from '../../../images/common/social-media/pinterest-default.svg'; import twitter from '../../../images/common/social-media/twitter-default.svg'; import whatsapp from '../../../images/common/social-media/whatsapp-default.svg'; const propTypes = {}; const defaultProps = {}; let { getArticleData } = require('./ArticleDataBuilder') class Article extends React.Component { constructor(props) { super(props); this.state = { tags: this.props.tags, article: getArticleData(this.props.article) }; } render() { return <div> <div className="articleoverview aem-GridColumn aem-GridColumn--default--7"> <div className="p-article-detail"> <section className="o-overview"> <div className="m-overview__hero -image"> <div className="cmp-image" data-cmp-src="/content/dam/afn/global/en/articles/4-easy-peasy-to-keep-your-cooking-clena/AFN_kitchen.jpg" itemScope="" itemType="http://schema.org/ImageObject"> <LazyLoad placeholder={<img src={lowRes} alt={this.state.article.articleTitle} title={this.state.article.articleTitle} className="blur-up cmp-image__image"/>}> <img className="blur-up cmp-image__image lazyloaded" itemProp="contentUrl" data-cmp-hook-image="image" alt={this.state.article.articleTitle} title={this.state.article.articleTitle} src={this.state.article.imageMastheadUrl} /> </LazyLoad> </div> </div> <div className="a-overview__author"> <span>{this.state.article.author}</span> </div> <div className="a-overview__date"> <span>{this.state.article.articleDate}</span> </div> <div className="a-page-title"> <h1>{this.state.article.articleTitle}</h1> </div> <div className="a-overview__description"> <p>{this.state.article.articleDescription}</p> </div> <div className="m-overview__overallRating"> <a className="m-ratings gigya-style-modern gigya-mac gigya-chrome" smooth-scroll="" scroll-current="true" href="#article-ratings-reviews-container" id="view-overall-article-ratings" data-rating="overall-ratings" rating-categoryid="afn_ratings_reviews_default_configuration" rating-container="view-overall-article-ratings"> <div className="gig-rating gig-clr"> <div className="gig-stars-container"> <div className="gig-rating-topbar"> <span className="gig-rating-averageRating">Average rating:</span> <span className="gig-rating-stars" title="0" alt="0"> <div className="gig-rating-star gig-rating-star-empty"></div> <div className="gig-rating-star gig-rating-star-empty"></div> <div className="gig-rating-star gig-rating-star-empty"></div> <div className="gig-rating-star gig-rating-star-empty"></div> <div className="gig-rating-star gig-rating-star-empty"></div> </span> </div> <div className="gig-rating-dimensions"></div> </div> </div> </a> <div className="gig-button-container gig-clr"> <a href className="gig-rating-readReviewsLink">0 Reviews</a> <a href className="gig-rating-writeYourReview gig-rating-button">Write your review</a> </div> </div> <div className="m-overview__bookmark"> <button className="a-button -withIcon" button-click="save-bookmark" bookmark-type="afn" bookmark-author="Debbie Wong" bookmark-category="article" bookmark-subcategory="default" bookmark-thumbnail="/content/dam/afn/global/en/articles/4-easy-peasy-to-keep-your-cooking-clena/AFN_kitchen.jpg.transform/1280x853/img.png" bookmark-title="4 Easy Peasy Ways To Keep Your Cooking Clean (And Germ-Free!)" bookmark-url="/content/afn/global/en/articles/four-easy-peasy-ways-cooking-clean-germ-free.html" bookmark-ratingconfigid="afn_ratings_reviews_default_configuration" bookmark-streamid="L2NvbnRlbnQvYWZuL2dsb2JhbC9lbi9hcnRpY2xlcy9mb3VyLWVhc3ktcGVhc3ktd2F5cy1jb29raW5nLWNsZWFuLWdlcm0tZnJlZS5odG1s" data-endpoint="https://asianfoodnetwork.com/en/articles/four-easy-peasy-ways-cooking-clean-germ-free/_jcr_content/root/responsivegrid_1564329275/container/articleoverview.gigya.bookmark.exist.json?uid={USERID}&amp;streamid=L2NvbnRlbnQvYWZuL2dsb2JhbC9lbi9hcnRpY2xlcy9mb3VyLWVhc3ktcGVhc3ktd2F5cy1jb29raW5nLWNsZWFuLWdlcm0tZnJlZS5odG1s"> <span className="button__icon"> <svg className="a-afnIcon -bookmark -filled" role="img" viewBox="0 0 12 17"> <path d="M.5 0h11c.3 0 .5.2.5.5v15.4a.5.5 0 0 1-.8.4l-5-3.1a.5.5 0 0 0-.5 0l-5 3.1a.5.5 0 0 1-.7-.4V.5C0 .2.2 0 .5 0z" fillRule="evenodd"></path> </svg> </span> <span className="button__copy">Save Article</span> </button> <button className="a-button -withIcon -disabled" disabled="disabled" button-disabled="saved"> <span className="button__icon"> <span className="icon-afn-check"></span> </span> <span className="button__copy">Saved!</span> </button> </div> <div className="m-overview__categoryTags"> <div className="category-tags-round"> <div className="m-category-tags"> <ul className="m-category-tags__list"> <li><span className="m-category-tags__label">Related to: </span> </li> { this.state.tags && this.state.tags.map((tag, i) => { return <li key={i}> <div className="a-category-tag"> <Link to={"/en/search.html?search=" + encodeURI(tag.name)}> <span className="a-category-tag__title">{tag.name}</span> </Link> </div> </li> })} </ul> </div> </div> </div> <div className="m-overview__socialSharing"> <div className="m-social-sharing-bar "> <div className="m-social-sharing__label"> <span>Share This Article:</span> </div> <div className="m-social-sharing__list" id="m-overview__socialSharing1584532182793_gig_containerParent"> <div className="m-social-sharing__icons" id="m-overview__socialSharing1584532182793" gigid="showShareBarUI"> <div className="gig-bar-container gig-share-bar-container"> <table cellSpacing="0" cellPadding="0" role="presentation"> <tbody> <tr> <td> <div className="gig-button-container gig-button-container-count-none gig-button-container-facebook gig-button-container-facebook-count-none gig-share-button-container gig-button-container-horizontal"> <div className="gig-button gig-share-button gig-button-up gig-button-count-none" id="m-overview__socialSharing1584532182793-reaction0" title="" alt="" tabIndex="0" role="button"> <table cellPadding="0" cellSpacing="0" role="presentation"> <tbody> <tr> <td id="m-overview__socialSharing1584532182793-reaction0-left" aria-hidden="true"></td> <td id="m-overview__socialSharing1584532182793-reaction0-icon"> <img id="m-overview__socialSharing1584532182793-reaction0-icon_img" src={facebook} alt="" focusable="false" /> </td> <td id="m-overview__socialSharing1584532182793-reaction0-right" aria-hidden="true"></td> </tr> </tbody> </table> </div> </div> </td> <td> <div className="gig-button-container gig-button-container-count-none gig-button-container-twitter gig-button-container-twitter-count-none gig-share-button-container gig-button-container-horizontal"> <div className="gig-button gig-share-button gig-button-up gig-button-count-none" id="m-overview__socialSharing1584532182793-reaction1" title="" alt="" tabIndex="0" role="button"> <table cellPadding="0" cellSpacing="0" role="presentation"> <tbody> <tr> <td id="m-overview__socialSharing1584532182793-reaction1-left" aria-hidden="true"></td> <td id="m-overview__socialSharing1584532182793-reaction1-icon"> <img id="m-overview__socialSharing1584532182793-reaction1-icon_img" src={twitter} alt="" focusable="false" /> </td> <td id="m-overview__socialSharing1584532182793-reaction1-right" aria-hidden="true"></td> </tr> </tbody> </table> </div> </div> </td> <td> <div className="gig-button-container gig-button-container-count-none gig-button-container-pinterest gig-button-container-pinterest-count-none gig-share-button-container gig-button-container-horizontal"> <div className="gig-button gig-share-button gig-button-up gig-button-count-none" id="m-overview__socialSharing1584532182793-reaction2" title="" alt="" tabIndex="0" role="button"> <table cellPadding="0" cellSpacing="0" role="presentation"> <tbody> <tr> <td id="m-overview__socialSharing1584532182793-reaction2-left" aria-hidden="true"></td> <td id="m-overview__socialSharing1584532182793-reaction2-icon"> <img id="m-overview__socialSharing1584532182793-reaction2-icon_img" src={pinterest} alt="" focusable="false" /> </td> <td id="m-overview__socialSharing1584532182793-reaction2-right" aria-hidden="true"></td> </tr> </tbody> </table> </div> </div> </td> <td> <div className="gig-button-container gig-button-container-count-none gig-button-container-whatsapp gig-button-container-whatsapp-count-none gig-share-button-container gig-button-container-horizontal"> <div className="gig-button gig-share-button gig-button-up gig-button-count-none" id="m-overview__socialSharing1584532182793-reaction3" title="" alt="" tabIndex="0" role="button"> <table cellPadding="0" cellSpacing="0" role="presentation"> <tbody> <tr> <td id="m-overview__socialSharing1584532182793-reaction3-left" aria-hidden="true"></td> <td id="m-overview__socialSharing1584532182793-reaction3-icon"> <img id="m-overview__socialSharing1584532182793-reaction3-icon_img" src={whatsapp} alt="" focusable="false" /> </td> <td id="m-overview__socialSharing1584532182793-reaction3-right" aria-hidden="true"></td> </tr> </tbody> </table> </div> </div> </td> </tr> </tbody> </table> </div> </div> <button className="m-email-sharing"> <a href="mailto:?subject=4%20Easy%20Peasy%20Ways%20To%20Keep%20Your%20Cooking%20Clean%20(And%20Germ-Free!)&amp;body=From quarantining your proteins, to isolating your cutting boards, Debbie Wong tells us just how easy it is to be clean in the kitchen - https://asianfoodnetwork.com/en/articles/four-easy-peasy-ways-cooking-clean-germ-free.html"> <svg width="32" height="32" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="32" cy="32" r="32" fill="#C84152"></circle> <path d="M20.125 21C19.1821 21 18.3171 21.3186 17.6264 21.8404L31.8306 35.0187C32.1488 35.3142 32.8512 35.3142 33.1694 35.0187L47.3759 21.8404C46.6603 21.2968 45.7806 21.0012 44.875 21H20.125ZM16.5421 23.0617C16.2027 23.6551 16 24.3431 16 25.0749V38.9274C16 39.7585 16.2546 40.525 16.6836 41.1669L16.7213 41.1438L27.1021 32.8669L16.5398 23.0617H16.5421ZM48.4579 23.0617L37.9002 32.8669L48.2787 41.1415L48.3164 41.1669C48.762 40.5015 48.9996 39.7231 49 38.9274V25.0749C49 24.3407 48.7973 23.6551 48.4579 23.0617V23.0617ZM28.3114 33.9867L17.8551 42.3258C18.5056 42.7483 19.2859 43 20.125 43H44.875C45.7141 43 46.4944 42.7483 47.1426 42.3258L36.6886 33.9867L34.3056 36.2031C33.8173 36.6544 33.1714 36.9058 32.5 36.9058C31.8286 36.9058 31.1827 36.6544 30.6944 36.2031L28.3114 33.9867V33.9867Z" fill="white"></path> </svg> </a> </button> <button className="m-copy-to-clipboard" data-copy="link" data-clipboard-text="https://asianfoodnetwork.com/en/articles/four-easy-peasy-ways-cooking-clean-germ-free.html"> <svg width="32" height="32" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="32" cy="32" r="32" fill="#C84152"></circle> <g clipPath="url(#clip0)"> <path d="M34.85 39.3202L29.2825 44.8889C27.9343 46.2342 26.1097 46.993 24.2051 47.0005C22.3006 47.0079 20.4701 46.2635 19.1113 44.9289C19.1045 44.9224 19.0979 44.9157 19.0913 44.9089L19.0713 44.8889C17.7368 43.5304 16.9924 41.7 16.9999 39.7957C17.0074 37.8914 17.7661 36.0669 19.1113 34.7189L25.2488 28.5814C26.5971 27.2367 28.4216 26.4784 30.3258 26.4711C32.2301 26.4639 34.0603 27.2083 35.4188 28.5427L35.4388 28.5614L35.4588 28.5814C35.7963 28.9239 36.0913 29.2914 36.3463 29.6777L34.6788 31.3452C34.2038 31.8202 33.4788 31.8977 32.9225 31.5789C32.8482 31.4856 32.769 31.3963 32.685 31.3114C32.0584 30.6974 31.2149 30.3552 30.3376 30.3592C29.4602 30.3632 28.6198 30.713 27.9988 31.3327L21.8613 37.4702C21.2416 38.0916 20.892 38.9324 20.8885 39.8101C20.8849 40.6877 21.2278 41.5313 21.8425 42.1577C22.4691 42.7723 23.3128 43.1149 24.1904 43.1111C25.068 43.1074 25.9088 42.7576 26.53 42.1377L30.0188 38.6502C31.5391 39.3074 33.2095 39.5389 34.8513 39.3202H34.85ZM44.8888 19.0714C43.5302 17.7365 41.6996 16.9919 39.7949 16.9994C37.8903 17.0069 36.0656 17.7659 34.7175 19.1114L29.15 24.6802C30.7919 24.4619 32.4623 24.6939 33.9825 25.3514L37.47 21.8627C38.0913 21.2428 38.932 20.893 39.8097 20.8892C40.6873 20.8855 41.531 21.2281 42.1575 21.8427C42.7723 22.469 43.1151 23.3126 43.1116 24.1903C43.1081 25.0679 42.7585 25.9087 42.1388 26.5302L36.0013 32.6677C35.3805 33.2872 34.5404 33.6369 33.6634 33.6412C32.7864 33.6454 31.943 33.3037 31.3163 32.6902C31.2325 32.6052 31.1532 32.5159 31.0788 32.4227C30.8011 32.2635 30.4787 32.2001 30.1614 32.2421C29.844 32.2841 29.5493 32.4293 29.3225 32.6552L27.655 34.3227C27.91 34.7102 28.2063 35.0777 28.5425 35.4189L28.5625 35.4389L28.5825 35.4589C29.9411 36.7938 31.7718 37.5385 33.6764 37.531C35.581 37.5235 37.4057 36.7645 38.7538 35.4189L44.8913 29.2814C46.2358 27.9329 46.9939 26.1084 47.001 24.2041C47.008 22.2999 46.2633 20.4698 44.9288 19.1114L44.91 19.0914L44.89 19.0714H44.8888Z" fill="white"></path> </g> <defs> <clipPath id="clip0"> <rect width="30" height="30" fill="white" transform="translate(17 17)"></rect> </clipPath> </defs> </svg> </button> </div> </div> </div> </section> </div> </div> </div>; } } Article.propTypes = propTypes; Article.defaultProps = defaultProps; // #endregion export default Article;
98.526316
1,997
0.448139
d5c93c006fcb54603e7c3ba949e1c6f792fd4549
4,895
js
JavaScript
test/HTML-conversion.js
sandhawke/lazydom
ff28dec30d7843f7542d20ea8ad4dd31d8e9265a
[ "MIT" ]
null
null
null
test/HTML-conversion.js
sandhawke/lazydom
ff28dec30d7843f7542d20ea8ad4dd31d8e9265a
[ "MIT" ]
2
2016-04-10T03:22:45.000Z
2016-04-10T03:28:17.000Z
test/HTML-conversion.js
sandhawke/lazydom
ff28dec30d7843f7542d20ea8ad4dd31d8e9265a
[ "MIT" ]
null
null
null
'use strict' /* todo: - reorg most of this as driven by external json */ const test = require('tape') const arraydom = require('..') let compact=true function run (t, tree, html) { t.plan(2) t.equal(arraydom.stringify(tree, {compact: compact}), html) t.deepEqual(arraydom.parseElement(html), tree) } function run1 (t, tree, html) { t.plan(1) t.equal(arraydom.stringify(tree, {compact: compact}), html) } test('minimal element', t => { let tree = ['div'] let html = '<div></div>' run(t, tree, html) }) test('single class', t => { let tree = ['div foo'] let html = '<div class="foo"></div>' run(t, tree, html) }) test('multiple classes', t => { let tree = ['div foo bar baz'] let html = '<div class="foo bar baz"></div>' run(t, tree, html) }) test('string attr', t => { let tree = ['div', {a:'b'}] let html = '<div a="b"></div>' run(t, tree, html) }) test('number attr gets quoted', t => { let tree = ['div', {a:1}] let html = '<div a="1"></div>' run(t, tree, html) }) test('alphabetic order of attrs', t => { let tree = ['div', {a:1, b:2, c:3}] let html = '<div a="1" b="2" c="3"></div>' run(t, tree, html) }) test('style attrs', t => { let tree = ['div', { a:1, z:2, 'style.border':'solid red 1px', 'style.margin-left': '3em'}] let html = '<div a="1" style="border: solid red 1px; margin-left: 3em;" z="2"></div>' run1(t, tree, html) }) test('single string child', t => { let tree = ['div', {}, 'hello'] let html = '<div>hello</div>' run(t, tree, html) }) test('multiple string children', t => { let tree = ['div', {}, 'Hello', ', ', '', 'World', '!'] let html = '<div>Hello, World!</div>' run1(t, tree, html) }) test('self-closing', t => { let tree = ['hr'] let html = '<hr/>' run(t, tree, html) }) test('self-closing with attr', t => { let tree = ['hr', {a:1}] let html = '<hr a="1" />' run(t, tree, html) }) test('single simple child element', t => { let tree = ['div', {}, ['span']] let html = '<div><span></span></div>' run(t, tree, html) }) test('four child elements', t => { let tree = ['div', {}, ['span a'], ['span b'], ['span c'], ['span d'] ] let html = '<div><span class="a"></span><span class="b"></span><span class="c"></span><span class="d"></span></div>' run(t, tree, html) }) test('child element tree', t => { let tree = ['div', {}, ['span a', {}, ['span b'] ] ] let html = '<div><span class="a"><span class="b"></span></span></div>' run(t, tree, html) }) test('four-node child element tree', t => { let tree = ['div', {}, ['span a'], ['span b'], ['span c', {}, ['span c1'] ] ] let html = '<div><span class="a"></span><span class="b"></span><span class="c"><span class="c1"></span></span></div>' run(t, tree, html) }) test('complex child element tree', t => { let tree = ['div', {}, ['span a'], ['span b'], ['span c', {}, ['span c1'], ['span c2', {}, ['span c2x'], ['span c2y'] ] ], ['span d', {}, 'hello', ['br'], 'there' ] ] let html = '<div><span class="a"></span><span class="b"></span><span class="c"><span class="c1"></span><span class="c2"><span class="c2x"></span><span class="c2y"></span></span></span><span class="d">hello<br/>there</span></div>' run(t, tree, html) }) test('mixed content', t => { let tree = ['div', {}, 'a', ['br'], 'b', ['br'], 'c' ] let html = '<div>a<br/>b<br/>c</div>' run(t, tree, html) }) test('indenting', t => { let tree = ['div', {}, ['span', {color:4}], ['hr'], ['span a', {}, 'foo'], ['span b'], ['span c', {}, ['span c1'], ['span c2', {}, ['span c2x'], ['span c2y'] ] ], ['span d', {}, 'hello', ['br'], 'there', ] ] let html = `<div> <span color="4"></span> <hr/> <span class="a">foo</span> <span class="b"></span> <span class="c"> <span class="c1"></span> <span class="c2"> <span class="c2x"></span> <span class="c2y"></span> </span> </span> <span class="d">hello<br/>there</span> </div> ` compact = false run(t, tree, html) compact = true }) test('skip attrs', t => { let tree = ['div', 'hello'] let html = '<div>hello</div>' // just one way for now; we don't denomalize on read (yet) run1(t, tree, html) })
23.089623
231
0.452707
d5c9678b8224529f0a508cfa3d0dcb24e124ccbb
768
js
JavaScript
src/server.js
VictorMello1993/nlw3
4242defedbebb235701ba5c24ec6746ff68523c2
[ "MIT" ]
null
null
null
src/server.js
VictorMello1993/nlw3
4242defedbebb235701ba5c24ec6746ff68523c2
[ "MIT" ]
null
null
null
src/server.js
VictorMello1993/nlw3
4242defedbebb235701ba5c24ec6746ff68523c2
[ "MIT" ]
null
null
null
const express = require('express') const server = express() const path = require('path') const pages = require('./pages') server .use(express.urlencoded({extended: true})) // Utilizando body-parser (corpo da requisição) .use(express.static('public')) //Utilizando arquivos estáticos // Configurando Template engine .set('views', path.join(__dirname, 'views')) .set('view engine', 'hbs') // Rotas da aplicação .get('/', pages.index) .get('/orphanage', pages.orphanage) .get('/orphanages', pages.orphanages) .get('/create-orphanage', pages.createOrphanage) .post('/save-orphanage', pages.saveOrphanage) // Ligando o servidor server.listen(5500, (req, res) => console.log('Executando...')) // Exemplos de arquivos estáticos: // imagens, arquivos css, html, etc
28.444444
90
0.713542
d5c990788314aac7b0e2b0471a5073a9de873794
4,173
js
JavaScript
process-migration-service/frontend/src/component/tabMigration/PageEditMigrationDefinitionModal.js
dupliaka/droolsjbpm-integration
3f5e2ac7092da6909440f0b5196234573cd60ae0
[ "Apache-2.0" ]
2
2020-10-05T17:12:08.000Z
2020-10-05T17:12:11.000Z
process-migration-service/frontend/src/component/tabMigration/PageEditMigrationDefinitionModal.js
dupliaka/droolsjbpm-integration
3f5e2ac7092da6909440f0b5196234573cd60ae0
[ "Apache-2.0" ]
24
2021-07-16T06:03:57.000Z
2022-03-21T13:36:17.000Z
process-migration-service/frontend/src/component/tabMigration/PageEditMigrationDefinitionModal.js
dupliaka/droolsjbpm-integration
3f5e2ac7092da6909440f0b5196234573cd60ae0
[ "Apache-2.0" ]
10
2021-06-24T09:16:41.000Z
2022-02-17T21:30:54.000Z
import React from "react"; import PropTypes from "prop-types"; import { Button, Modal, Icon, OverlayTrigger, Tooltip } from "patternfly-react"; import PageMigrationScheduler from "../tabMigrationPlan/wizardExecuteMigration/PageMigrationScheduler"; import MigrationClient from "../../clients/migrationClient"; import FormGroup from "patternfly-react/dist/js/components/Form/FormGroup"; import ControlLabel from "patternfly-react/dist/js/components/Form/ControlLabel"; import FormControl from "patternfly-react/dist/js/components/Form/FormControl"; import { Form } from "patternfly-react/dist/js/components/Form"; export default class PageEditMigrationDefinitionModal extends React.Component { constructor(props) { super(props); this.state = { id: this.props.migrationId, showEditDialog: false, isValid: true, definition: { execution: {}, processInstanceIds: [] } }; } openEditDialog = () => { MigrationClient.get(this.props.migrationId).then(migration => { this.setState({ showEditDialog: true, definition: migration.definition }); }); }; hideEditDialog = () => { this.setState({ showEditDialog: false }); }; submit = () => { MigrationClient.update(this.props.migrationId, this.state.definition).then( () => { this.hideEditDialog(); } ); }; onExecutionFieldChange = (field, value) => { const { definition } = this.state; if (value === null) { delete definition.execution[field]; } else { definition.execution[field] = value; } this.setState({ definition }); }; onFormIsValid = isValid => { this.setState({ isValid }); }; render() { const tooltipEdit = ( <Tooltip id="tooltip"> <div>Edit</div> </Tooltip> ); const defaultBody = ( <Form> <FormGroup controlId="EditMigration_PlanId"> <ControlLabel>Plan ID:</ControlLabel> <FormControl type="text" readOnly value={this.state.definition.planId} /> </FormGroup> <FormGroup controlId="EditMigration_Pids"> <ControlLabel>Process instances ID: </ControlLabel> <FormControl type="text" readOnly value={this.state.definition.processInstanceIds.sort()} /> </FormGroup> <FormGroup controlId="EditMigration_kieId"> <ControlLabel>KIE Server ID: </ControlLabel> <FormControl type="text" readOnly value={this.state.definition.kieServerId} /> </FormGroup> <PageMigrationScheduler callbackUrl={this.state.definition.execution.callbackUrl} scheduledStartTime={ this.state.definition.execution.scheduledStartTime } onFieldChange={this.onExecutionFieldChange} onIsValid={this.onFormIsValid} /> </Form> ); return ( <div> <OverlayTrigger overlay={tooltipEdit} placement={"bottom"}> <Button bsStyle="link" onClick={this.openEditDialog}> <Icon type="fa" name="edit" /> </Button> </OverlayTrigger> <Modal show={this.state.showEditDialog} onHide={this.hideEditDialog} size="lg" > <Modal.Header> <Modal.CloseButton onClick={this.hideEditDialog} /> <Modal.Title>Edit Migration Definition</Modal.Title> </Modal.Header> <Modal.Body>{defaultBody}</Modal.Body> <Modal.Footer> <Button bsStyle="default" className="btn-cancel" onClick={this.hideEditDialog} > Cancel </Button> <Button bsStyle="primary" onClick={this.submit} disabled={!this.state.isValid} > Submit </Button> </Modal.Footer> </Modal> </div> ); } } PageEditMigrationDefinitionModal.propTypes = { migrationId: PropTypes.number.isRequired };
28.195946
103
0.58567
d5ca2058aee955f265e9450918a17660629fd0b8
638
js
JavaScript
spec/toThrowSpec.js
ricardowestphal/curso_teste_unitario
cd0dfbaee131789c9bfa7ff543ea21d6ed5c8cc9
[ "MIT" ]
null
null
null
spec/toThrowSpec.js
ricardowestphal/curso_teste_unitario
cd0dfbaee131789c9bfa7ff543ea21d6ed5c8cc9
[ "MIT" ]
null
null
null
spec/toThrowSpec.js
ricardowestphal/curso_teste_unitario
cd0dfbaee131789c9bfa7ff543ea21d6ed5c8cc9
[ "MIT" ]
null
null
null
/* Verifica se uma excecão é lançada por um método Não realiza a validação em detalhe o tipo da exceção lançada, apenas certifica que um erro ocorreu na execução da função. Deve ser utilizada quando deseja apenas certificar que um erro ocorreu, sem se preocupar com detalhes como tipo ou mensagem de erro. */ describe("Teste do toThrow", function() { it("Deve demonstrar o uso do toThrow", function() { function multiplicar() { numero * 10; } function somar(n1, n2) { return n1 + n2; } expect(multiplicar).toThrow(); expect(somar).not.toThrow(); }); });
27.73913
71
0.647335
d5ca8a6952d00e92f19cfd1e4267b5e8b69d620b
2,093
js
JavaScript
node_modules/serialport/lib/list-unix.js
palysoft/node-red-exploration
bf5de98dd1733ac5a0050cc6290d40845c90fe3d
[ "MIT" ]
null
null
null
node_modules/serialport/lib/list-unix.js
palysoft/node-red-exploration
bf5de98dd1733ac5a0050cc6290d40845c90fe3d
[ "MIT" ]
null
null
null
node_modules/serialport/lib/list-unix.js
palysoft/node-red-exploration
bf5de98dd1733ac5a0050cc6290d40845c90fe3d
[ "MIT" ]
1
2022-03-18T20:30:41.000Z
2022-03-18T20:30:41.000Z
'use strict'; var Promise = require('bluebird'); var childProcess = Promise.promisifyAll(require('child_process')); var fs = Promise.promisifyAll(require('fs')); var path = require('path'); function udevParser(output) { var udevInfo = output.split('\n').reduce(function(info, line) { if (!line || line.trim() === '') { return info; } var parts = line.split('=').map(function(part) { return part.trim(); }); info[parts[0].toLowerCase()] = parts[1]; return info; }, {}); var pnpId; if (udevInfo.devlinks) { udevInfo.devlinks.split(' ').forEach(function(path) { if (path.indexOf('/by-id/') === -1) { return } pnpId = path.substring(path.lastIndexOf('/') + 1); }); } var vendorId = udevInfo.id_vendor_id; if (vendorId && vendorId.substring(0, 2) !== '0x') { vendorId = '0x' + vendorId; } var productId = udevInfo.id_model_id; if (productId && productId.substring(0, 2) !== '0x') { productId = '0x' + productId; } return { comName: udevInfo.devname, manufacturer: udevInfo.id_vendor, serialNumber: udevInfo.id_serial, pnpId: pnpId, vendorId: vendorId, productId: productId }; } function checkPathAndDevice(path) { // get only serial port names if (!(/(tty(S|ACM|USB|AMA|MFD)|rfcomm)/).test(path)) { return false; } return fs.statAsync(path).then(function(stats) { return stats.isCharacterDevice(); }); } function lookupPort(file) { var udevadm = 'udevadm info --query=property -p $(udevadm info -q path -n ' + file + ')'; return childProcess.execAsync(udevadm).then(udevParser); } function listUnix(callback) { var dirName = '/dev'; fs.readdirAsync(dirName) .catch(function(err) { // if this directory is not found we just pretend everything is OK // TODO Depreciated this check? if (err.errno === 34) { return []; } throw err; }) .map(function(file) { return path.join(dirName, file) }) .filter(checkPathAndDevice) .map(lookupPort) .asCallback(callback); } module.exports = listUnix;
25.52439
91
0.626851
d5cce49e8d14cd80b0d56ccf19379a4fcc7b8ef0
830
js
JavaScript
preciosDescuentos.js
Diego-Lliteras/cursoPracticoJS
22228cf1a5d9dc21e56015e8fd3419c89c736169
[ "MIT" ]
null
null
null
preciosDescuentos.js
Diego-Lliteras/cursoPracticoJS
22228cf1a5d9dc21e56015e8fd3419c89c736169
[ "MIT" ]
null
null
null
preciosDescuentos.js
Diego-Lliteras/cursoPracticoJS
22228cf1a5d9dc21e56015e8fd3419c89c736169
[ "MIT" ]
null
null
null
// const precioOriginal = 120; // const descuento = 18; // const porcentajePrecioConDescuento = 100 - descuento; // const precioConDescuento = (precioOriginal * porcentajePrecioConDescuento)/100; // console.log({ // precioOriginal, // descuento, // porcentajePrecioConDescuento, // precioConDescuento, // }) function calcularPrecioConDescuento (precio, descuento) { return (precio * (100 - descuento))/ 100; } function onClickButtonPriceDiscount(){ const inputPrice = document.getElementById("InputPrice").value; const inputDiscount = document.getElementById("InputDiscount").value; const precioFinal = calcularPrecioConDescuento(inputPrice, inputDiscount); const resultP = document.getElementById("ResultPrice"); resultP.innerText = "El precio con descuento es de $" + precioFinal; }
31.923077
82
0.736145
d5cd98b2b5e4491e0487b21d3e3ad9c0aac08623
2,579
js
JavaScript
src/redux/Modules/links.js
Gronax/link-listing-app
869b0228c7938db9cfb992ed85b8b2d1a9fc00bd
[ "MIT" ]
null
null
null
src/redux/Modules/links.js
Gronax/link-listing-app
869b0228c7938db9cfb992ed85b8b2d1a9fc00bd
[ "MIT" ]
5
2021-03-10T01:17:06.000Z
2022-02-26T21:06:42.000Z
src/redux/Modules/links.js
Gronax/link-listing-app
869b0228c7938db9cfb992ed85b8b2d1a9fc00bd
[ "MIT" ]
null
null
null
import { toastr } from 'react-redux-toastr' import store from 'store2' import moment from 'moment' import sort from 'fast-sort' const initialState = {} const FORM_NAME = 'links_store' // Actions export const ADD_LINK = 'ADD_LINK' export const GET_LINKS = 'GET_LINKS' export const UPDATE_POINTS = 'UPDATE_POINTS' export const DELETE_LINK = 'DELETE_LINK' function CreateUUID() { return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ) } // Action Creators export function addLink (values) { const myStore = store.get(FORM_NAME) || [] let data = { id: CreateUUID(), points: 0, created_date: moment(), ...values, } // if created UUID is not unique create new one myStore.some((el) => (el.id === data.id)) ? data.id = CreateUUID() : data.id // if link name is not unique don't add it const isUniqueName = myStore.some((el) => (el.link_name === data.link_name)) if (!isUniqueName) { myStore.push(data) store.set(FORM_NAME, myStore) toastr.success('Success', `${data.link_name} added.`) } else { toastr.error('Error', 'Duplicated link name.') } return { type: ADD_LINK, payload: { links: myStore } } } export function getLinks (order = 'desc') { const myStore = store.get(FORM_NAME) || [] const pointsOrder = order === 'asc' ? { asc: u => u.points } : { desc: u => u.points } sort(myStore).by([ pointsOrder, { desc: u => u.created_date } ]) return { type: GET_LINKS, payload: { links: myStore } } } export function updatePoints (id, isUpvote) { let myStore = store.get(FORM_NAME) || [] const newStore = myStore.map(item => { let temp = Object.assign({}, item); if (temp.id === id) { isUpvote ? temp.points++ : temp.points-- } return temp }) store.set(FORM_NAME, newStore) return { type: UPDATE_POINTS, payload: { links: newStore } } } export function deleteLink (id) { let myStore = store.get(FORM_NAME) || [] myStore.map(item => { if (item.id === id) { toastr.success('Success', `${item.link_name} removed.`) } }) myStore = myStore.filter(obj => obj.id !== id) store.set(FORM_NAME, myStore) console.log('myStore', myStore) return { type: DELETE_LINK, payload: myStore } } export function linkReducer (state = initialState, action) { const {type, payload} = action switch (type) { case GET_LINKS: return payload.links default: return state } }
21.491667
88
0.620783
d5ceba192c3151b9eded3f0ef1f240ff6b0330df
902
js
JavaScript
node_modules/ix/targets/es2015/esm/add/asynciterable/of.js
iteaky/random
7de7795493b147743cea5657bdc48f7f63d1c50e
[ "Unlicense" ]
null
null
null
node_modules/ix/targets/es2015/esm/add/asynciterable/of.js
iteaky/random
7de7795493b147743cea5657bdc48f7f63d1c50e
[ "Unlicense" ]
7
2021-03-09T22:36:52.000Z
2022-02-18T14:28:36.000Z
node_modules/ix/targets/esnext/esm/add/asynciterable/of.js
iteaky/random
7de7795493b147743cea5657bdc48f7f63d1c50e
[ "Unlicense" ]
null
null
null
import { AsyncIterableX } from '../../asynciterable'; import { of as ofStatic } from '../../asynciterable/of'; AsyncIterableX.of = ofStatic; //# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImFkZC9hc3luY2l0ZXJhYmxlL29mLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxjQUFjLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQztBQUNyRCxPQUFPLEVBQUUsRUFBRSxJQUFJLFFBQVEsRUFBRSxNQUFNLHdCQUF3QixDQUFDO0FBRXhELGNBQWMsQ0FBQyxFQUFFLEdBQUcsUUFBUSxDQUFDIiwiZmlsZSI6ImFkZC9hc3luY2l0ZXJhYmxlL29mLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgQXN5bmNJdGVyYWJsZVggfSBmcm9tICcuLi8uLi9hc3luY2l0ZXJhYmxlJztcbmltcG9ydCB7IG9mIGFzIG9mU3RhdGljIH0gZnJvbSAnLi4vLi4vYXN5bmNpdGVyYWJsZS9vZic7XG5cbkFzeW5jSXRlcmFibGVYLm9mID0gb2ZTdGF0aWM7XG5cbmRlY2xhcmUgbW9kdWxlICcuLi8uLi9hc3luY2l0ZXJhYmxlJyB7XG4gIG5hbWVzcGFjZSBBc3luY0l0ZXJhYmxlWCB7XG4gICAgZXhwb3J0IGxldCBvZjogdHlwZW9mIG9mU3RhdGljO1xuICB9XG59Il19
150.333333
759
0.937916
d5cf27a7a1369d363debb083f78fd372333ece8b
72
js
JavaScript
PouchyStore.ios.js
ajiagahari/pouchy-store
4e166adad180ccf6afeefdd563f05ca68452bc04
[ "MIT" ]
10
2019-03-16T01:45:21.000Z
2021-06-15T03:00:02.000Z
PouchyStore.ios.js
ajiagahari/pouchy-store
4e166adad180ccf6afeefdd563f05ca68452bc04
[ "MIT" ]
9
2019-03-13T10:11:24.000Z
2021-01-15T04:51:39.000Z
PouchyStore.ios.js
ajiagahari/pouchy-store
4e166adad180ccf6afeefdd563f05ca68452bc04
[ "MIT" ]
5
2019-04-22T05:03:04.000Z
2021-03-19T08:51:42.000Z
import PouchyStore from './PouchyStoreRN'; export default PouchyStore;
18
42
0.805556
d5cf528a8e0198749be48dbcc32288d45e3c40b5
253
js
JavaScript
www/js/home.js
jerearth/ecg
ba7eedacb8b3cc680796fccac55a7f37de9f878c
[ "BSD-2-Clause" ]
null
null
null
www/js/home.js
jerearth/ecg
ba7eedacb8b3cc680796fccac55a7f37de9f878c
[ "BSD-2-Clause" ]
4
2021-11-19T20:18:05.000Z
2022-01-25T16:59:52.000Z
www/js/home.js
jerearth/ecg
ba7eedacb8b3cc680796fccac55a7f37de9f878c
[ "BSD-2-Clause" ]
null
null
null
const input = require('./js/input.js'); //init local storage with nulls localStorage.setItem('portpath',null) localStorage.setItem('port',null) setInterval(function listPorts() { input.listSerialPorts(); // setTimeout(listPorts, 2000); }, 2000);
23
40
0.727273
d5d06a98642acfa85047d4f7dbbc277a09fd6c83
1,233
js
JavaScript
resources/js/actions/signupActions.js
Sambreezy/breezy_pastquestion_laravel
0a0726de27bb50c064572efabccdaba69582c423
[ "MIT" ]
null
null
null
resources/js/actions/signupActions.js
Sambreezy/breezy_pastquestion_laravel
0a0726de27bb50c064572efabccdaba69582c423
[ "MIT" ]
1
2021-02-02T16:51:25.000Z
2021-02-02T16:51:25.000Z
resources/js/actions/signupActions.js
Sambreezy/breezy_pastquestion_laravel
0a0726de27bb50c064572efabccdaba69582c423
[ "MIT" ]
null
null
null
import { SIGNUP_USER, SIGNUP_USER_TRUE } from './types'; import { SIGNUP_VALUE } from './types'; import Swal from 'sweetalert2'; import axios from 'axios'; export const signupUser = ( name, email, phone, password, password_confirmation ) => { let data = { name, email, phone, password, password_confirmation }; return dispatch => { dispatch({ type: SIGNUP_USER_TRUE, payload: true }); axios .post('https://pastquestions.xyz/api/v1/auth/register', data) .then(res => { dispatch({ type: SIGNUP_USER, payload: res.data.message }); //Swal.fire({ //type: 'success', //text: res.data ? res.data.message : 'Signed Up Successfully' //}); window.location.replace('/login'); }) .catch(err => { Swal.fire({ type: 'error', title: 'Oops...', text: err.response ? err.response.data.message : 'Something went wrong', confirmButtonText: 'Ok' }); }); }; }; export const signupValue = payload => { return dispatch => { dispatch({ type: SIGNUP_VALUE, payload: payload }); }; };
20.898305
70
0.536902
d5d106967a7450d1c832e9ae3c4299214df49b5a
2,360
js
JavaScript
commands/cancel.js
TheCodeSinger/equibot
4e199d7b7d8c6f68f38a7f56034f27915a16824b
[ "MIT" ]
1
2020-08-01T00:38:35.000Z
2020-08-01T00:38:35.000Z
commands/cancel.js
dclose73/equibot
59fc8009568b2c294733aab5673636601ecac32b
[ "MIT" ]
23
2020-05-19T01:01:19.000Z
2020-06-04T06:55:04.000Z
commands/cancel.js
dclose73/equibot
59fc8009568b2c294733aab5673636601ecac32b
[ "MIT" ]
2
2020-09-01T20:14:08.000Z
2021-07-29T19:03:16.000Z
exports.run = async (client, message, args, level) => { // eslint-disable-line no-unused-vars try { const lotto = client.lotto; const config = client.config; const isBotAdmin = client.levelCache['Bot Support'] <= level; if (!lotto) { return message.reply('No active lotto. Why don\'t you start one?'); } if (message.author !== lotto.starter && !isBotAdmin) { return message.reply('Only the starter (or bot admin) can cancel a lotto.'); } const output = { 'embed': { 'color': config.colors.default, 'description': 'It appears that ' + lotto.starter.toString() + ' got cold feet and cancelled the lotto.', 'footer': { 'text': 'They probably deserve to be TP\'d or forked or some other innocous but socially approved form of hazing.' } } }; message.reply('Are you sure you want to cancel this lotto? [yes/no]') .then(() => { message.channel .awaitMessages(response => (response.author.username === message.author.username), { max: 1, time: 7000, // 7 seconds errors: ['time'], } ) .then((collected) => { switch(collected.first().cleanContent.toLowerCase()) { case 'yes': case 'y': lotto.channel.send(output); // Must use the original reference when setting null. client.lotto = null; client.updateGameStats('lotto', 'canceled', lotto.starter.id); break; case 'no': case 'n': message.reply('Phew! Aren\'t you glad I asked!'); break; default: message.reply('Not sure what you mean by that response. If you still need to cancel, ask me again.'); } }) .catch((error) => { client.logger.error(`Error confirming 'cancel' command: ${error}`); message.reply('Done waiting. If you still need to cancel, ask me again.'); }); }); } catch (e) { client.logger.error(`Error executing 'cancel' command: ${e}`); } }; exports.conf = { enabled: true, guildOnly: true, aliases: [], permLevel: 'User', }; exports.help = { name: 'cancel', };
30.649351
124
0.532203
d5d1b74a9e12c719099265ea7ed19696b1597283
237
js
JavaScript
webpack.config.js
JesusGuerrero/MAHRIO-LMS
a82de7f9af74d30d86860935e1277ee6a76d390e
[ "ISC" ]
null
null
null
webpack.config.js
JesusGuerrero/MAHRIO-LMS
a82de7f9af74d30d86860935e1277ee6a76d390e
[ "ISC" ]
null
null
null
webpack.config.js
JesusGuerrero/MAHRIO-LMS
a82de7f9af74d30d86860935e1277ee6a76d390e
[ "ISC" ]
null
null
null
switch( process.env.NODE_ENV ) { case 'PROD': case 'prod': case 'PRODUCTION': case 'production': module.exports = require('./config/webpack.prod'); break; default: module.exports = require('./config/webpack.dev'); }
23.7
54
0.64557
d5d21d9d95407b2cbf7519ae9fa085fed5fb3135
66
js
JavaScript
core/js/loaders/core_body_js_loader.js
skoolbus39/dcf
0d21ed7eabe618bd0f21200f9556a9a5aa1b39fb
[ "BSD-3-Clause" ]
null
null
null
core/js/loaders/core_body_js_loader.js
skoolbus39/dcf
0d21ed7eabe618bd0f21200f9556a9a5aa1b39fb
[ "BSD-3-Clause" ]
null
null
null
core/js/loaders/core_body_js_loader.js
skoolbus39/dcf
0d21ed7eabe618bd0f21200f9556a9a5aa1b39fb
[ "BSD-3-Clause" ]
null
null
null
// lazy load const dcf_lazyload = require('../app/lazy-load.js');
22
52
0.681818
d5d402062347392becf5fb875df7f936095fe038
2,026
js
JavaScript
config.js
RutujaMuppid1997/API
f6e329de7e33f57e9a433b67133895b9a8afd51c
[ "MIT" ]
null
null
null
config.js
RutujaMuppid1997/API
f6e329de7e33f57e9a433b67133895b9a8afd51c
[ "MIT" ]
null
null
null
config.js
RutujaMuppid1997/API
f6e329de7e33f57e9a433b67133895b9a8afd51c
[ "MIT" ]
null
null
null
require('dotenv').config(); module.exports = { port: process.env[`${process.env.NODE_ENV}_PORT`], databaseHost: process.env[`${process.env.NODE_ENV}_DB_HOST`], databaseUser: process.env[`${process.env.NODE_ENV}_DB_USER`], databasePassword: process.env[`${process.env.NODE_ENV}_DB_PASSWORD`], databaseName: process.env[`${process.env.NODE_ENV}_DB_NAME`], databaseInitial: process.env[`${process.env.NODE_ENV}_DB_INITIAL`], databasePort: process.env[`${process.env.NODE_ENV}_DB_PORT`], tokenkey: process.env[`${process.env.NODE_ENV}_TOKEN_KEY`], bodyEncryption: false, cryptokey: process.env[`${process.env.NODE_ENV}_CRYPTO_KEY`], minContribution: process.env[`${process.env.NODE_ENV}_MINI_CONTRIBUTION`], yBTokenPrice: process.env[`${process.env.NODE_ENV}_YB_TOKEN_PRICE`], yBMaxContri: process.env[`${process.env.NODE_ENV}_YB_MAX_CONTRI`], yBSupply: process.env[`${process.env.NODE_ENV}_YB_SUPPLY`], yCashTokenPrice: process.env[`${process.env.NODE_ENV}_YCASH_TOKEN_PRICE`], yCashMaxContri: process.env[`${process.env.NODE_ENV}_YCASH_MAX_CONTRI`], yCashSupply: process.env[`${process.env.NODE_ENV}_YCASH_SUPPLY`], yBDepositAddress: process.env[`${process.env.NODE_ENV}_YB_DEPOSIT_ADDRESS`], yCashDepositAddress: process.env[`${process.env.NODE_ENV}_YCASH_DEPOSIT_ADDRESS`], yBLiquidityDepositAddress: process.env[`${process.env.NODE_ENV}_YB_LIQUIDITY_DEPOSIT_ADDRESS`], yCashLiquidityDepositAddress: process.env[`${process.env.NODE_ENV}_YCASH_LIQUIDITY_DEPOSIT_ADDRESS`], uniswapRouterAddress: process.env[`${process.env.NODE_ENV}_UNISWAP_ROUTER_ADDRESS`], yBCompoundInterfaceAddress: process.env[`${process.env.NODE_ENV}_YB_COMPOUND_INTERFACE`], yBUniswapInterfaceAddress: process.env[`${process.env.NODE_ENV}_YB_UNISWAP_INTERFACE`], web3Provider: process.env[`${process.env.NODE_ENV}_WEB3_PROVIDER`], web3Network: process.env[`${process.env.NODE_ENV}_WEB3_NETWORK`], recaptchaSecret: process.env[`${process.env.NODE_ENV}_RECAPTCHA_SECRET`], };
53.315789
78
0.76999
d5d621a06680b5fc497006d83de0f4de07f93042
1,967
js
JavaScript
src/pages/contact.js
benjamin25116/gatsby-netlify-cms
a497b3c792630b25c91b88c9140852560ce0f927
[ "RSA-MD" ]
null
null
null
src/pages/contact.js
benjamin25116/gatsby-netlify-cms
a497b3c792630b25c91b88c9140852560ce0f927
[ "RSA-MD" ]
null
null
null
src/pages/contact.js
benjamin25116/gatsby-netlify-cms
a497b3c792630b25c91b88c9140852560ce0f927
[ "RSA-MD" ]
null
null
null
import React from "react" import Layout from "../components/layout" import Seo from "../components/seo" const Contact = () => { return ( <Layout> <Seo title="Contact Us" /> <h1>Contact Us</h1> <address> New Covenant Community 4-2, <br /> Jalan 14/48a, Sentulraya Boulevard <br /> 51000, Kuala Lumpur, Malaysia. </address> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3983.65321998491!2d101.6897877148705!3d3.18556949768058!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x31cc480ed1bf511f%3A0x6b0c2eb036cbfae0!2sNew%20Covenant%20Community%20Church!5e0!3m2!1sen!2smy!4v1610178284532!5m2!1sen!2smy" width="400" height="300" frameborder="0" style={{ border: 0 }} allowFullScreen="" aria-hidden="false" // tabindex="0" title="Map to New Covenant Community Church" ></iframe> <p> We'd love to hear from you. Please use the form below to send us your enquiry. </p> <form name="contact" method="POST" action="/contact-thank-you" data-netlify="true" > <input name="form-name" value="contact" type="hidden" /> <p> <label> Your Name <input type="text" name="name" placeholder="Your Name" /> </label> </p> <p> <label> Your Email <input type="text" name="email" placeholder="Your Email" /> </label> </p> <p> <label> Subject <input type="text" name="subject" placeholder="Subject" /> </label> </p> <p> <label> Your Message <textarea name="message" placeholder="Your message" /> </label> </p> <button type="submit">Send</button> </form> </Layout> ) } export default Contact
28.1
299
0.540925
d5d6a91e1bddea2c84c5e2846be1f37ff56242cd
15,702
js
JavaScript
app/modules/QRCodeScanner/QRCodeScannerScreen.js
belyokhin/trusteeWallet
31460e68bea08653cff0667d21c6d9e1f005ccfa
[ "MIT" ]
null
null
null
app/modules/QRCodeScanner/QRCodeScannerScreen.js
belyokhin/trusteeWallet
31460e68bea08653cff0667d21c6d9e1f005ccfa
[ "MIT" ]
2
2021-01-27T19:50:21.000Z
2021-04-30T06:02:51.000Z
app/modules/QRCodeScanner/QRCodeScannerScreen.js
belyokhin/trusteeWallet
31460e68bea08653cff0667d21c6d9e1f005ccfa
[ "MIT" ]
2
2021-02-17T00:01:48.000Z
2021-02-26T15:03:36.000Z
/** * @version 0.9 */ import React, { Component } from 'react' import { connect } from 'react-redux' import { View, Dimensions, Text, TouchableOpacity } from 'react-native' import QRCodeScanner from 'react-native-qrcode-scanner' import Navigation from '../../components/navigation/Navigation' import NavStore from '../../components/navigation/NavStore' import { showModal } from '../../appstores/Stores/Modal/ModalActions' import { strings } from '../../services/i18n' import { setSendData } from '../../appstores/Stores/Send/SendActions' import _ from 'lodash' import copyToClipboard from '../../services/UI/CopyToClipboard/CopyToClipboard' import { decodeTransactionQrCode } from '../../services/UI/Qr/QrScan' import Log from '../../services/Log/Log' import firebase from 'react-native-firebase' import UpdateOneByOneDaemon from '../../daemons/back/UpdateOneByOneDaemon' import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' import { openQrGallery } from '../../services/UI/Qr/QrGallery' const SCREEN_HEIGHT = Dimensions.get('window').height const SCREEN_WIDTH = Dimensions.get('window').width console.disableYellowBox = true class QRCodeScannerScreen extends Component { componentDidMount() { this._onFocusListener = this.props.navigation.addListener('didFocus', (payload) => { this.setState({}) try { this.scanner.reactivate() } catch { } }) } async onSuccess(param) { try { const { account: oldAccount, cryptoCurrency: oldCurrency, currencyCode, type, inputType } = this.props.qrCodeScanner.config if (type === 'CASHBACK_LINK') { setSendData({ isCashbackLink: true, qrCashbackLink: param.data }) NavStore.goNext('CashbackScreen') return } const res = await decodeTransactionQrCode(param, currencyCode) if (type === 'MAIN_SCANNER') { const { selectedWallet } = this.props.main const { cryptoCurrencies, accountStore } = this.props let cryptoCurrency if (typeof res.data.currencyCode !== 'undefined' && res.data.currencyCode) { try { cryptoCurrency = _.find(cryptoCurrencies, { currencyCode: res.data.currencyCode }) } catch (e) { e.message += ' on _.find by cryptoCurrencies ' throw e } } let account = JSON.parse(JSON.stringify(accountStore.accountList)) account = account[selectedWallet.walletHash][res.data.currencyCode] if (res.status !== 'success') { let tmp = res.data.parsedUrl || res.data.address copyToClipboard(tmp) showModal({ type: 'INFO_MODAL', icon: true, title: strings('modal.qrScanner.success.title'), description: strings('modal.qrScanner.success.description') + ' ' + tmp }, () => { NavStore.goBack(null) }) return } if (typeof cryptoCurrency === 'undefined') { showModal({ type: 'YES_NO_MODAL', icon: 'INFO', title: strings('modal.exchange.sorry'), description: strings('modal.tokenNotAdded.description'), noCallback: () => { this.setState({}) try { this.scanner.reactivate() } catch { } } }, () => { NavStore.goNext('AddAssetScreen') }) return } if (+cryptoCurrency.isHidden) { showModal({ type: 'YES_NO_MODAL', icon: 'INFO', title: strings('modal.exchange.sorry'), description: strings('modal.tokenHidden.description'), noCallback: () => { this.setState({}) try { this.scanner.reactivate() } catch { } } }, () => { NavStore.goNext('AddAssetScreen') }) return } setSendData({ disabled: typeof res.data.needToDisable !== 'undefined' && !!(+res.data.needToDisable), address: res.data.address, value: res.data.amount.toString(), account: account, cryptoCurrency: cryptoCurrency, comment: res.data.label, description: strings('send.description'), useAllFunds: false, type }) NavStore.goNext('SendScreen') } else if (type === 'ADD_CUSTOM_TOKEN_SCANNER') { setSendData({ isToken: true, address: res.data.address || res.data.parsedUrl }) NavStore.goNext('AddCustomTokenScreen') } else if (type === 'SEND_SCANNER') { if (res.status === 'success' && res.data.currencyCode === currencyCode) { setSendData({ disabled: typeof res.data.needToDisable !== 'undefined' && !!(+res.data.needToDisable), address: res.data.address, value: res.data.amount.toString(), account: oldAccount, cryptoCurrency: oldCurrency, inputType, comment: res.data.label, description: strings('send.description'), useAllFunds: false, type }) NavStore.goNext('SendScreen') } else if (res.status === 'success' && res.data.currencyCode !== currencyCode) { showModal({ type: 'INFO_MODAL', icon: false, title: strings('modal.qrScanner.error.title'), description: strings('modal.qrScanner.error.description') }, () => { try { this.scanner.reactivate() } catch { } }) } else { setSendData({ disabled: false, address: res.data.parsedUrl, value: '', account: oldAccount, cryptoCurrency: oldCurrency, inputType, description: strings('send.description'), useAllFunds: false, type }) NavStore.goNext('SendScreen') } } } catch (e) { Log.err('QRCodeScanner.onSuccess error ' + e.message) showModal({ type: 'INFO_MODAL', icon: 'INFO', title: strings('modal.exchange.sorry'), description: strings('tradeScreen.modalError.serviceUnavailable') }, () => { NavStore.goBack() }) } } async onOpenGallery() { try { const res = await openQrGallery() if (res) { this.onSuccess(res) } } catch (e) { let message = strings('tradeScreen.modalError.serviceUnavailable') let goBack = true if (e.message === 'NOT_FOUND') { message = strings('tradeScreen.modalError.qrNotFoundInFile') goBack = false } else { Log.err('QRCodeScanner.onOpenGallery error ' + e.message) } showModal({ type: 'INFO_MODAL', icon: 'INFO', title: strings('modal.exchange.sorry'), description: message }, () => { if (goBack) { NavStore.goBack() } }) } } renderOpenGallery() { return ( <TouchableOpacity onPress={this.onOpenGallery.bind(this)}> <View style={{ paddingLeft: 23, paddingRight:23 }} > <MaterialCommunityIcons name="file-find" size={24} color="#855eab"/> </View> </TouchableOpacity> ) } render() { UpdateOneByOneDaemon.pause() firebase.analytics().setCurrentScreen('QRCodeScannerScreen.index') return ( <View style={{ flex: 1, backgroundColor: 'transparent' }}> <Navigation RightComponent={this.renderOpenGallery.bind(this)} /> <QRCodeScanner ref={(node) => { this.scanner = node }} showMarker onRead={this.onSuccess.bind(this)} cameraStyle={{ height: SCREEN_HEIGHT }} topViewStyle={{ height: 0, flex: 0 }} bottomViewStyle={{ height: 0, flex: 0 }} customMarker={ <View style={styles.rectangleContainer}> <View style={styles.topOverlay}> </View> <View style={{ flexDirection: 'row' }}> <View style={styles.leftAndRightOverlay}/> <View style={styles.rectangle}> <View style={styles.rectangle__topLeft}> <View style={styles.vertical}></View> <View style={{ ...styles.horizontal, ...styles.rectangle__top_fix }}></View> </View> <View style={styles.rectangle__topRight}> <View style={styles.vertical}></View> <View style={{ ...styles.horizontal, ...styles.rectangle__top_fix }}></View> </View> <View style={styles.rectangle__bottomLeft}> <View style={{ ...styles.horizontal, ...styles.rectangle__bottom_fix }}></View> <View style={styles.vertical}></View> </View> <View style={styles.rectangle__bottomRight}> <View style={{ ...styles.horizontal, ...styles.rectangle__bottom_fix }}></View> <View style={styles.vertical}></View> </View> </View> <View style={styles.leftAndRightOverlay}/> </View> <View style={styles.bottomOverlay}> <Text style={styles.text}> {strings('qrScanner.line1')} </Text> <Text style={styles.text}> {strings('qrScanner.line2')} </Text> </View> </View> } /> </View> ) } } const mapStateToProps = (state) => { return { main: state.mainStore, cryptoCurrencies: state.currencyStore.cryptoCurrencies, qrCodeScanner: state.qrCodeScannerStore, sendStore: state.sendStore, accountStore: state.accountStore } } const mapDispatchToProps = (dispatch) => { return { dispatch } } export default connect(mapStateToProps, mapDispatchToProps)(QRCodeScannerScreen) const overlayColor = 'transparent' // this gives us a black color with a 50% transparency const rectDimensions = SCREEN_WIDTH * 0.65 // this is equivalent to 255 from a 393 device width const rectBorderWidth = 0 // this is equivalent to 2 from a 393 device width const rectBorderColor = '#b995d8' const scanBarWidth = SCREEN_WIDTH * 0.46 // this is equivalent to 180 from a 393 device width const scanBarHeight = SCREEN_WIDTH * 0.0025 // this is equivalent to 1 from a 393 device width const scanBarColor = '#22ff00' const styles = { rectangleContainer: { flex: 1, width: '100%', alignItems: 'center', justifyContent: 'center', backgroundColor: 'transparent' }, gradient: { flex: 1, width: '100%' }, rectangle: { position: 'relative', height: rectDimensions, width: rectDimensions, borderWidth: rectBorderWidth, borderColor: rectBorderColor, alignItems: 'center', justifyContent: 'center', backgroundColor: 'transparent', zIndex: 1 }, vertical: { width: 30, height: 7, borderRadius: 3, backgroundColor: '#fff' }, horizontal: { height: 30, width: 7, borderRadius: 3, backgroundColor: '#fff' }, block__text: { flex: 1, fontFamily: 'SFUIDisplay-Regular', fontSize: 19, color: '#404040' }, rectangle__topLeft: { position: 'absolute', top: -5, left: -5 }, rectangle__top_fix: { position: 'relative', top: -5 }, rectangle__bottom_fix: { position: 'relative', bottom: -5 }, rectangle__topRight: { alignItems: 'flex-end', position: 'absolute', top: -5, right: -6 }, rectangle__bottomLeft: { position: 'absolute', bottom: -5, left: -5 }, rectangle__bottomRight: { alignItems: 'flex-end', position: 'absolute', bottom: -3, right: -6 }, topOverlay: { flex: 1, width: '100%', backgroundColor: overlayColor, justifyContent: 'center', alignItems: 'center' }, bottomOverlay: { flex: 1, width: '100%', marginTop: 20, backgroundColor: overlayColor }, leftAndRightOverlay: { flex: 1, height: '100%', backgroundColor: overlayColor }, scanBar: { width: scanBarWidth, height: scanBarHeight, backgroundColor: scanBarColor }, text: { paddingLeft: 30, paddingRight: 30, textAlign: 'center', fontSize: 16, fontFamily: 'SFUIDisplay-Regular', color: '#e3e6e9' } }
34.662252
119
0.460196
d5d6bf46a169f37a71b5ebbd44ea25deefc3f8e0
1,669
js
JavaScript
public/javascripts/inkling.js
nicholasf/inkling
40d2a76e11df2b5ef6ec802fefbeb920c35a77c7
[ "MIT", "Ruby", "Unlicense" ]
2
2015-11-05T15:22:02.000Z
2019-05-29T01:49:45.000Z
public/javascripts/inkling.js
nicholasf/inkling
40d2a76e11df2b5ef6ec802fefbeb920c35a77c7
[ "MIT", "Ruby", "Unlicense" ]
null
null
null
public/javascripts/inkling.js
nicholasf/inkling
40d2a76e11df2b5ef6ec802fefbeb920c35a77c7
[ "MIT", "Ruby", "Unlicense" ]
null
null
null
//custom js for the content tree in the CMS $(document).ready(function(){ $("li.tree-item span").droppable({ tolerance : "touch", hoverClass : "tree-hover", drop : function(event, ui){ var dropped = ui.draggable; dropped.css({top: 0, left: 0}); var me = $(this).parent(); if(me == dropped) return; var subbranch = $(me).children("ul"); if(subbranch.size() == 0) { me.find("span").after("<ul></ul>"); subbranch = me.find("ul"); } var oldParent = dropped.parent(); subbranch.eq(0).append(dropped); var oldBranches = $("li", oldParent); var newParent = me.attr('id') var child = dropped.attr('id') $.post("/inkling/update_tree", {new_parent: newParent, child: child}); } }); $("li.tree-item").draggable({ opacity: 0.5, revert: true }); $(".toggle_content_tree").live("click", function(){ $(this).parent().children(".content_tree").toggle(); }) $(".toggle_content_form").live("click", function(){ $(this).parent().children(".content_form").toggle(); }) }); function submitForm(selectElement){ if (selectElement.options[selectElement.selectedIndex].value == "") return; selectElement.form.submit(); } //requests specified path to controller#action for a content object function getOperation(selectElement){ var path = selectElement.options[selectElement.selectedIndex].value if (path == "") return; document.location = path; }
28.775862
82
0.55003
d5d83fa9db00a9c09417cd60167e457db769bdf2
3,609
js
JavaScript
test/bigtest/tests/duplicate-amendment-modal-test.js
CalamityC/ui-licenses
8541630371a1160f77f14c21e0d36a314a1bb977
[ "Apache-2.0" ]
null
null
null
test/bigtest/tests/duplicate-amendment-modal-test.js
CalamityC/ui-licenses
8541630371a1160f77f14c21e0d36a314a1bb977
[ "Apache-2.0" ]
269
2018-11-15T14:31:53.000Z
2022-03-18T14:35:24.000Z
test/bigtest/tests/duplicate-amendment-modal-test.js
CalamityC/ui-licenses
8541630371a1160f77f14c21e0d36a314a1bb977
[ "Apache-2.0" ]
6
2018-10-18T12:59:39.000Z
2021-01-20T16:53:13.000Z
import React from 'react'; import { beforeEach, describe, it } from '@bigtest/mocha'; import chai from 'chai'; import spies from 'chai-spies'; import { mountWithContext } from '../helpers/mountWithContext'; import DuplicateAmendmentModalInteractor from '../interactors/duplicate-amendment-modal'; import DuplicateAmendmentModal from '../../../src/components/DuplicateAmendmentModal'; const modalInteractor = new DuplicateAmendmentModalInteractor(); chai.use(spies); const { expect, spy } = chai; const onClone = spy(() => Promise.resolve()); const onClose = spy(() => Promise.resolve()); describe('Duplicate amendment modal tests', () => { describe('Rendering duplicate amendment modal', () => { beforeEach(async function () { await mountWithContext( <DuplicateAmendmentModal onClone={onClone} onClose={onClose} /> ); }); it('renders the modal', () => { expect(modalInteractor.isDuplicateModalPresent).to.be.true; }); it('renders selectAll checkbox at the top', () => { expect(modalInteractor.checkBoxList(0).label).to.equal('selectAll'); }); it('renders amendmentInfo checkbox', () => { expect(modalInteractor.checkBoxList(1).label).to.equal('amendmentInfo'); }); it('renders amendmentDateInfo checkbox', () => { expect(modalInteractor.checkBoxList(2).label).to.equal('amendmentDateInfo'); }); it('renders coreDocs checkbox', () => { expect(modalInteractor.checkBoxList(3).label).to.equal('coreDocs'); }); it('renders terms checkbox', () => { expect(modalInteractor.checkBoxList(4).label).to.equal('terms'); }); it('renders supplementaryDocs checkbox', () => { expect(modalInteractor.checkBoxList(5).label).to.equal('supplementaryDocs'); }); describe('Selecting some fields to duplicate', () => { describe('Selecting all', () => { beforeEach(async function () { await modalInteractor.checkBoxList(0).click(); await modalInteractor.clickSaveAndClose(); }); it('sends correct duplication params', () => { expect(onClone).to.have.been.called.with({ amendmentDateInfo: true, amendmentInfo: true, coreDocs: true, supplementaryDocs: true, terms: true }); }); }); describe('Selecting amendmentDateInfo and supplementaryDocs checkboxes', () => { beforeEach(async function () { await modalInteractor.checkBoxList(2).click(); await modalInteractor.checkBoxList(5).click(); await modalInteractor.clickSaveAndClose(); }); it('sends correct duplication params', () => { const expectedPayload = { amendmentDateInfo: true, supplementaryDocs:true }; expect(onClone).to.have.been.called.with(expectedPayload); }); }); describe('Selecting amendmentInfo, coreDocs and terms checkboxes', () => { beforeEach(async function () { await modalInteractor.checkBoxList(1).click(); await modalInteractor.checkBoxList(3).click(); await modalInteractor.checkBoxList(4).click(); await modalInteractor.clickSaveAndClose(); }); it('sends correct duplication params', () => { const expectedPayload = { amendmentInfo: true, coreDocs: true, terms: true }; expect(onClone).to.have.been.called.with(expectedPayload); }); }); }); }); });
31.657895
89
0.613743
d5d93d1dfc3ebfe75d693aa63756fa95189361c5
3,526
js
JavaScript
src/background/messenger.js
alexanderby/mova
09ed9f18f2103106466ce885ba53ec0db49944a6
[ "MIT" ]
5
2020-02-21T16:35:05.000Z
2022-02-04T20:06:21.000Z
src/background/messenger.js
alexanderby/mova
09ed9f18f2103106466ce885ba53ec0db49944a6
[ "MIT" ]
null
null
null
src/background/messenger.js
alexanderby/mova
09ed9f18f2103106466ce885ba53ec0db49944a6
[ "MIT" ]
1
2022-02-27T21:46:39.000Z
2022-02-27T21:46:39.000Z
/** @type {Set<chrome.runtime.Port>} */ const tabPorts = new Set(); /** @type {Set<number>} */ const connectedTabs = new Set(); /** * @param {number} tabId * @returns {boolean} */ function isTabConnected(tabId) { return connectedTabs.has(tabId); } /** * @typedef Message * @property {string} type * @property {any} data */ /** * @typedef {(msg: Message, sendMessage: (msg: Message) => void) => void} PortMessageListener */ /** @type {Set<PortMessageListener>} */ const popupListeners = new Set(); /** * @param {PortMessageListener} listener */ function onPopupMessage(listener) { popupListeners.add(listener); } /** @type {Set<PortMessageListener>} */ const tabListeners = new Set(); /** * @param {PortMessageListener} listener */ function onTabMessage(listener) { tabListeners.add(listener); } /** @type {Set<PortMessageListener>} */ const editorListeners = new Set(); /** * @param {PortMessageListener} listener */ function onEditorMessage(listener) { editorListeners.add(listener); } /** * @typedef {(sendMessage: (msg: Message) => void) => void} TabConnectListener */ /** @type {Set<TabConnectListener>} */ const tabConnectListeners = new Set(); /** * @param {TabConnectListener} listener */ function onTabConnect(listener) { tabConnectListeners.add(listener); } /** * @param {chrome.runtime.Port} port * @returns {(message: Message) => void} */ function createPortCallback(port) { return (message) => port.postMessage(message); } /** * @param {Message} data */ function sendToAllTabs(data) { tabPorts.forEach((port) => port.postMessage(data)); } /** * @param {chrome.runtime.Port} port */ function connectTab(port) { const tabId = port.sender.tab.id; if (port.sender.frameId === 0) { connectedTabs.add(tabId); } tabPorts.add(port); port.onDisconnect.addListener(() => { tabPorts.delete(port); if (port.sender.frameId === 0) { connectedTabs.delete(tabId); } }); port.onMessage.addListener((message) => { const sendMessage = createPortCallback(port); tabListeners.forEach((listener) => listener(message, sendMessage)); }); const sendMessage = createPortCallback(port); tabConnectListeners.forEach((listener) => listener(sendMessage)); port.onMessage.addListener(({type, data}) => { if (type === 'get-sender-tab-url') { const requestId = data; port.postMessage({ type: 'sender-tab-url', data: { id: requestId, url: port.sender.tab.url, }, }); } }); } /** * @param {chrome.runtime.Port} port */ function connectPopup(port) { port.onMessage.addListener((message) => { const sendMessage = createPortCallback(port); popupListeners.forEach((listener) => listener(message, sendMessage)); }); } /** * @param {chrome.runtime.Port} port */ function connectEditor(port) { port.onMessage.addListener((message) => { const sendMessage = createPortCallback(port); editorListeners.forEach((listener) => listener(message, sendMessage)); }); } const connectors = { 'tab': connectTab, 'popup': connectPopup, 'editor': connectEditor, }; chrome.runtime.onConnect.addListener((port) => connectors[port.name](port)); export default { isTabConnected, onPopupMessage, onTabConnect, onTabMessage, onEditorMessage, sendToAllTabs, };
22.0375
93
0.627623
d5d979f88039a6caff24659344d7c243dc16a4a0
2,089
js
JavaScript
src/core/local-server/database/models/Method.js
douglashipolito/occ-tools
643666846bfb436b2a17f7290717b75f83b2147d
[ "MIT" ]
8
2019-11-15T13:20:46.000Z
2020-07-28T13:08:29.000Z
src/core/local-server/database/models/Method.js
douglashipolito/occ-tools
643666846bfb436b2a17f7290717b75f83b2147d
[ "MIT" ]
25
2019-11-07T19:29:31.000Z
2021-05-06T16:58:05.000Z
src/core/local-server/database/models/Method.js
douglashipolito/occ-tools
643666846bfb436b2a17f7290717b75f83b2147d
[ "MIT" ]
4
2020-05-15T13:54:21.000Z
2021-05-31T12:43:42.000Z
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { const Method = sequelize.define('Method', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, unique: true, autoIncrement: true, field: 'met_id' }, summary: { type: DataTypes.TEXT, allowNull: true, field: 'met_summary' }, operationId: { type: DataTypes.TEXT, allowNull: false, field: 'met_operationId' }, description: { type: DataTypes.TEXT, allowNull: true, field: 'met_description' }, produces: { type: DataTypes.TEXT, allowNull: false, defaultValue: 'application/json', field: 'met_produces' }, methodTypeId: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'mty_method_type', key: 'mty_id' }, field: 'mty_id' }, schemaId: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'sch_schema', key: 'sch_id' }, field: 'sch_id' }, createdAt: { type: DataTypes.TEXT, allowNull: true, field: 'met_created_at' }, updatedAt: { type: DataTypes.TEXT, allowNull: true, field: 'met_updated_at' } }, { tableName: 'met_method', createdAt: 'met_created_at', updatedAt: 'met_updated_at' }); Method.associate = function (models) { models.Method.belongsTo(models.MethodType, { onDelete: "CASCADE", foreignKey: { name: 'methodTypeId', allowNull: false } }); models.Method.belongsTo(models.Schema, { onDelete: "CASCADE", foreignKey: { name: 'schemaId', allowNull: false } }); models.Method.hasMany(models.AllowedParameters, { foreignKey: { name: 'id', allowNull: false } }); models.Method.hasOne(models.Descriptor, { foreignKey: { name: 'id', allowNull: false } }); }; return Method; };
20.480392
53
0.549545
d5da633b9d65fe518330ad89f192317afc7ca7e8
2,347
js
JavaScript
src/locale/zh_CN/Basic/AdminPerson.js
cleverwo/Lis-client
4ea7bb07c6d7a19f43dc378cddb33b3ba9c090cf
[ "MIT" ]
null
null
null
src/locale/zh_CN/Basic/AdminPerson.js
cleverwo/Lis-client
4ea7bb07c6d7a19f43dc378cddb33b3ba9c090cf
[ "MIT" ]
null
null
null
src/locale/zh_CN/Basic/AdminPerson.js
cleverwo/Lis-client
4ea7bb07c6d7a19f43dc378cddb33b3ba9c090cf
[ "MIT" ]
null
null
null
export default { 'adminperson.username': '登录名', 'adminperson.password': '密码', 'adminperson.password.again': '确认密码', 'adminperson.name': '姓名', 'adminperson.certType': '证件类型', 'adminperson.certType.idcard': '身份证', 'adminperson.certType.passport': '护照', 'adminperson.certType.other': '其他', 'adminperson.address': '地址', 'adminperson.createTime': '注册时间', 'adminperson.lastLoginTime': '最后登录时间', 'adminperson.cellPhone': '手机', 'adminperson.phone': '电话', 'adminperson.wechat': '微信', 'adminperson.qq': 'qq', 'adminperson.email': '邮箱', 'adminperson.portrait': '头像', 'adminperson.please.input.username': '请输入登录名', 'adminperson.please.input.name': '请输入姓名', 'adminperson.please.input.password': '请输入密码', 'adminperson.please.input.certNum': '请输入证件号', 'adminperson.please.input.address': '请输入地址', 'adminperson.please.input.email': '请输入邮箱地址', 'adminperson.please.input.cellPhone': '请输入手机号', 'adminperson.please.select.portrait': '请选择头像', 'adminperson.please.select.certType': '请选择证件类型', 'adminperson.please.input.phone': '请输入电话号码', 'adminperson.please.input.qq': '请输入QQ', 'adminperson.please.input.wechat': '请输入wechat', 'adminperson.error.username.exists': '用户名已存在', 'adminperson.error.name.exists': '姓名已存在', 'adminperson.error.pwd.input': '请输入密码', 'adminperson.error.pwd.valid.length': '请输入5-21位密码', 'adminperson.error.pwd.valid.same': '两次密码输入不一致', 'adminperson.error.portrait.format': '请上传JPEG或PNG格式的图片!', 'adminperson.error.portrait.size': '图片大小不能超过2MB!', 'adminperson.error.email.invalid': '邮箱格式不正确', 'adminperson.create': '新建管理员', 'adminperson.edit': '编辑', 'adminperson.view': '查看', 'adminperson.delete': '删除管理员', 'adminperson.resetPassword': '重置密码', 'adminperson.business': '人员信息管理', 'adminperson.confirm.delete': '确定删除人员信息吗?', 'adminperson.confirm.resetPassword': '确定重置密码为初始密码123456吗?', 'adminperson.OK': '确定', 'adminperson.ok': '确定', 'adminperson.cancel': '取消', 'adminperson.create.success': '新建管理员成功', 'adminperson.update.success': '编辑管理员成功', 'adminperson.fetch.failed': '获取管理员列表失败', 'adminperson.create.failed': '新建管理员失败', 'adminperson.update.failed': '编辑管理员失败', 'adminperson.delete.failed': '删除管理员失败', 'adminperson.get.failed': '获取管理员详情失败', 'adminperson.checkUserName.failed': '校验登录名失败', 'adminperson.checkName.failed': '校验姓名失败', };
36.107692
61
0.701321
d5da980cdfc29bbfa8e37337d3618ddd4a1fe4e3
2,135
js
JavaScript
src/fill_queue.js
z3dev/martinez
246d8683ea6c6a9e0e2dbdc12d8a68febec09c80
[ "MIT" ]
2
2022-03-15T21:48:16.000Z
2022-03-16T10:24:25.000Z
src/fill_queue.js
z3dev/martinez
246d8683ea6c6a9e0e2dbdc12d8a68febec09c80
[ "MIT" ]
null
null
null
src/fill_queue.js
z3dev/martinez
246d8683ea6c6a9e0e2dbdc12d8a68febec09c80
[ "MIT" ]
null
null
null
import Queue from 'tinyqueue' import SweepEvent from './sweep_event' import compareEvents from './compare_events' import { DIFFERENCE } from './operation' const max = Math.max const min = Math.min let contourId = 0 const processPolygon = (contourOrHole, isSubject, depth, Q, bbox, isExteriorRing) => { let i, len, s1, s2, e1, e2 for (i = 0, len = contourOrHole.length - 1; i < len; i++) { s1 = contourOrHole[i] s2 = contourOrHole[i + 1] e1 = new SweepEvent(s1, false, undefined, isSubject) e2 = new SweepEvent(s2, false, e1, isSubject) e1.otherEvent = e2 if (s1[0] === s2[0] && s1[1] === s2[1]) { continue // skip collapsed edges, or it breaks } e1.contourId = e2.contourId = depth if (!isExteriorRing) { e1.isExteriorRing = false e2.isExteriorRing = false } if (compareEvents(e1, e2) > 0) { e2.left = true } else { e1.left = true } const x = s1[0] const y = s1[1] bbox[0] = min(bbox[0], x) bbox[1] = min(bbox[1], y) bbox[2] = max(bbox[2], x) bbox[3] = max(bbox[3], y) // Pushing it so the queue is sorted from left to right, // with object on the left having the highest priority. Q.push(e1) Q.push(e2) } } const fillQueue = (subject, clipping, sbbox, cbbox, operation) => { const eventQueue = new Queue(null, compareEvents) let polygonSet, isExteriorRing, i, ii, j, jj //, k, kk for (i = 0, ii = subject.length; i < ii; i++) { polygonSet = subject[i] for (j = 0, jj = polygonSet.length; j < jj; j++) { isExteriorRing = j === 0 if (isExteriorRing) contourId++ processPolygon(polygonSet[j], true, contourId, eventQueue, sbbox, isExteriorRing) } } for (i = 0, ii = clipping.length; i < ii; i++) { polygonSet = clipping[i] for (j = 0, jj = polygonSet.length; j < jj; j++) { isExteriorRing = j === 0 if (operation === DIFFERENCE) isExteriorRing = false if (isExteriorRing) contourId++ processPolygon(polygonSet[j], false, contourId, eventQueue, cbbox, isExteriorRing) } } return eventQueue } export default fillQueue
27.727273
88
0.612646
d5daf9ab2f8e4c39bf2d8132c9e0527a35d1b58c
515
js
JavaScript
src/util/ad-buffet.js
zentrick/iab-vast-model
ea10db540c6053d8e41e00a858b15e242a95d102
[ "MIT" ]
12
2016-07-11T09:15:14.000Z
2022-03-26T08:29:30.000Z
src/util/ad-buffet.js
zentrick/iab-vast-model
ea10db540c6053d8e41e00a858b15e242a95d102
[ "MIT" ]
47
2016-08-02T11:16:08.000Z
2021-02-24T19:06:01.000Z
src/util/ad-buffet.js
zentrick/iab-vast-model
ea10db540c6053d8e41e00a858b15e242a95d102
[ "MIT" ]
7
2017-07-19T07:44:12.000Z
2019-05-01T13:22:11.000Z
import { SortedList } from './sorted-list' /** * Represents a VAST ad buffet. */ export class AdBuffet { constructor () { this._ads = new SortedList() this._adPod = null } /** * The ads in this ad buffet. * * @type {SortedList} */ get ads () { return this._ads } /** * The ad pod for this ad buffet. * * @type {AdPod} */ get adPod () { return this._adPod } set adPod (value) { this._adPod = value } get $type () { return 'AdBuffet' } }
13.552632
42
0.537864