branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># Review Questions ## What is Node.js? ## What is Express? ## Mention two parts of Express that you learned about this week. ## What is Middleware? ## What is a Resource? ## What can the API return to help clients know if a request was successful? ## How can we partition our application into sub-applications? ## What is express.json() and why do we need it? 1. Node.js is a runtime environment that executes javascript applications outside the browser. 2. Express is like React for the back end. It's a web app framework that sits on top of Node.js. 3. routing and middleware 4. Functions that operate on the request and response objects. Together they're like an array of functions that either return the response or pass to the next middleware. 5. Everything is a resource, accessible via a unique URL. 6. It can return a 200-299 series message. 7. By splitting off different sets of endpoints into separate router files. 8. It allows express to parse json info from the req body.<file_sep>const express = require('express'); const projectRoutes = require('./routes/projectRoutes.js'); const actionRoutes = require('./routes/actionRoutes.js'); const server = express(); //middleware server.use(express.json()); server.use('/projects', projectRoutes); server.use('/actions', actionRoutes); server.listen(9000, () => console.log('\n== API on port 9k ==\n'));
1b9e792005282d8b4da85918f8cd8fc9c3272024
[ "Markdown", "JavaScript" ]
2
Markdown
AlexanderCaves/Sprint-Challenge-Node-Express
6e7d7d05c465ecea2c464400a98daaf94daff56f
2859d0170a08f7358d8970b5cc2c8fa023bdb22f
refs/heads/main
<repo_name>ZheniaSteger/producerConsumerThreads<file_sep>/prodcon.c //============================================================================== // Author : <NAME> // Purpose : Demonstrate use of semaphores and threads. // ============================================================================= // INCLUDE FILES #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> // GLOBAL VARIABLE DECLARATIONS char *shmPointer = NULL; // global shared memory pointer int memsize = 0; // int ntimes = 0; // global memsize and ntimes int err; pthread_t tid[2]; // pthread_mutex_t mutex; // mutex semaphore sem_t empty, full, count; // create semaphores // PROTOTYPE FUCNTIONS unsigned short checksum(char* data); // PRODUCER THREAD - WRITES RANDOM DATA TO 32 BYTE BUFFER AND COMPUTES CHECKSUM void *producer() { char localBuffer[32]; // LOCAL BUFFER SO WE DONT HAVE TO WAIT AS LONG int i = 0; int j = 0; unsigned short int sum = 0; // FOR THE CHECKSUM // LOOPS NTIMES for(i = 0; i < ntimes; i++) { for(j = 0; j < 30; j++) { localBuffer[j] = (char)(rand()%256); } sum = checksum(localBuffer); // ASSIGN THE CHECKSUM TO THE LAST 2 BYTES OF THE LOCAL BUFFER localBuffer[25] = (uint8_t)((sum >> 8) & 0xff); localBuffer[26] = (uint8_t)(sum & 0xff); for(j = 0; i < 32; i++) { sem_wait(&empty); /* Begin the critical section */ pthread_mutex_lock(&mutex); shmPointer[i] = localBuffer[i]; sem_post(&count); pthread_mutex_unlock(&mutex); /* end the critical section */ sem_post(&full); } } } // CONSUMER THREAD - READS RANDOM DATA FROM THE 32 BYTE BUFFER AND CHEKS CHECKSUM void *consumer() { char localBuffer[32]; // LOCAL BUFFER SO WE DONT HAVE TO WAIT AS LONG int i = 0; int j = 0; unsigned short int sumRead = 0; // FOR THE CHECKSUM unsigned short int sumVerify = 0; // CHECKSUM // LOOPS NTIMES for(j = 0; i < 32; i++) { sem_wait(&full); /* Begin the critical section */ pthread_mutex_lock(&mutex); localBuffer[i] = shmPointer[i]; sem_wait(&count); pthread_mutex_unlock(&mutex); /* end the critical section */ sem_post(&empty); } // CHECK THE CHECKSUM OF THE DATA COMING IN sumVerify = checksum(localBuffer); // READ THE CHECKSUM FROM THE LAST 2 BYTES uint8_t firstByte, secondByte; firstByte = localBuffer[25]; secondByte = localBuffer[26]; sumRead = (firstByte << 8) | secondByte; // IF THE CHECKSUMS DO NOT MATCH PRINT AN ERROR if (sumRead != sumVerify) { printf("\n Error: Checksum does not match.\n"); } } // INTERNET CHECKSUM FUNCTION unsigned short checksum(char* data) { int i = 0; // Initialise the accumulator. unsigned short acc=0xffff; // Handle complete 16-bit blocks. for (i = 0; i+1<30; i += 2) { uint16_t word; memcpy(&word,data+i,2); acc+=word; if (acc>0xffff) { acc-=0xffff; } } // Return the checksum return acc; } // MAIN METHOD RUNS THE PROGRAM - REQUIRES TWO ARGUMENTS // memsize | is the amount of memory to pass // ntimes | how many times the producer writes and the consumer reads from the buffer int main(int argc, char const *argv[]) { // VARIABLE AND SEMAPHORE DECLARATIONS //pthread_mutex_lock(&mutex); // mutex semaphore declaration if(sem_init(&empty, 0, memsize)) {perror("Semaphore create error."); exit(0);} if(sem_init(&full, 0, memsize)) {perror("Semaphore create error."); exit(0);} if(sem_init(&count, 0, memsize)) {perror("Semaphore create error."); exit(0);} /* ERROR CHECKING */ if (argc !=3) {fprintf(stderr, "Error. Incorrect number of arguments (Needed 2)\n"), exit(0);} if (atoi(argv[1]) == 0) {fprintf(stderr, "memsize is not an integer.\n"); exit(0);} if (atoi(argv[1]) == 0) {fprintf(stderr, "ntimes is not an integer.\n"); exit(0);} memsize = atoi(argv[1]); // Assigns the value to memsize from the prog argument if (memsize < 0) {fprintf(stderr, "memsize cannot be negative.\n"); return -1;} if (memsize >= 65) {fprintf(stderr, "memsize cannot be greater than 64.\n"); return -1;} if (memsize % 32 != 0) {fprintf(stderr, "memsize must be a multiple of 32.\n"); return -1;} ntimes = atoi(argv[2]); // Assigns the value to ntimes from the prog argument if (ntimes < 0) {fprintf(stderr, "ntimes cannot be negative.\n"); return -1;} /* END ERROR CHECKING */ shmPointer = malloc(memsize); // CREATING MUTEX SEMAPHORE if (pthread_mutex_init(&mutex, NULL) != 0) { printf("\nError creating mutex\n"); return -1; } // CREATING THE PRODUCER THREAD err = pthread_create(&(tid[0]), NULL, &producer, NULL); if (err != 0) { printf("\ncan't create thread 2 :[%s]", strerror(err)); } // CREATING THE CONSUMER THREAD err = pthread_create(&(tid[1]), NULL, &consumer, NULL); if (err != 0) { printf("\ncan't create thread 2 :[%s]", strerror(err)); } // JOINING THE THREADS pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); // DESTROY THE SEMAPHORE REFERENCE pthread_mutex_destroy(&mutex); return 0; }
bb0f05a322a3e08e32828a678c73011df1c041c7
[ "C" ]
1
C
ZheniaSteger/producerConsumerThreads
7869913b4c1d65908e681f9aa283c5e839a3e6b6
bf9e1f5a2d040511705ba685c00a6f6648e3667a
refs/heads/master
<file_sep>const express = require('express') var cors = require('cors') var app = express() const port = 8080 const fetch = require('node-fetch'); app.use(cors()) app.get('/todos', function (req, res) { var url = 'https://0je8g9zvze.execute-api.eu-west-1.amazonaws.com/test/todos'; fetch(url) .then(res => res.json()) .then(data => { res.send({ data }); }) .catch(err => { res.send(err); }); }); app.get('/todos/:id', function (req, res) { var url = 'https://0je8g9zvze.execute-api.eu-west-1.amazonaws.com/test/todos/'+ req.params.id; fetch(url) .then(res => res.json()) .then(data => { res.send({ data }); }) .catch(err => { res.send(err); }); }); app.post('/todos', function (req, res) { console.log(req) var url = 'https://0je8g9zvze.execute-api.eu-west-1.amazonaws.com/test/todos'; fetch(url,{ method: 'POST', body:req.body }) .then(res => res.json()) .then(data => { res.send({ data }); }) .catch(err => { res.send(err); }); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
4bf4699e9ebcd08870cd1f214d9735a31a8509df
[ "JavaScript" ]
1
JavaScript
johnaroj/todo-list-app
12b6b66d9045dc629b3a177e0e5fb476c56bd2a0
81b4133650e0f88cd2ad36fe6138d4ca2e25e667
refs/heads/master
<file_sep>import styled from 'styled-components'; import { NavLink } from 'react-router-dom'; import { Form, Field } from 'formik'; // App Styles export const StyledAppMain = styled.main` background-color: black; box-shadow: 0px 0px 5px 5px #7ab363; padding: 25px; `; // Header Styles export const StyledH1 = styled.h1` font-family: 'Get Schwitchy'; font-size: 64px; color: #1f9ace; text-shadow: 1px 1px 5px #7ab363, -1px -1px 5px #7ab363; `; export const StyledH1Span = styled.span` font-size: 32px; `; export const StyledNavUl = styled.ul` list-style: none; width: 25%; display: flex; justify-content: space-around; margin: 50px auto; `; export const StyledLink = styled(NavLink)` margin-right: 25px; text-decoration: none; color: #1f9ace; &:hover { color: #7ab363; } `; // WelcomePage Styles export const StyledWelcomeHeader = styled.div` text-align: center; `; // SearchForm Styles export const StyledForm = styled(Form)` display: flex; flex-direction: column; width: 158px; margin: 0 auto; `; export const StyledField = styled(Field)` margin: 0; `; export const StyledSubmitInput = styled.input` border: 1px solid transparent; margin: 0 `; // CharacterList Styles export const StyledCharacterListSection = styled.section` display: flex; flex-wrap: wrap; justify-content: space-between; `; // NoCharacters Styles export const StyledNoListDiv = styled.div` text-align: center; margin: 25px auto; `; // CharacterCard Styles export const StyledCharacterCardDiv = styled.div` box-shadow: 0px 0px 5px 5px #7ab363; width: 307px; margin 25px 0; `; export const StyledCharacterCardImg = styled.img` width: 100% `; export const StyledCardInfoH2 = styled.h2` `; export const StyledCharacterCardUl = styled.ul` list-style: none; padding: 0; margin: 0; `; export const StyledCardInfoDiv = styled.div` padding: 10px; `; // Pagination Styles export const StyledContainerDiv = styled.div` text-align: center; margin: 20px 0; `; export const StyledPaginationButton = styled.button` border-color: transparent; background-color: transparent; color: #1f9ace; font-size: 16px; `; export const StyledPaginationUl = styled.ul` list-style: none; display: flex; margin: 10px auto; padding: 0; `; <file_sep>import React, { useState, useEffect } from 'react'; import { StyledPaginationButton, StyledContainerDiv } from './style'; const Pagination = (props) => { const [currentPage, setCurrentPage] = useState(1); useEffect(() => { console.log(props.url); if (props.url.includes('&name')) { setCurrentPage(props.url.split('&')[0].split('=')[1]); } else if (props.url.includes('?page')) { setCurrentPage(props.url.split('=')[1]); } else { setCurrentPage(1); } }, [props.url]) const nextPage = () => { if (currentPage < props.info.pages) { props.urlSetter(props.info.next); } } const prevPage = () => { if (currentPage > 1) { props.urlSetter(props.info.prev); } } // const pageHandler = (page, url) => { // if (currentPage !== page) { // if (url[url.length - 1] === '/' || url.includes('?page')) { // props.urlSetter(`?page=${page}`); // } else if (url.includes('&page')) { // props.urlSetter(`${url.split('&')[0].substr(78)}&page=${page}`); // } else { // props.urlSetter(`${url.substr(78)}&page=${page}`); // } // setCurrentPage(page); // } return( <StyledContainerDiv> <StyledPaginationButton onClick={() => prevPage()}>&lt;Prev</StyledPaginationButton><span>Page {currentPage} of {props.info.pages}</span><StyledPaginationButton onClick={() => nextPage()}>Next&gt;</StyledPaginationButton> </StyledContainerDiv> /* <StyledPaginationUl> {[...Array(props.info.pages)].map((x, index) => index+1).map(page => { return <li key={page}><StyledPaginationButton onClick={() => pageHandler(props.url, page)}>{page}</StyledPaginationButton></li> })} </StyledPaginationUl> */ ) } export default Pagination; // return <li key={page}><StyledPaginationButton onClick={() => props.url(prevState => prevState + `&page=` + page)} /></li> // props.urlSetter(url.splice(-1) === '/' ? `?page=${}`<file_sep>import Header from './Header'; import SearchForm from './SearchForm'; import CharacterList from './CharacterList'; import CharacterCard from './CharacterCard'; import WelcomePage from './WelcomePage'; import NoCharacters from './NoCharacters'; import Pagination from './Pagination'; export { Header, SearchForm, CharacterCard, CharacterList, WelcomePage, NoCharacters, Pagination };<file_sep>import React from "react"; import { StyledCharacterCardDiv, StyledCharacterCardImg, StyledCharacterCardUl, StyledCardInfoDiv, StyledCardInfoH2 } from './style' export default function CharacterCard(props) { return( <StyledCharacterCardDiv> <StyledCharacterCardImg src={props.character.image} alt="portrait" /> <StyledCardInfoDiv> <StyledCardInfoH2>{props.character.name}</StyledCardInfoH2> <StyledCharacterCardUl> <li>Status: {props.character.status}</li> <li>Species: {props.character.species}</li> <li>Gender: {props.character.gender}</li> <li>Origin: {props.character.origin.name}</li> </StyledCharacterCardUl> </StyledCardInfoDiv> </StyledCharacterCardDiv> ) } <file_sep>import React, { useEffect, useState } from "react"; import CharacterCard from './CharacterCard'; import { SearchForm, NoCharacters, Pagination } from './index'; import axios from 'axios'; import { StyledCharacterListSection } from './style'; export default function CharacterList() { const [characterData, setCharacterData] = useState({results: [], info: {}}); const [url, setUrl] = useState(`https://cors-anywhere.herokuapp.com/https://rickandmortyapi.com/api/character/`); useEffect(() => { axios.get(url) .then(response => setCharacterData(response.data)) .catch(err => setCharacterData(false)); }, [url]); const urlSetter = (url) => { setUrl(url) } return ( <> <SearchForm urlSetter={urlSetter} /> {!characterData ? null : <Pagination info={characterData.info} urlSetter={urlSetter} url={url} />} <StyledCharacterListSection className="character-list"> {!characterData ? <NoCharacters /> : characterData.results.map(character => { return <CharacterCard character={character} key={character.id} /> })} </StyledCharacterListSection> {!characterData ? null : <Pagination info={characterData.info} urlSetter={urlSetter} url={url} />} </> ); } <file_sep>import React from "react"; import { StyledH1, StyledH1Span, StyledNavUl, StyledLink } from './style'; export default function Header() { return ( <header className="ui centered"> <StyledH1 className="ui center">Rick <StyledH1Span>and</StyledH1Span> Morty<br />Fan Page</StyledH1> <StyledNavUl> <li><StyledLink exact to="/" activeStyle={{color: '#7ab363'}}>Home</StyledLink></li> <li><StyledLink to="/characters" activeStyle={{color: '#7ab363'}}>Characters</StyledLink></li> </StyledNavUl> </header> ); }
e8f772e8b14ce288d1f0b309eb081174f04bf831
[ "JavaScript" ]
6
JavaScript
DMConklin/Sprint-Challenge-Single-Page-Apps
8fabb310a2081b5ebb7b4b3b55f31f1cdb2bf6ba
1ed6be3873695e2bd8b9cc0ead0c0f415e627852
refs/heads/master
<file_sep>import React, { useState, useEffect } from "react"; import { useAuthContext } from "../../../context/auth/AuthState"; import Spinner from "../../../components/Spinner/Spinner"; import "./MyDetails.css"; const MyDetails = () => { const defaultState = { oldPassword: "", newPassword: "", confirmPassword: "" }; const [values, setValues] = useState(defaultState); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const { user, errorMessage, changePassword, changePasswordSuccess, loading, clearErrors } = useAuthContext(); const onChange = e => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const validate = values => { let errors = {}; if (!values.oldPassword) { errors.oldPassword = "Old password is required!"; } else if (values.oldPassword.length < 6) { errors.oldPassword = "Old password needs to be more than 6 characters!"; } if (!values.newPassword) { errors.newPassword = "Password is required!"; } else if (values.newPassword.length < 6) { errors.newPassword = "Password needs to be more than 6 characters!"; } if (!values.confirmPassword) { errors.confirmPassword = "Confirm password is required!"; } else if (values.newPassword !== values.confirmPassword) { errors.confirmPassword = "Passwords do not match!"; } return errors; }; const handleNewPassword = e => { e.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { changePassword(values); setValues(defaultState); } // eslint-disable-next-line }, [errors, isSubmitting]); useEffect(() => { clearErrors(); // eslint-disable-next-line }, []); return ( <div className="myDetails"> {loading && <Spinner />} <h2>My Details</h2> <div className="myDetails__personalInformation"> <h5>Personal Information</h5> <div className="myDetails__personalInformationGroup"> <p className="myDetails__personalInformationLabel">Email:</p> <p className="myDetails__personalInformationContent"> {user && user.email} </p> </div> <div className="myDetails__personalInformationGroup"> <p className="myDetails__personalInformationLabel">First Name:</p> <p className="myDetails__personalInformationContent"> {user && user.given_name} </p> </div> <div className="myDetails__personalInformationGroup"> <p className="myDetails__personalInformationLabel">Last Name:</p> <p className="myDetails__personalInformationContent"> {user && user.family_name} </p> </div> </div> <div className="myDetails__password"> <h5>Password</h5> <div className="myDetails__passwordGroup"> <p className="myDetails__passwordLabel">Password:</p> <p className="myDetails__passwordContent">********* </p> </div> <div className="myDetails__passwordGroup"> <button className="myDetails__passwordCollapseBtn" type="button" data-bs-toggle="collapse" data-bs-target="#passwordForm" aria-expanded="false" aria-controls="passwordForm" > Change Password </button> </div> <div className="collapse myDetails__passwordCollapse" id="passwordForm"> <h5>Change Password</h5> <form onSubmit={handleNewPassword} className="myDetails__passwordForm" > <div className="myDetails__passwordFormGroup"> <input className={`myDetails__passwordFormInput ${errors.oldPassword && "form-control is-invalid"}`} type="password" id="oldPassword" name="oldPassword" placeholder="Old <PASSWORD>" value={values.oldPassword} onChange={onChange} autoComplete="current-password" /> {errors.oldPassword && ( <label className="myDetails__passwordFormLabel" htmlFor="oldPassword" > {errors.oldPassword} </label> )} </div> <div className="myDetails__passwordFormGroup"> <input className={`myDetails__passwordFormInput ${errors.newPassword && "form-control is-invalid"}`} type="password" id="newPassword" name="newPassword" placeholder="<PASSWORD>" value={values.newPassword} onChange={onChange} autoComplete="current-password" /> {errors.newPassword && ( <label className="myDetails__passwordFormLabel" htmlFor="newPassword" > {errors.newPassword} </label> )} </div> <div className="myDetails__passwordFormGroup"> <input className={`myDetails__passwordFormInput ${errors.confirmPassword && "form-control is-invalid"} `} type="password" id="confirmPassword" name="confirmPassword" placeholder="<PASSWORD>" value={values.confirmPassword} onChange={onChange} autoComplete="username" /> {errors.confirmPassword && ( <label className="myDetails__passwordFormLabel" htmlFor="confirmPassword" > {errors.confirmPassword} </label> )} </div> <div className="myDetails__passwordFormGroup"> <input type="submit" value="SUBMIT" className="myDetails__passwordFormSubmit" placeholder="SUBMIT" name="submit" /> {errorMessage && ( <label className="myDetails__passwordFormLabel" htmlFor="submit" > {errorMessage} </label> )} {changePasswordSuccess && ( <p className="myDetails__passwordFormSuccess"> Password changed successfully! </p> )} </div> </form> </div> </div> </div> ); }; export default MyDetails; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import { format } from "date-fns"; import "./Author.css"; const Author = ({ author }) => { return ( <Link to={{ pathname: `author/${author.id}`, author: author }} className="author" > <p className="author__name">{`${author.firstName} ${author.lastName}`}</p> <p className="author__birthDate"> Born: {format(new Date(author.birthDate), "yyyy-MM-dd")} </p> <p className="author__description">{author.description}</p> </Link> ); }; export default Author; <file_sep>import React, { useState, useEffect } from "react"; import { Link, useHistory } from "react-router-dom"; import { useAuthContext } from "../../context/auth/AuthState"; import Spinner from "../../components/Spinner/Spinner"; import "./SigninPage.css"; const SigninPage = props => { const defaultState = { email: "", password: "" }; const history = useHistory(); const [values, setValues] = useState(defaultState); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const { loginUser, loginFail, loginSuccess, errorMessage, loading } = useAuthContext(); const onChange = e => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const validate = values => { let errors = {}; if (!values.email) { errors.email = "Email address is required!"; } else if (!/\S+@\S+\.\S+/.test(values.email)) { errors.email = "Email address is invalid"; } if (!values.password) { errors.password = "<PASSWORD>!"; } else if (values.password.length < 6) { errors.password = "Password needs to be more than 6 <PASSWORD>!"; } return errors; }; const handleSubmit = e => { e.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { loginUser(values); setValues(defaultState); } // eslint-disable-next-line }, [errors, isSubmitting]); useEffect(() => { if (loginSuccess) { if ( props.location && props.location.state && props.location.state.basket && props.location.state.basket === true ) { console.log("basket"); } else { history.push("/"); } } // eslint-disable-next-line }, [loginSuccess, history]); return ( <div className="signinPage"> {loading && <Spinner />} <h1>Signin Page</h1> <div className="signinPage__container"> <div className="signinPage__content"> <h2>Sign In</h2> <form onSubmit={handleSubmit} className="signInPage__form"> <div className="signinPage__formGroup"> <input className={`signinPage__formGroupInput ${errors.email && "form-control is-invalid"} `} type="email" id="email" name="email" placeholder=" Your Email" value={values.email} onChange={onChange} autoComplete="username" /> {errors.email && ( <label className="singupPage__formLabel" htmlFor="email"> {errors.email} </label> )} </div> <div className="signinPage__formGroup"> <input className={`signinPage__formGroupInput ${errors.password && "form-control is-invalid"}`} type="password" id="password" name="password" placeholder="<PASSWORD>" value={values.password} onChange={onChange} autoComplete="current-password" /> {errors.password && ( <label className="singupPage__formLabel" htmlFor="password"> {errors.password} </label> )} </div> <div className="signinPage__formGroup"> <input type="submit" value="SUBMIT" className="signinPage__formSubmit" placeholder="SUBMIT" name="submit" /> {loginFail && ( <label className="signinPage__formLabel" htmlFor="submit"> {errorMessage} </label> )} </div> </form> <div className="signinPage__containerLinks"> <div className="signinPage__links"> <p className="signinPage__register"> Don't have account?{" "} <Link to="/signup" className="signinPage__link"> Signup Here </Link> </p> <Link to="/forgot-password" className="signinPage__link"> Forgot password? </Link> </div> <Link to="/confirm" className="signinPage__link"> Go to confirm account. </Link> </div> </div> </div> </div> ); }; export default SigninPage; <file_sep>import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { Storage } from "aws-amplify"; import "./AuthorBook.css"; const AuthorBook = ({ book }) => { const [img, setImg] = useState(""); const getBookImg = async id => { try { setImg(await Storage.get(id)); } catch (error) { console.log(error); } }; useEffect(() => { getBookImg(book.image.name); // eslint-disable-next-line }, []); if (img) { book.link = img; } return ( <Link to={{ pathname: `/book/${book.id}`, book: book }} className="authorBook" > <div className="authorBook__img"> <img src={img} alt="book image" /> </div> <div className="authorBook__content"> <p className="authorBook__title">{book.title}</p> <p className="authorBook__category">{book.category}</p> <p className="authorBook__totalPages">Total pages: {book.totalPages}</p> <p className="authorBook__description">{book.description}</p> </div> </Link> ); }; export default AuthorBook; <file_sep>import React from "react"; import "./Welcome.css"; const Welcome = props => { return ( <div> <h1>Register Success, </h1> <h5>Email was sent to: {props.location.state.user}</h5> </div> ); }; export default Welcome; <file_sep>import React, { useState, useEffect } from "react"; import { Storage } from "aws-amplify"; import { Link, useHistory } from "react-router-dom"; import "./HomePageBook.css"; const HomePageBook = ({ book }) => { const [img, setImg] = useState(""); const getBookImg = async id => { try { setImg(await Storage.get(id)); } catch (error) { console.log(error); } }; useEffect(() => { getBookImg(book.image); // eslint-disable-next-line }, []); return ( <Link to={`/book/${book.id}`} className="homePageBook"> <div className="homePageBook__container"> <div className="homePageBook__containerImg"> <img src={img} alt="book Img" /> </div> <p className="homePageBook__containerTitle">{book.title}</p> <p className="homePageBook__containerAuthor">{book.authorName}</p> </div> </Link> ); }; export default HomePageBook; <file_sep>import React, { useState, useEffect } from "react"; import { useBookContext } from "../../../context/book/BookState"; import { KeyboardDatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers"; import DateFnsUtils from "@date-io/date-fns"; import awsExports from "../../../aws-exports"; import Spinner from "../../../components/Spinner/Spinner"; import "./AddBook.css"; const AddBook = () => { const defaultState = { title: "", authorID: "", publisher: "", publishedDate: new Date(), language: "", description: "", category: "", totalPages: "", isbn: "", totalCopies: "", status: "", image: {} }; const categories = [ "Action and Adventure", "Classics", "Comic Book or Graphic Novel", "Detective and Mystery", "Fantasy", "Horror", "Literary Fiction", "Romance", "Science Fiction", "Thrillers", "Biographies and Autobiographies", "History", "Poetry", "Travel" ]; const statuses = ["available", "not available"]; const languages = ["English", "Polish"]; const [values, setValues] = useState(defaultState); const [image, setImage] = useState({}); const [imageUrl, setImageUrl] = useState(); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const { authors, listAuthors, createBook, clearForm, loading, createBookSuccess } = useBookContext(); const onChange = e => { if (e.target) { const { name, value } = e.target; setValues({ ...values, [name]: value }); } else { setValues({ ...values, publishedDate: e }); } }; const onChangeAuthor = e => { const { name, value, options } = e.target; setValues({ ...values, [name]: value, authorName: options[options.selectedIndex].text }); }; const onChangeImage = e => { const file = e.target.files[0]; if (file) { setValues({ ...values, image: { name: file.name, bucket: awsExports.aws_user_files_s3_bucket, region: awsExports.aws_user_files_s3_bucket_region, key: "public/" + file.name } }); setImage(e.target.files[0]); setImageUrl(URL.createObjectURL(e.target.files[0])); } else { setValues({ ...values, image: {} }); setImage({}); setImageUrl(); } }; const validate = values => { let errors = {}; if (Object.keys(values.image).length === 0) { errors.image = "Image is required!"; } else if (image.type !== "image/jpeg" && image.type !== "image/png") { errors.image = "Image format only jpeg or png!"; } if (!values.title) { errors.title = "Title is required!"; } if (!values.authorID) { errors.authorID = "Author is required!"; } if (!values.publisher) { errors.publisher = "Publisher is required!"; } if (!values.publishedDate) { errors.publishedDate = "Publish Date is required!"; } if (!values.language) { errors.language = "Language is required!"; } if (!values.description) { errors.description = "Description is required!"; } if (!values.category) { errors.category = "Category is required!"; } if (!values.totalPages) { errors.totalPages = "Total Pages is required!"; } else if (!/^[0-9]*$/.test(values.totalPages)) { errors.totalPages = "Only numbers!"; } if (!values.isbn) { errors.isbn = "ISBN is required!"; } if (!values.totalCopies) { errors.totalCopies = "Total copies is required!"; } else if (!/^[0-9]*$/.test(values.totalCopies)) { errors.totalCopies = "Only numbers!"; } if (!values.status) { errors.status = "Status is required!"; } return errors; }; const handleSubmit = e => { e.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; useEffect(() => { if (authors.length === 0) { listAuthors(); } // eslint-disable-next-line }, [authors]); useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { createBook(values, image); setValues(defaultState); } // eslint-disable-next-line }, [errors, isSubmitting]); useEffect(() => { if (createBookSuccess) { const timer = setTimeout(() => { clearForm(); }, 4000); return () => clearTimeout(timer); } // eslint-disable-next-line }, [createBookSuccess]); useEffect(() => { clearForm(); // eslint-disable-next-line }, []); return ( <div className="addBook"> {loading && <Spinner />} <h2>Add Book</h2> <form onSubmit={handleSubmit} className="addBook__form"> <div className="addBook__formGroup"> <input className="addBook__formGroupInputImage" type="file" name="image" id="image" placeholder="Select book image" onChange={onChangeImage} /> <img src={imageUrl} alt="" className="addBook__formGroupImage" /> {errors.image && ( <label className="addBook__formLabel" htmlFor="image"> {errors.image} </label> )} </div> <div className="addBook__formGroup"> <input className={`addBook__formGroupInput ${errors.title && "form-control is-invalid"}`} type="text" id="title" name="title" placeholder="Title" value={values.title} onChange={onChange} /> {errors.title && ( <label className="addBook__formLabel" htmlFor="title"> {errors.title} </label> )} </div> <div className="addBook__formGroup"> <select className={`addBook__formGroupSelect ${errors.authorID && "form-control is-invalid"}`} type="text" id="authorID" name="authorID" placeholder="Author" value={values.authorID} onChange={onChangeAuthor} > <option key="1" value="" disabled> Author </option> {authors.map(e => ( <option key={e.id} value={e.id}> {e.firstName} {e.lastName} </option> ))} </select> {errors.authorID && ( <label className="addBook__formLabel" htmlFor="authorID"> {errors.authorID} </label> )} </div> <div className="addBook__formGroup"> <input className={`addBook__formGroupInput ${errors.publisher && "form-control is-invalid"}`} type="text" id="publisher" name="publisher" placeholder="Publisher" value={values.publisher} onChange={onChange} /> {errors.publisher && ( <label className="addBook__formLabel" htmlFor="publisher"> {errors.publisher} </label> )} </div> <div className="addBook__formGroup"> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker openTo="year" views={["year", "month"]} label="Published Date" name="publishedDate" value={values.publishedDate} onChange={onChange} format="yyyy/MM" /> </MuiPickersUtilsProvider> {errors.publishedDate && ( <label className="addBook__formLabel" htmlFor="publishedDate"> {errors.publishedDate} </label> )} </div> <div className="addBook__formGroup"> <select className={`addBook__formGroupSelect ${errors.language && "form-control is-invalid"}`} type="text" id="language" name="language" placeholder="Language" value={values.language} onChange={onChange} > <option key="1" value="" disabled> Language </option> {languages.map(language => ( <option key={language} value={language}> {language} </option> ))} </select> {errors.language && ( <label className="addBook__formLabel" htmlFor="language"> {errors.language} </label> )} </div> <div className="addBook__formGroup"> <textarea className={`addBook__formGroupInput ${errors.description && "form-control is-invalid"}`} type="text" id="bookDescription" name="description" placeholder="Description" value={values.description} onChange={onChange} /> {errors.description && ( <label className="addBook__formLabel" htmlFor="bookDescription"> {errors.description} </label> )} </div> <div className="addBook__formGroup"> <select className={`addBook__formGroupSelect ${errors.category && "form-control is-invalid"}`} type="text" id="category" name="category" placeholder="Category" value={values.category} onChange={onChange} > <option key="1" value="" disabled> Category </option> {categories.map(category => ( <option key={category} value={category}> {category} </option> ))} </select> {errors.category && ( <label className="addBook__formLabel" htmlFor="category"> {errors.category} </label> )} </div> <div className="addBook__formGroup"> <input className={`addBook__formGroupInput ${errors.totalPages && "form-control is-invalid"}`} type="text" id="totalPages" name="totalPages" placeholder="Total Pages" value={values.totalPages} onChange={onChange} /> {errors.totalPages && ( <label className="addBook__formLabel" htmlFor="totalPages"> {errors.totalPages} </label> )} </div> <div className="addBook__formGroup"> <input className={`addBook__formGroupInput ${errors.isbn && "form-control is-invalid"}`} type="text" id="isbn" name="isbn" placeholder="ISBN Number" value={values.isbn} onChange={onChange} /> {errors.isbn && ( <label className="addBook__formLabel" htmlFor="isbn"> {errors.isbn} </label> )} </div> <div className="addBook__formGroup"> <input className={`addBook__formGroupInput ${errors.totalCopies && "form-control is-invalid"}`} type="text" id="totalCopies" name="totalCopies" placeholder="Total Copies" value={values.totalCopies} onChange={onChange} /> {errors.totalCopies && ( <label className="addBook__formLabel" htmlFor="totalCopies"> {errors.totalCopies} </label> )} </div> <div className="addBook__formGroup"> <select className={`addBook__formGroupSelect ${errors.status && "form-control is-invalid"}`} type="text" id="status" name="status" placeholder="Category" value={values.status} onChange={onChange} > <option key="1" value="" disabled> Status </option> {statuses.map(status => ( <option key={status} value={status}> {status} </option> ))} </select> {errors.status && ( <label className="addBook__formLabel" htmlFor="status"> {errors.status} </label> )} </div> <div className="addBook__formGroup"> <input className="addBook__formSubmit" type="submit" value="SUBMIT" name="submit" placeholder="Submit" /> {!loading && createBookSuccess && ( <label className="addBook__formLabelSuccess" htmlFor="submit"> Book created successfuly! </label> )} </div> </form> </div> ); }; export default AddBook; <file_sep>import React, { useEffect, useState } from "react"; import { useBookContext } from "../../context/book/BookState"; import Book from "./components/Book"; import "./BooksPage.css"; const BooksPage = () => { const { listBooks, books } = useBookContext(); const [categoryInput, setCategoryInput] = useState("Action and Adventure"); const [search, setSearch] = useState(""); const categories = [ "Action and Adventure", "Classics", "Comic Book or Graphic Novel", "Detective and Mystery", "Fantasy", "Horror", "Literary Fiction", "Romance", "Science Fiction" ]; const handleCategory = e => { setCategoryInput(e.target.value); }; const handleSearch = e => { setSearch(e.target.value); }; useEffect(() => { if (!Object.keys(books).includes(categoryInput)) { listBooks(categoryInput); } // eslint-disable-next-line }, [categoryInput]); return ( <div className="booksPage"> <div className="booksPage__container"> <div className="booksPage__containerNav"> <h2>Category</h2> <div> {categories.map((category, id) => ( <div className="form-check" key={id}> <input className="form-check-input" type="radio" name="radioInput" id={category} onChange={handleCategory} value={category} checked={categoryInput === category} /> <label className="form-check-label" htmlFor={category}> {category} </label> </div> ))} </div> </div> <div className="booksPage__containerBooks"> <h1>Books</h1> <input type="text" className="booksPage__containerBooksSearch" onChange={handleSearch} value={search} placeholder="Search Book" autoFocus /> {Object.keys(books).includes(categoryInput) && books[categoryInput].length > 0 && books[categoryInput].map( book => book.title .toLowerCase() .includes(search.toLocaleLowerCase()) && ( <Book key={book.id} book={book} /> ) )} </div> </div> </div> ); }; export default BooksPage; <file_sep>import React, { useEffect } from "react"; import "./BasketPage.css"; import { useHistory } from "react-router-dom"; import { useBookContext } from "../../context/book/BookState"; import { useAuthContext } from "../../context/auth/AuthState"; import BasketBookPage from "./components/BasketPageBook"; const BasketPage = () => { const history = useHistory(); const { user } = useAuthContext(); const { basket, deleteFromBasket, deleteBasket, createOrder, orderSuccess, errorMessage, clearForm } = useBookContext(); const handleDelete = e => { e.preventDefault(); deleteBasket(); }; const handleOrder = e => { e.preventDefault(); if (user !== null && "email" in user && basket.length > 0) { createOrder({ user: user.sub, email: user.email, cart: basket.map(book => ({ id: book.id, title: book.title })) }); } else if (Object.keys(user).length === 0) { history.push({ pathname: "/signin", state: { basket: true } }); } }; useEffect(() => { if (orderSuccess) { deleteBasket(); } // eslint-disable-next-line }, [orderSuccess]); useEffect(() => { clearForm(); // eslint-disable-next-line }, []); return ( <div className="container basketPage"> <div className="basketPage__header"> <div className="basketPage__headerH1"> <h1>Your Books:</h1> </div> {basket.length > 0 && ( <div className="basketPage__headerBtn"> <button onClick={handleDelete}>Delete all books</button> </div> )} </div> {basket.length > 0 && ( <div className="basketPage__basketContent"> {basket.map(e => ( <BasketBookPage key={e.id} book={e} basket={basket} deleteElement={deleteFromBasket} /> ))} <button onClick={handleOrder}>Order</button> </div> )} {basket.length === 0 && !orderSuccess && ( <p className="basketPage__paragraph">You didn't add any books</p> )} {basket.length === 0 && orderSuccess && ( <p className="basketPage__orderSuccess">Order Success</p> )} {!orderSuccess && errorMessage && ( <p className="basketPage__orderFail">{errorMessage}</p> )} </div> ); }; export default BasketPage; <file_sep>import React from "react"; import { Route, Redirect } from "react-router-dom"; import { useAuthContext } from "../../context/auth/AuthState"; const AdminRoute = ({ component: Component, ...rest }) => { const { isLogged, loading, group } = useAuthContext(); return ( <Route {...rest} render={props => !isLogged && !group.includes("Admin") && loading ? ( <Redirect to="/signin" /> ) : ( <Component {...props} /> ) } /> ); }; export default AdminRoute; <file_sep>import React, { createContext, useReducer, useContext } from "react"; import { Auth } from "aws-amplify"; import authReducer from "./authReducer"; import { REGISTER_SUCCESS, REGISTER_FAIL, CONFIRM_REGISTER_SUCCESS, CONFIRM_REGISTER_FAIL, RESEND_CODE_SUCCESS, RESEND_CODE_FAIL, LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED, AUTH_ERROR, LOGOUT_SUCCESS, FORGOT_PASSWORD_SUCCESS, FORGOT_PASSWORD_FAIL, NEW_PASSWORD_SUCCESS, NEW_PASSWORD_FAIL, CHANGE_PASSWORD_SUCCESS, CHANGE_PASSWORD_FAIL, CLEAR_ERRORS, SET_LOADING } from "../types"; export const AuthState = props => { const initialState = { loading: false, group: [], isLogged: false, logoutSuccess: false, formSuccess: false, registerSuccess: false, registerFail: false, confirmRegister: false, resendCode: false, loginSuccess: false, loginFail: false, forgotPasswordSuccess: false, newPasswordSuccess: false, changePasswordSuccess: false, errorMessage: "", user: {}, loadingUser: true }; const [state, dispatch] = useReducer(authReducer, initialState); const loadUser = async () => { setLoading(); try { const user = await Auth.currentAuthenticatedUser(); dispatch({ type: USER_LOADED, payload: user }); } catch (error) { dispatch({ type: AUTH_ERROR, payload: error.message }); } }; const registerUser = async ({ given_name, family_name, email, password }) => { setLoading(); try { const res = await Auth.signUp({ username: email, password, attributes: { email, given_name, family_name } }); dispatch({ type: REGISTER_SUCCESS, payload: res.user }); } catch (error) { dispatch({ type: REGISTER_FAIL, payload: error.message }); } }; const confirmRegisterUser = async ({ username, code }) => { setLoading(); clearErrors(); try { const res = await Auth.confirmSignUp(username, code); dispatch({ type: CONFIRM_REGISTER_SUCCESS, payload: res }); } catch (error) { dispatch({ type: CONFIRM_REGISTER_FAIL, payload: error.message }); } }; const resendConfirmCode = async username => { setLoading(); try { await Auth.resendSignUp(username); dispatch({ type: RESEND_CODE_SUCCESS }); } catch (error) { dispatch({ type: RESEND_CODE_FAIL, payload: error.message }); } }; const loginUser = async ({ email, password }) => { setLoading(); try { const user = await Auth.signIn(email, password); dispatch({ type: LOGIN_SUCCESS, payload: user }); } catch (error) { dispatch({ type: LOGIN_FAIL, payload: error.message }); } }; const logout = async () => { clearErrors(); try { await Auth.signOut(); dispatch({ type: LOGOUT_SUCCESS }); } catch (error) { console.log(error); } }; const forgotPassword = async username => { setLoading(); try { await Auth.forgotPassword(username); dispatch({ type: FORGOT_PASSWORD_SUCCESS }); } catch (error) { dispatch({ type: FORGOT_PASSWORD_FAIL, payload: error.message }); } }; const newPassword = async ({ username, code, newPassword }) => { setLoading(); try { await Auth.forgotPasswordSubmit(username, code, newPassword); dispatch({ type: NEW_PASSWORD_SUCCESS }); } catch (error) { dispatch({ type: NEW_PASSWORD_FAIL, payload: error.message }); } }; const changePassword = async ({ oldPassword, newPassword }) => { setLoading(); try { const user = await Auth.currentAuthenticatedUser(); const res = await Auth.changePassword(user, oldPassword, newPassword); dispatch({ type: CHANGE_PASSWORD_SUCCESS, payload: res }); } catch (error) { dispatch({ type: CHANGE_PASSWORD_FAIL, payload: error.message }); } }; const clearErrors = () => { dispatch({ type: CLEAR_ERRORS }); }; const setLoading = () => { dispatch({ type: SET_LOADING }); }; return ( <AuthContext.Provider value={{ loading: state.loading, group: state.group, isLogged: state.isLogged, logoutSuccess: state.logoutSuccess, registerSuccess: state.registerSuccess, registerFail: state.registerFail, confirmRegister: state.confirmRegister, resendCode: state.resendCode, loginSuccess: state.loginSuccess, loginFail: state.loginFail, forgotPasswordSuccess: state.forgotPasswordSuccess, newPasswordSuccess: state.newPasswordSuccess, changePasswordSuccess: state.changePasswordSuccess, errorMessage: state.errorMessage, user: state.user, loadingUser: state.loadingUser, loadUser, registerUser, confirmRegisterUser, resendConfirmCode, loginUser, logout, forgotPassword, newPassword, changePassword, clearErrors, setLoading }} > {props.children} </AuthContext.Provider> ); }; export const AuthContext = createContext(); export const useAuthContext = () => useContext(AuthContext); <file_sep>import React, { createContext, useReducer, useContext } from "react"; import { v4 as uuidv4 } from "uuid"; import { API, Storage } from "aws-amplify"; import * as mutations from "../../api/mutations"; import * as queries from "../../api/queries"; import bookReducer from "./bookReducer"; import { CREATE_AUTHOR, CREATE_AUTHOR_FAIL, GET_AUTHOR, GET_AUTHOR_FAIL, LIST_AUTHORS, LIST_AUTHORS_FAIL, CREATE_BOOK, CREATE_BOOK_FAIL, LIST_BOOKS, LIST_BOOKS_FAIL, GET_BOOK, GET_BOOK_FAIL, ADD_TO_BASKET, ADD_TO_BASKET_FAIL, DELETE_FROM_BASKET, DELETE_BASKET, CREATE_ORDER, CREATE_ORDER_FAIL, GET_USER_ORDERS, GET_USER_ORDERS_FAIL, CLEAR_FORM, SET_LOADING } from "../types"; export const BookState = props => { const initialState = { loading: false, author: {}, authors: [], book: {}, books: [], basket: [], formErrorMessage: "", formFail: false, formSuccess: false, errorMessage: "", order: "", orderSuccess: false, orders: [], getOrdersSuccess: false, createAuthorSuccess: false, createBookSuccess: false }; const [state, dispatch] = useReducer(bookReducer, initialState); const createAuthor = async author => { clearForm(); setLoading(); try { const res = await API.graphql({ query: mutations.createAuthor, variables: { input: author } }); dispatch({ type: CREATE_AUTHOR, payload: res.data.createAuthor }); } catch (error) { dispatch({ type: CREATE_AUTHOR_FAIL, payload: error.message }); } }; const getAuthor = async id => { try { const res = await API.graphql({ variables: { id: id }, authMode: "API_KEY", query: queries.getAuthor }); dispatch({ type: GET_AUTHOR, payload: res.data.getAuthor }); } catch (error) { dispatch({ type: GET_AUTHOR_FAIL, payload: error }); } }; const listAuthors = async () => { try { const res = await API.graphql({ query: queries.listAuthors, authMode: "API_KEY" }); dispatch({ type: LIST_AUTHORS, payload: res.data.listAuthors.items }); } catch (error) { dispatch({ type: LIST_AUTHORS_FAIL, payload: error.message }); } }; const createBook = async (book, image) => { clearForm(); setLoading(); try { await Storage.put(image.name, image, { contentType: image.type }); const res = await API.graphql({ query: mutations.createBook, variables: { input: book } }); dispatch({ type: CREATE_BOOK, payload: res.data.createBook }); } catch (error) { dispatch({ type: CREATE_BOOK_FAIL, payload: error.errors[0].message }); } }; const listBooks = async categoryInput => { try { const res = await API.graphql({ query: queries.booksByCategory, authMode: "API_KEY", variables: { category: categoryInput } }); dispatch({ type: LIST_BOOKS, payload: { books: res.data.booksByCategory.items, category: categoryInput } }); } catch (error) { dispatch({ type: LIST_BOOKS_FAIL, payload: error }); } }; const getBook = async id => { try { let res = await API.graphql({ query: queries.getBook, variables: { id: id }, authMode: "API_KEY" }); const key = res.data.getBook.image.name; const signedURL = await Storage.get(key); res.data.getBook.link = signedURL; dispatch({ type: GET_BOOK, payload: res.data.getBook }); } catch (error) { dispatch({ type: GET_BOOK_FAIL, payload: error }); } }; const addToBasket = async book => { try { dispatch({ type: ADD_TO_BASKET, payload: book }); } catch (error) { dispatch({ type: ADD_TO_BASKET_FAIL, payload: error }); } }; const deleteFromBasket = basket => { dispatch({ type: DELETE_FROM_BASKET, payload: basket }); }; const deleteBasket = () => { dispatch({ type: DELETE_BASKET }); }; const createOrder = async orderDetails => { clearForm(); orderDetails.id = uuidv4(); try { const res = await API.graphql({ query: mutations.processOrder, variables: { input: orderDetails } }); dispatch({ type: CREATE_ORDER, payload: res }); } catch (error) { dispatch({ type: CREATE_ORDER_FAIL, payload: error }); } }; const getUserOrders = async email => { clearForm(); try { const res = await API.graphql({ variables: { customer: email, createdAt: { beginsWith: "2021" } }, query: queries.ordersByCustomerByDate }); dispatch({ type: GET_USER_ORDERS, payload: res.data.ordersByCustomerByDate.items }); } catch (error) { dispatch({ type: GET_USER_ORDERS_FAIL, payload: error }); } }; const clearForm = () => { dispatch({ type: CLEAR_FORM }); }; const setLoading = () => { dispatch({ type: SET_LOADING }); }; return ( <BookContext.Provider value={{ loading: state.loading, author: state.author, authors: state.authors, book: state.book, books: state.books, basket: state.basket, formErrorMessage: state.formErrorMessage, formSuccess: state.formSuccess, formFail: state.formFail, errorMessage: state.errorMessage, order: state.order, orderSuccess: state.orderSuccess, orders: state.orders, getOrdersSuccess: state.getOrdersSuccess, createAuthorSuccess: state.createAuthorSuccess, createBookSuccess: state.createBookSuccess, createAuthor, getAuthor, listAuthors, createBook, listBooks, getBook, addToBasket, deleteFromBasket, deleteBasket, createOrder, getUserOrders, clearForm, setLoading }} > {props.children} </BookContext.Provider> ); }; export const BookContext = createContext(); export const useBookContext = () => useContext(BookContext); <file_sep>import React from "react"; import "./Footer.css"; const Footer = () => { return ( <footer className="footer"> <div className="footer__container"> <div className="footer__containerName"> <h2> {"© "}Library App {new Date().getFullYear()} </h2> </div> <div className="footer__containerInfo"> <div className="footer__containerInfoItem"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-telephone-fill" viewBox="0 0 16 16" > <path fillRule="evenodd" d="M1.885.511a1.745 1.745 0 0 1 2.61.163L6.29 2.98c.329.423.445.974.315 1.494l-.547 2.19a.678.678 0 0 0 .178.643l2.457 2.457a.678.678 0 0 0 .644.178l2.189-.547a1.745 1.745 0 0 1 1.494.315l2.306 1.794c.829.645.905 1.87.163 2.611l-1.034 1.034c-.74.74-1.846 1.065-2.877.702a18.634 18.634 0 0 1-7.01-4.42 18.634 18.634 0 0 1-4.42-7.009c-.362-1.03-.037-2.137.703-2.877L1.885.511z" /> </svg> <p>+48 123 123 123</p> </div> <div className="footer__containerInfoItem"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-geo-alt-fill" viewBox="0 0 16 16" > <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10zm0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6z" /> </svg> <p>Kraków ul. Dluga 123</p> </div> <div className="footer__containerInfoItem"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-envelope-fill" viewBox="0 0 16 16" > <path d="M.05 3.555A2 2 0 0 1 2 2h12a2 2 0 0 1 1.95 1.555L8 8.414.05 3.555zM0 4.697v7.104l5.803-3.558L0 4.697zM6.761 8.83l-6.57 4.027A2 2 0 0 0 2 14h12a2 2 0 0 0 1.808-1.144l-6.57-4.027L8 9.586l-1.239-.757zm3.436-.586L16 11.801V4.697l-5.803 3.546z" /> </svg> <p><EMAIL></p> </div> </div> </div> </footer> ); }; export default Footer; <file_sep>import React, { useState, useEffect } from "react"; import { Link, useHistory } from "react-router-dom"; import { useAuthContext } from "../../context/auth/AuthState"; import Spinner from "../../components/Spinner/Spinner"; import "./SignupPage.css"; const SignupPage = () => { const defaultState = { given_name: "", family_name: "", email: "", password: "", password2: "" }; const history = useHistory(); const [isSubmitting, setIsSubmitting] = useState(false); const [errors, setErrors] = useState({}); const [values, setValues] = useState(defaultState); const { registerUser, registerFail, errorMessage, registerSuccess, user, clearErrors, loading } = useAuthContext(); const onChange = e => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const validate = values => { let errors = {}; if (!values.given_name) { errors.given_name = "Name is required!"; } if (!values.family_name) { errors.family_name = "Last name is required!"; } if (!values.email) { errors.email = "Email address is required!"; } else if (!/\S+@\S+\.\S+/.test(values.email)) { errors.email = "Email address is invalid"; } if (!values.password) { errors.password = "<PASSWORD>!"; } else if (values.password.length < 6) { errors.password = "Password needs to be more than 6 characters!"; } if (!values.password2) { errors.password2 = "Confirm password!"; } else if (values.password !== values.password2) { errors.password2 = "Passwords do not match!"; } return errors; }; const handleSubmit = e => { e.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; useEffect(() => { clearErrors(); }, []); useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { registerUser(values); setValues(defaultState); } // eslint-disable-next-line }, [errors, isSubmitting]); useEffect(() => { if (registerSuccess && user) { history.push(`/confirm/${user.username}`); } }, [registerSuccess]); return ( <div className="signupPage"> {loading && <Spinner />} <h1>Signup Page</h1> <div className="signupPage__container"> <div className="signupPage__content"> <h2>Create Account</h2> <form className="singupPage__form" onSubmit={handleSubmit}> <div className="signupPage__formGroup"> <input className={`signupPage__formGroupInput ${errors.given_name && "form-control is-invalid"}`} type="text" id="given_name" name="given_name" value={values.given_name} onChange={onChange} placeholder="<NAME>" /> {errors.given_name && ( <label className="singupPage__formLabel" htmlFor="given_name"> {errors.given_name} </label> )} </div> <div className="signupPage__formGroup"> <input className={`signupPage__formGroupInput ${errors.family_name && "form-control is-invalid"}`} type="text" id="family_name" name="family_name" value={values.family_name} onChange={onChange} placeholder="<NAME>" /> {errors.family_name && ( <label className="singupPage__formLabel" htmlFor="family_name"> {errors.family_name} </label> )} </div> <div className="signupPage__formGroup"> <input className={`signupPage__formGroupInput ${errors.email && "form-control is-invalid"}`} type="email" id="email" name="email" value={values.email} onChange={onChange} placeholder="Your Email" autoComplete="username" /> {errors.email && ( <label className="singupPage__formLabel" htmlFor="email"> {errors.email} </label> )} </div> <div className="signupPage__formGroup"> <input className={`signupPage__formGroupInput ${errors.password && "form-control is-invalid"}`} type="password" id="password" name="password" values={values.password} onChange={onChange} placeholder="<PASSWORD>" autoComplete="new-password" /> {errors.password && ( <label className="singupPage__formLabel" htmlFor="password"> {errors.password} </label> )} </div> <div className="signupPage__formGroup"> <input className={`signupPage__formGroupInput ${errors.password2 && "form-control is-invalid"}`} type="password" id="password2" name="password2" values={values.password2} onChange={onChange} placeholder="Repeat your password" autoComplete="new-password" /> {errors.password2 && ( <label className="singupPage__formLabel" htmlFor="password2"> {errors.password2} </label> )} </div> <div className="signupPage__formGroup"> <input type="submit" value="SUBMIT" className="signupPage__formSubmit" placeholder="SUBMIT" name="submit" /> {registerFail && ( <label className="singupPage__formLabel" htmlFor="submit"> {errorMessage} </label> )} </div> </form> <p className="signupPage__login"> Have already an account?{" "} <Link to="/signin" className="signupPage__link"> Login Here </Link> </p> </div> </div> </div> ); }; export default SignupPage; <file_sep>Demo: https://master.d17icfg1cxzgia.amplifyapp.com/ In this project I used AWS Amplify you can create your own account or login to test account: Email: <EMAIL> Password: <PASSWORD> <file_sep>/* eslint-disable */ export const processOrder = /* GraphQL */ ` mutation ProcessOrder($input: ProcessOrderInput!) { processOrder(input: $input) } `; export const createAuthor = /* GraphQL */ ` mutation CreateAuthor( $input: CreateAuthorInput! $condition: ModelAuthorConditionInput ) { createAuthor(input: $input, condition: $condition) { id firstName lastName birthDate description createdAt updatedAt books { nextToken } } } `; export const updateAuthor = /* GraphQL */ ` mutation UpdateAuthor( $input: UpdateAuthorInput! $condition: ModelAuthorConditionInput ) { updateAuthor(input: $input, condition: $condition) { id firstName lastName birthDate description createdAt updatedAt books { nextToken } } } `; export const deleteAuthor = /* GraphQL */ ` mutation DeleteAuthor( $input: DeleteAuthorInput! $condition: ModelAuthorConditionInput ) { deleteAuthor(input: $input, condition: $condition) { id firstName lastName birthDate description createdAt updatedAt books { nextToken } } } `; export const createBook = /* GraphQL */ ` mutation CreateBook( $input: CreateBookInput! $condition: ModelBookConditionInput ) { createBook(input: $input, condition: $condition) { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status orders { nextToken } image { name bucket region key } updatedAt author { id firstName lastName birthDate description createdAt updatedAt } } } `; export const updateBook = /* GraphQL */ ` mutation UpdateBook( $input: UpdateBookInput! $condition: ModelBookConditionInput ) { updateBook(input: $input, condition: $condition) { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status orders { nextToken } image { name bucket region key } updatedAt author { id firstName lastName birthDate description createdAt updatedAt } } } `; export const deleteBook = /* GraphQL */ ` mutation DeleteBook( $input: DeleteBookInput! $condition: ModelBookConditionInput ) { deleteBook(input: $input, condition: $condition) { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status orders { nextToken } image { name bucket region key } updatedAt author { id firstName lastName birthDate description createdAt updatedAt } } } `; export const createBookOrder = /* GraphQL */ ` mutation CreateBookOrder( $input: CreateBookOrderInput! $condition: ModelBookOrderConditionInput ) { createBookOrder(input: $input, condition: $condition) { id book_id order_id status customerId createdAt updatedAt book { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status updatedAt } customer } } `; export const updateBookOrder = /* GraphQL */ ` mutation UpdateBookOrder( $input: UpdateBookOrderInput! $condition: ModelBookOrderConditionInput ) { updateBookOrder(input: $input, condition: $condition) { id book_id order_id status customerId createdAt updatedAt book { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status updatedAt } customer } } `; export const deleteBookOrder = /* GraphQL */ ` mutation DeleteBookOrder( $input: DeleteBookOrderInput! $condition: ModelBookOrderConditionInput ) { deleteBookOrder(input: $input, condition: $condition) { id book_id order_id status customerId createdAt updatedAt book { id title authorID createdAt authorName publisher publishedDate language description category totalPages isbn totalCopies status updatedAt } customer } } `; export const createOrder = /* GraphQL */ ` mutation CreateOrder( $input: CreateOrderInput! $condition: ModelOrderConditionInput ) { createOrder(input: $input, condition: $condition) { id customer customerId status createdAt books { nextToken } updatedAt } } `; export const updateOrder = /* GraphQL */ ` mutation UpdateOrder( $input: UpdateOrderInput! $condition: ModelOrderConditionInput ) { updateOrder(input: $input, condition: $condition) { id customer customerId status createdAt books { nextToken } updatedAt } } `; export const deleteOrder = /* GraphQL */ ` mutation DeleteOrder( $input: DeleteOrderInput! $condition: ModelOrderConditionInput ) { deleteOrder(input: $input, condition: $condition) { id customer customerId status createdAt books { nextToken } updatedAt } } `; export const createCustomer = /* GraphQL */ ` mutation CreateCustomer( $input: CreateCustomerInput! $condition: ModelCustomerConditionInput ) { createCustomer(input: $input, condition: $condition) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; export const updateCustomer = /* GraphQL */ ` mutation UpdateCustomer( $input: UpdateCustomerInput! $condition: ModelCustomerConditionInput ) { updateCustomer(input: $input, condition: $condition) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; export const deleteCustomer = /* GraphQL */ ` mutation DeleteCustomer( $input: DeleteCustomerInput! $condition: ModelCustomerConditionInput ) { deleteCustomer(input: $input, condition: $condition) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; <file_sep>import React, { useState, useEffect } from "react"; import { Link, useHistory } from "react-router-dom"; import { useAuthContext } from "../../context/auth/AuthState"; import Spinner from "../../components/Spinner/Spinner"; import "./ForgotPasswordPage.css"; const ForgotPasswordPage = () => { const history = useHistory(); const [email, setEmail] = useState(""); const [errors, setErrors] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const { forgotPasswordSuccess, errorMessage, forgotPassword, loading, clearErrors } = useAuthContext(); const onChange = e => { setEmail(e.target.value); }; const validate = value => { let errors = ""; if (!value) { errors = "Email address is required!"; } else if (!/\S+@\S+\.\S+/.test(value)) { errors = "Email address is invalid"; } return errors; }; const handleSubmit = e => { e.preventDefault(); setErrors(validate(email)); setIsSubmitting(true); }; useEffect(() => { if (errors.length === 0 && isSubmitting) { forgotPassword(email); } }, [errors, isSubmitting]); useEffect(() => { if (forgotPasswordSuccess) { history.push(`/new-password/${email}`); } }, [forgotPasswordSuccess]); useEffect(() => { clearErrors(); }, []); return ( <div className="forgotPasswordPage"> {loading && <Spinner />} <h1>Forgot Password</h1> <div className="forgotPasswordPage__container"> <div className="forgotPasswordPage__content"> <h2>Forgot Password</h2> <form onSubmit={handleSubmit} className="forgotPasswordPage__form"> <div className="forgotPasswordPage__formGroup"> <input className={`forgotPasswordPage__formGroupInput ${errors && "form-control is-invalid"} `} type="email" id="username" name="username" placeholder="Your Email" value={email} onChange={onChange} /> {errors && ( <label className="forgotPasswordPage__formLabel" htmlFor="username" > {errors} </label> )} </div> <div className="forgotPasswordPage__submitGroup"> <Link to={`/confirm/${email}`} className="forgotPasswordPage__submitGroupLink" > Go to Confirm Page </Link> <input type="submit" value="SUBMIT" name="submit" placeholder="SUBMIT" className="forgotPasswordPage__submitGroupSubmit" /> </div> {errorMessage && ( <p className="forgotPasswordPage__errorMessage" htmlFor="submit"> {errorMessage} </p> )} </form> </div> </div> </div> ); }; export default ForgotPasswordPage; <file_sep>import React from "react"; import "./BasketPageBook.css"; const BasketPageBook = ({ book, basket, deleteElement }) => { const handleDelete = e => { e.preventDefault(); const newBasket = basket.filter(item => { return item.id !== book.id; }); deleteElement(newBasket); }; return ( <div className="basketPageBook"> <div className="basketPageBook__container"> <div className="basketPageBook__img"> <img src={book.link} alt="" /> </div> <div className="basketPageBook__containerDescription"> <p className="basketPageBook__title">{book.title}</p> <p className="basketPageBook__author">{book.authorName}</p> <p className="basketPageBook__category">{book.category}</p> <p className="basketPageBook__totalPages"> Total pages: {book.totalPages} </p> <div className="basketPageBook__containerBtn"> <button className="basketPageBook__deleteBtn" onClick={handleDelete} > Delete </button> </div> </div> </div> </div> ); }; export default BasketPageBook; <file_sep>/* eslint-disable */ // this is an auto generated file. This will be overwritten export const onCreateCustomer = /* GraphQL */ ` subscription OnCreateCustomer($id: String) { onCreateCustomer(id: $id) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; export const onUpdateCustomer = /* GraphQL */ ` subscription OnUpdateCustomer($id: String) { onUpdateCustomer(id: $id) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; export const onDeleteCustomer = /* GraphQL */ ` subscription OnDeleteCustomer($id: String) { onDeleteCustomer(id: $id) { id firstName email lastName ordersByDate { nextToken } ordersByStatus { nextToken } createdAt updatedAt } } `; <file_sep>import { CREATE_AUTHOR, CREATE_AUTHOR_FAIL, GET_AUTHOR, GET_AUTHOR_FAIL, LIST_AUTHORS, LIST_AUTHORS_FAIL, CREATE_BOOK, CREATE_BOOK_FAIL, LIST_BOOKS, LIST_BOOKS_FAIL, GET_BOOK, GET_BOOK_FAIL, ADD_TO_BASKET, ADD_TO_BASKET_FAIL, DELETE_FROM_BASKET, DELETE_BASKET, CREATE_ORDER, CREATE_ORDER_FAIL, GET_USER_ORDERS, GET_USER_ORDERS_FAIL, CLEAR_FORM, SET_LOADING } from "../types"; const bookReducer = (state, action) => { switch (action.type) { case CREATE_AUTHOR: return { ...state, createAuthorSuccess: true, author: action.payload, formSuccess: true, loading: false }; case CREATE_AUTHOR_FAIL: return { ...state, createAuthorSuccess: false, formFail: true, formErrorMessage: action.payload.message, loading: false }; case GET_AUTHOR: return { ...state, author: action.payload }; case GET_AUTHOR_FAIL: return { ...state, errorMessage: action.payload }; case LIST_AUTHORS: return { ...state, authors: action.payload }; case LIST_AUTHORS_FAIL: return { ...state, errorMessage: action.payload }; case CREATE_BOOK: return { ...state, book: action.payload, formSuccess: true, createBookSuccess: true, loading: false }; case CREATE_BOOK_FAIL: return { ...state, formFail: true, formErrorMessage: action.payload.message, createBookSuccess: false, loading: false }; case LIST_BOOKS: return { ...state, books: { ...state.books, [action.payload.category]: action.payload.books } }; case LIST_BOOKS_FAIL: return { ...state, errorMessage: action.payload }; case GET_BOOK: return { ...state, book: action.payload }; case GET_BOOK_FAIL: return { ...state, errorMessage: action.payload }; case ADD_TO_BASKET: return { ...state, basket: [...state.basket, action.payload] }; case ADD_TO_BASKET_FAIL: return { ...state, errorMessage: action.payload }; case DELETE_FROM_BASKET: return { ...state, basket: action.payload }; case DELETE_BASKET: return { ...state, basket: [] }; case CREATE_ORDER: return { ...state, order: action.payload, orderSuccess: true }; case CREATE_ORDER_FAIL: return { ...state, errorMessage: action.payload, orderSuccess: false }; case GET_USER_ORDERS: return { ...state, orders: action.payload, getOrdersSuccess: true }; case GET_USER_ORDERS_FAIL: return { ...state, errorMessage: action.payload, getOrdersSuccess: false }; case CLEAR_FORM: return { ...state, createAuthorSuccess: false, createBookSuccess: false, formFail: false, formSuccess: false, orderSuccess: false, getOrdersSuccess: false, formErrorMessage: "", errorMessage: "", author: {} }; case SET_LOADING: return { ...state, loading: true }; default: return state; } }; export default bookReducer; <file_sep>import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { useAuthContext } from "../../context/auth/AuthState"; import Spinner from "../../components/Spinner/Spinner"; import "./ConfirmPage.css"; const ConfirmPage = props => { const defaultState = { username: props.match.params.username, code: "" }; const [values, setValues] = useState(defaultState); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const { errorMessage, confirmRegister, confirmRegisterUser, clearErrors, loading } = useAuthContext(); const onChange = e => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const validate = values => { let errors = {}; if (!values.username) { errors.username = "Email address is required!"; } else if (!/\S+@\S+\.\S+/.test(values.username)) { errors.username = "Email address is invalid"; } if (!values.code) { errors.code = "Code is required!"; } return errors; }; const handleConfirm = e => { e.preventDefault(); setErrors(validate(values)); setIsSubmitting(true); }; useEffect(() => { if (Object.keys(errors).length === 0 && isSubmitting) { confirmRegisterUser(values); } // eslint-disable-next-line }, [errors, isSubmitting]); useEffect(() => { clearErrors(); }, []); return ( <div className="confirmPage"> {loading && <Spinner />} <h1>Confirm Page</h1> <div className="confirmPage__container"> <div className="confirmPage__content"> <h2>Confirm Email</h2> <form onSubmit={handleConfirm} className="confirmPage__form"> <div className="confirmPage__formGroup"> <input className={`confirmPage__formGroupInput ${errors.username && "form-control is-invalid"} `} type="email" id="username" name="username" placeholder="Your Email" value={values.username} onChange={onChange} /> {errors.username && ( <label className="confirmPage__formLabel" htmlFor="username"> {errors.username} </label> )} </div> <div className="confirmPage__formGroup"> <input className={`confirmPage__formGroupInput ${errors.code && "form-control is-invalid"} `} type="text" id="code" name="code" placeholder="Confirm Code" value={values.code} onChange={onChange} autoFocus /> {errors.code && ( <label className="confirmPage__formLabel" htmlFor="code"> {errors.code} </label> )} </div> <div className="confirmPage__formGroup"> <input type="submit" name="submit" value="SUBMIT" placeholder="SUBMIT" className="confirmPage__formSubmit" /> {errorMessage && ( <label className="confirmPage__formLabel" htmlFor="submit"> {errorMessage} </label> )} </div> </form> {confirmRegister && ( <p className="confirmPage__registerSuccess"> Cosnfirmation Succcess </p> )} <div className="confirmPage__containerLinks"> <Link to="/signin" className="confirmPage__link"> Go to Signin Page </Link> <Link to="/resendcode" className="confirmPage__link"> Go to Resend Code Page </Link> </div> </div> </div> </div> ); }; export default ConfirmPage; <file_sep>import { REGISTER_SUCCESS, REGISTER_FAIL, CONFIRM_REGISTER_SUCCESS, CONFIRM_REGISTER_FAIL, RESEND_CODE_SUCCESS, RESEND_CODE_FAIL, LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED, AUTH_ERROR, LOGOUT_SUCCESS, FORGOT_PASSWORD_SUCCESS, FORGOT_PASSWORD_FAIL, NEW_PASSWORD_SUCCESS, NEW_PASSWORD_FAIL, CHANGE_PASSWORD_SUCCESS, CHANGE_PASSWORD_FAIL, CLEAR_ERRORS, SET_LOADING } from "../types"; export default (state, action) => { switch (action.type) { case USER_LOADED: return { ...state, isLogged: true, loadingUser: false, loading: false, user: action.payload.attributes, group: action.payload.signInUserSession.idToken.payload["cognito:groups"] }; case AUTH_ERROR: return { ...state, loadingUser: false, isLogged: false, loading: false, user: {}, group: [] }; case REGISTER_SUCCESS: return { ...state, registerSuccess: true, user: action.payload, loading: false }; case REGISTER_FAIL: return { ...state, registerFail: true, errorMessage: action.payload, loading: false }; case CONFIRM_REGISTER_SUCCESS: return { ...state, confirmRegister: true, loading: false }; case CONFIRM_REGISTER_FAIL: return { ...state, confirmRegister: false, errorMessage: action.payload, loading: false }; case RESEND_CODE_SUCCESS: return { ...state, resendCode: true, loading: false }; case RESEND_CODE_FAIL: return { ...state, errorMessage: action.payload, loading: false }; case LOGIN_SUCCESS: return { ...state, loading: false, loginSuccess: true, loadingUser: false, loginFail: false, isLogged: true, user: action.payload.attributes, group: action.payload.signInUserSession.idToken.payload["cognito:groups"] }; case LOGIN_FAIL: return { ...state, loading: false, loadingUser: false, errorMessage: action.payload, loginFail: true, loginSuccess: false }; case LOGOUT_SUCCESS: return { ...state, logoutSuccess: true, user: {}, group: [], loginSuccess: false, isLogged: false }; case FORGOT_PASSWORD_SUCCESS: return { ...state, forgotPasswordSuccess: true, loading: false }; case FORGOT_PASSWORD_FAIL: return { ...state, errorMessage: action.payload, loading: false }; case NEW_PASSWORD_SUCCESS: return { ...state, newPasswordSuccess: true, loading: false }; case NEW_PASSWORD_FAIL: return { ...state, newPasswordSuccess: false, errorMessage: action.payload, loading: false }; case CHANGE_PASSWORD_SUCCESS: return { ...state, changePasswordSuccess: true, errorMessage: true, loading: false }; case CHANGE_PASSWORD_FAIL: return { ...state, changePasswordSuccess: false, errorMessage: action.payload, loading: false }; case CLEAR_ERRORS: return { ...state, changePasswordSuccess: false, newPasswordSuccess: false, forgotPasswordSuccess: false, logoutSuccess: false, registerSuccess: false, registerFail: false, confirmRegister: false, resendCode: false, errorMessage: "" }; case SET_LOADING: return { ...state, loading: true }; default: return state; } };
62d04f8de6017c3361e87e4da2b8cf08ae5325a4
[ "JavaScript", "Markdown" ]
22
JavaScript
M-Kolodziejczyk/library-app
ba5864454d3d3e7c5e3933269a5862ea31c3400c
8a4a51eb1f02f3e773600ccf3da1d7f2e7db8845
refs/heads/master
<file_sep>package org.test1; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.sikuli.script.FindFailed; import org.sikuli.script.Pattern; import org.sikuli.script.Screen; public class SikuliTesting { public static void main(String[] args) throws FindFailed { System.setProperty("webdriver.chrome.driver", "C:\\Users\\jegan\\eclipse-workspace\\MavenSample\\div\\chromedriver.exe"); WebDriver d=new ChromeDriver(); d.get("https://www.youtube.com/watch?v=lQWnIA0pJss"); Screen s=new Screen(); Pattern PlayImg=new Pattern("YT_PlayButton.png"); s.wait(PlayImg, 2000); s.click(); s.click(); Pattern PauseImg=new Pattern("YT_PauseButton (1).png"); s.wait(PauseImg, 5000); s.click(); s.click(); Pattern SettingImg=new Pattern("YT_Settings.png"); s.wait(SettingImg, 2000); s.click(); } } <file_sep>package org.test1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteExcel { public static void main(String[] args) throws IOException { File loc=new File("C:\\Users\\jegan\\eclipse-workspace\\MavenSample\\Excel\\Siva.xlsx"); FileOutputStream o=new FileOutputStream(loc); Workbook w=new XSSFWorkbook(); Sheet s = w.createSheet("Siva"); Row r = s.createRow(4); Cell c = r.createCell(2); c.setCellValue("Write"); w.write(o); System.out.println("Wrote Successfully"); } }
25c5a857f2a6a44a7cb23150445bbf8f4cb38c30
[ "Java" ]
2
Java
sivagane/MavenSample
14ed5e6fd960b5b825ceeacb63b251e265f9cc0c
446138a4aa5641a9f713af2e1f4ba2d214a95cdb
refs/heads/master
<file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: AccessController.inc *@FileCreator: Green Box Admin *@Comments: Access controller file */ //START// $RequestDateTime = date('Y-m-d H:i:s'); $TimeStart = microtime(true); $OutputArray = array(); $OutputArray["ApiStatus"] = null; $OutputArray["OperationalStatus"] = null; $OutputArray["OutputDatas"] = $OutputDatas = null; if($ApiSecureKey == '1234') { // Load your controller here if(file_exists($ActionController)) { include $ActionController; $OperationalStatus = 'Success'; $OperationalMessage = "Your {$ReqController}'s action executed!"; } else { $OperationalStatus = 'Failed'; $OperationalMessage = "Your {$ReqController}'s action controller not found"; } } else { $OperationalStatus = 'Failed'; $OperationalMessage = "Your API Secure Key is invalid"; } $TimeEnd = microtime(true); $ExecutionTime = number_format((float)($TimeEnd - $TimeStart), 4, '.', ''). ' second(s)'; <file_sep><?php // File define('DBCon_MySQL_dbconfig', "{$ConfigDir}MySQL_dbconfig.inc"); // Class define('Class_MySQLi', "{$LibsDir}Classes/ClassMySQLi.inc"); // Functions define('Function_gmtDateTime', "{$LibsDir}Functions/Function_gmtDateTime.inc"); define('Function_dt2mil2dt', "{$LibsDir}Functions/Function_dt2mil2dt.inc"); define('Function_gmt2gmt0mil', "{$LibsDir}Functions/Function_gmt2gmt0mil.inc"); define('Function_security_key', "{$LibsDir}Functions/security_key_function.inc"); define('Function_getIp', "{$LibsDir}Functions/getIp_function.inc"); define('Function_login_check', "{$LibsDir}Functions/login_check_function.inc"); define('Function_gotourl', "{$LibsDir}Functions/gotourl_function.inc"); define('Function_tuddc', "{$LibsDir}Functions/tuddc_function.inc"); define('Function_get_all_option', "{$LibsDir}Functions/get_all_option_function.inc"); define('Function_insertq', "{$LibsDir}Functions/insertq_function.inc"); define('Function_updateq', "{$LibsDir}Functions/updateq_function.inc"); define('Function_query_safe', "{$LibsDir}Functions/query_safe_function.inc"); define('Function_in_array_value_exist', "{$LibsDir}Functions/in_array_value_exist_function.inc"); define('Function_loan_cal', "{$LibsDir}Functions/loan_cal_function.inc"); define('Function_array_to_xml', "{$LibsDir}Functions/array_to_xml_function.inc"); <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function gmtDateTime($timezone, $format) { if($timezone == '') { $timezone = 0; } $zone = 3600 * $timezone; if($format == '') { $format = 'Y/m/d H:i:s'; } $GMTDateTime = gmdate($format, time()+ $zone); return $GMTDateTime; } <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: configurations.inc *@FileCreator: Green Box Admin *@Comments: Config file */ //START// // API Properties $ApiName = 'Test API By GAPIF'; $ApiAuthor = 'Green Box'; $ApiVersion = $ApiStatus; $BaseURL = "http://127.0.0.1/gapif/"; //Shared variable here $PassSalt = ''; $GMAPAPI = ''; // Get Mods $getmods = filter_input(INPUT_GET, 'mods'); $mods = explode('/', $getmods); if(count($mods)< 2) { // Load error JSON exit('Something is wrong! You have No Access!'); } else { $ApiSecureKey = $mods[0]; // $OutputType = $mods[1]; // JSON/XML if($mods[2] != '') { $ReqController = $mods[2]; } else { $ReqController = $mods[2] = 'GAPIF'; } } // Set Controllers Location (As Root Index) $ControllerLocation = $ApiDirectory . "Controllers/"; // Config Diretory $ConfigDir = $ApiDirectory . "Configs/"; // System Library Directory $LibsDir = $ApiDirectory . 'Systems/'; // Request/Action Controller file $ActionControllerLocation = $ControllerLocation . 'ActionController/'; // Default Access Controller file $AccessController = $ControllerLocation . 'AccessController.inc'; // Default Output Controller file $OutputController = $ControllerLocation . 'OutputController' . $OutputType . '.inc'; // Request/Action Controller file $ActionController = $ActionControllerLocation . $ReqController . 'Controller.inc'; // Call universal resource // Include Liberary for override the php ini propertise include("{$ConfigDir}phpiniconfig.inc"); // Include System Liberary Diretory File include("{$ConfigDir}systems_dir.inc"); include Function_gmtDateTime; include Function_dt2mil2dt; //END// <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: GAPIF.php *@FileCreator: Green Box Admin *@Comments: Init starting file */ //START// //header("Access-Control-Allow-Origin: *"); //header("Access-Control-Allow-Credentials: true"); //header('Content-Type: application/json'); /* * Api Status Value is current condition/version of your API */ $ApiStatus = 'dev'; // Example: dev, prod, v1, v1.1, v1.1.0 $ApiFrameWork = 'Green API Framework'; /* * Api Directory is the loaction of your api resource.. **Include slash symbol '/' after directory name */ $ApiRootDirectory = $_SERVER['DOCUMENT_ROOT'] . '/' . basename(dirname(__FILE__)). '/'; $ApiDirectory = $ApiRootDirectory . $ApiStatus . 'api/'; /* * SET ROUTE file name with directory */ $RouteDirectory = $ApiDirectory . 'ApiRoute.inc'; /* * Include Route File to Load your page . . . . . */ include $RouteDirectory; <file_sep><?php include Class_MySQLi; $DBCon = new ClassMySQLi('127.0.0.1', 'root', 'mysql', 'alumni_db'); $DBCon->setPrefix('gb_'); /* change character set to utf8*/ <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: phpiniconfig.inc *@FileCreator: Green Box Admin *@Comments: PHP ini Config */ //START// // Set default timezone date_default_timezone_set('Asia/Dhaka'); // Set display_errors ini_set('display_errors', 'On'); // Set max_execution_time ini_set('max_execution_time', '30'); <file_sep><?php include DBCon_MySQL_dbconfig; $GAPIF_OutputDatas = array('Message' => 'Welcome to Green API Framework (GAPIF)! Check the documentation of GAPIF.', 'Documentation' => 'https://gapif.gr33nbox.work'); <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: OutputControllerXML.inc *@FileCreator: Green Box Admin *@Comments: Output controller XML file */ //START// header('Content-Type: application/xml; charset=utf-8'); include Function_array_to_xml; $OutputArray["ApiStatus"] = array("ApiName" =>$ApiName, "ApiAuthor" =>$ApiAuthor, "ApiVersion" =>$ApiVersion, "ApiFrameWork" =>$ApiFrameWork); $OutputArray["OperationalStatus"] = array("OperationalName" =>$ReqController, "OperationalStatus" =>$OperationalStatus, "OperationalMessage" =>$OperationalMessage, "RequestDateTime" =>$RequestDateTime, "ExecutionTime" =>$ExecutionTime); print array_to_xml($OutputArray); <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function gmt2gmt0mil($mil, $timezone, $mil_plus_minus) { return($mil -(1 *($timezone *(3600000))))+ $mil_plus_minus; } <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: array_to_xml_function.inc *@FileCreator: Green Box Admin *@Comments: Array to xml */ //START// function array_to_xml($array, $wrap = 'OutputXML', $upper = true) { // set initial value for XML string $xml = ''; // wrap XML with $wrap TAG if($wrap != null) { $xml .= "<$wrap>\n"; } // main loop foreach($array as $key => $value) { // set tags in uppercase if needed if($upper == true) { $key = strtoupper($key); } // append to XML string $xml .= "<$key>" . htmlspecialchars(trim($value)). "</$key>"; } // close wrap TAG if needed if($wrap != null) { $xml .= "\n</$wrap>\n"; } // return prepared XML string return $xml; } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function dt2mil2dt($DT, $Mil, $DTFormat, $timezone) { if($DT == '' && $Mil != '') { // Returm Datetime if($DTFormat == '') { $DTFormat = 'Y/m/d H:i:s'; } // if($timezone != '' && is_numeric($timezone)) { $timezone = $timezone; } else { $timezone = 0; } $Millis =($Mil +($timezone * 3600000))/ 1000; return date($DTFormat, $Millis); } elseif($DT != '' && $Mil == '') { // Done return strtotime($DT)* 1000; } } <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: ApiRoute.inc *@FileCreator: Green Box Admin *@Comments: Routing file */ //START// header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST'); // Include Config File include("{$ApiDirectory}Configs/configurations.inc"); // Include Access & Ouput Controller if(file_exists($AccessController)&& file_exists($OutputController)) { include($AccessController); include($OutputController); } else { header('Content-Type: application/json'); echo json_encode("Access or,and Output Controller not exist(s)."); } <file_sep><?php /*@Green Api Framework [An Open Source API Framework Based On PHP] *@Developer Agency: Green Box *@Publisher Agency: Open Source Solver *@Author: Green Box & Open Source Solver *@Copyright: Green Box & Open Source Solver *@Copyright Under: http://creativecommons.org/licenses/by-nc-sa/4.0/ *@Contact: <EMAIL>, www.gr33nbox.work *@Address: Dhaka, Bangladesh */ /*@FileName: .............filename.php............. *@FileCreator: .............creator name............. *@Comments: .............comments............. */ //START// // .............Your PHP code here...............
35fe75991d7c22870f8a7a2f62f57f48e62f13f2
[ "PHP" ]
14
PHP
GR33NBOX/GAPIF
c51af87fd5c23e6b4f2a888ef05876d0e29f2d5c
8d945c80af74e2882d70bcd42f9b384071663f5c
refs/heads/master
<repo_name>mbibko/vdohnovenie.github.io<file_sep>/app/js/main.js 'use strict'; // (function($) { // var $event = $.event, // $special, // resizeTimeout; // $special = $event.special.debouncedresize = { // setup: function() { // $(this).on("resize", $special.handler); // }, // teardown: function() { // $(this).off("resize", $special.handler); // }, // handler: function(event, execAsap) { // // Save the context // var context = this, // args = arguments, // dispatch = function() { // // set correct event type // event.type = "debouncedresize"; // $event.dispatch.apply(context, args); // }; // if (resizeTimeout) { // clearTimeout(resizeTimeout); // } // execAsap ? // dispatch() : // resizeTimeout = setTimeout(dispatch, $special.threshold); // }, // threshold: 150 // }; // })(jQuery); // var wHeight = $(window).outerHeight(); // var wWidth = $(window).outerWidth(); // var screenOrientation = ($(window).width() > $(window).height()) ? 90 : 0; // $.fn.exists = function(callback) { // var args = [].slice.call(arguments, 1); // if (this.length) { // callback.call(this, args); // } // return this; // }; // var mobileBrowser = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // ;(function() { // var autosizeTextarea = autosize($('.js-autosize')); // }()); // ;(function() { // var $menu = $('.main-menu'); // $('.js-menu-link').on('click', function(e) { // $(this).toggleClass('active'); // if (!$menu.hasClass('active')) { // $menu.addClass('active'); // } else { // $menu.removeClass('active'); // }; // e.preventDefault(); // }); // $('.main-menu a, .js-scroll-to').on('click', function(e) { // $('html, body').animate({ // scrollTop: $($(this).attr('href')).offset().top // }, 900); // $menu.removeClass('active'); // e.preventDefault(); // }); // }()); // $(window).on('scroll', function() { // }); // $(window).on('resize', function() { // wHeight = $(window).outerHeight(); // wWidth = $(window).outerWidth(); // }); // $(document).on('click', function(event) { // if (!$(event.target).closest('#menucontainer').length) { // // Hide the menus. // } // });<file_sep>/app/js/dinamic-links.js ; (function() { // динамические линки на деревянные страницы $.ajax({ 'url': 'ajax.pages_list.php', 'type': 'get' }) .fail(function() { // alert('no pages'); }) .success(function(data) { if (data.toString().indexOf('<?php') == 0) return; var $wnd = $('<div style="font-size: 14px; color: #ffffff; position: absolute; top: 10px; left: 10px; background: #000000; border: 2px solid #cccccc; z-index: 51000; padding: 8px; "/>'); var $close = $('<a href="#" style="font-size: 14px; color: #ffffff; font-weight: normal; display: block;">Список шаблонов страниц :: Закрыть</a>') .click(function(e) { e.preventDefault(); $wnd.hide(); }) .appendTo($wnd); var even = false; $(data.pages).each(function() { var page = this; var style = even ? 'color: #000000; background: #aaaaaa; ' : 'background: #ffffff; color: #000000; ' $wnd.append('<a href="' + page + '" style="' + style + ' font-size: 14px; padding: 4px; font-weight: normal; display: block;">' + page + '</a>'); even = !even; }); $('body').append($wnd); }); }());<file_sep>/app/html/vvodnaya.html {% set currentPage = 'vvodnaya' %} {% extends "catalog.html" %} {% block content %} <div class="section-type-10"> <div class="container"> <div class="row"> <div class="col-md-8"> <section class="section-area"> {% for post in vvodnayaPosts %} <article class="b-post b-post_main clearfix"> <div class="entry-main"> <div class="entry-header"> <h2 class="entry-title"><a href="{{post.url}}.html">{{post.title}}</a></h2> </div> <div class="entry-content">{{post.excerpt}}</div> <div class="entry-footer"><a class="btn-bd-primary" href="{{post.url}}.html">Читать далее</a> </div> </div> </article> {% endfor %} </section> </div> <div class="col-md-4"> </div> </div> </div> </div> {% endblock %}
4ffabcdba59f3ebc737de01abb4424378ac95149
[ "JavaScript", "HTML" ]
3
JavaScript
mbibko/vdohnovenie.github.io
1ea67f1b50bd567e5dcbf5705f3815565b38eaca
5b08652f66a96a1687863e09ddc51488b340ed15
refs/heads/master
<file_sep>import os import re import json import copy import cgi import random import string import pytest import responses from urlobject import URLObject from nylas import APIClient # pylint: disable=redefined-outer-name,too-many-lines #### HANDLING PAGINATION #### # Currently, the Nylas API handles pagination poorly: API responses do not expose # any information about pagination, so the client does not know whether there is # another page of data or not. For example, if the client sends an API request # without a limit specified, and the response contains 100 items, how can it tell # if there are 100 items in total, or if there more items to fetch on the next page? # It can't! The only way to know is to ask for the next page (by repeating the API # request with `offset=100`), and see if you get more items or not. # If it does not receive more items, it can assume that it has retrieved all the data. # # This file contains mocks for several API endpoints, including "list" endpoints # like `/messages` and `/events`. The mocks for these list endpoints must be smart # enough to check for an `offset` query param, and return an empty list if the # client requests more data than the first page. If the mock does not # check for this `offset` query param, and returns the same mock data over and over, # any SDK method that tries to fetch *all* of a certain type of data # (like `client.messages.all()`) will never complete. def generate_id(size=25, chars=string.ascii_letters + string.digits): return "".join(random.choice(chars) for _ in range(size)) @pytest.fixture def message_body(): return { "busy": True, "calendar_id": "94rssh7bd3rmsxsp19kiocxze", "description": None, "id": "cv4ei7syx10uvsxbs21ccsezf", "location": "1 Infinite loop, Cupertino", "message_id": None, "namespace_id": "38<KEY>", "object": "event", "owner": None, "participants": [], "read_only": False, "status": "confirmed", "title": "The rain song", "when": { "end_time": 1441056790, "object": "timespan", "start_time": 1441053190, }, } @pytest.fixture def access_token(): return "<PASSWORD>" @pytest.fixture def account_id(): return "<KEY>" @pytest.fixture def api_url(): return "https://localhost:2222" @pytest.fixture def app_id(): return "fake-app-id" @pytest.fixture def app_secret(): return "nyl4n4ut" @pytest.fixture def api_client(api_url): return APIClient( app_id=None, app_secret=None, access_token=None, api_server=api_url ) @pytest.fixture def api_client_with_app_id(access_token, api_url, app_id, app_secret): return APIClient( app_id=app_id, app_secret=app_secret, access_token=access_token, api_server=api_url, ) @pytest.fixture def mocked_responses(): rmock = responses.RequestsMock(assert_all_requests_are_fired=False) with rmock: yield rmock @pytest.fixture def mock_save_draft(mocked_responses, api_url): save_endpoint = re.compile(api_url + "/drafts/") response_body = json.dumps( {"id": "4dl0ni6vxomazo73r5oydo16k", "version": "4dw0ni6txomazo33r5ozdo16j"} ) mocked_responses.add( responses.POST, save_endpoint, content_type="application/json", status=200, body=response_body, match_querystring=True, ) @pytest.fixture def mock_account(mocked_responses, api_url, account_id): response_body = json.dumps( { "account_id": account_id, "email_address": "<EMAIL>", "id": account_id, "name": "<NAME>", "object": "account", "provider": "gmail", "organization_unit": "label", "billing_state": "paid", "linked_at": 1500920299, "sync_state": "running", } ) mocked_responses.add( responses.GET, re.compile(api_url + "/account(?!s)/?"), content_type="application/json", status=200, body=response_body, ) @pytest.fixture def mock_accounts(mocked_responses, api_url, account_id, app_id): accounts = [ { "account_id": account_id, "email_address": "<EMAIL>", "id": account_id, "name": "<NAME>", "object": "account", "provider": "gmail", "organization_unit": "label", "billing_state": "paid", "linked_at": 1500920299, "sync_state": "running", } ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(accounts)) url_re = "{base}(/a/{app_id})?/accounts/?".format(base=api_url, app_id=app_id) mocked_responses.add_callback( responses.GET, re.compile(url_re), content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_folder_account(mocked_responses, api_url, account_id): response_body = json.dumps( { "email_address": "<EMAIL>", "id": account_id, "name": "<NAME>", "account_id": account_id, "object": "account", "provider": "eas", "organization_unit": "folder", } ) mocked_responses.add( responses.GET, api_url + "/account", content_type="application/json", status=200, body=response_body, match_querystring=True, ) @pytest.fixture def mock_labels(mocked_responses, api_url, account_id): labels = [ { "display_name": "Important", "id": "anuep8pe5ugmxrucchrzba2o8", "name": "important", "account_id": account_id, "object": "label", }, { "display_name": "Trash", "id": "f1xgowbgcehk235xiy3c3ek42", "name": "trash", "account_id": account_id, "object": "label", }, { "display_name": "Sent Mail", "id": "ah14wp5fvypvjjnplh7nxgb4h", "name": "sent", "account_id": account_id, "object": "label", }, { "display_name": "All Mail", "id": "ah14wp5fvypvjjnplh7nxgb4h", "name": "all", "account_id": account_id, "object": "label", }, { "display_name": "Inbox", "id": "dc11kl3s9lj4760g6zb36spms", "name": "inbox", "account_id": account_id, "object": "label", }, ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(labels)) endpoint = re.compile(api_url + "/labels.*") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_label(mocked_responses, api_url, account_id): response_body = json.dumps( { "display_name": "Important", "id": "anuep8pe5ugmxrucchrzba2o8", "name": "important", "account_id": account_id, "object": "label", } ) url = api_url + "/labels/anuep8pe5ugmxrucchrzba2o8" mocked_responses.add( responses.GET, url, content_type="application/json", status=200, body=response_body, ) @pytest.fixture def mock_folder(mocked_responses, api_url, account_id): folder = { "display_name": "My Folder", "id": "anuep8pe5ug3xrupchwzba2o8", "name": None, "account_id": account_id, "object": "folder", } response_body = json.dumps(folder) url = api_url + "/folders/anuep8pe5ug3xrupchwzba2o8" mocked_responses.add( responses.GET, url, content_type="application/json", status=200, body=response_body, ) def request_callback(request): payload = json.loads(request.body) if "display_name" in payload: folder.update(payload) return (200, {}, json.dumps(folder)) mocked_responses.add_callback( responses.PUT, url, content_type="application/json", callback=request_callback ) @pytest.fixture def mock_messages(mocked_responses, api_url, account_id): messages = [ { "id": "1234", "to": [{"email": "<EMAIL>", "name": "Foo"}], "from": [{"email": "<EMAIL>", "name": "Bar"}], "subject": "Test Message", "account_id": account_id, "object": "message", "labels": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": False, "unread": True, "date": 1265077342, }, { "id": "1238", "to": [{"email": "<EMAIL>", "name": "<NAME>"}], "from": [{"email": "<EMAIL>", "name": "<NAME>"}], "subject": "Test Message 2", "account_id": account_id, "object": "message", "labels": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": False, "unread": True, "date": 1265085342, }, { "id": "12", "to": [{"email": "<EMAIL>", "name": "<NAME>"}], "from": [{"email": "<EMAIL>", "name": "<NAME>"}], "subject": "Test Message 3", "account_id": account_id, "object": "message", "labels": [{"name": "archive", "display_name": "Archive", "id": "gone"}], "starred": False, "unread": False, "date": 1265093842, }, ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(messages)) endpoint = re.compile(api_url + "/messages") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback ) @pytest.fixture def mock_message(mocked_responses, api_url, account_id): base_msg = { "id": "1234", "to": [{"email": "<EMAIL>", "name": "Foo"}], "from": [{"email": "<EMAIL>", "name": "Bar"}], "subject": "Test Message", "account_id": account_id, "object": "message", "labels": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": False, "unread": True, } response_body = json.dumps(base_msg) def request_callback(request): payload = json.loads(request.body) if "labels" in payload: labels = [ {"name": "test", "display_name": "test", "id": l} for l in payload["labels"] ] base_msg["labels"] = labels return (200, {}, json.dumps(base_msg)) endpoint = re.compile(api_url + "/messages/1234") mocked_responses.add( responses.GET, endpoint, content_type="application/json", status=200, body=response_body, ) mocked_responses.add_callback( responses.PUT, endpoint, content_type="application/json", callback=request_callback, ) mocked_responses.add( responses.DELETE, endpoint, content_type="application/json", status=200, body="" ) @pytest.fixture def mock_threads(mocked_responses, api_url, account_id): threads = [ { "id": "5678", "subject": "Test Thread", "account_id": account_id, "object": "thread", "folders": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": True, "unread": False, "first_message_timestamp": 1451703845, "last_message_timestamp": 1483326245, "last_message_received_timestamp": 1483326245, "last_message_sent_timestamp": 1483232461, } ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(threads)) endpoint = re.compile(api_url + "/threads") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_thread(mocked_responses, api_url, account_id): base_thrd = { "id": "5678", "subject": "Test Thread", "account_id": account_id, "object": "thread", "folders": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": True, "unread": False, "first_message_timestamp": 1451703845, "last_message_timestamp": 1483326245, "last_message_received_timestamp": 1483326245, "last_message_sent_timestamp": 1483232461, } response_body = json.dumps(base_thrd) def request_callback(request): payload = json.loads(request.body) if "folder" in payload: folder = {"name": "test", "display_name": "test", "id": payload["folder"]} base_thrd["folders"] = [folder] return (200, {}, json.dumps(base_thrd)) endpoint = re.compile(api_url + "/threads/5678") mocked_responses.add( responses.GET, endpoint, content_type="application/json", status=200, body=response_body, ) mocked_responses.add_callback( responses.PUT, endpoint, content_type="application/json", callback=request_callback, ) @pytest.fixture def mock_labelled_thread(mocked_responses, api_url, account_id): base_thread = { "id": "111", "subject": "Labelled Thread", "account_id": account_id, "object": "thread", "folders": [{"name": "inbox", "display_name": "Inbox", "id": "abcd"}], "starred": True, "unread": False, "labels": [ { "display_name": "Important", "id": "anuep8pe5ugmxrucchrzba2o8", "name": "important", "account_id": account_id, "object": "label", }, { "display_name": "Existing", "id": "dfslhgy3rlijfhlsujnchefs3", "name": "existing", "account_id": account_id, "object": "label", }, ], "first_message_timestamp": 1451703845, "last_message_timestamp": 1483326245, "last_message_received_timestamp": 1483326245, "last_message_sent_timestamp": 1483232461, } response_body = json.dumps(base_thread) def request_callback(request): payload = json.loads(request.body) if "labels" in payload: existing_labels = {label["id"]: label for label in base_thread["labels"]} new_labels = [] for label_id in payload["labels"]: if label_id in existing_labels: new_labels.append(existing_labels[label_id]) else: new_labels.append( { "name": "updated", "display_name": "Updated", "id": label_id, "account_id": account_id, "object": "label", } ) copied = copy.copy(base_thread) copied["labels"] = new_labels return (200, {}, json.dumps(copied)) endpoint = re.compile(api_url + "/threads/111") mocked_responses.add( responses.GET, endpoint, content_type="application/json", status=200, body=response_body, ) mocked_responses.add_callback( responses.PUT, endpoint, content_type="application/json", callback=request_callback, ) @pytest.fixture def mock_drafts(mocked_responses, api_url): drafts = [ { "bcc": [], "body": "Cheers mate!", "cc": [], "date": 1438684486, "events": [], "files": [], "folder": None, "from": [], "id": "2h111aefv8pzwzfykrn7hercj", "namespace_id": "384uhp3aj8l7rpmv9s2y2rukn", "object": "draft", "reply_to": [], "reply_to_message_id": None, "snippet": "", "starred": False, "subject": "Here's an attachment", "thread_id": "clm33kapdxkposgltof845v9s", "to": [{"email": "<EMAIL>", "name": "<NAME>"}], "unread": False, "version": 0, } ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(drafts)) mocked_responses.add_callback( responses.GET, api_url + "/drafts", content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_draft_saved_response(mocked_responses, api_url): draft_json = { "bcc": [], "body": "Cheers mate!", "cc": [], "date": 1438684486, "events": [], "files": [], "folder": None, "from": [], "id": "2h111aefv8pzwzfykrn7hercj", "namespace_id": "384uhp3aj8l7rpmv9s2y2rukn", "object": "draft", "reply_to": [], "reply_to_message_id": None, "snippet": "", "starred": False, "subject": "Here's an attachment", "thread_id": "clm33kapdxkposgltof845v9s", "to": [{"email": "<EMAIL>", "name": "<NAME>"}], "unread": False, "version": 0, } def create_callback(_request): return (200, {}, json.dumps(draft_json)) def update_callback(request): try: payload = json.loads(request.body) except ValueError: return (200, {}, json.dumps(draft_json)) stripped_payload = {key: value for key, value in payload.items() if value} updated_draft_json = copy.copy(draft_json) updated_draft_json.update(stripped_payload) updated_draft_json["version"] += 1 return (200, {}, json.dumps(updated_draft_json)) mocked_responses.add_callback( responses.POST, api_url + "/drafts/", content_type="application/json", callback=create_callback, ) mocked_responses.add_callback( responses.PUT, api_url + "/drafts/2h111aefv8pzwzfykrn7hercj", content_type="application/json", callback=update_callback, ) @pytest.fixture def mock_draft_deleted_response(mocked_responses, api_url): mocked_responses.add( responses.DELETE, api_url + "/drafts/2h111aefv8pzwzfykrn7hercj", content_type="application/json", status=200, body="", ) @pytest.fixture def mock_draft_sent_response(mocked_responses, api_url): body = { "bcc": [], "body": "", "cc": [], "date": 1438684486, "events": [], "files": [], "folder": None, "from": [{"email": "<EMAIL>"}], "id": "2h111aefv8pzwzfykrn7hercj", "namespace_id": "384uhp3aj8l7rpmv9s2y2rukn", "object": "draft", "reply_to": [], "reply_to_message_id": None, "snippet": "", "starred": False, "subject": "Stay polish, stay hungary", "thread_id": "clm33kapdxkposgltof845v9s", "to": [{"email": "<EMAIL>", "name": "<NAME>"}], "unread": False, "version": 0, } values = [(400, {}, "Couldn't send email"), (200, {}, json.dumps(body))] def callback(request): payload = json.loads(request.body) assert payload["draft_id"] == "2h111aefv8pzwzfykrn7hercj" return values.pop() mocked_responses.add_callback( responses.POST, api_url + "/send/", callback=callback, content_type="application/json", ) @pytest.fixture def mock_files(mocked_responses, api_url, account_id): files_content = {"3qfe4k3siosfjtjpfdnon8zbn": b"Hello, World!"} files_metadata = { "3qfe4k3siosfjtjpfdnon8zbn": { "id": "3qfe4k3siosfjtjpfdnon8zbn", "content_type": "text/plain", "filename": "hello.txt", "account_id": account_id, "object": "file", "size": len(files_content["3qfe4k3siosfjtjpfdnon8zbn"]), } } mocked_responses.add( responses.GET, api_url + "/files", body=json.dumps(list(files_metadata.values())), ) for file_id in files_content: mocked_responses.add( responses.POST, "{base}/files/{file_id}".format(base=api_url, file_id=file_id), body=json.dumps(files_metadata[file_id]), ) mocked_responses.add( responses.GET, "{base}/files/{file_id}/download".format(base=api_url, file_id=file_id), body=files_content[file_id], ) def create_callback(request): uploaded_lines = request.body.decode("utf8").splitlines() content_disposition = uploaded_lines[1] _, params = cgi.parse_header(content_disposition) filename = params.get("filename", None) content = "".join(uploaded_lines[3:-1]) size = len(content.encode("utf8")) body = [ { "id": generate_id(), "content_type": "text/plain", "filename": filename, "account_id": account_id, "object": "file", "size": size, } ] return (200, {}, json.dumps(body)) mocked_responses.add_callback( responses.POST, api_url + "/files/", callback=create_callback ) @pytest.fixture def mock_event_create_response(mocked_responses, api_url, message_body): values = [(400, {}, ""), (200, {}, json.dumps(message_body))] def callback(_request): return values.pop() mocked_responses.add_callback( responses.POST, api_url + "/events/", callback=callback ) put_body = {"title": "loaded from JSON", "ignored": "ignored"} mocked_responses.add( responses.PUT, api_url + "/events/cv4ei7syx10uvsxbs21ccsezf", body=json.dumps(put_body), ) @pytest.fixture def mock_event_create_notify_response(mocked_responses, api_url, message_body): mocked_responses.add( responses.POST, api_url + "/events/?notify_participants=true&other_param=1", body=json.dumps(message_body), ) @pytest.fixture def mock_send_rsvp(mocked_responses, api_url, message_body): mocked_responses.add( responses.POST, re.compile(api_url + "/send-rsvp"), body=json.dumps(message_body), ) @pytest.fixture def mock_thread_search_response(mocked_responses, api_url): snippet = ( "Hey Helena, Looking forward to getting together for dinner on Friday. " "What can I bring? I have a couple bottles of wine or could put together" ) response_body = json.dumps( [ { "id": "evh5uy0shhpm5d0le89goor17", "object": "thread", "account_id": "<KEY>", "subject": "Dinner Party on Friday", "unread": False, "starred": False, "last_message_timestamp": 1398229259, "last_message_received_timestamp": 1398229259, "first_message_timestamp": 1298229259, "participants": [ {"name": "<NAME>", "email": "<EMAIL>.com"} ], "snippet": snippet, "folders": [ { "name": "inbox", "display_name": "INBOX", "id": "f0idlvozkrpj3ihxze7obpivh", } ], "message_ids": [ "251r594smznew6yhiocht2v29", "7upzl8ss738iz8xf48lm84q3e", "ah5wuphj3t83j260jqucm9a28", ], "draft_ids": ["251r594smznew6yhi12312saq"], "version": 2, } ] ) mocked_responses.add( responses.GET, api_url + "/threads/search?q=Helena", body=response_body, status=200, content_type="application/json", match_querystring=True, ) @pytest.fixture def mock_message_search_response(mocked_responses, api_url): snippet = ( "Sounds good--that bottle of Pinot should go well with the meal. " "I'll also bring a surprise for dessert. :) " "Do you have ice cream? Looking fo" ) response_body = json.dumps( [ { "id": "84umizq7c4jtrew491brpa6iu", "object": "message", "account_id": "<KEY>", "thread_id": "5vryyrki4fqt7am31uso27t3f", "subject": "Re: Dinner on Friday?", "from": [{"name": "<NAME>", "email": "<EMAIL>"}], "to": [{"name": "<NAME>", "email": "<EMAIL>"}], "cc": [], "bcc": [], "reply_to": [], "date": 1370084645, "unread": True, "starred": False, "folder": { "name": "inbox", "display_name": "INBOX", "id": "f0idlvozkrpj3ihxze7obpivh", }, "snippet": snippet, "body": "<html><body>....</body></html>", "files": [], "events": [], }, { "id": "84umizq7asdf3aw491brpa6iu", "object": "message", "account_id": "<KEY>", "thread_id": "5vryyralskdjfwlj1uso27t3f", "subject": "Re: Dinner on Friday?", "from": [{"name": "<NAME>", "email": "<EMAIL>"}], "to": [{"name": "<NAME>", "email": "<EMAIL>"}], "cc": [], "bcc": [], "reply_to": [], "date": 1370084645, "unread": True, "starred": False, "folder": { "name": "inbox", "display_name": "INBOX", "id": "f0idlvozkrpj3ihxze7obpivh", }, "snippet": snippet, "body": "<html><body>....</body></html>", "files": [], "events": [], }, ] ) mocked_responses.add( responses.GET, api_url + "/messages/search?q=Pinot", body=response_body, status=200, content_type="application/json", match_querystring=True, ) @pytest.fixture def mock_calendars(mocked_responses, api_url): calendars = [ { "id": "8765", "events": [ { "title": "Pool party", "location": "Local Community Pool", "participants": ["Alice", "Bob", "Claire", "Dot"], } ], } ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(calendars)) endpoint = re.compile(api_url + "/calendars") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_contacts(mocked_responses, account_id, api_url): contact1 = { "id": "5x6b54whvcz1j22ggiyorhk9v", "object": "contact", "account_id": account_id, "given_name": "Charlie", "middle_name": None, "surname": "Bucket", "birthday": "1964-10-05", "suffix": None, "nickname": None, "company_name": None, "job_title": "Student", "manager_name": None, "office_location": None, "notes": None, "picture_url": "{base}/contacts/{id}/picture".format( base=api_url, id="5x6b54whvcz1j22ggiyorhk9v" ), "emails": [{"email": "<EMAIL>", "type": None}], "im_addresses": [], "physical_addresses": [], "phone_numbers": [], "web_pages": [], } contact2 = { "id": "4zqkfw8k1d12h0k784ipeh498", "object": "contact", "account_id": account_id, "given_name": "William", "middle_name": "J", "surname": "Wonka", "birthday": "1955-02-28", "suffix": None, "nickname": None, "company_name": None, "job_title": "Chocolate Artist", "manager_name": None, "office_location": "W<NAME>onka Factory", "notes": None, "picture_url": None, "emails": [{"email": "<EMAIL>", "type": None}], "im_addresses": [], "physical_addresses": [], "phone_numbers": [], "web_pages": [{"type": "work", "url": "http://www.wonka.com"}], } contact3 = { "id": "9fn1aoi2i00qv6h1zpag6b26w", "object": "contact", "account_id": account_id, "given_name": "Oompa", "middle_name": None, "surname": "Loompa", "birthday": None, "suffix": None, "nickname": None, "company_name": None, "job_title": None, "manager_name": None, "office_location": "Willy Wonka Factory", "notes": None, "picture_url": None, "emails": [], "im_addresses": [], "physical_addresses": [], "phone_numbers": [], "web_pages": [], } contacts = [contact1, contact2, contact3] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(contacts)) def create_callback(request): payload = json.loads(request.body) payload["id"] = generate_id() return (200, {}, json.dumps(payload)) for contact in contacts: mocked_responses.add( responses.GET, re.compile(api_url + "/contacts/" + contact["id"]), content_type="application/json", status=200, body=json.dumps(contact), ) if contact.get("picture_url"): mocked_responses.add( responses.GET, contact["picture_url"], content_type="image/jpeg", status=200, body=os.urandom(50), stream=True, ) else: mocked_responses.add( responses.GET, "{base}/contacts/{id}/picture".format(base=api_url, id=contact["id"]), status=404, body="", ) mocked_responses.add_callback( responses.GET, re.compile(api_url + "/contacts"), content_type="application/json", callback=list_callback, ) mocked_responses.add_callback( responses.POST, api_url + "/contacts/", content_type="application/json", callback=create_callback, ) @pytest.fixture def mock_contact(mocked_responses, account_id, api_url): contact = { "id": "9hga75n6mdvq4zgcmhcn7hpys", "object": "contact", "account_id": account_id, "given_name": "Given", "middle_name": "Middle", "surname": "Sur", "birthday": "1964-10-05", "suffix": "Jr", "nickname": "Testy", "company_name": "Test Data Inc", "job_title": "QA Tester", "manager_name": "George", "office_location": "Over the Rainbow", "notes": "This is a note", "picture_url": "{base}/contacts/{id}/picture".format( base=api_url, id="9hga75n6mdvq4zgcmhcn7hpys" ), "emails": [ {"type": "first", "email": "<EMAIL>"}, {"type": "second", "email": "<EMAIL>"}, {"type": "primary", "email": "<EMAIL>"}, {"type": "primary", "email": "<EMAIL>"}, {"type": None, "email": "<EMAIL>"}, ], "im_addresses": [ {"type": "aim", "im_address": "SmarterChild"}, {"type": "gtalk", "im_address": "<EMAIL>"}, {"type": "gtalk", "im_address": "<EMAIL>"}, ], "physical_addresses": [ { "type": "home", "format": "structured", "street_address": "123 Awesome Street", "postal_code": "99989", "state": "CA", "country": "America", } ], "phone_numbers": [ {"type": "home", "number": "555-555-5555"}, {"type": "mobile", "number": "555-555-5555"}, {"type": "mobile", "number": "987654321"}, ], "web_pages": [ {"type": "profile", "url": "http://www.facebook.com/abc"}, {"type": "profile", "url": "http://www.twitter.com/abc"}, {"type": None, "url": "http://example.com"}, ], } def update_callback(request): try: payload = json.loads(request.body) except ValueError: return (200, {}, json.dumps(contact)) stripped_payload = {key: value for key, value in payload.items() if value} updated_contact_json = copy.copy(contact) updated_contact_json.update(stripped_payload) return (200, {}, json.dumps(updated_contact_json)) mocked_responses.add( responses.GET, "{base}/contacts/{id}".format(base=api_url, id=contact["id"]), content_type="application/json", status=200, body=json.dumps(contact), ) mocked_responses.add( responses.GET, contact["picture_url"], content_type="image/jpeg", status=200, body=os.urandom(50), stream=True, ) mocked_responses.add_callback( responses.PUT, "{base}/contacts/{id}".format(base=api_url, id=contact["id"]), content_type="application/json", callback=update_callback, ) @pytest.fixture def mock_events(mocked_responses, api_url): events = [ { "id": "1234abcd5678", "message_id": "evh5uy0shhpm5d0le89goor17", "ical_uid": "19960401T080045Z-<EMAIL>", "title": "Pool party", "location": "Local Community Pool", "participants": [ { "comment": None, "email": "<EMAIL>", "name": "<NAME>", "status": "noreply", }, { "comment": None, "email": "<EMAIL>", "name": "<NAME>", "status": "no", }, ], }, { "id": "9876543cba", "message_id": None, "ical_uid": None, "title": "Event Without Message", "description": "This event does not have a corresponding message ID.", }, ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(events)) endpoint = re.compile(api_url + "/events") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback ) @pytest.fixture def mock_resources(mocked_responses, api_url): resources = [ { "object": "room_resource", "email": "<EMAIL>", # Google's resourceEmail "name": "Training Room 1A", # Google's resourceName }, { "object": "room_resource", "email": "<EMAIL>", # Google's resourceEmail "name": "Training Room 2B", # Google's resourceName }, ] def list_callback(request): url = URLObject(request.url) offset = int(url.query_dict.get("offset") or 0) if offset: return (200, {}, json.dumps([])) return (200, {}, json.dumps(resources)) endpoint = re.compile(api_url + "/resources") mocked_responses.add_callback( responses.GET, endpoint, content_type="application/json", callback=list_callback, ) @pytest.fixture def mock_account_management(mocked_responses, api_url, account_id, app_id): account = { "account_id": account_id, "email_address": "<EMAIL>", "id": account_id, "name": "<NAME>", "object": "account", "provider": "gmail", "organization_unit": "label", "billing_state": "paid", } paid_response = json.dumps(account) account["billing_state"] = "cancelled" cancelled_response = json.dumps(account) upgrade_url = "{base}/a/{app_id}/accounts/{id}/upgrade".format( base=api_url, id=account_id, app_id=app_id ) downgrade_url = "{base}/a/{app_id}/accounts/{id}/downgrade".format( base=api_url, id=account_id, app_id=app_id ) mocked_responses.add( responses.POST, upgrade_url, content_type="application/json", status=200, body=paid_response, ) mocked_responses.add( responses.POST, downgrade_url, content_type="application/json", status=200, body=cancelled_response, ) @pytest.fixture def mock_revoke_all_tokens(mocked_responses, api_url, account_id, app_id): revoke_all_url = "{base}/a/{app_id}/accounts/{id}/revoke-all".format( base=api_url, id=account_id, app_id=app_id ) mocked_responses.add( responses.POST, revoke_all_url, content_type="application/json", status=200, body=json.dumps({"success": True}), ) @pytest.fixture def mock_ip_addresses(mocked_responses, api_url, app_id): ip_addresses_url = "{base}/a/{app_id}/ip_addresses".format( base=api_url, app_id=app_id ) mocked_responses.add( responses.GET, ip_addresses_url, content_type="application/json", status=200, body=json.dumps( { "ip_addresses": [ "172.16.58.3", "23.10.341.123", "12.56.256.654", "67.20.987.231", ], "updated_at": 1552072984, } ), ) @pytest.fixture def mock_token_info(mocked_responses, api_url, account_id, app_id): token_info_url = "{base}/a/{app_id}/accounts/{id}/token-info".format( base=api_url, id=account_id, app_id=app_id ) mocked_responses.add( responses.POST, token_info_url, content_type="application/json", status=200, body=json.dumps( { "created_at": 1563496685, "scopes": "calendar,email,contacts", "state": "valid", "updated_at": 1563496685, } ), ) @pytest.fixture def mock_free_busy(mocked_responses, api_url): free_busy_url = "{base}/calendars/free-busy".format(base=api_url) def free_busy_callback(request): payload = json.loads(request.body) email = payload["emails"][0] resp_data = [ { "object": "free_busy", "email": email, "time_slots": [ { "object": "time_slot", "status": "busy", "start_time": 1409594400, "end_time": 1409598000, }, { "object": "time_slot", "status": "busy", "start_time": 1409598000, "end_time": 1409599000, }, ], } ] return 200, {}, json.dumps(resp_data) mocked_responses.add_callback( responses.POST, free_busy_url, content_type="application/json", callback=free_busy_callback, )
6d5541463d78b498811fc7c91fc8331ea25d6c78
[ "Python" ]
1
Python
fagan2888/nylas-python
676547a3ba05dd6cc30322a9ed67575b540e0310
b991242fd5d64e2410651185084efb11fbf20cea
refs/heads/main
<repo_name>laithalenooz/php-mini-website<file_sep>/index.php <?php include 'functions.php'; ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <?php echo $bootstrap; ?> <title>Form Validation</title> </head> <body> <?php echo $mainNav. $slider;?> </body> <?php echo $bootstrapjs; ?> </html><file_sep>/user.php <?php session_start(); $newArr = $_SESSION; include 'functions.php'; ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <?php echo $bootstrap; ?> <title>Form Validation</title> </head> <body> <?php echo $navbar; ?> <div class="container border p-5 mt-5 bg-light text-center mx-auto" > <h1><?php echo "<pre>"; print_r($_SESSION['username']); echo "Welcome " . $_SESSION['username']; ?></h1> </div> </body> <?php echo $bootstrapjs; ?> </html><file_sep>/formProcess.php <?php session_start(); $username['username'] = $_POST; $password['password'] = $_POST; $_SESSION['username'] = $username; $_SESSION['password'] = $password; global $users; $users = [ ['username' => 'Laith', 'password' => '<PASSWORD>', 'role' => 'admin',] , ['username' => 'Sadi', 'password' => '<PASSWORD>', 'role' => 'user',] , ['username' => 'Sara', 'password' => '<PASSWORD>', 'role' => 'user',] , ['username' => 'Ayham', 'password' => '<PASSWORD>', 'role' => 'user',] , ['username' => 'Alaa', 'password' => '<PASSWORD>', 'role' => 'admin'] ]; //$_SESSION = $users = $GLOBALS = [ // ['username' => 'Laith', // 'password' => '<PASSWORD>', // 'role' => 'admin',] , // ['username' => 'Sadi', // 'password' => '<PASSWORD>', // 'role' => 'user',] , // ['username' => 'Sara', // 'password' => '<PASSWORD>', // 'role' => 'user',] , // ['username' => 'Ayham', // 'password' => '<PASSWORD>', // 'role' => 'user',] , // ['username' => 'Alaa', // 'password' => '<PASSWORD>', // 'role' => 'admin'] // ]; if (isset($_SESSION['username']) && isset($_SESSION['password'])) { foreach ($users as $key => $value) { if ($_SESSION['username'] == $users[$key]['username'] && $_SESSION['password'] == $users[$key]['password'] && $users[$key]['role'] == 'admin') { header("location: admin.php"); } elseif ($_SESSION['username'] == $users[$key]['username'] && $_SESSION['password'] == $users[$key]['password'] && $users[$key]['role'] == 'user') { header("location: user.php"); } } } ?><file_sep>/functions.php <?php $mainNav = '<!--Navbar --> <nav class="mb-1 navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="index.php">Form Validation</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-4" aria-controls="navbarSupportedContent-4" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent-4"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="login.php"> <i class=""></i> Login <span class="sr-only">(current)</span> </a> </li> <li class="nav-item active ml-2"> <a class="nav-link" href="signup.php"> <i class=""></i> Register <span class="sr-only">(current)</span> </a> </li> </ul> </div> </nav> <!--/.Navbar -->'; $slider = '<!--/.Slider --> <div class="container"> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEhUTExIVFhUXFxUVFRUVGBUVFxUWFxUXFhUXFxUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGy0dHR0tLS0rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKzc3Ny0tLS03N//AABEIAN8A4gMBIgACEQEDE<KEY>" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://i.pinimg.com/originals/5b/b4/8b/5bb48b07fa6e3840bb3afa2bc821b882.jpg" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://www.mandysam.com/img/random.jpg" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div>'; $navbar = '<!--Navbar --> <nav class="mb-1 navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="index.php">Form Validation</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-4" aria-controls="navbarSupportedContent-4" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </nav> <!--/.Navbar -->'; $bootstrap = ' <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"> <!-- Google Fonts --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"> <!-- Bootstrap core CSS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"> <!-- Material Design Bootstrap --> <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">'; $bootstrapjs = '<!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- JQuery --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Bootstrap tooltips --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script> <!-- Bootstrap core JavaScript --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- MDB core JavaScript --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js"></script> <!-- Option 2: jQuery, Popper.js, and Bootstrap JS <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> -->'; ?><file_sep>/registerVal.php <?php include 'formProcess.php'; $newUser = $_GET['username']; $newPassword = $_GET['password']; $_GET['username'] = $newUser; $_GET['password'] = $<PASSWORD>; $role = "user"; echo "<pre>"; if (isset($_GET['username']) && isset($_GET['password'])) { $newArr = ['username' => $newUser, 'password' => <PASSWORD>, 'role' => 'user']; array_merge( $newArr, ['username' => $newUser, 'password' => <PASSWORD>, 'role' => $role]); print_r($newArr); } else { echo "Error 404"; } ?><file_sep>/login.php <?php session_start(); include 'functions.php'; ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <?php echo $bootstrap; ?> <title>Form Validation</title> </head> <body> <?php echo $navbar; ?> <div class="container border p-5 mt-5 bg-light"> <form action="formProcess.php" method="post"> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter Username" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" name="password" class="form-control" id="exampleInputPassword1" placeholder="<PASSWORD>" required> </div> <input type="submit" name="submit" class="btn btn-dark"> </form> </div> </body> <?php echo $bootstrapjs; ?> </html>
a2ad8ab07884af5821e9edbccae25a28530c5589
[ "PHP" ]
6
PHP
laithalenooz/php-mini-website
b1330bd0b914051ed7dfb9b58474c5ab9a4c2453
e45f2fd937fb760fca7d9553beeb6e71f8f1a824
refs/heads/main
<repo_name>JohnCMello/starWarsGame<file_sep>/README.md ### Star Wars game in Vanilla JS. - Credits to Franks laboratory: https://www.youtube.com/watch?v=EYf_JwzwTlQ <file_sep>/src/script.js const canvas = document.getElementById('canvas2d'); const ctx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 500; const keys = []; // Lando 128x192 = 32x48 const player = { x: 200, y: 300, width: 32, height: 48, frameX: 0, frameY: 2, speed: 5, moving: false, }; const playerSprite = new Image(); playerSprite.src = '../assets/lando.png'; const background = new Image(); background.src = '../assets/background.png'; function drawSprite(img, sX, sY, sW, sH, dX, dY, dW, dH) { ctx.drawImage(img, sX, sY, sW, sH, dX, dY, dW, dH); } window.addEventListener('keydown', e => { keys.push(e.key); player.moving = true }); window.addEventListener('keyup', e => { keys.pop(e.key); player.moving = false }); function movePlayer() { if (keys[0] === 'ArrowDown' && player.y < canvas.height - player.height) { player.y += player.speed player.frameY = 0 } if (keys[0] === 'ArrowLeft' && player.x > 0) { player.x -= player.speed player.frameY = 1 } if (keys[0] === 'ArrowRight' && player.x < canvas.width - player.width) { player.x += player.speed player.frameY = 2 } if (keys[0] === 'ArrowUp' && player.y > 100) { player.y -= player.speed; player.frameY = 3 } } function handlePlayerFrame() { player.frameX < 3 && player.moving ? player.frameX++ : player.frameX = 0; } function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(background, 0, 0, canvas.width, canvas.height); drawSprite( playerSprite, //image source player.width * player.frameX, //where to cut in the sprite X axis player.height * player.frameY,//where to cut in the sprite Y axis player.width, //how much X value to cut in the sprite player.height, //how much Y value to cut in the sprite player.x, //where to draw in the canvas X axis player.y, //where to draw in the canvas Y axis player.width, //how much X value to draw in the canvas player.height //how much Y value to draw in the canvas ); movePlayer() handlePlayerFrame() requestAnimationFrame(animate); console.log(player.x, player.y) } animate();
3046856d9607645d3bafb8f1dfdc41d7c159904b
[ "Markdown", "JavaScript" ]
2
Markdown
JohnCMello/starWarsGame
16605b56acc60e1b39cd5a09c96f44e13f99ab46
f1a906d1755ff9e9d83b0ecc29a03fb5a51ce1fe
refs/heads/master
<file_sep>package com.example.ktlistview import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.* import androidx.appcompat.app.AlertDialog import com.google.android.material.snackbar.Snackbar class MainActivity : AppCompatActivity() { var m_city: String = "" val cities = ArrayList<String>() lateinit var listAdapter: ArrayAdapter<String> lateinit var addItemDialog: AlertDialog.Builder override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // val cities = ArrayList<String>("Boston", "Mumbai", "Chennai", "Bhubaneswar", "Cuttack", "Kolkata", "Pune") initData() val list = findViewById<ListView>(R.id.listView) listAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, cities) list.adapter = listAdapter addItemDialog = AlertDialog.Builder(this) addItemDialog.create() addItemDialog.setTitle("Add City") addItemDialog.setView(R.layout.dialoglayout) val editText: EditText? = findViewById<EditText>(R.id.itemInput) addItemDialog.setPositiveButton("Ok") { _, _ -> m_city = editText?.text.toString() } addItemDialog.setNegativeButton("Cancel") { _, _ -> Toast.makeText(this, "City not added", Toast.LENGTH_SHORT).show() } } private fun initData() { cities.add("Delhi") cities.add("Mumbai") cities.add("Chennai") cities.add("Bhubaneswar") cities.add("Pune") cities.add("Bangalore") } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_add -> { addItemDialog.show() addItem() } } return true } private fun addItem() { cities.add("m_city") listAdapter.notifyDataSetChanged() } }
8de845a4958849130159cebd7d48cf0c9985e8d5
[ "Kotlin" ]
1
Kotlin
smish-hash/KTListView
c6e487b066de1a7ccbdb6edfaf843f69f7e6f387
adcf124b94aad8b0bc1654aa8e75d29bc4f81fc7
refs/heads/master
<file_sep>let mongoose=require("mongoose"); let joi=require("joi"); let jwt=require("jsonwebtoken"); let config=require("config"); let userSchema=new mongoose.Schema({ firstname:{type:String,required:true,min:5,max:30}, lastname:{type:String,required:true,min:5,max:30}, newsLetterCheck:{type:Boolean}, UserLogin:{ userEmail:{type:String,required:true,unique:true}, userPassword:{type:String,required:true,min:8,max:25} }, termsAcceptCheck:{type:Boolean}, resetPasswordToken:{type:String}, resetPasswordExpires:{type:Date}, isAdmin:{type:Boolean,default:false}, recordDate:{type:Date, default:Date.now}, updateDate:{type:Date, default:Date.now} }); userSchema.methods.genToken=function() { let token = jwt.sign({_id:this._id,firstname:this.firstname,isAdmin:this.isAdmin},config.get("key")); return token; } let UserModel=mongoose.model("UserRegister",userSchema); function validationError (error) { let schema=joi.object({ firstname:joi.string().required().min(5).max(30), lastname:joi.string().required().min(5).max(30), newsLetterCheck:joi.boolean(), UserLogin:{ userEmail:joi.string().required().email(), userPassword:joi.string().required().min(8).max(25) }, termsAcceptCheck:joi.boolean(), resetPasswordToken:joi.string(), resetPasswordExpires:joi.date(), isAdmin:joi.boolean(), recordDate:joi.date(), updateDate:joi.date() }); return schema.validate(error); } module.exports={UserModel,validationError};<file_sep>let express=require("express"); let router=express.Router(); let User=require("../schema/userRegistrationSchema"); let Joi=require("joi"); let bcrypt=require("bcrypt"); let Auth = require('../middleware/auth'); router.post("/authUser",async(req,res)=>{ let {error}=validateError(req.body); if(error){return res.status(402).send(error.details[0].message)}; let email=await User.UserModel.findOne({"UserLogin.userEmail":req.body.UserLogin.userEmail}); if(!email){return res.status(402).send({message:"Invalid Email"})}; let password=await bcrypt.compare(req.body.UserLogin.userPassword,email.UserLogin.userPassword); if(!password){return res.status(402).send({message:"Invalid Password"})} let token=email.genToken(); //console.log(email); res.send({message:"Login Successful",t:token}); }); router.get("/UserIdentify",Auth,async(req,res)=> { let {error}=validateError(req.body); if(error){return res.status(402).send(error.details[0].message)}; let data=await User.UserModel.findById(req.userRegistrationSchema._id) .select("-UserLogin.userPassword"); res.send({userdata:data}); }) function validateError(error) { let schema=Joi.object({ UserLogin:{ userEmail:Joi.string().email().required(), userPassword:Joi.string().min(8).max(20).required() } }); return schema.validate(error); } module.exports=router;<file_sep>let express=require("express"); let router=express.Router(); let contact=require("../schema/contactSchema"); let nodemailer=require("nodemailer"); router.get("/allcontact",async(req,res)=>{ try{ let getcontact=await contact.ContactModel.find(); res.send(getcontact); } catch(error) { res.status(500).send(error.message); } }); router.post("/newcontact",async(req,res)=> { try{ let {error}=contact.validationError(req.body); if(error){res.status(402).send(error.details[0].message)}; let createcontact=new contact.ContactModel({ name:req.body.name, email:req.body.email, personalmessage:req.body.personalmessage }); await createcontact.save(); let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 465, secure: true, // true for 465, false for other ports auth: { user: "******************", // generated ethereal user pass: "********", // generated ethereal password }, }); let mailoptions= { from: '"<NAME> 👻" <<EMAIL>>', // sender address to: "<EMAIL>", // list of receivers subject: "Users Inquiries", // Subject line text: `name:${createcontact.name}</br>email:${createcontact.email}</br> message:${createcontact.personalmessage}` }; transporter.sendMail(mailoptions,(error,info)=>{ if(error){return console.error(error)} else{ console.log(`email send ,${info.messageId}`); } }); res.send({message:"message send"}); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>let express=require("express"); let router=express.Router(); let products=require("../schema/productSchema"); let getimage=require("../schema/productImageSchema"); let category=require("../schema/categorySchema"); let subcategory=require("../schema/subCategorySchema"); let Auth=require("../middleware/auth"); let Admin=require("../middleware/admin"); router.post("/addproduct",async(req,res)=>{ try{ let {error}=products.validationError(req.body); if(error){return res.status(402).send(error.details[0].message)}; let name=await category.CategoryModel.findById(req.body.categoryId); if(!name){return res.status(403).send({message:"category id not found "})}; let img= await getimage.ImageModel.findById(req.body.imageId); if(!img){return res.status(403).send({message:"image id not found "})}; let newproduct= new products.ProductModel({ name:req.body.name, image:{ _id:img._id, image:img.image }, description:req.body.description, price:req.body.price, quantity:req.body.quantity, offerPrice:req.body.offerPrice, isAvailable:req.body.isAvailable, isTodayOffer:req.body.isTodayOffer, category:{ _id:name._id, categoryName:name.categoryName, subCategory:name.subCategory }, isAdmin:req.body.isAdmin }); let saveproduct=await newproduct.save(); res.send({message:"prodcut added",p:saveproduct}); } catch(error) { res.status(500).send(error.message); } }); router.get("/allproducts",async(req,res)=>{ try{ let getalldata=await products.ProductModel.find(); res.send(getalldata); } catch(error) { res.status(500).send(error.message); } }); router.put("/updateproduct/:id",async(req,res)=>{ try{ let checkid=await products.ProductModel.findById(req.params.id); if(!checkid){res.status(401).send({message:"product id not found"})}; checkid['price']=req.body.price, checkid['quantity']=req.body.quantity, checkid['offerPrice']=req.body.offerPrice, checkid['isAvailable']=req.body.isAvailable checkid['isTodayOffer']=req.body.isTodayOffer let udata=await checkid.save(); res.send({message:"data updated",u:udata}); } catch(error) { res.status(500).send(error.message); } }); router.get("/findproductbyid/:id",async(req,res)=>{ try{ let productbyid=await products.ProductModel.findById(req.params.id); if(!productbyid){return res.status(400).send({message:"category id not found"})}; res.send(productbyid); } catch(error) { res.status(500).send(error.message); } }); router.delete("/removeproduct/:id",[Auth,Admin],async(req,res)=>{ try{ let productby=await products.ProductModel.findById(req.params.id); if(!productby){return res.status(400).send({message:"prodcut id not in database"})}; let productdelete=await products.ProductModel.findByIdAndDelete({_id:req.params.id}); if(!productdelete){return res.status(400).send({message:"product id not found"})}; res.send({message:"product deleted"}); } catch(error) { res.status(500).send(error.message); } }); router.get("/findtodayoffer",async(req,res)=>{ try{ let todayoffer=await products.ProductModel.find({isTodayOffer:true}); res.send({t:todayoffer}); } catch(error) { res.status(500).send(error.message); } }); router.get("/findlatestproduct",async(req,res)=>{ try { let availableproduct=await products.ProductModel.find({isAvailable:true}); res.send({a:availableproduct}); } catch(error) { res.status(500).send(error.message); } }); router.post("/productpageindex/:page",async(req,res)=>{ try{ let perpage=2; let currentpage=req.params.page || 1; let data=await products.ProductModel .find() .skip((perpage*currentpage)-perpage) .limit(perpage) let pagecount=await products.ProductModel.count(); let totalpages=Math.ceil(pagecount/perpage); res.send({ perpage:perpage, data:data, totalpages:totalpages }); } catch(error) { res.status(500).send(error.message); } }); router.post("/category/:catid/page/:pageindex",async(req,res)=>{ try{ let perpage=1; let currentpage=req.params.pageindex || 1; let cat=await category.CategoryModel.findById(req.params.catid); let data= await products.ProductModel. find({"category.categoryName":cat.categoryName}) .skip((perpage*currentpage)-perpage) .limit(perpage); let pagecount=await products.ProductModel.find({"category.categoryName":cat.categoryName}).count(); let totalpages=Math.ceil(pagecount/perpage); res.send({ perpage:perpage, currentpage:currentpage, data:data, pagecount:pagecount, totalpages:totalpages, }); } catch(error) { res.status(500).send(error.message); } }); router.post("/category/:catid/subcategory/:subcatid/page/:pageindex",async(req,res)=>{ try{ let perpage=1; let currentpage=req.params.pageindex || 1; let cat=await category.CategoryModel.findById(req.params.catid); let subcat=await subcategory.SubCategoryModel.findById(req.params.subcatid); let data=await products.ProductModel.find({"category.categoryName":cat.categoryName,"category.subCategory.name":subcat.name}) .skip((perpage*currentpage)-perpage) .limit(perpage) let pagecount=await products.ProductModel.find({"category.categoryName":cat.categoryName,"category.subCategory.name":subcat.name}).count(); let totalpages=Math.ceil(pagecount/perpage); res.send({ perpage:perpage, currentpage:currentpage, data:data, totalpages:totalpages }); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>function Admin(req,res,next) { if(!req.userRegistrationSchema.isAdmin) { return res.status(402).send({message:"invalid access"}); } next(); } module.exports=Admin;<file_sep>let mongoose=require("mongoose"); let joi=require("joi"); let subCategorySchema=new mongoose.Schema({ name:{type:String,required:true,min:1,max:100}, catName:{type:String} }); let SubCategoryModel=mongoose.model("SubCategories",subCategorySchema); function validationError(error) { let schema=joi.object({ name:joi.string().required().min(1).max(100), catName:joi.string().required() }); return schema.validate(error); } module.exports={SubCategoryModel,subCategorySchema,validationError};<file_sep>let express=require("express"); let router=express.Router(); let category=require("../schema/categorySchema"); let subcategory=require("../schema/subCategorySchema"); router.post("/addcategory",async(req,res)=>{ try{ let {error}=category.validationError(req.body); if(error){return res.status(402).send(error.details[0].message)}; let checksubcat=await subcategory.SubCategoryModel.findById(req.body.subCategoryId); if(!checksubcat){return res.status(402).send({message:"subcategory id not matched"})}; let createcat=new category.CategoryModel({ categoryName:req.body.categoryName, subCategory:{ _id:checksubcat._id, name:checksubcat.name, catName:checksubcat.catName } }); let cat=await createcat.save(); res.send({message:"category added",c:cat}); } catch(error) { res.status(500).send(error.message); } }) router.get("/allcategory",async(req,res)=>{ try{ let allcat=await category.CategoryModel.find(); res.send(allcat); } catch(error) { res.status(500).send(error.message); } }); router.get("/findcategorybyid/:id",async(req,res)=>{ try{ let catbyid=await category.CategoryModel.findById(req.params.id); if(!catbyid){return res.status(400).send({message:"category id not found"})}; res.send(catbyid); } catch(error) { res.status(500).send(error.message); } }); router.delete("/deletecategorybyid/:id",async(req,res)=>{ try{ let catby=await category.CategoryModel.findById(req.params.id); if(!catby){return res.status(400).send({message:"category id not in database"})}; let catdelete=await category.CategoryModel.findByIdAndDelete({_id:req.params.id}); if(!catdelete){return res.status(400).send({message:"category id not found"})}; res.send({message:"Category deleted"}); } catch(error) { res.status(500).send(error.message); } }); router.post("/catpageIndex/:page",async(req,res)=>{ try{ let perpage=2; let currentpage=req.params.page || 1; let data=await category.CategoryModel .find() .skip((perpage*currentpage)-perpage) .limit(perpage) let pagecount=await category.CategoryModel.count(); let totalpages=Math.ceil(pagecount/perpage); res.send({ perpage:perpage, data:data, totalpages:totalpages }); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>module.exports=function(mongoose) { //db connection mongoose.connect("mongodb://localhost:27017/nodejsproject",{ useNewUrlParser: true ,useUnifiedTopology: true }) .then(()=>console.log("database connected sucessfully")) .catch((error)=>console.log(`error found ${error.message}`)); } <file_sep>let express=require("express"); let router=express.Router(); let subcategory=require("../schema/subCategorySchema"); router.post("/addsubcategory",async(req,res)=>{ try{ let {error}=subcategory.validationError(req.body); if(error){return res.status(402).send(error.details[0].message)}; let newsub=new subcategory.SubCategoryModel({ name:req.body.name, catName:req.body.catName }); let createsub=await newsub.save(); res.send({message:"subcategory created",c:createsub}); } catch(error) { res.status(500).send(error.message); } }); router.get("/allsubcategory",async(req,res)=>{ try{ let getcategory=await subcategory.SubCategoryModel.find(); res.send(getcategory); } catch(error) { res.status(500).send(error.message); } }); router.post("/pageIndex/:page",async(req,res)=>{ try{ let perpage=2; let currentpage=req.params.page || 1; let data=await subcategory.SubCategoryModel .find() .skip((perpage*currentpage)-perpage) .limit(perpage) let pagecount=await subcategory.SubCategoryModel.count(); let totalpages=Math.ceil(pagecount/perpage); res.send({ perpage:perpage, data:data, totalpages:totalpages }); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>let express=require("express"); let cors = require('cors'); let ex=express(); ex.use(cors()); ex.use(express.json()); let mongoose=require("mongoose"); const port = process.env.PORT || 4500; let morgan=require("morgan"); require("./startup/dbconnection")(mongoose); require("./startup/routes")(ex); let config=require("config"); let Fawn=require('fawn'); Fawn.init(mongoose); if(!config.get("key")) { console.log("server get crashed"); process.exit(1); } if(config.get('host.mode') === 'Development mode'){ ex.use(morgan('tiny')); }; if(process.env.NODE_ENV === 'Production'){ console.log(`password: ${config.get('password')}`); } ex.use("/productimages",express.static('productimages')); ex.listen(port,()=>console.log(`connect to port ${port}`));<file_sep>let express=require("express"); let router=express.Router(); let multer=require("multer"); let imageupload=require("../schema/productImageSchema"); let port="http://localhost:4500"; let storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "./productimages/") }, filename: function (req, file, cb) { cb(null, file.originalname) } }) function fileFilter (req, file, cb) { if(file.mimetype === "image/jpg" || file.mimetype ==="image/png" || file.mimetype ==="image/jpeg") { cb(null, true) } else{ cb(null,false) } }; var upload = multer({ storage: storage, limits:{ filesize:1024*1024*50 }, fileFilter:fileFilter }); router.post("/productimageupload", upload.single("image"), async(req,res)=>{ try{ let fu=new imageupload.ImageModel({ image:port + "/./productimages/" + req.file.filename }); let sd=await fu.save(); res.send(sd); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>let userRegister=require("../routes/userRegistration"); let contact=require("../routes/contact"); let sendmail=require("../routes/sendmail"); let resetpassword=require("../routes/resetPassword"); let products=require("../routes/product"); let productimage=require("../routes/productImageUpload"); let subcategory=require("../routes/subCategory"); let category=require("../routes/category"); let usercart=require("../routes/userCart"); let auth=require("../routes/auth"); module.exports=function(ex) { ex.use("/api",userRegister); ex.use("/api",contact); ex.use("/api",sendmail); ex.use("/api",resetpassword); ex.use("/api",products); ex.use("/api",productimage); ex.use("/api",subcategory); ex.use("/api",category); ex.use("/api",usercart); ex.use("/api",auth); }<file_sep>let express=require("express"); let router=express.Router(); let product=require("../schema/productSchema"); let usercart=require("../schema/userCartSchema"); let auth=require("../middleware/auth"); let userreg=require("../schema/userRegistrationSchema"); let Fawn=require('fawn'); let mongoose=require("mongoose"); router.post("/addtocart/:productsId",auth,async(req,res)=>{ try{ let {error}=usercart.validationError(req.body); if(error){return res.status(403).send(error.details[0].message)}; let uid= await userreg.UserModel.findById(req.userRegistrationSchema._id).select("UserLogin.userEmail"); let productdata=await product.ProductModel.findById(req.params.productsId); if(!productdata){return res.status(402).send({message:"product id not found"})}; let addcart=await usercart.CartModel({ userEmail:uid.UserLogin.userEmail, products: { _id:productdata._id, name:productdata.name, image:productdata.image, description:productdata.description, price:productdata.price, quantity:productdata.quantity, offerPrice:productdata.offerPrice, isAvailable:productdata.isAvailable, isTodayOffer:productdata.isTodayOffer, category:{ _id:productdata.category._id, categoryName:productdata.category.categoryName, }, isAdmin:productdata.isAdmin }, userquantity:req.body.userquantity }); new Fawn.Task() .update("products",{_id:productdata._id},{ $inc:{ quantity:-req.body.userquantity } }) .run(); let checkoutcart=await addcart.save(); /* let carditem=await usercart.CheckoutModel({ userEmail:uid.UserLogin.userEmail, cartItems:savecart }); let checkoutcart= await carditem.save(); */ mongoose.connection.db.collection('addtocarts').count(function(err, count) { console.dir(err); console.dir(count); if( count == 0) { console.log("No Found Records."); } else { console.log("Found Records : " + count); } }); res.send({message:"product added to cart",c:checkoutcart}); } catch(error) { res.status(500).send(error.message); } }); router.put("/updateusercart/:id",auth,async(req,res)=>{ try{ let prid=await usercart.CartModel.findById(req.params.id); if(!prid){return res.status(402).send({message:"product id not found"})}; prid['quantity']=req.body.quantity prid['totalPrice']=prid.price*prid.quantity res.send({message:"add to cart updated"}); } catch(error) { res.status(500).send(error.message); } }); router.get("/getallusercart",async(req,res)=>{ try{ let getdata=await usercart.CartModel.find(); res.send(getdata); } catch(error) { res.status(500).send(error.message); } }); router.post("/cartbyuser",auth,async(req,res)=>{ try{ let uid= await userreg.UserModel.findById(req.userRegistrationSchema._id) .select("UserLogin.userEmail"); let checkoutcart=await usercart.CartModel.find({'userEmail':uid.UserLogin.userEmail}); res.send({message:"success",c:checkoutcart}); } catch(error) { res.status(500).send(error.message); } }); router.post("/addquantity",async(req,res)=>{ try{ let pdata=await usercart.CartModel.findById(req.body.id); if(!pdata){return res.status(402).send({message:"product not found in cart"})}; console.log(pdata); if(pdata==pdata.products.id) { userquantity=+1; } res.send({message:"quantity added"}); } catch(error) { res.status(500).send(error.message); } }); router.delete("/removecartitem/:id",async(req,res)=>{ try{ let cartid= await usercart.CartModel.findByIdAndRemove(req.params.id); if(!cartid){return res.status(402).send({message:"cart id not found"})}; res.send({message:"removed item from cart"}); } catch(error) { res.status(500).send(error.message); } }); module.exports=router;<file_sep>let mongoose=require("mongoose"); let joi=require("joi"); let contactSchema=new mongoose.Schema({ name:{type:String,required:true,min:5,max:30}, email:{type:String,required:true,min:5,max:50}, personalmessage:{type:String,required:true,min:20,max:250} }); let ContactModel=mongoose.model("contactus",contactSchema); function validationError(error) { let schema=joi.object({ name:joi.string().required().min(5).max(30), email:joi.string().required().min(5).max(50).email(), personalmessage:joi.string().required().min(20).max(250) }); return schema.validate(error); } module.exports={ContactModel,validationError};
e3d94f50205482faa41572787d11c253b80dd87c
[ "JavaScript" ]
14
JavaScript
mayurdeveloper95/nodejsproject
ea66cdad89db30fc5a68d89417326f09412f2491
e81563eb8090d7869177f0684d800cd9f578681c
refs/heads/master
<file_sep>namespace Messenger.Client.Objects { public static class WebviewHeightRatios { public const string Compact = "compact"; public const string Full = "full"; public const string Tall = "tall"; } } <file_sep> namespace Messenger.Client.Objects { public static class MessengerTemplateType { public const string AirlineBoardingPass = "airline_boardingpass"; public const string AirlineCheckin = "airline_checkin"; public const string AirlineItiniery = "airline_itinerary"; public const string AirlineFlightUpdate = "airline_update"; public const string Button = "button"; public const string Generic = "generic"; public const string List = "list"; public const string Receipt = "receipt"; } } <file_sep>namespace Messenger.Client.Objects { public class MessengerGreetingTextSetting : MessengerThreadSetting { public override string SettingType => "greeting"; public MessengerGreeting Greeting { get; set; } } } <file_sep>using Newtonsoft.Json; namespace Messenger.Client.Objects { public class MessengerCallToAction { public string Type { get; set; } public string Title { get; set; } public string Url { get; set; } public string Payload { get; set; } [JsonProperty("webview_height_ratio")] public string WebviewHeightRatio { get; set; } [JsonProperty("messenger_extensions")] public bool? MessengerExtensions { get; set; } } } <file_sep>using System; namespace Messenger.Client.Objects { public class MessengerAttachment { public String Type { get; set; } public MessengerPayload Payload { get; set; } } } <file_sep>namespace Messenger.Client.Objects { public static class MessengerDomainActionType { public const string Add = "add"; public const string Remove = "remove"; } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Messenger.Client.Objects { public class MessengerDomainWhitelistingSetting : MessengerThreadSetting { public override string SettingType => "domain_whitelisting"; [JsonProperty("whitelisted_domains")] public ICollection<string> WhitelistedDomains { get; set; } [JsonProperty("domain_action_type")] public string DomainActionType { get; set; } } } <file_sep>using System.Collections.Generic; using Newtonsoft.Json; namespace Messenger.Client.Objects { public class MessengerGettingStartedSetting : MessengerThreadSetting { public MessengerGettingStartedSetting() { ThreadState = "new_thread"; } public override string SettingType => "call_to_actions"; [JsonProperty("call_to_actions")] public ICollection<MessengerPayloadCallToAction> CallToActions { get; set; } } } <file_sep>namespace Messenger.Client.Objects { public static class MessengerPersistentMenuActionType { public const string Nested = "nested"; public const string Postback = "postback"; public const string WebUrl = "web_url"; } } <file_sep>using System; using Newtonsoft.Json; namespace Messenger.Client.Objects { public class MessengerQuickReply { [JsonProperty("content_type")] public String ContentType { get; set; } public String Title { get; set; } public String Payload { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Messenger.Client.Objects { public class MessengerGetStarted { public string Payload { get; set; } } } <file_sep>using System.Collections.Generic; using Newtonsoft.Json; namespace Messenger.Client.Objects { public abstract class MessengerThreadSetting { [JsonProperty("setting_type")] public abstract string SettingType { get; } [JsonProperty("thread_state")] public string ThreadState { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Messenger.Client.Objects { public static class TemplateTypes { public const string Button = "button"; public const string Generic = "generic"; public const string List = "list"; public const string Receipt = "receipt"; } } <file_sep>using System.Collections.Generic; using Newtonsoft.Json; namespace Messenger.Client.Objects { public class MessengerListPayload : MessengerPayload { public ICollection<MessengerListElement> Elements { get; set; } public ICollection<MessengerButton> Buttons { get; set; } public override string TemplateType => MessengerTemplateType.List; [JsonProperty("top_element_style")] public string TopElementStyle { get; set; } } } <file_sep>using System; using Newtonsoft.Json; namespace Messenger.Client.Objects { public abstract class MessengerPayload { [JsonProperty("template_type")] public abstract String TemplateType { get; } } }<file_sep>using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Messenger.Client.Objects { [Obsolete] public class MessengerPersistentMenuSetting : MessengerThreadSetting { public MessengerPersistentMenuSetting() { ThreadState = "existing_thread"; } public override string SettingType => "call_to_actions"; [JsonProperty("call_to_actions")] public ICollection<MessengerCallToAction> CallToActions { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Messenger.Client.Objects { public class MessengerListDefaultAction { } } <file_sep>namespace Messenger.Client.Objects { public static class MessengerTopElementStyles { public const string Compact = "compact"; public const string Large = "large"; } }
9df723a266cf583bb32a91dfcb9e91c98a8ad121
[ "C#" ]
18
C#
TheNest/messenger-client
a51b6d9cc771074dfe4d7e567417b06d55b0daa9
be104d4d3832aee44589bed19d018126875b7030
refs/heads/main
<file_sep>module github.com/mamoralesMELI/go-hands-on go 1.15 require ( github.com/gin-gonic/gin v1.6.3 github.com/go-resty/resty/v2 v2.3.0 ) <file_sep>package main import ( "github.com/gin-gonic/gin" "github.com/mamoralesMELI/go-hands-on/rest" ) type Greeting struct { greeting string `json:"greeting"` owner string `json:"owner"` repository string `json:"repository"` } func main() { r := gin.Default() r.GET("/mygreeting",addCors, func(c *gin.Context){ r := rest.New() g := new(Greeting) r.Get("https://fanaur-workshop-go-hands-on.herokuapp.com/fanaur",nil, g) c.JSON(200, gin.H{ "owner": "<NAME>", "greeting": g.greeting, "repository": "https://github.com/mamoralesMELI/go-hands-on", }) }) r.Run() } func addCors(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method") c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE") c.Header("Allow", "GET, POST, OPTIONS, PUT, DELETE") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } c.Next() }<file_sep># go-hands-on
019471b97e6f8e7db6fe7b4597412254894e4e45
[ "Go", "Go Module", "Markdown" ]
3
Go Module
mamoralesMELI/go-hands-on
2242e856f57464d373270d4698b862dc0f3d62bf
4b378b8168ceb938ceab402bd3d4a043abb523be
refs/heads/master
<file_sep>/* mixer.c */ #include <stdio.h> #include <stdlib.h> #define TRACK_MAX 10 #define DATA_MAX 44100*300 #define VALUE_MAX 30000 double sum[DATA_MAX]; int main(int argc, char *argv[]){ FILE *f[TRACK_MAX]; int flag[TRACK_MAX], flag2; double n[TRACK_MAX]; int i, max, data; long j, t; /* file load */ if(argc < 2){ printf("Usage: a.out file1 file2 ...\n"); exit(1); } else if(argc > TRACK_MAX+1){ printf("too much track.\n"); exit(1); } for(i=0; i<argc-1; i++){ f[i] = fopen(argv[i+1], "r"); if(f[i] == NULL){ printf("cannot open %s.\n",argv[i+1]); exit(1); } flag[i] = 0; } /* add */ max = 0.0; t = 0; while(1){ sum[t] = 0.0; for(i=0; i<argc-1; i++){ if(flag[i] != EOF){ flag[i] = fscanf(f[i], "%lf", &n[i]); } else n[i] = 0.0; sum[t] += n[i]; } if(sum[t] > max){ max = sum[t]; } else if(sum[t]<0 && -sum[t] > max){ max = -sum[t]; } t++; flag2 = 1; for(i=0; i<argc-1; i++){ if(flag[i] != EOF){ flag2 = 0; break; } } if(flag2) break; } /* put */ for(j=0; j<t; j++){ data = sum[j]/max*VALUE_MAX; printf("%d\n",data); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define POINT_MAX 44100 #define SAMPLING_RATE 44100 int n[POINT_MAX]; int point, start, finish, s; int main(int argc, char *argv[]){ int i, t, f; double s_sec, f_sec; if(argc != 4){ printf("Usage: a.out point start_time finish_time\n"); exit(1); } point = atoi(argv[1]); s_sec = atof(argv[2]); f_sec = atof(argv[3]); start = SAMPLING_RATE * s_sec; finish = SAMPLING_RATE * f_sec; for(i=0; i<POINT_MAX; i++){ n[i] = 0; } s = 0; f = scanf("%d",&t); while(f!=EOF){ s++; if(s < start || s > finish+point) printf("%d\n",t); else{ for(i=0; i<point; i++){ n[i] += t/point; } printf("%d\n",n[0]); for(i=1; i<point; i++){ n[i-1] = n[i]; } n[point-1] = 0; } f = scanf("%d",&t); } return 0; } <file_sep>#include <stdio.h> #include <math.h> #include <stdlib.h> /* track status */ #define SAMPLING_RATE 44100 #define SONG_LENGTH 300 #define WAVE_STYLE_NUM 3 #define MELODY_NUM 12 #define MELODY_BASE 3 #define VOLUME_MAX 32767 #define PI 3.1416 /* wave form */ #define SIN 's' #define TRIANGLE 't' #define NOKOGIRI 'n' #define PULSE 'p' /* wave data */ double wave[SAMPLING_RATE][SONG_LENGTH]; /* track wave style */ struct wave_parameter{ int form; int attack; int decay; int sustain; int release; int volume; int key; }; struct wave_parameter style[WAVE_STYLE_NUM]; double freq[WAVE_STYLE_NUM]; /* velocity from adsr+v */ double velocity_start[WAVE_STYLE_NUM][SAMPLING_RATE]; double velocity_finish[WAVE_STYLE_NUM][SAMPLING_RATE]; void velocity_set(void); void make_wave(void); double wave_generator(int x, int t); void output_wave(void); int main(void){ int i, j; /* initalize */ for(i=0;i<SAMPLING_RATE;i++){ for(j=0;j<SONG_LENGTH;j++){ wave[i][j] = 0.0; } } /* wave_style load */ for(i=0;i<WAVE_STYLE_NUM;i++){ style[i].form = getchar(); /* check format */ while(style[i].form < 'a' || style[i].form > 'z'){ style[i].form = getchar(); } scanf("%d",&style[i].attack); scanf("%d",&style[i].decay); scanf("%d",&style[i].sustain); scanf("%d",&style[i].release); scanf("%d",&style[i].volume); scanf("%d",&style[i].key); } /* do making */ velocity_set(); make_wave(); output_wave(); return 0; } /* velocity setting to velocity_start and velocity_finish. */ void velocity_set(void){ int i, j; for(i=0; i<WAVE_STYLE_NUM; i++){ for(j=0; j<SAMPLING_RATE; j++){ /* setting to start velocity */ /* before attack timing */ /* reject patern to devide 0. */ if(style[i].attack == 0 && j == 0){ velocity_start[i][j] = style[i].volume; } else if(j<=style[i].attack){ velocity_start[i][j] = j*style[i].volume/style[i].attack; } /* after attack and before decay */ /* reject patern to devide 0. */ if(style[i].decay > 0){ if(j>style[i].attack && j<=style[i].attack+style[i].decay){ velocity_start[i][j] = style[i].volume - ( (j-style[i].attack)*style[i].volume*(100-style[i].sustain)/(style[i].decay*100) ); } } /* setting to finish velocity */ /* reject patern to devide 0. */ if(style[i].release > 0){ if(j < style[i].attack+style[i].decay+style[i].release){ velocity_finish[i][j] = (style[i].volume*style[i].sustain/100) - (style[i].volume*style[i].sustain*j/(100*style[i].release)); } } } } } /* wave data making by input track data */ void make_wave(void){ int melody, velocity, start_sec, start_wave, finish_sec, finish_wave; double start_time, finish_time; int i, t, x, tmp; double melody_freq[MELODY_NUM] = {440.0, 466.164, 495.883, 523.251, 554.365, 587.330, 622.254, 659.255, 698.456, 739.989, 783.991, 830.609}; scanf("%d",&melody); while(melody != 0){ scanf("%d %lf %lf",&velocity, &start_time, &finish_time); /* convert to sec */ start_sec = start_time; finish_sec = finish_time; /* convert to wave timing */ start_wave = (start_time - start_sec) * SAMPLING_RATE; finish_wave = (finish_time - finish_sec) * SAMPLING_RATE; /* convert melody to frequency */ for(i=0; i<WAVE_STYLE_NUM; i++){ freq[i] = melody_freq[melody%MELODY_NUM] * (pow(2, (melody/MELODY_NUM)-MELODY_BASE)) * (pow(2, (style[i].key-2)-MELODY_BASE)); } t = start_sec; /* time */ x = start_wave; /* heni */ /* loop start time to finish time */ /* wave[start_wave][start_sec] ~ wave[finish_wave][finish_sec] */ while(1){ if(t==finish_sec && (x%SAMPLING_RATE) == finish_wave) break; wave[x%SAMPLING_RATE][t] += velocity * wave_generator(x-start_wave, 0); x++; if(x%SAMPLING_RATE == 0) t++; } tmp = x; /* loop finish time to more 1 sec for release*/ while(1){ if(t==finish_sec+1 && (x%SAMPLING_RATE) == finish_wave) break; wave[x%SAMPLING_RATE][t] += velocity * wave_generator(x-start_wave, x-tmp); x++; if(x%SAMPLING_RATE == 0) t++; } scanf("%d",&melody); } } /* wave data generate by melody */ double wave_generator(int x, int t){ double tmp_wave = 0.0; int i, j; double df, f; /* start wave */ if(t == 0){ for(i=0; i<WAVE_STYLE_NUM;i++){ /* calc diff */ j = x/(SAMPLING_RATE/freq[i]); df = x-j*(SAMPLING_RATE/freq[i]); /* SIN wave */ if(style[i].form == SIN){ /* before decay */ if(x<style[i].attack+style[i].decay){ tmp_wave += velocity_start[i][x] * sin(2*PI*freq[i]*df/SAMPLING_RATE); } /* after decay */ else{ tmp_wave += (style[i].volume*style[i].sustain * sin(2*PI*freq[i]*df/SAMPLING_RATE))/100; } } /* TRIANGLE wave */ else if(style[i].form == TRIANGLE){ /* before decay */ if(x<style[i].attack+style[i].decay){ if(df < SAMPLING_RATE/freq[i]/4){ tmp_wave += velocity_start[i][x] * 4*df*freq[i]/SAMPLING_RATE; } else if(df > 3*SAMPLING_RATE/freq[i]/4){ tmp_wave += velocity_start[i][x] * 4*df*freq[i]/SAMPLING_RATE - 4*velocity_start[i][x]; } else{ tmp_wave += - (velocity_start[i][x] * 4*df*freq[i]/SAMPLING_RATE) + 2*velocity_start[i][x]; } } /* after decay */ else{ if(df < (SAMPLING_RATE/freq[i]/4)){ tmp_wave += (style[i].volume*style[i].sustain * 4*df*freq[i]/SAMPLING_RATE/100); } else if(df > 3*SAMPLING_RATE/freq[i]/4){ tmp_wave += (style[i].volume*style[i].sustain * 4*df*freq[i]/SAMPLING_RATE - 4*style[i].volume*style[i].sustain)/100; } else{ tmp_wave +=( - (style[i].volume*style[i].sustain * 4*df*freq[i]/SAMPLING_RATE) + 2*style[i].volume*style[i].sustain)/100; } } } /* NOKOGIRI wave */ else if(style[i].form == NOKOGIRI){ /* before decay */ if(x<style[i].attack+style[i].decay){ tmp_wave += -velocity_start[i][x] + 2*velocity_start[i][x] * df*freq[i]/SAMPLING_RATE; } /* after decay */ else{ tmp_wave += (-style[i].volume*style[i].sustain + 2*style[i].volume*style[i].sustain * df*freq[i]/SAMPLING_RATE)/100; } } /* PULSE wave */ else if(style[i].form == PULSE){ /* before decay */ if(x<style[i].attack+style[i].decay){ if(df < SAMPLING_RATE/freq[i]/2){ tmp_wave += velocity_start[i][x]; } else{ tmp_wave += -velocity_start[i][x]; } } /* after decay */ else{ if(df < SAMPLING_RATE/freq[i]/2){ tmp_wave += style[i].volume*style[i].sustain/100; } else{ tmp_wave += -style[i].volume*style[i].sustain/100; } } } /* other wave */ else tmp_wave += 0.0; } } /* finish wave */ else { for(i=0; i<WAVE_STYLE_NUM;i++){ /* calc diff */ j = x/(SAMPLING_RATE/freq[i]); df = x-j*(SAMPLING_RATE/freq[i]); /* SIN wave */ if(style[i].form == SIN){ if(t<style[i].release){ tmp_wave += velocity_finish[i][t] * sin(2*PI*freq[i]*df/SAMPLING_RATE); } } /* TRIANGLE wave */ else if(style[i].form == TRIANGLE){ if(t<style[i].release){ if(df < SAMPLING_RATE/freq[i]/4){ tmp_wave += velocity_finish[i][t] * 4*df*freq[i]/SAMPLING_RATE; } else if(df > 3*SAMPLING_RATE/freq[i]/4){ tmp_wave += velocity_finish[i][t] * 4*df*freq[i]/SAMPLING_RATE - 4*velocity_finish[i][t]; } else{ tmp_wave += - (velocity_finish[i][t] * 4*df*freq[i]/SAMPLING_RATE) + 2*velocity_finish[i][t]; } } } /* NOKOGIRI wave */ else if(style[i].form == NOKOGIRI){ if(t<style[i].release){ tmp_wave += -velocity_finish[i][t] + 2*velocity_finish[i][t] * df*freq[i]/SAMPLING_RATE; } } /* PULSE wave */ else if(style[i].form == PULSE){ if(t<style[i].release){ if(df < SAMPLING_RATE/freq[i]/2){ tmp_wave += velocity_finish[i][t]; } else{ tmp_wave += -velocity_finish[i][t]; } } } /* other wave */ else tmp_wave += 0.0; } } return tmp_wave; } /* output wave data */ void output_wave(void){ int i, j, k, zero_count; zero_count = 0; for(j=0;j<SONG_LENGTH;j++){ for(i=0;i<SAMPLING_RATE;i++){ if(wave[i][j] > 0.01 || wave[i][j] < -0.01){ for(k=0; k<zero_count; k++){ printf("0.0\n"); } zero_count = 0; printf("%f\n",wave[i][j]); } else{ zero_count++; if(zero_count > SAMPLING_RATE) break; } } if(zero_count > SAMPLING_RATE) break; } printf("0.0\n0.0\n0.0\n"); } <file_sep>/******************************************************************/ /* txt2wav テキストデータ -> wavフォーマットデータ 変換プログラム */ /* */ /* データ 16bit(-2^15 〜 2^15 - 1, -32768 〜 +32767, 無音 = 0) */ /* データ 8bit( 0 〜 2^8 - 1 , 0 〜 +225 , 無音 = 128) */ /* */ /* モノラル(1ch) ステレオ(2ch) */ /* data Lch Rch */ /* data Lch Rch */ /* : : */ /* */ /* 2000.11.13 */ /* <EMAIL> */ /******************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #define PCM 1 #define BUFSIZE (1000) #ifndef UCHAR_MAX #define UCHAR_MAX (255) #endif #ifndef UCHAR_MIN #define UCHAR_MIN (0) #endif #ifndef SHRT_MAX #define SHRT_MAX (32767) #endif #ifndef SHRT_MIN #define SHRT_MIN (-32768) #endif #ifndef _MAX_PATH #define _MAX_PATH (255) #endif static char cmdname[] = "txt2wav"; void usage(void) { fprintf(stderr, "\n" "ASCII テキストデータ ---> wav フォーマット変換プログラム...\n" "使い方 : %s [sampling_rate] <text_file> [wav_file]\n" "\t sampling_rate は " "- に続けてサンプリングレート(単位 Hz)を指定します\n" "\t (wav_file の指定が無い場合 " "text_file.wav のファイルが作成されます)\n" "\n" "例 : %s -44100 filename.txt\n" " (filename.txt のデータを 44.1kHz で " "filename.wav に書き出します)\n" " %s -48000 filename.txt output.wav\n" " (filename.txt のデータを 48kHz で " "output.wav に書き出します)\n" "\n" "データが 0〜255 ならば 8bit wav を出力します\n" "それ以外ならば 16bit wav を出力します\n" "( 8bit データ : 0〜 +255, 無音=128)\n" "(16bit データ : -32768〜+32767, 無音= 0)\n" "\n" "テキストデータ形式 : \n" "\t1ch(モノラル)の場合 2ch(ステレオ)の場合\n" "\tdata Lch Rch\n" "\tdata Lch Rch\n" "\t : : :\n" "\n", cmdname, cmdname, cmdname); exit(1); } void openerror(char *filename) { fprintf(stderr, "Can't open file: %s\n", filename); exit(1); } void formaterror(FILE *fp) { fprintf(stderr, "File format error : %ld\n", ftell(fp)); exit(1); } /*----------------*/ /* ファイル名取得 */ /*----------------*/ int getbasename(char *dest, char *src) { int i, start, end, ret; i = -1; start = 0; end = 0; // ファイル名のはじめと終わりを検出 while (src[++i]) { if (src[i] == '\\' || src[i] == ':') { start = i + 1; end = 0; } if (src[i] == '.') { end = i; } } if (end == 0) { end = i; } // ファイル名が有る場合 if (start < end) { for (i = 0; i < end; i++) { dest[i] = src[i]; } dest[i] = '\0'; ret = 1; } else { dest[0] = '\0'; ret = 0; } return ret; } /*----------------------*/ /* ASCII ファイルの行数 */ /*----------------------*/ unsigned long filesize(FILE *fp) { int c; long count = 0; rewind(fp); while ((c = getc(fp)) != EOF) { if (c == '\n') { count++; } } return count; } /*--------------------*/ /* 量子化ビット数確認 */ /*--------------------*/ short bytecheck(FILE *fp) { int data; char buf[BUFSIZE]; rewind(fp); while (fscanf(fp, "%s", buf) != EOF) { data = strtol(buf, (char **) NULL, 10); if (UCHAR_MAX < data) { return 2; } else if (data < UCHAR_MIN) { return 2; } } // データが 0〜255 ならば 1byte(8bit) return 1; } /*--------------*/ /* チャンネル数 */ /*--------------*/ short chcheck(FILE *fp) { int a, b; short ch; char buf[BUFSIZE]; char s[2]; rewind(fp); fgets(buf, BUFSIZE, fp); ch = sscanf(buf, "%d %d %1s", &a, &b, s); if (ch == 1 || ch == 2) { ; } else { fprintf(stderr, "channel must be 1 or 2\n"); formaterror(fp); } return ch; } /*------------------------------*/ /* データオーバーフローチェック */ /*------------------------------*/ short datacheck(short data, short max, short min) { // オーバーフローする場合 + か - を表示 if (data > max) { fprintf(stderr, "+"); data = max; } if (data < min) { fprintf(stderr, "-"); data = min; } return data; } /*--------------------------------------*/ /* 16 bit データ -32768〜32767 (無音 0) */ /* 8 bit データ 0〜255 (無音 128) */ /*--------------------------------------*/ long datawrite(unsigned short ch, unsigned short byte, FILE *txt, FILE *wav) { short left, right; int n; unsigned long count = 0; char s[2], buf[BUFSIZE]; rewind(txt); while ((fgets(buf, BUFSIZE, txt) != NULL)) { n = sscanf(buf, "%hd %hd %1s", &left, &right, s); if (feof(txt)) { break; } if (ch != n) { formaterror(txt); } // モノラル else if (ch == 1) { // 8 ビット if (byte == 1) { datacheck(left, UCHAR_MAX, UCHAR_MIN); fputc(left, wav); count++; } // 16 ビット else if (byte == 2) { datacheck(left, SHRT_MAX, SHRT_MIN); fwrite(&left, sizeof(short), 1, wav); count++; } } // ステレオ else if (ch == 2) { // 8 ビット if (byte == 1) { datacheck(left, UCHAR_MAX, UCHAR_MIN); datacheck(right, UCHAR_MAX, UCHAR_MIN); fputc(left, wav); fputc(right, wav); count++; } // 16 ビット else if (byte == 2) { datacheck(left, SHRT_MAX, SHRT_MIN); datacheck(right, SHRT_MAX, SHRT_MIN); fwrite(&left, sizeof(short), 1, wav); fwrite(&right, sizeof(short), 1, wav); count++; } } else { formaterror(txt); } } return count; } /*--------------------*/ /* サンプリングレート */ /*--------------------*/ unsigned long sampling(void) { unsigned long sr = 0; char buf[BUFSIZE]; while (sr == 0) { fprintf(stderr, "sampling rate [Hz] : "); fgets(buf, BUFSIZE, stdin); sr = labs(strtoul(buf, (char **) NULL, 10)); } return sr; } /*----------------*/ /* 各種パラメータ */ /*----------------*/ unsigned long parameter(FILE *fp, unsigned long *points, unsigned short *channel, unsigned short *byte) { // データ数 *points = filesize(fp); // 量子化バイト数 1Byte = 8bit, 2Byte = 16bit *byte = bytecheck(fp); // チャンネル数 *channel = chcheck(fp); return (unsigned long) (*points * *byte * *channel); } /*----------------------*/ /* wav ファイル書き出し */ /*----------------------*/ void wavwrite(char *datafile, char *wavfile, unsigned long sr) { unsigned long points, file_size, count, var_long; unsigned short ch, bytes, var_short; char s[4]; FILE *fp1, *fp2; // テキストファイル if ((fp1 = fopen(datafile, "r")) == NULL) { openerror(datafile); } file_size = parameter(fp1, &points, &ch, &bytes); printf("%s : %ld Hz sampling, %d bit, %d channel\n", wavfile, sr, bytes * 8, ch); // WAV ファイル if ((fp2 = fopen(wavfile, "wb")) == NULL) { openerror(wavfile); } // RIFF ヘッダ s[0] = 'R'; s[1] = 'I'; s[2] = 'F'; s[3] = 'F'; fwrite(s, 1, 4, fp2); // ファイルサイズ var_long = file_size + 36; fwrite(&var_long, sizeof(long), 1, fp2); printf(" file size (header + data) = %ld [Byte]\n", var_long); // WAVE ヘッダ s[0] = 'W'; s[1] = 'A'; s[2] = 'V'; s[3] = 'E'; fwrite(s, 1, 4, fp2); // chunkID (fmt チャンク) s[0] = 'f'; s[1] = 'm'; s[2] = 't'; s[3] = ' '; fwrite(s, 1, 4, fp2); // chunkSize (fmt チャンクのバイト数 無圧縮 wav は 16) var_long = 16; fwrite(&var_long, sizeof(long), 1, fp2); // wFromatTag (無圧縮 PCM = 1) var_short = PCM; fwrite(&var_short, sizeof(short), 1, fp2); // dwChannels (モノラル = 1, ステレオ = 2) fwrite(&ch, 2, 1, fp2); printf(" PCM type = %hu\n", var_short); // dwSamplesPerSec (サンプリングレート(Hz)) fwrite(&sr, sizeof(long), 1, fp2); printf(" sampling rate = %ld [Hz]\n", sr); // wdAvgBytesPerSec (Byte/秒) var_long = bytes * ch * sr; fwrite(&var_long, sizeof(long), 1, fp2); printf(" Byte / second = %ld [Byte]\n", var_long); // wBlockAlign (Byte/サンプル*チャンネル) var_short = bytes * ch; fwrite(&var_short, sizeof(short), 1, fp2); printf(" Byte / block = %hu [Byte]\n", var_short); // wBitsPerSample (bit/サンプル) var_short = bytes * 8; fwrite(&var_short, sizeof(short), 1, fp2); printf(" bit / sample = %hu [bit]\n", var_short); // chunkID (data チャンク) s[0] = 'd'; s[1] = 'a'; s[2] = 't'; s[3] = 'a'; fwrite(s, 1, 4, fp2); // chunkSize (データ長 Byte) fwrite(&file_size, 4, 1, fp2); printf(" file size (data) = %ld [Byte]\n", file_size); // ヘッダ (44 Byte) 書き込みここまで if (ftell(fp2) != 44) { fprintf(stderr, "%s : wav header write error\n", wavfile); exit(1); } // waveformData (データ) 書き込み count = datawrite(ch, bytes, fp1, fp2); // データ書き込みここまで if (count != points) { fprintf(stderr, "%s : data write error\n", wavfile); exit(1); } fclose(fp1); fclose(fp2); printf(" %ld points write\n", count); printf("%s : %ld bytes (%g sec)\n", wavfile, count * bytes * ch + 44, (double) count / sr); } /**************/ /* メイン関数 */ /**************/ int main(int argc, char *argv[]) { int ac = 0, optc = 0; unsigned long sr = 0; char txtfile[_MAX_PATH], wavfile[_MAX_PATH]; if (argc != 1) { int i; ac = argc - 1; for (i = 1; i < argc; i++) { // サンプリングレート指定あり if (argv[i][0] == '-') { sr = labs(strtoul(&argv[i][1], (char **) NULL, 10)); ac = argc - 2; optc = 1; } } } else usage(); // コマンドチェック(オプション以外の引数) if (ac < 1) { usage(); } else if (ac == 1) { char basename[_MAX_PATH]; strcpy(txtfile, argv[optc + 1]); getbasename(basename, argv[optc + 1]); sprintf(wavfile, "%s.wav", basename); } else if (ac == 2) { strcpy(txtfile, argv[optc + 1]); strcpy(wavfile, argv[optc + 2]); } else { usage(); } // サンプリングレート if (sr == 0) { sr = sampling(); } wavwrite(txtfile, wavfile, sr); return 0; }
7b040b2e1d4daafe4881c78ad54b30000e268fdf
[ "C" ]
4
C
rionslion/synth
2f040a2d7f5ffb0a6216086f645808585106e20d
a3e39b256f0f06d4a20434577a9bcdfa49c8e172
refs/heads/master
<repo_name>LaurenMangibin/CheatSheet<file_sep>/Stack/StackTester.java public class StackTester { public static void main(String[] args) { AStack myStack = new AStack(); System.out.println(myStack.isEmpty()); //myStack.pop(); for (int i = 0; i < 1000; i++){ myStack.push(i); } while(!myStack.isEmpty()){ System.out.println(myStack.pop()); } } } <file_sep>/README.md # CheatSheet Data Structure Implementations, Algorithms, Concepts <file_sep>/Stack/AStack.java //Stack Implementation with Array import java.io.*; import java.util.*; public class AStack { static final int MAX = 1000; int[] Stack = new int[MAX]; int top = -1; public void push(int item){ //check if full if (top+1 >= MAX){ throw new RuntimeException("Stack full"); } System.out.println(item); Stack[++top] = item; } public int pop(){ //check if empty if(top < 0){ throw new RuntimeException("Stack Empty"); } return Stack[top--]; } public int peek(){ //check if empty if(top < 0){ throw new RuntimeException("Stack Empty"); } return Stack[top]; } //returns true if there is nothing in the stack public boolean isEmpty(){ return (top < 0); } } <file_sep>/Stack/LLStack.java import java.io.*; import java.util.*; //Stack Implementation with Nodes public class LLStack<T> { //Stack node private static class StackNode<T> { private T data; private StackNode<T> next; public StackNode (T inputData){ data = inputData; } } //indicates top of stack private StackNode<T> top; //adds element to top of the stack public void push (T item){ StackNode<T> node = new StackNode<>(item); node.next = top; top = node; } //returns and removes the top element off the stack public T pop (){ //check if empty if (top == null){ throw new EmptyStackException(); } T item = top.data; top = top.next; return item; } //returns top element in stack public T peek(){ if (top == null){ throw new EmptyStackException(); } T item = top.data; return item; } //returns true if stack is empty public boolean isEmpty(){ if (top == null){ return true; } return false; } }
4bfb236c432e330ff24a0e82bfaa9074aac2b946
[ "Markdown", "Java" ]
4
Java
LaurenMangibin/CheatSheet
0bfc47cd777bc5876a321a6a72345b56c8e051ed
3b43685ccb3429b1ca2b011556ceb2c1f1f2fc92
refs/heads/master
<repo_name>alex-slapoguzov/HT1<file_sep>/src/test/java/com/epam/training/pages/UsersPage.java package com.epam.training.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class UsersPage extends AbstractPage { @FindBy(xpath = "//div[@class=\"task\"][3]//a[@class=\"task-link\"]") private WebElement createUserLink; @FindBy(xpath = "//a[@href=\"user/someuser/delete\"]") private WebElement deleteLink; public UsersPage(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); } public CreateUserPage clickCreateUserLink() { createUserLink.click(); return new CreateUserPage(driver); } public SomeUserPage clickDeleteLink() { deleteLink.click(); return new SomeUserPage(driver); } public String isLinkPresent() { String result = null; if (createUserLink.isEnabled()) { result = createUserLink.getText(); } return result; } } <file_sep>/src/test/java/com/epam/training/driver/ChromeDriverSettings.java package com.epam.training.driver; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.concurrent.TimeUnit; public class ChromeDriverSettings { private static WebDriver driver; private static final String WEBDRIVER_CHROMEDRIVER = "webdriver.chromedriver"; private static final String CHROMEDRIVER_PATH = ".\\chromedriver\\chromedriver.exe"; public static WebDriver getDriver() { if (null == driver) { System.setProperty(WEBDRIVER_CHROMEDRIVER, CHROMEDRIVER_PATH); ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--lang=en-US"); driver = new ChromeDriver(chromeOptions); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); } return driver; } public static void closeDriver() { driver.quit(); driver = null; } } <file_sep>/src/test/java/com/epam/training/JenkinsTests.java package com.epam.training; import com.epam.training.actions.Actions; import com.epam.training.validators.Validators; import org.testng.Assert; import org.testng.annotations.*; public class JenkinsTests { //Run with testng.xml private Actions actions; private Validators validators; @Parameters({"userForLogIn", "passwordForLogIn", "BASE_URL"}) @BeforeClass public void setUp(String userForLogIn, String passwordForLogIn, String BASE_URL) { validators = new Validators(); actions = new Actions(); actions.initBrowser(); actions.loginJenkins(userForLogIn, passwordForLogIn, BASE_URL); } @AfterClass() public void stopBrowser() { actions.closeDriver(); } @Parameters({"tagname1", "tagname2", "manageUsersText1", "manageUsersText2"}) @Test public void testManageJenkins(String tagname1, String tagname2, String manageUsersText1, String manageUsersText2) { actions.clickToLinkManageJenkins(); Assert.assertTrue(validators.checkElementPresentWithTagNameAndText(tagname1, manageUsersText1), "[Element " + tagname1 + " with text " + manageUsersText1 + " is absent]"); Assert.assertTrue(validators.checkElementPresentWithTagNameAndText(tagname2, manageUsersText2), "[Element " + tagname2 + " with text " + manageUsersText2 + " is absent]"); } @Test() public void testManageUsers() { actions.clickToLinkManageUsers(); String link = actions.getLink(); Assert.assertTrue(validators.checkLinkPresent(link), "Link isn't present"); } @Test() public void testCreateUser() { actions.clickToLinkCreateUser(); Assert.assertTrue(validators.checkFormPresent(), "[Form with fields of type text and password isn't present]"); Assert.assertTrue(validators.checkFieldsInFormEmpty(), "[All fields in form aren't empty]"); } @Parameters({"userForTest", "passwordForTest", "fullNameForTest", "emailAddressForTest", "tagname3", "tagname4"}) @Test public void testCreateNewUser(String userForTest, String passwordForTest, String fullNameForTest, String emailAddressForTest, String tagname3, String tagname4) { actions.submitForm(userForTest, passwordForTest, fullNameForTest, emailAddressForTest); Assert.assertTrue(validators.checkTextPresent(tagname3, tagname4, userForTest), "Element with text someuser absent!"); } @Parameters({"textConfirmation"}) @Test public void testDeleteButton(String textConfirmation) { actions.clickToLinkDelete(); String text = actions.getText(); Assert.assertTrue(validators.checkTextConfirmation(text, textConfirmation), "[Text ]" + textConfirmation + "[ isn't present]"); } @Parameters({"tagname3", "tagname4", "userForTest", "textHrefAttribute1"}) @Test public void testDeleteUser(String tagname3, String tagname4, String userForTest, String textHrefAttribute1) { actions.clickYesButton(); Assert.assertFalse(validators.checkTextPresent(tagname3, tagname4, userForTest), "Element is on the page"); Assert.assertFalse(validators.checkLinkWithHrefPresent(textHrefAttribute1), "Link is on the page"); } @Parameters({"textHrefAttribute2"}) @Test public void testLinkWithHrefPresent(String textHrefAttribute2) { Assert.assertFalse(validators.checkLinkWithHrefPresent(textHrefAttribute2), "Link is on the page"); } } <file_sep>/src/test/java/com/epam/training/validators/Validators.java package com.epam.training.validators; import com.epam.training.driver.ChromeDriverSettings; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.Collection; public class Validators { private WebDriver driver = ChromeDriverSettings.getDriver(); private WebDriverWait wait = new WebDriverWait(driver, 30); public boolean checkElementPresentWithTagNameAndText(String tagname, String text) { Collection<WebElement> tags = driver.findElements(By.tagName(tagname)); if (tags.isEmpty()) { return false; } boolean result = false; for (WebElement element : tags) { if (element.getText().equals(text)) { result = true; break; } } return result; } public boolean checkLinkPresent(String link) { boolean result = false; if (driver.findElement(By.linkText(link)).isEnabled()) { result = true; } return result; } public boolean checkTextPresent(String tagname1, String tagname2, String text) { Collection<WebElement> tags = driver.findElements(By.tagName(tagname1)); if (tags.isEmpty()) { return false; } boolean result = false; for (WebElement element : tags) { Collection<WebElement> tags2 = element.findElements(By.tagName(tagname2)); if (tags.isEmpty()) { return false; } for (WebElement element2 : tags2) { if (element2.getText().equals(text)) { result = true; break; } } } return result; } public boolean checkLinkWithHrefPresent(String text) { Collection<WebElement> tags = driver.findElements(By.xpath("//table[@class=\"sortable pane bigtable\"]")); if (tags.isEmpty()) { return false; } boolean result = false; for (WebElement element : tags) { if (element.findElement(By.tagName("a")).getAttribute("href").equalsIgnoreCase(text)) { result = true; break; } } return result; } public boolean checkFormPresent() { wait.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//div[@id=\"main-panel\"]//form"), 1)); WebElement form = driver.findElement(By.xpath("//div[@id=\"main-panel\"]//form")); boolean form_found = false; if ((form.findElement(By.name("username")).getAttribute("type").equalsIgnoreCase("text")) && (form.findElement(By.name("password1")).getAttribute("type").equalsIgnoreCase("password")) && (form.findElement(By.name("password2")).getAttribute("type").equalsIgnoreCase("password")) && (form.findElement(By.name("fullname")).getAttribute("type").equalsIgnoreCase("text")) && (form.findElement(By.name("email")).getAttribute("type").equalsIgnoreCase("text"))) { form_found = true; } return form_found; } public boolean checkFieldsInFormEmpty() { wait.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//div[@id=\"main-panel\"]//form"), 1)); WebElement form = driver.findElement(By.xpath("//div[@id=\"main-panel\"]//form")); boolean form_found = false; if ((form.findElement(By.name("username")).getText().equals("")) && (form.findElement(By.name("password1")).getText().equals("")) && (form.findElement(By.name("password2")).getText().equals("")) && (form.findElement(By.name("fullname")).getText().equals("")) && (form.findElement(By.name("email")).getText().equals(""))) { form_found = true; } return form_found; } public boolean checkTextConfirmation(String text, String textConfirmation) { boolean result = false; if (text.contains(textConfirmation)) { result = true; } return result; } public boolean checkErrorMessage(String message, String currentMessage) { boolean result = false; if (message.equals(currentMessage)) { result = true; } return result; } public boolean checkButtonColor(String currentColor, String color) { if (color.equals(currentColor)) { return true; } else { return false; } } } <file_sep>/src/test/java/com/epam/training/pages/SomeUserPage.java package com.epam.training.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SomeUserPage extends AbstractPage { @FindBy(id = "yui-gen4-button") private WebElement yesButton; @FindBy(xpath = "//form[@name=\"delete\"]") private WebElement formWithText; public SomeUserPage(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); } public UsersPage clickYesButton() { yesButton.click(); return new UsersPage(driver); } public String getTextConfirmation() { return formWithText.getText(); } public String getColor(){ return yesButton.getCssValue("background-color"); } }
45af58b9909909496b3d845fd10da6ed1a3c9267
[ "Java" ]
5
Java
alex-slapoguzov/HT1
0f8cd1b73eccbc727e4c91e9ed91daf644ef1af5
3bfe372c20f966804dd5d7441b421d68c0318d52
refs/heads/master
<file_sep>!#/bin/bash export LC_ALL=C.UTF-8 && export LANG=C.UTF-8 alias python=python3 touch db/$DATABASE_NAME python migrate.py db upgrade flask run --host 0.0.0.0 --port 5020<file_sep>"""empty message Revision ID: 5c158644cc09 Revises: <PASSWORD> Create Date: 2019-12-10 17:36:35.994702 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5c158644cc09' down_revision = '<PASSWORD>' branch_labels = None depends_on = None connection = op.get_bind() def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('BookTypes', sa.Column('minimumCharge', sa.Float(), nullable=True)) op.add_column('BookTypes', sa.Column('minimumRetention', sa.Integer(), nullable=True)) op.add_column('BookTypes', sa.Column('trialCharge', sa.Float(), nullable=True)) op.add_column('BookTypes', sa.Column('trialPeriod', sa.Integer(), nullable=True)) connection.execute(""" Update "BookTypes" set "minimumCharge"=2, "minimumRetention"=2, "trialCharge"=1, "trialPeriod"=2 where "type"='regular'; """) connection.execute(""" Update "BookTypes" set "minimumCharge"=4.5, "minimumRetention"=3 where "type"='novel'; """) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('BookTypes', 'trialPeriod') op.drop_column('BookTypes', 'trialCharge') op.drop_column('BookTypes', 'minimumRetention') op.drop_column('BookTypes', 'minimumCharge') # ### end Alembic commands ### <file_sep>import json import os def get_json_from_file(filename, my_path): file_content = read_local_file(filename, my_path) response = json.loads(file_content) return response def read_local_file(relative_path_filename, my_path): path = os.path.join(my_path, relative_path_filename) with open(path) as f: return f.read()<file_sep>"""empty message Revision ID: aed8bac5375d Revises: Create Date: 2019-12-10 13:30:45.562666 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'aed8bac5375d' down_revision = None branch_labels = None depends_on = None connection = op.get_bind() def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('BookTypes', sa.Column('type', sa.String(length=20), nullable=False), sa.Column('charge', sa.Float(), nullable=False), sa.PrimaryKeyConstraint('type'), sa.UniqueConstraint('type') ) connection.execute(""" INSERT INTO "BookTypes"("type", "charge") VALUES ('regular','1.5'), ('fiction','3'), ('novel','1.5'); """) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('BookTypes') # ### end Alembic commands ### <file_sep>import unittest import sys sys.path.append('..') from app import calculate_amount, app from utilities.file_operations import * class TestClass(unittest.TestCase): def setUp(self): # self.app = app.test_client() self.app = app self.app.testing = True self.client = self.app.test_client() def test_calculate_amount(self): self.assertEqual(24 == calculate_amount(get_json_from_file("test_data/rented_book_items.json", os.path.abspath(os.path.dirname(__file__)))), True) def test_index(self): response = self.client.get("/") self.assertEqual(response.status_code, 200) def test_statement(self): response = self.client.get("/statement") self.assertEqual(response.status_code, 200) def test_calculate(self): payload = get_json_from_file("test_data/rented_book_items.json", os.path.abspath(os.path.dirname(__file__))) amount = calculate_amount(payload) response = self.client.post("/calculate", data=json.dumps(payload), headers={"Content-Type": "application/json"}) response = json.loads(response.data.decode().replace("'", '"')) self.assertEqual(response, {"url": "/statement?amount=" + str(amount)}) def test_calculate_fail(self): payload = get_json_from_file("test_data/fail_rented_book_items.json", os.path.abspath(os.path.dirname(__file__))) response = self.client.post("/calculate", data=json.dumps(payload), headers={"Content-Type": "application/json"}) self.assertEqual(response.status_code, 400) if __name__ == '__main__': unittest.main() <file_sep>from flask import Flask, render_template, request, flash, redirect, url_for, jsonify from flask_cors import CORS import logging from db.db import * from db.db_functions import * app = Flask(__name__) app.config.from_object("config") app.secret_key = app.config['FLASK_SECRET_KEY'] app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + database_file app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False CORS(app) db.app = app db.init_app(app) logging.basicConfig(level=logging.DEBUG) @app.route('/', methods=["get", "post"]) def index(): flash("Welcome home !! " , "info") return render_template('index.html') @app.route('/calculate', methods=['post']) def calculate(): try: # comment just for trying BFG BFG BFG # BFG app.logger.info('processing request') app.logger.info(request) app.logger.debug(request.get_json()) items = request.get_json() amount = calculate_amount(items) app.logger.debug("amount is " + str(amount)) app.logger.debug(type(int) is type(amount)) app.logger.debug(type(amount)) result = { "url": url_for('statement') + "?amount=" + str(amount)} return jsonify(result) except Exception as e: print(str(e)) flash("Error occurred: " + str(e), "danger") return render_template('errors/404.html'), 400 @app.route('/statement') def statement(): flash("Please find your bill ", "info") return render_template('statement.html', amount=request.args.get('amount'), currency=app.config['CURRENCY']) def calculate_amount(items): bookTypeInfo = get_book_types_and_charges() import json app.logger.debug(json.dumps(bookTypeInfo, indent=4)) amount = 0 for item in items: cost = 0 originalCharge = bookTypeInfo[item["bookType"]]["charge"] minimumCharge = bookTypeInfo[item["bookType"]]["minimumCharge"] minimumRetention = bookTypeInfo[item["bookType"]]["minimumRetention"] trialCharge = bookTypeInfo[item["bookType"]]["trialCharge"] trialPeriod = bookTypeInfo[item["bookType"]]["trialPeriod"] quantity = item["bookQuantity"] duration = item["dayDuration"] if minimumCharge is None and minimumRetention is None: if trialPeriod is not None: cost = min(trialPeriod, duration) * quantity * trialCharge duration = duration - trialPeriod if duration > trialPeriod else 0 cost += duration * quantity * originalCharge elif minimumRetention is None and minimumCharge is not None: if trialPeriod is not None: cost = min(trialPeriod, duration) * quantity * trialCharge duration = duration - trialPeriod if duration > trialPeriod else 0 cost += duration * quantity * originalCharge cost = max(cost, minimumCharge) elif minimumCharge is not None and minimumRetention is not None: if duration < minimumRetention: cost = minimumCharge else: if trialPeriod is not None: cost = min(trialPeriod, duration) * quantity * trialCharge duration = duration - trialPeriod if duration > trialPeriod else 0 cost += duration * quantity * originalCharge else: if trialPeriod is not None: cost = min(trialPeriod, duration) * quantity * trialCharge duration = duration - trialPeriod if duration > trialPeriod else 0 cost += duration * quantity * originalCharge amount += cost app.logger.debug(cost) app.logger.debug(amount) return amount if __name__ == '__main__': app.run(host="127.0.0.1", port=5020, debug=app.debug)<file_sep> ## steps to run this application 1. cd <your_project_directory_root> 2. python -m virtualenv venv 3. source venv/Scripts/activate 4. python -m pip install -r requirements.txt 5. source envs/dev ("dev" for "development" environment, "prod" for "production" environment) 6. Clear the database dependencies by running the "Database migration commands" mentioned in the [README.md](README.md) file 7. python app.py ## update requirements.txt If you've installed any other packages apart from requirements.txt then update your requirements.txt file by ```bash run "python -m pip freeze>requirements.txt" ``` <file_sep>from db.db import * # return all available book types from DB def get_book_types_list(): bookTypesRecords = BookTypes.query.with_entities(BookTypes.type).all() bookTypes = [] for bookType in bookTypesRecords: bookTypes.append(bookType.type) return bookTypes # return all book types and its charges per day from DB def get_book_types_and_charges(): bookTypesRecords = BookTypes.query.all() bookTypes = {} for bookType in bookTypesRecords: record = dict() record["charge"] = bookType.charge record["minimumCharge"] = bookType.minimumCharge record["minimumRetention"] = bookType.minimumRetention record["trialCharge"] = bookType.trialCharge record["trialPeriod"] = bookType.trialPeriod bookTypes[bookType.type] = record return bookTypes <file_sep> # this alone is not sufficient for jenkins, jenkins configuration on the server/local has to be made manually. # but these below commands are what needed in the jenkins' pipeline configure's execute shell section to build the code. CONTAINER_NAME=python-flask-book-rental-calculator:latest # stopping all containers built from this image docker ps -a | awk '{print $1, $2}' | grep python-flask-book-rental-calculator:latest | awk '{print $1}' | xargs -n 1 docker stop # removing all containers built from this image docker ps -a | awk '{print $1, $2}' | grep python-flask-book-rental-calculator:latest | awk '{print $1}' | xargs -n 1 docker rm # just printing list of files and directories on pwd ls -la # just printing docker version docker --version # building image from the repo docker build -t python-flask-book-rental-calculator:latest . # creating container from the image built docker run --name flask-book-app --env-file book-rental-calculator/envs/dev -d -p 5020:5020 python-flask-book-rental-calculator:latest <file_sep># Python-Flask Book Rental Calculator This is a simple book rental calculator app ### To install the dependencies and run the application For steps to run the application, please refer to [this file](steps.md) ### Initial DB creation As this project is using a sqlite database, we need to create a file which can be used as storage for our database **Note**: Please make sure you completed the above "dependencies" section to proceed further. 1 Create a file for database with the environment specific database name ```bash source envs/dev touch db/$DATABASE_NAME ``` 2 a. Initialize the migrations folder for database related changes and information. b. run the migrate command to generate the migration script contains DB schema(for First time) and changes in schema(from Second time onwards) ```bash python migrate.py db init python migrate.py db migrate ``` c. Make any required changes in the generated migration script and run the following command ```bash python migrate.py db upgrade ``` ### Run the application ```bash Python app.py ``` ### Unittests The **tests** folder contains unittest files. Run the following command to run all the files in this **test** folder ```bash coverage run -m unittest discover -s tests/ -p 'test_*.py' ``` To see the report generated over the run command, run the following command ```bash coverage report ``` ### Dockerize the application Go to the root folder of this project( where Dockerfile is located). 1 To build ``` docker build -t <custom_image_name> . ``` 2 To create container from the created image ```bash docker run --name <custom_container_name> --env-file book-rental-calculator\envs\dev -d -p 5020:5020 <img_id> ``` As we have redirected the port from container port to HOST machine port using **-p** command, now we can access the application in the container form the localhost browser (http://127.0.0.1:5020). 3 To create tage for this image ```bash docker tag <img_id> <tag-nameeg:4329/python-flask-book-rental-calculator:1.1.0> ``` 4 To push this image to our docker hub repository ```bash docker push <tag-name eg: 4329/python-flask-book-rental-calculator:1.1.0> ``` **Note:** Don't forget to do "Docker login" before pushing the image <file_sep>import unittest import sys sys.path.append('..') from db.db_functions import * from utilities.file_operations import * from app import app class MyTestCase(unittest.TestCase): def setUp(self): # self.app = app.test_client() self.app = app self.app.testing = True self.client = self.app.test_client() def test_get_book_types_list(self): bookTypes = get_json_from_file("test_data/book_types.json", os.path.abspath(os.path.dirname(__file__))) bookTypes = bookTypes["bookTypes"] assert (bookTypes.sort() == get_book_types_list().sort()) def test_get_book_types_and_charges(self): bookTypeCharges = get_json_from_file("test_data/book_type_charges.json", os.path.abspath(os.path.dirname(__file__))) assert(bookTypeCharges == get_book_types_and_charges()) if __name__ == '__main__': unittest.main() <file_sep>import unittest import sys sys.path.append('..') from db.db import BookTypes class MyTestCase(unittest.TestCase): def setUp(self): self.bookType = BookTypes() def test_repr(self): self.bookType.type = 'fiction' self.bookType.charge = 3 assert (repr(self.bookType) == "<Type: fiction Charge: 3>") if __name__ == '__main__': unittest.main() <file_sep>FROM ubuntu:latest MAINTAINER jaggu4329 <<EMAIL>> RUN apt-get update -y RUN apt-get install -y python3-pip python3-dev build-essential && apt-get install curl -y && apt-get install vim -y COPY book-rental-calculator/ /book-rental-calculator RUN pip3 install -r /book-rental-calculator/requirements.txt WORKDIR /book-rental-calculator/ EXPOSE 5020 RUN ls -al CMD ["sh", "dev.sh"] <file_sep>import os # fetching project's root PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) print("project root", PROJECT_ROOT) FLASK_SECRET_KEY = os.environ["FLASK_SECRET_KEY"].encode() FLASK_ENV = os.environ["FLASK_ENV"] CURRENCY = os.environ["CURRENCY"] DATABASE_NAME = os.environ["DATABASE_NAME"]<file_sep>alembic==1.3.1 certifi==2019.9.11 cffi==1.13.2 chardet==3.0.4 Click==7.0 coverage==4.5.4 cryptography==2.8 Flask==1.1.1 Flask-Cors==3.0.8 Flask-Migrate==2.5.2 Flask-Script==2.0.6 Flask-SQLAlchemy==2.4.1 idna==2.8 itsdangerous==1.1.0 Jinja2==2.10.3 linecache2==1.0.0 Mako==1.1.0 MarkupSafe==1.1.1 pipenv==2018.6.25 pycparser==2.19 PyJWT==1.7.1 python-dateutil==2.8.1 python-editor==1.0.4 requests==2.22.0 six==1.13.0 SQLAlchemy==1.3.11 traceback2==1.4.0 unittest2==1.1.0 urllib3==1.25.7 waitress==1.3.1 Werkzeug==0.16.0 <file_sep>import os from config import PROJECT_ROOT, DATABASE_NAME from flask_sqlalchemy import SQLAlchemy database_file = os.path.join(PROJECT_ROOT, 'db', DATABASE_NAME) db = SQLAlchemy() class BookTypes(db.Model): __tablename__ = 'BookTypes' type = db.Column(db.String(20), unique=True, nullable=False, primary_key=True) charge = db.Column(db.Float, nullable=False) # original charge per day minimumCharge = db.Column(db.Float, nullable=True) # minimum charge to be paid minimumRetention = db.Column(db.Integer, nullable=True) # minimumDays to avoid minimum charge trialCharge = db.Column(db.Float, nullable=True) # discounted charge per day in trial period trialPeriod = db.Column(db.Integer, nullable=True) # no. of days for trial period def __repr__(self): return "<Type: {} Charge: {}>".format(self.type, self.charge)
a8d6ddf06f67c424a438d1e1896f876eaef65d59
[ "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
16
Shell
jagadish432/large_flask
5f29bc0f49f809ea2fb3811333aa93b1df1cf224
7bff34fc14cc196618dc5f2a5ec0f48f8abceff4
refs/heads/master
<file_sep>/* <NAME> March 14, 2013 Wiring: * GND = GND * VCC = 3.3 V * SCL = A5 * SDA = A4 * SDO = GND * CS = 3.3 V * INT2 = NC * INT1 = NC */ #include <Wire.h> #define CTRL_REG1 0x20 #define CTRL_REG2 0x21 #define CTRL_REG3 0x22 #define CTRL_REG4 0x23 #define CTRL_REG5 0x24 int L3G4200D_Address = 0b1101000; // L3G4200D's I2C address int x; int y; int z; int temp; const int numReadings = 35; int readings[numReadings]; // the readings from the analog input int index = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average void setup() { Wire.begin(); // join the I2C bus as master Serial.begin(115200); // open serial port for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } //Serial.println("Starting up L3G4200D..."); setupL3G4200D(2000); // configure L3G4200 at 250, 500, or 2000 degrees per second delay(2000); // wait for the sensor to be ready } void loop() { getGyroValues(); // update x, y, and z with new values Serial.println(x); // send it to the computer as ASCII digits } void loopAlt() { getGyroValues(); // update x, y, and z with new values total = total - readings[index]; // subtract the last reading readings[index] = x; // read from the sensor total = total + readings[index]; // add the reading to the total index++; // advance to the next position in the array if (index >= numReadings) // if we're at the end of the array, { index = 0; // wrap around to the beginning } average = total / numReadings; // calculate the average Serial.println(average); // send it to the computer as ASCII digits delay(1); } void getGyroValues() { byte xMSB = readRegister(L3G4200D_Address, 0x29); byte xLSB = readRegister(L3G4200D_Address, 0x28); x = ((xMSB << 8) | xLSB); byte yMSB = readRegister(L3G4200D_Address, 0x2B); byte yLSB = readRegister(L3G4200D_Address, 0x2A); y = ((yMSB << 8) | yLSB); byte zMSB = readRegister(L3G4200D_Address, 0x2D); byte zLSB = readRegister(L3G4200D_Address, 0x2C); z = ((zMSB << 8) | zLSB); } int setupL3G4200D(int scale) // From <NAME>'s (Sparkfun) code { // Enable x, y, z, and turn off power down: writeRegister(L3G4200D_Address, CTRL_REG1, 0b00001111); // If you'd like to adjust/use the HPF, you can edit the line below to configure CTRL_REG2: writeRegister(L3G4200D_Address, CTRL_REG2, 0b00000000); // Configure CTRL_REG3 to generate data ready interrupt on INT2 // No interrupts used on INT1, if you'd like to configure INT1 // or INT2 otherwise, consult the datasheet: writeRegister(L3G4200D_Address, CTRL_REG3, 0b00001000); // CTRL_REG4 controls the full-scale range, among other things: if(scale == 250) { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00000000); } else if(scale == 500) { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00010000); } else { writeRegister(L3G4200D_Address, CTRL_REG4, 0b00110000); } // CTRL_REG5 controls high-pass filtering of outputs, use it // if you'd like: writeRegister(L3G4200D_Address, CTRL_REG5, 0b00000010); } void writeRegister(int deviceAddress, byte address, byte val) { Wire.beginTransmission(deviceAddress); // start transmission to device Wire.write(address); // send register address Wire.write(val); // send value to write Wire.endTransmission(); // end transmission } int readRegister(int deviceAddress, byte address) { int v; Wire.beginTransmission(deviceAddress); Wire.write(address); // register to read Wire.endTransmission(); Wire.requestFrom(deviceAddress, 1); // request one byte from slave while(!Wire.available()) // wait until one byte is received { } v = Wire.read(); // store received byte return v; }
b8b77b4ca4d27b0071fc4be90a485e657d8a129a
[ "C++" ]
1
C++
ryanmaksymic/Dissolving_Self
9bc60ea1f47500bfb87780a5f02fc78c69fcb4df
c332396ba9abda1ed29a7576f949f9a78c056a2b
refs/heads/master
<file_sep>health = 20 --1 enemyhealth = 20 --2 attack = 1--3 money = 0 cost = 0--5 enemyattack= 1 price = money-cost--7 level = 1 attacklevel=1 xp= 0 xpneeded=10 weapon= "fists" repeat--8 print("Your Health="..health)--9 print("The enemies health="..enemyhealth) print("Your weapon="..weapon) print("Your Attack="..attack)--11 print("The enemy's attack="..enemyattack) print("Your Money="..money) print("Your xp="..xp) print("Xp needed="..xpneeded) print("Your level="..level) if health<=enemyattack then print("Warning!") end injury= enemyhealth-attack--13 print("attack?")--14 move = io.read()--15 if move == "y" then--16 enemyhealth= enemyhealth - attack enemymove= math.random(2)--19 if enemymove == 1 then--20 health= health-enemyattack elseif enemymove== 2 then enemyhealth = enemyhealth+enemyattack end enemyattack =enemyattack +level/4 xp= xp + enemyattack if xp >=xpneeded then level = level + 1 print("You have leveled up!") print("Do you want to level up in attack, health,") levelup=io.read() if levelup == "a" then print("You have lost your weapons but gained attack") weapon= "fists" attacklevel= attacklevel+level*3 attack= attacklevel xp=0 money= money+level xpneeded=xpneeded+enemyattack*enemyattack elseif levelup== "h" then health = health + level*10 xp= 0 money=money+level xpneeded=xpneeded+enemyattack*enemyattack end end money = money + level elseif move == "n" then--Store print("Do you want to use the store?")--23 store = io.read()--24 if store == "y" then--25 print(" Do you want to buy a sword(10),knife(2),potion("..level.."),longsword(20),mace(15),Warhammer(50)") buy = io.read()--27 if buy == "s" then--28 if money>=10 then--29 cost = 10--30 money = money- cost attack= attacklevel+5 weapon= "sword" elseif money<10 then--34 print("Not enough money")--35 end--36 elseif buy == "k" then--37 if money>=2 then money = money-2 attack = attacklevel+3 weapon= "knife" elseif money<2 then print("Not enough money!") end elseif buy == "p" then if money>= level then money = money -level health = health + math.random(level*5) elseif money< 1 then print("Not enough money") end elseif buy == "l" then if money>= 20 then money = money-20 attack = attacklevel+ 10 elseif money < 20 then weapon="longsword" print("Not enough money!") end elseif buy== "m" then if money>=15 then money=money-15 attack=attacklevel+7 weapon="mace" elseif money<15 then print("Not enough money!") end elseif buy == "w" then if money>=50 then money= money-50 attack=attacklevel+30 weapon="warhammer" elseif money < 50 then print("Not enough money!") end end--End of store elseif store == "n" then print("Quit?") quit = io.read() if quit == "y" then print("Draw!") break elseif quit == "n" then end end end until enemyhealth <= 0 or health<= 0 if health<= 0 then print("You have lost") elseif enemyhealth<=0 then print("You have won!") end
f3f42aa55440b755a5cdb6051546c654247531dd
[ "Lua" ]
1
Lua
singofwalls/simple-text-arena
c3b834755670ede4cde3501916dc1bca9ecdf038
0198ad4390587cfe495e5c23b6bc8cace530b024
refs/heads/master
<repo_name>NikiSchlifke/javascript_niki_schlifke-codereview_week02_redo<file_sep>/README.md # javascript_niki_schlifke-codereview_week02_redo ## Usage The game asks you 2 times for the player names, first the right one, then the left ount Push the roll button on each side and compare the results. If you'd like to measure your luck again press the New Game Button in the middle. Good Luck!1 ## Breakpoints The game has three screen modes Landscape, Portrait and Desktop. ## Javascript There is one main javascript file which is mostly independent of the document. The dom specifc ones are kept mostly inline. ## SCSS You need to run sass from the main directory with: ``` sass --watch scss:style ``` to generate a new main.css file that is included in index.html <file_sep>/js/game.js // game.js /** * Roll a dice with a number of faces. * @param {Number} * @return {Number} */ function diceRoll(faces) { return Math.round(1 + Math.random() * (faces - 1)); } /** * Roll three dice with the same number of faces. * @param {Number} * @return {Number} */ function threeDiceRoll(faces) { return [diceRoll(faces), diceRoll(faces), diceRoll(faces)]; } /** * Fill the results of a dice roll into an array of dom objects innerHTML. * @param {array} * @param {array} */ function fillRoll(results, container) { for (i = 0; i < container.length; i++) { container[i].innerHTML = results[i]; } } /** * Fill a given score into a dom object's innerHTML. * @param {number} * @param {symbol} */ function fillScore(score, container) { container.innerHTML = score; } /** * Using the reduce array method with a anonymous function to calculate an array's sum. * @param {array} * @return {number} */ function sumArray(values) { return values.reduce(function(former, latter) { return former + latter; }); } /** * Generate a roll and place it into the given dom. * Is called by the roll buttons. * @param {array} * @return {number} */ function playerRoll(dice_doms) { var results = threeDiceRoll(6); fillRoll(results, dice_doms); // Leaving in the "easy" way to get the result for brevity. // return results[0] + results[1] + results[2]; return sumArray(results); } function nextPlayer(button1, button2) { button1.disabled = true; if (hasBeenRolled) { button2.disabled = false; } } /** * Ask a players name and store it into the given dom object. * Return the players name for later use. * @param {symbol} * @param {number} * @return {string} */ function promptPlayer(name_dom, player_id) { var name = prompt("Please enter Player" + player_id + "'s Name: "); name_dom.textContent = name; return name; } /** * Generates a random number beteen 0 and 255 * @return {Number} */ function random255() { return Math.floor(Math.random() * 255); } /** * Generates a random 8 bit hex string. * @return {string} */ function randomHex() { return (random255()).toString(16); } /** * Generates a random html color hex string * @return {string} */ function randomColor() { return '#' + randomHex() + randomHex() + randomHex(); } /** * Use the DOMContentReloaded Event listener to initialize the game when the page is loaded. */ document.addEventListener("DOMContentLoaded", function() { var title = ''; title += promptPlayer(document.getElementById('player1--name'), 1); title += ' vs '; title += promptPlayer(document.getElementById('player2--name'), 2); document.title = title; document.body.style.backgroundColor = randomColor(); // Global variable for rolling state. hasBeenRolled = false; });
729cfcd1bba30179c55caad40a6db9d07e46324e
[ "Markdown", "JavaScript" ]
2
Markdown
NikiSchlifke/javascript_niki_schlifke-codereview_week02_redo
93a861629ac547ba2c48941bffb1226209024f6b
71418c1fcfc4fee197ed8966c9da572cb00ad978
refs/heads/master
<file_sep> public class Demo6 { public static void main(String[] args) { System.out.println("Hello World£¡Â½»Ô¶«"); } } <file_sep>import java.awt.BorderLayout; import java.awt.FileDialog; import java.awt.Font; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import frameUtil.FrameTools; public class NotePad { JFrame frame=new JFrame("记事本"); JMenuBar bar=new JMenuBar(); JMenu fileMenu=new JMenu("文件"); JMenu editMenu=new JMenu("编辑"); JMenu swichMenu=new JMenu("最近文件"); JMenuItem openMenu=new JMenuItem("打开"); JMenuItem saveMenu=new JMenuItem("保存"); JMenuItem exitMenu=new JMenuItem("退出"); JMenuItem encryptMenu=new JMenuItem("加密"); JMenuItem decodeMenu=new JMenuItem("解密"); JMenuItem fileMenu1=new JMenuItem(""); JMenuItem fileMenu2=new JMenuItem(""); JMenuItem fileMenu3=new JMenuItem(""); TextArea area=new TextArea(20,10); public void initNotepad(){ Font x=new Font("lhd", 1, 15); area.setFont(x); swichMenu.add(fileMenu1); swichMenu.add(fileMenu2); swichMenu.add(fileMenu3); fileMenu.add(swichMenu); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); openMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { FileDialog fileDialog=new FileDialog(frame,"打开",FileDialog.LOAD); fileDialog.setVisible(true); String path=fileDialog.getDirectory(); String fileName=fileDialog.getFile(); String sourcePath=path+"\\"+fileName; open(sourcePath); setSwichMenu(sourcePath); } }); fileMenu1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { open(fileMenu1.getText()); } }); fileMenu2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { open(fileMenu2.getText()); } }); fileMenu3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { open(fileMenu3.getText()); } }); saveMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { FileDialog fileDialog=new FileDialog(frame,"另存为",FileDialog.SAVE); fileDialog.setVisible(true); String path=fileDialog.getDirectory(); String fileName=fileDialog.getFile(); FileOutputStream fileOutputStream=new FileOutputStream(new File(path,fileName)); String content=area.getText(); content=content.replaceAll("\n", "\r\n"); fileOutputStream.write(content.getBytes()); fileOutputStream.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); exitMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //to be CONTINUED } }); editMenu.add(encryptMenu); editMenu.add(decodeMenu); encryptMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { encrypt(); } }); decodeMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { encrypt(); } }); bar.add(fileMenu); bar.add(editMenu); frame.add(bar,BorderLayout.NORTH); frame.add(area); FrameTools.initFrame(frame, 500, 400); } public void encrypt(){ char[] buf=area.getText().toCharArray(); for(int i=0;i<buf.length;i++){ int a=(int)buf[i]; a=a^3; buf[i]=(char)a; } area.setText(String.valueOf(buf)); } public void open(String sourcePath){ try { area.setText(null); BufferedReader bufferedReader=new BufferedReader(new FileReader(new File(sourcePath))); String line=null; while((line=bufferedReader.readLine())!=null){ area.setText(area.getText()+line+"\r\n"); } bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean flag1=false; static boolean flag2=false; public void setSwichMenu(String sourcePath){ if(fileMenu1.getText().equals("")||flag1){ fileMenu1.setText(sourcePath); flag1=false; flag2=true; }else if(fileMenu2.getText().equals("")||flag2){ fileMenu2.setText(sourcePath); flag2=false; }else{ fileMenu3.setText(sourcePath); flag1=true; } } public static void main(String[] args) { new NotePad().initNotepad(); } } <file_sep># notePad java 记事本
107d55f45435544217ab4cd6a545cf45d644c723
[ "Markdown", "Java" ]
3
Java
LHD2018/notePad
5281feef6e7e30d87906470838a4d3b69ef85996
3fd34250379802080028c226abe5d6bcaba89459
refs/heads/master
<file_sep>Android XML Coder Plugin ============================================= This plugin help you to edit xml in your Android project. ## Remove current tag ![remove_tag](https://raw.githubusercontent.com/tommykw/android-xml-coder-plugin/master/captures/remove_tag.gif) <file_sep>buildscript { ext.kotlin_version = '1.0.6' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } plugins { id "org.jetbrains.intellij" version "0.1.10" } apply plugin: 'org.jetbrains.intellij' apply plugin: 'kotlin' sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 intellij { version '15.0.4' plugins 'android' pluginName 'Android XML Coder Plugin' } group 'com.github.tommykw.android-xml-coder-plugin' version '0.0.1' repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" testCompile 'junit:junit:4.12' } task wrapper(type: Wrapper) { gradleVersion = '2.5' }<file_sep>import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.xml.XmlFile class RemoveTagIntention : IntentionAction { override fun getFamilyName() = text override fun getText() = "Remove current tag" override fun startInWriteAction() = true override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { return file is XmlFile } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val offset = editor?.caretModel?.offset ?: return val psiElement = file?.findReferenceAt(offset) ?: return psiElement.element.delete() } }
2277c706dd5b61407e93a93c8d334cfb17fbe0bb
[ "Markdown", "Kotlin", "Gradle" ]
3
Markdown
tommykw/android-xml-coder-plugin
aa755eb74de9ee4c4efdd99fe0747185e4e573c3
0ea4a0c1a4c647c768f37c8a3efe6573560db763
refs/heads/master
<repo_name>manfredsteyer/2019_09_06<file_sep>/projects/flight-app/src/app/flight-booking/+state/flight-booking.effects.ts import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { FlightService } from '@flight-workspace/flight-api'; import { loadFlights, flightsLoaded } from './flight-booking.actions'; import { switchMap, map } from 'rxjs/operators'; @Injectable() export class FlightBookingEffects { constructor( private actions$: Actions, private flightService: FlightService) {} loadFlights$ = createEffect(() => this.actions$.pipe( ofType(loadFlights), switchMap(a => this.flightService.find(a.from, a.to, a.urgent)), map(flights => flightsLoaded({flights})) )); // loadFlightBookings$ = createEffect(() => this.actions$.pipe( // ofType(FlightBookingActions.flightsLoaded), // /** An EMPTY observable only emits completion. Replace with your own observable API request */ // concatMap(() => EMPTY) // )); } <file_sep>/projects/flight-app/src/app/flight-booking/+state/flight.facade.ts import { FlightService } from "@flight-workspace/flight-api"; import { Store } from "@ngrx/store"; import { FlightBookingAppState } from "./flight-booking.reducer"; import { Injectable } from "@angular/core"; import { flightsLoaded, updateFlight, loadFlights } from "./flight-booking.actions"; import { first } from "rxjs/operators"; import { BehaviorSubject } from "rxjs"; @Injectable({ providedIn: 'root' }) export class FlightBookingFacade { flights$ = this.store.select(a => a.flightBooking.flights); constructor(private flightService: FlightService, private store: Store<FlightBookingAppState>) { } // find(from: string, to: string, urgent: boolean): void { // this.flightService // .find(from, to, urgent) // .subscribe( // flights => { // this.store.dispatch(flightsLoaded({flights})); // } // ) // } find(from: string, to: string, urgent: boolean): void { this.store.dispatch(loadFlights({from, to, urgent})); } delay(): void { this.flights$.pipe(first()).subscribe(flights => { const f = flights[0]; const flight = {...f, date: new Date().toISOString()}; this.store.dispatch(updateFlight({flight})); }); } }<file_sep>/projects/flight-app/src/app/lookahead/flight-lookahead.component.ts import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Observable, interval, combineLatest, of } from 'rxjs'; import { Component, OnInit } from '@angular/core'; import { FormControl } from "@angular/forms"; import { debounceTime, switchMap, tap, startWith, map, distinctUntilChanged, filter, shareReplay, delay, mergeMap, concatMap, exhaustMap, catchError } from 'rxjs/operators'; import { _do } from "rxjs/operator/do"; import { Flight } from '@flight-workspace/flight-api'; @Component({ selector: 'flight-lookahead', templateUrl: './flight-lookahead.component.html' }) export class FlightLookaheadComponent implements OnInit { constructor(private http: HttpClient) { } control: FormControl; flights$: Observable<Flight[]>; loading: boolean = false; online$: Observable<boolean>; online: boolean; ngOnInit() { this.control = new FormControl(); this.online$ = interval(2000).pipe( startWith(0), map(_ => true), distinctUntilChanged(), shareReplay(1), // // Nebeneffekt :-( // tap(value => this.online = value) ); const debouncedInput$ = this.control.valueChanges.pipe(debounceTime(300)); this.flights$ = combineLatest(debouncedInput$, this.online$).pipe( filter( ([_, online]) => online), tap(_ => this.loading = true), switchMap( ([input, _]) => this.load(input)), tap(_ => this.loading = false), ); /* this ; */ } load(from: string) { let url = "http://www.angular.at/api/flight"; let params = new HttpParams() .set('from', from); let headers = new HttpHeaders() .set('Accept', 'application/json'); return this.http.get<Flight[]>(url, {params, headers}).pipe( catchError(_ => of([])) ) }; }
51bc4928c5ed4a761270d096e8dee94ebd8e4a0e
[ "TypeScript" ]
3
TypeScript
manfredsteyer/2019_09_06
6ea3aaad598a9c5e382562169428c681a6267182
a22820be02a212198781e18762b9b965ea5205cc
refs/heads/master
<file_sep>function password(state = { }, { type, payload }) { switch(type) { case "CHANGE_PASSWORD_SUCCESS": case "CHANGE_PASSWORD_FAILURE": return state default: return state } } export default password <file_sep>import { createStore, applyMiddleware } from "redux" import thunkMiddleware from "redux-thunk" import createLogger from "redux-logger" import { browserHistory } from "react-router" import { routerMiddleware } from "react-router-redux" import app from "../reducers" export default createStore( app, applyMiddleware( thunkMiddleware, routerMiddleware(browserHistory), createLogger() ) ) <file_sep>import React, { PropTypes, Component } from "react" import { connect } from "react-redux" import { bindActionCreators } from "redux" import { Link } from "react-router" import { replace } from "react-router-redux" import Header from "../components/auth/Header" import Footer from "../components/auth/Footer" import getVerifyEmail from "../actions/getVerifyEmail" const initCount = 60 class SignupSuccess extends Component { constructor() { super() this.state = { leftCount: initCount, canResend: true, _fn: null } } componentWillMount() { let { replace } = this.props if (this.props.isAuthenticated) { // NOTE // 这里的`return`是必须的, // 不然存在既满足`isAuthenticated`为真,同时又满足`!email`为真的时候 return replace("/") } if (!this.props.email) { replace("/signup") } } componentWillUnmount() { clearInterval(this.state._fn) } handleResendClick() { this.state._fn = setInterval(() => { this.setState( this.state.leftCount === 0 ? { leftCount: initCount, canResend: true } : { leftCount: --this.state.leftCount, canResend: false } ) }, 1000) this.props.getVerifyEmail({ email: this.props.email }) } render() { return ( <div className="container-fluid"> <div className="row"> <div className="col-sm-offset-2 col-sm-8 col-lg-offset-3 col-lg-6"> <Header pathname={this.props.location.pathname} /> <div> <h1 className="text-center text-success">很好!</h1> <div className="alert alert-success">我们已经往你的邮箱<u>{this.props.email}</u>发送了激活邮件,下一步去<em>激活你的帐号</em>。</div> {this.state.canResend ? ( <p> 如果长时间没有收到邮件,请 {this.props.email ? ( <button className="btn btn-primary" type="button" onClick={() => this.handleResendClick()} disabled={!this.state.canResend} > 再次发送激活邮件 </button> ) : ( <Link to="/signup">重新注册</Link> )} </p> ) : ( <p><span className="text-success">邮件已发送</span>,<span className="text-muted">需要等待{this.state.leftCount}秒之后才可以继续重发。</span></p> )} <hr /> <div className="text-center"><Link to="/signin">返回主页</Link></div> </div> <Footer /> </div> </div> </div> ) } } export default connect( state => ({ isAuthenticated: state.signin.isAuthenticated, email: state.signup.email }), dispatch => bindActionCreators({ getVerifyEmail, replace }, dispatch) )(SignupSuccess) <file_sep>function profile(state = { profile: { // FIXME email: "...", nickname: "", join_ip: "...", join_time: "...", last_login: "..." } }, { type, payload }) { switch(type) { case "GET_PROFILE_SUCCESS": case "SAVE_DISPLAY_NAME_SUCCESS": return Object.assign({}, state, { profile: Object.assign({}, state.profile, payload.profile) }) case "GET_PROFILE_FAILURE": case "SAVE_DISPLAY_NAME_FAILURE": return state default: return state } } export default profile <file_sep>import React, { Component } from "react" export default class Alert extends Component { constructor(props) { super(props) this.state = { isShown: props.isShown } } componentWillReceiveProps(nextProps) { if (nextProps !== this.props) { this.setState({ isShown: nextProps.isShown }) } } dismiss() { this.setState({ isShown: false }) } render() { let classNames = `alert alert-${this.props.status}` return this.state.isShown ? ( <div className={classNames}> <button className="close" type="button" onClick={() => this.dismiss()}>&times;</button> <div dangerouslySetInnerHTML={{ __html: this.props.children }} /> </div> ) : null } } <file_sep>import webpack from "webpack" import path from "path" import ExtractTextPlugin from "extract-text-webpack-plugin" export default { entry: { app: path.join(__dirname, "src"), vendor: [ "axios", "babel-polyfill", "cookie", "react", "react-dom", "react-redux", "react-router", "react-router-redux", "redux", "redux-logger", "redux-thunk" ] }, output: { path: path.join(__dirname, "build"), filename: "bundle.js" }, module: { loaders: [ { test: /\.js?$/, exclude: /node_modules/, loader: "babel?presets[]=es2015&presets[]=react" }, { test: /\.scss$/, loader: ExtractTextPlugin.extract("css?sourceMap!sass?sourceMap") } ] }, plugins: process.env.NODE_ENV === "production" ? [ new webpack.DefinePlugin({ "process.env": { "NODE_ENV": JSON.stringify("production") } }), new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js"), new webpack.optimize.UglifyJsPlugin({ compress: { warning: false } }), new ExtractTextPlugin("bundle.css") ] : [ new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js"), new ExtractTextPlugin("bundle.css") ], sassLoader: { includePaths: [ "./src/styles" ] } } <file_sep>import cookie from "cookie" function signin(state = { isAuthenticated: !!cookie.parse(document.cookie)["_at_"] }, { type, payload }) { switch(type) { case "SIGNIN_SUCCESS": // 登录 case "LOGOUT_SUCCESS": // 注销 return Object.assign({}, state, { isAuthenticated: payload.isAuthenticated }) default: return state } } export default signin <file_sep>import React from "react" const Header = () => <div className="page-header"> <h1 className="text-center">BlockMeta</h1> </div> export default Header <file_sep>import cookie from "cookie" import axios from "../middleware/api" import getCaptcha from "./getCaptcha" import { replace } from "react-router-redux" import * as errorMsg from "./errorMsg" const signinRequest = { type: "SIGNIN_REQUEST" } const signinSuccess = { type: "SIGNIN_SUCCESS", payload: { isAuthenticated: true } } export default function signin(data) { return (dispatch) => { dispatch(errorMsg.reset) dispatch(signinRequest) axios.get(`/auth/token?code=${data.captcha}`, { headers: { "Authorization": `Basic ${btoa(data.email + ":" + data.password)}` } }) .then(res => { const options = { maxAge: data.remember ? 30*24*60*60 : res.data.expire } document.cookie = cookie.serialize("_at_", res.data.access_token, options) document.cookie = cookie.serialize("_rt_", res.data.refresh_token, options) // FIXME axios.defaults.headers.common["Authorization"] = `Basic ${btoa(":" + cookie.parse(document.cookie)["_at_"])}` dispatch(signinSuccess) dispatch(replace("/")) }, err => { const errors = { "1010": "验证码错误,请输入验证码。", "1011": "等等,需要输入验证码。", "1012": "邮箱或密码不正确。", // 验证码正确,但邮箱或密码不正确。 "1003": "邮箱或密码不正确。", "1006": "你的邮箱还未激活。" } if ([1010, 1011, 1012].indexOf(err.data.code) >= 0) { dispatch(getCaptcha()) } dispatch(errorMsg.display({ status: "danger", message: errors[err.data.code] })) }) } } <file_sep>import express from "express" const html = ` <!doctype html> <html> <head> <meta charset="utf-8"> <title>BlockMeta</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"> <link href="/bundle.css" rel="stylesheet"> <style>body{font-size:18px;font-family:LatoLatin-Light,Helvetica Neue,Helvetica,sans-serif;}</style> </head> <body> <div id="root"></div> <script src="/vendor.js"></script> <script src="/bundle.js"></script> </body> </html> ` const app = express() app.use(express.static(`${__dirname}/build`)) app.get("*", (req, res) => { res.send(html.replace(/\n/g, "").replace(/\>[\s]*\</g, "><")) }) const PORT = 2222 app.listen(PORT, () => { console.log(`${new Date}: Now servering at http://localhost:${PORT}`) }) <file_sep>import axios from "../middleware/api" const getProfileRequest = { type: "GET_PROFILE_REQUEST" } function getProfileSuccess(data) { return { type: "GET_PROFILE_SUCCESS", payload: { profile: data.profile } } } function getProfileFailure() { return { type: "GET_PROFILE_FAILURE", payload: { } } } export default function getProfile() { return (dispatch) => { axios.get("/users/me") .then(res => { dispatch(getProfileSuccess({ profile: res.data })) }, err => { dispatch(getProfileFailure()) }) } } <file_sep>import React from "react" import { Link } from "react-router" const styles = { position: "fixed", top: 50, left: 0, bottom: 0, width: 200, height: "100%", backgroundColor: "#1c2b36" } const Sidebar = (props) => <div className="sidebar" style={styles}> <ul className="nav nav-pills nav-stacked text-capitalize"> <li><a href="javascript:;">资产</a></li> <li><a href="javascript:;">算力</a></li> </ul> </div> export default Sidebar <file_sep>import axios from "axios" import { replace } from "react-router-redux" import cookie from "cookie" const verifyRequest = { type: "VERIFY_REQUEST" } const verifySuccess = { type: "VERIFY_SUCCESS", payload: { isVerifying: false, isVerified: true } } function verifyFailure() { return { type: "VERIFY_FAILURE", payload: { isVerifying: false } } } export default function verify(data) { return (dispatch) => { dispatch(verifyRequest) axios.put("/auth/activate", data) .then(res => { dispatch(verifySuccess) document.cookie = cookie.serialize("_em_", "") // 验证成功之后, 清除`cookie`中的`_em_`, 即阻止用户继续访问`/signup-success`页面 const timeoutId = setTimeout(() => { dispatch(replace("/signin")) clearTimeout(timeoutId) }, 15000) }, err => { console.warn(err) dispatch(verifyFailure()) }) } } <file_sep>import React from "react" import { connect } from "react-redux" import { bindActionCreators } from "redux" import signup from "../actions/signup" import Alert from "../components/Alert" import { REG_EMAIL, REG_PASSWORD } from "../constants" function handleBlur(e, pattern) { const el = e.target, value = el.value.trim(), parent = el.parentElement, sibling = el.nextSibling if (pattern.test(value)) { sibling.classList.add("hide") return parent.classList.remove("has-error") } sibling.classList.remove("hide") parent.classList.add("has-error") } const Signup = (props) => { let _email, _password, _terms return ( <form onSubmit={(e) => { e.preventDefault() if (REG_EMAIL.test(_email.value.trim()) && REG_PASSWORD.test(_password.value.trim())) { return props.signup({ isChecked: _terms.checked, data: { email: _email.value.trim(), password: _password.value.trim() } }) } // FIXME: 手动模拟人为输入动作 _email.focus(); _email.blur() _password.focus(); _password.blur() }}> <Alert status={props.error.status} isShown={props.error.message}>{props.error.message}</Alert> <div className="form-group"> <label className="control-label" htmlFor="field__email">邮箱</label> <input className="form-control input-lg" id="field__email" type="text" ref={node => _email = node} onBlur={(e) => handleBlur(e, REG_EMAIL)} /> <span className="help-block hide">必须提供一个有效的邮箱。</span> </div> <div className="form-group"> <label className="control-label" htmlFor="field__password">密码</label> <input className="form-control input-lg" id="field__password" type="password" ref={node => _password = node} onBlur={(e) => handleBlur(e, REG_PASSWORD)} /> <p className="help-block">密码必须匹配<code>{"/^[a-zA-Z0-9!@#$%^&*]{6,16}$/"}</code>。</p> </div> <div className="checkbox"> <label> <input type="checkbox" ref={node => _terms = node} /> 我同意区块元的<a href="" target="_blank">用户协议</a> </label> </div> <button className="btn btn-success btn-lg btn-block" type="submit">注册</button> </form> ) } export default connect( state => ({ error: state.errorMsg.error }), dispatch => bindActionCreators({ signup }, dispatch) )(Signup) <file_sep>import React, { PropTypes, Component } from "react" import { connect } from "react-redux" import { replace } from "react-router-redux" import { Link } from "react-router" import Header from "../components/auth/Header" import Footer from "../components/auth/Footer" class Auth extends Component { componentWillMount() { if (this.props.isAuthenticated) { this.props.dispatch(replace("/")) } } render() { const pathname = this.props.location.pathname return ( <div className="container"> <div className="row"> <div className="col-sm-offset-2 col-sm-8 col-lg-offset-3 col-lg-6"> <Header pathname={this.props.location.pathname} /> {/\/sign(in|up)/.test(pathname) ? ( <ul className="nav nav-tabs nav-justified" style={{ marginBottom: 20 }}> <li className={pathname === "/signin" ? "active" : ""}><Link to="/signin">登录</Link></li> <li className={pathname === "/signup" ? "active" : ""}><Link to="/signup">注册</Link></li> </ul> ) : null} {this.props.children} <Footer /> </div> </div> </div> ) } } export default connect( state => ({ isAuthenticated: state.signin.isAuthenticated }) )(Auth) <file_sep>export default function forgetPassword(state = { isSubmitted: false }, { type, payload }) { if (type === "FORGET_PASSWORD_SUCCESS") { return Object.assign({}, state, { isSubmitted: payload.isSubmitted }) } return state } <file_sep>import React from "react" import { Link } from "react-router" const styles = { position: "fixed", top: 0, left: 0, right: 0, width: "100%", marginBottom: 0 } const Navbar = (props) => <div className="navbar navbar-default navbar-fixed-top" style={styles}> <div className="container-fluid"> <div className="navbar-header"> <Link to="/" className="navbar-brand">BlockMeta<sup>&trade;</sup></Link> </div> <div className="collapse navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <li><a href="javascript:;">通知<sup className="badge">4</sup></a></li> <li className={/account/.test(props.location.pathname) && "active"}> <Link to="/account"> {/account/.test(props.location.pathname) ? <span>&darr;</span> : <span>&rarr;</span>} <em><u>{props.profile.nickname || props.profile.email}</u></em> </Link> </li> <li><a href="javascript:;" onClick={() => props.logout()}>注销</a></li> </ul> </div> </div> </div> export default Navbar <file_sep>import React, { Component } from "react" import { bindActionCreators } from "redux" import { connect } from "react-redux" import logout from "../actions/logout" import getProfile from "../actions/getProfile" import Navbar from "../components/Navbar" import Sidebar from "../components/Sidebar" const styles = { marginLeft: 200 } class Dashboard extends Component { componentWillMount() { this.props.getProfile() } render() { return ( <div style={{ paddingTop: 50 }}> <Navbar {...this.props} /> <Sidebar {...this.props} /> <div className="main" style={styles}> <div style={{ padding: 20 }}> <div className="container-fluid"> {this.props.children} </div> </div> </div> </div> ) } } export default connect( state => ({ profile: state.profile.profile }), dispatch => bindActionCreators({ logout, getProfile }, dispatch) )(Dashboard) <file_sep>import axios from "../middleware/api" const changePasswordRequest = { type: "CHANGE_PASSWORD_REQUEST" } function changePasswordSuccess() { return { type: "CHANGE_PASSWORD_SUCCESS", payload: { } } } function changePasswordFailure() { return { type: "CHANGE_PASSWORD_FAILURE", payload: { } } } export default function changePassword(data) { return (dispatch) => { axios.put("/users/me/reset-password", data) .then(res => { dispatch(changePasswordSuccess()) }, err => { dispatch(changePasswordFailure()) }) } } <file_sep>export default function resetPassword(state = { }, { type, payload }) { if (type === "RESET_PASSWORD_SUCCESS") { return Object.assign({}, state, { isUpdated: payload.isUpdated }) } return state } <file_sep>import cookie from "cookie" function signup(state = { email: atob(cookie.parse(document.cookie)["_em_"]||"") }, { type, payload }) { switch(type) { case "SIGNUP_SUCCESS": return Object.assign({}, state, { email: payload.email }) default: return state } } export default signup <file_sep>import React from "react" import { bindActionCreators } from "redux" import { connect } from "react-redux" import { push } from "react-router-redux" import changePassword from "../actions/changePassword" const Password = (props) => { let p1, p2, p3 return ( <div> <ul className="breadcrumb"> <li><a href="javascript:;" onClick={() => props.push("/account")}>back</a></li> </ul> <div className="page-header"> <h1>Password</h1> </div> <div className="container-fluid"> <div className="row"> <div className="col-sm-offset-2 col-sm-8 col-lg-offset-3 col-lg-6"> <form onSubmit={(e) => { e.preventDefault() props.changePassword({ old_password: p3.value.trim(), new_password_1: p1.value.trim(), new_password_2: p2.value.trim() }) p1.value = p2.value = p3.value = "" }}> <div className="form-group"> <label htmlFor="field__p3">Old password</label> <input className="form-control input-lg" type="password" ref={node => p3 = node} /> <p className="help-block">Please provide your current password to continue.</p> </div> <hr /> <div className="form-group"> <label htmlFor="field__p1">New password</label> <input className="form-control input-lg" id="field__p1" type="password" ref={node => p1 = node} /> <p className="help-block">Password must matches <code>{"/^[a-zA-Z0-9!@#$%^&*]{6,16}$/"}</code></p> </div> <div className="form-group"> <label htmlFor="field__p2">Confirm new password</label> <input className="form-control input-lg" id="field__p2" type="password" ref={node => p2 = node} /> </div> <button className="btn btn-primary btn-lg" type="submit">Save new password</button> </form> </div> </div> </div> </div> ) } export default connect( null, dispatch => bindActionCreators({ changePassword, push }, dispatch) )(Password) <file_sep>import axios from "../middleware/api" import * as errorMsg from "./errorMsg" const resetPasswordSuccess = { type: "RESET_PASSWORD_SUCCESS", payload: { isUpdated: true } } export default function resetPassword(data) { return (dispatch) => { dispatch(errorMsg.reset) axios.put("/users/me/forget-password", data) .then(res => { dispatch(resetPasswordSuccess) }, err => { const errors = { "1004": "请检查你的新密码,确保是有效的。", "1005": "链接不合法或已过期。" } dispatch(errorMsg.display({ status: "danger", message: errors[err.data.code] })) }) } } <file_sep>import axios from "axios" import cookie from "cookie" import { push } from "react-router-redux" import * as errorMsg from "./errorMsg" const signupRequest = { type: "SIGNUP_REQUEST" } function signupSuccess(data) { return { type: "SIGNUP_SUCCESS", payload: { email: data.email } } } export default function signup(data) { return (dispatch) => { if (!data.isChecked) { return dispatch(errorMsg.display({ status: "warning", message: "你必须同意<a href='' target='_blank'>用户协议</a>才能注册。" })) } dispatch(errorMsg.reset) dispatch(signupRequest) axios.post("/users", data.data) .then(res => { document.cookie = cookie.serialize("_em_", btoa(data.data.email), { maxAge: 10*60 // 10 minutes }) dispatch(signupSuccess({ email: data.data.email })) dispatch(push("/signup-success")) }, err => { const errors = { "1004": "邮箱或密码不正确。", "1007": "该邮箱已经注册,请直接登录。" } dispatch(errorMsg.display({ status: "danger", message: errors[err.data.code] })) }) } } <file_sep>import React from "react" import { connect } from "react-redux" const IndexPage = (props) => <div> <div className="page-header"> <h1>lorem ipsum</h1> </div> <blockquote> <p>Lorem ipsum dolor sit amet, mei adhuc scripta offendit at. Mel elitr animal explicari ea, ad modus impetus consulatu eum. Ne tale graeco cotidieque has. Mel ex gubergren adipiscing, cum vivendum voluptaria accommodare no. Sed facer moderatius id, cu vel enim elit.</p> <footer>Someone famous in <cite>Source Title</cite></footer> </blockquote> </div> export default connect( )(IndexPage) <file_sep>import React, { PropTypes, Component } from "react" import { bindActionCreators } from "redux" import { connect } from "react-redux" import { Link } from "react-router" import verify from "../actions/verify" class Verification extends Component { componentWillMount() { if (this.props.isAuthenticated) { return this.context.router.replace("/") } this.props.verify({ code: this.props.location.query.code }) } render() { return ( <div className="text-center"> <div><Link to="/">BlockMeta</Link></div> <div className="page-header"> {this.props.isVerifying ? ( <div className="text-info"> <h1>稍等片刻</h1> <p>我们正在验证你的邮箱...</p> </div> ) : this.props.isVerified ? ( <div className="text-success"> <h1>注册完成!</h1> <p>你的邮箱已经被验证。 <br />该页面会在10秒种之后跳转。</p> </div> ) : ( <div className="text-warning"> <h1>注册失败!</h1> <p>你的邮箱无法验证</p> </div> )} </div> <div>&copy; 2016 <strong>BlockMeta</strong></div> </div> ) } } Verification.contextTypes = { router: PropTypes.object.isRequired } export default connect( state => ({ isAuthenticated: state.signin.isAuthenticated, isVerifying: state.verify.isVerifying, isVerified: state.verify.isVerified }), dispatch => bindActionCreators({ verify }, dispatch) )(Verification) <file_sep>import axios from "../middleware/api" import * as errorMsg from "./errorMsg" const forgetPasswordRequest = { type: "FORGET_PASSWORD_REQUEST" } const forgetPasswordSuccess = { type: "FORGET_PASSWORD_SUCCESS", payload: { isSubmitted: true } } export default function forgetPassword(data) { return (dispatch) => { dispatch(errorMsg.reset) axios.post("/users/me/forget-password", data) .then(res => { dispatch(forgetPasswordSuccess) }, err => { const errors = { "1004": "邮箱不正确。", "1013": "该邮箱未注册。" } dispatch(errorMsg.display({ status: "danger", message: errors[err.data.code] })) }) } } <file_sep>import { combineReducers } from "redux" import { routerReducer as routing } from "react-router-redux" import errorMsg from "./errorMsg" import captcha from "./captcha" import signin from "./signin" import forgetPassword from "./forgetPassword" import resetPassword from "./resetPassword" import signup from "./signup" import verify from "./verify" import profile from "./profile" import password from "./password" const app = combineReducers({ routing, errorMsg, signin, captcha, forgetPassword, resetPassword, signup, verify, profile, password }) export default app <file_sep>import React, { Component } from "react" import { connect } from "react-redux" import { bindActionCreators } from "redux" import saveDisplayName from "../actions/saveDisplayName" import { Link } from "react-router" import moment from "moment" moment.locale("zh-cn") class Account extends Component { constructor(props) { super(props) this.state = { nickname: this.props.profile.nickname } } componentWillReceiveProps(nextProps) { if (nextProps !== this.props) { this.setState({ nickname: nextProps.profile.nickname }) } } render() { let { profile } = this.props return ( <div> <div className="page-header"> <h1>账号</h1> </div> <div className="container-fluid"> <div className="row"> <div className="col-sm-offset-2 col-sm-8 col-lg-offset-3 col-lg-6"> <form onSubmit={(e) => { e.preventDefault() this.props.saveDisplayName({ nickname: this.state.nickname.trim() }) }}> <div className="form-group form-group-lg"> <label>邮箱</label> <p className="form-control-static"> {profile.email} {!/\.{3}/.test(profile.email) && ( <span style={{ fontSize: 14, marginLeft: 10 }}> <Link to="/account/password">更改密码</Link> </span>)} </p> <p className="help-block"><small>注册邮箱无法更改。</small></p> </div> <div className="form-group form-group-lg"> <label htmlFor="field__nickname">昵称</label> <input className="form-control input-lg" id="field__nickname" type="text" value={this.state.nickname} placeholder="e.g. <NAME>" onChange={(e) => { this.setState({ nickname: e.target.value }) }} /> <p className="help-block">给自己起一个昵称。</p> </div> <button className="btn btn-primary btn-lg" type="submit">保存昵称</button> </form> <div className="well" style={{ marginTop: 20 }}> <h3 className="h3">账号信息</h3> <dl style={{ marginBottom: 0 }}> <dt>注册IP</dt> <dd>{profile.join_ip} (Taiwan)</dd> <dt>注册时间</dt> <dd>{profile.join_time}</dd> <dt className="text-info">最后登录</dt> <dd className="text-info">{profile.last_login}</dd> </dl> </div> </div> </div> </div> </div> ) } } export default connect( state => ({ profile: state.profile.profile }), dispatch => bindActionCreators({ saveDisplayName }, dispatch) )(Account) <file_sep>import React from "react" import { connect } from "react-redux" import "./App.scss" const App = (props) => <div> {props.children} </div> export default connect( )(App) <file_sep>export const BASE_URL = "http://172.16.17.32:30000/api" export const REG_EMAIL = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i export const REG_PASSWORD = /^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d).*$/ <file_sep>export const reset = { type: "RESET_ERROR_MESSAGE", payload: { error: { status: "default", message: "" } } } export function display(error) { return { type: "DISPLAY_ERROR_MESSAGE", payload: { error } } } <file_sep>const initState = { error: { status: "default", message: "" } } export default function errorMsg(state = initState, { type, payload }) { switch(type) { // 当router更改的时候,Alert也应该重置,避免夸组件之间出现。 case "@@router/LOCATION_CHANGE": return Object.assign({}, state, { error: initState.error }) case "DISPLAY_ERROR_MESSAGE": case "RESET_ERROR_MESSAGE": return Object.assign({}, state, { error: payload.error }) default: return state } } <file_sep>import axios from "axios" const getVerifyEmailRequest = { type: "GET_VERIFY_REQUEST" } const getVerifyEmailSuccess = { type: "GET_VERIFY_SUCCESS" } function getVerifyEmailFailure() { return { type: "GET_VERIFY_FAILURE", payload: { } } } export default function getVerifyEmail(data) { return (dispatch) => { dispatch(getVerifyEmailRequest) axios.get(`/auth/activate?email=${data.email}`) .then(res => { dispatch(getVerifyEmailSuccess) }, err => { dispatch(getVerifyEmailFailure()) }) } } <file_sep>import axios from "axios" import { BASE_URL } from "../constants" function getCaptchaRequest() { return { type: "GET_CAPTCHA_REQUEST", payload: { isFetchingCaptcha: true } } } function getCaptchaSuccess(data) { return { type: "GET_CAPTCHA_SUCCESS", payload: { captcha: `${BASE_URL}/${data.url.replace(/\/api\//, "")}`, isFetchingCaptcha: false } } } function getCaptchaFailure() { return { type: "GET_CAPTCHA_FAILURE", payload: { // TODO } } } export default function getCaptcha() { return (dispatch) => { dispatch(getCaptchaRequest()) axios.get("/tools/captcha") .then(res => { dispatch(getCaptchaSuccess(res.data)) }, err => { console.warn(err) dispatch(getCaptchaFailure()) }) } }
f12b447f74bdbbfa27269f4daa4a2bdb497c8ba0
[ "JavaScript" ]
35
JavaScript
8itcoin/console.blockmeta
441ca3114cdfdeb657a5fecc2b385f47bab8ea8f
1d8fe7e770b5db1a9e6971803d0bf41ccccb60fb
refs/heads/master
<repo_name>headbanging3/Team_Project1-3<file_sep>/src/main/java/com/acorn/shoopse/agency/controller/AgencyController.java package com.acorn.shoopse.agency.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.acorn.shoopse.agency.dto.AgencyDto; import com.acorn.shoopse.agency.service.AgencyService; @Controller public class AgencyController { @Autowired private AgencyService agencyService; @RequestMapping("/manager/insertformagency") public ModelAndView insertformAgency(){ ModelAndView mView = new ModelAndView(); mView.setViewName("manager/insertform_agency"); return mView; } @RequestMapping("manager/insertagency") public String insert(@ModelAttribute AgencyDto dto){ System.out.println("company 출력 :"+dto.getCompany()); agencyService.insert(dto); return "redirect:agencylist.do"; } @RequestMapping("manager/agencylist") public ModelAndView getList(){ ModelAndView mView=agencyService.getList(); mView.setViewName("manager/agency_list"); return mView; } } <file_sep>/src/main/java/com/acorn/shoopse/users/controller/UsersController.java package com.acorn.shoopse.users.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.acorn.shoopse.users.dto.UsersDto; import com.acorn.shoopse.users.service.UsersService; @Controller public class UsersController { @Autowired private UsersService usersService; // 로그인/회원가입 팝업 페이지 이동 @RequestMapping("/popup/loginresult") public ModelAndView loginresult(@ModelAttribute UsersDto dto, HttpServletRequest request){ ModelAndView mView= usersService.signin(dto, request); mView.setViewName("/popup/loginresult"); return mView; } @RequestMapping("/popup/signinform") public String signinForm(){ return "popup/signinform"; } @RequestMapping("/logout") public ModelAndView signout(HttpSession session){ session.invalidate(); ModelAndView mView=new ModelAndView(); mView.addObject("url", session.getServletContext().getContextPath()); mView.setViewName("redirect:/home.do"); return mView; } //사용자 정보 제공 동의 페이지 이동 @RequestMapping("/users/agree_info") public String agreeInfo(){ return "users/agree_info"; } //회원가입 폼 이동 @RequestMapping("/users/signup_form") public String signupForm(){ return "users/signup_form"; } //회원가입시 아이디 중복확인 @RequestMapping("/users/overlab") public ModelAndView overLab(@RequestParam String id){ ModelAndView mView=new ModelAndView(); mView=usersService.isOverlab(id); mView.setViewName("users/overlab"); return mView; } //회원가입 이후 홈 리다이렉트 @RequestMapping("/users/signup") public String signup(@ModelAttribute UsersDto dto){ usersService.usersSignup(dto); return "redirect:/home.do"; } //아이디 찾는 페이지로 이동 @RequestMapping("/users/find_id") public String findIdForm(){ return "users/find_id"; } //아이디 찾기 @RequestMapping("/users/find_id_ajax") public ModelAndView findIdAjax(@ModelAttribute UsersDto dto){ ModelAndView mView=usersService.findId(dto); mView.setViewName("users/find_id_ajax"); System.out.println("mView 리턴전"); return mView; } //비밀번호 찾기 @RequestMapping("/users/find_pwd_ajax") public ModelAndView findPwdAjax(@ModelAttribute UsersDto dto){ ModelAndView mView=usersService.findPwd(dto); mView.setViewName("users/find_pwd_ajax"); System.out.println("mView 리턴전"); return mView; } @RequestMapping("/users/info") public ModelAndView privateinfo(HttpServletRequest request){ ModelAndView mView=usersService.getData(request); mView.setViewName("users/info"); return mView; } @RequestMapping("/users/updateform") public ModelAndView privateupdateForm(HttpServletRequest request){ String id=(String)request.getSession().getAttribute("id"); ModelAndView mView=usersService.getData(request); mView.setViewName("users/updateform"); return mView; } @RequestMapping("/users/delete") public String privatedelete(@RequestParam int num, HttpServletRequest request){ usersService.delete(num, request); return "redirect:/home.do"; } @RequestMapping("/users/update") public String privateupdate(@ModelAttribute UsersDto dto){ usersService.update(dto); return "redirect:/home.do"; } } <file_sep>/src/main/java/com/acorn/shoopse/manager/service/ManagerServiceImpl.java package com.acorn.shoopse.manager.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; import com.acorn.shoopse.manager.dao.ManagerDao; import com.acorn.shoopse.manager.dto.ManagerDto; import com.acorn.shoopse.products.dto.ProductsDto; import com.acorn.shoopse.products.dto.ProductsKindDto; import com.acorn.shoopse.users.dao.UsersDao; import com.acorn.shoopse.users.dto.UsersDto; @Service public class ManagerServiceImpl implements ManagerService{ @Autowired private ManagerDao managerDao; @Override public void insert(HttpServletRequest request, UsersDao dao) { // TODO Auto-generated method stub } @Override public ModelAndView list() { List<ManagerDto> list = managerDao.getList(); ModelAndView mView = new ModelAndView(); mView.addObject("list", list); return mView; } @Override public void delete(int mem_num) { managerDao.delete(mem_num); } @Override public ModelAndView getData(int mem_num) { ModelAndView mView = new ModelAndView(); if(mem_num>=1) { ManagerDto dto = managerDao.getData(mem_num); mView.addObject("dto", dto); } return mView; } @Override public void update(ManagerDto dto) { managerDao.update(dto); } @Override public ModelAndView p_list() { List<ProductsDto> p_list= managerDao.p_list(); ModelAndView mView= new ModelAndView(); mView.addObject("list",p_list); return mView; } @Override public ModelAndView getCategory() { ModelAndView mView=new ModelAndView(); List<ProductsKindDto> categoryList=managerDao.getCategory(); mView.addObject("categoryList", categoryList); return mView; } @Override public List<ProductsKindDto> getDivision(int parent_kind_code) { List<ProductsKindDto> divisionList=managerDao.getDivision(parent_kind_code); return divisionList; } } <file_sep>/src/main/java/com/acorn/shoopse/manager/service/ManagerService.java package com.acorn.shoopse.manager.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.acorn.shoopse.manager.dto.ManagerDto; import com.acorn.shoopse.products.dto.ProductsKindDto; import com.acorn.shoopse.users.dao.UsersDao; public interface ManagerService { public void insert(HttpServletRequest request, UsersDao dao); public ModelAndView list(); public void delete(int mem_num); public ModelAndView getData(int mem_num); public void update(ManagerDto dto); public ModelAndView p_list(); public ModelAndView getCategory(); public List<ProductsKindDto> getDivision(int parent_kind_code); } <file_sep>/src/main/java/com/acorn/shoopse/users/dao/UsersDaoImpl.java package com.acorn.shoopse.users.dao; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.acorn.shoopse.users.dto.UsersDto; @Repository public class UsersDaoImpl implements UsersDao{ @Autowired private SqlSession session; @Override public void usersSignup(UsersDto dto) { session.insert("users.insertBefore",dto); session.insert("users.insert",dto); } @Override public String findId(UsersDto dto) { String id=session.selectOne("users.findId", dto); return id; } @Override public String findPwd(UsersDto dto) { String pwd=session.selectOne("users.findPwd", dto); return pwd; } @Override public String isOverlab(String id) { String resultId=session.selectOne("users.overLab",id); return resultId; } @Override public boolean isValid(UsersDto dto) { UsersDto resultDto=session.selectOne("users.isValid",dto); if(resultDto==null){ System.out.println("daoimple isvalid 넘어옴"); return false; }else{ System.out.println("daoimple isvalid else 넘어옴"); return true; } } @Override public UsersDto getData(String id) { UsersDto dto=session.selectOne("users.getData",id); return dto; } @Override public void delete(int num) { session.delete("users.delete",num); } @Override public void update(UsersDto dto) { session.update("users.update",dto); } }
30f11e12c195cd5ec23c89ed1d23e7881756b69a
[ "Java" ]
5
Java
headbanging3/Team_Project1-3
379bba79e3ca900b6f813cd1c32c816482d79dee
028a348a520b33f977a387fddf8ac0cf4b9793c3
refs/heads/master
<repo_name>LHugueniot/InverseKinematicsTest<file_sep>/emitter.h #ifndef EMITTER_H #define EMITTER_H #endif // EMITTER_H <file_sep>/particle.cpp #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #include "glm/glm.hpp" #include "particle.h" #include <iostream> #include <cstdlib> #include <glm/gtc/random.hpp> Particle::Particle(glm::vec3 _pos, int _type, int _life) { life = _life; type = _type; pos = _pos; velocity = glm::vec3(0,0,0); vel2 = glm::vec3(0,glm::diskRand(1.0f)); vel3 = glm::sphericalRand(1.0f); ballrand = glm::ballRand(0.2f); // col.r= ((float) rand() / (RAND_MAX)); // col.g= ((float) rand() / (RAND_MAX)); // col.b= ((float) rand() / (RAND_MAX)); if(type==firework) { col.r= 1; col.g= 0.5; col.b= 0; col.a=1; } if(type==fire) { col.r= 255/255; col.g= 127/255; col.b= 80/255; col.a=1; } alive = true; } void Particle::draw() { if(alive == true) { glColor4f(col.r,col.g,col.b,col.a); glPointSize(3); glBegin(GL_POINTS); glVertex3f(pos.x,pos.y,pos.z); glEnd(); glColor4f(col.r,col.g,col.b,col.a); glPointSize(2); glBegin(GL_POINTS); glVertex3f(pos.x-10*velocity.x,pos.y-10*velocity.y,pos.z-10*velocity.z); glEnd(); glColor4f(col.r,col.g,col.b,col.a); glPointSize(1); glBegin(GL_POINTS); glVertex3f(pos.x-20*velocity.x,pos.y-20*velocity.y,pos.z-20*velocity.z); glEnd(); } } void Particle::update() { //glm::vec3 ballrand = glm::ballRand(2.0f); if(type==firework) { if(alive == true) { pos+=velocity; if(life>150) { velocity= glm::vec3(0.2,0,0);; } if(life<150) { velocity=ballrand; } --life; } } if(type==fire) { //std::cout<<life<<'\n'; if(alive == true) { pos+=velocity; velocity= glm::vec3(0.2,glm::diskRand(0.1f)); --life; while(col.g < 1.0f||col.b>0) { col.g+=0.0001; col.b-=0.0001; } } } if(life<=0) { alive = 0; } } <file_sep>/main.cpp #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #include <iostream> #include <cstdlib> #include <glm/glm.hpp> #include "sdlwindow.h" #include "particle.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> #include <algorithm> #include "InvKinTest.h" // constants const int WIDTH = 720*1.5; const int HEIGHT = 576*1.5; // function to init the basic OpenGL scene for this demo int framecount = 0; std::vector<Particle>fuzzy; std::vector<InvKinTest>waddup; float angle=0; int num_part=100; int mean_fire_part_num; int current_num_part=0; bool fireon=false; enum _type{firework,fire}; void initOpenGL(); // function to render our scene. void grid(); void draw(); void spawn(int type); void line(double _p1x,double _p1y,double _p1z,double _p2x,double _p2y,double _p2z,double _r,double _g,double _b); void loadView(); int main() { SDLWindow win("Particle System demo", 0,0, WIDTH, HEIGHT); InvKinTest* test=new InvKinTest; win.makeCurrent(); win.setBackground(); initOpenGL(); bool quit=false; while(!quit) { SDL_Event event; //glm::perspective(glm::radians(180.f),6.0f,0.1f,1000.0f); // grab the event from the window (note this explicitly calls make current) win.pollEvent(event); switch (event.type) { // this is the window x being clicked. case SDL_QUIT : quit = true; break; // now we look for a keydown event case SDL_KEYDOWN: { switch( event.key.keysym.sym ) { // if it's the escape key quit case SDLK_ESCAPE : quit = true; break; // make OpenGL draw wireframe case SDLK_w : spawn(firework); break; case SDLK_a : fireon=!fireon; //std::cout << std::boolalpha << fireon << '\n'; break; // make OpenGL draw solid case SDLK_s : glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); break; case SDLK_LEFT : win.rotate.z +=1; break; case SDLK_RIGHT : win.rotate.z -=1; break; case SDLK_UP : win.rotate.x +=1; break; case SDLK_DOWN : win.rotate.x -=1; break; case SDLK_r : test->solveIk(glm::vec3(0,99,0)); //std::cout<<"%f"<<waddup[0].ArmList[0].m_angle; break; case SDLK_d : test->MakeArms(glm::vec3(0,0,10),10); test->drawArms(); break; } // end of key process } // end of keydown default : break; } // end of event switch loadView(); if(55>=win.rotate.x) { win.rotate.x=win.rotate.x+1; } if(win.rotate.x>=-125) { win.rotate.x=win.rotate.x-1; } glRotatef(win.rotate.x,0,-0.5,0.5); glRotatef(win.rotate.z,1,0,0); if(fireon==true) { spawn(fire); } for(auto &p : fuzzy) { p.draw(); p.update(); if (p.alive==0) { fuzzy.erase(fuzzy.begin()); } } grid(); test->drawArms(); win.swapWindow(); ++framecount; //std::cout<<framecount<<"\n"; //std::cout<<fuzzy.size()<<"\n"; } return EXIT_SUCCESS; } void initOpenGL() { glClearColor(0.8,0.8,0.8,1.0); glEnable(GL_POINT_SMOOTH); } void loadView() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMultMatrixf(glm::value_ptr(glm::perspective(0.5f,float(WIDTH/HEIGHT),0.01f,500.0f))); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMultMatrixf(glm::value_ptr(glm::lookAt(glm::vec3(250.0f, 250.0f, 250.0f),glm::vec3(0.0f, 0.0f, 0.0f),glm::vec3(1.0f, 0.0f, 0.0f)))); } void spawn(int type) { int firework_life=500; //int fire_life=50 + ((rand() % (-1) + 1)*50); int fire_life=(200 + (rand() % 1 + 50)); //std::cout<<fire_life<<'\n'; if(type==firework) { for(int i=0;i<num_part;i++) { Particle p(glm::vec3(0,0,0),firework,firework_life); fuzzy.push_back(p); } } if(type==fire) { Particle p(glm::vec3(glm::sphericalRand(10.0f)),fire,fire_life); fuzzy.push_back(p); } } void grid() { for(int i=-5;i<=5;i++) { line(0.0,50.0,(i*10.0),0.0,-50.0,(i*10.0),1,1,1); line(0.0,(i*10.0),50.0,0.0,(i*10.0),-50.0,1,1,1); } line(0,0,0,0,0,20,0,0,1); //line z line(0,0,0,20,0,0,1,0,0); //line x line(0,0,0,0,20,0,0,1,0); //line y } void line(double _p1x,double _p1y,double _p1z,double _p2x,double _p2y,double _p2z,double _r,double _g,double _b) { double p1x=_p1x; double p1y=_p1y; double p1z=_p1z; double p2x=_p2x; double p2y=_p2y; double p2z=_p2z; glLineWidth(1); glColor3f(_r,_g,_b); glBegin(GL_LINES); glVertex3f(p1x,p1y,p1z); glVertex3f(p2x,p2y,p2z); glEnd(); } <file_sep>/InvKinTest.h #ifndef INVKINTEST_H #define INVKINTEST_H #ifdef __linux__ #include <GL/gl.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #endif #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/random.hpp" #include <vector> class InvKinTest { public: InvKinTest(); ~InvKinTest(); void MakeArms(glm::vec3 m_origin, int m_numArms); void drawArms(); void rotateArms(int i, float angle); void update(); float getArmLength(); void solveIk(glm::vec3 m_goal); void solveIkwhole(glm::vec3 m_goal); void solveIkstep(glm::vec3 m_goal); struct Arm{ glm::vec3 m_p1; glm::vec3 m_p2; glm::vec3 m_rot = glm::vec3(0,0,1); glm::vec3 m_p2prime; glm::vec3 m_p1prime; float m_len = 10.0; float m_angle=0; }; //glm::vec3 goal = glm::vec3(0,0,3); std::vector<Arm> ArmList; std::vector<glm::vec3> VertArray; }; #endif // INVKINTEST_H <file_sep>/particle.h #ifndef PARTICLE_H #define PARTICLE_H #ifdef __linux__ #include <GL/gl.h> #endif #ifdef __APPLE__ #include <OpenGL/gl.h> #endif #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/random.hpp" class Particle { public: Particle(glm::vec3 _pos, int _type, int _life); void draw(); void update(); // int life; bool alive; glm::vec3 vel2; glm::vec3 vel3; glm::vec3 ballrand; enum type{firework,fire}; //glm::vec3 firework; private: int life; int type; glm::vec3 pos; glm::vec3 velocity; glm::vec4 col; }; #endif // PARTICLE_H <file_sep>/sdlwindow.cpp #include "glm/glm.hpp" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #include "sdlwindow.h" #include "SDL2/SDL.h" #include <iostream> SDLWindow::SDLWindow(const std::string &_name, int _x, int _y, int _width, int _height) { m_name=_name; m_x=_x; m_y=_y; m_width=_width; m_height=_height; init(); } void SDLWindow::init() { if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { ErrorExit("Could Not Init Everything"); } m_window=SDL_CreateWindow(m_name.c_str(),m_x,m_y, m_width,m_height, SDL_WINDOW_OPENGL ); if(!m_window) { ErrorExit("Could not create Window"); } createGLContext(); } void SDLWindow::createGLContext() { SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION,2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,4); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); m_glContext=SDL_GL_CreateContext(m_window); } void SDLWindow::setBackground() { glClearColor(0,0,0,1); } void SDLWindow::pollEvent(SDL_Event &_event) { makeCurrent(); SDL_PollEvent(&_event); } void SDLWindow::ErrorExit(const std::string &_msg) const { std::cerr<<_msg<<std::endl; std::cerr<<SDL_GetError()<<std::endl; SDL_Quit(); exit(EXIT_FAILURE); } <file_sep>/InvKinTest.cpp #include "InvKinTest.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #define GLM_SWIZZLE #include "glm/glm.hpp" #include <iostream> #include <cstdlib> #include <glm/gtx/rotate_vector.hpp> #include <glm/gtc/random.hpp> #include <glm/gtx/transform.hpp> InvKinTest::InvKinTest() { } InvKinTest::~InvKinTest() { } void InvKinTest::MakeArms(glm::vec3 m_origin, int m_numArms) { glm::vec3 temp; auto numArms=m_numArms; for(int i=0; i<numArms;i++) { Arm p; if(i==0) { ArmList.push_back(p); ArmList[i].m_p1=m_origin; ArmList[i].m_p2=ArmList[i].m_p1+glm::vec3(1,0,0)*ArmList[i].m_len; } else { ArmList.push_back(p); ArmList[i].m_p1=ArmList[i-1].m_p2; ArmList[i].m_p2=ArmList[i].m_p1+glm::vec3(1,0,0)*ArmList[i].m_len; } } } void InvKinTest::update() { for(int i=1; i<ArmList.size();i++) { } } //void InvKinTest::Smooth(glm::vec3 m_goal,int time) //{ // auto diffVec=m_goal- ArmList[i].m_p2; // auto distVec=glm::length(diffVec); // auto step = distVec/time; // auto stepgoal=diffVec; // //for() // solveIk(stepgoal); //} float InvKinTest::getArmLength() { float ArmSize=0; for(int i=0; i<ArmList.size();i++) { ArmSize=ArmList[i].m_len; } return ArmSize; } void InvKinTest::addArm() { } void InvKinTest::removeArm() { } void InvKinTest::solveIk(glm::vec3 m_goal) { auto goal=m_goal; auto maxLength=glm::length(goal-ArmList[0].m_p1); auto ArmSize=getArmLength(); bool solved=false; if(maxLength>ArmSize) { goal=glm::normalize(goal)*maxLength; } if(!solved) { for(int i=ArmList.size(); i>0;i--) { if(i==ArmList.size()) { ArmList[i].m_p2prime=goal; ArmList[i].m_p1prime=glm::normalize(ArmList[i].m_p1-ArmList[i].m_p2prime)*ArmList[i].m_len+ArmList[i].m_p2prime; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); //printf("%d\n",i); //printf("%f\n",ArmList[i].m_p1prime); } else { ArmList[i].m_p2prime=ArmList[i+1].m_p1prime; ArmList[i].m_p1prime=glm::normalize(ArmList[i].m_p1-ArmList[i].m_p2prime)*ArmList[i].m_len+ArmList[i].m_p2prime; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } printf("%d\n",i); } for(int i=0; i<ArmList.size();i++) { if(i==ArmList.size()) { ArmList[i].m_p2=glm::normalize(ArmList[i].m_p2prime-ArmList[i].m_p1)*ArmList[i].m_len+ArmList[i].m_p1; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } else { ArmList[i].m_p2=glm::normalize(ArmList[i].m_p2prime-ArmList[i].m_p1)*ArmList[i].m_len+ArmList[i].m_p1; ArmList[i+1].m_p1=ArmList[i].m_p2; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } } auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); if(distance<0.2) { solved=true; } } } void InvKinTest::drawArms() { for(int i=0; i<ArmList.size();i++) { glm::vec3 p1=ArmList[i].m_p1; glm::vec3 p2=ArmList[i].m_p2; //printf("hi \np1=%f%f%f \np2=%f%f%f",p1.x,p1.y,p1.z,p2.x,p2.y,p2.z); glLineWidth(1); glColor3f(1,0,0); glBegin(GL_POINTS); glPointSize(100); glVertex3f(p1.x,p1.y,p1.z); glVertex3f(p2.x,p2.y,p2.z); glEnd(); glBegin(GL_LINES); glVertex3f(p1.x,p1.y,p1.z); glVertex3f(p2.x,p2.y,p2.z); glEnd(); //printf("\n\n"); } } void InvKinTest::rotateArms(int i, float angle) { ArmList[i].m_angle=angle;//*ArmList[i].m_len; update(); } //-----------------------------#shitcode-------------------------------------- void InvKinTest::solveIkwhole(glm::vec3 m_goal) { bool running=true; bool can=true; if (can) { solveIk(m_goal); drawArms(); auto goal=m_goal; float distance= glm::length(goal - ArmList[ArmList.size()].m_p2); if (distance < 0.2)running = false; } } void InvKinTest::solveIkstep(glm::vec3 m_goal) { auto goal=m_goal; auto maxLength=glm::length(goal-ArmList[0].m_p1); bool solved=false; for(int i=ArmList.size(); i>0;i--) { if(i==ArmList.size()) { ArmList[i].m_p2prime=goal; ArmList[i].m_p1prime=glm::normalize(ArmList[i].m_p1-ArmList[i].m_p2prime)*ArmList[i].m_len+ArmList[i].m_p2prime; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); //printf("%d\n",i); //printf("%f\n",ArmList[i].m_p1prime); } else { ArmList[i].m_p2prime=ArmList[i+1].m_p1prime; ArmList[i].m_p1prime=glm::normalize(ArmList[i].m_p1-ArmList[i].m_p2prime)*ArmList[i].m_len+ArmList[i].m_p2prime; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } printf("%d\n",i); } for(int i=0; i<ArmList.size();i++) { if(i==ArmList.size()) { ArmList[i].m_p2=glm::normalize(ArmList[i].m_p2prime-ArmList[i].m_p1)*ArmList[i].m_len+ArmList[i].m_p1; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } else { ArmList[i].m_p2=glm::normalize(ArmList[i].m_p2prime-ArmList[i].m_p1)*ArmList[i].m_len+ArmList[i].m_p1; ArmList[i+1].m_p1=ArmList[i].m_p2; auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); printf("%f\n",distance); } } auto distance= glm::length(goal - ArmList[ArmList.size()].m_p2); }
d17fc909a9bc88ab9cae3eb757f80197ffd27d66
[ "C", "C++" ]
7
C
LHugueniot/InverseKinematicsTest
ef35f8034d01d80727c9d0ed9705d67dbc0f3e94
1912694209807539e6d1021c2f5a0f866324eb4f
refs/heads/master
<repo_name>filipelinemburger/appClientRegister<file_sep>/src/test/java/com/br/appclientregister/AppClientRegisterApplicationTests.java package com.br.appclientregister; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class AppClientRegisterApplicationTests { @Test void contextLoads() { } } <file_sep>/src/test/java/com/br/appclientregister/city/CityServiceTest.java package com.br.appclientregister.city; import com.br.appclientregister.entities.City; import com.br.appclientregister.repositories.CityRepository; import com.br.appclientregister.rest.dto.CityDTO; import com.br.appclientregister.services.impl.CityServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyObject; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration public class CityServiceTest { public static String CITY_PALHOCA = "Palhoça"; public static String CITY_BLUMENAU = "Blumenau"; public static String STATE = "SC"; @InjectMocks private static CityServiceImpl cityService; @Mock private CityRepository cityRepository; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } public City getCityObjectWithId1ToTest(){ City city = new City(); city.setId(1); city.setName(CITY_PALHOCA); city.setState(STATE); return city; } public CityDTO getCityDTOObjectWithoutIdToTest(){ CityDTO cityDTO = new CityDTO(); cityDTO.setCityName(CITY_PALHOCA); cityDTO.setState(STATE); return cityDTO; } @Test public void saveANewCityTest() { City city = getCityObjectWithId1ToTest(); CityDTO cityDTO = getCityDTOObjectWithoutIdToTest(); Mockito.when(cityRepository.save(anyObject())).thenReturn(city); CityDTO citySaved = cityService.save(cityDTO); assertTrue(citySaved.getCityName().equals(CITY_PALHOCA)); assertTrue(citySaved.getState().equals(STATE)); } @Test public void findCityByNameTest() { City city = getCityObjectWithId1ToTest(); List<City> citiesMock = new ArrayList<>(); citiesMock.add(city); Mockito.when(cityRepository.findAllByNameIgnoreCase(CITY_PALHOCA)).thenReturn(citiesMock); List<CityDTO> citySaved = cityService.findAllByNameIgnoreCase(CITY_PALHOCA); assertTrue(citySaved.get(0).getCityName().equals(CITY_PALHOCA)); assertTrue(citySaved.get(0).getState().equals(STATE)); } @Test public void findCityByStateTest() { City city = getCityObjectWithId1ToTest(); List<City> citiesMock = new ArrayList<>(); citiesMock.add(city); Mockito.when(cityRepository.findAllByStateIgnoreCase(STATE)).thenReturn(citiesMock); List<CityDTO> cities = cityService.findAllByStateIgnoreCase(STATE); assertTrue(cities.get(0).getCityName().equals(CITY_PALHOCA)); assertTrue(cities.get(0).getState().equals(STATE)); } } <file_sep>/src/main/java/com/br/appclientregister/entities/enums/Genre.java package com.br.appclientregister.entities.enums; public enum Genre { MALE(0), FEMALE(1); private int value; Genre(int genre) {this.value = genre;} public int getValue() { return value; } } <file_sep>/src/main/java/com/br/appclientregister/entities/City.java package com.br.appclientregister.entities; import com.br.appclientregister.rest.dto.CityDTO; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Set; import static javax.persistence.CascadeType.ALL; import static javax.persistence.FetchType.LAZY; import static javax.persistence.GenerationType.AUTO; @Entity @Table(name = "city") @Data @NoArgsConstructor @AllArgsConstructor public class City { @Id @GeneratedValue(strategy = AUTO) @Column private Integer id; @Column(length = 50) private String name; @Column(length = 50) private String state; @OneToMany(mappedBy = "city", fetch = LAZY, cascade = ALL) private Set<Client> clients; public City(CityDTO cityDTO){ this.setName(cityDTO.getCityName()); this.setState(cityDTO.getState()); } } <file_sep>/src/main/java/com/br/appclientregister/entities/Client.java package com.br.appclientregister.entities; import com.br.appclientregister.entities.enums.Genre; import com.br.appclientregister.rest.dto.ClientDTO; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; import static javax.persistence.FetchType.EAGER; import static javax.persistence.GenerationType.AUTO; @Entity @Table(name = "client") @Data @NoArgsConstructor @AllArgsConstructor public class Client implements Serializable { @Id @GeneratedValue(strategy = AUTO) @Column private Integer id; @Column(length = 50, nullable = false) private String name; @Column(name = "genre", nullable = false) @Enumerated(EnumType.ORDINAL) private Genre genre; @Column(nullable = false) @JsonFormat(pattern="yyyy-MM-dd") private LocalDate birthday; @ManyToOne(fetch = EAGER, optional = false) @JoinColumn(name = "city_id", nullable = false) private City city; public Client(ClientDTO clientDTO) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); this.setBirthday(LocalDate.parse(clientDTO.getBirthdayDate(), formatter)); Genre genre = clientDTO.getGenre().toLowerCase().equals("male") ? Genre.MALE : Genre.FEMALE; this.setGenre(genre); this.setName(clientDTO.getClientName()); } public int getAge(){ Period period = Period.between(birthday, LocalDate.now()); return Math.abs(period.getYears()); } }<file_sep>/src/test/java/com/br/appclientregister/client/ClientDTOTest.java package com.br.appclientregister.client; import com.br.appclientregister.city.CityServiceTest; import com.br.appclientregister.entities.Client; import com.br.appclientregister.rest.dto.ClientDTO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestComponent; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.jupiter.api.Assertions.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration @TestComponent public class ClientDTOTest { private ClientServiceTest clientServiceTest; private CityServiceTest cityServicesTest; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); cityServicesTest = new CityServiceTest(); clientServiceTest = new ClientServiceTest(); } @Test public void mountClientDTOTest() { Client client = clientServiceTest.getClientObjectWithId1ToTest(); client.setCity(cityServicesTest.getCityObjectWithId1ToTest()); ClientDTO dto = new ClientDTO(client); assertTrue(dto.getClientId() == client.getId()); assertTrue(dto.getAge() == client.getAge()); assertTrue(dto.getClientName().equals(client.getName())); String genre = client.getGenre().toString().substring(0, 1).toUpperCase() + client.getGenre().toString().substring(1).toLowerCase(); assertTrue(dto.getGenre().equals(genre)); assertTrue(dto.getCityId() == client.getCity().getId()); assertTrue(dto.getCity().equals(client.getCity().getName())); } } <file_sep>/src/main/java/com/br/appclientregister/rest/dto/ClientDTO.java package com.br.appclientregister.rest.dto; import com.br.appclientregister.entities.Client; import com.br.appclientregister.entities.enums.Genre; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.time.format.DateTimeFormatter; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ClientDTO { private Integer clientId; private String clientName; private String birthdayDate; private String genre; private int age; private Integer cityId; private String city; public ClientDTO(Client client){ this.setClientId(client.getId()); this.setClientName(client.getName()); this.setAge(client.getAge()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); this.setBirthdayDate(client.getBirthday().format(formatter)); this.setCityId(client.getCity().getId()); this.setCity(client.getCity().getName()); this.setGenre(client.getGenre() == Genre.MALE ? "Male": "Female"); } } <file_sep>/src/test/java/com/br/appclientregister/client/ClientServiceTest.java package com.br.appclientregister.client; import com.br.appclientregister.city.CityServiceTest; import com.br.appclientregister.entities.Client; import com.br.appclientregister.entities.enums.Genre; import com.br.appclientregister.repositories.CityRepository; import com.br.appclientregister.repositories.ClientRepository; import com.br.appclientregister.rest.dto.ClientDTO; import com.br.appclientregister.services.impl.ClientServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Matchers.anyObject; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration public class ClientServiceTest { public Integer ID_CLIENT = 1; public static String CLIENT_NAME = "Mario"; LocalDate birthday = LocalDate.of(1990, 1, 1); public static String GENRE_MALE = "Male"; @InjectMocks private static ClientServiceImpl clientService; @Mock private CityRepository cityRepository; @Mock private ClientRepository clientRepository; private CityServiceTest cityServicesTest; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); cityServicesTest = new CityServiceTest(); } @Test public void saveANewClientTest() throws Exception { Client client = getClientObjectWithId1ToTest(); client.setCity(cityServicesTest.getCityObjectWithId1ToTest()); ClientDTO clientDTO = getClientDTOObjectWithId1ToTest(); Mockito.when(clientRepository.save(anyObject())).thenReturn(client); Mockito.when(cityRepository.findById(clientDTO.getCityId())).thenReturn(Optional.of(cityServicesTest.getCityObjectWithId1ToTest())); ClientDTO clientSaved = clientService.save(clientDTO); assertTrue(clientSaved.getClientId().equals(clientDTO.getClientId())); assertTrue(clientSaved.getClientName().equals(clientDTO.getClientName())); assertTrue(clientSaved.getGenre().equals(clientDTO.getGenre())); assertTrue(clientSaved.getCityId() == clientDTO.getCityId()); assertTrue(clientSaved.getCity().equals(client.getCity().getName())); } @Test public void findClientByNameTest() throws Exception { Client client = getClientObjectWithId1ToTest(); client.setCity(cityServicesTest.getCityObjectWithId1ToTest()); List<Client> listClients = new ArrayList<>(); listClients.add(client); ClientDTO clientDTO = getClientDTOObjectWithId1ToTest(); Mockito.when(clientRepository.findAllByNameIgnoreCase(CLIENT_NAME)).thenReturn(listClients); List<ClientDTO> clientDTOList = clientService.findByNameIgnoreCase(CLIENT_NAME); assertTrue(clientDTOList.get(0).getClientId() == client.getId()); assertTrue(clientDTOList.get(0).getClientName().equals(client.getName())); assertTrue(clientDTOList.get(0).getGenre().equals(GENRE_MALE)); assertTrue(clientDTOList.get(0).getCityId().equals(client.getCity().getId())); assertTrue(clientDTOList.get(0).getCity().equals(client.getCity().getName())); } @Test public void findClientByIdTest() throws Exception { Client client = getClientObjectWithId1ToTest(); client.setCity(cityServicesTest.getCityObjectWithId1ToTest()); ClientDTO clientDTO = getClientDTOObjectWithId1ToTest(); Mockito.when(clientRepository.findById(ID_CLIENT)).thenReturn(Optional.ofNullable(client)); ClientDTO clientSaved = clientService.findClientDTOById(ID_CLIENT); assertTrue(clientSaved.getClientId() == client.getId()); assertTrue(clientSaved.getClientName().equals(client.getName())); assertTrue(clientSaved.getGenre().equals(GENRE_MALE)); assertTrue(clientSaved.getCityId().equals(client.getCity().getId())); assertTrue(clientSaved.getCity().equals(client.getCity().getName())); } public Client getClientObjectWithId1ToTest() { Client client = new Client(); client.setId(1); client.setBirthday(birthday); client.setGenre(Genre.MALE); client.setName(CLIENT_NAME); return client; } public ClientDTO getClientDTOObjectWithId1ToTest() { Client client = this.getClientObjectWithId1ToTest(); client.setCity(cityServicesTest.getCityObjectWithId1ToTest()); return new ClientDTO(client); } }
12d7e3ab4f7bc35c00f8adcc34eabd8702914b60
[ "Java" ]
8
Java
filipelinemburger/appClientRegister
5da0810cb9deb1f0619dedfabb7a5110654fd1ee
81fc3aedb5c3582cf1486082772393c0f5d6f55d
refs/heads/master
<file_sep>#!/bin/bash for l1 in 1 2 3 4 5 6 7 do for samp in 1 2 3 4 5 6 7 8 do ./a.out $l1 $samp done done
51884a47fcf45da264a19b274d18c644343469a7
[ "Shell" ]
1
Shell
Nikos-T/BP-CUDA
fd392e35f7c4b7530f4d1a2164d0cdb643dc8c25
5033cd3a8f4e519e8f6fccf38a9916d49ddd8b63
refs/heads/main
<repo_name>CRLTeam/HLF_Evaluation_Chaincode<file_sep>/evaluation.js /* * Ryserson Cybersecurity Research Lab * <NAME> * * SPDX-License-Identifier: MIT */ 'use strict'; const { Contract } = require('fabric-contract-api'); class Evaluation extends Contract { async InitLedger(ctx) { await ctx.stub.putState('StateData', Buffer.from('0')); console.info('Evaluation stateData initialized'); } // Write the stateData value. async WriteState(ctx, _stateData) { ctx.stub.putState('StateData', Buffer.from(_stateData)); await this.ctx.stub.setEvent('watchState', Buffer.from(JSON.stringify(stateData))); return _stateData; } // Read the stateData value. async ReadState(ctx) { const _stateData = await ctx.stub.getState('StateData'); return _stateData; } // Call the interop function async callInterop(ctx, _interopDID, _func, _callerDID, _nonce, _sig) { const _stateData = await ctx.stub.getState('StateData'); let callData = { interopDID: _interopDID, func: _func, value: _stateData, callerDID, _callerDID, nonce: _nonce, sig: _sid, // encrypted hash of previous values txID: ctx.stub.getTxID(), // transaction proposal ID userID: ctx.clientIdentity.getID(), // user ID orgID: ctx.clientIdentity.getMSPID() // org information } await this.ctx.stub.setEvent('interopCall', Buffer.from(JSON.stringify(callData))); } } module.exports = Evaluation;
3515706490e58d61574ecf80b22d25d8984ef00b
[ "JavaScript" ]
1
JavaScript
CRLTeam/HLF_Evaluation_Chaincode
5733c1edff6020580fec79470d15a03de4f3f39b
2f6d9940979a25722cbc574897995c5e2ffb3f5a
refs/heads/master
<repo_name>johneosborne/Simon<file_sep>/Simon/src/edu/apsu/csci/simon/Game.java /* * Name: <NAME> * Date: 2/8/2014 * Assignment: #1 - Simon * Class: CSCI 4020 */ package edu.apsu.csci.simon; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.SoundPool; import android.opengl.Visibility; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * Runs the game. It includes instances of SimonButton * and an inner Computer class that controls Simon. */ public class Game extends Activity implements OnTouchListener { private static SoundPool soundPool; private ImageView centerImageIV; private ImageView magicLeeIV; private SimonButton[] button = new SimonButton[4]; private Button newGameButton; private TextView playersTurnTV; private TextView roundNumberTV; private boolean isPlayersTurn; private boolean playerFinishedTurn; private List<Integer> computersChoices; private int playersChoices; private int turnNumber; private int roundNumber; private HashMap<Integer, Integer> endingSounds; //stores possible sounds for losing private int amIGoingTooFastSoundId; private int askToReceiveSoundId; private int highScore; final private int GREEN_BUTTON = 0, YELLOW_BUTTON = 1, BLUE_BUTTON = 2, RED_BUTTON = 3; private Simon simon; // is null by default @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.single_player); // GET HIGH SCORE FROM MAIN_ACTIVITY Intent intent = getIntent(); Bundle extras = intent.getExtras(); highScore = extras.getInt(MainActivity.HIGH_SCORE_FIELD); // INITIALIZE VARIABLES soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); computersChoices = new ArrayList<Integer>(); roundNumber = 1; playerFinishedTurn = true; // must be initialized to true for the first turn int buttonIds[] = {R.id.greenButton, R.id.yellowButton, R.id.blueButton, R.id.redButton}; newGameButton = (Button) findViewById(R.id.newGameButton); newGameButton.setOnTouchListener(this); centerImageIV = (ImageView) findViewById(R.id.centerImage); magicLeeIV = (ImageView) findViewById(R.id.magicLee); playersTurnTV = (TextView) findViewById(R.id.playersTurnTV); roundNumberTV = (TextView) findViewById(R.id.roundNumberTV); // INITIALIZE BUTTON SOUNDS AND TOUCH LISTENERS for (int b = 0; b < button.length; b++) { button[b] = (SimonButton)findViewById(buttonIds[b]); button[b].setPlaySoundId(soundPool.load(this, button[b].getSoundId(), 1)); button[b].setOnTouchListener(this); } // POSSIBLE LOSING SOUNDS. JUST ADD TO MAP AND IT'LL HAVE A CHANCE OF BEING SELECTED endingSounds = new HashMap<Integer, Integer>(); endingSounds.put(0, soundPool.load(this, R.raw.haha, 1)); endingSounds.put(1, soundPool.load(this, R.raw.i_finally_win_one, 1)); endingSounds.put(2, soundPool.load(this, R.raw.what_the, 1)); endingSounds.put(3, soundPool.load(this, R.raw.he_had_balls, 1)); endingSounds.put(4, soundPool.load(this, R.raw.holy_crap, 1)); amIGoingTooFastSoundId = soundPool.load(this, R.raw.am_i_going_too_fast, 1); askToReceiveSoundId = soundPool.load(this, R.raw.ask_ye_receiver, 1); } @Override protected void onResume() { super.onResume(); Log.i("RESUME", "onResume called" + isPlayersTurn + " " + playerFinishedTurn); // CREATE COMPUTER IF NEEDED if (simon == null) { simon = new Simon(); simon.execute(); } else { Log.i("INFO", "Computer already running"); } } @Override protected void onPause() { super.onPause(); Log.i("PAUSE", "onPause called" + isPlayersTurn + " " + playerFinishedTurn); if (simon != null) { simon.cancel(true); simon = null; } soundPool.autoPause(); } @Override protected void onDestroy() { super.onDestroy(); Log.i("DESTROYED", "onDestroy called"); soundPool.release(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.main, menu); return true; } /** Method that is used by the SimonButton class to access the SoundPool in order to play a sound. */ public static void playSound(int soundId) { soundPool.play(soundId, 1f, 1f, 0, 0, 1f); } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Log.i("INFO", "onTouch Called"); if (isPlayersTurn) { if(v.getId() == button[0].getId()) { button[0].blinkButton(); playersChoices = GREEN_BUTTON; } else if(v.getId() == button[1].getId()) { button[1].blinkButton(); playersChoices = YELLOW_BUTTON; } else if(v.getId() == button[2].getId()) { button[2].blinkButton(); playersChoices = BLUE_BUTTON; } else { button[3].blinkButton(); playersChoices = RED_BUTTON; } checkPlayerChoice(); return true; } else { if (v.getId() == newGameButton.getId()) { startNewGame(); } } } return false; } /** Checks each button that the player touches to make sure it's the right one. */ void checkPlayerChoice() { if (playersChoices == computersChoices.get(turnNumber-1)) { //If player's button choice is correct. if (simon == null && turnNumber == computersChoices.size()) { // If player wins the round. playerFinishedTurn = true; simon = new Simon(); // Check for new high score. if(roundNumber > highScore) { highScore = roundNumber; Toast toast = Toast.makeText(this, "NEW HIGH SCORE!!!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); writeHighScore(); } // Make Dr. Lee pop up every 5 turns if (roundNumber % 5 == 0) { popUpDrLee(); } roundNumber++; simon.execute(); // make Simon start next round } else { Log.i("Game.checkPlayersChoice", "Player still has " + (computersChoices.size()-turnNumber) + " buttons left"); } } else { // This else runs if the player chooses the wrong button. Log.i("Game.playersChoice", "INCORRECT"); isPlayersTurn = false; playerFinishedTurn = false; roundNumberTV.setVisibility(View.INVISIBLE); newGameButton.setVisibility(View.VISIBLE); playersTurnTV.setText("You Lose..."); spinNicholsonHead(); playLosingSound(); } turnNumber++; } /** Plays a random sound that has been loaded into the endSounds hashmap. */ public void playLosingSound() { Random r = new Random(); soundPool.play(endingSounds.get(r.nextInt(endingSounds.size())), 1, 1, 0, 0, 1); } /** Restarts the game by resetting the computersChoices array and the roundNumber. */ public void startNewGame() { Log.i("INFO", "startNewGame called"); roundNumber = 1; playerFinishedTurn = true; computersChoices.clear(); soundPool.play(askToReceiveSoundId, 1, 1, 0, 0, 1); centerImageIV.setImageResource(R.drawable.small_eyes_with_background); newGameButton.setVisibility(View.INVISIBLE); roundNumberTV.setVisibility(View.VISIBLE); if (simon == null) { simon = new Simon(); simon.execute(); } else { Log.i("INFO", "Computer already running"); } } public void writeHighScore() { try { FileOutputStream outputFile = openFileOutput("high_scores", MODE_PRIVATE); OutputStreamWriter writer = new OutputStreamWriter(outputFile); BufferedWriter buf = new BufferedWriter(writer); PrintWriter printer = new PrintWriter(buf); printer.println(turnNumber); printer.close(); Log.i("HIGH_SCORE", "File written, high score " + turnNumber); } catch (FileNotFoundException e) { Log.i("CATCH", "File could not be written out."); } } /** Controls Dr. Lee animation. */ void popUpDrLee() { //http://developer.android.com/guide/topics/graphics/view-animation.html Animation leePopup = AnimationUtils.loadAnimation(this, R.anim.lee_popup); new Handler().postDelayed(new Runnable() { @Override public void run() { soundPool.play(amIGoingTooFastSoundId, 1, 1, 0, 0, 1); } }, 2000); magicLeeIV.startAnimation(leePopup); } /** Controls Dr. Nicholson animation. */ void spinNicholsonHead() { Animation bugEyes = AnimationUtils.loadAnimation(this, R.anim.spin_head); centerImageIV.startAnimation(bugEyes); centerImageIV.setImageResource(R.drawable.big_eyes_with_background); } /** Inner class that is used to generate and save random button presses by Simon. */ public class Simon extends AsyncTask<Void, Integer, Void> { Random randomButtonGenerator = new Random(); @Override protected void onPreExecute() { if (newGameButton.getVisibility() != View.VISIBLE) { playersTurnTV.setText(""); roundNumberTV.setText("Round " + roundNumber); } } @Override protected Void doInBackground(Void... params) { try { isPlayersTurn = false; turnNumber = 1; if (playerFinishedTurn) { int buttonNumber = randomButtonGenerator.nextInt(4); computersChoices.add(buttonNumber); playerFinishedTurn = false; Log.i("RANDOM_BUTTON", "i = " + buttonNumber); } // fixes the problem when player loses and then exits the game so they can start again if(newGameButton.getVisibility() != View.VISIBLE) { Thread.sleep(1500); for (int i = 0; i < computersChoices.size(); i++) { Thread.sleep(500); // controls game speed publishProgress(computersChoices.get(i)); } } } catch (InterruptedException e) { Log.i("VALUES", "----- INTERUPTED -----"); } simon = null; return null; } @Override protected void onProgressUpdate(Integer... values) { Log.i("INFO", "inside onProgress Update"); button[values[0]].blinkButton(); } @Override protected void onPostExecute(Void result) { if(newGameButton.getVisibility() != View.VISIBLE) { playersTurnTV.setText("Your Turn..."); isPlayersTurn = true; } } } }<file_sep>/Simon/src/edu/apsu/csci/simon/SimonButton.java /* * Name: <NAME> * Date: 2/8/2014 * Assignment: #1 - Simon * Class: CSCI 4020 */ package edu.apsu.csci.simon; import java.lang.ref.Reference; import android.content.Context; import android.content.res.TypedArray; import android.media.AudioManager; import android.media.SoundPool; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; public class SimonButton extends ImageView { private int loadSoundId; private int playSoundId; private int image; private int pressedImage; public SimonButton(Context context) { super(context); init(null); } public SimonButton(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public SimonButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } /** Initializes member variables with XML values. */ private void init(AttributeSet attrs) { loadSoundId = 0; image = 0; pressedImage = 0; TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SimonButton); Log.i("SimonButton", "loading XML"); loadSoundId = a.getResourceId(R.styleable.SimonButton_soundId, loadSoundId); image = a.getResourceId(R.styleable.SimonButton_image, image); pressedImage = a.getResourceId(R.styleable.SimonButton_pressedImage, pressedImage); setImageResource(image); // Don't forget this a.recycle(); } /** Flips the button's image for 100 ms and plays the sound associated * with it by using the Game class' static method. */ void blinkButton() { setImageResource(pressedImage); this.postDelayed(new Runnable() { @Override public void run() { setImageResource(image); } }, 100); Game.playSound(playSoundId); } /** Allows Game to load the SoundPool with the SimonButton sound. */ void setPlaySoundId(int soundId) { playSoundId = soundId; } @Override public boolean isPressed() { // TODO Auto-generated method stub return super.isPressed(); } int getImage() { return image; } int getPressedImage() { return pressedImage; } int getSoundId() { return loadSoundId; } }<file_sep>/README.md Simon ===== Simon Says memory game developed for CSCI 4020. Developed on 7 inch screen so might appear broken on smaller screen.
45d964581733a83288c123244f1eff2976294257
[ "Markdown", "Java" ]
3
Java
johneosborne/Simon
3937fe75beacba29a314e033312666197f9ab50f
3de074c9b881935878844269b6b987ec3d19f11f
refs/heads/master
<file_sep>import requests url = 'http://apps.webofknowledge.com/full_record.do?product=UA&search_mode=GeneralSearch&qid=1&SID=7E8ocoeQDScVAjO5OzL&page=1&doc=7' html = requests.get(url).text print(html)<file_sep>zz=1 def y(): x() def x(): global zz zz = 3 y() print(zz)
c9d8febb5063fc2105eaaa6f306d0b1dbf4a1827
[ "Python" ]
2
Python
ZuiYee/ProxyPool
8bd70f58619000e97784be808d401b4db3f8246f
28307445201d58423c6280fabdfbddf31af4ccd8
refs/heads/main
<repo_name>kflores56/UFO-Sitings-Filter<file_sep>/README.md # Javascript Challenge ## Background The extra-terrestrial menace has come to Earth and we here at `ALIENS-R-REAL` have collected all of the eye-witness reports we could to prove it! All we need to do now is put this information online for the world to see and then the matter will finally be put to rest. There is just one tiny problem though...the collection is too large to search through manually. Even the most dedicated followers are complaining that they are having trouble locating specific reports in this mess. This project provides a code that will create a table dynamically based upon a [provided dataset](UFO-level-1/static/js/data.js). Users should be able to filter the table data for specific values. This code uses JavaScript, HTML, and CSS, and D3.js on our web pages. ## Automatic Table and Date Search * This code creates a basic HTML web page using the UFO dataset provided in the form of an array of JavaScript objects * The code appends a table to the web page and then adds new rows of data for each UFO sighting. * Columns include `date/time`, `city`, `state`, `country`, `shape`, and `comment`. * The a date form was used in the HTML document as well as JavaScript code that listened for events and search through the `date/time` column to find rows that match user input. <file_sep>/UFO-level-1/static/js/app.js // from data.js var tableData = data; // set variables var tbody = d3.select("tbody"); var button = d3.select("#filter-btn"); var form = d3.select("form"); ////CREATE TABLE//// // Step 1: Use `Object.entries` to console.log each ufo report data.forEach(function(ufoReport) { Object.entries(ufoReport).forEach(function([key, value]) { }); }); // Step 2: Use d3 to append 1 cell per ufo report data.forEach(function(ufoReport) { var row = tbody.append("tr"); Object.entries(ufoReport).forEach(function([key, value]) { }); }); // Step 3: Use d3 to update each cell with ufo report data.forEach(function(ufoReport) { console.log(ufoReport); var row = tbody.append("tr"); Object.entries(ufoReport).forEach(function([key, value]) { console.log(key, value); // Append a cell to the row for each record // in the ufo report var cell = row.append("td"); cell.text(value); }); }); ////FILTER TABLE//// // Create event handlers button.on("click", runEnter); form.on("submit",runEnter); // Complete the event handler function for the form function runEnter() { // Prevent the page from refreshing d3.event.preventDefault(); // Select the input element and get the raw HTML node var inputElement = d3.select("#datetime"); // Get the value property of the input element var inputValue = inputElement.property("value"); console.log(inputValue); var filteredData = tableData.filter(ufoReport => ufoReport.datetime === inputValue); console.log(filteredData); ////CREATE NEW TABLE WITH FILTERED DATA//// // Clear out data in current chart tbody.html('') // Build new chart filteredData.forEach(function(ufoReport) { console.log(ufoReport); var row = tbody.append("tr"); Object.entries(ufoReport).forEach(function([key, value]) { console.log(key, value); // Append a cell to the row for each record // in the ufo report var cell = row.append("td"); cell.text(value); }); }); };
c0d5feb9eb48a7c9a346f710913bc56337bd7de6
[ "Markdown", "JavaScript" ]
2
Markdown
kflores56/UFO-Sitings-Filter
1bf55b967e90dcc1b133999c32da5a051da9fe06
ac4cbaa7c50f7ffb9fe5a21053bcc195888fa447
refs/heads/master
<file_sep>var itemTemplate = Handlebars.compile($('#item-template').html()); $('.btn-submit-item').click(function() { if (itemlength % 3 === 0) { addRow(); } var $lastRow = $('.shopping-cart-table').find('.row').last(); var newItem = newItemObj(); itemlength++ $('.shopping-cart-table').find('.row').last().append(itemTemplate(newItem)); }); function addRow() { $('.shopping-cart-table').append('<div class="row"></div>'); } function newItemObj() { var itemObj = { name: $('#new-item-name').val(), price: $('#new-item-price').val(), picture: $('#new-item-pic').val() } return itemObj; }<file_sep>// Local Storage Init var STORAGE_ID = 'shopping-cart'; var saveToLocalStorage = function() { localStorage.setItem(STORAGE_ID, JSON.stringify(cart)); }; var getFromLocalStorage = function() { return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]'); }; // an array with all of our cart items var cart = []; var itemlength = 6 var source = $('#store-template').html(); var template = Handlebars.compile(source); var updateCart = function() { $('.cart-list').empty(); // Update cart from local storage cart = getFromLocalStorage(); var totalPrice = 0; for (i = 0; i < cart.length; i++) { var HTML = template(cart[i]); $('.cart-list').append(HTML); totalPrice += cart[i].price * cart[i].quantity; // Set quantity dropdown position on current quantity $('.cart-list').find('select').last().val(cart[i].quantity); } $('.total').html(totalPrice); } var addItem = function(item) { var itemExists = false; for (i = 0; i < cart.length; i++) { if (cart[i].name === item.name) { itemExists = true; break; } } if (itemExists) { cart[i].quantity++ } else { item.quantity = 1; cart.push(item); } // Update Local Storage saveToLocalStorage(); } var removeItem = function(itemIndex) { cart.splice(itemIndex, 1); // Update Local Storage saveToLocalStorage(); updateCart(); } var clearCart = function() { cart = []; // Update Local Storage saveToLocalStorage(); updateCart(); } var changeQuantity = function(cartIndex, newQuantity) { cart[cartIndex].quantity = newQuantity; saveToLocalStorage(); updateCart(); } $('.view-cart').on('click', function() { var shoppingCart = $('.shopping-cart'); shoppingCart.toggle(); }); $('.shopping-cart-table').on('click', '.add-to-cart', function() { // TODO: get the "item" object from the page var item = $(this).closest('.card').data(); addItem(item); updateCart(); }); $('.clear-cart').on('click', function() { clearCart(); }); $('.cart-list').on('click', '.remove', function() { var itemIndex = $(this).closest('.cart-item').index(); // get item's index removeItem(itemIndex); }); $('.shopping-cart').on('change', 'select', function() { var index = $(this).closest('.cart-item').index(); var value = $(this)[0].value; changeQuantity(index, value); }); // update the cart as soon as the page loads! updateCart();
1c6bc3eeb13cdc62db52f70b3a008aded94444c6
[ "JavaScript" ]
2
JavaScript
YZeitler/shopping-cart
603db0d9abfd655e7be0d63d9793074d20e907f0
0f83e4d4e6c5fdabbe0a809f1002a826d2a33439
refs/heads/master
<repo_name>cvlasin/Fillit<file_sep>/srcs/verificare.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* verificare.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cvlasin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/24 18:24:36 by cvlasin #+# #+# */ /* Updated: 2018/01/31 16:53:19 by moana ### ########.fr */ /* */ /* ************************************************************************** */ int verificare_caractere(char *str, int nr_piese, int i, int puncte) { int diez; int newline; diez = 0; newline = 0; while (str[i]) { if (str[i] != '.' && str[i] != '#' && str[i] != '\n') return (0); if (str[i] == '.') puncte++; if (str[i] == '#') diez++; if (str[i] == '\n') newline++; i++; } if (puncte != 12 * nr_piese) return (0); if (diez != 4 * nr_piese) return (0); if (newline != 4 * nr_piese + nr_piese - 1) return (0); return (1); } int verificare_conexiuni(char *str, int i, int index_piesa, int conex) { if (str[i + 1] == '#') conex++; if (str[i - 1] == '#') conex++; if (str[i - 5] == '#' && index_piesa > 3) conex++; if (str[i + 5] == '#' && index_piesa < 13) conex++; return (conex); } int validare_piese(char *str) { int i; int conex; int index_piesa; i = 0; conex = 0; index_piesa = 0; while (str[i]) { if (str[i] != '\n') index_piesa++; if (str[i] == '#') conex = verificare_conexiuni(str, i, index_piesa, conex); if (index_piesa == 16) { if (conex != 6 && conex != 8) return (0); if (str[i + 1] != '\n') return (0); index_piesa = 0; conex = 0; } i++; } return (1); } <file_sep>/includes/fillit.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: moana <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/24 17:22:50 by moana #+# #+# */ /* Updated: 2018/01/31 16:55:30 by moana ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLIT_H # define FILLIT_H # include <stdio.h> # include <fcntl.h> # include <string.h> # include <stdlib.h> # include <unistd.h> void eroare(void); int nr_piese(char *str); int verificare_caractere(char *str, int nr_piese, int i, int puncte); int verificare_conexiuni(char *str, int i, int index_piesa, int conex); int validare_piese(char *str); char ***get_matrix(char *buf); char **alocare_matrice(int size); char **transform(char *str, int count, int i); void golire_sol(char **sol); char **stergere_solutie(char **sol, int x, int t, int f); void ft_print_mat(char **mat); int verif_pct_linie(char *str); int lungime(char *str); char *ignor_pct(char *str); int tetri_departat(char *str, char c); int first_char(char *str); int verif(char **mat, char *str, int i, int j); char **inserare_solutie(char **mat, char *str, int i, int j); int ft_sqrt(int i); void fillit(char **str, int nr_piese); void ft_putendl(const char *s); void aux(char *str, int k, int j); #endif <file_sep>/srcs/extra1.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* extra1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: moana <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/27 22:56:04 by moana #+# #+# */ /* Updated: 2018/01/31 16:48:24 by moana ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" #include "../libft/libft.h" int lungime(char *str) { int nr; int i; nr = 0; i = 0; while (i < 4) { if (verif_pct_linie(str) == 0) nr++; str = str + 4; i++; } return (nr); } int tetri_departat(char *str, char c) { int mn; int k; int i; i = 0; mn = 3; while (i < 4) { k = 0; while (str[k] != c) k++; if (mn > k) mn = k; str = str + 4; i++; } return (mn); } int first_char(char *str) { int i; i = 0; while (str[i] == '.') i++; return (i % 4); } int verif(char **mat, char *str, int i, int j) { int x; int k; int col; char c; c = str[first_char(str)]; x = ft_strlen(str) / 4; if (j - first_char(str) + tetri_departat(str, c) < 0) return (0); while (x-- > 0) { col = j; k = first_char(str); while (str[k] == c) { if (mat[i][col] != '.') return (0); col++; k++; } str = str + 4; j = j + first_char(str) - first_char(str - 4); i++; } return (1); } char **inserare_solutie(char **mat, char *str, int i, int j) { int k; int x; int col; char c; c = str[first_char(str)]; x = ft_strlen(str) / 4; while (x-- > 0) { col = j; k = first_char(str); while (str[k] == c) { mat[i][col] = c; k++; col++; } str = str + 4; j = j + first_char(str) - first_char(str - 4); i++; } return (mat); } <file_sep>/srcs/fillit.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: moana <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/25 20:40:50 by moana #+# #+# */ /* Updated: 2018/01/31 16:48:26 by moana ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" #include "../libft/libft.h" char **alocare_matrice(int size) { char **mat; int j; int k; j = 0; mat = (char**)malloc(sizeof(char*) * size + 1); mat[size] = NULL; while (j < size) { k = 0; mat[j] = (char*)malloc(sizeof(char) * size + 1); mat[j][size] = '\0'; while (k < size) { mat[j][k] = '.'; k++; } j++; } return (mat); } int ft_sqrt(int i) { int r; r = 0; while (r * r < i) r++; return (r); } int backtracking(char **sol, char **tet, int x, int size) { int i; int j; char str[17]; if (!tet[x]) return (1); ft_strcpy(str, tet[x]); i = -1; while (++i < size) { j = -1; while (++j < size) { if (sol[i][j] == '.' && i + lungime(str) <= size) if (verif(sol, ignor_pct(str), i, j)) { inserare_solutie(sol, ignor_pct(str), i, j); if (backtracking(sol, tet, x + 1, size) == 1) return (1); else stergere_solutie(sol, x, i, 0); } } } return (0); } void fillit(char **str, int nr_piese) { char **solutie; int size; size = ft_sqrt(nr_piese * 4); solutie = alocare_matrice(size); while (backtracking(solutie, str, 0, size) == 0) { size++; golire_sol(solutie); solutie = alocare_matrice(size); } ft_print_mat(solutie); } <file_sep>/srcs/extra.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* extra.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: moana <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/28 01:09:47 by moana #+# #+# */ /* Updated: 2018/01/31 16:32:35 by moana ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" #include "../libft/libft.h" int nr_piese(char *str) { int i; int nr_p; nr_p = 0; i = 0; while (str[i]) { if (str[i] == '\n' && str[i + 1] == '\n') nr_p++; i++; } return (nr_p + 1); } char **transform(char *str, int count, int i) { int j; int k; char **mat; k = 0; count = nr_piese(str); mat = (char**)malloc(sizeof(char*) * (count + 1)); while (++i < count) { mat[i] = (char*)malloc(sizeof(char) * 16 + 1); j = 0; while (j < 16) { if (str[k] != '\n' && str[k] != '.') mat[i][j++] = 'A' + i; if (str[k] != '\n' && str[k] == '.') mat[i][j++] = '.'; k++; aux(str, k, j); } mat[i][16] = '\0'; } mat[i] = NULL; return (mat); } void golire_sol(char **sol) { int i; i = 0; while (sol[i]) { free(sol[i]); i++; } free(sol); } char **stergere_solutie(char **sol, int x, int t, int f) { int i; int j; i = t; while (sol[i]) { j = f; while (sol[i][j]) { if (sol[i][j] == 'A' + x) sol[i][j] = '.'; j++; } i++; } return (sol); } void ft_print_mat(char **mat) { int i; i = 0; while (mat[i]) { ft_putstr(mat[i]); ft_putchar('\n'); i++; } } <file_sep>/README.md # Fillit Resolving a tetriminos puzzle
b7b9b17746f76e37d7fd220091ab911d81784c9a
[ "Markdown", "C" ]
6
C
cvlasin/Fillit
1f7dec9dbae1c1b12fa5c1a9df4d6930f6985e9c
186f43e764527b1eb229517ed21805fecfcdf42a
refs/heads/master
<repo_name>james-yun/firebase-lab<file_sep>/components/DayCalendar.js import * as React from 'react'; import { View, StyleSheet, FlatList } from 'react-native'; import DayDetailsCard from './DayDetailsCard'; import moment from 'moment'; export default function DayCalendar(props) { let firstdate = props.eventsForMonth.length > 0 ? props.eventsForMonth[0].date : moment([2019, 11, 1]); let year = firstdate.year(); //Could optimize by ingnoring event before previous date function padEvents(month, eventsForMonth) { let eventDayMap = []; eventsForMonth.map(event => { eventDayMap[event.date.date() - 1] = event; }); //Get number of days in month let numdays = firstdate.daysInMonth(); for (let i = 0; i < numdays; i++) { if (eventDayMap[i] == undefined) { eventDayMap[i] = { id: i, date: moment([year, month, i + 1]), }; } else { eventDayMap[i].id = i; } } return eventDayMap; } return ( <View style={styles.container}> <FlatList data={padEvents(props.month, props.eventsForMonth)} renderItem={({ item }) => ( <DayDetailsCard id={item.id} pic={item.pic} name={item.name} date={item.date} accepted={item.accepted} /> )} keyExtractor={item => item.id.toString()} /> </View> ); } const styles = StyleSheet.create({ container: { flexGrow:1, justifyContent: 'center', width: '100%', height: '100%', paddingBottom: 10, backgroundColor: 'rgba(255,255,255,0.4)', }, }); <file_sep>/components/DayDetailsCard.js import * as React from 'react'; import { Text, View, StyleSheet, Image } from 'react-native'; export default function InvationCard(props) { let imageBase = 'https://www.cs.virginia.edu/~dgg6b/Mobile/ScrollLabJSON/Images/'; function formatDate(date) { return date.format('h:mm a'); } function headerForCalendar(date){ return date.format('dddd Do MMMM'); } return ( <View style={styles.container}> <Text style={styles.dayHeader}> {headerForCalendar(props.date)} </Text> {props.accepted=== true ? (<View style={styles.topSection}> <View style={{flex:1, flexDirection:'row', alignItems: 'center'}}> <Image style={styles.profileImage} source={{ uri: imageBase + props.pic }} /> <View style={styles.textSection}> <Text>{props.name}</Text> <Text>{formatDate(props.date)}</Text> </View> </View> <View style={{flex:1, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', paddingRight: 10}}> <Image style={{margin: 5}} source={require('../assets/call.png')}/> <Image style={{margin: 5}} source={require('../assets/email.png')}/> </View> </View>): ( <View style={styles.addEventButton}> <Image source={require('../assets/addnewEventButton.png')}/> </View> )} </View> ); } const styles = StyleSheet.create({ container: { justifyContent: 'center', width: '100%', height: 110, }, addEventButton:{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderColor: 'rgba(0,0,0,0.05)', borderWidth: 1, }, dayHeader:{ fontSize: 13, color: '#000000', padding: 15, fontWeight: '500' }, profileImage: { width: 50, height: 50, margin: 10, }, topSection: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%', height: 50, borderColor: 'rgba(0,0,0,0.05)', borderWidth: 1, }, }); <file_sep>/components/MonthCalendar.js import * as React from 'react'; import { Text, View, ScrollView, StyleSheet, TouchableOpacity } from 'react-native'; export default function MonthCalender(props){ return (<View style={styles.container}> <ScrollView horizontal> {props.monthData.map((item, index) => ( <TouchableOpacity key={index} onPress={(()=>props.callBackOnPress(index))}> <Text style={[styles.monthText, props.selectedMonth === index ? {opacity: 1} :{opacity: 0.3} ]}> {item.label} </Text> </TouchableOpacity> ))} </ScrollView> </View> ) } const styles = StyleSheet.create({ container: { flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: "100%", height: 30, marginBottom: 10, }, monthText:{ opacity: 0.3, fontSize: 14, color: "#000000", letterSpacing: 0, paddingLeft: 15, paddingRight: 15, paddingTop: 7 } });<file_sep>/README.md # Scroll Lab Part 2 This is second part of the scroll layout lab. In this section we discuss, overall data architecture. And state. We also discuss how the state will flow, to subcompoents. ## Important Think State First
123eb62ef71368d9f7d4ca234aceae85cb051fa7
[ "JavaScript", "Markdown" ]
4
JavaScript
james-yun/firebase-lab
c50a97f14bab0b8bdcc001a35bb51ea4a5eea89f
2bf57d321e21f2ae5c70dbe8846cab95fd036503
refs/heads/master
<repo_name>jyhi/practice<file_sep>/hanoi.c /* A program to print how Hanoi Tower should be move when "total" disks on it. * Also a practice of recursion. */ # include <stdio.h> void move ( int n, char z1, char z2, char z3 ); int main ( void ) { int total = 0; printf ( "Enter the number of disks in Hanoi Tower: " ); scanf ( "%d", &total ); move ( total, 'A', 'B', 'C' ); return 0; } void move ( int n, char z1, char z2, char z3 ) { if ( n == 1 ) printf ( "%c -> %c\n", z1, z3 ); else { move ( n - 1, z1, z3, z2 ); printf ( "%c -> %c\n", z1, z3 ); move ( n - 1, z2, z1, z3 ); } } <file_sep>/anxn.c /* A practice to calculate T = a0 + a1x^1 + a2x^2 + ... + anx^n */ # include <stdio.h> # include <stdlib.h> /* # include <math.h> */ int main ( void ) { int n = 0, x = 0, *a, t = 0, tmp = 0; puts ( "n x" ); scanf ( "%d %d", &n, &x ); a = ( int * ) calloc ( n + 1, sizeof ( int ) ); printf ( "a[] from 0 to %d\n", n ); for ( tmp = 0; tmp <= n; tmp++ ) scanf ( "%d", &a[tmp] ); /* General algorithm for ( tmp = n; tmp >= 1; tmp-- ) t += a[tmp] * pow ( x, tmp ); t += a[0]; */ /* Qin Jiushao algorithm, also Horner algorithm, the so-called * Tsin ling lung kae fang, has less computation: * N times plus and N times multiple. */ t = a[n]; for ( tmp = ( n - 1 ); tmp >= 0; tmp-- ) t = t * x + a[tmp]; printf ( "%d", t ); return 0; } <file_sep>/aminusb.c /* This is a program to calculate some expressions like: * * 1/3-1/2 * 10/4-2/2 * 3/2-1/2 * * NOTICE: This is a problem in NOIP2010 FCF. * This is an extreme complicated version, for it traverses every expressions and take numbers out. * Actually it can be easier, for using fscanf(fi, "%d/%d-%d/%d", ...) is okay. */ # include <stdio.h> # include <stdlib.h> # include <string.h> # define LENGTH 512 int main ( void ) { /* I think these may be a waste of memory... */ int n = 0, /* First line in *fi */ tmp = 0, /* 1st temp */ stmp = 0, /* 2nd temp */ ttmp = 0, /* 3rd temp */ common = 0, /* Largest common divisor */ c = 1, /* Counter */ f_or_b = 0, /* Front or back? ( enum? BOOL? ) */ sub_pos = 0, /* Position of the subtraction sign */ a1 = 0, a2 = 0, /* The 1st fraction: a1 / a2 */ b1 = 0, b2 = 0, /* The 2nd fraction: b1 / b2 */ t1 = 0, t2 = 0; /* The sum fraction: t1 / t2 */ char **expr = NULL; /* Group to save the expressions */ FILE *fi = fopen ( "aminusb.in", "r" ), /* Input file */ *fo = fopen ( "aminusb.out", "w" ); /* Output file */ fscanf ( fi, "%d", &n ); expr = ( char ** ) calloc ( n, sizeof ( char * ) ); for ( tmp = 0; tmp < n; tmp++ ) expr[tmp] = ( char * ) calloc ( LENGTH, sizeof ( char ) ); for ( tmp = 0; tmp < n; tmp++ ) fscanf ( fi, "%s", expr[tmp] ); /* Oh fsck I should use scanf("%d/%d-%d/%d", ...) */ /* Go You! */ /* Traverse from 1st expression to the last */ for ( tmp = 0; tmp < n; tmp++ ) { /* Traverse from the head of expression to the tail */ for ( stmp = 0, f_or_b = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, t1 = 0, t2 = 0; stmp < strlen ( expr[tmp] ); stmp++ ) { if ( expr[tmp][stmp] == '-' ) { f_or_b = 1; /* Enter the back */ sub_pos = stmp; /* Position of the subtraction sign */ while ( expr[tmp][stmp - 1] != '/' ) /* a2 */ { /* Traverse from an opposite direction to get numbers: * <---- * 10000/19683-1000/6561 * ^ a2 */ a2 += ( ( int ) expr[tmp][stmp - 1] - '0' ) * c; c *= 10; stmp--; } c = 1; stmp = sub_pos; /* Restore the pointer */ } if ( expr[tmp][stmp] == '/' ) { if ( f_or_b == 0 ) { for ( ttmp = stmp - 1; ttmp >= 0; ttmp-- ) /* a1 */ { /* <---- * 10000/19683-1000/6561 * ^ a1 */ a1 += ( ( int ) expr[tmp][ttmp] - '0' ) * c; c *= 10; } c = 1; } else { for ( ttmp = stmp - 1; ttmp > sub_pos; ttmp-- ) /* b1 */ { /* <--- * 10000/19683-1000/6561 * ^ b1 */ b1 += ( ( int ) expr[tmp][ttmp] - '0' ) * c; c *= 10; } c = 1; } } } while ( expr[tmp][stmp - 1] != '/' ) /* b2 */ { /* <--- * 10000/19683-1000/6561 * ^ b2 */ b2 += ( ( int ) expr[tmp][stmp - 1] - '0' ) * c; c *= 10; stmp--; } c = 1; /* Calculate */ if ( a2 != b2 ) { /* 10000 1000 * ----- - ---- * 19683 <=> 6561 * * Reduce the fractions to a common if denominators are not the same */ a1 *= b2; b1 *= a2; a2 *= b2; b2 = a2; } t1 = a1 - b1; t2 = a2; /* Calculate the largest common divisor */ if ( t1 < 0 ) /* Numerator is negative */ { t1 = 0 - t1; for ( stmp = 1; stmp <= t1; stmp++ ) { if ( ( t1 % stmp == 0 ) && ( t2 % stmp == 0 ) ) common = stmp; } t1 = 0 - t1; } else { /* Oh oh I repeat it... */ for ( stmp = 1; stmp <= t1; stmp++ ) { if ( ( t1 % stmp == 0 ) && ( t2 % stmp == 0 ) ) common = stmp; } } /* Reduce the sum fraction to its lowest terms */ if ( common != 0 ) { t1 /= common; t2 /= common; } /* Output. Finally. QAQ */ if ( ( t1 != t2 ) && ( t2 != 1 ) ) { if ( t1 != 0 ) fprintf ( fo, "%d/%d\n", t1, t2 ); else fprintf ( fo, "0\n" ); } else fprintf ( fo, "%d\n", t1 ); } fclose ( fi ); fclose ( fo ); return 0; } <file_sep>/count.c # include <stdio.h> # include <stdlib.h> void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ); int *a; int main ( void ) { int n = 0, c = 0, /* Counter */ tmp = 0; FILE *fi = fopen ( "count.in", "r" ), *fo = fopen ( "count.out", "w" ); fscanf ( fi, "%d", &n ); /* Numbers still remain in stdin */ a = calloc ( n + 1, sizeof ( int ) ); for ( tmp = 0; tmp < n; tmp++ ) fscanf ( fi, "%d", &a[tmp] ); a[n] = 0; /* No over run. */ /* Go You! */ /* Quick Sort */ QuickSort ( 0, n - 1 ); /* Compare */ for ( tmp = 1; tmp <= n; tmp++ ) /* Over run? No. */ { if ( a[tmp] == a[tmp - 1] ) c++; else { /* Print first */ fprintf ( fo, "%d %d\n", a[tmp - 1], c + 1 ); /* The first number */ /* c = 0 */ c = 0; /* Go on */ continue; } } fclose ( fi ); fclose ( fo ); return 0; } void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ) { int temp = 0, i = l, j = r, mid = a[ ( l + r ) / 2 ]; do { while ( a[i] < mid ) i++; while ( a[j] > mid ) j--; if ( i <= j ) { /* Exchange */ temp = a[i]; a[i] = a[j]; a[j] = temp; /* Move pointers */ i++; j--; } } while ( i <= j ); /* Until ^HEAD > ^TAIL */ if ( l < j ) QuickSort ( l, j ); if ( i < r ) QuickSort ( i, r ); } <file_sep>/expr.c # include <stdio.h> # include <stdlib.h> # include <string.h> int main ( void ) { int t = 0, tmp = 0, *num = ( int * ) calloc ( 512, sizeof ( int ) ); char *expr = ( char * ) calloc ( 512, sizeof ( char ) ); FILE *fi = fopen ( "expr.in", "r" ), *fo = fopen ( "expr.out", "w" ); fscanf ( fi, "%s", expr ); for ( tmp = 0; tmp < strlen ( expr ); tmp++ ) { if ( ( expr[tmp] >= '0' ) && ( expr[tmp] <= '9' ) ) num[tmp] = ( int ) expr[tmp] - '0'; } for ( tmp = 0; tmp < strlen ( expr ); tmp++ ) { if ( expr[tmp] == '*' ) { num[tmp + 1] = num[tmp - 1] * num[tmp + 1]; num[tmp - 1] = 0; } } for ( tmp = 0; tmp < strlen ( expr ); tmp++ ) { if ( expr[tmp] == '+' ) { num[tmp + 1] = num[tmp - 1] + num[tmp + 1]; num[tmp - 1] = 0; } } for ( tmp = 0; tmp < strlen ( expr ); tmp++ ) t += num[tmp]; fprintf ( fo, "%d", t ); fclose ( fi ); fclose ( fo ); return 0; } <file_sep>/parallelogram.c /* A program which print a parallelogram like: * @@@@@ * @@@@@ * @@@@@ * @@@@@ * @@@@@ * Also a simple practice of "for". */ # include <stdio.h> int main ( void ) { int l = 0, /* Line */ w = 0, /* Width */ i = 0, tmp = 0; /* Temp */ printf ( "Input the height of parallelogram: " ); scanf ( "%d", &l ); printf ( "Input the width of parallelogram: " ); scanf ( "%d", &w ); for ( i = 1; i <= l; i++ ) { for ( tmp = l; tmp >= i; tmp-- ) printf ( " " ); for ( tmp = 1; tmp <= w; tmp++ ) printf ( "@" ); printf ( "\n" ); } return 0; } <file_sep>/block.c # include <stdio.h> int main ( void ) { int n = 0, c = 0, /* Counter */ *blks = NULL, s = 0, e = 0, /* Start && end */ tmp = 0, stmp = 0; FILE *fi = fopen ( "block.in", "r" ), *fo = fopen ( "block.out", "w" ); fscanf ( fi, "%d", &n ); blks = ( int * ) calloc ( n, sizeof ( int ) ); for ( tmp = 0; tmp < n; tmp++ ) fscanf ( fi, "%d", &blks[tmp] ); do { for ( tmp = 0; tmp < n; tmp++ ) { if ( blks[tmp] != 0 ) { for ( stmp = tmp; stmp < n; stmp++ ) { if ( blks[stmp] == 0 ) c++; } } } if ( blks[n - 1] != 0 ) c++; for ( tmp = 0; tmp < n; tmp++ ) blks[tmp] -= 1; } while ( ... ); return 0; } <file_sep>/convert.c # include <stdio.h> void convert ( unsigned long n, unsigned long k, unsigned long s ); int main ( void ) { unsigned long n = 0, /* Number to be converted */ k = 0, /* */ s = 0; scanf ( "%lu %lu", &n, &k ); convert ( n, k, s ); return 0; } void convert ( unsigned long n, unsigned long k, unsigned long s ) { s = n % k; if ( n / k != 0 ) convert ( n / k, k, s ); printf ( "%lu", s ); } <file_sep>/waiting.c /* A quick sort practice * Although there is a C standard function: * * void qsort ( void *base, int nelem, int width, int ( *fcmp ) ( const void *, const void * ) ); * * I won't use it for NOIP doesn't allow anybody to use it. (But NOI does) */ # include <stdio.h> # include <stdlib.h> void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ); int *w; /* Waiting time */ int main ( void ) { int n = 0, /* People */ tmp = 0; puts ( "n" ); scanf ( "%d", &n ); w = calloc ( n, sizeof ( int ) ); printf ( "w[] from 1 to %d\n", n ); for ( tmp = 0; tmp < n; tmp++ ) scanf ( "%d", &w[tmp] ); /* Go You! */ QuickSort ( 0, n - 1 ); /* Output */ for ( tmp = 0; tmp < n; tmp++ ) printf ( "%-6d", w[tmp] ); return 0; } void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ) { int temp = 0, i = l, j = r, mid = w[ ( l + r ) / 2 ]; do { while ( w[i] < mid ) i++; while ( w[j] > mid ) j--; if ( i <= j ) { /* Exchange */ temp = w[i]; w[i] = w[j]; w[j] = temp; /* Move pointers */ i++; j--; } } while ( i <= j ); /* Until ^HEAD > ^TAIL */ if ( l < j ) QuickSort ( l, j ); if ( i < r ) QuickSort ( i, r ); } <file_sep>/rps.c /* rps.c: CCF NOIP 2014 day.1 */ # include <stdio.h> # include <stdlib.h> int main ( void ) { int n = 0, na = 0, nb = 0, /* N, NA, NB */ tmp = 0, /* TEMP use */ sa = 0, sb = 0, /* Score of A & B */ *pa = NULL, *pb = NULL; /* Cycle of Player A & B */ /* FILE *fi = fopen ( "rps.in" , "r" ), *fo = fopen ( "rps.out", "w" ); */ //fscanf ( fi, "%d %d %d", &n, &na, &nb ); scanf ( "%d %d %d", &n, &na, &nb ); pa = calloc ( na, sizeof ( int ) ); pb = calloc ( nb, sizeof ( int ) ); for ( tmp = 0; tmp < na; tmp++ ) //fscanf ( fi, "%d", &pa[tmp] ); /* Player A reading */ scanf ( "%d", &pa[tmp] ); for ( tmp = 0; tmp < nb; tmp++ ) //fscanf ( fi, "%d", &pb[tmp] ); /* Player B reading */ scanf ( "%d", &pb[tmp] ); /* Go You! */ int a = 0, b = 0; /* Array subscript for pa and pb */ for ( tmp = 0; tmp < n; a++, b++, tmp++ ) { /* First check if tmp>na or tmp>nb to prevent overflow */ if ( a >= na ) a = 0; if ( b >= nb ) b = 0; if ( pa[a] != pb[b] ) { switch ( pa[a] ) { case 0: if ( ( pb[b] == 2 ) || ( pb[b] == 3 ) ) /* A win */ sa += 1; else /* B win */ sb += 1; break; case 1: if ( ( pb[b] == 0 ) || ( pb[b] == 3 ) ) /* A win */ sa += 1; else /* B win */ sb += 1; break; case 2: if ( ( pb[b] == 1 ) || ( pb[b] == 4 ) ) /* A win */ sa += 1; else /* B win */ sb += 1; break; case 3: if ( ( pb[b] == 2 ) || ( pb[b] == 4 ) ) /* A win */ sa += 1; else /* B win */ sb += 1; break; case 4: if ( ( pb[b] == 0 ) || ( pb[b] == 1 ) ) /* A win */ sa += 1; else /* B win */ sb += 1; break; } /* switch ( pa[a] ) */ } /* if ( pa[a] != pb[b] ) */ /* No need to do anything if they planish. */ } /* Output the result */ //fprintf ( fo, "%d %d", sa, sb ); printf ( "%d %d", sa, sb ); /* fclose ( fi ); fclose ( fo ); */ return 0; } <file_sep>/aminusb-1.c /* aminusb.c revised version 1 (aminusb-1.c) * This is a program to calculate some expressions like: * * 1/3-1/2 * 10/4-2/2 * 3/2-1/2 * * NOTICE: This is a problem in NOIP2010 FCF. * This is a simple version, for it uses fscanf to take numbers out, and uses Euclidean algorithm to calculate greatest common divisor. * See also: aminusb.c ("Extreme complicated version") */ # include <stdio.h> # include <stdlib.h> void gcd ( long *output, long n1, long n2 ); int main ( void ) { int n = 0; /* First line in *fi */ long common = 0; /* Largest common divisor */ FILE *fi = fopen ( "aminusb.in", "r" ), /* Input file */ *fo = fopen ( "aminusb.out", "w" ); /* Output file */ fscanf ( fi, "%d", &n ); for ( long tmp = 0, a1 = 0, a2 = 0, /* The 1st fraction: a1 / a2 */ b1 = 0, b2 = 0, /* The 2nd fraction: b1 / b2 */ t1 = 0, t2 = 0; /* The sum fraction: t1 / t2 */ tmp < n; tmp++ ) { /* Input */ fscanf ( fi, "%ld/%ld-%ld/%ld", &a1, &a2, &b1, &b2 ); /* Calculate */ if ( a2 != b2 ) { /* 10000 1000 * ----- - ---- * 19683 <=> 6561 * * Reduce the fractions to a common if denominators are not the same */ a1 *= b2; b1 *= a2; a2 *= b2; /* b2 = a2; */ } t1 = a1 - b1; t2 = a2; /* Calculate the greatest common divisor */ gcd ( &common, t1, t2 ); /* Reduce the sum fraction to its lowest terms */ if ( common != 0 ) { t1 /= common; t2 /= common; } /* Output. Finally. QAQ */ if ( ( t1 != t2 ) && ( t2 != 1 ) ) { if ( t1 != 0 ) fprintf ( fo, "%ld/%ld\n", t1, t2 ); else fprintf ( fo, "0\n" ); } else fprintf ( fo, "%ld\n", t1 ); } fclose ( fi ); fclose ( fo ); return 0; } void gcd ( long *output, long n1, long n2 ) { if ( n1 < 0 ) n1 = -n1; if ( n2 < 0 ) n2 = -n2; do { if ( n1 > n2 ) n1 = n1 - n2; else n2 = n2 - n1; } while ( ( n2 != 0 ) && ( n1 != 0 ) ); if ( n2 == 0 ) *output = n1; else *output = n2; } <file_sep>/yh.c /* A program to output 10 lines' Pascal's triangle. * I may improve it to let it output any lines of Pascal's triangle. */ # include <stdio.h> # include <string.h> # include <stdlib.h> int main ( void ) { int i = 1, /* line */ j = 1, /* col */ yh[11][11], /* array */ tmp = 0; memset ( yh, 0, sizeof ( yh ) ); yh[1][1] = 1; for ( i = 2; i <= 10; i++ ) { yh[i][1] = 1; yh[i][i] = 1; for ( j = 2; j < i; j++ ) yh[i][j] = yh[i - 1][j - 1] + yh[i - 1][j]; } for ( i = 1; i <= 10; i++ ) { for ( tmp = 1; tmp <= 30 - i * 3; tmp++ ) printf ( " " ); for ( j = 1; j <= i; j++ ) printf ( "%6d", yh[i][j] ); printf ( "\n" ); } return 0; } <file_sep>/expr-old.c # include <stdio.h> # include <stdlib.h> # include <string.h> # define LENGTH 512 # define op_left_assoc( c ) ( c == '+' || c == '-' || c == '/' || c == '*' || c == '%' ) # define is_operator( c ) ( c == '+' || c == '-' || c == '/' || c == '*' || c == '!' || c == '%' || c == '=' ) # define is_function( c ) ( c >= 'A' && c <= 'Z' ) # define is_ident( c ) ( ( c >= '0' && c <= '9' ) || ( c >= 'a' && c <= 'z' ) ) int opr_preced ( const char c ); typedef struct /* For operators */ { int top; char *a; } stack; int main ( void ) { stack opr = { 0, NULL }, /* Operators */ suf = { 0, NULL }; /* Suffix notation */ char *s = ( char * ) calloc ( LENGTH, sizeof ( char ) ), /* Input */ *outq = ( char * ) calloc ( LENGTH, sizeof ( char ) ); /* Output Queue */ int tmp = 0, p = 0, /* "Pointer" for *outq */ t = 0; /* Total */ puts ( "Input an infix notation:" ); scanf ( "%s", s ); opr.a = ( char * ) calloc ( LENGTH, sizeof ( char ) ); /* Go You!*/ for ( tmp = 0; tmp < strlen ( s ); tmp++ ) { if ( is_ident ( s[tmp] ) ) { outq[p] = s[tmp]; p++; } else if ( is_operator ( s[tmp] ) ) { if ( is_operator ( opr.a[opr.top] ) && opr_preced ( opr.a[opr.top] ) > s[tmp] ) { /* Pop */ outq[p] = opr.a[opr.top - 1]; p++; opr.top--; } else { opr.a[opr.top] = s[tmp]; opr.top++; } } /* 先不考虑括号和函数什么的 */ } /* Put the operators inside stack into output queue */ for ( tmp = opr.top; tmp >= 0; tmp-- ) { outq[p] = opr.a[opr.top - 1]; p++; opr.top--; } /* Calculate */ p = 0; suf.a = ( char * ) calloc ( LENGTH, sizeof ( char ) ); for ( tmp = 0; tmp < strlen ( outq ); tmp++ ) { if ( is_ident ( outq[p] ) ) { /* Push */ suf.a[suf.top] = outq[p]; p++; suf.top++; } else if ( is_operator ( outq[p] ) ) { /* TODO: God knows whether there are 2 numbers or not... */ switch ( outq[p] ) { case '+': t = suf.a[suf.top - 1] + suf.a[suf.top - 2]; break; case '-': break; /* ... */ case '*': t = suf.a[suf.top - 1] * suf.a[suf.top - 2]; break; case '/': break; /* ... */ } } } printf ( "%d", t ); return 0; } int opr_preced ( const char c ) { switch ( c ) { case '!': return 4; case '*': case '/': case '%': return 3; case '+': case '-': return 2; case '=': return 1; } return 0; }<file_sep>/fruit.c # include <stdio.h> # include <stdlib.h> void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ); int *a, /* Input */ *b; /* Output */ int main ( void ) { int n = 0, tmp = 0; FILE *fi = fopen ( "fruit.in", "r" ), *fo = fopen ( "fruit.out", "w" ); fscanf ( fi, "%d", &n ); a = calloc ( n, sizeof ( int ) ); b = calloc ( n, sizeof ( int ) ); for ( tmp = 0; tmp <= n; tmp++ ) fscanf ( fi, "%d", &a[tmp] ); /* Go You! */ /* Quick sort (fsck >_<) */ QuickSort ( 0, n - 1 ); /* Plus */ b[0] = a[0] + a[1]; for ( tmp = 1; tmp <= ( n - 2 ); tmp++ ) /* NOTICE: "n" will be n but not n-1 when over */ b[tmp] = b[tmp - 1] + a[tmp + 1]; /* b[n - 1] will be the total */ for ( tmp = 0; tmp <= ( n - 2 ); tmp++ ) b[n - 1] += b[tmp]; /* Print ^o^ */ fprintf ( fo, "%u", b[n - 1] ); fclose ( fi ); fclose ( fo ); return 0; } void QuickSort ( int l, /* ^HEAD */ int r /* ^TAIL */ ) { int temp = 0, i = l, j = r, mid = a[ ( l + r ) / 2 ]; do { while ( a[i] < mid ) i++; while ( a[j] > mid ) j--; if ( i <= j ) { /* Exchange */ temp = a[i]; a[i] = a[j]; a[j] = temp; /* Move pointers */ i++; j--; } } while ( i <= j ); /* Until ^HEAD > ^TAIL */ if ( l < j ) QuickSort ( l, j ); if ( i < r ) QuickSort ( i, r ); } <file_sep>/multiply.c # include <stdio.h> int main ( void ) { int i = 1, /* line */ j = 1, /* col */ tmp = 1; for ( i = 1; i <= 9; i++ ) { for ( j = i; j <= 9; j++ ) printf ( "%d*%d=%-2d ", i, j, i * j ); printf ( "\n" ); for ( tmp = 1; tmp <= i ; tmp++ ) printf ( " " ); } return 0; } <file_sep>/rhombus.c # include <stdio.h> # include <stdlib.h> # include <string.h> void fill ( int l, int c, int n ); void print ( int l, int c, int n ); int a[31][31]; /* Data */ int main ( void ) { int l = 0, /* 行指示 line */ c = 0, /* 列指示 col*/ n = 0; /* N */ memset ( a, 0, sizeof ( a ) ); /* Initialize */ scanf ( "%d", &n ); fill ( l, c, n ); print ( l, c, n ); return 0; } void fill ( int l, int c, int n ) { int tmp = 2; /* 临时以及顺序数生成 */ a[1][n] = 1; for ( l = 2; l <= n; l++ ) /* 上部分 */ { if ( l % 2 == 0 ) { /* 逆序 */ for ( c = n; c >= ( n + 1 - l ); c--, tmp++ ) a[l][c] = tmp; } else { /* 正序 */ for ( c = ( n + 1 - l ); c <= n; c++, tmp++ ) a[l][c] = tmp; } } for ( l = ( n + 1 ); l <= ( 2 * n - 1 ); l++ ) /* 下部分 */ { if ( l % 2 == 0 ) { /* 逆序 */ for ( c = n; c >= ( l - n + 1 ); c--, tmp++ ) a[l][c] = tmp; } else { /* 正序 */ for ( c = ( l - n + 1 ); c <= n; c++, tmp++ ) a[l][c] = tmp; } } } void print ( int l, int c, int n ) { int tmp = 1; /* 临时以及顺序数生成 */ for ( l = 1; l <= n; l++ ) /* 上部分 */ { for ( tmp = 1; tmp <= n*3-l*3; tmp++ ) printf ( " " ); for ( c = n; c >= ( n - l + 1 ); c-- ) printf ( "%-6d", a[l][c] ); printf ( "\n" ); } for ( l = ( n + 1 ); l <= ( 2 * n - 1 ); l++ ) /* 下部分 */ { for ( tmp = 1; tmp <= l*3-n*3; tmp++ ) printf ( " " ); for ( c = n; c >= ( l - n + 1 ); c-- ) printf ( "%-6d", a[l][c] ); printf ( "\n" ); } } <file_sep>/common.c /* Largest common divisor & Minimum common multiple */ # include <stdio.h> int lcdiv ( int n, int m, int i ); int mcmul ( int n, int m, int j ); int main ( void ) { int n = 0, /* Input 1 */ m = 0, /* Input 2 */ i = 0, /* Largest common divisor */ j = 0; /* Minimum common multiple */ scanf ( "%d %d", &n, &m ); i = lcdiv ( n, m, i ); j = mcmul ( n, m, j ); printf ( "Largest common divisor: %d\nMinimum common multiple: %d", i, j ); return 0; } int lcdiv ( int n, int m, int i ) { /* int tmp = 0; for ( tmp = 1; tmp <= n; tmp++ ) if ( ( n % tmp == 0 ) && ( m % tmp == 0 ) ) i = tmp; return i; */ do { if ( n > m ) n = n - m; else m = m - n; } while ( ( m != 0 ) && ( n != 0 ) ); if ( m == 0 ) return n; else return m; } int mcmul ( int n, int m, int j ) { int tmp = 0; for ( tmp = n;; tmp++ ) { if ( ( tmp % n == 0 ) && ( tmp % m == 0 ) ) { j = tmp; break; } } return j; } <file_sep>/seven.c # include <stdio.h> # include <stdlib.h> int main ( void ) { int n = 0, tmp = 0; scanf ( "%d", &n ); for ( tmp = 0; tmp < n; tmp++ ) { if ( ( tmp % 7 == 0 ) || ( tmp % 10 == 7 ) || ( tmp / 10 == 7 ) ) continue; else printf ( "%5d", tmp ); } return 0; }
b40e26c051581dc34efd9bb070d26b9e235281ec
[ "C" ]
18
C
jyhi/practice
63302c73afbdc916c16a3f36ecfefe3effa39707
ea361aecde7b8e75d085f75f469a83de9e4063c7
refs/heads/master
<repo_name>sgaikwad/StorePriceCalculator<file_sep>/PriceCalculator/Factory/DiscountFactory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor.Factory { public class DiscountFactory { public static IPriceDiscountFactory GetDiscountFactory(string factoryName) { switch (factoryName) { case "UnitBasedDiscount": return new UnitBasedDiscount(); case "FlatDiscount": return new FlatDiscount(); default: throw new Exception("Invalid DiscountType"); } } } } <file_sep>/PriceCalculator/Factory/IPriceDiscountFactory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Entities; namespace PriceCalcutor { public interface IPriceDiscountFactory { Product CalculatePrice(string item, string discountValue); } } <file_sep>/PriceCalculator/Strategies/ItemLevelDiscountStrategy.cs using System; using System.Collections.Generic; using System.Linq; using PriceCalcutor.Entities; using PriceCalcutor.Factory; namespace PriceCalcutor { public class ItemLevelDiscountStrategy : IDiscountStrategy { public List<Product> GetDiscount(string discountItems) { var products = new List<Product>(); var itemList = discountItems.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); var discountList = Helper.GetItemDiscount(); Product product = null; foreach (var item in itemList) { string discountValue; if (discountList.TryGetValue(item, out discountValue)) { int configuredPrice; int.TryParse(discountValue, out configuredPrice); if (configuredPrice > 0) { var factory = DiscountFactory.GetDiscountFactory("FlatDiscount"); product = factory.CalculatePrice(item.ToLower(), discountValue); } else { var factory = DiscountFactory.GetDiscountFactory("UnitBasedDiscount"); product = factory.CalculatePrice(item.ToLower(), discountValue); } } products.Add(product); } return products; } } } <file_sep>/PriceCalculator/Entities/Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor.Entities { public class Product { public string ProductName { get; set; } public double TotalRate { get; set; } public double BaseRate { get; set; } public string Discount { get; set; } } } <file_sep>/PriceCalculator/Strategies/SpecialDiscountStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor { public class SpecialDiscountStrategy: IDiscountStrategy { public string GetDiscount(string discountItems) { throw new NotImplementedException(); } List<Entities.Product> IDiscountStrategy.GetDiscount(string discountItems) { throw new NotImplementedException(); } } } <file_sep>/PriceCalculator/Helper.cs using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor { public sealed class Helper { public static Dictionary<string, double> GetItemPriceList() { var itemPrice = new Dictionary<string, double>(); var itemsList = ConfigurationManager.AppSettings["ItemPrice"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (itemsList.Count > 0) { foreach (var item in itemsList) { var itemDetail = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (itemDetail.Length > 0) { itemPrice.Add(itemDetail[0], Convert.ToDouble(itemDetail[1])); } } } return itemPrice; } public static Dictionary<string, string> GetItemDiscount() { var itemDiscount = new Dictionary<string, string>(); var itemsList = ConfigurationManager.AppSettings["ItemDiscount"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (itemsList.Count > 0) { foreach (var item in itemsList) { var itemDetail = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (itemDetail.Length > 0) { itemDiscount.Add(itemDetail[0], itemDetail[1]); } } } return itemDiscount; } public static Dictionary<string, string> GetWeekDayDiscount() { var itemDiscount = new Dictionary<string, string>(); var itemsList = ConfigurationManager.AppSettings["WeekDayDiscount"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (itemsList.Count > 0) { foreach (var item in itemsList) { var itemDetail = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (itemDetail.Length > 0) { itemDiscount.Add(itemDetail[0], itemDetail[1]); } } } return itemDiscount; } } } <file_sep>/PriceCalculator/Interface/ISpecialDiscountStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor.Interface { public interface ISpecialDiscountStrategy { double GetSpecialDiscountBill(double totalBillAmount); } } <file_sep>/PriceCalculator/Program.cs using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Context; using PriceCalcutor.Strategies; namespace PriceCalcutor { class Program { static void Main(string[] args) { Console.Write("Enter Item to be purschased(comma separated): "); string name = Console.ReadLine(); if (string.IsNullOrEmpty(name) == false) { var discountContext = new DiscountContext(new ItemLevelDiscountStrategy()); var products = discountContext.GetDiscount(name); var totalBillAmount = GetTotalBillAmount(products); var specialDiscountContext = new SpecialDiscountContext(new WeekDayDiscountStrategy()); var totalAmount = specialDiscountContext.GetTotalAmount(totalBillAmount); DispalyBill(totalAmount, totalBillAmount); } else { Console.WriteLine("Please enter valid items"); Console.ReadLine(); } } private static void DispalyBill(double totalAmount, double totalBillAmount) { string billDate = string.Format("{0}:{1}", "Bill Date", DateTime.Now.ToString("yyyy-MM-dd")); Console.WriteLine(billDate); string resultTotalAmount = string.Format("{0}:{1}", "Total Bill Amount", totalAmount); Console.WriteLine(resultTotalAmount); string resultTotalDiscountAmount = string.Format("{0}:{1}", "Total Amount Saved", totalBillAmount - totalAmount); Console.WriteLine(resultTotalDiscountAmount); Console.ReadLine(); } private static double GetTotalBillAmount(List<Entities.Product> products) { if (products != null && products.Count > 0) { return products.Sum(x => x != null ? x.TotalRate : 0); } return 0; } } } <file_sep>/PriceCalculator/Context/DiscountContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Entities; namespace PriceCalcutor { public class DiscountContext { private readonly IDiscountStrategy _discountStrategy; public DiscountContext(IDiscountStrategy discountStrategy) { _discountStrategy = discountStrategy; } public List<Product> GetDiscount(string item) { return _discountStrategy.GetDiscount(item); } } } <file_sep>/PriceCalculator/Factory/FlatDiscount.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Entities; namespace PriceCalcutor { public class FlatDiscount : IPriceDiscountFactory { public Entities.Product CalculatePrice(string item, string discountValue) { var items = Helper.GetItemPriceList(); double itemPrice; Product product = null; if (items.TryGetValue(item, out itemPrice)) { int val = Convert.ToInt32(discountValue); double discountedPrice = (itemPrice/100)*val; double totalPrice = itemPrice - discountedPrice; product = new Product { ProductName = item, TotalRate = totalPrice, Discount = discountValue, BaseRate = itemPrice }; } return product; } } } <file_sep>/PriceCalculator/Strategies/WeekDayDiscountStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Interface; namespace PriceCalcutor.Strategies { public class WeekDayDiscountStrategy : ISpecialDiscountStrategy { public double GetSpecialDiscountBill(double totalBillAmount) { var weekDayDiscountList = Helper.GetWeekDayDiscount(); string weekDayDiscount; weekDayDiscountList.TryGetValue(DateTime.Now.DayOfWeek.ToString().ToLower(), out weekDayDiscount); int configuredPrice; int.TryParse(weekDayDiscount, out configuredPrice); double totalPrice; if (configuredPrice > 0) { double discountedPrice = (totalBillAmount / 100) * configuredPrice; totalPrice = totalBillAmount - discountedPrice; } else { totalPrice = totalBillAmount; } return totalPrice; } } } <file_sep>/PriceCalculator/Context/SpecialDiscountContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Interface; namespace PriceCalcutor.Context { public class SpecialDiscountContext { private readonly ISpecialDiscountStrategy _specialDiscountStrategy = null; public SpecialDiscountContext(ISpecialDiscountStrategy specialDiscountStrategy) { _specialDiscountStrategy = specialDiscountStrategy; } public double GetTotalAmount(double totalBill) { return _specialDiscountStrategy.GetSpecialDiscountBill(totalBill); } } } <file_sep>/PriceCalculator/Factory/IDiscountFactory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PriceCalcutor.Factory { interface IDiscountFactory { } } <file_sep>/PriceCalculator/Factory/UnitBasedDiscount.cs using System; using PriceCalcutor.Entities; namespace PriceCalcutor { public class UnitBasedDiscount : IPriceDiscountFactory { public Product CalculatePrice(string item, string discountValue) { var items = Helper.GetItemPriceList(); double itemPrice; Product product = null; if (items.TryGetValue(item, out itemPrice)) { product = new Product { ProductName = item, TotalRate = itemPrice, Discount = discountValue, BaseRate = itemPrice }; } return product; } } } <file_sep>/PriceCalculator/Interface/IDiscountStrategy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PriceCalcutor.Entities; namespace PriceCalcutor { public interface IDiscountStrategy { List<Product> GetDiscount(string discountItems); } }
b8e8d96bad47c5e4efb877d535b1bc19dd42f7c1
[ "C#" ]
15
C#
sgaikwad/StorePriceCalculator
9fe86fb5f9a8db46d5a46b8aa6bc7f5150fd591c
043c6f9577ee2fe991631eff0c03767eeaabde68
refs/heads/master
<repo_name>renium/Python<file_sep>/MacTestGit/MacTest.py from builtins import print __author__ = 'rene' import random import math a = 1; b = 2; print (a+b*b); Ottoei = "Hello Ottoei, pycharm!"; print (Ottoei);
be6f47022815c2aa0a125d3106d134c319e517f1
[ "Python" ]
1
Python
renium/Python
3a1fb80afe8f089016d9775c88524171ba5ea9b5
7662a8e975016b8c6ce2653388837fc1f252adea
refs/heads/master
<repo_name>corcor27/pycbc-<file_sep>/inference.ini [variable_args] ; waveform parameters that will vary in MCMC tc = mchirp = q = spin1_a = spin1_azimuthal = spin1_polar = spin2_a = spin2_azimuthal = spin2_polar = distance = coa_phase = inclination = polarization = ra = dec = [static_args] ; waveform parameters that will not change in MCMC approximant = IMRPhenomPv2 f_lower = 19.0 [prior-tc] ; coalescence time prior name = uniform min-tc = 1126259461.8 max-tc = 1126259462.2 [prior-mchirp] name = uniform min-mchirp = 7. max-mchirp = 40. [prior-q] name = uniform min-q = 1. max-q = 5. [prior-spin1_a] name = uniform min-spin1_a = 0.0 max-spin1_a = 0.9 [prior-spin1_polar+spin1_azimuthal] name = uniform_solidangle polar-angle = spin1_polar azimuthal-angle = spin1_azimuthal [prior-spin2_a] name = uniform min-spin2_a = 0.0 max-spin2_a = 0.9 [prior-spin2_polar+spin2_azimuthal] name = uniform_solidangle polar-angle = spin2_polar azimuthal-angle = spin2_azimuthal [prior-distance] ; distance prior name = uniform min-distance = 10 max-distance = 1000 [prior-coa_phase] ; coalescence phase prior name = uniform_angle [prior-inclination] ; inclination prior name = sin_angle [prior-ra+dec] ; sky position prior name = uniform_sky [prior-polarization] ; polarization prior name = uniform_angle <file_sep>/pycbc_inference.sh # injection parameters TRIGGER_TIME=1126259462.0 INJ_PATH=injection.xml.gz # sampler parameters CONFIG_PATH=inference.ini OUTPUT_PATH=inference.hdf SEGLEN=8 PSD_INVERSE_LENGTH=4 IFOS="H1 L1" STRAIN="H1:aLIGOZeroDetHighPower L1:aLIGOZeroDetHighPower" SAMPLE_RATE=2048 F_MIN=30. N_UPDATE=500 N_WALKERS=5000 N_ITERATIONS=12000 N_CHECKPOINT=1000 PROCESSING_SCHEME=cpu # the following sets the number of cores to use; adjust as needed to # your computer's capabilities NPROCS=12 # get coalescence time as an integer TRIGGER_TIME_INT=${TRIGGER_TIME%.*} # start and end time of data to read in GPS_START_TIME=$((${TRIGGER_TIME_INT} - ${SEGLEN})) GPS_END_TIME=$((${TRIGGER_TIME_INT} + ${SEGLEN})) # run sampler # specifies the number of threads for OpenMP # Running with OMP_NUM_THREADS=1 stops lalsimulation # to spawn multiple jobs that would otherwise be used # by pycbc_inference and cause a reduced runtime. OMP_NUM_THREADS=1 \ pycbc_inference --verbose \ --seed 12 \ --instruments ${IFOS} \ --gps-start-time ${GPS_START_TIME} \ --gps-end-time ${GPS_END_TIME} \ --psd-model ${STRAIN} \ --psd-inverse-length ${PSD_INVERSE_LENGTH} \ --fake-strain ${STRAIN} \ --fake-strain-seed 44 \ --sample-rate ${SAMPLE_RATE} \ --low-frequency-cutoff ${F_MIN} \ --channel-name H1:FOOBAR L1:FOOBAR \ --injection-file ${INJ_PATH} \ --config-file ${CONFIG_PATH} \ --output-file ${OUTPUT_PATH} \ --processing-scheme ${PROCESSING_SCHEME} \ --sampler kombine \ --skip-burn-in \ --update-interval ${N_UPDATE} \ --likelihood-evaluator gaussian \ --nwalkers ${N_WALKERS} \ --niterations ${N_ITERATIONS} \ --checkpoint-interval ${N_CHECKPOINT} \ --checkpoint-fast \ --nprocesses ${NPROCS} \ --save-strain \ --save-psd \ --save-stilde \ --force
804b0eba7c86586cbf424c5865c7fc5a66368b0b
[ "Shell", "INI" ]
2
INI
corcor27/pycbc-
df4728ffc9eea4c32cb8d67e7ba7292781c6c377
9b56e574009fccc3c67810fd9ae5eb9df41118ca
refs/heads/master
<repo_name>flouis1/conffile<file_sep>/config_vim_plugins.sh #bin/bash echo "install vim" git clone https://github.com/vim/vim mv vim .vim echo "install pathogen" mkdir -p .vim/autoload curl -LSso .vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim echo "yeahhh cloning your vim pugins" echo "enter in ~/conffile/.vim/bundle folder" mkdir -p .vim/bundle cd .vim/bundle LINK=https://github.com/junegunn/vader.vim.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/vim-airline/vim-airline-themes EXTEN=${LINK##*/} if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/LaTeX-Box-Team/LaTeX-Box.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/scrooloose/nerdtree.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/vim-airline/vim-airline EXTEN=${LINK##*/} if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/edkolev/tmuxline.vim EXTEN=${LINK##*/} if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/vim-syntastic/syntastic.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/tpope/vim-sensible.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ LINK=https://github.com/xuhdev/vim-latex-live-preview.git EXTEN=$(basename ${LINK##*/} .git) if [ -e "$EXTEN" ]; then cd $EXTEN && git pull origin master && cd - ; else git clone --depth=1 $LINK; fi &&\ echo "clone done" echo "Add helptages" find . -name 'doc' -exec vim -u NONE -c 'helptags '{} -c q \; echo "done" cd ~/conffile <file_sep>/cfg_copy.sh # /bin/bash #first version cd ~/ ln -s ~/conffile/.tmux.conf .tmux.conf ln -s ~/conffile/.viminfo .viminfo ln -s ~/conffile/.vimrc .vimrc ln -sr ~/conffile/vim vim cd - <file_sep>/README.txt 26/12/17 This file will contains main dotfiles. Use symlinks to clone these files in home dir
194d748985e0c1511f8dc7aa585324febc71d6c7
[ "Text", "Shell" ]
3
Shell
flouis1/conffile
802ddc1c706d3ffd325fb60c2eb1241ad26b4377
2ac3a4aa759994c77f86c994102cc2b9f37e4628
refs/heads/main
<repo_name>deepanshuyadav22/turtle<file_sep>/Ellipse.py import turtle t = turtle.Turtle() t.seth(-45) #t.seth(45) r = 100 for i in range(0,2): t.circle(r, 90) t.circle(r // 2, 90) turtle.done() <file_sep>/Rhombus.py import turtle t = turtle.Turtle() t.left(135) for i in range(0,4): t.forward(100) t.left(90) turtle.done() <file_sep>/Line.py import turtle t = turtle.Turtle() t.forward(100) turtle.done() <file_sep>/Triangle.py import turtle t = turtle.Turtle() for i in range(0,3): t.forward(100) t.left(120) #t.right(120) turtle.done() <file_sep>/Circle.py import turtle t = turtle.Turtle() t.circle(50) turtle.done()
dca67a6015f56a81aa2e8b7ae277c1e28cf31d89
[ "Python" ]
5
Python
deepanshuyadav22/turtle
f2786eb92482aad14bdc06c05096a138c7d07cd7
b70590908b23d5f83ab5d5ea01d45c11aefa64fd
refs/heads/main
<repo_name>camawa556/sorceryTest2<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base before_action :login_required private def not_authenticated redirect_to login_path, alert: "Please login first" end def login_required redirect_to login_url unless current_user end end <file_sep>/db/migrate/20210908225635_add_name_to_users.rb class AddNameToUsers < ActiveRecord::Migration[5.2] def change add_column :users,:first_name,:string,null: false add_column :users,:last_name,:string,null: false end end
d72d853d9e661566af517962bc534eb0c78da7ec
[ "Ruby" ]
2
Ruby
camawa556/sorceryTest2
e1aaf4a60b8a010837530abc8798fcfd7541fda6
7198e45e17ce793120955968553d24bc98415e4e
refs/heads/main
<repo_name>DarkestEcho/rest_api_flask<file_sep>/static/handlers.js const addButtonElem = document.querySelector('#add-book-button'); addButtonElem.addEventListener('click', () => { if(document.forms[0].dataset.id != '-1') { document.forms[0].dataset.id = '-1'; document.forms[0].reset(); document.querySelector('#confirm-button').value = 'Добавить'; } else if(document.forms[0].style.display == 'none') document.forms[0].style.display = ''; else document.forms[0].style.display = 'none'; }); const closeButtonElem = document.querySelector('#close-form-button'); closeButtonElem.addEventListener('click', () => { if(document.forms[0].dataset.id != '-1') { document.forms[0].dataset.id = '-1'; document.forms[0].reset(); document.querySelector('#confirm-button').value = 'Добавить'; } document.forms[0].style.display = 'none'; }); document.forms[0].onsubmit = () =>{ const author = document.querySelector('#author'); const genre = document.querySelector('#genre'); const title = document.querySelector('#title'); const num = document.querySelector('#year'); if(author.value == '' || genre.value == '' || num.value == '') { alert('Введите все необходимые данные'); return false; } if(document.forms[0].dataset.id == '-1') { fetch('/last-id') .then(res => res.text()) .then(result =>{ const newRow = document.createElement('tr'); newRow.innerHTML = `<td>${result}</td> <td>${author.value}</td> <td>${title.value}</td> <td>${genre.value}</td> <td>${num.value}</td> <td><input type="button" value="Изменить" data-id="${result}" onclick="EditHandler(this)"/></td> <td><input type="checkbox" data-id="${result}"/></td>`; document.querySelector('#table-body').append(newRow); fetch('/books', { method: 'PUT', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify({id: result, author: author.value, title: title.value, genre: genre.value, year: num.value}) }); document.forms[0].reset(); }); } else { fetch('/books', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify({id: document.forms[0].dataset.id, author: author.value, title: title.value, genre: genre.value, year: num.value}) }); const rows = document.querySelector('#table-body').querySelectorAll('tr'); let i = 0; for(; i < rows.length; i++) if(rows[i].querySelector('td').innerHTML == document.forms[0].dataset.id) break; const cells = rows[i].querySelectorAll('td'); cells[1].innerHTML = author.value; cells[2].innerHTML = title.value; cells[3].innerHTML = genre.value; cells[4].innerHTML = num.value; document.forms[0].reset(); document.forms[0].dataset.id = '-1'; document.querySelector('#confirm-button').value = 'Добавить'; } return false; }; const deleteButtonElem = document.querySelector('#delete-book-button'); deleteButtonElem.addEventListener('click', () =>{ const a = []; const rows = document.querySelector('#table-body').querySelectorAll('tr'); for(let i = 0; i < rows.length; i++) { const e = rows[i].querySelectorAll('input')[1]; if(e.checked) { a.push(e.dataset.id); rows[i].remove(); } } if(a.length == 0) { alert('Не выбрано ни одной записи'); return; } fetch('/books', { method: 'DELETE', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(a) }); }); function EditHandler(elem) { document.forms[0].style.display = ''; document.forms[0].dataset.id = elem.dataset.id; document.querySelector('#confirm-button').value = 'Применить'; const elems = elem.parentElement.parentElement.querySelectorAll('td'); document.querySelector('#author').value = elems[1].innerHTML; document.querySelector('#title').value = elems[2].innerHTML; document.querySelector('#genre').value = elems[3].innerHTML; document.querySelector('#year').value = elems[4].innerHTML; }<file_sep>/app.py from flask import Flask, url_for, request, jsonify from markupsafe import escape app = Flask(__name__) bookList = [] @app.route('/', methods=['GET']) def index(): return app.send_static_file('index.html') @app.route('/<filename>', methods=['GET']) def src(filename=None): return app.send_static_file(filename) @app.route('/books', methods=['GET']) def get_list(): return jsonify(bookList) @app.route('/last-id', methods=['GET']) def get_id(): return str(int(bookList[len(bookList) - 1]["id"]) + 1) if len(bookList) > 0 else '0' @app.route('/books', methods=['PUT']) def add_book(): obj = request.get_json() if 'id' in obj and 'author' in obj and 'title' in obj and 'genre' in obj and 'year' in obj: bookList.append(obj) return '',201 return '', 400 @app.route('/books', methods=['POST']) def edit_book(): obj = request.get_json() if 'id' in obj and 'author' in obj and 'title' in obj and 'genre' in obj and 'year' in obj: i = 0 while i < len(bookList): if bookList[i]['id'] == obj['id']: break i+=1 if i < len(bookList): bookList[i]['author'] = obj['author'] bookList[i]['title'] = obj['title'] bookList[i]['genre'] = obj['genre'] bookList[i]['year'] = obj['year'] return '', 202 else: return '', 400 @app.route('/books', methods=['DELETE']) def delete_book(): obj = request.get_json() i = 0 while i < len(bookList): if str(bookList[i]['id']) in obj: del bookList[i] continue i+=1 return '', 202
a2c6da5175fdfcd0edbe31390e2420eab4f009c3
[ "JavaScript", "Python" ]
2
JavaScript
DarkestEcho/rest_api_flask
4db51124af3bf2ddfba9867381280419ebbefc96
5b8e1a846e786c1c2fa731773e2ee65f2f18e426
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class PosAvg{ private static final int INITIAL_SIZE = 10; private String stID; //creating a class variable for the passed in stID private String[] stationData = new String[INITIAL_SIZE]; //array that stores all station ID's private int numStations = 0; //counter for the stationData array starting at zero /* * This constructor takes in an ID input as a parameter and uses a reader to extract the data from * Mesonet.txt */ public PosAvg(String stID) throws IOException{ this.stID = stID; //updating class variable with parameter ID //creating the BufferedReader to read in the file BufferedReader br = new BufferedReader(new FileReader("Mesonet.txt")); for (int i = 0; i < 3; ++i) { br.readLine(); //reading through first 3 lines of the file that don't contain data } String dataLine = br.readLine(); //first line that actually contains data stored in String while (br.ready()) { //while file still has data to be read if (numStations == stationData.length) { expandArray(); //expanding the array if capacity is full } /* *splitting the dataLine String by white spaces and storing the second element into info because *the first index is a white space */ String info = dataLine.split("\\s+")[1]; stationData[numStations++] = info; //storing all the stID's into the stationData array dataLine = br.readLine(); //reading the next line for the next iteration of the loop } br.close(); //closing the reading when finished } /* * This method finds the index number of the line that a given stationID is on and returns it */ public int indexOfStation() { int index = 1; //the file reader begins at index 1 for (int i = 0; i < numStations - 1; i++) { String test = stationData[i]; if (stID.equalsIgnoreCase(test)) { return index; } ++index; } return index; } /* * This method simply expands the stationData array length when the capacity becomes full */ public void expandArray() { int newSize = stationData.length * 2; String[] newArray = new String[newSize]; for (int i = 0; i < stationData.length; ++i) { newArray[i] = stationData[i]; //copying over the old array contents to new array } this.stationData = newArray; //updating class reference } /* * This method is used to calculate the index average value of two station's indexes in stationData * that equals the indexofStation() value */ public String[] indexAverage() { String[] average = new String[4]; //returning 2 sets of stations which have an average equal to index int index = indexOfStation(); //getting the index value of the stID in question /* * since we are pulling Strings from stationData array, and we started at index 1 instead of zero, * the we subtract by 2 and 0, and 3 and -1. */ String temp = stationData[index-2]; //first set of stations that share average average[0] = temp; temp = stationData[index]; average[1] = temp; temp = stationData[index-3]; //second set of stations that share average average[2] = temp; temp = stationData[index+1]; average[3] = temp; return average; } /* * This method overrides the toString method to print out some more data about the averages */ public String toString() { return String.format("This index is average of %s and %s, %s and %s, and so on.",indexAverage()[0], indexAverage()[1],indexAverage()[2],indexAverage()[3]); } } <file_sep> public class MesoInherit extends MesoAbstract { private static final int NUM_LETTERS = 26; //number of letters in alphabet private int[] ascii = new int[NUM_LETTERS]; //array that contains the ASCII values of letters private char[] letters; //array that contains all of the letters private String stID; //the station ID that all the calculations will be done on /* * This constructor takes in a MesoStation object as a parameter and also fills in the * ASCII values in the ascii array */ public MesoInherit(MesoStation stID){ this.stID = stID.getStID(); //updating the reference of stID to the one in the parameter int startingVal = 65; for (int i = 0; i < ascii.length; ++i) { //using a for loop to fill in the ASCII values ascii[i] = startingVal++; } letters = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M', //filling the letters array 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; } /* * This method calculates the ASCII Ceiling, ASCII Floor, and the ASCII Average */ public int[] calAverage() { int[] result = new int[3]; //array that holds the results of the method //getting all of the chars from stID char c1 = stID.charAt(0); char c2 = stID.charAt(1); char c3 = stID.charAt(2); char c4 = stID.charAt(3); //explosive double ascii1 = 0.0, ascii2 = 0.0, ascii3 = 0.0, ascii4 = 0.0; //variable to store all ASCII values in for(int i = 0; i < ascii.length; ++i) { //this for loop finds all of the ASCII values for each char int asciiVal = ascii[i]; char cTest = letters[i]; if (c1 == cTest) { //finds c1's ASCII if true ascii1 = asciiVal; } if (c2 == cTest) { //finds c2's ASCII if true ascii2 = asciiVal; } if (c3 == cTest) { //finds c3's ASCII if true ascii3 = asciiVal; } if (c4 == cTest) { //finds c4's ASCII if true ascii4 = asciiVal; } } //finding the average after getting the ASCII values double average = (ascii1 + ascii2 + ascii3 + ascii4) / 4.0; //using 4.0 so that the ASCII values get casted to a double result[0] = (int)Math.ceil(average); //ASCII Ceiling result[1] = (int)Math.floor(average); //ASCII Floor /* * testing whether the decimal is less than or greater than 0.5 in order to apply the correct function */ if ((average - (int)average) >= 0.5) { result[2] = (int)Math.ceil(average); } else { result[2] = (int)Math.floor(average); } return result; } /* * This method finds the letter average using ASCII values */ public char letterAverage() { int average = calAverage()[2]; //gets the average ASCII value: either floor or ceiling} int index = 0; for (int i = 0; i < ascii.length; ++i) { //finds the array index where the ASCII value is located if (average == ascii[i]) { index = i; } } char result = letters[index]; //using the array index to find the corresponding letter return result; } } <file_sep># Project02_CS2334 * The problem: The problem presented by Project02 requires a way to return the index of a given station from the same Mesonet.txt file from Project01. Additionally, two sets of stations that exhibit an average index that is the same as the index of the original station will be returned. Calculations will be done on the given station using the ASCII values. These calculations include Ceiling, Floor, and Average. After calculating the ASCII Average, the letter that corresponds to that average needs to be returned. Finally, the number of stations that begin with that letter average and the stations themselves will need to be returned. - Problem-solving approach: From the provided Driver.java, MesoStation.java and Mesonet.txt files, it is clear that we will need to use multiple classes in order to perform all of the calculations. The MesoAbstract.java class is responsible for providing the 'blueprint' of methods that any extended class must implement. In this case, the MesoInherit.java is extending MesoAbstract.java. The classes PosAvg.java and LetterAvg.java will be doing calculations that require the use of the text file. Therefore, both of those classes will have a BufferedReader to read in data. The output can therefore be broken down line-by-line between the different classes where: Lines 1-2: PosAvg.java Lines 3-6: MesoInherit.java Lines 7-rest: MesoInherit.java and LetterAvg.java * LetterAvg.java: - Local class variables: String[] stationData: this array holds all the station ID's after reading via a BufferedReader, initially set to size 10 String[] same: this array holds all the station ID's that begin with the letter average char char c: the letter average char that is found in the MesoInherit class via the letterAverage() method String output: this String is used to set up the correctly formatted toString output to be used in the toString method This class takes in the letter average that is calculated by MesoInherit.java as its constructor value. The constructor in the updates the char c to the calculated char, and reads in info from Mesonet.txt to extract the stationID's. The stationID's are stored in the stationData[] array to be used for calculations in other methods. The numberofStationWithLetterAvg() method finds the number of stations in the stationData[] array that begin with char c using for loops and if statements. A counter is used to keep track of the number of stations that do begin with char c and that value is returned. The stringForToString() method does a similar test as numberOfStationWithLetterAvg(); however, this time instead of incrementing a counter, the stationID's themselves are stored into the same[] array. Then, the String output is updated to contain Lines 7-rest of the output. The toString method sets the String output to a value by calling the stringForToString() method. It then returns the String which will not only contain the correct value, but also the required formatting. Other class methods include two expand array methods which simply expand either the same[] or stationData[] array if they are full. * MesoAbstract.java: This class is responsible for setting up the methods that any MesoStation object must implement. Since every MesoInherit object is constructed using a MesoStation object, the MesoAbstract class is responsible for setting up the framework specifically for the MesoInherit class. The two methods defined: calAverage() and letterAverage() will be implemented and explained in the MesoInherit class. * MesoInherit.java - Local class variables: int[] ascii: this array holds the ascii values for letters 'A' - 'Z' starting at A's value and ending at Z's char[] letters: this array holds the letters 'A' - 'Z' String stID: this String is the given stationID used for calculations The constructor for this class takes in a MesoStation object as a parameter to use for the class's testing. The stID String is updated by calling MesoStation's getStID() method, since the parameter isn't a String directly. Additionally, the constructor fills the ascii[] and letters[] array with the correct values. The calAverage method breaks the String stID down into each of its chars, and finds the corresponding value of that char stepping through both the ascii[] and letters[] array in the same for loop, since the index of one array directly corresponds to the other. (I.e. if the letter was 'C' in the letters array, finding that index and using it for the ascii[index] array would return the corresponding ASCII value since both have the same length.) After testing each char to see if it matches the letter[i] char, all 4 char's will be given their correct ASCII value. The average is then calculated by taking the four ASCII value's and dividing by 4. The returned array that was initialized at the beginning is filled via the following way: result[0]: Math.ceil result[1]: Math.floor result[2]: average: either floor or ceil, depending on whether or not the decimal following the whole number is greater than or equal to 0.5 The letterAverage() method takes the result[2] from calAverage() and uses it to step through the ascii[] array to find which index corresponds to that number. Then, using the index in the letters[index] array pulls the correct Letter Avg char and returns it. This char is the one used in the LetterAvg.java class. * MesoStation.java - Local class variables: String stID: the given stationID String This class is used to construct a MesoStation object by passing in a stationID String into the constructor. It has a getStID() method that MesoInherit.java accesses to get and store the String value. * PosAvg.java - Local class variables: String stID: the given stationID String used for calculations String stationData[]: this array holds all the station ID's after reading via a BufferedReader, initially set to size 10 This class's constructor takes in a stationID and updates the reference stID. This class also uses the BufferedReader in the same way that the LetterAvg.java class does. The stationID's are stored in stationData[] array for calculations in other methods. The indexOfStation() method begins with a counter set to 1, since the index of a file begins at 1 instead of 0 like arrays. The String stID is compared to each stationID in stationData until they are the same, in which the correct index value is returned. The expandArray() simply expands stationData[] when needed. The indexAverage() method returns an array of Strings that contain the two sets of stationID's that share an average index value equal to indexOfStation()'s returned index value. They are found by taking the stationData[] array and finding the station before the indexed station by subtracting 2 (the array's index start at 0 so instead of subtracting 1 and adding 1, we have to subtract 2 and add 0). The other two sets of stations can be found by simply subtracting 2 values to index and adding 2 more values to index. The toString then uses String.format and calls the indexAverage() method at specific indexes in the array. (I.e. indexAverage()[0],indexAverage()[1]...)
14cb836153ae42f0ccd2d8890dce831a60e3437f
[ "Markdown", "Java" ]
3
Java
chrisbharucha/CS2334_Project02
9b6bc7acaf8f38a5864269c843e71e24c3b16f98
ae8ea4fd90d2334e7b63062547c3838d085f153a
refs/heads/master
<file_sep># Euclidian-Axiom A little GUI program showcasing the Euclidian Parallelism Axiom. Click once for the first point, twice for the second point to form a line, and then the third click will be the third point, which the parallel line will have to go through. <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Euc { public partial class MainForm : Form { private Point[] _3Points = new Point[3]; private int clicks = 0; private int GlobalPointCount = 0; public Graphics graphics; Pen pen = new Pen(Color.Black) { Width = 6 }; public MainForm() { InitializeComponent(); this.MouseClick += onMouseClick; graphics = this.CreateGraphics(); } private void Form1_Load(object sender, EventArgs e) { } private void onMouseClick(object sender, MouseEventArgs e) { if (clicks >= 3) { clicks = 0; } Rectangle rect = new Rectangle(e.Location, new Size(1, 1)); pen.Color = Color.Red; graphics.DrawRectangle(pen, rect); pen.Color = Color.Black; Point CurrentPoint = e.Location; _3Points[clicks] = CurrentPoint; if (clicks == 1) CompleteLine(); if (clicks == 2) DrawParrallelLine(); clicks++; CreateLabelForPoint(CurrentPoint, GlobalPointCount); GlobalPointCount++; } private void CompleteLine() { graphics.DrawLine(pen, _3Points[0], _3Points[1]); } private void DrawParrallelLine() { Point BeginPoint = _3Points[0]; Point EndPoint = _3Points[1]; Point ShouldCrossPoint = _3Points[2]; float AverageYDistanceFromPoint3 = ((BeginPoint.Y - ShouldCrossPoint.Y) + (EndPoint.Y - ShouldCrossPoint.Y)) / 2; float AverageXDistanceFromPoint3 = ((BeginPoint.X - ShouldCrossPoint.X) + (EndPoint.X - ShouldCrossPoint.X)) / 2; PointF shiftedBegin = new PointF(BeginPoint.X - AverageXDistanceFromPoint3, BeginPoint.Y - AverageYDistanceFromPoint3); PointF shiftedEnd = new PointF(EndPoint.X - AverageXDistanceFromPoint3, EndPoint.Y - AverageYDistanceFromPoint3); Pen BluePen = new Pen(Color.Blue) { Width = 6 }; graphics.DrawLine(BluePen, shiftedBegin, shiftedEnd); } private void CreateLabelForPoint(Point p, int index) { Point location = new Point(p.X - 5, p.Y - 20); Label label = new Label() { Location = location, Text = GetPointName(index), ForeColor = Color.Black, Size = new Size(20, 15)}; this.Controls.Add(label); } private string GetPointName(int index) { int ReducedIndex = index % 26; char c = Convert.ToChar(ReducedIndex + 96 + 1); int AdditionalNumber = index / (26); string s = c.ToString(); if (AdditionalNumber > 0) { s += AdditionalNumber; } return s; } } }
75c68ff1147400f463a0288fdc3db784fbae6a70
[ "Markdown", "C#" ]
2
Markdown
Matyasmester/Euclidian-Axiom
6480ed8963f05d167042e0f1d6d2ee60f5db1608
3118f9a67b660b4c80ee93c85448c81ddcbadb73
refs/heads/master
<repo_name>breatheco-de/attendancy<file_sep>/src/js/store/flux.js import PropTypes from "prop-types"; const ASSETS_URL = process.env.ASSETS_URL + "/apis"; const API_URL = process.env.API_URL; const params = new URLSearchParams(location.search); const assets_token = params.get("assets_token"); const access_token = params.get("token"); const academy = params.get("academy"); console.log("Some ", { assets_token, access_token }); const getState = ({ getStore, setStore, getActions }) => { return { store: { cohorts: [], current: null, students: null, dailyAvg: {}, totalAvg: null }, actions: { getTokensFromURL: props => { const initialCohort = params.get("cohort_slug"); const { cohorts } = getStore(); if (initialCohort) { console.log("cohorts", cohorts); getActions("getStudentsAndActivities")({ cohort: cohorts.find(c => c.slug === initialCohort), props }); } }, getStudentsAndActivities: async ({ cohort, props }) => { const cohortSlug = cohort.slug; const c = await getActions("getSingleCohort")(cohort.id); setStore({ students: null, dailyAvg: null, current: c }); let url = `${API_URL}/v1/admissions/cohort/user?cohorts=${cohortSlug}&roles=STUDENT`; let headers = { Authorization: `Token ${access_token}`, Academy: cohort.academy.id }; // Fetch students from cohort fetch(url, { cache: "no-cache", headers }) .then(response => { if (!response.ok) { props.history.push("/?error=renew_access_token"); throw Error; } return response.json(); }) .then(students => { getActions("formatNames")(students); let id_map = {}; students.forEach(s => (id_map[s.user.email] = s.user.id)); // Fetch all activities from cohort const _activities = ["classroom_attendance", "classroom_unattendance"]; url = `${API_URL}/v1/activity/cohort/${cohortSlug}?slug=${_activities.join(",")}`; fetch(url, { cache: "no-cache", headers }) .then(response => { if (!response.ok) { response.json().then(error => { throw Error(error.msg || "Error fetching activities"); }); } else { return response.json(); } }) .then(activities => { if (!Array.isArray(activities)) activities = []; // Merge students with their activities let student = {}; let stuAct = {}; // {student_id: {day0: unattendance, day1: attendance, ...}} let stuActEmail = {}; // legacy let dailyAvg = {}; // {day0: 89%, day1: 61%, ...} // activities.filter(item => item.slug.includes("attendance")).forEach(element => { let days = element.data.day; // map ideas with old breathecode from new breathecode if (!element.academy_id) element.user_id = id_map[element.email]; if (student[element.user_id] === undefined) { student[element.user_id] = {}; student[element.user_id].student_id = element.user_id; student[element.user_id].attendance = 0; student[element.user_id].unattendance = 0; student[element.user_id].days = []; student[element.user_id].totalAttendance = 0; student[element.user_id].dailyAttendance = 0; } if (!student[element.user_id].days.includes(days)) { student[element.user_id].attendance += element.slug.includes("attendance") ? 1 : 0; student[element.user_id].unattendance += element.slug.includes("unattendance") ? 1 : 0; if (element.user_id == 3777 && element.day == 1) { console.log(`${element.user_id} ${element.slug} on day ${element.day}`); } student[element.user_id].days.push(days); student[element.user_id].totalAttendance = (student[element.user_id].days.length * 100) / 45; student[element.user_id].dailyAttendance = (student[element.user_id].attendance * 100) / (student[element.user_id].attendance + student[element.user_id].unattendance); dailyAvg[day] += element.slug.includes("unattendance") ? 0 : 1; } let day = `day${element.data.day}`; // Create temp obj to store all activities by student id if (stuAct[element.user_id] === undefined) { stuAct[element.user_id] = {}; stuAct[element.user_id].avg = 0; // duplicate element but index be email, because legacy can only use emails stuActEmail[element.email] = stuAct[element.user_id]; } if (dailyAvg[day] === undefined) { dailyAvg[day] = 0; } // Inside also store all the activities by creating a day property // if (element.user_id == 3777 && element.day == 1) { // console.log(`${element.user_id} ${element.slug} on day ${element.day}`); // } stuAct[element.user_id][day] = element; stuAct[element.user_id].avg += element.slug.includes("unattendance") ? 0 : 1; dailyAvg[day] += element.slug.includes("unattendance") ? 0 : 1; }); // Add cohort assistance into students array for (let studentProp in student) { students.forEach(item => { if (item.attendance_log === undefined) { item.attendance_log = {}; item.attendance_log.totalAttendance = 0; (item.attendance_log.dailyAttendance = 0), (item.attendance_log.attendance = 0); item.attendance_log.unattendance = 0; item.attendance_log.days = []; } // ⬇ just for legacy, previous breathecode api was just id instead of user.id if (item.user.id == studentProp || item.id == studentProp) { item.attendance_log = student[item.user.id]; } }); } // divide by the number of students to get the avg Object.keys(dailyAvg).map( key => (dailyAvg[key] = (dailyAvg[key] / students.length) * 100) ); // divide by the amount of days recorded to get the avg Object.keys(stuAct).map( key => (stuAct[key].avg = (stuAct[key].avg / (Object.keys(stuAct[key]).length - 1)) * 100) // Minus the avg key ); students.forEach(e => { // console.log(`Student ${e.user.id}`, stuAct[e.user.id]); let _id = e.user != undefined ? e.user.id : e.id; // console.log("stuAct[_id]", _id, stuAct[_id], e); e.attendance = stuAct[_id] ? stuAct[_id] : stuActEmail[e.user.email] ? stuActEmail[e.user.email] : []; }); setStore({ students, dailyAvg }); }); props.history.push( `/?cohort_slug=${cohortSlug}&academy=${cohort.academy.id}&token=${access_token}` ); }); }, formatNames: data => { const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); const getUserName = email => email.substring(0, email.indexOf("@")).toLowerCase(); const fullTrim = str => { let newStr = ""; str = str.trim(); for (let i in str) if (str[i] !== " " || str[i - 1] !== " ") newStr += str[i]; return newStr; }; for (let i in data) { let first = data[i].user.first_name; let last = data[i].user.last_name; if (last === null) last = ""; // In the fetch url, Students have email, Users have username let username = data[i].user.username === undefined ? getUserName(data[i].user.email) : getUserName(data[i].user.username); // first_name: null // first_name: "null null" if (first === null || first.includes("null")) { first = username; } // first === email username, keep lowercase else if (first.toLowerCase() === username && last === "") { first = username; } else { first = fullTrim(first); last = fullTrim(last); let arr = first.split(" "); // first_name: "John" // first_name: "JohnDoe" // first_name: "JOHNDOE" if (arr.length === 1) { if (first !== first.toLowerCase() && first !== first.toUpperCase()) { let temp = ""; for (let char of first) { if (char === char.toUpperCase() && isNaN(char)) temp += " " + char; else temp += char; } first = temp.trim(); arr = first.split(" "); if (arr.length === 1) first = capitalize(arr[0]); } else first = capitalize(first); } // first_name: "<NAME>", last_name: "" if (arr.length === 2 && last === "") { first = capitalize(arr[0]); last = capitalize(arr[1]); } // first_name: "<NAME>", last_name: "" else if (arr.length === 3 && last === "") { first = capitalize(arr[0]) + " " + capitalize(arr[1]); last = capitalize(arr[2]); } // first_name: "<NAME>", last_name: "<NAME>" else if (last !== "") { let arrl = last.split(" "); for (let i in arr) arr[i] = capitalize(arr[i]); for (let i in arrl) arrl[i] = capitalize(arrl[i]); first = arr.join(" "); last = arrl.join(" "); } } data[i].user.first_name = first; data[i].user.last_name = last; } }, getMe: async () => { const url = `${process.env.API_URL}/v1/auth/user/me`; const resp = await fetch(url, { cache: "no-cache", headers: { Authorization: `Token ${access_token}` } }); console.log("resp", resp); if (resp.status === 401 || resp.status === 403) { window.location.href = "/"; return false; } const data = resp.json(); return data; }, getSingleCohort: async cohort_id => { const url = `${process.env.API_URL}/v1/admissions/academy/cohort/${cohort_id}`; const resp = await fetch(url, { cache: "no-cache", headers: { Authorization: `Token ${access_token}`, Academy: academy } }); const data = resp.json(); console.log("Cohort", data); return data; }, getCohorts: () => new Promise((resolve, reject) => { const url = `${process.env.API_URL}/v1/admissions/academy/cohort`; fetch(url, { cache: "no-cache", headers: { Authorization: `Token ${access_token}`, Academy: academy } }) .then(response => { return response.json(); }) .then(data => { setStore({ cohorts: data.sort((a, b) => (a.name > b.name ? 1 : -1)) }); resolve(data); }) .catch(error => { reject(error); }); }) } }; }; getState.propTypes = { history: PropTypes.object }; export default getState; <file_sep>/src/js/views/home.js import React, { useState, useEffect, useContext } from "react"; import { Context } from "../store/appContext"; import Popover from "../component/popover"; const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; export const Home = props => { const [zoom, setZoom] = useState("font-size-10px"); const [totalEveryone, setTotalEveryone] = useState(0); const [academies, setAcademies] = useState([]); const { store, actions } = useContext(Context); const params = new URLSearchParams(location.search); useEffect(() => { if (params.has("token")) { actions.getMe().then(me => { if (!me) return; let aca = me.roles.map(r => r.academy); setAcademies(aca); if (aca.length == 1 && !params.has("academy")) window.location.href = window.location.href + "&academy=" + aca[0].id; }); if (params.has("academy")) { actions.getCohorts().then(data => actions.getTokensFromURL(props)); } if (params.has("cohort_slug")) { const cohort_slug = params.get("cohort_slug"); actions.getSingleCohort(cohort_slug).then(cohort => { actions.getStudentsAndActivities({ cohort, props }); }); } } }, []); const daysInCohort = store.current ? store.current.syllabus_version.duration_in_days : 0; const noData = <i className={`fas fa-exclamation-circle text-sand cursor-pointer ${zoom}`} />; const thumbsUp = <i className={`fas fa-thumbs-up text-darkgreen cursor-pointer ${zoom}`} />; const thumbsDown = <i className={`fas fa-thumbs-down text-darkred cursor-pointer ${zoom}`} />; if (!params.has("token")) return ( <div className="alert alert-danger"> Please{" "} <a href={`${process.env.API_URL}/v1/auth/view/login?url=${window.location.href}`}>log in first</a> </div> ); if (!params.has("academy") && !params.has("cohort_slug") && academies.length > 1) return ( <div className="alert alert-danger"> Please choose an academy : <ul> {academies.map(a => ( <li key={a.id}> <a href={`${window.location.href}&academy=${a.id}`}>{a.name}</a> </li> ))} </ul> </div> ); return ( <div className="mt-2 p-3 line-height-1"> <select className="mb-4" value={store.current ? store.current.slug : ""} onChange={e => actions.getStudentsAndActivities({ cohort: store.cohorts.find(c => c.slug === e.target.value), props }) }> {store.cohorts.length > 0 ? ( store.cohorts.map((e, i) => ( <option key={i} value={e.slug}> {e.name} </option> )) ) : ( <option value={null}>Loading cohorts...</option> )} </select> {params.has("error") ? ( <div className="text-center my-5"> <h2 className="mb-5">Try renewing the access token in the url</h2> <h4>?token=<PASSWORD></h4> </div> ) : params.has("cohort_slug") && !store.students ? ( <h2 className="text-center my-5">Loading students...</h2> ) : ( params.has("cohort_slug") && ( <div> <span className="position-absolute cursor-pointer" style={{ right: "50px", top: "30px" }}> {zoom.includes("10px") ? ( <i className="fas fa-search-plus fa-lg" onClick={() => setZoom("font-size-25px")} /> ) : ( <i className="fas fa-search-minus fa-lg" onClick={() => setZoom("font-size-10px")} /> )} </span> <table className="d-inline-block cell-spacing"> <tbody> {/******************* * EVERYONE NAME *********************/} <tr> <td className="border rounded d-flex justify-content-between mr-4 h-50px align-items-center"> <b className="p-2 w-200px">Everyone</b> {store.students && ( <b className="p-2"> {store.students !== null ? Math.ceil( store.students.reduce( (total, item, index) => store.students[index].attendance_log !== undefined ? total + store.students[index].attendance_log .dailyAttendance : 0, 0 ) / store.students.length ) : 0} % </b> )} </td> </tr> {/************************ * ALLS STUDENT NAMES **************************/} {!store.students ? ( <p>Loading students</p> ) : store.students.length === 0 ? ( <p>There are no students on this cohort.</p> ) : ( store.students.map((e, i) => ( <tr key={i}> <td className="border rounded d-flex justify-content-between mr-4 h-50px align-items-center"> <span className="p-2 w-200px"> {e.user.first_name} {e.user.last_name} </span> <span className="p-2"> {e.attendance_log !== undefined ? Math.ceil(e.attendance_log.dailyAttendance) : "0"} % </span> </td> </tr> )) )} </tbody> </table> <div className="d-inline-block overflow"> <table className="cell-spacing"> <tbody> {/****************************** * FIRST ROW DAYS IN COHORT ********************************/} <tr className=" hover-gray"> {new Array(daysInCohort).fill(null).map((e, i) => ( <td key={i} className="h-50px"> <Popover body={ <div className="pop"> <div>Day {i}</div> </div> }> {store.dailyAvg[`day${i}`] === undefined ? noData : store.dailyAvg[`day${i}`] >= 85 ? thumbsUp : thumbsDown} </Popover> </td> ))} </tr> {/********************************* * ALLS STUDENT DAYS IN COHORT ***********************************/} {store.students.map((data, i) => ( <tr key={i} className="hover-gray"> {new Array(daysInCohort).fill(null).map((e, i) => { let d = data.attendance[`day${i}`] ? data.attendance[`day${i}`].created_at || data.attendance[`day${i}`].created_at.date : null; let date = ""; if (d) { date = new Date(d); date = `${ months[date.getMonth()] } ${date.getDate()}, ${date.getFullYear()}`; } return ( <td key={i} className="h-50px"> <Popover body={ <div className="pop"> <div>Day {i}</div> <div>{date}</div> </div> }> {!data.attendance[`day${i}`] ? noData : data.attendance[`day${i}`].slug.includes( "unattendance" ) ? thumbsDown : thumbsUp} </Popover> </td> ); })} </tr> ))} </tbody> </table> </div> </div> ) )} </div> ); }; <file_sep>/.env.example ASSETS_URL=https://assets.breatheco.de API_URL=https://api.breatheco.de/
93e3f986e23a53515b0920ccd5515bacff4b7db6
[ "JavaScript", "Shell" ]
3
JavaScript
breatheco-de/attendancy
77b03f6269d5d93743d45bec1ac80bc40cc142f9
d50bee2abe765524be8a27d07e15e0a33559cbb2
refs/heads/master
<repo_name>nancyzhan/vueblog<file_sep>/target/maven-archiver/pom.properties version=0.0.1-SNAPSHOT groupId=com.wqzhan artifactId=vueblog <file_sep>/src/main/java/com/wqzhan/mapper/UserMapper.java package com.wqzhan.mapper; import com.wqzhan.entity.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /** * <p> * Mapper 接口 * </p> * * @author wqzhan * @since 2020-08-26 */ public interface UserMapper extends BaseMapper<User> { }
9eb4678f16479af7c9742fa87d6b881804571972
[ "Java", "INI" ]
2
INI
nancyzhan/vueblog
28fcdf545e9b1fcec1e1f6e9fb89d4c15e8607c0
a3f1f65b7a998038bc15424ba5aacde2ce5d66ad
refs/heads/master
<repo_name>ly05010419/Prim-Kruskal<file_sep>/Prim und Kruskal/ProgramAlgorithmus.cs using namespaceStuktur; using namespaceUtility; using System; using System.Collections; using System.Collections.Generic; namespace namespaceAlgorithmus { class Algorithmus { public void zeitOfAlgorithmus(string path, String methode) { Console.WriteLine(methode); Algorithmus algorithmus = new Algorithmus(); Graph graph = Parse.getGraphByFile(path); DateTime befor = System.DateTime.Now; if (methode == "Kruskal") { algorithmus.kruskal(graph); } else { algorithmus.prim(graph); } DateTime after = System.DateTime.Now; TimeSpan ts = after.Subtract(befor); Console.WriteLine("\n\n{0}s", ts.TotalSeconds); } public void prim(Graph graph) { List<Node> result = new List<Node>(); Node node = graph.nodeList[0]; node.weight = 0; while ((node = findMinNode(graph.nodeList))!=null) { //Console.WriteLine("min:" + node.id); foreach (Edge e in node.edgeList) { Node n = e.endNode; if (n.visited == false) { if (n.weight > e.weight) { n.weight = e.weight; } } } node.visited = true; } double sum = 0; foreach (Node n in graph.nodeList) { sum = sum + n.weight; //Console.WriteLine(n.id + "," + n.weight); } Console.WriteLine("sum:" + sum); } public Node findMinNode(List<Node> nodeList) { Node min = null; foreach (Node n in nodeList) { if (n.visited == false) { if (min == null) { min = n; } else if (n.weight < min.weight) { min = n; } } } return min; } int[] father; int[] rank; public void MakeSet(int length) { father = new int[length]; rank = new int[length]; for (int i = 0; i < length; i++) { father[i] = i; rank[i] = 0; } } int Find_Set(int x) { int root = x; while (father[root] != root) root = father[root]; return root; } public bool Union(int x, int y) { x = Find_Set(x); y = Find_Set(y); if (x == y) return false; if (rank[x] > rank[y]) { father[y] = x; } else if (rank[x] < rank[y]) { father[x] = y; } else { rank[y]++; father[x] = y; } return true; } public void kruskal(Graph graph) { List<Edge> result = new List<Edge>(); graph.edgeList.Sort(); MakeSet(graph.nodeList.Count); foreach (Edge edge in graph.edgeList) { //Console.WriteLine(edge.startNode.id + "-" + edge.endNode.id); if (Union(edge.startNode.id, edge.endNode.id)) { result.Add(edge); } } double sum = 0; foreach (Edge e in result) { sum = sum + e.weight; //Console.WriteLine(e.startNode.id + "-" + e.endNode.id); } Console.WriteLine("sum: " + sum); } } } <file_sep>/Prim und Kruskal/ProgramUtility.cs using namespaceStuktur; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace namespaceUtility { class Parse { public static Graph getGraphByFile(string path) { List<Node> nodeList = new List<Node>(); List<Edge> edgeList = new List<Edge>(); StreamReader sr = new StreamReader(path, Encoding.Default); String lineStr; int nodeCount = 0; while ((lineStr = sr.ReadLine()) != null) { if (nodeCount == 0) { initNode(int.Parse(lineStr), nodeList); } else { string[] word = Regex.Split(lineStr, "\t"); createEdge(int.Parse(word[0]), int.Parse(word[1]), float.Parse(word[2]), nodeList, edgeList); createNode(int.Parse(word[0]), int.Parse(word[1]), float.Parse(word[2]), nodeList); } nodeCount++; } Graph g = new Graph(nodeList, edgeList); return g; } static void initNode(int nodeCount,List<Node> nodeList) { for (int i = 0; i < nodeCount; i++) { Node node = new Node(i); nodeList.Add(node); } } static void createNode(int vaterIndex, int sonIndex,float weight, List<Node> nodeList) { Node vater1 = nodeList[vaterIndex]; Node son1 = nodeList[sonIndex]; Edge edge1 = new Edge(vater1,son1, weight); vater1.edgeList.Add(edge1); Node vater2 = nodeList[sonIndex]; Node son2 = nodeList[vaterIndex]; Edge edge2 = new Edge(vater2,son2, weight); vater2.edgeList.Add(edge2); } static void createEdge(int vaterIndex, int sonIndex, float weight, List<Node> nodeList, List<Edge> edgeList) { Node vater = nodeList[vaterIndex]; Node son = nodeList[sonIndex]; Edge edge = new Edge(vater,son, weight); edgeList.Add(edge); } } }<file_sep>/Prim und Kruskal/ProgramStukur.cs using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace namespaceStuktur { class Graph { public List<Node> nodeList; public List<Edge> edgeList; public Graph(List<Node> nodeList, List<Edge> edgeList) { this.nodeList = nodeList; this.edgeList = edgeList; } } class Node : IComparable<Node> { public int id; public List<Edge> edgeList; public bool visited = false; public double weight; public Node(int id) { this.id = id; this.edgeList = new List<Edge>(); this.weight = float.MaxValue; } public int CompareTo(Node other) { return this.weight.CompareTo(other.weight); } } class Edge : IComparable<Edge> { public Node endNode; public Node startNode; public double weight; public Edge(Node startNode, Node endNode, double weight) { this.startNode = startNode; this.endNode = endNode; this.weight = weight; } public int CompareTo(Edge other) { return this.weight.CompareTo(other.weight); } } }<file_sep>/README.md # 通过Prim或者Kruskal获得MST(最小生成树) # Prim > 总是两集合之间的寻找最小边,得到最小生成树。 > 1. 已访问集合V{a,b,c} 未访问集合W{c,d,e} > 2. 寻找V和W之间的最小边Kante, 把Kante.EndNode加入已访问集合V. > 原理如下 > https://github.com/ly05010419/Prim-Kruskal/blob/master/Algorithmus%20von%20Prim.pdf 具体实现没有使用到边,相反通过利用PriorityQueue和Knoten,点继承了边的权重,实现Krim算法: > 1. StartKnoten得到所有子Knoten,更新子Knoten的Gewicht为Kante.gewicht. > 2. 通过PriorityQueue获得最小的Knote,作为新的StartNode,继续下去。 # Kruskal > 通过插入最小的变,注意不能形成圈,得到最小生成树。 > 1. 按从小到大排序所有边 > 2. 依次加入最小边 > 3. 检查有无圈存在 > 4. 加入所有边后就是最小生成树 ## 圖示 ![GITHUB](https://upload.wikimedia.org/wikipedia/commons/b/bb/KruskalDemo.gif "git圖示") TUM算法详解 http://www-m9.ma.tum.de/Allgemeines/GraphAlgorithmenEn <file_sep>/Prim und Kruskal/Program.cs using namespaceAlgorithmus; using System; namespace PrimKruskal { class Program { static void Main(string[] args) { Algorithmus algorithmus = new Algorithmus(); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2_1.txt","prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2_1.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2_2.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2_2.txt", "Kruskal"); algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_2.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_20.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_20.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_200.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_1_200.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_10_20.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_10_20.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_10_200.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_10_200.txt", "Kruskal"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_100_200.txt", "prim"); //algorithmus.zeitOfAlgorithmus(@"../../MST/G_100_200.txt", "Kruskal"); Console.WriteLine("\n"); Console.ReadLine(); } } }
0ff0ee1a09a811951dd40d9a9d9d952b9dedabbc
[ "Markdown", "C#" ]
5
C#
ly05010419/Prim-Kruskal
7445e5c7d7fb2894475451546d934da03ca6801c
13d38722eb5890057f4928e03cad86c7f9d5ce9b
refs/heads/master
<repo_name>altmivip/chrome<file_sep>/chk-code.py #!/usr/bin/python ''' @desc : some svn-hook write with python @author : <EMAIL> @date : 2013/05/12 ''' # dir check
74ebc08ff94367ccec7f3753082f755bf7d237de
[ "Python" ]
1
Python
altmivip/chrome
c098f216bec663668ce4b6df51fa8491b11c9103
c1a231eda97c7c9a23680c173857fb7f2e1de1bb
refs/heads/master
<file_sep>using System; using System.IO; using System.Reflection; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; namespace uitest.browser { #region Namespace Imports using System; using System.IO; using System.Reflection; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; #endregion public class UiSetup { public static IWebDriver getDriver { get; private set; } public static IWebDriver InitDriver(string browser) { ChromeOptions options = new ChromeOptions(); switch (browser) { case "chrome": options.AddArgument("--no-sandbox"); options.AddArgument("--disable-dev-shm-using"); var runtime = System.Runtime.InteropServices.RuntimeInformation.OSDescription; if (runtime.ToLower().Contains("linux")) { getDriver = new ChromeDriver("/usr/bin", options); } else { getDriver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); } break; case "firefox": getDriver = new FirefoxDriver(); break; default: options.AddArgument("--no-sandbox"); options.AddArgument("--disable-dev-shm-using"); runtime = System.Runtime.InteropServices.RuntimeInformation.OSDescription; if (runtime.ToLower().Contains("linux")) { getDriver = new ChromeDriver("/usr/bin", options); } else { getDriver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); } break; } getDriver.Manage().Window.Maximize(); getDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); return getDriver; } public static IWebDriver InitDriverAndOpenWebPage(string browser, string url) { var driver = InitDriver(browser); driver.Url = url; return driver; } } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using uitest.browser; namespace DockerChrome { [TestClass] public class UITest { [TestMethod] public void GoogTest() { var driver = UiSetup.InitDriverAndOpenWebPage("chrome", "https://google.com"); var title = driver.Title; Assert.IsNotNull(driver.Title); Assert.IsTrue(driver.Title.Equals("Google")); driver.Close(); } } }
69e1c3e4c2f835f75255c32781b210f787289dcf
[ "C#" ]
2
C#
surya818/DockDN
c3244976fb344bc1d7087c73ab174ee2fbe194f7
d38f7b8088e04999601decdc33d93b040664d955
refs/heads/master
<repo_name>steveturczyn/svh1<file_sep>/README.rdoc Slapton Village Hall Message Forum Provides a web locale where hall business can be discussed and commented on. <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController def new @user = User.new end def show @user = User.find(params[:id]) @posts = @user.posts.find(:all, order: 'id DESC') end def comments @user = User.find(params[:id]) @comments = @user.comments.find(:all, order: 'id DESC') @posts = @user.posts.find(:all, order: 'id DESC') @show_comments = true render :show end def create @user = User.new(user_params) if @user.save redirect_to root_path, notice: 'You are registered!' else @user.errors.delete[:password_digest] render :new end end def user_params params.require(:user).permit(:username, :email, :password) end def show @user = User.find(params[:id]) @posts = @user.posts.find(:all, order: 'id DESC') end end<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user, :logged_in?, :user_match def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] != nil end def logged_in? !!current_user end def require_user unless logged_in? flash[:error] = "You must be logged in to do that" redirect_to root_path end end def user_match(post) if current_user != post.user flash[:error] = "Not permitted to modify this post" redirect_to post_path end end end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def fix_url(string) # make a valid url string.starts_with?("http://") ? string : (string.starts_with?("https://") ? string : "http://#{string}" ) end end <file_sep>/config/routes.rb Postit::Application.routes.draw do root to: 'posts#index' # post '/posts/:id/vote', to: 'posts#vote' # post '/comments/:id/vote', to: 'comments#vote' get '/register', to: 'users#new' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' resources :posts do member do post 'vote' end collection do get 'demonstration' end resources :comments do member do post 'vote' end end end resources :users do member do get 'comments' end end resources :categories end <file_sep>/app/models/comment.rb class Comment < ActiveRecord::Base include Voteable belongs_to :user belongs_to :post has_many :votes, as: :voteable validates :comment_text, presence: true def score self.votes.where(vote: true).size - self.votes.where(vote: false).size end end <file_sep>/app/controllers/categories_controller.rb class CategoriesController < ApplicationController before_filter :require_user, only: [:new, :create, :edit, :update] helper ApplicationHelper def index end def new @category = Category.new fix_url("www.cnn.com") end def create if params[:commit] == "Cancel" flash[:notice] = "New category was cancelled." redirect_to posts_path else @category = Category.new(params[:category]) if @category.save flash[:notice] = "Category successfully added!" redirect_to posts_path else render :new end end end def show @category = Category.find(params[:id]) @posts = @category.posts.find(:all, order: 'id DESC') end def edit end def update end def destroy end end <file_sep>/app/controllers/comments_controller.rb class CommentsController < ApplicationController before_filter :require_user, only: [:new, :create, :edit, :update] before_filter :find_post, only: [:create, :vote] def index @comments = Comments.all end def new @comment = Comment.new end def create @comment = Comment.new(comment_params) @comment.post_id = @post.id @comment.user = current_user if @comment.save flash[:notice] = "Comment added." redirect_to post_path(params[:post_id]) else binding.pry render 'posts/show' end end def show render :show => "posts/#{params[:id]}" end def edit end def update end def destroy end def vote @comment = Comment.find(params[:id]) @vote = @comment.votes.where("user_id = ?",current_user.id).first if @vote if @vote.vote != params[:vote] @vote.destroy else @vote.save end else @vote = Vote.new @vote.vote = params[:vote] @vote.user = current_user @comment.votes << @vote @vote.save end respond_to do |format| format.html do redirect_to :back end @myobject = @comment format.js do render 'posts/vote' end end end def comment_params params.require(:comment).permit(:comment_text) end def find_post @post = Post.where("slug = ?",params[:post_id]).first #@post = Post.find_by_slug(params[:post_id]) end end <file_sep>/extras/voteable.rb module Voteable def self.included(base) base.send(:include, InstanceMethods) base.extend ClassMethods base.class_eval do my_class_method end end module InstanceMethods def like?(current_user) answer = false vote = self.votes.where("user_id = ?",current_user.id).first if vote answer = vote.vote end answer end def dislike?(current_user) answer = false vote = self.votes.where("user_id = ?",current_user.id).first if vote answer = ! vote.vote end answer end def score self.votes.where(vote: true).size - self.votes.where(vote: false).size end end module ClassMethods def my_class_method puts "module's class method!" end end end<file_sep>/app/models/user.rb class User < ActiveRecord::Base include GravatarTurczyn has_secure_password has_many :posts has_many :comments before_validation do self.email = self.email.downcase.strip end validates :username, presence: true, uniqueness: true validates :password, presence: true, on: :create def hash_it_up Digest::MD5.hexdigest(self.email) end end <file_sep>/app/controllers/posts_controller.rb class PostsController < ApplicationController before_filter :require_user, only: [:new, :create, :edit, :update, :destroy, :vote] before_filter :find_post, only: [:show, :edit, :update, :destroy, :vote] def index # @posts = Post.all @posts = Post.find(:all, order: 'id DESC') end def new @post = Post.new end def create # binding.pry if params[:commit] == "Cancel" flash[:notice] = "New post was cancelled." redirect_to posts_path else @post = Post.new(post_params[:post]) @post.user = current_user if @post.save flash[:notice] = "Post successfully added!" redirect_to posts_path else render :new end end end def show @comment = Comment.new end def edit user_match(@post) end def update user_match(@post) if params[:commit] == "Cancel" flash[:notice] = "Update post was cancelled." redirect_to posts_path else # @post.categories = [] if @post.update_attributes(post_params[:post]) # if @post.save flash[:notice] = "Post successfully changed!" redirect_to posts_path else render :edit end end end def destroy user_match(@post) @post.destroy #Post.destroy(params[:id]) flash[:notice] = "Post was deleted!" redirect_to posts_path end def vote @vote = @post.votes.where("user_id = ?",current_user.id).first if @vote if @vote.vote != params[:vote] @vote.destroy else @vote.save end else @vote = Vote.new @vote.vote = params[:vote] @vote.user = current_user @post.votes << @vote @vote.save end respond_to do |format| format.html do redirect_to :back end @myobject = @post format.js end end def post_params params.permit(post: [:title, :description, :url, :category_ids => []]) end def find_post @post = Post.where("slug = ?",params[:id]).first #@post = Post.find_by_slug(params[:id]) end end <file_sep>/app/controllers/sessions_controller.rb class SessionsController < ApplicationController def new #leave empty end def create # binding.pry @post = Post.where("slug = ?",session[:modal]).first if session[:modal] user = User.find_by_username(params[:username]) if user && user.authenticate(params[:password]) session[:user_id] = user.id if session[:modal] #@post = Post.find_by_slug(session[:modal]) @comment = Comment.new session[:modal] = false redirect_to post_path(@post) else redirect_to root_path, notice: "Welcome, #{params[:username]}, you are now logged in." end else flash[:error] = "wrong user or password" render :new # redirect_to login_path, error: "wrong user or password" end end def destroy session[:user_id] = nil redirect_to root_path, notice: "logged out" end end
939e64b503cfbeeeed0ed180229cd37d321cff04
[ "RDoc", "Ruby" ]
12
RDoc
steveturczyn/svh1
78fca329f2aabb3bdfbea718a44b7274277303d9
969f13d8a2776ccfe06fa66487ccad9a04e86ff9
refs/heads/master
<repo_name>fim-engineering/backend-sisfo<file_sep>/routes/formCompletenessRoute.js const express = require('express'); const router = express.Router(); const { body } = require('express-validator/check') const formCompletenessController = require('../controllers/formCompletenessController'); const isAuth = require('../middleware/is-auth-middleware'); router.get('', isAuth, formCompletenessController.getFormCompleteness); router.post('/submit', isAuth, formCompletenessController.submitFormCompleteness); module.exports = router;<file_sep>/seeders/20200727135433-add-tunnel-for-fim-22.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Tunnels', [ { id: 9, name: 'Alumni FIM 20', description: 'Merupakan Jalur Kader NextGen FIM yang telah mengikuti Rangkaian Pelatihan FIM Wilayah angkatan 20.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1597599523/icon/Icon-alumni.png', batchFim: '22' }, { id: 10, name: 'Volunteer FIM', description: 'Merupakan anggota relawan FIM Regional yang ditetapkan dalam SK Keanggotaan dari FIM Regional.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1597599523/icon/Icon-volunteer.png', batchFim: '22' }, { id: 11, name: '<NAME>', description: 'Merupakan pemuda, mahasiswa, dan profesional dengan berbagai latar belakang (Non Alumni FIM) dan pernah memiliki pengalaman mengikuti kegiatan FIM baik di FIM Pusat, FIM Regional, maupun kegiatan FIM Club (misal: pernah mengikuti Public Seminar, Webinar FIM, kerjasama komunitas, dll).', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1597599523/icon/Icon-sahabat.png', batchFim: '22' } ]) }, down: async (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Tunnels', { batchFim: '22' }, {}) } }; <file_sep>/models/fimbatch.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Fimbatch = sequelize.define('Fimbatch', { name: DataTypes.STRING, date_start_registration: DataTypes.DATE, date_end_registration: DataTypes.DATE, date_event_start: DataTypes.DATE, date_event_end: DataTypes.DATE, leader: DataTypes.INTEGER, tagline: DataTypes.STRING }, {}); Fimbatch.associate = function(models) { }; return Fimbatch; }; <file_sep>/models/summary.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Summary = sequelize.define('Summary', { ktpNumber: DataTypes.STRING, TunnelId: DataTypes.INTEGER, batchFim: DataTypes.STRING, isFinal: DataTypes.INTEGER, recruiterId: DataTypes.INTEGER, scoreFinal: DataTypes.INTEGER, createdBy: DataTypes.INTEGER, scoreDataDiri: DataTypes.INTEGER, scoreAktivitas: DataTypes.INTEGER, scoreProject: DataTypes.INTEGER, scoreOther: DataTypes.INTEGER, notes: DataTypes.TEXT }, {}); Summary.associate = function (models) { models.Summary.belongsTo(models.Tunnel) models.Summary.belongsTo(models.Identity, { foreignKey: 'ktpNumber', targetKey: 'ktpNumber' }); models.Summary.belongsToMany(models.User, { through: models.ParticipantRecruiter, foreignKey:'ktpNumber' }) }; return Summary; }; <file_sep>/seeders/20190708162106-tunnel.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Tunnels', [ { id: 1, name: '<NAME>', description:'peserta FIM yang akan menjadi kader inti dalam berbagai aktivitas FIM, baik ditingkat pusat maupun regional. Jalur ini dikhususkan bagi alumni FIM 20 yang telah mengikuti pelatihan wilayah pada 2018 lalu untuk meningkatkan kapasitas dan memperluas jejaring dalam skala nasional. Peserta dari jalur ini mendapat peluang kuota sebesar 70%', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/NG_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:2, name: '<NAME>', description:'calon peserta FIM yang merupakan pimpinan/aktivis atau calon pemimpin kampus yang memiliki misi untuk mendapat posisi strategis di organisasi kemahasiswaan. Peserta dari jalur ini diharapkan memperkuat jejaring stategis & kolaborasi pemimpin kampus untuk memberikan impact yang lebih nyata. FIM terbuka bagi setiap calon peserta dengan berbagai model organisasi asalkan sepakat untuk open mind dan menjaga koridor yang terstruktur dalam menghadapi perbedaan.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/CL_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:3, name: '<NAME>', description: 'calon peserta FIM yang merupakan pegiat yang fokus membangun kapasitas atau pemberdayaan masyarakat lokal di lingkungan daerah tempat tinggalnya. Jalur ini diharapkan bisa memberikan exposure yang lebih baik bagi para pejuang kerja-kerja basis, sekaligus memperbesar skala dan impact pekerjaannya. Aktivis yang dimaksud tidak terbatas pada kegiatan sosial saja, melainkan juga kegiatan ekonomi, politik, budaya, dan lainnya yang memiliki akar kuat di masyarakat', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/LL_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:4, name: '<NAME>', description: 'calon peserta yang berasal dari profesional muda yang telah bekerja selama 1-5 tahun setelah lulus kuliah. Peserta dari jalur ini diharapkan bisa mengamplifikasi FIM kepada jejaring profesional secara lebih luas, agar mampu meningkatkan social impact dari berbagai program FIM. Bagi profesional muda yang berasal dari perusahaan yang masuk dalam 500 Fortune Indonesia akan menjadi prioritas.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328024/icon/YP_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:5, name: '<NAME>', description: 'merupakan calon peserta dari jalur ini menyasar pada anak muda yang bercita-cita untuk menjadi expert/specialist di bidang/keilmuan tertentu. Jalur ini diharapkan bisa mengakselerasi proses transfer knowledge dan network creation dalam mencetak expert Indonesia di masa depan Bagi calon peserta yang juga pebisnis, bisa mendaftar melalui jalur ini untuk saling memperkuat benefit yang didapatkan dari network FIM', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328024/icon/YE_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:6, name: '<NAME>', description: 'bagi calon peserta merupakan anak muda yang mengambil karir sebagai aparatur sipil negara. Jalur ini diharapkan mampu mengkonsolidasikan berbagai ide dan inisiatif jejaring FIM mengenai reformasi birokrasi ataupun perbaikan layanan bagi masyarakat. FIM percaya bahwa mendorong perubahan birokrasi / pemerintahan oleh anak-anak muda merupakan kontribusi yang menjadi prioritas aksi nyata saat ini.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/PS_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:7, name: 'Military', description: 'jalur khusus yang diadakan untuk para calon pemimpin Indonesia di masa depan yang berasal dari militer (AD, AL, AU, dan polisi). Calon peserta merupakan top performer dari berbagai jalur di akademi militer dan kepolisian', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/MI_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' }, { id:8, name: 'Influencer', description: 'diperuntukan bagi calon peserta FIM yang mewakili spirit dan karakter generasi millennial sebagai digital influencer, tech savvy dengan jangkauan network yang luas. Peserta dari jalur ini memiliki misi untuk memperkuat digital movement dari berbagai kampanye program FIM. FIM percaya bahwa masa depan Indonesia dipengaruhi oleh banyaknya berbagai kampanye kebaikan berbasis online. Digital footprint FIM diharapkan bisa menjadi role model bagi gerakan anak muda lainnya.', createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: 'https://res.cloudinary.com/fim-indonesia/image/upload/v1563328023/icon/IF_-_IKON_JALUR_MASUK_-_WEB_-_ILUSTRASI.png', batchFim: '21' } ], {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Tunnels', null, {}); } }; <file_sep>/migrations/20190714154657-add religion and url Photo tunnel.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return Promise.all([ queryInterface.addColumn('Identities', 'otherReligion', {type:Sequelize.STRING}), queryInterface.addColumn('Tunnels', 'urlPicture', {type:Sequelize.STRING}), queryInterface.changeColumn('Answers', 'answer', {type:Sequelize.TEXT('long')}) ]); }, down: (queryInterface, Sequelize) => { return Promise.all([ queryInterface.removeColumn('Identities', 'otherReligion'), queryInterface.removeColumn('Tunnels', 'urlPicture'), queryInterface.changeColumn('Answers', 'answer', {type:Sequelize.TEXT}) ]); } }; <file_sep>/seeders/20200805170810-add_quesiton_pivot_fim22.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return queryInterface.bulkInsert('tunnelQuestions', [ { id: 100, TunnelId: 9, QuestionId: 36, createdAt: new Date(), updatedAt: new Date() }, { id: 101, TunnelId: 10, QuestionId: 36, createdAt: new Date(), updatedAt: new Date() }, { id: 102, TunnelId: 11, QuestionId: 36, createdAt: new Date(), updatedAt: new Date() }, { id: 103, TunnelId: 9, QuestionId: 37, createdAt: new Date(), updatedAt: new Date() }, { id: 104, TunnelId: 10, QuestionId: 37, createdAt: new Date(), updatedAt: new Date() }, { id: 105, TunnelId: 11, QuestionId: 37, createdAt: new Date(), updatedAt: new Date() }, { id: 106, TunnelId: 9, QuestionId: 38, createdAt: new Date(), updatedAt: new Date() }, { id: 107, TunnelId: 10, QuestionId: 38, createdAt: new Date(), updatedAt: new Date() }, { id: 108, TunnelId: 11, QuestionId: 38, createdAt: new Date(), updatedAt: new Date() }, { id: 109, TunnelId: 9, QuestionId: 39, createdAt: new Date(), updatedAt: new Date() }, { id: 110, TunnelId: 10, QuestionId: 39, createdAt: new Date(), updatedAt: new Date() }, { id: 111, TunnelId: 11, QuestionId: 39, createdAt: new Date(), updatedAt: new Date() }, { id: 112, TunnelId: 9, QuestionId: 40, createdAt: new Date(), updatedAt: new Date() }, { id: 113, TunnelId: 10, QuestionId: 40, createdAt: new Date(), updatedAt: new Date() }, { id: 114, TunnelId: 11, QuestionId: 40, createdAt: new Date(), updatedAt: new Date() }, { id: 115, TunnelId: 9, QuestionId: 41, createdAt: new Date(), updatedAt: new Date() }, { id: 116, TunnelId: 10, QuestionId: 41, createdAt: new Date(), updatedAt: new Date() }, { id: 117, TunnelId: 11, QuestionId: 41, createdAt: new Date(), updatedAt: new Date() }, { id: 118, TunnelId: 9, QuestionId: 42, createdAt: new Date(), updatedAt: new Date() }, { id: 119, TunnelId: 10, QuestionId: 42, createdAt: new Date(), updatedAt: new Date() }, { id: 120, TunnelId: 11, QuestionId: 42, createdAt: new Date(), updatedAt: new Date() }, { id: 121, TunnelId: 9, QuestionId: 43, createdAt: new Date(), updatedAt: new Date() }, { id: 122, TunnelId: 10, QuestionId: 43, createdAt: new Date(), updatedAt: new Date() }, { id: 123, TunnelId: 11, QuestionId: 43, createdAt: new Date(), updatedAt: new Date() }, { id: 124, TunnelId: 9, QuestionId: 44, createdAt: new Date(), updatedAt: new Date() }, { id: 125, TunnelId: 10, QuestionId: 44, createdAt: new Date(), updatedAt: new Date() }, { id: 126, TunnelId: 11, QuestionId: 44, createdAt: new Date(), updatedAt: new Date() }, { id: 127, TunnelId: 9, QuestionId: 45, createdAt: new Date(), updatedAt: new Date() }, { id: 128, TunnelId: 10, QuestionId: 45, createdAt: new Date(), updatedAt: new Date() }, { id: 129, TunnelId: 11, QuestionId: 45, createdAt: new Date(), updatedAt: new Date() }, { id: 130, TunnelId: 9, QuestionId: 46, createdAt: new Date(), updatedAt: new Date() }, { id: 131, TunnelId: 10, QuestionId: 46, createdAt: new Date(), updatedAt: new Date() }, { id: 132, TunnelId: 11, QuestionId: 46, createdAt: new Date(), updatedAt: new Date() }, { id: 133, TunnelId: 9, QuestionId: 47, createdAt: new Date(), updatedAt: new Date() }, { id: 134, TunnelId: 10, QuestionId: 47, createdAt: new Date(), updatedAt: new Date() }, { id: 135, TunnelId: 11, QuestionId: 47, createdAt: new Date(), updatedAt: new Date() }, { id: 136, TunnelId: 9, QuestionId: 48, createdAt: new Date(), updatedAt: new Date() }, { id: 137, TunnelId: 10, QuestionId: 48, createdAt: new Date(), updatedAt: new Date() }, { id: 138, TunnelId: 11, QuestionId: 48, createdAt: new Date(), updatedAt: new Date() }, { id: 139, TunnelId: 9, QuestionId: 49, createdAt: new Date(), updatedAt: new Date() }, { id: 140, TunnelId: 10, QuestionId: 49, createdAt: new Date(), updatedAt: new Date() }, { id: 141, TunnelId: 11, QuestionId: 49, createdAt: new Date(), updatedAt: new Date() }, { id: 142, TunnelId: 9, QuestionId: 50, createdAt: new Date(), updatedAt: new Date() }, { id: 143, TunnelId: 10, QuestionId: 50, createdAt: new Date(), updatedAt: new Date() }, { id: 144, TunnelId: 11, QuestionId: 50, createdAt: new Date(), updatedAt: new Date() }, { id: 145, TunnelId: 9, QuestionId: 51, createdAt: new Date(), updatedAt: new Date() }, { id: 146, TunnelId: 10, QuestionId: 51, createdAt: new Date(), updatedAt: new Date() }, { id: 147, TunnelId: 11, QuestionId: 51, createdAt: new Date(), updatedAt: new Date() }, { id: 149, TunnelId: 10, QuestionId: 52, createdAt: new Date(), updatedAt: new Date() }, { id: 150, TunnelId: 11, QuestionId: 53, createdAt: new Date(), updatedAt: new Date() } ]) }, down: async (queryInterface, Sequelize) => { return await queryInterface.bulkDelete('tunnelQuestions', {id: {$between: [100,150]}}, {}) } }; <file_sep>/app.js // require('newrelic'); const path = require('path'); require('dotenv').config({ path: path.join(__dirname, '.env') }); const express = require('express'); const bodyParser = require('body-parser'); const helmet = require('helmet'); const compression = require('compression'); const { Client } = require('pg'); var cors = require('cors') // Route Require const userRoute = require('./routes/userRoute'); const homeRoute = require('./routes/homeRoute'); const dataRoute = require('./routes/dataRoute'); const tunnelRoute = require('./routes/tunnelRoute'); const questionRoute = require('./routes/questionRoute'); const answerRoute = require('./routes/answerRoute'); const summaryRoute = require('./routes/summaryRoute'); const recruiterRoute = require('./routes/recruiterRoute'); const regionalRoute = require('./routes/regionalRoute'); const participantRoute = require('./routes/participantRoute'); const documentRoute = require('./routes/documentRoute'); const formCompletenessRoute = require('./routes/formCompletenessRoute'); // init express js const app = express(); app.use(cors()); app.options('*', cors()) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // CORS app.use((req,res,next)=> { res.setHeader('Access-Control-Allow-Origin', '*' ); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE' ); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); next(); }); // Auth Route app.use('/auth', userRoute); app.use('/', homeRoute) app.use('/data', dataRoute); app.use('/tunnel', tunnelRoute); app.use('/question', questionRoute); app.use('', answerRoute); app.use('/summary', summaryRoute); app.use('/recruiter', recruiterRoute); app.use('/regional', regionalRoute); app.use('/participant', participantRoute); app.use('/document', documentRoute); app.use('/form-completeness', formCompletenessRoute); app.use(helmet()); app.use(compression()); app.listen( process.env.PORT||8080); <file_sep>/controllers/questionController.js const model = require('../models/index'); const redisClient = require('../util/redis'); exports.getAll = async (req, res, next) => { const findTunnel = await model.Tunnel.findOne({ where: { id: req.query.tunnelId, batchFim: req.query.batchFim }, include: [{ model: model.Question, order: [['id', 'ASC']] }] }) if (findTunnel == null) { res.status(200).json({ status: true, message: "Data Fetched", data: [] }); } else { var questions = findTunnel.Questions if (questions) { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": questions }) } else { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": [] }) } } } exports.create = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; const data = { question: req.body.question, isMany: req.body.isMany, header: JSON.stringify(req.body.header), TunnelId: req.body.TunnelId, batchFim: req.body.batchFim, createdBy: userId } if (err) { return res.status(400).json({ status: false, message: "Token Expired", data: err }); } model.Question.create(data).then(result => { res.status(200).json({ status: true, message: "Data Created", data: result }); }).catch(err => { res.status(400).json({ status: false, message: "Error", data: err }); }) }); } exports.read = async (req, res, next) => { const idQuestion = req.body.idQuestion; model.Question.findByPk(idQuestion).then(result => { res.status(200).json({ status: true, message: "Data Fetched", data: result }); }) } exports.update = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; if (err) { return res.status(400).json({ status: false, message: "Token Expired", data: err }); } const data = { idQuestion: req.body.idQuestion, question: req.body.question, isMany: req.body.isMany, header: JSON.stringify(req.body.header), TunnelId: req.body.TunnelId, batchFim: req.body.batchFim, createdBy: userId } model.Question.update(data, { where: { id: data.idQuestion } } ).then((status, result) => { res.status(200).json({ status: true, message: "Data Updated", data: status }); }).catch(err => { res.status(400).json({ status: false, message: "Error", data: err }); }) }); } exports.delete = async (req, res, next) => { model.Question.destroy({ where: { id: req.body.idQuestion } }).then(result => { res.status(200).json({ status: true, message: "Data Deleted", data: null }); }).catch(err => { console.log(err) res.status(400).json({ status: false, message: "Error Occured", data: err }); }) } <file_sep>/controllers/dataController.js const model = require('../models/index'); const dataUniv = require('../data/university-list.json'); const Sequelize = require('sequelize'); const Op = Sequelize.Op const Excel = require('exceljs'); // const ExcelJS = require('exceljs/dist/es5'); const path = require('path'); exports.getUniversity = async (req, res, next) => { res.status(200).json({ status: true, message: "university data fetched", data: dataUniv }); } exports.downloadExcel = async (req, res, next) => { const list = req.body.listCheck; // array const test = ['Nama', 'email', 'no HP', 'KTP', 'Regional Saat Ini', 'Editing Video Status', 'Regional Pengembangan']; // Mencari Batch FIM Paling Terakhir const fimBatch = await model.Fimbatch.findAll({ limit: 1, order: [['id', 'DESC']] }).then(result => { return result[0] }) // All submit const allSubmit = await model.Summary.findAll({ where: { isFinal: 1, updatedAt: { $between: [fimBatch.date_start_registration, fimBatch.date_end_registration] } } }).then(result => { return result }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }); const listLolosKtp = []; if (req.query.fimBatch) { const listLolos = await model.Identity.findAll({ where: { status_accept: 2 }, attributes: ['batchFim', 'ktpNumber'] }).then(result => { JSON.parse(JSON.stringify(result)).map((value, index) => { listLolosKtp.push(value.ktpNumber) }) }) } const listKTPSubmitted = []; await allSubmit.map((value, index) => { listKTPSubmitted.push(value.ktpNumber); }) const listIdentity = await model.Identity.findAndCountAll({ where: { ktpNumber: { [Op.in]: req.query.fimBatch && listLolosKtp > 0 ? listLolosKtp : listKTPSubmitted } }, // attributes: ['userId', 'name', 'ktpNumber', 'video_editing'], include: [ { model: model.Summary, where: { isFinal: 1 }, include: [{ model: model.Tunnel, attributes: ['name'] }] }, { model: model.User, include: [{ model: model.Regional, attributes: ['name', 'city', 'province'] }] }, ] }).then(result => { return result.rows }).catch(err => { console.log(err) }) // Pengembangan Regional const JawabanRegionalBaru = await model.Answer.findAll({ where: { QuestionId: 47, ktpNumber: { $in: listKTPSubmitted } } }).then(answ => { const ans = JSON.parse(JSON.stringify(answ)); return ans; // if (ans !== null) { // const extract = JSON.parse(ans.answer); // const jawab = extract.answer; // const newRegional = extract['Membangun Regional Baru']; // } }) // console.log(JawabanRegionalBaru) const restructurization = []; await Promise.all([ listIdentity.map(async (value) => { const jawb = JawabanRegionalBaru.filter((regi) => { return value.ktpNumber == regi.ktpNumber }) let extract = null; let jawab = null; let newRegional = null; if (jawb[0] !== undefined) { extract = JSON.parse(jawb[0].answer); jawab = extract.answer; newRegional = extract['Membangun Regional Baru']; } restructurization.push({ name: value.name, email: value.User.email, phone: value.phone, ktpNumber: value.ktpNumber, jalur: value.Summaries !== null ? value.Summaries[0].Tunnel.name : null, regional: value.User.Regional !== null ? value.User.Regional.city : null, videoEdit: value.video_editing, nextActivity: jawab, newRegional: newRegional, mbti:value.mbti }) }) ]).then(result => { res.status(200).json({ status: true, message: "data fetched", data: restructurization }); }) // console.log(JSON.parse(JSON.stringify(listIdentity))) // Create Workbook // const workbook = new Excel.Workbook(); // const sheet = workbook.addWorksheet('Data Calon Anggota FIM'); // const worksheet = workbook.getWorksheet('Data Calon Anggota FIM'); // worksheet.columns = [ // { header: 'Id', key: 'id', width: 10 }, // { header: 'Name', key: 'name', width: 32 }, // { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } // ]; // // Insert a row by sparse Array (assign to columns A, E & I) // worksheet.insertRow(1, { id: 1, name: '<NAME>', dob: new Date(1970, 1, 1) }); // worksheet.insertRow(1, { id: 2, name: '<NAME>', dob: new Date(1965, 1, 7) }); // const thefile = await workbook.xlsx.writeFile('exports.xls'); // const file = await path.join(__dirname, '/exports.xls'); // console.log(file); // if (list.includes('Nama')) { // } // res.download(file) } <file_sep>/controllers/documentController.js const model = require('../models/index'); const redisClient = require('../util/redis'); exports.getDocument = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; model.PersonalDocument.findOne({ where: { userId: userId } }).then(result => { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": result }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) }) } exports.saveDocument = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; validateDocumentRequestBody(req.body) const data = { userId: userId, identityFileUrl: req.body.identityFileUrl.trim(), recommendationLetterUrl: req.body.recommendationLetterUrl.trim(), commitmentLetterUrl: req.body.commitmentLetterUrl.trim() } const findPersonalDocument = await model.PersonalDocument.findOne({ where: { userId: userId }, attributes: { exclude: ['userId', 'createdAt', 'updatedAt'] } }) if (findPersonalDocument == null) { await model.PersonalDocument.create(data) .then(result => { setFourthFormCompletenessToTrue(userId) return res.status(200).json({ "status": true, "message": "Data Inserted", "data": result }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findPersonalDocument.update(data) .then(result => { setFourthFormCompletenessToTrue(userId) return res.status(200).json({ "status": true, "message": "Data Updated", "data": result }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function validateDocumentRequestBody(reqBody) { if (!reqBody.identityFileUrl || reqBody.identityFileUrl.trim() == "") throw new Error('identityFileUrl is required!'); if (!reqBody.recommendationLetterUrl || reqBody.recommendationLetterUrl.trim() == "") throw new Error('recommendationLetterUrl is required!'); if (!reqBody.commitmentLetterUrl || reqBody.commitmentLetterUrl.trim() == "") throw new Error('commitmentLetterUrl is required!'); } function setFourthFormCompletenessToTrue(userId) { model.FormCompleteness.findOne({ where: { userId: userId }}) .then(formCompleteness => { data = { userId: userId, fimBatch: "23", /* TODO: Make it dynamic */ isFourthStepCompleted: true } if (formCompleteness == null) { model.FormCompleteness.create(data) .catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { formCompleteness.update(data) .catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) }<file_sep>/migrations/20200731143108-add more field to profile.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.addColumn('Identities', 'occupation', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'instagram', { type: Sequelize.TEXT }), queryInterface.addColumn('Identities', 'twitter', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'facebook', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'website', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'reference_by', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'video_editing', { type: Sequelize.STRING }), ]) }, down: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.removeColumn('Identities', 'occupation'), queryInterface.removeColumn('Identities', 'instagram'), queryInterface.removeColumn('Identities', 'twitter'), queryInterface.removeColumn('Identities', 'facebook'), queryInterface.removeColumn('Identities', 'website'), queryInterface.removeColumn('Identities', 'reference_by'), queryInterface.removeColumn('Identities', 'video_editing'), ]) } }; <file_sep>/models/personalDocument.js 'use strict'; module.exports = (sequelize, DataTypes) => { const personalDocument = sequelize.define('PersonalDocument', { userId: DataTypes.INTEGER, identityFileUrl: DataTypes.STRING, recommendationLetterUrl: DataTypes.STRING, commitmentLetterUrl: DataTypes.STRING }, {}); personalDocument.associate = function (models) { models.PersonalDocument.belongsTo(models.User, { foreignKey: 'userId' }) }; return personalDocument; };<file_sep>/seeders/20190718224031-update-question-nextgen.js 'use strict'; const model = require('../models'); const dataUpdate = { note: '<a href="`https://res.cloudinary.com/fim-indonesia/raw/upload/v1563242868/document/SURAT_PERNYATAAN_KOMITMEN_DIRI.docx`">Format Terlampir</a>' } const dataDown = { note: null } module.exports = { up: (queryInterface, Sequelize) => { return model.Question.update(dataUpdate, { where: { id: 4 }}) }, down: (queryInterface, Sequelize) => { return model.Question.update(dataDown, { where: { id: 4 }}) } }; <file_sep>/routes/userRoute.js const express = require('express'); const router = express.Router(); const { body } = require('express-validator/check') const userController = require('../controllers/userController'); const isAuth = require('../middleware/is-auth-middleware'); router.post('/login', userController.socialLogin); router.post('/checksession', userController.checkSession); router.get('/profile', isAuth, userController.getProfile); router.post('/profile/identity', isAuth, userController.saveIdentity); router.post('/profile/skill', isAuth, userController.saveSkill); router.post('/profile/social-media', isAuth, userController.saveSocialMedia); router.post('/profile/alumni-reference', isAuth, userController.saveAlumniReference); router.post('/profile/fim-activity', isAuth, userController.saveFimActivity); router.post('/profile/organization-experience', isAuth, userController.saveOrganizationExperience); router.post('/save-tunnel', isAuth, userController.saveTunnel); module.exports = router;<file_sep>/migrations/20200809093227-create-fimbatch.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('Fimbatches', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, name: { type: Sequelize.STRING }, date_start_registration: { type: Sequelize.DATE }, date_end_registration: { type: Sequelize.DATE }, date_event_start: { type: Sequelize.DATE }, date_event_end: { type: Sequelize.DATE }, leader: { type: Sequelize.INTEGER }, tagline: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('Fimbatches'); } };<file_sep>/controllers/recruiterController.js const model = require('../models/index'); const redisClient = require('../util/redis'); const Sequelize = require('sequelize'); const Op = Sequelize.Op exports.addAdmin = async (req, res, next) => { const email = req.body.email; let therole = 1; const findUser = await model.User.findOne({ where: { email: email } }).then(result => { return result }).catch(err => { return res.status(400).json({ status: false, message: "Whoops Something Error Line 16", data: err }); }) // update role 3 untuk admin yang nambah recruiter if (findUser !== null) { model.Identity.findOne({ where: { userId: findUser.id } }).then(result => { if (req.params.type == "admin") { therole = 3; } else if (req.params.type == "recruit") { therole = 2; } // update role result.update({ role: therole }).then(result => { res.status(200).json({ status: true, message: "Admin Added", data: { name: result.name, email: result.email, role: result.role } }); }).catch(err => { return res.status(400).json({ status: false, message: "Whoops Something Error Lin2 40", error: err }); }) }).catch(err => { return res.status(400).json({ status: false, message: "Whoops Something Error Line 47 KTP number not found", error: err }); }) } else { return res.status(200).json({ status: false, message: "User Not Found" }); } } exports.listSubmitted = async (req, res, next) => { const fimBatch = await model.Fimbatch.findAll({ limit: 1, order: [['id', 'DESC']] }).then(result => { return result[0] }) // Cari yang sudah submit final const allSubmit = await model.Summary.findAll({ where: { isFinal: 1, updatedAt: { $between: [fimBatch.date_start_registration, fimBatch.date_end_registration] } } }).then(result => { return result }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }); // dapatktpsubmit const listKTPSubmitted = []; if (allSubmit !== null) { await allSubmit.map((value, index) => { listKTPSubmitted.push(value.ktpNumber); }) } else { return res.status(200).json({ status: false, message: "No One Submitted", data: null }); } // query jika ada parameter fimBatch maka ambil peserta yang statusnya seperti nama fim dan kode x bagi yang tidak bisa ikut const listLolosKtp = []; if (req.query.fimBatch) { const listLolos = await model.Identity.findAll({ where: { status_accept: 2 }, attributes: ['batchFim', 'ktpNumber'] }).then(result => { JSON.parse(JSON.stringify(result)).map((value, index) => { listLolosKtp.push(value.ktpNumber) }) }) } // fetch recruiter dari masing-masing peserta const listRecruiter = await model.ParticipantRecruiter.findAll({}).then(result => { return JSON.parse(JSON.stringify(result)) }).catch(err => { console.log(err) }) const listRecruiterParticipant = []; const listIdentity = await model.Identity.findAndCountAll({ where: { ktpNumber: { [Op.in]: req.query.fimBatch && listLolosKtp.length > 0 ? listLolosKtp : listKTPSubmitted } }, attributes: [ 'userId', 'name', 'ktpNumber', 'status_accept', 'batchFim', 'attendenceConfirmationDate', 'mbti', 'paymentDate', 'bankTransfer', 'urlTransferPhoto', 'phone' ], include: [ { model: model.Summary, where: { isFinal: 1 }, include: [{ model: model.Tunnel, attributes: ['name'] }] }, { model: model.User, include: [{ model: model.Regional, attributes: ['name', 'city', 'province'] }] }, ] }).then(result => { return result.rows }).catch(err => { console.log(err) }) // Menambahkan list recruiter yang ditugaskan await listIdentity.map(async (value) => { const rec = await listRecruiter.filter((recruit) => { return recruit.ktpNumber == value.ktpNumber }) // console.log(rec) await listRecruiterParticipant.push({ ...JSON.parse(JSON.stringify(value)), recruiters: rec }) }) return res.status(200).json({ status: true, message: "Data Fetched", data: listRecruiterParticipant }); } exports.listRecruiter = async (req, res, next) => { model.Identity.findAll({ where: { role: { $in: [2, 3] }, }, attributes: ['name', 'ktpNumber', 'phone', 'email', 'batchFim'] }).then(result => { return res.status(200).json({ status: true, message: "Data Fetched", data: result }); }).catch(err => { console.log(err) }) } exports.newAssignRecruiter = async (req, res, next) => { const theRecruiter = await model.User.findOne({ where: { email: req.body.emailRecruiter, }, include: [ { model: model.Identity } ], attributes: ['id'] }).then(result => { return result }).catch(err => { console.log(err) }) try { model.ParticipantRecruiter.findOrCreate({ where: { ktpNumber: req.body.ktpParticipant, recruiterId: theRecruiter.id, emailRecruiter: req.body.emailRecruiter, nameRecruiter: theRecruiter.Identity.name } }) res.status(200).json({ status: true, message: "Recruiter Assigned", }); } catch (error) { res.status(200).json({ status: false, message: error, }); } } exports.assignRecruiter = async (req, res, next) => { const ktpRecruiter = req.body.ktpRecruiter; const listPeserta = req.body.ktpPeserta; // array // const ArrayPeserta: []; // listPeserta.map((value,index)=>{ // value. // }) // findRecruiter const theRecruiter = await model.Identity.findOne({ where: { email: req.body.emailRecruiter, }, attributes: ['id', 'name', 'userId'] }).then(result => { return result }).catch(err => { console.log(err) }) if (theRecruiter !== null) { // update Summary const listSummary = await model.Summary.findOne({ where: { ktpNumber: req.body.ktpNumberPeserta, TunnelId: req.body.TunnelId }, // attributes: ['ktpNumber'] }).then(result => { return result; }).catch(err => console.log(err)) if (listSummary !== null) { // await listSummary.map((value, index) => { listSummary.update({ recruiterId: theRecruiter.userId }) // }) return res.status(200).json({ status: true, message: "Participant Assigned to " + theRecruiter.name }); } else { return res.status(200).json({ status: false, message: "Participant List Null" }); } } else { return res.status(200).json({ status: false, message: "Recruiter User Not Found" }); } } exports.listByRecruiter = async (req, res, next) => { const emailRecruiter = req.body.emailRecruiter; if (req.query.ktpNum !== undefined) { const allSubmit = await model.Summary.findAll({ where: { isFinal: 1, ktpNumber: req.query.ktpNum }, include: [ { model: model.Identity, include: [ { model: model.User, include: [{ model: model.Regional, attributes: ['name', 'city', 'province'] }] }, ] }, { model: model.Tunnel, where: { batchFim: { $in: ['22', '22x'] } } }, ] }).then(result => { return result }).catch(err => { console.log(err) }); return res.status(200).json({ status: true, message: "Data Fetched", data: allSubmit }); } const theIdUser = await model.User.findOne({ where: { email: emailRecruiter } }).then(result => { return result.id }).catch(err => { return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }) const listsParticipants = []; const findListParticipant = await model.ParticipantRecruiter.findAll({ where: { recruiterId: theIdUser } }).then(result => { const strResult = JSON.parse(JSON.stringify(result)) strResult.map((value) => { listsParticipants.push(value.ktpNumber) }) }).catch(err => console.log(err)) const allSubmit = await model.Summary.findAll({ where: { isFinal: 1, ktpNumber: { $in: listsParticipants } }, include: [ { model: model.Identity }, { model: model.Tunnel, where: { batchFim: { $in: ['22', '22x'] } } }, ] }).then(result => { return result }).catch(err => { console.log(err) }); // const listKTPSubmitted = []; // if (allSubmit !== null) { // await allSubmit.map((value, index) => { // listKTPSubmitted.push(value.ktpNumber); // }) // } else { // return res.status(200).json({ // status: false, // userId:theIdUser, // message: "No One Submitted", // data: null // }); // } // const listIdentity = await model.Identity.findAll({ // where: { // ktpNumber: { [Op.in]: listKTPSubmitted } // }, // attributes: ['userId', 'name', 'ktpNumber'], // include: [{ // model: model.Summary, // where: { isFinal: 1 }, // include: [{ // model: model.Tunnel, // attributes: ['name', 'id'] // }] // }] // }).then(result => { // return result // }).catch(err => { // return res.status(400).json({ // status: false, // message: "Whoops Something Error", // error: err // }); // }) return res.status(200).json({ status: true, message: "Data Fetched", data: allSubmit }); } exports.detailParticipant = async (req, res, next) => { const TunnelId = req.body.TunnelId; const ktpNumber = req.body.ktpNumber; model.Identity.findOne({ where: { ktpNumber: ktpNumber, userId: { [Op.ne]: null } }, include: [ { model: model.Summary, where: { isFinal: 1 }, include: [ { model: model.Tunnel, attributes: ['name', 'id'] }, ] }, { model: model.Answer, where: { TunnelId: TunnelId }, include: [ { model: model.Tunnel }, { model: model.Question } ] } ] }).then(result => { return res.status(200).json({ status: true, message: "Data Fetched", data: result }); }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }) } exports.updateScore = async (req, res, next) => { const TunnelId = req.body.TunnelId; const ktpNumber = req.body.ktpNumber; model.Summary.findOne({ where: { ktpNumber: ktpNumber, TunnelId: TunnelId }, }).then(async result => { await result.update({ scoreDataDiri: req.body.scoreDataDiri, scoreAktivitas: req.body.scoreAktivitas, scoreProject: req.body.scoreProject, scoreOther: req.body.scoreOther, scoreFinal: parseInt(req.body.scoreDataDiri, 10) * 0.15 + parseInt(req.body.scoreAktivitas, 10) * 0.5 + parseInt(req.body.scoreProject, 10) * 0.3 + parseInt(req.body.scoreOther, 10) * 0.05, notes: req.body.notes }).then(result => { return res.status(200).json({ status: true, message: "Score Updated", data: result }); }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }) }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }) } exports.addRecruiter = async (req, res, next) => { const email = req.body.email; const findIdentity = await model.Identity.findOne({ where: { email: email } }).then(resp => { return resp; }).catch(err => { console.log(err) }) if (findIdentity == null) { model.Identity.create({ email: email, role: 2 }).then(resp => { return res.status(200).json({ status: true, message: "Recruiter " + email + " Added", }); }) } else { if (findIdentity.role == 2) { return res.status(200).json({ status: false, message: "Recruiter " + email + " Already Exists", }); } else { findIdentity.update({ role: 2 }).then(result => { return res.status(200).json({ status: true, message: "Recruiter " + email + " Updated", }); }).catch(err => { return res.status(400).json({ status: false }); }) } } } exports.availableAssing = (req, res, next) => { const email = req.body.email; model.Summary.findAll({ where: { recruiterId: null, isFinal: 1, }, include: [ { model: model.Identity }, { model: model.Tunnel }, ] }).then(result => { return res.status(200).json({ status: true, message: "Lists Fetched", data: result }); }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Something Error " + err, }); }) } exports.toAssign = async (req, res, next) => { const email = req.body.email; // find UserId const theRecuiter = await model.Identity.findOne({ where: { email: email } }).then(result => { return result }).catch(err => { console.log(err) }) model.Summary.findAll({ where: { recruiterId: theRecuiter.userId }, include: [ { model: model.Identity }, { model: model.Tunnel }, ] }).then(result => { return res.status(200).json({ status: true, message: "Lists Fetched", data: result }); }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Something Error " + err, }); }) } exports.undoAssign = async (req, res, next) => { // findRecruiter const theRecruiter = await model.Identity.findOne({ where: { email: req.body.emailRecruiter, }, attributes: ['id', 'name', 'userId'] }).then(result => { return result }).catch(err => { console.log(err) }) if (theRecruiter !== null) { // update Summary const listSummary = await model.Summary.findOne({ where: { ktpNumber: req.body.ktpNumberPeserta, TunnelId: req.body.TunnelId }, // attributes: ['ktpNumber'] }).then(result => { return result; }).catch(err => console.log(err)) if (listSummary !== null) { // await listSummary.map((value, index) => { listSummary.update({ recruiterId: null }) // }) return res.status(200).json({ status: true, message: "Participant Assigned to " + theRecruiter.name }); } else { return res.status(200).json({ status: false, message: "Participant List Null" }); } } else { return res.status(200).json({ status: false, message: "Recruiter User Not Found" }); } } exports.removeAssignRecruiter = async (req, res, next) => { const ktpNumber = req.body.ktpParticipant; const recruiterId = req.body.recruiterId; model.ParticipantRecruiter.destroy({ where: { ktpNumber: ktpNumber, recruiterId: recruiterId } }).then(result => { res.status(200).json({ status: true, message: "Data Deleted", data: result }); }).catch(err => { res.status(400).json({ status: false, message: "Error Occured", data: err }); }) }<file_sep>/models/participantrecruiter.js 'use strict'; module.exports = (sequelize, DataTypes) => { const ParticipantRecruiter = sequelize.define('ParticipantRecruiter', { ktpNumber: DataTypes.STRING, recruiterId: DataTypes.INTEGER, emailRecruiter: DataTypes.STRING, nameRecruiter: DataTypes.STRING, }, {}); ParticipantRecruiter.associate = function(models) { models.ParticipantRecruiter.belongsTo(models.User, { foreignKey: 'recruiterId', targetKey: 'id' }); }; return ParticipantRecruiter; }; <file_sep>/seeders/20190715170427-add question Pivot Data.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('People', [{ name: '<NAME>', isBetaMember: false }], {}); */ return queryInterface.bulkInsert('tunnelQuestions', [ { id: 1, TunnelId: 1, QuestionId: 1, createdAt: new Date(), updatedAt: new Date() }, { id: 2, TunnelId: 1, QuestionId: 2, createdAt: new Date(), updatedAt: new Date() }, { id: 3, TunnelId: 1, QuestionId: 3, createdAt: new Date(), updatedAt: new Date() }, { id: 4, TunnelId: 1, QuestionId: 4, createdAt: new Date(), updatedAt: new Date() }, { id: 5, TunnelId: 1, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 6, TunnelId: 2, QuestionId: 5, createdAt: new Date(), updatedAt: new Date() }, { id: 7, TunnelId: 2, QuestionId: 6, createdAt: new Date(), updatedAt: new Date() }, { id: 8, TunnelId: 2, QuestionId: 7, createdAt: new Date(), updatedAt: new Date() }, { id: 9, TunnelId: 2, QuestionId: 8, createdAt: new Date(), updatedAt: new Date() }, { id: 10, TunnelId: 2, QuestionId: 9, createdAt: new Date(), updatedAt: new Date() }, { id: 11, TunnelId: 2, QuestionId: 10, createdAt: new Date(), updatedAt: new Date() }, { id: 12, TunnelId: 2, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 13, TunnelId: 2, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 14, TunnelId: 2, QuestionId: 4, createdAt: new Date(), updatedAt: new Date() }, { id: 15, TunnelId: 2, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 16, TunnelId: 2, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 17, TunnelId: 2, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 18, TunnelId: 2, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 19, TunnelId: 3, QuestionId: 5, createdAt: new Date(), updatedAt: new Date() }, { id: 20, TunnelId: 3, QuestionId: 6, createdAt: new Date(), updatedAt: new Date() }, { id: 21, TunnelId: 3, QuestionId: 7, createdAt: new Date(), updatedAt: new Date() }, { id: 22, TunnelId: 3, QuestionId: 8, createdAt: new Date(), updatedAt: new Date() }, { id: 23, TunnelId: 3, QuestionId: 9, createdAt: new Date(), updatedAt: new Date() }, { id: 24, TunnelId: 3, QuestionId: 16, createdAt: new Date(), updatedAt: new Date() }, { id: 25, TunnelId: 3, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 26, TunnelId: 3, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 27, TunnelId: 3, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 28, TunnelId: 3, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 29, TunnelId: 3, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 30, TunnelId: 3, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 31, TunnelId: 3, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 32, TunnelId: 4, QuestionId: 18, createdAt: new Date(), updatedAt: new Date() }, { id: 33, TunnelId: 4, QuestionId: 19, createdAt: new Date(), updatedAt: new Date() }, { id: 34, TunnelId: 4, QuestionId: 20, createdAt: new Date(), updatedAt: new Date() }, { id: 35, TunnelId: 4, QuestionId: 21, createdAt: new Date(), updatedAt: new Date() }, { id: 36, TunnelId: 4, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 37, TunnelId: 4, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 38, TunnelId: 4, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 39, TunnelId: 4, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 40, TunnelId: 4, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 41, TunnelId: 4, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 42, TunnelId: 4, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 43, TunnelId: 5, QuestionId: 22, createdAt: new Date(), updatedAt: new Date() }, { id: 44, TunnelId: 5, QuestionId: 23, createdAt: new Date(), updatedAt: new Date() }, { id: 45, TunnelId: 5, QuestionId: 24, createdAt: new Date(), updatedAt: new Date() }, { id: 46, TunnelId: 5, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 47, TunnelId: 5, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 48, TunnelId: 5, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 49, TunnelId: 5, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 50, TunnelId: 5, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 51, TunnelId: 5, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 52, TunnelId: 5, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 53, TunnelId: 6, QuestionId: 18, createdAt: new Date(), updatedAt: new Date() }, { id: 54, TunnelId: 6, QuestionId: 25, createdAt: new Date(), updatedAt: new Date() }, { id: 55, TunnelId: 6, QuestionId: 26, createdAt: new Date(), updatedAt: new Date() }, { id: 56, TunnelId: 6, QuestionId: 27, createdAt: new Date(), updatedAt: new Date() }, { id: 57, TunnelId: 6, QuestionId: 28, createdAt: new Date(), updatedAt: new Date() }, { id: 58, TunnelId: 6, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 59, TunnelId: 6, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 60, TunnelId: 6, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 61, TunnelId: 6, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 62, TunnelId: 6, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 63, TunnelId: 6, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 64, TunnelId: 6, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 65, TunnelId: 7, QuestionId: 29, createdAt: new Date(), updatedAt: new Date() }, { id: 66, TunnelId: 7, QuestionId: 30, createdAt: new Date(), updatedAt: new Date() }, { id: 67, TunnelId: 7, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 68, TunnelId: 7, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 69, TunnelId: 7, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 70, TunnelId: 7, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, { id: 71, TunnelId: 8, QuestionId: 31, createdAt: new Date(), updatedAt: new Date() }, { id: 72, TunnelId: 8, QuestionId: 32, createdAt: new Date(), updatedAt: new Date() }, { id: 73, TunnelId: 8, QuestionId: 33, createdAt: new Date(), updatedAt: new Date() }, { id: 74, TunnelId: 8, QuestionId: 11, createdAt: new Date(), updatedAt: new Date() }, { id: 75, TunnelId: 8, QuestionId: 12, createdAt: new Date(), updatedAt: new Date() }, { id: 76, TunnelId: 8, QuestionId: 17, createdAt: new Date(), updatedAt: new Date() }, { id: 77, TunnelId: 8, QuestionId: 13, createdAt: new Date(), updatedAt: new Date() }, { id: 78, TunnelId: 8, QuestionId: 14, createdAt: new Date(), updatedAt: new Date() }, { id: 79, TunnelId: 8, QuestionId: 15, createdAt: new Date(), updatedAt: new Date() }, { id: 80, TunnelId: 8, QuestionId: 34, createdAt: new Date(), updatedAt: new Date() }, ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('tunnelQuestions', null, {}); } }; <file_sep>/models/regional.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Regional = sequelize.define('Regional', { name: DataTypes.STRING, address: DataTypes.TEXT, city: DataTypes.STRING, province: DataTypes.STRING, logo_url:DataTypes.STRING, description:DataTypes.TEXT, createdBy: DataTypes.INTEGER, createdAt: DataTypes.DATE, updatedAt: DataTypes.DATE }, {}); Regional.associate = function (models) { models.Regional.hasMany(models.User, {foreignKey:'RegionalId',sourceKey:'id'}) }; return Regional; };<file_sep>/controllers/userController.js const model = require('../models/index'); const { validationResult } = require('express-validator/check'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const redisClient = require('../util/redis'); const Sequelize = require('sequelize'); const Op = Sequelize.Op exports.checkSession = (req, res, next) => { const token = req.body.token; redisClient.get('login_portal:' + token, function (err, response) { if (err) { res.status(500).json({ message: "Somethin Went Wrong " + err, data: null, status: false }) } if (response == null) { res.status(200).json({ message: `Token Not Found`, data: null, status: false }) } else { res.status(200).json({ message: `Token Found`, data: JSON.parse(response), status: true }) } }) } exports.socialLogin = (req, res, next) => { model.User.findOrCreate({ where: { email: req.body.email }, defaults: { profilPicture: req.body.profilPicture, socialId: req.body.socialId, loginSource: req.body.loginSource } }).then(async ([user]) => { const userData = await user.get(); let status = userData.status !== null ? userData.status : 0; const data_identity = { email: userData.email, userId: userData.id, step: status } const token = jwt.sign(data_identity, process.env.JWT_KEY, { expiresIn: 60000 }); redisClient.setex('login_portal:' + token, 60000, JSON.stringify(data_identity)) return res.status(200).json({ "code": 200, "token": token, "status": status }); }).catch(err => { return res.json({ code: 401, message: err }); }) } exports.getProfile = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, function (err, response) { const user = JSON.parse(response); const userId = user.userId; model.User.findOne({ where: { id: userId }, attributes: {exclude: ['password', 'status', 'createdAt', 'updatedAt']}, include: [ { model: model.Identity, attributes: { exclude: [ 'userId', 'email', 'headline', 'batchFim', 'otherReligion','reference_by', 'expertise', 'video_editing', 'mbti', 'role', 'ktpUrl', 'status_accept', 'attendenceConfirmationDate', 'paymentDate', 'bankTransfer', 'urlTransferPhoto', 'createdAt', 'updatedAt' ] } }, { model: model.Skill, attributes: {exclude: ['userId', 'createdAt', 'updatedAt']} }, { model: model.SocialMedia, attributes: {exclude: ['userId', 'createdAt', 'updatedAt']} }, { model: model.AlumniReference, attributes: {exclude: ['userId', 'createdAt', 'updatedAt']} }, { model: model.FimActivity, attributes: {exclude: ['userId', 'createdAt', 'updatedAt']} }, { model: model.OrganizationExperience, attributes: {exclude: ['userId', 'createdAt', 'updatedAt']} } ]}).then(result => { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": result }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) }) } exports.saveIdentity = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { try { validateIdentityRequestBody(req.body) let userIdentity = JSON.parse(response); let userId = userIdentity.userId; findIdentity = await model.Identity.findOne({ where: { userId: userId } }) if (findIdentity == null) { await model.Identity.create(parseIdentityRequest(userId, req.body)) .then(result => { setFirstFormCompletenessToTrue(userId) return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseIdentityResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findIdentity.update(parseIdentityRequest(userId, req.body)) .then(result => { setFirstFormCompletenessToTrue(userId) return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseIdentityResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } } catch(err) { return res.status(400).json({ "status": false, "message": err.message, "data": null }) } }) } function validateIdentityRequestBody(reqBody) { if (!reqBody.firstName || reqBody.firstName.trim() == "") throw new Error('firstName is required!'); if (!reqBody.phone || reqBody.phone.trim() == "") throw new Error('phone is required!'); if (!reqBody.emergencyPhone || reqBody.emergencyPhone.trim() == "") throw new Error('emergencyPhone is required!'); if (!reqBody.photoUrl || reqBody.photoUrl.trim() == "") throw new Error('photoUrl is required!'); if (!reqBody.ktpNumber || reqBody.ktpNumber.trim() == "") throw new Error('ktpNumber is required!'); if (!reqBody.religion || reqBody.religion.trim() == "") throw new Error('religion is required!'); if (!reqBody.bornPlace || reqBody.bornPlace.trim() == "") throw new Error('bornPlace is required!'); if (!reqBody.bornDate || reqBody.bornDate.trim() == "") throw new Error('bornDate is required!'); if (!reqBody.address || reqBody.address.trim() == "") throw new Error('address is required!'); if (!reqBody.cityAddress || reqBody.cityAddress.trim() == "") throw new Error('cityAddress is required!'); if (!reqBody.provinceAddress || reqBody.provinceAddress.trim() == "") throw new Error('provinceAddress is required!'); if (!reqBody.gender || reqBody.gender.trim() == "") throw new Error('gender is required!'); if (!reqBody.bloodGroup || reqBody.bloodGroup.trim() == "") throw new Error('bloodGroup is required!'); if (!reqBody.hobby || reqBody.hobby.trim() == "") throw new Error('hobby is required!'); if (!reqBody.institution || reqBody.institution.trim() == "") throw new Error('institution is required!'); if (!reqBody.occupation || reqBody.occupation.trim() == "") throw new Error('occupation is required!'); } function parseIdentityRequest(userId, reqBody) { firstName = reqBody.firstName; lastName = reqBody.lastName; fullName = firstName.concat(" ", lastName); return { userId: userId, fullName: fullName.trim(), firstName: firstName.trim(), lastName: lastName.trim(), phone: reqBody.phone.trim(), emergencyPhone: reqBody.emergencyPhone.trim(), ktpNumber: reqBody.ktpNumber.trim(), photoUrl: reqBody.photoUrl.trim(), religion: reqBody.religion.trim(), bornPlace: reqBody.bornPlace.trim(), bornDate: reqBody.bornDate.trim(), address: reqBody.address.trim(), cityAddress: reqBody.cityAddress.trim(), provinceAddress: reqBody.provinceAddress.trim(), gender: reqBody.gender.trim(), bloodGroup: reqBody.bloodGroup.trim(), hobby: reqBody.hobby.trim(), institution: reqBody.institution.trim(), occupation: reqBody.occupation.trim() } } function parseIdentityResponse(data) { return { id: data.id, fullName: data.fullName, firstName: data.firstName, lastName: data.lastName, phone: data.phone, emergencyPhone: data.emergencyPhone, ktpNumber: data.ktpNumber, photoUrl: data.photoUrl, religion: data.religion, bornPlace: data.bornPlace, bornDate: data.bornDate, address: data.address, cityAddress: data.cityAddress, provinceAddress: data.provinceAddress, gender: data.gender, bloodGroup: data.bloodGroup, hobby: data.hobby, institution: data.institution, occupation: data.occupation } } exports.saveSkill = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; findSkill = await model.Skill.findOne({ where: { userId: userId } }) if (findSkill == null) { await model.Skill.create(parseSkillRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseSkillResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findSkill.update(parseSkillRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseSkillResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function parseSkillRequest(userId, reqBody) { if (reqBody.isAbleVideoEditing) isAbleVideoEditing = reqBody.isAbleVideoEditing else isAbleVideoEditing = false return { userId: userId, isAbleVideoEditing: isAbleVideoEditing, videoEditingPortofolioUrl: reqBody.videoEditingPortofolioUrl ? reqBody.videoEditingPortofolioUrl.trim() : null, firstCertificateUrl: reqBody.firstCertificateUrl ? reqBody.firstCertificateUrl.trim() : null, secondCertificateUrl: reqBody.secondCertificateUrl ? reqBody.secondCertificateUrl.trim() : null, thirdCertificateUrl: reqBody.thirdCertificateUrl ? reqBody.thirdCertificateUrl.trim() : null } } function parseSkillResponse(data) { return { id: data.id, isAbleVideoEditing: data.isAbleVideoEditing, videoEditingPortofolioUrl: data.videoEditingPortofolioUrl, firstCertificateUrl: data.firstCertificateUrl, secondCertificateUrl: data.secondCertificateUrl, thirdCertificateUrl: data.thirdCertificateUrl } } exports.saveSocialMedia = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; findSocialMedia = await model.SocialMedia.findOne({ where: { userId: userId } }) if (findSocialMedia == null) { await model.SocialMedia.create(parseSocialMediaRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseSocialMediaResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findSocialMedia.update(parseSocialMediaRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseSocialMediaResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function parseSocialMediaRequest(userId, reqBody) { return { userId: userId, instagramUrl: reqBody.instagramUrl ? reqBody.instagramUrl.trim() : null, twitterUrl: reqBody.twitterUrl ? reqBody.twitterUrl.trim() : null, facebookUrl: reqBody.facebookUrl ? reqBody.facebookUrl.trim() : null, websiteUrl: reqBody.websiteUrl ? reqBody.websiteUrl.trim() : null, otherSiteUrl: reqBody.otherSiteUrl ? reqBody.otherSiteUrl.trim() : null, reason: reqBody.reason ? reqBody.reason.trim() : null } } function parseSocialMediaResponse(data) { return { id: data.id, instagramUrl: data.instagramUrl, twitterUrl: data.twitterUrl, facebookUrl: data.facebookUrl, websiteUrl: data.websiteUrl, otherSiteUrl: data.otherSiteUrl, reason: data.reason } } exports.saveAlumniReference = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; findAlumniReference = await model.AlumniReference.findOne({ where: { userId: userId } }) if (findAlumniReference == null) { await model.AlumniReference.create(parseAlumniReferenceRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseAlumniReferenceResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findAlumniReference.update(parseAlumniReferenceRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseAlumniReferenceResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function parseAlumniReferenceRequest(userId, reqBody) { return { userId: userId, fullName: reqBody.fullName ? reqBody.fullName.trim() : null, batch: reqBody.batch? reqBody.batch.trim() : null, phoneNumber: reqBody.phoneNumber ? reqBody.phoneNumber.trim() : null, relationship: reqBody.relationship ? reqBody.relationship.trim() : null, acquaintedSince: reqBody.acquaintedSince ? reqBody.acquaintedSince.trim() : null } } function parseAlumniReferenceResponse(data) { return { id: data.id, fullName: data.fullName, batch: data.batch, phoneNumber: data.phoneNumber, relationship: data.relationship, acquaintedSince: data.acquaintedSince } } exports.saveFimActivity = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; const findFimActivity = await model.FimActivity.findOne({ where: { userId: userId } }) if (findFimActivity == null) { await model.FimActivity.create(parseFimActivityRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseFimActivityResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findFimActivity.update(parseFimActivityRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseFimActivityResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function parseFimActivityRequest(userId, reqBody) { return { userId: userId, responsibility: reqBody.responsibility ? reqBody.responsibility.trim() : null, role: reqBody.role ? reqBody.role.trim() : null, duration: reqBody.duration ? reqBody.duration.trim() : null, eventScale: reqBody.eventScale ? reqBody.eventScale.trim() : null, result: reqBody.result ? reqBody.result.trim() : null } } function parseFimActivityResponse(data) { return { id: data.id, responsibility: data.responsibility, role: data.role, duration: data.duration, eventScale: data.eventScale, result: data.result } } exports.saveOrganizationExperience = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { try { let userIdentity = JSON.parse(response); let userId = userIdentity.userId; validateOrganizationExperienceRequestBody(req.body) model.OrganizationExperience.findAll({ where: { userId: userId } }) .then(result => { deleteExistingOrganizationExperience(userId, result) model.OrganizationExperience.bulkCreate(parseOrganizationExperienceRequest(userId, req.body)) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseOrganizationExperienceResponse(result) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) }) } catch (err) { return res.status(400).json({ "status": false, "message": err.message, "data": null }) } }) } function validateOrganizationExperienceRequestBody(reqBody) { if (reqBody.length == 0 || reqBody.length > 3) throw new Error("Data can't be less than one or more than three!"); } function deleteExistingOrganizationExperience(userId, data) { if (data.length > 0) { model.OrganizationExperience.destroy({ where: { userId: userId } }) .catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } } function parseOrganizationExperienceRequest(userId, reqBody) { let i = 0; organizationArr = []; organizationObj = {}; for (;reqBody[i];) { organizationObj = { userId: userId, referencePerson: reqBody[i].referencePerson ? reqBody[i].referencePerson.trim() : null, role: reqBody[i].role ? reqBody[i].role.trim() : null, duration: reqBody[i].duration ? reqBody[i].duration.trim() : null, eventScale: reqBody[i].eventScale ? reqBody[i].eventScale.trim() : null, result: reqBody[i].result ? reqBody[i].result.trim() : null, } organizationArr.push(organizationObj); i++; } return organizationArr; } function parseOrganizationExperienceResponse(data) { let i = 0; organizationArr = []; organizationObj = {}; for (;data[i];) { organizationObj = { id: data[i].id, referencePerson: data[i].referencePerson, role: data[i].role, duration: data[i].duration, eventScale: data[i].eventScale, result: data[i].result, } organizationArr.push(organizationObj); i++; } return organizationArr; } function setFirstFormCompletenessToTrue(userId) { model.FormCompleteness.findOne({ where: { userId: userId }}) .then(formCompleteness => { data = { userId: userId, fimBatch: "23", /* TODO: Make it dynamic */ isFirstStepCompleted: true } if (formCompleteness == null) { model.FormCompleteness.create(data) .catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { formCompleteness.update(data) .catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } exports.saveTunnel = (req, res, nex) => { let token = req.get('Authorization').split(' ')[1]; const data = { TunnelId: req.body.TunnelId, RegionalId: req.body.RegionalId } redisClient.get('login_portal:' + token, function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; model.User.findOne({ where: { id: userId } }) .then(result => { result.update({ TunnelId: data.TunnelId, RegionalId:data.RegionalId, status: 3 }).then(dataresult => { redisClient.set('login_portal:' + token, JSON.stringify({ ...userIdentity, step: 3 })) return res.status(200).json({ "status": true, "message": "Tunnel Updated", "data": dataresult }) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }); }); }<file_sep>/routes/participantRoute.js const express = require('express'); const router = express.Router(); const participantController = require('../controllers/participantController'); router.post('/update-status-accept',participantController.update_status_accept); router.post('/confirmation/update', participantController.confirmation_update); router.post('/mbti/update',participantController.mbti_update); router.post('/payment/confirmation', participantController.payment_confirmation); module.exports = router;<file_sep>/routes/summaryRoute.js const express = require('express'); const router = express.Router(); const summaryController = require('../controllers/summaryController'); const isAuth = require('../middleware/is-auth-middleware'); router.get('/lists',summaryController.lists); router.post('/update-final-submit', isAuth, summaryController.updateFinal); router.post('/update-score', summaryController.updateScore); router.post('/update-evaluator', summaryController.updateEvaluator); router.post('/check',summaryController.checkDaftar ) // Statistic router.get('/statistic-in-batch', summaryController.statisticBatch); // router.get('/statistic-by-regional', summaryController.statisticBatchByRegional); module.exports = router;<file_sep>/routes/recruiterRoute.js const express = require('express'); const router = express.Router(); const isAuth = require('../middleware/is-auth-middleware'); const recruiterController = require('../controllers/recruiterController'); // add admin router.post('/:type(recruit|admin)/add',recruiterController.addAdmin); // list capes submit router.get('/participant/submited', recruiterController.listSubmitted); router.get('/lists', recruiterController.listRecruiter); router.post('/assign', recruiterController.assignRecruiter); // view detail tiap capes router.post('/participant/by-recruiter', recruiterController.listByRecruiter); router.post('/participant/detail',recruiterController.detailParticipant); router.post('/participant/update/score',recruiterController.updateScore); router.post('/recruiter/add', recruiterController.addRecruiter); router.post('/participant/available-to-assign', recruiterController.availableAssing); router.post('/participant/to-assign', recruiterController.toAssign); router.post('/participant/undo-assign', recruiterController.undoAssign); router.post('/new-assign', recruiterController.newAssignRecruiter); router.post('/remove-assign', recruiterController.removeAssignRecruiter); module.exports = router;<file_sep>/seeders/20190708165353-question-local-leader.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:16, headline: "Proyek Kolaboratif", note:null, question: "Tuliskan rencana proyek yang akan kamu kolaborasikan bersama FIM ", TunnelId: 3, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ // "Pilih Jenis Proyek (Sosial, Pendidikan dan Budaya, Ekonomi dan Industri Kreatif, Sains dan Teknologi, Politik dan Kebijakan Publik)": "[{'option':'Sosial'},{'option':'Pendidikan dan Budaya'},{'option':'Ekonomi dan Industri Kreatif'},{'option':'Sains dan Teknologi'},{'option':'Politik dan Kebijakan Publik'}]", "Pilih Jenis Proyek (Sosial, Pendidikan dan Budaya, Ekonomi dan Industri Kreatif, Sains dan Teknologi, Politik dan Kebijakan Publik)": "text", "Apa peran kamu dalam proyek ini ?": "textarea", "Dimana proyek ini akan dilakukan ?":"text", "Apa yang dilakukan dalam proyek ini ?":"text", "Apa saja sumberdaya yang dibutuhkan untuk mengeksekusi proyek ini ?": "textarea", "Bagaimana FIM bisa meningkatkan nilai manfaat proyek ini ? (Min 100 kata)": "textarea", }), createdAt: new Date(), updatedAt: new Date() }, { id:17, headline: "Pernyataan Komitmen", note:null, question: '<a href="https://res.cloudinary.com/fim-indonesia/raw/upload/v1563242868/document/SURAT_PERNYATAAN_KOMITMEN_DIRI.docx" >Format Terlampir</a>', TunnelId: 3, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "URL File": "text" }), createdAt: new Date(), updatedAt: new Date() }, ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/migrations/20200920062546-add status accept.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return Promise.all([ queryInterface.addColumn('Identities', 'status_accept', { type: Sequelize.INTEGER, defaultValue: 0 }), ]) }, down: (queryInterface, Sequelize) => { return Promise.all([ queryInterface.removeColumn('Identities', 'status_accept') ]) } }; <file_sep>/migrations/20210916134514-create-fim-activities-table.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('FimActivities', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, userId: { allowNull: false, type: Sequelize.INTEGER }, responsibility: { type: Sequelize.STRING }, role: { type: Sequelize.STRING }, duration: { type: Sequelize.STRING }, eventScale: { type: Sequelize.STRING }, result: { type: Sequelize.TEXT }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }).then(() => queryInterface.addIndex('FimActivities', ['userId'])); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('FimActivities'); } }; <file_sep>/routes/documentRoute.js const express = require('express'); const router = express.Router(); const { body } = require('express-validator/check') const documentController = require('../controllers/documentController'); const isAuth = require('../middleware/is-auth-middleware'); router.get('/', isAuth, documentController.getDocument); router.post('/', isAuth, documentController.saveDocument); module.exports = router;<file_sep>/migrations/20190812001124-add-some-score-column-in-summaries.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.createTable('users', { id: Sequelize.INTEGER }); */ return Promise.all([ queryInterface.addColumn('Summaries', 'scoreDataDiri', { type: Sequelize.INTEGER }), queryInterface.addColumn('Summaries', 'scoreAktivitas', { type: Sequelize.INTEGER }), queryInterface.addColumn('Summaries', 'scoreProject', { type: Sequelize.INTEGER }), queryInterface.addColumn('Summaries', 'scoreOther', { type: Sequelize.INTEGER }), queryInterface.addColumn('Summaries', 'notes', { type: Sequelize.TEXT }), ]) }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.dropTable('users'); */ return Promise.all([ queryInterface.removeColumn('Summaries', 'scoreDataDiri'), queryInterface.removeColumn('Summaries', 'scoreAktivitas'), queryInterface.removeColumn('Summaries', 'scoreProject'), queryInterface.removeColumn('Summaries', 'scoreOther'), queryInterface.removeColumn('Summaries', 'notes'), ]) } }; <file_sep>/controllers/participantController.js const model = require('../models/index'); const { validationResult } = require('express-validator/check'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const RedisClient = require('../util/redis'); exports.update_status_accept = async (req, res, next) => { const value = req.body.value; const ktpNumber = req.body.ktpNumber; const statusNumber = [0, 1, 999999]; await model.Identity.findOne({ where: { 'ktpNumber': ktpNumber } }).then(async result => { if (value == 0 || value == 1 || value == 2 || value == 999999) { await result.update({ status_accept: value }) } else { await result.update({ status_accept: 100, // diterima batchFim: value }) } return res.status(200).json({ status: true, message: "Status Updated", data: result }); }).catch(err => { console.log(err) return res.status(400).json({ status: false, message: "Whoops Something Error", error: err }); }) } exports.confirmation_update = async (req, res, next) => { const kehadiran = req.body.kehadiran; const token = req.get('Authorization').split(' ')[1]; if (kehadiran == null) { return res.status(200).json({ status: false, message: "User Not Authorized", }); } RedisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); if (userIdentity.userId == req.body.idUser) { const fimBatch = await model.Fimbatch.findAll({ limit: 1, order: [['id', 'DESC']] }).then(result => { return result[0] }) await model.Identity.findOne({ where: { 'userId': userIdentity.userId } }).then(async result => { const updated = await result.update({ batchFim: req.body.kehadiran == 1 ? fimBatch.name : fimBatch.name + 'x', attendenceConfirmationDate: new Date() }) return res.status(200).json({ status: true, message: "Status Updated", data: updated }); }).catch(err => { console.log(err) }) } else { return res.status(200).json({ status: false, message: "User Not Authorized", }); } }) // await.model.Identity.findOne } exports.mbti_update = async (req, res, next) => { const token = req.get('Authorization').split(' ')[1]; if (req.body.mbti == null) { return res.status(200).json({ status: false, message: "Please fill answer", }); } RedisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); if (userIdentity.userId == req.body.idUser) { await model.Identity.findOne({ where: { 'userId': userIdentity.userId } }).then(async result => { const updated = await result.update({ mbti: req.body.mbti }) return res.status(200).json({ status: true, message: "MBTI Updated", data: updated }); }).catch(err => { console.log(err) }) } else { return res.status(200).json({ status: false, message: "User Not Authorized", }); } }) } exports.payment_confirmation = async (req, res, next) => { const token = req.get('Authorization').split(' ')[1]; if (req.body.paymentDate == null || req.body.bankTransfer == null || req.body.urlTransferPhoto == null ) { return res.status(200).json({ status: false, message: "Please fill answer", }); } RedisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); if (userIdentity.userId == req.body.idUser) { await model.Identity.findOne({ where: { 'userId': userIdentity.userId } }).then(async result => { const updated = await result.update({ paymentDate: req.body.paymentDate, bankTransfer: req.body.bankTransfer, urlTransferPhoto: req.body.urlTransferPhoto, }) return res.status(200).json({ status: true, message: "Payment Updated", data: updated }); }).catch(err => { console.log(err) }) } else { return res.status(200).json({ status: false, message: "User Not Authorized", }); } }) } <file_sep>/util/database.js const Sequelize = require('sequelize'); let sequelize = null; // console.log(process.env.JAWSDB_URL) if(process.env.JAWSDB_URL) { // the application is executed on Heroku sequelize = new Sequelize(process.env.JAWSDB_URL, { host:'tyduzbv3ggpf15sx.cbetxkdyhwsb.us-east-1.rds.amazonaws.com', port:'3306', dialect : 'mysql', operatorsAliases: false }) } else { sequelize = new Sequelize(process.env.DATABASE_NAME,process.env.DATABASE_USER,process.env.DATABASE_PASS,{ host:process.env.HOST, dialect : process.env.DIALECT, operatorsAliases: false }); } module.exports = sequelize; <file_sep>/seeders/20190708165410-question-young-professional.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:18, headline: "Aktivitas dan Pencapaian", note: null, question: "Tuliskan informasi tentang tempat Anda bekerja saat ini", TunnelId: 4, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Perusahaan": "text", "Jabatan / posisi": "text", "Nama rekan kerja": "text", "Nomor hp rekan kerja": "text", "Deskripsi singkat peran dan tanggung jawab yang Anda kerjakan": "text", }), createdAt: new Date(), updatedAt: new Date() }, { id:19, headline: "Aktivitas dan Pencapaian", note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Tuliskan 3 aktivitas dan/atau pencapaian terbaik dalam konteks aktivitas saat ini yang telah Anda raih. Aktivitas dan pencapaian di sini diartikan dalam arti yang luas, bisa jadi berupa menjadi project leader, promosi jabatan, menangani cabang baru, menangani bidang kerja baru, scope pekerjaan , penghargaan dari instansi dll.", TunnelId: 4, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 1/ Pencapaian 1": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:20, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan Jelaskan aktivitas dan/atau pencapaian 2", TunnelId: 4, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 2/ Pencapaian 2": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:21, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan Jelaskan aktivitas dan/atau pencapaian 3", TunnelId: 4, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 3/ Pencapaian 3": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/seeders/20190708165427-question-public-servant.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:25, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Tuliskan 3 aktivitas dan/atau pencapaian terbaik dalam konteks aktivitas saat ini yang telah Anda raih. Aktivitas dan pencapaian di sini diartikan dalam arti yang luas, bisa jadi berupa proyek yang ditangani, kajian kebijakan yang telah dilakukan ", TunnelId: 6, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 1/ Pencapaian 1": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "textarea" }), createdAt: new Date(), updatedAt: new Date() }, { id:26, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan Jelaskan aktivitas dan/atau pencapaian terbaik 2", TunnelId: 6, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 2/ Pencapaian 2": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "textarea" }), createdAt: new Date(), updatedAt: new Date() }, { id:27, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan Jelaskan aktivitas dan/atau pencapaian terbaik 3", TunnelId: 6, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 3/ Pencapaian 3": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "textarea" }), createdAt: new Date(), updatedAt: new Date() }, { id:28, headline: "Essai", note: "(maksimal 400 kata)", question: "Tema : bagaimana FIM bisa membantu Anda untuk meningkatkan kualitas diri Anda secara personal sehingga mampu memberikan keuntungan untuk masyarakat (maksimal 400 kata)", TunnelId: 6, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Essai": "textarea" }), createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/seeders/20210922151039-add-tunnel-fim-23.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Tunnels', [ { id: 12, name: 'Alumni / Umum', description: null, createdBy: 1, createdAt: new Date(), updatedAt: new Date(), urlPicture: null, batchFim: '23' } ]) }, down: async (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Tunnels', { batchFim: '23' }, {}) } };<file_sep>/models/answer.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Answer = sequelize.define('Answer', { answer: DataTypes.TEXT, ktpNumber: DataTypes.STRING, TunnelId: DataTypes.INTEGER, createdBy: DataTypes.INTEGER, QuestionId:DataTypes.INTEGER }, {}); Answer.associate = function(models) { models.Answer.belongsTo(models.User, { foreignKey: 'createdBy' }) models.Answer.belongsTo(models.Tunnel, { foreignKey: 'id', sourceKey: 'TunnelId' }) models.Answer.belongsTo(models.Question, { sourceKey: 'QuestionId', targetKey: 'id' }) }; return Answer; };<file_sep>/seeders/20190708165229-question-campus-leader.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:5, headline: "Aktivitas dan Pencapaian", note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan jelaskan 5 aktivitas dan/atau pencapaian terbaik dalam konteks kepemimpinan yang telah Anda raih. Aktivitas dan pencapaian di sini diartikan dalam arti yang luas, bisa jadi berupa pengalaman organisasi, pengalaman kepanitiaan, pengalaman mendirikan organisasi,menjuarai kompetisi, partisipasi dalam suatu konferensi, penulisan ilmiah, dll.", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 1 / Pencapaian 1": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:6, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan jelaskan aktivitas 2", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 2/ Pencapaian 2": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:7, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan jelaskan aktivitas 3", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 3/ Pencapaian 3": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:8, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan jelaskan aktivitas 4", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 4/ Pencapaian 4": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:9, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan dan jelaskan aktivitas 5", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 5/ Pencapaian 5": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:10, headline: "Essai", note: "(maksimal 400 kata)", question: "Tema : rencana strategis Anda di kampus dan bagaimana FIM dapat membantu mewujudkannya", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Answer": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:11, headline: "Video Profil", note: null, question: "Sertakan karya yang berisikan profil singkat diri Anda beserta alasan mengapa ingin bergabung dalam keluarga besar FIM. Karya dapat berupa video, tulisan blog, rekaman podcast, unggahan instagram atau lainnya sesuai dengan platform yang Anda gunakan. Bagi pendaftar jalur selain Influencer, tugas ini bersifat optional (sebagai nilai tambah). Silahkan tuliskan link nya di bawah ini. ", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "URL Link Video": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:12, headline: "Surat Rekomendasi", note: '<a href="https://res.cloudinary.com/fim-indonesia/raw/upload/v1563327650/document/Surat_Rekomendasi_FIM_21_non_next_gen.docx" >Format Terlampir</a>', question: "Pada Jalur ini, rekomendasi ini dapat diberikan oleh siapapun, baik itu teman baik, dosen, tokoh masyarakat, pemuka adat, petinggi organisasi, petinggi partai politik, atau alumni FIM, siapa saja asalkan mengenal kamu dengan baik", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "URL File": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:13, headline: null, note: null, question: "Jika pernah, mohon sebutkan berapa kali Anda telah mendaftar FIM ?", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "FIM Ke-": "text", "Tahun": "number", }), createdAt: new Date(), updatedAt: new Date() }, { id:14, headline: null, note: null, question: "Pendaftaran FIM ke 2 ?", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "FIM Ke-": "text", "Tahun": "number", }), createdAt: new Date(), updatedAt: new Date() }, { id:15, headline: null, note: null, question: "Pendaftaran FIM ke 3 ?", TunnelId: 2, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "FIM Ke-": "text", "Tahun": "number", }), createdAt: new Date(), updatedAt: new Date() }, ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/controllers/tunnelController.js const model = require('../models/index'); const redisClient = require('../util/redis'); const Sequelize = require('sequelize'); const Op = Sequelize.Op exports.lists = async (req, res, next) => { const token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; // search apakah dia fim 20 atau engga const findIdentity = await model.Identity.findOne({ where: { userId: userId } }).then(identity => { return identity; }).catch(err => console.log(err)) // search di summary apakah ada jalur yang sudah final. // karena ada kemungkinan 1 user ada banyak summary ketika dia tidak jadi memilih 1 jalur dan belum final // Hal ini mencegah peserta daftar di multi jalur const arrayDenied = []; const findSummary = await model.Summary.findAll({ where: { ktpNumber: findIdentity.ktpNumber, isFinal:1 , batchFim: '22' } }).then(result => { result.map((value) => { arrayDenied.push(value.TunnelId); }) }).catch(err => console.log(err)); // bukan anak FIM // kalau udah milih 1 di summary dan sudah menunjukan data final // maka udah ga boleh milih yang lain lagi let whereNotFim = null; if (arrayDenied.length > 0) { whereNotFim = { name: { [Op.not]: "Alumni FIM 20" }, id: { [Op.in]: arrayDenied }, batchFim: '22' }; } else { whereNotFim = { name: { [Op.not]: "Alumni FIM 20" }, batchFim: '22' }; } // conditional anak FIM let whereFim = null; if (arrayDenied.length > 0 && arrayDenied.length < 2) { if (arrayDenied.indexOf(1) !== -1) // artinya ada next gen di sana { whereFim = { id: { [Op.notIn]: arrayDenied }, batchFim: '22' }; } // jika tidak ada next gen , maka pilihannya hanya next Gen else { whereFim = { name: "<NAME>", batchFim: '22' }; } } else if (arrayDenied.length >= 2) { whereFim = { id: { [Op.in]: arrayDenied }, batchFim: '22' }; } else { whereFim = { name: "<NAME>", createdAt: { [Op.not]: null }, batchFim: '22' }; } // console.log(whereFim) // bukan anak fim if (findIdentity !== null && findIdentity.batchFim == null) { listTunnel = await model.Tunnel.findAll({ where: whereNotFim }).then(result => { return result }).catch(err => { console.log(err) }); } // anak FIM else { listTunnel = await model.Tunnel.findAll({ where: whereFim }).then(result => { return result }).catch(err => { console.log(err) }); } res.status(200).json({ status: true, message: "data fetched", data: listTunnel }); }); } exports.create = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; const data = { name: req.body.name, description: req.body.description } if (err) { return res.status(400).json({ status: false, message: "Token Expired", data: err }); } model.Tunnel.create({ name: data.name, createdBy: userId }).then(result => { res.status(200).json({ status: true, message: "Data Created", data: result }); }).catch(err => { res.status(400).json({ status: false, message: "Error", data: err }); }) }); } exports.read = async (req, res, next) => { const idTunnel = req.body.idTunnel; model.Tunnel.findByPk(idTunnel).then(result => { res.status(200).json({ status: true, message: "Data Fetched", data: result }); }) } exports.update = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; if (err) { return res.status(400).json({ status: false, message: "Token Expired", data: err }); } const data = { idTunnel: req.body.idTunnel, name: req.body.name, description: req.body.description } model.Tunnel.update({ name: data.name, createdBy: userId }, { where: { id: data.idTunnel } } ).then((status, result) => { res.status(200).json({ status: true, message: "Data Updated", data: status }); }).catch(err => { res.status(400).json({ status: false, message: "Error", data: err }); }) }); } exports.delete = async (req, res, next) => { model.Tunnel.destroy({ where: { id: req.body.idTunnel } }).then(result => { res.status(200).json({ status: true, message: "Data Deleted", data: null }); }).catch(err => { console.log(err) res.status(400).json({ status: false, message: "Error Occured", data: err }); }) } <file_sep>/models/tunnelquestion.js 'use strict'; module.exports = (sequelize, DataTypes) => { const tunnelQuestion = sequelize.define('tunnelQuestion', { TunnelId: DataTypes.INTEGER, QuestionId: DataTypes.INTEGER }, {}); tunnelQuestion.associate = function(models) { // associations can be defined here }; return tunnelQuestion; };<file_sep>/routes/answerRoute.js const express = require('express'); const router = express.Router(); const answerController = require('../controllers/answerController'); router.get('/answer?:tunnelId', answerController.getAnswer); router.post('/answer', answerController.saveAnswer); module.exports = router;<file_sep>/controllers/formCompletenessController.js const model = require('../models/index'); const redisClient = require('../util/redis'); exports.getFormCompleteness = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; model.FormCompleteness.findOne({ where: { userId: userId } }) .then(result => { if (result == null) { payload = { userId: userId, fimBatch: "23" /* TODO: Make it dynamic */ } model.FormCompleteness.create(payload) .then(result => { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": parseResponse(result.dataValues) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { return res.status(200).json({ "status": true, "message": "Data Fetched", "data": parseResponse(result.dataValues) }) } }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) }) } exports.submitFormCompleteness = async (req, res, next) => { let token = req.get('Authorization').split(' ')[1]; redisClient.get('login_portal:' + token, async function (err, response) { const userIdentity = JSON.parse(response); const userId = userIdentity.userId; const findFormCompleteness = await model.FormCompleteness.findOne({ where: { userId: userId } }) submittedAt = null; if (findFormCompleteness) { submittedAt = findFormCompleteness.submittedAt; if (submittedAt == null) submittedAt = new Date(); } else { submittedAt = new Date(); } const data = { userId: userId, fimBatch: "23", /* TODO: Make it dynamic */ submittedAt: submittedAt } if (findFormCompleteness == null) { await model.FormCompleteness.create(data) .then(result => { return res.status(200).json({ "status": true, "message": "Data Inserted", "data": parseResponse(result.dataValues) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } else { findFormCompleteness.update(data) .then(result => { return res.status(200).json({ "status": true, "message": "Data Updated", "data": parseResponse(result.dataValues) }) }).catch(err => { return res.status(400).json({ "status": false, "message": "Something Error " + err, "data": null }) }) } }) } function countProgress(formCompleteness) { progress = 0; isFirstStepCompleted = formCompleteness.isFirstStepCompleted; isSecondStepCompleted = formCompleteness.isSecondStepCompleted; isThirdStepCompleted = formCompleteness.isThirdStepCompleted; isFourthStepCompleted = formCompleteness.isFourthStepCompleted; if (isFirstStepCompleted == true) progress += 25; if (isSecondStepCompleted == true) progress += 25; if (isThirdStepCompleted == true) progress += 25; if (isFourthStepCompleted == true) progress += 25; return progress; } function parseResponse(formCompleteness) { return { id: formCompleteness.id, isFirstStepCompleted: formCompleteness.isFirstStepCompleted, isSecondStepCompleted: formCompleteness.isSecondStepCompleted, isThirdStepCompleted: formCompleteness.isThirdStepCompleted, isFourthStepCompleted: formCompleteness.isFourthStepCompleted, progress: countProgress(formCompleteness), submittedAt: formCompleteness.submittedAt, } }<file_sep>/seeders/20190708165418-question-young-expert.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:22, headline: "Aktivitas dan Pencapaian", note: null, question: "Sebutkan dan jelaskan tentang portofolio riset/bisnis yang Anda geluti ", TunnelId: 5, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Lembaga": "text", "Jabatan / posisi / peran": "text", "Nama rekan kerja": "text", "Nomor hp rekan kerja": "text", "Deskripsi singkat peran dan tanggung jawab yang Anda kerjakan": "text", }), createdAt: new Date(), updatedAt: new Date() }, { id:23, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Sebutkan 1 aktivitas dan/atau pencapaian terbaik dalam konteks aktivitas saat ini yang telah Anda raih. Aktivitas dan pencapaian di sini diartikan dalam arti yang luas, bisa jadi berupa pengalaman mendirikan usaha, menjuarai kompetisi, partisipasi dalam suatu konferensi, penulisan ilmiah, dll.", TunnelId: 5, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 1/ Pencapaian 1": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:24, headline: "Portfolio", note: null, question: "Sertakan portofolio tulisan/artikel/jurnal yang telah Anda buat. Silahkan tuliskan link nya di bawah ini.", TunnelId: 5, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "URL Portfolio": "text", }), createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/models/skill.js 'use strict'; module.exports = (sequelize, DataTypes) => { const skill = sequelize.define('Skill', { userId: DataTypes.INTEGER, isAbleVideoEditing: DataTypes.BOOLEAN, videoEditingPortofolioUrl: DataTypes.STRING, firstCertificateUrl: DataTypes.STRING, secondCertificateUrl: DataTypes.STRING, thirdCertificateUrl: DataTypes.STRING, }, {}); skill.associate = function (models) { models.Skill.belongsTo(models.User, { foreignKey: 'userId' }) }; return skill; };<file_sep>/models/user.js 'use strict'; module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { email: DataTypes.STRING, password: DataTypes.STRING, lastLogin: DataTypes.DATE, status: DataTypes.INTEGER, socialId: DataTypes.STRING, loginSource: DataTypes.STRING, profilPicture: DataTypes.STRING, TunnelId: DataTypes.INTEGER, RegionalId: DataTypes.INTEGER }, {}); User.associate = function (models) { models.User.hasOne(models.Identity, { foreignKey: 'userId' }) models.User.hasOne(models.Skill, { foreignKey: 'userId' }) models.User.hasOne(models.SocialMedia, { foreignKey: 'userId' }) models.User.hasOne(models.AlumniReference, { foreignKey: 'userId' }) models.User.hasOne(models.FimActivity, { foreignKey: 'userId' }) models.User.hasOne(models.PersonalDocument, { foreignKey: 'userId' }) models.User.hasOne(models.FormCompleteness, { foreignKey: 'userId' }) models.User.hasMany(models.OrganizationExperience, { foreignKey: 'userId' }) models.User.belongsTo(models.Regional, { foreignKey: 'RegionalId' }) models.User.belongsToMany(models.Summary, { through: models.ParticipantRecruiter, foreignKey: 'recruiterId' }) }; return User; };<file_sep>/migrations/20210920165521-rename-hoby-column-on-identities-table.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { queryInterface.renameColumn('Identities', 'hoby', 'hobby'); }, down: async (queryInterface, Sequelize) => { queryInterface.renameColumn('Identities', 'hobby', 'hoby'); } }; <file_sep>/migrations/20200820031537-add_name_and_email_pivot_table.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.addColumn('ParticipantRecruiters', 'nameRecruiter', { type: Sequelize.STRING }), queryInterface.addColumn('ParticipantRecruiters', 'emailRecruiter', { type: Sequelize.STRING }), ]) }, down: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.removeColumn('ParticipantRecruiters', 'nameRecruiter'), queryInterface.removeColumn('ParticipantRecruiters', 'emailRecruiter'), ]) } }; <file_sep>/models/alumniReference.js 'use strict'; module.exports = (sequelize, DataTypes) => { const alumniReference = sequelize.define('AlumniReference', { userId: DataTypes.INTEGER, fullName: DataTypes.STRING, batch: DataTypes.STRING, phoneNumber: DataTypes.STRING, relationship: DataTypes.STRING, acquaintedSince: DataTypes.STRING, }, {}); alumniReference.associate = function (models) { models.AlumniReference.belongsTo(models.User, { foreignKey: 'userId' }) }; return alumniReference; };<file_sep>/seeders/20190708165448-question-influencer.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:31, headline: "Aktivitas dan Pencapaian", note: null, question: "Sebutkan dan jelaskan 3 portofolio aktivitas, project kolaborasi terbaik yang pernah dilakukan, atau pun penghargaan yang telah Anda raih.", TunnelId: 8, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Platform yang digunakan 1": "text", "Nama akun": "text", "Genre (Film, Komedi, Musik, Travel, Beauty, Food, Fashion, Lainnya )": "text", "Portofolio hasil karya terbaik (link)": "text", "Alasan memilih genre tersebut (max. 350 kata)": "textarea", "Penghargaan atas karya yang dibuat": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:32, headline: null, note: null, question: "Sebutkan dan jelaskan portfolio ke 2", TunnelId: 8, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Platform yang digunakan 2": "text", "Nama akun": "text", "Genre (Film, Komedi, Musik, Travel, Beauty, Food, Fashion, Lainnya )": "text", "Portofolio hasil karya terbaik (link)": "text", "Alasan memilih genre tersebut (max. 350 kata)": "textarea", "Penghargaan atas karya yang dibuat": "text" }), createdAt: new Date(), updatedAt: new Date() }, { id:33, headline: null, note: null, question: "Sebutkan dan jelaskan portfolio ke 3", TunnelId: 8, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Platform yang digunakan 3": "text", "Nama akun": "text", "Genre (Film, Komedi, Musik, Travel, Beauty, Food, Fashion, Lainnya )": "text", "Portofolio hasil karya terbaik (link)": "text", "Alasan memilih genre tersebut (max. 350 kata)": "textarea", "Penghargaan atas karya yang dibuat": "text" }), createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/models/tunnel.js 'use strict'; module.exports = (sequelize, DataTypes) => { const Tunnel = sequelize.define('Tunnel', { name: DataTypes.STRING, createdBy: DataTypes.INTEGER, description: DataTypes.TEXT, urlPicture: DataTypes.STRING }, {}); Tunnel.associate = function (models) { models.Tunnel.belongsToMany(models.Identity, { through: models.Summary, foreignKey: 'TunnelId' }); models.Tunnel.belongsToMany(models.Question, { through: models.tunnelQuestion, foreignKey: 'TunnelId' }); }; return Tunnel; };<file_sep>/migrations/20210916134834-add-firstname-lastname-columns-to-identities-table.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.addColumn('Identities', 'firstName', { type: Sequelize.STRING }), queryInterface.addColumn('Identities', 'lastName', { type: Sequelize.STRING }) ]) }, down: async (queryInterface, Sequelize) => { return Promise.all([ queryInterface.removeColumn('Identities', 'firstName'), queryInterface.removeColumn('Identities', 'lastName') ]) } }; <file_sep>/models/formCompleteness.js 'use strict'; module.exports = (sequelize, DataTypes) => { const formCompleteness = sequelize.define('FormCompleteness', { userId: DataTypes.INTEGER, fimBatch: DataTypes.STRING, isFirstStepCompleted: DataTypes.BOOLEAN, isSecondStepCompleted: DataTypes.BOOLEAN, isThirdStepCompleted: DataTypes.BOOLEAN, isFourthStepCompleted: DataTypes.BOOLEAN, submittedAt: DataTypes.DATE, }, { freezeTableName: true, name: { singular: 'FormCompleteness', plural: 'FormCompleteness', } }, {}); formCompleteness.associate = function (models) { models.FormCompleteness.belongsTo(models.User, { foreignKey: 'userId' }) }; return formCompleteness; };<file_sep>/routes/questionRoute.js const express = require('express'); const router = express.Router(); const questionController = require('../controllers/questionController'); router.get('/',questionController.getAll); router.post('/create', questionController.create); router.post('/read', questionController.read); router.post('/update', questionController.update); router.post('/delete', questionController.delete); module.exports = router;<file_sep>/seeders/20190708165435-question-military.js 'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id:29, headline: "Aktivitas dan Pencapaian", note: null, question: "Tuliskan informasi tentang tempat Anda menempuh pendidikan saat ini", TunnelId: 7, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Instansi": "text", "Jabatan / pangkat": "text", "Nama rekan kerja": "text", "Nomor hp rekan kerja": "text", "Deskripsi singkat tentang pendidikan yang tengah/telah Anda jalani (maksimal 350 kata)": "textarea", "Deskripsi singkat peran dan tanggung jawab yang Anda kerjakan": "textarea" }), createdAt: new Date(), updatedAt: new Date() }, { id:30, headline: null, note: "*nomor telpon ketua/ penanggung jawab akan dihubungi untuk proses validasi", question: "Tuliskan 1 aktivitas dan/atau pencapaian terbaik dalam konteks aktivitas saat ini yang telah Anda raih. Aktivitas dan pencapaian di sini diartikan dalam arti yang luas, bisa jadi berupa pengalaman organisasi, pengalaman kepanitiaan, pengalaman mendirikan organisasi,menjuarai kompetisi, partisipasi dalam suatu konferensi, penulisan ilmiah, dll ", TunnelId: 7, createdBy: 1, batchFim: "20", isMany: 0, header: JSON.stringify({ "Nama Aktivitas 1/ Pencapaian 1": "text", "Penyelenggara": "text", "Waktu Mulai": "date", "Waktu Selesai": "date", "Durasi": "number", "Scope/Wilayah": "text", "Peran/ Prestasi": "text", "No. Telpon Ketua/ Penanggung Jawab": "text", "Alasan mengapa aktivitas / pencapaian ini merupakan yang terbaik bagi Anda ? (max. 350 kata)": "text" }), createdAt: new Date(), updatedAt: new Date() }, ], {}); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('People', null, {}); */ return queryInterface.bulkDelete('Questions', null, {}); } }; <file_sep>/controllers/homeController.js const model = require('../models/index'); const { validationResult } = require('express-validator/check'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); exports.homeRoute = async (req, res, next) => { res.status(200).json({ posts: [ { title: 'FIM RESTFul API', content: 'Koding untuk bangsaku', by: 'FIM Engineering', } ] }); } <file_sep>/seeders/20210923151635-add-question-fim-23.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Questions', [ { id: 54, headline: "Essay 1", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "essay", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "Jelaskan pengalaman Saudara ketika melakukan kesalahan yang murni disebabkan oleh diri anda sendiri yang dapat merugikan diri anda atau orang lain? dan Bagaimana Anda menyikapi hal tersebut?": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "Coba jelaskan situasi dimana kamu terpaksa berurusan dengan praktik konflik kepentingan yang membuat kamu harus mengambil keputusan secara cepat dan tepat?": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "Bagaimana sikap yang kamu ambil terhadap situasi di poin 2 dan jelaskan dampak dari sikap tersebut.": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, }), createdAt: new Date(), updatedAt: new Date() }, { id: 55, headline: "Essay 2", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "essay", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "Coba jelaskan nilai-nilai yang anda pegang teguh saat ini dan bagaimana anda mendapatkan nilai itu. Adakah figur yang nilai-nilainya kamu terapkan dalam hidup, jika iya, coba jelaskan siapa bagaimana dan mengapa. Berikan implementasi yang sudah kamu lakukan.": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "Bagaimana pendapatmu tentang ungkapan \"Setialah pada nilai, bukan Figur\" ? dan Berikan penerapannya dalam kehidupan sehari hari?": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, }), createdAt: new Date(), updatedAt: new Date() }, { id: 56, headline: "Essay 3", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "essay", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "Coba jelaskan aktivitas atau kegiatan apapun yang memberikan dampak kepada orang lain dan kenapa anda melakukan itu?": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, }), createdAt: new Date(), updatedAt: new Date() }, { id: 57, headline: "Essay 4", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "essay", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "Jelaskan arah tujuan hidupmu dan Ketika meninggal ingin diingat sebagai apa?": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, }), createdAt: new Date(), updatedAt: new Date() }, { id: 58, headline: "Essay 5", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "essay", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "Tuliskan bentuk kontribusi yang telah kamu lakukan untuk daerah / domisilimu saat ini dan mengapa kamu melakukan hal tersebut? (tuliskan peran, tanggung jawab, dan skala lingkupnya serta dapat sebelum dan selama pandemi, dan sertakan bukti jika ada yang dapat berupa link berita / foto / dll)": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "Bukti Dokumentasi": [{ type: "upload", placeholder: "Tambahkan link dokumentasi kontribusi (jika ada)" }, { type: "upload", placeholder: "Tambah Dokumentasi" }, { type: "upload", placeholder: "Tambah Dokumentasi" }] }), createdAt: new Date(), updatedAt: new Date() }, { id: 59, headline: "Rencana Pengabdian", note: null, question: "<small>Jawablah pertanyaan di bawah ini sesuai dengan pendapat kamu sendiri.<small>", TunnelId: 12, category: "volunteering_plan", createdBy: 1, batchFim: "23", isMany: 0, header: JSON.stringify({ "1. Tuliskan alasan mendaftar FIM 23": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "2. Tuliskan & jelaskan satu keahlian/keterampilan diri yang telah diimplementasikan dan dapat kamu berdayakan untuk berkontribusi di FIM (Regional & Pusat)": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, "3. Jelaskan kondisi Daerah / Regional kamu saat ini dan rencana program yang akan dilakukan setelah menyelesaikan Pelatihan FIM 23 untuk pengembangan daerah domisili kamu saat ini / regional (jawaban memuat informasi mengenai: kondisi daerah terkini, rencana program, pihak-pihak, indikator keberhasilan, dan langkah langkah serta timeline)": { type: "textarea", placeholder: "tulis jawaban kamu di sini" }, }), createdAt: new Date(), updatedAt: new Date() }, ]) }, down: async (queryInterface, Sequelize) => { return await queryInterface.bulkDelete('Questions', {id: {$between: [54,59]}}, {}); } }; <file_sep>/README.md # Documentation RESTful API FIM 2019 <!-- <img width="300" src="https://yt3.ggpht.com/a/AGF-l79eetQ4HNIL6hyZdbO82yr3GeshtGC737s8EQ=s900-mo-c-c0xffffffff-rj-k-no"> --> #### Development 1. `npm install` 2. `npm run docker:up` for running postgres docker 3. `npm run migrate` for migrated db in PG 4. `npm run docker:down` for stop postgress docker (*PLEASE DO THIS AFTER YOUR WORK!*) #### Login ``` /auth/login | POST ``` - Header : Content-Type (application/json), Accept (application/json) - Body : ``` { email: STRING, socialId: STRING, loginSource: STRING, profilPicture: STRING, firstName:STRING, lastName:STRING, } ``` - Return : ``` { "token": token, (jwtcode: 'thetokenstokens') "code": 200, "status": NUMBER STATUS } ``` #### Check Session ``` /auth/checksession | POST ``` - Header : Content-Type (application/json), Accept (application/json) - Body : ``` { token: STRING, } ``` - Return : ``` { message: `Token Not Found`, data: {} / null, status: false / true } ``` #### Save KTP ``` /auth/savektp | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { noKtp : STRING, urlKtp : STRING } ``` - Return : ``` { "status": false/true, "message": "Nomor KTP tersebut sudah digunakan oleh email <email>" / "KTP sudah terinput sebelumnya, User berhasil update" / "KTP & Foto KTP berhasil terupload" } ``` #### Get Profile ``` /auth/get-profile | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { } ``` - Return : ``` { "status": true/false, "message": "Data Fetched", "data":{} } ``` #### Update Profile ``` /auth/save-profile | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { "name" : req.body.name, "address": req.body.address, "phone": req.body.phone, "universityId": req.body.universityId, "photoUrl": req.body.urlPhoto, "headline" : req.body.headline, "photoUrl" : req.body.photoUrl, "religion" : req.body.religion, "bornPlace" : req.body.bornPlace, "bornDate" : req.body.bornDate, "cityAddress" : req.body.cityAddress, "provinceAddress" : req.body.provinceAddress, "emergencyPhone" : req.body.emergencyPhone, "gender" : req.body.gender, "bloodGroup" : req.body.bloodGroup, "hoby" : req.body.hoby, "expertise" : req.body.expertise, "institution":req.body.institution, "otherReligion": req.body.otherReligion } ``` - Return : ``` { "status": true/false, "message": "Sukses Update", "data":{} } ``` #### Get University Data ``` /data/get-university | GET ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` {} ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` # CRUD untuk Tunnel (Jalur) #### Tunnel List ``` /tunnel/list | GET ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` {} ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Tunnel Create ``` /tunnel/create | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { name: "Next Gen", description:"TEXT" } ``` - Return : ``` { "status": true, "message": "Data Created", "data":{} } ``` #### Tunnel Read ``` /tunnel/read | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idTunnel: "1" } ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Tunnel Update ``` /tunnel/update | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idTunnel: req.body.idTunnel, name: "Next Gen", description:"TEXT" } ``` - Return : ``` { "status": true, "message": "Data Updated", "data":{} } ``` #### Tunnel User Save ``` /auth/save-tunnel | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { TunnelId: "INTEGER } ``` - Return : ``` { "status": true, "message": "Tunnel Updated", "data":{} } ``` #### Tunnel Delete ``` /tunnel/delete | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idTunnel: "1" } ``` - Return : ``` { "status": true, "message": "Data Deleted", "data":{} } ``` # CRUD untuk Question (Pertanyaan) #### Question List ``` /question/list | GET ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idTunnel: "INTEGER" // ID Jalur Masuk } ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Question Create ``` /question/create | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { question: "STRING", isMany: "INTEGER BOOL" 1 /0, header: OBJECT { 'header_name':header_html_type, for <input type="header_html_type"> 'no':'number' } TunnelId : "INT", batchFim : "STRING" } ``` - Return : ``` { "status": true, "message": "Data Created", "data":{} } ``` #### Question Read ``` /question/read | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idQuestion: "1" } ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Question Update ``` /question/update | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idQuestion: idQuestion, question: question, isMany: "INTEGER BOOL" 1 /0, header: OBJECT { 'header_name':header_html_type, for <input type="header_html_type"> 'no':'number' } TunnelId: TunnelId, batchFim: batchFim, } ``` - Return : ``` { "status": true, "message": "Data Updated", "data":{} } ``` #### Question Delete ``` /question/delete | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idQuestion: "1" } ``` - Return : ``` { "status": true, "message": "Data Deleted", "data":{} } ``` # CRUD untuk Answer (Jawaban) #### Answer List ``` /answer/lists | GET ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { idTunnel: req.body.TunnelId, ktpNumber: req.body.ktpNumber } ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Answer Save ``` /answer/save | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { Answer: req.body.answers, // Array // [ // { // QuestionId:1, // answer: JSON with serialize header // } // ] ktpNumber: req.body.ktpNumber, TunnelId: req.body.TunnelId, createdBy: userId } ``` - Return : ``` { "status": "true", "message": "Answer Saved", "data": "userIdentity" } ``` # CRUD untuk Summary (Mapping dan Scoring) #### Participant List Based Tunne; ``` /summary/lists | GET ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { } ``` - Return : ``` { "status": true, "message": "Data Fetched", "data":{} } ``` #### Final Update ``` /summary/update-final-submit | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { ktpNumber: req.body.ktpNumber, TunnelId: req.body.tunneId } ``` - Return : ``` { "status": "true", "message": "Data Updated", "data": data } ``` #### recruiter Evaluator Update ``` /summary/update-evaluator | POST ``` - Header : Content-Type (application/json), Accept (application/json), Authorization (Bearer <Token>) - Body : ``` { ktpNumber: req.body.ktpNumber, TunnelId: req.body.tunneId, recruiterId: req.body.recruiterId } ``` - Return : ``` { "status": "true", "message": "Data Updated", "data": data } ```<file_sep>/seeders/20210923172900-add-question-pivot-fim-23.js 'use strict'; module.exports = { up: async (queryInterface, Sequelize) => { return queryInterface.bulkInsert('tunnelQuestions', [ { id: 160, TunnelId: 12, QuestionId: 54, createdAt: new Date(), updatedAt: new Date() }, { id: 161, TunnelId: 12, QuestionId: 55, createdAt: new Date(), updatedAt: new Date() }, { id: 162, TunnelId: 12, QuestionId: 56, createdAt: new Date(), updatedAt: new Date() }, { id: 163, TunnelId: 12, QuestionId: 57, createdAt: new Date(), updatedAt: new Date() }, { id: 164, TunnelId: 12, QuestionId: 58, createdAt: new Date(), updatedAt: new Date() }, { id: 165, TunnelId: 12, QuestionId: 59, createdAt: new Date(), updatedAt: new Date() } ]) }, down: async (queryInterface, Sequelize) => { return await queryInterface.bulkDelete('tunnelQuestions', {id: {$between: [160,165]}}, {}) } };
639ebdcd6517fe165b0aedf0b728d14a336327f4
[ "JavaScript", "Markdown" ]
56
JavaScript
fim-engineering/backend-sisfo
cb5df55ce2ba58e7a2cc4375f9380e2a0e059b9c
49c6c8d05d95460d419594b7d6e251036d1ca380
refs/heads/master
<repo_name>kokogamedev/Udemy_3_Project_Boost<file_sep>/Assets/Scenes/Oscillator.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; [DisallowMultipleComponent] //"modifies" class below it public class Oscillator : MonoBehaviour { [SerializeField] Vector3 movementVector = new Vector3(10f, 10f, 10f); //todo remove from inspector later [Range(0,1)] // this and the line below modify the movementFactor variable [SerializeField] float movementFactor; //0 for not moved, 1 for fully moved //store starting position Vector3 startingPos; //store the period [SerializeField] float period = 2f; // Start is called before the first frame update void Start() { startingPos = transform.position; } // Update is called once per frame void Update() { //set movement factor here so that it is automatically in a sinusoidal motion (slow at the edges and fast in the middle) // todo protect against period = 0 float cycles = Time.time / period; // grows continually from 0 const float tau = Mathf.PI * 2; float rawSinWave = Mathf.Sin(cycles * tau); movementFactor = rawSinWave/2f + 0.5f; Vector3 offset = movementFactor * movementVector; transform.position = startingPos + offset; } }
290119dc518fdc53c9fd365325d612f252713a3d
[ "C#" ]
1
C#
kokogamedev/Udemy_3_Project_Boost
daea1e8a9459f209926f41b6e80247217ad3e037
833e07bd55076f040a67f393554d81f87f5a8b68
refs/heads/master
<file_sep>[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-8d59dc4de5201274e310e4c54b9627a8934c3b88527886e3b421487c677d23eb.svg)](https://classroom.github.com/a/N3gPrse-) <file_sep>package edu.quinnipiac.ser210.bitsandpizza; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; /** * <NAME> * SER210 Chapter 12 Demo * Bits and Pizzas Top Fragment * 4/1/21 */ public class TopFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_top, container, false); } }
2fa1ab6169f2ebe1761571a0552d4cb1105a0227
[ "Markdown", "Java" ]
2
Markdown
SER210-SP21/headfirst-ch12-KevinCouillard
a7099ee87924d2c7b5950eddda213f48eaec07ed
0e99b2c85d994229a5894b22472f05373cb76e7a
refs/heads/main
<file_sep># PCS <NAME> 20.22.2393 <file_sep>package com.bibitaries.sepakbola.data.remote import com.bibitaries.sepakbola.data.model.OlahragaList import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface OlahragaService { @GET("/olahraga") fun listOlahraga() : Call<OlahragaList> @GET("detail/") fun detailOlahraga(@Query("url") url: String) : Call<OlahragaList> @GET("search/") fun searchOlahraga(@Query("q") query: String) : Call<OlahragaList> }<file_sep>package com.bibitaries.sepakbola.data.repository import android.app.DownloadManager import com.bibitaries.sepakbola.data.model.ActionState import com.bibitaries.sepakbola.data.model.Olahraga import com.bibitaries.sepakbola.data.remote.OlahragaService import com.bibitaries.sepakbola.data.remote.RetrofitApi import retrofit2.await import java.lang.Exception class OlahragaRepository { private val olahragaService: OlahragaService by lazy { RetrofitApi.olahragaService() } suspend fun listOlahraga() : ActionState<List<Olahraga>> { return try { val list = olahragaService.listOlahraga().await() ActionState(list.data) } catch (e: Exception) { ActionState(message = e.message, isSuccess = false) } } suspend fun detailOlahraga(url: String) : ActionState<Olahraga> { return try { val list = olahragaService.detailOlahraga(url).await() ActionState(list.data.first()) } catch (e: Exception) { ActionState(message = e.message, isSuccess = false) } } suspend fun searchOlahraga(query: String) : ActionState<List<Olahraga>> { return try { val list = olahragaService.searchOlahraga(query).await() ActionState(list.data) } catch (e: Exception) { ActionState(message = e.message, isSuccess = false) } } }<file_sep>package com.bibitaries.sepakbola.data.model data class OlahragaList( val data: List<Olahraga> = arrayListOf(), val length: Int = 0, val status: Int = 0 ) <file_sep>package com.bibitaries.sepakbola.ui.olahraga import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.bibitaries.sepakbola.R class OlahragaActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_olahraga) } companion object { const val OPEN_OLAHRAGA="open_olahraga" } }<file_sep>package com.bibitaries.sepakbola.ui.olahraga import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bibitaries.sepakbola.data.model.ActionState import com.bibitaries.sepakbola.data.model.Olahraga import com.bibitaries.sepakbola.data.repository.OlahragaRepository import kotlinx.coroutines.launch class OlahragaViewModel : ViewModel() { private val repo: OlahragaRepository by lazy { OlahragaRepository() } val loading = MutableLiveData( false) val actionState = MutableLiveData<ActionState<*>>() val listResp = MutableLiveData<List<Olahraga>>() val detailResp = MutableLiveData<Olahraga>() val searchResp = MutableLiveData<List<Olahraga>>() val url = MutableLiveData("") val query = MutableLiveData("") fun listOlahraga() { viewModelScope.launch { loading.value = true val resp = repo.listOlahraga() actionState.value = resp listResp.value = resp.data loading.value = false } } fun detailOlahraga(url: String? = this.url.value) { url?.let { viewModelScope.launch { loading.value = true val resp = repo.detailOlahraga(it) actionState.value = resp detailResp.value = resp.data loading.value = false } } } fun searchOlahraga(query: String? = this.query.value) { query?.let { viewModelScope.launch { loading.value = true val resp = repo.searchOlahraga(it) actionState.value = resp searchResp.value = resp.data loading.value = false } } } }<file_sep>package com.bibitaries.sepakbola.ui.olahraga import android.content.Context import android.content.Intent import androidx.databinding.ViewDataBinding import com.bibitaries.sepakbola.R import com.bibitaries.sepakbola.data.model.Olahraga import com.bibitaries.sepakbola.databinding.ItemOlahragaBinding import com.bibitaries.sepakbola.ui.base.BaseAdapter import com.bumptech.glide.Glide class OlahragaAdapter(val context: Context) : BaseAdapter<Olahraga>(R.layout.item_olahraga) { override fun onBind(binding: ViewDataBinding?, data: Olahraga) { val mBinding = binding as ItemOlahragaBinding Glide.with(context).load(data.poster).into(mBinding.itemPoster) } override fun onClick(binding: ViewDataBinding?, data: Olahraga) { val intent = Intent(context, OlahragaActivity::class.java) intent.putExtra(OlahragaActivity.OPEN_OLAHRAGA, data) context.startActivity(intent) } }
7702ff33e65bfee553f8013eab35d723ac10de7f
[ "Markdown", "Kotlin" ]
7
Markdown
bibitganteng/PCS
745759dfa3c9454586ddecf2cfd1c39d134de6ae
154b7af82d93bb579185667ee66cc6a47e2cdbc5
refs/heads/master
<repo_name>jordi-angmond/MyAlgorithymGit<file_sep>/HashTablesRansomNote.c #include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); char** split_string(char*); // Complete the checkMagazine function below. void checkMagazine(int magazine_count, char** magazine, int note_count, char** note) { int i, j, k, flag, flag2; for (i = 0; i<note_count; i++) { flag2 = 0; for (j = 0; j<magazine_count; j++) { flag = 0; if (strcmp(note[i], magazine[j]) == 0) { flag = 1; strcpy(magazine[j], ""); break; } } if (flag == 0) { printf("No"); return; } } printf("Yes"); } int main() { char** mn = split_string(readline()); char* m_endptr; char* m_str = mn[0]; int m = strtol(m_str, &m_endptr, 10); if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); } char* n_endptr; char* n_str = mn[1]; int n = strtol(n_str, &n_endptr, 10); if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } char** magazine_temp = split_string(readline()); char** magazine = malloc(m * sizeof(char*)); for (int i = 0; i < m; i++) { char* magazine_item = *(magazine_temp + i); *(magazine + i) = magazine_item; } int magazine_count = m; char** note_temp = split_string(readline()); char** note = malloc(n * sizeof(char*)); for (int i = 0; i < n; i++) { char* note_item = *(note_temp + i); *(note + i) = note_item; } int note_count = n; checkMagazine(magazine_count, magazine, note_count, note); return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } alloc_length <<= 1; data = realloc(data, alloc_length); if (!line) { break; } } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; data = realloc(data, data_length); } else { data = realloc(data, data_length + 1); data[data_length] = '\0'; } return data; } char** split_string(char* str) { char** splits = NULL; char* token = strtok(str, " "); int spaces = 0; while (token) { splits = realloc(splits, sizeof(char*) * ++spaces); if (!splits) { return splits; } splits[spaces - 1] = token; token = strtok(NULL, " "); } return splits; } <file_sep>/Heap.c #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tagHeapNode { int element; }HeapNode;//배열로 선언 //자식의 주소는 2k,2k+1에 존재.(index는 1부터 시작) //부모의 주소는 2로 나누면 됨.(index 0을 사용하지 않기 때문에 약간 쉬워짐) typedef struct tagHead { HeapNode *Nodes; int Capacity; int UsedSize; }Heap; void Heap_SwapNodes(Heap *H, int index1, int index2) { int Size = sizeof(HeapNode); HeapNode *tmp = (HeapNode*)malloc(sizeof(HeapNode)); memcpy(tmp, &H->Nodes[index1], Size); memcpy(&H->Nodes[index1], &H->Nodes[index2], Size); memcpy(&H->Nodes[index2], tmp, Size); free(tmp); } Heap* Heap_Create(int Size) { Heap *NewHeap = (Heap*)malloc(sizeof(Heap)); NewHeap->Capacity = Size; NewHeap->UsedSize = 1;//0번 index는 사용하지 않음. NewHeap->Nodes = (HeapNode*)malloc(sizeof(HeapNode)*NewHeap->Capacity); return NewHeap; } void Heap_Destroy(Heap *H) { free(H->Nodes); free(H); } void Heap_Insert(Heap *H, int element) { int CurrentPosition = H->UsedSize; int ParentPosition = CurrentPosition/2;//부모 노드를 찾음. if (H->UsedSize == H->Capacity) { H->Capacity *= 2; H->Nodes = (HeapNode*)realloc(H->Nodes, sizeof(HeapNode)*H->Capacity); } H->Nodes[CurrentPosition].element = element; while (CurrentPosition > 0 && H->Nodes[CurrentPosition].element < H->Nodes[ParentPosition].element) { Heap_SwapNodes(H, CurrentPosition, ParentPosition); CurrentPosition/=2;//부모 노드로. ParentPosition/=2;//부모의 부모 노드로 } H->UsedSize++; } void Heap_DeleteMin(Heap *H) { int ParentPosition = 1; int LeftPosition; int RightPosition; int Size = sizeof(HeapNode); H->UsedSize--; Heap_SwapNodes(H, 1, H->UsedSize); LeftPosition = ParentPosition * 2; RightPosition = ParentPosition * 2 + 1; while (1) { int SelectedChild; if (LeftPosition >= H->UsedSize) break; if (RightPosition >= H->UsedSize) SelectedChild = LeftPosition; else { if (H->Nodes[LeftPosition].element > H->Nodes[RightPosition].element) SelectedChild = RightPosition; else SelectedChild = LeftPosition; } if (H->Nodes[SelectedChild].element < H->Nodes[ParentPosition].element) { Heap_SwapNodes(H, ParentPosition, SelectedChild); ParentPosition = SelectedChild; } else break; LeftPosition = ParentPosition * 2; RightPosition = ParentPosition * 2 + 1; } } void Heap_PrintNodes(Heap *H) { int t = 1; for (int i = 1; i < H->UsedSize; i++) { printf("%d ", H->Nodes[i].element); if (i == t) { printf("\n"); t = t*2+1; } } } int main() { int i=1; Heap *H = Heap_Create(1024); while (1) { printf("삽입할 노드를 입력해주세요. 0을 입력하면 종료합니다:"); scanf("%d", &i); if (i < 1) break; Heap_Insert(H, i); } Heap_PrintNodes(H); printf("\n최소 노드 한개를 지웠습니다\n"); Heap_DeleteMin(H); Heap_PrintNodes(H); printf("\n최소 노드 한개를 지웠습니다\n"); Heap_DeleteMin(H); Heap_PrintNodes(H); scanf("%d", &i); return 0; }<file_sep>/ClimbingTheLeaderBoard.c #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int i, x, y, n, *a, *rank, tmp = 1; scanf("%d", &x); a = (int*)malloc(sizeof(int)*x); rank = (int*)malloc(sizeof(int)*x); for (i = 0; i < x; i++) { scanf("%d", &a[i]); if (i > 0 && a[i] < a[i - 1]) tmp++; rank[i] = tmp; } scanf("%d", &y); tmp++; x--; for (i = 0; i < y; i++) { scanf("%d", &n); while (n >= a[x] && x >= 0) { x--; if (a[x] != a[x + 1]) tmp--; } printf("%d\n", tmp); } scanf("%d", &i); return 0; }<file_sep>/GraphtopologicalSort.c #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 999999999; typedef struct tagVertex { int vertNum; int level;//奄層 骨是拭辞 杖原蟹 搾遂戚 琶推廃走 struct tagEdge* parent;//闘軒拭辞 切重税 採乞 娃識 }Vert; typedef struct tagEdge { int height;//亜掻帖 struct tagVertex* vert1; struct tagVertex* vert2; }Edge; Vert* opposite(Edge *edge, Vert* vert) { if (edge->vert1 == vert) return edge->vert2; else return edge->vert1; } Vert* removeMin(Vert** queue, int x) { int min = MAX, mini = 0, i; Vert* minVert; for (i = 0; i < x; i++) { if (min > queue[i]->level) { min = queue[i]->level; minVert = queue[i]; mini = i; } } for (i = mini; i < x - 1; i++) { queue[i] = queue[i + 1]; } return minVert; }//図楕生稽 哀 呪系 鏑. int main() { int i, j, N, M; int **arr; Edge **edge;//娃識引 亜掻帖 匂敗馬澗 楳慶 Vert **vert; scanf("%d %d\n", &N, &M); arr = (int**)malloc(sizeof(int*)*N); edge = (Edge**)malloc(sizeof(Edge*)*M);//M鯵税 娃識 vert = (Vert**)malloc(sizeof(Vert*)*N);//N鯵税 舛繊 for (i = 0; i < N; i++) { arr[i] = (int*)malloc(sizeof(int)*N); vert[i] = (Vert*)calloc(sizeof(Vert), N); vert[i]->level = 9999999;//max稽 竺舛. vert[i]->parent = NULL;//採乞澗 NULL稽 竺舛. vert[i]->vertNum = i + 1; for (j = 0; j < N; j++) { arr[i][j] = 0;//娃識精 蒸澗 依生稽, 亜掻帖澗 0生稽 段奄鉢 } }//舛繊 段奄鉢 for (i = 0; i < M; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); arr[x - 1][y - 1] = i + 1, arr[y - 1][x - 1] = i + 1; //i腰属 edge虞澗 社軒. edge[i]稽 達聖呪赤製. edge[i] = (Edge*)malloc(sizeof(Edge)); edge[i]->height = z; edge[i]->vert1 = vert[x - 1]; edge[i]->vert2 = vert[y - 1]; }//娃識 段奄鉢 Vert** queue = (Vert**)malloc(sizeof(Vert*)*N);//N鯵研 隔聖 呪 赤澗 queue 竺舛 int x = 0;//泥拭 級嬢亜 赤澗 据社亜 護鯵昔走 硝形捜. 廃鯵亀 蒸聖 凶 0 vert[0]->level = 0;//0腰 舛繊税 level精 0 for (i = 0; i < N; i++) { queue[x] = vert[i]; x++; } int result = 0; while (x > 0) { int flag = 0; Vert* u = removeMin(queue, x); printf(" %d", u->vertNum); x--; if (u->parent != NULL) { // printf("%dしししししし\n", u->parent->height); result += u->parent->height; } for (i = 0; i<N; i++) { if (arr[u->vertNum - 1][i] != 0) { Vert* tmp = opposite(edge[arr[u->vertNum - 1][i] - 1], u); flag = -1; for (j = 0; j < x; j++) { if (queue[j] == tmp) { flag = j; break; } } if (flag == -1) continue; if (tmp->level > edge[arr[u->vertNum - 1][i] - 1]->height) { tmp->level = edge[arr[u->vertNum - 1][i] - 1]->height; tmp->parent = edge[arr[u->vertNum - 1][i] - 1]; queue[flag]->level = edge[arr[u->vertNum - 1][i] - 1]->height; } } } } printf("\n%d", result); scanf("%d", &i); return 0; }<file_sep>/BinarySearchTree.c #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tagNode { int element; struct tagNode *parent; struct tagNode *left; struct tagNode *right; enum { RED, BLACK } Color; }Node; Node* createNode(int element,Node *left,Node *right){ Node *tmp = (Node*)malloc(sizeof(Node)); tmp->element = element; tmp->left = left; tmp->right = right; return tmp; } Node* searchNode(int element,Node *tmp) { if (tmp == NULL) { printf("찾는 원소가 없습니다.\n"); return NULL; } if (element == tmp->element) { printf("찾았습니다. 노드를 반환합니다\n"); return tmp; } else if (tmp->element<element){ searchNode(element, tmp->right); } else { searchNode(element, tmp->left); } } void RotateRight(Node **root, Node *Parent)//root를 바꿀 것이기 때문에 Node **root를 사용. { Node *leftChild = Parent->left; Parent->left = LeftChild->Right; } void appendNode(int element,Node *root) { Node *tmp; if(element>root->element){ if (root->right == NULL) { tmp = createNode(element,NULL,NULL); root->right = tmp; } else appendNode(element, root->right); } else if (element < root->element) { if (root->left == NULL) { tmp = createNode(element, NULL, NULL); root->left = tmp; } else appendNode(element, root->left); } else printf("이미 그 원소가 트리 안에 있습니다.\n"); } Node* deleteNode(int element,Node *parent,Node *tmp) { Node *Removed; if (tmp == NULL) printf("삭제할 노드가 없습니다"); else { if (tmp->element > element) Removed = deleteNode(element,tmp, tmp->left); else if (tmp->element < element) Removed = deleteNode(element,tmp, tmp->right); else//목표를 찾았을 때 { Removed = tmp; if (tmp->left == NULL && tmp->right == NULL) { if (parent->left == tmp) { parent->left = NULL; } else parent->right = NULL; free(tmp); }//no children else if (tmp->left != NULL && tmp->right != NULL) { Node *min = tmp->right;//오른쪽 노드중 가장 작은거. while (min->left != NULL) min = min->left; int x = min->element; Removed = deleteNode(min->element,NULL, tmp); tmp->element = x; }//two children else { Node *tmp2 = NULL; if(tmp->left != NULL) tmp2 = tmp->left; else tmp2 = tmp->right; if (parent->left == tmp) parent->left = tmp2; else parent->right = tmp2;//tmp의 외자식 노드를 부모노드에 연결 free(tmp); }//one child } } return Removed; } void printTree(Node *tmp) { if (tmp->left != NULL) printTree(tmp->left); printf("%d ", tmp->element); if (tmp->right != NULL) printTree(tmp->right); }//중위순회로 출력 int main() { int i, x; Node *tmp; Node *root = createNode(-1,NULL,NULL);//루트 생성 while(1){ if(root->element == -1){ printf("기준점 작성하세요:"); scanf("%d",&root->element); }//첫 기준점 작성 printf("1 : 트리 추가, 2 : 트리 삭제, 3 : 트리 검색, 4:트리 출력, 나머지 : 종료\n"); scanf("%d", &x); switch (x) { case 1: { printf("추가할 트리의 element를 적어주세요:"); scanf("%d", &i); appendNode(i,root); break; } case 2: { printf("삭제할 트리의 element를 적어주세요:"); scanf("%d", &i); tmp = deleteNode(i,root,root); break; } case 3: { printf("찾을 트리의 element를 적어주세요:"); scanf("%d", &i); tmp = searchNode(i, root); break; } case 4: { printf("트리 출력\n"); printTree(root); printf("\n"); break; } default: return; } } return 0; }<file_sep>/ListMergeSort.c #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tagNode { int element; struct tagNode *nextNode; }Node; typedef struct SingleLinkedList { Node *Head; Node *Tail; }List; List* createList() { List *tmp = (List*)malloc(sizeof(List)); tmp->Head = NULL; tmp->Tail = NULL; return tmp; } Node* createNode(int element) { Node *tmp = (Node*)malloc(sizeof(Node)); tmp->element = element; tmp->nextNode = NULL; return tmp; } void addLast(List *L, Node *node) { if (L->Head == NULL) { L->Head = node; L->Tail = node; } else { L->Tail->nextNode = node; L->Tail = L->Tail->nextNode; } } Node* deleteFirst(List *L) { Node *tmp = L->Head; if (L->Head->nextNode == NULL) L->Head = NULL; else { L->Head = L->Head->nextNode; } return tmp; } void printList(List *L) { Node* tmp = L->Head; while (tmp != NULL) { printf("%d ", tmp->element); tmp = tmp->nextNode; } } List* mergeList(List *L1, List *L2) { List *L = createList(); while (L1->Head != NULL && L2->Head != NULL) { if (L1->Head->element <= L2->Head->element) { addLast(L, deleteFirst(L1)); } else { addLast(L, deleteFirst(L2)); } } while (L1->Head != NULL) { addLast(L, deleteFirst(L1)); } while (L2->Head != NULL) { addLast(L, deleteFirst(L2)); } return L; } List* PartitionAndMerge(List *L, int k) { if (k > 1) { int i; List *L1 = createList(); List *L2 = createList(); L1->Head = L->Head;//처음원소. L1->Tail = L->Head;//처음원소. for (i = 0; i < k / 2 - 1; i++) { L1->Tail = L1->Tail->nextNode; } L2->Head = L1->Tail->nextNode;//두번째 L1->Tail->nextNode = NULL; //=======partition=======// L1 = PartitionAndMerge(L1, k / 2); L2 = PartitionAndMerge(L2, k - k / 2); L = mergeList(L1, L2); //========merge========// free(L1), free(L2); } return L; } int main() { int n, i; scanf("%d", &n); List *list = createList(); for (i = 0; i < n; i++) { int x; scanf("%d", &x); Node *tmp = createNode(x); addLast(list, tmp); }//입력 List *L = PartitionAndMerge(list, n); printf("답 : "); printList(L); scanf("%d", &i); return 0; } <file_sep>/kruskal(MST).c #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tagVertex { int vertNum; int level;//기준 범위에서 얼마나 비용이 필요한지 struct tagEdge* parent;//트리에서 자신의 부모 간선 }Vert; typedef struct tagEdge { int height;//가중치 struct tagVertex* vert1; struct tagVertex* vert2; }Edge; Vert* opposite(Edge *edge, Vert* vert) { if (edge->vert1 == vert) return edge->vert2; else return edge->vert1; } Vert* removeMin(Vert** queue, int x) { int min = 99999999, mini = 0, i; Vert* minVert; for (i = 0; i < x; i++) { if (min > queue[i]->level) { min = queue[i]->level; minVert = queue[i]; mini = i; } } for (i = mini; i < x - 1; i++) { queue[i] = queue[i + 1]; } return minVert; }//왼쪽으로 갈 수록 큼. int main() { int i, j, N, M; int **arr; Edge **edge;//간선과 가중치 포함하는 행렬 Vert **vert; scanf("%d %d\n", &N, &M); arr = (int**)malloc(sizeof(int*)*N); edge = (Edge**)malloc(sizeof(Edge*)*M);//M개의 간선 vert = (Vert**)malloc(sizeof(Vert*)*N);//N개의 정점 for (i = 0; i < N; i++) { arr[i] = (int*)malloc(sizeof(int)*N); vert[i] = (Vert*)calloc(sizeof(Vert), N); vert[i]->level = 9999999;//max로 설정. vert[i]->parent = NULL;//부모는 NULL로 설정. vert[i]->vertNum = i + 1; for (j = 0; j < N; j++) { arr[i][j] = 0;//간선은 없는 것으로, 가중치는 0으로 초기화 } }//정점 초기화 for (i = 0; i < M; i++) { int x, y, z; scanf("%d %d %d", &x, &y, &z); arr[x - 1][y - 1] = i + 1, arr[y - 1][x - 1] = i + 1; //i번째 edge라는 소리. edge[i]로 찾을수있음. edge[i] = (Edge*)malloc(sizeof(Edge)); edge[i]->height = z; edge[i]->vert1 = vert[x - 1]; edge[i]->vert2 = vert[y - 1]; }//간선 초기화 Vert** queue = (Vert**)malloc(sizeof(Vert*)*N);//N개를 넣을 수 있는 queue 설정 int x = 0;//큐에 들어가 있는 원소가 몇개인지 알려줌. 한개도 없을 때 0 vert[0]->level = 0;//0번 정점의 level은 0 for (i = 0; i < N; i++) { queue[x] = vert[i]; x++; } int result = 0; while (x > 0) { int flag = 0; Vert* u = removeMin(queue, x); x--; if (u->parent != NULL) { result += u->parent->height; } for (i = 0; i<N; i++) { if (arr[u->vertNum - 1][i] != 0) { Vert* tmp = opposite(edge[arr[u->vertNum - 1][i] - 1], u); flag = -1; for (j = 0; j < x; j++) { if (queue[j] == tmp) { flag = j; break; } } if (flag == -1) continue; if (tmp->level > edge[arr[u->vertNum - 1][i] - 1]->height) { tmp->level = edge[arr[u->vertNum - 1][i] - 1]->height; tmp->parent = edge[arr[u->vertNum - 1][i] - 1]; queue[flag]->level = edge[arr[u->vertNum - 1][i] - 1]->height; } } } } printf("%d", result); scanf("%d", &i); return 0; } <file_sep>/MatrixLayerRotation.c #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main() { int m; int n; int r; int i, j, k = 0, l; scanf("%i %i %i", &m, &n, &r); int matrix[m][n]; for (int matrix_i = 0; matrix_i < m; matrix_i++) { for (int matrix_j = 0; matrix_j < n; matrix_j++) { scanf("%i", &matrix[matrix_i][matrix_j]); } } // r%=(m-1)*2+(n-1)*2; //my code int min; if (m>n) min = n; else min = m; min /= 2; for (l = 0; l<r; l++) { for (k = 0; k<min; k++) { int tmp = matrix[k][k];//좌 상단 요소 저장 for (i = k + 1; i<n - k; i++) { matrix[k][i - 1] = matrix[k][i]; }//왼으로 감(첫 요소가 tmp로 저장됨) for (i = k + 1; i < m - k; i++) { matrix[i - 1][n - k - 1] = matrix[i][n - k - 1]; }//위로 감 for (i = n - k - 1; i>k; i--) { matrix[m - k - 1][i] = matrix[m - k - 1][i - 1]; }//오른쪽으로 감 for (i = m - k - 1; i>k; i--) { matrix[i][k] = matrix[i - 1][k]; }//아래로 감 matrix[k + 1][k] = tmp; } } for (i = 0; i<m; i++) { for (j = 0; j<n; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; } <file_sep>/KakaoColoringBook.cpp #include <vector> #include <iostream> using namespace std; vector<vector<int>> arr(100, vector<int>(100, 0));//picture 대신 사용하는 전역배열.(picture값복사) int number_of_area = 0; int max_size_of_one_area = 0; int recur(int i, int j, int m, int n) { int tmp = arr[i][j], flag = 0, x = 1; arr[i][j] = 0;//색깔을 지움. if (i>0 && tmp == arr[i - 1][j]) { x += recur(i - 1, j, m, n); flag = 1; } if (j>0 && tmp == arr[i][j - 1]) { x += recur(i, j - 1, m, n); flag = 1; } if (i<m-1 && tmp == arr[i + 1][j]) { x += recur(i + 1, j, m, n); flag = 1; } if (j<n-1 && tmp == arr[i][j + 1]) { x += recur(i, j + 1, m, n); flag = 1; } if (flag == 0) return 1; else return x; } // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요. vector<int> solution(int m, int n, vector<vector<int>> picture) { vector<int> answer(2); int i, j, flag = 0, x = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { arr[i][j] = picture[i][j]; } } for (i = 0 ; i<m ; i++) { for (j = 0 ; j<n ; j++) { if (arr[i][j] != 0) { x = recur(i, j, m, n); number_of_area++; if (x>max_size_of_one_area) max_size_of_one_area = x;//최댓값. } } } answer[0] = number_of_area; answer[1] = max_size_of_one_area; return answer; } int main() { int m, n,i,j,x; vector<int> answer(2); cin >> m >> n; vector<vector<int>> v(m, vector<int>(n, 0)); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cin >> v[i][j]; } } answer = solution(m, n, v); cout << answer[0] << " " << answer[1] << endl; cin >> x; return 0; }<file_sep>/README.txt Implementation magic square - https://www.hackerrank.com/challenges/magic-square-forming/problem Matrix Layer Rotation - https://www.hackerrank.com/challenges/matrix-rotation-algo/problem Climbing The LeaderBoard - https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem Kakao Coloring book - https://programmers.co.kr/learn/courses/30/lessons/1829?language=cpp Hash Tables: Ransom Note - https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps (시간복잡도가 너무 많이 들었다. 좀더 시간복잡도를 줄인 코드를 만들 수 있어야 할 듯) Data structure sort/search - bubble, insert, merge, quick / binary search binary tree + search ADT Heap + Priorty Queue<file_sep>/SelectInsertTimeCheck.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<windows.h> int compare(void *first, void *second) { if (*(int*)first > *(int*)second) return -1; else if (*(int*)first < *(int*)second) return 1; else return 0; }//reverse qsort(); void swap(int i, int j, int *arr) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } void selectsort(int *arr,int n) { int i,j,max,iMax; for (i = n-1; i >= 0; i--) { max = 0, iMax = i; for (j = 0; j <= i; j++) { if (max < arr[j]) { max = arr[j]; iMax = j; } } swap(i, iMax, arr); } }//선택 정렬 void insertsort(int *arr,int n) { int i, j,tmp; for (i = 0; i < n; i++) { j = i, tmp = arr[i]; while (tmp<arr[j - 1]) { arr[j] = arr[j - 1]; j--; } arr[j] = tmp; } }//삽입 정렬 double checkTime(void (*foo)(int *arr,int n),int *arr,int n) { LARGE_INTEGER Frequency,BeginTime,Endtime; int elapsed; double duringtime; QueryPerformanceFrequency(&Frequency); QueryPerformanceCounter(&BeginTime); //시간 측정 //=================================// foo(arr,n); //=================================// QueryPerformanceCounter(&Endtime); elapsed = Endtime.QuadPart - BeginTime.QuadPart; duringtime = (double)elapsed / (double)Frequency.QuadPart; return duringtime; } int main() { int a_i; for(a_i=0;a_i<5;a_i++){ int n, i, *a, *a2; double time[6]; scanf("%d", &n); a = (int*)malloc(sizeof(int)*n); a2 = (int*)malloc(sizeof(int)*n); for (i = 0; i < n; i++) { a[i] = rand()%(10000); } for (i = 0; i < n; i++) { a2[i] = rand() % (10000); } time[0] = checkTime(selectsort, a,n); time[1] = checkTime(insertsort, a2,n); time[2] = checkTime(selectsort, a, n); time[3] = checkTime(insertsort, a2, n); qsort(a, n, sizeof(int), compare);//reverse sort qsort(a2, n, sizeof(int), compare);//reverse sort time[4] = checkTime(selectsort, a, n); time[5] = checkTime(insertsort, a2, n); printf("\t\tnot sorted / sorted / reverse sorted\nselect sort\t%fms %fms %fms\ninsert sort\t%fms %fms %fms\n\n", time[0], time[2],time[4], time[1], time[3],time[5]); } scanf("%d", &a_i); return 0; }<file_sep>/QuickSortAndBinarySearch.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<stdio.h> #include<stdlib.h> #include<time.h> void Swap(int *arr, int x, int y) { int tmp = arr[x]; arr[x] = arr[y]; arr[y] = tmp; } int partition(int *arr, int left, int right) { int x1 = rand() % (right - left + 1) + left, x2 = rand() % (right - left + 1) + left, x3 = rand() % (right - left + 1) + left, pivot; if (left + 2 > right) pivot = x1;//원소 두개 이하일때 까지는 왼쪽거가 pivot else { if ((arr[x1] >= arr[x2] && arr[x3] >= arr[x1]) || (arr[x1] <= arr[x2] && arr[x3] <= arr[x1])) pivot = x1; else if ((arr[x2] >= arr[x1] && arr[x3] >= arr[x2]) || (arr[x2] <= arr[x1] && arr[x3] <= arr[x2])) pivot = x2;//x1이 젤큼 else pivot = x3; }//pivot 중간값 찾기 방법. pivot값은 left에 존재. Swap(arr, left, pivot);//왼쪽 원소로 hide*/ int low = left + 1, high = right; while (low <= high) { while (arr[left] >= arr[low] && low <= high) low++; while (arr[left] <= arr[high] && high >= low) high--;//중복값 찾기 가능 if (low <= high) Swap(arr, low, high); } Swap(arr, left, high); return high; } void QuickSort(int *arr, int l, int r) { if (l <= r) { int pivot = partition(arr, l, r); QuickSort(arr, l, pivot - 1); QuickSort(arr, pivot + 1, r); } } int binarySearch(int *arr, int left, int right, int k) { while (left <= right) { int pivot = (right + left) / 2; if (arr[pivot] == k) return pivot; else if (arr[pivot] < k) left = pivot + 1; else right = pivot - 1; } return left; } int main() { int i, n, *arr, x, result; scanf("%d", &n); arr = (int*)malloc(sizeof(int)*n); for (i = 0; i < n; i++) scanf("%d", &arr[i]); QuickSort(arr, 0, n - 1); for (i = 0; i < n; i++) printf(" %d", arr[i]); printf("\n"); scanf("%d", &x); result = binarySearch(arr, 0, n - 1, x); if (arr[result] == x) printf("값 %d이 %d번째 인덱스에 존재합니다.", x, result + 1); else { printf("값 %d는 존재하지 않습니다.\n", x); if (result == 0) printf("%d번째 인덱스 값 %d 앞에 들어갑니다.", result, arr[result]); else if (result == n) printf("%d번째 인덱스 값 %d 뒤에 들어갑니다", result - 1, arr[result - 1]); else printf("%d번째 인덱스 값 %d와 %d번째 인덱스 값 %d 사이에 들어갑니다.", result - 1, arr[result - 1], result, arr[result]); } free(arr); scanf("%d", &x); return 0; }<file_sep>/sort.c #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> int a[100]; void Swap(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } int mergeSort(int low,int high) { int mid = (low + high) / 2; if (high - low > 1) { mergeSort(low, mid); mergeSort(mid+1, high); } if (low == high) return; int left = low; int right = mid + 1; int i; int *tmpArr = (int*)malloc(sizeof(int)*(high - low + 1)); free(tmpArr); } void Q int main(){ int i,j, tmp; srand((unsigned int)time(NULL)); for(i=0;i<100;i++) { a[i] = rand()%1000; } for (i = 1; i < 100; i++) { for (j = 1; j < 100 - i+1; j++) { if (a[j - 1] > a[j]) { tmp = a[j - 1]; a[j - 1] = a[j]; a[j] = tmp; } } } for (i = 0; i < 100; i++) { printf("%d ", a[i]); }//bubble sort printf("\n\n\n"); for (i = 0; i<100; i++) { a[i] = rand() % 1000; } for (i = 1; i < 100; i++) { if (a[i - 1] <= a[i]) continue; int tmp = a[i]; j = i; while (j > 0 && a[j-1] > tmp) { a[j] = a[j-1]; j--; } a[j] = tmp; } for (i = 0; i < 100; i++) { printf("%d ", a[i]); }//insert sort printf("\n\n\n"); for (i = 0; i<100; i++) { a[i] = rand() % 1000; } mergeSort(0, 99); for (i = 0; i < 100; i++) { printf("%d ", a[i]); }//merge sort printf("\n\n\n"); for (i = 0; i<100; i++) { a[i] = rand() % 1000; } for (i = 0; i < 100; i++) { printf("%d ", a[i]); }//quick sort printf("\n\n\n"); quickSort(0, 99); for (i = 0; i < 100; i++) { printf("%d ", a[i]); }//quick sort printf("\n"); scanf("%d ", &i); return 0; }<file_sep>/graphDPSBPS.c #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct tagVertex { int num; int fresh;//방문했던 노드였는지 확인하기 위함 int height; struct tagNode *head; }Vert;//정점 typedef struct tagNode { struct tagNode* nextNode; struct tagEdge* edge; struct tagVertex* vert; }Node; typedef struct tagEdge { int weight;//간선의 우선순위. 지금은 의미없음. int fresh;//방문했던 노드였는지 확인하기 위함 Vert* vert1; Vert* vert2; }Edge;//간선 void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } Node* makeNode(Vert* vert, Edge* edge) { Node* tmp = (Node*)malloc(sizeof(Node)); tmp->edge = edge; tmp->vert = vert; tmp->nextNode = NULL; return tmp; } Vert* opposite(Edge *edge, Vert* vert) { if (edge->vert1 != vert) return edge->vert1; else return edge->vert2; } void insertNode(Vert* vert, Edge* edge) { Node* tmp = vert->head; Vert* x = opposite(edge,vert); while (tmp->nextNode != NULL) { Vert* x2 = opposite(tmp->nextNode->edge, vert); if (x->num < x2->num) break; tmp = tmp->nextNode; } Node *tmp2 = makeNode(vert, edge); tmp2->nextNode = tmp->nextNode; tmp->nextNode = tmp2; } Vert** makeVertex(int N) { Vert** tmp = (Vert**)calloc(sizeof(Vert*), (N + 1)); int i; for (i = 0; i < N; i++) { tmp[i] = (Vert*)malloc(sizeof(Vert)); tmp[i]->num = i + 1; tmp[i]->fresh = 0; tmp[i]->height = 0; tmp[i]->head = makeNode(tmp[i], NULL);//dummy head Node 추가 } return tmp; } Edge* makeEdgeNode(int a, int b, Vert** vert) { Edge* edge = (Edge*)malloc(sizeof(Edge)); if (a < b) swap(&a, &b);//a는 b와 같거나 작음. edge->vert1 = vert[a - 1]; edge->vert2 = vert[b - 1]; edge->fresh = 0;//아직 방문하지 않음 edge->weight = 0; //dummy return edge; } Edge** makeEdge(Vert** vert, int M) { int i; Edge** edge = (Edge**)malloc(sizeof(Edge*)*M); for (i = 0; i < M; i++) { int a, b; scanf("%d %d", &a, &b); edge[i] = makeEdgeNode(a, b, vert); insertNode(vert[a - 1], edge[i]); if (edge[i]->vert1 != edge[i]->vert2) insertNode(vert[b - 1], edge[i]); }//간선과 노드의 초기화. return edge; } void DFS(Vert* vert) { printf("%d\n", vert->num); vert->fresh = 1;//노드가 사용되었다는 것을 표시. Node* tmp = vert->head; while (tmp->nextNode != NULL) { tmp = tmp->nextNode; if (tmp->edge->fresh == 0) { tmp->edge->fresh = 1; Vert* op = opposite(tmp->edge, tmp->vert); if(op->fresh == 0) DFS(op); } } } void DepthFirstSearch(Vert** vert, Edge** edge, int N, int M, int S) { int i; for (i = 0; i < N; i++) { vert[i]->fresh = 0; }//vert initialization for (i = 0; i < M; i++) { edge[i]->fresh = 0; }//edge initialization DFS(vert[S - 1]); for (i = 0; i < N; i++) { if(vert[i]->fresh == 0) DFS(vert[i]); }//동떨어져 있는 노드가 있는지 확인 } void BFS(Vert* vert, int N) { vert->fresh = 1; Vert** Queue = (Vert**)calloc(sizeof(Vert*), N); int start = 0, end = 0;//힙 노드 배열에 노드를 추가하기 위한 변수. 처음에는 한개 들어있음. Queue[end] = vert;//처음 초기화. end++; while (start < end) { Node* tmp = Queue[start]->head; start++; printf("%d\n", tmp->vert->num); while (tmp->nextNode != NULL) { tmp = tmp->nextNode; if (tmp->edge->fresh == 1) continue; Vert* op = opposite(tmp->edge,tmp->vert); if (op->fresh == 0) { tmp->edge->fresh = 1; op->fresh = 1; Queue[end] = op; end++; } } } free(Queue); } void BreadthFirstSearch(Edge** edge, Vert** vert, int N, int M, int S) { int i; for (i = 0; i < N; i++) { vert[i]->fresh = 0; }//vert initialization for (i = 0; i < M; i++) { edge[i]->fresh = 0; }//edge initialization BFS(vert[S - 1],N); for (i = 0; i < N; i++) { if (vert[i]->fresh == 0) BFS(vert[i], N); } } void printEdge(Vert** vert) { int n; scanf("%d", &n); Node *tmp = vert[n]->head->nextNode; while (tmp != NULL) { int result; if (tmp->edge->vert1->num == vert[n]->num) result = tmp->edge->vert2->num; else result = tmp->edge->vert1->num; printf(" %d 가중치: %d\n", result, tmp->edge->weight); tmp = tmp->nextNode; } } int main() { int N, M, S, i; printf("노드 숫자와 간선 숫자, 순회를 시작할 숫자를 입력해주세요:\n");//리스트 형식으로도 만들 수 있다. scanf("%d %d %d", &N, &M, &S);//노드 숫자,간선 숫자,시작하는 노드의 숫자 Vert** vert = makeVertex(N); Edge** edge = makeEdge(vert,M); printf("DepthFirstSearch\n"); DepthFirstSearch(vert,edge, N, M, S); printf("\nBreadthFirstSearch\n"); BreadthFirstSearch(edge, vert, N, M, S); return 0; }
c3deb49b1f50e3cf71b003030b42d9359f1ce7dc
[ "C", "Text", "C++" ]
14
C
jordi-angmond/MyAlgorithymGit
41aa8e1281e3bdf251fef30f252a459b40b89317
4066af4a0c68cea470739eec621870af3e39e5e0
refs/heads/master
<file_sep>#ifndef DIMENSIONS_H #define DIMENSIONS_H #include "json11/json11.hpp" typedef struct Dimensions_t { int w; int h; } Dimensions; typedef struct Site_t { uint8_t owner; uint8_t strength; Site_t(json11::Json site_json); } Site; using Frame = std::vector<std::vector<Site>>; using Productions = std::vector<std::vector<uint8_t>>; #endif // DIMENSIONS_H <file_sep>#include "sdl.hpp" using namespace sdl; Surface::Surface(SDL_Surface *surface) { if (!surface) { throw std::runtime_error("Surface was null!"); } this->surface = surface; } Window::Window(SDL_Window *window) { if (!window) { throw std::runtime_error("Window was null!"); } this->window = window; } SDL::SDL(int num_players) { srand(time(NULL)); this->num_players = num_players; SDL_DisplayMode display_mode; if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw std::runtime_error( std::string("SDL failed to initialise! SDL_Error: ") + std::string(SDL_GetError())); } if (SDL_GetCurrentDisplayMode(0, &display_mode)) { throw std::runtime_error( std::string("SDL failed to get display mode! SDL_Error: ") + std::string(SDL_GetError())); } screen_dim.w = display_mode.w; screen_dim.h = display_mode.h; board_display_dim.w = MIN(screen_dim.w, screen_dim.h); board_display_dim.h = screen_dim.h; window = std::make_unique<Window>( SDL_CreateWindow("Halite Replay Visualiser", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_dim.w, screen_dim.h, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN)); screen_surface = std::make_unique<Surface>(SDL_GetWindowSurface(window->window)); // choose player colors player_color_choices.push_back(red); player_color_choices.push_back(green); player_color_choices.push_back(blue); player_color_choices.push_back(yellow); player_color_choices.push_back(aqua); player_color_choices.push_back(fuchsia); SDL_Rect pcolor_rect = {board_display_dim.w + 2, 2, 26, 26}; player_colors.push_back(white); // neutral player is white while (num_players-- > 0) { const int rand_color_index = std::rand() % player_color_choices.size(); const Color color = player_color_choices[rand_color_index]; player_colors.push_back(color); FillRect(&pcolor_rect, MapRGB(color)); pcolor_rect.y += 30; player_color_choices.erase(player_color_choices.begin() + rand_color_index); } } SDL::~SDL() { // we _must_ release the surface before quitting sdl // otherwise the destructor for screen_surface will be // called after sdl has shut down screen_surface.reset(); SDL_QuitSubSystem(SDL_INIT_VIDEO); } void SDL::SetBoardDim(Dimensions board_dim) { this->board_dim = board_dim; } void SDL::SetTileDim(Dimensions tile_dim) { this->tile_dim = tile_dim; } uint32_t SDL::MapRGB(uint8_t r, uint8_t g, uint8_t b) const { return SDL_MapRGB(screen_surface->surface->format, r, g, b); } uint32_t SDL::MapRGB(Color color, uint8_t intensity) const { return MapRGB((color.r / 255) * intensity, (color.g / 255) * intensity, (color.b / 255) * intensity); } uint32_t SDL::MapRGB(Color color) const { return MapRGB(color, 0xff); } void SDL::FillRect(const SDL_Rect *rect, uint32_t color) { if (SDL_FillRect(screen_surface->surface, rect, color) < 0) { throw std::runtime_error(std::string("SDL_FillRect failed! SDL_Error: ") + std::string(SDL_GetError())); } } void SDL::UpdateWindowSurface(void) { if (SDL_UpdateWindowSurface(window->window) < 0) { throw std::runtime_error( std::string("SDL_UpdateWindowSurface failed! SDL_Error: ") + std::string(SDL_GetError())); } } void SDL::RenderFrame(const Frame &frame, const HaliteReplay &replay) { // draw the board for (int y = 0; y < board_dim.h; y++) { for (int x = 0; x < board_dim.w; x++) { const uint8_t tp = replay.productions.at(y).at(x) * 10; const uint8_t owner = frame.at(y).at(x).owner; const uint8_t strength = frame.at(y).at(x).strength; const uint8_t swidth = strength * tile_dim.w / 510; const uint8_t sheight = strength * tile_dim.h / 510; const SDL_Rect r = {x * tile_dim.w, y * tile_dim.h, tile_dim.w, tile_dim.h}; const SDL_Rect ir = {x * tile_dim.w + (tile_dim.w / 2 - swidth), y * tile_dim.h + (tile_dim.w / 2 - sheight), swidth * 2, sheight * 2}; uint32_t bcolor = MapRGB(player_colors.at(owner), tp); uint32_t fcolor = MapRGB(player_colors.at(owner)); FillRect(&r, bcolor); FillRect(&ir, fcolor); } } // draw the player colors in the info section SDL_Rect game_info_color_rect = {board_display_dim.w + 2, 32 + (screen_dim.h / 2), 26, 26}; for (int i = 0; i < 3; i++) { for (int player = 1; player < (num_players + 1); player++) { FillRect(&game_info_color_rect, MapRGB(player_colors.at(player))); game_info_color_rect.y += 30; } game_info_color_rect.y += 30; } // Update the surface UpdateWindowSurface(); } void SDL::BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Rect *dstrect) { if (SDL_BlitSurface(src, srcrect, screen_surface->surface, dstrect) < 0) { throw std::runtime_error( std::string("SDL_BlitSurface failed! SDL_Error: ") + std::string(SDL_GetError())); } } <file_sep>cmake_minimum_required(VERSION 2.6) project(halite_native_visualiser) set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wall -Wextra -march=native -O3 -ffast-math") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wall -Wextra -march=native -g") file(GLOB SOURCES "src/*.cpp") file(GLOB JSON_SOURCES "src/json11/*.cpp") add_executable(${PROJECT_NAME} ${SOURCES}) find_package(SDL2 REQUIRED) if (SDL2_FOUND) include_directories(${SDL2_INCLUDE_DIR}) target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARY}) endif() find_package(SDL2_TTF REQUIRED) if (SDL2_TTF_FOUND) include_directories(${SDL2_TTF_INCLUDE_DIR}) target_link_libraries(${PROJECT_NAME} ${SDL2_TTF_LIBRARY}) endif() include_directories(include) add_library(sdl.o STATIC ${SOURCES}) add_library(ttf.o STATIC ${SOURCES}) add_library(json.o STATIC ${SOURCES}) target_link_libraries(${PROJECT_NAME} sdl.o ttf.o json.o) <file_sep>#ifndef HALITEGAMEINFO_H #define HALITEGAMEINFO_H #include <vector> class HaliteGameInfo { public: std::vector<int> territory_data; std::vector<int> production_data; std::vector<int> strength_data; HaliteGameInfo(int num_players); }; #endif // HALITEGAMEINFO_H <file_sep>#ifndef SDL_H #define SDL_H #include "dimensions.hpp" #include "halite_replay.hpp" #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <cstdlib> #define MIN(a, b) (a < b) ? a : b namespace sdl { class Surface { public: Surface(SDL_Surface *surface); ~Surface() { SDL_FreeSurface(surface); } SDL_Surface *surface; }; class Window { public: Window(SDL_Window *window); ~Window() { SDL_DestroyWindow(window); } SDL_Window *window; }; class SDL { public: typedef struct Color_t { uint8_t r; uint8_t g; uint8_t b; } Color; std::unique_ptr<Window> window; std::unique_ptr<Surface> screen_surface; Dimensions screen_dim; Dimensions board_display_dim; Dimensions board_dim; Dimensions tile_dim; int num_players; SDL(int num_players); ~SDL(); void SetBoardDim(Dimensions board_dim); void SetTileDim(Dimensions tile_dim); uint32_t MapRGB(uint8_t r, uint8_t g, uint8_t b) const; uint32_t MapRGB(Color color, uint8_t intensity) const; uint32_t MapRGB(Color color) const; void FillRect(const SDL_Rect *rect, uint32_t color); void UpdateWindowSurface(void); void RenderFrame(const Frame &frame, const HaliteReplay &replay); void BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Rect *dstrect); private: std::vector<Color> player_colors; // const Color black = {0x00, 0x00, 0x00}; const Color white = {0xff, 0xff, 0xff}; const Color red = {0xff, 0x00, 0x00}; const Color green = {0x00, 0xff, 0x00}; const Color blue = {0x00, 0x00, 0xff}; const Color yellow = {0xff, 0xff, 0x00}; const Color aqua = {0x00, 0xff, 0xff}; const Color fuchsia = {0xff, 0x00, 0xff}; std::vector<Color> player_color_choices; }; } #endif // SDL_H <file_sep>#ifndef HALITEREPLAY_H #define HALITEREPLAY_H #include "dimensions.hpp" #include "json11/json11.hpp" #include <algorithm> #include <iostream> class HaliteReplay { public: int num_players; int num_frames; Dimensions board_dimensions; std::vector<Frame> frames; Productions productions; HaliteReplay(const json11::Json &replay_json); }; #endif // HALITEREPLAY_H <file_sep>#include "ttf.hpp" TTF::TTF(sdl::SDL &sdl) : sdl(sdl) { this->num_players = sdl.num_players; if (TTF_Init()) { throw std::runtime_error("TTF failed to initialise!"); } font = TTF_OpenFont("DroidSansMono.ttf", 24); if (!font) { throw std::runtime_error("SDL_TTF failed to load \"FreeSans.ttf\"!"); } } TTF::~TTF() { TTF_CloseFont(font); TTF_Quit(); } void TTF::RenderGameInfo(const Frame &frame, const Productions &productions) { HaliteGameInfo game_info(num_players); std::vector<std::string> game_info_strings; CalculateGameInfo(game_info, frame, productions); MakeGameInfoStrings(game_info_strings, game_info); ClearGameInfo(); DrawGameInfo(game_info_strings); } void TTF::CalculateGameInfo(HaliteGameInfo &game_info, const Frame &frame, const Productions &productions) const { for (unsigned y = 0; y < frame.size(); y++) { std::vector<Site> row = frame[y]; for (unsigned x = 0; x < row.size(); x++) { Site site = row.at(x); int owner = site.owner - 1; // neutral id is 0, players start from 1 if (owner >= 0) { game_info.strength_data.at(owner) += site.strength; game_info.territory_data.at(owner)++; game_info.production_data.at(owner) += productions.at(y).at(x); } } } } void TTF::MakeGameInfoStrings(std::vector<std::string> &game_info_strings, const HaliteGameInfo &game_info) const { game_info_strings.push_back(std::string("Territory:")); for (const auto &territory : game_info.territory_data) { game_info_strings.push_back( std::string(" " + std::to_string(territory))); } game_info_strings.push_back(std::string("Production:")); for (const auto &production : game_info.production_data) { game_info_strings.push_back( std::string(" " + std::to_string(production))); } game_info_strings.push_back(std::string("Strength:")); for (const auto &strength : game_info.strength_data) { game_info_strings.push_back(std::string(" " + std::to_string(strength))); } } void TTF::DrawGameInfo(const std::vector<std::string> &game_info_strings) { SDL_Rect text_rect = {sdl.board_display_dim.w, sdl.screen_dim.h / 2, sdl.screen_dim.w - sdl.board_display_dim.w, 30}; for (const auto &s : game_info_strings) { sdl::Surface text_surface(TTF_RenderText_Solid(font, s.c_str(), white)); sdl.BlitSurface(text_surface.surface, NULL, &text_rect); text_rect.y += 30; } } void TTF::ClearGameInfo(void) { SDL_Rect game_info_rect = {sdl.board_display_dim.w, sdl.screen_dim.h / 2, sdl.screen_dim.w - sdl.board_display_dim.w, sdl.screen_dim.h / 2}; sdl.FillRect(&game_info_rect, sdl.MapRGB(0, 0, 0)); } void TTF::DrawGameTitle(const std::vector<std::string> &player_names) { SDL_Rect game_info_rect = {sdl.board_display_dim.w + 50, 0, sdl.screen_dim.w - sdl.board_display_dim.w - 50, 30}; auto draw_title_text = [this, &game_info_rect](const auto &text) mutable { sdl::Surface text_surface(TTF_RenderText_Solid(font, text.c_str(), white)); sdl.BlitSurface(text_surface.surface, NULL, &game_info_rect); game_info_rect.y += 30; }; std::for_each(player_names.begin(), player_names.end(), draw_title_text); game_info_rect.x -= 50; draw_title_text(std::string("https://halite.io to play!")); draw_title_text(std::string("http://bit.ly/2gixxGr for this visualiser")); } <file_sep>#include "halite_game_info.hpp" HaliteGameInfo::HaliteGameInfo(int num_players) { territory_data.resize(num_players); production_data.resize(num_players); strength_data.resize(num_players); // zero the vectors std::fill(territory_data.begin(), territory_data.end(), 0); std::fill(production_data.begin(), production_data.end(), 0); std::fill(strength_data.begin(), strength_data.end(), 0); } <file_sep>// <NAME> <<EMAIL>> // Will be better documented in the future, I promise #include "halite_native_visualiser.hpp" namespace { void GetJsonFromFile(json11::Json &replay, const std::string &file_name) { std::string json_string; std::ifstream replay_file(file_name); if (replay_file.is_open()) { std::getline(replay_file, json_string); replay_file.close(); } else { throw std::runtime_error("Couldn't open json file!"); } std::string err_string; // we don't really care about this replay = json11::Json::parse(json_string, err_string); } std::vector<std::string> GetPlayerNames(const json11::Json &player_names_json) { if (player_names_json.is_null()) { throw std::runtime_error("Couldn't get player names from json!"); } std::vector<std::string> player_names; for (const auto &player_name_json : player_names_json.array_items()) { // TODO: Make a wrapper for string_value() player_names.push_back(player_name_json.string_value()); } return player_names; } } char default_file_name[] = "replay.hlt"; int main(int argc, char *argv[]) { char *file_name = default_file_name; int total_time = 5; // seconds // get some arguments // TODO: Do this properly if (argc > 1) { file_name = argv[1]; } if (argc > 2) { total_time = std::stoi(argv[2]); } json11::Json root; GetJsonFromFile(root, file_name); HaliteReplay replay(root); sdl::SDL sdl(replay.num_players); TTF ttf(sdl); // can this be reworked? sdl.SetBoardDim(replay.board_dimensions); const int delay_ms = total_time * 1000 / replay.num_frames; sdl.SetTileDim({sdl.board_display_dim.w / sdl.board_dim.w, sdl.board_display_dim.h / sdl.board_dim.h}); ttf.DrawGameTitle(GetPlayerNames(root["player_names"])); for (const auto &frame : replay.frames) { sdl.RenderFrame(frame, replay); ttf.RenderGameInfo(frame, replay.productions); SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { goto finish; } } SDL_Delay(delay_ms); } finish: return 0; } <file_sep>#include "halite_replay.hpp" static json11::Json Get(const json11::Json &json, size_t index) { json11::Json r = json[index]; if (r.is_null()) { throw new std::runtime_error("Json index was wrong!"); } return r; } static json11::Json Get(const json11::Json &json, const std::string &str) { json11::Json r = json[str]; if (r.is_null()) { throw new std::runtime_error("Json element string was wrong!"); } return r; } static int GetInt(const json11::Json &json) { if (!json.is_number()) { throw new std::runtime_error( "GetInt called on something which wasn't a number!"); } return json.int_value(); } Site::Site_t(json11::Json site_json) { json11::Json owner_json = Get(site_json, 0); json11::Json strength_json = Get(site_json, 1); this->owner = GetInt(owner_json); this->strength = GetInt(strength_json); } HaliteReplay::HaliteReplay(const json11::Json &replay_json) { int version = GetInt(Get(replay_json, "version")); if (version != 11) { throw std::runtime_error(std::string("Replay is the wrong version: ") + std::to_string(version)); } num_players = GetInt(Get(replay_json, "num_players")); json11::Json productions_json = Get(replay_json, "productions"); json11::Json frames_json = Get(replay_json, "frames"); board_dimensions.w = GetInt(Get(replay_json, "width")); board_dimensions.h = GetInt(Get(replay_json, "height")); num_frames = GetInt(Get(replay_json, "num_frames")); for (const auto &frame_json : frames_json.array_items()) { Frame frame_vector; for (const auto &row_json : frame_json.array_items()) { std::vector<Site> row_vector; for (const auto &site_json : row_json.array_items()) { row_vector.push_back(Site(site_json)); } frame_vector.push_back(row_vector); } frames.push_back(frame_vector); } for (const auto &row_json : productions_json.array_items()) { std::vector<uint8_t> row_vector; for (const auto &production_json : row_json.array_items()) { row_vector.push_back(GetInt(production_json)); } productions.push_back(row_vector); } } <file_sep>#ifndef TTF_H #define TTF_H #include <SDL2/SDL_ttf.h> #include <algorithm> #include <memory> #include "dimensions.hpp" #include "halite_game_info.hpp" #include "sdl.hpp" class TTF { public: TTF(sdl::SDL &sdl); ~TTF(); void RenderGameInfo(const Frame &frame, const Productions &productions); void DrawGameTitle(const std::vector<std::string> &player_names); private: TTF_Font *font; sdl::SDL &sdl; const SDL_Color white = {0xff, 0xff, 0xff, 0xff}; void CalculateGameInfo(HaliteGameInfo &game_info, const Frame &frame, const Productions &productions) const; void MakeGameInfoStrings(std::vector<std::string> &game_info_strings, const HaliteGameInfo &game_info) const; void DrawGameInfo(const std::vector<std::string> &game_info_strings); void ClearGameInfo(); int num_players; }; #endif // TTF_H <file_sep>#ifndef HALITE_NATIVE_VISUALISER_H #define HALITE_NATIVE_VISUALISER_H #include <algorithm> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <vector> #include "halite_replay.hpp" #include "json11/json11.hpp" #include "sdl.hpp" #include "ttf.hpp" namespace { void GetJsonFromFile(json11::Json &replay, const std::__cxx11::string &file_name); std::vector<std::string> GetPlayerNames(const json11::Json &player_names_json); } #endif
27575131dc5473f843bb0f78befd393761b7d4ac
[ "CMake", "C++" ]
12
C++
notenoughram/halite-native-visualiser
e52e31541694ffb7d79ad804c58808095d9a9b8b
e2644151e954842c82c3a7be41b0cf8f8fae8d20
refs/heads/master
<repo_name>sonasuresh/switchon-Frontend<file_sep>/src/views/LoginView.js import React, { Component } from 'react' import { Link } from 'react-router-dom' import callAPI from '../lib/axios' import logger from '../lib/logger' import Alert from '../components/Alert' export default class LoginView extends Component { constructor(props) { localStorage.clear(); super(props) this.state = { email: '', password: '', alertFlag: '', message: '', showAlertFlag: false } } handleLoginClick = async () => { const { email, password } = this.state if (email === '' && password === '') { alert('Cannot proceed without username and/or password') } else { try { const response = await callAPI('post', '/user/login', { data: { email, password } }) if (response.status === 200) { localStorage.setItem('token', response.data.jwttoken) localStorage.setItem('email', response.data.email) localStorage.setItem('id', response.data.id) this.setState({ alertFlag: true }) this.setState({ showAlertFlag: true }) this.setState({ message: 'Login Successful!' }) window.location = '/#/' } else { logger.error(response.data.message) } } catch (error) { logger.error(error) this.setState({ message: 'Login Failed!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } } render() { return ( <div> <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4"></h1> <p className="lead" align="center"><h3>A One Step Solution to Invite Users via Form Request!</h3></p> </div> </div> {this.state.showAlertFlag ? <Alert flag={this.state.alertFlag} message={this.state.message} /> : ''} <div style={{display:"flex",justifyContent:"center"}}> <div className="card"> <div className="card-body"> <div className="pt-5 login-bg text-white h-100"> <div className="text-center"> <h3>Login Here..!</h3> <div style={{ fontSize: 20 }} className="mt-5"> <div style={{ marginLeft: 100, marginRight: 100 }}> <input className="form-control text-center placeholder-colored " placeholder="<EMAIL>" onChange={(e) => { const { state: currentState } = this currentState.email = e.target.value this.setState(currentState) }}></input> </div> <div className="mt-3" style={{ marginLeft: 100, marginRight: 100 }} > <input type="<PASSWORD>" className="form-control text-center placeholder-colored" placeholder="<PASSWORD>" onChange={(e) => { const { state: currentState } = this currentState.password = e.target.value this.setState(currentState) }}></input> </div> <div className="mt-3 rounded" > <button className="btn btn-info w-25" style={{ marginLeft: 120, marginRight: 100 }} onClick={this.handleLoginClick}> Login </button><br /> <Link to="/register" className="link"> Dont Have an Account? Sign Up </Link> </div> </div> </div> </div> </div> </div> </div> </div> ) } }<file_sep>/src/views/FormView.js import React, { Component } from 'react'; import NavBar from '../components/NavBar' import callAPI from '../lib/axios' import Alert from '../components/Alert' class FormView extends Component { constructor(props) { super(props); this.state = { currentUser: localStorage.getItem('id'), otherDepartments: [], departmentUsers: [], currentDepartment: '', assignedToUser: '', message: '', alertFlag: '', message: '', showAlertFlag: false } } componentDidMount() { this.getOtherDepartments() } getOtherDepartments = async () => { const departments = await callAPI('get', `/department/other/${localStorage.getItem('id')}`) const { state: currentState } = this currentState.otherDepartments = departments.data.message this.setState(currentState) } getUsersBasedOnDepartment = async () => { const departments = await callAPI('get', `user/department/${this.state.currentDepartment}`) const { state: currentState } = this currentState.departmentUsers = departments.data.message this.setState(currentState) } handleSendRequestClick = async () => { const { currentUser, assignedToUser, message } = this.state if (assignedToUser !== "") { if (message !== "") { try { await callAPI('post', '/form', { data: { createdById: currentUser, assignedToId: assignedToUser, message } }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: true }) this.setState({ message: 'Form Requested!' }) } catch (error) { this.setState({ message: 'An error occured!Try Again!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } else { this.setState({ message: 'Message is missing!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } else { this.setState({ message: 'One of the field is missing!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } render() { return ( <div> <NavBar /> {this.state.showAlertFlag ? <Alert flag={this.state.alertFlag} message={this.state.message} /> : ''} <div className="mt-5 container"> <div className="card"> <div className="card-header"> <h5>Form Request</h5> </div> <div className="card-body"> <div> <div className="text-center"> <div style={{ fontSize: 20 }} className="mt-2"> <form> <div className="form-group row"> <label className="col-sm-2 col-form-label">Created By</label> <div className="col-sm-10"> <input type="text" readOnly className="form-control" value={localStorage.getItem('email')} /> </div> </div> <div className="form-group row"> <label className="col-sm-2 col-form-label">Department</label> <div className="col-sm-10"> <select defaultValue={'DEFAULT'} className="custom-select mb-3" onChange={(e) => { const { state: currentState } = this currentState.currentDepartment = e.target.value this.setState(currentState) this.getUsersBasedOnDepartment() }} required > <option value="DEFAULT" disabled>Select Department</option> {this.state.otherDepartments.map((department,index) => ( <option key={index} value={department._id}> {department.name} </option> ))} </select> </div> </div> <div className="form-group row"> <label className="col-sm-2 col-form-label">Assign To</label> <div className="col-sm-10"> <select defaultValue={'DEFAULT'} className="custom-select mb-3" onChange={(e) => { const { state: currentState } = this currentState.assignedToUser = e.target.value this.setState(currentState) }} required > <option value="DEFAULT" disabled >Select Users</option> {this.state.departmentUsers.map(user => ( <option value={user._id}> {user.email} </option> ))} </select> </div> </div> <div className="form-group row"> <label className="col-sm-2 col-form-label">Message</label> <div className="col-sm-10"> <textarea className="form-control" id="exampleFormControlTextarea1" rows="3" onChange={(e) => { const { state: currentState } = this currentState.message = e.target.value this.setState(currentState) }}></textarea> </div> </div> <br /> <button className="btn btn-info w-35" style={{ marginLeft: 100, marginRight: 90 }} onClick={this.handleSendRequestClick}> Send Request </button> </form> </div> </div> </div> </div> </div> </div> </div> ); } } export default FormView;<file_sep>/src/components/FormCard.js import React from 'react' function FormCard(props) { return ( <div> <br /> <div className="container"> <div className="card"> <div className="card-body"> <div>{props.createdBy ? <b>Created By : {props.createdBy}</b> : ''}</div> <div>{props.assignedTo ? <b>Assigned To : {props.assignedTo} </b> : ''}</div> <b>Message</b>: {props.message} {props.displayFlag ? <span style={{ float: "right" }}> <i className="fa fa-check" style={{ color: "#79d70f", fontSize: "20px" }} onClick={() => { props.handleUpdateRequest(props.id, "Approved") }} > </i>&nbsp;&nbsp; <i className="fa fa-times" style={{ color: "red", fontSize: "20px" }} aria-hidden="true" onClick={() => { props.handleUpdateRequest(props.id, "Rejected") }} ></i></span> : "" } <span style={{ float: "right" }}>{props.status ? props.status === 'Approved' ? <span style={{ color: "#79d70f", fontSize: "20px" }}><b>Approved</b></span> : props.status == 'Rejected' ? <span style={{ color: "red", fontSize: "20px" }}><b>Rejected</b></span> : props.status == 'Pending' ? <span style={{ color: "yellow", fontSize: "20px" }}><b>Pending</b></span> : '' : ''}</span> </div> </div> </div> </div> ) } export default FormCard;<file_sep>/src/views/FormPendingView.js import React, { Component } from 'react'; import NavBar from '../components/NavBar'; import FormCard from '../components/FormCard' import callAPI from '../lib/axios' import { confirmAlert } from "react-custom-confirm-alert"; import "react-custom-confirm-alert/src/react-confirm-alert.css"; import Alert from '../components/Alert' class FormPendingView extends Component { constructor(props) { super(props); this.state = { MyPendingRequestFlag: true, MyPendingRequests: [], overallPendingRequests: [], isConfirmationModalOpen: false, alertFlag: '', alertMessage: '', showAlertFlag: false } } componentDidMount() { this.getFormRequests() } handleRequest = async () => { if (this.state.MyPendingRequestFlag) { this.getFormRequests() } else { this.getOverallPendingForms() } } handleModalOpen = () => { this.setState({ isConfirmationModalOpen: true }) } handleModalClose = () => { this.setState({ isConfirmationModalOpen: true }) } getOverallPendingForms = async () => { const forms = await callAPI('get', `/form/overallForms/${localStorage.getItem('id')}/Pending`) const { state: currentState } = this currentState.MyPendingRequests = forms.data.message this.setState(currentState) this._renderFormCards() } getFormRequests = async () => { const forms = await callAPI('get', `/form/${localStorage.getItem('id')}/Pending`) const { state: currentState } = this currentState.MyPendingRequests = forms.data.message this.setState(currentState) this._renderFormCards() } handleUpdateRequest = async (formId, status) => { console.log(formId) confirmAlert({ title: <h4>Confirm to {status === 'Approved' ? 'Approve' : 'Reject'}</h4>, message: "Are you sure to do this.", buttons: [ { label: "Yes", onClick: () => { try { callAPI('put', '/form', { data: { formId, status, } }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: true }) this.setState({ alertMessage: 'Status Updated!' }) window.location.reload(); } catch (error) { this.setState({ alertMessage: 'An error occured!Try Again!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } }, { label: "No", onClick: () => { } } ] }); } _renderFormCards = () => { if (this.state.MyPendingRequests.length > 0) { return ( <div> {this.state.MyPendingRequestFlag ? <h3 style={{ marginLeft: "80px" }}>My Pending Requests</h3> : <h3 style={{ marginLeft: "80px" }}>Overall Pending Requests</h3>} {this.state.MyPendingRequests.map((form, index) => ( <div key={index}> <FormCard message={form.message} displayFlag={this.state.MyPendingRequestFlag ? true : false} createdBy={this.state.MyPendingRequestFlag? form.user.email : false} assignedTo={this.state.MyPendingRequestFlag? false : form.user.email} id={form._id} handleUpdateRequest={this.handleUpdateRequest} /> </div> ))} </div> ) } else { return ( <div className="text-center"> <h3 className="text-danger"> <i className="fa fa-exclamation-circle mr-4" /> No Pending Requests </h3> </div> ) } } render() { return ( <div> <NavBar /> {this.state.showAlertFlag ? <Alert flag={this.state.alertFlag} message={this.state.alertMessage} /> : ''} <br /> <div style={{ float: "right",marginRight:"210px" }}> <label className="switch"> <input type="checkbox" onChange={(e) => { this.setState({MyPendingRequestFlag:!this.state.MyPendingRequestFlag}) this.handleRequest() }} /> <span className="slider round"></span> </label> </div> <div> {this._renderFormCards()} </div> </div> ); } } export default FormPendingView;<file_sep>/src/views/FormRequestedView.js import React, { Component } from 'react'; import NavBar from '../components/NavBar'; import callAPI from '../lib/axios' import FormCard from '../components/FormCard' class FormRequestedView extends Component { constructor(props) { super(props); this.state = { overallRejectedRequests: [] } } componentDidMount() { this.getOverallRejectedForms() } getOverallRejectedForms = async () => { const forms = await callAPI('get', `/form/requested/${localStorage.getItem('id')}`) const { state: currentState } = this currentState.overallRejectedRequests = forms.data.message this.setState(currentState) this._renderFormCards() } _renderFormCards = () => { if (this.state.overallRejectedRequests.length > 0) { return ( <div> <br /> <h3 style={{ marginLeft: "80px" }}>Requested Forms</h3> {this.state.overallRejectedRequests.map((form, index) => ( <div key={index}> <FormCard status={form.status} message={form.message} assignedTo={form.user.email} /> </div> ))} </div> ) } else { return ( <div className="text-center"> <br /> <h3 className="text-danger"> <i className="fa fa-exclamation-circle mr-4" /> No Forms Has Been Requested! </h3> </div> ) } } render() { return ( <div> <NavBar /> {this._renderFormCards()} </div> ); } } export default FormRequestedView; <file_sep>/src/views/RegisterView.js import React, { Component } from 'react' import { Link } from 'react-router-dom' import callAPI from '../lib/axios' import logger from '../lib/logger' import Alert from '../components/Alert' export default class RegisterView extends Component { constructor(props) { super(props) this.state = { email: '', password: '', department: '', departments: [], alertFlag: '', message: '', showAlertFlag: false } } componentDidMount() { this.getAllDepartments() } getAllDepartments = async () => { const departments = await callAPI('get', '/department') const { state: currentState } = this currentState.departments = departments.data.message this.setState(currentState) } handleRegisterClick = async () => { const { email, password, department } = this.state if (email === '' && password === '') { alert('Cannot proceed without username and/or password') } else { try { await callAPI('post', '/user', { data: { email, password, departmentId: department } }) this.setState({ alertFlag: true }) this.setState({ showAlertFlag: true }) this.setState({ message: 'Registration Successful!'}) } catch (error) { logger.error(error) this.setState({ message: 'Registration Failed!' }) this.setState({ showAlertFlag: true }) this.setState({ alertFlag: false }) } } } render() { return ( <div> <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4"></h1> <p className="lead" align="center"><h3>A One Step Solution to Invite Users via Form Request!</h3></p> </div> </div> {this.state.showAlertFlag ? <Alert flag={this.state.alertFlag} message={this.state.message} /> : ''} <div style={{ display: "flex", justifyContent: "center" }}> <div className="card"> <div className="card-body"> <div className="pt-5 login-bg text-white h-100"> <div className="text-center"> <h3>Register Here..!</h3> <div style={{ fontSize: 20 }} className="mt-5"> <div style={{ marginLeft: 100, marginRight: 100 }}> <input className="form-control text-center placeholder-colored" placeholder="<EMAIL>" onChange={(e) => { const { state: currentState } = this currentState.email = e.target.value this.setState(currentState) }}></input> </div> <div className="mt-3" style={{ marginLeft: 100, marginRight: 100 }}> <input type="<PASSWORD>" className="form-control text-center placeholder-colored" placeholder="<PASSWORD>" onChange={(e) => { const { state: currentState } = this currentState.password = e.target.value this.setState(currentState) }}></input> </div> <div class="dropright mt-3 w-70" style={{ marginLeft: 100, marginRight: 100 }}> <select class="custom-select mb-3" onChange={(e) => { const { state: currentState } = this currentState.department = e.target.value this.setState(currentState) }}> <option selected disabled >Department</option> {this.state.departments.map(department => ( <option value={department._id}> {department.name} </option> ))} </select> </div> <div className="mt-3 rounded" style={{ marginLeft: 100, marginRight: 100 }}> <button className="btn btn-info w-35" onClick={this.handleRegisterClick}> Sign Up </button><br /> <Link to="/login" className="link"> Already Registered?Click Here to Login.! </Link> </div> </div> </div> </div> </div> </div> </div> </div> ) } }<file_sep>/src/views/RootView.js import React, { Component } from 'react'; import { Route } from 'react-router-dom' import FormView from './FormView' import FormPendingView from './FormPendingView' import FormApprovedView from './FormApprovedView' import FormRejectedView from './FormRejectedView' import FormRequestedView from './FormRequestedView' import LoginView from './LoginView' import RegisterView from './RegisterView' class RootView extends Component { render() { return ( <div className="wrapper"> <Route path="/login" exact component={LoginView}></Route> <Route path="/register" exact component={RegisterView}></Route> <Route path="/pending" exact component={FormPendingView}></Route> <Route path="/approved" exact component={FormApprovedView}></Route> <Route path="/rejected" exact component={FormRejectedView}></Route> <Route path="/requested" exact component={FormRequestedView}></Route> <Route path="/" exact component={FormView}></Route> </div> ) } } export default RootView;
70a3130c32f068e4484a83a6bb75f856b8cc1e11
[ "JavaScript" ]
7
JavaScript
sonasuresh/switchon-Frontend
2e78642d36714cb3c0d6f61f2df7e3879ce65d7b
a5e36770b89bc3c049d34d3bb77837e776c9e039
refs/heads/master
<file_sep># Node.js Users Admin & Test App Sample This application demonstrates a simple, reusable Node.js web application based on the Express framework. ## Run the app locally 1. [Install Node.js][] 1. Provide a local [MongoDB][] instance without authentication (or else change internal configuration as needed) 1. `cd` into this project's root directory 1. Run `npm install` to install the app's dependencies 1. Run `npm start` to start the app 1. Access the running app (if no configuration is provided) in a browser at <http://localhost:9443> [Install Node.js]: https://nodejs.org/en/download/ [MongoDB]: https://www.mongodb.com <file_sep>const mongoose = require('mongoose'); const Ingredient = require('../models/ingredient'); const { WellKnownJsonRes, JsonResWriter } = require('../../../../api/middleware/json-response-util'); const { BasicRead } = require('../../../../api/middleware/crud'); // cRud exports.read_all = (req, res, next) => { BasicRead.all(req, res, next, Ingredient); }; // cRud/autocompleteOnTitle exports.autocomplete = (req, res, next) => { BasicRead.autocomplete(req, res, next, Ingredient, 'title', req._q.filterAcSimple, req._q.filter, req._q.projection); }; <file_sep>const mongoose = require('mongoose'); const komandaDBConn = require('../middleware/mongoose') const priceSchema = require('../../../../api/lib/models/price'); const dishSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, title: { type: String, required: true }, description: { type: String, required: true }, price: { type: priceSchema, required: true }, category: { type: String, required: true, match: /[a-z][a-z0-9-]*/ }, ingredients: [mongoose.Schema.Types.ObjectId] }); module.exports = komandaDBConn.model('Dish', dishSchema); <file_sep>const { FilterHelper } = require('../lib/tp/mongodb'); const { JsonObjectHelper } = require('../lib/util/json-util'); const { WellKnownJsonRes, JsonResWriter } = require('../middleware/json-response-util'); // others/flat_json exports.flat_json = (req, res, next) => { WellKnownJsonRes._genericDebug(res, 200, JsonObjectHelper.buildFlattenJson(req.body)); }; exports.encode_json = (req, res, next) => { WellKnownJsonRes.okSingle(res, { binaryData: JsonObjectHelper.encode(req.body) }); }; exports.decode_json = (req, res, next) => { WellKnownJsonRes.okSingle(res, JsonObjectHelper.decode(req.body.binaryData)); }; <file_sep>const express = require('express'); const router = express.Router(); const DishCtrl = require('../controllers/dish'); const checkAuth = require('../../../../api/middleware/check-auth'); const queryParser = require('../../../../api/middleware/parse-query'); router.get('/', checkAuth, queryParser, DishCtrl.read_all); router.get('/autocomplete', checkAuth, queryParser, DishCtrl.autocomplete); module.exports = router; <file_sep>'use strict'; const { FilterHelper } = require('../lib/tp/mongodb'); const { JsonObjectHelper } = require('../lib/util/json-util'); const { WellKnownJsonRes } = require('../middleware/json-response-util'); class BasicRead { // cRud static all(req, res, next, model, filter = {}, skip = 0, limit = 0, projection = {}, sort = {}) { model .find(filter) .skip(skip) .limit(limit) .sort(sort) .select(projection) .exec() .then((readResult) => { if (readResult) { if (limit > 0 && readResult.length == limit) { // when limit is specified, total items count can differ from size of result // in these cases a count query is necessary to get the correct value model .count(filter) .exec() .then((countResult) => { WellKnownJsonRes.okMulti(res, countResult, readResult, skip, limit); }) .catch((countError) => { WellKnownJsonRes.errorDebug(res, countError); }); // exit because response has been fulfilled at this stage return; } WellKnownJsonRes.okMulti(res, readResult.length, readResult, skip, limit); } else { WellKnownJsonRes.notFound(res); } }) .catch((readError) => { WellKnownJsonRes.errorDebug(res, readError); }); } // cRud/autocomplete static autocomplete( req, res, next, model, textFieldName, textSearch, filter = {}, projection = {}, maxResult = 10 ) { if (textSearch === undefined) { WellKnownJsonRes.okMulti(res); return; } Object.assign(filter, FilterHelper.buildAutocompleteFilter(textFieldName, textSearch)); model .find(filter) .limit(maxResult) .select(projection) .exec() .then((readResult) => { if (readResult) { WellKnownJsonRes.okMulti(res, readResult.length, readResult, 0, maxResult); } else { WellKnownJsonRes.okMulti(res); } }) .catch((readError) => { WellKnownJsonRes.errorDebug(res, readError); }); } // cRud/byId static byId(req, res, next, model, id) { model .findById(id) .exec() .then((readResult) => { if (readResult) { WellKnownJsonRes.okSingle(res, readResult); } else { WellKnownJsonRes.notFound(res); } }) .catch((readError) => { WellKnownJsonRes.errorDebug(res, readError); }); } // cRud/count static count(filter = {}) { model .count(filter) .exec() .then((countResult) => { WellKnownJsonRes.count(res, countResult); }) .catch((countError) => { WellKnownJsonRes.errorDebug(res, countError); }); } } class BasicWrite { // Crud static create(req, res, next, model) { model .save() .then((createResult) => { AccountDetailCtrl.init_by_account(res, createResult._id, createResult); }) .catch((createError) => { WellKnownJsonRes.errorDebug(res, createError); }); } // crUd/byId static updateById(req, res, next, model, id) { const updateFilter = { _id: id }; const updateStatement = { $set: JsonObjectHelper.buildFlattenJson(req.body) }; model .updateOne(updateFilter, updateStatement) .exec() .then((updateResult) => { WellKnownJsonRes.okSingle(res, updateFilter, 200, updateResult); }) .catch((updateError) => { WellKnownJsonRes.errorDebug(res, updateError); }); } // cruD/byId static deleteById(req, res, next, model, id) { model .deleteOne({ _id: id }) .exec() .then((deleteResult) => { WellKnownJsonRes._genericDebug(res, 200, deleteResult); }) .catch((deleteError) => { WellKnownJsonRes.errorDebug(res, deleteError); }); } } module.exports = { BasicRead, BasicWrite }; <file_sep>/*eslint-env node*/ // This application uses express as its web server // for more info, see: http://expressjs.com const express = require('express'); // cfenv provides access to your Cloud Foundry environment // for more info, see: https://www.npmjs.com/package/cfenv // var cfenv = require('cfenv'); // follows above replacement to run outside Cloud Foundry environment (I) require('dotenv').config(); // create a new express server const app = express(); // // CUSTOM PART - begin // const bodyParser = require('body-parser'); app.use( bodyParser.urlencoded({ extended: false }) ); app.use(bodyParser.json()); const mongoose = require('mongoose'); mongoose .connect('mongodb://127.0.0.1:27017/sample-nodejs-app?authSource=admin', { dbName: 'sample-nodejs-app', useNewUrlParser: true, useCreateIndex: true, family: 6 }) .then( () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ const db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', () => { console.log('MongoDB connection is up'); }); }, (err) => { /** handle initial connection error */ console.error.bind(console, 'MongoDB startup connection error:'); } ); // // basic & unsecure CORS handling // FIXME app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, Origin, X-Requested-With'); if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE'); return res.status(200).json({}); } next(); }); // // Response Headers handling app.disable('x-powered-by'); // here there are rest services routes // - basics const accountRoutes = require('./api/routes/account'); app.use('/accounts', accountRoutes); // - admin const accountDetailRoutes = require('./api/routes/accountDetail'); app.use('/account', accountDetailRoutes); // - utils const utilRoutes = require('./api/routes/util'); app.use('/util', utilRoutes); // - app: komanda const komandaDishRoutes = require('./app/komanda/api/routes/dish'); app.use('/komanda/public/menu', komandaDishRoutes); const komandaIngredientRoutes = require('./app/komanda/api/routes/ingredient'); app.use('/komanda/public/ingredients', komandaIngredientRoutes); // // CUSTOM PART I - end // // serve the files out of ./public as our main files app.use(express.static(__dirname + '/public')); // // CUSTOM PART II - begin // app.use((req, res, next) => { const error = new Error('Not Found'); error.status = 404; next(error); }); app.use((error, req, res, next) => { res.status(error.status || 500); res.json({ status: error.status, message: error.message }); }); // // CUSTOM PART II - end // // get the app environment from Cloud Foundry // const appEnv = cfenv.getAppEnv(); // const srvPort = appEnv.port; // const srvUrl = appEnv.url; // follows above replacement to run outside Cloud Foundry environment (I) const srvPort = process.env.srvPort || 9443; const srvUrl = process.env.srvUrl || 'localhost'; // start server on the specified port and binding host app.listen(srvPort, '0.0.0.0', function() { // print a message when the server starts listening console.log(`server starting on ${srvUrl}`); }); <file_sep>const mongoose = require('mongoose'); const Dish = require('../models/dish'); const { FilterHelper } = require('../../../../api/lib/tp/mongodb'); const { WellKnownJsonRes, JsonResWriter } = require('../../../../api/middleware/json-response-util'); // cRud exports.read_all = (req, res, next) => { Dish.aggregate([{ $match: req._q.filter }, { $lookup: { from: "ingredients", localField: "ingredients", foreignField: "_id", as: "ingredients" } }]).exec() .then(readResult => { if (readResult) { WellKnownJsonRes.okMulti(res, readResult.length, readResult); } else { WellKnownJsonRes.notFound(res); } }) .catch(readError => { WellKnownJsonRes.errorDebug(res, readError); }); }; // cRud/autocompleteOnTitle exports.autocomplete = (req, res, next) => { if (req._q.filterAcSimple === undefined) { WellKnownJsonRes.okMulti(res); return; } const filter = FilterHelper .buildAutocompleteFilter( 'title', req._q.filterAcSimple, req._q.filter, req._q.projection); const limit = 10; Dish.aggregate([{ $match: filter }, { $lookup: { from: "ingredients", localField: "ingredients", foreignField: "_id", as: "ingredients" } }, { $limit: limit }]).exec() .then(readResult => { if (readResult) { WellKnownJsonRes.okMulti(res, readResult.length, readResult, 0, limit); } else { WellKnownJsonRes.notFound(res); } }) .catch(readError => { WellKnownJsonRes.errorDebug(res, readError); }); }; <file_sep>const mongoose = require('mongoose'); const komandaDBConn = require('../middleware/mongoose') const triStateBoolType = require('../../../../api/lib/models/types/triStateBool'); const ingredientSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, title: { type: String, required: true }, description: { type: String, required: true }, allergyFriendly: { type: String, enum: triStateBoolType.values._all, default: triStateBoolType.values.undefined }, veganFriendly: { type: String, enum: triStateBoolType.values._all, default: triStateBoolType.values.undefined }, vegetarianFriendly: { type: String, enum: triStateBoolType.values._all, default: triStateBoolType.values.undefined } }); module.exports = komandaDBConn.model('Ingredient', ingredientSchema); <file_sep>"use strict"; class WellKnownJsonRes { static _genericDebug(res, status, debugJson = undefined) { new JsonResWriter(status) ._debug(debugJson) .applyTo(res); } static conflict(res, debugJson = undefined) { WellKnownJsonRes._genericDebug(res, 409, debugJson); } static count(res, total = 0) { new JsonResWriter(200) ._total(total) .applyTo(res); } static created(res, debugJson = undefined) { WellKnownJsonRes._genericDebug(res, 201, debugJson); } static error(res, status = 500, messages = undefined, debugJson = undefined) { // res.status(<status>).json({ // status: <status>, // messages: <messages> // _debug: <debugJson> // }); new JsonResWriter(status) ._messages(messages) ._debug(debugJson) .applyTo(res); } static errorDebug(res, debugJson = undefined) { // res.status(500).json({ // status: 500, // _debug: <debugJson> // }); WellKnownJsonRes._genericDebug(res, 500, debugJson); } static okSingle(res, jsonItem, status = 200, debugJson = undefined, messages = undefined) { // res.status(<status>).json({ // status: <status>, // total: 1, // skip: 0, // limit: 0, // set: [ jsonItem ] // }); new JsonResWriter(status) ._total(1) ._skip(0) ._limit(0) ._addToResultSet(jsonItem) ._debug(debugJson) ._messages(messages) .applyTo(res); } static okMulti(res, total = 0, jsonItems = [], skip = 0, limit = 0, status = 200) { // res.status(<status>).json({ // status: <status>, // total: <total>, // skip: <skip>, // limit: <limit>, // set: <jsonItems> // }); new JsonResWriter(status) ._total(total) ._skip(skip) ._limit(limit) ._resultSet(jsonItems) .applyTo(res); } static notFound(res, skip = 0, limit = 0) { // res.status(404).json({ // status: 404, // total: 0, // skip: <skip>, // limit: <limit>, // set: [] // }); new JsonResWriter(404) ._total(0) ._skip(skip) ._limit(limit) .applyTo(res); } static unauthorized(res, messages = ['Unauthorized'], debugJson = undefined) { // return res.status(401).json({ // status: 401, // messages: <messages>, // _debug: <debug> // }); WellKnownJsonRes.error(res, 401, messages, debugJson); } } class JsonResWriter { constructor(status) { this.status = status; } _status(status) { this.status = status; return this; } _total(total) { this.total = total; return this; } _skip(skip) { this.skip = skip; return this; } _limit(limit) { this.limit = limit; return this; } _resultSet(set) { this.set = set return this; } _addToResultSet(item) { if (this.set === undefined) { this.set = []; } if (item !== undefined) { this.set.push(item); } return this; } _messages(messages) { this.messages = messages; return this; } _addMessage(message) { if (this.messages === undefined) { this.messages = []; } this.messages.push(message); return this; } _debug(_debug) { this._debug = _debug; return this; } _addToDebug(key, value) { if (this._debug === undefined) { this._debug = {}; } this._debug[key] = value; return this; } _add(key, value) { return this._addAll({ [key]: value }); } _addAll(jsonPartial) { if (this.customFields === undefined) { this.customFields = {}; } Object.assign(this.customFields, jsonPartial); return this; } applyTo(res) { if (!res) { return; } const jsonBody = {}; if (this.status == 204) { res.status(this.status).json(); return; } jsonBody.status = this.status; if (this.messages !== undefined) { jsonBody.messages = this.messages; } if (this.total !== undefined) { jsonBody.total = this.total; } if (this.skip !== undefined) { jsonBody.skip = this.skip; } if (this.limit !== undefined) { jsonBody.limit = this.limit; } if (this.set !== undefined) { jsonBody.set = this.set; } if (this.customFields !== undefined) { Object.assign(jsonBody, this.customFields); } if (this._debug !== undefined) { jsonBody._debug = this._debug; } res.status(this.status).json(jsonBody); } } module.exports = { WellKnownJsonRes, JsonResWriter };
15a07611aaca6371d7751971b27ad2a8c09840e7
[ "Markdown", "JavaScript" ]
10
Markdown
fvalenti-hr/node-auth-sample
2952a7188399d48fbad8a0251a5a01ed9b85f88a
285734a44d428a3754b9d3d799898c7474aff82c
refs/heads/master
<repo_name>truopensource/hello-hactoberfest2019<file_sep>/languages/python.py import time def printOut(m): l = list(m) for i in range(0, len(l)): print(l[i], end='', flush=True) time.sleep(0.01) print() printOut("Hello World!") input() <file_sep>/CONTRIBUTING.md Contributing ============ * Your program should print "**Hi!**" or "**Hello**" * Create a file in `languages` with the language name as the file name (followed by the language file extension) * Only one file per one langauge will be accepted, if you to want make any change to file please submit a PR with changes and description. * Note: If it's spoken language use the last two or three charcters of language code. For short codes: <a href = "https://www.science.co.il/language/Codes.php"> language code link </a> * **EXAMPLE**: `java.java` * If your language has special characters (C++ for example), replace with however the language traditionally expresses the language (cpp) * Lowercase language names are preferred (`Java.java` should be `java.java`) * If you find a problem with any of the files, open a PR to change it!
ed1529d11c61a18198b385b33ceff6ee4a6edc12
[ "Markdown", "Python" ]
2
Python
truopensource/hello-hactoberfest2019
701f86ec68049e0ed1c739497143268d135d0009
dc0537c14f41c1e88c884c769cab5d41f4092947
refs/heads/master
<file_sep>To contribute to this repository, edit the file you want to make changes to. Then at the bottom of the page press propose changes. Next click create pull request and I will review it and merge it or ask you to change some things and then merge it. <file_sep># Changelog: ### v2.1.0 Added scrollbar to output Combined input to single window Changed output to pop up dialog box Added custom encryption keys ### v2.0.0 Enhanced encryption Added documentaion Added support for special characters Added support for capital letter Changed prompts ### v1.2.1 Fixed decryption button bug ### v1.2.0 Loops back to welcome screen ### v1.1.1 Enlarged output text boxes ### v1.1.0 Added copy-paste functionality ### v1.0.1 Test version Fixed termination bug ### v1.0.0 First test version <file_sep># import all reqired libraries from tkinter import * from tkinter import simpledialog, messagebox from tkinter import ttk import mpmath as mp from mpmath import * import math mp.dps = 10000 # set a heigher precision float def encrypt(message): # encrypt function enmessage = [] emessage = [] # define lists encrypted = [] for counter in range(0, len(message)): # loop through all element in message enmessage.append(message[counter]) for cc in enmessage: # replace all characters with corosponding numbers if cc == 'a': emessage.append(13) elif cc == 'b': emessage.append(14) elif cc == 'c': emessage.append(15) elif cc == 'd': emessage.append(16) elif cc == 'e': emessage.append(17) elif cc == 'f': emessage.append(18) elif cc == 'g': emessage.append(19) elif cc == 'h': emessage.append(20) elif cc == 'i': emessage.append(21) elif cc == 'j': emessage.append(22) elif cc == 'k': emessage.append(23) elif cc == 'l': emessage.append(24) elif cc == 'm': emessage.append(25) elif cc == 'n': emessage.append(26) elif cc == 'o': emessage.append(27) elif cc == 'p': emessage.append(28) elif cc == 'q': emessage.append(29) elif cc == 'r': emessage.append(30) elif cc == 's': emessage.append(31) elif cc == 't': emessage.append(32) elif cc == 'u': emessage.append(33) elif cc == 'v': emessage.append(34) elif cc == 'w': emessage.append(35) elif cc == 'x': emessage.append(36) elif cc == 'y': emessage.append(37) elif cc == 'z': emessage.append(38) elif cc == '1': emessage.append(3) elif cc == '2': emessage.append(4) elif cc == '3': emessage.append(5) elif cc == '4': emessage.append(6) elif cc == '5': emessage.append(7) elif cc == '6': emessage.append(8) elif cc == '7': emessage.append(9) elif cc == '8': emessage.append(10) elif cc == '9': emessage.append(11) elif cc == '0': emessage.append(12) elif cc == ' ': emessage.append(39) elif cc == '.': emessage.append(40) elif cc == ',': emessage.append(41) elif cc == ':': emessage.append(42) elif cc == '!': emessage.append(43) elif cc == '?': emessage.append(44) elif cc == 'A': emessage.append(45) elif cc == 'B': emessage.append(46) elif cc == 'C': emessage.append(47) elif cc == 'D': emessage.append(48) elif cc == 'E': emessage.append(49) elif cc == 'F': emessage.append(50) elif cc == 'G': emessage.append(51) elif cc == 'H': emessage.append(52) elif cc == 'I': emessage.append(53) elif cc == 'J': emessage.append(54) elif cc == 'K': emessage.append(55) elif cc == 'L': emessage.append(56) elif cc == 'M': emessage.append(57) elif cc == 'N': emessage.append(58) elif cc == 'O': emessage.append(59) elif cc == 'P': emessage.append(60) elif cc == 'Q': emessage.append(61) elif cc == 'R': emessage.append(62) elif cc == 'S': emessage.append(63) elif cc == 'T': emessage.append(64) elif cc == 'U': emessage.append(65) elif cc == 'V': emessage.append(66) elif cc == 'W': emessage.append(67) elif cc == 'X': emessage.append(68) elif cc == 'Y': emessage.append(69) elif cc == 'Z': emessage.append(70) elif cc == '@': emessage.append(71) elif cc == '#': emessage.append(72) elif cc == '$': emessage.append(73) elif cc == '%': emessage.append(74) elif cc == '^': emessage.append(75) elif cc == '&': emessage.append(76) elif cc == '*': emessage.append(77) elif cc == '(': emessage.append(78) elif cc == ')': emessage.append(79) elif cc == '-': emessage.append(80) elif cc == '_': emessage.append(81) elif cc == '=': emessage.append(82) elif cc == '+': emessage.append(83) elif cc == '{': emessage.append(84) elif cc == '}': emessage.append(85) elif cc == '|': emessage.append(87) elif cc == ';': emessage.append(88) elif cc == '"': emessage.append(89) elif cc == '\'': emessage.append(90) elif cc == '>': emessage.append(91) elif cc == '<': emessage.append(92) elif cc == '/': emessage.append(93) for thing in emessage: if e_key_input.get() != '' and pq_key_input.get != '': encyption_key = int(e_key_input.get()) main_key = int(pq_key_input.get()) else: encyption_key = e main_key = p*q sep = '.' quotent = (thing**encyption_key)/(main_key) # compute quotent rquotent = str(quotent) r = rquotent.split(sep, 1)[1] #[ r = ("0." + r) r = mpf(r) t = float(r)*(main_key) t = t*100000 t = str(t) t = t.split(sep, 1)[0] t = float(t) t = t/100000 encrypted_char = round(t) #] compute remainder encrypted.append(encrypted_char) # combine to new list return encrypted # returns encrypted list def decrypt(message): # decrypt function message = str(message) demessage = [] dmessage = [] decrypted = [] data = message.split() for temp in data: temp = int(temp) # splits message into list demessage.append(temp) for thing in demessage: sep = '.' quotent = (thing**d)/(p*q) #[ rquotent = str(quotent) r = rquotent.split(sep, 1)[1] r = ("0." + r) r = mpf(r) t = float(r)*(p*q) t = t*100000 t = str(t) t = t.split(sep, 1)[0] t = float(t) t = t/100000 decrypted_char = round(t) #] computes remaider dmessage.append(decrypted_char) # puts in list # replaces number with corosponding character for cc in dmessage: if cc == 3: decrypted.append('1') if cc == 4: decrypted.append('2') if cc == 5: decrypted.append('3') if cc == 6: decrypted.append('4') if cc == 7: decrypted.append('5') if cc == 8: decrypted.append('6') if cc == 9: decrypted.append('7') if cc == 10: decrypted.append('8') if cc == 11: decrypted.append('9') if cc == 12: decrypted.append('0') if cc == 13: decrypted.append('a') if cc == 14: decrypted.append('b') if cc == 15: decrypted.append('c') if cc == 16: decrypted.append('d') if cc == 17: decrypted.append('e') if cc == 18: decrypted.append('f') if cc == 19: decrypted.append('g') if cc == 20: decrypted.append('h') if cc == 21: decrypted.append('i') if cc == 22: decrypted.append('j') if cc == 23: decrypted.append('k') if cc == 24: decrypted.append('l') if cc == 25: decrypted.append('m') if cc == 26: decrypted.append('n') if cc == 27: decrypted.append('o') if cc == 28: decrypted.append('p') if cc == 29: decrypted.append('q') if cc == 30: decrypted.append('r') if cc == 31: decrypted.append('s') if cc == 32: decrypted.append('t') if cc == 33: decrypted.append('u') if cc == 34: decrypted.append('v') if cc == 35: decrypted.append('w') if cc == 36: decrypted.append('x') if cc == 37: decrypted.append('y') if cc == 38: decrypted.append('z') if cc == 39: decrypted.append(' ') if cc == 40: decrypted.append('.') if cc == 41: decrypted.append('~') if cc == 42: decrypted.append(':') if cc == 43: decrypted.append('!') if cc == 44: decrypted.append('?') if cc == 45: decrypted.append('A') if cc == 46: decrypted.append('B') if cc == 47: decrypted.append('C') if cc == 48: decrypted.append('D') if cc == 49: decrypted.append('E') if cc == 50: decrypted.append('F') if cc == 51: decrypted.append('G') if cc == 52: decrypted.append('H') if cc == 53: decrypted.append('I') if cc == 54: decrypted.append('J') if cc == 55: decrypted.append('K') if cc == 56: decrypted.append('L') if cc == 57: decrypted.append('M') if cc == 58: decrypted.append('N') if cc == 59: decrypted.append('O') if cc == 60: decrypted.append('P') if cc == 61: decrypted.append('Q') if cc == 62: decrypted.append('R') if cc == 63: decrypted.append('S') if cc == 64: decrypted.append('T') if cc == 65: decrypted.append('U') if cc == 66: decrypted.append('V') if cc == 67: decrypted.append('W') if cc == 68: decrypted.append('X') if cc == 69: decrypted.append('Y') if cc == 70: decrypted.append('Z') if cc == 71: decrypted.append('@') if cc == 72: decrypted.append('#') if cc == 73: decrypted.append('$') if cc == 74: decrypted.append('%') if cc == 75: decrypted.append('^') if cc == 76: decrypted.append('&') if cc == 77: decrypted.append('*') if cc == 78: decrypted.append('(') if cc == 79: decrypted.append(')') if cc == 80: decrypted.append('-') if cc == 81: decrypted.append('_') if cc == 82: decrypted.append('=') if cc == 83: decrypted.append('+') if cc == 84: decrypted.append('{') if cc == 85: decrypted.append('}') if cc == 87: decrypted.append('|') if cc == 88: decrypted.append(';') if cc == 89: decrypted.append('"') if cc == 90: decrypted.append('\'') if cc == 91: decrypted.append('>') if cc == 92: decrypted.append('<') if cc == 93: decrypted.append('/') plaintext = ''.join(decrypted) # returns decrypted message as string return plaintext def output_encrypted(encrypted): global encrypted_output_window encrypted_output_window = Toplevel(root) # create window encrypted_output_window.title('Encrypted') encrypted_output_window.geometry('-520+120') encrypted_text = StringVar() encrypted_output = Text(encrypted_output_window, width=20, height=8) encrypted_output.grid(column=0, row=0, sticky=(W, E), padx=10, pady=10, columnspan=2) # create lable encrypted = str(encrypted) encrypted = encrypted.replace(',', '') encrypted = encrypted.replace(']', '') # make readable encrypted = encrypted.replace('[', '') encrypted_output.insert(END, '%s' % encrypted) encrypted_output.configure(state="disabled") encrypted_output.configure(wrap="word") encrypted_scrollbar = ttk.Scrollbar(encrypted_output_window, orient=VERTICAL, command=encrypted_output.yview) encrypted_scrollbar.grid(column=2, row=0, sticky=(N, S, W)) # create scrollbar encrypted_output.configure(yscrollcommand=encrypted_scrollbar.set) ok = ttk.Button(encrypted_output_window, text='Ok', command=encrypted_output_window.destroy) ok.grid(column=1, row=2, sticky=(E), columnspan=2) ok.focus() ok.bind('<Return>', kill_encrypting) def output_decrypted(decrypted): global decrypted_output_window decrypted_output_window = Toplevel(root) # create window decrypted_output_window.title('Decrypted') decrypted_output_window.geometry('-520+120') decrypted_text = StringVar() decrypted_output = Text(decrypted_output_window, width=20, height=8) decrypted_output.grid(column=0, row=0, sticky=(W, E), padx=10, pady=10, columnspan=2) # create text box decrypted = str(decrypted) decrypted = decrypted.replace(',', '') decrypted = decrypted.replace('~', ',') decrypted = decrypted.replace(']', '') # remove list characters decrypted = decrypted.replace('[', '') decrypted_output.insert(END, '%s' % decrypted) decrypted_output.configure(state="disabled") # display ouptut decrypted_output.configure(wrap="word") decrypted_scrollbar = ttk.Scrollbar(decrypted_output_window, orient=VERTICAL, command=decrypted_output.yview) decrypted_scrollbar.grid(column=2, row=0, sticky=(N, S, W)) # create scrollbar decrypted_output.configure(yscrollcommand=decrypted_scrollbar.set) ok = ttk.Button(decrypted_output_window, text='Ok', command=decrypted_output_window.destroy) ok.grid(column=1, row=2, sticky=(E), columnspan=2) ok.focus() ok.bind('<Return>', kill_decrypting) def kill_encrypting(event): encrypted_output_window.destroy() def kill_decrypting(event): decrypted_output_window.destroy() def run(): error_message.set('') if "~" in message_input.get('1.0', 'end') or "[" in message_input.get('1.0', 'end') or "]" in message_input.get('1.0', 'end'): error_message.set('Can\'t encrypt ~ [ or ]') return if en_or_de.get() == 'encrypt': encrypted = encrypt(message_input.get('1.0', 'end')) output_encrypted(encrypted) elif en_or_de.get() == 'decrypt': message = message_input.get('1.0', 'end') data = message.split() for temp in data: try: temp = int(temp) except: error_message.set('Can only decrypt numbers') return decrypted = decrypt(message_input.get('1.0', 'end')) output_decrypted(decrypted) elif en_or_de.get() == 'else': error_message.set('Select encrypt or decrypt') return root = Tk() d = mpf(851) e = mpf(11) # set keys for encryption and decryption p = mpf(53) q = mpf(61) error_message = StringVar() en_or_de = StringVar() en_or_de.set('else') e_key = StringVar() pq_key = StringVar() root.title('Input') root.geometry('-500+100') frame = ttk.Frame(root) frame['padding'] = (20, 5, 20, 5) frame.grid(column=0, row=0, sticky=(N, E, S, W)) encrypt_or_decrypt = ttk.Label(frame, text='Do you want to encrypt or decrypt?').grid(column=3, row=1, sticky=(N, S), pady=5, padx=5, columnspan=3) encrypt_radiobutton = ttk.Radiobutton(frame, text='Encrypt', variable=en_or_de, value='encrypt').grid(column=3, row=2, sticky=(W)) decrypt_radiobutton = ttk.Radiobutton(frame, text='Decrypt', variable=en_or_de, value='decrypt').grid(column=5, row=2, sticky=(N), columnspan=2) ask_message = ttk.Label(frame, text='Enter the message:').grid(column=3, row=4, pady=10, columnspan=3, sticky=(N, S)) e_key_input = ttk.Entry(frame, textvariable='e_key', width=5) e_key_input.grid(column=3, row=3, padx=10, pady=5, sticky=(E, W)) pq_key_input = ttk.Entry(frame, textvariable='pq_key', width=5) pq_key_input.grid(column=5, row=3, padx=10, pady=5, sticky=(E, W)) message_input = Text(frame, width=20, height=5) message_input.grid(column=3, row=5, sticky=(N), padx=10, pady=10, columnspan=3) error = ttk.Label(frame, text='', foreground='red', textvariable=error_message) error.grid(column=3, row=6, columnspan=3, sticky=(N), pady=5) run_button = ttk.Button(frame, text='Run', command=run).grid(column=3, row=7, sticky=(E, W)) cancel_button = ttk.Button(frame, text='Cancel', command=root.destroy).grid(column=5, row=7, sticky=(E, W)) message_input.focus() root.mainloop() <file_sep># PKE ## Contents: 1. [About](#about) 1. [Release notes](#release_notes) 2. [Installation](#installation) 1. [Built version](#built_version) 2. [Python version](#python_version) 3. [Usage](#usage) 1. [Built version](#built) 2. [Python version](#python) 3. [Encrypting](#encrypting) 4. [Decrypting](#decrypting) ## About: <a name="about"></a> The PKE program is an encryption and decryption program inspired by the public key encryption protocol. It is *only* compatible with the latest Windows operating system or any operating system with python 3.7. ### Release notes of PKE-v2.1.0: <a name="release_notes"></a> - Added scrollbar to output - Combined input to single window - Changed output to pop up dialog box - Added custom encryption keys ## Installation: <a name="installation"></a> ### Built version <a name="built_version"></a> To install the built PKE program you will need the latest version of the windows operating system and about 250Mb of space on your hard disk. Once you have this, go ahead and go to the versions tab on the right hand side of the screen. under the latest release there is a space called asssests, under this there is a file called PKE.exe. Click on this and your download will start. Once it has downloaded move it to somewhere you can easily find. ### Python version <a name="python_version"></a> To install the python or source version of the PKE program, you will need python 3 installed on your computer and some space left on your hard disk. Once you have this, click the green Download button on the main page, then select the Download Zip option. This will download an compressed version of the code onto your device. Next, extract all the files from the zipped folder into a directory that is easily accessible. ## Usage: <a name="usage"></a> ### Built version <a name="built"></a> To run the built version of the PKE program, after you have downloaded it double click the file named PKE-vX.X.X.exe. ### Python version <a name="python"></a> To run the source code or the python version, right click the file called PKE.py and select open with. Then from the menu select python 3. ### Encrypting <a name="encrypting"></a> When you run the program you will be prompted with a window with a few configuration options follow these 4 steps to encrypt a message: 1. At the top select the encrypt radiobutton 2. Then if you want to encrypt your message with a custom encryption key, type the public key into the first box and the main key into the second, if you just want to use the default encryption key leave them blank 3. Next type your message to encrypt in the big text box and press 'run', your encrypted text will show up in a pop up dialog box for you to copy paste out of 4. To close the dialog box press 'ok' and it will diapear then you can encrypt, decrypt or close the program, to close the program press 'cancel' ### Decrypting <a name="decrypting"></a> When you run the program you will be prompted with a window with a few configuration options follow these 4 steps to decrypt a message: 1. At the top select the decrypt radiobutton 2. Ignore the two small text boxes they are for encrypting 3. Next type the message you want to decrypt in the big text box and press 'run', your decrypted text will show up in a pop up dialog box for you to read 4. To close the dialog box press 'ok' and it will diapear then you can encrypt, decrypt or close the program, to close the program press 'cancel'
7befae39120456a09cac43fcf91f2c949b009a87
[ "Markdown", "Python" ]
4
Markdown
Madff386/PKE
2112408b9de3ad0b46969f333468eb99f1d9972f
984f2a034c1b4138aa08bb2417d098e3b3d0f717
refs/heads/master
<repo_name>pmorvay/nornir-tools<file_sep>/examples/network/config_management/configure.py #!/usr/bin/env python """ Runbook to configure datacenter """ from nornir.core import InitNornir from nornir.plugins.functions.text import ( print_result, print_title ) from nornir.plugins.tasks.data import load_yaml from nornir.plugins.tasks.networking import napalm_configure from nornir.plugins.tasks.text import template_file def configure(task): """ This function groups all the tasks needed to configure the network: 1. Load extra data 2. Use templates to build configuration 3. Deploy configuration on the devices """ r = task.run( name="Base Configuration", task=template_file, template="base.j2", path=f"templates/{task.host.nos}", ) # r.result holds the result of rendering the template config = r.result r = task.run( name="Loading extra data", task=load_yaml, file=f"extra_data/{task.host}/l3.yaml", ) # r.result holds the data contained in the yaml files # we load the data inside the host itself for further use task.host["l3"] = r.result r = task.run( name="Interfaces Configuration", task=template_file, template="interfaces.j2", path=f"templates/{task.host.nos}", ) # we append the generated configuration config += r.result r = task.run( name="Routing Configuration", task=template_file, template="routing.j2", path=f"templates/{task.host.nos}", ) config += r.result r = task.run( name="Role-specific Configuration", task=template_file, template=f"{task.host['role']}.j2", path=f"templates/{task.host.nos}", ) # we update our hosts' config config += r.result task.run( name="Loading Configuration on the device", task=napalm_configure, replace=False, configuration=config, ) # Initialize nornir nr = InitNornir( config_file="nornir.yaml", dry_run=True, num_workers=20 ) # Let's just filter the hosts we want to operate on cmh = nr.filter(type="network_device", site="cmh") # Let's call the grouped tasks defined above results = cmh.run(task=configure) # Let's show everything on screen print_title("Playbook to configure the network") print_result(results) <file_sep>/tools/network/README.md network ======= Ready to use tools to do various operations in your networks. <file_sep>/tools/network/get_facts/get_facts.py #!/usr/bin/env python import argparse import logging import os from nornir.core import InitNornir from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.networking import napalm_get def main(config, getters, debug): nr = InitNornir( config_file=config, dry_run=False, num_workers=1 if debug else 20, ) result = nr.run( name="Retrieving facts from the device", task=napalm_get, getters=getters, ) print_result( result, severity_level=logging.DEBUG if debug else logging.INFO, ) return result def run(): parser = argparse.ArgumentParser( description="Tool to backup network equipment using napalm" ) parser.add_argument( "-d", "--debug", default=False, action="store_true" ) parser.add_argument( "-c", "--config", default=os.environ.get( "BRIGADE_CONFIGURATION", "nornir.yaml" ), help="Path to nornir configuration. Defaults to nornir.yaml. " "Can be set via env variable BRIGADE_CONFIGURATION", ) parser.add_argument( "-g", "--getter", default=[], action="append", help="Getters to retrieve. Pass this option as many times as you need", ) args = parser.parse_args() main(args.config, args.getter, args.debug) if __name__ == "__main__": run() <file_sep>/tests/wrapper.py import io import os import sys from decorator import decorator def wrap_cli_test(output, save_output=False): """ This decorator captures the stdout and stder and compare it with the contacts of the specified files. Instead of save_output you can set the env variable BRG_TOOLS_TESTS_SAVE_OUTPUT Arguments: output (string): Path to the output. stdout and stderr prefixes will be added automatically save_output (bool): Whether to save the output or not. Useful when creating the tests """ @decorator def run_test(func, *args, **kwargs): stdout = io.StringIO() backup_stdout = sys.stdout sys.stdout = stdout stderr = io.StringIO() backup_stderr = sys.stderr sys.stderr = stderr func(*args, **kwargs) sys.stdout = backup_stdout sys.stderr = backup_stderr if ( save_output or os.getenv("BRG_TOOLS_TESTS_SAVE_OUTPUT") ): with open(f"{output}.stdout", "w+") as f: f.write(stdout.getvalue()) with open(f"{output}.stderr", "w+") as f: f.write(stderr.getvalue()) with open(f"{output}.stdout", "r") as f: expected = f.read() assert stdout.getvalue() == expected with open(f"{output}.stderr", "r") as f: expected = f.read() assert stderr.getvalue() == expected return run_test <file_sep>/tests/conftest.py import os import shutil import pytest @pytest.fixture(scope="session", autouse=True) def tmp_folder(request): tmp = "/tmp/nr_tools_test" def fin(): shutil.rmtree(tmp) request.addfinalizer(fin) os.mkdir(tmp) return tmp <file_sep>/examples/network/get_facts/README.md get\_facts ========== This is a simple example to show how you can write a runbook to get facts from a device. The code is commented so feel free to take a peak and try to understand what's going on. You should be able to use the `Vagrantfile` in the `inventory` and run the command `./get_facts.py`. Feel free to change `getters=["facts", "interfaces"]`, to play with the `nr.filter` or to do whatever other experiments you may want to try out. <file_sep>/examples/network/config_management/README.md Configuration Management ======================== This is a simple example to show how you can write a runbook to deploy some configuration. The code is commented so feel free to take a peak and try to understand what's going on. You should be able to use the `Vagrantfile` in the `inventory` and run the command `./configure.py`. Feel free to change `dry_run=True` to `dry_run=False` to change the configuration, to play with the `nr.filter` or the templates or do whatever other experiments you may want to try out. <file_sep>/tests/tools/network/get_facts/test_get_facts.py from tests.wrapper import wrap_cli_test from tools.network.get_facts import get_facts class TestBackup(object): @wrap_cli_test( output="tests/tools/network/get_facts/output", save_output=False, ) def test_get_facts(self, tmp_folder): result = get_facts.main( "tests/mocked/config.yaml", ["interfaces", "config"], False, ) assert len(result) == 8 for host, results in result.items(): assert not results.failed assert len(results) == 1 <file_sep>/tools/network/backup/backup.py #!/usr/bin/env python import argparse import logging import os from nornir.core import InitNornir from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.files import write_file from nornir.plugins.tasks.networking import napalm_get def backup(task, path): r = task.run( task=napalm_get, getters=["config"], severity_level=logging.DEBUG, ) task.run( task=write_file, filename=f"{path}/{task.host}", content=r.result["config"]["running"], ) def main(config, path, debug): nr = InitNornir( config_file=config, dry_run=False, num_workers=1 if debug else 20, ) result = nr.run( name="Backup configuration of devices", task=backup, path=path, ) print_result( result, severity_level=logging.DEBUG if debug else logging.INFO, ) return result def run(): parser = argparse.ArgumentParser( description="Tool to backup network equipment using napalm" ) parser.add_argument( "-d", "--debug", default=False, action="store_true" ) parser.add_argument( "-c", "--config", default=os.environ.get( "BRIGADE_CONFIGURATION", "nornir.yaml" ), help="Path to nornir configuration. Defaults to nornir.yaml. " "Can be set via env variable BRIGADE_CONFIGURATION", ) parser.add_argument( "-p", "--path", default="backups", help="Path to directory where to save the configuration backups. Defaults to './backups/'", ) args = parser.parse_args() main(args.config, args.path, args.debug) if __name__ == "__main__": run() <file_sep>/tools/network/backup/README.md backup ====== Tool that retrieves the running configuration from a device and stores it locally. For help: $ tools/network/backup/backup.py --help usage: backup.py [-h] [-d] [-c CONFIG] [-p PATH] Tool to backup network equipment using napalm optional arguments: -h, --help show this help message and exit -d, --debug -c CONFIG, --config CONFIG Path to nornir configuration. Defaults to nornir.yaml. Can be set via env variable BRIGADE_CONFIGURATION -p PATH, --path PATH Path to directory where to save the configuration backups. Defaults to './backups/' <file_sep>/setup.py #!/usr/bin/env python from setuptools import setup with open("requirements.txt", "r") as fs: reqs = [ r for r in fs.read().splitlines() if (len(r) > 0 and not r.startswith("#")) ] with open("README.md", "r") as fs: long_description = fs.read() __author__ = "<EMAIL>" __license__ = "Apache License, version 2" __version__ = "0.0.1" setup( name="nornir-tools", version=__version__, description="Fighting fire with fire", long_description=long_description, long_description_content_type="text/markdown", author=__author__, url="https://github.com/nornir-automation/nornir-tools", entry_points={ "console_scripts": { "nornir-tools-nw-backup = tools.network.backup.backup:run", "nornir-tools-nw-get_facts = tools.network.get_facts.get_facts:run", } }, include_package_data=True, install_requires=reqs, packages=["tools"], license=__license__, test_suite="tests", platforms="any", classifiers=["Programming Language :: Python :: 3.6"], ) <file_sep>/tools/network/get_facts/README.md get\_facts ========== Tool that retrieves facts from devices For help: $ ./tools/network/get_facts/get_facts.py --help usage: get_facts.py [-h] [-d] [-c CONFIG] [-g GETTER] Tool to backup network equipment using napalm optional arguments: -h, --help show this help message and exit -d, --debug -c CONFIG, --config CONFIG Path to nornir configuration. Defaults to nornir.yaml. Can be set via env variable BRIGADE_CONFIGURATION -g GETTER, --getter GETTER Getters to retrieve. Pass this option as many times as you need <file_sep>/tools/README.md tools ===== Ready to use tools written using nornir. <file_sep>/tests/tools/network/backup/test_backup.py import os from tests.wrapper import wrap_cli_test from tools.network.backup import backup class TestBackup(object): @wrap_cli_test( output="tests/tools/network/backup/output", save_output=False, ) def test_backup(self, tmp_folder): folder = "{}/test_backup".format(tmp_folder) os.mkdir(folder) result = backup.main( "tests/mocked/config.yaml", folder, False ) assert len(result) == 8 for host, results in result.items(): assert not results.failed assert len(results) == 3 <file_sep>/tox.ini [tox] envlist = py36 black pylama [testenv] deps = -rrequirements.txt -rrequirements-dev.txt passenv = * commands = py.test [testenv:black] deps = black==18.4a1 basepython = python3.6 commands = black --line-length 60 --check . [testenv:pylama] deps = -rrequirements-dev.txt basepython = python3.6 commands = pylama . <file_sep>/examples/network/get_facts/get_facts.py #!/usr/bin/env python from nornir.core import InitNornir from nornir.plugins.functions.text import print_result from nornir.plugins.tasks.networking import napalm_get # Initialize nornir nr = InitNornir( config_file="nornir.yaml", dry_run=True, num_workers=20 ) # Let's just filter the hosts we want to operate on cmh = nr.filter(type="network_device", site="cmh") # Let's retrieve the information and print them on screen results = cmh.run( task=napalm_get, getters=["facts", "interfaces"] ) print_result(results) <file_sep>/requirements-dev.txt decorator pytest pytest-cov pytest-pythonpath pylama tox flake8-import-order black==18.4a1; python_version >= '3.6' -r requirements.txt
506bb2388f3b6bfda5887f83575d29e0f6e0626a
[ "Markdown", "Python", "Text", "INI" ]
17
Python
pmorvay/nornir-tools
cbccc26083c0c4bea6fc441e7b43c88187963d71
aff8569aa840534dc598ee763fe0c53595a55324
refs/heads/master
<repo_name>yuchengruan/eat-safe<file_sep>/public/javascripts/app.js var app = angular.module('angularjsNodejsTutorial', []); app.controller('loginController', function($scope, $http) { $scope.verifyLogin = function() { // To check in the console if the variables are correctly storing the input: // console.log($scope.username, $scope.password); var request = $http({ url: '/login', method: "POST", data: { 'username': $scope.username, 'password': $<PASSWORD> } }) request.success(function(response) { // success console.log(response); if (response.result === "success") { // After you've written the INSERT query in routes/index.js, uncomment the following line window.location.href = "http://localhost:8081/search" } }); request.error(function(err) { // failed console.log("error: ", err); }); }; }); app.controller('searchController', function($scope, $http) { $scope.searchRestaurant = function() { // To check in the console if the variables are correctly storing the input: var request = $http({ url: '/search', method: "POST", data: { 'restaurantname': $scope.restaurantname } }); request.success(function(response) { // success console.log(response); if (response.result === "success") { // After you've written the INSERT query in routes/index.js, uncomment the following line window.location.href = "http://localhost:8081/result" } }); request.error(function(err) { // failed console.log("error: ", err); }); }; }); app.controller('resultController', function($scope, $http) { $scope.showresult = function() { var request = $http({ url: '/result', method: "POST", data: { } }); request.success(function(response) { $scope.info = response; console.log($scope.info); }); request.error(function(err) { console.log("error: ", err); }); }; }); app.controller('userController', function($scope, $http) { var request = $http({ url: '/userList', method: "GET", data: { } }); request.success(function(response){ $scope.users = response; }); request.error(function(err) { // failed console.log("error: ", err); }); }); app.controller('topMovieController', function($scope, $http) { $scope.printGenres = function(){ var request = $http({ url: '/genres', method: "GET", data: { } }); request.success(function(response){ $scope.genres = response; }); request.error(function(err) { // failed console.log("error: ", err); }); }; $scope.printTopMovies = function(genre){ var request = $http({ url: '/topMovies/'+genre, method: "GET", data: { } }); request.success(function(response){ $scope.topMovies = response; $scope.showTable = true; console.log(rows); }); request.error(function(err) { // failed console.log("error: ", err); }); }; }); app.controller('RecommendationController', function($scope, $http) { $scope.recommend = function() { console.log($scope.movieId); var request = $http({ url: '/Recommendations/' + $scope.movieId, method: "GET" }) request.success(function(response) { console.log(response); $scope.whetherShowReco = true; $scope.results = response; }); request.error(function(err) { console.log("recommendation error: ", err); }); }; }); app.controller('BestOfController', function($scope, $http) { var range = []; for (var i = 2000; i <= 2017; i++) { range.push(i); } console.log(range); $scope.years = range; $scope.bestOf = function() { var request = $http({ url: '/BestOf/'+ $scope.years, method: "GET" }) request.success(function(response) { //console.log($scope.years); console.log(response); $scope.showtable = true; $scope.results = response; }); request.error(function(err) { console.log("bestOf error: ", err); }); }; }); app.controller('backController', function($scope, $http) { $scope.back = function() { window.location.href = "http://localhost:8081/search"; } }); // app.controller('posterController', function($scope, $http) { // var init = function () { // var request = $http({ // url: '/posters', // method: "POST", // data : { // } // }); // request.success(function(response) { // // success // $scope.posters = new Map(); // console.log("success"); // for (var i = 0;i < response.length;i++) { // var requestPoster = $http({ // url: "http://www.omdbapi.com/?i="+response[i].imdb_id+"&apikey=461ec312", // method: "GET" // }); // requestPoster.success(function(response2) { // $scope.posters[response2.Title] = [response2.Poster, response2.Website]; // }); // requestPoster.error(function(err) { // $scope.posters[response2.Title] = ["", ""]; // }); // } // console.log($scope.posters); // }); // request.error(function(err) { // console.log("error: ", err); // }); // }; // init(); // }); // app.controller('postersController', function($scope, $http) { // var init = function () { // var request = $http({ // url: '/posterLists', // method: "GET", // data: { // } // }); // request.success(function(response){ // $scope.results = response; // $scope.posters = new Map(); // console.log("success"); // for (var i = 0;i < response.length;i++) { // var requestPoster = $http({ // url: "http://www.omdbapi.com/?i="+response[i].imdb_id+"&apikey=461ec312", // method: "GET" // }); // requestPoster.success(function(response2) { // $scope.posters[response2.Title] = [response2.Poster, response2.Website]; // }); // requestPoster.error(function(err) { // $scope.posters[response2.Title] = ["", ""]; // }); // } // console.log($scope.posters); // }); // request.error(function(err) { // console.log("error: ", err); // }); // }; // init(); // }); // $scope.printPosters = function(imdbId){ // console.log(title); // var request = $http({ // url: 'http://www.omdbapi.com/?i='+imdbId+'&apikey=1ecd07b5', // method: "GET", // }); // console.log(url); // request.success(function(response2){ // $scope.jsonResults = response2; // $scope.image = response2.Poster; // $scope.website = response2.Website; // }); // request.error(function(err) { // // failed // console.log("error: ", err); // }); // }; // Template for adding a controller /* app.controller('dummyController', function($scope, $http) { // normal variables var dummyVar1 = 'abc'; // Angular scope variables $scope.dummyVar2 = 'abc'; // Angular function $scope.dummyFunction = function() { }; }); */ <file_sep>/README.md # **Eat Safe** Contributors: <NAME>, <NAME>, <NAME>, <NAME> ### Project Goals As frequent travelers, the four members in our team share the common experience of using Yelp to find places to eat when arriving in a new city. However, since we were unfamiliar with the city, sometimes we ended up in a shabby area that looked suspiciously risky. To ensure travelers and foodies that they would have a safe dining experience, we decided to build Eat Safe, a web app that integrates Yelp data and criminal records in major cities to indicate how likely they may encounter a crime in the vicinity of the restaurant they intend to go to. ### Data Sources **Yelp Open Dataset** (8.68GB) and **criminal records in Las Vegas** (20000 crime events ) ### Framework ![fw](fw.png) <file_sep>/routes/index.js var express = require('express'); var router = express.Router(); var path = require('path'); // Connect string to MySQL var mysql = require('mysql'); var restaurant; var connection = mysql.createConnection({ host: 'cis550project.chvnr3kzizz0.us-east-1.rds.amazonaws.com', user: 'cis550project', password: '<PASSWORD>', port: '1521', database: 'cis550project', }); connection.connect(function(err) { if (err) { console.log("Error Connection to DB" + err); return; } console.log("Connection established..."); }); /* GET home page. */ router.get('/', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'login.html')); }); router.get('/search', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'search.html')); }); router.get('/result', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'result.html')); }); <<<<<<< HEAD ======= >>>>>>> 9f34e0c51029c820abe1d8f741ebbdabfefd284b router.get('/recommend', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'recommend.html')); }); router.get('/contact', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'contact.html')); }); router.get('/posters', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'posters.html')); }); // To add a new page, use the templete below /* router.get('/routeName', function(req, res) { res.sendFile(path.join(__dirname, '../', 'views', 'fileName.html')); }); */ // Login uses POST request router.post('/login', function(req, res) { // use console.log() as print() in case you want to debug, example below: // console.log(req.body); will show the print result in your terminal // req.body contains the json data sent from the loginController // e.g. to get username, use req.body.username var query = "INSERT IGNORE INTO User VALUES ('"+req.body.username+"','"+req.body.password+"');"; /* Write your query here and uncomment line 21 in javascripts/app.js*/ connection.query(query, function(err, rows, fields) { console.log(req.body.username); // console.log("rows", rows); // console.log("fields", fields); if (err) console.log('insert error: ', err); else { res.json({ result: 'success' }); } }); }); router.post('/search', function(req, res) { // use console.log() as print() in case you want to debug, example below: // console.log(req.body); will show the print result in your terminal // req.body contains the json data sent from the loginController // e.g. to get username, use req.body.username // var query = "SELECT * FROM Business WHERE business_name = ('"+req.body.restaurantname+"');"; /* Write your query here and uncomment line 21 in javascripts/app.js*/ // connection.query(query, function(err, rows, fields) { // console.log(req.body.restaurantname); // // console.log("fields", fields); // if (err) console.log('error: ', err); // else { // res.json({ // result: 'success' // }); // } // }); restaurant = req.body.restaurantname; res.json({ result: 'success' }); }); router.post('/result', function(req, res) { // use console.log() as print() in case you want to debug, example below: // console.log(req.body); will show the print result in your terminal // req.body contains the json data sent from the loginController // e.g. to get username, use req.body.username var query = "SELECT * FROM Business WHERE business_name = ('"+restaurant+"');"; /* Write your query here and uncomment line 21 in javascripts/app.js*/ connection.query(query, function(err, rows, fields) { if (err) console.log('error: ', err); else { res.json(rows); } }); }); router.get('/userList', function(req, res) { var query = "SELECT * FROM User;"; connection.query(query, function(err, rows, fields) { if (err) console.log('get user info error: ', err); else { res.json(rows); } }); }); router.get('/genres', function(req, res) { var query = "SELECT DISTINCT genre FROM Genres;"; connection.query(query, function(err, rows, fields) { if (err) console.log('get user info error: ', err); else { res.json(rows); } }); }); router.get('/topMovies/:genre', function(req, res) { var query = "SELECT title, rating, vote_count FROM Genres JOIN Movies ON movie_id = id WHERE genre = '"+req.params.genre+"' ORDER BY rating DESC, vote_count DESC LIMIT 10;"; connection.query(query, function(err, rows, fields) { if (err) console.log('get user info error: ', err); else { res.json(rows); } }); }); router.get('/Recommendations/:movieId', function(req, res) { console.log(req.params.movieId); var query = "SELECT DISTINCT genre FROM Genres WHERE movie_id = '"+req.params.movieId+"'"; connection.query(query, function(err, rows, fields) { if (err) { console.log('get recommendations error: ', err); } else { //console.log(rows); var results = []; var titleList = []; var genreList = []; var total = 10; var genreNum = rows.length; var newQuery = "SELECT DISTINCT title, genre FROM Movies, (SELECT DISTINCT movie_id,genre FROM Genres WHERE genre IN ("+ query +")) G WHERE id = movie_id LIMIT 100;"; connection.query(newQuery, function(err, rows, fields) { if (err) console.log('Query error: ', err); else { for(var i in rows){ //console.log("rows "+i+rows[i].title); if(results.length < genreNum){ console.log("rows "+i+rows[i].title); if(!genreList.includes(rows[i].genre) && !titleList.includes(rows[i].title)){ results.push({"title": rows[i].title, "genre": rows[i].genre}); titleList.push(rows[i].title); genreList.push(rows[i].genre); console.log(titleList); } if(results.length == total){ break; } } else{ if(!titleList.includes(rows[i].title)){ results.push({"title": rows[i].title, "genre": rows[i].genre}); titleList.push(rows[i].title); //console.log(titleList); } if(results.length == total){ break; } } } console.log(results); res.json(results); } }); } }); }); //Movies (id, title, imdb_id, rating, release_year, vote_count) //Genres (movie_id, genre) router.get('/BestOf/:years', function(req, res) { var query = "SELECT M.title title, G.genre genre, M.vote_count votes "+ "FROM Movies M JOIN Genres G ON M.id = G.movie_id "+ "JOIN (SELECT genre, MAX(vote_count) vote_count "+ " FROM Movies JOIN Genres ON id = movie_id "+ " WHERE release_year = '"+req.params.years+ "'"+ " GROUP BY genre) Q "+ "ON G.genre = Q.genre "+ "WHERE M.vote_count = Q.vote_count "+ "ORDER BY G.genre;"; console.log(req.params.years); connection.query(query, function(err, rows, fields) { if (err) console.log('query error: ', err); else { var results = []; var genreList = []; for(var i in rows){ if(!genreList.includes(rows[i].genre)){ results.push({"title": rows[i].title, "genre": rows[i].genre, "votes": rows[i].votes}); genreList.push(rows[i].genre); } } res.json(results); } }); }); router.get('/posterLists', function(req, res) { var randomNumber = Math.floor(Math.random()*(15-10+1))+10; console.log(randomNumber); var query = "SELECT title, imdb_id FROM Movies ORDER BY RAND() LIMIT "+ randomNumber+";"; connection.query(query, function(err, rows, fields) { if (err) console.log(err); else { //console.log(rows); res.json(rows); } }); }); // template for GET requests /* router.get('/routeName/:customParameter', function(req, res) { var myData = req.params.customParameter; // if you have a custom parameter var query = ''; // console.log(query); connection.query(query, function(err, rows, fields) { if (err) console.log(err); else { res.json(rows); } }); }); */ module.exports = router;
c7067141d6fc3703509391b142e4dacd4ebfe79e
[ "JavaScript", "Markdown" ]
3
JavaScript
yuchengruan/eat-safe
ba8fd78d861bd59f2d09760d7b1296b69a57a29a
1dbdc0a29c09010354672a437fe2f38766c51768
refs/heads/master
<file_sep>/****************************************************************************** * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ var widgets = require('@jupyter-widgets/base'); var _ = require('lodash'); var PVDisplayModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name : 'PVDisplayModel', _view_name : 'PVDisplayView', _model_module : 'ipyparaview', _view_module : 'ipyparaview', _model_module_version : '0.1.0', _view_module_version : '0.1.0' }) }); var PVDisplayView = widgets.DOMWidgetView.extend({ render: function(){ //Utility functions var norm = function(x){ return Math.sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]); }; var normalize = function(x){ r = norm(x); return [ x[0]/r, x[1]/r, x[2]/r ]; }; var cross = function(x, y){ return [ x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2], x[0]*y[1] - x[1]*y[0] ]; }; var cartToSphr = function(x){ var r = norm(x); return [r, Math.atan2(x[0], x[2]), Math.asin(x[1]/r)]; }; var sphrToCart = function(x){ return [ x[0]*Math.sin(x[1])*Math.cos(x[2]), x[0]*Math.sin(x[2]), x[0]*Math.cos(x[1])*Math.cos(x[2]) ]; }; var vadd = function(x,y){ return [ x[0] + y[0], x[1] + y[1], x[2] + y[2] ]; }; var vscl = function(x,y){ return [ x[0]*y, x[1]*y, x[2]*y ]; }; this.model.on('change:frame', this.frameChange, this); // Create 'div' and 'canvas', and attach them to the...erm, "el" this.renderWindow = document.createElement('div'); this.canvas = document.createElement('canvas'); this.renderWindow.appendChild(this.canvas); this.el.appendChild(this.renderWindow); //convenience references var canvas = this.canvas; var ctx = canvas.getContext('2d'); var model = this.model; var view = this; cf = model.get('camf'); cp = cartToSphr(vadd(model.get('camp'), vscl(cf, -1.0))); cu = model.get('camu'); [canvas.width,canvas.height] = model.get('resolution'); //Perform the initial render let frame = new Uint8Array(this.model.get('frame').buffer); var imgData = ctx.createImageData(canvas.width,canvas.height); var i; for(i=0; i<imgData.data.length; i+=4){ imgData.data[i+0] = frame[i+0]; imgData.data[i+1] = frame[i+1]; imgData.data[i+2] = frame[i+2]; imgData.data[i+3] = 255; } ctx.putImageData(imgData, 0, 0); var m0 = {x: 0.0, y: 0.0}; //last mouse position //converts mouse from canvas space to NDC var getNDC = function(e){ var rect = canvas.getBoundingClientRect(); //compute current mouse coords in NDC var mx = (e.clientX - rect.left)/(rect.right-rect.left); var my = (e.clientY - rect.top)/(rect.top-rect.bottom); return {x: mx, y: my}; }; var getMouseDelta = function(e){ var m1 = getNDC(e); var md = {x: m1.x-m0.x, y: m1.y-m0.y}; m0 = m1; return md; }; //mouse event throttling--wait throttlems between mouse events const throttlems = 1000.0/20.0; var lastMouseT = Date.now(); var updateCam = function(){ var mt = Date.now(); if(mt - lastMouseT > throttlems){ model.set({"camp": vadd(sphrToCart(cp), cf), "camf": cf}); model.save_changes(); //triggers state synchronization (I think) view.send({event: 'updateCam', data: ''}); //trigger a render lastMouseT = mt; } }; // Mouse event handling -- drag and scroll var handleDrag = function(e){ const scl = 5.0; //rotation scaling factor const phiLim = 1.5175; //limit phi from reaching poles var md = getMouseDelta(e); cp[1] -= 5.0*md.x; cp[2] = Math.max(-phiLim, Math.min(phiLim, cp[2]-5.0*md.y)); updateCam(); }; var handleMidDrag = function(e){ const scl = 1.0/1.25; var md = getMouseDelta(e); ccp = sphrToCart(cp); h = normalize(cross(ccp, cu)); //horizontal v = normalize(cross(ccp, h)); //vertical d = vscl(vadd(vscl(h,md.x), vscl(v,md.y)), cp[0]*scl); //position delta cf = vadd(cf, d); //NOTE: cp is relative to cf updateCam(); }; var handleScroll = function(e){ const wheelScl = 40.0; const dScl = 0.05; const rlim = 0.00001; e.preventDefault(); e.stopPropagation(); var d = e.wheelDelta ? e.wheelDelta/wheelScl : e.detail ? -e.detail : 0; if(d){ cp[0] = Math.max(rlim, cp[0]*(1.0-dScl*d)); updateCam(); } }; // Add event handlers to canvas canvas.addEventListener('mousedown',function(e){ m0 = getNDC(e); if(e.button == 0){ canvas.addEventListener('mousemove',handleDrag,false); }else if(e.button == 1){ canvas.addEventListener('mousemove',handleMidDrag,false); } }, false); canvas.addEventListener('mouseup',function(e){ if(e.button == 0){ canvas.removeEventListener('mousemove',handleDrag,false); }else if(e.button == 1){ canvas.removeEventListener('mousemove',handleMidDrag,false); } }, false); canvas.addEventListener('wheel', handleScroll, false); }, frameChange: function() { let ctx = this.canvas.getContext('2d'); let frame = new Uint8Array(this.model.get('frame').buffer); var imgData = ctx.createImageData(this.canvas.width,this.canvas.height); var i; for(i=0; i<imgData.data.length; i+=4){ imgData.data[i+0] = frame[i+0]; imgData.data[i+1] = frame[i+1]; imgData.data[i+2] = frame[i+2]; imgData.data[i+3] = 255; } ctx.putImageData(imgData, 0, 0); }, }); module.exports = { PVDisplayModel : PVDisplayModel, PVDisplayView : PVDisplayView }; <file_sep>#!/bin/bash python setup.py build \ && pip install -e . \ && jupyter nbextension install --py --symlink --sys-prefix ipyparaview \ && jupyter nbextension enable --py --sys-prefix ipyparaview \ && jupyter labextension install js <file_sep>A widget for interactive server-side ParaView rendering Package Install --------------- **Prerequisites** - [node](http://nodejs.org/) ```bash npm install --save ipyparaview ``` <file_sep>ipyparaview =============================== A widget for interactive server-side ParaView rendering. Note that this requires a pre-existing ParaView installation and ParaView's python libraries to be locatable via $PYTHONPATH--see the `scripts` folders for examples. Installation ------------ Note that both the regular and developer installs currently require nodejs (for npm) in addition to the regular tools. For a regular user installation: $ pip install git+https://github.com/NickLeaf/ipyparaview.git $ jupyter nbextension enable --py --sys-prefix ipyparaview For a development installation: $ git clone https://github.com/NickLeaf/ipyparaview.git $ cd ipyparaview $ pip install -e . $ jupyter nbextension install --py --symlink --sys-prefix ipyparaview $ jupyter nbextension enable --py --sys-prefix ipyparaview $ jupyter labextension install js (*optional*)
10e17ccbed24a75034b28288f30437667eec2cad
[ "JavaScript", "Markdown", "Shell" ]
4
JavaScript
jjones-jr/ipyparaview
2c77a9f2ff843153d2c63270f327848ccd4c16b6
db8a3c872306f121e06d7e91802d343b51a6b037
refs/heads/main
<file_sep>import { mkdirSync, writeFileSync } from 'node:fs' import { join as joinPath } from 'node:path' import { getSVGs, getDirname } from './util.js' import chalk from 'chalk' const __dirname = getDirname(import.meta.url) const icons = [] const basepath = joinPath(__dirname, '../../vue/') mkdirSync(basepath, { recursive: true }) getSVGs().forEach(({ svg, filename, exportName }) => { const attrs = Array.from(svg.attrs).map(attr => attr.name + `: ` + `'` + attr.value + `'`) const output = [ `import { h } from 'vue'`, `export default (_, { attrs }) => h('svg', { ${attrs.join(', ')}, innerHTML: '${svg.html}', ...attrs })` ].join('\n') const path = joinPath(basepath, filename) writeFileSync(path, output, 'utf-8') icons.push({ exportName, filename }) }) console.log(`${chalk.green('vue')}: Wrote ${chalk.yellow(icons.length)} icon files`) const indexFile = icons.map(({ exportName, filename }) => `export { default as ${exportName} } from './${filename}'`).join('\n') const indexFilename = joinPath(basepath, 'index.js') writeFileSync(indexFilename, indexFile, 'utf-8') console.log(`${chalk.green('vue')}: Wrote ${chalk.yellow('index')} file`) <file_sep>import './elements.js' import './react.js' import './vue.js' <file_sep>import path from "path"; export const basedir = path.dirname(new URL(import.meta.url).pathname); export const iconsPath = path.join(basedir, "dist"); <file_sep>import fs from "fs-extra"; import glob from "glob"; import path from "path"; import nunjucks from "nunjucks"; import { basedir } from "../index.js"; const svgPaths = glob.sync(`./dist/**/*.svg`); const icons = svgPaths.map((svgPath) => { const data = fs.readFileSync(svgPath, "utf-8"); return { name: path.parse(svgPath).name, svg: data, iconSize: getIconSize(svgPath), }; }); // Group the icons by size const iconsBySize = {}; for (const icon of icons) { const array = iconsBySize[icon.iconSize] || []; array.push(icon); iconsBySize[icon.iconSize] = array; } fs.writeFileSync( "./preview/index.html", nunjucks.render(path.join(basedir, "preview/template.njk"), { iconsBySize, }) ); function getIconSize(filePath) { const dirname = path.dirname(filePath); const dirs = dirname.split("/"); return dirs[dirs.length - 1]; } <file_sep># Fabric Icons The icon set for Fabric, imported from the [Figma project](https://www.figma.com/file/pY4zC5fnUv7CPjwSrJV9nT/). **Note that the icons in the "raw" folder in this repository should never be used directly, as they aren't optimized.** ## Usage ### Elements #### Using NPM package ##### Install dependencies You will need to install both Fabric Elements and Lit Element which is the library we use for custom elements ``` npm install lit @fabric-ds/icons ``` ##### Import elements Import the individual element file, importing will load the component. Once imported, run your script through whatever bundling process your app uses (Rollup, Esbuild, etc) after which the component can be used in the page. ```js import '@fabric-ds/icons/elements/attachment-16'; import '@fabric-ds/icons/elements/attachment-24'; ``` ```html <f-icon-attachment16></f-icon-attachment16> <f-icon-attachment24></f-icon-attachment24> ``` ## Development ### Updating the icons Icons should never be added or edited manually in this repository, as the source of truth is in [Figma](https://www.figma.com/file/pY4zC5fnUv7CPjwSrJV9nT/). #### Figma access token If you are running the import script for the first time, it will prompt your for a [Figma access token](https://www.figma.com/developers/api#access-tokens). The token is is required to access Figma's API. It can be generated on your Figma account settings page. The import script may store the token to a local file, so you won't have to supply the token again on subsequent runs. ### Import script To update the icons, run the following script. If it has a valid Figma access token (see above), it will proceed to download all the icons as SVG files. ```sh ./scripts/figma-import.js ``` ### Local preview You can open a local preview of the icons. Use this to verify that the icons looks as they should. Run the following command. ```sh npm run start ``` ### Publishing If everything looks correct, publish the changes. ```sh npm publish ``` ```sh git push --follow-tags ``` ### Eik Eik versions for each of Vue, Elements and React icons are automatically created in the ./dist folder when builds are run. Eik configuration is based on values in package.json (name, version and eik keys) and running Eik publish will publish everything in the dist folder to Eik under the path `https://assets.finn.no/pkg/{name}/{version}/`. Example Paths: * React: `https://assets.finn.no/pkg/@fabric-ds/icons/v1/react/icons.min.js` * Vue: `https://assets.finn.no/pkg/@fabric-ds/icons/v1/vue/icons.min.js` * Custom Elements: `https://assets.finn.no/pkg/@fabric-ds/icons/v1/elements/icons.min.js` * Raw ads svg at size 16: `https://assets.finn.no/pkg/@fabric-ds/icons/v1/16/ads.svg` * Raw air con svg at size 24: `https://assets.finn.no/pkg/@fabric-ds/icons/v1/24/air-con.svg` ### Troubleshooting #### Auth If the scripts authentication issues, you could try to create a new access token and delete the local file `.FIGMA_TOKEN` before running the script again. #### Figma project structure The script is probably not resilient to changes in the structure of the Figma project. Changes there will probably require an update of the import script.
4721f9a3f4d359e08dc82f14411dc83321549457
[ "JavaScript", "Markdown" ]
5
JavaScript
finn-no/fabric-icons
3831a429054a68d4fd3af8e42e310747d9835efb
6ddacffcffe998fcafbc876124d9f53bf990c8db
refs/heads/main
<repo_name>marschall-lab/GFAffix<file_sep>/src/collapse_event_tracker.rs use handlegraph::{ handle::{Direction, Edge, Handle}, handlegraph::{IntoNeighbors, IntoSequences}, hashgraph::HashGraph, mutablehandlegraph::AdditiveHandleGraph, }; use rustc_hash::{FxHashMap, FxHashSet}; /* project use */ use crate::v2str; #[derive(Clone, Debug)] pub struct CollapseEventTracker { // tranform from (node_id, node_len) -> [(node_id, node_orient, node_len), ..] // ^ keys are always forward oriented pub transform: FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, pub overlapping_events: usize, pub bubbles: usize, pub events: usize, pub modified_nodes: FxHashSet<(usize, usize)>, } impl CollapseEventTracker { pub fn report( &mut self, collapsed_prefix_node: Handle, prefix_len: usize, splitted_node_pairs: &Vec<(usize, Direction, usize, Handle, Option<(Handle, usize)>)>, ) { self.events += 1; self.modified_nodes .insert((collapsed_prefix_node.unpack_number() as usize, prefix_len)); let is_bubble = splitted_node_pairs.iter().all(|x| x.4.is_none()); if is_bubble { self.bubbles += 1; } let prefix_id = collapsed_prefix_node.unpack_number() as usize; let prefix_orient = if collapsed_prefix_node.is_reverse() { Direction::Left } else { Direction::Right }; for (node_id, node_orient, node_len, _, suffix) in splitted_node_pairs { // do not report transformations of the same node to itself or to its reverse if node_id != &prefix_id || node_len != &prefix_len { // record transformation of node, even if none took place (which is the case if node v // equals the dedicated shared prefix node let mut replacement: Vec<(usize, Direction, usize)> = vec![(prefix_id, prefix_orient, prefix_len)]; if let Some((v, vlen)) = suffix { replacement.push(( v.unpack_number() as usize, if v.is_reverse() { Direction::Left } else { Direction::Right }, *vlen, )); self.modified_nodes .insert((v.unpack_number() as usize, *vlen)); } // orient transformation // important notice: // - handle_graph::split_handle() works only in forward direction // - the first node of the split pair an will always be the node itself (again in // forward direction) if *node_orient == Direction::Left { replacement.reverse(); for r in replacement.iter_mut() { r.1 = if r.1 == Direction::Left { Direction::Right } else { Direction::Left }; } } log::debug!( "new replacement rule {}:{} -> {}", node_id, node_len, replacement .iter() .map(|(rid, ro, rlen)| format!( "{}{}:{}", if *ro == Direction::Left { '<' } else { '>' }, rid, rlen )) .collect::<Vec<String>>() .join("") ); self.transform .insert((*node_id, *node_len), replacement.clone()); } } } pub fn expand( &self, node_id: usize, node_orient: Direction, node_len: usize, ) -> Vec<(usize, Direction, usize)> { let mut res: Vec<(usize, Direction, usize)> = Vec::new(); if self.transform.contains_key(&(node_id, node_len)) { for (rid, rorient, rlen) in self.transform.get(&(node_id, node_len)).unwrap() { // if identical node appears in its expansion sequence, don't expand... if (*rid, *rlen) != (node_id, node_len) { res.extend(self.expand(*rid, *rorient, *rlen)); } else { res.push((*rid, *rorient, *rlen)); } } if node_orient == Direction::Left { res.reverse(); for x in res.iter_mut() { x.1 = match x.1 { Direction::Left => Direction::Right, Direction::Right => Direction::Left, }; } } } else { res.push((node_id, node_orient, node_len)); } res } pub fn deduplicate_transform( &mut self, node_id: usize, node_len: usize, copies: &mut FxHashMap<(usize, usize), Vec<Handle>>, ) { let mut queue = vec![(node_id, node_len)]; while !queue.is_empty() { let (vid, vlen) = queue.pop().unwrap(); if self.transform.contains_key(&(vid, vlen)) { let mut copy_of_vid = vid; for (rid, _, rlen) in self.transform.get_mut(&(vid, vlen)).unwrap() { let key = (*rid, *rlen); if copies.contains_key(&key) { // replace by a copy let c = copies.get_mut(&key).unwrap().pop(); if c == None { panic!("not enough copies available for node {}:{} to deduplicate transformation rule of {}:{}", key.0, key.1, vid, vlen); } let rid_new = c.unwrap().unpack_number() as usize; log::debug!("replace {}:{} by {}:{} in de-duplication of transformation rule of {}:{}", rid, rlen, rid_new, rlen, vid, vlen); *rid = rid_new; // if copy is also key of transform table, then record new ID if key == (vid, vlen) { copy_of_vid = *rid } } // if identical node appears in its expansion sequence, don't expand... if (*rid, *rlen) != (copy_of_vid, vlen) { queue.push((*rid, *rlen)); } } // if copy is also key of transform table, then update key if copies.contains_key(&(vid, vlen)) && copy_of_vid != vid { let val = self.transform.remove(&(vid, vlen)).unwrap(); self.transform.insert((copy_of_vid, vlen), val); } } } } pub fn get_expanded_transformation( &self, ) -> FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>> { let mut res: FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>> = FxHashMap::default(); res.reserve(self.transform.len()); for (node_id, node_len) in self.transform.keys() { let expansion = self.expand(*node_id, Direction::Right, *node_len); log::debug!( "deep-expansion of walk {} of node {}:{} into {}", self.transform .get(&(*node_id, *node_len)) .unwrap() .iter() .map(|(rid, ro, rlen)| format!( "{}{}:{}", if *ro == Direction::Left { '<' } else { '>' }, rid, rlen )) .collect::<Vec<String>>() .join(""), node_id, node_len, expansion .iter() .map(|(rid, ro, rlen)| format!( "{}{}:{}", if *ro == Direction::Left { '<' } else { '>' }, rid, rlen )) .collect::<Vec<String>>() .join("") ); res.insert((*node_id, *node_len), expansion); } res } pub fn decollapse( &mut self, graph: &mut HashGraph, nodes: FxHashSet<(usize, usize)>, ) -> Vec<usize> { // first of all, remove unnecessary transformation rules let keys = self .transform .keys() .map(|(xid, xlen)| (*xid, *xlen)) .collect::<Vec<(usize, usize)>>(); for (vid, vlen) in keys { let rule = self.transform.get(&(vid, vlen)).unwrap(); if rule.len() == 1 && rule[0] == (vid, Direction::Right, vlen) { self.transform.remove(&(vid, vlen)); } } let mut count: FxHashMap<(usize, usize), usize> = FxHashMap::default(); for (vid, vlen) in nodes.iter() { let expansion = self.expand(*vid, Direction::Right, *vlen); for (uid, _, ulen) in expansion.iter() { *count.entry((*uid, *ulen)).or_insert(0) += 1; } } log::info!( "reverting {} collapses in order to de-duplicate nodes on given set of paths", count .values() .map(|&x| if x > 1 { 1 } else { 0 }) .sum::<usize>() ); // multiplicate nodes that occur more than once let mut copies: FxHashMap<(usize, usize), Vec<Handle>> = FxHashMap::default(); for ((vid, vlen), occ) in count.iter_mut() { // if a duplicated node is hit, create and record as many copies as needed to // de-duplicate it! if *occ > 1 { // yes, the duplicated node is a valid copy of its own! copies .entry((*vid, *vlen)) .or_insert(Vec::new()) .push(Handle::pack(*vid, false)); } // make some more copies while *occ > 1 { // create copy u of node v let v = Handle::pack(*vid, false); let u = graph.append_handle(&graph.sequence_vec(v)[..]); log::debug!( "creating duplicate {} of node {}", u.unpack_number(), v.unpack_number() ); // copy incident edges of v onto u for w in graph.neighbors(v, Direction::Left).collect::<Vec<Handle>>() { log::debug!( "creating duplicate edge <{}{}", u.unpack_number(), v2str(&w) ); graph.create_edge(Edge::edge_handle(u.flip(), w.flip())); } for w in graph .neighbors(v, Direction::Right) .collect::<Vec<Handle>>() { log::debug!( "creating duplicate edge >{}{}", u.unpack_number(), v2str(&w) ); graph.create_edge(Edge::edge_handle(u, w)); } copies.get_mut(&(*vid, *vlen)).unwrap().push(u); *occ -= 1 } } // collect copies for return let mut res = Vec::new(); for v in copies.values() { res.extend(v.iter().map(|x| x.unpack_number() as usize)); } // update transformation table for (vid, vlen) in nodes.iter() { self.deduplicate_transform(*vid, *vlen, &mut copies); } res } pub fn new() -> Self { CollapseEventTracker { transform: FxHashMap::default(), overlapping_events: 0, bubbles: 0, events: 0, modified_nodes: FxHashSet::default(), } } } <file_sep>/src/main.rs /* standard use */ use std::collections::VecDeque; use std::error::Error; use std::fs; use std::io; use std::io::prelude::*; use std::iter::{repeat, FromIterator}; use std::str::{self, FromStr}; /* crate use */ use clap::Parser; use gfa::{ gfa::{orientation::Orientation, GFA}, optfields::OptFields, parser::GFAParser, }; use handlegraph::{ handle::{Direction, Edge, Handle}, handlegraph::*, hashgraph::HashGraph, mutablehandlegraph::{AdditiveHandleGraph, MutableHandles}, pathhandlegraph::GraphPathNames, }; use quick_csv::Csv; use rayon::slice::ParallelSliceMut; use regex::Regex; use rustc_hash::{FxHashMap, FxHashSet}; /* mod declaration */ mod collapse_event_tracker; use collapse_event_tracker::*; mod affix_sub_graph; use affix_sub_graph::*; mod deleted_sub_graph; use deleted_sub_graph::*; #[derive(Parser, Debug)] #[clap( version = "0.1.5", author = "<NAME> <<EMAIL>>", about = "Discover and collapse walk-preserving shared affixes of a given variation graph.\n - Do you want log output? Call program with 'RUST_LOG=info gfaffix ...' - Log output not informative enough? Try 'RUST_LOG=debug gfaffix ...'" )] pub struct Command { #[clap(index = 1, help = "graph in GFA1 format", required = true)] pub graph: String, #[clap( short = 'o', long = "output_refined", help = "Write refined graph in GFA1 format to supplied file", default_value = " " )] pub refined_graph_out: String, #[clap( short = 't', long = "output_transformation", help = "Report original nodes and their corresponding walks in refined graph to supplied file", default_value = " " )] pub transformation_out: String, #[clap( short = 'c', long = "check_transformation", help = "Verifies that the transformed parts of the graphs spell out the identical sequence as in the original graph" )] pub check_transformation: bool, #[clap( short = 'x', long = "dont_collapse", help = "Do not collapse nodes on a given paths (\"P\" lines) that match given regular expression", default_value = " " )] pub no_collapse_path: String, } pub fn v2str(v: &Handle) -> String { format!( "{}{}", if v.is_reverse() { '<' } else { '>' }, v.unpack_number() ) } fn enumerate_branch( graph: &HashGraph, del_subg: &DeletedSubGraph, v: &Handle, ) -> FxHashMap<(u8, Vec<Handle>), VecDeque<Handle>> { let mut branch: FxHashMap<(u8, Vec<Handle>), VecDeque<Handle>> = FxHashMap::default(); // traverse multifurcation in the forward direction of the handle for u in graph.neighbors(*v, Direction::Right) { if !del_subg.edge_deleted(v, &u) { // get parents of u let mut parents: Vec<Handle> = graph .neighbors(u, Direction::Left) .filter(|w| !del_subg.edge_deleted(w, &u)) .collect(); parents.par_sort(); // insert child in walk-preserving data structure let mut c = graph.base(u, 0).unwrap(); // make all letters uppercase if c >= 90 { c -= 32 } let children = branch.entry((c, parents)).or_insert_with(VecDeque::new); // Sort handles with shared prefix so that reversed ones come first! This is important // for the case that two shared prefixes correspond to the same node, one in forward, // and one in backward dirction (e.g. >1209, <1209 share prefix 'C'). In those cases, // the code that splits handles only works iff the backward oriented handle is split // first (e.g., <1209 is split into <329203 and <1209) and then the forward oriented // handle (e.g., truncated handle >1209 is split into >1209 and 329204), Subsequently, // either >1209 or >329203 is deleted, with the other being advanced as dedicated // shared prefix node. if u.is_reverse() { children.push_front(u); } else { children.push_back(u); } } } branch } fn enumerate_walk_preserving_shared_affixes( graph: &HashGraph, del_subg: &DeletedSubGraph, v: Handle, ) -> Result<Vec<AffixSubgraph>, Box<dyn Error>> { let mut res: Vec<AffixSubgraph> = Vec::new(); // we do not allow that the same child is modified in the same iteration by two different // collapses as this will lead to an erroneous reduction; this can happen if both prefix and // suffix of a child share affixes from two different subsets; in order to prevent this, we // maintain a "visited" list of children. If a child appears later in another identified shared // affix, the instance will be simply ignored (and found again at some later iteration, which // is then fine). let mut visited_children: FxHashSet<Handle> = FxHashSet::default(); let branch = enumerate_branch(graph, del_subg, &v); for ((c, parents), children) in branch.into_iter() { if children.len() > 1 && (c == b'A' || c == b'C' || c == b'G' || c == b'T') { let mut children_vec: Vec<Handle> = children.into(); let mut prefix = get_shared_prefix(&children_vec, graph)?; log::debug!( "identified shared affix {} between nodes {} originating from parent(s) {}", if prefix.len() > 10 { prefix[..10].to_string() + "..." } else { prefix.clone() }, children_vec .iter() .map(v2str) .collect::<Vec<String>>() .join(","), parents.iter().map(v2str).collect::<Vec<String>>().join(",") ); let mut multiplicity: FxHashMap<Handle, usize> = FxHashMap::default(); children_vec.iter().for_each(|v| { multiplicity .entry(v.forward()) .and_modify(|m| *m += 1) .or_insert(1); }); multiplicity.into_iter().for_each(|(v, m)| { if m > 1 { let l = graph.node_len(v); if prefix.len() == l { // found palindrome! Let's remove the forward version of it log::info!("node {} is a palindrome", v.unpack_number()); // remember that children_vec is ordered, i.e., reverse followed by forward // nodes? So if the palindromic forward node is removed and replaced by the // last element (that's what swap_remove does), this order is still // maintained children_vec .swap_remove(children_vec.iter().position(|&u| u == v).unwrap()); } else if prefix.len() > l/2 { log::info!("prefix and suffix of node {} (length {}) share an overlapping match (overlap: {}bp), clipping overlap", v.unpack_number(), l, prefix.len() * 2 - l); prefix.truncate(l/2); } } }); if children_vec.len() > 1 { if children_vec .iter() .all(|x| !visited_children.contains(&x.forward())) { // add children to the list of previously visited children visited_children.extend(children_vec.iter().map(|x| x.forward())); // we are removing children if nodes are palindromes, so if only one node is left, // don't do anything res.push(AffixSubgraph { sequence: prefix, parents: parents.clone(), shared_prefix_nodes: children_vec, }); } else { log::debug!("skip shared affix because it shares children with a previous affix (will be collapsed next time)"); } } } } Ok(res) } fn collapse( graph: &mut HashGraph, shared_prefix: &AffixSubgraph, del_subg: &mut DeletedSubGraph, event_tracker: &mut CollapseEventTracker, ) -> Handle { let prefix_len = shared_prefix.sequence.len(); // update graph in two passes: // 1. split handle into shared prefix and distinct suffix and appoint dedicated shared // prefix node // 2. update deleted edge set, reassign outgoing edges of "empty" nodes to dedicated shared // prefix node // each element in splitted_node_pairs is of the form: // 1. node ID of original handle // 2. direction of original handle // 3. length of original handle // 4-5. splitted handle (IMPORTANT: that's generally not equivalent with the replacement // handles!) let mut splitted_node_pairs: Vec<(usize, Direction, usize, Handle, Option<(Handle, usize)>)> = Vec::new(); let mut shared_prefix_node: Option<Handle> = None; for v in shared_prefix.shared_prefix_nodes.iter() { let v_len = graph.node_len(*v); let node_id = v.unpack_number() as usize; let node_orient = if v.is_reverse() { Direction::Left } else { Direction::Right }; if v_len > prefix_len { // x corresponds to the shared prefix, let (x, u) = if v.is_reverse() { // apparently, rs-handlegraph does not allow splitting nodes in reverse direction let (u_rev, x_rev) = graph.split_handle(v.flip(), v_len - prefix_len); (x_rev.flip(), u_rev.flip()) } else { graph.split_handle(*v, prefix_len) }; // update dedicated shared prefix node if none has been assigned yet log::debug!( "splitting node {} into prefix {} and suffix {}", v2str(v), v2str(&x), v2str(&u) ); splitted_node_pairs.push(( node_id, node_orient, v_len, x, Some((u, graph.node_len(u))), )); match shared_prefix_node { None => { log::debug!("node {} is dedicated shared prefix node", v2str(&x)); shared_prefix_node = Some(x); } Some(w) => { // make all suffixes spring from shared suffix node if !graph.has_edge(w, u) { graph.create_edge(Edge::edge_handle(w, u)); log::debug!("create edge {}{}", v2str(&w), v2str(&u)); // mark redundant node as deleted log::debug!("flag {} as deleted", v2str(&x)); del_subg.add_node(x); } } }; } else { splitted_node_pairs.push((node_id, node_orient, v_len, *v, None)); log::debug!( "node {} matches prefix {}", v2str(v), if prefix_len > 10 { shared_prefix.sequence[..10].to_string() + "..." } else { shared_prefix.sequence.clone() } ); match shared_prefix_node { None => { log::debug!("node {} is dedicated shared prefix node", v2str(v)); shared_prefix_node = Some(*v); } Some(w) => { // if node coincides with shared prefix (but is not the dedicated shared prefix // node), then all outgoing edges of this node must be transferred to dedicated // node let outgoing_edges: Vec<Handle> = graph .neighbors(*v, Direction::Right) .filter(|u| !del_subg.edge_deleted(v, u)) .collect(); for x in outgoing_edges { if !graph.has_edge(w, x) { graph.create_edge(Edge::edge_handle(w, x)); log::debug!("create edge {}{}", v2str(&w), v2str(&x)); } } // mark redundant node as deleted log::debug!("flag {} as deleted", v2str(v)); del_subg.add_node(*v); } }; } } event_tracker.report( shared_prefix_node.unwrap(), graph.node_len(shared_prefix_node.unwrap()), &splitted_node_pairs, ); shared_prefix_node.unwrap() } fn get_shared_prefix( nodes: &[Handle], graph: &HashGraph, ) -> Result<String, std::string::FromUtf8Error> { let mut seq: Vec<u8> = Vec::new(); let sequences: Vec<Vec<u8>> = nodes.iter().map(|v| graph.sequence_vec(*v)).collect(); let mut i = 0; while sequences[0].len() > i { let c: u8 = sequences[0][i]; if sequences.iter().any(|other| { other.len() <= i || !matches!( (other[i], c), (b'A', b'A') | (b'A', b'a') | (b'a', b'A') | (b'a', b'a') | (b'C', b'C') | (b'C', b'c') | (b'c', b'C') | (b'c', b'c') | (b'G', b'G') | (b'G', b'g') | (b'g', b'G') | (b'g', b'g') | (b'T', b'T') | (b'T', b't') | (b't', b'T') | (b't', b't') ) }) { break; } seq.push(c); i += 1; } String::from_utf8(seq) } fn find_and_collapse_walk_preserving_shared_affixes<W: Write>( graph: &mut HashGraph, out: &mut io::BufWriter<W>, ) -> (DeletedSubGraph, CollapseEventTracker) { let mut del_subg = DeletedSubGraph::new(); let mut event_tracker = CollapseEventTracker::new(); let mut has_changed = true; while has_changed { has_changed = false; let mut queue: VecDeque<Handle> = VecDeque::new(); queue.extend(graph.handles().chain(graph.handles().map(|v| v.flip()))); while let Some(v) = queue.pop_front() { if !del_subg.node_deleted(&v) { log::debug!("processing oriented node {}", v2str(&v)); // process node in forward direction let affixes = enumerate_walk_preserving_shared_affixes(graph, &del_subg, v).unwrap(); for affix in affixes.iter() { has_changed |= true; // in each iteration, the set of deleted nodes can change and affect the // subsequent iteration, so we need to check the status the node every time if affix .shared_prefix_nodes .iter() .chain(affix.parents.iter()) .any(|u| del_subg.node_deleted(u)) { // push non-deleted parents back on queue queue.extend(affix.parents.iter().filter(|u| !del_subg.node_deleted(u))); } else { print(affix, out).unwrap(); if affix .parents .iter() .chain(affix.shared_prefix_nodes.iter()) .any(|&u| { event_tracker .modified_nodes .contains(&(u.unpack_number() as usize, graph.node_len(u))) }) { event_tracker.overlapping_events += 1 } let shared_prefix_node = collapse(graph, affix, &mut del_subg, &mut event_tracker); queue.push_back(shared_prefix_node); queue.push_back(shared_prefix_node.flip()); } } } } } log::info!( "identified {} shared prefixes, {} of which are overlapping, and {} of which are bubbles", event_tracker.events, event_tracker.overlapping_events, event_tracker.bubbles ); (del_subg, event_tracker) } fn transform_path( path: &[(usize, Direction, usize)], transform: &FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, ) -> Vec<(usize, Direction)> { let mut res: Vec<(usize, Direction)> = Vec::new(); for (sid, o, slen) in path.iter() { match transform.get(&(*sid, *slen)) { Some(us) => res.extend(match o { Direction::Right => us .iter() .map(|(x, y, _)| (*x, *y)) .collect::<Vec<(usize, Direction)>>(), Direction::Left => us .iter() .rev() .map(|(x, y, _)| { ( *x, if *y == Direction::Left { Direction::Right } else { Direction::Left }, ) }) .collect::<Vec<(usize, Direction)>>(), }), None => res.push((*sid, *o)), } } res } fn print_active_subgraph<W: io::Write>( graph: &HashGraph, del_subg: &DeletedSubGraph, out: &mut io::BufWriter<W>, ) -> Result<(), Box<dyn Error>> { for v in graph.handles() { if !del_subg.node_deleted(&v) { writeln!( out, "S\t{}\t{}", v.unpack_number(), String::from_utf8(graph.sequence_vec(v))? )?; } } for Edge(mut u, mut v) in graph.edges() { if u.is_reverse() && v.is_reverse() { let w = u.flip(); u = v.flip(); v = w; } if !del_subg.edge_deleted(&u, &v) { writeln!( out, "L\t{}\t{}\t{}\t{}\t0M", u.unpack_number(), if u.is_reverse() { '-' } else { '+' }, v.unpack_number(), if v.is_reverse() { '-' } else { '+' } )?; } } Ok(()) } fn check_transform( old_graph: &HashGraph, new_graph: &HashGraph, transform: &FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, del_subg: &DeletedSubGraph, ) { for ((vid, vlen), path) in transform.iter() { let path_len: usize = path.iter().map(|x| x.2).sum(); if *vlen != path_len { panic!( "length of walk {} does not sum up to that of its replacing node of {}:{}", path.iter() .map(|(rid, ro, rlen)| format!( "{}{}:{}", if *ro == Direction::Left { '<' } else { '>' }, rid, rlen )) .collect::<Vec<String>>() .join(""), vid, vlen ); } if path.len() > 1 { for i in 0..(path.len() - 1) { let u = Handle::pack(path[i].0, path[i].1 == Direction::Left); let v = Handle::pack(path[i + 1].0, path[i + 1].1 == Direction::Left); if del_subg.edge_deleted(&u, &v) { panic!( "edge {}{} is flagged as deleted new graph", v2str(&u), v2str(&v) ); } } } else { let v = Handle::pack(path[0].0, path[0].1 == Direction::Left); if del_subg.node_deleted(&v) { panic!("node {} is flagged as deleted new graph", v2str(&v)); } } // not all nodes of the transformation table are "old" nodes, but some have been created // by the affix-reduction let v = Handle::pack(*vid, false); if old_graph.has_node(v.id()) && old_graph.node_len(v) == *vlen { let old_seq = old_graph.sequence_vec(v); let new_seq = spell_walk(new_graph, path); if old_seq != new_seq { panic!( "node {} in old graph spells sequence {}, but walk {} in new graph spell sequence {}", vid, String::from_utf8(old_seq).unwrap(), path.iter() .map(|(rid, ro, _)| format!( "{}{}", if *ro == Direction::Left { '<' } else { '>' }, rid,)) .collect::<Vec<String>>() .join(""), String::from_utf8(new_seq).unwrap() ); } } } } fn print_transformations<W: Write>( transform: &FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, orig_node_lens: &FxHashMap<usize, usize>, out: &mut io::BufWriter<W>, ) -> Result<(), io::Error> { writeln!( out, "{}", ["original_node", "transformed_walk", "bp_length"].join("\t") )?; for ((vid, vlen), path) in transform.iter() { if match orig_node_lens.get(vid) { Some(l) => l == vlen, _ => false, } && (path.len() > 1 || *vid != path[0].0) { writeln!( out, "{}\t{}\t{}", vid, path.iter() .map(|(rid, ro, _)| format!( "{}{}", if *ro == Direction::Left { '<' } else { '>' }, rid, )) .collect::<Vec<String>>() .join(""), vlen )?; } } Ok(()) } fn spell_walk(graph: &HashGraph, walk: &[(usize, Direction, usize)]) -> Vec<u8> { let mut res: Vec<u8> = Vec::new(); let mut prev_v: Option<Handle> = None; for (i, (sid, o, _)) in walk.iter().enumerate() { let v = Handle::pack(*sid, *o != Direction::Right); if i >= 1 && !graph.has_edge(prev_v.unwrap(), v) { panic!("graph does not have edge {:?}-{:?}", &walk[i - 1], &walk[i]); } res.extend(graph.sequence_vec(v)); prev_v = Some(v); } res } fn print<W: io::Write>(affix: &AffixSubgraph, out: &mut io::BufWriter<W>) -> Result<(), io::Error> { let parents: Vec<String> = affix.parents.iter().map(v2str).collect(); let children: Vec<String> = affix.shared_prefix_nodes.iter().map(v2str).collect(); writeln!( out, "{}\t{}\t{}\t{}", parents.join(","), children.join(","), affix.sequence.len(), &affix.sequence, )?; Ok(()) } fn parse_and_transform_paths<W: io::Write, T: OptFields>( gfa: &GFA<usize, T>, orig_node_lens: &FxHashMap<usize, usize>, transform: &FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, out: &mut io::BufWriter<W>, ) -> Result<(), Box<dyn Error>> { for path in gfa.paths.iter() { log::debug!("transforming path {}", str::from_utf8(&path.path_name)?); let tpath = transform_path( &path .iter() .map(|(sid, o)| { ( sid, match o { Orientation::Forward => Direction::Right, Orientation::Backward => Direction::Left, }, *orig_node_lens.get(&sid).unwrap(), ) }) .collect::<Vec<(usize, Direction, usize)>>()[..], transform, ); writeln!( out, "P\t{}\t{}\t{}", str::from_utf8(&path.path_name)?, tpath .iter() .map(|(sid, o)| format!( "{}{}", sid, if *o == Direction::Right { '+' } else { '-' } )) .collect::<Vec<String>>() .join(","), path.overlaps .iter() .map(|x| match x { None => "*".to_string(), Some(c) => c.to_string(), }) .collect::<Vec<String>>() .join("") )?; } Ok(()) } fn parse_and_transform_walks<W: io::Write, R: io::Read>( mut data: io::BufReader<R>, // graph: &HashGraph, transform: FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, orig_node_lens: &FxHashMap<usize, usize>, // del_subg: &DeletedSubGraph, out: &mut io::BufWriter<W>, ) -> Result<(), Box<dyn Error>> { let reader = Csv::from_reader(&mut data) .delimiter(b'\t') .flexible(true) .has_header(false); for row in reader { let row = row.unwrap(); let mut row_it = row.bytes_columns(); if [b'W'] == row_it.next().unwrap() { let sample_id = str::from_utf8(row_it.next().unwrap())?; let hap_idx = str::from_utf8(row_it.next().unwrap())?; let seq_id = str::from_utf8(row_it.next().unwrap())?; let seq_start = str::from_utf8(row_it.next().unwrap())?; let seq_end = str::from_utf8(row_it.next().unwrap())?; let walk_ident = format!( "{}#{}#{}:{}-{}", sample_id, hap_idx, seq_id, seq_start, seq_end ); log::debug!("transforming walk {}", walk_ident); let walk_data = row_it.next().unwrap(); let mut walk: Vec<(usize, Direction, usize)> = Vec::new(); let mut cur_el: Vec<u8> = Vec::new(); for c in walk_data { if (c == &b'>' || c == &b'<') && !cur_el.is_empty() { let sid = usize::from_str(str::from_utf8(&cur_el[1..])?)?; let o = match cur_el[0] { b'>' => Direction::Right, b'<' => Direction::Left, _ => panic!( "unknown orientation '{}' of segment {} in walk {}", cur_el[0], sid, walk_ident ), }; walk.push((sid, o, *orig_node_lens.get(&sid).unwrap())); cur_el.clear(); } cur_el.push(*c); } if !cur_el.is_empty() { let sid = usize::from_str(str::from_utf8(&cur_el[1..])?)?; let o = match cur_el[0] { b'>' => Direction::Right, b'<' => Direction::Left, _ => panic!( "unknown orientation '{}' of segment {} in walk {}", cur_el[0], sid, walk_ident ), }; walk.push((sid, o, *orig_node_lens.get(&sid).unwrap())); } let tpath = transform_path(&walk, &transform); // check_path(graph, del_subg, &tpath); writeln!( out, "W\t{}\t{}\t{}\t{}\t{}\t{}", sample_id, hap_idx, seq_id, seq_start, seq_end, tpath .iter() .map(|(sid, o)| format!( "{}{}", if *o == Direction::Right { '>' } else { '<' }, sid )) .collect::<Vec<String>>() .join("") )?; } } Ok(()) } fn parse_header<R: io::Read>(mut data: io::BufReader<R>) -> Result<Vec<u8>, io::Error> { let mut buf = vec![]; while data.read_until(b'\n', &mut buf)? > 0 { if buf[0] == b'H' { // remove trailing new line character if buf.last() == Some(&b'\n') { buf.pop(); } break; } } Ok(buf) } fn count_copies( visited_nodes: &mut FxHashMap<usize, usize>, visited_edges: &mut FxHashMap<Edge, usize>, path: &Vec<(usize, Direction)>, ) { for i in 1..path.len() { let (u, ou) = path[i - 1]; let (v, ov) = path[i]; visited_nodes.get_mut(&u).map(|x| *x += 1); let e = Edge::edge_handle( Handle::pack(u, ou == Direction::Left), Handle::pack(v, ov == Direction::Left), ); visited_edges.get_mut(&e).map(|x| *x += 1); } if let Some((v, _)) = path.last() { visited_nodes.get_mut(&v).map(|x| *x += 1); } } fn remove_unused_copies<R: io::Read, T: OptFields>( copies: &Vec<usize>, graph: &HashGraph, mut data: io::BufReader<R>, gfa: &GFA<usize, T>, orig_node_lens: &FxHashMap<usize, usize>, transform: &FxHashMap<(usize, usize), Vec<(usize, Direction, usize)>>, del_subg: &mut DeletedSubGraph, ) -> (usize, usize) { // construct hashmap for counting the visits of edges introduced by the duplication process let mut visited_edges = FxHashMap::default(); for i in copies.iter() { let v = Handle::pack(*i, false); for w in graph.neighbors(v, Direction::Left) { visited_edges.insert(Edge::edge_handle(w, v), 0); } for w in graph.neighbors(v, Direction::Right) { visited_edges.insert(Edge::edge_handle(v, w), 0); } } // construct hashmap to count visits to nodes let mut visited_nodes: FxHashMap<usize, usize> = FxHashMap::from_iter(copies.iter().cloned().zip(repeat(0))); for path in gfa.paths.iter() { let tpath = transform_path( &path .iter() .map(|(sid, o)| { ( sid, match o { Orientation::Forward => Direction::Right, Orientation::Backward => Direction::Left, }, *orig_node_lens.get(&sid).unwrap(), ) }) .collect::<Vec<(usize, Direction, usize)>>()[..], transform, ); count_copies(&mut visited_nodes, &mut visited_edges, &tpath); } let reader = Csv::from_reader(&mut data) .delimiter(b'\t') .flexible(true) .has_header(false); for row in reader { let row = row.unwrap(); let mut row_it = row.bytes_columns(); if [b'W'] == row_it.next().unwrap_or(&[b'$']) { let walk_data = row_it.nth(5).unwrap(); let mut walk: Vec<(usize, Direction, usize)> = Vec::new(); let mut cur_el: Vec<u8> = Vec::new(); for c in walk_data { if (c == &b'>' || c == &b'<') && !cur_el.is_empty() { let sid = usize::from_str(str::from_utf8(&cur_el[1..]).unwrap()).unwrap(); let o = match cur_el[0] { b'>' => Direction::Right, b'<' => Direction::Left, _ => panic!("unknown orientation '{}' of segment {}", cur_el[0], sid), }; walk.push((sid, o, *orig_node_lens.get(&sid).unwrap())); cur_el.clear(); } cur_el.push(*c); } if !cur_el.is_empty() { let sid = usize::from_str(str::from_utf8(&cur_el[1..]).unwrap()).unwrap(); let o = match cur_el[0] { b'>' => Direction::Right, b'<' => Direction::Left, _ => panic!("unknown orientation '{}' of segment {}", cur_el[0], sid), }; walk.push((sid, o, *orig_node_lens.get(&sid).unwrap())); } let tpath = transform_path(&walk, &transform); count_copies(&mut visited_nodes, &mut visited_edges, &tpath); } } // counters for removed nodes and edges let mut cv = 0; let mut ce = 0; for (i, c) in visited_nodes.iter() { if *c == 0 { log::debug!("Removing unused duplicate node {}", i); del_subg.add_node(Handle::pack(*i, false)); cv += 1; } } for (Edge(u, v), c) in visited_edges.iter() { if *c == 0 { log::debug!("Removing unused duplicate edge {}{}", v2str(u), v2str(v)); // we don't need Edge::edge_handle here, because edges in visited_edges are already // canonical del_subg.add_edge(Edge(*u, *v)); ce += 1; } } (cv, ce) } fn main() -> Result<(), io::Error> { env_logger::init(); // print output to stdout let mut out = io::BufWriter::new(std::io::stdout()); // initialize command line parser & parse command line arguments let params = Command::parse(); // check if regex of no_collapse_path is valid if !params.no_collapse_path.trim().is_empty() && Regex::new(&params.no_collapse_path).is_err() { panic!( "Supplied string \"{}\" is not a valid regular expression", params.no_collapse_path ); } log::info!("loading graph {}", &params.graph); let parser = GFAParser::new(); let gfa: GFA<usize, ()> = parser.parse_file(&params.graph).unwrap(); log::info!("constructing handle graph"); let mut graph = HashGraph::from_gfa(&gfa); log::info!( "handlegraph has {} nodes and {} edges", graph.node_count(), graph.edge_count() ); log::info!("storing length of original nodes for bookkeeping"); let mut node_lens: FxHashMap<usize, usize> = FxHashMap::default(); node_lens.reserve(graph.node_count()); for v in graph.handles() { node_lens.insert(v.unpack_number() as usize, graph.node_len(v)); } let mut dont_collapse_nodes: FxHashSet<(usize, usize)> = FxHashSet::default(); if !params.no_collapse_path.trim().is_empty() { let re = Regex::new(&params.no_collapse_path).unwrap(); for path_id in graph.paths.keys() { let path_name_vec = graph.get_path_name_vec(*path_id).unwrap(); let path_name = str::from_utf8(&path_name_vec[..]).unwrap(); if re.is_match(path_name) { let path = graph.get_path(path_id).unwrap(); dont_collapse_nodes.extend(path.nodes.iter().map(|&x| { let xid = x.unpack_number() as usize; (xid, *node_lens.get(&xid).unwrap()) })); log::info!( "flagging nodes of path {} as non-collapsing, total number is now at {}", path_name, dont_collapse_nodes.len() ); } } } // // REMOVING PATHS FROM GRAPH -- they SUBSTANTIALLY slow down graph editing // graph.paths.clear(); log::info!("identifying walk-preserving shared affixes"); // yes, that's a "prefix", not an affix--because nodes are oriented accordingly writeln!( out, "{}", [ "oriented_parent_nodes", "oriented_child_nodes", "prefix_length", "prefix", ] .join("\t") )?; let (mut del_subg, mut event_tracker) = find_and_collapse_walk_preserving_shared_affixes(&mut graph, &mut out); if !dont_collapse_nodes.is_empty() { log::info!("de-collapse no-collapse handles and update transformation table"); let copies = event_tracker.decollapse(&mut graph, dont_collapse_nodes); let data = io::BufReader::new(fs::File::open(&params.graph)?); log::info!("cleaning up copies created during de-duplication..."); let (cv, ce) = remove_unused_copies( &copies, &graph, data, &gfa, &node_lens, &event_tracker.get_expanded_transformation(), &mut del_subg, ); log::info!("...removed {} unused duplicated nodes and {} edges", cv, ce); } log::info!("expand transformation table"); let transform = event_tracker.get_expanded_transformation(); if params.check_transformation { log::info!("checking correctness of applied transformations..."); let old_graph = HashGraph::from_gfa(&gfa); check_transform(&old_graph, &graph, &transform, &del_subg); log::info!("all correct!"); } if !params.transformation_out.trim().is_empty() { log::info!("writing transformations to {}", params.transformation_out); let mut trans_out = io::BufWriter::new(fs::File::create(params.transformation_out.clone())?); if let Err(e) = print_transformations(&transform, &node_lens, &mut trans_out) { panic!("unable to write graph transformations to stdout: {}", e); } } if !params.refined_graph_out.trim().is_empty() { log::info!("writing refined graph to {}", params.refined_graph_out); let mut graph_out = io::BufWriter::new(fs::File::create(params.refined_graph_out.clone())?); let data = io::BufReader::new(fs::File::open(&params.graph)?); let header = parse_header(data)?; writeln!( graph_out, "{}", if header.is_empty() { "H\tVN:Z:1.1" } else { str::from_utf8(&header[..]).unwrap() } )?; if let Err(e) = print_active_subgraph(&graph, &del_subg, &mut graph_out) { panic!( "unable to write refined graph to {}: {}", params.refined_graph_out, e ); } log::info!("transforming paths"); if let Err(e) = parse_and_transform_paths(&gfa, &node_lens, &transform, &mut graph_out) { panic!( "unable to write refined GFA path lines to {}: {}", params.refined_graph_out, e ); }; log::info!("transforming walks"); let data = io::BufReader::new(fs::File::open(&params.graph)?); if let Err(e) = parse_and_transform_walks(data, transform, &node_lens, &mut graph_out) { panic!( "unable to parse or write refined GFA walk lines to {}: {}", params.refined_graph_out, e ); } } out.flush()?; log::info!("done"); Ok(()) } <file_sep>/README.md [![Rust Build](https://github.com/marschall-lab/GFAffix/actions/workflows/rust_build.yml/badge.svg)](https://github.com/marschall-lab/GFAffix/actions/workflows/rust_build.yml) [![Anaconda-Server Badge](https://anaconda.org/bioconda/gfaffix/badges/version.svg)](https://conda.anaconda.org/bioconda) [![Anaconda-Server Badge](https://anaconda.org/bioconda/gfaffix/badges/platforms.svg)](https://anaconda.org/bioconda/gfaffix) [![Anaconda-Server Badge](https://anaconda.org/bioconda/gfaffix/badges/license.svg)](https://anaconda.org/bioconda/gfaffix) # GFAffix ![GFAffix collapses walk-preserving shared affixes](doc/gfaffix-illustration.png?raw=true "GFAffix collapses walk-preserving shared affixes") GFAffix identifies walk-preserving shared affixes in variation graphs and collapses them into a non-redundant graph structure. # Dependencies `GFAffix` is written in RUST and requires a working RUST build system for installation. See [https://www.rust-lang.org/tools/install](https://www.rust-lang.org/tools/install) for more details. It makes use of the following crates: * clap * env\_logger * gfa * handlegraph * log * quick-csv * regex * rustc-hash ## Installation ### From bioconda channel Make sure you have [conda](https://conda.io) installed! ``` conda install -c bioconda gfaffix ``` ### From binary release #### Linux x86\_64 ``` wget --no-check-certificate -c https://github.com/marschall-lab/GFAffix/releases/download/0.1.5/GFAffix-0.1.5_linux_x86_64.tar.gz tar -xzvf GFAffix-0.1.5_linux_x86_64.tar.gz # you are ready to go! ./GFAffix-0.1.5_linux_x86_64/gfaffix ``` #### MacOS X arm64 ``` wget --no-check-certificate -c https://github.com/marschall-lab/GFAffix/releases/download/0.1.5/GFAffix-0.1.5_macos_x_arm64.tar.gz tar -xzvf GFAffix-0.1.5_macos_x_arm64.tar.gz # you are ready to go! ./GFAffix-0.1.5_macos_x_arm64/gfaffix ``` ### From repository ``` # install GFAffix git clone https://github.com/marschall-lab/GFAffix.git # build program cargo build --manifest-path GFAffix/Cargo.toml --release ``` ## Command Line Interface ``` $ gfaffix --help gfaffix 0.1.5 <NAME> <<EMAIL>> Discover walk-preserving shared prefixes in multifurcations of a given graph. - Do you want log output? Call program with 'RUST_LOG=info gfaffix ...' - Log output not informative enough? Try 'RUST_LOG=debug gfaffix ...' USAGE: gfaffix [OPTIONS] <GRAPH> ARGS: <GRAPH> graph in GFA1 format OPTIONS: -c, --check_transformation Verifies that the transformed parts of the graphs spell out the identical sequence as in the original graph. Only for debugging purposes -h, --help Print help information -o, --output_refined <REFINED_GRAPH_OUT> Write refined graph in GFA1 format to supplied file [default: " "] -t, --output_transformation <TRANSFORMATION_OUT> Report original nodes and their corresponding walks in refined graph to supplied file [default: " "] -V, --version Print version information -x, --dont_collapse <NO_COLLAPSE_PATH> Do not collapse nodes on a given paths ("P" lines) that match given regular expression [default: " "] ``` ## Execution ``` RUST_LOG=info gfaffix examples/example1.gfa -o example1.gfa -t example1.trans > example1.shared_affixes ``` <file_sep>/src/deleted_sub_graph.rs use handlegraph::handle::{Edge, Handle}; use rustc_hash::FxHashSet; #[derive(Clone, Debug)] pub struct DeletedSubGraph { pub nodes: FxHashSet<Handle>, pub edges: FxHashSet<Edge>, } impl DeletedSubGraph { pub fn add_node(&mut self, v: Handle) -> bool { if v.is_reverse() { self.nodes.insert(v.flip()) } else { self.nodes.insert(v) } } pub fn add_edge(&mut self, e: Edge) -> bool { self.edges.insert(e) } pub fn edge_deleted(&self, u: &Handle, v: &Handle) -> bool { let mut res = self.edges.contains(&Edge::edge_handle(*u, *v)); res |= if u.is_reverse() { self.nodes.contains(&u.flip()) } else { self.nodes.contains(u) }; if v.is_reverse() { res |= self.nodes.contains(&v.flip()); } else { res |= self.nodes.contains(v); } res } pub fn node_deleted(&self, v: &Handle) -> bool { if v.is_reverse() { self.nodes.contains(&v.flip()) } else { self.nodes.contains(v) } } pub fn new() -> Self { DeletedSubGraph { nodes: FxHashSet::default(), edges: FxHashSet::default(), } } } <file_sep>/src/affix_sub_graph.rs use handlegraph::handle::Handle; // structure for storing reported subgraph pub struct AffixSubgraph { pub sequence: String, pub parents: Vec<Handle>, pub shared_prefix_nodes: Vec<Handle>, } <file_sep>/Cargo.toml [package] name = "gfaffix" version = "0.1.5" authors = ["<NAME> <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] clap = {version = "4.3", features = [ "derive" ] } rustc-hash = "1" regex = "1" handlegraph = "0.7.0-alpha.9" gfa = "0.10" quick-csv = "0.1.6" rayon = "1" # Logging and error management log = "0.4" env_logger = "0.10" [profile.release] debug = true
f755a9c82c6092ae664880f8f635425ca458d0e9
[ "Markdown", "Rust", "TOML" ]
6
Rust
marschall-lab/GFAffix
672bad7fa5f1de0315f7b2379780afa1bd53bbca
83c6a2ba1243971638c349149dc81adb0f794d48
refs/heads/master
<file_sep># ATR2 Test functions # Date import unittest from ATR2 import max_shown ''' #CONSTANTS progname = 'AT-Robots' version = '2.11' cnotice1 = 'Copyright 1997 ''99, <NAME>' cnotice2 = 'All Rights Reserved.' cnotice3 = 'Copyright 2014, William "<NAME>' main_filename = 'ATR2' robot_ext = '.AT2' locked_ext = '.ATL' config_ext = '.ATS' compile_ext = '.CMP' report_ext = '.REP' _T = True _F = False minint = -32768 # maxint=32787 is alrady defined by turbo pascal # robots max_robots = 31 # starts at 0, so total is max_robots+1 max_code = 1023 # same here max_op = 3 # etc... stack_size = 256 stack_base = 768 max_ram = 1023 # but this does start at 0 (odd #, 2^n-1) max_vars = 256 max_labels = 256 acceleration = 4 turn_rate = 8 max_vel = 4 max_missiles = 1023 missile_spd = 32 hit_range = 14 blast_radius = 25 crash_range = 8 max_sonar = 250 com_queue = 512 max_queue = 255 max_config_points= 12 max_mines = 63 mine_blast = 35 # simulator & graphics screen_scale = 0.46 screen_x = 5 screen_y = 5 robot_scale = 06 # What is this?????? //ASK default_delay = 20 default_slice = 05 # What is this?????? //ASK mine_circle = trunc(mine_blast*screen_scale)+1 blast_circle = trunc(blast_radius*screen_scale)+1 mis_radius = trunc(hit_range/2)+1 max_robot_lines = 8 #Gray50 : FillPatternType = ($AA, $55, $AA, $55, $AA, $55, $AA, $55) # //ASK ''' # FUNCTIONS START!!!!!! ''' def init_function_test(): # Calls init() A.init() # Tests variables print("step_mode: " + step_mode) print("logging_errors: " + logging_errors) print("stats_mode: " + stats_mode) print("insane_missiles: " + insane_missiles) print("insanity: " + insanity) print("windoze: " + windoze) print("graphix: " + graphix) print("no_gfx: " + no_gfx) print("sound_on: " + sound_on) print("timing: " + timing) print("matches: " + matches) print("played: " + played) print("old_shields: " + old_shields) # print("quit: " + quit) # Problem????? print("compile_only: " + compile_only) print("show_arcs: " + show_arcs) print("debug_info: " + debug_info) print("show_cnotice: " + show_cnotice) print("show_source: " + show_source) print("report: " + report) print("kill_count: " + kill_count) print("maxcode: " + maxcode) # Function calls #make_tables() # IS IN ATR2FUNC, CREATES the arrays that contain Sint and Cost values #randomize() # NOt in any of the files for the game, must be in a library somewhere print("num_robots: " + num_robots) print("game_limit:" + game_limit) print("game_cycle: " + game_cycle) print("game_delay: " + game_delay) print("time_slice: " + time_slice) print("registered: " + registered) print("reg_name: " + reg_name) print("reg_num: " + reg_num) def test_operand(): def test_mnemonic(n, m): a = A.mnemonic(n, m) print(a) print('alph') # b = A.mnemonic(1, 1) # print(b) if (a == 'NOP'): print('Pass') else: print('Fail') test_mnemonic(00, 0) ''' class TestMaxShown(unittest.TestCase): def test_max_shown(self): a = max_shown(1) self.assertEqual(a, 6) if __name__ == '__main__': unittest.main() ''' def test_log_error(): #Procedure def test_graph_check(): def test_robot_graph(): def test_update_armor(): def test_update_heat(): def test_robot_error(): def test_update_lives(): def test_update_cycle_window(): def test_setscreen(): def test_graph_mode(): def test_prog_error(): def test_print_code(): def test_parse1(): def test_check_plen(): def test_compile(): def test_robot_config(): def test_reset_software(): def test_reset_hardware(): def test_init_robot(): def test_create_robot(): def test_shutdown(): def test_delete_compile_report(): def test_write_compile_report(): def test_parse_param(): def test_init(): def test_draw_robot(): def test_get_from_ram(): def test_get_val(): def test_put_val(): def test_push(): def test_pop(): def test_find_label(): def test_init_mine(): def test_count_missiles(): def test_init_missile(): def test_damage(): def test_scan(): def test_com_transmit(): def test_com_receive(): def test_in_port(): def test_out_port(): def test_call_int(): def test_jump(): def test_update_debug_bars(): def test_update_debug_system(): def test_update_debug_registers(): def test_update_debug_flags(): def test_update_debug_memory(): def test_update_debug_code(): def test_update_debug_window(): def test_init_debug_window(): def test_close_debug_window(): def test_gameover(): def test_toggle_graphix(): def test_invalid_microcode(): def test_process_keypress(): def test_execute_instruction(): def test_do_robot(): def test_do_mine(): def test_do_missile(): def test_victor_string(): def test_show_statistics(): def test_score_robots(): def test_init_bout(): def test_bout(): def test_write_report(): def test_begin_window(): def test_main(): ''' <file_sep># omurice CS 370 - Software Engineering Team Name - Omurice Team Members - <NAME> <NAME> <NAME> Goal: Port the game AT-Robots from Turbo Pascal 6 to Python<file_sep>#2 moving Triangles: 1 moves with keys, 1 bounces off screen import pygame pygame.init()#initialize pygame size = width, height = 400 , 300#screen size may be changed screen = pygame.display.set_mode((size))#create screen logo = pygame.image.load("T-ROBOTS.bmp") #need to have file and proper path to file for this to work icon = pygame.display.set_icon(logo)#puts icon in corner pygame.display.set_caption('AT-Robots')#names window #colors used black = (0, 0, 0) blue = (0, 128, 255) pink = (191, 63, 63) #coordinates for blue triangle (moved with arrow keys) a = 100 b = 100 c = 150 d = 100#could possibly be the same as b e = 125 f = 50 #triangle points for pink triangle (moved automatically - bounces) h = 200 i = 200 j = 250 k = 200 l = 225 m = 150 x = 225#mid point of triangle y = 175#mid point of triangle xR = 1#triangle moving right yD = 1#triangle moving down wallTouch = 0#wall not touched yet done = False#window not closed clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill(black)#screen is black except for shapes pygame.draw.polygon(screen, blue, [[a, b], [c, d], [e, f]], 2)#blue triangle moves with keys press = pygame.key.get_pressed()#moves blue triangle using keyboard if press[pygame.K_UP]: b -= 3; d -= 3; f -= 3 if press[pygame.K_DOWN]: b += 3; d += 3; f += 3 if press[pygame.K_RIGHT]: a += 3; c += 3; e += 3 if press[pygame.K_LEFT]: a -= 3; c -= 3; e -= 3 #pygame.draw.rect(screen, pink, [x, y, 60, 60], 2)#rectangle test shape pygame.draw.polygon(screen, pink, [[h, i], [j, k], [l, m]], 2)#pink triangle bounces off screen if x < 25: wallTouch = 0#wall not touched or left wall touched last if y > height - 25: wallTouch = 1#bottom wall touched last if x > width - 25: wallTouch = 2#right wall touched last if y < 25: wallTouch = 3#top wall touched last if wallTouch == 0 and yD == 1:#touched left moving down x += 3 h += 3 j += 3 l += 3 y += 3 i += 3 k += 3 m += 3 xR = 1 yD = 1 if wallTouch == 1 and xR == 1:#touched bottom moving right x += 3 h += 3 j += 3 l += 3 y -= 3 i -= 3 k -= 3 m -= 3 xR = 1 yD = 0 if wallTouch == 2 and yD == 0:#touched right moving up x -= 3 h -= 3 j -= 3 l -= 3 y -= 3 i -= 3 k -= 3 m -= 3 xR = 0 yD = 0 if wallTouch == 3 and xR == 0:#touched top moving left x -= 3 h -= 3 j -= 3 l -= 3 y += 3 i += 3 k += 3 m += 3 xR = 0 yD = 1 if wallTouch == 3 and xR == 1:#touched top moving right x += 3 h += 3 j += 3 l += 3 y += 3 i += 3 k += 3 m += 3 xR = 1 yD = 1 if wallTouch == 2 and yD == 1:#touched right moving down x -= 3 h -= 3 j -= 3 l -= 3 y += 3 i += 3 k += 3 m += 3 xR = 0 yD = 1 if wallTouch == 1 and xR == 0:#touched bottom moving left x -= 3 h -= 3 j -= 3 l -= 3 y -= 3 i -= 3 k -= 3 m -= 3 xR = 0 yD = 0 if wallTouch == 0 and yD == 0:#touched left moving up x += 3 h += 3 j += 3 l += 3 y -= 3 i -= 3 k -= 3 m -= 3 xR = 1 yD = 0 pygame.display.flip()#necessary for movement clock.tick(30)#slows down movement to reasonable speed pygame.quit()#prevents error on closing program <file_sep>#!/usr/bin/python import os import math # globals: delay_per_sec = 0 registered = False graphix = False sound_on = False reg_name = '' reg_num = 0 sint = [0 for i in range(0, 256)] cost = [0 for i in range(0, 256)] # def textxy(x,y,s) GRAPHICAL # def coltextxy(x,y,s,c) GRAPHICAL # convert a 4 bit unsigned int to a hex string def hexnum(num): if num == 0: return '0' elif num == 1: return '1' elif num == 2: return '2' elif num == 3: return '3' elif num == 4: return '4' elif num == 5: return '5' elif num == 6: return '6' elif num == 7: return '7' elif num == 8: return '8' elif num == 9: return '9' elif num == 10: return 'A' elif num == 11: return 'B' elif num == 12: return 'C' elif num == 13: return 'D' elif num == 14: return 'E' elif num == 15: return 'F' else: return 'X' # convert an 8 bit unsigned int to a hex string def hexb(num): return hexnum(num >> 4) + hexnum(num & 15) # convert a 16 bit unsigned int to a hex string def hex(num): # num:word return hexb(int(num) >> 8) + hexb(int(num) & 255) # casts a string to int, returns 0 if unsuccessful def valuer(i): # i:string try: return int(i) except: return 0 # typecast used in old code from int to longint def value(i): return i # typecast a value (originally just a real) to a string def cstrr(i): return str(i) # identical to cstrr in Python def cstr(i): return str(i) # pad an int n to be l characters long, returns a string def zero_pad(n,l): s = cstr(n) while len(s) < l: s = '0' + s return s # identical to zero_pad in Python def zero_pads(s,l): return zero_pad(s,l) # add spaces to the left of string b to make it length l def addfront(b,l): while len(b) < l: b = ' ' + b return b # add spaces to the right of string b to make it length l def addrear(b,l): while len(b) < l: b = b + ' ' return b # make string s uppercase def ucase(s): return s.upper() # make string s lowercase def lcase(s): return s.lower() # return a string of spaces of length i def space(i): s = '' if i > 0: for k in range(0,i): s = s + ' ' return s # return a string of character c of length i def repchar(c,i): s = '' if i > 0: for k in range(0,i): s = s + c return s # trim off the left whitespace def ltrim(s1): return s1.lstrip() # trim off the right whitespace def rtrim(s1): return s1.rstrip() # trim off whitespace from both sides def btrim(s1): return ltrim(rtrim(s1)) # return a string of the l leftmost characters def lstr(s1,l): if len(s1) <= 1: return s1 else: return s1[0:l] # return a string of the l rightmost characters def rstr(s1,l): if len(s1) <= l: return s1 else: return s1[-l:] # def FlushKey: # not needed in Python # def calibrate_timing() GRAPHICAL # def time_delay(n) GRAPHICAL # THE ORIGINAL EDITS A GLOBAL VARIABLE THAT'S NEVER DECLARED IN THE FILE, THIS RETURNS A BOOLEAN # checks validity of the ATR2.REG file def check_registration(): registered = False if os.path.isfile('ATR2.REG'): f = open('ATR2.REG','r') reg_name = f.readline() reg_num = f.readline() f.close() w = 0 s = btrim(reg_name.upper()) for i in s: print(i) w = w + ord(i) w = w ^ 0x5AA5 if w == reg_num: registered = True return registered # rolls the bits in n left k times def rol(n,k): s = _bin(n) k = k % len(s) return s[k:] + s[:k] # rolls the bits in n right k times def ror(n,k): s = _bin(n) if k > len(s): return len(s) * '0' return s[len(s)-k:] + s[:len(s)-k] # shifs the bits in n left k times def sal(n,k): s = _bin(n) if k > len(s): return len(s) * '0' return s[k:] + k * '0' # shifts the bits in n right k times def sar(n,k): s = _bin(n) if k > len(s): return len(s) * '0' return k * '0' + s[:-k] # GRAPHICAL FUNCTIONS def viewport(x1,y1,x2,y2): pass def main_viewport(): viewport(5,5,474,474) # calculates sine and cosine tables def make_tables(): for i in range(0,256): sint[i] = math.sin(i/128*math.pi) cost[i] = math.cos(i/128*math.pi) # a lookup for determining color values def robot_color(n): # n:integer k = 7 m = n % 14 if m == 0: k = 10 elif m == 1: k = 12 elif m == 2: k = 9 elif m == 3: k = 11 elif m == 4: k = 13 elif m == 5: k = 14 elif m == 6: k = 7 elif m == 7: k = 6 elif m == 8: k = 2 elif m == 9: k = 4 elif m == 10: k = 1 elif m == 11: k = 3 elif m == 12: k = 5 elif m == 13: k = 15 else: k = 15 return k # graphical functions # def box(x1,y1,x2,y2) # def hole(x1,y1,x2,y2) # def chirp() # def click() # takes a string hex character to an integer def hex2int(s): # s:string i = 0 w = 0 while i < len(s): if s[i] == '0': w = (w << 4) | 0x0 elif s[i] == '1': w = (w << 4) | 0x1 elif s[i] == '2': w = (w << 4) | 0x2 elif s[i] == '3': w = (w << 4) | 0x3 elif s[i] == '4': w = (w << 4) | 0x4 elif s[i] == '5': w = (w << 4) | 0x5 elif s[i] == '6': w = (w << 4) | 0x6 elif s[i] == '7': w = (w << 4) | 0x7 elif s[i] == '8': w = (w << 4) | 0x8 elif s[i] == '9': w = (w << 4) | 0x9 elif s[i] == 'A': w = (w << 4) | 0xA elif s[i] == 'B': w = (w << 4) | 0xB elif s[i] == 'C': w = (w << 4) | 0xC elif s[i] == 'D': w = (w << 4) | 0xD elif s[i] == 'E': w = (w << 4) | 0xE elif s[i] == 'F': w = (w << 4) | 0xF else: i = len(s) i = i + 1 return w # converts a string to an integer def str2int(s): s = btrim(s.upper()) print('s:'+s) if s == '': return 0 if s[0] == '-': neg = True s = rstr(s,len(s)) k = 0 print(rstr(s,1)) if lstr(s,2) == '0X': k = hex2int(rstr(s,len(s)-2)) elif rstr(s,1) == 'H': k = hex2int(lstr(s,len(s)-1)) else: k = value(s) return k # returns the distance between two ordinal values def distance(x1,y1,x2,y2): # real return abs(math.sqrt(((y1-y2) ** 2) + ((x1 - x2) ** 2))) # needs review: what do the input variables mean? def find_angle(xx,yy,tx,ty): # all reals in original code q = 0 v = abs(round(tx-xx)) if v == 0: if (tx == xx) and (ty > yy): q = math.pi elif (tx == xx) and (ty < yy): q = 0 z = abs(round(ty - yy)) q = abs(math.atan(z / v)) if (tx > xx) and (ty > yy): q = math.pi / (2 + q) elif (tx > xx) and (ty < yy): q = math.pi / (2 - q) elif (tx < xx) and (ty < yy): q = (pi + math.pi) / (2 + q) elif (tx < xx) and (ty > yy): q = (math.pi + math.pi) / (2 - q) elif (tx == xx) and (ty > yy): q = math.pi / 2 elif (tx == xx) and (ty < yy): q = 0 elif (tx < xx) and (ty == yy): q = (pi + math.pi) / 2 elif (tx > xx) and (ty == yy): q = math.pi / 2 return q # needs review: no idea what this does at all but I'm fairly sure it's correct def find_anglei(xx,yy,tx,ty): i = round(find_angle(xx,yy,tx,ty) / math.pi * 128 + 256) while (i < 0): i = i + 256 i = i & 255 return i # returns a string representing the 16 bit value of integer n def _bin(n): bin_string = '' for i in range(0,16): if (n % 2) == 0: bin_string = '0' + bin_string else: bin_string = '1' + bin_string n = n // 2 return bin_string # returns a string containing num padded with 0 to size length def decimal(num,length): # this can also be achieved by zero_pad(num,length) dec_string = '' print(num) for i in range(0,length): dec_string = chr((int(num % 10)) + 48) + dec_string num = num / 10 return dec_string <file_sep>#!/usr/bin/python3 # Copyright 2018 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> # Permission is hereby granted, free of charge, to any person obtainning a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Python3 port of ATRLOCK.PAS ### # TODO: # Change software license to original # Implement a filename validation function valid() # # Encryption algoritm not identical to ATRLOCK.EXE output # - The logic of this program is equivalent to ATRLOCK.PAS # - To get this to work, we need to figure out how '#' and 'V' makes '7' import os, random, sys, time # REMOVE AFTER PORT IS COMPLETED import pdb from subprocess import call call(['rm','SNIPER.ATL']) LOCKTYPE = 3 lock_code = 0 lock_pos = 0 lock_dat = 0 def encode(s): global lock_pos global lock_code global lock_dat if lock_code != '': t = '' for i in s: lock_pos += 1 if lock_pos > len(lock_code): lock_pos = 0 if ((ord(i) in range(0,32)) or (ord(i) in range(128,256))): i = ' ' this_dat = ord(i) & 15 t = t + chr((ord(i) ^ (ord(lock_code[lock_pos - 1]) ^ lock_dat)) + 1) lock_dat = this_dat return t def prepare(s1): s = '' # remove comments if (len(s1) == 0) or (s1[0] == ';'): s1 = '' else: k = 0 for i in enumerate(reversed(s1),k): if i == ';': k = i if k > 0: s1 = s1[k - 1] # remove excess spaces s2 = '' for i in s1: if not (i in [' ','\b','\t','\n',',']): s2 = s2 + i elif s2 != '': s = s + s2 + ' ' s2 = '' if s2 != '': s = s + s2 return s def write_line(s1): s = prepare(s1) if len(s) > 0: s = encode(s) f2.write(s + '\n') random.seed(time.time()) lock_pos = 0 lock_dat = 0 if (len(sys.argv) < 2) | (len(sys.argv) > 4): print('Usage: ATRLOCK <robot[.at2]> [locked[.atl]]'); sys.exit(0) fn1 = sys.argv[1] # Needs a btrim() if not fn1.endswith('.AT2'): fn1 = fn1 + '.AT2' if not os.path.isfile(fn1): print('Robot "' + fn1 + '" not found!') sys.exit(0) if len(sys.argv) == 3: fn2 = sys.argv[2] # Needs a btrim() else: fn2 = os.path.splitext(fn1)[0] + '.ATL' if not True: # should be a properly functioning valid(fn2): print('Output name "' + fn2 + '" not valid!') sys.exit(0) if fn1 == fn2: print('Filenames can not be the same!') sys.exit(0) f1 = open(fn1,'r') f2 = open(fn2,'x') # copy comment header f2.write(';------------------------------------------------------------------------------\n') for s in f1: if s[0] == ';': f2.write(s) else: break # lock header f2.write(';------------------------------------------------------------------------------\n') f2.write('; ' + os.path.basename(fn1) + ' Locked on ' + time.strftime('%d/%m/%Y') + '\n') f2.write(';------------------------------------------------------------------------------\n') lock_code = '' k = random.randint(0,21) + 20 for i in range(1,k): lock_code = lock_code + chr(random.randint(0,31) + 65) lock_code = 'VMWVRXAJZ\\M]RGRYG^T]AD[GIMTA]DILPZ\\' # remove line when done testing f2.write('#LOCK' + str(LOCKTYPE) + ' ' + lock_code + '\n') # decode lock-code j = '' for i in lock_code: j = j + chr(ord(i) - 65) print('Encoding "' + fn1 + '"...') # encode robot s = s[1:-1] if len(s) > 0: write_line(s.upper()) f1.seek(0) for s1 in f1: # read line s1 = f1.readline() s1 = s1.upper() # still needs a btrim function s1 = s1[1:-1] # write line write_line(s1) print('Done. Used LOCK Format #' + str(LOCKTYPE) + '.') print('Only ATR2 v2.08 or later can decode.') print('LOCKed robot saved as "' + fn2 + '"') f1.close() f2.close() <file_sep>import ATR2FUNC ''' def func_test_hexnum(): #Pass pass_fail = "Fail" num_1 = ATR2FUNC.hexnum(0) num_2 = ATR2FUNC.hexnum(8) num_3 = ATR2FUNC.hexnum(15) #print('step_1') if (num_1 == '0') & (num_2 == '8') & (num_3 == 'F'): pass_fail = "Pass" #print('step_2') print(pass_fail) func_test_hexnum() def func_test_hexb(): #Pass #print('step_1') a = ATR2FUNC.hexb(11) #print(a) #print('step_2') if a == '0B': print('Pass') else: print('Fail') func_test_hexb() ''' def func_test_hex(): #Fail print('step_1') a = ATR2FUNC.hex(10) print(a) print('step_2') if a == '0FA': print('Pass') else: print('Fail') func_test_hex() ''' def func_test_valuer(): #Pass a = ATR2FUNC.valuer("100") #print(a) if type(a) is int and a == 100: print('Pass') else: print('Fail') func_test_valuer() def func_test_value(): #Pass a = ATR2FUNC.value(1) #print(a) if a == 1: print('Pass') else: print('Fail') func_test_value() def func_test_cstrr(): #Pass a = ATR2FUNC.cstrr(1.1) #print(a) if type(a) is str and a == "1.1": print('Pass') else: print('Fail') func_test_cstrr() def func_test_cstr(): #Pass a = ATR2FUNC.cstr(1.1) #print(a) if type(a) is str and a == "1.1": print('Pass') else: print('Fail') func_test_cstr() def func_test_zero_pad(): #Pass s = ATR2FUNC.zero_pad(5, 10) #print(s) if type(s) is str and len(s) == 10: print('Pass') else: print('Fail') func_test_zero_pad() def func_test_zero_pads(): #Pass s = ATR2FUNC.zero_pads(5, 10) #print(s) if type(s) is str and len(s) == 10: print('Pass') else: print('Fail') func_test_zero_pads() def func_test_addfront(): #Pass s = ATR2FUNC.addfront('5', 10) #print(s) if type(s) is str and len(s) == 10: print('Pass') else: print('Fail') func_test_addfront() def func_test_addrear(): #Pass s = ATR2FUNC.addrear('5', 10) #print(s) if type(s) is str and len(s) == 10: print('Pass') else: print('Fail') func_test_addrear() def func_test_ucase(): #Pass s = ATR2FUNC.ucase('a') #print(s) if type(s) is str and s.isupper(): print('Pass') else: print('Fail') func_test_ucase() def func_test_lcase(): #Pass s = ATR2FUNC.lcase('a') #print(s) if type(s) is str and s.islower(): print('Pass') else: print('Fail') func_test_lcase() def func_test_space(): #Pass s = ATR2FUNC.space(10) #print(s) if type(s) is str and len(s) == 10: print('Pass') else: print('Fail') func_test_space() def func_test_repchar(): #Pass s = ATR2FUNC.repchar('a', 5) #print(s) if type(s) is str and len(s) == 5: print('Pass') else: print('Fail') func_test_repchar() def func_test_ltrim(): #Pass s = ATR2FUNC.ltrim('12345') #print(s) if type(s) is str and s == '2345': print('Pass') else: print('Fail') func_test_ltrim() def func_test_rtrim(): #Pass s = ATR2FUNC.rtrim('12345') #print(s) if type(s) is str and s == '1234': print('Pass') else: print('Fail') func_test_rtrim() def func_test_btrim(): #Pass s = ATR2FUNC.btrim('12345') #print(s) if type(s) is str and s == '234': print('Pass') else: print('Fail') func_test_btrim() def func_test_lstr(): #Pass s = ATR2FUNC.lstr('12345', 3) #print(s) s1 = ATR2FUNC.lstr('1', 3) #print(s1) if type(s) is str and s == '123' and s1 == s1: print('Pass') else: print('Fail') func_test_lstr() def func_test_rstr(): #Pass s = ATR2FUNC.rstr('12345', 3) #print(s) s1 = ATR2FUNC.rstr('1', 3) #print(s1) if type(s) is str and s == '345' and s1 == s1: print('Pass') else: print('Fail') func_test_rstr() def func_test_check_registration(): #Not Finished a = ATR2FUNC.check_registration() #print(a) func_test_check_registration() def func_test_rol(): #Pass #print(ATR2FUNC._bin(10)) a = ATR2FUNC.rol(10, 1) #print(a) #print(type(a)) if a == '0000000000010100': print('Pass') else: print('Fail') func_test_rol() def func_test_ror(): #Pass #print(ATR2FUNC._bin(10)) a = ATR2FUNC.ror(10, 1) #print(a) if type(a) == str and a == '0000000000000101': print('Pass') else: print('Fail') func_test_ror() def func_test_sal(): #Pass #print(ATR2FUNC._bin(10)) a = ATR2FUNC.sal(10, 1) #print(a) if type(a) == str and a == '0000000000010100': print('Pass') else: print('Fail') func_test_sal() def func_test_sar(): #Pass #print(ATR2FUNC._bin(10)) a = ATR2FUNC.sar(10, 1) #print(a) if type(a) == str and a == '0000000000000101': print('Pass') else: print('Fail') func_test_sar() def func_test_make_tables(): #Fail sint = () cost = () ATR2FUNC.make_tables() if sint[1] == math.sin(i/128*math.pi): print('Pass') else: print('Fail') func_test_make_tables() def func_test_robot_color(): #Pass a = ATR2FUNC.robot_color(27) #print(a) if a == 15: print('Pass') else: print('Fail') func_test_robot_color() def func_test_hex2int(): a3 = ATR2FUNC.hex2int('5') #print(a3) a2 = ATR2FUNC.hex2int('C8') #print(a2) a1 = ATR2FUNC.hex2int('1') #print(a1) if a3 == 5 and a2 == 200 and a1 == 1: print('Pass') else: print('Fail') func_test_hex2int() def func_test_str2int(): a = ATR2FUNC.str2int("") '''<file_sep>#!/usr/bin/python ### A very incomplete to-do list, please add to this things you see wrong!########################## # Robots aren't being compiled properly # Need to figure out what keypressed is supposed to do, can use pygame for this, until then keypressed returns false # keypressed basically shows whether a key was pressed or not but it # unfortunately has something to do with checking the buffer (which is the # reason for all of those calls to 'clear buffer'). I'm not sure whether or not # this'll cause a problem once we use Pygame. # More info: https://www.freepascal.org/docs-html/rtl/crt/keypressed.html #################################################################################################### # Copyright (c) 1999, <NAME>. All rights reserved. # # Bug fixes and additional additions Copyright (c) 2014, William "<NAME> # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by <NAME> III & # NecroBones Enterprises. # No modified or derivative copies or software may be distributed in the # guise of official or original releases/versions of this software. Such # works must contain acknowledgement that it is modified from the original. # Neither the name of the author nor the name of the business or # contributers may be used to endorse or promote products derived # from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def keypressed(): return False from ATR2FUNC import * import random import time import os import pdb import pygame import sys progname = 'AT-Robots' version = '2.11' cnotice1 = 'Copyright 1997 ''99, <NAME>' cnotice2 = 'All Rights Reserved.' cnotice3 = 'Copyright 2014, <NAME>' main_filename = 'ATR2' robot_ext = '.AT2' locked_ext = '.ATL' config_ext = '.ATS' compile_ext = '.CMP' report_ext = '.REP' _T = True _F = False maxint = 32787 minint = -32768 # debugging/compiler show_code = True compile_by_line = False max_var_len = 16 debugging_compiler = True # robots max_robots = 31 # starts at 0, so total is max_robots + 1 max_code = 1023 # same here max_op = 3 # etc... stack_size = 256 stack_base = 768 max_ram = 1023 # but this does start at 0 (odd #, 2 ^ n - 1) max_vars = 256 max_labels = 256 acceleration = 4 turn_rate = 8 max_vel = 4 max_missiles = 1023 missile_spd = 32 hit_range = 14 blast_radius = 25 crash_range = 8 max_sonar = 250 com_queue = 512 max_queue = 255 max_config_points = 12 max_mines = 63 mine_blast = 35 # simulator & graphics screen_scale = 0.46 screen_x = 5 screen_y = 5 robot_scale = 6 default_delay = 20 default_slice = 5 mine_circle = int(mine_blast * screen_scale) + 1 blast_circle = int(blast_radius * screen_scale) + 1 mis_radius = int(hit_range / 2.0) + 1 max_robot_lines = 8 # gray50 thing goes here class op_rec: op = [0 for i in range(0, max_op + 1)] prog_type = [op_rec() for i in range(0, max_code + 1)] # note: must be careful when accessing values of prog_type if we need attribute of class class config_rec: scanner = 0 weapon = 0 armor = 0 engine = 0 heatsinks = 0 shield = 0 mines = 0 class mine_rec: x = 0 y = 0 detect = 0 _yield = 0 detonate = False class robot_rec: is_locked = False mem_watch = 0 x = 0 y = 0 lx = 0 ly = 0 xv = 0 yv = 0 speed = 0 shotstrength = 0 damageadj = 0 speedadj = 0 meters = 0 hd = 0 thd = 0 lhd = 0 spd = 0 tspd = 0 armor = 0 larmor = 0 heat = 0 lheat = 0 ip = 0 plen = 0 scanarc = 0 accuracy = 0 shift = 0 err = 0 delay_left = 0 robot_time_limit = 0 max_time = 0 time_left = 0 lshift = 0 arc_count = 0 sonar_count = 0 scanrange = 0 last_damage = 0 last_hit = 0 transponder = 0 shutdown = 0 channel = 0 lendarc = 0 endarc = 0 lstartarc = 0 startarc = 0 mines = 0 tx = [0 for i in range(0, max_robot_lines)] ltx = [0 for i in range(0, max_robot_lines)] ty = [0 for i in range(0, max_robot_lines)] lty = [0 for i in range(0, max_robot_lines)] wins = 0 trials = 0 kills = 0 deaths = 0 startkills = 0 shots_fired = 0 match_shots = 0 hits = 0 damage_total = 0 cycles_lived = 0 error_count = 0 config = config_rec name = '' fn = '' shields_up = False lshields = False overburn = False keepshift = False cooling = False won = False code = prog_type ram = [0 for i in range(0, max_ram + 1)] mine = [mine_rec() for i in range(0, max_mines + 1)] errorlog = open('errorlog', 'a').close() # not sure who removed this/why, but it's needed by many functions class missile_rec: x = 0 y = 0 lx = 0 ly = 0 mult = 0 mspd = 0 source = 0 a = 0 hd = 0 rad = 0 lrad = 0 max_rad = 0 missile = [] missile = [missile_rec() for i in range(0, max_missiles + 1)] robot = [] robot = [robot_rec() for i in range(-2, max_robots + 3)] # NOTE: in the original code these were just declarations, I've picked values that make sense for them to have # robot variables num_robots = 2 # compiler variables # f = open('f', 'a').close() numvars = 0 numlabels = 0 maxcode = 0 lock_pos = 0 lock_dat = 0 varname = [] varname = ['' for i in range(1, max_vars + 1)] varloc = [] varloc = [0 for i in range(1, max_vars + 1)] labelname = [] labelname = ['' for i in range(1, max_vars + 1)] labelnum = [x for x in range(max_labels)] varnum = [] varnum = [0 for i in range(1, max_labels + 1)] show_source = True compile_only = False lock_code = '' # simulator/graphics variables bout_over = False # made global from procedure bout step_mode = 0 # 0=off, for (0<step_mode<=9) = #of game cycles per step temp_mode = 0 # stores previous step_mode for return to step step_count = 1 # step counter used as break flag step_loop = False # break flag for stepping # show_debugger = False # flag for viewing debugger panel vs. robot stats matches = 1 played = 0 old_shields = False insane_missiles = False debug_info = False windoze = False no_gfx = False logging_errors = False timing = False show_arcs = False game_delay = 0 time_slice = 1 insanity = 0 update_timer = 1 max_gx = 1000 max_gy = 1000 stats_mode = 0 game_limit = 100 game_cycle = 0 # general settings _quit = False report = True show_cnotice = False kill_count = 0 report_type = 0 def operand(n,m): s = chr(n) # Microcode: # 0 = instruction, number, constant # 1 = variable, memory access # 2 = :label # 3 = !label (unresolved) # 4 = !label (resolved) # 8h mask = inderect addressing (enclosed in []) x = m & 7 if x == 1: s = '@' + s if x == 2: s = ':' + s if x == 3: s = '$' + s if x == 4: s = '!' + s else: s = cstr(n) if (m and 8) > 0: s = '[' + s + ']' return s def mnemonic(n,m): s = chr(n) if m == 0: if n == 0: s = 'NOP' elif n == 1: s = 'ADD' elif n == 2: s = 'SUB' elif n == 3: s = 'OR' elif n == 4: s = 'AND' elif n == 5: s = 'XOR' elif n == 6: s = 'NOT' elif n == 7: s = 'MPY' elif n == 8: s = 'DIV' elif n == 9: s = 'MOD' elif n == 10: s = 'RET' elif n == 11: s = 'CALL' elif n == 12: s = 'JMP' elif n == 13: s = 'JLS' elif n == 14: s = 'JGR' elif n == 15: s = 'JNE' elif n == 16: s = 'JE' elif n == 17: s = 'SWAP' elif n == 18: s = 'DO' elif n == 19: s = 'LOOP' elif n == 20: s = 'CMP' elif n == 21: s = 'TEST' elif n == 22: s = 'MOV' elif n == 23: s = 'LOC' elif n == 24: s = 'GET' elif n == 25: s = 'PUT' elif n == 26: s = 'INT' elif n == 27: s = 'IPO' elif n == 28: s = 'OPO' elif n == 29: s = 'DELAY' elif n == 30: s = 'PUSH' elif n == 31: s = 'POP' elif n == 32: s = 'ERR' elif n == 33: s = 'INC' elif n == 34: s = 'DEC' elif n == 35: s = 'SHL' elif n == 36: s = 'SHR' elif n == 37: s = 'ROL' elif n == 38: s = 'ROR' elif n == 39: s = 'JZ' elif n == 40: s = 'JNZ' elif n == 41: s = 'JGE' elif n == 42: s = 'JLE' elif n == 43: s = 'SAL' elif n == 44: s = 'SAR' elif n == 45: s = 'NEG' elif n == 46: s = 'JTL' else: s = 'XXX' else: s = operand(n,m) return s def log_error(n,i,ov): if not logging_errors: return else: for n in robot: if i == 1: s = 'Stack full - Too many CALLs?' elif i == 2: s = 'Label not found. Hmmm.' elif i == 3: s = 'Can\'t assign value - Tisk tisk.' elif i == 4: s = 'Illegal memory reference' elif i == 5: s = 'Stack empty - Too many RETs?' elif i == 6: s = 'Illegal instruction. How bizarre.' elif i == 7: s = 'Return out of range - Woops!' elif i == 8: s = 'Divide by zero' elif i == 9: s = 'Unresolved !label. WTF?' elif i == 10: s = 'Invalid Interrupt Call' elif i == 11: s = 'Invalid Port Access' elif i == 12: s = 'Com Queue empty' elif i == 13: s = 'No mine-layer, silly.' elif i == 14: s = 'No mines left' elif i == 15: s = 'No shield installed - Arm the photon torpedoes instead. :-)' elif i == 16: s = 'Invalid Microcode in instruction.' else: s = 'Unknown error' print(robot[n].errorlog + '<' + i + '> ' + s + ' (Line #' + robot[n].ip + ') [Cycle: ' + game_cycle + ', Match: ' + played + '/' + matches + ']\n') print(robot[n].errorlog + ' ' + mnemonic(robot[n].code[robot[n].ip].op[0] + robot[n].code[robot[n].ip].op[3] and 15) + ' ' + operand(robot[n].code[robot[n].ip].op[1] + (robot[n].code[robot[n].ip].op[3] >> 4) & 15) + ' + ' + operand(robot[n].code[robot[n].ip].op[2] + (robot[n].code[robot[n].ip].op[3] >> 8) & 15)) if ov != '': print(robot[n].errorlog + ' (Values: ' + ov + ')') else: print(robot[n].errorlog) print(robot[n].errorlog + ' AX=' + addrear(chr(robot[n].ram[65])+',',7)) print(robot[n].errorlog + ' BX=' + addrear(chr(robot[n].ram[66])+',',7)) print(robot[n].errorlog + ' CX=' + addrear(chr(robot[n].ram[67])+',',7)) print(robot[n].errorlog + ' DX=' + addrear(chr(robot[n].ram[68])+',',7)) print(robot[n].errorlog + ' EX=' + addrear(chr(robot[n].ram[69])+',',7)) print(robot[n].errorlog + ' FX=' + addrear(chr(robot[n].ram[70])+',',7)) print(robot[n].errorlog + ' Flags=' + robot[n].ram[64] + '\n') print(robot[n].errorlog + ' AX=' + addrear(hex(robot[n].ram[65])+',',7)) print(robot[n].errorlog + ' BX=' + addrear(hex(robot[n].ram[66])+',',7)) print(robot[n].errorlog + ' CX=' + addrear(hex(robot[n].ram[67])+',',7)) print(robot[n].errorlog + ' DX=' + addrear(hex(robot[n].ram[68])+',',7)) print(robot[n].errorlog + ' EX=' + addrear(hex(robot[n].ram[69])+',',7)) print(robot[n].errorlog + ' FX=' + addrear(hex(robot[n].ram[70])+',',7)) print(robot[n].errorlog + ' Flags=' + hex(robot[n].ram[64])) print(robot[n].errorlog) def max_shown(): if stats_mode == 1: return 12 elif stats_mode == 2: return 32 else: return 6 def graph_check(n): ok = True if (not graphix) or (n < 0) or (n > num_robots) or (n >= max_shown): ok = False return ok def robot_graph(n): if stats_mode == 1: viewport(480,4+n*35,635,37+n*35) max_gx = 155 max_gy = 33 elif stats_mode == 2: viewport(480,4+n*13,635,15+n*13) max_gx = 155 max_gy = 11 else: viewport(480,4+n*70,n*70) max_gx = 155 max_gy = 66 setfillstyle(1,robot_color(n)) setcolor(robot_color(n)) def update_armor(n): if graph_check(n) & step_mode <=0: #needs more work robot[n].n robot_graph(n) if robot[n].armor>0: if stats_mode == 1: bar(30,13,29+robot[n].armor,18) bar(88,3,87+(robot[n].armor >> 2),8) else: bar(30,25,29+robot[n].armor,30) setfillstyle(1,8) if robot[n].armor < 100: if stats_mode == 1: bar(30+robot[n].armor,13,129,18) elif stats_mode == 2: bar(88+(robot[n].armor >> 2), 3,111,8) else: bar(30+robot[n].armor,25,129,30) def update_heat(n): if graph_check(n) & step_mode <= 0: robot[n].n robot_graph(n) if robot[n].heat > 5: if stats_mode == 1: bar(30,23,29+(robot[n].heat // 5), 28) elif stats_mode == 2: bar(127,3,126+(robot[n].heat // 20),8) else: bar(30,35,29+(robot[n].heat // 5),40) setfillstyle(1,8) if robot[n].heat<500: if stats_mode == 1: bar(30,(robot[n].heat // 5),23,129,28) elif stats_mode == 2: bar(127+(robot[n].heat // 20), 3,151,8) # find *(heat div 20) else: bar(30+(robot[n].heat // 5), 35,129,40) def robot_error(n, i, ov): if graph_check(n) and step_mode <= 0: if stats_mode == 0: robot_graph(n) setfillstyle(1,0) bar(66,56,154,64) setcolor(robot_color(n)) outtextxy(66,56,addrear(cstr(i), 7) + hex(i)) chirp() if logging_errors: log_error(n,i,ov) robot[n].error_count +=1 def update_lives(n): if graph_check(n) and stats_mode == 0 and step_mode <= 0: robot[n].n robot_graph(n) setcolor(robot_color(n)-8) setfillstyle(1,0) bar(11,46,'K:') # check K: outtextxy(11,46,'K:') outtextxy(29,46,zero_pad(robot[n].kills,4)) outtextxy(80,46,'D:') # check D: outtextxy(98,46,zero_pad(robot[n].deaths,4)) def update_cycle_window(): if not graphix: print('\t' + 'Match ' + str(played) + '/' + str(matches) + ', Cycle: ' + zero_pad(game_cycle,9)) # else: # viewport(480,440,635,475) # setfillstyle(1,0) # bar(59,2,154,10) # setcolor(7) # outtextxy(75,03,zero_pad(game_cycle,9)) def setscreen(): if not graphix: sys.exit() # BIG GRAPHICAL PART GOES HERE def graph_mode(on): if on and not graphix: Graph_VGA cleardevice graphix = True else: if (not on) and graphix: closegraph graphix = False def prog_error(n, ss): #graph_mode(False) # graphics related #textcolor(15) # graphics related print("Error #", n, ": ", end = '') if n == 0: s = ss elif n == 1: s = "Invalid :label - \"" + ss + "\", silly mortal." elif n == 2: s = "Undefined identifier - \"" + ss + "\". A typo perhaps?" elif n == 3: s = "Memory access out of range - \"" + ss + "\"" elif n == 4: s = "Not enough robots for combat. Maybe we should just drive in circles." elif n == 5: s = "Robot names and settings must be specified. An empty arena is no fun." elif n == 6: s = "Config file not found - \"" + ss + "\"" elif n == 7: s = "Cannot access a config file from a config file - \"" + ss + "\"" elif n == 8: s = "Robot not found \"" + ss + "\". Perhaps you mistyped it?" elif n == 9: s = "Insufficient RAM to load robot: \"" + ss + "\"... This is not good." elif n == 10: s = "Too many robots! We can only handle " + str(max_robots + 1) + "! Blah.. limits are limits." elif n == 11: s = "You already have a perfectly good #def for \"" + ss + "\", silly." elif n == 12: s = "Variable name too long! (Max:" + str(max_var_len) + ") \"" + ss + "\"" elif n == 13: s = "!Label already defined \"" + ss + "\", silly." elif n == 14: s = "Too many variables! (Var Limit: " + str(max_vars) + ")" elif n == 15: s = "Too many !labels! (!Label Limit: " + str(max_labels) + ")" elif n == 16: s = "Robot program too long! Boldly we simplify, simplify along..." + ss elif n == 17: s = "!Label missing error. !Label #" + ss + "." elif n == 18: s = "!Label out of range: " + ss elif n == 19: s = "!Label not found. " + ss elif n == 20: s = "Invalid config option: \"" + ss + "\". Inventing a new device?" elif n == 21: s = "Robot is attempting to cheat; Too many config points (" + ss + ")" elif n == 22: s = "Insufficient data in data statement: \"" + ss + "\"" elif n == 23: s = "Too many asterisks: \"" + ss + "\"" elif n == 24: s = "Invalid step count: \"" + ss + "\"" elif n == 25: s = "\"" + ss + "\"" else: s = ss print(s) print() exit() def print_code(n, p): i = 0 print(hex(p)+': ') for i in range(max_op): sys.stdout.write(str(zero_pad(robot[n].code[p].op[i],5)) + ' ') sys.stdout.write('= ') for i in range(max_op): sys.stdout.write(str(hex(robot[n].code[p].op[i])) + 'h ') print('\n') def parse1(n, p, s): global numlabels ss = '' for i in range(max_op-1): k = 0 found = False opcode = 0 microcode = 0 s[i] = btrim(ucase(s[i])) indirect = False # Microcode: # 0 = instruction, number, constant # 1 = variable, memory access # 2 = :label # 3 = !label (unresolved) # 4 = !label (resolved) # 8h mask = inderect addressing (enclosed in []) if s[i] == '': opcode = 0 microcode = 0 found = True if lstr(s[i], 1) == '[' and (rstr(s[i], 1) == ']'): s[i] = copy(s[i], 2, len(s[i]) - 2) indirect = True if (not found) and (s[i][0] == '!'): ss = s[i] ss = btrim(rstr(ss,len(ss)-1)) if numlabels > 0: for j in range(1,numlabels): if ss == labelname[i]: found = True if labelnum[j] > 0: opcode = labelnum[j] microcode = 4 # resovled !label else: opcode = j microcode = 3 # unresovled !label if not found: numlabels +=1 if numlabels > max_labels: prog_error(15, ' ') else: labelname[numlabels] = ss labelnum[numlabels] = -1 opcode = numlabels microcode = 3 # unresolved !label found = True if numvars > 0 and not found: for j in range(1,numvars): if s[i] == varname[j]: opcode = varloc[j] microcode = 1 found = True # instructions if s[i] == 'NOP': opcode = 000 found = True elif s[i] == 'ADD': opcode = 1 found = True elif s[i] == 'SUB': opcode = 2 found = True elif s[i] == 'OR': opcode = 3 found = True elif s[i] == 'AND': opcode = 4 found = True elif s[i] == 'XOR': opcode = 5 found = True elif s[i] == 'NOT': opcode = 6 found = True elif s[i] == 'MPY': opcode = 7 found = True elif s[i] == 'DIV': opcode == 7 found = True elif s[i] == 'MOD': opcode= 9 found= True elif s[i] == 'RET': opcode = 10 found = True elif s[i] == 'RETURN': opcode = 10 found = True elif s[i] == 'GSB': opcode = 11 found = True elif s[i] == 'GOSUB': opcode = 11 found = True elif s[i] == 'CALL': opcode = 11 found = True elif s[i] == 'JMP': opcode = 12 found = True elif s[i] == 'JUMP': opcode = 12 found = True elif s[i] == 'GOTO': opcode = 12 found = True elif s[i] == 'JLS': opcode = 13 found = True elif s[i] == 'JB': opcode = 13 found = True elif s[i] == 'JGR': opcode = 14 found = True elif s[i] == 'JA': opcode = 14 found = True elif s[i] == 'JNE': opcode = 15 found = True elif s[i] == 'JEQ': opcode = 16 found = True elif s[i] == 'JE': opcode = 16 found = True elif s[i] == 'XCHG': opcode = 17 found = True elif s[i] == 'SWAP': opcode = 17 found = True elif s[i] == 'DO': opcode = 18 found= True elif s[i] == 'LOOP': opcode = 19 found = True elif s[i] == 'CMP': opcode = 20 found = True elif s[i] == 'TEST': opcode = 21 found = True elif s[i] == 'SET': opcode = 22 found = True elif s[i] == 'MOV': opcode = 22 found = True elif s[i] == 'LOC': opcode = 23 found = True elif s[i] == 'ADDR': opcode = 23 found = True elif s[i] == 'GET': opcode = 24 found= True elif s[i] == 'PUT': opcode = 25 found = True elif s[i] == 'INT': opcode = 26 found = True elif s[i] == 'IPO': opcode = 27 found = True elif s[i] == 'IN': opcode = 27 found = True elif s[i] == 'OPO': opcode = 28 found = True elif s[i] == 'OUT': opcode = 28 found = True elif s[i] == 'DEL': opcode = 29 found = True elif s[i] == 'DELAY': opcode = 29 found = True elif s[i] == 'PUSH': opcode = 30 found = True elif s[i] == 'POP': opcode = 31 found = True elif s[i] == 'ERR': opcode = 32 found = True elif s[i] == 'ERROR': opcode = 32 found = True elif s[i] == 'INC': opcode = 33 found = True elif s[i] == 'DEC': opcode = 34 found = True elif s[i] == 'SHL': opcode = 35 found = True elif s[i] == 'SHR': opcode == 36 found = True elif s[i] == 'ROL': opcode = 37 found = True elif s[i] == 'ROR': opcode = 37 found = True elif s[i] == 'JZ': opcode = 39 found = True elif s[i] == 'JNZ': opcode = 40 found = True elif s[i] == 'JAE': opcode = 41 found = True elif s[i] == 'JGE': opcode = 41 found = True elif s[i] == 'JLE': opcode = 42 found = True elif s[i] == 'JBE': opcode = 42 found = True elif s[i] == 'SAL': opcode = 43 found = True elif s[i] == 'SAR': opcode = 44 found = True elif s[i] == 'NEG': opcode = 45 found = True elif s[i] == 'JTL': opcode = 46 found = True # registers elif s[i] == 'COLCNT': opcode = 8 microcode = 1 found = True elif s[i] == 'METERS': opcode = 9 microcode = 1 found = True elif s[i] == 'COMBASE': opcode = 10 microcode = 1 found = True elif s[i] == 'COMEND': opcode = 11 microcode = 1 found = True elif s[i] == 'FLAGS': opcode = 64 microcode = 1 elif s[i] == 'AX': opcode = 64 microcode = 1 found = True elif s[i] == 'BX': opcode = 66 microcode = 1 found = True elif s[i] == 'CX': opcode = 67 microcode = 1 found = True elif s[i] == 'DX': opcode = 68 microcode = 1 found = True elif s[i] == 'EX': opcode = 69 microcode = 1 found = True elif s[i] == 'FX': opcode = 70 microcode = 1 found = True elif s[i] == 'SP': opcode = 71 microcode = 1 found = True # constants elif s[i] == 'MAXINT': opcode = 32767 microcode = 0 found = True elif s[i] == 'MININT': opcode = 32768 microcode = 0 found = True elif s[i] == 'P_SPEDOMETER': opcode = 1 microcode = 0 found = True elif s[i] == 'P_HEAT': opcode = 2 microcode = 0 found = True elif s[i] == 'P_COMPASS': opcode = 3 microcode = 0 found = True elif s[i] == 'P_TANGLE': opcode = 4 microcode = 0 found = True elif s[i] == 'P_TURRENT_OFS': opcode = 4 microcode = 0 found = True elif s[i] == 'P_THEADING': opcode = 5 microcode = 0 found = True elif s[i] == 'P_TURRENT_ABS': opcode = 5 microcode = 0 found = True elif s[i] == 'P_ARMOR': opcode = 6 microcode = 0 found = True elif s[i] == 'P_DAMAGE': opcode = 6 microcode = 0 found = True elif s[i] == 'P_SCAN': opcode = 7 microcode = 0 found = True elif s[i] == 'P_ACCURACY': opcode = 8 microcode = 0 found = True elif s[i] == 'P_RADAR': opcode = 9 microcode = 0 found = True elif s[i] == 'P_RANDOM': opcode = 10 microcode = 0 found = True elif s[i] == 'P_RAND': opcode = 10 microcode = 0 found = True elif s[i] == 'P_THROTTLE': opcode = 11 microcode = 0 found = True elif s[i] == 'P_TROTATE': opcode = 12 microcode = 0 found = True elif s[i] == 'P_OFS_TURRENT': opcode = 12 microcode = 0 found = True elif s[i] == 'P_TAIM': opcode = 13 microcode = 0 found = True elif s[i] == 'P_ABS_TURRENT': opcode = 13 microcode = 0 found = True elif s[i] == 'P_STEERLING': opcode = 14 microcode = 0 found = True elif s[i] == 'P_WEAP': opcode = 15 microcode = 0 found = True elif s[i] == 'P_WEAPON': opcode = 15 microcode = 0 found = True elif s[i] == 'P_FIRE': opcode = 15 microcode = 0 found = True elif s[i] == 'P_SONAR': opcode = 16 microcode = 0 found = True elif s[i] == 'P_ARC': opcode = 17 microcode = 0 found = True elif s[i] == 'P_SCANARC': opcode = 17 microcode = 0 found = True elif s[i] == 'P_OVERBURN': opcode = 18 microcode = 0 found = True elif s[i] == 'P_TRANSPONDER': opcode = 19 microcode = 0 found = True elif s[i] == 'P_SHUTDOWN': opcode = 20 microcode = 0 found = True elif s[i] == 'P_CHANNEL': opcode = 21 microcode = 0 found = True elif s[i] == 'P_MINELAYER': opcode = 22 microcode = 0 found = True elif s[i] == 'P_MINETRIGGER': opcode = 23 microcode = 0 found = True elif s[i] == 'P_SHIELD': opcode = 24 microcode = 0 found = True elif s[i] == 'P_SHIELDS': opcode = 24 microcode = 0 found = True elif s[i] == 'I_DESTRUCT': opcode = 0 microcode = 0 found = True elif s[i] == 'I_RESET': opcode = 1 microcode = 0 found = True elif s[i] == 'I_LOCATE': opcode = 2 microcode = 0 found = True elif s[i] == 'I_KEEPSHELIFT': opcode = 3 microcode = 0 found = True elif s[i] == 'I_OVERBURN': opcode = 4 microcode = 0 found = True elif s[i] == 'I_ID': opcode = 5 microcode = 0 found = True elif s[i] == 'I_TIMER': opcode = 6 microcode = 0 found = True elif s[i] == 'I_ANGLE': opcode = 7 microcode = 0 found = True elif s[i] == 'I_TID': opcode = 8 microcode = 0 found = True elif s[i] == 'I_TARGETID': opcode = 8 microcode = 0 found = True elif s[i] == 'I_TINFO': opcode = 9 microcode = 0 found = True elif s[i] == 'I_TARGETINFO': opcode = 9 microcode = 0 found = True elif s[i] == 'I_GINFO': opcode = 10 microcode = 0 found = True elif s[i] == 'I_GAMEINFO': opcode = 10 microcode = 0 found = True elif s[i] == 'I_RINFO': opcode = 11 microcode = 0 found = True elif s[i] == 'I_ROBOTINFO': opcode = 11 microcode = 0 found = True elif s[i] == 'I_COLLISIONS': opcode = 13 microcode = 0 found = True elif s[i] == 'I_RESETCOLCNT': opcode = 13 microcode = 0 found = True elif s[i] == 'I_TRANSMIT': opcode = 14 microcode = 0 found = True elif s[i] == 'I_RECEIVE': opcode = 15 microcode = 0 found = True elif s[i] == 'I_DATAREADY': opcode = 16 microcode = 0 found = True elif s[i] == 'I_CLEARCOM': opcode = 17 microcode = 0 found = True elif s[i] == 'I_KILLS': opcode = 18 microcode = 0 found = True elif s[i] == 'I_DEATHS': opcode = 18 microcode = 0 found = True elif s[i] == 'I_CLEARMETERS': opcode = 19 microcode = 0 found = True # memory addresses if (not found) and (s[i][1] == '@') and s[i][2].isdigit(): opcode = str2int(rstr(s[i], len(s[i])-1)) if(opcode < 0) or (opcode > (max_ram + 1) + ((max_code + 1) << 3) - 1): prog_error(3,s[i]) microcode = 1 found = True if (not found) and s[i][1].isdigit(): opcode = str2int(s[i]) found = True if found: robot[n].code[p].op[i] = opcode if indirect: microcode = microcode | 8 robot[n].code[p].op[max_op] = robot[n].code[p].op[max_op] or (microcode << (i*4)) # check elif s[i] != '': prog_error(2, s[i]) if show_code: print_code(n, p) if compile_by_line: readkey() def check_plen(plen): if plen > maxcode: prog_error(16,'\t\nMaximum program length exceeded, (Limit: ' + cstr(maxcode+1) + ' compiled lines)') def _compile(n, filename): global numvars global numlabels lc = '' lock_code = '' lock_pos = 0 locktype = 0 lock_dat = 0 pp = [''] * max_op if not os.path.isfile(filename): prog_error(8, filename) # textcolor(robot_color(n)) print('Compiling robot #' + str(n + 1) + ': ' + filename) robot[n].is_locked = False # textcolor(robot_color(n)) numvars = 0 numlabels = 0 for k in range(max_code): for i in range(max_op): robot[n].code[k].op[i] = 0 robot[n].plen = 0 f = open(filename, 'r') s = '' linecount = 0 for line in f: if s == '#END': # and plen <= maxcode break s = line linecount += 1 if locktype < 3: lock_pos = 0 if lock_code != '': for i in s: lock_pos += 1 if lock_pos > len(lock_code): lock_pos = 0 if locktype == 3: s[i] = chr((ord(s[i]) - 1) ^ (ord(lock_code[lock_pos]) ^ lock_dat)) elif locktype == 2: s[i] = chr(ord(s[i]) ^ (ord(lock_code[lock_pos]) ^ 1)) else: s[i] = chr(ord(s[i]) ^ ord(lock_code[lock_pos])) lock_dat = ord(s[i]) & 15 s = btrim(s) orig_s = s t = '' for i in s: if ord(i) in range(0,33) or ord(i) in range(128,256) or i == ',': t += ' ' else: t += i s = t if show_source and ((lock_code == '') or debugging_compiler): print(zero_pad(linecount, 3) + ':' + zero_pad(robot[n].plen, 3) + ' ' + s) if debugging_compiler: if pygame.key.get_pressed() == chr(27): sys.exit() k = -1 for i in range(len(t) - 1, -1, -1): if s[i] == ';': k = i if k == 0: s = '' elif k > 0: s = lstr(s, k) s = btrim(s.upper()) # for i in range(max_op): # pp.append('') # This is already at length max_op?! if (len(s) > 0) and (s[0] != ';'): if s[0] == '#': # Compiler Directives s1 = btrim(rstr(s,len(s)-1)).upper() msg = btrim(rstr(orig_s, len(orig_s) - 5)) k = 0 for i in range(len(s1)): if (k == 0) and (s1[i] == ' '): k = i #k -= 1 if k > 1: s2 = lstr(s1, k) s3 = btrim(rstr(s1, len(s1) - k)).upper() k = 0 if numvars > 0: for i in range(0, numvars): if s3 == varname[i]: k = i if (s2 == 'DEF') and (numvars < max_vars): if len(s3) > max_var_len: prog_error(12, s3) elif k > 0: prog_error(11, s3) else: numvars += 1 if numvars > max_vars: prog_error(14, '') else: varname[numvars - 1] = s3 varloc[numvars - 1] = 127 + numvars elif (lstr(s2, 4) == 'LOCK'): is_locked = True if len(s2) > 4: locktype = value(rstr(s2, len(s2) - 4)) lock_code = btrim(s3.upper()) print('Robot is of LOCKed format from this point forward. [' + locktype + ']') # print('Using key: "', lock_code, '"') for i in range(len(lock_code)): lock_code[i] = chr(ord(lock_code[i]) - 65) elif s2 == 'MSG': name = msg elif s2 == 'TIME': robot_time_limit = value(s3) if robot_time_limit < 0: robot_time_limit = 0 elif s2 == 'CONFIG': if lstr(s3, 8) == 'SCANNER=': robot[n].config.scanner = int(rstr(s3, len(s3) - 8)) elif lstr(s3, 7) == 'SHIELD=': robot[n].config.shield == int(rstr(s3, len(s3) - 7)) elif lstr(s3, 7) == 'WEAPON=': robot[n].config.weapon = int(rstr(s3, len(s3) - 7)) elif lstr(s3, 6) == 'ARMOR=': robot[n].config.armor = int(rstr(s3, len(s3) - 6)) elif lstr(s3, 7) == 'ENGINE=': robot[n].config.engine = int(rstr(s3, len(s3) - 7)) elif lstr(s3, 10) == 'HEATSINKS=': robot[n].config.heatsinks = int(rstr(s3,len(s3) - 10)) elif lstr(s3, 6) == 'MINES=': robot[n].config.mines = int(rstr(s3, len(s3) - 6)) else: prog_error(20, s3) if robot[n].config.scanner < 0: robot[n].config.scanner = 0 if robot[n].config.scanner > 5: robot[n].config.scanner = 5 if robot[n].config.weapon < 0: robot[n].config.weapon = 0 if robot[n].config.weapon > 5: robot[n].config.weapon = 5 if robot[n].config.armor < 0: robot[n].config.armor = 0 if robot[n].config.armor > 5: robot[n].config.armor = 5 if robot[n].config.engine < 0: robot[n].config.engine = 0 if robot[n].config.engine > 5: robot[n].config.engine = 5 if robot[n].config.heatsinks < 0: robot[n].config.heatsinks = 0 if robot[n].config.heatsinks > 5: robot[n].config.heatsinks = 0 if robot[n].config.mines < 0: robot[n].config.mines = 0 if robot[n].config.mines > 5: robot[n].config.mines = 5 else: print('Warning: unknown directive "' + s2 + '"') elif s[0] == '*': # Inline Pre-Compiled Machine Code print('Inline Machine Code') check_plen(robot[n].plen) for i in range(max_op): pp[i] = '' for i in range(1,len(s)): if s[i] == '*': prog_error(23, s) k = 0 i = 1 s1 = '' if len(s) <= 2: prog_error(22, s) while (i < len(s)) and (k <= max_op): i += 1 if ord(s[i]) in [x in range(33,42), x in range(43,128)]: pp[k] = pp[k] + s[i] elif ord(s[i]) in [x in range(0,33), x in range(128, 256)] and ord(s[i-1]) in [x in range(33, 42), x in range(43, 128)]: k += 1 for i in range(max_op): robot[n].code[robot[n].plen].op[i] = str2int(pp[i]) robot[n].plen += 1 elif s[0] == ':': # :labels check_plen(robot[n].plen) s1 = rstr(s, len(s) - 1) for i in range(1, len(s1)): if not int(s1[i]) in range(10): print(i) prog_error(1, s) robot[n].code[robot[n].plen].op[0] = str2int(s1) robot[n].code[robot[n].plen].op[max_op] = 2 if show_code: print_code(n, robot[n].plen) robot[n].plen += 1 elif s[0] == '!': # !labels check_plen(robot[n].plen) s1 = btrim(rstr(s, len(s) - 1)) k = 0 for i in range(len(s1) - 1,0,-1): if s1[i] in [';', chr(8), chr(9), chr(10), ' ', ',']: k = i if k > 0: s1 = lstr(s1, k - 1) k = 0 for i in range(numlabels): if labelname[i] == s1: if labelnum[i] >= 0: prog_error(13, '"!' + s1 + '" (' + cstr(labelnum[i]) + ')') k = i if k == 0: numlabels += 1 if numlabels > max_labels: prog_error(15, '') k = numlabels labelname[k] = s1 labelnum[k] = robot[n].plen else: # Instructions/Numbers check_plen(robot[n].plen) # Parse instructions # Remove comments k = 0 for i in range(len(s)-1, 0, -1): if s[i] == ';': k = i if k > 0: s = lstr(s, k) # Setup variables for parsing k = 0 for j in range(max_op): pp[j] = '' for j in range(len(s)): c = s[j] if not c in [' ', chr(8), chr(9), chr(10), ','] and k <= max_op: pp[k] = pp[k] + c elif not lc in [' ', chr(8), chr(9), chr(10), ',']: k += 1 lc = c parse1(n, robot[n].plen, pp) robot[n].plen += 1 f.close() # Add our implied NOP if there's room. This was originally to make sure # no one tries using an empty robot program, kinda pointless otherwise if robot[n].plen <= maxcode: for i in range(max_op): pp[i] = '' pp[0] = 'NOP' parse1(n, robot[n].plen, pp) else: robot[n].plen -= 1 # second pass, resolving !labels if numlabels > 0: for i in range(robot[n].plen): for j in range(max_op - 1): if robot[n].code[i].op[max_op] >> (j * 4) == 3: # unresolved !label k = robot[n].code[i].op[j] if k > 0 and k <= numlabels: l = labelnum[k] if l < 0: prog_error(19, '"!' + labelname[k] + '" (' + cstr(l) + ')') if l < 0 or l > maxcode: prog_error(18, '"!' + labelname[k] + '" (' + cstr(l) + ')') else: robot[n].code[i].op[j] = l mask = not (0xF << (j * 4)) robot[n].code[i].op[max_op] = (robot[n].code[i].op[max_op] & mask) or (4 << (j * 4)) else: prog_error(17, cstr(k)) # textcolor(7) def robot_config(n): if robot[n].config.scanner == 5: robot[n].scanrange = 1500 elif robot[n].config.scanner == 4: robot[n].scanrange = 1000 elif robot[n].config.scanner == 3: robot[n].scanrange = 700 elif robot[n].config.scanner == 2: robot[n].scanrange = 500 elif robot[n].config.scanner == 1: robot[n].scanrange = 350 else: robot[n].scanrange = 250 if robot[n].config.weapon == 5: robot[n].shotstrength = 1.5 elif robot[n].config.weapon == 4: robot[n].shotstrength = 1.35 elif robot[n].config.weapon == 3: robot[n].shotstrength = 1.2 elif robot[n].config.weapon == 2: robot[n].shotstrength = 1 elif robot[n].config.weapon == 1: robot[n].shotstrength = 0.8 else: robot[n].shotstrength = .5 if robot[n].config.armor == 5: robot[n].damageadj = 0.66 robot[n].speedadj = 0.66 elif robot[n].config.armor == 4: robot[n].damageadj = 0.77 robot[n].speedadj = 0.75 elif robot[n].config.armor == 3: robot[n].damageadj = 0.83 robot[n].speedadj = 0.85 elif robot[n].config.armor == 2: robot[n].damageadj = 1 robot[n].speedadj = 1 elif robot[n].config.armor == 1: robot[n].damageadj = 1.5 robot[n].speedadj = 1.2 else: robot[n].damageadj = 2 robot[n].speedadj = 1.33 if robot[n].config.engine == 5: robot[n].speedadj = robot[n].speedadj * 1.5 elif robot[n].config.engine == 4: robot[n].speedadj = robot[n].speedadj * 1.35 elif robot[n].config.engine == 3: robot[n].speedadj = robot[n].speedadj * 1.2 elif robot[n].config.engine == 2: robot[n].speedadj = robot[n].speedadj * 1 elif robot[n].config.engine == 1: robot[n].speedadj = robot[n].speedadj * 0.8 else: robot[n].speedadj = robot[n].speedadj * 0.5 # heatsinks are handled seperately if robot[n].config.mines == 5: robot[n].mines = 24 elif robot[n].config.mines == 4: robot[n].mines = 16 elif robot[n].config.mines == 3: robot[n].mines = 10 elif robot[n].config.mines == 2: robot[n].mines = 6 elif robot[n].config.mines == 1: robot[n].mines = 4 else: robot[n].mines = 2 robot[n].config.mines = 0 robot[n].shields_up = False if (robot[n].config.shield < 3) or (robot[n].config.shield > 5): robot[n].config.shield = 0 if (robot[n].config.heatsinks < 0) or (robot[n].config.heatsinks > 5): robot[n].config.heatsinks = 0 def reset_software(n): for i in range(0, max_ram): robot[n].ram[i] = 0 robot[n].ram[71] = 768 robot[n].thd = robot[n].hd robot[n].tspd = 0 robot[n].scanarc = 8 robot[n].shift = 0 robot[n].err = 0 robot[n].overburn = False robot[n].keepshift = False robot[n].ip = 0 robot[n].accuracy = 0 robot[n].meters = 0 robot[n].delay_left = 0 robot[n].time_left = 0 robot[n].shields_up = False def reset_hardware(n): for i in range(max_robot_lines): robot[n].ltx[i] = 0 robot[n].tx[i] = 0 robot[n].lty[i] = 0 robot[n].ty[i] = 0 while True: robot[n].x = random.randint(0, 999) robot[n].y = random.randint(0, 999) dd = 1000 for i in range(0, num_robots + 1): if robot[i].x < 0: robot[i].x = 0 if robot[i].x > 1000: robot[i].x = 1000 if robot[i].y < 0: robot[i].y = 0 if robot[i].y > 1000: robot[i].y = 1000 d = distance(robot[n].x, robot[n].y, robot[i].x, robot[i].y) if((robot[i].armor > 0) and (i != n) and (d < dd)): dd = d if dd > 32: break for i in range(0, max_mines + 1): robot[n].mine[i].x = -1 robot[n].mine[i].y = -1 robot[n].mine[i]._yield = 0 robot[n].mine[i].detonate = False robot[n].mine[i].detect = 0 robot[n].lx = -1 robot[n].ly = -1 robot[n].hd = random.randint(0, 255) robot[n].shift = 0 robot[n].lhd = robot[n].hd + 1 robot[n].lshift = robot[n].shift + 1 robot[n].spd = 0 robot[n].speed = 0 robot[n].cooling = False robot[n].armor = 100 robot[n].larmor = 0 robot[n].heat = 0 robot[n].lheat = 1 robot[n].match_shots = 0 robot[n].won = False robot[n].last_damage = 0 robot[n].last_hit = 0 robot[n].transponder = n + 1 robot[n].meters = 0 robot[n].shutdown = 400 robot[n].shields_up = False robot[n].channel = robot[n].transponder robot[n].startkills = robot[n].kills robot_config(n) def init_robot(n): robot[n].wins = 0 robot[n].trials = 0 robot[n].kills = 0 robot[n].deaths = 0 robot[n].shots_fired = 0 robot[n].match_shots = 0 robot[n].hits = 0 robot[n].damage_total = 0 robot[n].cycles_lived = 0 robot[n].error_count = 0 robot[n].plen = 0 robot[n].max_time = 0 robot[n].name = '' robot[n].fn = '' robot[n].speed = 0 robot[n].arc_count = 0 robot[n].robot_time_limit = 0 robot[n].scanrange = 1500 robot[n].shotstrength = 1 robot[n].damageadj = 1 robot[n].speedadj = 1 robot[n].mines = 0 robot[n].config.scanner = 5 robot[n].config.weapon = 2 robot[n].config.armor = 2 robot[n].config.engine = 2 robot[n].config.heatsinks = 1 robot[n].config.shield = 0 robot[n].config.mines = 0 for i in range(0, max_ram + 1): robot[n].ram[i] = 0 robot[n].ram[71] = 768 for i in range(0, max_code + 1): for k in range(0, max_op + 1): robot[n].code[i].op[k] = 0 reset_hardware(n) reset_software(n) def create_robot(n, filename): #if maxavail < sizeof(robot_rec): # commented out since this will not be a problem on today's computers #prog_error(9, base_name(no_path(filename))) #robot[n] init_robot(n) filename = ucase(btrim(filename)) if filename == filename.split('.')[0]: # base_name(filename) originally if filename[0] == '?': filename = filename + locked_ext else: filename = filename + robot_ext if filename[0] == '?': filename = rstr(filename, len(filename) - 1) robot[n].fn = filename.split('/')[-1].split('.')[0] # no_path takes "dksjl/ kdsjlf/dlj" and gives you all after the last slash _compile(n, filename) robot_config(n) k = robot[n].config.scanner + robot[n].config.armor + robot[n].config.weapon + robot[n].config.engine + robot[n].config.heatsinks + robot[n].config.shield + robot[n].config.mines if k > max_config_points: prog_error(21, cstr(k) + '/' + cstr(max_config_points)) def shutdown(): #graph_mode(False) # graphics if show_cnotice: #textcolor(3) # graphics print(progname, '', version, '') print(cnotice1) print(cnotice2) print(cnotice3) #textcolor(7) # graphics if not registered: # from ATR2FUNC #textcolor(4) # graphics print('Unregistered version') else: print('Registered to: ', reg_name) # reg_name defined in ATR2FUNC #textolor(7) # graphics print() if logging_errors: for i in range(0, num_robots + 1): print('Robot error-log created: ' + robot[i].fn + '.ERR') robot[i].errorlog = open(robot[i].errorlog, 'a').close() quit() def delete_compile_report(): if os.path.isfile(main_filename + compile_ext): os.remove(main_filename + compile_ext) def write_compile_report(): f = open(main_filename + compile_ext, 'w') f.write(str(num_robots + 1)) for i in range(0, num_robots + 1): f.write(str(robot[i].fn)) f.close() #textcolor(15) # graphics print() print("All compiles successful!") print() shutdown() def parse_param(s): global step_mode global game_delay global time_slice global game_limit global matches global show_source global no_gfx global report global report_type global compile_only global show_cnotice global show_arcs global windoze global debug_info global maxcode global insane_missiles global old_shields global logging_errors global insanity global num_robots global sound_on s1 = '' found = False s = btrim(ucase(s)) if s == '': return if s[0] == '#': fn = rstr(s, len(s) - 1) if fn == fn.split('.')[0]: fn = fn + config_ext if not os.path.isfile(fn): prog_error(6, fn) f = open(fn, 'r') for line in f: s1 = ucase(btrim(s1)) if s1[0] == '#': prog_error(7, s1) else: parse_param(s1) f.close() found = True elif s[0] in ['/', '-', '=']: s1 = rstr(s, len(s) - 1) if s1[0] == 'X': step_mode = value(rstr(s1, len(s1) - 1)) found = True if step_mode == 0: step_mode = 1 if (step_mode < 1) or (step_mode > 9): prog_error(24, rstr(s1, len(s1) - 1)) if s1[0] == 'D': game_delay = value(rstr(s1, len(s1) - 1)) found = True if s1[0] == 'T': time_slice = value(rstr(s1, len(s1) - 1)) found = True if s1[0] == 'L': game_limit = value(rstr(s1, len(s1) - 1)) * 1000 found = True if s1[0] == 'Q': sound_on = False # sound_on defined in ATR2FUNC found = True if s1[0] == 'M': matches = value(rstr(s1, len(s1) - 1)) found = True if s1[0] == 'S': show_source = False found = True if s1[0] == 'G': no_gfx = True found = True if s1[0] == 'R': report = True found = True if (len(s1) > 1): report_type = value(rstr(s1, len(s1) - 1)) if s1[0] == 'C': compile_only = True found = True if s1[0] == '^': show_cnotice = False found = True if s1[0] == 'A': show_arcs = True found = True if s1[0] == 'W': windoze = False found = True if s1[0] == '$': debug_info = True found = True if s1[0] == '#': maxcode = value(rstr(s1, len(s1) - 1)) - 1 found = True if s1[0] == '!': insane_missiles = True if (len(s1) > 1): insanity = value(rstr(s1, len(s1) - 1)) found = True if s1[0] == '@': old_shields = True found = True if s1[0] == 'E': logging_errors = True found = True if insanity < 0: insanity = 0 if insanity > 15: insanity = 15 elif s[0] == ';': found = True elif(num_robots < max_robots) and (s != ''): num_robots += 1 create_robot(num_robots, s) found = True if num_robots == max_robots: print("Maximum number of robots reached.") else: prog_error(10, '') if not found: prog_error(8, s) def init(): global step_mode global logging_errors global stats_mode global insane_missiles global insanity global windoze global no_gfx global timing global matches global played global old_shields global _quit global compile_only global show_arcs global debug_info global show_cnotice global show_source global report global kill_count global maxcode global max_code global num_robots global game_limit global game_cycle global game_delay global default_delay global time_slice global default_slice global temp_mode global delay_per_sec global sound_on global reg_num if debugging_compiler or compile_by_line or show_code: print("!!! Warning !!! Compiler Debugging enabled !!!\n") step_mode = 0 # {stepping disabled} logging_errors = False stats_mode = 0 insane_missiles = False insanity = 0 delay_per_sec = 0 # initialized in ATR2FUNC windoze = True graphix = False # initialized in ATR2FUNC no_gfx = True sound_on = True # initialized in ATR2FUNC timing = True matches = 1 played = 0 old_shields = False _quit = False compile_only = False show_arcs = False debug_info = False show_cnotice = True show_source = True report = False kill_count = 0 maxcode = max_code make_tables() # in ATR2FUNC random.seed(time.time()) # "randomize" in original code num_robots = -1 game_cycle = 0 game_delay = default_delay time_slice = default_slice for i in range(0, max_missiles + 1): missile[i].a = 0 missile[i].source = -1 missile[i].x = 0 missile[i].y = 0 missile[i].lx = 0 missile[i].ly = 0 missile[i].mult = 1 registered = False # initialized in ATR2FUNC reg_name = "Unregistered" # initialized in ATR2FUNC reg_num = 0xFFFF # initialized in ATR2FUNC check_registration() # in ATR2FUNC print() #textcolor(3) # graphical print(progname, '', version, '') print(cnotice1) print(cnotice2) #textcolor(7) # graphical if not registered: #textcolor(4) # graphical print("Unregistered version") else: print("Registered to: ", reg_name) #textcolor(7) # graphical print() # {create_robot(0,'SDUCK');} delete_compile_report() if len(sys.argv) > 1: for i in range(1, len(sys.argv)): parse_param(btrim(sys.argv[i].upper())) # uses ATR2FUNC else: prog_error(5, '') temp_mode = step_mode # {store initial step_mode} if logging_errors: for i in range (0, num_robots + 1): robot[i].errorlog = open(robot[i].fn.split('.')[0] + '.ERR', 'w') if os.path.isfile(robot[i].errorlog): os.remove(robot[i].errorlog) robot[i].errorlog = open(robot[i].fn.split('.')[0] + '.ERR', 'w') robot[i].errorlog.close() if compile_only: write_compile_report() if num_robots < 1: prog_error(4, '') '''if not no_gfx: #commeting out since graphics-related graph_mode(True) # func on bool line 552 ''' # {--fix ups--} if matches > 100000: matches = 100000 if matches < 1: matches = 1 if game_delay > 1000: game_delay = 1000 if game_delay < 0: game_delay = 0 if time_slice > 100: time_slice = 100; if time_slice < 1: time_slice = 1 if game_limit < 0: game_limit = 0 if game_limit > 100000: game_limit = 100000 if maxcode < 1: maxcode = 1 # {0 based, so actually 2 lines} if maxcode > max_code: maxcode = max_code # {--Just to avoid floating pointers--} for i in range(num_robots + 1, max_robots + 3): robot[i] = robot[0] robot[-1] = robot[0] robot[-2] = robot[0] if not graphix: #print("Freemem: ", memavail) # don't have to do since we have much memavail print() # def draw_robot(n): GRAPHICAL def get_from_ram(n,i,j): if (i < 0) or (i > (max_ram + 1) + (((max_code + 1) << 3) - 1)): k = 0 robot[n].robot_error(n,4,cstr(i)) else: if i <= max_ram: k = robot[n].ram[i] else: l = i - max_ram - 1 k = robot[n].code[l >> 2].op[l & 3] return k def get_val(n,c,o): k = 0 j = (robot[n].code[c].op[max_op] >> (4*o)) & 15 i = robot[n].code[c].op[o] if (j & 7) == 1: k = get_from_ram(n,i,j) else: k = i if (j & 8) > 0: k = get_from_ram(n,k,j) return k def put_val(n,c,o,v): k = 0 i = 0 j = 0 j = (robot[n].code[c].op[max_op] >> (4 * o)) & 15 i = robot[n].code[c].op[o] if (j and 7) == 1: if (i<0) or (i>max_ram): robot_error(n,4,cstr(i)) else: if (j and 8) > 0: i = robot[n].ram[i] if (i < 0) or (i > max_ram): robot_error(n,4,cstr(i)) else: robot[n].ram[i] = v else: robot[n].ram[i] = v else: robot_error(n,3,'') def push(n,v): if (robot[n].ram[71] >= stack_base) and (robot[n].ram[71] < (stack_base + stack_size)): robot[n].ram[robot[n].ram[71]] = v robot[n].ram[71] = robot[n].ram[71] + 1 else: robot_error(n,1,cstr(robot[n].ram[71])) def pop(n): if (robot[n].ram[71] > stack_base) and (robot[n].ram[71] <= (stack_base + stack_size)): robot[n].ram[71] = robot[n].ram[71] - 1 k = robot[n].ram[robot[n].ram[71]] else: robot_error(n,5,cstr(robot[n].ram[71])) return k def find_label(n,l,m): k = -1 if m == 3: robot_error(n,9,'') elif m == 4: k = l else: for i in range(robot[n].plen,0,-1): j = robot[n].code[i].op[max_op] & 15 if (j == 2) and (robot[n].code[i].op[0] == l): k = i return k def init_mine(n,detectrange,size): k = -1 for i in range(0,max_mines): if ((robot[n].mine[i].x < 0) or (robot[n].mine[i].x > 1000) or (robot[n].mine[i].y < 0) or (robot[n].mine[i].y > 1000) or (robot[n].mine[i]._yield <= 0)) and (k < 0): k = i if k >= 0: robot[n].mine[k].x = x robot[n].mine[k].y = y robot[n].mine[k].detect = detectrange robot[n].mine[k]._yield = size robot[n].mine[k].detonate = False click() def count_missiles(): k = 0 for i in range(0,max_missiles): if missile[i].a > 0: k = k + 1 return k def init_missile(xx,yy,xxv,yyv,dir,s,blast,ob): k = -1 click() for i in range(max_missiles,0,-1): if missile[i].a == 0: k = i if k >= 0: missile[k].source = s missile[k].x = xx missile[k].lx = missile.x missile[k].y = yy missile[k].ly = missile.y missile[k].rad = 0 missile[k].lrad = 0 if missile[k].ob: missile[k].mult = 1.25 else: missile[k].mult = 1 if missile[k].blast > 0: missile[k].max_rad = missile.blast a = 2 else: if (s >= 0) and (s <= num_robots): missile[k].mult = missile[k].mult * (robot[s].shotstrength) m = missile[k].mult if ob: m = m + 0.25 missile[k].mspd = missile[k].missile_spd * missile[k].mult if insane_missiles: missile[k].mspd = 100 + (50 * insanity) * missile[k].mult if (s >= 0) and (s <= num_robots): robot[s].heat += round(20*m) robot[s].shots_fired += 1 robot[s].match_shots += 1 a = 1 missile[k].hd = dir missile[k].max_rad = mis_radius if debug_info: print('\v' + zero_pad(game_cycle,5) + ' F ' + s + ': hd=' + ' ') ### repeat until keypressed; flushkey; end; DOES NOTHING IN PYTHON def damage(n,d,physical): global debug_info if (n < 0) or (n > num_robots) or (robot[n].armor <= 0): sys.exit() if robot[n].config.shield < 3: robot[n].shields_up = False h = 0 if (robot[n].shields_up) and (not physical): dd = robot[n].d if (robot[n].old_shields) and (robot[n].config.shield >= 3): robot[n].d = 0 h = 0 else: if robot[n].config.shield == 3: robot[n].d = round(dd * 2 / 3.0) if robot[n].d < 1: robot[n].d = 1 h = round(dd * 2 / 3.0) elif robot[n].config.shield == 4: h = int(dd / 2.0) robot[n].d = dd - h elif robot[n].config.shield == 5: robot[n].d = round(dd * 1 / 3.0) if robot[n].d < 1: robot[n].d = 1 h = round(dd * 1 / 3.0) if h < 1: h = 1 if robot[n].d < 0: robot[n].d = 0 if debug_info: print('\r' + zero_pad(game_cycle,5) + ' D ' + n + ': ' + robot[n].armor + '-' + robot[n].d + '=' + str(robot[n].armor - robot[n].d) + ' ') # repeat until keypressed; flushkey; end; if robot[n].d > 0: robot[n].d = round(robot[n].d * robot[n].damageadj) if d < 1: d = 1 robot[n].armor -= robot[n].d robot[n].heat -= h robot[n].last_damage = 0 if robot[n].armor <= 0: robot[n].armor = 0 update_armor(n) robot[n].heat = 500 update_heat(n) robot[n].armor = 0 robot[n].kill_count += 1 robot[n].deaths += 1 update_lives(n) if graphix and timing: time_delay(10) # draw_robot(n) GRAPHICAL robot[n].heat = 0 update_heat(n) init_missile(robot[n].x,robot[n].y,0,0,0,n,blast_circle,False) if overburn: m = 1.3 else: m = 1 for i in range(0,num_robots): if (i != n) and (robot[i].armor > 0): k = round(distance(robot[n].x, robot[n].y, robot[i].x, robot[i].y)) if k < blast_radius: damage(i, round(abs(blast_radius - k) * m), False) def scan(n): nn = -1 _range = maxint if not (0 <= n <= num_robots): return if robot[n].scanarc < 0: robot[n].scanarc = 0 robot[n].accuracy = 0 nn = -1 _dir = (robot[n].shift + robot[n].hd) & 255 if debug_info: print('<SCAN Arc=', robot[n].scanarc, ', Dir=', _dir, '>') for i in range(0, num_robots): if (i != n) and (robot[i].armor > 0): j = find_anglei(robot[n].x, robot[n].y, robot[i].x, robot[i].y) d = distance(robot[n].x, robot[n].y, robot[i].x, robot[i].y) k = round(d) if (k < _range) and (k <= robot[n].scanrange) and ((abs(j - _dir) <= abs(robot[n].scanarc)) or (abs(j - _dir) >= 256 - abs(robot[n].scanarc))): _dir = (dir + 1024) & 255 xx = round(sint[_dir] * d + robot[n].x) yy = round(-cost[_dir] * d + robot[n].y) r = distance(xx, yy, robot[i].x, robot[i].y) if debug_window: print('SCAN HIT! Scan X,Y: ' + round(xx) + ',' + round(yy) + ' Robot X,Y: ' + round(robot[i].x) + ',' + round(robot[i].y) + ' Dist=' + round(r)) while True: if keypressed: break if (robot[n].scanarc > 0) or (r < hit_range - 2): _range = k robot[n].accuracy = 0 if robot[n].scanarc > 0: j = (j + 1024) & 255 _dir = (_dir + 1024) & 255 if (j < _dir): sign = -1 if (j > _dir): sign = 1 if (j > 190) and (_dir < 66): _dir = _dir + 256 sign = -1 if (_dir > 190) and (j < 66): j = j + 256 sign = 1 acc = abs(j - _dir) / robot[n].scanarc * 2 if sign < 0: robot[n].accuracy = -abs(round(acc)) else: robot[n].accuracy = abs(round(acc)) nn = i if debug_info: print('\r' + zero_pad(game_cycle, 5) + ' S ' + robot[n].n + ': nn=' + nn + ', range=' + _range + ', acc=' + accuracy + ' ') while True: if keypressed: break if 0 <= nn <= num_robots: robot[n].ram[5] = robot[nn].transponder robot[n].ram[6] = (robot[nn].hd - (robot[n].hd + robot[n].shift) + 1024) & 255 robot[n].ram[7] = robot[nn].spd robot[n].ram[13] = round(robot[nn].speed * 100) return _range def com_transmit(n, chan, data): for i in range(0, num_robots + 1): if (robot[i].armor > 0) and (i != n) and (robot[i].channel == chan): if (robot[i].ram[10] < 0) or (robot[i].ram[10] > max_queue): robot[i].ram[10] = 0 if (robot[i].ram[11] < 0) or (robot[i].ram[11] > max_queue): robot[i].ram[11] = 0 robot[i].ram[robot[i].ram[11] + com_queue] = data robot[i].ram[11] += 1 if (robot[i].ram[11] > max_queue): robot[i].ram[11] = 0 if (robot[i].ram[11] == robot[i].ram[10]): robot[i].ram[10] += 1 if (robot[i].ram[10] > max_queue): robot[i].ram[10] = 0 def com_receive(n): k = 0 if (robot[n].ram[10] != robot[n].ram[11]): if (robot[n].ram[10] < 0) or (robot[n].ram[10] > max_queue): robot[n].ram[10] = 0 if (robot[n].ram[11] < 0) or (robot[n].ram[11] > max_queue): robot[n].ram[11] = 0 k = robot[n].ram[robot[n].ram[10] + com_queue] robot[n].ram[10] += 1 if (robot[n].ram[10] > max_queue): robot[n].ram[10] = 0 else: robot_error(n, 12, '') return k def in_port(n,p,time_used): global minint v = 0 if p == 1: v = robot[n].spd elif p == 2: v = robot[n].heat elif p == 3: v = robot[n].hd elif p == 4: v = robot[n].shift elif p == 5: v = (robot[n].shift + robot[n].hd) & 255 elif p == 6: v = robot[n].armor elif p == 7: v = scan(n) time_used += 1 if show_arcs: robot[n].arc_count = 2 elif p == 8: v = robot[n].accuracy time_used += 1 elif p == 9: nn = -1 time_used += 3 k = 65535 nn = -1 for i in range(0,num_robots): j = round(distance(robot[n].x,robot[n].y,robot[i].x,robot[i].y)) if (n != i) and (j < k) and (robot[i].armor > 0): k = j nn = i v = k if nn in range(0,num_robots): robot[n].ram[5] = robot[nn].transponder elif p == 10: v = random.randint(0, 65535) + random.randint(0, 2) elif p == 16: nn = -1 if show_arcs: robot[n].sonar_count = 2 time_used += 40 l = -1 k = 65535 nn = -1 for i in range(0, num_robots): j = round(distance(robot[n].x, robot[n].y, robot[i].x, robot[i].y)) if (n != i) and (j < k) and (j < max_sonar) and (robot[i].armor > 0): k = j l = i nn = i if l >= 0: v = (round(find_angle(robot[n].x, robot[n].y, robot[l].x, robot[l].y) / math.pi*128 + 1024 + random(65) - 32) & 255) else: v = minint if nn in range(0,num_robots): robot[n].ram[5] = robot[nn].transponder elif p == 17: v = robot[n].scanarc elif p == 18: if robot[n].overburn: v = 1 else: v = 0 elif p == 19: v = robot[n].transponder elif p == 20: v = robot[n].shutdown elif p == 21: v = robot[n].channel elif p == 22: v = robot[n].mines elif p == 23: if robot[n].config.mines >= 0: k = 0 for i in range(0, max_mines): if (robot[n].mine[i].x >= 0) and (robot[n].mine[i].x <= 1000) and (robot[n].mine[i].y >= 0) and (robot[n].mine[i].y <= 1000) and (robot[n].mine[i]._yield > 0): k += 1 v = k else: v = 0 elif p == 24: if robot[n].config.shield > 0: if robot[n].shields_up: v = 1 else: v = 0 else: v = 0 robot[n].shields_up = False else: robot_error(n,11,cstr(p)) return v def out_port(n,p,v,time_used): if p == 11: robot[n].tspd = v if p == 12: robot[n].shift = (robot[n].shift + v + 1024) & 255 if p == 13: robot[n].shift = (v + 1024) & 255 if p == 14: robot[n].thd = (robot[n].thd + v + 1024) & 255 if p == 15: time_used += 3 if v > 4: v = 4 if v < -4: v = -4 init_missile(robot[n].x, robot[n].y, robot[n].xv, robot[n].yv, (robot[n].hd + robot[n].shift + v) & 255, n, 0, robot[n].overburn) if p == 17: robot[n].scanarc = v if p == 18: if v == 0: robot[n].overburn = False else: robot[n].overburn = True if p == 19: robot[n].transponder = v if p == 20: robot[n].shutdown = v if p == 21: robot[n].channel = v if p == 22: if robot[n].config.mines >= 0: if robot[n].mines > 0: init_mine(n,v,robot[n].mine_blast) robot[n].mines -= 1 else: robot_error(n, 14, '') else: robot_error(n, 13, '') if p == 23: if robot[n].config.mines >= 0: for i in range(0, max_mines): robot[n].mine[i].detonate = True else: robot_error(n, 13, '') if p == 24: if robot[n].config.shield >= 3: if v == 0: robot[n].shields_up = False else: robot[n].shields_up = True else: robot[n].shields_up = False robot_error(n, 15, '') else: robot_error(n, 11, cstr(p)) if robot[n].scanarc > 64: robot[n].scanarc = 64 if robot[n].scanarc < 0: robot[n].scanarc = 0 def call_int(n,int_num,time_used): if int_num == 0: damage(n,1000,True) if int_num == 1: reset_software(n) time_used = 10 if int_num == 2: time_used = 5 robot[n].ram[69] = round(robot[n].x) robot[n].ram[70] = round(robot[n].y) if int_num == 3: time_used = 2 if robot[n].ram[65] == 0: robot[n].keepshift = False else: robot[n].keepshift = True robot[n].ram[70] = robot[n].shift & 255 if int_num == 4: if robot[n].ram[65] == 0: robot[n].overburn = False else: robot[n].overburn = True if int_num == 5: time_used = 2 robot[n].ram[70] = robot[n].transponder if int_num == 6: time_used = 2 robot[n].ram[69] = game_cycle >> 16 robot[n].ram[70] = game_cycle & 65535 if int_num == 7: j = robot[n].ram[69] k = robot[n].ram[70] if j < 0: j = 0 if j > 1000: j = 1000 if k < 0: k = 0 if k > 1000: k = 1000 robot[n].ram[65] = round(find_angle(round(robot[n].x), round(robot[n].y),j,k) / math.pi * 128 + 256) & 255 time_used = 32 if int_num == 8: robot[n].ram[70] = robot[n].ram[5] time_used = 1 if int_num == 9: robot[n].ram[69] = robot[n].ram[6] robot[n].ram[70] = robot[n].ram[7] time_used = 2 if int_num == 10: k = 0 for i in range(0, num_robots): if robot[i].armor > 0: k += 1 robot[n].ram[68] = k robot[n].ram[69] = played robot[n].ram[70] = matches time_used = 4 if int_num == 11: robot[n].ram[68] = round(robot[n].speed * 100) robot[n].ram[69] = robot[n].last_damage robot[n].ram[70] = robot[n].last_hit time_used = 5 if int_num == 12: robot[n].ram[70] = robot[n].ram[8] time_used = 1 if int_num == 13: robot[n].ram[8] = 0 time_used = 1 if int_num == 14: com_transmit(n, robot[n].channel, robot[n].ram[65]) time_used = 1 if int_num == 15: if robot[n].ram[10] != robot[n].ram[11]: robot[n].ram[70] = com_receive(n) else: robot_error(n,12,'') time_used = 1 if int_num == 16: if (robot[n].ram[11] >= robot[n].ram[10]): robot[n].ram[70] = robot[n].ram[11] - robot[n].ram[10] else: robot[n].ram[70] = max_queue + 1 - robot[n].ram[10] + robot[n].ram[11] time_used = 1 if int_num == 17: robot[n].ram[10] = 0 robot[n].ram[11] = 0 time_used = 1 if int_num == 18: robot[n].ram[68] = robot[n].kills robot[n].ram[69] = robot[n].kills - robot[n].startkills robot[n].ram[70] = robot[n].deaths time_used = 3 if int_num == 19: robot[n].ram[9] = 0 robot[n].meters = 0 else: robot_error(n,10,cstr(int_num)) def jump(n, o, inc_ip): loc = find_label(n, get_val(n, robot[n].ip, 0), robot[n].code[robot[n].ip].op[max_op] >> (o * 4)) if (loc >= 0) and (loc <= robot[n].plen): inc_ip = False robot[n].ip = loc else: robot_error(n, 2, cstr(loc)) # def update_debug_bars(): # def update_debug_system(): # def update_debug_registers(): # def update_debug_flags(): # def update_debug_memory(): # def update_debug_code(): # def update_debug_window(): def update_debug_window(): # lines 2404-2428 if graphix and (step_mode > 0): update_debug_bars # {armour + heat} update_debug_system # {system variables} update_debug_registers # {registers} update_debug_flags # {flag register} update_debug_memory # {memory} update_debug_code # {code} # def init_debug_window(): # def close_debug_window(): def gameover(): global game_cycle global game_limit global num_robots if (game_cycle >= game_limit) and (game_limit > 0): return True if game_cycle & 31 == 0: k = 0 for n in range(num_robots + 1): if robot[n].armor > 0: k += 1 if k <= 0: return True else: return False else: return False def toggle_graphix(): graph_mode(not graphix) if not graphix: #textcolor(7) # graphics-related print('Match ' + played + '/' + matches + ', Battle in progress...') print() else: setscreen def invalid_microcode(n, ip): invalid = False for i in range(3): k = (robot[n].code[ip].op[max_op] >> (i << 2)) & 7 if not (k in [0, 1, 2, 4]): invalid = True return invalid def process_keypress(c): global timing global show_arcs global debug_info global windoze global bout_over global _quit global step_loop if c == 'C': calibrate_timing elif c == 'T': timing = not timing elif c == 'A': show_arcs = not show_arcs elif (c == 'S') or (c == 'Q'): if sound_on: chirp sound_on = not sound_on if sound_on: chirp elif c == '$': debug_info = not debug_info elif c == 'W': windoze = not windoze elif c == '\b': bout_over = True elif c == '\e': _quit = True step_loop = False def execute_instruction(n): global step_count global step_loop global executed # update system variables robot[n].ram[0] = robot[n].tspd robot[n].ram[1] = robot[n].thd robot[n].ram[2] = robot[n].shift robot[n].ram[3] = robot[n].accuracy time_used = 1 inc_ip = True loc = 0 if (robot[n].ip > robot[n].plen) or \ (robot[n].ip < 0): robot[n].ip = 0 if invalid_microcode(n, robot[n].ip): time_used = 1 robot_error(n, 16, hex(robot[n].code[robot[n].ip].op[max_op])) # the following is graphics-related '''elif graphix and (step_mode>0) and (n=0) then {if stepping enabled...} begin inc(step_count); update_cycle_window; update_debug_window; if (step_count mod step_mode)=0 then step_loop:=true else step_loop:=false; while step_loop and (not(quit or gameover or bout_over)) do if keypressed then with robot[0]^ do begin c:=upcase(readkey); case c of 'X':begin temp_mode:=step_mode; step_mode:=0; step_loop:=false; close_debug_window; end; ' ':begin step_count:=0; step_loop:=false; end; '1'..'9':begin step_mode:=value(c); step_count:=0; step_loop:=false; end; '0':begin step_mode:=10; step_count:=0; step_loop:=false; end; '-','_':if mem_watch>0 then begin setcolor(0); for i:=0 to 9 do outtextxy(035,212+(10*i),decimal((mem_watch+i),4) + ' :'); dec(mem_watch); update_debug_memory; end; '+','=':if mem_watch<1014 then begin setcolor(0); for i:=0 to 9 do outtextxy(035,212+(10*i),decimal((mem_watch+i),4) + ' :'); inc(mem_watch); update_debug_memory; end; '[','{':if mem_watch>0 then begin setcolor(0); for i:=0 to 9 do outtextxy(035,212+(10*i),decimal((mem_watch+i),4) + ' :'); dec(mem_watch,10); if mem_watch<0 then mem_watch:=0; update_debug_memory; end; ']','}':if mem_watch<1014 then begin setcolor(0); for i:=0 to 9 do outtextxy(035,212+(10*i),decimal((mem_watch+i),4) + ' :'); inc(mem_watch,10); if mem_watch>1014 then mem_watch:=1014; update_debug_memory; end; 'G':begin toggle_graphix; temp_mode:=step_mode; step_mode:=0; step_loop:=false; end; else process_keypress(c); end; end; end;''' if ((robot[n].code[robot[n].ip].op[max_op] & 7) in [0, 1]): time_used = 0 else: if get_val(n, robot[n].ip, 0) == 0: # NOP executed += 1 elif get_val(n, robot[n].ip, 0) == 1: # ADD put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) + get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 2: # SUB put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) - get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 3: # OR put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) | get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 4: # AND put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) & get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 5: # XOR put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) ^ get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 6: # NOT put_val(n, robot[n].ip, 1, not(get_val(n, robot[n].ip, 1))) executed += 1 elif get_val(n, robot[n].ip, 0) == 7: # MPY put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) * get_val(n, robot[n].ip, 2)) time_used = 10 executed += 1 elif get_val(n, robot[n].ip, 0) == 8: # DIV j = get_val(n, robot[n].ip, 2) if j != 0: put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) // j) time_used = 10 executed += 1 elif get_val(n, robot[n].ip, 0) == 9: # MOD j = get_val(n, robot[n].ip, 2) if j != 0: put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) % j) else: robot_error(n, 8, '') time_used = 10 executed += 1 elif get_val(n, robot[n].ip, 0) == 10: # RET robot[n].ip = pop(n) if (robot[n].ip < 0) or (robot[n].ip > robot[n].plen): robot_error(n, 7, cstr(robot[n].ip)) executed += 1 elif get_val(n, robot[n].ip, 0) == 11: # GSB loc = find_label(n, get_val(n, robot[n].ip, 1), code[robot[n].ip].op[max_op] >> (1 * 4)) # local variable if loc >= 0: push(n, robot[n].ip) inc_ip = False # local variable robot[n].ip = loc else: robot_error(n, 2, cstr(get_val(n, robot[n].ip, 1))) executed += 1 elif get_val(n, robot[n].ip, 0) == 12: # JMP jump(n, 1, inc_ip) executed += 1 elif get_val(n, robot[n].ip, 0) == 13: # JLS, JB if robot[n].ram[64] & 2 > 0: jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 14: # JGR, JA if robot[n].ram[64] & 4 > 0: jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 15: # JNE if robot[n].ram[64] & 1 == 0: jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 16: # JEQ, JE if robot[n].ram[64] & 1 > 0: jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 17: # SWAP, XCHG robot[n].ram[4] = get_val(n, robot[n].ip, 1) put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 2)) put_val(n, robot[n].ip, 2, robot[n].ram[4]) time_used = 3 executed += 1 elif get_val(n, robot[n].ip, 0) == 18: # DO robot[n].ram[67] = get_val(n, robot[n].ip, 1) executed += 1 elif get_val(n, robot[n].ip, 0) == 19: # LOOP robot[n].ram[67] -= 1 if robot[n].ram[67] > 0: jump(n, 1, inc_ip) executed += 1 elif get_val(n, robot[n].ip, 0) == 20: # CMP k = get_val(n, robot[n].ip, 1) - get_val(n, robot[n].ip, 2) robot[n].ram[64] = robot[n].ram[64] & 0xFFF0 if k == 0: robot[n].ram[64] = robot[n].ram[64] | 1 if k < 0: robot[n].ram[64] = robot[n].ram[64] | 2 if k > 0: robot[n].ram[64] = robot[n].ram[64] | 4 if (get_val(n, robot[n].ip, 2) == 0) and (k == 0): robot[n].ram[64] = robot[n].ram[64] | 8 executed += 1 elif get_val(n, robot[n].ip, 0) == 21: # TEST k = get_val(n, robot[n].ip, 1) & get_val(n, robot[n].ip, 2) robot[n].ram[64] = robot[n].ram[64] & 0xFFF0 if k == get_val(n, robot[n].ip, 2): robot[n].ram[64] = robot[n].ram[64] | 1 if k == 0: robot[n].ram[64] = robot[n].ram[64] | 8 executed += 1 elif get_val(n, robot[n].ip, 0) == 22: # MOV, SET put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 23: # LOC put_val(n, robot[n].ip, 1, robot[n].code[robot[n].ip].op[2]) time_used = 2 executed += 1 elif get_val(n, robot[n].ip, 0) == 24: # GET k = get_val(n, robot[n].ip, 2) if (k >= 0) and (k <= max_ram): put_val(n, robot[n].ip, 1, robot[n].ram[k]) elif (k > max_ram) and (k <= (max_ram + 1) + (((max_code + 1) << 3) - 1)): j = k - max_ram - 1 put_val(n, robot[n].ip, 1, robot[n].code[j >> 2].op[j & 3]) else: robot_error(n, 4, cstr(k)) time_used = 2 executed += 1 elif get_val(n, robot[n].ip, 0) == 25: # PUT k = get_val(n, robot[n].ip, 2) if (k >= 0) and (k <= max_ram): robot[n].ram[k] = get_val(n, robot[n].ip, 1) else: robot_error(n, 4, cstr(k)) time_used = 2 executed += 1 elif get_val(n, robot[n].ip, 0) == 26: # INT call_int(n, get_val(n, robot[n].ip, 1), time_used) executed += 1 elif get_val(n, robot[n].ip, 0) == 27: # IPO, IN time_used = 4 put_val(n, robot[n].ip, 2, in_port(n, get_val(n, robot[n].ip, 1), time_used)) executed += 1 elif get_val(n, robot[n].ip, 0) == 28: # OPO, OUT time_used = 4 out_port(n, get_val(n, robot[n].ip, 1), get_val(n, robot[n].ip, 2), time_used) executed += 1 elif get_val(n, robot[n].ip, 0) == 29: # DEL, DELAY time_used = get_val(n, robot[n].ip, 1) executed += 1 elif get_val(n, robot[n].ip, 0) == 30: # PUSH push(n, get_val(n, robot[n].ip, 1)) executed += 1 elif get_val(n, robot[n].ip, 0) == 31: # POP put_val(n, robot[n].ip, 1, pop(n)) executed += 1 elif get_val(n, robot[n].ip, 0) == 32: # ERR robot_error(n, get_val(n, robot[n].ip, 1), '') time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 33: # INC put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) + 1) executed += 1 elif get_val(n, robot[n].ip, 0) == 34: # DEC put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) - 1) executed += 1 elif get_val(n, robot[n].ip, 0) == 35: # SHL put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) << get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 36: # SHR put_val(n, robot[n].ip, 1, get_val(n, robot[n].ip, 1) >> get_val(n, robot[n].ip, 2)) executed += 1 elif get_val(n, robot[n].ip, 0) == 37: # ROL put_val(n, robot[n].ip, 1, rol(get_val(n, robot[n].ip, 1), get_val(n, robot[n].ip, 2))) executed += 1 elif get_val(n, robot[n].ip, 0) == 38: # ROR put_val(n, robot[n].ip, 1, ror(get_val(n, robot[n].ip, 1), get_val(n, robot[n].ip, 2))) executed += 1 elif get_val(n, robot[n].ip, 0) == 39: # JZ time_used = 0 if robot[n].ram[64] & 8 > 0: jump(n, 1, inc_ip) executed += 1 elif get_val(n, robot[n].ip, 0) == 40: # JNZ time_used = 0 if robot[n].ram[64] & 8 == 0: jump(n, 1, inc_ip) executed += 1 elif get_val(n, robot[n].ip, 0) == 41: # JAE, JGE if (robot[n].ram[64] & 1 > 0) or (robot[n].ram[64] & 4 > 0): jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 42: # JBE, JLE if (robot[n].ram[64] & 1 > 0) or (robot[n].ram[64] & 2 > 0): jump(n, 1, inc_ip) time_used = 0 executed += 1 elif get_val(n, robot[n].ip, 0) == 43: # SA put_val(n, robot[n].ip, 1, sal(get_val(n, robot[n].ip, 1), get_val(n, robot[n].ip, 2))) executed += 1 elif get_val(n, robot[n].ip, 0) == 44: # SAR put_val(n, robot[n].ip, 1, sar(get_val(n, robot[n].ip, 1), get_val(n, robot[n].ip, 2))) executed += 1 elif get_val(n, robot[n].ip, 0) == 45: # NEG put_val(n, robot[n].ip, 1, 0 - get_val(n, robot[n].ip, 1)) executed += 1 elif get_val(n, robot[n].ip, 0) == 46: # JTL loc = get_val(n, robot[n].ip, 1) if (loc >= 0) and (loc <= robot[n].plen): inc_ip = False robot[n].ip = loc else: robot_error(n, 2, cstr(loc)) else: robot_error(n, 6, '') robot[n].delay_left += time_used if inc_ip: robot[n].ip += 1 if graphix and (n == 0) and (step_mode > 0): update_debug_window() def do_robot(n): global executed if (n < 0) or (n > num_robots): return if robot[n].armor <= 0: return # Time slice robot[n].time_left = time_slice if (robot[n].time_left > robot[n].robot_time_limit) and (robot[n].robot_time_limit > 0): robot[n].time_left = robot[n].robot_time_limit if (robot[n].time_left > robot[n].max_time) and (robot[n].max_time > 0): robot[n].time_left = robot[n].max_time executed = 0 # Execute timeslice while (robot[n].time_left > 0) and (not robot[n].cooling) and (executed < 20 + time_slice) and (robot[n].armor > 0): if robot[n].delay_left < 0: robot[n].delay_left = 0 if (robot[n].delay_left > 0): robot[n].delay_left -= 1 robot[n].time_left -= 1 if (robot[n].time_left >= 0) and (robot[n].delay_left == 0): execute_instruction(n) if robot[n].heat >= robot[n].shutdown: robot[n].cooling = True robot[n].shields_up = False if robot[n].heat >= 500: damage(n, 1000, True) # Fix up variables robot[n].thd = (robot[n].thd + 1024) & 255 robot[n].hd = (robot[n].hd + 1024) & 255 robot[n].shift = (robot[n].shift + 1024) & 255 if robot[n].tspd < -75: robot[n].tspd = -75 if robot[n].tspd > 100: robot[n].tspd = 100 if robot[n].spd < -75: robot[n].spd = -75 if robot[n].spd > 100: robot[n].spd = 100 if robot[n].heat < 0: robot[n].heat = 0 if robot[n].last_damage < maxint: robot[n].last_damage += 1 if robot[n].last_hit < maxint: robot[n].last_hit += 1 if robot[n].shields_up and (game_cycle & 3 == 0): robot[n].heat += 1 if not robot[n].shields_up: if robot[n].heat > 0: if robot[n].config.heatsinks == 5: if game_cycle & 1 == 0: robot[n].heat -= 1 elif robot[n].config.heatsinks == 4: if game_cycle % 3 == 0: robot[n].heat -= 1 elif robot[n].config.heatsinks == 3: if game_cycle & 3 == 0: robot[n].heat -= 1 elif robot[n].config.heatsinks == 2: if game_cycle & 7 == 0: robot[n].heat -= 1 elif game_cycle & 3 == 0: robot[n].heat += 1 if robot[n].overburn and (game_cycle % 3 == 0): robot[n].heat += 1 if (robot[n].heat > 0): robot[n].heat -= 1 if (robot[n].heat > 0) and (game_cycle and 7 == 0) and (abs(robot[n].tspd) <= 25): robot[n].heat -= 1 if (robot[n].heat <= robot[n].shutdown - 50) or (robot[n].heat <= 0): robot[n].cooling = False if robot[n].cooling: robot[n].tspd = 0 heat_mult = 1 if 80 <= robot[n].heat <= 99: heat_mult = 0.98 elif 100 <= robot[n].heat <= 149: heat_mult = 0.95 elif 150 <= robot[n].heat <= 199: heat_mult = 0.85 elif 200 <= robot[n].heat <= 249: heat_mult = 0.75 elif 250 <= robot[n].heat <= maxint: heat_mult = 0.50 if robot[n].overburn: heat_mult = heat_mult * 1.30 if (robot[n].heat >= 475) and (game_cycle & 3 == 0): damage(n, 1, True) elif (robot[n].heat >= 450) and (game_cycle & 7 == 0): damage(n, 1, True) elif (robot[n].heat >= 400) and (game_cycle & 15 == 0): damage(n, 1, True) elif (robot[n].heat >= 350) and (game_cycle & 31 == 0): damage(n, 1, True) elif (robot[n].heat >= 300) and (game_cycle & 63 == 0): damage(n, 1, True) if (abs(robot[n].spd - robot[n].tspd) <= acceleration): robot[n].spd = robot[n].tspd else: if robot[n].tspd > robot[n].spd: robot[n].spd += acceleration else: robot[n].spd -= acceleration tthd = robot[n].hd + robot[n].shift if (abs(robot[n].hd - robot[n].thd) <= turn_rate) or (abs(robot[n].hd - robot[n].thd) >= 256 - turn_rate): robot[n].hd = robot[n].thd elif robot[n].hd != robot[n].thd: k = 0 if ((robot[n].thd > robot[n].hd) and (abs(robot[n].hd - robot[n].thd) <= 128)) or ((robot[n].thd < robot[n].hd) and (abs(robot[n].hd - robot[n].thd) >= 128)): k = 1 if k == 1: robot[n].hd = (robot[n].hd + turn_rate) & 255 else: robot[n].hd = (robot[n].hd + 256 - turn_rate) & 255 robot[n].hd = robot[n].hd & 255 if robot[n].keepshift: robot[n].shift = (tthd - robot[n].hd + 1024) & 255 robot[n].speed = robot[n].spd / 100 * (max_vel * heat_mult * robot[n].speedadj) robot[n].xv = sint[robot[n].hd] * robot[n].speed robot[n].yv = -cost[robot[n].hd] * robot[n].speed if (robot[n].hd == 0) or (robot[n].hd == 128): robot[n].xv = 0 if (robot[n].hd == 64) or (robot[n].hd == 192): robot[n].yv = 0 if robot[n].xv != 0: ttx = robot[n].x + robot[n].xv else: ttx = robot[n].x if robot[n].yv != 0: tty = robot[n].y + robot[n].yv else: tty = robot[n].y if (ttx < 0) or (tty < 0) or (ttx > 1000) or (tty > 1000): robot[n].ram[8] += 1 robot[n].tspd = 0 if abs(robot[n].speed) >= max_vel / 2: damage(n, 1, True) robot[n].spd = 0 for i in range (0, num_robots + 1): if (i != n) and (robot[i].armor > 0) and (distance(ttx, tty, robot[i].x, robot[i].y) < crash_range): robot[n].tspd = 0 robot[n].spd = 0 ttx = robot[n].x tty = robot[n].y robot[i].tspd = 0 robot[i].spd = 0 robot[n].ram[8] += 1 robot[i].ram[8] += 1 if abs(robot[n].speed) >= max_vel / 2: damage(n, 1, True) damage(i, 1, True) if ttx < 0: ttx = 0 if tty < 0: tty = 0 if ttx > 1000: ttx = 1000 if tty > 0: tty = 1000 robot[n].meters = robot[n].meters + distance(robot[n].x, robot[n].y, ttx, tty) if robot[n].meters >= maxint: robot[n].meters = robot[n].meters - maxint robot[n].ram[9] = int(robot[n].meters) robot[n].x = ttx robot[n].y = tty if robot[n].armor < 0: robot[n].armor = 0 if robot[n].heat < 0: robot[n].heat = 0 if graphix: if robot[n].armor != robot[n].larmor: update_armor(n) if robot[n].heat // 5 != robot[n].lheat // 5: update_heat(n) draw_robot(n) robot[n].lheat = robot[n].heat robot[n].larmor = robot[n].armor robot[n].cycles_lived += 1 def do_mine(n, m): global kill_count if ((robot[n].mine[m].x >= 0) and (robot[n].mine[m].x <= 1000) and (robot[n].mine[m].y >= 0) and (robot[n].mine[m].y <= 1000) and (robot[n].mine[m]._yield > 0)): for i in range(0, num_robots + 1): if (robot[i].armor > 0) and (i != n): d = distance(robot[n].mine[m].x, robot[n].mine[m].y, robot[i].x, robot[i].y) if (d <= robot[n].mine[m].detect): robot[n].mine[m].detonate = True if (robot[n].mine[m].detonate): init_missile(robot[n].mine[m].x, robot[n].mine[m].y, 0, 0, 0, n, mine_circle, False) kill_count = 0 if (robot[n].armor > 0): source_alive = True else: source_alive = False for i in range(0, num_robots + 1): if (robot[i].armor > 0): k = round(distance(robot[n].mine[m].x, robot[n].mine[m].y, robot[i].x, robot[i].y)) if k < robot[n].mine[m]._yield: damage(i, round(abs(_yield - k)), False) if (0 <= n <= num_robots) and (i != n): robot[n].damage_total += round(abs(_yield - k)) if (kill_count > 0) and (source_alive) and (robot[n].armor <= 0): kill_count -= 1 if kill_count > 0: robot[n].kills += kill_count update_lives(n) if graphix: pass #putpixel(round(x*screen_scale)+screen_x,round(y*screen_scale)+screen_y,0); # graphics robot[n].mine[m]._yield = 0 robot[n].mine[m].x = -1 robot[n].mine[m].y = -1 else: if graphix and (game_cycle & 1 == 0): pass '''main_viewport; setcolor(robot_color(n)); line(round(x*screen_scale)+screen_x,round(y*screen_scale)+screen_y-1, round(x*screen_scale)+screen_x,round(y*screen_scale)+screen_y+1); line(round(x*screen_scale)+screen_x+1,round(y*screen_scale)+screen_y, round(x*screen_scale)+screen_x-1,round(y*screen_scale)+screen_y);''' def do_missile(n): global kill_count missile[n] if a == 0: pass else: if a ==1: if (x<-20) | (x>1020) | (y<-20) | (y>1020): a = 0 llx = lx lly = ly lx = x ly = y if a > 0: hd = (hd+256) and 255 xv = sint[hd] * mspd yv = -cost[hd]*mspd x = x+xv y = y +yv #look for hit on a robot k =1 l = mixint for i in len(num_robots): if(i.armor>0) and (i !=source): d = distance(lx,ly,robot[i].x,robot[i].y) if (d<=mspd) and (r<hit_range) and (round(d)<=1): k= i l = round(d) dd = round(r) tx = xx ty = y if k >= 0: x = tx y = ty a = 2 rad = 0 lrad = 0 if source in range(0,num_robots): robot[source].last_hit = 0 (robot[source].hits) + 1 for i in range(0,num_robots): dd = round(distance(x,y,robot[i].x,robot[i].y)) if dd <=hit_range: dam = round(abs(hit_range-dd)*mult) if dam <= 0: dam = 1 kill_count = 0 if robot[source].armor>0: source_alive = True else: source_alive = False damage(i,dam,False) if source in range(0,num_robots) and (i!= source): (robot[source].damage_tota,dam)+1 if kill_count > 0 and source_alive and robot[source].armor <=0: kill_count -=1 if kill_count > 0: robot[source].kills +=1 kill_count +=1 update_lives(source) #draw missile def victor_string(k, n): s = '' if k == 1: s = 'Robot #' + cstr(n + 1) + ' (' + robot[n].fn + ') wins!' if k == 0: s = 'Simultaneous destruction, match is a tie.' if k > 1: s = 'No clear victor, match is a tie.' return s def show_statistics(): i = 0 j = 0 k = 0 n = 0 sx = 0 sy = 0 sx = 24 sy = 93 - num_robots * 3 # viewport(0,0,639,479) # box(sx+0,sy,sx+591,sy+102+num_robots*12) # hole(sx + 4, sy + 4, sx + 587, sy + 98 + num_robots * 12) # setfillpattern(gray50,1) # bar(sx+5,sy+5,sx+586,sy+97+num_robots*12) # setcolor(15) # outtextxy(sx+16,sy+20, 'Robot Scored wins Matches Armor kills death shots') # outtextxy(sx+16,sy+30) n = -1 k =0 for i in range(num_robots + 1): armor = robot[i].armor if robot[i].armor > 0 | robot[i].armor == robot[i].won: k += 1 for i in range(num_robots + 1): robot[i].armor = robot[i].armor # setcolor(robot_color(i)) if k == 1 and n == i: j = 1 else: j = 0 ''' outtextxy(sx+016,sy+042+i*12,addfront(cstr(i+1),2)+' - '+addrear(fn,15)+cstr(j) +addfront(cstr(wins),8)+addfront(cstr(trials),8) +addfront(cstr(armor)+'%',9)+addfront(cstr(kills),7) +addfront(cstr(deaths),8)+addfront(cstr(match_shots),9)); ''' # outtextxy(sx+16,sy+42+i*12,addfront(str(i+1),2) +'- '+ addrear(fn,15) + str(j)) # setcolor(15) # outtextxy(sx+16,sy+64,num_robots*12,victor_string(k,n)) if windoze: pass # outtextxy(sx+16,sy+76+num_robots*12, 'Press any key to continue...') # flushkey # readkey # textcolor(15) print(chr(13) + ' ' + chr(13)) print('\n Match', played, '/', matches, 's') print('Robot Scored Wins Matches Armor Kills Deaths Shots') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') n = -1 k = 0 for i in range(num_robots + 1): if robot[i].armor > 0 or robot[i].won: k += 1 n = i for i in range(num_robots + 1): # textcolor(robot_color[i]) if k == 1 and n == i: j = 1 else: j = 0 print(addfront(cstr(i + 1), 2) + ' - ' + \ addrear(robot[i].fn, 15)+cstr(j) + \ addfront(cstr(robot[i].wins), 8) + \ addfront(cstr(robot[i].trials), 8) + \ addfront(cstr(robot[i].armor) + '%', 9) + \ addfront(cstr(robot[i].kills), 7) + \ addfront(cstr(robot[i].deaths), 8) + \ addfront(cstr(robot[i].match_shots), 9)) # textcolor(15) # print('\n') print(victor_string(k,n)) print('\n') def score_robots(): k = 0 n = -1 for i in range(0, num_robots + 1): robot[i].trials += 1 if robot[i].armor > 0: k += 1 n = i if (k == 1) and (n >= 0): robot[n].wins += 1 robot[n].won = True def init_bout(): global game_cycle game_cycle = 0 for i in range(max_missiles): missile[i].a = 0 missile[i].source = -1 missile[i].x = 0 missile[i].y = 0 missile[i].lx = 0 missile[i].ly = 0 missile[i].mult = 1 for i in range(num_robots + 1): robot[i].mem_watch = 128 reset_hardware(i) reset_software(i) if graphix: setscreen if graphix and (step_mode > 0): init_debug_window if not graphix: pass # textcolor(7) def bout(): global game_cycle global game_delay global played global step_loop global step_mode global _quit global graphix if _quit: sys.exit() played += 1 init_bout() bout_over = False if step_mode == 0: step_loop = False else: step_loop = True step_count = -1 if graphix and (step_mode > 0): for i in range(num_robots + 1): draw_robot(i) while not _quit and not gameover() and not bout_over: game_cycle += 1 for i in range(num_robots + 1): if robot[i].armor > 0: do_robot(i) for i in range(max_missiles): if missile[i].a > 0: do_missile(i) for i in range(num_robots + 1): for k in range(max_mines): if robot[i].mine[k]._yield > 0: do_mine(i,k) if graphix and timing: time_delay(game_delay) if keypressed: c = str(pygame.key.get_pressed()).upper() else: c = chr(255) if c == 'X': if not robot[0].is_locked: if not graphix: toggle_graphix() if robot[0].armor > 0: if temp_mode > 0: step_mode = temp_mode else: step_mode = 1 step_count += 1 init_debug_window() elif c == '+' or c == '=': if game_delay < 100: if game_delay in range(0,5): game_delay = 5 elif game_delay in range(5,10): game_delay = 10 elif game_delay in range(10,15): game_delay = 15 elif game_delay in range(15,20): game_delay = 30 elif game_delay in range(20,30): game_delay = 40 elif game_delay in range(30,40): game_delay = 50 elif game_delay in range(50,60): game_delay = 60 elif game_delay in range(60,75): game_delay = 75 else: game_delay = 100 elif c == '-' or c == '_': if game_delay > 0: if game_delay in range(0,6): game_delay = 0 elif game_delay in range(6,11): game_delay = 5 elif game_delay in range(11,16): game_delay = 10 elif game_delay in range(16,21): game_delay = 15 elif game_delay in range(21,31): game_delay = 20 elif game_delay in range(31,41): game_delay = 30 elif game_delay in range(41,51): game_delay = 40 elif game_delay in range(51,61): game_delay = 50 elif game_delay in range(61,75): game_delay = 60 else: game_delay = 75 elif c == 'G': toggle_graphix() else: process_keypress(c) if game_delay < 0: game_delay = 0 if game_delay > 100: game_delay = 100 if game_delay in range(0,2): k = 100 elif game_delay in range(2,6): k = 50 elif game_delay in range(6,11): k = 25 elif game_delay in range(11,26): k = 20 elif game_delay in range(26,41): k = 10 elif game_delay in range(41,71): k = 5 elif game_delay in range(71,maxint + 1): k = 1 else: k = 10 if not graphix: k = 100 if graphix: if ((game_cycle % k) == 0) or (game_cycle == 10): update_cycle_window() else: if (update_timer != mem[0:0x46C] >> 1): update_cycle_window() update_timer = mem[0:0x46C] >> 1 update_cycle_window() # Commented out in the original: {if (not graphix) then print;} score_robots() show_statistics() def write_report(): f = open(main_filename + report_ext, 'w') f.write(str(num_robots + 1)) for i in range(0, num_robots + 2): if report_type == 2: f.write(str(robot[i].wins) + ' ' + str(robot[i].trials) + ' ' + str(robot[i].kills) + ' ' + str(robot[i].deaths) + ' ' + str(robot[i].fn) + ' ') elif report_type == 3: f.write(str(robot[i].wins) + ' ' + str(robot[i].trials) + ' ' + str(robot[i].kills) + ' ' + str(robot[i].deaths) + ' ' + str(robot[i].armor) + ' ' + str(robot[i].heat) + ' ' + str(robot[i].shots_fired) + ' ' + str(robot[i].fn) + ' ') elif report_type == 4: f.write(str(robot[i].wins) + ' ' + str(robot[i].trials) + ' ' + str(robot[i].kills) + ' ' + str(robot[i].deaths) + ' ' + str(robot[i].armor) + ' ' + str(robot[i].heat) + ' ' + str(robot[i].shots_fired) + ' ' + str(robot[i].hits) + ' ' + str(robot[i].damage_total) + ' ' + str(robot[i].cycles_lived) + ' ' + str(robot[i].error_count) + ' ' + str(robot[i].fn) + ' ') else: f.write(str(robot[i].wins) + ' ' + str(robot[i].trials) + ' ' + str(robot[i].fn) + ' ') f.close() def begin_window(): if (not graphix) or (not windoze): pass # May need to be a sys.exit() setscreen viewport(0,639,479) box(100,150,539,200) hole(105,155,534,195) setfillpattern(gray50,1) bar(105,155,534,195) setcolor(15) s = 'Press any to begin!' outtextxy(320-((len(s) << 3) >> 1), 172,s) flushkey readkey setscreen def main(): if graphix: begin_window if matches > 0: for i in range(1, matches + 1): bout() if not graphix: print() if _quit: return if matches > 1: print() print() graph_mode(False) # textcolor(15) print('Bout complete! (', matches, ' matches)') print() k = 0 w = 0 for i in range(0, num_robots + 1): if robot[i].wins == w: k = k + 1 if robot[i].wins > w: k = 1 n = i w = robot[i].wins print('Robot Wins Matches Kills Deaths Shots') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') for i in range(0, num_robots + 1): # textcolor(robot_color(i)) print(addfront(cstr(i + 1), 2) + ' - ' + addrear(robot[i].fn, 8) + addfront(cstr(robot[i].wins), 7) + addfront(cstr(robot[i].trials), 8) + addfront(cstr(robot[i].kills), 8) + addfront(cstr(robot[i].deaths), 8) + addfront(cstr(robot[i].shots_fired), 9)) # textcolor(15) print() if k == 1: print('Robot #', n + 1, ' (', robot[n].fn, ') wins the bout! (score: ', w, '/', matches, ')') else: print('There is no clear victor!') print() elif graphix: graph_mode(False) show_statistics() if report: write_report() if __name__ == "__main__": pygame.init() init() main() shutdown() pygame.quit() else: print("Being Imported")
dad6a2a99d68d4818c8e44550bdb93755b59a64e
[ "Markdown", "Python" ]
7
Python
Seth0110/omurice
309f9dddf776a221fca8b21284a7f2f3e3b5894b
0c554a51e6f5357d2f28310ec695f228ced6b4b4
refs/heads/master
<repo_name>LRTNZ/test-vlc-application<file_sep>/app/build.gradle apply plugin: 'com.android.application' android { // Compiles for android 9 compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.LRTNZ.testvlcapplication" minSdkVersion 26 targetSdkVersion 29 versionCode 1 versionName "1.0" ndk { abiFilters "armeabi", "armeabi-v7a", "x86", "mips" } signingConfig signingConfigs.debug } buildTypes { debug { debuggable true jniDebuggable true signingConfig signingConfigs.debug } release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } lintOptions { // The app isn't indexed, doesn't have translations, and has a // banner for AndroidTV that's only in xhdpi density. disable 'GoogleAppIndexingWarning','MissingTranslation','IconDensities' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.aar']) implementation 'androidx.leanback:leanback:1.0.0' // Logging tool wrapper used in the app, instead of the default logger. implementation 'com.jakewharton.timber:timber:4.7.1' } <file_sep>/app/src/main/java/com/LRTNZ/testvlcapplication/App.java package com.LRTNZ.testvlcapplication; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.EditText; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Timer; import java.util.TimerTask; import org.jetbrains.annotations.NotNull; import org.videolan.libvlc.LibVLC; import org.videolan.libvlc.Media; import org.videolan.libvlc.MediaPlayer; import org.videolan.libvlc.interfaces.IVLCVout; import timber.log.Timber; /** * Main Activity of the application */ public class App extends Activity implements IVLCVout.Callback{ /** * {@link LibVLC} instance variable, to be used as required */ LibVLC libVLC = null; /** * {@link org.videolan.libvlc.MediaPlayer} instance, used to play the media in the app */ org.videolan.libvlc.MediaPlayer mediaPlayer = null; /** * {@link Media} source instance, provides the source for the {@link #mediaPlayer} instance */ static Media mediaSource; /** * {@link IVLCVout} instance to be used in the app */ IVLCVout vlcOut; // Surfaces for the stream to be displayed on SurfaceHolder vidHolder; SurfaceView vidSurface; /** * {@link Integer} value of which of the two streams is being played */ // Actual first stream to be played is the inverse of this, just the quick logic setup I put together needs it this way int currentStreamIndex = 1; /** * {@link String} value of the network address of the current streaming source to be played back */ String currentStreamAddress = ""; // Text box at the top of the screen, that will have the current stream name/index being played in it, to make it easy to see what is happening in the application /** * {@link EditText} that is the box at the top of the screen showing the details about the current stream being played */ EditText streamName; /** * {@link ArrayList}<{@link String}> of the two IP addresses of the multicast streams that are to be cycled through. * These are where you load in the addressed of the two multicast streams you are creating on your own network, to run this application. */ // |---------------------------| // | Configure stream IPs here | // |---------------------------| ArrayList<String> streamAddresses = new ArrayList<String>(){{ add("udp://@172.16.58.3:1234"); add("udp://@172.16.31.10:1234"); }}; ArrayList<String> videoFiles = new ArrayList<String>(){{ add("resort_flyover.mp4"); add("waves_crashing.mp4"); }}; static boolean streamOrFile = true; static int numPlaybacks = 0; @Override protected void onCreate(Bundle savedInstance){ // Run the super stuff for this method super.onCreate(savedInstance); // Creates the timber debug output, and sets the tag for the log messages if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree() { @Override protected void log(int priority, String tag, @NotNull String message, Throwable t) { super.log(priority, "Test-VLC", message, t); } }); Timber.d("In debug mode"); } // Sets the main view setContentView(R.layout.main); // Populates and loads the two values for the video layout stuff vidSurface = findViewById(R.id.video_layout); vidSurface.setVisibility(View.VISIBLE); vidHolder = vidSurface.getHolder(); // Adds arguments to the list of args to pass when initialising the lib VLC instance. // If you need to add in more arguments to the vlc instance, just follow the format below // |-----------------------------| // | Additional LibVLC Arguments | // |-----------------------------| addArg("fullscreen", "--fullscreen"); addArg("verbose", "-vvv"); // addArg("deinterlace", "--deinterlace=1"); //addArg("mode","--deinterlace-mode=yadif"); // addArg("filter","--video-filter=deinterlace"); // Load the editText variable with a reference to what it needs to fill in the layout streamName = findViewById(R.id.stream_ID); // Run the libVLC creation/init method createLibVLC(); } /** * Method that handles the creation of the {@link LibVLC} instance */ public void createLibVLC() { // Get the list of arguments from the provided arguments above ArrayList<String> args = new ArrayList<>(arguments.values()); // Debug: Print out the passed in arguments Timber.d("Arguments for VLC: %s", args); // Create the LibVLC instance, with the provided arguments libVLC = new LibVLC(this, args); // Create the new media player instance to be used mediaPlayer = new org.videolan.libvlc.MediaPlayer(libVLC); // Get the details of the display DisplayMetrics displayMetrics = new DisplayMetrics(); // Load displayMetrics with the details of the default display of the device getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); // Set the size of the mediaplayer to match the resolution of the device's screen mediaPlayer.getVLCVout().setWindowSize(displayMetrics.widthPixels, displayMetrics.heightPixels); // Load vlcOut with the value from the created media player vlcOut = mediaPlayer.getVLCVout(); // Passes the event listener for the media player to use to be this runnable/lambda mediaPlayer.setEventListener(event -> { // Standard switch between all the different events thrown by the mediaplayer switch (event.type) { case MediaPlayer.Event.Buffering: // Timber.d("onEvent: Buffering"); break; case MediaPlayer.Event.EncounteredError: Timber.d("onEvent: EncounteredError"); break; case MediaPlayer.Event.EndReached: //Timber.d("onEvent: EndReached"); break; case MediaPlayer.Event.ESAdded: // Timber.d("onEvent: ESAdded"); break; case MediaPlayer.Event.ESDeleted: // Timber.d("onEvent: ESDeleted"); break; case MediaPlayer.Event.MediaChanged: Timber.d("onEvent: MediaChanged"); //mediaPlayer.setVolume(0); break; case MediaPlayer.Event.Opening: Timber.d("onEvent: Opening"); break; case MediaPlayer.Event.PausableChanged: // Timber.d("onEvent: PausableChanged"); break; case MediaPlayer.Event.Paused: // Timber.d("onEvent: Paused"); break; case MediaPlayer.Event.Playing: Timber.d("onEvent: Playing"); break; case MediaPlayer.Event.PositionChanged: // Timber.d("onEvent: PositionChanged"); break; case MediaPlayer.Event.SeekableChanged: // Timber.d("onEvent: SeekableChanged"); break; case MediaPlayer.Event.Stopped: Timber.d("onEvent: Stopped"); break; case MediaPlayer.Event.TimeChanged: // Timber.d("onEvent: TimeChanged"); break; case MediaPlayer.Event.Vout: // Timber.d("onEvent: Vout"); break; } }); // Call the change stream, to preload the first stream at startup, instead of waiting for an input changeStream(); // If you do not have the means to automatically generate an alternative two pulse up/two pulse down signal input for the Android TV, // these two lines can be uncommented in order to enable the automatic up/down changing. // The reason there are the two input options, is to prove it is not the source of the call to changing the stream that is causing the issues with the crashing. // |------------------------------------| // | Optional automatic stream changing | // |------------------------------------| runAutomaticTimer = true; runTimedStreamChange(); } /** * {@link LinkedHashMap}<{@link String}, {@link String}> of the arguments that are to be passed to the LibVLC instance */ static LinkedHashMap<String, String> arguments = new LinkedHashMap<>(); /** * Method that takes a k/v pair and adds it to the map of arguments to be used when creating the LibVLC instance. * The key is used in the full application, as the potential to remove existing arguments is present there. * * @param argName {@link String} value of the name to use as the key for the argument * @param argValue {@link String} value of the argument that will be recognised when passed to LibVLC */ public void addArg(String argName, String argValue) { // If the argument with the key already exists, just update the existing one to the new value if (arguments.containsKey(argName)) { arguments.replace(argName, argValue); } else { // Otherwise if the argument does not exist, add it as a new one to the list arguments.put(argName, argValue); } } @Override public void onNewIntent(Intent intent) { // Standard android stuff super.onNewIntent(intent); Timber.d("Player ran new intent"); setIntent(intent); } @Override public void onStart() { // Run super stuff super.onStart(); // Set the output view to use for the video to be the surface vlcOut.setVideoView(vidSurface); // Add the callback for the vlcOut to be this class mediaPlayer.getVLCVout().addCallback(this); // Attach the video views passed to the output vlcOut.attachViews(); } @Override public void onResume() { super.onResume(); Timber.d("App ran resume"); } @Override public void onPause() { super.onPause(); Timber.d("App ran paused"); } @Override public void onStop() { super.onStop(); // Release the various VLC things when the activity is stopped mediaPlayer.stop(); runAutomaticTimer = false; mediaPlayer.getVLCVout().detachViews(); mediaPlayer.getVLCVout().removeCallback(this); Timber.d("Player ran stop"); } /** * {@link Boolean} value that stores whether or not the automatic timer should cancel, once it has been set going */ volatile boolean runAutomaticTimer = false; /** * Method that can be called to start a timer to automatically change the stream every 10 seconds from inside the application. */ void runTimedStreamChange(){ Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if(!runAutomaticTimer){ this.cancel(); } runOnUiThread(() -> changeStream()); } }, 5000, 10000); } /** * Method that is called to change the multicast stream VLC is currently playing */ void changeStream(){ // If the current stream being played is the first if(currentStreamIndex == 0){ currentStreamIndex = 1; if(streamOrFile){ Timber.d("Selected Stream: 1"); currentStreamAddress = streamAddresses.get(1); } else { Timber.d("Selected Video: 1 - %s", videoFiles.get(1)); currentStreamAddress = videoFiles.get(1); } // Perform the inverse if the second stream is currently playing } else { currentStreamIndex = 0; if(streamOrFile){ Timber.d("Selected Stream: 0"); currentStreamAddress = streamAddresses.get(0); } else { Timber.d("Selected Video: 0 - %s", videoFiles.get(0)); currentStreamAddress = videoFiles.get(0); } } // Load the values of the current stream and index into the textbox at the top of the screen, to make it easier to see what is happening streamName.setText(String.format("Stream: %s/%s", currentStreamIndex,currentStreamAddress)); // If the current media source is not null, as it would be at start up, release it. if (mediaSource != null) { mediaSource.release(); } if(streamOrFile){ mediaSource = new Media(this.libVLC, Uri.parse(this.currentStreamAddress)); } else { try { mediaSource = new Media(this.libVLC, getAssets().openFd(this.currentStreamAddress)); } catch (IOException e) { e.printStackTrace(); } } //mediaSource.setHWDecoderEnabled(true, true); // Finish up the process of loading the stream into the player finishPlayer(); } /** * Method that is called to load in a new mediasource and to set it playing out the output, from VLC */ void finishPlayer(){ if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); } // Add the option to be in fullscreen to the new mediasource mediaSource.addOption(":fullscreen"); // mediaPlayer. // Set the player to use the provided media source mediaPlayer.setMedia(mediaSource); // Release the media source mediaSource.release(); // Start the media player mediaPlayer.play(); Timber.d("Number of playbacks: %s", numPlaybacks); numPlaybacks ++; } // Required handler things for the vlcOut interface @Override public void onSurfacesCreated(IVLCVout ivlcVout) { } @Override public void onSurfacesDestroyed(IVLCVout ivlcVout) { } /** * {@link Boolean} value that stores whether button inputs are to be observed or not at the current time by the app. */ volatile boolean buttonLockout = false; /** * Enum that represents the direction the channel change button on the remote was pressed */ private enum directionPressedEnum{ STREAM_UP, STREAM_DOWN } boolean pressedOnce = false; boolean secondPress = false; /** * Stores the curremt {@link directionPressedEnum} of what button direction was last pushed */ static directionPressedEnum directionPressed = null; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Debug: Log that a button that can be read in by the program has been pressed Timber.v("Remote button was pressed"); // If the app is to observe the button presses or not. Required due to the fact the TV this is being tested on (Sony Bravia) likes to sometimes read in extraneous button presses that are non existent. if(!buttonLockout){ // If the button pressed was the channel up if(keyCode == KeyEvent.KEYCODE_CHANNEL_UP){ // Debug Timber.d("Channel up pressed"); // If the direction that was last pressed was down/app is starting if(directionPressed == directionPressedEnum.STREAM_DOWN || directionPressed == null){ Timber.d("First up press"); // Set the direction that has been pressed, and that the channel button has been pressed once directionPressed = directionPressedEnum.STREAM_UP; pressedOnce = true; // Otherwise if the last press was already in this direction } else if(directionPressed == directionPressedEnum.STREAM_UP && pressedOnce){ Timber.d("Second up press"); // Button being pressed for a second time, so lock out taking in any more inputs secondPress = true; buttonLockout = true; } // Same as above, just for the channel down key on the remote } else if(keyCode == KeyEvent.KEYCODE_CHANNEL_DOWN){ Timber.d("Channel down pressed"); if(directionPressed == directionPressedEnum.STREAM_UP || directionPressed == null){ Timber.d("First down press"); directionPressed = directionPressedEnum.STREAM_DOWN; pressedOnce = true; } else if(directionPressed == directionPressedEnum.STREAM_DOWN && pressedOnce){ Timber.d("Second down press"); secondPress = true; buttonLockout = true; } // Catches other button presses that the program has received } else { Timber.d("Other button press"); //return super.onKeyDown(keyCode, event); } // If the button has been pressed for a second time, and the button input has been locked out if(secondPress && buttonLockout){ Timber.d("Change stream called"); // Reset variables pressedOnce = false; secondPress = false; // Call the stream change changeStream(); // Call the handler to reset the lockout after a timeout handleButtonLockout(); } // Return true to stop the OS pulling you out of this app on any button press return true; } // return true so any buttons read in that the program doesn't handle, doesn't close the program return true; } /** * Handler to reset the {@link #buttonLockout} value after a timeout period */ void handleButtonLockout(){ // Create new Handler Handler handler = new Handler(); // Run this runnable after a second handler.postDelayed(() -> buttonLockout = false, 1000); } }<file_sep>/readme.md # Test LibVLC Application Note: This application is not intended for general use. So please do not take it as an example of how to use LibVLC with android. ## Purpose of Application This is the bare minium example to demonstrate an issue with the LibVLC library, and multicast streaming. The issue this aims to show is that there is a memory leak occurring within LibVLC, after changing the media source to be played back multiple times. ## Issue That is Being Demonstrated The problem that this application is demonstrating, is that of a suspected memory leak in the LibVLC library for android. This library, which the .aar file for has been compiled from the latest state of the master branch in the "VLC-Android" repository on code.videolan.org The issue that is occuring, is that after a number of media source changes of multicast network streams, LibVLC reaches a point where it just straight up breaks. The native memory usage of the app climbs over time, until the app eventually dies. When it does, if the app is restarted, LibVLC will sit there, not playing any network streams until the device the app is on is restarted. If you look at the memory usage of the app when it is in this state, in the memory profiler in Android Studio, you can see the native memory usage just going up and up and up, when nothing is happening. However, this issue does not just affect the one app, to require the restart. Any other copy of LibVLC on the device, such as the full version this app is mimicking some of the behavior of, and even the full VLC-Android application, is unable to play a network stream until the device is restarted. This is quite a severe issue, as it appears the scope of any problems are leaking outside of just merely the one app with the issue, it affects the device to a much greater extent. # Usage of the Application ## Initial Setup This application is made to run on Android TVs, running either Android 8 or 9. When preparing to use this application, the first thing you need is two multicast streams going out on the network that the TV is on, which are to be cycled between as the two media sources. You then need to enter these IP addresses into the two fields in the code, as shown below: ``` // |---------------------------| // | Configure stream IPs here | // |---------------------------| ArrayList<String> streamAddresses = new ArrayList<String>(){{ add("udp://@172.16.17.32:1234"); add("udp://@172.16.58.3:1234"); }}; ``` Keep to the format as shown here, using the '@' symbol, as otherwise VLC will not pick these up as valid stream sources. You then have the choice of whether you will use an external box to send in IR signals to the TV, to change the channel up and down, or to use the inbuilt timer in the app, to automatically start cycling between the streams every 10 seconds. If you have something like an AMX box which can be used for the first option, set it up to send the "Channel up" pulse 2x times, wait for ten seconds, "Channel down" pulse 2x times, wait ten seconds, and repeat. For those of you who would just rather use the automatic timer and avoid that hassle (I only have the channel up/down button option as a way to prove that part is not the issue), merely uncomment these two lines: ``` // |------------------------------------| // | Optional automatic stream changing | // |------------------------------------| // runAutomaticTimer = true; // runTimedStreamChange(); ``` You can find these two lines at the bottom of the "createLibVLC" Method. ## Optional VLC Parameters If you want to pass additional parameters to LibVLC, simply add them to the section in the code, that matches the following: ``` // |-----------------------------| // | Additional LibVLC Arguments | // |-----------------------------| addArg("fullscreen", "--fullscreen"); addArg("verbose", "-vvv"); ``` This can be found in the "onCreate" Method of the application. ## Usage Once this has been done, you can then compile the application (Ideally as a debug apk), and install it onto the Android TV of your choosing. Once this has happened and the app has been started, it will immediately start looking to play one of the two streams, and will continue to do so when the source it is looking at is changed. You can see the stream that it is attempting to playback in the text box at the top of the application. The amount of time for the issue to arise varies across devices (Presumably depending on how long it takes for memory to start being filled up), but for me it has always just reached a point where it will suddenly stop playing and just sit there frozen, potentially crashing fully. Any attempts to then close the app, and reopen it to continue playing will fail, and the entire device will need to be restarted for it to begin working again. Also at this time, if you try to open up the VLC-Android application on the TV, and to playback one of the network streams you have been playing in this app, you should find it will also fail to do so, until the device is restarted. Another note: If you look in the logs of the application when the app is restarted after crashing, and if the verbose output is enabled for LibVLC, you should see that it is indeed still buffering in the stream from the network, it just never appears to do anything with it after it reaches 100% buffered.<file_sep>/settings.gradle include ':app' rootProject.name='Test VLC Application'
f06cf727f63d46d9b788d317281682bf81f7383c
[ "Markdown", "Java", "Gradle" ]
4
Gradle
LRTNZ/test-vlc-application
45aeb38e5d676c4d2f2a90e49f6ab0933bad46eb
71c2651bc0435c680e7d80e45180b082f329fe05
refs/heads/master
<file_sep> import React from 'react'; import * as Sentry from '@sentry/react-native'; //Initialize Sentry with your dsn id Sentry.init({ dsn: '', }); function App() { return ( <View style={styles.container}> <Text>Olá, Sentry!</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ededed', justifyContent: 'center', alignItems: 'center' } }); export default App; <file_sep>defaults.url=https://sentry.io/ defaults.org=uxmob defaults.project=sentry-example auth.token=298ed42fd0fe4d56abb804bc8079b6097b60f525e7044f08ac7997282299891a
b7227704eb1f4a14a5f084d6510f0201098802d4
[ "JavaScript", "INI" ]
2
JavaScript
mensinho/sentry-example
1cc7d953f4919b33c1a7e01f0828710de4083620
161af0c09599b0aea53d69e35cd243eaa3fe0eb0
refs/heads/master
<file_sep>var fs = require('fs'); var _ = require('lodash'); var pkg = require('./package.json'); var config = require('./config.json'); // detect if there is default setting for language if (!config || !config.locale) { config.locale = 'default'; } // set laguage file var i18n = require('./i18n/' + config.locale + '.json'); // init variables var namelist = []; var passnames = []; var interval; var options = { bypass: true }; var btn = document.getElementById("roll"); var container = document.getElementById('container'); /** * add message to message board * @param {string} msg message to show * @param {string} type message type */ function addMsg(msg, type) { var msgBoard = $('#message'); if (type) { msgBoard.attr('class', 'bg-' + type); } msgBoard.text(msg).css('z-index', 1000).siblings().css('z-index', 900); } /** * show roll result * @param {string} result result to show */ function showResult(result) { var resultBoard = $('#result'); resultBoard.text(result).css('z-index', 1000).siblings().css('z-index', 900); } window.ondragover = function(e) { e.preventDefault(); return false; }; window.ondrop = function(e) { e.preventDefault(); return false; }; container.ondragover = function() { this.className = 'hover'; return false; }; container.ondragend = function() { this.className = ''; return false; }; container.ondrop = function(e) { this.className = ''; e.preventDefault(); var file = e.dataTransfer.files[0]; var reader = new FileReader(); reader.onload = function(e) { var names = e.target.result.split(/[\r\n]+/g).filter(function(itm) { return itm.length > 0; }); namelist = _.shuffle(names); addMsg(i18n.ready, 'info'); }; reader.readAsText(file, "GBK"); return false; }; function roll() { if(namelist.length <= 0) { addMsg(i18n.nofile, 'warning'); return; } if(interval) { passnames.push($('#result').text()); clearInterval(interval); interval = null; btn.innerHTML = i18n.btn_roll; return; } interval = setInterval(function() { var _temp = []; if (options.bypass) { _temp = namelist.slice(0); _temp = _temp.filter(function(itm) { return passnames.indexOf(itm) < 0; }); } else { _temp = namelist; } if (_temp.length <= 1) { addMsg(i18n.tip_reset, 'warning'); clearInterval(interval); return false; } var shuffled = _.shuffle(_temp)[0]; showResult(shuffled); }, 30); btn.innerHTML = i18n.btn_pause; $('#roll').blur(); } function reset() { passnames = []; if(interval) { clearInterval(interval); interval = null; } btn.innerHTML = i18n.btn_roll; addMsg(i18n.ready, 'info'); $('#reset').blur(); } $('#roll').click(roll); $('#reset').click(reset); $('body').keydown(function(e) { if (e.which === 32) { roll(); } else if (e.which === 13) { reset(); } }); function handlePrefs() { if(options.bypass === true) { $('.drawer #ipt-bypass').attr('checked', true); } } $('.drawer-handle').click(function() { handlePrefs(); $('.drawer').toggleClass('open'); }); $('#container').click(function() { if ($('.drawer').hasClass('open')) { $('.drawer').removeClass('open'); } }); $('.drawer #ipt-bypass').change(function() { options.bypass = $(this).is(':checked'); if (options.bypass === false) { passnames = []; } }); $('.drawer #select-i18n').change(function() { config.locale = $(this).val(); updateConfig(config); i18n = require('./i18n/' + config.locale + '.json'); $('.drawer #select-i18n [value="'+ config.locale +'"]').attr('selected', 'selected').siblings().removeAttr('selected'); // reload window document.location.reload(true); }); $('.drawer .version').text('v' + pkg.version); $(function() { addMsg(i18n.splash, 'info'); $('.drawer #select-i18n [value="'+ config.locale +'"]').attr('selected', 'selected').siblings().removeAttr('selected'); $('[data-i18n]').toArray().forEach(function(elm) { $(elm).text(i18n[$(elm).attr('data-i18n')]); }); }); function updateConfig(config) { fs.writeFileSync('./config.json', JSON.stringify(config)); } <file_sep># rollcall A simple rollcall app based on nw.js (node-webkit). > **Note:** > I just have made it work, the code is messy now. ## How to run? ### Mac: 1\. clone this repo. ```sh $ git clone <EMAIL>:lisposter/rollcall.git ``` 2\. install node-modules ```sh $ cd /path/to/rollcall $ npm i ``` 3\. run with nw.js ``` $ /path/to/nw/nwjs.app/Contents/MacOS/nwjs /path/to/this/repo ``` ## How to use? 1\. drag and drop a text file contains names of others(one item per line) into app's window. 2\. click 'Roll!' key button to shuffle, and click 'Pause' button to pick up one or just press the space to toggle. The 'Reset'/ enter key is for reset the bypass. ## Options * `Bypass`, if this is `true`, the names which has been called will be ignored next calling. * `Language`, currently, there are two languages avaliable: `English`, `简体中文`. ## License MIT © [<NAME>](http://zhu.li)
6331b6c4087797416c984d1ea39f5db675840b6e
[ "JavaScript", "Markdown" ]
2
JavaScript
lisposter/rollcall
e5e988cfeee36107ce7e316e6f5f59cfbfb0df2d
20359fa4e13c16654a7fa09f0100dd124e4dfbcd
refs/heads/master
<file_sep>import React from 'react' class Welfare extends React.Component { render() { return ( <div>Welfare</div> ) } } export default Welfare <file_sep># react-seed React Seed <file_sep>// import React from 'react' // import { render } from 'react-dom' // import { Router, Route, Link } from 'react-router' // import { createHistory, useBasename } from 'history' // const history = useBasename(createHistory)({ // basename: '' // }) // const rootRoute = { // component: 'div', // childRoutes: [{ // path: '/', // component: require('./components/App'), // childRoutes: [ // require('./routes/Homepage'), // require('./routes/Reservation'), // require('./routes/Profile'), // require('./routes/Welfare') // ] // }] // } // render(<Router history={history} routes={rootRoute} />, document.getElementById('app')) import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); <file_sep>var gulp = require('gulp'); var connect = require('gulp-connect'); var livereload = require('gulp-livereload'); var uglyfly = require('gulp-uglyfly'); var rev = require("gulp-rev"); var webpack = require("gulp-webpack"); var sass = require('gulp-sass'); console.log(__dirname); var webpackConfig = require('./webpack.config'); gulp.task('webserver', function () { connect.server({ livereload: true, fallback: 'index.html' }); }); gulp.task('build', function() { gulp.src('./index.js') .pipe(webpack(webpackConfig)) .pipe(gulp.dest('./build')) .pipe(connect.reload()); }); gulp.task('dist', function() { return gulp.src('./index.js') .pipe(webpack(webpackConfig)) .pipe(uglyfly()) .pipe(gulp.dest('./build')); }); gulp.task('sass', function() { gulp.src('./scss/index.scss') .pipe(sass({includePaths: ['scss', 'node_modules', 'store']}).on('error', sass.logError)) .pipe(gulp.dest('./build')) .pipe(connect.reload()); }) gulp.task('watch', function() { gulp.watch(['./**/*.js', '!./build/bundle.js'], ['build']); gulp.watch(['./scss/**/*.scss'], ['sass']); }); gulp.task('dev', ['build', 'webserver', 'watch']); gulp.task('default', ['dev']);
7c14f0ae177ee74cca22e4a85c8f5578a76db144
[ "JavaScript", "Markdown" ]
4
JavaScript
bravemantonyzheng/react-seed
1618713d88c57b588aaa3bb56fcc463f8b1a12a0
e3a8f9d4819cd2c27ff8e4c278b498e04e40aae4
refs/heads/master
<file_sep># _Vacation Destination Picker_ #### By _**<NAME>**_ created on 1/15/16 ## Description _After answering 5 questions about yourself, you will be given a suggested destination to visit_ ## Technologies Used _This site was created using HTML, CSS, Bootstrap, Javascript, and jQuery_ ### License Copyright (c) 2016 **_<NAME>_** <file_sep>$(document).ready(function(){ $("form#blanks").submit(function(event){ var temp = $("input[name='tempOptions']:checked").val(); var citytype = $("input[name='cityTypeOptions']:checked").val(); var name = $("input#inputName").val(); var age = $("input#inputAge").val(); var color = $("input#inputColor").val(); if (age < 18) { var destination = "Disney"; } else { if (temp === 'warm'){ if (citytype === 'urban'){ var destination = "Honolulu"; } else { var destination = "Fiji"; } } else { if (citytype === 'urban'){ var destination = "Moscow"; } else { var destination = "Nuuk"; } } } $(".results").show(); $(".vacationSelection").text(destination).css("color", color); $(".nameGiven").text(name); $(".photoSelection").empty().append('<img src="img/' + destination + '.jpg">'); event.preventDefault(); }); });
96e31abc686492918c37b828b4a266ec6b8d384d
[ "Markdown", "JavaScript" ]
2
Markdown
londonb/destination
304a975632ee2dd47fad5f376c71591ee4bece68
44fa9dd47643dabad85abaca2cdbdb04fec7fe2e
refs/heads/main
<repo_name>ysdnoproject/fast-api-ec-demo<file_sep>/backend/app/src/util/security.py from datetime import timedelta, datetime from typing import Optional from jose import jwt from passlib.context import CryptContext from src.config import settings PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto") ALGORITHM = "HS256" def verify_password(*, plain: str, hashed: str) -> bool: return PWD_CONTEXT.verify(plain, hashed) def get_password_hash(password: str) -> str: return PWD_CONTEXT.hash(password) def create_access_token(email: str, expires_delta: Optional[timedelta] = None): if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode = {"exp": expire, "sub": email} encoded_jwt = jwt.encode(to_encode, settings.attributes().secret_key, algorithm=ALGORITHM) return encoded_jwt def decode_access_token(token: str) -> dict: payload = jwt.decode( token, settings.attributes().secret_key, algorithms=[ALGORITHM] ) return payload <file_sep>/backend/app/src/api/v1/routers/login.py from fastapi import APIRouter, Depends, HTTPException from fastapi.security import OAuth2PasswordRequestForm from sqlalchemy.orm import Session from starlette import status from src import crud, schemas from src.api.deps import get_db from src.util.security import create_access_token router = APIRouter() @router.post("/login/", response_model=schemas.Token) def login(db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()): user = crud.user.authenticate(db, form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token = create_access_token(user.email) return {"access_token": access_token, "user": user} <file_sep>/backend/app/src/schemas/__init__.py from .user import * from .token import * <file_sep>/frontend/src/store/user/actions.ts import { ActionContext } from "vuex"; import { UserState } from "@/store/user/states"; import { RootState } from "@/store/states"; import { LoginResponse } from "@/types/LoginInterface"; import api from "@/api"; type UserContext = ActionContext<UserState, RootState>; const actions = { async fetchUserByToken(context: UserContext) { const token = context.state.token || localStorage.getItem("token"); if (token) { try { const response = await api.getMe(token); localStorage.setItem("token", token); context.commit("setToken", token); context.commit("setUser", response.data); } catch (e) { // do nothing } } else { context.commit("clearUser"); } }, loggedIn(context: UserContext, payload: LoginResponse) { localStorage.setItem("token", payload.access_token); context.commit("setToken", payload.access_token); context.commit("setUser", payload.user); }, logout(context: UserContext) { context.commit("clearUser"); context.commit("clearToken"); localStorage.removeItem("token"); } }; export default actions; <file_sep>/backend/app/src/main.py from fastapi import status, Request, FastAPI from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from src.api.v1.api import api_router from src.app_responses_schema import app_responses from src.exceptions import AppValidationError from src.init_app import init_app app = FastAPI( title="ec demo", description="ec api", responses=app_responses ) init_app(app) app.include_router(api_router) @app.exception_handler(AppValidationError) async def app_validation_exception_handler(request: Request, exc: AppValidationError): detail = [] for e in exc.errors: detail.append({"field": e.field, "msg": e.msg}) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(detail)}, ) @app.exception_handler(RequestValidationError) async def request_validation_exception_handler(request: Request, exc: RequestValidationError): detail = [] for e in exc.errors(): detail.append({"field": e.get('loc')[1], "msg": e.get('msg')}) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(detail)}, ) <file_sep>/backend/app/src/crud/crud_user.py from typing import Any, Dict, Optional, Union from sqlalchemy.orm import Session from src.crud.base import CRUDBase from src.models.user import User from src.schemas.user import UserCreate, UserUpdate from src.util.security import get_password_hash, verify_password class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): def create(self, db: Session, *, obj_in: UserCreate) -> User: obj_in.password = get_password_hash(obj_in.password) db_obj = User(**obj_in.dict()) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def update( self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] ) -> User: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) if update_data["password"]: update_data["password"] = get_password_hash(update_data["password"]) return super().update(db, db_obj=db_obj, obj_in=update_data) def authenticate(self, db: Session, email: str, password: str) -> Optional[User]: obj = self.find_by(db, field="email", value=email) if not obj: return None if not verify_password(plain=password, hashed=obj.password): return None return obj user = CRUDUser(User) <file_sep>/backend/app/src/db/seeds.py import yaml from src import crud from src.db.db_context_manager import DbContextManager from src.schemas.user import UserCreate with open('resources/db/seeds/user.yaml') as f: datalist = yaml.load(f, yaml.SafeLoader) with DbContextManager() as db: for key in datalist: data = datalist[key] user = UserCreate(**data) crud.user.create(db, obj_in=user) <file_sep>/backend/app/src/schemas/user.py from datetime import datetime from typing import Optional from phonenumbers import ( NumberParseException, PhoneNumberType, is_valid_number, number_type, parse as parse_phone_number, ) from pydantic import BaseModel, EmailStr, constr, validator # Shared properties class UserBase(BaseModel): email: EmailStr phone: constr(max_length=50, strip_whitespace=True) name: constr(max_length=255, strip_whitespace=True) @validator('phone') def check_phone(cls, v): try: n = parse_phone_number(v, 'CN') except NumberParseException as e: raise ValueError('Please provide a valid mobile phone number') if not is_valid_number(n) or number_type(n) not in (PhoneNumberType.MOBILE, PhoneNumberType.FIXED_LINE_OR_MOBILE): raise ValueError('Please provide a valid mobile phone number') return n.national_number class UserCreate(UserBase): password: str class UserUpdate(UserBase): password: Optional[str] = None class UserInDBBase(UserBase): id: int created_at: datetime updated_at: Optional[datetime] class Config: orm_mode = True # Additional properties to return via API class User(UserInDBBase): pass # Additional properties stored in DB class UserInDB(UserInDBBase): password: str <file_sep>/frontend/src/store/user/mutations.ts import { UserState } from "@/store/user/states"; import { User } from "@/models/User"; const mutations = { setToken(state: UserState, payload: string) { state.token = payload; }, clearToken(state: UserState) { state.token = null; }, setUser(state: UserState, payload: User) { state.user = payload; }, clearUser(state: UserState) { state.user = null; } }; export default mutations; <file_sep>/README.md # fast-api-ec-demo ``` cd backend/app PYTHONPATH=. poetry run alembic revision --autogenerate -m "Added users table" PYTHONPATH=. poetry run alembic upgrade head PYTHONPATH=. poetry run python src/db/seeds.py PYTHONPATH=. poetry run uvicorn src.main:app ``` <file_sep>/backend/app/src/models/base.py from sqlalchemy import Column, Integer, DateTime, func from sqlalchemy.ext.declarative import as_declarative, declared_attr from src.util import word_util @as_declarative() class Base: id = Column(Integer, primary_key=True, index=True, nullable=False) # Generate __tablename__ automatically @declared_attr def __tablename__(cls) -> str: return word_util.plural(cls.__name__.lower()) @declared_attr def created_at(cls) -> Column: return Column(DateTime, default=func.now(), nullable=True) @declared_attr def updated_at(cls) -> Column: return Column(DateTime, onupdate=func.now(), nullable=True) <file_sep>/backend/app/src/init_app.py from fastapi import FastAPI from src.initializers import exec_initializers def init_app(app: FastAPI): exec_initializers(app) <file_sep>/frontend/src/api.ts import axios, { AxiosResponse } from "axios"; import { CreateUserRequest, CreateUserResponse } from "@/types/CreateUserInterface"; import setupInterceptors from "@/axios-interceptors"; import { LoginRequest, LoginResponse } from "@/types/LoginInterface"; import { User } from "@/models/User"; export interface ApiClient { createUser: ( request: CreateUserRequest ) => Promise<AxiosResponse<CreateUserResponse>>; login: (request: LoginRequest) => Promise<AxiosResponse<LoginResponse>>; getMe: (token: string) => Promise<AxiosResponse<User>>; } const authHeaders = (token: string) => { return { headers: { Authorization: `Bearer ${token}` } }; }; const create = (): ApiClient => { const axiosInstance = axios.create({ baseURL: process.env.VUE_APP_SERVE_BASE_URL, timeout: parseInt(process.env.VUE_APP_REQUEST_TIMEOUT as string, 10) }); setupInterceptors(axiosInstance); const createUser = (request: CreateUserRequest) => { return axiosInstance.post("/users", request); }; const login = (request: LoginRequest) => { const formData = new FormData(); formData.append("username", request.username); formData.append("password", request.password); return axiosInstance.post("/login", formData); }; const getMe = (token: string) => { return axiosInstance.get("/users/me", authHeaders(token)); }; return { createUser, login, getMe }; }; const api = create(); export default api; <file_sep>/backend/app/src/exceptions.py from typing import List class AppValidationErrorItem: def __init__(self, *, field: str, msg: str) -> None: self.field = field self.msg = msg class AppValidationError(Exception): def __init__(self, errors: List[AppValidationErrorItem]) -> None: self.errors = errors <file_sep>/backend/app/pyproject.toml [tool.poetry] name = "fast-api-ec-demo-server" version = "0.1.0" description = "" authors = ["YuanShiDong <<EMAIL>>"] [tool.poetry.dependencies] python = "^3.9" uvicorn = "^0.13.3" fastapi = "^0.63.0" python-multipart = "^0.0.5" requests = "^2.25.1" SQLAlchemy = "^1.3.22" inflect = "^5.0.2" python-dotenv = "^0.15.0" phonenumbers = "^8.12.15" email-validator = "^1.1.2" alembic = "^1.4.3" PyMySQL = "^1.0.1" PyYAML = "^5.3.1" passlib = {extras = ["bcrypt"], version = "^1.7.4"} python-jose = {extras = ["cryptography"], version = "^3.2.0"} [tool.poetry.dev-dependencies] pytest = "^6.2.1" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" <file_sep>/backend/app/src/db/db_context_manager.py from src.db.session import SessionLocal class DbContextManager: def __init__(self): self.db = SessionLocal() def __enter__(self): return self.db def __exit__(self, exc_type, exc_value, traceback): self.db.close() <file_sep>/backend/app/src/schemas/token.py from typing import Optional from pydantic.main import BaseModel from src.schemas import User class Token(BaseModel): access_token: str user: User class TokenPayload(BaseModel): sub: Optional[str] = None <file_sep>/backend/app/src/api/deps.py from typing import Generator from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError from pydantic import ValidationError from sqlalchemy.orm import Session from src import crud, schemas from src.db.db_context_manager import DbContextManager from src.models.user import User from src.util.security import decode_access_token # TODO oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/v1/login/") def get_db() -> Generator: with DbContextManager() as db: yield db def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)) -> User: try: payload = decode_access_token(token) token_data = schemas.TokenPayload(**payload) except (JWTError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) return crud.user.find_by(db, field="email", value=token_data.sub) <file_sep>/frontend/src/store/user/index.ts import mutations from "@/store/user/mutations"; import actions from "@/store/user/actions"; import getters from "@/store/user/getters"; import state from "@/store/user/states"; const userModule = { namespaced: true, state, mutations, actions, getters }; export default userModule; <file_sep>/backend/app/src/api/v1/api.py from fastapi import APIRouter from src.api.v1.routers import login, users api_router = APIRouter(prefix="/v1") api_router.include_router(users.router) api_router.include_router(login.router) <file_sep>/frontend/src/store/index.ts import Vue from "vue"; import Vuex, { StoreOptions } from "vuex"; import userModule from "@/store/user"; import { RootState } from "@/store/states"; Vue.use(Vuex); const storeOptions: StoreOptions<RootState> = { modules: { user: userModule } }; const store = new Vuex.Store<RootState>(storeOptions); export default store; <file_sep>/frontend/src/transforms/ApiRequestTransform.ts import { CreateUserFormParams, CreateUserRequest } from "@/types/CreateUserInterface"; import { LoginFormParams, LoginRequest } from "@/types/LoginInterface"; export const buildCreateUserRequest = ( params: CreateUserFormParams ): CreateUserRequest => { return { email: params.email, phone: params.phone, name: params.name, password: params.<PASSWORD> }; }; export const buildLogInRequest = (params: LoginFormParams): LoginRequest => { return { username: params.email, password: <PASSWORD> }; }; <file_sep>/backend/app/src/db/session.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from src.config import settings engine = create_engine(settings.attributes().database_url) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) <file_sep>/backend/app/src/models/user.py from sqlalchemy import Column, String from src.models.base import Base class User(Base): email = Column(String(255), nullable=False, unique=True) password = Column(String(255), nullable=False) phone = Column(String(50), nullable=False) name = Column(String(255), nullable=False) <file_sep>/backend/app/src/util/word_util.py import inflect def plural(word: str) -> str: return inflect.engine().plural(word) <file_sep>/frontend/src/types/Enums.ts // eslint-disable-next-line import/prefer-default-export export enum ValidateStates { SUCCESS = "success", VALIDATING = "validating", ERROR = "error" } export enum HeaderDropDownCommand { LOGOUT = "logout" } <file_sep>/backend/app/src/config/settings.py from functools import lru_cache from pydantic import BaseSettings # @lru_cache() modifies the function it decorates to # return the same value that was returned the first time, # instead of computing it again, executing the code of the function every time. # As a result,the .env file will only read once at first access. # You need to restart app after modify .env @lru_cache() def attributes(): return Settings() class Settings(BaseSettings): database_url: str secret_key: str class Config: env_file = "resources/config/.env" <file_sep>/frontend/src/store/states.ts import { UserState } from "@/store/user/states"; export interface RootState { user: UserState; } <file_sep>/frontend/src/types/CreateUserInterface.ts interface CreateUserBase { email: string; phone: string; name: string; } export interface CreateUserRequest extends CreateUserBase { password: string; } export interface CreateUserResponse extends CreateUserBase { id: number; created_at: string; updated_at: string; } export interface CreateUserFormParams extends CreateUserBase { password: string; confirmPassword: string; } <file_sep>/backend/app/src/initializers/cors_settings.py import json from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware def init(app: FastAPI): with open('resources/config/allow_origins.json', 'r') as f: allow_origins = json.load(f) if allow_origins: app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in allow_origins], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) <file_sep>/backend/app/src/api/v1/routers/users.py from typing import List from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from src import crud, schemas from src.api.deps import get_db, get_current_user from src.exceptions import AppValidationError, AppValidationErrorItem from src.models.user import User router = APIRouter(prefix="/users", tags=["users"]) @router.get("/", response_model=List[schemas.User]) def root(db: Session = Depends(get_db)): users = crud.user.get_multi(db) return users @router.post('/', response_model=schemas.User) def create_user(user_in: schemas.UserCreate, db: Session = Depends(get_db)): user = crud.user.find_by(db, field='email', value=user_in.email) if user is not None: raise AppValidationError( [AppValidationErrorItem(msg="The user with this email already exists in the system.", field="email")] ) user = crud.user.create(db, obj_in=user_in) return user @router.get("/me", response_model=schemas.User) def get_me( current_user: User = Depends(get_current_user), ): return current_user @router.put('/me', response_model=schemas.User) def update_me( user_in: schemas.UserUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) ): user = crud.user.find_by(db, field='email', value=user_in.email) if user is not None and user.id != current_user.id: raise AppValidationError( [AppValidationErrorItem(msg="The user with this email already exists in the system.", field="email")] ) user = crud.user.update(db, db_obj=current_user, obj_in=user_in) return user <file_sep>/frontend/src/types/ErrorInterface.ts export interface ValidationError { detail: Array<ValidationErrorDetail>; } export interface ValidationErrorDetail { field: string; msg: string; } <file_sep>/backend/app/debug.py import uvicorn from src.main import app # for debug.Add breakpoint at anywhere,then click debug. if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) <file_sep>/frontend/src/types/LoginInterface.ts import { User } from "@/models/User"; export interface LoginRequest { username: string; password: string; } export interface LoginResponse { access_token: string; user: User; } export interface LoginFormParams { email: string; password: string; } <file_sep>/frontend/src/utils/FormUtil.ts import { ValidationError } from "@/types/ErrorInterface"; import { ElFormExtend } from "@/index.d"; import { ValidateStates } from "@/types/Enums"; // eslint-disable-next-line import/prefer-default-export export const serverValidationError = ( error: ValidationError, form: ElFormExtend ): void => { error.detail.forEach(e => { const field = form.fields.find(f => f.prop === e.field); if (field) { field.validateMessage = e.msg; field.validateState = ValidateStates.ERROR; } }); }; <file_sep>/backend/app/src/initializers/__init__.py import glob import importlib from os.path import dirname, isfile, basename from fastapi import FastAPI def exec_initializers(app: FastAPI): py_files = glob.glob(dirname(__file__) + "/*.py") for f in py_files: if isfile(f) and not f.endswith('__init__.py'): module_name = basename(f)[:-3] module_path = '%s.%s' % (__package__, module_name) module = importlib.import_module(module_path) if hasattr(module, 'init'): func = getattr(module, 'init') func(app) <file_sep>/backend/app/src/crud/base.py from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union from fastapi.encoders import jsonable_encoder from pydantic import BaseModel from sqlalchemy.orm import Session from src.models.base import Base ModelType = TypeVar("ModelType", bound=Base) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model_class: Type[ModelType]): self.model_class = model_class def find(self, db: Session, id: int) -> Optional[ModelType]: return db.query(self.model_class).get(id) def find_by(self, db: Session, *, field: str, value: Any) -> Optional[ModelType]: return db.query(self.model_class).filter(getattr(self.model_class, field) == value).first() def get_multi( self, db: Session, *, skip: int = 0, limit: int = 100 ) -> List[ModelType]: return db.query(self.model_class).offset(skip).limit(limit).all() def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model_class(**obj_in_data) # type: ignore db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def update( self, db: Session, *, db_obj: ModelType, obj_in: Union[UpdateSchemaType, Dict[str, Any]] ) -> ModelType: obj_data = jsonable_encoder(db_obj) if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) for field in obj_data: if field in update_data: setattr(db_obj, field, update_data[field]) db.add(db_obj) db.commit() db.refresh(db_obj) return db_obj def remove(self, db: Session, *, id: int) -> ModelType: obj = db.query(self.model_class).get(id) db.delete(obj) db.commit() return obj <file_sep>/frontend/src/index.d.ts // eslint-disable-next-line max-classes-per-file import { ElForm } from "element-ui/types/form.d"; import { ElFormItem } from "element-ui/types/form-item.d"; import { ValidateStates } from "@/types/Enums"; export declare class ElFormItemExtend extends ElFormItem { validateMessage: string; validateState: ValidateStates; } export declare class ElFormExtend extends ElForm { fields: Array<ElFormItemExtend>; } <file_sep>/frontend/src/store/user/getters.ts import { UserState } from "@/store/user/states"; export default { isLoggedIn: (state: UserState): boolean => { return !!state.token; } }; <file_sep>/frontend/src/axios-interceptors.ts import { AxiosRequestConfig, AxiosResponse } from "axios"; import Vue from "vue"; const setupInterceptors = (axiosInstance): void => { const onRequest = (_config: AxiosRequestConfig) => { console.log(_config); }; const onResponse = (_response: AxiosResponse) => { console.log(_response); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const onError = (error: any) => { if (error.response) { console.log("Response Data", error.response.data); console.log("Response status", error.response.status); console.log("Response headers", error.response.headers); } else if (error.request) { Vue.prototype.$message.error(error.message); console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log("Error", error.message); } console.log(error.config); }; axiosInstance.interceptors.request.use( (config: AxiosRequestConfig) => { onRequest(config); return config; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any (error: any) => { onError(error); return Promise.reject(error); } ); // Add a response interceptor axiosInstance.interceptors.response.use( (response: AxiosResponse) => { onResponse(response); return response; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any (error: any) => { onError(error); return Promise.reject(error); } ); }; export default setupInterceptors; <file_sep>/backend/app/src/db/base.py # Import all the models, so that Base has them before being # imported by Alembic from src.models.base import Base # noqa from src.models.user import User # noqa <file_sep>/frontend/src/store/user/states.ts import { User } from "@/models/User"; export interface UserState { token: string | null; user: User | null; } const state = (): UserState => ({ token: null, user: null }); export default state; <file_sep>/frontend/src/router/index.ts import Vue from "vue"; import VueRouter, { RouteConfig } from "vue-router"; import Home from "@/views/Home.vue"; Vue.use(VueRouter); const routes: Array<RouteConfig> = [ { path: "/", name: "home", component: Home, meta: { title: "主页" } }, { path: "/register", name: "register", // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ "@/views/Registration.vue"), meta: { title: "注册" } }, { path: "/login", name: "login", component: () => import(/* webpackChunkName: "about" */ "@/views/Login.vue"), meta: { title: "登录" } }, { path: "/404", name: "notFound", component: () => import(/* webpackChunkName: "about" */ "@/views/NotFound.vue"), meta: { title: "404" } }, { path: "/*", redirect: { name: "notFound" } } ]; const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes }); router.beforeEach((to, _from, next) => { document.title = to.meta.title; next(); }); export default router; <file_sep>/backend/app/src/initializers/logging.py import glob import logging.config import yaml from fastapi import FastAPI def init(app: FastAPI): yaml_files = glob.glob("resources/config/logging/*.yaml") for file in yaml_files: with open(file, 'r') as f: dict_conf = yaml.load(f, yaml.SafeLoader) logging.config.dictConfig(dict_conf)
d0b6819693ee45d98023dea5592f2183a512c7b2
[ "Markdown", "TOML", "Python", "TypeScript" ]
44
Python
ysdnoproject/fast-api-ec-demo
2ee2b7217084a1d8a1bf2513b856e1bea3ca4b9d
629e611f949bd94a7374bc873452de3ff5cc2d8c
refs/heads/master
<repo_name>prabhavathidodda/FoodOrderingApp<file_sep>/FoodOrderingApp-service/src/main/java/com/upgrad/FoodOrderingApp/service/dao/OrderDAO.java package com.upgrad.FoodOrderingApp.service.dao; import com.upgrad.FoodOrderingApp.service.entity.AddressEntity; import com.upgrad.FoodOrderingApp.service.entity.OrdersEntity; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import java.util.List; @Repository public class OrderDAO { @PersistenceContext private EntityManager entityManager; /** * @param addressEntity * @return */ public List<OrdersEntity> getOrdersByAddress(AddressEntity addressEntity) { try { List<OrdersEntity> ordersEntities = entityManager.createNamedQuery("getOrdersByAddress", OrdersEntity.class) .setParameter("address", addressEntity).getResultList(); return ordersEntities; } catch (NoResultException nre) { return null; } } }
ddd9976040bbf1e448408155a515e45c0593922b
[ "Java" ]
1
Java
prabhavathidodda/FoodOrderingApp
984b14b835ce43929c28f50c9fb7aa9843c54579
2f6f5d9f27c20978bf470d78546e87aeb337e5fe
refs/heads/master
<repo_name>harmijay/Gateway-Service<file_sep>/src/main/java/com/jayandra/bank/gateway/Config.java package com.jayandra.bank.gateway; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Config { @Bean public RouteLocator gatewayRoutes(RouteLocatorBuilder routeLocatorBuilder) { return routeLocatorBuilder.routes() .route("appdemo", rt -> rt.path("/") .uri("http://localhost:8080/")) .route("gawa", rt -> rt.path("/api/v1/student") .uri("http://10.10.30.31:7005")) .build(); } }
435cc54c6695def8511fde485ec80b7ed6b400c2
[ "Java" ]
1
Java
harmijay/Gateway-Service
5c1a34e2469b7368c384ab681f2e7dfaa0e58e0a
029fe1c2310a0fdb83183de64885130335070b17
refs/heads/main
<repo_name>prathameshsanga/Notes-App<file_sep>/routes/noteRouter.js const router = require('express').Router(); const noteController = require('../controllers/noteController'); router.route('/').get(noteController.getNotes).post(noteController.createNote); router .route('/:id') .get(noteController.getNote) .put(noteController.updateNote) .delete(noteController.deleteNote); module.exports = router;
f2f9517dcee7258d4f114454469b780781144007
[ "JavaScript" ]
1
JavaScript
prathameshsanga/Notes-App
7f0f9d0cb16f7c959df5c7279efdca18002ab83f
25e6f858814d10ed2358f6411c13ae437337f30c
refs/heads/master
<repo_name>peterbarraud/rapo-browserify-budo-sassify<file_sep>/README.md # Browserify with Budo & sassify Alright. So we have a base template ([browserify-budo](https://github.com/peterbarraud/rapo-browserify-budo)), and a very convenient [browserify-css](https://github.com/cheton/browserify-css). So let's get to using [SASS](http://sass-lang.com) in our Rapo projects. And for that, we use the [SASSIFY](https://github.com/davidguttman/sassify) browserify transform. ## How this works Pretty straightforward: - Local stylesheets: You include your local SASS / SCSS files in the `index.js`. - External SASS-based libs: You include any external libs in the `index.js`. ## External libs I've tried [bulma](https://bulma.io) and all it takes in a `required('bulma')` statement in your `index.js`. After that you're going to have to set the sassify tranform in the `package.json` with the -g (for global) flag to pick up libs from anywhere in the node_modules for. **Note**: Bulma works just fine with a simple require('bulma') statement. You're going to have to check how to include any other libs that you use. ## Get going 1. Clone this repo 2. `cd` into the cloned dir 3. Run `npm install` to get the dependencies 4. Run `npm start` to launch the project in your default browser running on a local (`Node`-based) web server with `livereload` - all setup. That's it. ## Building the project for deployment This is split into two parts * `build.js`: Builds the `JS` and `CSS` outputs * `html-dist.config`: Uses [html-dist](https://www.npmjs.com/package/html-dist) to inject the CSS into the HTML Then generate build: ``` npm run build ``` *IMPORTANT*: The buildCSS function requires a new function be added to sassify. So you're going to have to copy (and overwrite) `sassify/index.js` to `node_modules/sassify/lib` ``` cp sassify/index.js node_modules/sassify/lib ``` ### Testing the build If you want to check the build - Just to make sure: ``` npm run testbuild ``` This runs `budo` on the build<file_sep>/index.js // js includes require('./src/js/main.js'); // style includes require('./src/styles/main.scss'); // require('bulma'); <file_sep>/scripts/build.js var fs = require('fs'); var buildJS = function(){ console.log('Building index.js'); var b = require('browserify')(); b.add('src/js/main.js'); b.transform('uglifyify', { global: true }) var indexjs = fs.createWriteStream('build/index.js'); b.bundle().pipe(indexjs); console.log('Done: Building index.js'); }; var buildCSS = function(){ console.log('Building index.css'); var b = require('browserify')(); b.add('index.js'); b.transform(require('sassify'), { global: true, sendToCSSFile:true, onSendToCSSFile: function(data){ fs.appendFileSync('build/index.css', data); }, }); b.bundle(); console.log('Done: Building index.css'); } var buildHTML = function(){ fs.readFile('index.html', 'utf8', function(err, data){ if (err) { return console.log(err); } var minify = require('html-minifier').minify; var result = minify(data, { removeAttributeQuotes: true }); // console.log(result); fs.writeFileSync('build/index.html', result); }); }; console.log("using rimraf just to first we clean out the entire build dir"); require('rimraf')('build', function(){ console.log("re-make the build folder from scratch"); require('mkdirp')('build', function (err) { if (err) { console.error(err); } else { console.log("build the index.js"); buildJS(); console.log("build the index.css"); buildCSS(); console.log('build the index.html'); buildHTML(); } }); });
38978a83246956a30c918a53f4b16820595ce48b
[ "Markdown", "JavaScript" ]
3
Markdown
peterbarraud/rapo-browserify-budo-sassify
3c5f98025bd48b8f325a6ffadf8b0dfb5cfb67ba
ecf5ea50697b59177adadcdd6c8324ec2f931c02
refs/heads/master
<repo_name>Devil7DK/apkname<file_sep>/Main.cpp // // Copyright 2006 The Android Open Source Project // // Android Asset Packaging Tool main entry point. // #include "AaptXml.h" //#include "ApkBuilder.h" //#include "Images.h" //#include "Main.h" //#include "ResourceFilter.h" //#include "ResourceTable.h" #include "XMLNode.h" //#include <utils/Errors.h> //#include <utils/KeyedVector.h> //#include <utils/List.h> //#include <utils/Log.h> //#include <utils/SortedVector.h> //#include <utils/threads.h> //#include <utils/Vector.h> //#include <errno.h> //#include <fcntl.h> //#include <iostream> //#include <string> //#include <sstream> //using namespace android; /* * Return the percent reduction in size (0% == no compression). */ int calcPercent(long uncompressedLen, long compressedLen) { if (!uncompressedLen) { return 0; } else { return (int) (100.0 - (compressedLen * 100.0) / uncompressedLen + 0.5); } } // These are attribute resource constants for the platform, as found // in android.R.attr enum { LABEL_ATTR = 0x01010001, }; int main(int argc, char **argv) { if (argc < 2) return 1; status_t result = UNKNOWN_ERROR; const char* filename = argv[1]; AssetManager assets; int32_t assetsCookie; if (!assets.addAssetPath(String8(filename), &assetsCookie)) { fprintf(stderr, "ERROR: dump failed because assets could not be loaded\n"); return 1; } // Make a dummy config for retrieving resources... we need to supply // non-default values for some configs so that we can retrieve resources // in the app that don't have a default. The most important of these is // the API version because key resources like icons will have an implicit // version if they are using newer config types like density. ResTable_config config; memset(&config, 0, sizeof(ResTable_config)); config.language[0] = 'e'; config.language[1] = 'n'; config.country[0] = 'U'; config.country[1] = 'S'; config.orientation = ResTable_config::ORIENTATION_PORT; config.density = ResTable_config::DENSITY_MEDIUM; config.sdkVersion = 10000; // Very high. config.screenWidthDp = 320; config.screenHeightDp = 480; config.smallestScreenWidthDp = 320; config.screenLayout |= ResTable_config::SCREENSIZE_NORMAL; assets.setConfiguration(config); const ResTable& res = assets.getResources(false); if (res.getError() != NO_ERROR) { fprintf(stderr, "ERROR: dump failed because the resource table is invalid/corrupt.\n"); return 1; } // Source for AndroidManifest.xml const String8 manifestFile("AndroidManifest.xml"); // The dynamicRefTable can be null if there are no resources for this asset cookie. // This fine. const DynamicRefTable* dynamicRefTable = res.getDynamicRefTableForCookie(assetsCookie); Asset* asset = NULL; asset = assets.openNonAsset(assetsCookie, "AndroidManifest.xml", Asset::ACCESS_BUFFER); if (asset == NULL) { fprintf(stderr, "ERROR: dump failed because no AndroidManifest.xml found\n"); //got bail; } ResXMLTree tree(dynamicRefTable); if (tree.setTo(asset->getBuffer(true), asset->getLength()) != NO_ERROR) { fprintf(stderr, "ERROR: AndroidManifest.xml is corrupt\n"); //got bail; } tree.restart(); Vector<String8> locales; res.getLocales(&locales); Vector<ResTable_config> configs; res.getConfigurations(&configs); size_t len; ResXMLTree::event_code_t code; int depth = 0; String8 error; String8 pkg; String8 packageLabel; String8 packageName; while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) { if (code == ResXMLTree::END_TAG) depth--; if (code != ResXMLTree::START_TAG) continue; depth++; const char16_t* ctag16 = tree.getElementName(&len); if (ctag16 == NULL) { SourcePos(manifestFile, tree.getLineNumber()).error( "ERROR: failed to get XML element name (bad string pool)"); //got bail; } String8 tag(ctag16); if (depth >2) { continue; } else if (depth == 1) { if (tag != "manifest") { SourcePos(manifestFile, tree.getLineNumber()).error( "ERROR: manifest does not start with <manifest> tag"); //got bail; } pkg = AaptXml::getAttribute(tree, NULL, "package", NULL); packageName = ResTable::normalizeForOutput(pkg.string()); } else if (depth == 2) { if (tag == "application") { String8 label; const size_t NL = locales.size(); for (size_t i=0; i<NL; i++) { const char* localeStr = locales[i].string(); assets.setConfiguration(config, localeStr != NULL ? localeStr : ""); String8 llabel = AaptXml::getResolvedAttribute(res, tree, LABEL_ATTR, &error); if (llabel != "") { if (localeStr == NULL || strlen(localeStr) == 0) { label = llabel; } else { if (label == "") { label = llabel; } } } } assets.setConfiguration(config); packageLabel = ResTable::normalizeForOutput(label.string()); } } } printf("package: name = %s; label = %s\n", packageName.string(), packageLabel.string()); result = NO_ERROR; return 0; }
c948094f9c16d3b76a7f53a117df327d1e853a3e
[ "C++" ]
1
C++
Devil7DK/apkname
dbce0a00ec3be5c35c9547d417d2295563f40f63
ca4031f53d9627358d9530f72a1cf7b575e9e0b5
refs/heads/master
<file_sep># Tri-Top Simple arcade game with limited time and lives. The goal is to find the top triangle on the screen and tap it as fast as possible. You think it's easy, let's find out if you were right! <p float="left"> <img src="https://github.com/neczpal/tritop/raw/master/img/screenshot_1.png" width="200" /> <img src="https://github.com/neczpal/tritop/raw/master/img/screenshot_2.png" width="200" /> <img src="https://github.com/neczpal/tritop/raw/master/img/screenshot_3.png" width="200" /> <img src="https://github.com/neczpal/tritop/raw/master/img/screenshot_4.png" width="200" /> </p> ### Play it [here](https://neczpal.github.io/tritop/) ## Instructions ### Objective Click the top triangle on the screen, but you can only guess incorrectly 3 times per level. ### Points: 1 point / correctly clicked triangle ## License MIT Copyright (c) 2021 <NAME>. The project is uploaded for educational purpose. Contribution and fair use of the scripts and assets are welcomed, however, please contact me before doing so. ## Contact <NAME> - [<EMAIL>](mailto:<EMAIL>) Project Link - [https://github.com/neczpal/tritop](https://github.com/neczpal/tritop)<file_sep>let c, ctx; let view_width, view_height; let bgColor; let lose, score, timer, current_life, left_time; let high_score; let runningGame; let lives, node_count, time; let life_color, time_color; let wires; const MIN_SIZE = 3500; function _r(n){ return Math.floor(Math.random()*n); } function _ra(n, m){ return _r(m)+n; } function _rp(n, m, k, l){ return new Point(_ra(n, m), _ra(k, l)); } function _rpin(){ return _rp(0, view_width, 0, view_height); } function _rpain(n){ let nodes = []; for(let i=0; i < n; i++){ nodes[i] = _rpin(); } return nodes; } function _rh(){ let r = _r(15); if(r < 10){ return r; }else{ switch(r){ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F"; } } } function _rh13(){ let r = _r(13); if(r < 10){ return r; }else{ switch(r){ case 10: return "A"; case 11: return "B"; case 12: return "C"; } } } function _rcnored(){ return "#"+_rh13()+_rh()+_rh()+_rh()+_rh()+_rh(); } function _rc(){ return "#"+_rh()+_rh()+_rh()+_rh()+_rh()+_rh(); } function Point(x,y){ this.x = x; this.y = y; } function dist(p1, p2){ return Math.sqrt(Math.pow(p2.y - p1.y, 2) + Math.pow(p2.x - p1.x, 2)); } function Wire(){ this.color = _rcnored(); this.nodes = _rpain(3); this.inside = function(x , y){ let i, j, c = false; for (i = 0, j = this.nodes.length-1; i < this.nodes.length; j = i++) { if ( ((this.nodes[i].y> y) !== (this.nodes[j].y > y)) && (x < (this.nodes[j].x-this.nodes[i].x) * (y - this.nodes[i].y) / (this.nodes[j].y-this.nodes[i].y) + this.nodes[i].x)) c = !c; } return c; }; this.sizeof = function(){ let a = dist(this.nodes[0], this.nodes[1]); let b = dist(this.nodes[1], this.nodes[2]); let c = dist(this.nodes[2], this.nodes[0]); let s = (a+b+c)/2; return Math.sqrt(s*(s-a)*(s-b)*(s-c)); } this.draw = function(){ ctx.fillStyle = this.color; ctx.beginPath(); ctx.moveTo(this.nodes[0].x, this.nodes[0].y); for(let i=1; i < this.nodes.length; i++){ ctx.lineTo(this.nodes[i].x, this.nodes[i].y); } ctx.closePath(); ctx.fill(); }; } function animPlusScore(){ ps.html("-1"); bgColor = "#F"+_r(5)+_r(5); ps.css('color', "#000000"); ps.fadeIn(150, function(){ ps.fadeOut(150); }); } function drawLife(x, y, r){ ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = "#000"; ctx.fill(); for(let i=current_life; i > 0; i--){ ctx.fillStyle = life_color[i-1]; ctx.beginPath(); ctx.arc(x, y, r, -0.5*Math.PI + 2 * Math.PI * (i-1) / lives, 2 * Math.PI * i / lives -0.5*Math.PI); ctx.closePath(); ctx.fill(); } ctx.fillStyle = "#FFF"; if(current_life <= 9){ ctx.fillText(current_life, x-2, y+5); }else if(current_life <= 99){ ctx.fillText(current_life, x-5, y+5); }else{ ctx.font="8px Verdana"; if(current_life <= 999){ ctx.fillText(current_life, x-7, y+5); }else if(current_life <= 9999){ ctx.fillText(current_life, x-10, y+5); }else{ ctx.font="7px Verdana"; ctx.fillText("99999", x-10, y+6); } } } function drawTime(x, y, r){ ctx.lineWidth = 2; for(let i=left_time; i > 0; i--){ ctx.strokeStyle = time_color[i-1]; ctx.beginPath(); ctx.arc(x, y, r, -0.5*Math.PI + 2 * Math.PI * (i-1) / time, 2 * Math.PI * i / time -0.5*Math.PI); ctx.closePath(); ctx.stroke(); } ctx.fillStyle = "#FFF"; if(left_time <= 9){ ctx.fillText(left_time, x-2, y+3); }else if(left_time <= 99){ ctx.fillText(left_time, x-5, y+3); }else if(left_time <= 999){ ctx.fillText(left_time, x-8, y+3); }else if(left_time <= 9999){ ctx.fillText(left_time, x-10, y+3); }else{ ctx.fillText(left_time, x-13, y+3); } } function drawScore(x, y){ if(score <= 9){ ctx.fillText(score, x-7, y); }else if(score <= 99){ ctx.fillText(score, x-15, y); }else if(score <= 999){ ctx.fillText(score, x-24, y); }else if(score <= 9999){ ctx.fillText(score, x-30, y); }else{ ctx.fillText(score, x-39, y); } } function drawBigScore(x, y){ if(score <= 9){ ctx.fillText(score, x-14, y); }else if(score <= 99){ ctx.fillText(score, x-30, y); }else if(score <= 999){ ctx.fillText(score, x-48, y); }else if(score <= 9999){ ctx.fillText(score, x-60, y); }else{ ctx.fillText(score, x-78, y); } } function addTime(n){ drawGame(); if(n > 0){ time ++; left_time ++; n--; setTimeout("addTime("+n+")", 10); } } function addWires(n){ drawGame(); if(n <= 0){ return; } if(wires.length === 0){ let temp; do{ temp = new Wire(); }while(temp.sizeof() < MIN_SIZE); wires.push(temp); }else{ let temp, connect = false, top_wire = wires[wires.length-1]; do{ do{ temp = new Wire(); }while(temp.sizeof() < MIN_SIZE); for(let i = 0; i < temp.nodes.length; i++){ if(top_wire.inside(temp.nodes[i].x, temp.nodes[i].y)){ connect = true; } } }while(!connect); wires.push(temp); } n--; setTimeout("addWires("+n+")", 10); } function recolor(){ bgColor = _rcnored(); for(let i=0; i < wires.length; i++){ wires[i].color = _rcnored(); } recolorLife(); } function recolorLife(){ for(let i=0; i < lives; i++){ life_color[i] = _rcnored(); } } function recolorTime(){ for(let i=0; i < time; i++){ time_color[i] = _rc(); } } function newGame(t, l, s){ lose = false; wires = []; score = 0; timer = 0; time = t; lives = l; node_count = s; bgColor = _rcnored(); addWires(node_count); life_color = []; recolorLife(); time_color = []; recolorTime(); current_life = lives; left_time = time; runningGame = setInterval("runGame()", 50); drawGame(); } function loseGame(){ clearInterval(runningGame); drawFinalScore(); } let ps; function init(){ c = document.getElementById("surface"); ctx = c.getContext("2d"); ctx.font="30px Verdana"; view_width = c.width = window.innerWidth; view_height = c.height = window.innerHeight; c.addEventListener("mousedown", doMouseDown, false); ps = $("#plus_score"); if(window.localStorage.getItem("high_score")){ high_score = window.localStorage.getItem("high_score"); }else{ high_score = 0; } lose = true; drawMenu(); } function doMouseDown(event){ if(!lose){ if(wires[wires.length-1].inside(event.pageX, event.pageY)){ wires.pop(); score++; recolor(); if(wires.length === 0){ node_count+= Math.floor(node_count/2); addWires(node_count); addTime(node_count/1.5); recolorTime(); current_life = lives; } drawGame(); }else{ animPlusScore(); current_life--; drawGame(); if(current_life <= 0){ lose = true; } } } else { newGame(15,3,3); } } function runGame(){ if(timer % 20 === 0){ left_time--; if(left_time <= 0){ lose = true; } } if(lose){ loseGame(); }else{ drawGame(); } timer++; } function refresh(){ ctx.fillStyle = bgColor; ctx.fillRect(0, 0, view_width, view_height); } function drawGame(){ refresh(); for(let i=0; i < wires.length; i++){ wires[i].draw(); } ctx.font="10px Verdana"; drawLife(23, 23, 20); ctx.font="10px Verdana"; drawTime(view_width-23, 23, 20); ctx.font="30px Verdana"; drawScore(view_width/2, 30); } function drawFinalScore(){ bgColor = "#F"+_r(5)+_r(5); refresh(); ctx.font="30px Verdana"; ctx.fillStyle="#000000"; let tmp; ctx.font="40px Verdana"; if(current_life === 0){ ctx.fillText("YOU DIED!", view_width/2-120, view_height/2-150); }else{ ctx.fillText("TIME IS UP!", view_width/2-130, view_height/2-150); } ctx.font="30px Verdana"; if(score > high_score){ window.localStorage.setItem("high_score", score); high_score = score; ctx.fillText("NEW HIGH SCORE!", view_width/2-140, view_height/2-50); }else{ ctx.fillText("Your Score:", view_width/2-100, view_height/2-50); ctx.fillText("High score:", view_width/2-100, view_height/2+50); tmp = score; score = high_score; drawBigScore(view_width/2, view_height/2+100); score = tmp; } ctx.font="bold 30px Verdana"; drawBigScore(view_width/2, view_height/2); ctx.font="italic 30px Verdana"; ctx.fillText("Tap to play again!", view_width/2-140, view_height/2+200); } function drawMenu(){ bgColor = _rcnored(); refresh(); time = 30; left_time = 17; lives = 3; current_life = 2; score = high_score; life_color = []; recolorLife(); time_color = []; recolorTime(); ctx.fillStyle = "#FFF"; ctx.font="30px Verdana"; ctx.fillText("Help", view_width/2-45, view_height/2-150); ctx.font="20px Verdana"; ctx.fillText("Game:", view_width/2-150, view_height/2-100); ctx.font="10px Verdana"; ctx.fillText("Tap on the top triangle", view_width/2-60, view_height/2-105); ctx.fillText("Be careful because this game is", view_width/2-60, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("c", view_width/2+120, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("o", view_width/2+125, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("l", view_width/2+131, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("o", view_width/2+133, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("r", view_width/2+139, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("f", view_width/2+144, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("u", view_width/2+147, view_height/2-90); ctx.fillStyle = _rc(); ctx.fillText("l", view_width/2+153, view_height/2-90); drawLife(view_width/2-120, view_height/2-40, 20); ctx.fillText("It shows your left lives", view_width/2-60, view_height/2-45); ctx.fillText("Resets after clearing a map", view_width/2-60, view_height/2-30); drawTime(view_width/2-120, view_height/2+40, 20); ctx.fillText("It shows the left time", view_width/2-60, view_height/2+35); ctx.fillText("Adds some after clearing a map", view_width/2-60, view_height/2+50); ctx.font="20px Verdana"; ctx.fillText("High score:", view_width/2-85, view_height/2+135); drawBigScore(view_width/2+75, view_height/2+135); ctx.font="italic 30px Verdana"; ctx.fillText("Tap to play!", view_width/2-90, view_height/2+200); }
f9babd2569f61418abbf5b8d80a8a7e5d6778190
[ "Markdown", "JavaScript" ]
2
Markdown
neczpal/tritop
7034bd6eea2c02e4769614651084dea2fc616a60
d89ee7ae01854e3679dfcc3d9d9111e1a7de6977
refs/heads/main
<file_sep>import axios from "axios"; const envVariables = ""; import actions from "./types"; const sayHello = (payload) => ({ type: actions.META_SAY_HELLO, payload, }); const toggleModelSelector = (payload) => ({ type: actions.META_TOGGLE_PANEL, payload, }); const goToNextStep = () => ({ type: actions.META_GO_TO_NEXT_STEP, }); const goToPreviousStep = () => ({ type: actions.META_GO_TO_PREVIOUS_STEP, }); const showNeedMoreHelpModal = () => ({ type: actions.META_SHOW_NEED_MORE_HELP_MODAL, }); const hideNeedMoreHelpModal = () => ({ type: actions.META_HIDE_NEED_MORE_HELP_MODAL, }); const showRecommendedLayoutsModal = () => ({ type: actions.META_SHOW_RECOMMENDED_LAYOUTS_MODAL, }); const hideRecommendedLayoutsModal = () => ({ type: actions.META_HIDE_RECOMMENDED_LAYOUTS_MODAL, }); const showRoomBuilderPositionHelperModal = () => ({ type: actions.META_SHOW_ROOM_BUILDER_POSITION_HELPER, }); const hideRoomBuilderPositionHelperModal = () => ({ type: actions.META_HIDE_ROOM_BUILDER_POSITION_HELPER, }); const showWishlistModal = () => ({ type: actions.META_SHOW_WISHLIST_MODAL, }) const hideWishlistModal = () => ({ type: actions.META_HIDE_WISHLIST_MODAL, }) const toggleWishlistModal = () => ({ type: actions.META_TOGGLE_WISHLIST_MODAL, }) // Actions export const SayHello = () => async (dispatch) => { try { dispatch(sayHello()); } catch (e) {} }; export const TogglePanel = (state) => async (dispatch) => { try { dispatch(toggleModelSelector(state)); } catch (e) {} }; export const GoToNextStep = () => async (dispatch) => { try { dispatch(goToNextStep()); } catch (e) {} }; export const GoToPreviousStep = () => async (dispatch) => { try { dispatch(goToPreviousStep()); } catch (e) {} }; export const ShowNeedMoreHelpModal = () => async (dispatch) => { try { dispatch(showNeedMoreHelpModal()); } catch (e) {} }; export const HideNeedMoreHelpModal = () => async (dispatch) => { try { dispatch(hideNeedMoreHelpModal()); } catch (e) {} }; export const ShowRecommendedLayoutsModal = () => async (dispatch) => { try { dispatch(showRecommendedLayoutsModal()); } catch (e) {} }; export const HideRecommendedLayoutsModal = () => async (dispatch) => { try { dispatch(hideRecommendedLayoutsModal()); } catch (e) {} }; export const ShowRoomBuilderPositionHelperModal = () => async (dispatch) => { try { dispatch(showRoomBuilderPositionHelperModal()); } catch (e) {} }; export const HideRoomBuilderPositionHelperModal = () => async (dispatch) => { try { dispatch(hideRoomBuilderPositionHelperModal()); } catch (e) {} }; export const ShowWishlistModal = () => async dispatch => { try { dispatch(showWishlistModal()); } catch (e) {} } export const HideWishlistModal = () => async dispatch => { try { dispatch(hideWishlistModal()); } catch (e) {} } export const ToggleWishlistModal = () => async dispatch => { try { dispatch(toggleWishlistModal()); } catch (e) {} } <file_sep>import actionTypes from "./types"; import threekitConfig from '../../../config/threekitConfig'; const INIT_STATE = { threekitScriptURL: threekitConfig.threekitScriptURL, threekitURL: threekitConfig.threekitURL, threekitAuthToken: threekitConfig.authToken, threekitInitialAsset: threekitConfig.assetId, threekitOrgId: threekitConfig.orgId }; export default (state = INIT_STATE, action) => { let _data = state.data; const { payload, type } = action; switch (type) { default: return { ...state }; } }; <file_sep>import React, { Suspense } from "react"; import { Provider } from "react-redux"; import { PersistGate } from 'redux-persist/integration/react'; import { configureStore } from "./app/redux/store"; import ReactDOM from "react-dom"; import App from "./app/containers/App/index.js"; import "./index.css"; // const store = configureStore(); const e = React.createElement; const domContainer = document.getElementById("react-root"); ReactDOM.render( e(() => ( <Provider store={configureStore().store}> <PersistGate loading={null} persistor={configureStore().persistor}> <Suspense fallback={<div className="loading" />}> <App /> </Suspense> </PersistGate> </Provider> )), domContainer ); <file_sep>import React from "react"; import ReactPlayer from 'react-player'; const VideoPlayer = (props) => { const { url } = props; return ( <div className="video-player-container"> <ReactPlayer controls url={url} onReady={() => console.log("on ready callback")} onStart={() => console.log("on start callback")} onPause={() => console.log("on pause callback")} onEnded={() => console.log("on end callback")} onError={() => console.log("on error callback")} /> </div> ) } export default VideoPlayer;<file_sep>import React, { useState, useEffect } from 'react'; import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; import "./pdfGenerator.css"; import jsPDF from 'jspdf'; import html2canvas from 'html2canvas'; import { EMAIL_SEND_PDF } from '../../api/baseUrl'; import { get, post } from '../../api/api'; import manifoldImg from '../../../assets/manifold.png'; import Threekit_Player from '../../components/Threekit/Player'; import threekitHelper from "../../util/threekit"; import threekitConfig from '../../../config/threekitConfig'; const volumnJson = [ { amount: '2', category: 'Tubing', company: 'Saint-Gobain', label: 'C-Flex', material: 'Silicone', ID: '1/8', OD: '3/8', wall: '3/4', length: '1m', fillingVol: '-', holdupVol: '8 ml' }, { amount: '5', category: 'Bags', company: 'Entegris', label: '', material: 'PP', ID: '-', OD: '-', wall: '-', length: '-', fillingVol: '5 L', holdupVol: '-' } ] const PdfDocument = ({ props }) => { const [pdfRowData, setPdfRowData] = useState([]); const [apiMessage, setApiMessage] = useState(''); const setpdfData = async () => { // let image = new Image(); // let imgSrc = await player.snapshotAsync(); // image.src = imgSrc; let products = await threekitHelper.fetchProducts( threekitConfig.productId ); let productId = sessionStorage.getItem("currentIdPresetOnFocusThreeD"); const currentProd = products.filter(item =>{ if(item.id == productId){ return item } return }); console.log("threekit image", currentProd); // setPdfRowData(volumnJson); // console.log("pdf data", pdfRowData); const input = document.querySelector("#divToPrint")//docPdf(); // await html2canvas(input).then((canvas) => { // document.body.appendChild(canvas); // const imgData = canvas.toDataURL('image/png'); // const pdf = new jsPDF(); // pdf.addImage(imgData, 'JPEG', 0, 0); // pdf.output('dataurlnewwindow'); // pdf.save("download.pdf"); // }); const bodyParser = { to: "", html: input } // console.log("bodyParser", bodyParser); // return const reqObj = { productId: sessionStorage.getItem("currentIdPresetOnFocusTwoD"), // linkpreview: products.attributes.images[0] } console.log("reqObj", reqObj); // post(EMAIL_SEND_PDF, reqObj).then(res => { // console.log("Mail send response response => ", res); // }).catch(err => { // console.log("Error response => ", err); // }); // setTimeout(() => { // window.close(); // }, 200); } useEffect(() => { setpdfData(); }, []); return (<Document> <Page size="A4"> <div id="divToPrint" className="mt4"> <table> <tr> <td colSpan="8"> <div id='threekit-embed' style={{ height: '100%', width: '100%', position: 'relative', bottom: '33%' }}> <Threekit_Player idSelector='threekit-embed' model={sessionStorage.getItem("currentIdPresetOnFocusTwoD")} /> </div> </td> </tr> </table> <table> <tr> <th style={{ fontSize: 11 }}>Amount</th> <th style={{ fontSize: 11 }}>Category</th> <th style={{ fontSize: 11 }}>Company</th> <th style={{ fontSize: 11 }}>Label</th> <th style={{ fontSize: 11 }}>Material</th> <th style={{ fontSize: 11 }}>ID</th> <th style={{ fontSize: 11 }}>OD</th> <th style={{ fontSize: 11 }}>Wall</th> <th style={{ fontSize: 11 }}>Length</th> <th style={{ fontSize: 11 }}>Filling volume</th> <th style={{ fontSize: 11 }}>Holdup volume</th> </tr> <tr> <td style={{ fontSize: 11 }}>2</td> <td style={{ fontSize: 11 }}>Tubing</td> <td style={{ fontSize: 11 }}>Saint-Gobain</td> <td style={{ fontSize: 11 }}>C-Flex</td> <td style={{ fontSize: 11 }}>Silicone</td> <td style={{ fontSize: 11 }}>1/8</td> <td style={{ fontSize: 11 }}>3/8</td> <td style={{ fontSize: 11 }}>3/4</td> <td style={{ fontSize: 11 }}>1m</td> <td style={{ fontSize: 11 }}>-</td> <td style={{ fontSize: 11 }}>8ml</td> </tr> </table> </div> </Page> </Document>); } export default PdfDocument; <file_sep>import React, { useState } from 'react'; import ReactDOM from 'react-dom'; import 'antd/dist/antd.css'; import { Modal, Button } from 'antd'; import "./modalCommon.css"; const ModalCommon = (props) => { const { isModalVisible, handleCancel, modalTitle, classProp, modalWidth } = props; return ( <> <Modal title={modalTitle} visible={isModalVisible} footer={null} onCancel={handleCancel} className={classProp} width={modalWidth}> {props.children} </Modal> </> ); }; export default ModalCommon;<file_sep>import actions from "./types"; import accessories from '../../data/accessories.json'; import bags from '../../data/bags.json'; import bottles from '../../data/bottles.json'; import connectors from '../../data/connectors.json'; import filters from '../../data/filters.json'; import fittings from '../../data/fittings.json'; import tubings from '../../data/tubings.json'; import specialItems from '../../data/specialItems.json' const updateModels = (payload) => ({ type: actions.USER_ELEMENT_UPDATED_ADD, payload }); export const UpdateModels = (data) => dispatch => { const accessoriesJson = accessories; const bagsJson = bags; const bottlesJson = bottles; const connectorsJson = connectors; const filtersJson = filters; const fittingsJson = fittings; const tubingsJson = tubings; const specialItemsJson = specialItems; try { switch(data){ case 'accessories': dispatch(updateModels(accessoriesJson)); break; case 'bags': dispatch(updateModels(bagsJson)); break; case 'filters': dispatch(updateModels(filtersJson)); break; case 'fittings': dispatch(updateModels(fittingsJson)); break; case 'bottles': dispatch(updateModels(bottlesJson)); break; case 'tubings': dispatch(updateModels(tubingsJson)); break; case 'connectors': dispatch(updateModels(connectorsJson)); break; case 'specialItems': dispatch(updateModels(specialItemsJson)); break; } } catch (e) { } };<file_sep>const USER_ELEMENT_UPDATED_ADD = "USER_ELEMENT_UPDATED_ADD"; const USER_ELEMENT_UPDATED_REMOVE = "USER_ELEMENT_UPDATED_REMOVE"; export default { USER_ELEMENT_UPDATED_ADD, USER_ELEMENT_UPDATED_REMOVE };<file_sep>import React, { useState, useEffect } from "react"; import loadjs from "loadjs"; import { useActions } from "../../hooks/useActions"; import { useSelector } from "react-redux"; import { ThreekitSetSinglePlayerLoadingStatus, ThreekitSelectModel, ThreekitInitCameraValues, ThreekitFetchModels } from '../../redux/Threekit/actions'; const Threekit_Player = (props) => { const { idSelector, model } = props; const [playerConfiguration, setPlayerConfiguration] = useState(null); const [playerImgSnap, setPlayerImgSnap] = useState(''); const state = useSelector((store) => { return { Meta: store.Meta, Config: store.Config, }; }); const actions = useActions({ ThreekitSetSinglePlayerLoadingStatus, ThreekitSelectModel, ThreekitFetchModels, ThreekitInitCameraValues }); useEffect(() => { actions.ThreekitSetSinglePlayerLoadingStatus(true); actions.ThreekitInitCameraValues(true); loadjs(state.Config.threekitScriptURL); window .threekitPlayer({ authToken: state.Config.threekitAuthToken, el: idSelector ? document.getElementById(idSelector) : document.getElementById("player-container"), assetId: model ? model : 'd44c3e8d-f766-4806-bc06-5686c4b2500b', orgId: state.Config.threekitOrgId, showConfigurator: false, showAR: false, showLoadingThumbnail: true, //publishStage: 'draft', }) .then(async (api) => { api.enableApi("configurator"); api.enableApi("player"); api.enableApi("store"); //let metadata = window.threeDPlayer.configurator.getMetadata().categories ? window.threeDPlayer.configurator.getMetadata().categories : undefined; //metadata = metadata ? JSON.parse(metadata) : undefined; // console.log('metadata', metadata) //const number = 10; //await twoD.camera.zoom(number); if(idSelector == 'threekit-embed'){ window.twoDPlayer = api; } else { window.threeDPlayer = api; window.threeDPlayer.configurator = await api.getConfigurator(); debugger } //await api.when("loaded"); //api.tools.setTool('orbit', { options: { turnTableMobileOnly: false } }); // api.selectionSet.setStyle({ outlineColor: "#B49F7D" }); // window.roomBuilder = {}; // window.roomBuilder.clickedComponent = null; // window.roomBuilder.api = api; // window.roomBuilder.api.configurator = await api.getConfigurator(); /* TODO: Crear método para configuración inicial de modelo, en caso de ser requerido window.roomBuilder.api.configurator.setConfiguration({ "Cup Holder": "Black", }); */ // setPlayerConfiguration(window.roomBuilder.api.configurator); // actions.ThreekitSetSinglePlayerLoadingStatus(false); // let attributeName = "Component 1"; // let player = await window.roomBuilder.api.enableApi("player"); // let parentConfigurator = await player.getConfigurator(); // let values = parentConfigurator.getDisplayAttributes().filter(e => e.name == "Component 1")[0].values; // let value = values.filter(e => e.assetId == parentConfigurator.configuration["Component 1"].assetId)[0]; // actions.ThreekitSelectModel(value) }); }, []); // const shouldShowSinglePlayer = () => { // return true; // let shouldShow = false; // if (state.Meta.currentActivity == 1) { // shouldShow = true; // } // return shouldShow; // } // const shouldShowRoomBuilderPlayer = () => { // return true; // let shouldShow = false; // if (state.Meta.currentActivity == 2) { // shouldShow = true; // } // return shouldShow; // } return ( <div id="player"> {/* <div id="player-preview" hidden={ !shouldShowSinglePlayer() } className={className}></div> <div id="room-builder-preview" hidden={ !shouldShowRoomBuilderPlayer() } className={className}></div> */} </div> ); }; export default Threekit_Player; <file_sep>import React, { useState, useEffect } from "react"; const Button = (props) => { const { icon, label, onClickHandler, className,disabled } = props; return ( <button className={className} onClick={onClickHandler} disabled={disabled}> {icon} {label} </button> ); }; export default Button;<file_sep>import React, { useState, useEffect } from "react"; import { ListGroup, Row, Col } from "react-bootstrap"; import Threekit_Player from "./Player"; const Threekit = (props) => { const { className } = props; const [playerModel, setPlayerModel] = useState(null); return ( <> <div id="player-container" className="p-0"> <Threekit_Player className={className} model={playerModel} /> </div> </> ); }; export default Threekit; <file_sep>const THREEKIT_FETCH_MODELS = "THREEKIT_FETCH_MODELS"; const THREEKIT_SET_MODELS_SET = "THREEKIT_SET_MODELS_SET"; const THREEKIT_SELECT_MODEL = "THREEKIT_SELECT_MODEL"; const THREEKIT_FETCH_TEXTURES = "THREEKIT_FETCH_TEXTURES"; const THREEKIT_SET_TEXTURES_SET = "THREEKIT_SET_TEXTURES_SET"; const THREEKIT_FETCH_NAILHEAD_MATERIALS = "THREEKIT_FETCH_NAILHEAD_MATERIALS"; const THREEKIT_SET_NAILHEAD_MATERIALS_SET = "THREEKIT_SET_NAILHEAD_MATERIALS_SET"; const THREEKIT_SET_SELECTED_MODEL_SEATING_TEXTURE = "THREEKIT_SET_SELECTED_MODEL_SEATING_TEXTURE"; const THREEKIT_SET_SELECTED_MODEL_NAILHEADS_MATERIAL = "THREEKIT_SET_SELECTED_MODEL_NAILHEADS_MATERIAL"; const THREEKIT_SET_COLOR_BLOCKING_TEXTURES = "THREEKIT_SET_COLOR_BLOCKING_TEXTURES"; const THREEKIT_INIT_CAMERA_VALUES = "THREEKIT_INIT_CAMERA_VALUES"; const THREEKIT_SET_ACTIVE_CAMERA = "THREEKIT_SET_ACTIVE_CAMERA"; const THREEKIT_SET_SINGLE_PLAYER_LOADING_STATUS = "THREEKIT_SET_SINGLE_PLAYER_LOADING_STATUS"; const THREEKIT_SET_ROOM_BUILDER_PLAYER_LOADING_STATUS = "THREEKIT_SET_ROOM_BUILDER_PLAYER_LOADING_STATUS"; const THREEKIT_SET_ROOM_BUILDER_COMPONENT_MODEL = "THREEKIT_SET_ROOM_BUILDER_COMPONENT_MODEL"; export default { THREEKIT_FETCH_MODELS, THREEKIT_SET_MODELS_SET, THREEKIT_SELECT_MODEL, THREEKIT_FETCH_TEXTURES, THREEKIT_SET_TEXTURES_SET, THREEKIT_SET_SELECTED_MODEL_SEATING_TEXTURE, THREEKIT_FETCH_NAILHEAD_MATERIALS, THREEKIT_SET_NAILHEAD_MATERIALS_SET, THREEKIT_SET_SELECTED_MODEL_NAILHEADS_MATERIAL, THREEKIT_SET_COLOR_BLOCKING_TEXTURES, THREEKIT_INIT_CAMERA_VALUES, THREEKIT_SET_ACTIVE_CAMERA, THREEKIT_SET_SINGLE_PLAYER_LOADING_STATUS, THREEKIT_SET_ROOM_BUILDER_PLAYER_LOADING_STATUS, THREEKIT_SET_ROOM_BUILDER_COMPONENT_MODEL, }; <file_sep>import React, { useState, useEffect } from "react"; import Slider from "react-slick"; import slideOne from "../../../assets/1.png"; import slideTwo from "../../../assets/2.jpeg"; import slideThree from "../../../assets/3.jpg"; import slideFour from "../../../assets/4.jpg"; import slideFive from "../../../assets/5.jpg"; import slideSix from "../../../assets/6.jpg"; import { RightOutlined, LeftOutlined , } from '@ant-design/icons'; const images = [slideOne, slideTwo, slideThree, slideFour, slideFive, slideSix]; const Carousel = (props) => { const [imageIndex, setImageIndex] = useState(0); const [leftIndex, setLeftIndex] = useState(images.length - 1); const [rightIndex, setRightIndex] = useState(imageIndex + 1); const playerTwoDIds = [ 'b1024215-eb9a-4c47-9b4b-7a50799f7ab9', '3c5111b5-46b3-42ea-ba7f-b2884b54f0be', '53444ea4-a0d6-4a23-a6cc-436b0d28d523', '5fcc8fff-d1aa-426d-b298-fc6f85778be1', '2cd6bcd4-6a71-4da8-81b0-d0370ef1fc99', '1a757cca-6162-4197-99bb-2ef833c3bb8e', '6563829b-925e-47b7-8afb-9edd5df8c09b', 'd520b0a1-f004-4877-9e6c-fdde57533580', '3d5fe4c0-836a-4430-8ed9-b5f94ec18eee' ] const NextArrow = ({onClick}) => { return ( <button className="arrow next" onClick={onClick}> <RightOutlined className="arrow-icon" /> </button> ) } const PrevArrow = ({onClick}) => { return ( <button className="arrow prev" onClick={onClick}> <LeftOutlined className="arrow-icon" /> </button> ) } const settings = { infinite: true, lazyLoad: true, speed: 300, slidesToShow: 5, slidesToScroll: 5, centerMode: true, centerPadding: 0, nextArrow: <NextArrow />, prevArrow: <PrevArrow />, beforeChange: (current, next) => { setImageIndex(next); setLeftIndex(next); setRightIndex(next); }, initialSlide: 0, responsive: [ { breakpoint: 1600, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, /*dots: true*/ } }, { breakpoint: 980, settings: { slidesToShow: 2, slidesToScroll: 2, initialSlide: 2 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }; return ( <div className="carousel-container"> {console.log('playerTwoDIds', playerTwoDIds[1])} <Slider {...settings} className="slides-container"> {images.map((img, i) => { if(i === imageIndex) { return ( <div className="slide-wrapp primary"> <div key={i} className={"slide activeSlide"} assetId={playerTwoDIds[i]}> <img src={img} alt={img} /> </div> </div> ) } else if(i === (imageIndex + 1) || i === rightIndex) { return ( <div className="slide-wrapp"> <div key={i} className={"slide rightActiveSlide"} assetId={playerTwoDIds[i]}> <img src={img} alt={img} /> </div> </div> ) } else if(i === (imageIndex - 1) || i === leftIndex) { return ( <div className="slide-wrapp"> <div key={i} className={"slide leftActiveSlide"}> <img src={img} alt={img} /> </div> </div> ) } else { return ( <div className="slide-wrapp"> <div key={i} className={"slide"}> <img src={img} alt={img} /> </div> </div> ) } })} </Slider> </div> ) } export default Carousel;<file_sep>import React, { useState, useEffect } from "react"; import Button from "../Button/Button"; import Modal from 'react-modal'; Modal.setAppElement('#react-root'); const customStyles = { overlay: { position: 'fixed', zIndex: '1000', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(255, 255, 255, 0.75)', }, content: { position: 'absolute', top: '40px', left: '42%', right: '40px', bottom: '40px', border: '1px solid #fff', background: '#fff', boxShadow: '0 -2rem 6rem rgba(0, 0, 0, 0.3)', overflow: 'auto', WebkitOverflowScrolling: 'touch', borderRadius: '4px', outline: 'none', padding: '20px', } }; const PresetModal = (props) => { const { modalIsOpen, afterOpenModal, closeModal } = props; return ( <div> <Modal isOpen={modalIsOpen} onAfterOpen={afterOpenModal} onRequestClose={closeModal} contentLabel="Preset Modal" style={customStyles} > <div> <p>hello</p> <button className="btn btn-gray" onClick={closeModal}>close</button> </div> </Modal> </div> ) } export default PresetModal;<file_sep>import React, { useState, useEffect } from "react"; import Button from "../../components/Button/Button"; import Carousel from "../Carousel/Carousel"; import PlayerPannel from "../PlayerPannel/PlayerPannel"; import logo from "../../../assets/logo.png"; import { Link } from 'react-router-dom'; import "./HomePage.css"; const HomePage = () => { function bringPresetFromPlayer() { sessionStorage.setItem("currentIdPresetOnFocusThreeD",document.querySelector('.slick-current').children[0].children[0].attributes.assetidthreed.value); sessionStorage.setItem("currentIdPresetOnFocusTwoD",document.querySelector('.slick-current').children[0].children[0].attributes.assetidtwod.value); } return ( <div className="homepage"> <div className="logo"> <img src={logo} /> </div> <PlayerPannel className="player-button" iconClassName="icon-size" /> <div className="preset-container"> <Carousel /> <div className="preset-buttons"> <Link to={'/add-preset'}> <Button icon={null} label={"add a preset"} className="btn btn-white" onClickHandler={bringPresetFromPlayer} /> </Link> <Link to="/new-design"> <Button icon={null} label={"new design"} className="btn btn-transparent" onClickHandler={() => {}} /> </Link> </div> </div> </div> ) } export default HomePage;<file_sep>import threekitHelper from "../../util/threekit"; import actions from "./types"; import threekitConfig from '../../../config/threekitConfig'; const threekitSetModelSet = payload => ({ type: actions.THREEKIT_SET_MODELS_SET, payload }) const threekitSetTextureSet = payload => ({ type: actions.THREEKIT_SET_TEXTURES_SET, payload }) const threekitSetColorBlockingTextures = payload => ({ type: actions.THREEKIT_SET_COLOR_BLOCKING_TEXTURES, payload }) const threekitSetNailheadMaterialSet = payload => ({ type: actions.THREEKIT_SET_NAILHEAD_MATERIALS_SET, payload }) const threekitSelectModel = payload => ({ type: actions.THREEKIT_SELECT_MODEL, payload }) const threekitSetRoomBuilderComponentModel = payload => ({ type: actions.THREEKIT_SET_ROOM_BUILDER_COMPONENT_MODEL, payload }) const threekitSetSelectedModelSeatingTexture = payload => ({ type: actions.THREEKIT_SET_SELECTED_MODEL_SEATING_TEXTURE, payload }) const threekitSetSelectedModelNailheadsMaterial = payload => ({ type: actions.THREEKIT_SET_SELECTED_MODEL_NAILHEADS_MATERIAL, payload }) const threekitInitCameraValues = payload => ({ type: actions.THREEKIT_INIT_CAMERA_VALUES, payload }) const threekitSetSinglePlayerLoadingStatus = payload => ({ type: actions.THREEKIT_SET_SINGLE_PLAYER_LOADING_STATUS, payload }) const threekitSetRoomBuilderPlayerLoadingStatus = payload => ({ type: actions.THREEKIT_SET_ROOM_BUILDER_PLAYER_LOADING_STATUS, payload }) // Actions export const ThreekitFetchModels = () => async dispatch => { try { let products = await threekitHelper.fetchProducts( "preview", threekitConfig.authToken, threekitConfig.orgId, "component", "ui" ); let models = products.map((product, i) => { let features = {}; try { features = JSON.parse(product.description); } catch (e) {} return { id: product.id, name: product.name, attributes: { images: [`https://preview.threekit.com/api/assets/thumbnail/${product.id}?orgId=0db40a8d-a8fd-4900-8258-963ab37d7eb9&failOnEmpty=true&cacheMaxAge=300&cacheScope=thumbnail&bearer_token=<PASSWORD>`], featuredText: features?.featuredText, nailHeads: { available: product.keywords.filter(keyword => keyword == "nailheads").length > 0, values: [] }, colorBlocking: { available: product.keywords.filter(keyword => keyword == "color_blocking_1").length > 0, values: [], }, animationImage: features.animationImage || null }, features: features?.specifications, standardFeatures: features?.standardFeatures, armrestSelection: [], } }) dispatch(threekitSetModelSet(models)); } catch (e) { console.error(e); } } export const ThreekitFetchTextures = () => async dispatch => { try { let products = await threekitHelper.fetchProducts( "preview", "31755654-4081-45d7-88e1-ee46a673b350", "0db40a8d-a8fd-4900-8258-963ab37d7eb9", "texture" ); let textures = products.map(product => { let features = {}; try { features = JSON.parse(product.description); } catch (e) {} return { id: product.id, label: product.name, image: [`https://preview.threekit.com/api/assets/thumbnail/${product.id}?orgId=0db40a8d-a8fd-4900-8258-<PASSWORD>&failOnEmpty=true&cacheMaxAge=300&cacheScope=thumbnail&bearer_token=<PASSWORD>`], } }) dispatch(threekitSetTextureSet(textures)); } catch (e) {} } export const ThreekitFetchNailheadMaterials = () => async dispatch => { try { fetch("https://preview.threekit.com/api/catalog/products?bearer_token=<PASSWORD>&orgId=0db40a8d-a8fd-4900-8258-963ab37d7eb9&tags=nailhead_material") .then(r => r.json()) .then(response => { let products = response.products ? response.products : []; let materials = []; materials = products.map((product, i) => { let features = {}; try { features = JSON.parse(product.description); } catch (e) {} return { id: product.id, label: product.name, image: [`https://preview.threekit.com/api/assets/thumbnail/${product.id}?orgId=0db40a8d-a8fd-4900-8258-963ab37d7eb9&failOnEmpty=true&cacheMaxAge=300&cacheScope=thumbnail&bearer_token=<PASSWORD>`], } }) dispatch(threekitSetNailheadMaterialSet(materials)); }) } catch (e) {} } export const ThreekitFetchColorBlockingTextures = () => async dispatch => { try { fetch("https://preview.threekit.com/api/catalog/products?bearer_token=<PASSWORD>-4081-45d7-88e1-ee46a673b350&orgId=0db40a8d-a8fd-4900-8258-963ab37d7eb9&tags=texture") .then(r => r.json()) .then(response => { let products = response.products ? response.products : []; let textures = []; textures = products.map((product, i) => { let features = {}; try { features = JSON.parse(product.description); } catch (e) {} return { id: product.id, label: product.name, image: [`https://preview.threekit.com/api/assets/thumbnail/${product.id}?orgId=0db40a8d-a8fd-4900-8258-963ab37d7eb9&failOnEmpty=true&cacheMaxAge=300&cacheScope=thumbnail&bearer_token=<PASSWORD>`], } }) dispatch(threekitSetColorBlockingTextures(textures)); }) } catch (e) {} } export const ThreekitSelectModel = model => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); const configurator = await threekitHelper.getParentConfigurator(); const value = await threekitHelper.getDisplayAttribute(model?.name, "Component 1", configurator); void await threekitHelper.setConfiguration(configurator, { "Component 1" : { assetId : value.assetId } }); void await dispatch(threekitSelectModel(model)); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) { console.error(e); } } export const ThreekitSetRoomBuilderComponentModel = (row, seat, model) => async dispatch => { const maxSeatsPerRow = 8; const componentNumber = row > 1 ? (seat + ((row - 1) * maxSeatsPerRow)) : seat; if (row == 2) { seat += 8; } try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let attributeName = "Component " + componentNumber; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let values = parentConfigurator.getDisplayAttributes().filter(e => e.name == attributeName)[0].values; let value = values.filter(e => e.name == model)[0]; // TODO: @olivermontalvanm Encontrar una mejor forma de hacer esto: /* Por alguna razón, Component X no puede ser un valor dinámico como [attributeName] */ switch(componentNumber) { case 1: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 1" : { assetId : value.assetId } }); break; case 2: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 2" : { assetId : value.assetId } }); break; case 3: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 3" : { assetId : value.assetId } }); break; case 4: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 4" : { assetId : value.assetId } }); break; case 5: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 5" : { assetId : value.assetId } }); break; case 6: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 6" : { assetId : value.assetId } }); break; case 7: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 7" : { assetId : value.assetId } }); break; case 8: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 8" : { assetId : value.assetId } }); break; case 9: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 9" : { assetId : value.assetId } }); break; case 10: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 10" : { assetId : value.assetId } }); break; case 11: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 11" : { assetId : value.assetId } }); break; case 12: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 12" : { assetId : value.assetId } }); break; case 13: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 13" : { assetId : value.assetId } }); break; case 14: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 14" : { assetId : value.assetId } }); break; case 15: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 15" : { assetId : value.assetId } }); break; case 16: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 16" : { assetId : value.assetId } }); break; case 17: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 17" : { assetId : value.assetId } }); break; case 18: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 18" : { assetId : value.assetId } }); break; case 19: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 19" : { assetId : value.assetId } }); break; case 20: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 20" : { assetId : value.assetId } }); break; case 21: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 21" : { assetId : value.assetId } }); break; case 22: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 22" : { assetId : value.assetId } }); break; case 23: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 23" : { assetId : value.assetId } }); break; case 24: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 24" : { assetId : value.assetId } }); break; case 25: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 25" : { assetId : value.assetId } }); break; case 26: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 26" : { assetId : value.assetId } }); break; case 27: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 27" : { assetId : value.assetId } }); break; case 28: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 28" : { assetId : value.assetId } }); break; case 29: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 29" : { assetId : value.assetId } }); break; case 30: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 30" : { assetId : value.assetId } }); break; case 31: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 31" : { assetId : value.assetId } }); break; case 32: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 32" : { assetId : value.assetId } }); break; } void await dispatch(threekitSetRoomBuilderComponentModel(model)); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) { console.error(e); } } export const ThreekitSwapModelsInRow = (row, model) => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); for (let i = 1; i <= 8; i++){ let attributeName = "Component " + i; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let values = parentConfigurator.getDisplayAttributes().filter(e => e.name == attributeName)[0].values; let value = values.filter(e => e.name == model)[0]; // TODO: @olivermontalvanm Encontrar una mejor forma de hacer esto: /* Por alguna razón, Component X no puede ser un valor dinámico como [attributeName] */ switch(row) { case 1: void await window.roomBuilder.api.configurator.setConfiguration( { "Component 1" : { assetId : value.assetId }, "Component 2" : { assetId : value.assetId }, "Component 3" : { assetId : value.assetId }, "Component 4" : { assetId : value.assetId }, "Component 5" : { assetId : value.assetId }, "Component 6" : { assetId : value.assetId }, "Component 7" : { assetId : value.assetId }, "Component 8" : { assetId : value.assetId }, } ); break; case 2: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 9" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 10" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 11" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 12" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 13" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 14" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 15" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 16" : { assetId : value.assetId } }); break; case 3: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 17" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 18" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 19" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 20" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 21" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 22" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 23" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 24" : { assetId : value.assetId } }); break; case 4: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 25" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 26" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 27" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 28" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 29" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 30" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 31" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 32" : { assetId : value.assetId } }); break; } void await dispatch(threekitSetRoomBuilderComponentModel(model)); } dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch(e) { console.error(e); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } } export const ThreekitPopulateRowWithModel = (row, seats, model) => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); for (let i = 1; i <= seats; i++){ let attributeName = "Component " + i; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let values = parentConfigurator.getDisplayAttributes().filter(e => e.name == attributeName)[0].values; let value = values.filter(e => e.name == model)[0]; // TODO: @olivermontalvanm Encontrar una mejor forma de hacer esto: /* Por alguna razón, Component X no puede ser un valor dinámico como [attributeName] */ switch(row) { case 1: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 1" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 2" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 3" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 4" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 5" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 6" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 7" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 8" : { assetId : value.assetId } }); break; case 2: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 9" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 10" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 11" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 12" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 13" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 14" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 15" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 16" : { assetId : value.assetId } }); break; case 3: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 17" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 18" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 19" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 20" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 21" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 22" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 23" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 24" : { assetId : value.assetId } }); break; case 4: void await window.roomBuilder.api.configurator.setConfiguration({ "Component 25" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 26" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 27" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 28" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 29" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 30" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 31" : { assetId : value.assetId } }); void await window.roomBuilder.api.configurator.setConfiguration({ "Component 32" : { assetId : value.assetId } }); break; } void await dispatch(threekitSetRoomBuilderComponentModel(model)); } dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) { console.error(e); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } }; export const ThreekitSetSelectedModelSeatingTexture = texture => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let attributeName = "Component 1"; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let itemId = await parentConfigurator.getAppliedConfiguration(attributeName); let configurator = await window.roomBuilder.api.scene.get({ id: itemId, evalNode: true, }).configurator; let seatingValues = configurator.getDisplayAttributes().filter(e => e.name == "Seating Texture")[0].values; let seatingValue = seatingValues.filter(e => e.name == texture)[0]; void await configurator.setConfiguration({ "Seating Texture" : { assetId : seatingValue.assetId } }); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} } export const ToggleSingleComponentMeasurements = () => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); void await parentConfigurator.setConfiguration({ "Show Dimensions" : parentConfigurator.getAppliedConfiguration("Show Dimensions") == "False" ? "True" : "False" }); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} } export const ThreekitToggleSceneMode = value => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); void await parentConfigurator.setConfiguration({ "Mode" : value }); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch(e){} }; export const ThreekitCloneComponent = (componentSource, componentTarget) => async dispatch => { let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let component1Id = await parentConfigurator.getAppliedConfiguration("Component 1"); let component2Id = await parentConfigurator.getAppliedConfiguration("Component 10"); let component1Config = await window.roomBuilder.api.scene.get({ id: component1Id, evalNode: true, }).configurator; let component2Config = await window.roomBuilder.api.scene.get({ id: component2Id, evalNode: true, }).configurator; component2Config.setConfiguration({ "Seating Texture" : { assetId : component1Config.appliedConfiguration["Seating Texture"] }, "Piping Texture" : { assetId : component1Config.appliedConfiguration["Piping Texture"] }, "Nailheads Material" : { assetId : component1Config.appliedConfiguration["Nailheads Material"] }, }); } export const ThreekitSetSelectedModelNailheadsMaterial = material => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let attributeName = "Component 1"; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let itemId = await parentConfigurator.getAppliedConfiguration(attributeName); let configurator = await window.roomBuilder.api.scene.get({ id: itemId, evalNode: true, }).configurator; let nailheadValues = configurator.getDisplayAttributes().filter(e => e.name == "Nailheads Material")[0].values; let nailheadValue = nailheadValues.filter(e => e.name == material)[0]; void await configurator.setConfiguration({ "Nailheads Material" : { assetId : nailheadValue.assetId } }); void await dispatch(threekitSetSelectedModelNailheadsMaterial(material)); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} } export const ThreekitSetSelectedModelColorBlockingTexture = material => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); let attributeName = "Component 1"; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let itemId = await parentConfigurator.getAppliedConfiguration(attributeName); let configurator = await window.roomBuilder.api.scene.get({ id: itemId, evalNode: true, }).configurator; let seatingValues = configurator.getDisplayAttributes().filter(e => e.name == "Color Blocking 1 Texture")[0].values; let seatingValue = seatingValues.filter(e => e.name == material)[0]; void await configurator.setConfiguration({ "Color Blocking 1 Texture" : { assetId : seatingValue.assetId } }); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} } export const ThreekitInitCameraValues = () => async dispatch => { try { void dispatch(threekitSetSinglePlayerLoadingStatus(true)); let attributeName = "Active Camera"; let player = await window.roomBuilder.api.enableApi("player"); let parentConfigurator = await player.getConfigurator(); let cameraValues = parentConfigurator.getDisplayAttributes().filter(e => e.name == attributeName)[0].values; void await dispatch(threekitInitCameraValues(cameraValues)); void dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} }; export const ThreekitSetActiveCamera = camera => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(true)); const attributeName = "Active Camera"; const player = await window.roomBuilder.api.enableApi("player"); const parentConfigurator = await player.getConfigurator(); const cameraValues = parentConfigurator.getDisplayAttributes().filter(e => e.name == attributeName)[0].values; const cameraValue = cameraValues.filter(e => e.label == camera)[0]; void await parentConfigurator.setConfiguration({"Active Camera" : cameraValue.value }); dispatch(threekitSetSinglePlayerLoadingStatus(false)); } catch (e) {} }; export const ThreekitSetSinglePlayerLoadingStatus = status => async dispatch => { try { dispatch(threekitSetSinglePlayerLoadingStatus(status)); } catch (e) {} }; export const ThreekitSetRoomBuilderPlayerLoadingStatus = status => async dispatch => { try { dispatch(threekitSetRoomBuilderPlayerLoadingStatus(status)); } catch (e) {} };
7de4e24644345d1a3c939734383bab1e9f2777e0
[ "JavaScript" ]
16
JavaScript
joel1001/single-use-dev
28efed69ab765bfff32bee49cc6b3b9f4edb89ab
d4ed2981897d093be90b1c9bf6ac7b3b2d4f8d7d
refs/heads/master
<file_sep>import pandas as pd import numpy as np import urllib.request import bs4 from coordinate import Coordinate, dms_to_decimal, deg2rad, rad2nm, meters2nm class AirportData: def __init__(self): self.airport_df = None def get_csv_data(self, filename='airports.csv'): #https://openflights.org/data.html self.airport_df = pd.read_csv(filename, usecols=['Name','ICAO', 'Latitude', 'Longitude', 'Altitude']) #print(self.airport_df) def get_nearby_airports(self, pos, dist=250): """ Get the airports within a distance threshold of a given position Input: pos - reference position, Coordinate object dist - theshold distance in terms of nauthical miles Output: nearby_airports - dataframe of airports that meet the filtering criteria """ # Create dataframe with airports within a distance threshold of pos dist_bool = self.airport_df.apply(lambda x: abs(pos.calc_dist(Coordinate(x['Latitude'], x['Longitude']))) < dist, axis=1) nearby_airports = self.airport_df[dist_bool] # Add a column with the distance between the position reference and each nearby airport nearby_airports['Distance'] = nearby_airports.apply(lambda x: pos.calc_dist(Coordinate(x['Latitude'], x['Longitude'])), axis=1) return nearby_airports def get_reachable_airports(self, pos, altitude, glide_ratio=20): """ Get the airports that an aircraft can feasibly glide to, based on its glide ratio and current altitude. Input: pos - aircraft's current position coordinate altitude - aircraft's current altitude (meters) glide_ratio - aircraft's glide ratio, default set to 20 (20 units of horizontal travel for every unit of lost altitude) Output: valid_airports - pandas dataframe with reachable airports, with columns for buffer distance and true heading added """ # Get nearby airports and add glide distance column, which describes how far the aircraft can glide # from its altitude to the altitude of each airport nearby_airports = self.get_nearby_airports(pos) nearby_airports['Glide Distance'] = nearby_airports['Altitude'].apply(lambda x: meters2nm((altitude - x)*glide_ratio)) # Valid airports as those which are closer than the glide distance valid_airports = nearby_airports[nearby_airports['Glide Distance'] > nearby_airports['Distance']] return valid_airports def get_airport_lookup_info(self, icao): #TODO implement more scrapping to get more info of interest, such as comm frequencies """ Performs webscrapping on SkyVector to get more information about a given airport Input: icao - unique airport identification code Output: airport_info - dataframe containing the following information about the airport of interest: ....... """ # Get xml data for the airport corresponding to the icao code from url request, convert to bs4 object req = urllib.request.Request('https://skyvector.com/airport/'+icao) response = urllib.request.urlopen(req) self.page = bs4.BeautifulSoup(response.read(), "lxml") # Get all aptdata objects sections = self.page.find_all('div', class_='aptdata') # Iterate through each table, looking for values of interest for table in sections: # Determine which table type is being parsed title = table.find('div', class_='aptdatatitle').text # If runway table, isolate runway name and dimensions if 'Runway' in title: tr = table.find('tr') td = tr.find('td') runway_name = title runway_dim = td.text elif 'Operations' in title: pass elif 'Airport Comm' in title: pass else: continue if __name__ == "__main__": ad = AirportData() ad.get_csv_data("airports.csv") #ad.get_reachable_airports(Coordinate(33, -118), 10000) ad.get_airport_lookup_info('KLAX') <file_sep>import pandas as pd import numpy as np import time from coordinate import * from opensky_api import OpenSkyApi class ATC_Data: def __init__(self): # Initialize live data API and state vector self.api = OpenSkyApi() self.aircraft_dict = {} self.aircraft_df = None def get_live_data(self, bounds=None): """ Get current aircraft data from OpenSky API and create a dataframe with info of interest Input: bounds - if only interested in aircraft within a specified lat and long range. Otherwise, gets current data for all aircraft """ # Get current state vector for aircraft. If bbox argument is passed in, will # only get info for aircraft in that coordinate range if bounds: self.states = self.api.get_states(bbox=bounds) else: self.states = self.api.get_states() # For each aircraft, extract relevant values and place into dictionary for s in self.states.states: self.aircraft_dict[s.icao24] = [s.latitude, s.longitude, s.heading, s.velocity, s.geo_altitude, s.vertical_rate, s.on_ground, s.callsign, time.time()-s.last_contact] # Create dataframe from dictionary self.aircraft_df = pd.DataFrame.from_dict(self.aircraft_dict, orient='index', columns=['Latitude', 'Longitude', 'Heading', 'Velocity', 'Altitude', 'Vertical Velocity', 'On Ground', 'Callsign', 'Time Since Last Contact']) #print(self.aircraft_df) def get_csv_data(self, filename): # TODO record live data, make csv file from recorded info, then add in csv reader to work with # the recorded data. Alternatively pull csv data from openskyapi website pass def get_cpa_info(p0, u, q0, v): # TODO check if this works, debug # TODO add in an altitude filter so only aircraft within some height threshold are compared """ Find CPA distance and time to CPA between two aircraft Formulas at http://geomalgorithms.com/a07-_distance.html Input: p0, q0 - current 2D position vectors of aircraft one and two u, v - current 2D velocity vectors of aircraft one and two Output: cpa distance and time to cpa """ # Calculate time to CPA if u - v == 0.0: time_to_cpa = 0 else: time_to_cpa = np.dot((q0 - p0), (u-v)) / sum((u-v)**2) # Estimate position at CPA time pos1 = p0 + u * time_to_cpa pos2 = q0 + v * time_to_cpa # Calculate CPA distance cpa_distance = np.sqrt((pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2) return cpa_distance, time_to_cpa def get_nearby_aircraft(self, pos, distance): #TODO actually implement this function, everything is just a placeholder currently """ Get aircraft within a distance theshold of a given coordinate position Input: pos - Coordinate object reference position distance - theshold distance used to create a bounding box to return aircraft of interest Output: nearby_aircraft - dataframe of nearby aircraft with heading, velocity, and altitude info """ bounds = ((pos[0]-distance, pos[1]-distance), (pos[0]+distance, pos[1]+distance)) states = self.api.get_states(bbox=bounds) return states def nearest_neighbors_cpa(self, aircraft): # TODO Actually implement this function, currently everything is just a placeholder neighbors = self.get_nearby_aircraft(aircraft) for plane in neighbors: cpa = self.get_cpa_info(aircraft.thing1, aircraft.thing2, plane.thing1, plane.thing2) if __name__ == "__main__": ad = ATC_Data() ad.get_live_data(bounds=(45.8389, 47.8229, 5.9962, 10.5226)) <file_sep># Coordinate class from Lab 2 # New method added to get the true heading to another coordinate import math import datetime class Coordinate: '''A simple class to represent lat/lon values.''' def __init__(self,lat,lon): self.lat = float(lat) # make sure it's a float self.lon = float(lon) # Follows the specification described in the Aviation Formulary v1.46 # by <NAME> (originally at http://williams.best.vwh.net/avform.htm) def calc_dist(self, other): lat1 = deg2rad(self.lat) lon1 = deg2rad(self.lon) lat2 = deg2rad(other.lat) lon2 = deg2rad(other.lon) # there are two implementations of this function. # implementation #1: #dist_rad = math.acos(math.sin(lat1) * math.sin(lat2) # + math.cos(lat1) * math.cos(lat2) * math.cos(lon1-lon2)) # implementation #2: (less subject to numerical error for short distances) dist_rad=2*math.asin(math.sqrt((math.sin((lat1-lat2)/2))**2 + math.cos(lat1)*math.cos(lat2)*(math.sin((lon1-lon2)/2))**2)) return rad2nm(dist_rad) def calc_true_heading(self, other): #TODO Check if this works # Adapted from https://gist.github.com/jeromer/2005586 lat1 = math.radians(self.lat) lat2 = math.radians(other.lat) diffLong = math.radians(other.lon - self.lon) x = math.sin(diffLong) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diffLong)) initial_bearing = math.atan2(x, y) # Now we have the initial bearing but math.atan2 return values # from -180° to + 180° which is not what we want for a compass bearing # The solution is to normalize the initial bearing as shown below initial_bearing = math.degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 return compass_bearing # end of class Coordinate # The following functions are of general use. def dms_to_decimal(degrees,minutes,seconds): '''Convertes coordinates in dms to decimals.''' return degrees + minutes/60 + seconds/3600 def deg2rad(degrees): '''Converts degrees (in decimal) to radians.''' return (math.pi/180)*degrees def rad2nm(radians): '''Converts a distance in radians to a distance in nautical miles.''' return ((180*60)/math.pi)*radians def meters2nm(meters): '''Converts a distance in meters to a distance in nautical miles.''' return meters * 0.000539957 <file_sep>from PIL import Image colorImage = Image.open("p1.png") for theta in range(0, 365, 10): rotated = colorImage.rotate(-theta, expand=False) rotated = rotated.resize((50, 50), Image.ANTIALIAS) outfile = 'p' + str(theta) + '.png' rotated.save(outfile, optimize=True, quality=10)
d324dc348187e5fe18242c6faa833836afefdd8b
[ "Python" ]
4
Python
mluerman/computational_methods
ad13de64edc105d9705540537c3919111b5473c5
50ecf78c1bcf9b62ba6b0afc97b19ea1c6f5db86
refs/heads/main
<repo_name>SamuelFang/spring-2021-235-assignments-kartikk221<file_sep>/recursion/basics.cpp #include <iostream> #include <map> int fib(int n){ return n <= 1 ? n : fib(n - 1) + fib(n - 2); } int fib_iter(int n){ int prev_number = 0; int next_number = 1; for(int i = 1; i <= n; i++){ int sum = prev_number + next_number; prev_number = next_number; next_number = sum; } return prev_number; } /* David's Staircase Problem */ std::map<int, int> steps_cache = {}; int stepPerms(int n) { switch(n){ case 1: return 1; case 2: return 2; case 3: return 4; default: if(steps_cache.count(n) > 0) return steps_cache[n]; steps_cache[n] = stepPerms(n - 1) + stepPerms(n - 2) + stepPerms(n - 3); return steps_cache[n]; } } int main(){ std::cout << "Fibonacci Sequence Recursive @ (n = 9) -> " << fib(9) << std::endl; std::cout << "Fibonacci Sequence Loop @ (n = 9) -> " << fib_iter(9) << std::endl; std::cout << "David's Staircase Possibilities For 10 Stairs @ (n = 10) -> " << stepPerms(10) << std::endl; return 0; }
fa11a6da2d0b6fb90895579a806bb1e1b0b2b480
[ "C++" ]
1
C++
SamuelFang/spring-2021-235-assignments-kartikk221
2edf31d83cf7a861a4f7e1fe507f7ce5e084e223
3c708eff01e8e19f6e06d382d3ef0aab69ca1a98
refs/heads/master
<repo_name>wafflemakr/gethereum<file_sep>/truffle-config.js const HDWalletProvider = require("@truffle/hdwallet-provider"); require("dotenv").config(); const providerFactory = network => { if (process.env.PRIVATE_KEY) return new HDWalletProvider( process.env.PRIVATE_KEY, `https://${network}.infura.io/v3/${process.env.INFURA_KEY}` ); return new HDWalletProvider( process.env.MNEMONICS, `https://${network}.infura.io/v3/${process.env.INFURA_KEY}`, 0, 20 ); }; module.exports = { networks: { development: { host: "127.0.0.1", port: 8545, network_id: 999, gasPrice: 5000000000 // 5 Gwei }, mainnet: { provider: () => providerFactory("mainnet"), network_id: 1, gas: 3000000, gasPrice: 5000000000 // 5 Gwei }, rinkeby: { provider: () => providerFactory("rinkeby"), network_id: 4, gas: 6900000, gasPrice: 10000000000 // 10 Gwei } }, compilers: { solc: { version: "0.5.11", settings: { optimizer: { enabled: true, runs: 200 } } } } }; <file_sep>/migrations/2_deploy_contracts.js const Gethereum = artifacts.require("Gethereum"); const newOwner = "0x7dd9B933ED8385F473Ff81e9DDc334777f20Bf1f"; module.exports = async (deployer, network, accounts) => { await deployer.deploy(Gethereum); const gethereum = await Gethereum.deployed(); await gethereum.transferOwnership(newOwner); }; <file_sep>/README.md # Gethereum ## Contracts Gethereum Contract (Rinkeby): [0xBC6162D5069fED333E4E08DAc4c8686f654Da0ba](https://rinkeby.etherscan.io/address/0xBC6162D5069fED333E4E08DAc4c8686f654Da0ba) Gethereum Contract (Mainnet): [0x6665b844bf69AF051446562D6A1f61f0861d5DDE](https://etherscan.io/address/0x6665b844bf69AF051446562D6A1f61f0861d5DDE)
eb1c211769f1a8a1d3422358e26ba1aa4971a40f
[ "JavaScript", "Markdown" ]
3
JavaScript
wafflemakr/gethereum
c383a52fd31437128a439bee2c5ad66f83bebe1f
c855bd8bfbef55ad25be8b6631540d3a07496b36
refs/heads/main
<repo_name>wasimiqbal1/Flutter<file_sep>/firstapp_wasim/android/app/src/main/kotlin/com/example/firstapp_wasim/MainActivity.kt package com.example.firstapp_wasim import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
a32b2964faf22d76ae62dd711ccd1d4f43d577d4
[ "Kotlin" ]
1
Kotlin
wasimiqbal1/Flutter
ea9f103209e4c3973db55d1e6e27d06c6e7c7c51
f0107e454d9ee20be52cdfca67b77a3ef4f8715d
refs/heads/master
<file_sep>import java.applet.Applet; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.Random; /** * Created by <NAME> on 13/01/2015. * The Asteroid.java is the game itself */ public class Asteroids extends Applet implements Runnable, KeyListener { //the main thread becames the game loop Thread gameLoop; //use this as a double buffer BufferedImage backbuffer; //the main drawing object for back buffer Graphics2D g2d; //toggle for drawing bounding boxes boolean showBounds = false; //create the asteroid array int ASTEROIDS = 20; Asteroid[] ast = new Asteroid[ASTEROIDS]; //create the bullet array int BULLETS = 10; Bullet[] bullet = new Bullet[BULLETS]; int currentBullet = 0; //the player's ship Ship ship = new Ship(); //create the identity transform(0,0) AffineTransform identity = new AffineTransform(); //create a random number generator Random rand = new Random(); //applet init event public void init() { //create the back buffer for smooth graphics backbuffer = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB); g2d = backbuffer.createGraphics(); //set up the ship ship.setX(320); ship.setY(240); //set up the bullets for (int n = 0; n < BULLETS; n++) { bullet[n] = new Bullet(); } //create the asteroids for (int n = 0; n < ASTEROIDS; n++) { ast[n] = new Asteroid(); ast[n].setRotationVelocity(rand.nextInt(3) + 1); ast[n].setX((double) rand.nextInt(600) + 20); ast[n].setY((double) rand.nextInt(440) + 20); ast[n].setMoveAngle((double) rand.nextInt(360)); double ang = ast[n].getMoveAngle() - 90; ast[n].setVelX(calcAngleMoveX(ang)); ast[n].setVelY(calcAngleMoveY(ang)); } //start the user input listener addKeyListener(this); } //strub method public double calcAngleMoveY(double ang) { return 0; } //strub method public double calcAngleMoveX(double ang) { return 0; } //applet update event to redraw the screen public void update(Graphics g){ //start off transforms at identity g2d.setTransform(identity); //erase the background g2d.setPaint(Color.black); g2d.fillRect(0,0,getSize().width, getSize().height); //print same status information g2d.setColor(Color.white); g2d.drawString("Ship: " + Math.round(ship.getX())+ "," + Math.round(ship.getY()), 5, 10); g2d.drawString("Move angle: " + Math.round(ship.getMoveAngle())+90, 5, 25); g2d.drawString("{{ ", 5, 40); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void run() { } } <file_sep>import java.awt.Shape; /** * Created by <NAME> on 11/01/2015. * */ public class BaseVectorShape { private Shape shape; private boolean alive; private double x, y; private double velX, velY; private double moveAngle, faceAngle; //accessor methods public Shape getShape(){return shape;} public boolean isAlive(){return alive;} public double getX(){return x;} public double getY(){return y;} public double getVelX(){return velX;} public double getVelY(){return velY;} public double getMoveAngle(){return moveAngle;} public double getFaceAngle(){return faceAngle;} //mutator and helpers public void setShape(Shape shape){this.shape = shape;} public void setAlive(boolean alive){this.alive = alive;} public void setX(double x){this.x = x;} public void incX(double i){this.x += i;} public void setY(double y){this.y = y;} public void incY(double i){this.y += i;} public void setVelX(double velX){this.velX = velX;} public void incVelX(double i){this.velX += i;} public void setVelY(double velY){this.velY = velY;} public void incVelY(double i){this.velY += i;} public void setMoveAngle(double angle){this.moveAngle = angle;} public void incMoveAngle(double i){this.moveAngle += i;} public void setFaceAngle(double angle){this.faceAngle = angle;} public void incFaceAngle(double i){this.faceAngle += i;} //default constructor BaseVectorShape(){ setShape(null); setAlive(false); setX(0.0); setY(0.0); setVelX(0.0); setVelY(0.0); setMoveAngle(0.0); setFaceAngle(0.0); } }
d097a9b9dc012e2064c7f6b33e040038026c9a3c
[ "Java" ]
2
Java
juanramonestrada/Asteroids
47e8c96d96e7ad65126a52930a48c61e6d84beac
c31013d67d3715f1547620f7920d384a6995cc9f
refs/heads/master
<repo_name>Jackson1603/2020jjvc<file_sep>/api.php <?php ////// error_reporting(0); date_default_timezone_set('Asia/Jakarta'); if ($_SERVER['REQUEST_METHOD'] == "POST") { extract($_POST); } elseif ($_SERVER['REQUEST_METHOD'] == "GET") { extract($_GET); } function GetStr($string, $start, $end) { $str = explode($start, $string); $str = explode($end, $str[1]); return $str[0]; } $separa = explode("|", $lista); $cc = $separa[0]; $mes = $separa[1]; $ano = $separa[2]; $cvv = $separa[3]; function value($str,$find_start,$find_end) { $start = @strpos($str,$find_start); if ($start === false) { return ""; } $length = strlen($find_start); $end = strpos(substr($str,$start +$length),$find_end); return trim(substr($str,$start +$length,$end)); } function mod($dividendo,$divisor) { return round($dividendo - (floor($dividendo/$divisor)*$divisor)); } //put you sk_live keys here $skeys = array( 1 => '<KEY>', 2 => '<KEY>', ); $skey = array_rand($skeys); $sk = $skeys[$skey]; #=====================================================================================================# $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/customers'); ////To generate customer id curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERPWD, $sk. ':' . ''); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'content-type: application/x-www-form-urlencoded', )); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_POSTFIELDS, 'name=Red Penguin'); $f = curl_exec($ch); $info = curl_getinfo($ch); $time = $info['total_time']; $httpCode = $info['http_code']; $time = substr($time, 0, 4); $id = trim(strip_tags(getstr($f,'"id": "','"'))); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/setup_intents'); ////To generate payment token [It wont charge] curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERPWD, $sk. ':' . ''); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'content-type: application/x-www-form-urlencoded', )); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_POSTFIELDS, 'payment_method_data[type]=card&customer='.$id.'&confirm=true&payment_method_data[card][number]='.$cc.'&payment_method_data[card][exp_month]='.$mes.'&payment_method_data[card][exp_year]='.$ano.'&payment_method_data[card][cvc]='.$cvv.''); $result = curl_exec($ch); $info = curl_getinfo($ch); $time = $info['total_time']; $httpCode = $info['http_code']; $time = substr($time, 0, 4); $c = json_decode(curl_exec($ch), true); curl_close($ch); $pam = trim(strip_tags(getstr($result,'"payment_method": "','"'))); $cvv = trim(strip_tags(getstr($result,'"cvc_check": "','"'))); if ($c["status"] == "succeeded") { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/customers/'.$id.''); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_USERPWD, $k . ':' . ''); $result = curl_exec($ch); curl_close($ch); // $pm = $c["payment_method"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_methods/'.$pam.'/attach'); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERPWD, $sk. ':' . ''); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'content-type: application/x-www-form-urlencoded', )); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_POSTFIELDS, 'customer='.$id.''); $result = curl_exec($ch); $attachment_to_her = json_decode(curl_exec($ch), true); curl_close($ch); $attachment_to_her; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/charges'); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERPWD, $sk. ':' . ''); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'content-type: application/x-www-form-urlencoded', )); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); curl_setopt($ch, CURLOPT_POSTFIELDS, '&amount=10000&currency=usd&customer='.$id.''); $result = curl_exec($ch); if (!isset($attachment_to_her["error"]) && isset($attachment_to_her["id"]) && $attachment_to_her["card"]["checks"]["cvc_check"] == "pass") { echo '<font size=2 color="white"><font class="badge badge-success">Approved </i></font> <font class="badge badge-primary"> '.$lista.' </i></font> <font size=2 color="green"> <font class="badge badge-success"> Approved [✓CVV MATCHED✓] @GodHacker_SC</i></font><br>'; } else { echo '<font size=2 color="red"><font class="badge badge-danger">Declined †</i></font> <font class="badge badge-primary"> '.$lista.' </i></font> <font size=2 color="red"> <font class="badge badge-light"> Reprovada [x CVV MISSMATCH x] @GodHacker_SC</i></font> </i></font><br>'; } } elseif(strpos($result, '"cvc_check": "pass"')){ echo '<font size=2 color="white"><font class="badge badge-danger">Declined </i></font> <font class="badge badge-primary"> '.$lista.' </i></font> <font size=2 color="green"> <font class="badge badge-secondary"> [CVV Matched] @GodHacker_SC </i></font> <font class="badge badge-danger"> Additional Response: [' . $c["error"]["decline_code"] . '] </i></font> <br>'; } elseif(strpos($result, 'security code is incorrect')){ echo '<font size=2 color="white"><font class="badge badge-success">Approved </i></font> <font class="badge badge-primary"> '.$lista.' </i></font> <font size=2 color="green"> <font class="badge badge-secondary"> [✓CCN LIVE/CVV INCORECTO✓] </i></font> </i></font> <br>'; } elseif (isset($c["error"])) { echo '<font size=2 color="white"><font class="badge badge-danger">Declined </i></font> <font class="badge badge-primary"> '.$lista.' </i></font> <font size=2 color="green"> <font class="badge badge-danger"> ' . $c["error"]["message"] . ' ' . $c["error"]["decline_code"] . ' </i></font></span><br>'; } else { echo '<font size=2 color="white"><font class="badge badge-danger">Declined </i></font> <font class="badge badge-primary"> '.$lista.' </i></font><font size=2 color="red"> <font class="badge badge-warning">ERROR EN LA GATE CONTACTE A @GodHacker_SC </i></font><br>'; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/customers/'.$id.''); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_USERPWD, $sk . ':' . ''); curl_exec($ch); curl_close($ch); // sleep(5)
4d50f892321ff0978fe2ab71d5e32512b420dfe6
[ "PHP" ]
1
PHP
Jackson1603/2020jjvc
716d4b70e0e07d340741df8fe5baa672fae2c707
eb1fd9e48ddb88c045001d4299ab39bcc2610832
refs/heads/main
<file_sep>#' Hardy Weinbergy Equilibrium Function #' #' This is the main function for the HWE analysis. #' @param Tab data frame of genotype files post processing. #' @note This function is for internal BIGDAWG use only. HWE <- function(Tab) { HWE.out <- list() All.ColNames <- colnames(Tab) loci <- as.list(unique(All.ColNames[3:length(All.ColNames)])) nloci <- length(loci) #HWE Controls / Group 0 genos.sub <- Tab[which(Tab[,2]==0),3:ncol(Tab)] HWE.out[["controls"]] <- HWE.ChiSq(genos.sub,loci,nloci) #HWE Cases / Group 1 genos.sub <- Tab[which(Tab[,2]==1),3:ncol(Tab)] HWE.out[["cases"]] <- HWE.ChiSq(genos.sub,loci,nloci) return(HWE.out) } <file_sep>#' DRB345 Column Processing #' #' Separates DRB345 column pair into separate columns for each locus #' @param Tab Data frame of sampleIDs, phenotypes, and genotypes #' @note This function is for internal BIGDAWG use only. DRB345.parser <- function(Tab) { #Tab Dataset Data-frame getCol <- grep("DRB345",colnames(Tab)) df <- matrix(data="^",nrow=nrow(Tab),ncol=6) colnames(df) <- c("DRB3","DRB3.1","DRB4","DRB4.1","DRB5","DRB5.1") tmp.1 <- sapply(Tab[,getCol[1]],FUN=GetField,Res=1) ; tmp.2 <- sapply(Tab[,getCol[2]],FUN=GetField,Res=1) tmp <- list() # DRB3 tmp[[1]] <- unlist(grep("DRB3",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB3",Tab[,getCol[2]])) df[tmp[[1]],1] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],2] <- Tab[tmp[[2]],getCol[2]] df[setdiff(1:nrow(df),tmp[[1]]),1] <- "DRB3*^" ; df[setdiff(1:nrow(df),tmp[[2]]),2] <- "DRB3*^" df[which(tmp.1=="00"),1] <- paste("DRB3*",Tab[which(tmp.1=="00"),getCol[1]],sep="") df[which(tmp.2=="00"),2] <- paste("DRB3*",Tab[which(tmp.2=="00"),getCol[2]],sep="") tmp <- list() # DRB4 tmp[[1]] <- unlist(grep("DRB4",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB4",Tab[,getCol[2]])) df[tmp[[1]],3] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],4] <- Tab[tmp[[2]],getCol[2]] df[setdiff(1:nrow(df),tmp[[1]]),3] <- "DRB4*^" ; df[setdiff(1:nrow(df),tmp[[2]]),4] <- "DRB4*^" df[which(tmp.1=="00"),3] <- paste("DRB4*",Tab[which(tmp.1=="00"),getCol[1]],sep="") df[which(tmp.2=="00"),4] <- paste("DRB4*",Tab[which(tmp.2=="00"),getCol[2]],sep="") tmp <- list() # DRB5 tmp[[1]] <- unlist(grep("DRB5",Tab[,getCol[1]])) ; tmp[[2]] <- unlist(grep("DRB5",Tab[,getCol[2]])) df[tmp[[1]],5] <- Tab[tmp[[1]],getCol[1]] ; df[tmp[[2]],6] <- Tab[tmp[[2]],getCol[2]] df[setdiff(1:nrow(df),tmp[[1]]),5] <- "DRB5*^" ; df[setdiff(1:nrow(df),tmp[[2]]),6] <- "DRB5*^" df[which(tmp.1=="00"),5] <- paste("DRB5*",Tab[which(tmp.1=="00"),getCol[1]],sep="") df[which(tmp.2=="00"),6] <- paste("DRB5*",Tab[which(tmp.2=="00"),getCol[2]],sep="") # NA's df[is.na(Tab[,getCol[1]]),] <- NA ; df[is.na(Tab[,getCol[2]]),] <- NA Tab.sub <- Tab[,-getCol] Tab <- cbind(Tab.sub,df) return(Tab) } #' DRB345 haplotype zygosity wrapper #' #' Checks DR haplotypes for correct zygosity and flags unanticipated haplotypes #' @param Genotype Row of data set data frame following DRB345 parsing #' @param Loci.DR DRBx Loci of interest to test for consistency #' @note This function is for internal use only. DRB345.Check.Wrapper <- function(Genotype,Loci.DR) { # Set non-DRB1 Loci Loci.DR <- Loci.DR[-grep("DRB1",Loci.DR)] # Substitute ^ for 00:00 Genotype[] <- sapply(Genotype,as.character) if( sum(grepl("\\^",Genotype)) > 0 ) { Genotype[] <- gsub("\\^","00:00",Genotype) ; Fill.Flag <- T } else { Fill.Flag <- F } # Apply Function to each DRBx Locus tmp <- lapply(Loci.DR,FUN=DRB345.Check.Zygosity,Genotype=Genotype) tmp.calls <- lapply( seq(length(tmp)), FUN = function(i) cbind(tmp[[i]]['Locus_1'], tmp[[i]]['Locus_2']) ) Genotype[,!grepl("DRB1",colnames(Genotype))] <- do.call(cbind, tmp.calls) if( Fill.Flag ) { Genotype[] <- gsub("00:00","^",Genotype) } DR.HapFlag <- unlist(lapply(tmp,'[','Flag')) DR.HapFlag <-paste(DR.HapFlag[which(DR.HapFlag!="")],collapse=",") Genotype <- cbind(Genotype,DR.HapFlag) return(Genotype) } #' DRB345 haplotype zygosity checker single locus #' #' Checks DR haplotypes for correct zygosity and flags unanticipated haplotypes for a single DRBx #' @param Locus Locus of interest to test for consistency #' @param Genotype Row of data set data frame following DRB345 parsing #' @note This function is for internal use only. DRB345.Check.Zygosity <- function(Locus,Genotype) { # Remove Abs Strings Genotype <- Filler(Genotype,Type="Remove") ; Genotype <- Genotype[which(Genotype!="")] ; Genotype <- Genotype[which(Genotype!="")] DR.out <- data.frame(Locus_1=character(), Locus_2=character(), DR.HapFlag=character(), stringsAsFactors=F) Abs <- paste(Locus,"*00:00",sep="") DR.Locus <- gsub("HLA-","",Locus) ; DR.Calls <- gsub("HLA-","",Genotype) DR.Calls <- sapply(DR.Calls,FUN=GetField,Res=1) # get 1 Field Resolution for Genotype Calls names(DR.Calls) <- NULL ; Flag <- NULL #DRB1 - get expected DRB3/4/5 genotypes DR345.Exp.Calls <- DRB345.Exp(DR.Calls[grep("DRB1",DR.Calls)]) #DRB345 Check getDRB345 <- grep(DR.Locus,DR.Calls) ; DR.obs <- length(getDRB345) ; DR.exp <- sum(grepl(DR.Locus,DR345.Exp.Calls)) # Assign Genotypes if( DR.obs != DR.exp ) { # Inconsistent Genotype Possibilities if ( DR.obs==0 && DR.exp>=1 ) { # Missing Allele DR.out[1, 'Locus_1'] <- Abs ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- paste(Locus,"_M",sep="") } else if ( DR.obs >=1 && DR.exp==0 ) { # Extra Allele DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- paste(Locus,"_P",sep="") } else if( DR.obs==1 && DR.exp==2 ) { # Presumed Homozygote Missing Allele DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Flag'] <- "" } else if( DR.obs==2 && DR.exp==1 ) { if( Genotype[getDRB345[1]] == Genotype[getDRB345[2]] ) { # Extra Allele ... False Homozygote Assumption DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs ; DR.out[1, 'Flag'] <- "" } else { # Extra Allele Present DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <-Genotype[getDRB345[2]] ; DR.out[1, 'Flag'] <- paste(Locus,"_P",sep="") } } } else { DR.out[1, 'Flag'] <- "" # Consistent Genotype if( DR.obs==0 ) { DR.out[1, 'Locus_1'] <-Abs ; DR.out[1, 'Locus_2'] <- Abs } else if( DR.obs==1 ) { DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Abs } else if ( DR.obs==2 ) { DR.out[1, 'Locus_1'] <- Genotype[getDRB345[1]] ; DR.out[1, 'Locus_2'] <- Genotype[getDRB345[2]] } } # Return Result return(DR.out) } #' DRB345 Expected #' #' Checks DRB1 Genotype and Returns Expected DR345 Loci #' @param DRB1.Genotype DRB1 Subject Genotypes #' @note This function is for internal use only. DRB345.Exp <- function(DRB1.Genotype) { #Checks for and fixes certain DRB345 errors that are consistent with known DR haplotypes Rules <- list("DRB1*01"="","DRB1*10"="","DRB1*08"="", "DRB1*03"="DRB3","DRB1*11"="DRB3","DRB1*12"="DRB3","DRB1*13"="DRB3","DRB1*14"="DRB3", "DRB1*04"="DRB4","DRB1*07"="DRB4","DRB1*09"="DRB4", "DRB1*15"="DRB5","DRB1*16"="DRB5") DRB1.Genotype <- gsub("HLA-","",DRB1.Genotype) DRB1.Genotype <- sapply(DRB1.Genotype,FUN=GetField,Res=1) # Allele 1 DRB1.1 <- DRB1.Genotype[1] DR.Gtype <- as.character(Rules[DRB1.1]) # Allele 2 if(length(DRB1.Genotype)==1) { #Consider Homozygote DRB1.2 <- DRB1.Genotype[1] } else { DRB1.2 <- DRB1.Genotype[2] } DR.Gtype <- c(DR.Gtype,as.character(Rules[DRB1.2])) DR.Gtype <- DR.Gtype[which(DR.Gtype!="")] if(length(DR.Gtype)>0) { DR.Gtype <- paste("HLA-",DR.Gtype,sep="") } return(DR.Gtype) } <file_sep>#' Alignment Filter #' #' Filter Protein Exon Alignment File for Specific Alleles. #' @param Align Protein Alignment Object. #' @param Alleles to be pulled. #' @param Locus Locus to be filtered against. #' @note This function is for internal BIGDAWG use only. AlignmentFilter <- function(Align, Alleles, Locus) { getCols <- c(match(c("Trimmed","Unknowns","NullPositions"), colnames(Align)), grep("Pos\\.",colnames(Align))) getRows <- Align[,"Trimmed"] %in% Alleles Align.sub <- Align[getRows,getCols] Align.sub <- unique(Align.sub) if(!is.null(nrow(Align.sub))) { Alleles.S <- names(which(table(Align.sub[,'Trimmed'])==1)) Alleles.M <- names(which(table(Align.sub[,'Trimmed'])>1)) # Removing Duplicates at 2-Field Level if( length(Alleles.M > 0 ) ) { Align.tmp <- list() for( m in 1:length(Alleles.M) ) { Allele <- Alleles.M[m] Alignsub.Grp <- Align.sub[which(Align.sub[,"Trimmed"]==Allele),] Unknowns.Grp <- which(Alignsub.Grp[,'Unknowns']==min(Alignsub.Grp[,'Unknowns'])) if(length(Unknowns.Grp)>1) { Unknowns.Grp <- Unknowns.Grp[1] } Align.tmp[[Allele]] <- Alignsub.Grp[Unknowns.Grp,] } Align.tmp <- do.call(rbind,Align.tmp) if( length(Alleles.S) > 0 ) { AlignMatrix <- rbind(Align.tmp, Align.sub[which(Align.sub[,'Trimmed'] %in% Alleles.S==T),,drop=F]) } else { AlignMatrix <- Align.tmp } } else { AlignMatrix <- Align.sub } AlignMatrix <- cbind(rep(Locus,nrow(AlignMatrix)),AlignMatrix) rownames(AlignMatrix) <- NULL colnames(AlignMatrix)[1] <- "Locus" colnames(AlignMatrix)[which(colnames(AlignMatrix)=="Trimmed")] <- "Allele.2D" AlignMatrix <- AlignMatrix[ order(AlignMatrix[,'Allele.2D']), ] } else { AlignMatrix <- cbind(rep(Locus,nrow(Align.sub)),Align.sub) rownames(AlignMatrix) <- NULL colnames(AlignMatrix)[1] <- "Locus" colnames(AlignMatrix)[which(colnames(AlignMatrix)=="Trimmed")] <- "Allele.2D" AlignMatrix <- AlignMatrix[ order(AlignMatrix[,'Allele.2D']), ] } return(AlignMatrix) } #' Amino Acid Contingency Table Build #' #' Build Contingency Tables for Amino Acid Analysis. #' @param x Filtered alignmnet list element. #' @param y Phenotype groupings. #' @note This function is for internal BIGDAWG use only. AAtable.builder <- function(x,y) { #x = list element for filtered alignment (TabAA.list) #y = HLA_grp (case vs control) # Create count Grp 0 v Grp 1 (Control v Case) x[,2] <- gsub(" ","Null",x[,2]) x[,2] <- gsub("\\*","Unknown",x[,2]) x[,2] <- gsub("\\.","InDel",x[,2]) Residues <- unique(x[,2]) AminoAcid.df <- mat.or.vec(nr=length(Residues),2) colnames(AminoAcid.df) <- c("Group.0", "Group.1") rownames(AminoAcid.df) <- Residues y[,2:3] <- apply(y[,2:3],MARGIN=c(1,2),GetField,Res=2) # Grp 0 (Control) Grp0 <- y[which(y[,'grp']==0),] Grp0cnt <- table(c(x[match(Grp0[,2],x[,1]),2], x[match(Grp0[,3],x[,1]),2])) PutRange <- match(rownames(AminoAcid.df),names(Grp0cnt)) AminoAcid.df[,'Group.0'] <- Grp0cnt[PutRange] # Grp 1 (Case) Grp1 <- y[which(y[,'grp']==1),] Grp1cnt <- table(c(x[match(Grp1[,2],x[,1]),2], x[match(Grp1[,3],x[,1]),2])) PutRange <- match(rownames(AminoAcid.df),names(Grp1cnt)) AminoAcid.df[,'Group.1'] <- Grp1cnt[PutRange] AminoAcid.df[is.na(AminoAcid.df)] <- 0 # drop unknowns rmRow <- which(row.names(AminoAcid.df)=="Unknown") if( length(rmRow) > 0 ) { AminoAcid.df <- AminoAcid.df[-rmRow,,drop=F] } return(AminoAcid.df) } #' Contingency Table Check #' #' Checks amino acid contingency table data frame to ensure required variation exists. #' @param x contingency table. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test. #' @note This function is for internal BIGDAWG use only. AA.df.check <- function(x,Strict.Bin) { # Returns true if insufficient variations exists # RunChiSq Flag is true is sufficient variant exists if( nrow(x)<2 ) { return(FALSE) } else if (Strict.Bin) { return(!(RunChiSq(x)$Flag)) } else { return(!(RunChiSq_c(x)$Flag)) } } #' Contingency Table Amino Acid ChiSq Testing #' #' Runs ChiSq test on amino acid contingency table data frames. #' @param x contingency table. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test. #' @note This function is for internal BIGDAWG use only. AA.df.cs <- function(x,Strict.Bin) { # RunChiSq on data frame if( nrow(x) < 2 ) { tmp.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") row.names(tmp.chisq) <- "X-squared" chisq.out <- list(Matrix = x, Binned = NA, Test = tmp.chisq, Flag = FALSE) return( chisq.out ) } else if (Strict.Bin) { return( RunChiSq(x) ) } else { return( RunChiSq_c(x) ) } } #' Create Empty Table #' #' Creates matrix of NA for no result tables. #' @param Locus Locus being analyzed. #' @param Names Column names for final matrix. #' @param nr Number of rows. #' @note This function is for internal BIGDAWG use only. Create.Null.Table <- function(Locus,Names,nr) { nc <- length(Names) Data <- c( Locus,rep(NA,nc-1) ) tmp <- matrix(Data,nrow=nr,ncol=nc) colnames(tmp) <- Names rownames(tmp) <- NULL return(tmp) } #' Filter Exon Specific Alignment Sections #' #' Filters the ExonPtnAlign object by locus and exon. #' @param Locus Locus being analyzed. #' @param Exon Exon being analyzed. #' @param EPL.Locus ExonPtnAlign object filtered by Locus #' @param RefExons Reference Exon Table #' @param E.Ptn.Starts Exon Protein Overlay Map #' @note This function is for internal BIGDAWG use only. Exon.Filter <- function(Locus,Exon,EPL.Locus,RefExons,E.Ptn.Starts) { # Get Reference Protoen Start Ref.Start <- as.numeric(RefExons[RefExons[,'Locus']==Locus,'Reference.Start']) # Define 5'/3' Boundary Positions E.Start <- as.numeric(E.Ptn.Starts[which(E.Ptn.Starts[,'Exon']==Exon),'Start']) E.Stop <- as.numeric(E.Ptn.Starts[which(E.Ptn.Starts[,'Exon']==Exon),'Stop']) E.Length <- E.Stop - E.Start + 1 # Ensure Number Shift Due to lack of Position 0 if( E.Start >= abs(Ref.Start) ) { E.Start.Pos <- E.Start + Ref.Start } else { E.Start.Pos <- E.Start + Ref.Start - 1 } E.Stop.Pos <- E.Start.Pos + E.Length - 1 if( E.Start.Pos < 0 && E.Stop.Pos > 0 ) { E.Stop.Pos <- E.Start.Pos + E.Length } # Find Exon 5' Boundary Position in ExonPtnAlign Object E.Start.Pos <- paste0("Pos.",E.Start.Pos) getStart <- match(E.Start.Pos,colnames(EPL.Locus)) # Find Exon 3' Boundary Position E.Stop.Pos <- paste0("Pos.",E.Stop.Pos) getStop <- match(E.Stop.Pos,colnames(EPL.Locus)) testStop <- grep(paste0(E.Stop.Pos,"."),colnames(EPL.Locus),fixed=TRUE) if( length(testStop)>0 ) { getStop <- max(testStop) } # Define Amino Acid Range to Carve Out getOverlap <- seq(getStart,getStop) # Restructure Final ExnPtnAlign Object getEndCol <- seq(ncol(EPL.Locus)-3,ncol(EPL.Locus)) EPL.Locus.Exon <- EPL.Locus[,c(1:4,getOverlap,getEndCol),drop=F] return(EPL.Locus.Exon) } #' Condensing Exon Specific Alignments to Single Dataframe #' #' Combines multiple Exon Specific Alignments into a single Alignment object #' @param EPL.Exon Exon-Locus Specific Amino Acid Alignment. #' @note This function is for internal BIGDAWG use only. Condense.EPL <- function(EPL.Exon) { df.1 <- EPL.Exon[[1]][,1:4] getCol <- ncol(EPL.Exon[[1]]) df.2 <- EPL.Exon[[1]][,seq(getCol-3,getCol)] df <- list() for( i in 1:length(EPL.Exon) ) { totalCol <- ncol(EPL.Exon[[i]]) - 4 df[[i]] <- EPL.Exon[[i]][,5:totalCol,drop=F] } df <- do.call(cbind,df) df.out <- cbind(df.1,df,df.2) return(df.out) } <file_sep>#' Case-Control Odds ratio calculation and graphing #' #' cci function port epicalc version 2.15.1.0 (<NAME>, 2012) #' @param caseexp Number of cases exposed #' @param controlex Number of controls exposed #' @param casenonex Number of cases not exosed #' @param controlnonex Number of controls not exposed #' @param cctable A 2-by-2 table. If specified, will supercede the outcome and exposure variables #' @param graph If TRUE (default), produces an odds ratio plot #' @param design Specification for graph; can be "case control","case-control", "cohort" or "prospective" #' @param main main title of the graph #' @param xlab label on X axis #' @param ylab label on Y axis #' @param xaxis two categories of exposure in graph #' @param yaxis two categories of outcome in graph #' @param alpha level of significance #' @param fisher.or whether odds ratio should be computed by the exact method #' @param exact.ci.or whether confidence limit of the odds ratio should be computed by the exact method #' @param decimal number of decimal places displayed #' @note This function is for internal BIGDAWG use only. cci <- function (caseexp, controlex, casenonex, controlnonex, cctable = NULL, graph = FALSE, design = "cohort", main, xlab, ylab, xaxis, yaxis, alpha = 0.05, fisher.or = TRUE, exact.ci.or = TRUE, decimal = 2) { if (is.null(cctable)) { frame <- cbind(Outcome <- c(1, 0, 1, 0), Exposure <- c(1, 1, 0, 0), Freq <- c(caseexp, controlex, casenonex, controlnonex)) Exposure <- factor(Exposure) expgrouplab <- c("Non-exposed", "Exposed") levels(Exposure) <- expgrouplab Outcome <- factor(Outcome) outcomelab <- c("Negative", "Positive") levels(Outcome) <- outcomelab table1 <- xtabs(Freq ~ Outcome + Exposure, data = frame) } else { table1 <- as.table(get("cctable")) } fisher <- fisher.test(table1) caseexp <- table1[2, 2] controlex <- table1[1, 2] casenonex <- table1[2, 1] controlnonex <- table1[1, 1] se.ln.or <- sqrt(1/caseexp + 1/controlex + 1/casenonex + 1/controlnonex) if (!fisher.or) { or <- (caseexp * controlnonex) / (casenonex * controlex) #p.value <- chisq.test(table1, correct = FALSE)$p.value p.value <- chisq.test(table1,correct=TRUE)$p.value } else { or <- fisher$estimate p.value <- fisher$p.value } if (exact.ci.or) { ci.or <- as.numeric(fisher$conf.int) } else { #ci.or <- or * exp(c(-1, 1) * qnorm(1 - alpha/2) * se.ln.or) ci.or <- c( exp(log(or) - ( qnorm(1 - alpha/2) * se.ln.or) ), exp(log(or) + ( qnorm(1 - alpha/2) * se.ln.or) ) ) } if (graph == TRUE) { caseexp <- table1[2, 2] controlex <- table1[1, 2] casenonex <- table1[2, 1] controlnonex <- table1[1, 1] if (!any(c(caseexp, controlex, casenonex, controlnonex) < 5)) { if (design == "prospective" || design == "cohort" || design == "cross-sectional") { if (missing(main)) main <- "Odds ratio from prospective/X-sectional study" if (missing(xlab)) xlab <- "" if (missing(ylab)) ylab <- paste("Odds of being", ifelse(missing(yaxis), "a case", yaxis[2])) if (missing(xaxis)) xaxis <- c("non-exposed", "exposed") axis(1, at = c(0, 1), labels = xaxis) } else { if (missing(main)) main <- "Odds ratio from case control study" if (missing(ylab)) ylab <- "Outcome category" if (missing(xlab)) xlab <- "" if (missing(yaxis)) yaxis <- c("Control", "Case") axis(2, at = c(0, 1), labels = yaxis, las = 2) mtext(paste("Odds of ", ifelse(xlab == "", "being exposed", paste("exposure being", xaxis[2]))), side = 1, line = ifelse(xlab == "", 2.5, 1.8)) } title(main = main, xlab = xlab, ylab = ylab) } } if (!fisher.or) { results <- list(or.method = "Asymptotic", or = or, se.ln.or = se.ln.or, alpha = alpha, exact.ci.or = exact.ci.or, ci.or = ci.or, table = table1, decimal = decimal, p.value = p.value) } else { results <- list(or.method = "Fisher's", or = or, alpha = alpha, exact.ci.or = exact.ci.or, ci.or = ci.or, table = table1, decimal = decimal, p.value = p.value) } class(results) <- c("cci", "cc") return(results) } #' Creation of a 2x2 table using the indicated orientation. #' #' make2x2 function port epicalc version 2.15.1.0 (<NAME>, 2012) #' @param caseexp Number of cases exposed #' @param controlex Number of controls exposed #' @param casenonex Number of cases not exosed #' @param controlnonex Number of controls not exposed #' @note This function is for internal BIGDAWG use only. make2x2 <- function (caseexp, controlex, casenonex, controlnonex) { table1 <- c(controlnonex, casenonex, controlex, caseexp) dim(table1) <- c(2, 2) rownames(table1) <- c("Non-diseased", "Diseased") colnames(table1) <- c("Non-exposed", "Exposed") attr(attr(table1, "dimnames"), "names") <- c("Outcome", "Exposure") table1 } #' Table Maker #' #' Table construction of per haplotype for odds ratio, confidence intervals, and pvalues #' @param x Contingency table with binned rare cells. #' @note This function is for internal BIGDAWG use only. TableMaker <- function(x) { grp1_sum <- sum(x[,'Group.1']) grp0_sum <- sum(x[,'Group.0']) grp1_exp <- x[,'Group.1'] grp0_exp <- x[,'Group.0'] grp1_nexp <- grp1_sum - grp1_exp grp0_nexp <- grp0_sum - grp0_exp cclist <- cbind(grp1_exp, grp0_exp, grp1_nexp, grp0_nexp) tmp <- as.data.frame(t(cclist)) names(tmp) <- row.names(x) return(tmp) } #' Case Control Odds Ratio Calculation from Epicalc #' #' Calculates odds ratio and pvalues from 2x2 table #' @param x List of 2x2 matrices for calculation, output of TableMaker. #' @note This function is for internal BIGDAWG use only. cci.pval <- function(x) { tmp <- list() caseEx <- x[1] controlEx <- x[2] caseNonEx <- x[3] controlNonEx <- x[4] table1 <- make2x2(caseEx, controlEx, caseNonEx, controlNonEx) tmp1 <- cci(cctable=table1, design = "case-control") tmp[['OR']] <- round(tmp1$or,digits=2) tmp[['CI.L']] <- round(tmp1$ci.or[1],digits=2) tmp[['CI.U']] <- round(tmp1$ci.or[2],digits=2) tmp[['p.value']] <- format.pval(tmp1$p.value) tmp[['sig']] <- ifelse(tmp1$p.value <= 0.05,"*","NS") return(tmp) } #' Case Control Odds Ratio Calculation from Epicalc list variation #' #' Variation of the cci.pval function #' @param x List of 2x2 matrices to apply the cci.pval function. List output of TableMaker. #' @note This function is for internal BIGDAWG use only. cci.pval.list <- function(x) { tmp <- lapply(x, cci.pval) tmp <- do.call(rbind,tmp) colnames(tmp) <- c("OR","CI.lower","CI.upper","p.value","sig") return(tmp) } #' Strict Chi-squared Contingency Table Test #' #' Calculates chi-squared contingency table tests and bins all rare cells. #' @param x Contingency table. #' @note This function is for internal BIGDAWG use only. RunChiSq <- function(x) { ### get expected values for cells ExpCnts <- chisq.test(as.matrix(x))$expected ## pull out cells that don't need binning, bin remaining #unbinned OK.rows <- as.numeric(which(apply(ExpCnts,min,MARGIN=1)>=5)) if(length(OK.rows)==0) { # All rows have cells with expected less than 5. tmp.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = NA, Binned = NA, Test = tmp.chisq, Flag = FALSE) } else { if(length(OK.rows)>=2) { unbinned <- x[OK.rows,] } else { unbinned <- do.call(cbind,as.list(x[OK.rows,])) rownames(unbinned) <- rownames(x)[OK.rows] } #binned Rare.rows <- as.numeric(which(apply(ExpCnts,min,MARGIN=1)<5)) if(length(Rare.rows)>=2) { binned <- x[Rare.rows,] New.df <- rbind(unbinned,colSums(x[Rare.rows,])) rownames(New.df)[nrow(New.df)] <- "binned" } else { binned <- cbind(NA,NA) colnames(binned) <- c("Group.0","Group.1") New.df <- x } if(nrow(New.df)>1) { # flag if final matrix fails Cochran's rule of thumb (more than 20% of exp cells are less than 5) # True = OK ; False = Not good for Chi Square ExpCnts <- chisq.test(New.df)$expected if(sum(ExpCnts<5)==0){ # all expected are greater than 5 flag <- TRUE } else if( sum(ExpCnts<5)/sum(ExpCnts>=0)<=0.2 && sum(ExpCnts>=1)==length(ExpCnts) ){ # expected counts < 5 are greater than or equal to 20% of cells # all individual counts are >= 1 flag <- TRUE } else { # else flag contingency table # invalid flag <- FALSE } ## chi square test on binned data df.chisq <- chisq.test(New.df) Sig <- if(df.chisq$p.value > 0.05) { "NS" } else { "*" } ## show results of overall chi-square analysis tmp.chisq <- data.frame(cbind(round(df.chisq$statistic,digits=4), df.chisq$parameter, format.pval(df.chisq$p.value), Sig)) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = New.df, Binned = binned, Test = tmp.chisq, Flag = flag) } else { tmp.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = New.df, Binned = binned, Test = tmp.chisq, Flag = FALSE) } } return(chisq.out) } #' Contextual Binning Chi-squared Contingency Table Test #' #' Calculates chi-squared contingency table tests and bins rare cells at 20% capture rate. #' @param x Contingency table. #' @note This function is for internal BIGDAWG use only. RunChiSq_c <- function(x) { ### get expected values for cells ExpCnts <- chisq.test(as.matrix(x))$expected # Order Counts getOrder <- order(ExpCnts[,1],ExpCnts[,2],decreasing=T) ExpCnts <- ExpCnts[getOrder,] x.sub <- x[getOrder,] # Define Rows Safe.cells.rows <- as.numeric(which(apply(ExpCnts,min,MARGIN=1)>=5)) Rare.cells.rows <- as.numeric(which(apply(ExpCnts,min,MARGIN=1)<5)) # Define Flags Check.Rebinned <- FALSE No.Bin <- FALSE if(length(Safe.cells.rows)==0) { # All rows have cells with expected less than 5. tmp.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = NA, Binned = NA, Test = tmp.chisq, Flag = FALSE) } else { ### pull out cells that don't need binning, bin remaining #unbinned if(length(Safe.cells.rows)>=2) { unbinned <- x.sub[Safe.cells.rows,] } else { unbinned <- do.call(cbind,as.list(x.sub[Safe.cells.rows,])) rownames(unbinned) <- rownames(x.sub)[Safe.cells.rows] } unbinned.tmp <- unbinned # Iterate through rows -- adding back rows until threshold exceeds 0.2 (20%) if( length(Rare.cells.rows)>=3 ) { threshold=0 ; i=1 repeat { # Process through adding back rows until threshold exceeds 0.2 (20%) get.putRow <- Rare.cells.rows[seq(1,i)] get.binRow <- Rare.cells.rows[seq(i+1,length(Rare.cells.rows))] if ( length(get.binRow)==1 ) { Stop = i - 1 ; break } unbinned.test <- rbind(unbinned.tmp, x.sub[get.putRow,], rbind(colSums(x.sub[get.binRow,])) ) unbinned.test.cs <- chisq.test(unbinned.test)$expected threshold <- sum(unbinned.test.cs<5)/ length(unbinned.test.cs) if( threshold<=0.2 ) { i = i + 1 } else { Stop = i - 1 ; break } }# End repeat if( Stop>0 ) { # Set up which rows to rescue and bin getRescued <- Rare.cells.rows[1:Stop] putBinned <- Rare.cells.rows[seq(i,length(Rare.cells.rows))] # binning must be more than 1 row if( length(putBinned)==1 ) { putBinned <- c(getRescued[length(getRescued)],putBinned) getResuced <- getRescued[-length(getRescued)] } # Reclaim any rescued rows to unbinned matrix if( length(getRescued) > 1 ) { unbinned <- rbind(unbinned, x.sub[getRescued,]) rownames(unbinned)[getRescued] <- rownames(x.sub)[getRescued] } else { rebin.tmp <- do.call(cbind,as.list(x.sub[getRescued,])) rownames(rebin.tmp) <- rownames(x.sub)[getRescued] unbinned <- rbind(unbinned, rebin.tmp) } # Bin remaining rows binned <- x.sub[putBinned,] rownames(binned) <- rownames(x.sub)[putBinned] Check.Rebinned <- TRUE } else { # Stop == 0 # No rows identified to rescue, bin all rare cell containing rows binned <- x.sub[Rare.cells.rows,] rownames(binned) <- rownames(x.sub)[Rare.cells.rows] } } else if ( length(Rare.cells.rows)==2 ) { # For Rare cells in only 2 rows threshold <- sum(ExpCnts<5) / length(x.sub) if( threshold > 0.2 ) { # must bin both binned <- x.sub[Rare.cells.rows,] rownames(binned) <- rownames(x.sub)[Rare.cells.rows] } else { # no binning required No.Bin <- TRUE } } else { # Rare.cells.rows == 1 # No binning possible No.Bin <- TRUE } # Playing no favorites # Check if rescued cell expected counts overlap binned expected counts if(Check.Rebinned) { # If check.rebinned = T # getRescued = rescued rows ... can be 1 row # putBinned = binned rows ... must be greater than 1 row # Rescued rows expected counts if(length(getRescued)>1) { rescue.expcnts <- apply(ExpCnts[getRescued,],MARGIN=1,paste,collapse=":") } else { rescue.expcnts <- paste(ExpCnts[getRescued,],collapse=":") } # Binned rows expected counts bin.expcnts <- apply(ExpCnts[putBinned,],MARGIN=1,paste,collapse=":") bin.expcnts.rev <- apply(ExpCnts[putBinned,c(2,1)],MARGIN=1,paste,collapse=":") rebin.hits <- unique(c(which((rescue.expcnts %in% bin.expcnts)==T), which((rescue.expcnts %in% bin.expcnts.rev)==T))) if ( length(rebin.hits)>0 ) { rebin.names <- names(rescue.expcnts[rebin.hits]) rebin.rows <- which((row.names(unbinned) %in% rebin.names)==T) binned <- rbind(binned,unbinned[rebin.rows,,drop=F]) unbinned <- unbinned[-rebin.rows,] } } # Create final matrix New.df if ( No.Bin || nrow(unbinned)==0 ) { binned <- cbind(NA,NA) colnames(binned) <- c("Group.0","Group.1") New.df <- x.sub } else { # merge unbinned and column sums of binned New.df <- rbind(unbinned,colSums(binned)) rownames(New.df)[nrow(New.df)] <- "binned" # Reorder binned by row names binned <- binned[order(rownames(binned)),] } # Reorder New.df by row names putOrder <- order(row.names(New.df)) New.df <- New.df[putOrder,] if(nrow(New.df)>1) { ExpCnts <- chisq.test(New.df)$expected # flag if final matrix fails Cochran's rule of thumb (more than 20% of exp cells are less than 5) # True = OK ; False = Not good for Chi Square if(sum(ExpCnts<5)==0){ # all expected are greater than 5 flag <- TRUE } else if( sum(ExpCnts<5)/sum(ExpCnts>=0)<=0.2 && sum(ExpCnts>=1)==length(ExpCnts) ){ # expected counts < 5 are greater than or equal to 20% # all individual counts are >= 1 flag <- TRUE } else { # else flag contingency table flag <- FALSE } ## chi square test on binned data df.chisq <- chisq.test(New.df) Sig <- if(df.chisq$p.value > 0.05) { "NS" } else { "*" } ## show results of overall chi-square analysis tmp.chisq <- data.frame(cbind(round(df.chisq$statistic,digits=4), df.chisq$parameter, format.pval(df.chisq$p.value), Sig)) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = New.df, Binned = binned, Test = tmp.chisq, Flag = flag) } else { flag <- FALSE tmp.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(tmp.chisq) <- c("X.square", "df", "p.value", "sig") chisq.out <- list(Matrix = New.df, Binned = binned, Test = tmp.chisq, Flag = FALSE) } } return(chisq.out) } <file_sep>#' Haplotype Analysis Function for Multicore #' #' This is the workhorse function for the haplotype analysis. #' @param genos.sub The genotype columns of the loci(locus) set being analyzed. #' @param grp Case/Control or Phenotype groupings. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test #' @param Verbose Summary display carryover from main BIGDAWG function #' @note This function is for internal BIGDAWG use only. H.MC <- function(genos.sub,grp,Strict.Bin,Verbose) { loci.sub <- unique(gsub(".1","",colnames(genos.sub),fixed=T)) nloci.sub <- as.numeric(length(loci.sub)) Haplotype <- paste(loci.sub,collapse="~") cat("Estimating Haplotypes ...",Haplotype,"\n") ### estimate haplotypes Tab.out <- haplo.stats::haplo.em(geno=genos.sub,locus.label=loci.sub) ## extract haplotype freqs for cases and controls Subjects <- as.list(seq_len(nrow(genos.sub))) Tab.Haps <- lapply(Subjects,FUN=getHap,HaploEM=Tab.out) Tab.Haps <- cbind(grp,do.call(rbind,Tab.Haps)) colnames(Tab.Haps)[2:3] <-c("Haplotype.1","Haplotype.2") ## Build Contingency Matrix of Counts haps <- sort(unique(c(Tab.Haps[,'Haplotype.1'],Tab.Haps[,'Haplotype.2']))) haps_counts <- mat.or.vec(nr=length(haps),nc=2) rownames(haps_counts) <- haps colnames(haps_counts) <- c('Group.0','Group.1') #Group 0 Tab.Haps.grp0 <- Tab.Haps[which(Tab.Haps[,'grp']==0),c('Haplotype.1','Haplotype.2')] haps_grp0 <- table(Tab.Haps.grp0) haps_counts[match(names(haps_grp0),haps),'Group.0'] <- haps_grp0 #Group 1 Tab.Haps.grp1 <- Tab.Haps[which(Tab.Haps[,'grp']==1),c('Haplotype.1','Haplotype.2')] haps_grp1 <- table(Tab.Haps.grp1) haps_counts[match(names(haps_grp1),haps),'Group.1'] <- haps_grp1 ### get expected values for cells, bin small cells, and run chi square if(Strict.Bin) { Result <- RunChiSq(haps_counts) } else { Result <- RunChiSq_c(haps_counts) } if( !(Result$Flag) ) { haps_binned <- NULL Final_binned <- haps_counts overall.chisq <- NULL ## Convert counts to frequencies haps_freq <- haps_counts haps_freq[,'Group.0'] <- haps_freq[,'Group.0']/(nrow(Tab.Haps.grp0)*2) haps_freq[,'Group.1'] <- haps_freq[,'Group.1']/(nrow(Tab.Haps.grp1)*2) ## make a nice table of ORs, ci, p values ccdat <-TableMaker(haps_counts) ORout <- lapply(ccdat, cci.pval) #OR list ORout <- do.call(rbind,ORout) #OR matrix rmRows <- which(ORout[,'sig']=="NA") if( length(rmRows > 0) ) { ORout <- ORout[-rmRows,,drop=F] } } else { haps_binned <- Result$Binned Final_binned <- Result$Matrix overall.chisq <- Result$Test ## Convert counts to frequencies haps_freq <- haps_counts haps_freq[,'Group.0'] <- haps_freq[,'Group.0']/(nrow(Tab.Haps.grp0)*2) haps_freq[,'Group.1'] <- haps_freq[,'Group.1']/(nrow(Tab.Haps.grp1)*2) ## make a nice table of ORs, ci, p values ccdat <-TableMaker(Final_binned) ORout <- lapply(ccdat, cci.pval) #OR list ORout <- do.call(rbind,ORout) #OR rmRows <- which(ORout[,'sig']=="NA") if( length(rmRows > 0) ) { ORout <- ORout[-rmRows,,drop=F] } } ####################################################### Build Output List #haps_binned - Binned Haplotypes if( is.null(row.names(haps_binned)) ) { names <- "Nothing.binned" } else { names <- rownames(haps_binned) } haps_binned_fix <- cbind(names,haps_binned) colnames(haps_binned_fix) <- c(Haplotype,colnames(haps_binned)) rownames(haps_binned_fix) <- NULL if( sum(grepl("\\^",haps_binned_fix[,Haplotype]))>0 ) { haps_binned_fix[,Haplotype] <- gsub("\\^","Abs",haps_binned_fix[,Haplotype]) } #final_binned - Contingency Table for ChiSq Final_binned_fix <- cbind(rownames(Final_binned),Final_binned) colnames(Final_binned_fix) <- c(Haplotype,colnames(Final_binned)) rownames(Final_binned_fix) <- NULL if( sum(grepl("^",Final_binned_fix[,Haplotype]))>0 ) { Final_binned_fix[,Haplotype] <- gsub("\\^","Abs",Final_binned_fix[,Haplotype]) } #haps_freq - Frequencies haps_freq_fix <- cbind(rownames(haps_freq),haps_freq) colnames(haps_freq_fix) <- c(Haplotype,colnames(haps_freq)) rownames(haps_freq_fix) <- NULL if(sum(grepl("\\^",haps_freq_fix[,Haplotype]))>0) { haps_freq_fix[,Haplotype] <- gsub("\\^","Abs",haps_freq_fix[,Haplotype]) } #ORout - ODDs Ratios ORout_fix <- cbind(rownames(ORout),ORout) colnames(ORout_fix) <- c(Haplotype,colnames(ORout)) rownames(ORout_fix) <- NULL if(sum(grepl("\\^",ORout_fix[,Haplotype]))>0) { ORout_fix[,Haplotype] <- gsub("\\^","Abs",ORout_fix[,Haplotype]) } #Haplotype - Replace Abs symbols if(sum(grepl("\\^",Tab.Haps[,'Haplotype.1'])) + sum(grepl("\\^",Tab.Haps[,'Haplotype.2'])) >0) { Tab.Haps[,'Haplotype.1'] <- gsub("\\^","Abs",Tab.Haps[,'Haplotype.1']) Tab.Haps[,'Haplotype.2'] <- gsub("\\^","Abs",Tab.Haps[,'Haplotype.2']) } colnames(Tab.Haps)[2:3] <- c(paste(Haplotype,".Hap1",sep=""),paste(Haplotype,".Hap2",sep="")) #Overall ChiSq NULL if( is.null(overall.chisq) ) { overall.chisq <- data.frame(rbind(rep("NCalc",4))) colnames(overall.chisq) <- c("X.square", "df", "p.value", "sig") } H.tmp <- list() H.tmp[['Haplotypes']] <- Tab.Haps[,2:3] # table of subject haplotypes H.tmp[['freq']] <- haps_freq_fix # rounded frequencies H.tmp[['binned']] <- haps_binned_fix # binned haplotypes H.tmp[['OR']] <- ORout_fix # odd ratio table H.tmp[['chisq']] <- overall.chisq # chi sq test statistic H.tmp[['table']] <- Final_binned_fix # final table for chi sq #if(Verbose) { # overall.chisq$X.square <- round(as.numeric(levels(overall.chisq$X.square)),digits=5) # print(overall.chisq, row.names=F) # cat("\n") #} return(H.tmp) } <file_sep>#' Check Input Parameters #' #' Check input parameters for invalid entries. #' @param HLA Logical indicating whether data is HLA class I/II genotyping data only. #' @param Loci.Set Input list defining which loci to use for analyses (combinations permitted). #' @param Exon Numeric Exon(s) for targeted amino acid analysis. #' @param All.Pairwise Logical indicating whether all pairwise loci should be analyzed in haplotype analysis. #' @param Trim Logical indicating if HLA alleles should be trimmed to a set resolution. #' @param Res Numeric setting what desired resolution to trim HLA alleles. #' @param EVS.rm Logical indicating if expression variant suffixes should be removed. #' @param Missing Numeric setting allowable missing data for running analysis (may use "ignore"). #' @param Cores.Lim Integer setting the number of cores accessible to BIGDAWG (Windows limit is 1 core). #' @param Return Logical Should analysis results be returned as list. #' @param Output Logical Should analysis results be written to output directory. #' @param Merge.Output Logical Should analysis results be merged into a single file for easy access. #' @param Verbose Logical Should a summary of each analysis be displayed in console. #' @note This function is for internal use only. Check.Params <- function (HLA,Loci.Set,Exon,All.Pairwise,Trim,Res,EVS.rm,Missing,Cores.Lim,Return,Output,Merge.Output,Verbose) { # Logicals: HLA=TRUE, All.Pairwise=FALSE, EVS.rm=FALSE, Trim=FALSE, Return=FALSE, Merge.FALSE, Verbose=TRUE, TRUE, # Numerics: Res=2, Missing=2, Cores.Lim=1L # Untested: Data, Results.Dir, Run.Tests, Loci.Set if( is.na(as.logical(HLA)) ) { Err.Log(FALSE,"P.Error","HLA") ; stop("Analysis Stopped.",call.=FALSE) } if( !missing(Loci.Set) && !is.list(Loci.Set) ) { Err.Log(FALSE,"P.Error","Loci.Set") ; stop("Analysis Stopped.",call.=FALSE) } if( !missing(Exon) && !is.numeric(Exon) ) { Err.Log(FALSE,"P.Error","Exon") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(All.Pairwise) ) { Err.Log(FALSE,"P.Error","All.Pairwise") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(EVS.rm) ) { Err.Log(FALSE,"P.Error","EVS.rm") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(Trim) ) { Err.Log(FALSE,"P.Error","Trim") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(Return) ) { Err.Log(FALSE,"P.Error","Return") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(Merge.Output) ) { Err.Log(FALSE,"P.Error","Merge.Output") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(Verbose) ) { Err.Log(FALSE,"P.Error","Verbose") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(Output) ) { Err.Log(FALSE,"P.Error","Output") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.numeric(Res) ) { Err.Log(FALSE,"P.Error","Res") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.numeric(Cores.Lim) && !is.integer(Cores.Lim) ) { Err.Log(FALSE,"P.Error","Cores.Lim") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.numeric(Missing) ) { if(Missing!="ignore") { Err.Log(FALSE,"P.Error","Missing") ; stop("Analysis Stopped.",call.=FALSE) } } } #' Check Input Parameters for GLS conversion #' #' Check input parameters for invalid entries. #' @param Convert String Direction for conversion. #' @param File.Output String Type of output. #' @param System String Genetic system (HLA or KIR) of the data being converted #' @param HZY.Red Logical Reduction of homozygote genotypes to single allele. #' @param DRB345.Check Logical Check DR haplotypes for consistency and flag unusual haplotypes. #' @param Cores.Lim Integer How many cores can be used. #' @note This function is for internal use only. Check.Params.GLS <- function (Convert,File.Output,System,HZY.Red,DRB345.Check,Cores.Lim) { if( is.na(match(Convert,c("GL2Tab","Tab2GL"))) ) { Err.Log(FALSE,"P.Error","Convert") ; stop("Analysis Stopped.",call.=FALSE) } if( is.na(match(File.Output,c("R","txt","csv","pypop"))) ) { Err.Log(FALSE,"P.Error","File.Output") ; stop("Analysis Stopped.",call.=FALSE) } if( is.na(match(System,c("HLA","KIR"))) ) { Err.Log(FALSE,"P.Error","System") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(HZY.Red) ) { Err.Log(FALSE,"P.Error","HZY.Red") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.logical(DRB345.Check) ) { Err.Log(FALSE,"P.Error","DRB345.Check") ; stop("Analysis Stopped.",call.=FALSE) } if( !is.numeric(Cores.Lim) || !is.integer(Cores.Lim) ) { Err.Log(FALSE,"P.Error","Cores.Lim") ; stop("Analysis Stopped.",call.=FALSE) } } #' Check Cores Parameters #' #' Check cores limitation for OS compatibility #' @param Cores.Lim Integer How many cores can be used. #' @param Output Logical Should analysis results be written to output directory. Check.Cores <- function(Cores.Lim,Output) { if ( Cores.Lim!=1L ) { Cores.Max <- as.integer( floor( parallel::detectCores() * 0.9) ) if(Sys.info()['sysname']=="Windows" && as.numeric(Cores.Lim)>1) { Err.Log(Output,"Windows.Cores") ; stop("Analysis Stopped.",call. = F) } else if( Cores.Lim > Cores.Max ) { Cores <- Cores.Max } else { Cores <- Cores.Lim } } else { Cores <- Cores.Lim } return(Cores) } #' HLA Formatting Check for Amino Acid Analysis #' #' Checks data to see if HLA data is properly formatted . #' @param x All columns of HLA genotyping data. #' @note This function is for internal BIGDAWG use only. CheckHLA <- function(x) { #Return TRUE if properly formatted HLA # temporary reassignment for test x[is.na(x)] <- "00:00" # NA cells x[x=="^"] <- "00:00" # absent cells x[x==""] <- "00:00" # empty cells # test for colon delimiters test <- apply(x,MARGIN=c(1,2),FUN=function(z) length(unlist(strsplit(as.character(z),split=":")))) test <- apply(test,MARGIN=2,FUN=min) Flag <- as.logical(min(test)==2) return(Flag) } #' HLA Loci Legitimacy Check for Amino Acid Analysis #' #' Checks available loci against data to ensure complete overlap. #' @param x Loci available in exon protein list alignment object. #' @param y Unique column names #' @note This function is for internal BIGDAWG use only. CheckLoci <- function(x,y) { #Returns TRUE if absent locus(loci) encountered #x=Loci available in ExonPtnList #y=Loci.Set from data Output <- list() y <- unique(unlist(y)) y <- gsub("HLA-","",y) Flag <- ( !sum(y %in% x) == length(y) ) Output[['Flag']] <- Flag if(Flag) { Output[['Loci']] <- paste(y[!y %in% x],collapse=",") } else { Output[['Loci']] <- NA } return(Output) } #' HLA Allele Legitimacy Check for Amino Acid Analysis #' #' Checks available alleles against data to ensure complete overlap. #' @param x Exon protein list alignment object. #' @param y Genotypes from data file #' @note This function is for internal BIGDAWG use only. CheckAlleles <- function(x,y) { # Returns TRUE if unknown allele(s) encountered # Checks at 2 levels of resolution: Full, 3-Field, 2-Field, 1-Field # Define Loci Loci <- unique( gsub("\\.1|\\.2|\\_1|\\_2","",colnames(y)) ) Output <- list() for(i in Loci ) { # Database Alleles x.locus <- x[[i]][,'Allele'] x.locus[] <- sapply(x.locus, FUN = gsub, pattern="[[:alpha:]]", replacement="") # Current Data Alleles y.locus <- y[,grep(i,colnames(y))] y.locus <- unique(c(y.locus[,1],y.locus[,2])) y.locus[] <- sapply(y.locus, FUN = gsub, pattern="[[:alpha:]]", replacement="") y.locus <- na.omit(y.locus) y.locus <- y.locus[y.locus!="^"] y.locus <- y.locus[y.locus!=""] # Check Each Allele against Database at defined resolution Resolution <- c("Full",3,2,1) ; r = 1 repeat{ Res <- Resolution[r] #cat(r,":",Res,"\n") if( Res=="Full" ) { y.locus.sub <- y.locus ; x.locus.sub <- x.locus } else { y.locus.sub <- sapply(y.locus,GetField,Res=Res) x.locus.sub <- sapply(x.locus,GetField,Res=Res) } A.check <- y.locus.sub %in% x.locus.sub if( sum(A.check)==length(y.locus.sub) ) { A.Flag <- FALSE ; break } else { r <- r + 1 ; A.Flag <- TRUE } if( r > length(Resolution) ) { break } } if(A.Flag) { Alleles <- y.locus[!A.check] ; Alleles <- paste(Alleles,collapse=",") } Output[[i]] <- list( Flag = ifelse(A.Flag,TRUE,FALSE), Alleles = ifelse(A.Flag,Alleles,"") ) } Flags <- unlist(lapply(Output,"[","Flag")) ; Alleles <-lapply(Output,"[","Alleles") if( sum(Flags)>0 ) { getFlags <- which(Flags==TRUE) Alleles.Flagged <- sapply(getFlags,FUN= function(z) paste(Loci[z], unlist(Alleles[[z]]) , sep="*" ) ) Out <- list( Flag = TRUE, Alleles = Alleles.Flagged ) } else { Out <- list( Flag=FALSE , Alleles="" ) } return(Out) } #' Data Summary Function #' #' Summary function for sample population within data file. #' @param Tab Loci available in exon protein list alignment object. #' @param All.ColNames Column names from genotype data. #' @param rescall HLA resolution set for analysis. #' @param HLA HLA BIGDAWG argument passed to function #' @param Verbose Summary display carryover from BIGDAWG function. #' @param Output Data output carryover form BIGDAWG function #' @note This function is for internal BIGDAWG use only. PreCheck <- function(Tab,All.ColNames,rescall,HLA,Verbose,Output) { Grp0 <- which(Tab[,2]==0) Grp1 <- which(Tab[,2]==1) nGrp0 <- length(Tab[Grp0,2]) nGrp1 <- length(Tab[Grp1,2]) if(min(nGrp0,nGrp1)==0) { Err.Log(Output,"Case.Con") stop("Analysis Stopped.",call. = F) } Loci <- as.list(unique(All.ColNames[3:length(All.ColNames)])) nLoci <- length(Loci) GTYPE <- Tab[,3:ncol(Tab)] colnames(GTYPE) <- All.ColNames[3:length(All.ColNames)] nGTYPE <- unlist(lapply(Loci,function(x) length(unique(unlist(GTYPE[,which(colnames(GTYPE)==x)]))))) Grp0un <- unlist(lapply(Loci,function(x) length(unique(unlist(GTYPE[Grp0,which(colnames(GTYPE)==x)]))))) Grp1un <- unlist(lapply(Loci,function(x) length(unique(unlist(GTYPE[Grp1,which(colnames(GTYPE)==x)]))))) nMissing <- unlist(lapply(Loci,function(x) sum(is.na(GTYPE[,which(colnames(GTYPE)==x)])))) Grp0miss <- unlist(lapply(Loci,function(x) sum(is.na(GTYPE[Grp0,which(colnames(GTYPE)==x)])))) Grp1miss <- unlist(lapply(Loci,function(x) sum(is.na(GTYPE[Grp1,which(colnames(GTYPE)==x)])))) if(Verbose) { cat(" Sample Summary\n") cat(" Sample Size (n):",nrow(Tab),"\n") cat(" ...Number of Controls/Cases:",paste(paste(nGrp0,nGrp1,sep="/"),collapse=", "),"\n") cat(" Allele Count (2n):",nrow(Tab)*2,"\n") cat(" Total loci in file:",nLoci,"\n") cat(" Unique loci:",paste(Loci,collapse=", "),"\n") cat(" Unique alleles per locus:",paste(nGTYPE,collapse=", "),"\n") cat(" ...Unique in Controls/Cases:",paste(paste(Grp0un,Grp1un,sep="/"),collapse=", "),"\n") cat(" Missing alleles per locus:",paste(nMissing,collapse=", "),"\n") cat(" ...Missing in Controls/Cases:",paste(paste(Grp0miss,Grp1miss,sep="/"),collapse=", "),"\n") cat("\n") } if(HLA) { Grp0res <- max(unlist(lapply(Loci,function(x) max(unlist(lapply(strsplit(unlist(GTYPE[Grp0,which(colnames(GTYPE)==x)]),split=":"),length)))))) Grp1res <- max(unlist(lapply(Loci,function(x) max(unlist(lapply(strsplit(unlist(GTYPE[Grp1,which(colnames(GTYPE)==x)]),split=":"),length)))))) if(max(Grp0res,Grp1res)>4) { Err.Log(Output,"High.Res") stop("Analysis Stopped.",call. = F) } if(Verbose){ cat(" Observed Allele Resolution\n") cat(" Max Resolution Controls:",paste(Grp0res,"-Field",sep=""),"\n") cat(" Max Resolution Cases:",paste(Grp1res,"-Field",sep=""),"\n") cat(" Defined Resolution:",rescall,"\n") if(Grp0res!=Grp1res){ cat(" ***** Warning. \n") } if(Grp0res!=Grp1res){ cat(" ***** There may exist a Case-Control field resolution imbalance.\n") } if(Grp0res!=Grp1res){ cat(" ***** Considering trimming to",paste(min(Grp0res,Grp1res),"-Field resolution.",sep=""),"\n") } cat("\n") } } if(HLA) { Out <- list(Sample.Size=nrow(Tab), No.Controls=nGrp0, No.Cases=nGrp1, Allele.Count=nrow(Tab)*2, Total.Loci=nLoci, Loci=paste(Loci,collapse=", "), AllelePerLocus=paste(nGTYPE,collapse=", "), MissingPerLocus=paste(nMissing,collapse=", "), MaxResGrp0=paste(Grp0res,"-Field",sep=""), MaxResGrp1=paste(Grp1res,"-Field",sep=""), Suggested.Res=paste(min(Grp0res,Grp1res),"-Field",sep=""), SetRes=rescall) } else { Out <- list(Sample.Size=nrow(Tab), No.Controls=nGrp0, No.Cases=nGrp1, Allele.Count=nrow(Tab)*2, Total.Loci=nLoci, Loci=paste(Loci,collapse=", "), AllelePerLocus=paste(nGTYPE,collapse=", "), MissingPerLocus=paste(nMissing,collapse=", "), SetRes=rescall) } return(do.call(rbind,Out)) } #' Check Data Structure #' #' Check data structure for successful conversion. #' @param Data String Type of output. #' @param System Character Genetic system HLA or KIR #' @param Convert String Direction for conversion. #' @note This function is for internal use only. Check.Data <- function (Data,System,Convert) { if(Convert=="Tab2GL") { # Check for column formatting consistency if( ncol(Data) < 3 ) { Err.Log(FALSE,"Table.Col") ; stop("Analysis Stopped.",call.=F) } # Check for GL string field delimiters Presence if ( sum(grepl("\\+",Data[,ncol(Data)])) > 0 || sum(grepl("\\^",Data[,ncol(Data)])) > 0 || sum(grepl("\\|",Data[,ncol(Data)])) > 0 ) { Err.Log(FALSE,"Tab.Format") ; stop("Analysis Stopped.",call.=F) } # Check for repeating column names colnames(Data) <- sapply(colnames(Data),FUN=gsub,pattern="\\.1|\\.2|\\_1|\\_2",replacement="") DataCol <- which(table(colnames(Data))==2) if( length(DataCol)==0 ) { Err.Log(FALSE,"Table.Pairs") ; stop("Analysis Stopped.",call.=F) } } if(Convert=="GL2Tab") { LastCol <- ncol(Data) #Check for System Name in GL String test <- na.omit(Data[,LastCol]) test <- test[-which(sapply(test,nchar)==0)] if(length(grep(System,test))!=length(test)) { Err.Log(FALSE,"GL.Format") ; stop("Analysis Stopped.",call.=F) } # Check for GL string field delimiters Absence if ( sum(grepl("\\+",Data[,LastCol])) == 0 && sum(grepl("\\^",Data[,LastCol])) == 0 && sum(grepl("\\|",Data[,LastCol])) == 0 ) { Err.Log(FALSE,"GL.Format") ; stop("Analysis Stopped.",call.=F) } # Check for ambiguous data at genotype "|" if( sum(grepl("\\|",Data[,LastCol]))>0 ) { Check.Rows <- paste(grep("\\|",Data[,LastCol]),collapse=",") Err.Log(FALSE,"GTYPE.Amb",Check.Rows) ; stop("Analysis Stopped.",call.=F) } } } #' GL String Locus Check #' #' Check GL string for loci appearing in multiple gene fields. #' @param x GL String to check against #' @param Loci Loci to check #' @note This function is for internal use only. CheckString.Locus <- function(x,Loci) { Calls <- sapply(x,FUN=function(x) strsplit(x,"\\+")) Calls.loci <- lapply(Calls,FUN=function(x) unlist(lapply(strsplit(x,"\\*"),"[",1))) Calls.loci.1 <- unlist(lapply(Calls.loci,"[",1)) Calls.loci.1 <- colSums(sapply(Loci, FUN = function(z) Calls.loci.1 %in% z)) Calls.loci.2 <- as.character(unlist(lapply(Calls.loci,"[",2))) Calls.loci.2 <- colSums(sapply(Loci, FUN = function(z) Calls.loci.2 %in% z)) test.CS <- colSums(rbind(Calls.loci.1,Calls.loci.2)) if( max(test.CS)>2 ) { Loci.Err <- paste(Loci[which(test.CS>2)],collapse=",") GLS <- paste(x,collapse="^") Err.Log(FALSE,"Locus.MultiField",GLS,Loci.Err) stop("Analysis Stopped.",call.=FALSE) } return("ok") } #' GL String Allele Check #' #' GL String check for allele ambiguity formatting #' @param x GL String to check against #' @note This function is for internal use only. CheckString.Allele <- function(x) { x <- as.character(x) if(grepl("/",x)) { tmp <- strsplit(unlist(strsplit(x,"/")),"\\*") tmp.len <- length(unique(lapply(tmp,length))) if( tmp.len > 1 ) { Err.Log(FALSE,"Allele.Amb.Format",x) stop("Analysis Stopped.",call.=FALSE) } } return("ok") } #' Function to Check Release Versions #' #' This updates the protein aligment used in checking HLA loci and alleles as well as in the amino acid analysis. #' @param Package Logical to check for BIGDAWG package versions #' @param Alignment Logical to check the IMGT/HLA database version for the alignment bundled with BIGDAWG. #' @param Output Should any error be written to a file #' @note Requires active internet connection. CheckRelease <- function(Package=T,Alignment=T,Output=F) { if( !inherits(try(XML::readHTMLTable("http://cran.r-project.org/web/packages/BIGDAWG/index.html",header=F),silent=T),"try-error") ) { if(Package) { CranR <- as.character(XML::readHTMLTable("http://cran.r-project.org/web/packages/BIGDAWG/index.html",header=F)[[1]][1,2]) GitHubR <- read.table("https://raw.githubusercontent.com/IgDAWG/BIGDAWG/master/DESCRIPTION",sep="\t",stringsAsFactors=F,nrows=4) GitHubR <- unlist(strsplit(GitHubR[4,],split=" "))[2] CurrR <- as.character(packageVersion('BIGDAWG') ) } if(Alignment) { # Get IMGT Release Version # release_version not updated consistently #download.file("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/release_version.txt",destfile="release_version.txt",method="libcurl") #Release <- read.table("release_version.txt",comment.char="",sep="\t") #Release <- apply(Release,MARGIN=1,FUN= function(x) gsub(": ",":",x)) #RV.current <- unlist(strsplit(Release[3],split=":"))[2] URL=file("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/Allele_status.txt",method=getOption("url.method", "libcurl")) df <- read.table(URL,sep="\t",nrows=3,comment.char="") df.v <- unlist(strsplit(df[3,],split=" ")) RV.current <- paste(df.v[3:4],collapse=" ") # Get BIGDAWG UPL <- paste(path.package('BIGDAWG'),"/data/UpdatePtnAlign.RData",sep="") UpdatePtnList <- NULL ; rm(UpdatePtnList) if( file.exists(UPL) ) { load(UPL) EPL <- UpdatePtnList rm(UpdatePtnList,UPL) UPL.flag=T } else { EPL <- ExonPtnList UPL.flag=F } RV.BIGDAWG <- EPL$Release.Version } cat("\n") if(Package) { cat("BIGDAWG Package Versions:\n","Installed Version: ",CurrR,"\n CRAN Release Version: ",CranR,"\n Developmental version: ",GitHubR,"\n") } if(Package & Alignment) { cat("\n") } if(Alignment) { if(UPL.flag) { cat("IMGT/HLA Versions:\n","IMGT/HLA Version: ",RV.current,"\n BIGDAWG version (from update): ",RV.BIGDAWG,"\n") } else { cat("IMGT/HLA Versions:\n","IMGT/HLA Version: ",RV.current,"\n BIGDAWG version: ",RV.BIGDAWG,"\n") } } cat("\n") } else { Err.Log(Output,"No.Internet") stop("Analysis stopped.",call.=F) } } <file_sep>#' BIGDAWG Main Wrapper Function #' #' This is the main wrapper function for each analysis. #' @param Data Name of the genotype data file. #' @param HLA Logical Indicating whether data is HLA class I/II genotyping data only. #' @param Run.Tests Specifics which tests to run. #' @param Loci.Set Input list defining which loci to use for analyses (combinations permitted). #' @param Exon Numeric Exon(s) for targeted amino acid analysis. #' @param All.Pairwise Logical indicating whether all pairwise loci should be analyzed in haplotype analysis. #' @param Trim Logical indicating if HLA alleles should be trimmed to a set resolution. #' @param Res Numeric setting what desired resolution to trim HLA alleles. #' @param EVS.rm Logical indicating if expression variant suffixes should be removed. #' @param Missing Numeric setting allowable missing data for running analysis (may use "ignore"). #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test. #' @param Cores.Lim Integer setting the number of cores accessible to BIGDAWG (Windows limit is 1 core). #' @param Results.Dir Optional, string of full path directory name for BIGDAWG output. #' @param Return Logical Should analysis results be returned as list. #' @param Output Logical Should analysis results be written to output directory. #' @param Merge.Output Logical Should analysis results be merged into a single file for easy access. #' @param Verbose Logical Should a summary of each analysis be displayed in console. #' @examples #' \dontrun{ #' ### The following examples use the synthetic data set bundled with BIGDAWG #' #' # Haplotype analysis with no missing genotypes for two loci sets #' # Significant haplotype association with phenotype #' # BIGDAWG(Data="HLA_data", Run.Tests="H", Missing=0, Loci.Set=list(c("DRB1","DQB1"))) #' #' # Hardy-Weinberg and Locus analysis ignoring missing data #' # Significant locus associations with phenotype at all but DQB1 #' # BIGDAWG(Data="HLA_data", Run.Tests="L", Missing="ignore") #' #' # Hardy-Weinberg analysis trimming data to 2-Field resolution with no output to files (console only) #' # Significant locus deviation at DQB1 #' BIGDAWG(Data="HLA_data", Run.Tests="HWE", Trim=TRUE, Res=2, Output=FALSE) #' } BIGDAWG <- function(Data, HLA=TRUE, Run.Tests, Loci.Set, Exon, All.Pairwise=FALSE, Trim=FALSE, Res=2, EVS.rm=FALSE, Missing=2, Strict.Bin=FALSE, Cores.Lim=1L, Results.Dir, Return=FALSE, Output=TRUE, Merge.Output=FALSE, Verbose=TRUE) { options(warn=-1) MainDir <- getwd() on.exit(setwd(MainDir), add = TRUE) # CHECK PARAMETERS if( missing(Data) ) { Err.Log("P.Missing","Data") ; stop("Analysis Stopped.",call.=FALSE) } HLA <- as.logical(HLA) Check.Params(HLA, Loci.Set, Exon, All.Pairwise, Trim, Res, EVS.rm, Missing, Cores.Lim, Return, Output, Merge.Output, Verbose) # MULTICORE LIMITATIONS Cores <- Check.Cores(Cores.Lim,Output) cat(rep("=",40)) cat("\n BIGDAWG: Bridging ImmunoGenomic Data Analysis Workflow Gaps\n") cat(rep("=",40),"\n") cat("\n>>>>>>>>>>>>>>>>>>>>>>>>> BEGIN Analysis <<<<<<<<<<<<<<<<<<<<<<<<<\n\n") # Define Output object BD.out <- list() # ===================================================================================================================================== #### # Read in Data ________________________________________________________________________________________________________________________ #### NAstrings=c("NA","","****","-","na","Na") if(is.character(Data)) { if (Data=="HLA_data") { # Using internal synthetic set Tab <- BIGDAWG::HLA_data Data.Flag <- "Internal Synthetic Data Set" } else { # Read in data file entered as string if(!file.exists(Data)) { Err.Log(Output,"Bad.Filename", Data) ; stop("Analysis stopped.",call.=F) } Tab <- read.table(Data, header = T, sep="\t", stringsAsFactors = F, na.strings=NAstrings, fill=T, comment.char = "#", strip.white=T, blank.lines.skip=T, colClasses="character", check.names=FALSE) Data.Flag <- Data } } else { # Using R object Tab <- Data Data.Flag <- deparse(substitute(Data)) # Convert Empty Cells to NA for ( i in 3:ncol(Tab) ) { putCell <- which( sapply( Tab[,i], nchar )==0 ) if( length(putCell) > 0 ) { Tab[putCell,i] <- NA } } } # Declare Data Input Parameter cat("Data Input:",Data.Flag,"\n\n\n") # Convert GLS data if( ncol(Tab) == 3 ) { GLSFLAG = TRUE } else { GLSFLAG = FALSE } if( GLSFLAG && !HLA ) { Err.Log(Output,"notHLA.GLS") } if( GLSFLAG && HLA ) { cat("Converting Gene List Strings to Tabular Format...\n\n") Tab <- GLSconvert(Tab,Convert="GL2Tab",System="HLA",File.Output="R",Strip.Prefix=T,Abs.Fill=T,Cores.Lim=Cores) } # Prep Data for processing and checks Tab <- prepData(Tab) # Define and Change to the required output directory if (Output) { if(missing(Results.Dir)) { OutDir <- paste(MainDir,"/output ",format(Sys.time(), "%d%m%y %H%M%S"),sep="") dir.create(OutDir) } else { OutDir <- Results.Dir } } if(Output) { setwd(OutDir) } # ===================================================================================================================================== #### # Data Processing and Sanity Checks ___________________________________________________________________________________________________ #### cat(">>>> DATA PROCESSING AND CHECKS.\n") #### General processing and checks for all data # Define Data Columns Data.Col <- seq(3,ncol(Tab)) # RUN TESTS DEFINITIONS if ( missing(Run.Tests) ) { Run <- c("HWE","H","L","A") } else { Run <- Run.Tests } if(!HLA) { if("A" %in% Run) { cat("Not HLA data. Skipping Amino Acid Analysis.\n") Run <- Run[-which(Run=="A")] } } # BAD DATA DEFINITIONS - No 1's or 0's if( length(which(Tab[,Data.Col]==0))>0 || length(which(Tab[,Data.Col]==0))>1 ) { Err.Log(Output,"Bad.Data") stop("Analysis Stopped.",call. = F) } # MISSING DATA if(Missing == "ignore") { cat("Ignoring any missing data.\n") Err.Log(Output,"Ignore.Missing") rows.rm <- NULL } else { if (Missing > 2) { if ("H" %in% Run) { Err.Log(Output,"Big.Missing") } } cat("Removing any missing data. This will affect Hardy-Weinberg Equilibrium test.\n") geno.desc <- summaryGeno.2(Tab[,Data.Col], miss.val=NAstrings) test <- geno.desc[,2] + 2*geno.desc[,3] rows.rm <- which(test > Missing) if( length(rows.rm) > 0 ) { rows.rm <- which(test > Missing) ID.rm <- Tab[rows.rm,1] Tab <- Tab[-rows.rm,] if(Output) { write.table(ID.rm, file="Removed_SampleIDs.txt", sep="\t", row.names=F, col.names=F, quote=F) } rm(ID.rm) } rm(geno.desc,test) if(nrow(Tab)==0) { Err.Log(Output,"TooMany.Missing") ; stop("Analysis Stopped.",call. = F) } } # MULTIPLE SETS AND ANALYSIS DUPLICATION if(!missing(Loci.Set)) { if( length(Loci.Set)>1 && (All.Pairwise | "L" %in% Run | "A" %in% Run ) ) { Err.Log(Output,"MultipleSets") } } # DATA MERGE AND NUMBER OF LOCI if(Output && Merge.Output && All.Pairwise) { if(ncol(Tab)>52) { Err.Log(Output,"AllPairwise.Merge") } } ##### HLA specific checks #Check for the updated ExonPtnList 'UpdatePtnList' and use if found. UpdatePtnList <- NULL UPL <- paste(path.package('BIGDAWG'),"/data/UpdatePtnAlign.RData",sep="") if( file.exists(UPL) ) { load(UPL) EPL <- UpdatePtnList rm(UpdatePtnList) UPL.flag=T } else { rm(UpdatePtnList,UPL) EPL <- BIGDAWG::ExonPtnList UPL.flag=F } if(Trim & !HLA) { Err.Log(Output,"NotHLA.Trim") } if(EVS.rm & !HLA) { Err.Log(Output,"NotHLA.EVS.rm") } if(!HLA) { DRBFLAG <- NULL } else { DRB345.test <- length(grep("DRB345",colnames(Tab)))>0 } if(HLA) { if(Trim | EVS.rm | "A" %in% Run | DRB345.test ) { cat("Running HLA specific check functions...\n") } # Check Locus*Allele Formatting across all loci CheckCol <- sum( unlist( apply(Tab[,Data.Col], MARGIN=c(1,2), FUN = function(x) grepl("\\*",na.omit(x))) ) ) TotalCol <- ( dim(Tab[,Data.Col])[1] * dim(Tab[,Data.Col])[2] ) - ( length(which(Tab[,Data.Col]=="^")) + sum(is.na(Tab[,Data.Col])) ) if( CheckCol>0 && CheckCol!=TotalCol ) { Err.Log(Output,"Bad.Format.HLA") stop("Analysis Stopped.",call. = F) } # Separate DRB345 if exists as single column pair and check zygosity if(DRB345.test) { cat("Processing DRB345 column data.\n") DRBFLAG <- T # Expand DRB3/4/5 to separate column pairs Tab <- DRB345.parser(Tab) colnames(Tab) <- sapply(colnames(Tab),FUN=gsub,pattern="\\.1",replacement="") # Redefine Data Columns Data.Col <- seq(3,ncol(Tab)) # Define DR Loci to Process getCol <- grep("DRB",colnames(Tab)) Loci.DR <- unique(colnames(Tab)[getCol]) # Process Loci Tab.list <- lapply(seq_len(nrow(Tab)), FUN=function(z) Tab[z,getCol]) Tab.tmp <- mclapply(Tab.list,FUN=DRB345.Check.Wrapper,Loci.DR=Loci.DR,mc.cores=Cores) Tab.tmp <- do.call(rbind,Tab.tmp) Tab[,getCol] <- Tab.tmp[,grep("DRB",colnames(Tab.tmp))] Tab <- cbind(Tab,Tab.tmp[,'DR.HapFlag']) ; colnames(Tab)[ncol(Tab)] <- "DR.HapFlag" #Identify DR345 flagged haplotypes and Write to File DR.Flags <- Tab[which(Tab[,'DR.HapFlag']!=""),c(1,2,getCol,ncol(Tab))] ; row.names(DR.Flags) <- NULL if(Output) { if(!is.null(DR.Flags)) { Err.Log(Output,"Bad.DRB345.hap") ; cat("\n") write.table(DR.Flags,file="Flagged_DRB345_Haplotypes.txt",sep="\t",quote=F,row.names=F,col.names=T) } } cat("\n") } else { DRBFLAG <- F } # Separate locus and allele names if data is formatted as Loci*Allele Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),FUN=Stripper) # Sanity Check for Resolution if Trim="T" and Trim Data if(Trim & CheckHLA(Tab[,Data.Col])) { cat("--Trimming Data.\n") #Tab.untrim <- Tab Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),GetField,Res=Res) rownames(Tab) <- NULL } else if (Trim) { Err.Log(Output,"Bad.Format.Trim") stop("Analysis Stopped.",call. = F) } # Sanity Check for Expression Variant Suffix Stripping if(EVS.rm & CheckHLA(Tab[,Data.Col])) { cat("--Stripping Expression Variants Suffixes.\n") Tab[,Data.Col] <- apply(Tab[,Data.Col],MARGIN=c(1,2),gsub,pattern="[[:alpha:]]",replacement="") EVS.loci <- as.list(names(EPL)) EPL <- lapply(EVS.loci,EVSremoval,EPList=EPL) names(EPL) <- EVS.loci ; rm(EVS.loci) } else if (EVS.rm) { Err.Log(Output,"Bad.Format.EVS") stop("Analysis Stopped.",call. = F) } # Sanity Check for Amino Acid Test Feasibility if ("A" %in% Run) { cat("Running Amino Acid Analysis specific checks functions...\n") Release <- EPL$Release.Version # Sanity Check for Known HLA loci in Bundled Database Release cat(paste("--Checking loci against database version",Release,".\n",sep="")) test <- CheckLoci(names(EPL),unique(colnames(Tab)[Data.Col])) if( test$Flag ) { Err.Log(Output,"Bad.Locus.HLA",test$Loci) ; stop("Analysis stopped.",call. = F) } # Sanity Check for Known HLA alleles in Bundled Database Release cat(paste("--Checking alleles against database version",Release,".\n",sep="")) test <- CheckAlleles(EPL, Tab[,Data.Col]) if( test$Flag ) { Err.Log(Output,"Bad.Allele.HLA",test$Alleles) ; stop("Analysis stopped.",call. = F) } # Sanity Check for Analysis and HLA Allele Resolution (MUST perform THIS STEP AFTER TRIM!!!!) if(Res<2 | !CheckHLA(Tab[,Data.Col])) { Err.Log(Output,"Low.Res") cat("You have opted to run the amino acid analysis.\n") stop("Analysis stopped.",call. = F) } } # End A if statement } # End HLA if statement and HLA specific functionalities # LOCI SET COLUMN DEFINITIONS # This section MUST follow DRB345 processing (above) on the chance that DRB345 is formatted as single column # and DRB3, DRB4, or DRB5 is defined in Loci.Set. if(missing(Loci.Set)) { Set <- list(Data.Col) } else { Loci.Set <- lapply(Loci.Set,FUN=function(x) sapply(x,toupper)) Set <- lapply(Loci.Set,FUN=function(x) seq(1,ncol(Tab))[colnames(Tab) %in% x]) } # LOCUS SET DEFINED DOES NOT EXIST IN DATA if(!missing(Loci.Set)) { Loci.Set <- unique(unlist(Loci.Set)) Loci.Data <- colnames(Tab)[Data.Col] if ( sum(Loci.Set %in% Loci.Data) != length(Loci.Set) ) { Err.Log(Output,"PhantomSets") ; stop("Analysis Stopped.",call. = F) } } # ===================================================================================================================================== #### # Case-Control Summary ________________________________________________________________________________________________________________ #### cat("\n>>>> CASE - CONTROL SUMMARY STATISTICS\n") #cat(paste(rep("_",50),collapse=""),"\n") if (Trim) { rescall <- paste(Res,"-Field",sep="") } else { rescall <- "Not Defined" } Check <- PreCheck(Tab,colnames(Tab),rescall,HLA,Verbose,Output) if(Output) { write.table(Check,file="Data_Summary.txt",sep=": ",col.names=F,row.names=T,quote=F); rm(Check,rescall) } # ===================================================================================================================================== #### # Write to Parameter File _____________________________________________________________________________________________________________ #### if(Output) { if(HLA && !is.null(DRBFLAG)) { DRB345.tmp <- DRBFLAG } else { DRB345.tmp <- NULL } if(HLA) { Trim.tmp <- Trim } else { Trim.tmp <- NULL } if(HLA && Trim) { Res.tmp <- Res } else { Res.tmp <- NULL } if(HLA) { EVS.rm.tmp <- EVS.rm } else { EVS.rm.tmp <- NULL } if( !missing(Exon) ) { Exon.tmp <- paste(unique(unlist(Exon)),collapse=",") } else { Exon.tmp <- NULL } Params.Run <- list(Time = format(Sys.time(), "%a %b %d %X %Y"), BD.Version = as.character(packageVersion("BIGDAWG")), Cores.Used = Cores, File = Data.Flag, Output.Results = Output, Merge = Merge.Output, Return.Object = Return, Display.Results = Verbose, HLA.Data = HLA, Exon = Exon.tmp, DRB345.Parsed = DRB345.tmp, Tests = paste(Run,collapse=","), All.Pairwise = All.Pairwise, Trim = Trim.tmp, Resolution = Res.tmp, Suffix.Stripping = EVS.rm.tmp, Missing.Allowed = Missing, Strict.Binning = Strict.Bin, Samples.Removed = length(rows.rm)) Params.Run <- do.call(rbind,Params.Run) write.table(Params.Run,file="Run_Parameters.txt",sep=": ", row.names=T, col.names=F, quote=F) } # ===================================================================================================================================== #### # Hardy Weignberg Equilibrium 'HWE' ___________________________________________________________________________________________________ #### if ("HWE" %in% Run) { cat("\n>>>> STARTING HARDY-WEINBERG ANALYSIS...\n") #cat(paste(rep("_",50),collapse=""),"\n") if(HLA && Trim) { cat("HWE performed at user defined resolution.\n") } else if (HLA) { cat("HWE performed at maximum available resolution.\n") } HWE <- HWE.wrapper(Tab,Output,Verbose) BD.out[['HWE']] <- HWE rm(HWE) } #END HARDY-WEINBERG # ===================================================================================================================================== #### # Set Loop Begin (loop through each defined locus/loci set) ___________________________________________________________________________ #### if ( sum( c("H","L","A") %in% Run ) > 0 ) { cat("\n>>>>>>>>>>>>>>>>>>>>>>>>> Begin Locus Sets <<<<<<<<<<<<<<<<<<<<<<<<<\n\n") if(length(Set)==1) { cat("Your analysis has 1 set to analyze.\n") } else { cat(paste("Your analysis has ", length(Set), " sets to analyze.", sep=""),"\n") } for(k in 1:length(Set)) { cat("\n") cat(paste(rep(">",35),collapse=""),"Running Set",k,"\n") cols <- Set[[k]] Tabsub <- Tab[,c(1,2,cols)] #Set Specific Global Variables SID <- Tabsub[,1] # sample IDs genos <- Tabsub[,3:ncol(Tabsub)] # genotypes genos[genos==""] <- NA grp <- Tabsub[, 2] # phenotype #nGrp0 <- length(which(grp==0))*2 #nalleles #nGrp1 <- length(which(grp==1))*2 #nalleles loci <- unique(gsub(".1","",colnames(genos),fixed=T)) # name of loci loci.ColNames <- gsub(".1","",colnames(genos),fixed=T) # column names nloci <- as.numeric(length(loci)) # number of loci SetName <- paste('Set',k,sep="") if(HLA==T) { genos[genos=='^'] <- "00:00" } if(Output) { OutSetDir <- paste(OutDir,"/Set",k,sep="") dir.create(OutSetDir) setwd(OutSetDir) Params.set <- list(Set = paste("Set",k), Loci.Run = paste(loci,collapse=",") ) Params.set <- do.call(rbind,Params.set) write.table(Params.set,file="Set_Parameters.txt",sep=": ", row.names=T, col.names=F, quote=F) } SAFE <- c(ls(),"SAFE") # ===================================================================================================================================== #### # Haplotype Analysis 'H' ______________________________________________________________________________________________________________ #### if ("H" %in% Run) { #cat(paste(rep("_",50),collapse="","\n")) # Sanity check for set length and All.Pairwise=T if (nloci<2) { Err.Log(Output,"Loci.No") stop("Analysis Stopped.", call. = F) } else if (All.Pairwise & nloci<=2) { Err.Log(Output,"Loci.No.AP") stop("Analysis Stopped.", call. = F) } Haps.list <- H.MC.wrapper(SID,Tabsub,loci,loci.ColNames,genos,grp,All.Pairwise,Strict.Bin,Output,Verbose,Cores) if(All.Pairwise) { if(length(BD.out[['H']])>0) { BD.out[['H']] <- c(BD.out[['H']],Haps.list) } else { BD.out[['H']] <- Haps.list } } else { BD.out[['H']][[SetName]] <- Haps.list } rm(list=ls()[!(ls() %in% SAFE)]) } #END HAPLOTYPE # ===================================================================================================================================== #### # Locus Level 'L' _____________________________________________________________________________________________________________________ #### if ("L" %in% Run) { #cat(paste(rep("_",50),collapse="")) L.list <- L.wrapper(nloci,loci,loci.ColNames,genos,grp,Strict.Bin,Output,Verbose) BD.out[['L']][[SetName]] <- list(binned=L.list[['AB']], freq=L.list[['AF']], OR=L.list[['OR']], chisq=L.list[['CS']], table=L.list[['FB']]) rm(list=ls()[!(ls() %in% SAFE)]) } #END LOCUS # ===================================================================================================================================== #### # Amino Acid Level 'A' ________________________________________________________________________________________________________________ #### if(HLA) { if ("A" %in% Run) { #cat(paste(rep("_",50),collapse="")) if(UPL.flag) { cat("Using updated protein exon alignments for amino acid analysis.\n") } A.list <- A.wrapper(loci,loci.ColNames,genos,grp,Exon,EPL,Cores,Strict.Bin,Output,Verbose) if(Output) { ## write to file write.table(Release, file = "Set_Parameters.txt", sep="\t", row.names = F, col.names=F, quote = F, append=T) } BD.out[['A']][[SetName]] <- list(log=A.list[['AL']], binned=A.list[['AB']], freq=A.list[['AF']], OR=A.list[['OR']], chisq=A.list[['CS']], table=A.list[['FB']]) rm(list=ls()[!(ls() %in% SAFE)]) } #END AMINO ACID }#END if(HLA) # ===================================================================================================================================== #### # End Analyses ________________________________________________________________________________________________________________________ #### }; rm(k) }# END SET LOOP if(Output) { if(Merge.Output) { cat("\nMerging data files ...\n") if("HWE" %in% Run) { Run <- Run[-which(Run=="HWE")] } if( length(Run)>=1 ) { MergeData_Output(BD.out,Run,OutDir) } } } # ===================================================================================================================================== #### cat("\n>>>>>>>>>>>>>>>>>>>>>>>>>> End Analysis <<<<<<<<<<<<<<<<<<<<<<<<<<\n") if(Output) { setwd(OutDir); save(BD.out, file="Analysis.RData") } options(warn=0) if(Return) { return(BD.out) } }# END FUNCTION <file_sep># BIGDAWG Data sets and functions for chi-squared Hardy-Weinberg and case-control association tests of highly polymorphic genetic data [e.g., human leukocyte antigen (HLA) data]. Performs association tests at multiple levels of polymorphism (haplotype, locus and HLA amino-acids) as described in Pappas DJ, <NAME>, Hollenbach JA, <NAME> (2016) <doi:10.1016/j.humimm.2015.12.006>. Combines rare variants to a common class to account for sparse cells in tables as described by <NAME>, <NAME>, <NAME>, <NAME> (2012) <doi:10.1007/978-1-61779-842-9_14>. For more details, please visit http://tools.immunogenomics.org. <file_sep>#' Genotype List String to Tabular Data Conversion #' #' Expands GL strings to columns of adjacent locus pairs. #' @param df Data frame containing GL strings #' @param System Character Genetic system HLA or KIR #' @param Strip.Prefix Logical Should System/Locus prefixes be stripped from table data. #' @param Abs.Fill Logical Should absent loci special designations be used. #' @param Cores Integer How many cores can be used #' @note This function is for internal use only GL2Tab.wrapper <- function(df,System,Strip.Prefix,Abs.Fill,Cores) { # Data column LastCol <- ncol(df) MiscCol <- seq(1,ncol(df)-1) # Remove empty data rows df <- na.omit(df) rmRows <- which(nchar(df[,LastCol])==0) if( length(rmRows)!=0 ) { df <- df[-rmRows,] } # Run Conversion df.list <- strsplit(df[,LastCol],"\\^") Tab <- parallel::mclapply(df.list,FUN=GL2Tab.Sub,System=System,mc.cores=Cores) Loci <- sort(unique(gsub("_1|_2","",unlist(lapply(Tab,colnames))))) if( sum(grepl('DR.HapFlag',Loci)) > 0 ) { Loci <- Loci[-grep('DR.HapFlag',Loci)] } Order <- Build.Matrix(System,Loci) Tab <- parallel::mclapply(Tab,FUN=Format.Tab,Order=Order,mc.cores=Cores) Tab <- do.call(rbind,Tab) Tab[Tab==0] <- "" Tab[grepl("\\^",Tab)] <- "" # Pad Absent Calls for DRBx? if( System=="HLA-") { getCol <- grep("DRB3|DRB4|DRB5",colnames(Tab)) if(length(getCol)>0) { if(Abs.Fill) { Tab[,getCol] <- sapply(getCol,FUN=function(i) Filler(Tab[,i], colnames(Tab)[i], Type="Fill")) } else { Tab[,getCol] <- sapply(getCol,FUN=function(i) Filler(Tab[,i], Type="Remove")) } } } # Strip Prefixes? if(Strip.Prefix) { Tab[,seq(1,ncol(Tab)-1)] <- apply(Tab[,seq(1,ncol(Tab)-1)],MARGIN=c(1,2),FUN=Stripper) } # Final Table with Misc Information Appended Tab <- cbind(df[,MiscCol],Tab) return(Tab) } #' Genotype List String Expander #' #' Expands GL string into a table of adjacent loci #' @param x Character GL string to expand #' @param System Character Genetic system HLA or KIR #' @note This function is for internal use only. GL2Tab.Sub <- function(x,System) { # Break GL String and Remove Any Absent Call Type Strings (00:00) Calls <- unlist(sapply(x,FUN=function(x) strsplit(x,"\\+"))) ; names(Calls) <- NULL # Check GL String For Locus*Allele/Locus*Allele Ambiguity Formatting invisible(sapply(Calls,CheckString.Allele)) # Collapse Ambiguous allele names to remove locus prefix if( sum(grepl("/",Calls)>0 ) ) { Calls <- unlist(lapply(Calls,Format.Allele,Type="off")) } # Get loci and initialize table Loci <- unique(unlist(lapply(strsplit(Calls,"\\*"),"[",1))) if(System=="HLA-") { if( sum(grepl("DRB1",Loci))>0 ) { Loci <- c(Loci,DRB345.Exp(Calls[grep("DRB1",Calls)])) } Loci <- unique(Loci) } Tab <- Build.Matrix(System,Loci) # Check GL String For Locus^Gene Field Consistency invisible(CheckString.Locus(x,Loci)) # Populate table tmp <- lapply(Loci,GL2Tab.Loci,Genotype=Calls,System=System) tmp.calls <- lapply( seq(length(tmp)), FUN = function(i) cbind(tmp[[i]]['Locus_1'], tmp[[i]]['Locus_2']) ) tmp.calls <- do.call(cbind, tmp.calls) DR.HapFlag <- unlist(lapply(tmp,'[','DR.HapFlag')) DR.HapFlag <-paste(DR.HapFlag[which(DR.HapFlag!="")],collapse=",") Tab[1,] <- cbind(tmp.calls,DR.HapFlag) return(Tab) } #' Locus Ordering for GL2Tab #' #' Orders Locus Calls #' @param Locus Locus to condense #' @param Genotype Row of loci to condense #' @param System Character Genetic system HLA or KIR #' @note This function is for internal use only. GL2Tab.Loci <- function(Locus,Genotype,System) { Alleles <- Genotype[grep(Locus,Genotype)] if( length(Alleles) == 1 && System=="HLA-" ) { if( Locus!="HLA-DRB3" || Locus!="HLA-DRB4" || Locus!="HLA-DRB5" ) { # Homozygous Assumption for HLA non-DRB345 Alleles <- c(Alleles,Alleles) } } else if ( length(Alleles) == 1 ) { Alleles <- c(Alleles,"") } else if ( length(Alleles) == 0 ) { Alleles <- c("","") } names(Alleles) <- c('Locus_1','Locus_2') if(System=="HLA-") { if(Locus=="HLA-DRB3" || Locus=="HLA-DRB4" || Locus=="HLA-DRB5") { if( sum(grepl("DRB1",Genotype))>0 ) { # Assumptions for DRB345 DRB.GTYPE <- DRB345.Check.Zygosity(Locus,Genotype[grep("DRB",Genotype)]) DRB.GTYPE[1,grepl("\\^",DRB.GTYPE)] <- "" Alleles[] <- c(DRB.GTYPE[,'Locus_1'],DRB.GTYPE[,'Locus_2']) # for inconsistent DR haplotypes DRB345.Flag <- DRB.GTYPE[,'Flag'] } else { # No DRB1 but DBR345 (ZYgosity Check Not Determined) DRB345.Flag <- "DRB345_ND" } # fi DRB1 } else { DRB345.Flag <- NULL } # fi DRB345 } # fi HLA if(System=="HLA-") { DR.HapFlag <- ifelse(!is.null(DRB345.Flag), paste(unlist(DRB345.Flag),collapse=",") , "") Out <- c(Alleles,DR.HapFlag) names(Out)[length(Out)] <- "DR.HapFlag" } else { Out <- Alleles } return(Out) } <file_sep>#' Update function for protein aligment upon new IMGT HLA data release #' #' This updates the protein aligment used in checking HLA loci and alleles as well as in the amino acid analysis. #' @param Restore Logical specifying if the original alignment file be restored. #' @param Force Logical specifiying if update should be forced. #' @param Output Logical indicating if error reporting should be written to file. UpdateRelease <- function(Force=F,Restore=F,Output=F) { if( !inherits(try(XML::readHTMLTable("http://cran.r-project.org/web/packages/BIGDAWG/index.html",header=F),silent=T),"try-error") ) { MainDir <- getwd() on.exit(setwd(MainDir), add = TRUE) getDir <- path.package('BIGDAWG') putDir <- paste(getDir,"/data",sep="") if(!dir.exists(putDir)) { dir.create(putDir) } if(!Restore) { #Check current version against BIGDAWG version if(!Force) { setwd(putDir) # Get IMGT Release Version invisible(download.file("ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/version_report.txt",destfile="release_version.txt",method="libcurl")) Release <- read.table("version_report.txt",comment.char="",sep="\t") RV.current <- Release[2] file.remove("version_report.txt") # Get BIGDAWG UPL <- paste(path.package('BIGDAWG'),"/data/UpdatePtnAlign.RData",sep="") UpdatePtnList <- NULL ; rm(UpdatePtnList) if( file.exists(UPL) ) { load(UPL) EPL <- UpdatePtnList rm(UpdatePtnList,UPL) UPL.flag=T } else { EPL <- ExonPtnList UPL.flag=F } RV.BIGDAWG <- EPL$Release.Version cat("Versions:\n","IMGT/HLA current: ",RV.current,"\n BIGDAWG version: ",RV.BIGDAWG,"\n") if(grepl(RV.current,RV.BIGDAWG)) { Flag <- T } else { Flag <- F } } else { Flag <- F }# End if() for setting Flag #Run Update if Flag = T if(Flag) { cat("\nYour database seems up to date. Use Force = T to force the update.") } else { # For creating UpdatePtnAlign.RData object # Define download directory setwd(putDir) Safe <- dir() Safe <- c(Safe[!grepl(".txt",Safe)],"UpdatePtnAlign.RData") #STEP 1: Define Loci and Read in Reference Exon Map Files Loci <- c("A","B","C","DPA1","DPB1","DQA1","DQB1","DRB1","DRB3","DRB4","DRB5") #Currently DRB1, DRB3, DRB4, DRB5 aligments in single file #Remove if split into individual files Loci.get <- c("A","B","C","DPA1","DPB1","DQA1","DQB1","DRB") #Exon Info RefTab <- BIGDAWG::ExonPtnList$RefExons #STEP 2: Download protein alignments and other ancillary files cat("Updating reference object for the amino acid analysis.\n") cat("Downloading alignment files from the IMGT/HLA.\n") GetFiles(Loci.get) Release <- read.table('Release.txt',sep="\t") # created during GetFiles download #STEP 3: Format alignments for exons of interest cat("Formatting alignment files.\n") for(i in 1:length(Loci)) { Locus <- Loci[i] ; ExonPtnAlign.Create(Locus,RefTab) } #STEP 4: Create ExonPtnAlign list object for BIGDAWG package AlignObj.Update(Loci,Release,RefTab) #STEP 5: Clean up cat("Cleaning up.\n") invisible(file.remove(dir()[which(dir() %in% Safe!=T)])) cat("Updated.\n") } } else if (Restore) { setwd(putDir) if(!file.exists('UpdatePtnAlign.RData')) { stop("No prior update to restore.", call.= F) } cat("Restoring original alignment reference object for amino acid analysis.\n") invisible(file.remove('UpdatePtnAlign.RData')) cat("Restored.\n") } } else { Err.Log(Output,"No.Internet") stop("Update stopped.",call.=F) } } <file_sep> #' Amino Acid Analysis Function #' #' This is the workhorse function for the amino acid analysis. #' @param Locus Locus being analyzed. #' @param loci.ColNames The column names of the loci being analyzed. #' @param genos Genotype table. #' @param grp Case/Control or Phenotype groupings. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test. #' @param ExonAlign Exon protein alignment filtered for locus. #' @param Cores Number of cores to use for analysis. #' @note This function is for internal BIGDAWG use only. A <- function(Locus,loci.ColNames,genos,grp,Strict.Bin,ExonAlign,Cores) { # pull out locus specific columns getCol <- seq(1,length(loci.ColNames),1)[loci.ColNames %in% Locus] HLA_grp <- cbind(grp,genos[,getCol]) rownames(HLA_grp) <- NULL nAllele <- length(na.omit(HLA_grp[,2])) + length(na.omit(HLA_grp[,3])) ## extract alleles Alleles <- unique(c(HLA_grp[,2],HLA_grp[,3])) Alleles2F <- sort(unique(as.character(sapply(Alleles, GetField, Res=2)))) if( length(Alleles2F)>1 ) { # Filter exon alignment matrix for specific alleles TabAA <- AlignmentFilter(ExonAlign,Alleles2F,Locus) TabAA.list <- lapply(seq_len(ncol(TabAA)), function(x) TabAA[,c(2,x)]) TabAA.list <- TabAA.list[5:ncol(TabAA)] TabAA.names <- colnames(TabAA)[5:ncol(TabAA)] # Generate Contingency Tables ConTabAA.list <- parallel::mclapply(TabAA.list,AAtable.builder,y=HLA_grp,mc.cores=Cores) names(ConTabAA.list) <- TabAA.names # Check Contingency Tables # FlagAA.list <- parallel::mclapply(ConTabAA.list,AA.df.check,Strict.Bin=Strict.Bin,mc.cores=Cores) # Run ChiSq ChiSqTabAA.list <- parallel::mclapply(ConTabAA.list,AA.df.cs,Strict.Bin=Strict.Bin,mc.cores=Cores) FlagAA.list <- lapply(ChiSqTabAA.list,"[[",4) # build data frame for 2x2 tables Final_binned.list <- lapply(ChiSqTabAA.list,"[[",1) ccdat.list <- lapply(Final_binned.list,TableMaker) OR.list <- lapply(ccdat.list, cci.pval.list) #OR } else { # Filter exon alignment matrix for single allele TabAA <- AlignmentFilter(ExonAlign,Alleles2F,Locus) FlagAA.list <- as.list(rep(TRUE,length(TabAA[6:length(TabAA)]))) names(FlagAA.list) <- names(TabAA[6:length(TabAA)]) ChiSqTabAA.list <- NA OR.list <- NA Final_binned.list <- NA } ####################################################### Build Output List A.tmp <- list() ## AAlog_out - Positions with insufficient variation or invalid ChiSq csRange <- which(FlagAA.list==FALSE) # all failed ChiSeq FlagAA.fail <- rownames(do.call(rbind,FlagAA.list[csRange])) if( length(csRange)>0 ) { # identify insufficient vs invalid flags invRange <- intersect(names(csRange), names(which(lapply(Final_binned.list,nrow)>=2)) )# invalid cont table isfRange <- setdiff(names(csRange),invRange) # insufficient variation if( length(isfRange)>=1 ){ AAlog.out.isf <- cbind(rep(Locus,length(isfRange)), isfRange, rep("Insufficient variation at position.",length(isfRange))) } else { AAlog.out.isf <- NULL } if( length(invRange)>=1 ){ AAlog.out.inv <- cbind(rep(Locus,length(invRange)), invRange, rep("Position invalid for Chisq test.",length(invRange))) } else { AAlog.out.inv <- NULL } # Final AAlog.out AAlog.out <- rbind(AAlog.out.inv, AAlog.out.isf) colnames(AAlog.out) <- c("Locus","Position","Comment") rownames(AAlog.out) <- NULL AAlog.out <- AAlog.out[match(FlagAA.fail,AAlog.out[,'Position']),] } else { AAlog.out <- NULL } A.tmp[['log']] <- AAlog.out ## AminoAcid.binned_out if(length(ChiSqTabAA.list)>1) { binned.list <- lapply(ChiSqTabAA.list,"[[",2) binned.list <- binned.list[which(lapply(binned.list,is.logical)==F)] binned.out <- do.call(rbind,binned.list) if(!is.null(nrow(binned.out))) { binned.out <- cbind(rep(Locus,nrow(binned.out)), rep(names(binned.list),as.numeric(lapply(binned.list,nrow))), rownames(binned.out), binned.out) colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1") rownames(binned.out) <- NULL A.tmp[['binned']] <- binned.out } else { binned.out <- cbind(Locus,'Nothing.binned',NA,NA,NA) colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1") rownames(binned.out) <- NULL A.tmp[['binned']] <- binned.out } } else{ binned.out <- cbind(Locus,'Nothing.binned',NA,NA,NA) colnames(binned.out) <- c("Locus","Position","Residue","Group.0","Group.1") rownames(binned.out) <- NULL A.tmp[['binned']] <- binned.out } ## overall.chisq_out rmPos <- match(FlagAA.fail,names(ChiSqTabAA.list)) ChiSqTabAA.list <- ChiSqTabAA.list[-rmPos] if(length(ChiSqTabAA.list)>1) { ChiSq.list <- lapply(ChiSqTabAA.list,"[[",3) ChiSq.out <- do.call(rbind,ChiSq.list) if(!is.null(ChiSq.out)){ ChiSq.out <- cbind(rep(Locus,nrow(ChiSq.out)), rownames(ChiSq.out), ChiSq.out) colnames(ChiSq.out) <- c("Locus","Position","X.square","df","p.value","sig") rownames(ChiSq.out) <- NULL A.tmp[['chisq']] <- ChiSq.out } else { Names <- c("Locus","Position","X.square","df","p.value","sig") A.tmp[['chisq']] <- Create.Null.Table(Locus,Names,nr=1) } } else { Names <- c("Locus","Position","X.square","df","p.value","sig") A.tmp[['chisq']] <- Create.Null.Table(Locus,Names,nr=1) } ## ORtable_out #rmPos <- match(FlagAA.fail,names(OR.list)) #OR.list <- OR.list[-rmPos] if(length(OR.list)>1) { OR.out <- do.call(rbind,OR.list) if(!is.null(OR.out)) { OR.out <- cbind(rep(Locus,nrow(OR.out)), rep(names(OR.list),as.numeric(lapply(OR.list,nrow))), rownames(OR.out), OR.out) colnames(OR.out) <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig") rownames(OR.out) <- NULL rmRows <- unique(which(OR.out[,'sig']=="NA")) if( length(rmRows) > 0 ) { OR.out <- OR.out[-rmRows,,drop=F] } A.tmp[['OR']] <- OR.out } else { Names <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig") A.tmp[['OR']] <- Create.Null.Table(Locus,Names,nr=1) } } else { Names <- c("Locus","Position","Residue","OR","CI.lower","CI.upper","p.value","sig") A.tmp[['OR']] <- Create.Null.Table(Locus,Names,nr=1) } ## Final_binned_out (Final Table) #rmPos <- match(FlagAA.fail,names(Final_binned.list)) #Final_binned.list <- Final_binned.list[-rmPos] if( length(Final_binned.list)>1 ) { Final_binned.out <- do.call(rbind,Final_binned.list) if(!is.null(Final_binned.out)) { Final_binned.out <- cbind(rep(Locus,nrow(Final_binned.out)), rep(names(Final_binned.list),as.numeric(lapply(Final_binned.list,nrow))), rownames(Final_binned.out), Final_binned.out) colnames(Final_binned.out) <- c("Locus","Position","Residue","Group.0","Group.1") rownames(Final_binned.out) <- NULL A.tmp[['table']] <- Final_binned.out } else { Final_binned.out <- NULL Names <- c("Locus","Position","Residue","Group.0","Group.1") A.tmp[['table']] <- Create.Null.Table(Locus,Names,nr=1) } } else { Final_binned.out <- NULL Names <- c("Locus","Position","Residue","Group.0","Group.1") A.tmp[['table']] <- Create.Null.Table(Locus,Names,nr=1) } ## AminoAcid.freq_out if( !is.null(Final_binned.out) ) { Positions <- unique(Final_binned.out[,'Position']) for(p in Positions) { getRows <- which(Final_binned.out[,'Position']==p) FBO_tmp <- Final_binned.out[getRows,,drop=F] Final_binned.out[getRows,'Group.0'] <- round(as.numeric(FBO_tmp[,'Group.0']) / sum(as.numeric(FBO_tmp[,'Group.0'])), digits=5) Final_binned.out[getRows,'Group.1'] <- round(as.numeric(FBO_tmp[,'Group.1']) / sum(as.numeric(FBO_tmp[,'Group.1'])), digits=5) } A.tmp[['freq']] <- Final_binned.out } else { Names <- c("Locus","Position","Residue","Group.0","Group.1") A.tmp[['freq']] <- Create.Null.Table(Locus,Names, nr=1) } return(A.tmp) } <file_sep>#' Haplotype List Builder #' #' Builds table of haplotypes from combinations #' @param Combn Combination of loci to extraction from genos #' @param genos The genotype columns of the loci set being analyzed. #' @param loci Character vector of unique loci being analyzed. #' @param loci.ColNames Character vector of genos column names. #' @note This function is for internal BIGDAWG use only. buildHAPsets <- function(Combn,genos,loci,loci.ColNames) { # Range in matrix Set.H <- loci.ColNames %in% loci[Combn] return(genos[,Set.H]) } #' Haplotype Name Builder #' #' Builds table of names for HAPsets #' @param Combn Combination of loci to extraction from genos #' @param loci Character vector of unique loci being analyzed. #' @note This function is for internal BIGDAWG use only. buildHAPnames <- function(Combn,loci) { return(paste(loci[Combn],collapse="~")) } #' Haplotype Table Maker #' #' Builds table of haplotypes #' @param HaploEM Haplotype output object from haplo.stat::haplo.em function. #' @param SID Index number (i.e., row number) of sample ID from genotype matrix. #' @note This function is for internal BIGDAWG use only. getHap <- function(SID,HaploEM) { # SID subject number # haplotype object from Haplo.em # Range in matrix Range <- which(HaploEM$indx.subj==SID) HapGet <- which.max(HaploEM$post[Range]) # Which haplotype (when more than one possibility) Hap1.no <- HaploEM$hap1code[Range][HapGet] Hap2.no <- HaploEM$hap2code[Range][HapGet] # Combine into a haplotype string Hap1 <- paste(HaploEM$haplotype[Hap1.no,],collapse="~") Hap2 <- paste(HaploEM$haplotype[Hap2.no,],collapse="~") # Output haplotype return(c(Hap1,Hap2)) } <file_sep>--- title: "GLSconvert" author: "<NAME>, Ph.D. (<EMAIL>)" date: "2020-02-10" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{GLSconvert} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ## Overview GLSconvert represents a suite of tools for cross converting HLA or KIR genotyping data from gene list text strings to multi-column tabular format as desribed in Milius RP, Mack SJ, Hollenbach JA, et al. 2013. Genotype List String: a grammar for describing HLA and KIR genotyping results in a text string. [Tissue Antigens. 82:106-112](https://pubmed.ncbi.nlm.nih.gov/23849068/). ### Anatomy of a GL String The figure below depicts a genotype List (GL) String representation of a multilocus unphased genotype. A GL String representing HLA-A genotype (A*02:69 and A*23:30, or A*02:302 and, either A*23:26 or A*23:39) and HLA-B genotype (B*44:02:13 and B*49:08) for a single individual is shown. GL String delimiters are parsed hierarchically starting from the locus delimiter (^), proceeding to the genotype delimiter (|), then the chromosome delimiter (+), and ending with the allele delimiter (/). A GL String should include the genetic system name (HLA or KIR) as part of the locus name. ![](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3715123/bin/tan0082-0106-f1.jpg) ### Input Data Data may be passed to GLSconvert() as a tab delimited text file name (full path recommended) or as a R object (data frame). Whether a text file or an R object, the first row must be a header line and include column names for the GL string/locus genotypes. Any column preceeding the genotyping information is considered to be identifying/miscellanous information. This would generally include at least the sample id. While there is no limit to the number of columns, the direction of the conversion may dictate a specific column order. Empty rows will be excluded from final output. _**GL String to Table**_ Formatting for GL string conversion requires that the last column of the data table must contain the GL string. |SubjectID |Exp ID |GLString | |----------|:------:|:---------------------------------------------:| |Subject1 |Center1 |HLA-A\*01:01+HLA-A\*02:01\^HLA-B\*08:01+HLA-B\*44:02\^HLA-DRB1\*01:01+HLA-DRB1\*03:01 | _**Table to GL String**_ Formatting for table conversion requires at least three columns. One (or more) column(s) of identifying information followed by column pairs for each locus. Genotype locus pairs must be located in adjacent columns. Column names for a given locus may use (not required) '_1', '.1','_2','.2' to distinguish each locus pair. Only columns defining genotypes names for each locus may repeat, all other column names must be unique. You may format your alleles as Locus*Allele or Allele following defined HLA and KIR naming conventions. |SubjectID |Exp ID | A | A | B | B | DRB1 | DRB1 | DRB3 | DRB3 | |----------|:------:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:| |Subject1 |Center1 |01:01 |02:01 |08:01 |44:02 |01:01 |04:01 | | | **Ambiguity** Only ambiguity at the allele level is compatible with the GL conversion tool (separated by "/"). Ambiguity at the genotype (separated by "|") cannot be used with the GL conversion tool and will terminate the script. This includes tables submitted for conversion to GL strings containing rows of identical non-genotype identifying information (sample ID, experiment ID, etc.), these will be considered to be ambiguous genotypes in the table and the conversion tool will stop. **Homozygosity** Homozygous allele calls can be represented as single alleles in the GL string. For example, HLA-A\*01:01:01:01 + HLA-A\*01:01:01:01 can be written as HLA-A*01:01:01:01. This only applies to Tab2GL conversions. When a locus is represented by a single allele in a GL string, that allele will be reported in both fields for that locus in the converted table **HLA-DRB3, HLA-DRB4, and HLA-DRB5** HLA-DRB3, HLA-DRB4, and HLA-DRB5 are parsed for homozygous or hemizygous status based on the DRB1 haplotype as defined by Andersson, 1998 (<NAME>. 1998. Evolution of the HLA-DR region. [Front Biosci. 3:d739-45](https://pubmed.ncbi.nlm.nih.gov/9675159/)) and can be flagged for inconsistency. Inconsistent haplotypes will be indicated in a separate column called "DR.HapFlag" with the locus or loci that are inconsistent with the respective DRB1 status. You may choose not to have haplotypes flagged using the 'DRB345.Check' parameter (see below). **Missing Information** For HLA-DRB3, HLA-DRB4, and HLA-DRB5 (HLA-DRBx) When there is missing information, either for lack of genotyping calls or absence of genotyped loci, GLSconvert allows for a convention to differentiate data missing due to genomic structural variation (i.e., locus absence). The acceptable indicator of locus absence is the 2-Field designation HLA-DRBx*00:00 (x = 3,4,5). For example, HLA-DRB5\*00:00+HLA-DRB5\*00:00 would indicate absence of a HLA-DRB5 locus and not a failed or missing genotype call. You may choose to have GLSconvert fill in absent calls for these loci. For Tab2GL conversion, a NA can be used to indicate missing due to lack of genotyping call, however a NA is not compatible with GL2Tab conversion and should be avoided. ## Data Output Data can be output to either a text file (tab or comma delimitted) or R object (sent to data frame). See Output parameters below. When running the GL2Tab conversion, all adjacent pairs of loci will include '_1' and '_2' to distinguish each chromosome. Please note, subsequent programs used to analyze the data table such as BIGDAWG or Pypop may not accept files with ambiguous genotyping data. ## Parameters `GLSconvert(Data,Convert,Output="txt",System="HLA",HZY.Red=FALSE,DRB345.Check=FALSE,Strip.Prefix=TRUE,Cores.Lim=1L)` **Data** Class: String/Object. (No Default). e.g., Data="/your/path/to/file/foo.txt" -or- Data="foo.txt" -or- Data=foo (No Default) Specifies data file name or data object. File name is either full file name path to specify file location (recommended) or name of file within a set working directory. See Data Input section for details about file formatting. **This parameter is required for the conversion utility.** **Convert** Class: String. Options: "GL2Tab" -or- "Tab2GL" (No Default). Specifies data file name or data object. May use file name within working directory or full file name path to specify file location (recommended). See Data Input section for details about file formatting. **This parameter is required for the conversion utility.** **File.Output** Class: String. Options: "R" -or- "txt" -or- "csv" -or- "pypop" (Default = "txt"). Specifies the type of output for the converted genotypes. For file writing, if you specified the full path for a file name then the resultant file will be written to the same directory. Otherwise the file will be written to whichever working directory was defined at initiation of conversion. The converted file name will be of the form "Converted_foo.txt" depending on output setting. If the data was an R object, the file name will be "Converted.txt" if output to file is desired. To output as R object will require an assignment to some object (see examples below). **System** Class: String. Options: "HLA" or "KIR" (Default="HLA"). Defines the genetic system of the data being converted. This parameter is required for Tab2GL conversion and is ignored for GL2Tab. The default system is HLA. **HZY.Red** Class: Logical (Default=FALSE). Homozygous reduction: Indicates if non-DRBx homozygotes should be represented by a single allele name in GL string. For example: HLA-A*01:01:01:01+HLA-A*01:01:01:01 as HLA-A*01:01:01:01. The default behavior is to keep both allele names in the GL string. This parameter is only used when Convert = Tab2GL, and only applies to non-DRBx genotype data **DRB345.Check** Class: Logical (Default=FALSE). Indicates whether DR haplotypes should be parsed for correct zygosity and unusual DR haplotypes flagged. Inconsistent loci will appear flagged in a separate column labeled 'DR.HapFlag' that follows the genotype columns. The default behavior will flag unusual haplotypes. HLA-DRBx alleles without a respective HLA-DRB1 will remain unchanged and the flag will say 'ND' for not determined. **Strip.Prefix** Class: Logical (Default=TRUE). Applies only to Convert="GL2Tab" conversions. Indicates whether alleles should be stripped of System/Locus prefixes in the final data when converting from GL strings to tabular format. For example, should HLA-A*01:01:01:01 be recorded as 01:01:01:01 in the final table. Required when outputting to a PyPop compatible file. The default will strip prefixes. **Abs.Fill** Class: Logical (Default=FALSE). Relevant only to data containing one or more of the loci: HLA-DRB3, HLA-DRB4, or HLA-DRB5. Directs GLSconvert to fill in missing information with the 2-Field designation HLA-DRBx\*00:00. For example, when data contain HLA-DRB5 typing, those subjects with no HLA-DRB5 will be given the designation HLA-DRB5\*00:00 or HLA-DRB5\*00:00+HLA-DRB5\*00:00 depending on the situation. If you have absent locus designations already present in your data, then GLconverion will remove them in the final output. ## Examples These are examples only and need not be run as defined below. ``` # Run the GL2Tab conversion on a data file with default output to text file and no prefix stripping GLSconvert(Data="/your/path/to/file/foo.txt", Convert="GL2Tab", Strip.Prefix=FALSE) # Run the Tab2GL conversion on a R object outputting to a R object with DRB345 Flagging foo.tab <- GLSconvert(Data=foo, Convert="Tab2GL", File.Output="R", DRB345.Check=TRUE) # Run the Tab2GL conversion on a text file outputting to a csv file and with homozygous allele reduction of non-DRB345 alleles GLSconvert(Data=foo, Convert="Tab2GL", File.Output="csv", HZY.Red=TRUE) # Run the GL2Tab conversion on a data file without the full path name setwd("/your/path/to/file") GLSconvert(Data="foo.txt", Convert="GL2Tab") ``` *End of vignette.* <file_sep>#' Locus Wrapper #' #' Wrapper for main L function #' @param nloci Number of loci being analyzed. #' @param loci Loci being analyzed. #' @param loci.ColNames The column names of the loci being analyzed. #' @param genos Genotype table #' @param grp Case/Control or Phenotype groupings. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test #' @param Output Data return carryover from main BIGDAWG function #' @param Verbose Summary display carryover from main BIGDAWG function #' @note This function is for internal BIGDAWG use only. L.wrapper <- function(nloci,loci,loci.ColNames,genos,grp,Strict.Bin,Output,Verbose) { cat("\n>>>> STARTING LOCUS LEVEL ANALYSIS...\n") Allele.binned <- list() # Alleles binned during chi-square test Allele.freq <- list() # Alleles Frequencies overall.chisq <- list() # Chi-Square Table ORtable <- list() # Odds Ratio Table Final_binned <- list() # Contingency Table for(j in 1:nloci) { # Get Locus Locus <- loci[j] # Run Locus Level Analysis L.list <- L(loci.ColNames,Locus,genos,grp,Strict.Bin) # Build Output Lists Allele.binned[[Locus]] <- L.list[['binned']] Allele.freq[[Locus]] <- L.list[['freq']] overall.chisq[[Locus]] <- L.list[['chisq']] ORtable[[Locus]] <- L.list[['OR']] Final_binned[[Locus]] <- L.list[['table']] }# END locus loop Out <- list() Out[['AB']] <- do.call(rbind,Allele.binned) Out[['AF']] <- do.call(rbind,Allele.freq) Out[['CS']] <- do.call(rbind,overall.chisq) Out[['OR']] <- do.call(rbind,ORtable) Out[['FB']] <- do.call(rbind,Final_binned) if(Output) { ## write to file write.table(Out[['AF']], file = paste("Locus_freqs.txt",sep=""), sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['FB']], file = paste("Locus_table.txt",sep=""), sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['AB']], file = paste("Locus_binned.txt",sep=""), sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['OR']], file = paste("Locus_OR.txt",sep=""), sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['CS']], file = paste("Locus_chisq.txt",sep=""), sep="\t", row.names = F, col.names=T, quote = F) } cat("> LOCUS LEVEL ANALYSIS COMPLETED","\n") if(Verbose) { print(as.data.frame(Out[['CS']]),row.names=F) cat("\n") } return(Out) } <file_sep>#' Genotype List String to Tabular Data Conversion #' #' Expands GL strings to columns of adjacent locus pairs. #' @param df Data frame containing GL strings #' @param System Character Genetic system HLA or KIR #' @param HZY.Red Logical Should homozygote genotypes be a single allele for non-DRB345. #' @param Abs.Fill Logical Should absent loci special designations be used #' @param Cores Integer How many cores can be used. #' @note This function is for internal use only. Tab2GL.wrapper <- function(df,System,HZY.Red,Abs.Fill,Cores) { # Define data locus columns assuming Locus columns come in pairs colnames(df) <- sapply(colnames(df),FUN=gsub,pattern="\\.1|\\.2|\\_1|\\_2",replacement="") DataCol <- which(colnames(df) %in% names(which(table(colnames(df))==2))==TRUE) MiscCol <- setdiff(1:ncol(df),DataCol) # Check for identical rows of miscellanous information from non-data columns. Ambiguous Data Flag. Misc.tmp <- apply(df[,MiscCol],MARGIN=1,FUN=paste,collapse=":") if( length(which(table(Misc.tmp)>1))>0 ) { Err.Log(FALSE,"Table.Amb") ; stop("Conversion stopped.",call.=F) }; rm(Misc.tmp) # Remove empty data rows rmRows <- which(rowSums(apply(df[,DataCol],MARGIN=c(1,2),FUN=nchar))==0) if( length(rmRows)!=0 ) { df <- df[-rmRows,] ; rownames(df) <- NULL } # Pre-format data to SystemLoci*Allele if necessary if( sum(grepl(System,colnames(df)[DataCol]))==0 ) { colnames(df)[DataCol] <- paste(System,colnames(df)[DataCol],sep="") } for(i in DataCol) { if(sum(grepl(colnames(df)[i],df[,i]))==0) { df[,i] <- sapply(df[,i], FUN = Append.System, df.name=colnames(df)[i] ) } } # Pad Absent Calls for DRBx? if( System=="HLA-") { getCol <- grep("DRB3|DRB4|DRB5",colnames(df)) if(length(getCol)>0) { if(Abs.Fill) { df[,getCol] <- sapply(getCol,FUN=function(i) Filler(df[,i], colnames(df)[i], Type="Fill")) } else { df[,getCol] <- sapply(getCol,FUN=function(i) Filler(df[,i], Type="Remove")) } } } # Run Conversion df.list <- lapply(seq(1,nrow(df)), FUN=function(k) df[k,DataCol]) GL <- parallel::mclapply(df.list,FUN=Tab2GL.Sub,System=System,HZY.Red=HZY.Red,mc.cores=Cores) GL <- do.call(rbind,GL) if(ncol(GL)==1) { colnames(GL) <- "GL.String" } else if(ncol(GL)==2) { colnames(GL) <- c("GL.String","DR.HapFlag") } GL <- cbind(df[,MiscCol],GL) return(GL) } #' Genotype List String Condenser #' #' Condenses column of loci into a GL string using "^" #' @param x Row of loci to condense #' @param System Character Genetic system HLA or KIR #' @param HZY.Red Logical Should homozygote genotypes be a single allele for non-DRB345. #' @note This function is for internal use only. Tab2GL.Sub <- function(x,System,HZY.Red) { # Identify Loci in data and for HLA-DRB1 expected DRB345 Loci x <- x[which(x!="")] colnames(x) <- sapply(colnames(x),FUN=gsub,pattern="\\.1|\\.2|\\_1|\\_2",replacement="") Loci <- unique(colnames(x)) if(System=="HLA-") { if( sum(grepl("DRB1",Loci))>0 ) { Loci <- c(Loci,DRB345.Exp(x[grep("DRB1",colnames(x))])) } if( sum(grepl("\\^",Loci))>0 ) { Loci <- Loci[-grep("\\^",Loci)] } Loci <- unique(Loci) } # Append Locus to ambiguous Allele/Allele calls x[] <- sapply(x,Format.Allele,Type="on") # Condense Alleles (+) GLS <- lapply(Loci,Tab2GL.Loci,Genotype=x,System=System,HZY.Red=HZY.Red) GLS <- do.call(rbind,GLS) GLS[,1] <- sapply(GLS[,1],FUN=gsub,pattern="NA+NA|\\+NA|NA\\+",replacement="") GLS[GLS=="OK"] <- "" # Condense Chromosomes (^) Out <- paste(as.character(na.omit(GLS[,1])),collapse="^") Flag <- paste(GLS[which(GLS[,2]!=""),2],collapse="") Out <- c(Out,Flag) } #' Locus Condenser for Tab2GL #' #' Condenses alleles calls of a single locus string using "+" #' @param Locus Locus to condense #' @param Genotype Row of loci to condense #' @param System Character Genetic system HLA or KIR #' @param HZY.Red Logical Should homozygote genotypes be a single allele for non-DRB345. #' @note This function is for internal use only. Tab2GL.Loci <- function(Locus,Genotype,System,HZY.Red) { Alleles <- Genotype[grep(Locus,Genotype)] if(System=="HLA-") { if(Locus=="HLA-DRB3" || Locus=="HLA-DRB4" || Locus=="HLA-DRB5") { if( sum(grepl("DRB1",Genotype))>0 ) { # Assumptions for DRB345 DRB.GTYPE <- DRB345.Check.Zygosity(Locus, Genotype[grep("DRB",Genotype)] ) DRB.GTYPE[1,grepl("\\^",DRB.GTYPE)] <- NA Alleles <- c(DRB.GTYPE[,'Locus_1'],DRB.GTYPE[,'Locus_2']) # for inconsistent DR haplotypes DRB345.Flag <- DRB.GTYPE[,'Flag'] } else if( sum(grepl(grep("DRB",Genotype)))>0 ) { # DRB345 but no DRB1 (ZYgosity Check Not Determined) DRB345.Flag <- "DRB345_ND" } # fi no DRB1 but DRB345 } else { DRB345.Flag <- NULL } # fi DRB345 } # fi HLA if( sum(is.na(Alleles))==0 && HZY.Red && Alleles[1]==Alleles[2] ) { # Homozygous Reduction GLS <- Alleles[1] } else { # Remove NA Strings and Collapse Alleles <- Alleles[!is.na(Alleles)] GLS <- paste(Alleles,collapse="+") } if(System=="HLA-") { DR.HapFlag <- ifelse(!is.null(DRB345.Flag), paste(unlist(DRB345.Flag),collapse=",") , "") Out <- c(GLS,DR.HapFlag) } else { Out <- GLS } return(Out) } <file_sep>#' Locus Analysis Function #' #' This is the workhorse function for the locus level analysis. #' @param loci.ColNames The column names of the loci being analyzed. #' @param Locus Locus being analyzed. #' @param genos Genotype table #' @param grp Case/Control or Phenotype groupings. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test #' @note This function is for internal BIGDAWG use only. L <- function(loci.ColNames,Locus,genos,grp,Strict.Bin) { # pull out locus specific columns getCol <- seq(1,length(loci.ColNames),1)[loci.ColNames %in% Locus] HLA_grp <- cbind(grp,genos[,getCol]) rownames(HLA_grp) <- NULL nAllele <- length(na.omit(HLA_grp[,2])) + length(na.omit(HLA_grp[,3])) ## extract alleles and counts for Grp1 and Grp0 Alleles <- sort(unique(c(HLA_grp[,2],HLA_grp[,3]))) # Build Contingency Matrix of Counts Allele.df <- list() for(i in 1:length(Alleles)) { Allele.df[[i]] <- cbind(Locus, Alleles[i], sum(length(which(subset(HLA_grp, grp==0)[,2]==Alleles[i])), length(which(subset(HLA_grp, grp==0)[,3]==Alleles[i]))), sum(length(which(subset(HLA_grp, grp==1)[,2]==Alleles[i])), length(which(subset(HLA_grp, grp==1)[,3]==Alleles[i])))) }; rm(i) Allele.df <- do.call(rbind,Allele.df) colnames(Allele.df) <- c("Locus","Allele","Group.0","Group.1") Allele.con <- matrix(as.numeric(Allele.df[,3:4]), ncol=2, dimnames=list(Allele.df[,'Allele'],c("Group.0", "Group.1"))) if(nrow(Allele.con)>1) { ### get expected values for cells, bin small cells, and run chi square if(Strict.Bin) { Result <- RunChiSq(Allele.con) } else { Result <- RunChiSq_c(Allele.con) } if( !Result$Flag ) { alleles_binned <- NULL Final_binned <- NULL overall.chisq <- NULL ORout <- NULL } else { alleles_binned <- Result$Binned Final_binned <- Result$Matrix overall.chisq <- Result$Test ## make a nice table of ORs, ci, p values ccdat <-TableMaker(Final_binned) ORout <- lapply(ccdat, cci.pval) #OR ORout <- do.call(rbind,ORout) colnames(ORout) <- c("OR","CI.lower","CI.upper","p.value","sig") rmRows <- which(ORout[,'sig']=="NA") if( length(rmRows > 0) ) { ORout <- ORout[-rmRows,,drop=F] } } } else { alleles_binned <- NULL Final_binned <- NULL overall.chisq <- NULL ORout <- NULL } ####################################################### Build Output List L.tmp <- list() ## Alleles.binned_out if( !is.null(alleles_binned) ) { if( sum(is.na(alleles_binned))==2) { alleles_binned <- NULL } } if( !is.null(alleles_binned) ) { Allele.binned.tmp <- cbind(rep(Locus,nrow(alleles_binned)), rownames(alleles_binned), alleles_binned) rownames(Allele.binned.tmp) <- NULL colnames(Allele.binned.tmp) <- c("Locus","Allele","Group.0","Group.1") if(sum(grepl("\\^",Allele.binned.tmp[,'Allele']))>0) { Allele.binned.tmp[,'Allele'] <- gsub("\\^","Abs",Allele.binned.tmp[,'Allele']) } L.tmp[['binned']] <- Allele.binned.tmp } else { binned.out <- cbind(Locus,'Nothing.binned',NA,NA) colnames(binned.out) <- c("Locus","Allele","Group.0","Group.1") rownames(binned.out) <- NULL L.tmp[['binned']] <- binned.out } ## Allele.freq_out Allele.freq.out <- cbind(rep(Locus,nrow(Allele.con)), rownames(Allele.con), round(Allele.con[,'Group.0']/sum(Allele.con[,'Group.0']),digits=5), round(Allele.con[,'Group.1']/sum(Allele.con[,'Group.1']),digits=5)) rownames(Allele.freq.out) <- NULL colnames(Allele.freq.out) <- c("Locus","Allele","Group.0","Group.1") if(sum(grepl("\\^",Allele.freq.out[,'Allele']))>0) { Allele.freq.out[,'Allele'] <- gsub("\\^","Abs",Allele.freq.out[,'Allele']) } L.tmp[['freq']] <- Allele.freq.out ## ORtable_out if(!is.null(ORout)) { ORtable_out.tmp <- cbind(rep(Locus,nrow(ORout)), rownames(ORout), ORout) rownames(ORtable_out.tmp) <- NULL colnames(ORtable_out.tmp) <- c("Locus","Allele","OR","CI.lower","CI.upper","p.value","sig") if(sum(grepl("\\^",ORtable_out.tmp[,'Allele']))>0) { ORtable_out.tmp[,'Allele'] <- gsub("\\^","Abs",ORtable_out.tmp[,'Allele']) } L.tmp[['OR']] <- ORtable_out.tmp } else { ORtable_out.tmp <- cbind(Locus,Alleles,"NCalc","NCalc","NCalc","NCalc","NCalc") rownames(ORtable_out.tmp) <- NULL colnames(ORtable_out.tmp) <- c("Locus","Allele","OR","CI.lower","CI.upper","p.value","sig") if(sum(grepl("\\^",ORtable_out.tmp[,'Allele']))>0) { ORtable_out.tmp[,'Allele'] <- gsub("\\^","Abs",ORtable_out.tmp[,'Allele']) } L.tmp[['OR']] <- ORtable_out.tmp } ## overall.chisq_out if(!is.null(overall.chisq)) { overall.chisq.tmp <- cbind(Locus, overall.chisq) rownames(overall.chisq.tmp) <- NULL colnames(overall.chisq.tmp) <- c("Locus","X.square","df","p.value","sig") L.tmp[['chisq']] <- overall.chisq.tmp } else { overall.chisq.tmp <- cbind(Locus,"NCalc","NCalc","NCalc","NCalc") rownames(overall.chisq.tmp) <- NULL colnames(overall.chisq.tmp) <- c("Locus","X.square","df","p.value","sig") L.tmp[['chisq']] <- overall.chisq.tmp } ## Final_binned_out if(!is.null(Final_binned)) { Final_binned.tmp <- cbind(rep(Locus,nrow(Final_binned)), rownames(Final_binned), Final_binned) rownames(Final_binned.tmp) <- NULL colnames(Final_binned.tmp) <- c("Locus","Allele","Group.0","Group.1") if(sum(grepl("\\^",Final_binned.tmp[,'Allele']))>0) { Final_binned.tmp[,'Allele'] <- gsub("\\^","Abs",Final_binned.tmp[,'Allele']) } L.tmp[['table']] <- Final_binned.tmp } else { Final_binned.tmp <- cbind(Locus,Alleles,"NCalc","NCalc") rownames(Final_binned.tmp) <- NULL colnames(Final_binned.tmp) <- c("Locus","Allele","Group.0","Group.1") if(sum(grepl("\\^",Final_binned.tmp[,'Allele']))>0) { Final_binned.tmp[,'Allele'] <- gsub("\\^","Abs",Final_binned.tmp[,'Allele']) } L.tmp[['table']] <- Final_binned.tmp } return(L.tmp) } <file_sep>#' Haplotype Wrapper for Multicore #' #' Wrapper for main H function #' @param SID Character vector of subject IDs. #' @param Tabsub Data frame of genotype calls for set being analyzed. #' @param loci Character vector of unique loci being analyzed. #' @param loci.ColNames Character vector of genos column names. #' @param genos The genotype columns of the loci set being analyzed. #' @param grp Case/Control or Phenotype groupings. #' @param All.Pairwise Haplotype argument carryover from main BIGDAWG function #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test #' @param Output Data return carryover from main BIGDAWG function #' @param Verbose Summary display carryover from main BIGDAWG function #' @param Cores Cores carryover from main BIGDAWG function #' @note This function is for internal BIGDAWG use only. H.MC.wrapper <- function(SID,Tabsub,loci,loci.ColNames,genos,grp,All.Pairwise,Strict.Bin,Output,Verbose,Cores) { cat(">>>> STARTING HAPLOTYPE ANALYSIS...","\n") # Define Pairwise Combinations to Run When Selected if(All.Pairwise) { # Define Combinations Combos <- t(combn(length(loci),2)) Combos <- lapply(seq_len(nrow(Combos)),FUN=function(x) Combos[x,]) cat("\nYou have opted to run all pairwise combinations for the haplotype analysis.\n") cat("There are", length(Combos), "possible locus combinations to run.\n" ) # Define Pairwise Sets HAPsets <- parallel::mclapply(Combos,FUN=buildHAPsets,genos=genos,loci=loci,loci.ColNames=loci.ColNames,mc.cores=Cores) HAPnames <- unlist(parallel::mclapply(Combos,FUN=buildHAPnames,loci=loci,mc.cores=Cores)) names(HAPsets) <- HAPnames } else { HAPsets <- list() HAPsets[[paste(loci,collapse='~')]] <- genos } # Run H #Start <- Sys.time() H.list <- parallel::mclapply(HAPsets,H.MC,grp=grp,Strict.Bin=Strict.Bin,Verbose=Verbose,mc.cores=Cores) #Sys.time() - Start if(All.Pairwise) { #chisq tmp.cs <- parallel::mclapply(H.list,"[[","chisq",mc.cores=Cores) tmp.cs <- do.call(rbind,tmp.cs) tmp.cs <- cbind(rownames(tmp.cs),tmp.cs) colnames(tmp.cs)[1] <- "Pairwise.Loci" rownames(tmp.cs) <- NULL } if(Output) { # Gathering List Elements H.out <- list() if(All.Pairwise) { #Frequencies tmp <- parallel::mclapply(H.list,"[[","freq",mc.cores=Cores) nrow.tmp <- lapply(tmp,nrow) haps.tmp <- rep(names(nrow.tmp),nrow.tmp) tmp <- cbind(haps.tmp,do.call(rbind,tmp)) colnames(tmp)[1:2] <- c("Pairwise.Loci","Haplotype") H.out[['freq']] <- tmp #binned tmp <- parallel::mclapply(H.list,"[[","binned",mc.cores=Cores) nrow.tmp <- lapply(tmp,nrow) haps.tmp <- rep(names(nrow.tmp),nrow.tmp) tmp <- cbind(haps.tmp,do.call(rbind,tmp)) colnames(tmp)[1:2] <- c("Pairwise.Loci","Haplotype") H.out[['binned']] <- tmp #OR tmp <- parallel::mclapply(H.list,"[[","OR",mc.cores=Cores) nrow.tmp <- lapply(tmp,nrow) haps.tmp <- rep(names(nrow.tmp),nrow.tmp) tmp <- cbind(haps.tmp,do.call(rbind,tmp)) colnames(tmp)[1:2] <- c("Pairwise.Loci","Haplotype") H.out[['OR']] <- tmp #chisq H.out[['chisq']] <- tmp.cs #table tmp <- parallel::mclapply(H.list,"[[","table",mc.cores=Cores) nrow.tmp <- lapply(tmp,nrow) haps.tmp <- rep(names(nrow.tmp),nrow.tmp) tmp <- cbind(haps.tmp,do.call(rbind,tmp)) colnames(tmp)[1:2] <- c("Pairwise.Loci","Haplotype") H.out[['table']] <- tmp #Haplotypes tmp <- parallel::mclapply(H.list,"[[","Haplotypes",mc.cores=Cores) nrow.tmp <- lapply(tmp,nrow) haps.tmp <- rep(names(nrow.tmp),nrow.tmp) tmp <- cbind(SID,haps.tmp,do.call(rbind,tmp)) colnames(tmp) <- c("SAMPLE.ID","Pairwise.Loci","Haplotype.1","Haplotype.2") H.out[['Haplotypes']] <- tmp } else { #Frequencies-binned-OR-chisq-table H.out[['freq']] <- H.list[[1]][['freq']] H.out[['binned']] <- H.list[[1]][['binned']] H.out[['OR']] <- H.list[[1]][['OR']] H.out[['chisq']] <- H.list[[1]][['chisq']] H.out[['table']] <- H.list[[1]][['table']] #Haplotyeps tmp <- H.list[[1]][['Haplotypes']] tmp <- cbind(SID,tmp) colnames(tmp)[1] <- "SAMPLE.ID" H.out[['Haplotypes']] <- tmp } ## write to file write.table(H.out[['freq']], "haplotype_freqs.txt", sep="\t", quote = F, row.names=F, col.names=T) write.table(H.out[['binned']], "haplotype_binned.txt", sep="\t", quote = F, row.names=F, col.names=T) write.table(H.out[['OR']], "haplotype_OR.txt", sep="\t", quote = F, row.names=F, col.names=T) write.table(H.out[['chisq']], "haplotype_chisq.txt", sep="\t", row.names = F, quote = F) write.table(H.out[['table']], "haplotype_table.txt", sep="\t", row.names = F, quote = F) write.table(H.out[['Haplotypes']], "haplotype_HapsbySubject.txt", sep="\t", row.names = F, quote = F) } if(All.Pairwise) { PairSetName <- paste("Pairwise.Set",seq_len(length(H.list)),sep="") # Hapset Legend File if(Output) { tmp <- cbind(PairSetName,names(HAPsets)) colnames(tmp) <- c("Set_Name","Loci") write.table(tmp,file="haplotype_PairwiseSets.txt",sep="\t",quote=F,col.names=T,row.names=F) } names(H.list) <- PairSetName } else { H.list <- H.list[[1]] } cat("> HAPLOTYPE ANALYSIS COMPLETED","\n") if(Verbose) { if(All.Pairwise) { overall.chisq <- tmp.cs } else { overall.chisq <- H.list[['chisq']] } print(as.data.frame(overall.chisq), row.names=F) cat("\n") } return(H.list) } <file_sep>#' Prepare imported data #' #' Prepare imported data for processing, checks, and analysis. #' @param Tab Genotypes dataframe. #' @note This function is for internal BIGDAWG use only. prepData <- function(Tab) { Tab[] <- lapply(Tab, as.character) colnames(Tab) <- gsub( "HLA-","",colnames(Tab) ) colnames(Tab) <- gsub( "\\.1|\\.2|\\_1|\\_2","",colnames(Tab) ) colnames(Tab) <- toupper(colnames(Tab)) colnames(Tab) <- gsub( "DRB3.4.5|DRB3/4/5","DRB345",colnames(Tab) ) rownames(Tab) <- NULL Tab <- rmABstrings(Tab) return(Tab) } #' Replace absent allele strings #' #' Replaces allowable absent allele strings with ^ symbol. #' @param df Genotypes dataframe. #' @note This function is for internal BIGDAWG use only. rmABstrings <- function(df) { df[] <- apply(df, MARGIN=c(1,2), FUN=function(x) gsub("ABSENT|Absent|absent|Abs|ABS|ab|Ab|AB","^",x) ) df[df=="00"] <- "^" df[df=="00:00"] <- "^" df[df=="00:00:00"] <- "^" df[df=="00:00:00:00"] <- "^" return(df) } #' Replace or Fill 00:00 allele strings #' #' Replaces or Fills absent allele strings. #' @param x Genotype #' @param Locus Locus column to adjust. #' @param Type String specifying whether to pad ('Fill') or leave blank ('Remove') absent calls #' @note This function is for internal use only. Filler <- function(x,Locus=NULL,Type) { if (Type=="Fill") { which(x=="") Locus <- gsub("_1|_2","",Locus) x[which(x=="")] <- paste(Locus,"*00:00",sep="") } if (Type=="Remove") { x[] <- sapply(x, FUN=function(x) gsub("ABSENT|Absent|absent|Abs|ABS|ab|Ab|AB","",x) ) x[grep("\\*00",x)] <- "" } if (Type=="Sub") { x[] <- sapply(x, FUN=function(x) gsub("ABSENT|Absent|absent|Abs|ABS|ab|Ab|AB","^",x) ) x[grep("\\*00",x)] <- "^" } return(x) } #' Removes System and Locus from Alleles #' #' Removes the System and Locus designations for alleles calls in GL2Tab #' @param x Allele #' @note This function is for internal use only. Stripper <- function(x) { if( grepl("\\*",x) ) { if( is.na(x) ) { Fix <- x } else if ( x!="" ) { Fix <- unlist(strsplit(x,"\\*"))[2] } else { Fix <- x } } else { return (x) } return(Fix) } #' Expression Variant Suffix Removal #' #' Removes expression variant suffixes from HLA alleles in the exon protein alignment object. #' @param Locus Locus to be filtered against. #' @param EPList Exon Protein Alignment Object #' @note This function is for internal BIGDAWG use only. EVSremoval <- function(Locus,EPList) { if( Locus=='Release.Date' || Locus=='Release.Version' || Locus=='RefExons' || Locus=='ExonPtnMap' ) { tmp <- EPList[[Locus]] return(tmp) } else { tmp <- EPList[[Locus]] tmp[,'Trimmed'] <- sapply(tmp[,'Trimmed'],gsub,pattern="[[:alpha:]]",replacement="") return(tmp) } } #' HLA trimming function #' #' Trim a properly formatted HLA allele to desired number of fields. #' @param x HLA allele. #' @param Res Resolution desired. #' @note This function is for internal BIGDAWG use only. GetField <- function(x,Res) { Tmp <- unlist(strsplit(as.character(x),":")) if (length(Tmp)<2) { return(x) } else if (Res==1) { return(Tmp[1]) } else if (Res > 1) { Out <- paste(Tmp[1:Res],collapse=":") return(Out) } } #' Haplotype missing Allele summary function #' #' Summary function for identifying missing alleles in a matrix of genotypes. #' @param geno Matrix of genotypes. #' @param miss.val Vector of codes for allele missing values. #' @note This function is for internal BIGDAWG use only and is ported from haplo.stats. summaryGeno.2 <- function (geno, miss.val = 0) { # Ported from R package haplo.stats v 1.7.7 # Authors: <NAME>, <NAME> # URL: https://cran.r-project.org/web/packages/haplo.stats/index.html n.loci <- ncol(geno)/2 nr <- nrow(geno) geno <- haplo.stats::setupGeno(geno, miss.val) loc0 <- numeric(nr) loc1 <- numeric(nr) loc2 <- numeric(nr) for (i in 1:nr) { first.indx <- seq(1, (2 * n.loci - 1), by = 2) miss.one <- is.na(geno[i, first.indx]) | is.na(geno[i, first.indx + 1]) miss.two <- is.na(geno[i, first.indx]) & is.na(geno[i, first.indx + 1]) loc2[i] <- sum(miss.two) loc1[i] <- sum(miss.one - miss.two) loc0[i] <- sum(!miss.one) } tbl <- data.frame(missing0 = loc0, missing1 = loc1, missing2 = loc2) return(tbl) } #' Data Object Merge and Output #' #' Whole data set table construction of per haplotype for odds ratio, confidence intervals, and pvalues #' @param BD.out Output of analysis as list. #' @param Run Tests that are to be run as defined by Run.Tests. #' @param OutDir Output directory defined by Results.Dir or default. #' @note This function is for internal BIGDAWG use only. MergeData_Output <- function(BD.out,Run,OutDir) { FM.out <- data.frame(Analysis=character(), Locus=character(), Allele=character(), Group.0=numeric(), Group.1=numeric()) CN.out <- data.frame(Analysis=character(), Locus=character(), Allele=character(), Group.0=numeric(), Group.1=numeric()) OR.out <- data.frame(Analysis=character(), Locus=character(), Allele=character(), OR=numeric(), CI.Lower=numeric(), CI.Upper=numeric(), p.value=numeric(), sig=character()) CS.out <- data.frame(Analysis=character(), Locus=character(), x.square=numeric(), df=numeric(), p.value=numeric(), sig=character()) for(i in Run) { switch(i, H= { TestName <- "Haplotype" }, L= { TestName <- "Locus" }, A= { TestName <- "AminoAcid" } ) Test <- BD.out[[i]] for(k in 1:length(Test)) { Test.sub <- Test[[k]] #Frequencies tmp <- Test.sub$freq if(i=="A") { Allele <- paste(tmp[,'Position'],tmp[,'Residue'],sep="::") } switch(i, H = { tmp <- cbind(rep(TestName,nrow(tmp)),rep(colnames(tmp)[1],nrow(tmp)),tmp) }, L = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp) }, A = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp[,'Locus'],Allele,tmp[,c('Group.0','Group.1')]) }) colnames(tmp) <- c("Analysis","Locus","Allele","Group.0","Group.1") FM.out <- rbind(tmp,FM.out) ; rm(tmp) #Counts tmp <- Test.sub$table if(i=="A") { Allele <- paste(tmp[,'Position'],tmp[,'Residue'],sep="::") } switch(i, H = { tmp <- cbind(rep(TestName,nrow(tmp)),rep(colnames(tmp)[1],nrow(tmp)),tmp) }, L = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp) }, A = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp[,'Locus'],Allele,tmp[,c('Group.0','Group.1')]) }) colnames(tmp) <- c("Analysis","Locus","Allele","Group.0","Group.1") CN.out <- rbind(tmp,CN.out) ; rm(tmp) #Odds Ratios tmp <- Test.sub$OR if(i=="A") { Allele <- paste(tmp[,'Position'],tmp[,'Residue'],sep="::") } switch(i, H = { tmp <- cbind(rep(TestName,nrow(tmp)),rep(colnames(tmp)[1],nrow(tmp)),tmp) }, L = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp) }, A = { tmp <- cbind(rep(TestName,nrow(tmp)),tmp[,'Locus'],Allele,tmp[,c("OR","CI.lower","CI.upper","p.value","sig")]) }) colnames(tmp) <- c("Analysis","Locus","Allele","OR","CI.Lower","CI.Upper","p.value","sig") OR.out <- rbind(tmp,OR.out) ; rm(tmp) #ChiSq tmp <- Test.sub$chisq if(i=="A") { Locus <- paste(tmp[,'Locus'],tmp[,'Position'],sep="::") } switch(i, H = { tmp <- cbind(rep(TestName,nrow(tmp)), rep(names(Test)[k],nrow(tmp)), tmp) }, L = { tmp <- cbind(rep(TestName,nrow(tmp)), tmp) }, A = { tmp <- cbind(rep(TestName,nrow(tmp)), Locus, tmp[,c('X.square','df','p.value','sig')] ) } ) colnames(tmp)[1:2] <- c("Analysis","Locus") rownames(tmp) <- NULL CS.out <- rbind(tmp,CS.out); rm(tmp) }; rm(k) }; rm(i) setwd(OutDir) # Remove redundant entries # Especially relevant to multi-set runs FM.out <- unique(FM.out) CN.out <- unique(CN.out) CS.out <- unique(CS.out) OR.out <- apply(OR.out,MARGIN=c(1,2),as.character) OR.out <- unique(OR.out) write.table(FM.out,file="Merged_Frequencies.txt",sep="\t",col.names=T,row.names=F,quote=F) write.table(CN.out,file="Merged_Counts.txt",sep="\t",col.names=T,row.names=F,quote=F) write.table(CS.out,file="Merged_ChiSq.txt",sep="\t",col.names=T,row.names=F,quote=F) write.table(OR.out,file="Merged_OddsRatio.txt",sep="\t",col.names=T,row.names=F,quote=F) } #' File Name Extraction #' #' Function to extract file path. #' @param x File name. #' @note This function is for internal use only. getFileName <- function(x) { tmpDir <- dirname(x) tmpName <- basename(x) if(basename(x)==x) { outName <- paste("Converted_",x,sep="") } else { outName <- paste(tmpDir,"/Converted_",tmpName,sep="") } outName <- gsub(".txt","",outName) return(outName) } #' Build Output Matrix for GL2Tab Conversion #' #' Initializes output matrix format for GL2Tab conversion #' @param System Character Genetic system HLA- or KIR #' @param Loci The loci for header names #' @note This function is for internal use only. Build.Matrix <- function(System,Loci) { Loci.Grp <- rep(Loci,each=2) if(System=="HLA-") { Out <- mat.or.vec(nr=1,nc=length(Loci.Grp)+1) ; colnames(Out) <- c(Loci.Grp,"DR.HapFlag") } else { Out <- mat.or.vec(nr=1,nc=length(Loci.Grp)) ; colnames(Out) <- Loci.Grp } colnames(Out)[seq(1,length(Loci.Grp),by=2)] <- paste(Loci,"_1",sep="") colnames(Out)[seq(2,length(Loci.Grp),by=2)] <- paste(Loci,"_2",sep="") return(Out) } #' Tabular Data Locus Format Tool #' #' Correctly orders the expanded GL string #' @param x Single row of converted GL string #' @param Order Single row data frame for mapping converted GL strings #' @note This function is for internal use only. Format.Tab <- function(x,Order) { Order[,match(colnames(x),colnames(Order))] <- x return(Order) } #' Ambiguous Alleles Locus Name Formatting #' #' Remove or Append Locus name from/to allele in an ambiguous allele string #' @param x Allele String #' @param Type String specifying whether to strip ('off') or append ('on') locus prefix #' @note This function is for internal use only. Format.Allele <- function(x,Type) { if(Type=="off") { if(grepl("/",x)) { tmp <- strsplit(unlist(strsplit(x,"/")),"\\*") Fix <- paste(unlist(lapply(tmp,"[",1)[1]), paste(unlist(lapply(tmp,"[",2)),collapse="/"), sep="*") } else { Fix <- x } } if(Type=="on"){ if(grepl("/",x)) { Locus <- unlist(strsplit(x,"\\*"))[1] Fix <- paste( paste( Locus,unlist(strsplit(unlist(strsplit(x,"\\*"))[2],"/")) ,sep="*") ,collapse="/") } else { Fix <- x } } return(Fix) } #' Append Genetic System Locus Designation to Allele String #' #' Adds genetic system (HLA/KIR) to each allele name #' @param x Vector Column genotypes to append #' @param df.name String SystemLocus name for each allele. #' @note This function is for internal use only. Append.System <- function(x,df.name) { getAllele <- which(x!="") x[getAllele] <- paste(df.name,x[getAllele],sep="*") return(x) } <file_sep>#' Genotype List String Conversion #' #' Main Workhorse wrapper for cross converting columnar table to GL string representaion. #' @param Data String File name or R Data Frame. #' @param Convert String Direction for conversion. #' @param File.Output String Type of File.Output. #' @param System String Genetic system (HLA or KIR) of the data being converted #' @param HZY.Red Logical Reduction of homozygote genotypes to single allele. #' @param DRB345.Check Logical Check DR haplotypes for consistency and flag unusual haplotypes. #' @param Strip.Prefix Logical Should System/Locus prefixes be stripped from table data. #' @param Abs.Fill Logical Should absent loci special designations be used. #' @param Cores.Lim Integer How many cores can be used. GLSconvert <- function(Data,Convert,File.Output="txt",System="HLA",HZY.Red=FALSE,DRB345.Check=FALSE,Strip.Prefix=TRUE,Abs.Fill=FALSE,Cores.Lim=1L) { # Check Parameters if( missing(Data) ) { Err.Log(FALSE,"P.Missing","Data") ; stop("Conversion Stopped.",call.=FALSE) } if( missing(Convert) ) { Err.Log(FALSE,"P.Missing","Convert") ; stop("Conversion Stopped.",call.=FALSE) } Check.Params.GLS(Convert,File.Output,System,HZY.Red,DRB345.Check,Cores.Lim) # MultiCore Limitations Cores <- Check.Cores(Cores.Lim,FALSE) # Set nomenclature system and Prefix stripping for pypop output if( System == "HLA" ) { System <- "HLA-" } if( File.Output == "pypop" ) { Strip.Prefix <- TRUE } # Read in Data and Set File.Output File Name if( is.character(Data) ) { if( file.exists(Data) ) { df <- read.table(file=Data,header=T,sep="\t", stringsAsFactors=FALSE, fill=T, comment.char = "#", strip.white=T, blank.lines.skip=T, colClasses="character") colnames(df) <- gsub("HLA.","HLA-",colnames(df)) fileName <- getFileName(Data) } else { Err.Log(FALSE,"File.Error",Data) ; stop("Conversion Stopped.",call.=FALSE) } } else { df <- Data ; fileName <- "Converted" } df[] <- lapply(df, as.character) df[is.na(df)] <- "" # Check Data Structure/Formatting Check.Data(df,System,Convert) # Run Data Conversion switch(Convert, GL2Tab = { data.out <- GL2Tab.wrapper(df,System,Strip.Prefix,Abs.Fill,Cores) } , Tab2GL = { data.out <- Tab2GL.wrapper(df,System,HZY.Red,Abs.Fill,Cores) } ) # Output DR.HapFlag for HLA data if( System=="HLA-" && !DRB345.Check ) { data.out <- data.out[,-grep('DR.HapFlag',colnames(data.out))] } # File Name Ouput Options switch(File.Output, txt = { fileName <- paste(fileName,".txt",sep="") }, csv = { fileName <- paste(fileName,".csv",sep="") }, pypop = { fileName <- paste(fileName,".pop",sep="") } ) # File.Output Final Converted File switch(File.Output, R = return(data.out), txt = write.table(data.out,file=fileName,sep="\t",quote=F,col.names=T,row.names=F), csv = write.csv(data.out,file=fileName,quote=F,col.names=T,row.names=F), pypop = write.table(data.out,file=fileName,sep="\t",quote=F,col.names=T,row.names=F) ) } <file_sep>#' Amino Acid Wrapper #' #' Wrapper function for amino acid analysis. #' @param loci Loci being analyzed. #' @param loci.ColNames The column names of the loci being analyzed. #' @param genos Genotype table. #' @param grp Case/Control or Phenotype groupings. #' @param Exon Exon(s)for targeted analysis. #' @param EPL Protein Alignment List. #' @param Cores Number of cores to use for analysis. #' @param Strict.Bin Logical specify if strict rare cell binning should be used in ChiSq test #' @param Output Data return carryover from main BIGDAWG function #' @param Verbose Summary display carryover from main BIGDAWG function #' @note This function is for internal BIGDAWG use only. A.wrapper <- function(loci,loci.ColNames,genos,grp,Exon,EPL,Cores,Strict.Bin,Output,Verbose) { cat("\n>>>> STARTING AMINO ACID LEVEL ANALYSIS...\n") # Define Lists for Per Loci Running Tallies AAlog <- list() AminoAcid.binned <- list() AminoAcid.freq <- list() overall.chisq <- list() ORtable <- list() Final_binned <- list() cat("Processing Locus: ") # Loop Through Loci for(x in 1:length(loci)) { # Get Locus Locus <- as.character(loci[x]) cat(Locus,".. ") # Read in Locus Alignment file for Locus specific alignments if( !missing(Exon) ) { Exon <- as.numeric(unique(unlist(Exon))) # Get ExonPtnAlign for Locus EPL.Locus <- EPL[[Locus]] RefExons <- EPL[["RefExons"]] E.Ptn.Starts <- EPL[["ExonPtnMap"]][[Locus]] EPL.Exon <- list() ; p <- NULL for (e in 1:length(Exon)) { getExon <- Exon[e] if( getExon %in% E.Ptn.Starts[,'Exon'] ) { if ( is.null(p) ) { p=1 } else { p = p + 1 } EPL.Exon[[p]] <- Exon.Filter(Locus,getExon,EPL.Locus,RefExons,E.Ptn.Starts) } else { Err.Log(Output,"Exon",Locus) stop("Analysis Stopped.",call. = F) } } ExonAlign <- Condense.EPL(EPL.Exon) #cbind(colnames(ExonAlign)) } else { ExonAlign <- EPL[[Locus]] } # Run Amino Acid Analysis A.list <- A(Locus,loci.ColNames,genos,grp,Strict.Bin,ExonAlign,Cores) # Build Output Lists AAlog[[Locus]] <- A.list[['log']] AminoAcid.binned[[Locus]] <- A.list[['binned']] overall.chisq[[Locus]] <- A.list[['chisq']] ORtable[[Locus]] <- A.list[['OR']] Final_binned[[Locus]] <- A.list[['table']] AminoAcid.freq[[Locus]] <- A.list[['freq']] }; rm(x) #locus loop cat("\n\n") Out <- list() Out[['AL']] <- do.call(rbind,AAlog) Out[['AB']] <- do.call(rbind,AminoAcid.binned) Out[['AF']] <- do.call(rbind,AminoAcid.freq) Out[['CS']] <- do.call(rbind,overall.chisq) Out[['OR']] <- do.call(rbind,ORtable) Out[['FB']] <- do.call(rbind,Final_binned) if(Output) { ## write to file write.table(Out[['AL']], file = "AA_log.txt", sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['AF']], file = "AA_freqs.txt", sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['AB']], file = "AA_binned.txt", sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['OR']], file = "AA_OR.txt", sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['CS']], file = "AA_chisq.txt", sep="\t", row.names = F, col.names=T, quote = F) write.table(Out[['FB']], file = "AA_table.txt", sep="\t", row.names = F, col.names=T, quote = F) } cat("> AMINO ACID ANALYSIS COMPLETED\n") if(Verbose){ cat("Significant Amino Acid Position(s):","\n") tmp <- do.call(rbind,overall.chisq); rownames(tmp) <- NULL tmp.sig <- tmp[which(tmp[,'sig']=="*"),]; rownames(tmp.sig) <- NULL if(nrow(tmp.sig)>0) { print(as.data.frame(tmp.sig),row.names=F) } } return(Out) } <file_sep>#' Hardy-Weinbery Wrapper #' #' Wrapper for main HWE function #' @param Tab Data frame of genotype files post processing. #' @param Output Data return carryover from main BIGDAWG function #' @param Verbose Summary display carryover from main BIGDAWG function #' @note This function is for internal BIGDAWG use only. HWE.wrapper <- function(Tab,Output,Verbose) { HWE <- HWE(Tab) if(Output) { sink("HWE.txt") print(HWE,quote=F) sink() } cat("\n> HARDY-WEINBERG ANALYSIS COMPLETED\n") if(Verbose) { cat("\nControls (Group 0):\n") HWE.con <- as.data.frame(HWE[['controls']]) print(HWE.con,row.names=F,quote=F) cat("\nCases (Group 1):\n") HWE.cas <- as.data.frame(HWE[['cases']]) print(HWE.cas,row.names=F,quote=F) cat("\n") } return(HWE) } <file_sep>#' Example HLA Dataset #' #' A synthetic dataset of HLA genotypes for using bigdawg. #' #' @format A data frame with 2000 rows and 14 variables "HLA_data" #' Exon protein alignments. #' #' Alignment object for use in the amino acid analysis. #' #' @format A list where each element is an alignment dataframe for a single locus. "ExonPtnList" <file_sep>#' File Fetcher #' #' Download Protein Alignment and Accessory Files #' @param Loci HLA Loci to be fetched. Limited Loci available. #' @note This function is for internal BIGDAWG use only. GetFiles <- function(Loci) { #downloads *_prot.txt alignment files #downloads hla_nom_p.txt file # Get P-Groups Files download.file("https://raw.githubusercontent.com/ANHIG/IMGTHLA/Latest/wmda/hla_nom_p.txt",destfile="hla_nom_p.txt",method="libcurl") # Get Release Version df <- readLines(con="hla_nom_p.txt", n=3) RD <- unlist(strsplit(df[2],split=" "))[3] RV <- paste(unlist(strsplit(df[3],split=" "))[3:4],collapse=" ") write.table(c(RD,RV),file="Release.txt",quote=F,col.names=F,row.names=F) # Get Locus Based Alignments for(i in 1:length(Loci)) { Locus <- Loci[i] FileName <- paste(Locus,"_prot.txt",sep="") URL <- paste("https://raw.githubusercontent.com/ANHIG/IMGTHLA/Latest/alignments/",FileName,sep="") download.file(URL,destfile = FileName,method="libcurl") } } #' HLA P group File Formatter #' #' Format the hla_nom_p.txt read table object for a specific locus. #' @param x P group object from read.table command. #' @param Locus Locus to be filtered on. #' @note This function is for internal BIGDAWG use only. PgrpFormat <- function(x,Locus) { # Identify for Locus ... change necessary if DRB x.sub <- x[which(x[,1]==Locus),] rownames(x.sub) <- NULL x.sub[,2] <- sapply(x.sub[,2],function(i) paste(paste(Locus,"*",unlist(strsplit(i,"/")),sep=""),collapse="/")) colnames(x.sub) <- c("Locus","Allele","P.Group") #Expand x.list <- list() for(i in 1:nrow(x.sub)) { if(grepl("/",x.sub[i,'Allele'],fixed=T)) { tmp <- unlist(strsplit(x.sub[i,'Allele'],"/")) tmp <- cbind(rep(Locus,length(tmp)),tmp,rep(x.sub[i,'P.Group'],length(tmp))) colnames(tmp) <- colnames(x.sub) x.list[[i]] <- tmp } else { x.list[[i]] <- x.sub[i,] } } x.list <- do.call(rbind,x.list) x.list <- x.list[order(x.list[,'Allele']),] rownames(x.list) <- NULL colnames(x.list) <- c("Locus","Allele","P.Group") return(x.list) } #' HLA P group Finder #' #' Identify P group for a given allele if exists. #' @param x Allele of interest. #' @param y Formatted P groups. #' @note This function is for internal BIGDAWG use only. PgrpExtract <- function(x,y) { getRow <- grep(x,y[,'Allele'],fixed=T) if(length(getRow)>=1) { if(length(getRow)>1) { getRow <- getRow[which(sapply(as.character(y[getRow,'Allele']),nchar)==nchar(x))] } return(as.character(y[getRow,'P.Group'])) } else { return("") } } #' Protein Exon Alignment Formatter #' #' Dynamically creates an alignmnet of Allele exons for Analysis. #' @param Locus Locus alignment to be formatted. #' @param RefTab Reference exon protein information for alignment formatting. #' @note This function is for internal BIGDAWG use only. ExonPtnAlign.Create <- function(Locus,RefTab) { ######################################################################### # Need to remove if DRB split into single locus files if(grepl("DRB",Locus)) { Locus.get <- "DRB" } else { Locus.get <- Locus } ######################################################################### AlignMatrix <- NULL; rm(AlignMatrix) #Read in P-Groups Pgrps <- read.table("hla_nom_p.txt",fill=T,header=F,sep=";",stringsAsFactors=F,strip.white=T,colClasses="character") Pgrps[,1] <- gsub("\\*","",Pgrps[,1]) Pgrps <- PgrpFormat(Pgrps,Locus) #Read in Alignment Name <- paste0(Locus.get,"_prot.txt") Align <- read.table(Name,fill=T,header=F,sep="\t",stringsAsFactors=F,strip.white=T,colClasses="character") #Trim Align <- as.matrix(Align[-nrow(Align),]) #Remove Footer #Begin Formatting Align <- as.matrix(Align[-grep("\\|",Align[,1]),1]) #Remove Pipes Align[,1] <- sapply(Align[,1],FUN=sub,pattern=" ",replacement="~") Align[,1] <- sapply(Align[,1],FUN=gsub,pattern=" ",replacement="") Align <- strsplit(Align[,1],"~") Align <- as.matrix(do.call(rbind,Align)) #Adjust rows to blank where Sequence column == Allele Name Align[which(Align[,1]==Align[,2]),2] <- "" # Remove Prot Numbering Headers Align <- Align[-which(Align[,1]=="Prot"),] # Get Unique Alleles Alleles <- unique(Align[,1]) # Loop Through and Build Alignment Block Block <- list() for(i in Alleles) { getRows <- which(Align[,1]==i) Block[[i]] <- paste(Align[getRows,2],collapse="") } Block <- cbind(Alleles,do.call(rbind,Block)) #Fill end gaps with * to make char lengths even Block.len <- max(as.numeric(sapply(Block[,2],FUN=nchar))) for( i in 1:nrow(Block) ) { Block.miss <- Block.len - nchar(Block[i,2]) if( Block.miss > 0 ) { Block[i,2] <- paste0(as.character(Block[i,2]), paste(rep(".",Block.miss),collapse="")) } }; rm(i) #Split Allele name into separate Locus and Allele, Send Back to Align object AlignAlleles <- do.call(rbind,strsplit(Block[,1],"[*]")) AlignAlleles <- cbind(AlignAlleles,apply(AlignAlleles,MARGIN=c(1,2),FUN=GetField,Res=2)[,2]) rownames(AlignAlleles) <- NULL Align <- cbind(AlignAlleles,Block) colnames(Align) <- c("Locus","Allele","Trimmed","FullName","Sequence") #Split Sub Alignment into composite elements and Extract relevant positions Align.split <- strsplit(Align[,'Sequence'],"") Align.split <- do.call(rbind,Align.split) AlignMatrix <- cbind(Align[,1:4],Align.split) rownames(AlignMatrix) <- NULL #Ensure Reference in Row 1 RefAllele <- paste(RefTab[which(RefTab[,'Locus']==Locus),'Reference.Locus'], RefTab[which(RefTab[,'Locus']==Locus),'Reference.Allele'], sep="*") if( !AlignMatrix[1,'FullName']==RefAllele ) { Align.tmp <- rbind(AlignMatrix[which(AlignMatrix[1,'Allele']==RefAllele),], AlignMatrix[-which(AlignMatrix[1,'Allele']==RefAllele),]) AlignMatrix <- Align.tmp rm(Align.tmp) } #Save Reference Row RefSeq <- AlignMatrix[1,] #Ensure Locus Specific Rows AlignMatrix <- AlignMatrix[which(AlignMatrix[,'Locus']==Locus),] #Rebind Reference if removed (only for DRB3, DRB4, and DRB5) if( !AlignMatrix[1,'FullName']==RefAllele ) { AlignMatrix <- rbind(RefSeq,AlignMatrix) } #Remove columns with no amino acids positions (only for DRB3, DRB4, and DRB5) #Count occurence of "." and compare to nrow of AlignMatrix rmCol <- which( apply(AlignMatrix,MARGIN=2, FUN=function(x) length(which(x=="."))) == nrow(AlignMatrix) ) if( length(rmCol)>0 ) { AlignMatrix <- AlignMatrix[,-rmCol] } #Propagate Consensus Positions for( i in 5:ncol(AlignMatrix) ) { x <- AlignMatrix[,i] x[which(x=="-")] <- x[1] AlignMatrix[,i] <- x } #Rename amino acid positions based on reference numbering #Deletions are named according to the preceding position with a .1,.2,etc. RefStart <- as.numeric(RefTab[which(RefTab[,'Locus']==Locus),'Reference.Start']) RefArray <- AlignMatrix[1,5:ncol(AlignMatrix)] Names <- NULL ; RefPos <- RefStart for(i in 1:length(RefArray) ) { if(RefArray[i]==".") { Names <- c(Names, paste0("Pos.",RefPos-1,".",Iteration) ) Iteration = Iteration + 1 } else { Iteration=1 Names <- c(Names, paste0("Pos.",RefPos)) RefPos <- RefPos + 1 if (RefPos==0) { RefPos <- 1 } } } colnames(AlignMatrix)[5:ncol(AlignMatrix)] <- Names rownames(AlignMatrix) <- NULL #Add Absent Allele (Absence due to lack of allele and not lack of typing information) AlignMatrix <- rbind(c(Locus,"00:00:00:00","00:00",paste(Locus,"*00:00:00:00",sep=""),rep("^",ncol(AlignMatrix)-4)), AlignMatrix) #Assign P groups AlignMatrix <- cbind(AlignMatrix, sapply(AlignMatrix[,'FullName'],PgrpExtract,y=Pgrps) ) colnames(AlignMatrix)[ncol(AlignMatrix)] <- "P.group" #Tally Unknowns as separate column AlignMatrix <- cbind(AlignMatrix, apply(AlignMatrix[,5:(ncol(AlignMatrix)-1)],MARGIN=1,FUN=function(x) length(which(unlist(grep("*",x,fixed=T))>0))) ) colnames(AlignMatrix)[ncol(AlignMatrix)] <- "Unknowns" #Tally Null Positions as separate column AlignMatrix <- cbind(AlignMatrix, apply(AlignMatrix[,5:(ncol(AlignMatrix)-2)],MARGIN=1,FUN=function(x) length(which(unlist(grep("-",x,fixed=T))>0))) ) colnames(AlignMatrix)[ncol(AlignMatrix)] <- "NullPositions" #Tally InDels AlignMatrix <- cbind(AlignMatrix, apply(AlignMatrix[,5:(ncol(AlignMatrix)-3)],MARGIN=1,FUN=function(x) length(which(unlist(grep(".",x,fixed=T))>0))) ) colnames(AlignMatrix)[ncol(AlignMatrix)] <- "InDels" rownames(AlignMatrix) <- NULL FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="") save(AlignMatrix,file=FileName) } #' Alignment Object Creator #' #' Create Object for Exon Protein Alignments. #' @param Loci Loci to be bundled. #' @param Release IMGT/HLA database release version. #' @param RefTab Data of reference exons used for protein alignment creation. #' @note This function is for internal BIGDAWG use only. AlignObj.Create <- function(Loci,Release,RefTab) { AlignMatrix <- NULL; rm(AlignMatrix) ExonPtnList <- list() for(i in 1:length(Loci)) { Locus <- Loci[i] FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="") load(FileName) #Loads AlignMatrix ExonPtnList[[Locus]] <- AlignMatrix } ExonPtnList[['Release.Version']] <- as.character(Release[2,]) ExonPtnList[['Release.Date']] <- as.character(Release[1,]) ExonPtnList[['RefExons']] <- RefTab save(ExonPtnList,file="ExonPtnAlign.obj") } #' Updated Alignment Object Creator #' #' Synthesize Object for Exon Protein Alignments. #' @param Loci Loci to be bundled. #' @param Release IMGT/HLA database release version. #' @param RefTab Data of reference exons used for protein alignment creation. #' @note This function is for internal BIGDAWG use only. AlignObj.Update <- function(Loci,Release,RefTab) { AlignMatrix <- NULL; rm(AlignMatrix) UpdatePtnList <- list() for(i in 1:length(Loci)) { Locus <- Loci[i] FileName <- paste("ExonPtnAlign_",Locus,".obj",sep="") load(FileName) #Loads AlignMatrix UpdatePtnList[[Locus]] <- AlignMatrix } UpdatePtnList[['Release.Version']] <- as.character(Release[2,]) UpdatePtnList[['Release.Date']] <- as.character(Release[1,]) UpdatePtnList[['RefExons']] <- RefTab save(UpdatePtnList,file="UpdatePtnAlign.RData") } <file_sep>#' Genotype Combination Maker #' #' Make data frame of possible genotype combinations #' @param x Number of alleles. #' @note This function is for internal BIGDAWG use only. makeComb <- function(x) { if(x >= 2) { tmp <- t(combn(x,2)) tmp <- rbind(tmp,t(matrix(rep(1:x,2),byrow=T,ncol=x))) tmp <- tmp[do.call(order, as.data.frame(tmp)),] return(tmp) } else ( return(NA) ) } #' Observed Frequency #' #' Get observed frequency of genotypes #' @param x Single genotype. #' @param genos.locus Locus genotypes. #' @note This function is for internal BIGDAWG use only. getObsFreq <- function(x,genos.locus) { if(x[1]==x[2]) { length(which(genos.locus[,1]==x[1] & genos.locus[,2]==x[2])) } else { return(sum(length(which(genos.locus[,1]==x[1] & genos.locus[,2]==x[2])), length(which(genos.locus[,1]==x[2] & genos.locus[,2]==x[1])))) } } #' Chi square matrices #' #' Chi Square contingency matrix builder with rare cell binning #' @param Locus Locus of interest. #' @param genos.sub Genotypes for locus of interest. #' @param Allele.Freq Allele frequencies. #' @param Allele.Combn Allele combinations. #' @note This function is for internal BIGDAWG use only. getCS.Mat <- function(Locus,genos.sub,Allele.Freq,Allele.Combn) { GTYPES <- Allele.Combn[[Locus]] if(!is.na(GTYPES)[1]) { nSID <- nrow(genos.sub) ColNames <- gsub(".1","",colnames(genos.sub),fixed=T) # column names genos.locus <- genos.sub[,which(ColNames==Locus)] freq <- Allele.Freq[[Locus]] GTYPES <- Allele.Combn[[Locus]] GTYPES <- lapply(seq_len(nrow(GTYPES)), function(x) GTYPES[x,]) #Expected Counts freq.Exp <- lapply(GTYPES,FUN=function(x) ifelse(x[1]==x[2],prod(freq[x])*nSID,2*prod(freq[x])*nSID)) #Observed Counts GTYPES <- lapply(GTYPES,FUN=function(x) names(freq[x])) freq.Obs <- lapply(GTYPES,getObsFreq,genos.locus=genos.locus) freq.mat <- cbind(do.call(rbind,GTYPES), do.call(rbind,freq.Obs), do.call(rbind,freq.Exp)) colnames(freq.mat) <- c("Allele.1","Allele.2","Obs","Exp") #bin rare cells freq.bin <- freq.mat[which(as.numeric(freq.mat[,'Exp'])<5),] freq.bin <- matrix(data=freq.bin,ncol=ncol(freq.mat),dimnames=dimnames(freq.mat)) if(nrow(freq.bin)>0) { freq.bin <- matrix(c("binned.1","binned.2",sum(as.numeric(freq.bin[,'Obs'])),sum(as.numeric(freq.bin[,'Exp']))), ncol=ncol(freq.bin), dimnames=dimnames(freq.bin)) } #Final Matrix for ChiSq if(nrow(freq.bin)>0) { freq.final <- rbind(freq.mat[which(as.numeric(freq.mat[,'Exp'])>=5),],freq.bin) } else { freq.final <- freq.mat } #Calculate (Obs - Exp)^2 / Exp if(nrow(freq.final)>1) { freq.final <- cbind(freq.final, apply(freq.final[,c('Obs','Exp')], MARGIN=1, FUN=function(x) ((as.numeric(x['Obs']) - as.numeric(x['Exp']))^2)/as.numeric(x['Exp']))) } else { freq.final <- cbind(freq.final,0) } colnames(freq.final)[ncol(freq.final)] <- "O-E2|E" return(freq.final) } else { return(NA) } } #' Chi square test statistic #' #' Calculate chi square test statistic #' @param Locus Locus of interest. #' @param Freq.Final Contingency Matrix getCS.Mat output. #' @note This function is for internal BIGDAWG use only. getCS.stat <- function(Locus,Freq.Final) { df <- Freq.Final[[Locus]] if(!is.null(nrow(df))) { return(sum(as.numeric(df[,'O-E2|E']))) } else { return(NA) } } #' Recompute number of alleles #' #' Using Freq.Final, recompute number of alleles #' @param x Locus specific contingency matrix getCS.Mat output. #' @note This function is for internal BIGDAWG use only. getAllele.Count <- function(x) { if(!is.null(nrow(x))) { return( length(unique(c(x[,'Allele.1'],x[,'Allele.2']))) ) } else { return(NA) } } #' Hardy Weinbergy Equilibrium Function #' #' This is the workhorse function for each group analysis. #' @param genos.sub data frame of genotype files post processing. #' @param loci list of loci. #' @param nloci number of loci in list #' @note This function is for internal BIGDAWG use only. HWE.ChiSq <- function(genos.sub,loci,nloci) { #Format genotypes df.1 <- data.frame(genos.sub[,seq(1,nloci*2,2)]) df.2 <- data.frame(genos.sub[,seq(2,nloci*2,2)]) colnames(df.2) <- colnames(df.1) df <- rbind(df.1,df.2) colnames(df) <- do.call(rbind,loci) rm(df.1,df.2) #Allele info Alleles <- lapply(loci,FUN=function(x) sort(unique(df[,x]))); names(Alleles) <- loci # unique allele names nAlleles <- lapply(loci,FUN=function(x) length(na.omit(unique(df[,x])))); names(nAlleles) <- loci # no. unique alleles nAlleles.tot <- lapply(loci,FUN=function(x) length(df[,x])); names(nAlleles.tot) <- loci # total no. alleles #Possible Genotypes Allele.Combn <- lapply(nAlleles,makeComb); names(Allele.Combn) <- loci #Get Allele Counts and Frequencies Allele.cnts <- lapply(loci,FUN=function(x) table(df[,x])); names(Allele.cnts) <- loci Allele.Freq <- lapply(loci,FUN=function(x) Allele.cnts[[x]]/nAlleles.tot[[x]]); names(Allele.Freq) <- loci #Get Observed and Expected Frequencies Matrix for genotypes Freq.Final <- lapply(loci,FUN=getCS.Mat,genos.sub=genos.sub,Allele.Freq=Allele.Freq,Allele.Combn=Allele.Combn) names(Freq.Final) <- loci #Calculate Chi Square Statistic for each Locus Freq.chisq <- lapply(loci,FUN=getCS.stat,Freq.Final=Freq.Final) names(Freq.chisq) <- loci #Recompute number of alleles and genotypes at each locus from binned contingency matrices (Freq.Final) nAlleles.bin <- lapply(Freq.Final,FUN=getAllele.Count) names(nAlleles.bin) <- loci nGenotypes.bin <- lapply(Freq.Final,nrow) names(nGenotypes.bin) <- loci nGenotypes.bin[which(as.numeric(lapply(nGenotypes.bin,FUN=is.null))==1)] <- NA #Get degrees of freedom for each locus #Alleles = a ; possible genotypes =g ; df = g - (a - 1) Allele.dof <- lapply(loci,FUN=function(x) nGenotypes.bin[[x]] - (nAlleles.bin[[x]] - 1) ); names(Allele.dof) <- loci #Get P.values from Chi Square distribution Freq.pvals <- lapply(loci,FUN=function(x) 1-pchisq(as.numeric(Freq.chisq[[x]]), as.numeric(Allele.dof[[x]]))) names(Freq.pvals) <- loci #Format Output Test.out <- cbind(loci, do.call(rbind,Freq.chisq), do.call(rbind,Allele.dof), do.call(rbind,Freq.pvals), rep('NS',nloci)) colnames(Test.out) <- c("Locus","X.square","df","p.value","sig") rownames(Test.out) <- NULL Test.out[which(as.numeric(Test.out[,'p.value'])<0.05),"sig"] <- "*" Test.out <- matrix(unlist(Test.out),ncol=ncol(Test.out),dimnames=dimnames(Test.out)) rownames(Test.out) <- NULL Test.out[,'X.square'] <- sapply(as.numeric(Test.out[,'X.square']),FUN=round,digits=4) Test.out[,'p.value'] <- sapply(as.numeric(Test.out[,'p.value']),FUN=function(x) format.pval(x)) #Flag for invalid degrees of freedom flagLoci <- which(as.numeric(Test.out[,'df'])<1) #Flag for invalid chi square matrices Freq.Flag <- lapply(loci,FUN=function(x) ifelse(nrow(Freq.Final[[x]])>2,0,1)) flagLoci <- unique(c(flagLoci,which(Freq.Flag==1))) #Flag for invalid chi square matrices flagLoci <- unique(c(flagLoci,which(is.na(Test.out[,'X.square'])))) if(length(flagLoci)>0){ Test.out[Test.out[,'Locus'] %in% unlist(loci[flagLoci]),2:ncol(Test.out)] <- "NCalc" } return(Test.out) }
1226e728232e48c238a97519a853b74e12660b3a
[ "Markdown", "R", "RMarkdown" ]
24
R
IgDAWG/BIGDAWG
b5efe5d64e5506dd2da49f22898eff2daf873b18
f14cd5bcfa9a3a0423ffd2c60b26e1d436273ce8
refs/heads/master
<repo_name>zhouyi10/Enable-Cloud-Exam<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/CustomRestTemplate.java package com.enableets.edu.enable.cloud.exam.manager.core; import com.enableets.edu.framework.core.util.RestTemplate; import com.enableets.edu.framework.core.util.StringUtils; import com.enableets.edu.module.service.core.Response; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.http.client.*; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * @author duffy_ding * @since 2020/08/27 */ @Slf4j public class CustomRestTemplate extends RestTemplate { public CustomRestTemplate(String clientId, String clientSecret) { super(); this.getInterceptors().add(new CustomClientHttpRequestInterceptor(clientId, clientSecret)); } public <R> R get(String url) { ParameterizedTypeReference<Response<R>> responseType = new ParameterizedTypeReference<Response<R>>() { }; R result = this.exchange(url, HttpMethod.GET, new HttpEntity<String>(null, getDefaultHeaders()), responseType).getBody().getData(); return result; } public <R> List<R> getList(String url) { ParameterizedTypeReference<Response<List<R>>> responseType = new ParameterizedTypeReference<Response<List<R>>>() { }; List<R> result = this.exchange(url, HttpMethod.GET, new HttpEntity<String>(null, getDefaultHeaders()), responseType).getBody().getData(); return result; } public <P, R> R post(String url, P param) { ParameterizedTypeReference<Response<R>> responseType = new ParameterizedTypeReference<Response<R>>() { }; R result = this.exchange(url, HttpMethod.POST, new HttpEntity<P>(param, getDefaultHeaders()), responseType).getBody().getData(); return result; } public <P, R> List<R> postList(String url, P param) { ParameterizedTypeReference<Response<List<R>>> responseType = new ParameterizedTypeReference<Response<List<R>>>() { }; List<R> result = this.exchange(url, HttpMethod.POST, new HttpEntity<P>(param, getDefaultHeaders()), responseType).getBody().getData(); return result; } private HttpHeaders getDefaultHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); return headers; } public static class CustomHttpRequestWrapper implements HttpRequest { private HttpRequest request; private URI uri; public CustomHttpRequestWrapper(HttpRequest request, URI uri) { this.request = request; this.uri = uri; } @Override public HttpMethod getMethod() { return request.getMethod(); } @Override public String getMethodValue() { return null; } @Override public URI getURI() { return uri; } @Override public HttpHeaders getHeaders() { return request.getHeaders(); } } public static class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { private String clientId; private String clientSecret; private ClientHttpRequestFactory factory; public CustomClientHttpRequestInterceptor(String clientId, String clientSecret) { this.clientId = clientId; this.clientSecret = clientSecret; factory = new SimpleClientHttpRequestFactory(); } @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { Map<String, String> params = collectSignParam(request.getURI(), body); String sign = sign(params); URI newUri = newUri(request.getURI(), params, sign); return execution.execute(new CustomHttpRequestWrapper(request, newUri), body); } public URI newUri(URI oldUri, Map<String, String> params, String sign) throws IOException { StringBuilder builder = new StringBuilder(); for (String key : params.keySet()) { if (!"data".equals(key) && StringUtils.isNotBlank(params.get(key))) { builder.append("&").append(key).append("=").append(params.get(key)); } } builder.append("&clientId=").append(clientId).append("&sign=").append(sign); URI newUri = null; try { newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), builder.substring(1), oldUri.getFragment()); } catch (URISyntaxException e) { log.error(e.getMessage(), e); } return newUri; } public String sign(Map<String, String> params) { String[] keyArray = params.keySet().toArray(new String[0]); Arrays.sort(keyArray); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(clientId); for(int i = 0; i < keyArray.length; ++i) { String key = keyArray[i]; if (StringUtils.isNotBlank(params.get(key))) { stringBuilder.append(key).append(params.get(key)); } } stringBuilder.append(clientSecret); try { return DigestUtils.sha1Hex(stringBuilder.toString().getBytes("UTF-8")).toUpperCase(); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); return null; } } public Map<String, String> collectSignParam(URI uri, byte[] body) { Map<String, String> params = new HashMap(); if (body != null && body.length > 0) { try { String bodystr = new String(body, "UTF-8"); params.put("data", bodystr); } catch (UnsupportedEncodingException e) { params.put("data", new String(body)); } } String query = uri.getQuery(); if (StringUtils.isNotBlank(uri.getQuery())) { List<String> queries = Arrays.asList(uri.getQuery().split("&")); Collections.reverse(queries); for (String paramStr : queries) { String[] split = paramStr.split("="); if (split.length < 2 || StringUtils.isBlank(split[1])){ continue; } params.put(split[0], split[1]); } } params.put("timestamp", String.valueOf(System.currentTimeMillis())); return params; } } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/CommFun.java package com.enableets.edu.enable.cloud.exam.manager.core; import com.enableets.edu.sdk.school3.dto.UserIdentityDTO; import java.util.Random; /** * 公共方法 * @author <EMAIL> * @since 2018/3/22 */ public class CommFun { /** * 随机生成子目录 */ public static String randDir(int level) { final String allChar = "0123456789abcdefghijklmnopqrstuvwxyz"; StringBuffer path = new StringBuffer(); Random random = new Random(); for (int i = 0; i < level; i++) { String p = String.valueOf(allChar.charAt(random.nextInt(allChar.length()))); if ("".equals(path.toString())) path.append(p); else { path.append("/" + p); } } Long time = System.currentTimeMillis(); path.append("/"+time); return path.toString(); } public static String randStr(){ final String allChar = "0123456789abcdefghijklmnopqrstuvwxyz"; StringBuffer path = new StringBuffer(); Random random = new Random(); for (int i = 0; i < 5; i++) { path.append(String.valueOf(allChar.charAt(random.nextInt(allChar.length())))); } Long time = System.currentTimeMillis(); path.append(time); return path.toString(); } /** * 判断是否是老师角色 * @param userIdentity * @return */ public static boolean isTeacher(UserIdentityDTO userIdentity){ return isContians(userIdentity.getIdentities(),Constants.TEACHER_IDENTITY_CODE); } /** * 判断是否是学生角色 * @param userIdentity * @return */ public static boolean isStudent(UserIdentityDTO userIdentity){ return isContians(userIdentity.getIdentities(),Constants.STUDENT_IDENTITY_CODE); } /** * 判断是否是管理员角色 * @param userIdentity * @return */ public static boolean isAdmin(UserIdentityDTO userIdentity){ return isContians(userIdentity.getIdentities(),Constants.ADMIN_IDENTITY_CODE); } private static boolean isContians(String[] arr,String key){ if(arr == null || arr.length==0) return false; for(String str : arr){ if(str.equals(key)){ return true; } } return false; } public static String getSatgeCodeByGradeCode(String gradeCode){ if(gradeCode.indexOf("21")==0) return "2"; else if(gradeCode.indexOf("31")==0) return "3"; else if(gradeCode.indexOf("34")==0) return "4"; return ""; } } <file_sep>/Exam Manager/src/main/resources/static/custom/cloudexam/js/paging/lang/en_US.js var $lang={ "prev_page" : "Previous page", "next_page" : "Next page", "first_page" : "Home page", "last_page" : "Last page", "go_to" : "Go to", "page_num" : "Page" }<file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamDictionaryDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.po.ExamDictionaryPO; import com.enableets.edu.framework.core.dao.BaseDao; import java.util.List; import java.util.Map; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 字典DAO */ public interface ExamDictionaryDAO extends BaseDao<ExamDictionaryPO> { /** * 查询字典数据 * @param condition * @return */ List<ExamDictionaryPO> query(Map<String, Object> condition); } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/ExamDetailsMarkAssigneeVO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @author <EMAIL> * @since 2020/05/21 */ @ApiModel @JsonIgnoreProperties(ignoreUnknown = true) public class ExamDetailsMarkAssigneeVO { /** * 考试明细标识 */ @ApiModelProperty(value = "考试明细标识") private Long examDetailsId; /** * 批阅者的userId */ @ApiModelProperty(value = "批阅者的userId") private String userId; /** * classId */ @ApiModelProperty(value = "班级标识") private String classId; /** * @return the examDetailsId */ public Long getExamDetailsId() { return examDetailsId; } /** * @param examDetailsId the examDetailsId to set */ public void setExamDetailsId(Long examDetailsId) { this.examDetailsId = examDetailsId; } /** * @return the userId */ public String getUserId() { return userId; } /** * @param userId the userId to set */ public void setUserId(String userId) { this.userId = userId; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/ExamStatisticsResultV2VO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import io.swagger.annotations.ApiModelProperty; import java.util.Date; /** * 查询考试详情结果信息 * @author <EMAIL> * @since 2020/9/18 */ public class ExamStatisticsResultV2VO { /** * 总分 */ private Float totalScore; /** * 考试明细标识 */ private Long examDetailsId; /** * 考试标识 */ private Long examId; /** * 年级编码 */ private String gradeCode; /** * 年级名称 */ private String gradeName; /** * 学期名称 */ private String termName; /** * 考试类别 */ private String name; /** * 班级标识 */ private String classId; /** * 班级名称 */ private String className; /** * 学科代码 */ private String subjectCode; /** * 学科名称 */ private String subjectName; /** * 课程标识 */ private String courseId; /** * 课程名称 */ private String courseName; /** * 创建者 */ private String creator; /** * 创建时间 */ private Date createTime; /** * 修改者 */ private String updator; /** * 修改时间 */ private Date updateTime; /** * 学校id */ private String schoolId; /** * 学期id */ private String termId; @ApiModelProperty(value = "任务信息") private ExamDetailsStepTaskInfoVO stepTaskInfo; private Integer offset; private Integer rows; /** * 发布状态 0未发布 1已发布 */ private String publishStatus; /** * 考试类别 */ private String typeName; /** * 考试类型 */ private String type; public Float getTotalScore() { return totalScore; } public void setTotalScore(Float totalScore) { this.totalScore = totalScore; } public Long getExamDetailsId() { return examDetailsId; } public void setExamDetailsId(Long examDetailsId) { this.examDetailsId = examDetailsId; } public Long getExamId() { return examId; } public void setExamId(Long examId) { this.examId = examId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getTermName() { return termName; } public void setTermName(String termName) { this.termName = termName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public ExamDetailsStepTaskInfoVO getStepTaskInfo() { return stepTaskInfo; } public void setStepTaskInfo(ExamDetailsStepTaskInfoVO stepTaskInfo) { this.stepTaskInfo = stepTaskInfo; } public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } public String getPublishStatus() { return publishStatus; } public void setPublishStatus(String publishStatus) { this.publishStatus = publishStatus; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getType() { return type; } public void setType(String type) { this.type = type; } } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/impl/DefaultExamResultInfoService.java package com.enableets.edu.enable.cloud.sdk.exam.impl; import com.enableets.edu.enable.cloud.sdk.exam.IExamResultInfoService; import com.enableets.edu.enable.cloud.sdk.exam.dto.AddExamResultInfoDTO; import com.enableets.edu.enable.cloud.sdk.exam.dto.QueryExamResultInfoResultDTO; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamResultInfoServiceFeignClient; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; public class DefaultExamResultInfoService implements IExamResultInfoService { @Autowired private IExamResultInfoServiceFeignClient examResultInfoServiceFeignClient; public DefaultExamResultInfoService(IExamResultInfoServiceFeignClient examResultInfoServiceFeignClient) { this.examResultInfoServiceFeignClient=examResultInfoServiceFeignClient; } /** * 添加/修改学生成绩 * @param resultInfoDTOList * @return */ @Override public Boolean addOrEditExamResultInfo(List<AddExamResultInfoDTO> resultInfoDTOList) { return examResultInfoServiceFeignClient.addOrEditExamResultInfo(resultInfoDTOList).getData(); } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamDetailsStepTaskInfoDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.po.ExamDetailsStepTaskInfoPO; import com.enableets.edu.framework.core.dao.BaseDao; import java.util.List; /** * @author <EMAIL> * @since 2020/05/21 */ public interface ExamDetailsStepTaskInfoDAO extends BaseDao<ExamDetailsStepTaskInfoPO> { public void batchInsert(List<ExamDetailsStepTaskInfoPO> stepTaskInfoPOList); } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/PaperInfoVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import lombok.Data; import org.dozer.Mapping; import java.util.List; /** * @author <EMAIL> * @since 2020/08/03 **/ @Data public class PaperInfoVO { /** Paper ID */ private String paperId; /** Paper Name */ private String name; /***/ private String paperType; /** Stage Info */ @Mapping(value = "stage.code") private String stageCode; @Mapping(value = "stage.name") private String stageName; /** Grade Info */ @Mapping(value = "grade.code") private String gradeCode; @Mapping(value = "grade.name") private String gradeName; /** Subject Info */ @Mapping(value = "subject.code") private String subjectCode; @Mapping(value = "subject.name") private String subjectName; @Mapping(value = "materialVersion.id") private String materialVersion; private List<String> searchCodes; /** Paper Total Score */ private Float totalPoints; /** Paper Nodes */ private List<PaperNodeInfoVO> nodes; /**Knowledge */ private List<KnowledgeInfoVO> knowledges; /** User ID*/ private String userId; /** */ private List<FileInfoVO> files; /** */ private AddAnswerCardInfoVO answerCard; /***/ private String opener; /***/ private String subtitle; private String examStypeinfoPO; private String sumBigtopic; } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/bo/ExamInfoV2BO.java package com.enableets.edu.enable.cloud.exam.framework.bo; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @Auther: yvonne_yu * @Date: 20200521 * @Description: 考试信息BO */ @Data @Accessors(chain = true) public class ExamInfoV2BO implements Serializable { /** * */ private static final long serialVersionUID = 3241898777959719060L; /** * 考试标识 */ private Long examId; /** * 考试名称 */ private String name; /** * 考试类型 */ private String type; /** * 考试类型名称 */ private String typeName; /** * 学校标识 */ private String schoolId; /** * 学校编码 */ private String schoolCode; /** * 学年 */ private String schoolYear; /** * 不包含的学期标识 */ private String excludeTermId; /** * 学期标识 */ private String termId; /** * 学期名称 */ private String termName; /** * 学段 */ private String gradeStage; private String gradeCode; private String gradeName; /** exam publish status, default 0, if all details is published, it's 1, else 2 */ private String publishStatus; /** * 创建者 */ private String creator; /** * 创建时间 */ private Date createTime; /** * 修改者 */ private String updator; /** * 修改时间 */ private Date updateTime; /** * 班级 */ private List<IdNameMapBO> classes; private List<ExamDetailsInfoV2BO> details; /** * 笔数 */ private Integer rows; /** * 当前页 */ private Integer offset; } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/ExamLevelInfoVO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 分数等级VO */ public class ExamLevelInfoVO { /** * 等级标识 */ private Integer levelId; /** * 等级名称 */ private String levelName; /** * 学校标识 */ private String schoolId; /** * 学校编码 */ private String schoolCode; /** * 年级编码 */ private String gradeCode; /** * 最低分 */ private Float minPoint; /** * 最高分 */ private Float maxPoint; /** * 顺序 */ private Integer sequence; public Integer getLevelId() { return levelId; } public void setLevelId(Integer levelId) { this.levelId = levelId; } public String getLevelName() { return levelName; } public void setLevelName(String levelName) { this.levelName = levelName; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getSchoolCode() { return schoolCode; } public void setSchoolCode(String schoolCode) { this.schoolCode = schoolCode; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public Float getMinPoint() { return minPoint; } public void setMinPoint(Float minPoint) { this.minPoint = minPoint; } public Float getMaxPoint() { return maxPoint; } public void setMaxPoint(Float maxPoint) { this.maxPoint = maxPoint; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/core/ErrorConstants.java package com.enableets.edu.enable.cloud.exam.framework.core; /** * 定义school微服务错误码和错误信息 * @author <EMAIL> * @since 2017/08/16 */ public class ErrorConstants { /** * 错误码格式模版-系统级(1)、服务级(2)+模块编码(2位数字)+模块错误编码(2位数字) */ public static final String ERROR_CODE_FORMAT = "%s%s%s"; /** * 系统级错误编码 */ public static final String SYSTEM_ERROR = "1"; /** * 服务级错误编码 */ public static final String SERVICE_ERROR = "2"; /** * 必要参数缺失错误码 */ public static final String ERROR_CODE_REQUIRED_PARAMETER_MISSING = String.format(ERROR_CODE_FORMAT, SYSTEM_ERROR, "00", "01"); /** * 日期格式错误码 */ public static final String ERROR_CODE_DATE_TIME_FORMAT_ERROR = String.format(ERROR_CODE_FORMAT, SYSTEM_ERROR, "00", "02"); /** 试卷不存在 */ public static final String ERROR_CODE_EXAM_NOT_EXISTS = String.format(ERROR_CODE_FORMAT, SERVICE_ERROR, Constants.MODULE_EXAM, "01"); public static final String ERROR_MESSAGE_EXAM_NOT_EXISTS = String.format(ErrorMsgTemplate.ERROR_MESSAGE_NOT_EXISTS_FORMAT, "试卷信息"); } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/bo/ExamPointInputSettingBO.java package com.enableets.edu.enable.cloud.exam.framework.bo; import lombok.Data; import lombok.experimental.Accessors; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 录分老师安排BO */ @Data @Accessors(chain = true) public class ExamPointInputSettingBO { /** * 考试明细标识 */ private Long examDetailsId; /** * 老师标识 */ private String userId; /** * 老师名称 */ private String fullName; private String type; private String classId; private String className; private String gradeCode; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/StageInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author <EMAIL> * @since 2020/08/10 **/ @Data @NoArgsConstructor @AllArgsConstructor public class StageInfoBO { private String stageCode; private String stageName; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWPaperHeadBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; /** * 试卷头部信息 * * @author <EMAIL> * @since 2020/09/01 13:48 **/ @Data public class XKWPaperHeadBO { /* 2020-2021学年度???学校8月月考卷 */ private String mainTitle; /* 1.答题前填写好自己的姓名、班级、考号等信息\\r\\n2.请将答案正确填写在答题卡上 */ private String notice; /* 学校:___________姓名:___________班级:___________考号:___________ */ private String studentInput; /* 试卷副标题 */ private String subTitle; /* 考试范围:xxx;考试时间:100分钟;命题人:xxx */ private String testInfo; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWCategoriesBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; import java.util.List; /** * 知识点目录 * * @author <EMAIL> * @since 2020/09/01 15:17 **/ @Data public class XKWCategoriesBO { List<XKWIdNameBO> categories; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/service/XKWService.java package com.enableets.edu.enable.cloud.exam.manager.paper.service; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.http.HtmlUtil; import com.enableets.edu.enable.cloud.exam.manager.bo.CodeNameMapBO; import com.enableets.edu.enable.cloud.exam.manager.bo.xkw.*; import com.enableets.edu.enable.cloud.exam.manager.core.BaseInfoManager; import com.enableets.edu.enable.cloud.exam.manager.core.Constants; import com.enableets.edu.enable.cloud.exam.manager.core.CustomRestTemplate; import com.enableets.edu.enable.cloud.exam.manager.core.PaperConfigReader; import com.enableets.edu.enable.cloud.exam.manager.utils.XkwBaseInfoTransformUtils; import com.enableets.edu.framework.core.util.BeanUtils; import com.enableets.edu.sdk.content.dto.ContentFileInfoDTO; import com.enableets.edu.sdk.content.dto.ContentInfoDTO; import com.enableets.edu.sdk.content.service.IContentInfoService; import com.enableets.edu.sdk.pakage.ppr.dto.*; import com.enableets.edu.sdk.pakage.ppr.service.IPPRPaperInfoService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.jsoup.Jsoup; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.util.*; /** * 学科网服务 * * @author <EMAIL> * @since 2020/09/02 09:56 **/ @Service @Slf4j public class XKWService { private static final String QUES_BODY_PREFIX = "【题文】"; private static final String QUES_ANSWER_PREFIX = "【答案】"; private static final String QUES_ANSWER_ANALYSIS = "【解析】"; private static final String SOURCE_CODE = "_xkw_cc_paper"; private static final String SOURCE_NAME = "_xkw_cc_paper"; private final static Logger LOGGER = LoggerFactory.getLogger(XKWService.class); @Autowired private IPPRPaperInfoService pprPaperInfoServiceSDK; @Autowired private IContentInfoService contentInfoServiceSDK; @Autowired private PaperConfigReader paperConfigReader; @Autowired private BaseInfoManager baseInfoManager; public String get(String paperId, String openId){ CloseableHttpClient httpClient = HttpClients.createDefault(); String paperUrl = paperConfigReader.getGetPaperUrl().replace("{openId}", openId).replace("{paperId}", paperId); HttpGet httpGet = new HttpGet(paperUrl); String key = new StringBuilder(paperConfigReader.getXkwAppId()).append(":").append(paperConfigReader.getXkwSecret()).toString(); try { String code = Base64.getEncoder().encodeToString(key.getBytes("UTF-8")); httpGet.setHeader("Authorization", "Basic " + code); CloseableHttpResponse execute = httpClient.execute(httpGet); return EntityUtils.toString(execute.getEntity()); } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } return null; } public String add(XKWPaperBO xkwPaper) { QueryPaperInfoResultDTO paper = pprPaperInfoServiceSDK.add(buildPaper(xkwPaper)); //推动到账号所在的场域 String fieldDomainUrl = baseInfoManager.getAccountOriginDomain(); if (StringUtils.isBlank(fieldDomainUrl)){ LOGGER.error("Field Domain Url Not Found!", "(UserId="+baseInfoManager.getUserId()+")Field Domain Url Not Found!"); }else{ ContentInfoDTO content = contentInfoServiceSDK.get(paper.getPaperId()).getData(); String fileId = null; String paperUrl = null; if (CollectionUtils.isNotEmpty(content.getFileList())){ for (ContentFileInfoDTO contentFileInfoDTO : content.getFileList()) { if (contentFileInfoDTO.getFileExt().toLowerCase().equals("paper")){ fileId = contentFileInfoDTO.getFileId(); paperUrl = contentFileInfoDTO.getUrl(); break; } } } if (StringUtils.isBlank(fileId) || StringUtils.isBlank(paperUrl)) { LOGGER.error(".paper File Not Found!", "Paper("+paper.getPaperId()+") .paper File Not Found!"); } try { //String translationUrl = "http://192.168.118.12:9116" + "/microservice/paper/transform/v2/transfrom"; String translationUrl = fieldDomainUrl + "/microservice/paper/transform/v2/transfrom"; Map<String, Object> params = new HashMap<>(); params.put("contentId", paper.getPaperId()); params.put("typeCode", Constants.DICTIONARY_CONTENT_TYPE_PAPER); params.put("url", paperUrl); params.put("fileId", fileId); params.put("providerCode", Constants.PROVIDER_CODE_DEFAULT); params.put("userId", baseInfoManager.getUserId()); params.put("sourceCode", SOURCE_CODE); params.put("sourceName", SOURCE_NAME); CustomRestTemplate restTemplate = new CustomRestTemplate(paperConfigReader.getSsoClientId(), paperConfigReader.getSsoSecret()); restTemplate.post(translationUrl, params); }catch (Exception e){ LOGGER.error("Push Domain["+fieldDomainUrl+"] fail!", e); } } return fieldDomainUrl; } public AddPaperInfoDTO buildPaper(XKWPaperBO xkwPaper) { if (ObjectUtil.isNull(xkwPaper.getHead()) || CollectionUtil.isEmpty(xkwPaper.getBody())) return null; AddPaperInfoDTO paper = new AddPaperInfoDTO(); buildBaseInfo(xkwPaper, paper); buildPart(xkwPaper, paper); return paper; } private void buildBaseInfo(XKWPaperBO xkwPaper, AddPaperInfoDTO paper) { paper.setProviderCode(Constants.PROVIDER_CODE_DEFAULT); String name = ""; if (ObjectUtil.isNotNull(xkwPaper.getHead())) name = xkwPaper.getHead().getMainTitle(); paper.setName(name); if (ObjectUtil.isNotNull(xkwPaper.getBankId())) { int bankId = xkwPaper.getBankId(); paper.setSubject(XkwBaseInfoTransformUtils.getSubjectByBankId(bankId)); paper.setStage(XkwBaseInfoTransformUtils.getStageByBankId(bankId)); } } private void buildPart(XKWPaperBO xkwPaper, AddPaperInfoDTO paper) { List<PaperNodeInfoDTO> nodes = new ArrayList<>(); paper.setNodes(nodes); CodeNameMapDTO subject = paper.getSubject(); float totalPoints = 0f; for (XKWPartBO xkwPart : xkwPaper.getBody()) { PaperNodeInfoDTO partNode = creatNode(nodes, 1); Float points = 0f; String name = ""; String description = ""; if (ObjectUtil.isNotNull(xkwPart.getPartHead())) { name = xkwPart.getPartHead().getName(); description = xkwPart.getPartHead().getNote(); } partNode.setName(name); partNode.setDescription(description); for (XKWPartBodyBO partBody : xkwPart.getPartBody()) { // 大题 PaperNodeInfoDTO quesTypeNode = buildQuesType(partBody, nodes, subject); quesTypeNode.setParentNodeId(partNode.getNodeId()); points += quesTypeNode.getPoints(); } partNode.setPoints(points); totalPoints += points; } paper.setTotalPoints(totalPoints); // 获取最高年级 for (PaperNodeInfoDTO node : paper.getNodes()) { if (node.getLevel() >= 3 && node.getQuestion() != null && node.getQuestion().getGrade() != null) { if (paper.getGrade() == null) { paper.setGrade(node.getQuestion().getGrade()); } else { if (Integer.parseInt(paper.getGrade().getCode()) < Integer.parseInt(node.getQuestion().getGrade().getCode())) paper.setGrade(node.getQuestion().getGrade()); } } } } private PaperNodeInfoDTO buildQuesType(XKWPartBodyBO partBody, List<PaperNodeInfoDTO> nodes, CodeNameMapDTO subjectCN) { PaperNodeInfoDTO quesTypeNode = creatNode(nodes, 2); Float points = 0f; String name = ""; String description = ""; if (ObjectUtil.isNotNull(partBody.getType())) { name = partBody.getType().getName(); description = partBody.getType().getNote(); } quesTypeNode.setName(name); quesTypeNode.setDescription(description); for (XKWQuestionBO question : partBody.getQuestions()) { PaperNodeInfoDTO questionNode = buildQuestion(question, nodes, subjectCN); questionNode.setParentNodeId(quesTypeNode.getNodeId()); points += questionNode.getPoints(); } quesTypeNode.setPoints(points); return quesTypeNode; } private PaperNodeInfoDTO buildQuestion(XKWQuestionBO xkwQuestion, List<PaperNodeInfoDTO> nodes, CodeNameMapDTO subjectCN) { PaperNodeInfoDTO quesNode = creatNode(nodes, 3); PaperQuestionDTO question = new PaperQuestionDTO(); quesNode.setQuestion(question); question.setQuestionId(String.valueOf(xkwQuestion.getId())); // question.setProviderCode(Constants.PROVIDER_CODE_XKW); // question.setSource(Constants.XKW_QUESTION_SOURCE_CODE); question.setSubject(subjectCN); CodeNameMapDTO questionType = new CodeNameMapDTO(); if (ObjectUtil.isNotNull(xkwQuestion.getQuesType())) { questionType = XkwBaseInfoTransformUtils.getQuestionType(String.valueOf(xkwQuestion.getQuesType().getId())); } question.setType(questionType); QuestionStemInfoDTO stm = new QuestionStemInfoDTO(); question.setStem(stm); String quesBody = cleanPrefix(xkwQuestion.getQuesBody(), QUES_BODY_PREFIX); stm.setRichText(quesBody); if (StringUtils.isNotBlank(quesBody)) stm.setPlaintext(HtmlUtil.cleanHtmlTag(quesBody)); QuestionAnswerDTO answer = new QuestionAnswerDTO(); question.setAnswer(answer); String xkwQuesAnswer = cleanPrefix(xkwQuestion.getQuesAnswer(), QUES_ANSWER_PREFIX); answer.setLabel(xkwQuesAnswer); answer.setStrategy(xkwQuesAnswer); String analysis = cleanPrefix(xkwQuestion.getQuesParse(), QUES_ANSWER_ANALYSIS); answer.setAnalysis(analysis); CodeNameMapDTO grade = new CodeNameMapDTO(); CodeNameMapDTO stage = new CodeNameMapDTO(); if (CollectionUtil.isNotEmpty(xkwQuestion.getGrades()) && xkwQuestion.getGrades().size() > 0) { CodeNameMapDTO gradeTemp = null; XKWGradeBO xkwGradeBO = null; for (XKWGradeBO xkwGrade : xkwQuestion.getGrades()) { // 取最高年级 CodeNameMapDTO temp = XkwBaseInfoTransformUtils.getGrade(xkwGrade.getId()); if(gradeTemp == null || (Integer.parseInt(temp.getCode()) > Integer.parseInt(gradeTemp.getCode()))) { gradeTemp = temp; xkwGradeBO = xkwGrade; } } stage = XkwBaseInfoTransformUtils.getStage(xkwGradeBO.getStageId()); grade = gradeTemp; } question.setStage(stage); question.setGrade(grade); CodeNameMapDTO abilityCN = new CodeNameMapDTO(); if (ObjectUtil.isNotNull(xkwQuestion.getQuesAttribute())) { abilityCN.setCode(String.valueOf(xkwQuestion.getQuesAttribute().getId())); abilityCN.setName(xkwQuestion.getQuesAttribute().getName()); } question.setAbility(abilityCN); CodeNameMapDTO difficultyCN = new CodeNameMapDTO(); if (ObjectUtil.isNotNull(xkwQuestion.getQuesDiff())) difficultyCN = XkwBaseInfoTransformUtils.getDifficulty(String.valueOf(xkwQuestion.getQuesDiff().getId())); question.setDifficulty(difficultyCN); question.setQuestionNo(String.valueOf(xkwQuestion.getId())); List<QuestionKnowledgeInfoDTO> knowledgeList = new ArrayList<>(); if (CollectionUtil.isNotEmpty(xkwQuestion.getCategories())) { Map<String, QuestionKnowledgeInfoDTO> knowledgeMap = buildKnowledge(xkwQuestion.getCategories(), "XKW_ML_"); knowledgeList.addAll(new ArrayList<>(knowledgeMap.values())); } if (CollectionUtil.isNotEmpty(xkwQuestion.getChapters())) { Map<String, QuestionKnowledgeInfoDTO> knowledgeMap = buildKnowledge(xkwQuestion.getChapters(), "XKW_ZJ_"); knowledgeList.addAll(new ArrayList<>(knowledgeMap.values())); } question.setKnowledges(knowledgeList); /* 子题目 暂无数据*/ Float points = 1f; if (xkwQuestion.getQuesScore() != null && xkwQuestion.getQuesScore() > 0) points = xkwQuestion.getQuesScore(); if (CollectionUtil.isNotEmpty(xkwQuestion.getChildQues())) { int childNum = xkwQuestion.getChildQues().size(); points = 0f; float childPoint = 1f; if (xkwQuestion.getQuesScore() != null && xkwQuestion.getQuesScore() > 0) childPoint = xkwQuestion.getQuesScore()/childNum; /*List<QueryQuestionChildInfoResultDTO> childQues = new ArrayList<>(); for (int i = 0; i < childNum; i++) { XKWChildQuestionBO xkwChildQue = xkwQuestion.getChildQues().get(i); PaperNodeInfoBO childQueNode = buildChildQuestion(nodes, xkwChildQue, question); childQueNode.setParentId(quesNode.getNodeId()); childQueNode.setExternalNo(quesNode.getExternalNo() + "." + childQueNode.getInternalNo()); // 设置小题题号 childQueNode.setPoints(childPoint); QueryQuestionChildInfoResultDTO childQuestion = BeanUtils.convert(childQueNode.getQuestion(), QueryQuestionChildInfoResultDTO.class); if (childQuestion != null) { childQuestion.setPoints(childPoint); childQuestion.setSequencing(i+1); childQues.add(childQuestion); } points += childPoint; } question.setChildren(childQues);*/ question.setChildAmount(childNum); } else { if (("01, 02").contains(questionType.getCode())) { question.setOptions(buildOptions(quesBody)); } } question.setPoints(points); quesNode.setPoints(points); return quesNode; } private PaperNodeInfoDTO buildChildQuestion(List<PaperNodeInfoDTO> nodes, XKWChildQuestionBO childQue, PaperQuestionDTO parentQuestion) { PaperNodeInfoDTO node = creatNode(nodes, 4); PaperQuestionDTO question = BeanUtils.convert(parentQuestion, PaperQuestionDTO.class); question.setQuestionNo(parentQuestion.getQuestionNo() + "-" + node.getInternalNo()); question.setQuestionId(parentQuestion.getQuestionId() + "-" + node.getInternalNo()); node.setQuestion(question); QuestionStemInfoDTO stm = new QuestionStemInfoDTO(); question.setStem(stm); String childBody = cleanPrefix(childQue.getChildBody(), QUES_BODY_PREFIX); stm.setRichText(childBody); if (StringUtils.isNotBlank(childBody)) stm.setPlaintext(HtmlUtil.cleanHtmlTag(childBody)); QuestionAnswerDTO answer = new QuestionAnswerDTO(); question.setAnswer(answer); String childAnswer = cleanPrefix(childQue.getChildAnswer(), QUES_ANSWER_PREFIX); answer.setLabel(childAnswer); answer.setStrategy(childAnswer); List<QuestionOptionDTO> options = new ArrayList<>(); if ( question.getType()!=null && ("01, 02").contains(question.getType().getCode())) { options = buildOptions(childBody); } question.setOptions(options); return node; } private Map<String, QuestionKnowledgeInfoDTO> buildKnowledge(List<List<XKWIdNameBO>> xkwIdNameList, String tag) { Map<String, QuestionKnowledgeInfoDTO> knowledgeMap = new HashMap<>(); for (List<XKWIdNameBO> chapter : xkwIdNameList) { if (CollectionUtil.isNotEmpty(chapter) && chapter.size() >= 2) { CodeNameMapBO xkwMaterialVersion = new CodeNameMapBO(tag + chapter.get(0).getId(), chapter.get(0).getName()); StringBuilder searchCode = new StringBuilder(); for (XKWIdNameBO xkwKnowledge : chapter) { if (xkwKnowledge == null) continue; QuestionKnowledgeInfoDTO knowledgeInfo = new QuestionKnowledgeInfoDTO(); String id = tag + xkwKnowledge.getId(); knowledgeMap.put(id, knowledgeInfo); knowledgeInfo.setKnowledgeId(id); knowledgeInfo.setKnowledgeName(xkwKnowledge.getName()); knowledgeInfo.setMaterialVersion(xkwMaterialVersion.getCode()); knowledgeInfo.setMaterialVersionName(xkwMaterialVersion.getName()); searchCode.append(id).append("-"); knowledgeInfo.setSearchCode(searchCode.substring(0, searchCode.length() - 1)); } } } return knowledgeMap; } private String cleanPrefix(String body, String prefixTag) { if (StringUtils.isNotBlank(body) && body.contains(prefixTag)) { String[] split = body.split(prefixTag); if (split.length > 1) { body = split[1]; } } return body; } public List<QuestionOptionDTO> buildOptions(String quesBody) { // 从题干中获取选项 List<QuestionOptionDTO> options = new ArrayList<>(); int optionSize = 4; /*if (StringUtils.isNotBlank(quesBody)) { Document document = Jsoup.parse(quesBody); Elements optionsTable = document.getElementsByAttributeValue("name", "optionsTable"); Elements optionTd = optionsTable.get(0).select("td"); optionSize = optionTd.size(); } for (int i = 0; i < optionSize; i++) { QuestionOptionDTO option = new QuestionOptionDTO(null, String.valueOf((char) (65 + i)), "", i+""); options.add(option); }*/ return options; } private PaperNodeInfoDTO creatNode(List<PaperNodeInfoDTO> nodes, int level) { PaperNodeInfoDTO node = new PaperNodeInfoDTO(); node.setLevel(level); long nodeId = 1; int sequencing = 1; int internalNo = 1; String externalNo = "1"; if (CollectionUtil.isNotEmpty(nodes) && nodes.size() > 0) { PaperNodeInfoDTO lastNode = nodes.get(nodes.size()-1); nodeId += lastNode.getNodeId(); sequencing += lastNode.getSequencing(); boolean isResetInternalNo = false; // 第二卷重置题号 if (level != lastNode.getLevel()) { lastNode = null; for (int i = nodes.size()-1; i >=0 ; i--) { PaperNodeInfoDTO nodeTemp = nodes.get(i); if (nodeTemp.getLevel() == 1 && level == 3) { isResetInternalNo = true; } if (nodeTemp.getLevel() == level) { lastNode = nodeTemp; break; } } } if (lastNode!= null && lastNode.getLevel() == level) { if (level != 3 || !isResetInternalNo) { internalNo += lastNode.getInternalNo(); externalNo = String.valueOf(internalNo); } } } node.setNodeId(nodeId); node.setSequencing(sequencing); node.setInternalNo(internalNo); node.setExternalNo(externalNo); nodes.add(node); return node; } } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/dto/QueryExamInfoDTO.java package com.enableets.edu.enable.cloud.sdk.exam.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import lombok.experimental.Accessors; /** * @author duffy_ding * @since 2020/07/29 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Data @Accessors(chain = true) public class QueryExamInfoDTO { /** school id */ private String schoolId; /** term id */ private String termId; /** user id */ private String userId; /** exam name */ private String examName; /** class id */ private String classId; /** course id */ private String courseId; /** offset */ private Integer offset; /** rows */ private Integer rows; } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/webUploader/UploadFileUtils.js /** * upload file utils */ (function() { window.UploadFileUtils = {}; })(); /** default param */ (function(utils){ var defaultParam = { // swf path swf: '../webUploader/Uploader.swf', // server url server: '', // the btn pick: null, // no zip resize: false, autoMd5: true, events: {} }; utils._options = { param: defaultParam }; utils.global = function(obj) { if (!utils.checkEnv()) return; if (obj == undefined) return $.extend({}, utils._options.param); if (typeof obj != 'object') return utils._options.param[obj]; $.extend(utils._options.param, obj); if (obj.uploadUrl) { utils._options.param.server = obj.uploadUrl; } }; })(UploadFileUtils); /** error code */ (function(utils){ var errorCode = { FailedWhenMd5: 'md5', FailedWhenCheckExist: 'checkFileExist', FailedWhenGetToken: 'getToken', FailedWhenUpload: 'upload', }; utils.ErrorCode = errorCode; })(UploadFileUtils); /** check environment */ (function(utils) { utils.checkEnv = function() { if (typeof $ == 'undefined') { console.error("no dependency to jquery or zepto!"); return false; } if (typeof WebUploader == "undefined") { console.error("no dependency to webUploader!"); return false; } return true; } })(UploadFileUtils); (function(utils){ /** * check the file exists * @param fileName file name * @param md5 md5 * @param checkUrl url * @returns {*} */ function checkExist(fileName, md5, checkUrl) { var def = $.Deferred(); checkUrl = checkUrl || utils.global('checkUrl'); if (checkUrl) { $.get(checkUrl, {"fileName" : fileName, "md5" : md5}, function(result){ if (result.status == 1) { result = result.data; def.resolve(result); } else { def.reject(result); } }).fail(function(result) { def.reject(result); }); } else { def.resolve(null); } return def.promise(); } /** * get upload token * @param tokenUrl token url * @returns {*} */ function getUploadToken(tokenUrl,md5,size) { var def = $.Deferred(); tokenUrl = tokenUrl || utils.global('tokenUrl'); if (tokenUrl) { $.ajax({ url: tokenUrl, data: { md5: md5, size: size }, async: false, type: 'GET', success: function(result) { if (result && result.status == 1) { def.resolve(result.data); } else { def.reject(result); } }, error: function(result) { def.reject(result); } }); } else { def.resolve(''); } return def.promise(); } function md5File(file) { file.ruid = '' + new Date().getTime(); file.getSource = function() {return this}; var deferred = $.Deferred(); var md5 = new WebUploader.Lib.Md5(); md5.on( 'progress load', function( e ) { e = e || {}; deferred.notify( e.total ? e.loaded / e.total : 1 ); }); md5.on( 'complete', function() { deferred.resolve( md5.getResult() ); }); md5.on( 'error', function( reason ) { deferred.reject( reason ); }); md5.loadFromBlob( file ); return deferred.promise(); } $.extend(utils, { md5File: md5File, checkExist: checkExist, getUploadToken: getUploadToken }); })(UploadFileUtils); (function(utils, ErrorCode) { function dialogChooseFile(func) { var $fileInput = $('<input type="file" style="display: none;" />') $(document.body).append($fileInput); $fileInput.on('change', function() { var file = this.files[0]; $fileInput.remove(); func(file); }); $fileInput.click(); } function doUpload(file, param) { var def = $.Deferred(); if (param.tokenUrl) { utils.getUploadToken(param.tokenUrl, param._file.md5, param._file.size).done(function (fileCode) { fileCode && (param._file.fileCode = fileCode); def.resolve(); }).fail(function() { def.reject(); }); } else { def.resolve(); } var uploadProgress = param.events.uploadProgress, uploadSuccess = param.events.uploadSuccess, uploadError = param.events.uploadError; def.done(function() { var uploadUrl = param.uploadUrl; uploadUrl += '?fileName=' + encodeURIComponent(param._file.name); param._file.fileCode && (uploadUrl += '&fileCode=' + param._file.fileCode); var formData = new FormData(); formData.append('file', file); $.ajax({ url: uploadUrl, type: 'post', data: formData, processData : false, contentType : false, xhr: function(){ var myXhr = $.ajaxSettings.xhr(); if(myXhr.upload && uploadProgress){ myXhr.upload.onprogress = function(e){ uploadProgress(file, e.loaded / e.total); }; } return myXhr; }, success: function(result) { uploadSuccess && uploadSuccess(param._file, result.data); }, error: function() { uploadError && uploadError(param._file, ErrorCode.FailedWhenUpload); }, complete: function() { param.events.uploadComplete && param.events.uploadComplete(param._file); } }); }).fail(function() { uploadError && uploadError(file, ErrorCode.FailedWhenGetToken); param.events.uploadComplete && param.events.uploadComplete(param._file); }); } function uploadFile(file, events) { file = file || null; if (typeof file == 'object' && typeof events == 'undefined' && !(file instanceof window.File)) { events = file; file = null; } if (!file) { dialogChooseFile(function(f) { uploadFile(f, events); }); return; } var param = $.extend(utils.global(), {events: events || {}, _file: {name: file.name, ext: '', size: file.size, type: file.type}}); param.events.uploadUrl && (param.uploadUrl = param.events.uploadUrl, delete param.events.uploadUrl); param.events.tokenUrl && (param.tokenUrl = param.events.tokenUrl, delete param.events.tokenUrl); param.events.checkUrl && (param.checkUrl = param.events.checkUrl, delete param.events.checkUrl); if (param._file.name.indexOf('.') > 0) { param._file.ext = param._file.name.substring(param._file.name.lastIndexOf('.') + 1); } var beforeAddFile = param.events.beforeAddFile, uploadSuccess = param.events.uploadSuccess, uploadError = param.events.uploadError; if (beforeAddFile) { var result = beforeAddFile(param._file); if (result == false) return; } utils.md5File(file).done(function(md5) { md5 && (param._file.md5 = md5); if (!!param.checkUrl) { utils.checkExist(param._file.name, param._file.md5, param.checkUrl).done(function(result) { if (result != null) { uploadSuccess && uploadSuccess(param._file, result); param.events.uploadComplete && param.events.uploadComplete(param._file); } else { doUpload(file, param); } }).fail(function(){ doUpload(file, param); }); } else { doUpload(file, param); } }).fail(function() { uploadError && uploadError(param._file, ErrorCode.FailedWhenMd5); param.events.uploadComplete && param.events.uploadComplete(param._file); }); } utils.uploadFile = uploadFile; })(UploadFileUtils, UploadFileUtils.ErrorCode); (function(utils) { function upload(uploader, file, callbackIfExist) { var checkUrl = uploader.options.checkUrl; if (checkUrl == undefined || checkUrl == null || $.trim(checkUrl) == '') { uploader.upload(file); return; } if (typeof file != 'object') { file = uploader.getFile(file); } var def = $.Deferred(); if (file.md5 == undefined) { uploader.md5File(file).then(function (md5) { file.md5 = md5; def.resolve(); }); } else { def.resolve(); } def.done(function() { utils.checkExist(file.name, file.md5, checkUrl).done(function(result) { if (result != null) { uploader.skipFile(file); callbackIfExist && callbackIfExist(file, result); } else { uploader.upload(file); } }).fail(function(){ uploader.upload(file); }); }); } utils.upload = upload; })(UploadFileUtils); /** * param options * - autoMd5 true/false auto md5 file when file add to queue * - beforeAddFile func(fileInfo):boolean you can check you file here, * - ... */ (function(utils, ErrorCode){ function create(options, events) { if (!utils.checkEnv()) return; var param = $.extend({}, utils.global()); if (options) { $.extend(param, options); if (options.uploadUrl) { param.server = options.uploadUrl; } } if (events) { $.extend(param.events, events); } if (param.server == null || param.server == '') { console.error("server cannot be empty"); return; } var uploader = WebUploader.create(param); uploader.on( 'beforeFileQueued', function( file ) { if (events.beforeAddFile != undefined && typeof events.beforeAddFile == 'function') { var result = events.beforeAddFile(file); return result == undefined ? true : result; } return true; }); uploader.on( 'fileQueued', function( file ) { var promise = null; if (param.autoMd5) { promise = uploader.md5File(file); } else { var def = $.Deferred(); def.resolve(null); promise = def.promise(); } promise.then(function(md5) { md5 && (file.md5 = md5); if (events.addFile != undefined && typeof events.addFile == 'function') { events.addFile(file, md5); } }); }); uploader.on('uploadStart', function(file) { var returned = null; if (events.uploadStart != undefined && typeof events.uploadProgress == 'function') { returned = events.uploadStart(file); } file.firstUpload = true; }); uploader.on( 'uploadBeforeSend', function(object, data, headers ) { object.transport.options.server += '?fileName=' + encodeURIComponent(data.name); if (object.file.firstUpload) {// avoid re request token delete object.file.firstUpload; return utils.getUploadToken(param.tokenUrl, object.file.md5, object.file.size).done(function (fileCode) { fileCode && (object.file.fileCode = fileCode, object.transport.options.server += '&fileCode=' + fileCode); }).fail(function() { if (events.uploadError != undefined && typeof events.uploadError == 'function') { events.uploadError(object.file, ErrorCode.FailedWhenGetToken); } }); } }); uploader.on( 'uploadProgress', function(file , percentage) { if (events.uploadProgress != undefined && typeof events.uploadProgress == 'function') { events.uploadProgress(file, percentage); } }); var _this = this; uploader.on( 'uploadSuccess', function(file, response) { if (response && response.statusCode == '200' && response.data && response.data.fileId) { if (events.uploadSuccess != undefined && typeof events.uploadSuccess == 'function') { response = response.data; events.uploadSuccess(file, response); } } else if (events.uploadError != undefined && typeof events.uploadError == 'function') { events.uploadError(file, "System Err."); } }); uploader.on( 'uploadError', function( file, reason) { if (events.uploadError != undefined && typeof events.uploadError == 'function') { events.uploadError(file, reason); } }); uploader.on( 'uploadComplete', function( file ) { if (events.uploadComplete != undefined && typeof events.uploadComplete == 'function') { events.uploadComplete(file); } }); return uploader; } utils.create = create; })(UploadFileUtils, UploadFileUtils.ErrorCode);<file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/core/DruidExamConfiguration.java package com.enableets.edu.enable.cloud.exam.framework.core; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import tk.mybatis.spring.annotation.MapperScan; import javax.sql.DataSource; /** * Multi-data source configuration -- pricure-microservice configuration */ @Configuration @ConditionalOnClass(DruidDataSource.class) @AutoConfigureBefore(DataSourceAutoConfiguration.class) @ConditionalOnProperty(prefix = "druid.exam",name="url") @MapperScan(basePackages = {"com.enableets.edu.enable.cloud.exam.framework.dao"}, sqlSessionTemplateRef = "examSqlSessionTemplate") public class DruidExamConfiguration { /**account microService dataSourse druidPictureProperties*/ @Autowired private DruidExamProperties druidExamProperties; @Bean(name= "examDataSource") @Primary public DataSource accountDataSource(){ return new DataSourceCreator(druidExamProperties).create(); } @Bean(name = "examSqlSessionFactory") @Primary public SqlSessionFactory examSqlSessionFactory(@Qualifier("examDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(druidExamProperties.getMapperLocations())); return bean.getObject(); } @Bean(name = "examTransactionManager") @Primary public DataSourceTransactionManager examTransactionManager(@Qualifier("examDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "examSqlSessionTemplate") @Primary public SqlSessionTemplate examSqlSessionTemplate(@Qualifier("examSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/core/DruidCustomProperties.java package com.enableets.edu.enable.cloud.exam.framework.core; import com.enableets.edu.framework.core.dao.datasource.DruidProperties; import lombok.Data; import lombok.experimental.Accessors; /** * @author <EMAIL> * @date 2021/05/21 **/ @Data @Accessors(chain = true) public class DruidCustomProperties extends DruidProperties { private String mapperLocations; } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/ueditor/lang/zh-tw/zh-tw.js /** * Created with JetBrains PhpStorm. * User: taoqili * Date: 12-6-12 * Time: 下午5:02 * To change this template use File | Settings | File Templates. */ UE.I18N['zh-cn'] = { 'labelMap':{ 'anchor':'錨點', 'undo':'復原', 'redo':'重複', 'bold':'粗體', 'indent':'首行縮排', 'snapscreen':'截圖', 'italic':'斜體', 'underline':'底線', 'strikethrough':'刪除線', 'subscript':'下標','fontborder':'字元框線', 'superscript':'上標', 'formatmatch':'複製格式', 'source':'編輯html', 'blockquote':'引用', 'pasteplain':'貼上純文字', 'selectall':'全選', 'print':'列印', 'preview':'預覽', 'horizontal':'分隔線', 'removeformat':'清除格式', 'time':'時間', 'date':'日期', 'unlink':'移除超連結', 'insertrow':'插入上方列', 'insertcol':'插入左方欄', 'mergeright':'往右合併儲存格', 'mergedown':'往下合併儲存格', 'deleterow':'删除列', 'deletecol':'删除欄', 'splittorows':'拆分成列', 'splittocols':'拆分成欄', 'splittocells':'完全拆分儲存格','deletecaption':'删除表格標題','inserttitle':'插入標題', 'mergecells':'合併儲存格', 'deletetable':'删除表格', 'cleardoc':'清除','insertparagraphbeforetable':"表格前插入段落",'insertcode':'代碼語言', 'fontfamily':'字型', 'fontsize':'字型大小', 'paragraph':'段落格式', 'simpleupload':'上傳單圖', 'insertimage':'上傳多圖','edittable':'表格屬性','edittd':'儲存格屬性', 'link':'超連結', 'emotion':'表情符號', 'spechars':'特殊符號', 'searchreplace':'取代', 'map':'百度地圖', 'gmap':'Google地圖', 'insertvideo':'影片', 'help':'幫助', 'justifyleft':'靠左對齊', 'justifyright':'靠右對齊', 'justifycenter':'置中', 'justifyjustify':'左右對齊', 'forecolor':'字型色彩', 'backcolor':'背景色', 'insertorderedlist':'編號', 'insertunorderedlist':'項目符號', 'fullscreen':'全螢幕', 'directionalityltr':'從左而右輸入', 'directionalityrtl':'從右而左輸入', 'rowspacingtop':'與前段距離', 'rowspacingbottom':'與後段距離', 'pagebreak':'分頁', 'insertframe':'插入Iframe', 'imagenone':'預設', 'imageleft':'左浮動', 'imageright':'右浮動', 'attachment':'附件', 'imagecenter':'置中', 'wordimage':'圖片轉存', 'lineheight':'行距','edittip' :'編輯提示','customstyle':'自定義標題', 'autotypeset':'自動排版', 'webapp':'百度應用','touppercase':'字母大寫', 'tolowercase':'字母小寫','background':'背景','template':'模板','scrawl':'塗鴉', 'music':'音樂','inserttable':'插入表格','drafts': '從草稿箱載入', 'charts': '圖表' }, 'insertorderedlist':{ 'num':'1,2,3...', 'num1':'1),2),3)...', 'num2':'(1),(2),(3)...', 'cn':'一,二,三....', 'cn1':'一),二),三)....', 'cn2':'(一),(二),(三)....', 'decimal':'1,2,3...', 'lower-alpha':'a,b,c...', 'lower-roman':'i,ii,iii...', 'upper-alpha':'A,B,C...', 'upper-roman':'I,II,III...' }, 'insertunorderedlist':{ 'circle':'○ 大圓圈', 'disc':'● 小黑點', 'square':'■ 小方塊 ', 'dash' :'— 破折號', 'dot':' 。 小圓圈' }, 'paragraph':{'p':'段落', 'h1':'標題 1', 'h2':'標題 2', 'h3':'標題 3', 'h4':'標題 4', 'h5':'標題 5', 'h6':'標題 6'}, 'fontfamily':{ 'songti':'宋體', 'kaiti':'楷體', 'heiti':'黑體', 'lishu':'隸書', 'yahei':'微軟雅黑', 'andaleMono':'andale mono', 'arial': 'arial', 'arialBlack':'arial black', 'comicSansMs':'comic sans ms', 'impact':'impact', 'timesNewRoman':'times new roman' }, 'customstyle':{ 'tc':'標題置中', 'tl':'標題居左', 'im':'強調', 'hi':'明顯強調' }, 'autoupload': { 'exceedSizeError': '文件大小超出限制', 'exceedTypeError': '文件格式不允許', 'jsonEncodeError': '伺服器傳回格式錯誤', 'loading':"正在上傳...", 'loadError':"上傳錯誤", 'errorLoadConfig': '後端配置項没有正常載入,上傳插件不能正常使用!' }, 'simpleupload':{ 'exceedSizeError': '檔案大小超出限制', 'exceedTypeError': '檔案格式不允許', 'jsonEncodeError': '伺服器傳回格式錯誤', 'loading':"正在上傳...", 'loadError':"上傳錯誤", 'errorLoadConfig': '後端配置項没有正常載入,上傳插件不能正常使用!' }, 'elementPathTip':"元素路徑", 'wordCountTip':"字數統計", 'wordCountMsg':'目前已輸入{#count}個字元, 您還可以輸入{#leave}個字元。 ', 'wordOverFlowMsg':'<span style="color:red;">字數超出最大允許值!</span>', 'ok':"確認", 'cancel':"取消", 'closeDialog':"關閉對話框", 'tableDrag':"表格拖動必須引入uiUtils.js文件!", 'autofloatMsg':"工具欄浮動依賴編輯器UI,您首先需要引入UI文件!", 'loadconfigError': '獲取後台配置項請求出錯,上傳功能將不能正常使用!', 'loadconfigFormatError': '後台配置項返回格式出錯,上傳功能將不能正常使用!', 'loadconfigHttpError': '請求後台配置項http錯誤,上傳功能將不能正常使用!', 'snapScreen_plugin':{ 'browserMsg':"僅支援IE瀏覽器!", 'callBackErrorMsg':"伺服器返回資料有誤,請檢查配置項之後重試。", 'uploadErrorMsg':"截圖上傳失敗,請檢查伺服器端環境! " }, 'insertcode':{ 'as3':'ActionScript 3', 'bash':'Bash/Shell', 'cpp':'C/C++', 'css':'CSS', 'cf':'ColdFusion', 'c#':'C#', 'delphi':'Delphi', 'diff':'Diff', 'erlang':'Erlang', 'groovy':'Groovy', 'html':'HTML', 'java':'Java', 'jfx':'JavaFX', 'js':'JavaScript', 'pl':'Perl', 'php':'PHP', 'plain':'Plain Text', 'ps':'PowerShell', 'python':'Python', 'ruby':'Ruby', 'scala':'Scala', 'sql':'SQL', 'vb':'Visual Basic', 'xml':'XML' }, 'confirmClear':"確定清除?", 'contextMenu':{ 'delete':"删除", 'selectall':"全選", 'deletecode':"删除代碼", 'cleardoc':"清除內容", 'confirmclear':"確定清除目前內容嗎?", 'unlink':"删除超連結", 'paragraph':"段落格式", 'edittable':"表格屬性", 'aligntd':"儲存格對齊方式", 'aligntable':'表格對齊方式', 'tableleft':'左浮動', 'tablecenter':'置中顯示', 'tableright':'右浮動', 'edittd':"儲存格屬性", 'setbordervisible':'設定表格邊線可見', 'justifyleft':'靠左對齊', 'justifyright':'靠右對齊', 'justifycenter':'置中對齊', 'justifyjustify':'左右對齊', 'table':"表格", 'inserttable':'插入表格', 'deletetable':"删除表格", 'insertparagraphbefore':"前插入段落", 'insertparagraphafter':'後插入段落', 'deleterow':"删除當前列", 'deletecol':"删除當前欄", 'insertrow':"前插入列", 'insertcol':"左插入欄", 'insertrownext':'後插入列', 'insertcolnext':'右插入欄', 'insertcaption':'插入表格名稱', 'deletecaption':'删除表格名稱', 'inserttitle':'插入表格標題', 'deletetitle':'删除表格標題', 'inserttitlecol':'插入表格標題欄', 'deletetitlecol':'删除表格標題欄', 'averageDiseRow':'平均分布各欄', 'averageDisCol':'平均分布各列', 'mergeright':"向右合併", 'mergeleft':"向左合併", 'mergedown':"向下合併", 'mergecells':"合併儲存格", 'splittocells':"完全拆分儲存格", 'splittocols':"拆分成列", 'splittorows':"拆分成行", 'tablesort':'表格排序', 'enablesort':'設定表格可排序', 'disablesort':'取消表格可排序', 'reversecurrent':'與目前相反排序', 'orderbyasc':'按ASCII字元升序', 'reversebyasc':'按ASCII字元降序', 'orderbynum':'按數值大小升序', 'reversebynum':'按數值大小降序', 'borderbk':'邊框底纹', 'setcolor':'表格隔行變色', 'unsetcolor':'取消表格隔行變色', 'setbackground':'選區背景隔行', 'unsetbackground':'取消選區背景', 'redandblue':'紅藍相間', 'threecolorgradient':'三色漸變', 'copy':"複製(Ctrl + c)", 'copymsg': "瀏覽器不支援,請使用 'Ctrl + c'", 'paste':"貼上(Ctrl + v)", 'pastemsg': "瀏覽器不支援,請使用 'Ctrl + v'" }, 'copymsg': "瀏覽器不支援,請使用 'Ctrl + c'", 'pastemsg': "瀏覽器不支援,請使用 'Ctrl + v'", 'anthorMsg':"連結", 'clearColor':'清除顏色', 'standardColor':'標準顏色', 'themeColor':'主題顏色', 'property':'屬性', 'default':'預設', 'modify':'修改', 'justifyleft':'左對齊', 'justifyright':'右對齊', 'justifycenter':'置中', 'justify':'預設', 'clear':'清除', 'anchorMsg':'錨點', 'delete':'删除', 'clickToUpload':"點擊上傳", 'unset':'尚未設定語言文件', 't_row':'列', 't_col':'欄', 'more':'更多', 'pasteOpt':'貼上選項', 'pasteSourceFormat':"保留源格式", 'tagFormat':'只保留標籤', 'pasteTextFormat':'只保留文字', 'autoTypeSet':{ 'mergeLine':"合併空行", 'delLine':"清除空行", 'removeFormat':"清除格式", 'indent':"首行縮排", 'alignment':"對齊方式", 'imageFloat':"圖片浮動", 'removeFontsize':"清除字型大小", 'removeFontFamily':"清除字體", 'removeHtml':"清除多餘HTML碼", 'pasteFilter':"貼上過濾", 'run':"執行", 'symbol':'符號轉換', 'bdc2sb':'全形轉半形', 'tobdc':'半形轉全形' }, 'background':{ 'static':{ 'lang_background_normal':'背景設定', 'lang_background_local':'線上圖片', 'lang_background_set':'選項', 'lang_background_none':'無背景色', 'lang_background_colored':'有背景色', 'lang_background_color':'顏色設定', 'lang_background_netimg':'網路圖片', 'lang_background_align':'對齊方式', 'lang_background_position':'精確定位', 'repeatType':{'options':["置中", "横向重複", "縱向重複", "平鋪","自定義"]} }, 'noUploadImage':"當前未上傳過任何圖片!", 'toggleSelect':"單擊可切換選中狀態\n原圖尺寸: " }, //===============dialog i18N======================= 'insertimage':{ 'static':{ 'lang_tab_remote':"插入圖片", //節點 'lang_tab_upload':"本機上傳", 'lang_tab_online':"線上管理", 'lang_tab_search':"圖片搜尋", 'lang_input_url':"地址:", 'lang_input_size':"大小:", 'lang_input_width':"寬度", 'lang_input_height':"高度", 'lang_input_border':"邊框:", 'lang_input_vhspace':"邊距:", 'lang_input_title':"描述:", 'lang_input_align':'圖片浮動方式:', 'lang_imgLoading':" 圖片載入中……", 'lang_start_upload':"開始上傳", 'lock':{'title':"鎖定寬高比例"}, //屬性 'searchType':{'title':"圖片類型", 'options':["新聞", "背景圖片", "表情", "個人圖片"]}, //select的option 'searchTxt':{'value':"請輸入搜尋關鍵字"}, 'searchBtn':{'value':"查詢百度"}, 'searchReset':{'value':"清除搜尋"}, 'noneAlign':{'title':'無浮動'}, 'leftAlign':{'title':'左浮動'}, 'rightAlign':{'title':'右浮動'}, 'centerAlign':{'title':'置中獨占一行'} }, 'uploadSelectFile':'點擊選擇圖片', 'uploadAddFile':'繼續添加', 'uploadStart':'開始上傳', 'uploadPause':'暫停上傳', 'uploadContinue':'繼續上傳', 'uploadRetry':'重試上傳', 'uploadDelete':'删除', 'uploadTurnLeft':'向左旋轉', 'uploadTurnRight':'向右旋轉', 'uploadPreview':'預覽中', 'uploadNoPreview':'不能預覽', 'updateStatusReady': '選中_張圖片,共_KB。', 'updateStatusConfirm': '已成功上傳_張照片,_張照片上傳失敗', 'updateStatusFinish': '共_張(_KB),_張上傳成功', 'updateStatusError': ',_張上傳失敗。', 'errorNotSupport': 'WebUploader 不支援您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器。', 'errorLoadConfig': '後端配置項没有正常載入,上傳插件不能正常使用!', 'errorExceedSize':'文件大小超出', 'errorFileType':'文件格式不允許', 'errorInterrupt':'文件傳輸中斷', 'errorUploadRetry':'上傳失敗,請重試', 'errorHttp':'http請求錯誤', 'errorServerUpload':'伺服器返回出錯', 'remoteLockError':"寬高不正確,不能所定比例", 'numError':"請輸入正確的長度或者寬度值!例如:123,400", 'imageUrlError':"不允許的圖片格式或者圖片欄位!", 'imageLoadError':"圖片載入失敗!請檢查連結地址或網路狀態!", 'searchRemind':"請輸入搜尋關鍵字", 'searchLoading':"圖片載入中,請稍後……", 'searchRetry':" :( ,抱歉,没有找到圖片!請重試一次!" }, 'attachment':{ 'static':{ 'lang_tab_upload': '上傳附件', 'lang_tab_online': '線上附件', 'lang_start_upload':"開始上傳", 'lang_drop_remind':"可以將文件拖曳到這裡,單次最多可選100個文件" }, 'uploadSelectFile':'點擊選擇文件', 'uploadAddFile':'繼續添加', 'uploadStart':'開始上傳', 'uploadPause':'暫停上傳', 'uploadContinue':'繼續上傳', 'uploadRetry':'重試上傳', 'uploadDelete':'删除', 'uploadTurnLeft':'向左旋轉', 'uploadTurnRight':'向右旋轉', 'uploadPreview':'預覽中', 'updateStatusReady': '選中_個文件,共_KB。', 'updateStatusConfirm': '已成功上傳_個文件,_個文件上傳失敗', 'updateStatusFinish': '共_個(_KB),_個上傳成功', 'updateStatusError': ',_張上傳失敗。', 'errorNotSupport': 'WebUploader 不支援您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器。', 'errorLoadConfig': '後端配置項没有正常載入,上傳插件不能正常使用!', 'errorExceedSize':'文件大小超出', 'errorFileType':'文件格式不允許', 'errorInterrupt':'文件傳輸中斷', 'errorUploadRetry':'上傳失敗,請重試', 'errorHttp':'http請求錯誤', 'errorServerUpload':'伺服器返回出錯' }, 'insertvideo':{ 'static':{ 'lang_tab_insertV':"插入影片", 'lang_tab_searchV':"搜尋影片", 'lang_tab_uploadV':"上傳影片", 'lang_video_url':"影片網址", 'lang_video_size':"影片尺寸", 'lang_videoW':"寬度", 'lang_videoH':"高度", 'lang_alignment':"對齊方式", 'videoSearchTxt':{'value':"請輸入查詢關鍵字!"}, 'videoType':{'options':["全部", "熱門", "娛樂", "搞笑", "體育", "科技", "綜藝"]}, 'videoSearchBtn':{'value':"百度一下"}, 'videoSearchReset':{'value':"清除結果"}, 'lang_input_fileStatus':' 當前未上傳文件', 'startUpload':{'style':"background:url(upload.png) no-repeat;"}, 'lang_upload_size':"影片尺寸", 'lang_upload_width':"寬度", 'lang_upload_height':"高度", 'lang_upload_alignment':"對齊方式", 'lang_format_advice':"建議使用mp4格式." }, 'numError':"請輸入正確的數值,如123,400", 'floatLeft':"左浮動", 'floatRight':"右浮動", '"default"':"預設", 'block':"獨占一行", 'urlError':"輸入的影片地址有誤,請檢查後再試!", 'loading':" &nbsp;影片載入中,請等待……", 'clickToSelect':"點擊選中", 'goToSource':'原始影片', 'noVideo':" &nbsp; &nbsp;抱歉,找不到對應的影片,請重試!", 'browseFiles':'瀏覽文件', 'uploadSuccess':'上傳成功!', 'delSuccessFile':'從成功隊列中移除', 'delFailSaveFile':'移除保存失敗文件', 'statusPrompt':' 個文件已上傳! ', 'flashVersionError':'當前Flash版本過低,請更新FlashPlayer後重試!', 'flashLoadingError':'Flash載入失敗!請檢查路徑或網路狀態', 'fileUploadReady':'等待上傳……', 'delUploadQueue':'從上傳序列中移除', 'limitPrompt1':'單次不能選擇超過', 'limitPrompt2':'個文件!請重新選擇!', 'delFailFile':'移除失敗文件', 'fileSizeLimit':'文件大小超出限制!', 'emptyFile':'空文件無法上傳!', 'fileTypeError':'文件類型不允許!', 'unknownError':'未知錯誤!', 'fileUploading':'上傳中,請等待……', 'cancelUpload':'取消上傳', 'netError':'網路錯誤', 'failUpload':'上傳失敗!', 'serverIOError':'伺服器存取錯誤!', 'noAuthority':'無權限!', 'fileNumLimit':'上傳個數限制', 'failCheck':'驗證失敗,本次上傳被跳過!', 'fileCanceling':'取消中,請等待……', 'stopUploading':'上傳已停止……', 'uploadSelectFile':'點擊選擇文件', 'uploadAddFile':'繼續添加', 'uploadStart':'開始上傳', 'uploadPause':'暫停上傳', 'uploadContinue':'繼續上傳', 'uploadRetry':'重試上傳', 'uploadDelete':'删除', 'uploadTurnLeft':'向左旋轉', 'uploadTurnRight':'向右旋轉', 'uploadPreview':'預覽中', 'updateStatusReady': '選中_個文件,共_KB。', 'updateStatusConfirm': '成功上傳_個,_個失敗', 'updateStatusFinish': '共_個(_KB),_個成功上傳', 'updateStatusError': ',_張上傳失敗。', 'errorNotSupport': 'WebUploader 不支援您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器。', 'errorLoadConfig': '後端配置項没有正常載入,上傳插件不能正常使用!', 'errorExceedSize':'文件大小超出', 'errorFileType':'文件格式不允許', 'errorInterrupt':'文件傳輸中斷', 'errorUploadRetry':'上傳失敗,請重試', 'errorHttp':'http請求錯誤', 'errorServerUpload':'伺服器返回出錯' }, 'webapp':{ 'tip1':"本功能由百度APP提供,如看到此頁面,請各位站長首先申請百度APPKey!", 'tip2':"申請完成之後請至ueditor.config.js中配置獲得的appkey! ", 'applyFor':"點此申請", 'anthorApi':"百度API" }, 'template':{ 'static':{ 'lang_template_bkcolor':'背景顏色', 'lang_template_clear' : '保留原有内容', 'lang_template_select' : '選擇模板' }, 'blank':"空白內容", 'blog':"部落格文章", 'resume':"個人簡歷", 'richText':"圖文混排", 'sciPapers':"科技論文" }, 'scrawl':{ 'static':{ 'lang_input_previousStep':"上一步", 'lang_input_nextsStep':"下一步", 'lang_input_clear':'清除', 'lang_input_addPic':'添加背景', 'lang_input_ScalePic':'縮放背景', 'lang_input_removePic':'删除背景', 'J_imgTxt':{title:'添加背景圖片'} }, 'noScarwl':"尚未作畫", 'scrawlUpLoading':"塗鴉上傳中,請稍後", 'continueBtn':"繼續", 'imageError':"糟糕,圖片讀取失敗了!", 'backgroundUploading':'背景圖片上傳中,請稍後' }, 'music':{ 'static':{ 'lang_input_tips':"輸入歌手/歌曲/專輯,搜尋您感興趣的音樂!", 'J_searchBtn':{value:'搜尋歌曲'} }, 'emptyTxt':'未搜尋到相關音樂結果,請換一個關鍵字試試。', 'chapter':'歌曲', 'singer':'歌手', 'special':'專輯', 'listenTest':'試聽' }, 'anchor':{ 'static':{ 'lang_input_anchorName':'錨點名稱:' } }, 'charts':{ 'static':{ 'lang_data_source':'資料來源:', 'lang_chart_format': '圖表格式:', 'lang_data_align': '資料對齊方式', 'lang_chart_align_same': '資料來源與圖表X軸Y軸一致', 'lang_chart_align_reverse': '資料來源與圖表X軸Y軸相反', 'lang_chart_title': '圖表標題', 'lang_chart_main_title': '主標題:', 'lang_chart_sub_title': '子標題:', 'lang_chart_x_title': 'X軸標題:', 'lang_chart_y_title': 'Y軸標題:', 'lang_chart_tip': '提示文字', 'lang_cahrt_tip_prefix': '提示文字前綴:', 'lang_cahrt_tip_description': '僅圓餅圖有效,當滑鼠移動到圓餅圖中相應的區塊時,提示框内的文字的前綴', 'lang_chart_data_unit': '資料單位', 'lang_chart_data_unit_title': '單位:', 'lang_chart_data_unit_description': '顯示在每個資料點上的資料的單位, 比如: 溫度的單位 ℃', 'lang_chart_type': '圖表類型:', 'lang_prev_btn': '上一個', 'lang_next_btn': '下一個' } }, 'emotion':{ 'static':{ 'lang_input_choice':'精選', 'lang_input_Tuzki':'兔斯基', 'lang_input_BOBO':'BOBO', 'lang_input_lvdouwa':'綠豆蛙', 'lang_input_babyCat':'baby猫', 'lang_input_bubble':'泡泡', 'lang_input_youa':'有啊' } }, 'gmap':{ 'static':{ 'lang_input_address':'地址', 'lang_input_search':'查詢', 'address':{value:"台北"} }, searchError:'無法定位到該地址!' }, 'help':{ 'static':{ 'lang_input_about':'關于UEditor', 'lang_input_shortcuts':'快捷鍵', 'lang_input_introduction':'UEditor是由百度web前端研發部開發的所見即所得豐富文本web編輯器,具有輕量,可客製,注重用户體驗等特點。開源基于BSD協議,允許自由使用和修改代碼。', 'lang_Txt_shortcuts':'快捷鍵', 'lang_Txt_func':'功能', 'lang_Txt_bold':'選取文字設定為粗體', 'lang_Txt_copy':'複製選取内容', 'lang_Txt_cut':'剪下選取内容', 'lang_Txt_Paste':'貼上', 'lang_Txt_undo':'重新執行上次操作', 'lang_Txt_redo':'取消上一次操作', 'lang_Txt_italic':'選取文字設定為斜體', 'lang_Txt_underline':'選取文字加底線', 'lang_Txt_selectAll':'全部選取', 'lang_Txt_visualEnter':'自動換行', 'lang_Txt_fullscreen':'全螢幕' } }, 'insertframe':{ 'static':{ 'lang_input_address':'地址:', 'lang_input_width':'寬度:', 'lang_input_height':'高度:', 'lang_input_isScroll':'允許捲軸:', 'lang_input_frameborder':'顯示邊框:', 'lang_input_alignMode':'對齊方式:', 'align':{title:"對齊方式", options:["預設", "靠左對齊", "靠右對齊", "置中"]} }, 'enterAddress':'請輸入地址!' }, 'link':{ 'static':{ 'lang_input_text':'内容:', 'lang_input_url':'連結地址:', 'lang_input_title':'標題:', 'lang_input_target':'是否在新窗口打開:' }, 'validLink':'只支援選中一個連結時生效', 'httpPrompt':'您輸入的超連結中不包含http等協議名稱,預設將為您添加http://前綴' }, 'map':{ 'static':{ lang_city:"城市", lang_address:"地址", city:{value:"北京"}, lang_search:"搜尋", lang_dynamicmap:"插入動態地圖" }, cityMsg:"請選擇城市", errorMsg:"抱歉,找不到該位置!" }, 'searchreplace':{ 'static':{ lang_tab_search:"查找", lang_tab_replace:"替換", lang_search1:"查找", lang_search2:"查找", lang_replace:"替換", lang_searchReg:'支援正規表示法,添加前後斜線標示為正規表示法,例如“/表示法/”', lang_searchReg1:'支援正規表示法,添加前後斜線標示為正規表示法,例如“/表示法/”', lang_case_sensitive1:"區分大小寫", lang_case_sensitive2:"區分大小寫", nextFindBtn:{value:"下一個"}, preFindBtn:{value:"上一個"}, nextReplaceBtn:{value:"下一個"}, preReplaceBtn:{value:"上一個"}, repalceBtn:{value:"替換"}, repalceAllBtn:{value:"全部替換"} }, getEnd:"已經搜尋到文章末尾!", getStart:"已經搜尋到文章起始", countMsg:"總共替換了{#count}處!" }, 'snapscreen':{ 'static':{ lang_showMsg:"截圖功能需要首先安裝UEditor截圖插件! ", lang_download:"點此下載", lang_step1:"第一步,下載UEditor截圖插件並安裝。", lang_step2:"第二步,插件安裝完成後即可使用,如不生效,請重啟瀏覽器後再試!" } }, 'spechars':{ 'static':{}, tsfh:"特殊字元", lmsz:"羅馬字元", szfh:"數學字元", rwfh:"日文字元", xlzm:"希臘字母", ewzm:"俄文字元", pyzm:"拼音字母", yyyb:"英語音標", zyzf:"其他" }, 'edittable':{ 'static':{ 'lang_tableStyle':'表格樣式', 'lang_insertCaption':'添加表格名稱行', 'lang_insertTitle':'添加表格標題行', 'lang_insertTitleCol':'添加表格標題列', 'lang_orderbycontent':"使表格内容可排序", 'lang_tableSize':'自動調整表格尺寸', 'lang_autoSizeContent':'按表格文字自動調整', 'lang_autoSizePage':'按頁面寬度自動調整', 'lang_example':'示例', 'lang_borderStyle':'表格邊框', 'lang_color':'顏色:' }, captionName:'表格名稱', titleName:'標題', cellsName:'内容', errorMsg:'有合併儲存格,不可排序' }, 'edittip':{ 'static':{ lang_delRow:'删除整行', lang_delCol:'删除整列' } }, 'edittd':{ 'static':{ lang_tdBkColor:'背景顏色:' } }, 'formula':{ 'static':{ } }, 'wordimage':{ 'static':{ lang_resave:"轉存步驟", uploadBtn:{src:"upload.png",alt:"上傳"}, clipboard:{style:"background: url(copy.png) -153px -1px no-repeat;"}, lang_step:"1、點擊頂部複製按鈕,將地址複製到剪貼簿;2、點擊添加照片按鈕,在彈出的對話框中使用Ctrl+V貼上地址;3、點擊打開後選擇圖片上傳流程。" }, 'fileType':"圖片", 'flashError':"FLASH初始化失敗,請檢查FLASH插件是否正確安裝!", 'netError':"網路連接錯誤,請重試!", 'copySuccess':"圖片地址已經複製!", 'flashI18n':{} //留空預設中文 }, 'autosave': { 'saving':'儲存中...', 'success':'儲存成功' } }; <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/jsTree/custom/treeDropDown.js // var DropDownTree = window.DropDownTree = { // obj : null, // treeDiv : null, // init : function() { // if (this.treeDiv == null) { // var thisId = $(this.obj).attr("id"); // var id = "tree" + (thisId == undefined ? (Math.random() * 10000) : thisId); // var width = $(this.obj).parent().width(); // $(this.obj).parent().append("<div id='" + id + "' style='position:fixed;background-color: white;z-index:2;width:" + width + "px;' ></div>"); // this.treeDiv = $(this.obj).parent().find("div#" + id); // // var _this =this; // this.treeDiv.on("changed.jstree", function (e, data) { // if(data.selected.length) { // $(_this.obj).parent().find("input").val(data.instance.get_node(data.selected[0]).text); //// alert('The selected node is: ' + data.instance.get_node(data.selected[0]).text); // } // }).jstree({ // 'core' : { // "multiple" : false, // 'data' : treeData, // 'dblclick_toggle': false //禁用tree的双击展开 // }, // "plugins" : ["search"] // }); // this.treeDiv.hide(); // } // }, // toggle : function(obj) { // this.obj = $(obj); // this.init(); // if ($(this.treeDiv).is(":visible")) { // $(this.treeDiv).hide(); // } else { // $(this.treeDiv).show(); // } // } // } /** * */ (function($){ var streeSelect = { //inputWarpClass外层类名 ,streeWarpId放置tree的层,Datas数据(此处为url,取消data里面的注释部分即可使用) //treePlugins单选多选的展现方式 selectType为选择方式(单选false或者多选true) init : function(inputWarpClass,streeWarpId,Datas,selectType, changeCallBack){ this.streeInitCheckbox(inputWarpClass,streeWarpId,Datas,selectType, changeCallBack); this.inputClick(inputWarpClass); }, inputClick:function(inputWarpClass){ $(inputWarpClass).find('input').on("click",function(e){ e.stopPropagation(); //console.log(Datas) $(inputWarpClass).find('.stree_warp').toggle(); }).on("focus", function(){ this.blur(); }); }, streeInitCheckbox:function(inputWarpClass,streeWarpId,Datas,selectType, changeCallBack){ var plugins=[]; if (selectType) { plugins=["wholerow","checkbox","types","changed"]; } else{ plugins=["wholerow","types","changed"]; } //console.log() $(streeWarpId) .jstree({ 'plugins': plugins, 'checkbox': {      "three_state": selectType //父子级不关联选中  }, 'core': { "multiple": selectType,//单选 "themes" : { "responsive": false }, "check_callback" : true, 'data': Datas }, "types" :{ "default" : { "icon" : "fa fa-folder icon-state-warning icon-lg" }, "file" : { "icon" : "fa fa-file icon-state-warning icon-lg" } } }).bind("load_node.jstree", function(e, data) { var checkDiv = $(streeWarpId).html(); var array = checkDiv.split(","); var nodeIds = data.node.children; for(var i=0;i<nodeIds.length;i++){ for(var j=0;j<array.length;j++){ if(array[j] == nodeIds[i]){ $(this).andSelf().removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-clicked"); } } } }).on("changed.jstree",function(e,data){ e.stopPropagation(); if (selectType) { var selectValues=[]; var selectedId=$(this).jstree().get_checked(true); //console.log(selectedId.length); if (selectedId.length>0) { for (var i=0;i<selectedId.length;i++) { var selectNode = data.instance.get_node(data.selected[i]); if ( selectNode.children.length == 0){ //console.log(selectNode.text); selectValues.push(selectNode.text); } } console.log(selectValues.length) //如果改变的选中值 $(this).siblings('.streeControl_box').find('.streeSure').on('click',function(){ if (selectValues.length>0) { $(inputWarpClass).find('input').val(selectValues); selectedId=0; selectValues=[]; $(inputWarpClass).find('.stree_warp').hide(); } }); } } else{ var selectValues=[]; var ClickId=$(this).jstree().get_bottom_selected(true); //console.log(ClickId.length); if (ClickId.length>0) { for (var i=0;i<ClickId.length;i++) { var ClickNode = data.instance.get_node(data.selected[i]); if ( ClickNode.children.length == 0){ //console.log(ClickNode.text); selectValues.push(ClickNode.text); } } //console.log(selectValues) //如果改变的选中值 $(inputWarpClass).find('input').val(selectValues); changeCallBack && changeCallBack(data.instance.get_node(data.selected[0])); selectedId=0; selectValues=[]; $(inputWarpClass).find('.stree_warp').hide(); } } // if (selectedId.length>0) { // for (var i=0;i<selectedId.length;i++) { // var selectNode = data.instance.get_node(data.selected[i]); // if ( selectNode.children.length == 0){ // //console.log(selectNode.text); // selectValues.push(selectNode.text); // } // } // console.log(selectValues.length) // //如果改变的选中值 // //console.log(data.instance.get_node(data.selected[0]).text) // if (selectType) { // $(this).siblings('.streeControl_box').find('.streeSure').on('click',function(){ // if (selectValues.length>0) { // $(this).parents(inputWarpClass).find('input').val(selectValues); // selectedId=0; // selectValues=[]; // $(inputWarpClass).find('.stree_warp').hide(); // } // }); // } else if (!selectType) { // $(this).parents(inputWarpClass).find('input').val(selectValues); // selectedId=0; // selectValues=[]; // $(inputWarpClass).find('.stree_warp').hide(); // } // // } }); //取消按钮关闭下拉树 $(".streeControl_box .streeCancel").on('click',function(){ $(inputWarpClass).find('.stree_warp').hide(); }) //点击下拉树以外部分关闭下拉树 $(inputWarpClass).siblings().on('click',function(event){ $(inputWarpClass).find('.stree_warp').hide(); }); $(inputWarpClass).parents().siblings().on('click',function(event){ $(inputWarpClass).find('.stree_warp').hide(); event.stopPropagation(); }); } }; function initDropTree(treeData, selectType, changeCallBack){ selectType = selectType == 'single' ? false : true; if ($(this).next().length == 0 || !$(this).next().hasClass(".stree_warp")) { var treeId = $(this).attr("id"); if (treeId == undefined || treeId == "") { treeId = "tree" + Math.random() * 10000; } else { treeId = treeId + "tree"; } var html = ''; if(selectType == true) { html = '<div class="stree_warp select_tree">' + '<div class="stree_box" id="' + treeId + '">' + '</div><div class="streeControl_box"><a class="streeSure">确定</a><a class="streeCancel">取消</a></div></div>'; }else if(selectType == false) { html = '<div class="stree_warp select_tree">' + '<div class="stree_box" id="' + treeId + '">' + '</div></div>'; } $(this).after(html); } $(this).next().hide(); streeSelect.init($(this).parent(), '#' + treeId ,treeData, selectType, changeCallBack); } $.fn.treeSelect = function(){ initDropTree.apply(this, arguments) // var method = arguments[0]; // if(methods[method]){ // method = methods[method]; // arguments = Array.protoType.slice.call(arguments,1); // }else if( typeof(method) == 'object' || !method ){ // method = methods.init; // }else{ // $.error( 'Method ' + method + ' does not exist on jQuery.collectStar' ); // return this; // } // return method.apply(this,arguments); }; })(jQuery);<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/PaperNodeInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import java.util.List; /** * 试卷结构节点信息bo * @author duffy_ding * @since 2018/03/20 */ public class PaperNodeInfoBO { /** 试卷节点标识 */ private String nodeId; /** 父节点标识 */ private String parentId; /** 节点名称 */ private String name; /** 节点顺序 */ private Integer sequencing; /** 内部编号 */ private Integer internalNo; /** 外部编号,如1.1 */ private String externalNo; /** 节点描述 */ private String description; /** 节点层级 */ private Integer level; /** 节点分数 */ private Float points; /** 试题信息 */ private QuestionInfoBO question; /** 推题条件*/ private RecommendQuestionConditionBO condition; /** 子节点(组装大小题使用) */ private List<PaperNodeInfoBO> children; public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSequencing() { return sequencing; } public void setSequencing(Integer sequencing) { this.sequencing = sequencing; } public Integer getInternalNo() { return internalNo; } public void setInternalNo(Integer internalNo) { this.internalNo = internalNo; } public String getExternalNo() { return externalNo; } public void setExternalNo(String externalNo) { this.externalNo = externalNo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Float getPoints() { return points; } public void setPoints(Float points) { this.points = points; } public QuestionInfoBO getQuestion() { return question; } public void setQuestion(QuestionInfoBO question) { this.question = question; } public RecommendQuestionConditionBO getCondition() { return condition; } public void setCondition(RecommendQuestionConditionBO condition) { this.condition = condition; } public List<PaperNodeInfoBO> getChildren() { return children; } public void setChildren(List<PaperNodeInfoBO> children) { this.children = children; } } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/ExamDetailsStepTaskInfoVO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import com.enableets.edu.enable.cloud.exam.framework.core.Constants; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.format.annotation.DateTimeFormat; /** * @author <EMAIL> * @since 2020/05/21 */ @ApiModel @JsonIgnoreProperties(ignoreUnknown = true) public class ExamDetailsStepTaskInfoVO { /** * 考试详情标识 */ @ApiModelProperty(value = "考试详情标识") private Long examDetailsId; /** * 考试发布后,考试详情对应的打卡任务的标识 */ @ApiModelProperty(value = "考试发布后,考试详情对应的打卡任务的标识") private String activityId; /** * 试卷信息,json串 */ @ApiModelProperty(value = "试卷信息,json串") private String contentInfo; /** * 0:指定时间发布 1:立即发布 */ @ApiModelProperty(value = "0:指定时间发布 1:立即发布") private String publishNow; /** * 发布时间 */ @ApiModelProperty(value = "发布时间") @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date publishTime; /** * 状态 0:未派卷 1:已派卷 */ @ApiModelProperty(value = "状态 0:未派卷 1:已派卷 ") private String status; /** * 试卷下载时间,提前下载分钟数 */ @ApiModelProperty(value = "试卷下载时间,提前下载分钟数") private Long downloadInAdvanceMinutes; /** * 考试时长 */ @ApiModelProperty(value = "考试时长") private Long minutesOfExam; /** * 答卷开始时间 */ @ApiModelProperty(value = "答卷开始时间") @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date answerStartTime; /** * 答卷结束时间 */ @ApiModelProperty(value = "答卷结束时间") @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date answerEndTime; /** * 答卷后多少分钟可以交卷 */ @ApiModelProperty(value = "答卷后多少分钟可以交卷") private Long minutesAfterTheStartToHandIn; /** * 交卷结束时间 */ @ApiModelProperty(value = "交卷结束时间") @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date handInEndTime; /** * 阅卷开始时间 */ @ApiModelProperty(value = "阅卷开始时间") @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date markStartTime; /** * 阅卷结束时间 */ @ApiModelProperty(value = "阅卷结束时间") @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private java.util.Date markEndTime; /** * @return the examDetailsId */ public Long getExamDetailsId() { return examDetailsId; } /** * @param examDetailsId the examDetailsId to set */ public void setExamDetailsId(Long examDetailsId) { this.examDetailsId = examDetailsId; } /** * @return the activityId */ public String getActivityId() { return activityId; } /** * @param activityId the activityId to set */ public void setActivityId(String activityId) { this.activityId = activityId; } /** * @return the contentInfo */ public String getContentInfo() { return contentInfo; } /** * @param contentInfo the contentInfo to set */ public void setContentInfo(String contentInfo) { this.contentInfo = contentInfo; } /** * @return the publishNow */ public String getPublishNow() { return publishNow; } /** * @param publishNow the publishNow to set */ public void setPublishNow(String publishNow) { this.publishNow = publishNow; } /** * @return the publishTime */ public java.util.Date getPublishTime() { return publishTime; } /** * @param publishTime the publishTime to set */ public void setPublishTime(java.util.Date publishTime) { this.publishTime = publishTime; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the downloadInAdvanceMinutes */ public Long getDownloadInAdvanceMinutes() { return downloadInAdvanceMinutes; } /** * @param downloadInAdvanceMinutes the downloadInAdvanceMinutes to set */ public void setDownloadInAdvanceMinutes(Long downloadInAdvanceMinutes) { this.downloadInAdvanceMinutes = downloadInAdvanceMinutes; } /** * @return the minutesOfExam */ public Long getMinutesOfExam() { return minutesOfExam; } /** * @param minutesOfExam the minutesOfExam to set */ public void setMinutesOfExam(Long minutesOfExam) { this.minutesOfExam = minutesOfExam; } /** * @return the answerStartTime */ public java.util.Date getAnswerStartTime() { return answerStartTime; } /** * @param answerStartTime the answerStartTime to set */ public void setAnswerStartTime(java.util.Date answerStartTime) { this.answerStartTime = answerStartTime; } /** * @return the answerEndTime */ public java.util.Date getAnswerEndTime() { return answerEndTime; } /** * @param answerEndTime the answerEndTime to set */ public void setAnswerEndTime(java.util.Date answerEndTime) { this.answerEndTime = answerEndTime; } /** * @return the minutesAfterTheStartToHandIn */ public Long getMinutesAfterTheStartToHandIn() { return minutesAfterTheStartToHandIn; } /** * @param minutesAfterTheStartToHandIn the minutesAfterTheStartToHandIn to set */ public void setMinutesAfterTheStartToHandIn(Long minutesAfterTheStartToHandIn) { this.minutesAfterTheStartToHandIn = minutesAfterTheStartToHandIn; } /** * @return the handInEndTime */ public java.util.Date getHandInEndTime() { return handInEndTime; } /** * @param handInEndTime the handInEndTime to set */ public void setHandInEndTime(java.util.Date handInEndTime) { this.handInEndTime = handInEndTime; } /** * @return the markStartTime */ public java.util.Date getMarkStartTime() { return markStartTime; } /** * @param markStartTime the markStartTime to set */ public void setMarkStartTime(java.util.Date markStartTime) { this.markStartTime = markStartTime; } /** * @return the markEndTime */ public java.util.Date getMarkEndTime() { return markEndTime; } /** * @param markEndTime the markEndTime to set */ public void setMarkEndTime(java.util.Date markEndTime) { this.markEndTime = markEndTime; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/controller/ErrorQuestionInfoController.java package com.enableets.edu.enable.cloud.exam.manager.report.controller; import com.enableets.edu.enable.cloud.exam.manager.core.BaseInfoManager; import com.enableets.edu.enable.cloud.exam.manager.core.Constants; import com.enableets.edu.sdk.pakage.ppr.dto.ErrorQuestionInfoDTO; import com.enableets.edu.sdk.pakage.ppr.dto.QueryErrorQuestionInfoDTO; import com.enableets.edu.sdk.pakage.ppr.dto.TeacherCourseInfoDTO; import com.enableets.edu.sdk.pakage.ppr.service.IPPRErrorQuestionInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping(value = Constants.CONTEXT_PATH + "/error/question") public class ErrorQuestionInfoController { private static final String PAGE_TEACHER_ERROR_QUESTIONS = "errorQuestion/indexTeacher"; @Autowired private IPPRErrorQuestionInfoService errorQuestionInfoServiceSDK; @Autowired private BaseInfoManager baseInfoManager; @RequestMapping(value = "/list") public String list(Model model) { String userId = baseInfoManager.getUserId(); List<TeacherCourseInfoDTO> subjects = errorQuestionInfoServiceSDK.getTeachSubject(userId, baseInfoManager.getSchoolId(userId), getTermId()); model.addAttribute("teachCourseList", subjects); model.addAttribute("teachGroups", baseInfoManager.getTeachGroup(userId, null, null)); model.addAttribute("termId", getTermId()); return PAGE_TEACHER_ERROR_QUESTIONS; } @PostMapping(value = "/getErrorQuestions") @ResponseBody public List<ErrorQuestionInfoDTO> getErrorQuestionsData(@RequestBody QueryErrorQuestionInfoDTO queryErrorQuestionInfoDTO){ List<ErrorQuestionInfoDTO> list = errorQuestionInfoServiceSDK.getErrorQuestionMasterList(queryErrorQuestionInfoDTO); return list; } @PostMapping(value = "/getErrorQuestionCount") @ResponseBody public Integer getErrorQuestionCount(@RequestBody QueryErrorQuestionInfoDTO queryErrorQuestionInfoDTO){ Integer num = errorQuestionInfoServiceSDK.getErrorQuestionCount(queryErrorQuestionInfoDTO); return num; } public String getTermId() { String userId = baseInfoManager.getUserId(); String schoolId = baseInfoManager.getSchoolId(userId); return baseInfoManager.getCurrentTermId(schoolId); } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/QuestionAxisVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import lombok.Data; /** * @author <EMAIL> * @since 2020/10/22 **/ @Data public class QuestionAxisVO { private String questionId; private String fileId; private Float xAxis; private Float yAxis; private Float width; private Float height; public Float getxAxis() { return xAxis; } public void setxAxis(Float xAxis) { this.xAxis = xAxis; } public Float getyAxis() { return yAxis; } public void setyAxis(Float yAxis) { this.yAxis = yAxis; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamLevelInfoDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.po.ExamLevelInfoPO; import com.enableets.edu.framework.core.dao.BaseDao; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @Auther: <EMAIL> * @Date: 2019/1/23 14:02 * @Description: 分数等级DAO */ public interface ExamLevelInfoDAO extends BaseDao<ExamLevelInfoPO> { /** * 查询考试等级 * @param schoolId * @param gradeCode * @return */ List<ExamLevelInfoPO> getExamInfo(@Param("schoolId") String schoolId, @Param("gradeCode") String gradeCode); } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/impl/DefaultExamLevelInfoService.java package com.enableets.edu.enable.cloud.sdk.exam.impl; import com.enableets.edu.enable.cloud.sdk.exam.IExamLevelInfoService; import com.enableets.edu.enable.cloud.sdk.exam.dto.ExamLevelInfoDTO; import com.enableets.edu.enable.cloud.sdk.exam.dto.ExamLevelTemplateDTO; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamLevelInfoFeignClient; import java.util.List; public class DefaultExamLevelInfoService implements IExamLevelInfoService { private IExamLevelInfoFeignClient examLevelInfoFeignClient; public DefaultExamLevelInfoService(IExamLevelInfoFeignClient examDetailsServiceFeignClient) { this.examLevelInfoFeignClient = examDetailsServiceFeignClient; } /** * 查询考试等级 * @param schoolId,gradeCode * @param gradeCode * @return */ @Override public List<ExamLevelInfoDTO> getExamLevelList(String schoolId, String gradeCode) { return examLevelInfoFeignClient.getExamLevelList(schoolId,gradeCode).getData(); } @Override public List<ExamLevelTemplateDTO> getLevelTemplate() { return examLevelInfoFeignClient.getLevelTemplate().getData(); } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/PaperQuestionAnswerBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Test Paper Structure-Question Answer Information */ @Data @NoArgsConstructor @AllArgsConstructor public class PaperQuestionAnswerBO { /** Question ID */ private Long questionId; /** Answer display text */ private String label; /** Answer matching strategy */ private String strategy; /** Answer analysis */ private String analysis; } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/jsTree/custom/leftTree.js $(function(){ // $("#leftTreeNav").jstree({ // 'core' : { // "multiple" : false, // 'data' : treeData, // 'dblclick_toggle': false //禁用tree的双击展开 // }, // "plugins" : ["search"] // }); $('#tree_1').jstree({ "core" : { 'data' : treeData, "themes" : { "responsive": false } }, "types" : { "default" : { "icon" : "fa fa-folder icon-state-warning icon-lg" }, "file" : { "icon" : "fa fa-file icon-state-warning icon-lg" } }, "plugins": ["types"] }); $('#tree_1').on('select_node.jstree', function(e,data) { var link = $('#' + data.selected).find('a'); if (link.attr("href") != "#" && link.attr("href") != "javascript:;" && link.attr("href") != "") { if (link.attr("target") == "_blank") { link.attr("href").target = "_blank"; } document.location.href = link.attr("href"); return false; } }); });<file_sep>/Exam Manager/src/main/resources/static/comm/plugins/paging/lang/zh_TW.js var $lang={ "prev_page" : "上一頁", "next_page" : "下一頁", "first_page" : "首頁", "last_page" : "尾頁" }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/PaperConfigReader.java package com.enableets.edu.enable.cloud.exam.manager.core; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @author <EMAIL> * @since 2020/09/03 **/ @Component @Data public class PaperConfigReader { @Value("${security.oauth2.sso.client.clientId:wiedu_application_key}") private String ssoClientId; @Value("${security.oauth2.sso.client.clientSecret:wiedu_application_secret}") private String ssoSecret; @Value("${storage.host.upload-url}") private String uploadFileUrl; @Value("${xkw.enable:false}") private boolean xkwEnable; @Value("${xkw.make-paper-url:null}") private String xkwMakePaperUrl; @Value("${xkw.appId:null}") private String xkwAppId; @Value("${xkw.secret:null}") private String xkwSecret; @Value("${xkw.get-paper-url:null}") private String getPaperUrl; @Value("${xkw.imgUrlHost:http://static.zujuan.xkw.com/}") private String imgUrlHost; @Value("${xkw.service-auth-url:null}") private String serviceAuthUrl; @Value("${xkw.save-paper-callback-url:null}") private String savePaperCallbackUrl; @Value("${xkw.iframe-url:null}") private String iframeUrl; @Value("${onlinefile.url:null}") private String onlineFileUrl; } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/ueditor/ueditor.modify.js /** * [deprecated] 已废弃 * write by duffy * 改配置文件是为了避免文件上传与后台打交道所使用,,只测试了文件上传部分,不支持重复性检查 */ (function() { /* 前后端通信相关的配置,注释只允许使用多行方式 */ var configData = { "fileUrl" : "/manager/studytask/upload", /* 上传图片配置项 */ "imageActionName" : "uploadimage", /* 执行上传图片的action名称 */ "imageFieldName" : "upfile", /* 提交的图片表单名称 */ "imageMaxSize" : 2048000, /* 上传大小限制,单位B */ "imageAllowFiles" : [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 上传图片格式显示 */ "imageCompressEnable" : true, /* 是否压缩图片,默认是true */ "imageCompressBorder" : 1600, /* 图片压缩最长边限制 */ "imageInsertAlign" : "none", /* 插入的图片浮动方式 */ "imageUrlPrefix" : "", /* 图片访问路径前缀 */ "imagePathFormat" : "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ /* {time} 会替换成时间戳 */ /* {yyyy} 会替换成四位年份 */ /* {yy} 会替换成两位年份 */ /* {mm} 会替换成两位月份 */ /* {dd} 会替换成两位日期 */ /* {hh} 会替换成两位小时 */ /* {ii} 会替换成两位分钟 */ /* {ss} 会替换成两位秒 */ /* 非法字符 \ : * ? " < > | */ /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ /* 涂鸦图片上传配置项 */ "scrawlActionName" : "uploadscrawl", /* 执行上传涂鸦的action名称 */ "scrawlFieldName" : "upfile", /* 提交的图片表单名称 */ "scrawlPathFormat" : "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "scrawlMaxSize" : 2048000, /* 上传大小限制,单位B */ "scrawlUrlPrefix" : "", /* 图片访问路径前缀 */ "scrawlInsertAlign" : "none", /* 截图工具上传 */ "snapscreenActionName" : "uploadimage", /* 执行上传截图的action名称 */ "snapscreenPathFormat" : "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "snapscreenUrlPrefix" : "", /* 图片访问路径前缀 */ "snapscreenInsertAlign" : "none", /* 插入的图片浮动方式 */ /* 抓取远程图片配置 */ "catcherLocalDomain" : [ "127.0.0.1", "localhost", "img.baidu.com" ], "catcherActionName" : "catchimage", /* 执行抓取远程图片的action名称 */ "catcherFieldName" : "source", /* 提交的图片列表表单名称 */ "catcherPathFormat" : "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "catcherUrlPrefix" : "", /* 图片访问路径前缀 */ "catcherMaxSize" : 2048000, /* 上传大小限制,单位B */ "catcherAllowFiles" : [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 抓取图片格式显示 */ /* 上传视频配置 */ "videoActionName" : "uploadvideo", /* 执行上传视频的action名称 */ "videoFieldName" : "upfile", /* 提交的视频表单名称 */ "videoPathFormat" : "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "videoUrlPrefix" : "", /* 视频访问路径前缀 */ "videoMaxSize" : 102400000, /* 上传大小限制,单位B,默认100MB */ "videoAllowFiles" : [ ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid" ], /* 上传视频格式显示 */ /* 上传文件配置 */ "fileActionName" : "uploadfile", /* controller里,执行上传视频的action名称 */ "fileFieldName" : "upfile", /* 提交的文件表单名称 */ "filePathFormat" : "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */ "fileUrlPrefix" : "", /* 文件访问路径前缀 */ "fileMaxSize" : 51200000, /* 上传大小限制,单位B,默认50MB */ "fileAllowFiles" : [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ], /* 上传文件格式显示 */ /* 列出指定目录下的图片 */ "imageManagerActionName" : "listimage", /* 执行图片管理的action名称 */ "imageManagerListPath" : "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */ "imageManagerListSize" : 20, /* 每次列出文件数量 */ "imageManagerUrlPrefix" : "", /* 图片访问路径前缀 */ "imageManagerInsertAlign" : "none", /* 插入的图片浮动方式 */ "imageManagerAllowFiles" : [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 列出的文件类型 */ /* 列出指定目录下的文件 */ "fileManagerActionName" : "listfile", /* 执行文件管理的action名称 */ "fileManagerListPath" : "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */ "fileManagerUrlPrefix" : "", /* 文件访问路径前缀 */ "fileManagerListSize" : 20, /* 每次列出文件数量 */ "fileManagerAllowFiles" : [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml" ] /* 列出的文件类型 */ } /** * 获取url */ delete UE.Editor.prototype.getActionUrl; UE.Editor.prototype.getActionUrl = function(action) { var actionName = this.getOpt(action) || action, fileUrl = this.getOpt('fileUrl'), //文件上传路径 serverUrl = this.getOpt('serverUrl'); if (actionName === 'uploadimage' || actionName === 'uploadfile') { return fileUrl; } return serverUrl; } /** * 加载后台config文件修改,不请求后台数据 */ delete UE.Editor.prototype.loadServerConfig; UE.Editor.prototype.loadServerConfig = function() { var me = this; setTimeout(function() { me.fireEvent('serverConfigLoaded'); UE.utils.extend(me.options, configData); if (window.uploadFileUrl != undefined && window.uploadFileUrl != null) { me.options.fileUrl = window.uploadFileUrl;// 设置上传文件url } me._serverConfigLoaded = true; }); }; })();<file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/service/ExamDetailsService.java package com.enableets.edu.enable.cloud.exam.framework.service; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamDetailsInfoBO; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamResultInfoBO; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamStatisticsInfoV2BO; import com.enableets.edu.enable.cloud.exam.framework.core.ErrorConstants; import com.enableets.edu.enable.cloud.exam.framework.dao.ExamDetailsInfoDAO; import com.enableets.edu.enable.cloud.exam.framework.dao.ExamDetailsStepTaskInfoDAO; import com.enableets.edu.enable.cloud.exam.framework.po.ExamDetailsInfoPO; import com.enableets.edu.enable.cloud.exam.framework.po.ExamDetailsStepTaskInfoPO; import com.enableets.edu.enable.cloud.exam.framework.po.ExamStatisticsInfoPO; import com.enableets.edu.framework.core.service.ServiceAdapter; import com.enableets.edu.framework.core.util.BeanUtils; import com.enableets.edu.module.service.core.MicroServiceException; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import tk.mybatis.mapper.entity.Example; import java.util.*; @Service public class ExamDetailsService extends ServiceAdapter<ExamDetailsInfoBO, ExamDetailsInfoPO> { /** exam info service */ @Autowired private ExamInfoService examInfoService; @Autowired private ExamDetailsInfoDAO examDetailsDAO; @Autowired private ExamDetailsStepTaskInfoDAO examDetailsStepTaskInfoDAO; @Autowired private ExamResultInfoService examResultInfoService; public List<ExamStatisticsInfoV2BO> queryExamDetailsInfoV2(Map<String, Object> condition) { List<ExamStatisticsInfoPO> examStatisticsList = examDetailsDAO.queryExamDetailsInfoV2(condition); return BeanUtils.convert(examStatisticsList, ExamStatisticsInfoV2BO.class); } public Integer countExamDetailsInfoV2(Map<String, Object> condition) { return examDetailsDAO.countV2(condition); } /** * 根据考试详情id查询考试详情和考试结果 * * @param examDetailsId * @return */ public ExamDetailsInfoBO getExamDetailsByExamDetailsId(Long examDetailsId) { Map<String, Object> map = new HashMap<>(); map.put("examDetailsId", examDetailsId); List<ExamDetailsInfoPO> examDetails = examDetailsDAO.queryExamDetails(map); ExamDetailsInfoBO examDetailsBO = null; if (!CollectionUtils.isEmpty(examDetails)) { examDetailsBO = BeanUtils.convert(examDetails.get(0), ExamDetailsInfoBO.class); List<ExamResultInfoBO> examResultInfoList = examResultInfoService.getExamResultInfo(examDetailsId); if (CollectionUtils.isEmpty(examResultInfoList)) { examDetailsBO.setExamResultInfoList(null); } else { examDetailsBO.setExamResultInfoList(examResultInfoList); } } return examDetailsBO; } /** * bind activity to exam detail * @param examDetailsIds exam details * @param activityId activity id */ public boolean bindStepTask(String examDetailsIds, String activityId) { Assert.hasText(examDetailsIds, "exam details cannot be empty!"); Assert.hasText(activityId, "activity id cannot be empty!"); List<String> detailsIdList = Arrays.asList(examDetailsIds.split(",")); // 1. check exam info Map<String, Object> map = new HashMap<>(); map.put("examDetailsId", detailsIdList.get(0)); List<ExamDetailsInfoPO> examDetails = examDetailsDAO.queryExamDetails(map); if (CollectionUtils.isEmpty(examDetails) || examDetails.get(0) == null) { throw new MicroServiceException(ErrorConstants.ERROR_CODE_EXAM_NOT_EXISTS, ErrorConstants.ERROR_MESSAGE_EXAM_NOT_EXISTS); } Long examId = examDetails.get(0).getExamId(); // 2. update details activity id Example example = new Example(ExamDetailsStepTaskInfoPO.class); example.createCriteria().andIn("examDetailsId", detailsIdList); ExamDetailsStepTaskInfoPO po = new ExamDetailsStepTaskInfoPO(); po.setActivityId(activityId); po.setUpdateTime(Calendar.getInstance().getTime()); boolean result = examDetailsStepTaskInfoDAO.updateByExampleSelective(po, example) > 0; // 3. update exam publish status examInfoService.updatePublishStatus(examId); return result; } } <file_sep>/Exam Manager/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.enableets.edu.enable.cloud.exam</groupId> <artifactId>enable-cloudexam-manager</artifactId> <version>1.0.0.RELEASE</version> <name>Enable Cloud Exam Manger</name> <parent> <groupId>com.enableets.edu.framework</groupId> <artifactId>enableets-manager-extension-parent</artifactId> <version>1.0.3.RELEASE</version> <relativePath></relativePath> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <jsoup.version>1.11.3</jsoup.version> </properties> <dependencies> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>${jsoup.version}</version> </dependency> <dependency> <groupId>com.enableets.edu.module</groupId> <artifactId>enableets-module-security</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-content</artifactId> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-account-v2</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-school3-v2</artifactId> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-steptask</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-activity-v2</artifactId> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-package</artifactId> <version>1.0.1.RELEASE</version> </dependency> <dependency> <groupId>com.enableets.edu.ueditor</groupId> <artifactId>ueditor-service</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-group</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> </dependency> <!-- acm sdk --> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>acm-menu-provider</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-assessment</artifactId> <version>1.0.0.RELEASE</version> </dependency> <dependency> <groupId>com.enableets.edu.sdk</groupId> <artifactId>sdk-paper</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> </plugin> </plugins> </build> </project> <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/jsTree/selectclass-tree.js /** * */ (function($){ var streeSelect = { //inputWarpClass外层类名 ,streeWarpId放置tree的层,Datas数据(此处为url,取消data里面的注释部分即可使用) //treePlugins单选多选的展现方式 selectType为选择方式(单选false或者多选true) // selectData已选数据数组 init : function(inputWarpClass,streeWarpId,Datas,selectType, selectData){ this.streeInitCheckbox(inputWarpClass,streeWarpId,Datas,selectType, selectData); this.inputClick(inputWarpClass); }, inputClick:function(inputWarpClass){ $(inputWarpClass).find('div.out1').on("click",function(e){ e.stopPropagation(); $(inputWarpClass).find('.stree_warp').toggle(); }).on("focus", function(){ this.blur(); }); }, streeInitCheckbox:function(inputWarpClass,streeWarpId,Datas,selectType, selectData){ var plugins=[]; if (selectType) { plugins=["wholerow","checkbox","types","changed"]; } else{ plugins=["wholerow","types","changed"]; } $(streeWarpId) .jstree({ 'plugins': plugins, 'checkbox': {      "three_state": selectType //父子级不关联选中  }, 'core': { "multiple": selectType,//单选 "themes" : { "responsive": false }, "check_callback" : true, 'data': Datas }, "types" :{ "default" : { "icon" : "fa fa-folder icon-state-warning icon-lg" }, "file" : { "icon" : "fa fa-file icon-state-warning icon-lg" } } }).bind("load_node.jstree", function(e, data) { if (selectData != null) { // 设置已选数据 var ref = $(streeWarpId).jstree(true); for (var i = 0; i < selectData.length; i++) { var node = ref.get_node(selectData[i]); if (node) { ref.check_node(node); } } } }).on("changed.jstree", function (e, data) { if (data.action = "select_node" && data.node != null) { jsTreeChecked(data.node, streeWarpId); } }); //取消按钮关闭下拉树 $(".streeControl_box .streeCancel").on('click',function(){ $(inputWarpClass).find('.stree_warp').hide(); }) //点击下拉树以外部分关闭下拉树 $(inputWarpClass).siblings().on('click',function(event){ $(inputWarpClass).find('.stree_warp').hide(); }); $(inputWarpClass).parents().siblings().on('click',function(event){ $(inputWarpClass).find('.stree_warp').hide(); event.stopPropagation(); }); } }; function initDropTree(obj, treeData, selectData){ if ($(obj).next().length == 0 || !$(obj).next().hasClass(".stree_warp")) { var treeId = $(obj).attr("id"); if (treeId == undefined || treeId == "") { treeId = "tree" + Math.random() * 10000; } else { treeId = treeId + "tree"; } $(obj).after('<div class="stree_warp select_tree">' + '<div class="stree_box" id="' + treeId + '">' + '</div></div>'); } streeSelect.init($(obj).parent(), '#' + treeId ,treeData, true, selectData); $(obj).next().hide(); } $.fn.treeSelect = function(){ initDropTree(this, arguments[0], arguments[1]) }; })(jQuery); function jsTreeChecked(currentNode, streeWarpId) { // 获取当前节点 var nodeId = currentNode.id; var text = currentNode.text; var checked = currentNode.state.selected; if (checked) { $("#in1").append(addcontact(currentNode)); } else { $("#in1").find("#div_"+nodeId).remove(); } var parentId = currentNode.parent; var ref = $(streeWarpId).jstree(true); //表示是根节点 if (parentId == "#") { var child = currentNode.children; for (var i = 0; i < child.length; i ++) { var id = child[i]; $("#in1").find("#div_"+id).remove(); } } else { //子节点 var node = ref.get_node(parentId); var child = node.children; var flag = true; for (var i = 0; i < child.length; i ++) { var state = ref.get_node(child[i]).state.selected; if (!state) { flag = false; } } //全部子节点被勾选,则移除单个子节点,加入整个父节点 if (flag) { for (var i = 0; i < child.length; i ++) { var id = child[i]; $("#in1").find("#div_"+id).remove(); } $("#in1").append(addcontact(node)); } else { var $parent = $("#in1").find("#div_"+parentId); if($parent.length>0) { $parent.remove(); for (var i = 0; i < child.length; i ++) { var childNode = ref.get_node(child[i]); var state = childNode.state.selected; if (state) { $("#in1").append(addcontact(childNode)); } } } } } } function addcontact(node) { var div = "<div id='div_"+node.id+"' style='width:auto;float:left;'>"+ "<a onclick=javascript:deleteJSTree('"+node.id+"');>"+node.text+"</a>;</div>"; return div; } function deleteJSTree(id) { var ref = $('#classestree').jstree(true); $("#in1").find("#div_"+id).remove(); ref.uncheck_node(ref.get_node(id)); } function getSelectAll(id) { var ref = $("#"+id).jstree(true); var nodes = $("#"+id).jstree("get_checked"); var toArray = new Array(); for(var i=0;i<nodes.length;i++){ var nodeInfo = ref.get_node(nodes[i]); if(ref.is_leaf(nodeInfo)){ toArray.push(nodeInfo.id); } } return toArray; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/controller/PaperInfoController.java package com.enableets.edu.enable.cloud.exam.manager.paper.controller; import com.alibaba.fastjson.JSON; import com.enableets.edu.acm.menu.provider.util.BeanUtils; import com.enableets.edu.enable.cloud.exam.manager.bo.TeacherBaseInfoBO; import com.enableets.edu.enable.cloud.exam.manager.bo.xkw.XKWPaperBO; import com.enableets.edu.enable.cloud.exam.manager.core.*; import com.enableets.edu.enable.cloud.exam.manager.paper.bo.ContentKnowledgeInfoBO; import com.enableets.edu.enable.cloud.exam.manager.paper.bo.PaperInfoBO; import com.enableets.edu.enable.cloud.exam.manager.paper.service.PaperInfoService; import com.enableets.edu.enable.cloud.exam.manager.paper.service.XKWService; import com.enableets.edu.enable.cloud.exam.manager.paper.vo.QueryPaperVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <EMAIL> * @date 2021/06/18 **/ @Controller @RequestMapping(value = Constants.CONTEXT_PATH + "/paper") public class PaperInfoController { /** 基础信息 */ @Autowired private BaseInfoManager baseInfo; @Autowired private PaperConfigReader paperConfigReader; @Autowired private XKWService xkwService; @Autowired private PaperInfoService paperInfoService; @Autowired private DictionaryInfoService dictionaryInfoService; @RequestMapping(value = "/xkw") public String xkw(){ String userId = baseInfo.getUserId(); return "redirect:" + paperConfigReader.getXkwMakePaperUrl() + userId; } @RequestMapping(value = "/xkw/notice") public String notice(String paperid, String openid, HttpServletRequest request, Model model){ // String paperStr = xkwService.get(paperid, openid); // String fieldDomainUrl = xkwService.add(JSON.parseObject(paperStr, XKWPaperBO.class)); // return "redirect:"+fieldDomainUrl+"/manager/paper/list"; model.addAttribute("paperId", paperid); model.addAttribute("openId", openid); return "paperV3/progressing"; } @ResponseBody @RequestMapping(value = "/xkw/download") public OperationResult<String> download(String paperId, String openId){ String paperStr = xkwService.get(paperId, openId); String fieldDomainUrl = xkwService.add(JSON.parseObject(paperStr, XKWPaperBO.class)); return new OperationResult<>(fieldDomainUrl + "/manager/paper/list"); } @RequestMapping(value = "/index") public String index(){ String userId = baseInfo.getUserId(); return "paper/paperInfo"; } /** * Query Knowledges * * @param gradeCode Grade Code * @param subjectCode Subject Code * @param materialVersion * @return */ @RequestMapping(value = "/list") public String list(String providerCode, Model model) { String userId = baseInfo.getUserId(); TeacherBaseInfoBO teacherBaseInfo = baseInfo.getTeacherBaseInfo(userId); QueryPaperVO queryPaperVO1 = new QueryPaperVO(); //queryPaperVO1.setProviderCode("R01"); /*queryPaperVO1.setStageCode(teacherBaseInfo.getStageCode()); queryPaperVO1.setGradeCode(teacherBaseInfo.getGradeCode()); queryPaperVO1.setSubjectCode(teacherBaseInfo.getSubjectCode()); queryPaperVO1.setMaterialVersion(teacherBaseInfo.getMaterialVersion().getCode());*/ //queryPaperVO1.setUsageCode("assessment"); queryPaperVO1.setOffset(0); queryPaperVO1.setRows(10); PaperInfoBO paperInfoBO = BeanUtils.convert(queryPaperVO1, PaperInfoBO.class); paperInfoBO.setCreator(userId); paperInfoBO.setSchoolId(baseInfo.getSchoolId(userId)); paperInfoBO.setZoneCode(baseInfo.getUserZone(baseInfo.getUserId())); //paperInfoBO.setSearchCode("310113VER72NR711"); HashMap<String, Object> map = paperInfoService.query(paperInfoBO); model.addAttribute("paperList", map.get("paperList")); model.addAttribute("paperCount", map.get("paperCount")); /* List<ContentKnowledgeInfoBO> knowledgeInfos = dictionaryInfoService.contentKnowledge(gradeCode, subjectCode, materialVersion); model.addAttribute("knowledgeInfos", knowledgeInfos);*/ model.addAttribute("userId", userId); model.addAttribute("teacherBaseInfo", teacherBaseInfo); return "paper/paperInfo"; } /** * Query Knowledges * @param gradeCode Grade Code * @param subjectCode Subject Code * @param materialVersion * @return */ @RequestMapping(value = "/knowledge/query") @ResponseBody public HashMap<String, Object> queryKnowledge(){ HashMap<String, Object> map = new HashMap<>(); String userId = baseInfo.getUserId(); TeacherBaseInfoBO teacherBaseInfo = baseInfo.getTeacherBaseInfo(userId); map.put("teacherBaseInfo",teacherBaseInfo); List<ContentKnowledgeInfoBO> knowledgeInfos = dictionaryInfoService.contentKnowledge(teacherBaseInfo.getGradeCode(), teacherBaseInfo.getSubjectCode(), teacherBaseInfo.getMaterialVersion().getCode()); map.put("knowledgeInfos",knowledgeInfos); return map; } @RequestMapping(value = "/query") public String getPaperList(Model model) { String userId = baseInfo.getUserId(); TeacherBaseInfoBO teacherBaseInfo = baseInfo.getTeacherBaseInfo(userId); QueryPaperVO queryPaperVO1 = new QueryPaperVO(); queryPaperVO1.setProviderCode("R01"); queryPaperVO1.setOffset(0); queryPaperVO1.setRows(10); PaperInfoBO paperInfoBO = BeanUtils.convert(queryPaperVO1, PaperInfoBO.class); paperInfoBO.setCreator(userId); paperInfoBO.setSchoolId(baseInfo.getSchoolId(userId)); paperInfoBO.setZoneCode(baseInfo.getUserZone(baseInfo.getUserId())); HashMap<String, Object> map = paperInfoService.query(paperInfoBO); model.addAttribute("paperList", map.get("paperList")); return "paper/paperInfo::stepList"; //return new OperationResult<List<QueryPaperVO>>(BeanUtils.convert(map.get("paperList"), QueryPaperVO.class)); } } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/IExamDictionaryService.java package com.enableets.edu.enable.cloud.sdk.exam; import com.enableets.edu.enable.cloud.sdk.exam.dto.QueryExamDictionaryDTO; import com.enableets.edu.enable.cloud.sdk.exam.dto.QueryExamDictionaryResultDTO; import java.util.List; /** * @Auther: <EMAIL> * @Date: 2019/1/23 16:20 * @Description: 数据字典接口 */ public interface IExamDictionaryService { public List<QueryExamDictionaryResultDTO> query(QueryExamDictionaryDTO query); } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/handler/ResponseResultHandler.java package com.enableets.edu.enable.cloud.exam.microservice.handler; import com.enableets.edu.enable.cloud.exam.microservice.annotation.ResponseResult; import com.enableets.edu.module.service.core.Response; import com.enableets.edu.module.service.core.ResponseTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import javax.servlet.http.HttpServletRequest; /** * @author <EMAIL> * @date 2021/03/16 **/ @ControllerAdvice public class ResponseResultHandler implements ResponseBodyAdvice<Object> { @Autowired protected ResponseTemplate responseTemplate; @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = sra.getRequest(); ResponseResult responseResult = (ResponseResult)request.getAttribute(ResponseResultInterceptor.RESPONSE_RESULT_ANN); return responseResult == null ? false : true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { if (body instanceof Response) return body; return responseTemplate.format(body); } } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/js/Constants.js var Constants = window.Constants = { "PROVIDER_CODE_PERSONAL" : "R00", //个人资源 "PROVIDER_CODE_PUBLIC" : "R01", // 平台资源 "PROVIDER_CODE_SCHOOL" : "R02", // 校本资源 "PROVIDER_CODE_QIUJIEDA" : "R04", // 求解答资源 "EXAM_KIND_LEVEL" : 1, //试卷卷别level "EXAM_QUES_TYPE_LEVEL" : 2, //试卷题型level "EXAM_QUES_LEVEL" : 3, //试卷题目level "EXAM_QUES_CHILD_LEVEL" : 4, //试卷子题目level "MICRO_COURSE_USAGE_CODE" : "microCourse" // 微课试卷 } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/core/LongJsonDeserializer.java package com.enableets.edu.enable.cloud.exam.manager.paper.core; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * 反序列化时将string转化成long,解决异步请求返回参数转json时,long失精度 * @author <EMAIL> * @since 2017年11月6日 */ public class LongJsonDeserializer extends JsonDeserializer<Long> { private static final Logger log = LoggerFactory.getLogger(LongJsonDeserializer.class); @Override public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { String value = p.getText(); try { return value == null? null : Long.parseLong(value); } catch (Exception e) { log.error("parse Long error!", e); return null; } } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWPartBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; import java.util.List; /** * 试卷主体 * * @author <EMAIL> * @since 2020/09/01 13:48 **/ @Data public class XKWPartBO { private List<XKWPartBodyBO> partBody; private XKWPartHeadBO partHead; } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/IExamLevelInfoService.java package com.enableets.edu.enable.cloud.sdk.exam; import com.enableets.edu.enable.cloud.sdk.exam.dto.ExamLevelInfoDTO; import com.enableets.edu.enable.cloud.sdk.exam.dto.ExamLevelTemplateDTO; import java.util.List; /** * 考试等级接口 */ public interface IExamLevelInfoService { /** * 查询考试等级 * @param schoolId,gradeCode * @return */ public List<ExamLevelInfoDTO> getExamLevelList(String schoolId, String gradeCode); /** * 管理员管理考试分数等级信息 * jackli * @param * @return */ public List<ExamLevelTemplateDTO> getLevelTemplate(); } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamDetailsInfoDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.po.ExamDetailsInfoPO; import com.enableets.edu.enable.cloud.exam.framework.po.ExamStatisticsInfoPO; import com.enableets.edu.framework.core.dao.BaseDao; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 考试明细DAO */ public interface ExamDetailsInfoDAO extends BaseDao<ExamDetailsInfoPO> { List<ExamDetailsInfoPO> queryDetailsByExamId(Long examId); List<ExamStatisticsInfoPO> queryExamDetailsInfoV2(Map<String, Object> condition); Integer countV2(Map<String, Object> condition); List<ExamDetailsInfoPO> queryExamDetails(Map<String,Object> map); void batchInsert(List<ExamDetailsInfoPO> detailList); } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/js/head.js $(document).ready(function(){ setMinHeight(0); }); //设置随着屏幕大小变化 window.addEventListener("resize",function(){ setMinHeight(0); }); //主体部分设置一个最低高度 function setMinHeight(Number){ function MinHeight(minHight){ if ($("#footer").length > 0) { var footerh=$("#footer").outerHeight(); minHight=minHight-footerh; $(".mainContent").css('min-height',minHight); } else if($("#footer2").length > 0) { var footerh=$("#footer2").outerHeight(); minHight=minHight-footerh; $(".mainContent").css('min-height',minHight); } } if ($(".header").length > 0) { var minHight=$(window).height()-$(".header").outerHeight()-Number; MinHeight(minHight); }else if ($(".header3").length > 0) { var minHight=$(window).height()-$(".header3").outerHeight()-Number; MinHeight(minHight); } else{ var minHight=$(window).height()-Number; MinHeight(minHight); } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/EditQuestionOptionInfoVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * 题目选项信息vo * @author duffy_ding * @since 2017/12/29 */ @JsonIgnoreProperties(ignoreUnknown = true) public class EditQuestionOptionInfoVO { /** 选项标识*/ private String optionId; /** 选项标题 */ private String alias; /** 选项内容 */ private String lable; /** 选项排序 */ private String sequencing; public String getOptionId() { return optionId; } public void setOptionId(String optionId) { this.optionId = optionId; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getLable() { return lable; } public void setLable(String lable) { this.lable = lable; } public String getSequencing() { return sequencing; } public void setSequencing(String sequencing) { this.sequencing = sequencing; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/utils/Utils.java package com.enableets.edu.enable.cloud.exam.framework.utils; import com.enableets.edu.enable.cloud.exam.framework.core.Constants; /** * @author duffy_ding * @since 2020/07/29 */ public class Utils { /** * 查询资料总数量,默认50,最大单次200 * @param rows 数量 * @return 处理后查询数量 */ public static Integer rows(Integer rows) { if (rows == null || rows < 0) { rows = Constants.DEFAULT_QUERY_ROWS; } else if (rows > Constants.MAX_QUERY_ROWS) { rows = Constants.MAX_QUERY_ROWS; } return rows; } /** * 查询资料起始位置,默认为0 * @param offset 起始位置 * @return 处理后起始位置 */ public static Integer offset(Integer offset) { if (offset == null || offset < 0) { offset = 0; } return offset; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/DictionaryInfoService.java package com.enableets.edu.enable.cloud.exam.manager.core; import com.enableets.edu.enable.cloud.exam.manager.bo.CodeNameMapBO; import com.enableets.edu.enable.cloud.exam.manager.paper.bo.ContentKnowledgeInfoBO; import com.enableets.edu.enable.cloud.exam.manager.paper.core.PPRConstants; import com.enableets.edu.framework.core.util.BeanUtils; import com.enableets.edu.framework.core.util.JsonUtils; import com.enableets.edu.sdk.content.dto.ContentDictionaryInfoDTO; import com.enableets.edu.sdk.content.dto.ContentKnowledgeInfoDTO; import com.enableets.edu.sdk.content.service.IContentDictionaryInfoService; import com.enableets.edu.sdk.content.service.IContentInfoService; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Base Info Service * @author <EMAIL> * @since 2020/08/06 **/ @Component public class DictionaryInfoService { /** Content SDK Client*/ @Autowired private IContentDictionaryInfoService contentDictionaryInfoServiceSDK; @Autowired private StringRedisTemplate stringRedisTemplate; /** Content SDK Client*/ @Autowired private IContentInfoService contentInfoServiceSDK; /** * Content Dictionary Stage Info * @return List */ public List<CodeNameMapBO> contentStage(){ return contentDictionary(Constants.DICTIONARY_STAGE_TYPE_CODE); } /** * Get Stage Name By Code * @param code Code * @return */ public String matchStageName(String code){ return getName(Constants.DICTIONARY_STAGE_TYPE_CODE, code); } /** * Content Dictionary Grade Info * @return List */ public List<CodeNameMapBO> contentGrade(){ return contentDictionary(Constants.DICTIONARY_TYPE_GRADE); } /** * Get Grade Name By Code * @param code * @return */ public String matchGradeName(String code){ return getName(Constants.DICTIONARY_TYPE_GRADE, code); } /** * Content Dictionary Subject Info * @return List */ public List<CodeNameMapBO> contentSubject(){ return contentDictionary(Constants.DICTIONARY_SUBJECT_TYPE_CODE); } /** * Get Subject Name By Code * @param code Code * @return */ public String matchSubjectName(String code){ return getName(Constants.DICTIONARY_SUBJECT_TYPE_CODE, code); } /** * Content Dictionary MaterialVersion Info * @return */ public List<CodeNameMapBO> contentMaterialVersion(){ return contentDictionary(Constants.DICTIONARY_MATERIAL_TYPE_CODE); } /** * Get Material Version Name By Code * @param code * @return */ public String matchMaterialVersionName(String code){ return getName(Constants.DICTIONARY_MATERIAL_TYPE_CODE, code); } /** * Content Dictionary Question Type Info * @return */ public List<CodeNameMapBO> contentQuestionType(){ return contentDictionary(Constants.DICTIONARY_QUESTONTYPE_TYPE_CODE); } /** * Get Question Type Name By Id */ public String matchQuestionTypeName(String id){ return getName(Constants.DICTIONARY_QUESTONTYPE_TYPE_CODE, id); } /** * Content Dictionary Ability Info * @return */ public List<CodeNameMapBO> contentAbility(){ return contentDictionary(Constants.DICTIONARY_ABILITY_TYPE_CODE); } /** * Get Ability Name by Id * @param id * @return */ public String matchAbilityName(String id){ return getName(Constants.DICTIONARY_ABILITY_TYPE_CODE, id); } /** * Content Dictionary Difficulty Info * @return */ public List<CodeNameMapBO> contentDifficulty(){ return contentDictionary(Constants.DICTIONARY_DIFFICULTY_TYPE_CODE); } /** * Get Difficulty Name by Id * @param id * @return */ public String matchDifficultyName(String id){ return getName(Constants.DICTIONARY_DIFFICULTY_TYPE_CODE, id); } private String getName(String type, String code){ List<CodeNameMapBO> codeNameMapBOS = this.contentDictionary(type); if (CollectionUtils.isEmpty(codeNameMapBOS)) return null; String name = null; for (CodeNameMapBO codeNameMapBO : codeNameMapBOS) { if (codeNameMapBO.getCode().equals(code)) { name = codeNameMapBO.getName(); break; } } return name; } /** * Get Base Info From Content * @param type Base Info Type * @return */ private List<CodeNameMapBO> contentDictionary(String type){ if (StringUtils.isBlank(type)) return null; String dictionaryKey = new StringBuilder("com:enableets:edu:paper:content:dictionary:type:").append(type).toString(); String jsonStr = stringRedisTemplate.opsForValue().get(dictionaryKey); if (StringUtils.isNotBlank(jsonStr)) return JsonUtils.convert2List(jsonStr, CodeNameMapBO.class); List<ContentDictionaryInfoDTO> dictionaries = contentDictionaryInfoServiceSDK.query(Constants.DEFAULT_SCHOOL_ID, type, null, null, null, "0");//Query All if (CollectionUtils.isEmpty(dictionaries)) return null; List<CodeNameMapBO> dics = dictionaries.stream().map(e -> new CodeNameMapBO(e.getCode(), e.getName())).collect(Collectors.toList()); stringRedisTemplate.opsForValue().set(dictionaryKey, JsonUtils.convert(dics), Constants.DEFAULT_REDIS_CACHE_EXPIRE_TIME, TimeUnit.SECONDS); return dics; } /** * Get Knowledge Info */ public List<ContentKnowledgeInfoBO> contentKnowledge(String gradeCode, String subjectCode, String materialVersion){ if (StringUtils.isBlank(subjectCode) || StringUtils.isBlank(materialVersion)) return null; StringBuilder sb = new StringBuilder(PPRConstants.PACKAGE_PPR_CACHE_KEY_PREFIX).append("paper:knowledge:"); if (StringUtils.isNotBlank(gradeCode)) sb.append(gradeCode); String knowledgeCacheKey = sb.append(gradeCode).append(subjectCode).append(materialVersion).toString(); String knowledgeStr = stringRedisTemplate.opsForValue().get(knowledgeCacheKey); if (StringUtils.isNotBlank(knowledgeStr)){ return JsonUtils.convert2List(knowledgeStr, ContentKnowledgeInfoBO.class); } try { List<ContentKnowledgeInfoDTO> knowledgeDTOs = contentInfoServiceSDK.getKnowledgeList(gradeCode, subjectCode, materialVersion, Constants.CONTENT_PUBLIC_TYPE, null).getData(); List<ContentKnowledgeInfoBO> knowledgeInfos = knowledgeDTOs.stream().map(e -> BeanUtils.convert(e, ContentKnowledgeInfoBO.class)).collect(Collectors.toList()); stringRedisTemplate.opsForValue().set(knowledgeCacheKey, JsonUtils.convert(knowledgeInfos), Constants.DEFAULT_REDIS_CACHE_EXPIRE_TIME, TimeUnit.SECONDS); return knowledgeInfos; }catch (Exception e){ e.printStackTrace(); } return null; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/QuestionInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.Data; import java.util.List; @Data public class QuestionInfoBO { /** 题目资源标识*/ private Long questionContentId; /**源资源*/ private String providerContentId; /** 题目类型 */ private String questionId; /** 资源来源*/ private String providerCode; /** 题目类型 */ private CodeNameMapBO type; /** 学段标识 */ private CodeNameMapBO stage; /** 年级标识 */ private CodeNameMapBO grade; /** 学科标识 */ private CodeNameMapBO subject; /** 能力标识 */ private CodeNameMapBO ability; /* 学习表现 */ private List<PreformanceBO> preformanceList; /** 难易度标识 */ private CodeNameMapBO difficulty; /**题号*/ private String questionNo; /** 知识点信息列表 */ private List<KnowledgeInfoBO> knowledgeList; /** 题目分数 */ private Float points; /** 子题目个数 */ private Integer childAmount; /** 题干信息 */ private QuestionStemInfoBO stem; /** 选项信息 */ private List<QuestionOptionBO> options; /* *//** 答案信息 *//* private AnswerInfoDTO answer;*/ /** 听力原文*/ private String listen; /** 听力文件url */ private String affixId; /** 听力文件url */ private String affix; /* *//** 子题目信息 *//* private List<QueryQuestionChildInfoResultDTO> children;*/ /** 标签信息 */ private List<CodeNameMapBO> tags; /** 学校信息 */ private IdNameMapBO school; /** 用户信息 */ private IdNameMapBO user; /**版本*/ private CodeNameMapBO materialVersion; private String source; /**使用次数*/ private Integer downloadNumber; /* 用途 */ private String usageCode; } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/po/ExamQuestionMarkAssigneePO.java package com.enableets.edu.enable.cloud.exam.framework.po; import com.enableets.edu.framework.core.dao.BasePO; import lombok.Data; import lombok.experimental.Accessors; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * the teacher info in exam which marked the question * @author duffy_ding * @since 2020/05/29 */ @Entity @Table(name = "exam_question_mark_assignee") public class ExamQuestionMarkAssigneePO extends BasePO { /** exam id */ @Id @Column(name = "exam_id") private String examId; /** course id */ @Id @Column(name = "course_id") private String courseId; /** question id */ @Id @Column(name = "question_id") private String questionId; /** user id of teacher which marked the question */ @Id @Column(name = "user_id") private String userId; /** user id of teacher which marked the question */ @Column(name = "full_name") private String fullName; public String getExamId() { return examId; } public void setExamId(String examId) { this.examId = examId; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getQuestionId() { return questionId; } public void setQuestionId(String questionId) { this.questionId = questionId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/vo/BeginReportVO.java package com.enableets.edu.enable.cloud.exam.manager.report.vo; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; /** * @author <EMAIL> * @date 2021/6/22 **/ public class BeginReportVO { /** * termId */ private String termId; /** * gradeId */ private String gradeId; /** * subjectId */ private String subjectId; /** * testType */ private String testType; /** * offset */ private Integer offset; /** * rows */ private Integer rows; public BeginReportVO() { } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public String getGradeId() { return gradeId; } public void setGradeId(String gradeId) { this.gradeId = gradeId; } public String getSubjectId() { return subjectId; } public void setSubjectId(String subjectId) { this.subjectId = subjectId; } public String getTestType() { return testType; } public void setTestType(String testType) { this.testType = testType; } public Integer getOffset() { return offset; } public void setOffset(Integer offset) { this.offset = offset; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } }<file_sep>/Exam Manager/src/main/resources/static/comm/v5/fragments/fragments.5.0.js $(document).attr("title","三三云学堂"); $(document.head).append("<meta name=\"referrer\" content=\"no-referrer\"/>"); var headerFn = function(){ // logo图片 $(".main .header .header_tp > img.logoImg").on('click', function() { window.location.href = window.location.href.replace(window.location.pathname, ''); }); } //滚动条高度判断返回顶部按钮是否出现 function scrolltopFn($scrollTops){ //加入点击返回按钮 var $backBtn=$("<div id='backtop-btn' class='backtop-btn'><i></i></div>"); if ($("#backtop-btn").length == 0) { $("body").append($backBtn); } scrollFn($scrollTops); $("#backtop-btn").on('click',function(){ $('body,html').animate({scrollTop:0},500); }) } function scrollFn($scrollTops){ if ($scrollTops>($(window).height()/1.5)) { $("#backtop-btn").show(); }else{ $("#backtop-btn").hide(); } } $(document).ready(function(){ $(window).scroll(function(){ var $scrollTop=$(window).scrollTop(); scrollFn($scrollTop) }); reSizeContent(); $(window).resize(function () { reSizeContent(); }); }); function reSizeContent() { var headerHeight = $("#header").height(); var footerHeight = $("#footer").height(); $("#content").css("min-height", window.innerHeight - headerHeight - footerHeight - 44); } var header = window.header = { menuJson : null, menuJsonHeader : null, menuMap: {}, init : function() { var _this = this; if (_this.menuJson == null || _this.menuJson == '') { return; } if (_this.menuJsonHeader == null || _this.menuJsonHeader == '') { return; } if (typeof _this.navMenu == "string") { _this.menuJson = JSON.parse(_this.menuJson); _this.menuJsonHeader = JSON.parse(_this.menuJsonHeader); } if($('.header_bt')){ $('.header_bt').hide(); } _this.initNavigation(); headerFn(); _this.buildBreadcrumbs(); }, initNavigation : function() { var _this = this; var menuTopKey = null; var menuChildKey = null; if (sessionStorage) { menuTopKey = sessionStorage.getItem('_menu_50_top_key_'); menuChildKey = sessionStorage.getItem('_menu_50_child_key_'); } if (menuTopKey == null || menuTopKey == undefined || menuTopKey.trim() == '') { menuTopKey = $.cookie('_menu_50_top_key_'); if (menuTopKey != null && menuTopKey != undefined && menuTopKey.trim() != '' && sessionStorage) { sessionStorage.setItem('_menu_50_top_key_', menuTopKey); } } if (menuChildKey == null || menuChildKey == undefined || menuChildKey.trim() == '') { menuChildKey = $.cookie('_menu_50_child_key_'); if (menuChildKey != null && menuChildKey != undefined && menuChildKey.trim() != '' && sessionStorage) { sessionStorage.setItem('_menu_50_child_key_', menuChildKey); } } if(!$.isEmptyObject(_this.menuJsonHeader)) { var topMenuHtml = ""; var i = 0; _this.menuJsonHeader.forEach(function(element){ _this.menuMap[element.menuId] = element; if (i == 0 && $.isEmptyObject(menuTopKey)) { topMenuHtml += _this.appendTopMemuHtml(element, true); menuTopKey = element.menuId; } else { topMenuHtml += _this.appendTopMemuHtml(element); } i ++; }); $("#topMenu").html(topMenuHtml); } if(!$.isEmptyObject(_this.menuJson)) { var navigationHtml = ""; var i = 0; _this.menuJson.forEach(function(element){ _this.menuMap[element.menuId] = element; if (i == 0 && $.isEmptyObject(menuTopKey)) { navigationHtml += _this.appendNavigationHtml(element, true); menuChildKey = element.menuId; } else { navigationHtml += _this.appendNavigationHtml(element); } i ++; }); $("#navigation").html(navigationHtml); } menuTopKey = sessionStorage.getItem('_menu_50_top_key_'); $("#"+ menuTopKey).addClass("active"); menuChildKey = sessionStorage.getItem('_menu_50_child_key_'); $("#"+ menuChildKey).addClass("a_list_active"); }, changeChildren: function(menuId) { $("#"+ menuId).addClass("active"); var _this = this; var menu = _this.menuMap[menuId]; sessionStorage.setItem('_menu_50_top_key_', menuId); sessionStorage.removeItem("_menu_50_child_key_"); document.location.href = menu.url; }, appendTopMemuHtml: function(menu, isActive) { return '<div id="'+menu.menuId+'" class="' + (isActive ? 'tab active' : 'tab') + '" onclick="header.changeChildren(\''+menu.menuId+'\')">'+menu.name+'</div>'; }, appendNavigationHtml : function(menu, isActive) { return '<a id="'+menu.menuId+'" class="a_list ' + (isActive ? 'a_list_active' : '') + '" onclick="checkChildMenu(\''+menu.menuId+'\',\''+menu.url+'\')" >'+menu.name+'</a>'; }, buildBreadcrumbs: function (type) { } }; function checkChildMenu(menuId, menuUrl) { $("#"+ menuId).addClass("a_list_active"); sessionStorage.setItem('_menu_50_child_key_', menuId); document.location.href = menuUrl; header.buildBreadcrumbs("child"); } // 底部 var footer = { "_logoSrc": "/comm/img/xclogo.png", "address": "学创教育科技有限公司&emsp;&emsp;地址:武汉市光谷国际广场B座20楼&emsp;&emsp;电话:+86-027-87107188", "version" : "三三云学堂 V5.00", "copyright": "Copyright © 2016-2018 学创教育科技有限公司.All rights reserved.", "init": function() { var footer = '<div style="text-align: center;font-size: 12px;">'; footer += '<p>' + this.version + '</p>'; footer += '<p>' + this.copyright + '</p>'; footer += '</div>'; $(".footer").append(footer); } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/AddAnswerCardAxisVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import lombok.Data; /** * Answer card coordinates * @author <EMAIL> * @since 2020/10/30 **/ @Data public class AddAnswerCardAxisVO { /**Primary key*/ private String axisId; /** Answer Card ID */ private String answerCardId; /** Question Node ID*/ private String nodeId; /**Question ID*/ private String questionId; /**Parent Node ID*/ private String parentNodeId; /**Parent Question ID*/ private String parentId; /**Order(The order of blank lines (long and empty))*/ private Long sequencing; /**x Axis*/ private Double xAxis; /**y Axis*/ private Double yAxis; /**width*/ private Double width; /**height*/ private Double height; /**Page No*/ private Long pageNo; /**Type Code*/ private String typeCode; /**Type Name*/ private String typeName; /**Option Count(default :4)*/ private Long optionCount; /**Row Count*/ private Long rowCount; private String answer; public Double getxAxis() { return xAxis; } public void setxAxis(Double xAxis) { this.xAxis = xAxis; } public Double getyAxis() { return yAxis; } public void setyAxis(Double yAxis) { this.yAxis = yAxis; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/TeacherBaseInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.bo; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; import java.util.Map; /** * @author <EMAIL> * @date 2021/6/28 **/ @Data public class TeacherBaseInfoBO { private String schoolId; private String schoolName; private String termId; private String termName; private String stageCode; private String stageName; private String gradeCode; private String gradeName; private String subjectCode; private String subjectName; private CodeNameMapBO materialVersion; private Map<String, String> classMap; } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/dto/AddExamDetailsInfoV2DTO.java package com.enableets.edu.enable.cloud.sdk.exam.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; /** * @Auther: <EMAIL> * @Date: * @Description: 考试详情DTO */ @JsonIgnoreProperties(ignoreUnknown = true) public class AddExamDetailsInfoV2DTO { /** * 考试明细标识 */ private Long examDetailsId; /** * 考试标识 */ private Long examId; /** * 年级编码 */ private String gradeCode; /** * 年级名称 */ private String gradeName; /** * 班级标识 */ private String classId; /** * 班级名称 */ private String className; /** * 学科代码 */ private String subjectCode; /** * 学科名称 */ private String subjectName; /** * 课程标识 */ private String courseId; /** * 课程名称 */ private String courseName; /** * 文理科属性:理科;文科 */ private String courseAttribute; /** * 考试时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date examTime; /** * 计划考试学生数 */ private Integer planStudentNumber; /** * 实际考试学生数 */ private Integer actualStudentNumber; /** * 试卷总分 */ private float totalScore; /** * 创建者 */ private String creator; /** * 创建时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 修改者 */ private String updator; /** * 修改时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; private ExamDetailsStepTaskInfoDTO stepTaskInfo; private List<ExamDetailsMarkAssigneeDTO> markAssignees; /** assign question to be marked by special teacher */ private List<QuestionMarkAssigneeDTO> questionMarkAssignees; public Long getExamDetailsId() { return examDetailsId; } public void setExamDetailsId(Long examDetailsId) { this.examDetailsId = examDetailsId; } public Long getExamId() { return examId; } public void setExamId(Long examId) { this.examId = examId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseAttribute() { return courseAttribute; } public void setCourseAttribute(String courseAttribute) { this.courseAttribute = courseAttribute; } public Date getExamTime() { return examTime; } public void setExamTime(Date examTime) { this.examTime = examTime; } public Integer getPlanStudentNumber() { return planStudentNumber; } public void setPlanStudentNumber(Integer planStudentNumber) { this.planStudentNumber = planStudentNumber; } public Integer getActualStudentNumber() { return actualStudentNumber; } public void setActualStudentNumber(Integer actualStudentNumber) { this.actualStudentNumber = actualStudentNumber; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public float getTotalScore() { return totalScore; } public void setTotalScore(float totalScore) { this.totalScore = totalScore; } public List<ExamDetailsMarkAssigneeDTO> getMarkAssignees() { return markAssignees; } public void setMarkAssignees(List<ExamDetailsMarkAssigneeDTO> markAssignees) { this.markAssignees = markAssignees; } public ExamDetailsStepTaskInfoDTO getStepTaskInfo() { return stepTaskInfo; } public void setStepTaskInfo(ExamDetailsStepTaskInfoDTO stepTaskInfo) { this.stepTaskInfo = stepTaskInfo; } public List<QuestionMarkAssigneeDTO> getQuestionMarkAssignees() { return questionMarkAssignees; } public void setQuestionMarkAssignees(List<QuestionMarkAssigneeDTO> questionMarkAssignees) { this.questionMarkAssignees = questionMarkAssignees; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/bo/IdNameMapBO.java package com.enableets.edu.enable.cloud.exam.framework.bo; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) public class IdNameMapBO { public IdNameMapBO() { } public IdNameMapBO(String id, String name){ this.id = id; this.name = name; } private String id; private String name; private String studentAmount; } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/dto/QueryExamDictionaryDTO.java package com.enableets.edu.enable.cloud.sdk.exam.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 查询字典DTO */ @JsonIgnoreProperties(ignoreUnknown = true) public class QueryExamDictionaryDTO { private String schoolId; private String type; private String code; public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/vo/QueryErrorQuestionInfoVO.java package com.enableets.edu.enable.cloud.exam.manager.report.vo; import lombok.Data; @Data public class QueryErrorQuestionInfoVO { private Integer offset; private Integer limit; } <file_sep>/Exam Manager/src/main/resources/static/custom/cloudexam/js/paging/lang/zh_CN.js var $lang={ "prev_page" : "上一页", "next_page" : "下一页", "first_page" : "首页", "last_page" : "尾页", "go_to" : "到", "page_num" : "页" }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/AddAnswerCardTimelineVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import lombok.Data; /** * Answer card timelines * @author <EMAIL> * @since 2021/01/25 **/ @Data public class AddAnswerCardTimelineVO { /**Primary key*/ private String timelineId; /** Answer Card ID */ private String answerCardId; /** Answer triggerTime*/ private Integer triggerTime; /** Question Node ID*/ private String nodeId; /**Question ID*/ private String questionId; /**Parent Node ID*/ private String parentNodeId; /**Parent Question ID*/ private String parentId; /**Order(The order of blank lines (long and empty))*/ private Long sequencing; /**Page No*/ private Long pageNo; /**Type Code*/ private String typeCode; /**Type Name*/ private String typeName; /**Option Count(default :4)*/ private Long optionCount; /**Row Count*/ private Long rowCount; } <file_sep>/Exam Manager/src/main/resources/static/custom/cloudexam/js/errorQuestion/errorQuestionIndex.js var errorQuestionIndex = window.errorQuestionIndex = { queryParam:{offset:0,limit:10}, queryUrl:'', countUrl:'', currentPage: 1, teachGroups: [], searchCodes: [], init:function(){ $(".navLi").removeClass("activeLi"); $("#errorQuestion").addClass("activeLi"); this.initErrorQuestion(); }, initErrorQuestion: function (){ if (this.teachGroups.length > 0) { $("#class-select").find("option").eq(1).prop("selected",true) } this.getErrorQuestionData(); }, getErrorQuestionData:function (){ var index = layer.load(1, { shade: [0.3,'#000'] }); this.queryParam.searchCodes = this.searchCodes; this.queryParam.classIds = []; $(".stepList").html(""); var _this = this; let classVal = $("#class-select").val(); let classIds =[]; if (classVal == 'all') { _this.teachGroups.forEach(item => { classIds.push(item.classId); }); }else{ classIds.push(classVal); } this.queryParam.classIds = classIds; var completeFlag = 0; $.ajax({ type:'POST', url:_this.queryUrl, contentType: "application/json", data: JSON.stringify(_this.queryParam), dataType: "json", async:true, success:function(result){ if (null != result && result.length > 0) { result.forEach((item,index) => { let notMaster = item["notMasterCount"] + "/" + item["questionCount"]; let unmarkedCause = item["unmarkedCauseCount"] + "/" + item["questionCount"]; let orderNumber = _this.queryParam.offset * _this.queryParam.limit + index + 1; let questionContent = '<div class="questionBox ng-star-inserted">\n' + ' <div class="li_question">\n' + item["questionContent"] + ' </div>\n' + ' <div class="li_index">\n' + ' <div class="num">'+ orderNumber +'</div>\n' + ' <div class="info">\n' + ' <div class="content">\n' + ' <div>没有掌握:' + notMaster + '</div>\n' + ' |\n' + ' <div>未标错因:' + unmarkedCause +'</div>\n' + ' </div>\n' + ' </div>\n' + ' </div>\n' + ' </div>'; $(".stepList").append($(questionContent)); }); }else{ let nodataHtml = '<div class="no-data">没有查询到数据!</div>'; $(".stepList").append($(nodataHtml)); } },error:function (r){ },complete:function (c){ completeFlag++; if (completeFlag > 1) { layer.close(index); } } }); $.ajax({ type:'POST', url:_this.countUrl, contentType: "application/json", data: JSON.stringify(_this.queryParam), dataType: "json", async:true, success:function(result){ if (result > 0) { let pages = Math.ceil(result/10); let pageInfo = "共" + pages + "页/" + result + "条"; $("#pageInfo").text(pageInfo); }else{ $("#pageInfo").text(""); } $("#pageOne").initPage(result, _this.currentPage, function (pageNum) {//1、所有数据条数(自动每页十条)2、初次加载显示的页数 3、所执行函数 _this.queryParam.offset=(pageNum - 1) * 10; _this.currentPage = pageNum; _this.getErrorQuestionData(); }); },error:function (r){ },complete:function (c){ completeFlag++; if (completeFlag > 1) { layer.close(index); } } }); } }; $(function(){ $("#class-select").change(function (event){ errorQuestionIndex.currentPage = 1; errorQuestionIndex.queryParam.offset = 0; errorQuestionIndex.getErrorQuestionData(); }); }); function ztreeCall(obj){ errorQuestionIndex.searchCodes = []; if (!obj == false){ var treeNode = $('#knowledgeTree').jstree(true).get_checked(true); treeNode.forEach(item => { errorQuestionIndex.searchCodes.push(item['original']['searchCode']); }); } errorQuestionIndex.currentPage = 1; errorQuestionIndex.queryParam.offset = 0; errorQuestionIndex.getErrorQuestionData(); } <file_sep>/Exam Manager/src/main/resources/static/comm/js/BaseUtils.js /** * js base utils */ if (window.BaseUtils == undefined || window.BaseUtils == null) { window.BaseUtils = {}; } (function(BaseUtils) { var utils = { ajaxPreRequestFilterMap: {}, // ajax request map getCookie: function(name) { //get cookie by name use js var arr, reg = new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; }, submitForm: function(form) { // submit form , disabled resubmit by defaults var $form = form, _this = this; if (typeof $form == 'string' || $form.attr == undefined) { $form = $(form); } if ($form.length == 0) throw "no form ele!"; if ($form.attr('disabled') == 'disabled') { return; } $form.attr('disabled', 'disabled'); if ($form[0].tagName.toLowerCase() != 'form') {// the param is not a form, maybe just a child btn $form = $form.closest('form'); $form.attr('disabled', 'disabled'); } if ($form.find('input[name="_csrf"]').length == 0) { $form.append('<input type="hidden" name="_csrf" value="" />'); } $form.find('input[name="_csrf"]').val(_this.getCookie("XSRF-TOKEN")); $form[0].submit(); }, preAjax: function() { /*ajax预处理过滤*/ var _this = this; $.ajaxPrefilter(function (options, originalOptions, jqXHR) { jqXHR.setRequestHeader("X-XSRF-TOKEN", _this.getCookie("XSRF-TOKEN")); //判断请求是否为文件上传 var contentType = options.contentType; var i = -1; if (contentType != null && typeof contentType == "string") { if (contentType.toLowerCase().indexOf('multipart/form-data'.toLowerCase()) >= 0) { return; } } //如果不是上传文件,过滤请求 var key = options.url; if (options.data != null && options.data != undefined) { if (typeof options.data == 'string') { key += options.data; } else if (typeof options.data == 'object') { try { key += JSON.parse(options.data); } catch(e) {} } } if (_this.ajaxPreRequestFilterMap[key] != null && _this.ajaxPreRequestFilterMap[key] != undefined) { options.error = options.complete = function () { }; jqXHR.abort();//discard repeated triggered commits console.log("intercept repeated request!"); return; } _this.ajaxPreRequestFilterMap[key] = jqXHR; var oldComplete = options.complete; options.complete = function (jqXHR, textStatus) { _this.ajaxPreRequestFilterMap[key] = null; oldComplete && oldComplete.apply(this, arguments); } }) } }; utils.preAjax(); $.extend(BaseUtils, utils); })(window.BaseUtils); (function(BaseUtils) { $.extend(BaseUtils, { _markObj: null, showMask: function(mobile) { //show mask , use layer if (mobile == undefined || mobile == null || mobile == false) { this._markObj = layer.load(0, { shade: [0.5, '#000'], anim: -1 }); //无动画 } else { this._markObj = layer.open({ type: 2 }); } return this._markObj; }, closeMask: function() {//close mask , use layer if (this._markObj != undefined && this._markObj != null) { layer.close(this._markObj); } this._markObj = null; } }); })(window.BaseUtils);<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWTypeBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; /** * @author <EMAIL> * @since 2020/09/01 13:57 **/ @Data public class XKWTypeBO { private String name; private String note; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/ExamManagerBootstrap.java package com.enableets.edu.enable.cloud.exam.manager; import com.enableets.edu.acm.menu.provider.IMenuProvider; import com.enableets.edu.acm.menu.provider.IMenuProviderV2; import com.enableets.edu.acm.menu.provider.impl.DefaultMenuProvider; import com.enableets.edu.acm.menu.provider.impl.DefaultMenuProviderV2; import com.enableets.edu.enable.cloud.exam.manager.core.Constants; import com.enableets.edu.framework.core.bootstrap.ApplicationBootstrap; import com.enableets.edu.framework.core.util.SpringBeanUtils; import com.enableets.edu.module.service.EnableETSService; import com.enableets.edu.sdk.account.v2.annotation.EnableAccountV2ServiceSDK; import com.enableets.edu.sdk.acm.IUserMenuService; import com.enableets.edu.sdk.activity.annotation.EnableActivityV2ServiceSDK; import com.enableets.edu.sdk.assessment.annotation.EnableAssessmentServiceSDK; import com.enableets.edu.sdk.content.annotation.EnableContentServiceSDK; import com.enableets.edu.sdk.group.annotation.EnableGroupServiceSDK; import com.enableets.edu.sdk.pakage.annotation.EnablePackageServiceSDK; import com.enableets.edu.sdk.paper.annotation.EnablePaperServiceSDK; import com.enableets.edu.sdk.school3.annotation.EnableSchoolServiceSDK; import com.enableets.edu.sdk.school3.v2.annotation.EnableSchoolServiceV2SDK; import com.enableets.edu.sdk.steptask.annotation.EnableStepV2ServiceSDK; import com.enableets.edu.ueditor.manager.servlet.UEditorServlet; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicStringProperty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * Exam Manager Bootstrap * * @author <EMAIL> * @date 2021/05/13 **/ @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.enableets.edu.enable.cloud.exam.manager","com.enableets.edu.acm.menu.provider"}) @EnableETSService @EnableSchoolServiceSDK @EnableSchoolServiceV2SDK @EnableContentServiceSDK @EnableAccountV2ServiceSDK @EnableActivityV2ServiceSDK @EnableStepV2ServiceSDK @EnablePackageServiceSDK @EnableGroupServiceSDK @EnableAssessmentServiceSDK //@EnableCloudExamServiceSDK @EnablePaperServiceSDK public class ExamManagerBootstrap extends ApplicationBootstrap { @Value("${report.qps:10}") public double qps; private static final String APP_STUDY_TASK_50 = "APP_STUDY_TASK_50"; private static final String APP_HEADER_MENU_50 = "EnableV50_Header"; private static final String COOKIE_NAME_ENABLED_50_MENU = "enabled50Menu"; private static final String REQUEST_PARAM_NAME_ENABLED_50_MENU = "enabled50Menu"; public static void main(String[] args) { SpringApplication.run(ExamManagerBootstrap.class); } @Autowired private Environment environment; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(Constants.CONTEXT_PATH + "/custom/**").addResourceLocations("classpath:/static/custom/"); registry.addResourceHandler(Constants.CONTEXT_PATH + "/comm/**").addResourceLocations("classpath:/static/comm/"); } @ControllerAdvice(basePackages = {"com.enableets.edu.teachingassistant.manager.controller"}) public static class GlobalVariableController{ @ModelAttribute public void get(Model model){ Locale _locale = ((LocaleResolver) SpringBeanUtils.getBean(LocaleResolver.class)).resolveLocale((HttpServletRequest)null); model.addAttribute("_locale", _locale.toString()); DynamicStringProperty stringProperty = DynamicPropertyFactory.getInstance().getStringProperty("build.version", "0002"); model.addAttribute("_v", stringProperty.get()); model.addAttribute("_contextPath", Constants.CONTEXT_PATH); } } /** * ueditor 访问类 * @return */ @Bean public ServletRegistrationBean uEditorServletRegistrationBean() { return new ServletRegistrationBean(new UEditorServlet("classpath:config.json"), Constants.CONTEXT_PATH + "/ueditor/execute"); } @Bean public IMenuProviderV2 menuProviderV2(IUserMenuService userMenuService) { return new DefaultMenuProviderV2(userMenuService); } @Bean public IMenuProvider menuProvider(IUserMenuService userMenuService) { return new DefaultMenuProvider(userMenuService); } } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/annotation/CloudExamServiceSDKConfiguration.java package com.enableets.edu.enable.cloud.sdk.exam.annotation; import com.enableets.edu.enable.cloud.sdk.exam.IExamDictionaryService; import com.enableets.edu.enable.cloud.sdk.exam.IExamInfoService; import com.enableets.edu.enable.cloud.sdk.exam.IExamLevelInfoService; import com.enableets.edu.enable.cloud.sdk.exam.IExamResultInfoService; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamDictionaryServiceFeignClient; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamInfoServiceFeignClient; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamLevelInfoFeignClient; import com.enableets.edu.enable.cloud.sdk.exam.feign.IExamResultInfoServiceFeignClient; import com.enableets.edu.enable.cloud.sdk.exam.impl.DefaultExamDictionaryService; import com.enableets.edu.enable.cloud.sdk.exam.impl.DefaultExamInfoService; import com.enableets.edu.enable.cloud.sdk.exam.impl.DefaultExamLevelInfoService; import com.enableets.edu.enable.cloud.sdk.exam.impl.DefaultExamResultInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author <EMAIL> * @since 2021/03/09 **/ @Configuration @EnableFeignClients(basePackages = {"com.enableets.edu.enable.cloud.sdk.exam.feign"}) public class CloudExamServiceSDKConfiguration { @Autowired public IExamInfoServiceFeignClient examInfoServiceFeignClient; @Autowired public IExamLevelInfoFeignClient examLevelInfoFeignClient; @Autowired private IExamResultInfoServiceFeignClient examResultInfoServiceFeignClient; @Autowired private IExamDictionaryServiceFeignClient examDictionaryServiceFeignClient; @Bean(name = "bookInfoServiceSDK") public IExamInfoService bookInfoServiceSDK(){ return new DefaultExamInfoService(examInfoServiceFeignClient); } @Bean(name = "examLevelInfoServiceSDK") public IExamLevelInfoService examLevelInfoServiceSDK() { return new DefaultExamLevelInfoService(examLevelInfoFeignClient); } @Bean(name = "examResultInfoServiceSDK") public IExamResultInfoService examResultInfoServiceSDK() { return new DefaultExamResultInfoService(examResultInfoServiceFeignClient); } @Bean(name = "examDictionaryServiceSDK") public IExamDictionaryService examDictionaryServiceSDK() { return new DefaultExamDictionaryService(examDictionaryServiceFeignClient); } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/PaperQuestionVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import com.enableets.edu.enable.cloud.exam.manager.paper.bo.*; import lombok.Data; import java.util.Date; import java.util.List; /** * test paper structure questions * @author duffy_ding * @since 2017/12/29 */ @Data public class PaperQuestionVO { /** Question ID*/ private String questionId; /** Super Question ID*/ private String parentId; /** Question type */ private CodeNameMapBO type; /** stage info */ private CodeNameMapBO stage; /** grade info */ private CodeNameMapBO grade; /** subject info */ private CodeNameMapBO subject; /** ability info */ private CodeNameMapBO ability; /** difficulty info */ private CodeNameMapBO difficulty; /** knowledge list */ private List<QuestionKnowledgeInfoBO> knowledges; /** Question score */ private Float points; /** Number of question children */ private Integer childAmount; /** question content info */ private QuestionStemInfoBO stem; /** Option information */ private List<PaperQuestionOptionBO> options; /** Answer message */ private PaperQuestionAnswerBO answer; /** Listening text*/ private String listen; private Integer sequencing; /** Listening document */ private String affixId; /** Question number*/ private String questionNo; /** creator */ private String creator; /** create time */ private Date createTime; /** updater */ private String updator; /** update time */ private Date updateTime; /** Child Question*/ private List<PaperQuestionVO> children; private Integer downloadNumber; /** axis*/ private List<QuestionAxisVO> axises; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/vo/QueryTestInfoResultVO.java package com.enableets.edu.enable.cloud.exam.manager.report.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * Query Test Info * @author <EMAIL> * @since 2020/08/31 */ @Data public class QueryTestInfoResultVO { /** Test ID*/ private String testId; /** Test Document File ID*/ private String fileId; private String stepId; /** Activity ID*/ private String activityId; /** School ID*/ private String schoolId; /** School Name*/ private String schoolName; /** Term ID*/ private String termId; /** Term Name*/ private String termName; /** Grade Code*/ private String gradeCode; /** Grade Name*/ private String gradeName; /** Subject Code*/ private String subjectCode; /** Subject Name*/ private String subjectName; /** Test Name*/ private String testName; /** Exam ID*/ private String examId; /** Exam Name*/ private String examName; /** Exam Type*/ private String examType; /** Score*/ private Float score; /** Test Begin Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startTime; /** Test End Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date endTime; /** Test Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date testTime; /** Start Submit Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startSubmitTime; /** End Submit Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date endSubmitTime; /** Send Paper User ID*/ private String sender; /** Send Paper User Name*/ private String senderName; /** Test Cost Time*/ private Float testCostTime; /** Time allowed for late submission*/ private Integer delaySubmit; /** Maximum number of submissions*/ private Integer resubmit; /** Creator*/ private String creator; /** Create Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** Updater*/ private String updator; /** Update Time*/ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; private String processInstantId; } <file_sep>/Exam Manager/src/main/resources/static/custom/cloudexam/js/paging/page.js /** * Created by zxm on 2017/3/31. */ $.fn.extend({ "initPage":function(listCount,currentPage,fun){ var maxshowpageitem = $(this).attr("maxshowpageitem"); if(maxshowpageitem!=null&&maxshowpageitem>0&&maxshowpageitem!=""){ page.maxshowpageitem = maxshowpageitem; } var pagelistcount = $(this).attr("pagelistcount"); if(pagelistcount!=null&&pagelistcount>0&&pagelistcount!=""){ page.pagelistcount = pagelistcount; } var pageId = $(this).attr("id"); page.pageId=pageId; if(listCount<0){ listCount = 0; } if(currentPage<=0){ currentPage=1; } page.setPageListCount(pageId,listCount,currentPage,fun); } }); var page = { "maxshowpageitem":5,//最多显示的页码个数 "pagelistcount":10,//每一页显示的内容条数 /** * 初始化分页界面 * @param listCount 列表总量 */ "initWithUl":function(pageId,listCount,currentPage){ var pageCount = 1; if(listCount>0){ pageCount = listCount%page.pagelistcount>0?parseInt(listCount/page.pagelistcount)+1:parseInt(listCount/page.pagelistcount); } var appendStr = page.getPageListModel(pageCount,currentPage); $("#"+pageId).html(appendStr); }, /** * 设置列表总量和当前页码 * @param listCount 列表总量 * @param currentPage 当前页码 */ "setPageListCount":function(pageId,listCount,currentPage,fun){ listCount = parseInt(listCount); currentPage = parseInt(currentPage); page.initWithUl(pageId,listCount,currentPage); page.initPageEvent(pageId,listCount,fun); }, "initPageEvent":function(pageId,listCount,fun){ $("#"+pageId +">li[class='pageItem']").on("click",function(){ if(typeof fun == "function"){ fun($(this).attr("page-data")); } page.setPageListCount(pageId,listCount,$(this).attr("page-data"),fun); }); $("#ChangeNum").on("change",function(){ var pageCount = 1; if(listCount>0){ pageCount = listCount%page.pagelistcount>0?parseInt(listCount/page.pagelistcount)+1:parseInt(listCount/page.pagelistcount); } var changeNum = parseInt($("#ChangeNum").val()); if (typeof changeNum != "NaN" && changeNum > 0 && changeNum <= pageCount) { if(typeof fun == "function"){ fun(changeNum); } page.setPageListCount(pageId,listCount,changeNum,fun); }else { $("#ChangeNum").val(""); layer.msg("请输入正确的页码", {time: 1000}) } }); }, "getPageListModel":function(pageCount,currentPage){ var prePage = currentPage-1; var nextPage = currentPage+1; var prePageClass ="pageItem"; var nextPageClass = "pageItem"; if(prePage<=0){ prePageClass="pageItem disabled"; } if(nextPage>pageCount){ nextPageClass="pageItem disabled" } var appendStr =""; appendStr+="<li title='"+$lang['first_page']+"' id='home' page-data='1' class='"+prePageClass+"'><a><img id='imageOne'></a></li>"; appendStr+="<li title='"+$lang['prev_page']+"' page-data='"+prePage+"' class='"+prePageClass+"'><a><img id='imageTwo'></a></li>"; var miniPageNumber = 1; if(currentPage-parseInt(page.maxshowpageitem/2)>0&&currentPage+parseInt(page.maxshowpageitem/2)<=pageCount){ miniPageNumber = currentPage-parseInt(page.maxshowpageitem/2); }else if(currentPage-parseInt(page.maxshowpageitem/2)>0&&currentPage+parseInt(page.maxshowpageitem/2)>pageCount){ miniPageNumber = pageCount-page.maxshowpageitem+1; if(miniPageNumber<=0){ miniPageNumber=1; } } var showPageNum = parseInt(page.maxshowpageitem); if(pageCount<=showPageNum){ for(var i=0;i<pageCount;i++){ var pageNumber = miniPageNumber++; var itemPageClass = "pageItem"; if(pageNumber==currentPage){ itemPageClass = "pageItem active"; } appendStr+="<li id='"+pageNumber+"' page-data='"+pageNumber+"' page-rel='itempage' class='"+itemPageClass+"' ><a class='ng-star-inserted'>"+pageNumber+"</a></li>"; } }else { var firstPageNum = 0; for(var i=0;i<showPageNum - 1 ;i++){ var pageNumber = miniPageNumber++; if (i == 0){ firstPageNum = pageNumber; } var itemPageClass = "pageItem"; if(pageNumber==currentPage ){ itemPageClass = "pageItem active"; } appendStr+="<li id='"+pageNumber+"' page-data='"+pageNumber+"' page-rel='itempage' class='"+itemPageClass+"' ><a class='ng-star-inserted'>"+pageNumber+"</a></li>"; } if ((pageCount - firstPageNum + 1) != showPageNum){ appendStr+="<li class='pageEllipsis'><a class='ng-star-inserted'>···</a></li>"; } var itemPageClass = "pageItem"; if (pageCount == currentPage){ itemPageClass = "pageItem active"; } appendStr+="<li id='"+pageCount+"' page-data='"+pageCount+"' page-rel='itempage' class='"+itemPageClass+"' ><a class='ng-star-inserted'>"+pageCount+"</a></li>"; } appendStr+="<li title='"+$lang['next_page']+"' page-data='"+nextPage+"' class='"+nextPageClass+"'><a><img id='imageThree'></a></li>"; appendStr+="<li title='"+$lang['last_page']+"' id='tail' page-data='"+pageCount+"' class='"+nextPageClass+"'><a><img id='imageFour'></a></li>"; appendStr+="<li class='lastToNum'><span>" + $lang['go_to'] + "</span><input type='text' id='ChangeNum'><span id='sureInfo' class='num'>"+$lang['page_num']+"</span></li>"; return appendStr; } }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/IdNameMapBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author <EMAIL> * @since 2020/09/25 **/ @Data @NoArgsConstructor @AllArgsConstructor public class IdNameMapBO { private String id; private String name; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/ContentKnowledgeInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.Data; /** * @author <EMAIL> * @since 2020/08/06 **/ @Data public class ContentKnowledgeInfoBO { private String knowledgeId; private String parentId; private String knowledgeName; private String gradeCode; private String subjectCode; private String materialVersion; private String materialVersionName; private String searchCode; } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/dto/QueryExamDetailsResultDTO.java package com.enableets.edu.enable.cloud.sdk.exam.dto; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; /** * 查询考试详情结果信息 * @author duffy_ding * @since 2020/05/28 */ @Data @Accessors(chain = true) public class QueryExamDetailsResultDTO { /** 考试明细标识 */ private String examDetailsId; /** * 考试标识 */ private String examId; /** * 年级编码 */ private String gradeCode; /** * 年级名称 */ private String gradeName; /** * 学科代码 */ private String subjectCode; /** * 学科名称 */ private String subjectName; /** * 课程标识 */ private String courseId; /** * 课程名称 */ private String courseName; /** * 文理科属性:理科;文科 */ private String courseAttribute; /** * 考试时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date examTime; /** * 计划考试学生数 */ private Integer planStudentNumber; /** * 实际考试学生数 */ private Integer actualStudentNumber; /** * 试卷总分 */ private Float totalScore; private ExamDetailsStepTaskInfoDTO stepTaskInfo; private List<ExamDetailsMarkAssigneeDTO> markAssignees; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/service/PaperInfoService.java package com.enableets.edu.enable.cloud.exam.manager.paper.service; import com.enableets.edu.acm.menu.provider.util.BeanUtils; import com.enableets.edu.enable.cloud.exam.manager.core.Constants; import com.enableets.edu.enable.cloud.exam.manager.paper.bo.PaperInfoBO; import com.enableets.edu.framework.core.service.ServiceAdapter; import com.enableets.edu.sdk.assessment.ITestInfoService; import com.enableets.edu.sdk.paper.dto.QueryPaperDTO; import com.enableets.edu.sdk.paper.dto.QueryPaperInfoResultDTO; import com.enableets.edu.sdk.paper.service.IPaperInfoService; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; /** * @author <EMAIL> * @since 2021/6/18 **/ @Service @Configurable public class PaperInfoService extends ServiceAdapter<PaperInfoBO, QueryPaperDTO> { /* *//** School SDK Client*//* @Autowired private IDictionaryInfoV2Service dictionaryInfoV2ServiceSDK; *//** School SDK Client*//* @Autowired private IGradeInfoV2Service gradeInfoV2ServiceSDK;*/ /* */ /** School SDK Client*//* @Autowired private IOrgSubjectService orgSubjectServiceSDK; */ @Autowired private IPaperInfoService paperInfoServiceSDK; /* @Autowired private com.enableets.edu.enable.cloud.sdk.exam.IExamInfoService iExamInfoService;*/ @Qualifier("paperInfoRemoteServiceSDK") private IPaperInfoService paperInfoRemoteServiceSDK; @Autowired private ITestInfoService testInfoServiceSDK; /* */ /** * School Base Condition Info * @param schoolId * @return *//* @Cacheable(value = PPRConstants.PACKAGE_PPR_CACHE_KEY_PREFIX + "paper:school:condition", key = "#schoolId", unless = "#result == null") public BaseSearchConditionBO schoolConditionDictionary(String schoolId){ if (StringUtils.isBlank(schoolId)) return null; List<QueryDictionaryInfoDTO> stageInfos = dictionaryInfoV2ServiceSDK.query(schoolId, "02", null, null, null, null, null); if (CollectionUtils.isEmpty(stageInfos)) return null; BaseSearchConditionBO condition = new BaseSearchConditionBO(); condition.setStages(stageInfos.stream().map(e -> new StageInfoBO(e.getCode(), e.getName())).collect(Collectors.toList())); List<QueryGradeStageResultDTO> gradeStageInfos = gradeInfoV2ServiceSDK.query(schoolId, null, null); if (CollectionUtils.isEmpty(gradeStageInfos)) { //logger.error("Get Base Condition From School is Null, School Id is " + schoolId); return condition; } condition.setGrades(gradeStageInfos.stream().map(e -> new GradeInfoBO(e.getGradeCode(), e.getGradeName(), e.getStageCode())).collect(Collectors.toList())); List<QuerySubjectResultDTO> subjectInfos = orgSubjectServiceSDK.queryV2(schoolId, null); if (CollectionUtils.isEmpty(subjectInfos)) return condition; List<QueryStudentSelectionsResultDTO.SubjectInfoBO> subjects = new ArrayList<>(); for (QuerySubjectResultDTO subjectInfo : subjectInfos) { if (CollectionUtils.isEmpty(subjectInfo.getItems())){ for (GradeInfoBO grade : condition.getGrades()) { subjects.add(new SubjectInfoBO(subjectInfo.getSubjectCode(), subjectInfo.getSubjectName(), grade.getGradeCode())); } }else{ for (GradeInfoBO gradeBO : condition.getGrades()) { for (QuerySubjectResultDTO.ItemInfoDTO subjectItemInfo : subjectInfo.getItems()) { if (CollectionUtils.isNotEmpty(subjectItemInfo.getGrades())) { for (QuerySubjectResultDTO.GradeInfoDTO grade : subjectItemInfo.getGrades()) { if (grade.getGradeCode().equals(gradeBO.getGradeCode())) { subjects.add(new SubjectInfoBO(subjectInfo.getSubjectCode(), subjectInfo.getSubjectName(), grade.getGradeCode())); } } } } } } } condition.setSubjects(subjects); return condition; } */ /** * 查询试卷信息列表 * * @param paperInfoBO * @return */ public HashMap<String, Object> query(PaperInfoBO paperInfoBO) { HashMap<String, Object> map = new HashMap<>(); List<QueryPaperInfoResultDTO> result = null; if (Constants.ZT_CODE.equals(paperInfoBO.getProviderCode()) || Constants.PROVIDER_CODE_QIUJIEDA.equals(paperInfoBO.getProviderCode())) { result = paperInfoRemoteServiceSDK.queryByProviderCode(BeanUtils.convert(paperInfoBO, QueryPaperDTO.class), Constants.ZT_CODE); Long count = paperInfoRemoteServiceSDK.count(BeanUtils.convert(paperInfoBO, QueryPaperDTO.class)); map.put("paperList",BeanUtils.convert(result, PaperInfoBO.class)); map.put("paperCount",count); } /*else if (Constants.PROVIDER_CODE_QIUJIEDA.equals(paperInfoBO.getProviderCode())) { long startTime = System.currentTimeMillis(); result = qjdPaperInfoServiceSDK.query(BeanUtils.convert(paperInfoBO, QueryQJDPaperDTO.class)); long endTime = System.currentTimeMillis(); LOGGER.info("求解答试卷搜索耗时:" + (new BigDecimal(endTime).subtract(new BigDecimal(startTime))). divide(new BigDecimal(1000)) + "S"); }*/ else { QueryPaperDTO paperInfoDTO = BeanUtils.convert(paperInfoBO, QueryPaperDTO.class); result = paperInfoServiceSDK.query(paperInfoDTO); Long count = paperInfoServiceSDK.count(paperInfoDTO); map.put("paperList",getDispatchRecords(BeanUtils.convert(result, PaperInfoBO.class))); map.put("paperCount",count); return map; } return map; } private List<PaperInfoBO> getDispatchRecords(List<PaperInfoBO> list) { if(CollectionUtils.isNotEmpty(list)) { for (PaperInfoBO bo : list) { if(bo.getPaperId() != null) { Integer count = testInfoServiceSDK.countDispatchRecords(bo.getPaperId().toString()); bo.setDispatchRecordsNum(count); } } } return list; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamResultInfoDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamResultInfoBO; import com.enableets.edu.enable.cloud.exam.framework.po.ExamResultInfoPO; import com.enableets.edu.framework.core.dao.BaseDao; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * @Auther: <EMAIL> * @Date: 2019/1/23 14:27 * @Description: 考试成绩DAO */ public interface ExamResultInfoDAO extends BaseDao<ExamResultInfoPO> { /** * 查询考试结果 * @param examDetailsId * @return */ List<ExamResultInfoPO> getExamResultInfo(@Param("examDetailsId") Long examDetailsId); Integer batchInsert(List<ExamResultInfoPO> examResultInfoPOList); } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/QueryExamInfoResultV2VO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.List; /** * @author duffy_ding * @since 2020/05/28 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @ApiModel(value="QueryExamInfoV2ResultVO", description="I_50_01_01_036") public class QueryExamInfoResultV2VO implements Serializable { /** 考试标识 */ @ApiModelProperty(value = "I_50_01_10_010") private String examId; /** 考试名称 */ @ApiModelProperty(value = "I_50_01_04_034") private String name; /** 考试类型 */ @ApiModelProperty(value = "I_50_01_04_035") private String type; /** 考试类型名称 */ @ApiModelProperty(value = "I_50_01_04_113") private String typeName; /** 学校标识 */ @ApiModelProperty(value = "I_50_01_05_004") private String schoolId; /** 学校编码 */ @ApiModelProperty(value = "I_50_01_01_020") private String schoolCode; /** 学年 */ @ApiModelProperty(value = "I_50_01_01_021") private String schoolYear; /** 不包含的学期标识 */ @ApiModelProperty(value = "I_50_01_01_037") private String excludeTermId; /** 学期标识 */ @ApiModelProperty(value = "I_50_01_04_037") private String termId; /** 学期名称 */ @ApiModelProperty(value = "I_50_01_04_038") private String termName; /** 学段 */ @ApiModelProperty(value = "I_50_01_01_023") private String gradeStage; /** 年级代码 */ @ApiModelProperty(value = "I_50_01_18_016") private String gradeCode; /** 年级名称 */ @ApiModelProperty(value = "I_50_01_04_021") private String gradeName; /** exam publish status, default 0, if all details is published, it's 1, else 2 */ @ApiModelProperty(value = "exam publish status, default 0, if all details is published, it's 1, else 2") private String publishStatus; /** creator */ @ApiModelProperty(value = "creator") private String creator; /** 班级 */ @ApiModelProperty(value = "I_50_01_06_030") private List<IdNameMapVO> classes; /** 详情 */ @ApiModelProperty(value = "I_50_01_15_019") private List<QueryExamDetailsResultV2VO> details; public String getExamId() { return examId; } public void setExamId(String examId) { this.examId = examId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getSchoolCode() { return schoolCode; } public void setSchoolCode(String schoolCode) { this.schoolCode = schoolCode; } public String getSchoolYear() { return schoolYear; } public void setSchoolYear(String schoolYear) { this.schoolYear = schoolYear; } public String getExcludeTermId() { return excludeTermId; } public void setExcludeTermId(String excludeTermId) { this.excludeTermId = excludeTermId; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public String getTermName() { return termName; } public void setTermName(String termName) { this.termName = termName; } public String getGradeStage() { return gradeStage; } public void setGradeStage(String gradeStage) { this.gradeStage = gradeStage; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getPublishStatus() { return publishStatus; } public void setPublishStatus(String publishStatus) { this.publishStatus = publishStatus; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public List<IdNameMapVO> getClasses() { return classes; } public void setClasses(List<IdNameMapVO> classes) { this.classes = classes; } public List<QueryExamDetailsResultV2VO> getDetails() { return details; } public void setDetails(List<QueryExamDetailsResultV2VO> details) { this.details = details; } } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/bo/ExamResultInfoBO.java package com.enableets.edu.enable.cloud.exam.framework.bo; import lombok.Data; import lombok.experimental.Accessors; import java.util.Date; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 考试成绩BO */ @Data @Accessors(chain = true) public class ExamResultInfoBO { /** * 考试明细标识 */ private Long examDetailsId; /** * 学生标识 */ private String studentUserId; /** * 学生名称 */ private String studentFullName; /** * 学籍号 */ private String studentCode; /** * 学号(座位号) */ private String studentNo; /** * 1 正常 2缺考 3违纪 4补考 */ private String status; /** * 录分教师标识 */ private String teacherUserId; /** * 录分教师名称 */ private String teacherFullName; /** * A卷分 */ private Float aPoint; /** * B卷分 */ private Float bPoint; /** * 附加分 */ private Float additionalPoint; /** * 标准分 */ private Float standardPoint; /** * 总分 */ private Float totalPoint; /** * 分数等级 */ private String level; /** * 评语 */ private String comment; private String contentId; /** * 创建者 */ private String creator; /** * 创建时间 */ private Date createTime; /** * 修改者 */ private String updator; /** * 修改时间 */ private Date updateTime; private String subjectCode; private String subjectName; private String courseId; private String courseName; private String gradeCode; private String classId; private String className; private String examId; private String termId; /** * 试卷总分 */ private Float totalScore; private String typeCode; private String type; private String examName; private String termName; private String avgScore; } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/po/ExamResultInfoPO.java package com.enableets.edu.enable.cloud.exam.framework.po; import lombok.Data; import lombok.experimental.Accessors; import javax.persistence.*; import java.util.Date; @Entity @Table(name="exam_result_info") public class ExamResultInfoPO { /** * 考试明细标识 */ @Id @Column(name = "exam_details_id") private Long examDetailsId; /** * 学生标识 */ @Id @Column(name = "student_user_id") private String studentUserId; /** * 学生名称 */ @Column(name = "student_full_name") private String studentFullName; /** * 学籍号 */ @Column(name = "student_code") private String studentCode; /** * 学号(座位号) */ @Column(name = "student_no") private String studentNo; /** * 1 正常 2缺考 3违纪 4补考 */ @Column(name = "status") private String status; /** * 录分教师标识 */ @Column(name = "teacher_user_id") private String teacherUserId; /** * 录分教师名称 */ @Column(name = "teacher_full_name") private String teacherFullName; /** * A卷分 */ @Column(name = "a_point") private Float aPoint; /** * B卷分 */ @Column(name = "b_point") private Float bPoint; /** * 附加分 */ @Column(name = "additional_point") private Float additionalPoint; /** * 标准分 */ @Column(name = "standard_point") private Float standardPoint; /** * 总分 */ @Column(name = "total_point") private Float totalPoint; /** * 分数等级 */ @Column(name = "level") private String level; /** * 评语 */ @Column(name = "comment") private String comment; @Column(name = "content_id") private String contentId; @Column(name = "creator") private String creator; @Column(name = "create_time") private java.util.Date createTime; @Column(name = "updator") private String updator; @Column(name = "update_time") private java.util.Date updateTime; @Transient private String subjectCode; @Transient private String subjectName; @Transient private String courseId; @Transient private String courseName; @Transient private String classId; @Transient private String gradeCode; @Transient private String examId; @Transient private String termId; /** * 试卷总分 */ @Transient private Float totalScore; @Transient private String typeCode; @Transient private String type; @Transient private String examName; @Transient private String termName; @Transient private String avgScore; public Long getExamDetailsId() { return examDetailsId; } public void setExamDetailsId(Long examDetailsId) { this.examDetailsId = examDetailsId; } public String getStudentUserId() { return studentUserId; } public void setStudentUserId(String studentUserId) { this.studentUserId = studentUserId; } public String getStudentFullName() { return studentFullName; } public void setStudentFullName(String studentFullName) { this.studentFullName = studentFullName; } public String getStudentCode() { return studentCode; } public void setStudentCode(String studentCode) { this.studentCode = studentCode; } public String getStudentNo() { return studentNo; } public void setStudentNo(String studentNo) { this.studentNo = studentNo; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTeacherUserId() { return teacherUserId; } public void setTeacherUserId(String teacherUserId) { this.teacherUserId = teacherUserId; } public String getTeacherFullName() { return teacherFullName; } public void setTeacherFullName(String teacherFullName) { this.teacherFullName = teacherFullName; } public Float getaPoint() { return aPoint; } public void setaPoint(Float aPoint) { this.aPoint = aPoint; } public Float getbPoint() { return bPoint; } public void setbPoint(Float bPoint) { this.bPoint = bPoint; } public Float getAdditionalPoint() { return additionalPoint; } public void setAdditionalPoint(Float additionalPoint) { this.additionalPoint = additionalPoint; } public Float getStandardPoint() { return standardPoint; } public void setStandardPoint(Float standardPoint) { this.standardPoint = standardPoint; } public Float getTotalPoint() { return totalPoint; } public void setTotalPoint(Float totalPoint) { this.totalPoint = totalPoint; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getExamId() { return examId; } public void setExamId(String examId) { this.examId = examId; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public Float getTotalScore() { return totalScore; } public void setTotalScore(Float totalScore) { this.totalScore = totalScore; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getExamName() { return examName; } public void setExamName(String examName) { this.examName = examName; } public String getTermName() { return termName; } public void setTermName(String termName) { this.termName = termName; } public String getAvgScore() { return avgScore; } public void setAvgScore(String avgScore) { this.avgScore = avgScore; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWIdNameBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; /** * 学科网区域信息 * * @author <EMAIL> * @since 2020/09/01 13:58 **/ @Data public class XKWIdNameBO { private Integer id; private String name; } <file_sep>/SDK Exam/src/main/java/com/enableets/edu/enable/cloud/sdk/exam/dto/QuestionMarkAssigneeDTO.java package com.enableets.edu.enable.cloud.sdk.exam.dto; /** * @author duffy_ding * @since 2020/05/29 */ public class QuestionMarkAssigneeDTO { /** exam id */ private String examId; /** course id */ private String courseId; /** question id */ private String questionId; /** user id of teacher which marked the question */ private String userId; /** user id of teacher which marked the question */ private String fullName; public String getExamId() { return examId; } public void setExamId(String examId) { this.examId = examId; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getQuestionId() { return questionId; } public void setQuestionId(String questionId) { this.questionId = questionId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/CodeNameMapBO.java package com.enableets.edu.enable.cloud.exam.manager.bo; /** * 公用map对象(只含有code和name字段) * @author duffy_ding * @since 2017/12/29 */ public class CodeNameMapBO implements java.io.Serializable{ /** 编码 */ private String code; /** 名称 */ private String name; public CodeNameMapBO() { } public CodeNameMapBO(String code, String name,String... relations) { this.code = code; this.name = name; this.relationCode = join(relations); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String relationCode; private static String join(String...relations) { if (relations != null && relations.length > 0) { String result = ""; for (String s : relations) { result += "_" + s; } return result.substring(1); } else { return null; } } } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/ExamResultInfoVO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * 考试成绩结果信息 * @author link_li * */ @JsonIgnoreProperties(ignoreUnknown = true) @ApiModel(value = "examResultInfoVO", description = "考试成绩结果信息") public class ExamResultInfoVO { /** * 考试标识 */ @ApiModelProperty(value="考试标识") private String examId; /** * 考试记录标识 */ @ApiModelProperty(value="考试记录标识") private String examDetailsId; /** * 学生标识 */ @ApiModelProperty(value="学生标识") private String studentUserId; /** * 学生姓名 */ @ApiModelProperty(value="学生姓名") private String studentFullName; /** * 学籍号 */ @ApiModelProperty(value="学籍号") private String studentCode; /** * 学号(座位号) */ @ApiModelProperty(value="学号(座位号)") private String studentNo; /** * 参考情况 */ @ApiModelProperty(value="参考情况") private String status; /** * 录分老师标识 */ @ApiModelProperty(value="录分老师标识") private String teacherUserId; /** * 录分老师名称 */ @ApiModelProperty(value="录分老师名称") private String teacherFullName; /** * A卷分 */ @ApiModelProperty(value="A卷分") private Float aPoint; /** * B卷分 */ @ApiModelProperty(value="B卷分") private Float bPoint; /** * 附加分 */ @ApiModelProperty(value="附加分") private Float additionalPoint; /** * 标准分 */ @ApiModelProperty(value="标准分") private Float standardPoint; /** * 总分 */ @ApiModelProperty(value="总分") private Float totalPoint; /** * 分数等级 */ @ApiModelProperty(value="分数等级") private String level; /** * 评语 */ @ApiModelProperty(value="评语") private String comment; /** * 资源标识 */ @ApiModelProperty(value="资源标识") private String contentId; /** * 创建者 */ @ApiModelProperty(value="创建者") private String creator; /** * 创建时间 */ @ApiModelProperty(value="创建时间") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; /** * 更新者 */ @ApiModelProperty(value="更新者") private String updator; /** * 更新时间 */ @ApiModelProperty(value="更新时间") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date updateTime; /** * 学科代码 */ @ApiModelProperty(value="学科代码") private String subjectCode; /** * 学科名称 */ @ApiModelProperty(value="学科名称") private String subjectName; /** * 课程标识 */ @ApiModelProperty(value="课程标识") private String courseId; /** * 课程名称 */ @ApiModelProperty(value="课程名称") private String courseName; /** * 年级代码 */ @ApiModelProperty(value="年级代码") private String gradeCode; /** * 班级标识 */ @ApiModelProperty(value="班级标识") private String classId; /** * 班级名称 */ @ApiModelProperty(value="班级名称") private String className; /** * 试卷总分 */ @ApiModelProperty(value="试卷总分") private Float totalScore; /** * */ @ApiModelProperty(value="试卷类型代码") private String typeCode; /** * */ @ApiModelProperty(value="试卷类型名称") private String type; /** * */ @ApiModelProperty(value="考试名称") private String examName; /** * */ @ApiModelProperty(value="学期名称") private String termName; /** * */ @ApiModelProperty(value="学期标识") private String termId; /** * */ private String avgScore; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getAvgScore() { return avgScore; } public void setAvgScore(String avgScore) { this.avgScore = avgScore; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getExamName() { return examName; } public void setExamName(String examName) { this.examName = examName; } public String getTermName() { return termName; } public void setTermName(String termName) { this.termName = termName; } public Float getTotalScore() { return totalScore; } public void setTotalScore(Float totalScore) { this.totalScore = totalScore; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getExamDetailsId() { return examDetailsId; } public void setExamDetailsId(String examDetailsId) { this.examDetailsId = examDetailsId; } public String getStudentUserId() { return studentUserId; } public void setStudentUserId(String studentUserId) { this.studentUserId = studentUserId; } public String getStudentCode() { return studentCode; } public void setStudentCode(String studentCode) { this.studentCode = studentCode; } public String getStudentNo() { return studentNo; } public void setStudentNo(String studentNo) { this.studentNo = studentNo; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTeacherUserId() { return teacherUserId; } public void setTeacherUserId(String teacherUserId) { this.teacherUserId = teacherUserId; } public String getStudentFullName() { return studentFullName; } public void setStudentFullName(String studentFullName) { this.studentFullName = studentFullName; } public String getTeacherFullName() { return teacherFullName; } public void setTeacherFullName(String teacherFullName) { this.teacherFullName = teacherFullName; } public Float getaPoint() { return aPoint; } public void setaPoint(Float aPoint) { this.aPoint = aPoint; } public Float getbPoint() { return bPoint; } public void setbPoint(Float bPoint) { this.bPoint = bPoint; } public Float getAdditionalPoint() { return additionalPoint; } public void setAdditionalPoint(Float additionalPoint) { this.additionalPoint = additionalPoint; } public Float getStandardPoint() { return standardPoint; } public void setStandardPoint(Float standardPoint) { this.standardPoint = standardPoint; } public Float getTotalPoint() { return totalPoint; } public void setTotalPoint(Float totalPoint) { this.totalPoint = totalPoint; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } /** * @return the examId */ public String getExamId() { return examId; } /** * @param examId * the examId to set */ public void setExamId(String examId) { this.examId = examId; } /** * @return the courseId */ public String getCourseId() { return courseId; } /** * @param courseId * the courseId to set */ public void setCourseId(String courseId) { this.courseId = courseId; } /** * @return the courseName */ public String getCourseName() { return courseName; } /** * @param courseName * the courseName to set */ public void setCourseName(String courseName) { this.courseName = courseName; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/QuestionStemInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * question content info */ @Data @NoArgsConstructor @AllArgsConstructor public class QuestionStemInfoBO { /** question stem information with html tags */ public String richText; /** No HTML tag title stem information */ public String plaintext; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/service/ReportAnalysisService.java package com.enableets.edu.enable.cloud.exam.manager.report.service; import com.enableets.edu.enable.cloud.exam.manager.report.bo.QueryTestReportBO; import com.enableets.edu.enable.cloud.exam.manager.report.bo.TeacherTestResultBO; import com.enableets.edu.framework.core.util.BeanUtils; import com.enableets.edu.sdk.pakage.ppr.dto.QueryTeacherTestDTO; import com.enableets.edu.sdk.pakage.ppr.service.IPPRTestInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author <EMAIL> * @date 2021/6/22 **/ @Service public class ReportAnalysisService { @Autowired private IPPRTestInfoService pprTestInfoServiceSDK; public List<TeacherTestResultBO> queryResultForTeacher(QueryTestReportBO condition) { QueryTeacherTestDTO param = BeanUtils.convert(condition, QueryTeacherTestDTO.class); return BeanUtils.convert(pprTestInfoServiceSDK.queryResultForTeacher(param), TeacherTestResultBO.class); } public Integer countResultForTeacher(QueryTestReportBO condition) { QueryTeacherTestDTO param = BeanUtils.convert(condition, QueryTeacherTestDTO.class); return pprTestInfoServiceSDK.countResultForTeacher(param); } }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/report/bo/TeacherTestResultBO.java package com.enableets.edu.enable.cloud.exam.manager.report.bo; import java.util.Date; /** * Teacher Test Result */ public class TeacherTestResultBO { private String testId; private String stepId; private String activityId; private String activityType; private String schoolId; private String termId; private String gradeCode; private String gradeName; private String subjectCode; private String subjectName; private String testName; private String examId; private String fileId; private String markType; private String testType; private String testPublishType; private java.util.Date testPublishTime; private java.util.Date testTime; private java.util.Date startTime; private java.util.Date endTime; private java.util.Date startSubmitTime; private java.util.Date endSubmitTime; private String sender; private String senderName; private String creator; private java.util.Date createTime; private String updator; private java.util.Date updateTime; private String delStatus; private Float testCostTime; private String appId; private Integer delaySubmit; private Integer resubmit; private String from; private String examName; private String processInstanceId; private String userId; private String isSubmit; private Integer totalCount; private Integer submitCount; private Integer markCount; private Float score; private String classId; private String className; private String groupId; private String groupName; private String schoolCode; private String materialVersionId; private String actionType; public String getTestId() { return testId; } public void setTestId(String testId) { this.testId = testId; } public String getStepId() { return stepId; } public void setStepId(String stepId) { this.stepId = stepId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getActivityType() { return activityType; } public void setActivityType(String activityType) { this.activityType = activityType; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getTermId() { return termId; } public void setTermId(String termId) { this.termId = termId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getTestName() { return testName; } public void setTestName(String testName) { this.testName = testName; } public String getExamId() { return examId; } public void setExamId(String examId) { this.examId = examId; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getMarkType() { return markType; } public void setMarkType(String markType) { this.markType = markType; } public String getTestType() { return testType; } public void setTestType(String testType) { this.testType = testType; } public String getTestPublishType() { return testPublishType; } public void setTestPublishType(String testPublishType) { this.testPublishType = testPublishType; } public Date getTestPublishTime() { return testPublishTime; } public void setTestPublishTime(Date testPublishTime) { this.testPublishTime = testPublishTime; } public Date getTestTime() { return testTime; } public void setTestTime(Date testTime) { this.testTime = testTime; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getStartSubmitTime() { return startSubmitTime; } public void setStartSubmitTime(Date startSubmitTime) { this.startSubmitTime = startSubmitTime; } public Date getEndSubmitTime() { return endSubmitTime; } public void setEndSubmitTime(Date endSubmitTime) { this.endSubmitTime = endSubmitTime; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getSenderName() { return senderName; } public void setSenderName(String senderName) { this.senderName = senderName; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getDelStatus() { return delStatus; } public void setDelStatus(String delStatus) { this.delStatus = delStatus; } public Float getTestCostTime() { return testCostTime; } public void setTestCostTime(Float testCostTime) { this.testCostTime = testCostTime; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public Integer getDelaySubmit() { return delaySubmit; } public void setDelaySubmit(Integer delaySubmit) { this.delaySubmit = delaySubmit; } public Integer getResubmit() { return resubmit; } public void setResubmit(Integer resubmit) { this.resubmit = resubmit; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getExamName() { return examName; } public void setExamName(String examName) { this.examName = examName; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getIsSubmit() { return isSubmit; } public void setIsSubmit(String isSubmit) { this.isSubmit = isSubmit; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Integer getSubmitCount() { return submitCount; } public void setSubmitCount(Integer submitCount) { this.submitCount = submitCount; } public Integer getMarkCount() { return markCount; } public void setMarkCount(Integer markCount) { this.markCount = markCount; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getSchoolCode() { return schoolCode; } public void setSchoolCode(String schoolCode) { this.schoolCode = schoolCode; } public String getMaterialVersionId() { return materialVersionId; } public void setMaterialVersionId(String materialVersionId) { this.materialVersionId = materialVersionId; } public String getActionType() { return actionType; } public void setActionType(String actionType) { this.actionType = actionType; } }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/MenuControllerAdvice.java package com.enableets.edu.enable.cloud.exam.manager.core; import com.enableets.edu.acm.menu.provider.IMenuProvider; import com.enableets.edu.acm.menu.provider.bean.UserMenuBean; import com.enableets.edu.sdk.school3.IUserIdentityService; import com.enableets.edu.sdk.school3.dto.UserIdentityDTO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.stream.Collectors; /** * controller增强器,加载menues * * @author <EMAIL> * @since 2017/11/6 */ @ControllerAdvice(basePackages = "com.enableets.edu.enable.cloud.exam.manager") public class MenuControllerAdvice { @Autowired private IMenuProvider menuProvider; @Autowired private IUserIdentityService userIdentityService; @Autowired private BaseInfoManager baseInfoManager; private static final String APP_EXAMINATION_50 = "EnableV50_Testing"; private static final String APP_EXAMINATION_50_ID = "M5003"; private static final String APP_HEADER_MENU_50 = "EnableV50_Header"; private static final String APP_HEADER_USER_MENU_50 = "EnableV50_DropDown"; private static final String SELECT_MENU_TOP_KEY = "_menu_50_top_key_"; private static final String SELECT_MENU_CHILD_KEY = "_menu_50_child_key_"; @InitBinder public void initBinder(WebDataBinder binder) { } @ModelAttribute public void addAttributes(Model model, HttpServletRequest request, HttpServletResponse response) { List<UserMenuBean> headMenuV5 = menuProvider.list(APP_HEADER_MENU_50); if (CollectionUtils.isEmpty(headMenuV5)) return; Cookie[] cookies = request.getCookies(); model.addAttribute("menuJsonHeader", headMenuV5); model.addAttribute("menuHeaderId", APP_EXAMINATION_50_ID); List<UserMenuBean> navList = menuProvider.list(APP_EXAMINATION_50); if (CollectionUtils.isEmpty(navList)) return; model.addAttribute("menuJson", navList); if (!isCookieExist(cookies, navList, SELECT_MENU_CHILD_KEY)) { Cookie cookie = new Cookie(SELECT_MENU_CHILD_KEY, navList.get(0).getMenuId()); cookie.setPath("/"); response.addCookie(cookie); } List<UserMenuBean> userMenus = menuProvider.list(APP_HEADER_USER_MENU_50); model.addAttribute("userMenus", userMenus); List<UserIdentityDTO> identitys = userIdentityService.query(baseInfoManager.getUserId(), "", "", "", "", "", "", null, null); model.addAttribute("identitys", StringUtils.join(identitys.get(0).getIdentities())); } private Boolean isCookieExist(Cookie[] cookies, List<UserMenuBean> menuList, String key) { boolean isCookieExist = false; for (Cookie cookieTemp : cookies) { if (cookieTemp.getName().equals(key)) { for (UserMenuBean userMenuBean : menuList) { if (userMenuBean.getMenuId().equals(cookieTemp.getValue())) { isCookieExist = true; } } } } return isCookieExist; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/RecommendQuestionConditionBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import java.util.List; /** * 推荐题目条件BO * @author <EMAIL> * @since 2018年4月19日 */ public class RecommendQuestionConditionBO { /** 年级编码*/ private String gradeCode; /** 科目编码*/ private String subjectCode; /** 教材版本*/ private String materialVersion; /** 题型编码*/ private String typeCode; /** 难易度编码*/ private String difficultyCode; /** 知识点searchCode列表*/ private List<String> knowledges; public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getMaterialVersion() { return materialVersion; } public void setMaterialVersion(String materialVersion) { this.materialVersion = materialVersion; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getDifficultyCode() { return difficultyCode; } public void setDifficultyCode(String difficultyCode) { this.difficultyCode = difficultyCode; } public List<String> getKnowledges() { return knowledges; } public void setKnowledges(List<String> knowledges) { this.knowledges = knowledges; } } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/core/SecurityConfig.java package com.enableets.edu.enable.cloud.exam.manager.core; import com.enableets.edu.module.security.annotation.EnableETSOAuth2Sso; import com.enableets.edu.module.security.authorization.annotation.EnableACMPrivilege; import com.enableets.edu.module.security.oauth2.client.OAuth2LogoutHandler; import com.enableets.edu.module.security.oauth2.client.configure.CustomSsoSecurityConfigurer; import com.enableets.edu.web.framework.urlrewrite.handler.IUrlRewriteHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Login authentication * @author <EMAIL> * @since 2017/5/19 */ @Configuration @EnableETSOAuth2Sso @EnableACMPrivilege public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Value("${security.oauth2.sso.logoutUri}") private String logout; @Value("${security.oauth2.sso.redirectUri}") private String indexUrl; @Value("${security.oauth2.sso.logoutPath:/oauth2ClientLogout}") private String logoutPath; @Value("${security.oauth2.sso.un-authenticated-matchers}") private String[] unAuthenticatedMatchers; /** url matchers of ignoreCsrf */ @Value("${security.oauth2.sso.ignore-csrf-matchers}") private String[] ignoreCsrfMatchers; @Autowired private CustomSsoSecurityConfigurer customSsoSecurityConfigurer; @Autowired private IUrlRewriteHandler urlRewriteHandler; @Override protected void configure(HttpSecurity http) throws Exception { //By default, all requests are protected http.antMatcher("/**") .authorizeRequests() //Ajax, static resources and other requests are excluded, .antMatchers(unAuthenticatedMatchers).permitAll() // Other requests require user authentication .anyRequest().authenticated() .and() .logout().logoutUrl(Constants.CONTEXT_PATH + "/logout") //.addLogoutHandler(new OAuth2LogoutHandler(logout, indexUrl)) .addLogoutHandler(new OAuth2LogoutHandler(logout, indexUrl, urlRewriteHandler)) .logoutSuccessUrl("/").permitAll(); http.headers().frameOptions().sameOrigin(); customSsoSecurityConfigurer.configure(http); customSsoSecurityConfigurer.csrf(http, ignoreCsrfMatchers); http.csrf().disable(); } public String getLogout() { return logout; } public void setLogout(String logout) { this.logout = logout; } public String getIndexUrl() { return indexUrl; } public void setIndexUrl(String indexUrl) { this.indexUrl = indexUrl; } } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/vo/AddExamDetailsInfoV2VO.java package com.enableets.edu.enable.cloud.exam.microservice.vo; import com.enableets.edu.enable.cloud.exam.framework.core.Constants; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModelProperty; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; import java.util.List; /** * @Auther: <EMAIL> * @Date: 2019/1/23 * @Description: 考试详情VO */ @JsonIgnoreProperties(ignoreUnknown = true) public class AddExamDetailsInfoV2VO { /** * 考试标识 */ private Long examId; /** * 年级编码 */ private String gradeCode; /** * 年级名称 */ private String gradeName; /** * 学科代码 */ private String subjectCode; /** * 学科名称 */ private String subjectName; /** * 课程标识 */ private String courseId; /** * 课程名称 */ private String courseName; /** * 文理科属性:理科;文科 */ private String courseAttribute; /** * 考试时间 */ @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private Date examTime; /** * 计划考试学生数 */ private Integer planStudentNumber; /** * 实际考试学生数 */ private Integer actualStudentNumber; /** * 试卷总分 */ private float totalScore; /** * 创建者 */ private String creator; /** * 创建时间 */ @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private Date createTime; /** * 修改者 */ private String updator; /** * 修改时间 */ @DateTimeFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) @JsonFormat(pattern = Constants.DEFAULT_DATE_TIME_FORMAT) private Date updateTime; private ExamDetailsStepTaskInfoVO stepTaskInfo; private List<ExamDetailsMarkAssigneeVO> markAssignees; /** assign question to be marked by special teacher */ @ApiModelProperty(value = "the info of teachers who mark the questions") private List<AddQuestionMarkAssigneesVO> questionMarkAssignees; public Long getExamId() { return examId; } public void setExamId(Long examId) { this.examId = examId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public String getSubjectCode() { return subjectCode; } public void setSubjectCode(String subjectCode) { this.subjectCode = subjectCode; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseAttribute() { return courseAttribute; } public void setCourseAttribute(String courseAttribute) { this.courseAttribute = courseAttribute; } public Date getExamTime() { return examTime; } public void setExamTime(Date examTime) { this.examTime = examTime; } public Integer getPlanStudentNumber() { return planStudentNumber; } public void setPlanStudentNumber(Integer planStudentNumber) { this.planStudentNumber = planStudentNumber; } public Integer getActualStudentNumber() { return actualStudentNumber; } public void setActualStudentNumber(Integer actualStudentNumber) { this.actualStudentNumber = actualStudentNumber; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public float getTotalScore() { return totalScore; } public void setTotalScore(float totalScore) { this.totalScore = totalScore; } public List<ExamDetailsMarkAssigneeVO> getMarkAssignees() { return markAssignees; } public void setMarkAssignees(List<ExamDetailsMarkAssigneeVO> markAssignees) { this.markAssignees = markAssignees; } public ExamDetailsStepTaskInfoVO getStepTaskInfo() { return stepTaskInfo; } public void setStepTaskInfo(ExamDetailsStepTaskInfoVO stepTaskInfo) { this.stepTaskInfo = stepTaskInfo; } public List<AddQuestionMarkAssigneesVO> getQuestionMarkAssignees() { return questionMarkAssignees; } public void setQuestionMarkAssignees(List<AddQuestionMarkAssigneesVO> questionMarkAssignees) { this.questionMarkAssignees = questionMarkAssignees; } } <file_sep>/Exam Micro Service/src/main/java/com/enableets/edu/enable/cloud/exam/microservice/restful/ExamLevelInfoRestful.java package com.enableets.edu.enable.cloud.exam.microservice.restful; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamLevelInfoBO; import com.enableets.edu.enable.cloud.exam.framework.bo.ExamLevelTemplateBO; import com.enableets.edu.enable.cloud.exam.framework.service.ExamLevelInfoService; import com.enableets.edu.enable.cloud.exam.microservice.annotation.ResponseResult; import com.enableets.edu.enable.cloud.exam.microservice.vo.ExamLevelInfoVO; import com.enableets.edu.enable.cloud.exam.microservice.vo.ExamLevelTemplateVO; import com.enableets.edu.framework.core.util.BeanUtils; import com.enableets.edu.module.service.controller.ServiceControllerAdapter; import com.enableets.edu.module.service.core.Response; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 考试等级管理 *@author 作者 E-mail:<EMAIL> *@date:2018年12月3日 下午4:00:30 */ @Api(tags="(05)考试级别管理",description ="考试级别管理") @RestController @ResponseResult @RequestMapping("/microservice/cloud/examservice/level") public class ExamLevelInfoRestful { @Autowired private ExamLevelInfoService examLevelInfoService; /** * 考试等级查询 * @param schoolId * @return */ @ApiOperation(value = "考试级别查询",notes = "考试级别查询") @RequestMapping(value = "/list" ,method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"}) public List<ExamLevelInfoVO> getExamLevelList( @ApiParam(value="学校标识", required=true) @RequestParam(value="schoolId", required=true) String schoolId, @ApiParam(value="年级标识", required=true) @RequestParam(value="gradeCode", required=false)String gradeCode){ List<ExamLevelInfoBO> examLevelList = examLevelInfoService.getExamLevelList(schoolId,gradeCode); return BeanUtils.convert(examLevelList,ExamLevelInfoVO.class); } @ApiOperation(value = "查询模板分数等级信息", notes = "查询分数等级信息") @RequestMapping(value = "/template", method = RequestMethod.POST) public List<ExamLevelTemplateVO> queryTemplate( ){ List<ExamLevelTemplateBO> levelTemlate = examLevelInfoService.getLevelTemlate(); return BeanUtils.convert(levelTemlate, ExamLevelTemplateVO.class); } } <file_sep>/Exam Manager/src/main/resources/i18n/lang_en_US.properties #Created by JInto - www.guh-software.de #Fri Sep 30 15:53:11 CST 2016 <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/BaseSearchConditionBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; import lombok.Data; import java.util.List; /** * @author <EMAIL> * @since 2020/08/10 **/ @Data public class BaseSearchConditionBO { private List<StageInfoBO> stages; private List<GradeInfoBO> grades; private List<SubjectInfoBO> subjects; } <file_sep>/Exam Manager/src/main/resources/static/comm/plugins/paging/lang/zh_CN.js var $lang={ "prev_page" : "上一页", "next_page" : "下一页", "first_page" : "首页", "last_page" : "尾页" }<file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/bo/xkw/XKWPartHeadBO.java package com.enableets.edu.enable.cloud.exam.manager.bo.xkw; import lombok.Data; /** * 卷别头部信息 * * @author <EMAIL> * @since 2020/09/01 13:54 **/ @Data public class XKWPartHeadBO { /* 第I卷(选择题) */ private String name; /* 第I卷(选择题) */ private String note; } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/vo/KnowledgeInfoVO.java package com.enableets.edu.enable.cloud.exam.manager.paper.vo; import lombok.Data; /** * @author <EMAIL> * @since 2020/08/14 **/ @Data public class KnowledgeInfoVO { private String knowledgeId; private String knowledgeName; private String materialVersion; private String materialVersionName; private String searchCode; } <file_sep>/Exam Framework/src/main/java/com/enableets/edu/enable/cloud/exam/framework/dao/ExamPointInputSettingDAO.java package com.enableets.edu.enable.cloud.exam.framework.dao; import com.enableets.edu.enable.cloud.exam.framework.po.ExamPointInputSettingPO; import com.enableets.edu.framework.core.dao.BaseDao; /** * @Auther: <EMAIL> * @Date: 2019/1/23 14:19 * @Description: 录分老师安排DAO */ public interface ExamPointInputSettingDAO extends BaseDao<ExamPointInputSettingPO> { } <file_sep>/Exam Manager/src/main/java/com/enableets/edu/enable/cloud/exam/manager/paper/bo/KnowledgeInfoBO.java package com.enableets.edu.enable.cloud.exam.manager.paper.bo; /** * 知识点相关信息 * @author duffy_ding * @since 2018/03/08 */ public class KnowledgeInfoBO { /** * 知识点id */ private String knowledgeId; /** * 知识点名称 */ private String knowledgeName; /** * 检索码 */ private String searchCode; /** * 版本 */ private String materialVersion; /** * 版本名称 */ private String materialVersionName; /** 知识点编号*/ private String knowledgeNo; /** 教纲searchCode*/ private String outlineId; public String getKnowledgeId() { return knowledgeId; } public void setKnowledgeId(String knowledgeId) { this.knowledgeId = knowledgeId; } public String getKnowledgeName() { return knowledgeName; } public void setKnowledgeName(String knowledgeName) { this.knowledgeName = knowledgeName; } public String getSearchCode() { return searchCode; } public void setSearchCode(String searchCode) { this.searchCode = searchCode; } public String getMaterialVersion() { return materialVersion; } public void setMaterialVersion(String materialVersion) { this.materialVersion = materialVersion; } public String getMaterialVersionName() { return materialVersionName; } public void setMaterialVersionName(String materialVersionName) { this.materialVersionName = materialVersionName; } public String getKnowledgeNo() { return knowledgeNo; } public void setKnowledgeNo(String knowledgeNo) { this.knowledgeNo = knowledgeNo; } public String getOutlineId() { return outlineId; } public void setOutlineId(String outlineId) { this.outlineId = outlineId; } }
2e33f84705c54a242e4a7114ddd8295a450aa8c7
[ "JavaScript", "Java", "Maven POM", "INI" ]
96
Java
zhouyi10/Enable-Cloud-Exam
7efb6b973071c4369adf5b43cd8d8f986c80f1ab
eb3f30cd42ce958c909ed3a0806f5439d59dff2c
refs/heads/master
<repo_name>enow97/Engineering-Training-Assignments-projects<file_sep>/CEF 306 Assignment AmaraMachine/src/amaramachine/AmaraMachine.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package amaramachine; import static java.lang.System.*; import java.util.*; /** * * @author daniel */ public class AmaraMachine { public static void main(String[] args) { Dispenser dispenser = new Dispenser(); CashRegister cash = new CashRegister(); Scanner input = new Scanner(in); int index = 0; out.println("Menu:\n----------------------------------\n" + "1. Different Products.\n" + "2. Make Selection.\n" + "3. Show Price.\n" + "4. Make Payment.\n" + "5. Get Item.\n" + "6. View Cash.\n" + "7. Exit"); out.println("--------------------------------"); out.println("Choice: "); int choice = input.nextInt(); do { switch (choice) { case 1: dispenser.showProducts(); break; case 2: out.print("\nIndex: "); index = input.nextInt(); break; case 3: out.println("This item costs: " + dispenser.showPrice(index)); break; case 4: double amount = input.nextDouble(); cash.getAmount(index, amount); break; case 5: out.println("Thanks for making business with Mami Amara's Machine!\n"); out.println("\nExit? Yes(y/Y) / No(n/N) to quit."); break; case 6: out.print("Password: "); String password = input.next(); out.println(cash.viewCash(password)); break; case 7: out.println("Thanks for making business with Mami Amara's Machine!\nHave a nice Day!"); exit(0); break; default: out.println("Sorry: invalid choice."); break; } out.println("Menu:\n----------------------------------\n" + "1. Different Products.\n" + "2. Make Selection.\n" + "3. Show Price.\n" + "4. Make Payment.\n" + "5. Get Item.\n" + "6. View Cash.\n" + "7. Exit"); out.println("--------------------------------"); out.println("Choice: "); choice = input.nextInt(); } while (choice != 7); } } <file_sep>/README.md This is all about the challenging class projects during my degree training. <file_sep>/CEF 308 Website Assignment/index.php <html> <head> <meta charset="utf-8"> <title>Home Page</title> <link rel="stylesheet" type="text/css" href="./css/indexStyle.css"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css"> <link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script type="text/javascript"> function changeHeader() { // document.getElementsByClassName("dropmenu").onclick = function() { document.getElementById("contact").onclick = function() { document.getElementById("header").style.backgroundColor="green"; }; // } // }; } // window.onload = changeHeader; </script> </head> <body> <?php require('./include/indexFunction.php'); $caller = new WebPage("Tech-House"); if(empty($_GET['id'])) { $caller->header(); $caller->menu(); $caller->mainPage("Home"); $caller->footerHandle(); $caller->footer(); } else { $id = $_GET['id']; $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $db = "Tech-house"; $connection = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($connection->connect_error) { echo "Unsuccessfull connection"; } else { // echo "Successful"; } $caller->header(); $caller->menu(); // $caller->sidebar(); $caller->mainPage($id); // $caller->sidebar(); $caller->footerHandle(); $caller->footer(); // $userName = $_POST['name']; // $userEmail = $_POST['email']; // $userComment = $_POST['comments']; // // if (!$_POST['submit']) { // echo "no submit"; // } else { // $query = "INSERT INTO Accounts(Name, Email, Comment) values('$userName', '$userEmail', '$userComment')"; // // // if(mysqli_query($connection, $query)) { // echo "OK"; // } else { // echo "Problem"; // } // if (mysqli_query($connection, $query)) { // // $caller->message(); // echo "OK"; // // echo "<script type='text/javascript'>alert('Well done! // // Thanks for subscribing');</script>"; // } else { // echo "<script type='text/javascript'>alert('Something went wrong, please try later\n$mysqli->query($query)');</script>"; // // } // $fname = $_POST['fname']; // $lname = $_POST['lname']; // $phone = $_POST['phone']; // $email = $_POST['email2']; // $subject = $_POST['subject']; // $message = $_POST['message']; // // if($_POST['submit2']) { // $query2 = "insert into Contacts(First_name, Last_name, Phone, Email, Subject, Message) values('$fname', '$lname', '$phone', '$email', '$subject', '$message')"; // // if(mysqli_query($connection, $query2)) { // echo "OK"; // } else { // echo "<script type='text/javascript'>alert('Sorry, something went wrong, please try again');</script>"; // } // // } else { // echo "hmmmmmmmmmmmmmmmmmmmmmmmmm"; // } // } ?> <script type="text/javascript" src="script.js"></script> </body> </html> <file_sep>/CEF 308 Website Assignment/include/connection.php <?php $dbhost = "localhost"; $dbuser = "root"; $dbpass = ""; $db = "Tech-house"; $connection = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($connection->connect_error) { echo "Unsuccessfull connection"; } else { echo "Successful"; } ?> <file_sep>/BankAccount CEF 306 Assignment/src/bankaccount/CheckingAccount.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bankaccount; /** * * @author daniel */ public class CheckingAccount extends BankAccount { private static final double TRANSACTION_FEE = 100.0; private static final int FREE_TRANSACTIONS = 3; private int count; /** * Constructs a checking account with a given balance * @param initialBalance the initial balance */ public CheckingAccount(double initialBalance) { super(initialBalance); count = 1; } /** * Gives three free withdrawals per month * @param amount the amount to withdraw */ @Override public void withdraw(double amount) { if (count < FREE_TRANSACTIONS) { super.withdraw(amount); count++; } else { super.withdraw(amount); deductFees(); } } /** * Deducts the fees which equals 100frs */ private void deductFees() { super.withdraw(TRANSACTION_FEE); } } <file_sep>/BankAccount CEF 306 Assignment/src/bankaccount/BankAccount.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bankaccount; /** * A bank account has a balance that can be changed by * deposits and withdrawals * @author daniel */ public class BankAccount { private double balance; /** * Constructs a bank account with a zero balance. */ public BankAccount() { balance = 0; } /** * Constructs a bank account with a given balance. * @param initialBalance the initial balance. */ public BankAccount(double initialBalance) { balance = initialBalance; } /** * Deposits money into the bank account. * @param amount the amount to deposit. */ public void deposit(double amount) { balance += amount; } /** * Withdraws money from the bank account * @param amount the amount to withdraw */ public void withdraw(double amount) { balance -= amount; } /** * Gets the current balance of the bank account. * @return */ public double getBalance() { return balance; } /** * Transfers money from one account to another * @param amount the amount to transfer * @param other the other bank account */ public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } } <file_sep>/CEF 308 Website Assignment/include/indexFunction.php <?php // require('./include/connection.php'); error_reporting(0); class WebPage{ private $head; private $headId; private $image; private $menus = array("Home", "Activities", "About", "Contact"); private $activities = array("Recent-Techs", "Tech Fields", "Online Training"); private $query; private $dbpass; private $result; private $db; private $dbhost; private $userName; private $dbuser; private $userEmail; private $userComment; private $connection; private $fname; private $query2; private $lname; private $phone; private $email; private $subject; private $message; function WebPage($head) { $this->head = $head; } public function header() { echo "<div id='header'> <div class='logo'> <a href='#'>$this->head</a> </div> "; } public function menu() { echo "<div id='nav'>"; foreach ($this->menus as $menu) { if ($menu == "Activities") { echo " <div class='dropdown'> <span><a href='#$menu' class='dropbtn' >$menu</a></span> <div class='dropdown-content'>"; foreach ($this->activities as $activity) { echo "<a href='index.php?id=$activity' >$activity</a>"; } echo "</div></div>"; } elseif ($menu == "Contact") { echo " <div id='contactbtn'> <a href='index.php?id=$menu' id='contact' onclick='changeHeader()'>$menu</a> </div> "; } else { echo " <a href='index.php?id=$menu'>$menu</a> "; } } echo "</div></div>"; } private function sidebar($image) { echo " <div id='sidebar' style='visibility: hidden;'> <h3>You might like this!</h3> <p><img src=$image alt='jetman' width='275px' height='200px'></p> </div> "; } public function mainPage($item) { echo "<div id='container'> <div id='content' id='contentId'>"; if ($item == "Home") { $this->homeContent(); } elseif ($item == "About") { echo " <div class='aboutfont-title'> <h3>Who is Tech-House <span style='color: #e3b11c'>?</span></h3> </div> <hr> "; $aboutFile = fopen("./include/about", "r") or exit("Unable to open the file"); echo "<div class='about-content'>"; while (!feof($aboutFile)) { echo fgets($aboutFile); } echo "</div>"; // form(); } elseif ($item == "Recent-Techs") { $tech_file = fopen("./include/recent-tech", "r") or exit("Unable to open the file."); echo "<div id='tech-font-title'> <h3> The Current Alarming Technologies of 2017 </h3> </div> <hr id='length'> "; while(!feof($tech_file)) { echo fgets($tech_file); } fclose($tech_file); } elseif ($item == "Tech Fields") { $field_file = fopen("./include/tech-fields", "r") or exit("Unable to open the file ".$field_file); echo "<div id='tech-font-title'> <h3> Technology Fields. </h3> </div> <hr id='length'> "; while(!feof($field_file)) { echo fgets($field_file); } fclose($field_file); } elseif ($item == "Online Training") { $online_file = fopen("./include/online", "r") or exit("Unable to open the file ". $online_file); echo "<div id='tech-font-title'> <h3> Free Career-Advancing Courses You Can Take Online.</h3> </div> <hr id='length'> "; while(!feof($online_file)) { echo fgets($online_file); } fclose($online_file); } elseif ($item == "Contact") { // $form_file = fopen("./include/contact.html", "r") or exit("Unable to open the file ". $form_file); // // while(!feof($form_file)) { // echo fgets($form_file); // } // fclose($form_file); echo "<div class='block-content'> <h2 class='center-align'>Contact Information</h2> <hr id='length2'> <h3 class='contact-margin'style='color: #070e12;'>Main Address:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Support Office Address</h3> <br> <p id='overflow'>14504 Greenview Drive, Suite 415&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;349 South Port Circle</p> <br> <p>Laurel, MD 20708&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Virginia Beach, VA 23452 </p><br><br> <h3 class='contact-margin' style='color: #070e12';>Phone:</h3><br> <p>(MTN) +237 651 523 013</p><br> <p>Sales (301)886-8377</p> <br><br> <hr id='length3'> <div class='class-title'> Name&nbsp;&nbsp;<span>*</span> </div> <form method='post' action='index.php'> <div class='field'> <label class='caption'> <input class='field-element field-control' name='fname' x-autocompletetype='given-name' spellcheck='false' maxlength='30' data-title='First' type='text'> First Name </label> </div><br> <div class='field'> <label class='caption'> <input class='field-element field-control' name='lname' x-autocompletetype='surname' spellcheck='false' maxlength='30' data-title='Last' type='text'> Last Name </label> </div> <br><br> <div class='class-title'> Phone&nbsp;&nbsp;<span>*</span> </div> <div class='field'> <label class='caption'> <input class='field-element3' name='phone' x-autocompletetype='phone-area-code' spellcheck='false' maxlength='9' data-title='AreaCode' type='text'> (#########) </label> </div> <br><br> <div class='class-title'> Email Address&nbsp;&nbsp;<span>*</span> </div> <div class='field'> <label class='caption'> <input class='field-element field-control' name='email' x-autocompletetype='email' spellcheck='false' type='text'> </label> </div> <br><br> <div class='class-title'> Subject&nbsp;&nbsp;<span>*</span> </div> <div class='field'> <label class='caption'> <input class='field-element field-control' name='subject' type='text'> </label> </div> <br><br> <div class='class-title'> Message&nbsp;&nbsp;<span>*</span> </div> <div class='field'> <label class='caption'> <textarea class='field-element field-control' name='comments' spellcheck='true' type='text'></textarea> </label> </div> <div class='btn'> <input class='button' type='submit' name='submit' value='Submit'/> </div> </form> </div> "; } echo "</div>"; } public function footer() { echo " <footer class='footer-distributed'> <div class='footer-left'> <h3>Graham-<span>Tech</span></h3> <p class='footer-links'> <a href='index.php?id=Home'>Home</a> · <a href='index.php?id=Contact'>Contact</a> </p> <p class='footer-company-name'>Tech-House &copy; 2017</p> <div class='footer-icons'> <a href='#'><i class='fa fa-facebook'></i></a> <a href='#'><i class='fa fa-linkedin'></i></a> <a href='#'><i class='fa fa-yahoo'></i></a> <a href='#'><i class='fa fa-github'></i></a> </div> </div> <div class='footer-right'> <p>Comment:</p> <form action='index.php' method='post'> <input type='text' name='name' placeholder='Name' /> <input type='text' name='email' placeholder='Email' /> <textarea name='comments' placeholder='Message'></textarea> <input type='submit' name='submit' value='Send' id='button' /> </form> </div> </footer> "; } // {$_SERVER['PHP_SELF']} protected function homeContent() { $images = array("./images/jetman.jpg", "./images/ar&vr.jpeg", "./images/cloud.jpeg"); echo " <div class='height'> <div class='font'><h2><br>| Technology is a word that describes something that doesn’t work yet. |<br><br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| The greatest achievement of humanity is not its works of art, science, or technology, but the recognition of its own dysfunction. | </h2> </div><br><br> <div class='gall1'> <div><a href='index.php?id=electrical' data-title='Electrical'><img src='./images/elec.jpeg' alt='elec image'></a></div> <div class='desc'> <div class='summary'><a class='tialink' href='index.php?id=electrical'> Electrical and Electronic Technologies</a></div> </div> </div> <div class='gall2'> <div><a href='index.php?id=civil' data-title='Civil'><img src='./images/civil2.jpeg' alt='civil2 image'></a> </div> <div class='desc'> <div class='summary'><a href='index.php?id=civil'> Civil Technologies</a> </div> </div> </div> <div class='gall3'> <div><a href='index.php?id=computer' data-title='Computer'><img src='./images/cpt.jpeg' alt='cpt image'></a></div> <div class='desc'> <div class='summary'><a class='tialink' href='index.php?id=computer'> Computer Technologies</a> </div> </div> </div>"; foreach ($images as $image) { $this->sidebar($image); } echo "</div>"; } public function message() { echo " <script type='text/javascript'> var contentId = document.getElementById('contentId'); contentId.innerHTML = '<h3> Well done!</h3> <p>Thanks for subscribing</p>'; </script> "; } public function footerHandle() { $this->dbhost = "localhost"; $this->dbuser = "root"; $this->dbpass = ""; $this->db = "Tech-house"; $this->connection = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->db); if ($this->connection->connect_error) { echo "Unsuccessfull connection"; } else { // echo "Successful"; } $this->userName = $_POST['name']; $this->userEmail = $_POST['email']; $this->userComment = $_POST['comments']; if (!$_POST['submit']) { // echo "no submit"; } else { $this->query = "INSERT INTO Accounts(Name, Email, Comment) values('$this->userName', '$this->userEmail', '$this->userComment')"; if (mysqli_query($this->connection, $this->query)) { // $this->message(); // echo "OK"; echo "<script type='text/javascript'>alert('Well done! Thanks for subscribing');</script>"; } else { echo "<script type='text/javascript'>alert('Something went wrong, please try later');</script>"; } } } // public function contactHandler() { // // $this->fname = $_POST['fname']; // $this->lname = $_POST['lname']; // $this->phone = $_POST['phone']; // $this->email = $_POST['email']; // $this->subject = $_POST['subject']; // $this->comment = $_POST['comments']; // // if(!empty($_POST['contact_submit'])) { // $this->query2 = "INSERT INTO Contacts(First_name, Last_name, Phone, Email, Subject, Message) values('$this->fname', '$this->lname', '$this->phone', '$this->email', '$this->subject', '$this->message')"; // // if(mysqli_query($this->connection, $this->query2)) { // echo "OK"; // } else { // echo "Problem"; // // echo "<script type='text/javascript'>alert('Sorry, something went wrong, please try again');</script>"; // } // // } else { // echo "not OK for the contact"; // } // } public function slides() { echo ' <h2 class="w3-center">HTML slides</h2> <div class="w3-content" style="max-width:400px"> <div class="mySlides w3-container w3-red"> <h1><b>Did You Know?</b></h1> <h1><i>We plan to sell trips to the moon in the 2020s</i></h1> </div> <div class="mySlides w3-container w3-xlarge w3-white w3-card-4"> <p><span class="w3-tag w3-yellow">New!</span> <p>6 Crystal Glasses</p> <p>Only $99 !!!</p> </div> </div> '; echo "</div>"; } } ?> <!-- <p><img src='./images/affor.jpeg' alt='affor image' width='275px' height='200px'></p> <h4>Google announced android 7.0</h4> <p><img src='./images/androidg.jpeg' alt='androidg image' width='275px' height='200px'></p> --> <file_sep>/CEF 308 Website Assignment/connection.php <?php $host = "localhost"; $user = "root"; $password = ""; $db = "Tech-house"; $connection = new mysqli($host, $user, $password, $db); if ($connection->connect_error) { echo "Unsuccessfull connection"; } else { // echo "Successfull connection"; // echo 'Connected... ' . mysqli_get_host_info($connection) . "\n"; } // if (!@mysql_select_db($db, $connection)) { // echo "Could not connect to ".$db; // } // $query2 = "select Content from Recent-Tech-Content"; // $result = $connection->query($query2); // // if ($result->num_rows > 0) { // // output data of each row // while($row = $result->fetch_assoc()) { // echo $row["Content"]; // } // } else { // echo "0 results"; // } // $connection->close(); ?> <file_sep>/CEF 308 Website Assignment/include/formsub.php <?php include ('connection.php'); error_reporting(0); function form() { echo " <form action='index.php' method='POST'> Name: &nbsp;&nbsp;&nbsp;<input type='text' name='fname' required id='formin'><br> Email: &nbsp;&nbsp;&nbsp;<input type='email' name='umail' required id='formin'><br> Contact: <input type='text' name='ucon' required id='formin'><br> <input type='submit' name='submit' value='Create' id='formbtn'> </form> "; } ?><file_sep>/BankAccount CEF 306 Assignment/src/bankaccount/BankAccountTester.java package bankaccount; /** * A class to test the BankAccount class. * * @author daniel */ public class BankAccountTester { /** * Tests the methods of the BankAccount class. * * @param args not used */ public static void main(String[] args) { // SavingsAccount momsSavings = new SavingsAccount(0.5); // // CheckingAccount harrysChecking = new CheckingAccount(100); BankAccount myAccount = new CheckingAccount(9000); BankAccount saving = new SavingsAccount(0.5); myAccount.deposit(1000); System.out.println("Current Balance: " + myAccount.getBalance()); myAccount.withdraw(1000); myAccount.withdraw(4000); System.out.println("Current Balance: " + myAccount.getBalance()); myAccount.withdraw(3000); System.out.println("Current Balance(with fee subtracted): " + myAccount.getBalance()); // System.out.println("Harry's Current: " + harrysChecking.getBalance() + "\n"); // momsSavings.deposit(10000); // System.out.println("Mom's deposit: " + momsSavings.getBalance()); // // momsSavings.transfer(2000, harrysChecking); // System.out.println("Transferred: " + harrysChecking.getBalance() + " to Harry"); // harrysChecking.withdraw(1500); // System.out.println("After Harry's Withdraw: " + harrysChecking.getBalance()); // harrysChecking.withdraw(80); // System.out.println("After Harry's Withdraw: " + harrysChecking.getBalance()); // // momsSavings.transfer(1000, harrysChecking); // System.out.println("Harry's Current balance: " + harrysChecking.getBalance()); // harrysChecking.withdraw(400); // System.out.println("After Harry's Withdraw: " + harrysChecking.getBalance()); // // System.out.println(); // // Simulate end of month // momsSavings.addInterest(); // System.out.println("After adding Mom's interest: " + momsSavings.getBalance()); //// harrysChecking.deductFees(); // // System.out.println("Mom's savings balance: " + momsSavings.getBalance()); // System.out.println("Expected: 7035"); // // System.out.println("Harry's checking balance: " + harrysChecking.getBalance()); // System.out.println("Expected: 1116"); } } <file_sep>/AmaraMachine/src/amaramachine/CashRegister.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package amaramachine; import static java.lang.System.*; /** * * @author daniel */ public class CashRegister { private double cash; private String password; private double balance; String message = ""; private Dispenser disp; public CashRegister() { this.password = "<PASSWORD>"; disp = new Dispenser(); this.cash = 1200; } public void getAmount(int choice, double amount) { if (Dispenser.itemCosts[choice - 1] == amount) { message = disp.release(choice); out.println(message); cash += amount; } else if (amount < Dispenser.itemCosts[choice - 1]) { message = "Inssuficient amount. Please Enter the correct price!"; out.println(message); } else if (amount > Dispenser.itemCosts[choice - 1]) { out.println(returnChange(choice, amount)); message = disp.release(choice); out.println(message); cash += amount; } } private String returnChange(int choice, double amount) { balance = amount - Dispenser.itemCosts[choice - 1]; cash -= balance; return "Get Your Balance: " + balance; } public String viewCash(String password) { if (password.equals(this.password)) { return "Your current cash is : " + this.cash; } else { return "Invalid Password!"; } } } // out.print("\033[H\033[2J"); // out.flush();
05f96167aaebbc808e10bb6eb791a1bf54da46ea
[ "Markdown", "Java", "PHP" ]
11
Java
enow97/Engineering-Training-Assignments-projects
bc5e827384254eadfaf2aa765c8cdafaf7b5314c
426d2b40f068d25c08a7741609a1c69023a49b6a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.ProjectOxford.Vision; namespace PetCheckerFunction { public static class PetChecker { /// <summary> /// Функция Azure для проверки питомца когнитивным сервисом Azure /// </summary> [FunctionName("PetChecker")] public static async Task RunPetChecker([CosmosDBTrigger("pets", "checks", ConnectionStringSetting = "constr", CreateLeaseCollectionIfNotExists = true)] IReadOnlyList<Document> document, TraceWriter log) { // Проходим по документам foreach (dynamic doc in document) { var isProcessed = doc.IsApproved != null; // Если одобрено, то continue if (isProcessed) { continue; } // URL работы функции (само изображение) var url = doc.MediaUrl; // Время загрузки var uploaded = (DateTime)doc.Created; log.Info($">>> Обработка изображения в {url} загруженного в {uploaded.ToString()}"); using (var httpClient = new HttpClient()) { // Результат var res = await httpClient.GetAsync(url); // Поток var stream = await res.Content.ReadAsStreamAsync() as Stream; log.Info("--- Изображение успешно загружено из хранилища"); // Анализируем изображение var (allowed, message) = await PassesImageModerationAsync(stream, log); log.Info($"--- Изображение проанализировано. Это было {(allowed ? string.Empty : "НЕ")} одобрено"); // Формируем документ doc.IsApproved = allowed; doc.Message = message; log.Info("--- Обновление документа CosmosDb с историческими данными"); // Загружаем документ в CosmosDb await UpsertDocument(doc, log); log.Info($"<<< Изображение в {url} обработано!"); } // using } // foreach } // RunPetChecker /// <summary> /// Загрузка документа /// </summary> private static async Task UpsertDocument(dynamic doc, TraceWriter log) { // URI var endpoint = Environment.GetEnvironmentVariable("cosmos_uri"); // Ключ var auth = Environment.GetEnvironmentVariable("cosmos_key"); // Выполняем вход var client = new DocumentClient(new Uri(endpoint), auth); const string dbName = "pets"; const string colName = "checks"; doc.Analyzed = DateTime.Now; // Загрузка документа в космическую базу await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(dbName, colName), doc); log.Info("--- Обновлен документ CosmosDb."); } // UpsertDocument /// <summary> /// Анализ изображения /// </summary> public static async Task<(bool, string)> PassesImageModerationAsync(Stream image, TraceWriter log) { log.Info("--- Создание клиента VisionApi и анализ изображения"); // Ключ var key = Environment.GetEnvironmentVariable("MicrosoftVisionApiKey"); // Конечная точка Vision API var endpoint = Environment.GetEnvironmentVariable("MicrosoftVisionApiEndpoint"); // Создаём клиент var client = new VisionServiceClient(key, endpoint); // Выбираем Description - описание картинки var features = new[] { VisualFeature.Description }; // Запускаем анализ картинки var result = await client.AnalyzeImageAsync(image, features); log.Info($"--- Изображение проанализировано c тэгами: {string.Join(",", result.Description.Tags)}"); // Тэги для извлечения if (!int.TryParse(Environment.GetEnvironmentVariable("MicrosoftVisionNumTags"), out var tagsToFetch)) { tagsToFetch = 5; } // Анализируем результат. Если есть "dog" в описании значит картинка нам подходит var isAllowed = result.Description.Tags.Take(tagsToFetch).Contains("dog"); var message = result.Description?.Captions.FirstOrDefault()?.Text; return (isAllowed, message); } // PassesImageModerationAsync } // PetChecker }<file_sep>/// <reference path='../../node_modules/msal/out/msal.d.ts' /> import { Reducer } from 'redux'; import { Md5 } from 'ts-md5/dist/md5'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { settings } from '../Settings'; // Домен арендатор const tenant = settings.b2c.tenant; // Политика регистрации/входа const policy = settings.b2c.policy; // ИД клиента AAD B2C const client = settings.b2c.client; const scopes = ['openid']; // Ссылка авторизации const authority = `https://login.microsoftonline.com/tfp/${tenant}/${policy}`; // Менеджер пользователей let userManager: Msal.UserAgentApplication; // Описывает юзера interface IUser { user: Msal.User, email: string; } // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента export interface IUserState { id: string | null; name: string | null; email: string; gravatar: string; token: string; error: boolean; isLoading: boolean; } // Начальное состояние const initialState: IUserState = { id: null, name: null, email: '', gravatar: '', token: '', error: false, isLoading: false } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Инициализация interface INitAction { type: 'INIT_ACTION' } // Изменить пользователя interface ISetUserAction { type: 'SET_USER_ACTION', id: string | null, name: string | null, email: string, gravatar: string, token: string, isFake: boolean } // Логин interface ILoginAction { type: 'LOGIN_ACTION', error: boolean } // Логаут interface ILogoutAction { type: 'LOGOUT_ACTION' } // Известные действия type KnownAction = INitAction | ILoginAction | ILogoutAction | ISetUserAction; // Получить данные пользователя let getUserData = (accessToken: string): IUser => { // Получаем пользователя const user = userManager.getUser(); // Получаем email const jwt = Msal.Utils.decodeJwt(accessToken); let email = user.name; if (jwt && jwt.JWSPayload) { const decoded = JSON.parse(atob(jwt.JWSPayload)); if (decoded && decoded.emails && decoded.emails[0]) { email = decoded.emails[0]; } } return { user: user, email: email } } // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Инициализация init: (): AppThunkAction<KnownAction> => (dispatch, getState) => { userManager = new Msal.UserAgentApplication(client, authority, (errorDesc: any, token: any, error: any, tokenType: any) => { if (token) { userManager.acquireTokenSilent(scopes).then(accessToken => { const userData = getUserData(accessToken); //let bytes = encoder.encode(this.props.name); //let newName = decoder.decode(bytes); //console.log(name); //console.log(bytes); //console.log(newName); dispatch({ type: 'SET_USER_ACTION', id: userData.user.userIdentifier, name: userData.user.name, email: userData.email, gravatar: 'https://www.gravatar.com/avatar/' + Md5.hashStr(userData.email.toLowerCase()).toString(), token: accessToken, isFake: false }); }, error => { userManager.acquireTokenPopup(scopes).then(function (accessToken) { const userData = getUserData(accessToken); dispatch({ type: 'SET_USER_ACTION', id: userData.user.userIdentifier, name: userData.user.name, email: userData.email, gravatar: 'https://www.gravatar.com/avatar/' + Md5.hashStr(userData.email.toLowerCase()).toString(), token: accessToken, isFake: false }); }, function (error) { dispatch({ type: 'SET_USER_ACTION', id: null, name: null, email: '', gravatar: '', token: '', isFake: false }); }); }); } else { dispatch({ type: 'INIT_ACTION', id: null, name: null, email: '', gravatar: '', token: '' }); } }); dispatch({ type: 'INIT_ACTION' }); }, // Вход login: (): AppThunkAction<KnownAction> => (dispatch, getState) => { userManager.acquireTokenSilent(scopes) .then((accessToken: any) => { dispatch({ type: 'LOGIN_ACTION', error: false }); }, (error: any) => { userManager.loginRedirect(scopes); dispatch({ type: 'LOGIN_ACTION', error: true }); }); }, // Выход logout: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'LOGOUT_ACTION' }); localStorage.clear(); userManager.logout(); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IUserState> = (state: IUserState, action: KnownAction) => { switch (action.type) { case 'INIT_ACTION': return { ...state, isLoading: false }; case 'SET_USER_ACTION': return { ...state, error: false, id: action.id, name: action.name, email: action.email, gravatar: action.gravatar, token: action.token, isLoading: false }; case 'LOGIN_ACTION': return { ...state, error: action.error, isLoading: true }; case 'LOGOUT_ACTION': return { ...state, error: false }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>namespace SmartHotel220.Web.Services { /// <summary> /// Интерфейс рекомендации /// </summary> public interface ICustomerTestimonialService { CustomerTestimonial GetTestimonial(); } /// <summary> /// Клиентская рекомендация /// </summary> public class CustomerTestimonial { public string CustomerName { get; set; } public string Text { get; set; } } } <file_sep>import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { Reducer } from 'redux'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Описывает фичу (рекомендацию) export interface IFeature { title: string | null; imageUrl: string | null; description: string | null; } // Еденицы измерения type TranslationUnits = 'rem' | 'px' | 'em' | '%'; // Для передвижения карусели export interface ITranslation { current: number; factor: number; units: TranslationUnits; styles: any; min: number; max: number; } // Состояние фич export interface IFeaturesState { list: IFeature[]; translation: ITranslation; } // Начальное состояние const initialState: IFeaturesState = { list: [], translation: { current: 0, factor: 30, units: 'rem', styles: {}, min: 0, max: 0 } } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Запрос фич interface IRequestFeaturesAction { type: 'REQUEST_FEATURES_ACTION' } // Получение фич interface IReceiveFeaturesAction { type: 'RECEIVE_FEATURES_ACTION', list: IFeature[] } // Когда происходит свайп interface ITranslateAction { type: 'TRANSLATE_ACTION', current: number } // Известные действия type KnownAction = IRequestFeaturesAction | IReceiveFeaturesAction | ITranslateAction; // ----------------------------------------------------------------------------------------------------------------- // FUNCTIONS - Функции для повторного использования в этом коде // Передвинуть по иксу function createStyles(value: number, units: TranslationUnits): any { return { transform: `translateX(${value}${units})` } } // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Запрос request: (): AppThunkAction<KnownAction> => (dispatch, getState) => { // Статический контент const data = [ { title: null, imageUrl: null, description: null }, { title: 'Забронировать умный зал для конференций', imageUrl: '/assets/images/conference_room_1.png', description: 'Найдите идеальное место для проведения большой встречи на высоком уровне. Войдите в систему, настройте и забронируйте номер прямо сейчас. Инструменты SmartHotel220 помогут найти именно то, что Вам нужно.' }, { title: 'Автоматическая адаптация номера', imageUrl: '/assets/images/conference_room_2.png', description: 'Используя сенсоры и последние технологии, номер SmartHotel220 может снизить уровень освещения в солнечный день или предоставить услуги качественного питания для ваших гостей. Наши номера помогут Вам сделать обычный день необычным.' }, { title: 'Распознавание лиц', imageUrl: '/assets/images/conference_room_3.png', description: 'Наша технология распознавания лиц SmartHotel220 обеспечит отличную информацию о вашей аудитории. Определите людей в конференц-зале по имени и получите представление о эффективности вашей презентации.' }, { title: 'Настраивайте номер в один клик', imageUrl: '/assets/images/conference_room_4.png', description: 'Используйте приложение SmartHotel220 для настройки презентации. Создавайте и настраивайте собственную рабочую среду благодаря специальным эффектам SmartHotel220.' } ]; dispatch({ type: 'RECEIVE_FEATURES_ACTION', list: data }); }, // Перевести влево (свайп влево) translateLeft: (): AppThunkAction<KnownAction> => (dispatch, getState) => { // Получаем состояние const state = getState().conferenceRoomsFeatures; // Текущая позиция let current = state.translation.current -= state.translation.factor; // Передвигаем current = current < state.translation.max ? state.translation.current += state.translation.factor : current; dispatch({ type: 'TRANSLATE_ACTION', current: current}); }, // Перевести вправо (свайп вправо) translateRight: (): AppThunkAction<KnownAction> => (dispatch, getState) => { // Получаем состояние const state = getState().conferenceRoomsFeatures; // Текущая позиция let current = state.translation.current += state.translation.factor; // Передвигаем current = current > state.translation.min ? state.translation.current -= state.translation.factor : current; dispatch({ type: 'TRANSLATE_ACTION', current: current }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IFeaturesState> = (state: IFeaturesState, action: KnownAction) => { let translation = 0; switch (action.type) { case 'REQUEST_FEATURES_ACTION': return { ...state }; case 'RECEIVE_FEATURES_ACTION': // Длина списка const length = action.list.length % 2 === 0 ? action.list.length : action.list.length + 1; // Минимальное передвигаемое значение const min = ((length / 2) - 3) * state.translation.factor; // Максимальное передвигаемое значение const max = -((length / 2) - 2) * state.translation.factor; return { ...state, list: action.list, translation: { ...state.translation, min: min, max: max } }; case 'TRANSLATE_ACTION': return { ...state, translation: { ...state.translation, current: action.current, styles: createStyles(action.current, state.translation.units) } }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>import { Reducer } from 'redux'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { addTask } from 'domain-task'; import * as Search from './Search'; // Интерфейс описывает клиента, который озывается о компании // Testimonial - рекомендация interface ITestimonial { customerName: string; text: string; } // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Состоянии главной страницы export interface IHomeState { testimonial: ITestimonial; isLoading: boolean; } // Начальное состояние const initialState: IHomeState = { testimonial: {} as ITestimonial, isLoading: false } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Запрос рекомендации interface IRequestTestimonialAction { type: 'REQUEST_TESTIMONIAL_ACTION' } // Получение рекомендации interface IReceiveTestimonialAction { type: 'RECEIVE_TESTIMONIAL_ACTION', testimonial: ITestimonial } // Известные действия type KnownAction = IRequestTestimonialAction | IReceiveTestimonialAction; // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Запрос рекомендации requestTestimonial: (): AppThunkAction<KnownAction> => (dispatch, getState) => { let fetchTask = fetch(`/api/Testimonials`) .then(response => response.json() as Promise<ITestimonial>) .then(data => { dispatch({ type: 'RECEIVE_TESTIMONIAL_ACTION', testimonial: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_TESTIMONIAL_ACTION' }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IHomeState> = (state: IHomeState, action: KnownAction) => { switch (action.type) { case 'REQUEST_TESTIMONIAL_ACTION': return { ...state, isLoading: true }; case 'RECEIVE_TESTIMONIAL_ACTION': return { ...state, isLoading: false, testimonial: action.testimonial }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>using System; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using SmartHotel220.Web.Models.Settings; namespace SmartHotel220.Web.Services { /// <summary> /// Сервис опперирует настройками /// </summary> public class SettingsService { /// <summary> /// Серверные настройки /// </summary> public ServerSettings GlobalSettings { get; } /// <summary> /// Локальные настройки /// </summary> public LocalSettings LocalSettings { get; set; } private SettingsService(ServerSettings settings, LocalSettings localSettings) { GlobalSettings = settings; LocalSettings = localSettings; } /// <summary> /// Загрузка настроек по средствам http запроса /// </summary> /// <param name="localSettings">Локальные настройки</param> /// <returns>Сервис/служба настроек</returns> public static SettingsService Load(LocalSettings localSettings) { try { using (var client = new HttpClient()) { using (var response = client.GetAsync(new Uri(localSettings.SettingsUrl)).Result) { response.EnsureSuccessStatusCode(); var responseBody = response.Content.ReadAsStringAsync().Result; var model = JsonConvert.DeserializeObject<ServerSettings>(responseBody); model.Production = localSettings.Production; return new SettingsService(model, localSettings); } // using } // using } catch (Exception) { var model = new ServerSettings { Production = localSettings.Production }; return new SettingsService(model, localSettings); } // try-catch } // Load } // SettingsService }<file_sep>import { fetch, addTask } from 'domain-task'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { Reducer } from 'redux'; import { settings } from '../Settings'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Описывает номер export interface IRoom { id: number; name: string; itemType: string; city: string; rating: number; price: number; picture: string; } // Источники export enum Sources { Featured, Filtered } // Значения звёзд export type StarValues = 1 | 2 | 3 | 4 | 5; // Описывает фильтр interface IFilters { rating: StarValues; minPrice: number; maxPrice: number; } // Описывает состояние номера export interface IRoomsState { list: IRoom[]; isLoading: boolean; filters: IFilters; } // Начальное состояние const initialState: IRoomsState = { list: [], filters: { rating: 4, minPrice: 0, maxPrice: 1000 }, isLoading: false, } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Запрос рекомендуемых interface IRequestFeaturedAction { type: 'REQUEST_FEATURED_ACTION' } // Получение рекомендуемых interface IReceiveFeaturedAction { type: 'RECEIVE_FEATURED_ACTION', list: IRoom[] } // Запрос фильтрации interface IRequestFilteredAction { type: 'REQUEST_FILTERED_ACTION' } // Получение фильтрации interface IReceiveFilteredAction { type: 'RECEIVE_FILTERED_ACTION', list: IRoom[] } // Обновление цены interface IUpdatePriceAction { type: 'UPDATE_PRICE_ACTION', minPrice: number, maxPrice: number } // Обновление рейтинга interface IUpdateRatingAction { type: 'UPDATE_RATING_ACTION', rating: StarValues } // Известные действия type KnownAction = IRequestFeaturedAction | IReceiveFeaturedAction | IRequestFilteredAction | IReceiveFilteredAction | IUpdatePriceAction | IUpdateRatingAction; // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Запрос рекомендуемых requestFeatured: (): AppThunkAction<KnownAction> => (dispatch, getState) => { // Запрашиваем рекомендуемые номера let fetchTask = fetch(`${settings.urls.hotels}Featured`) .then(response => response.json() as Promise<IRoom[]>) .then(data => { dispatch({ type: 'RECEIVE_FEATURED_ACTION', list: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_FEATURED_ACTION' }); }, // Запрос профильтрованных requestFiltered: (): AppThunkAction<KnownAction> => (dispatch, getState) => { // Получаем состояние const state = getState(); // Запрашиваем отфильтрованные номера let fetchTask = fetch(`${settings.urls.hotels}Hotels/search?cityId=${state.search.where.value.id}&rating=${state.rooms.filters.rating}&minPrice=${state.rooms.filters.minPrice}&maxPrice=${state.rooms.filters.maxPrice}`, { method: 'GET' }) .then(response => response.json() as Promise<IRoom[]>) .then(data => { dispatch({ type: 'RECEIVE_FILTERED_ACTION', list: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_FILTERED_ACTION' }); }, // Обновление цены updatePrice: (minPrice: number, maxPrice: number): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'UPDATE_PRICE_ACTION', minPrice, maxPrice }); }, // Обновление рейтинга updateRating: (rating: StarValues): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'UPDATE_RATING_ACTION', rating }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IRoomsState> = (state: IRoomsState, action: KnownAction) => { switch (action.type) { case 'REQUEST_FEATURED_ACTION': return { ...state, isLoading: true }; case 'RECEIVE_FEATURED_ACTION': return { ...state, isLoading: false, list: action.list }; case 'REQUEST_FILTERED_ACTION': return { ...state, isLoading: true }; case 'UPDATE_PRICE_ACTION': return { ...state, filters: { ...state.filters, minPrice: action.minPrice, maxPrice: action.maxPrice } }; case 'UPDATE_RATING_ACTION': return { ...state, filters: { ...state.filters, rating: action.rating } }; case 'RECEIVE_FILTERED_ACTION': return { ...state, isLoading: false, list: action.list }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>using Microsoft.ApplicationInsights.AspNetCore; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.SnapshotCollector; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using SmartHotel220.Web.Models.Settings; using SmartHotel220.Web.Services; namespace SmartHotel220.Web { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // Этот метод вызывается во время выполнения. Используется для добавления сервисов в контейнер зависимостей. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Регистрируем локальный конфиг с настройками services.Configure<LocalSettings>(Configuration); // Загружаем настройки с сервера services.AddSingleton(sp => SettingsService.Load(sp.GetService<IOptions<LocalSettings>>().Value)); // Телеметрия ApplicationInsights services.AddSingleton<ITelemetryProcessorFactory>(new SnapshotCollectorTelemetryProcessorFactory()); // Кастомные сервисы if (!string.IsNullOrEmpty(Configuration["USE_NULL_TESTIMONIALS_SERVICE"])) { services.AddSingleton<ICustomerTestimonialService>(new NullCustomerTestimonialService()); } else { services.AddSingleton<ICustomerTestimonialService, PositiveTweetService>(); } } // Этот метод вызывается во время выполнения. Используйте этот метод для настройки конвейера HTTP-запросов. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ReactHotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( "default", "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( "spa-fallback", new { controller = "Home", action = "Index" }); }); } // Телеметрия ApplicationInsights private class SnapshotCollectorTelemetryProcessorFactory : ITelemetryProcessorFactory { public ITelemetryProcessor Create(ITelemetryProcessor next) => new SnapshotCollectorTelemetryProcessor(next); } } } <file_sep>import { Reducer } from 'redux'; import { History, Location } from 'history'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Описывает состояние навигации export interface INavMenuState { isHome: boolean; } // Начальное состояние const initialState: INavMenuState = { isHome: true } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() interface INavigateAction { type: 'NAVIGATE_ACTION' } // Домой interface INavigateHomeAction { type: 'NAVIGATE_HOME_ACTION' } // Известные действия type KnownAction = INavigateAction | INavigateHomeAction ; // ----------------------------------------------------------------------------------------------------------------- // FUNCTIONS - Функции для повторного использования в этом коде // Проверка на главную страницу function checkIsHome(pathname: string): boolean { return pathname === '/'; } // Выбрать диспетчера function chooseDispatcher(location: Location, dispatch: (action: KnownAction) => void): void { // Если это дом if (checkIsHome(location.pathname)) { dispatch({ type: 'NAVIGATE_HOME_ACTION' }); return; } // иначе dispatch({ type: 'NAVIGATE_ACTION' }); } // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Слушать историю браузера listen: (history: History): AppThunkAction<KnownAction> => (dispatch, getState) => { // Выбирать диспетчер в зависимости от местоположения history.listen((location: Location) => chooseDispatcher(location, dispatch)); chooseDispatcher(history.location, dispatch); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<INavMenuState> = (state: INavMenuState, action: KnownAction) => { switch (action.type) { case 'NAVIGATE_ACTION': return { ...state, isHome: false }; case 'NAVIGATE_HOME_ACTION': return { ...state, isHome: true }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>using System; using Newtonsoft.Json; namespace SmartHotel220.Web.Models { /// <summary> /// Документ питомца. Модель для API работы с хранилищем /// </summary> public class PetDocument { [JsonProperty(PropertyName = "id")] public Guid Id { get; set; } /// <summary> /// Имя питомца /// </summary> public string PetName { get; set; } /// <summary> /// URL картинки /// </summary> public string MediaUrl { get; set; } /// <summary> /// Одобрено или нет /// </summary> public bool? IsApproved { get; set; } /// <summary> /// Дата создания /// </summary> public DateTime Created { get; set; } /// <summary> /// Сообщение /// </summary> public string Message { get; set; } } } <file_sep>namespace SmartHotel220.Web.Models.Settings { /// <summary> /// Для более удобной работы с питомцами /// </summary> public class PetsConfig { /// <summary> /// URI CosmosDb /// </summary> public string CosmosUri { get; set; } /// <summary> /// Ключ CosmosDb /// </summary> public string CosmosKey { get; set; } /// <summary> /// Название BLOB-поля /// </summary> public string BlobName { get; set; } /// <summary> /// Ключ BLOB-поля /// </summary> public string BlobKey { get; set; } } } <file_sep>using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using SmartHotel220.Web.Models; using SmartHotel220.Web.Services; namespace SmartHotel220.Web.Controllers { /// <summary> /// Данные для запроса /// </summary> public class PetUploadRequest { /// <summary> /// Данные в формате строки base64 /// </summary> public string Base64 { get; set; } /// <summary> /// Название /// </summary> public string Name { get; set; } } /// <inheritdoc /> /// <summary> /// API для питомцев /// </summary> [Route("api/pets")] public class PetsApiController : Controller { private readonly SettingsService _settingsSvc; // БД космос private const string DbName = "pets"; // Коллекция private const string ColName = "checks"; public PetsApiController(SettingsService settingsSvc) { _settingsSvc = settingsSvc; } /// <summary> /// Загрузка изображения питомца /// </summary> /// <param name="petRequest"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> UploadPetImageAsync([FromBody]PetUploadRequest petRequest) { // Проверка на плохой запрос if (string.IsNullOrEmpty(petRequest?.Base64)) { return BadRequest(); } var tokens = petRequest.Base64.Split(','); //var ctype = tokens[0].Replace("data:", ""); var base64 = tokens[1]; // Получаем байты из base64 var content = Convert.FromBase64String(base64); // Загрузка байт в хранилище var blobUri = await UploadPetToStorageAsync(content); // Затем создаём документ в CosmosDb, чтобы уведомить нашу функцию var identifier = await UploadDocumentAsync(blobUri, petRequest.Name ?? "Bars"); return Ok(identifier); } /// <summary> /// Загрузка документа /// </summary> /// <param name="uri">URI BLOB-хранилища</param> /// <param name="petName">Имя питомца</param> private async Task<Guid> UploadDocumentAsync(Uri uri, string petName) { // Конечная точка cosmosDb var endpoint = new Uri(_settingsSvc.LocalSettings.PetsConfig.CosmosUri); // Ключ var auth = _settingsSvc.LocalSettings.PetsConfig.CosmosKey; // Выполняем вход var client = new DocumentClient(endpoint, auth); // Новый идентификатор var identifier = Guid.NewGuid(); // Создаём БД await client.CreateDatabaseIfNotExistsAsync(new Database { Id = DbName }); // Создаём коллекцию await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DbName), new DocumentCollection { Id = ColName }); // Создаём документ await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DbName, ColName), new PetDocument { Id = identifier, IsApproved = null, PetName = petName, MediaUrl = uri.ToString(), Created = DateTime.Now }); return identifier; } /// <summary> /// Загрузка питомца в хранилище /// </summary> private async Task<Uri> UploadPetToStorageAsync(byte[] content) { // Хранилище var storageName = _settingsSvc.LocalSettings.PetsConfig.BlobName; // Ключ var auth = _settingsSvc.LocalSettings.PetsConfig.BlobKey; // Загрузчик var uploader = new PhotoUploader(storageName, auth); // Загрузка var blob = await uploader.UploadPetPhotoAsync(content); return blob.Uri; } /// <summary> /// Проверяет состояние загрузки /// </summary> /// <param name="identifier">идентификатор документа</param> [HttpGet] public IActionResult GetUploadState(Guid identifier) { // Конечная точка cosmosDb var endpoint = new Uri(_settingsSvc.LocalSettings.PetsConfig.CosmosUri); // Ключ var auth = _settingsSvc.LocalSettings.PetsConfig.CosmosKey; // Выполняем вход var client = new DocumentClient(endpoint, auth); // URI коллекции var collectionUri = UriFactory.CreateDocumentCollectionUri(DbName, ColName); // Выполняем запрос к коллекции var query = client.CreateDocumentQuery<PetDocument>(collectionUri, new FeedOptions { MaxItemCount = 1 }); // Фильтруем var docs = query.Where(x => x.Id == identifier) .Where(x => x.IsApproved.HasValue) .ToList(); // Получаем документ var doc = docs.FirstOrDefault(); return Ok(new { // Одобрено ли Approved = doc?.IsApproved ?? false, // Сообщение Message = doc?.Message ?? "" }); } // GetUploadState } } <file_sep>namespace SmartHotel220.Web.Models.Settings { /// <summary> /// Серверные настройки (хранятся на сервере) /// </summary> public class ServerSettings { /// <summary> /// В продакшине или нет /// </summary> public bool Production { get; set; } /// <summary> /// Ссылки к API /// </summary> public Urls Urls { get; set; } /// <summary> /// Токены (например к картам Google или Bing) /// </summary> public Tokens Tokens { get; set; } /// <summary> /// Azure Active Directory B2C /// </summary> public B2c B2c { get; set; } } } <file_sep>namespace SmartHotel220.Web.Models.Settings { /// <summary> /// Azure Active Directory B2C /// </summary> public class B2c { public string Tenant { get; set; } public string Client { get; set; } public string Policy { get; set; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using SmartHotel220.Web.Services; namespace SmartHotel220.Web.Controllers { /// <inheritdoc /> /// <summary> /// Контроллирует API рекомендаций /// </summary> [Route("api/testimonials")] public class TestimonialsApiController : Controller { private readonly ICustomerTestimonialService _testimonialService; public TestimonialsApiController(ICustomerTestimonialService testimonialService) { _testimonialService = testimonialService; } [HttpGet] public IActionResult Index() { var testimonial = _testimonialService.GetTestimonial(); return Json(testimonial); } } } <file_sep>namespace SmartHotel220.Web.Models.Settings { /// <summary> /// Локальные настройки /// </summary> public class LocalSettings { public LocalSettings() { PetsConfig = new PetsConfig(); } /// <summary> /// В продакшине или нет /// </summary> public bool Production { get; set; } /// <summary> /// URL к файлу JSON с настройками. Этот конфиг может быть где угодно /// </summary> public string SettingsUrl { get; set; } /// <summary> /// Конфиг для работы с питомцами /// </summary> public PetsConfig PetsConfig { get; set; } } } <file_sep>import { Reducer } from 'redux'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { addTask } from 'domain-task'; // Путь к API питомцев const api = `/api/Pets`; // Статусы обработки export enum Status { None, Ok, Bad } // Инфо питомца export class PetInfo { public base64: string; } // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Состояние питомцев export interface IPetsState { isUploading: boolean; isThinking: boolean; id: string | null; image: string | null; status: PetAcceptedResponse; } // Начальное состояние const initialState: IPetsState = { isUploading: false, isThinking: false, id: null, image: null, status: {approved: false, message: ''} } // Класс описывающий успешный ответ class PetAcceptedResponse { public approved: boolean | null; public message: string; } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Инициализация interface INitAction { type: 'INIT_ACTION' } // Запрос загрузки питомца interface IRequestPetUploadAction { type: 'REQUEST_PET_UPLOAD_ACTION', image: string } // Получение загрузки питомца interface IReceivePetUploadAction { type: 'RECEIVE_PET_UPLOAD_ACTION', id: string } // Начало получения статуса interface IStartPoolingAction { type: 'START_POOLING_ACTION' } // Конец получения статуса interface IEndPoolingAction { type: 'END_POOLING_ACTION', status: PetAcceptedResponse } // Известные действия type KnownAction = INitAction | IRequestPetUploadAction | IReceivePetUploadAction | IStartPoolingAction | IEndPoolingAction; // ----------------------------------------------------------------------------------------------------------------- // FUNCTIONS - Функции для повторного использования в этом коде function postImage(pet: PetInfo): Promise<string> { // Грузим питомца в хранилище let fetchTask = fetch(api, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(pet) }).then(response => response.json() as Promise<string>); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); return fetchTask; } // Максимум попыток const maximumAttempts = 100; // Время ожидания const differenceTime = 400; // Начальное время, время старта let startTime: number; // Получает ли информацию let isGettingInfo: boolean; // Попыток let attempts: number; // Фрейм let frame: any; // Рекурсивно получаем результат загрузки function recursiveGet(id: string, resolve: any) { // Текущее время let now = Date.now(); // Если инфо не получено if (!isGettingInfo && (now - startTime > differenceTime)) { // Получаем isGettingInfo = true; // Делаем запрос let fetchTask = fetch(api + `?identifier=${id}`) .then(response => response.json() as Promise<PetAcceptedResponse>) .then(status => { // Инфо не получаем isGettingInfo = false; // Если сообщение НЕ пустое if (status.message !== '') { // Отменяем анимацию cancelAnimationFrame(frame); // Решаем задачу resolve(status); // иначе повторная попытка } else { // Попытка+1 attempts++; if (attempts >= maximumAttempts) { // Отменяем анимацию cancelAnimationFrame(frame); // Решено со статусом status resolve(status); } } // Сохраняем текущее время, как начало операции startTime = now; }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); } // Запрос на фрейм анимацию с вызовом текущей функции (рекурсия) frame = requestAnimationFrame(() => recursiveGet(id, resolve)); } // Получить статус (асинхронно) function getStatus(id: string): Promise<PetAcceptedResponse> { // Начальное время startTime = Date.now(); // Инфо не получаем isGettingInfo = false; // Сбрасываем попытки attempts = 0; // Возвращаем Promise с запросом на анимацию во фрейме и рекурсивной функцией // получения результата return new Promise(resolve => { frame = requestAnimationFrame(() => recursiveGet(id, resolve)); }); } // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Инициализация init: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'INIT_ACTION'}); }, // Загрузить питомца uploadPet: (pet: PetInfo): AppThunkAction<KnownAction> => (dispatch, getState) => { postImage(pet) .then(id => { dispatch({ type: 'RECEIVE_PET_UPLOAD_ACTION', id: id }); dispatch({ type: 'START_POOLING_ACTION' }); // Теперь начнем получать статус getStatus(id).then(status => { dispatch({ type: 'END_POOLING_ACTION', status: status }); }); }); dispatch({ type: 'REQUEST_PET_UPLOAD_ACTION', image: pet.base64 }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IPetsState> = (state: IPetsState, action: KnownAction) => { switch (action.type) { case 'INIT_ACTION': return { ...state, isUploading: false, isThinking: false, image: null, status: {approved: null, message: ''}}; case 'REQUEST_PET_UPLOAD_ACTION': return { ...state, isUploading: true, isThinking: false, image: action.image, status: { approved: null, message: '' } }; case 'RECEIVE_PET_UPLOAD_ACTION': return { ...state, isUploading: false, isThinking: false, id: action.id }; case 'START_POOLING_ACTION': return { ...state, isUploading: false, isThinking: true }; case 'END_POOLING_ACTION': return { ...state, isUploading: false, isThinking: false, image: null, status: action.status }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using SmartHotel220.Web.Models.Settings; using SmartHotel220.Web.Services; namespace SmartHotel220.Web.Controllers { /// <inheritdoc /> /// <summary> /// Одна единственная главная страница /// </summary> public class HomeController : Controller { private readonly ServerSettings _globalSettings; public HomeController(SettingsService settingsService) { _globalSettings = settingsService.GlobalSettings; } // Передаём глобальные настройки полученные от сервера при запуске public IActionResult Index() { return View(_globalSettings); } public IActionResult Error() { ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; return View(); } } }<file_sep>using Microsoft.Extensions.Options; using SmartHotel220.Web.Models.Settings; namespace SmartHotel220.Web.Services { /// <inheritdoc /> /// <summary> /// Фейковая позитивная рекомендация якобы из твиттера /// </summary> public class PositiveTweetService : ICustomerTestimonialService { private IOptions<LocalSettings> _localSettings; public PositiveTweetService(IOptions<LocalSettings> localSettings) { _localSettings = localSettings; } public CustomerTestimonial GetTestimonial() { var model = new CustomerTestimonial { CustomerName = "<NAME>", Text = "Этот отель является супер-высокотехнологичным! Рекомендую его всем!" }; return model; } } } <file_sep>import { Reducer } from 'redux'; import * as moment from 'moment'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { settings } from '../Settings'; import { fetch, addTask } from 'domain-task'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Опции export enum Option { Where, When, Guests, People } // Вкладки export enum Tab { Smart, Conference } // Гости export enum Guest { Adults, Kids, Babies } // Описывает ввод значения по конкретному типу interface INput<T> { value: T; list: T[]; } // Город export class City { constructor( public id?: number, public name?: string, public country?: string) {} } // Гости export class Guests { constructor( public adults: number, public kids: number, public baby: number, public rooms: number, public work?: boolean, public pet?: boolean) { } } // Люди export class People { constructor( public total: number) { } } // Даты export class Dates { constructor( public startDate?: moment.Moment, public endDate?: moment.Moment, public isStartDateSelected = false, public isEndDateSelected = false ) { } // Начальная дата полностью public get startFull(): string { return this.startDate ? `${this.startDate.format('DD MMM')}` : ''; } // Конечная дата полностью public get endFull(): string { return this.endDate ? `${this.endDate.format('DD MMM')}` : ''; } // Конечная дата полностью в комплексе public get endFullComplex(): string { return this.endDate ? `${this.endDate.format('dd, MMM DD, YYYY')}` : ''; } } // Состояние поиска export interface ISearchState { isLoading: boolean; minLength: number; where: INput<City>; when: INput<Dates>; guests: INput<Guests>; people: INput<People>; } // Начальное состояние const initialState: ISearchState = { minLength: 3, isLoading: false, where: { value: new City(), list: [] }, when: { value: new Dates(), list: [] }, guests: { value: new Guests(1, 0, 0, 1, false), list: [] }, people: { value: new People(1), list: [] } } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Инициализация interface INitAction { type: 'INIT_ACTION' } // Запрос "где" interface IRequestWhereAction { type: 'REQUEST_WHERE_ACTION' } // Получение "где" interface IReceiveWhereAction { type: 'RECEIVE_WHERE_ACTION', list: City[] } // Выбор "где" interface ISelectWhereAction { type: 'SELECT_WHERE_ACTION', city: City } // Сброс "где" interface IResetWhereAction { type: 'RESET_WHERE_ACTION' } // Брос "когда" interface IResetWhenAction { type: 'RESET_WHEN_ACTION' } // Сброс гостей interface IResetGuestsAction { type: 'RESET_GUESTS_ACTION' } // Сброс людей interface IResetPeopleAction { type: 'RESET_PEOPLE_ACTION' } // Выбор "когда" interface ISelectWhenAction { type: 'SELECT_WHEN_ACTION', next: Option, start?: moment.Moment, end?: moment.Moment } // Выбор гостей interface ISelectGuestsAction { type: 'SELECT_GUESTS_ACTION', adults: number, kids: number, baby: number, rooms: number, work: boolean, pet: boolean } // Выбор людей interface ISelectPepopleAction { type: 'SELECT_PEOPLE_ACTION', total: number } // Известные действия type KnownAction = INitAction | IRequestWhereAction | IReceiveWhereAction | ISelectWhereAction | IResetWhereAction | ISelectWhenAction | ISelectGuestsAction | ISelectPepopleAction | IResetWhenAction | IResetGuestsAction | IResetPeopleAction; // ----------------------------------------------------------------------------------------------------------------- // FUNCTIONS - Функции для повторного использования в этом коде // Получить полностью город export function getFullCity(city: City) { return city.name ? `${city.name}, ${city.country}` : ''; } // Получить полностью номера export function getFullRooms(guests: Guests) { return guests.rooms > 1 ? `${guests.rooms} Номеров` : `${guests.rooms} Номер`; } // Получить полностью гостей export function getFullGuests(guests: Guests) { return (guests.adults + guests.kids + guests.baby) > 1 ? `${guests.adults + guests.kids + guests.baby} Гостей` : `${guests.adults + guests.kids + guests.baby} Гость`; } // Получить номера и гостей export function getFullRoomsGuests(guests: Guests) { return `${getFullRooms(guests)}, ${getFullGuests(guests)}`; } // Получить полностью людей export function getFullPeople(people: People) { return people.total ? `${people.total} Люди` : ''; } // Получить короткую дату export function getShortDate(date?: moment.Moment) { date = moment(date).locale('ru'); return date ? `${date.format('DD MMM')}` : ''; } // Получить короткие даты export function getShortDates(startDate?: moment.Moment, endDate?: moment.Moment) { startDate = moment(startDate).locale('ru'); endDate = moment(endDate).locale('ru'); return `${getShortDate(startDate)} - ${startDate === endDate ? '' : getShortDate(endDate)}`; } // Получить длинную дату export function getLongDate(date: moment.Moment) { date = moment(date).locale('en'); return date; } // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Инициализация init: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'INIT_ACTION'}); }, // Поиск "где" searchWhere: (value: string): AppThunkAction<KnownAction> => (dispatch, getState) => { // Получаем состояние поиска const state = getState().search; // Проверка на длину if (value.length < state.minLength) { dispatch({ type: 'RECEIVE_WHERE_ACTION', list: [] }); return; } dispatch({ type: 'RECEIVE_WHERE_ACTION', list: [] }); // Выполняем поиск let fetchTask = fetch(`${settings.urls.hotels}Cities?name=${value}`) .then(response => response.json() as Promise<any>) .then(data => { data = data.map((item: any) => { return new City(item.id, item.name, item.country); }); dispatch({ type: 'RECEIVE_WHERE_ACTION', list: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_WHERE_ACTION' }); }, // Выбор "где" selectWhere: (city: City): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'SELECT_WHERE_ACTION', city: city }); }, // Сброс "где" resetWhere: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'RESET_WHERE_ACTION'}); }, // Сброс "когда" resetWhen: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'RESET_WHEN_ACTION' }); }, // Сброс гостей resetGuests: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'RESET_GUESTS_ACTION' }); }, // Сброс людей resetPeople: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'RESET_PEOPLE_ACTION' }); }, // Выбор начальной даты selectWhenStart: (date: moment.Moment): AppThunkAction<KnownAction> => (dispatch, getState) => { const end = getState().search.when.value.endDate; dispatch({ type: 'SELECT_WHEN_ACTION', next: Option.When, start: date, end: date}); }, // Выбор конечной даты selectWhenEnd: (date: moment.Moment): AppThunkAction<KnownAction> => (dispatch, getState) => { const state = getState().search; const start = state.when.value.startDate; dispatch({ type: 'SELECT_WHEN_ACTION', next: Tab.Smart === Tab.Smart ? Option.Guests : Option.People, start: (start || moment()), end: date }); }, // Обновление гостей, взрослые updateGuestsAdults: (value: number): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: value, kids: guests.kids || 0, baby: guests.baby || 0, rooms: guests.rooms || 0, work: guests.work || false , pet: guests.pet || false}); }, // Обновление гостей, дети updateGuestsKids: (value: number): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: guests.adults || 0, kids: value, baby: guests.baby || 0, rooms: guests.rooms || 0, work: guests.work || false, pet: guests.pet || false }); }, // Обновление гостей, маленькие updateGuestsBaby: (value: number): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: guests.adults || 0, kids: guests.kids || 0, baby: value, rooms: guests.rooms || 0, work: guests.work || false, pet: guests.pet || false}); }, // Обновление гостей, номера updateGuestsRooms: (value: number): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: guests.adults || 0, kids: guests.kids || 0, baby: guests.baby || 0, rooms: value, work: guests.work || false, pet: guests.pet || false }); }, // Обновление гостей, работа updateGuestsWork: (value: boolean): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: guests.adults || 0, kids: guests.kids || 0, baby: guests.baby || 0, rooms: guests.rooms || 0, work: value, pet: guests.pet || false }); }, // Обновление гостей, питомец updateGuestsPet: (value: boolean): AppThunkAction<KnownAction> => (dispatch, getState) => { const guests = getState().search.guests.value; dispatch({ type: 'SELECT_GUESTS_ACTION', adults: guests.adults || 0, kids: guests.kids || 0, baby: guests.baby || 0, rooms: guests.rooms || 0, work: guests.work || false, pet: value}); }, // Обновление людей updatePeople: (value: number): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'SELECT_PEOPLE_ACTION', total: value || 0 }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<ISearchState> = (state: ISearchState, action: KnownAction) => { switch (action.type) { case 'INIT_ACTION': return { ...state }; case 'REQUEST_WHERE_ACTION': return { ...state, isLoading: true }; case 'RECEIVE_WHERE_ACTION': return { ...state, isLoading: false, where: { ...state.where, list: action.list } }; case 'SELECT_WHERE_ACTION': return { ...state, where: { ...state.where, value: action.city } }; case 'RESET_WHERE_ACTION': return { ...state, where: { ...state.where, value: new City(), list: [] } }; case 'SELECT_WHEN_ACTION': return { ...state, when: { ...state.when, value: new Dates(action.start, action.end) } }; case 'RESET_WHEN_ACTION': return { ...state, when: { ...state.when, value: new Dates()} }; case 'SELECT_GUESTS_ACTION': return { ...state, guests: { ...state.guests, value: new Guests(action.adults, action.kids, action.baby, action.rooms, action.work, action.pet) } }; case 'RESET_GUESTS_ACTION': return { ...state, guests: { ...state.guests, value: new Guests(1, 0, 0, 1, false) } }; case 'RESET_PEOPLE_ACTION': return { ...state, people: { ...state.people, value: new People(1) } }; case 'SELECT_PEOPLE_ACTION': return { ...state, people: { ...state.people, value: new People(action.total) } }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>import * as NavMenu from './NavMenu'; import * as Rooms from './Rooms'; import * as User from './User'; import * as Search from './Search'; import * as ConferenceRoomsFeatures from './ConferenceRoomsFeatures'; import * as RoomDetail from './RoomDetail'; import * as ModalDialog from './ModalDialog'; import * as Home from './Home'; import * as Pets from './Pets'; // Описывает объект состояния верхнего уровня export interface IApplicationState { nav: NavMenu.INavMenuState; rooms: Rooms.IRoomsState; user: User.IUserState; conferenceRoomsFeatures: ConferenceRoomsFeatures.IFeaturesState; search: Search.ISearchState; roomDetail: RoomDetail.IRoomDetailState; modalDialog: ModalDialog.IModalDialogState; home: Home.IHomeState; pets: Pets.IPetsState; } // Всякий раз, когда отправляется действие, Redux обновляет каждое свойство состояния приложения верхнего уровня, используя // reducer с совпадающим именем. Важно, чтобы имена соответствовали точно, и что reducer // действует в соответствующем типе свойства ApplicationState. export const reducers = { nav: NavMenu.reducer, rooms: Rooms.reducer, user: User.reducer, conferenceRoomsFeatures: ConferenceRoomsFeatures.reducer, search: Search.reducer, roomDetail: RoomDetail.reducer, modalDialog: ModalDialog.reducer, home: Home.reducer, pets: Pets.reducer } // Этот тип можно использовать, как подсказку для создателей действий, чтобы его параметры "dispatch" и "getState" // правильно печатались в соответствии с хранилищем export interface IAppThunkAction<TAction> { (dispatch: (action: TAction) => void, getState: () => IApplicationState): void; }<file_sep>import { fetch, addTask } from 'domain-task'; import { Reducer } from 'redux'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; import { settings } from '../Settings'; import * as moment from 'moment'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Описывает сервис в номере export interface IService { id: number; name: string; } // Для описания словаря interface IServicesDicionary { key: number; } // Бронь export class Booking { constructor(public hotelId: number, public userId: string, public from: string, public to: string, public adults: number | 0, public kids: number | 0, public babies: number | 0, public roomType: number | 0, public price: number | 0) { } } // Словарь с сервисами export const servicesDictionary: { [index: number]: string } = { 1: 'sh-wifi', 2: 'sh-parking', 3: 'sh-tv', 4: 'sh-air-conditioning', 5: 'sh-dryer', 6: 'sh-indoor-fireplace', 7: 'sh-table', 8: 'sh-breakfast', 9: 'sh-kid-friendly', 10: 'sh-airport-shutle', 11: 'sh-pool', 12: 'sh-fitness-centre', 13: 'sh-gym', 14: 'sh-hot-tub', 15: 'sh-lunch', 16: 'sh-wheelchair-accessible', 17: 'sh-elevator' } // Сводка всего по номеру export interface IRoomSummary { roomId: number; roomName: string; roomPrice: number; discountApplied: number; originalRoomPrice: number; localRoomPrice: number; localOrginalRoomPrice: number; badgeSymbol: string; } // Подробности номера export interface IRoomDetail { defaultPicture: string; pictures: string[]; description: string; name: string; rating: number; city: string; street: string; latitude: number; longitude: number; checkInTime: string; checkOutTime: string; pricePerNight: number; phone: string; services: IService[]; rooms: IRoomSummary[]; } // Описывает отзыв export interface IReview { id: number; userId: string; submitted: number; description: string; hotelId: number; formattedDate: string; userName: string; } // Вкладки export enum Tabs { Hotel, Reviews } // Опции export enum Option { Hotel, Reviews } // Состояние подробностей номера export interface IRoomDetailState { room: IRoomDetail; reviews: IReview[]; isLoading: boolean; isBooking: boolean; booked: boolean; showConfirmationModal: boolean; } // Начальное состояние const initialState: IRoomDetailState = { room: { defaultPicture: '', pictures: [''], description: '', name: '', rating: 1, city: '', street: '', latitude: 0, longitude: 0, checkInTime: '', checkOutTime: '', pricePerNight: 0, phone: '', services: [], rooms: [{ badgeSymbol: '', discountApplied: 0, localOrginalRoomPrice: 0, localRoomPrice: 0, originalRoomPrice: 0, roomId: 0, roomName: '', roomPrice: 0 }] }, reviews: [], isLoading: false, isBooking: false, booked: false, showConfirmationModal: false } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Запрос номера interface IRequestRoomAction { type: 'REQUEST_ROOM_ACTION' } // Получение номера interface IReceiveRoomAction { type: 'RECEIVE_ROOM_ACTION', room: IRoomDetail } // Инициализация interface INitRoomDetailAction { type: 'INIT_ROOM_DETAIL_ACTION' } // Бронирование в целом interface IBookRoomAction { type: 'BOOK_ROOM_ACTION', booked: boolean, showConfirmationModal: boolean } // Бронирование номера interface IBookingRoomAction { type: 'BOOKING_ROOM_ACTION' } // Запрос отзывов interface IRequestReviewsAction { type: 'REQUEST_REVIEWS_ACTION' } // Получение отзывов interface IReceiveReviewsAction { type: 'RECEIVE_REVIEWS_ACTION', reviews: IReview[] } // Закрыть диалог interface IDismissModalAction { type: 'DISMISS_MODAL_ACTION' } // Известные действия type KnownAction = IRequestRoomAction | IReceiveRoomAction | INitRoomDetailAction | IBookRoomAction | IBookingRoomAction | IRequestReviewsAction | IReceiveReviewsAction | IDismissModalAction; // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Инициализация init: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'INIT_ROOM_DETAIL_ACTION' }); }, // Запрос номера requestRoom: (id: number, user: any): AppThunkAction<KnownAction> => (dispatch, getState) => { let url = `${settings.urls.hotels}Hotels/${id}`; // Если пользователь вошёл if (user.id != '' && user.id != null) { url = `${settings.urls.hotels}Hotels/${id}?user=${user.id}`; } // Получаем номер let fetchTask = fetch(url) .then(response => response.json() as Promise<IRoomDetail>) .then(data => { dispatch({ type: 'RECEIVE_ROOM_ACTION', room: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_ROOM_ACTION' }); }, // Запрос отзывов requestReviews: (id: number): AppThunkAction<KnownAction> => (dispatch, getState) => { // Получаем отзывы отеля let fetchTask = fetch(`${settings.urls.reviews}/reviews/hotel/${id}`) .then(response => response.json() as Promise<IReview[]>) .then(data => { dispatch({ type: 'RECEIVE_REVIEWS_ACTION', reviews: data }); }); // Нужно убедиться, что пререндеринг на стороне сервера ожидает завершения этого addTask(fetchTask); dispatch({ type: 'REQUEST_REVIEWS_ACTION' }); }, // Бронь book: (booking: Booking, user: any): AppThunkAction<KnownAction> => (dispatch, getState) => { // Заголовки let headers = new Headers(); // Говорим, что это будет json headers.append('Content-Type', 'application/json'); // И Bearer токен авторизации const auth = `Bearer ${user.token}`; // Выполняем запрос на бронь let fetchTask = fetch(`${settings.urls.bookings}Bookings`, { method: 'POST', headers: { 'Authorization': auth, 'Content-Type': 'application/json' }, body: JSON.stringify(booking) }).then(response => { dispatch({ type: 'BOOK_ROOM_ACTION', booked: true, showConfirmationModal: true }); console.log(response); }, (e) => { dispatch({ type: 'BOOK_ROOM_ACTION', booked: false, showConfirmationModal: false }); }); dispatch({ type: 'BOOKING_ROOM_ACTION' }); }, // Закрыть модальный диалог dismissModal: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'DISMISS_MODAL_ACTION' }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IRoomDetailState> = (state: IRoomDetailState, action: KnownAction) => { switch (action.type) { case 'INIT_ROOM_DETAIL_ACTION': return { ...state, isBooking: false, booked: false, showConfirmationModal: false }; case 'REQUEST_ROOM_ACTION': return { ...state, isLoading: true }; case 'RECEIVE_ROOM_ACTION': return { ...state, isLoading: false, room: action.room }; case 'BOOKING_ROOM_ACTION': return { ...state, isBooking: true, booked: false }; case 'BOOK_ROOM_ACTION': return { ...state, isBooking: false, booked: action.booked, showConfirmationModal: action.showConfirmationModal }; case 'REQUEST_REVIEWS_ACTION': return { ...state, isLoading: true }; case 'RECEIVE_REVIEWS_ACTION': return { ...state, isLoading: false, reviews: action.reviews }; case 'DISMISS_MODAL_ACTION': return { ...state, showConfirmationModal: false }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>// Настройки на TS class Settings { public production = false; public urls = { hotels: '', bookings: '', suggestions: '', tasks: '', images_Base: '', reviews: '' } public tokens = { bingmaps: '' } public b2c = { tenant: '', client: '', policy: '' } } declare global { interface Window { settings: Settings; } } //export var encoder = new TextEncoder('iso-8859-1'); //export var decoder = new TextDecoder('utf-8'); let clientSettings = new Settings(); // Получаем настройки из window.settings if (window.settings) { clientSettings = { ...clientSettings, ...window.settings } } // Экспортируем для дальнейшей работы в других файлах export let settings = clientSettings;<file_sep>using System; namespace SmartHotel220.Web.Services { /// <inheritdoc /> /// <summary> /// Нулевая рекомендация. Задаётся по умолчанию в стартапе /// </summary> public class NullCustomerTestimonialService : ICustomerTestimonialService { public CustomerTestimonial GetTestimonial() { throw new CustomerTestimonialServiceNotConfiguredException(); } } /// <inheritdoc /> /// <summary> /// Исключение на тот случай, если возникли проблемы с конфигурацией сервиса рекомендаций /// </summary> public class CustomerTestimonialServiceNotConfiguredException : ApplicationException { public CustomerTestimonialServiceNotConfiguredException() : base("Нет настройки службы отзывов клиентов") { } } } <file_sep>[license-image]: https://img.shields.io/npm/l/normalize.css.svg?style=flat [license-url]: LICENSE # SmartHotel220.Web [![license][license-image]][license-url] SmartHotel220 – fictional hotel company, which demonstrates the future of travel and offers to book worldwide special smart rooms for ordinary guests, as well as meeting rooms for business travelers. # SmartHotel220 Other Parts - **[SmartHotel220.Clients](https://github.com/AlexeyBuryanov/SmartHotel220.Clients)** - **[SmartHotel220.Backend](https://github.com/AlexeyBuryanov/SmartHotel220.Backend)** # Basic Functionality - Register & Login using Azure Active Directory B2C; - Adaptive interface; - Searching rooms in hotels by country and dates "from" and "to"; - Filtering hotel rooms found by cost or/and services; - Possibility to book a "smart" room for one or more guests include pets; - Possibility to book a "smart" conference hall for a business meetings; - Possibility to analyze your pet's photo using Azure Cognitive Service (Vision API) and find out whether the guest can take it with him to the room. ### Using ASP.NET Core MVC 2.0, React+Redux, NPM, TypeScript, SASS, Webpack, SVG, Docker. <file_sep>namespace SmartHotel220.Web.Models.Settings { /// <summary> /// Токены (например к картам Google или Bing) /// </summary> public class Tokens { public string Bingmaps { get; set; } } } <file_sep>import { Reducer } from 'redux'; import { IAppThunkAction as AppThunkAction } from 'ClientApp/store'; // ----------------------------------------------------------------------------------------------------------------- // STATE - определяет тип данных, хранящийся в хранилище Redux // Описывает внутреннее состояние компонента // Описывает состояние модального диалога export interface IModalDialogState { isModalOpen: boolean; onRef?: any; } // Начальное состояние const initialState: IModalDialogState = { isModalOpen: true } // ----------------------------------------------------------------------------------------------------------------- // ACTIONS - События/действия. Некоторый набор информации, который исходит от приложения к хранилищу // и который указывает, что именно нужно сделать. Для передачи этой информации у хранилища вызывается метод dispatch() // Инициализация interface INitAction { type: 'INIT_ACTION' } // Открытие диалога interface IOpenModalAction { type: 'OPEN_MODAL_ACTION' } // Закрытие диалога interface ICloseModalAction { type: 'CLOSE_MODAL_ACTION' } // Известные действия type KnownAction = INitAction | IOpenModalAction | ICloseModalAction; // ----------------------------------------------------------------------------------------------------------------- // ACTION CREATORS - Создатели действий. Функции, которые создают действия export const actionCreators = { // Инициализация init: (): AppThunkAction<KnownAction> => (dispatch, getState) => { let state = getState().modalDialog; dispatch({ type: 'INIT_ACTION' }); }, // Открыть open: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'OPEN_MODAL_ACTION' }); }, // Закрыть close: (): AppThunkAction<KnownAction> => (dispatch, getState) => { dispatch({ type: 'CLOSE_MODAL_ACTION' }); } } // ----------------------------------------------------------------------------------------------------------------- // REDUCER - функция (или несколько функций), которая получает действие и в соответствии с этим действием изменяет состояние хранилища export const reducer: Reducer<IModalDialogState> = (state: IModalDialogState, action: KnownAction) => { switch (action.type) { case 'INIT_ACTION': return { ...state, isModalOpen: false }; case 'OPEN_MODAL_ACTION': return { ...state, isModalOpen: true }; case 'CLOSE_MODAL_ACTION': return { ...state, isModalOpen: false }; default: const exhaustiveCheck: never = action; } // Для непризнанных действий (или в случаях, когда действия в кейсах не действуют), необходимо вернуть существующее состояние // (или начальное состояние по умолчанию) return state || { ...initialState }; }<file_sep>FROM microsoft/aspnetcore:2.0 AS base WORKDIR /app EXPOSE 80 FROM base as withnode RUN apt-get update && apt-get install -my wget gnupg RUN apt-get -qq update && apt-get -qqy --no-install-recommends install \ git \ unzip RUN curl -sL https://deb.nodesource.com/setup_6.x | bash - RUN apt-get install -y nodejs FROM microsoft/aspnetcore-build:2.0 AS build WORKDIR /src COPY SmartHotel220.Web/SmartHotel220.Web.csproj SmartHotel220.Web/ RUN dotnet restore SmartHotel220.Web/SmartHotel220.Web.csproj COPY . . RUN dotnet build SmartHotel220.Web/SmartHotel220.Web.csproj -c Release -o /webapp FROM build AS publish WORKDIR /src/SmartHotel220.Web RUN npm rebuild node-sass RUN dotnet publish SmartHotel220.Web.csproj -c Release -o /webapp FROM withnode AS final WORKDIR /app COPY --from=publish /webapp . ENTRYPOINT ["dotnet", "SmartHotel220.Web.dll"] <file_sep>using System; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace SmartHotel220.Web.Services { /// <summary> /// Загрузчик фото/картинок в BLOB хранилище Azure /// </summary> public class PhotoUploader { /// <summary> /// Полномочия хранилища /// </summary> private readonly StorageCredentials _credentials; /// <summary> /// Аккаут хранилища /// </summary> private readonly CloudStorageAccount _storageAccount; /// <summary> /// Клиент BLOB-объектов /// </summary> private readonly CloudBlobClient _blobClient; public PhotoUploader(string name, string constr) { _credentials = new StorageCredentials(name, constr); _storageAccount = new CloudStorageAccount(_credentials, true); _blobClient = _storageAccount.CreateCloudBlobClient(); } /// <summary> /// Загрузка фото питомца /// </summary> /// <param name="content">Контент в байтах т.к. это BLOB</param> public async Task<CloudBlockBlob> UploadPetPhotoAsync(byte[] content) { var petsContainer = _blobClient.GetContainerReference("pets"); await petsContainer.CreateIfNotExistsAsync(); var newBlob = petsContainer.GetBlockBlobReference(Guid.NewGuid().ToString()); await newBlob.UploadFromByteArrayAsync(content, 0, content.Length); return newBlob; } } }
d1b3f58d62fb1c34be700e11eea05961492ae55d
[ "Markdown", "C#", "TypeScript", "Dockerfile" ]
29
C#
AlexeyBuryanov/SmartHotel220.Web
0970a0548baa1507617a00c4ae96ca6dbda0c48e
2df71cb8979115295e46eb50df678849d2fcbc55
refs/heads/master
<repo_name>albertnovais/Repositorio<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/AdocaoController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Rosnando_semG.Controllers { public class AdocaoController : Controller { // GET: Adocao public ActionResult Index() { return View(); } } }<file_sep>/Rosnando_semG/Rosnando_semG/Rosnando_semG/Models/usu.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Rosnando_semG.Models; using System.ComponentModel.DataAnnotations; namespace Rosnando_semG.Models { public class Usu { [Required (ErrorMessage ="Campo Obrigatório")] public string email { get; set; } } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/PublicoController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Rosnando_semG.Models; namespace Rosnando_semG.Controllers { public class PublicoController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); // GET: Publico public ActionResult Index(int? a, int? b, int? tipo_dica_id) { var topp = bd.Usuario.OrderByDescending(x => x.usuario_pontos).Take(5).ToList(); var topd = bd.Usuario.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var topa = bd.TipoAnimal.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var dicas = bd.Dica.Where(x => x.dica_status == true).OrderByDescending(x => x.dica_data).Take(5).ToList(); ViewBag.dicas = dicas; ViewBag.topp = topp; ViewBag.topd = topd; ViewBag.topa = topa; ViewBag.a = a; ViewBag.b = b; // a = 1 --> Dica // a = 2 --> SOS if (a == 1) { ViewBag.dic = bd.TipoDica.Where(x => x.primeiro_socorros == false).ToList(); } else { ViewBag.dic = bd.TipoDica.Where(x => x.primeiro_socorros == true).ToList(); } ViewBag.ani = bd.TipoAnimal.ToList(); // b = 0 --> Todos os animais // b = 1 --> Gato // b = 3 --> Cachorro // b = 4 --> Outros // b = 5 --> para todos if (a == 1 && b == 0 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 0 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 1 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 1).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 1 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 1 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 3 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 3).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 3 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 3 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 4 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 5).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 1 && b == 4 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == false && x.dica_status == true && x.tipo_animal_id == 5 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 0 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true).ToList().OrderBy(x => x.dica_data).OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 0 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_dica_id == tipo_dica_id).ToList().OrderBy(x => x.dica_data).OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 1 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 1).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 1 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 1 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 3 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 3).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 3 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 3 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 4 && tipo_dica_id == null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 5).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else if (a == 2 && b == 4 && tipo_dica_id != null) { var mostrar = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true && x.dica_status == true && x.tipo_animal_id == 5 && x.tipo_dica_id == tipo_dica_id).ToList().OrderByDescending(x => x.dica_data); return View(mostrar); } else { var mostrar = bd.Dica.Where(x=> x.dica_status==true).ToList(); return View(mostrar); } } public ActionResult Dica(int dica_id) { var dicas = bd.Dica.Where(x => x.dica_status == true).OrderByDescending(x => x.dica_data).Take(5).ToList(); var topp = bd.Usuario.OrderByDescending(x => x.usuario_pontos).Take(5).ToList(); var topd = bd.Usuario.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var topa = bd.TipoAnimal.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); ViewBag.dicas = dicas; ViewBag.topp = topp; ViewBag.topd = topd; ViewBag.topa = topa; var dica = bd.Dica.FirstOrDefault(x => x.dica_id == dica_id); return View(dica); } } }<file_sep>/README.md #Repositorio To só fazendo uns testes <file_sep>/Rosnando_semG/Rosnando_semG/Rosnando_semG/Controllers/LoginController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using Rosnando_semG.Models; using System.ComponentModel.DataAnnotations; namespace Rosnando_semG.Controllers { public class LoginController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Usuario usuario) { var u = bd.Usuario.FirstOrDefault(x => x.usuario_email == usuario.usuario_email && x.usuario_senha == usuario.usuario_senha); if (u == null) { return RedirectToAction("Index", "Home"); } FormsAuthentication.SetAuthCookie(u.usuario_id.ToString(), true); return RedirectToAction("Index", "Home"); } public ActionResult Registro() { return View(); } [HttpPost] public ActionResult Registro(Usuario usuario) { if (bd.Usuario.FirstOrDefault(x => x.usuario_email == usuario.usuario_email) != null) return RedirectToAction("Index", "Home"); usuario.usuario_pontos = 50; usuario.acesso_id = 2; bd.Usuario.Add(usuario); bd.SaveChanges(); FormsAuthentication.SetAuthCookie(usuario.usuario_id.ToString(), true); return RedirectToAction("Index","Home"); } public ActionResult Logoff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } } }<file_sep>/Rosnando_semG/Rosnando_semG/Rosnando_semG/Models/Detalhe.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Rosnando_semG.Models; namespace Rosnando_semG.Views { public static class Detalhe { public static Usuario GetUsuario() { var nome = HttpContext.Current.User.Identity.Name; DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); var u = bd.Usuario.FirstOrDefault(x => x.usuario_id==Convert.ToInt32(nome)); return u; } } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/AnimalController.cs using Rosnando_semG.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Rosnando_semG.Controllers { public class AnimalController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); // GET: Animal [Authorize] public ActionResult List(int usuario_id) { //var dicas = bd.Dica.Where(x => x.dica_status == true).OrderByDescending(x => x.dica_data).Take(5).ToList(); //var topp = bd.Usuario.OrderByDescending(x => x.usuario_pontos).Take(5).ToList(); //var topd = bd.Usuario.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); //var topa = bd.TipoAnimal.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); //ViewBag.dicas = dicas; //ViewBag.topp = topp; //ViewBag.topd = topd; //ViewBag.topa = topa; var ani = bd.Animais.Where(x => x.usuario_id == usuario_id).ToList(); int a = Convert.ToInt32(HttpContext.User.Identity.Name); string nome = bd.Usuario.FirstOrDefault(x => x.usuario_id == a).usuario_nome; ViewBag.nome = nome; return View(ani); } public ActionResult Create() { // bd.Animais.FirstOrDefault(x =>x.animal_raca_id ); ViewBag.tipoanimal = new SelectList(bd.TipoAnimal, "tipo_animal_id", "tipo_animal_descricao"); // ViewBag.racaanimal = new SelectList(bd.RacaAnimal, "raca_animal_id", "raca_animal_descricao"); return View(); } [HttpPost] public ActionResult Create(Animais animais) { animais.status_animal_id = 1; animais.usuario_id = Convert.ToInt32(HttpContext.User.Identity.Name); bd.Animais.Add(animais); var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == animais.usuario_id); usu.usuario_pontos += 20; bd.Entry(usu).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); return RedirectToAction("List", "Usuario"); } public ActionResult Raca(int tipo_animal_id, int animal_id) { var animal = bd.Animais.FirstOrDefault(x => x.animal_id == animal_id); var racas = bd.RacaAnimal.Where(x => x.tipo_animal_id == tipo_animal_id); ViewBag.racaanimal = new SelectList(racas, "raca_animal_id", "raca_animal_descricao"); return View(animal); } [HttpPost] public ActionResult Raca(Animais animais) { var ani = bd.Animais.FirstOrDefault(x => x.animal_id == animais.animal_id); ani.animal_raca_id = animais.animal_raca_id; bd.Entry(ani).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); return RedirectToAction("Index", "Home"); } //public ActionResult Edit(int animal_id) //{ // var ani = bd.Animais.FirstOrDefault(x => x.animal_id == animal_id); // return View(ani); //} } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/SOSController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Rosnando_semG.Models; namespace Rosnando_semG.Controllers { public class SOSController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); // GET: Dicas [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult List() { var sos = bd.Dica.Where(x => x.TipoDica.primeiro_socorros == true).ToList(); return View(sos); } [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult Create() { ViewBag.tipoanimal = new SelectList(bd.TipoAnimal, "tipo_animal_id", "tipo_animal_descricao"); ViewBag.tipodica = new SelectList(bd.TipoDica.Where(x => x.primeiro_socorros == true), "tipo_dica_id", "descricao"); return View(); } [HttpPost] public ActionResult Create(Dica dica) { dica.usuario_id = Convert.ToInt32(HttpContext.User.Identity.Name); dica.dica_data = DateTime.Now; dica.dica_status = true; bd.Dica.Add(dica); bd.SaveChanges(); return RedirectToAction("List"); } [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult Details(int dica_id) { var sos = bd.Dica.FirstOrDefault(x => x.dica_id == dica_id); return View(sos); } [HttpPost] public ActionResult Details(Dica dica) { return RedirectToAction("List"); } [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult Edit(int dica_id) { ViewBag.tipoanimal = new SelectList(bd.TipoAnimal, "tipo_animal_id", "tipo_animal_descricao"); var dica = bd.Dica.FirstOrDefault(x => x.dica_id == dica_id); return View(dica); } [HttpPost] public ActionResult Edit(Dica dica) { var di = bd.Dica.FirstOrDefault(x => x.dica_id == dica.dica_id); di.dica_descricao = dica.dica_descricao; di.dica_img = dica.dica_img; di.dica_status = dica.dica_status; di.dica_texto = dica.dica_texto; di.dica_titulo = di.dica_titulo; di.dica_data = DateTime.Now; di.usuario_id = Convert.ToInt32(HttpContext.User.Identity.Name); di.tipo_animal_id = dica.tipo_animal_id; bd.Entry(di).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); return RedirectToAction("List"); } } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/MapsController.cs using Rosnando_semG.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Rosnando_semG.Controllers { public class MapsController : Controller { // GET: Maps DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); [Authorize] public ActionResult Map() { var topp = bd.Usuario.OrderByDescending(x => x.usuario_pontos).Take(5).ToList(); var topd = bd.Usuario.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var topa = bd.TipoAnimal.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var dicas = bd.Dica.Where(x => x.dica_status == true).OrderByDescending(x => x.dica_data).Take(5).ToList(); ViewBag.dicas = dicas; ViewBag.topp = topp; ViewBag.topd = topd; ViewBag.topa = topa; return View(); } } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Rosnando_semG.Models; using System.Web.Security; namespace Rosnando_semG.Controllers { public class HomeController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); public ActionResult Index(string message) { ViewBag.tipodica = bd.TipoDica.Where(x=>x.primeiro_socorros==false).ToList(); ViewBag.tiposos = bd.TipoDica.Where(x=>x.primeiro_socorros==true).ToList(); var dicas = bd.Dica.Where(x => x.dica_status == true).OrderByDescending(x => x.dica_data).Take(6).ToList(); var topp = bd.Usuario.OrderByDescending(x => x.usuario_pontos).Take(5).ToList(); var topd = bd.Usuario.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); var topa = bd.TipoAnimal.OrderByDescending(x => x.Animais.Count).Take(5).ToList(); ViewBag.topp = topp; ViewBag.topd = topd; ViewBag.topa = topa; ViewBag.message = message; return View(dicas); } public ActionResult Pontos() { return View(); } } }<file_sep>/Rosnando_semG/Rosnando_semG/Controllers/UsuarioController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Rosnando_semG.Models; namespace Rosnando_semG.Controllers { public class UsuarioController : Controller { DB_A41AF6_rosnandoEntities bd = new DB_A41AF6_rosnandoEntities(); // GET: Usuario public ActionResult usuario(int usuario_id) { var usu = bd.Usuario.FirstOrDefault(x=> x.usuario_id==usuario_id); int a = Convert.ToInt32(HttpContext.User.Identity.Name); string nome = bd.Usuario.FirstOrDefault(x => x.usuario_id == a).usuario_nome; ViewBag.nome = nome; return View(usu); } [Authorize] public ActionResult Edit(int usuario_id) { var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario_id); return View(usu); } [HttpPost] public ActionResult Edit(Usuario usuario) { var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario.usuario_id); bd.Entry(usu).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); return RedirectToAction("List", "Usuario"); } [Authorize] public ActionResult EditSenha(int usuario_id) { int a = Convert.ToInt32(HttpContext.User.Identity.Name); string nome = bd.Usuario.FirstOrDefault(x => x.usuario_id == a).usuario_nome; ViewBag.nome = nome; var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario_id); return View(usu); } [HttpPost] public ActionResult EditSenha(Usuario usuario, string novaSenha) { var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario.usuario_id); if(usuario.usuario_senha == usu.usuario_senha) { usu.usuario_senha = novaSenha; bd.Entry(usu).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); } else { } return RedirectToAction("List", "Usuario"); } //Administrativo [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult List() { var usu = bd.Usuario.ToList(); return View(usu); } [Authorize(Roles = "Administrador, Sub_adm")] public ActionResult EditADM(int usuario_id) { var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario_id); ViewBag.acesso = new SelectList(bd.Acesso, "acesso_id", "acesso_desricao"); return View(usu); } [HttpPost] public ActionResult EditADM(Usuario usuario) { var usu = bd.Usuario.FirstOrDefault(x => x.usuario_id == usuario.usuario_id); usu.acesso_id = usuario.acesso_id; usu.usuario_acesso= Convert.ToInt32(HttpContext.User.Identity.Name); bd.Entry(usu).State = System.Data.Entity.EntityState.Modified; bd.SaveChanges(); return RedirectToAction("List", "Usuario"); } } }
f3bf62f1f95c979f7b78f8a5cee158e8f7ba6218
[ "Markdown", "C#" ]
11
C#
albertnovais/Repositorio
f2e68f062f323e1f32885650bfc02c0ffbadae50
63d5d9753675ef7d30650ec4195e57fd9676c98d
refs/heads/master
<file_sep>/* Project: Lab 9 Purpose Details: Make Pizza Ordering Application Course: IST 242 Author: <NAME> Date Developed: 3/17/2018 Last Date Changed: 3/24/2018 Rev: */ package psu.edu.ist242; import java.util.ArrayList; import java.util.Scanner; //Uses other classes and prompts user for inputs //Use switch statements to access other classes or maybe quit?? //Use boolean statements to check for validations //Have counter for orderID?? public class Lab9Chen { public static void main(String[] args) { int numIn = 1; /***************************************Making the Menu***************************************/ ArrayList<Menu> items = new ArrayList<Menu>(); Menu cheese = new Menu("Cheese Pizza x" + numIn, 1.25 * numIn); items.add(cheese); Menu sausage = new Menu("Sausage Pizza x" + numIn, 1.50 * numIn); items.add(sausage); Menu pineapple = new Menu("Pineapple Pizza x" + numIn, 1.35 * numIn); items.add(pineapple); /*********************************************************************************************/ Customer cust = new Customer("", "", ""); ArrayList<Menu> _order = new ArrayList<Menu>(); Transaction transaction = new Transaction(""); long orderid = 0; int num1,num2 ; do { Order order = new Order(0); Scanner input = new Scanner(System.in); // Input stream for standard input System.out.println("Please select an option"); System.out.println("1. Add/Edit all customer information"); System.out.println("2. Edit specific customer information"); System.out.println("3. Place/Edit order"); System.out.println("4. Payment method"); System.out.println("5. Finish order"); num1 = input.nextInt(); switch (num1) { case 1: System.out.println("Please enter \"first name, last name, and street name\" separated by a space."); input.nextLine(); String lineIn = input.nextLine(); String[] seq = lineIn.split(" "); if (seq.length == 3) { cust.setCustFirstName(seq[0]); cust.setCustLastName(seq[1]); cust.setStreetName(seq[2]); System.out.printf("Your customer information: \nFirst Name: %s\nLast Name: %s\nStreet Name: %s\n", cust.getCustFirstName(), cust.getCustLastName(), cust.getStreetName()); } break; case 2: System.out.printf("Your current customer information: \nFirst Name: %s\nLast Name: %s\nStreet Name: %s\n", cust.getCustFirstName(), cust.getCustLastName(), cust.getStreetName()); System.out.println("Please select an option"); System.out.println("1. Edit first name"); System.out.println("2. Edit last name"); System.out.println("3. Edit street name"); System.out.println("Any other number to exit"); num2 = input.nextInt(); switch (num2) { case 1: System.out.println("Please enter a new first name:"); input.nextLine(); lineIn = input.nextLine(); cust.setCustFirstName(lineIn); break; case 2: System.out.println("Please enter a new last name:"); input.nextLine(); lineIn = input.nextLine(); cust.setCustLastName(lineIn); break; case 3: System.out.println("Please enter a new street name:"); input.nextLine(); lineIn = input.nextLine(); cust.setStreetName(lineIn); break; default: break; } break; case 3: System.out.print("Items on the menu\nPlease select which order you want.\n"); for (int i = 0; i < items.size(); i++) { int counter = i + 1; System.out.printf("%d. %s | Price: %.2f \n", counter, items.get(i).getName(), items.get(i).getPrice()); } System.out.println("Any other number to exit"); num2 = input.nextInt(); switch (num2) { case 1: System.out.println("Please enter how many you want to order.\nTo remove order, enter \"0\"."); numIn = input.nextInt(); order.setQuantity(numIn); Menu ordercheese = new Menu("Cheese Pizza x" + numIn, 1.25 * numIn); if (order.getQuantity() > 0){ _order.add(ordercheese); } else if (order.getQuantity() == 0) { for (int i = 0; i < _order.size(); i++) { if (_order.get(i).getName().startsWith("Cheese Pizza x")){ _order.remove(i); } } } else { break; } break; case 2: System.out.println("Please enter how many you want to order.\nTo remove order, enter \"0\"."); numIn = input.nextInt(); order.setQuantity(numIn); Menu ordersausage = new Menu("Sausage Pizza x" + numIn, 1.50 * numIn); if (order.getQuantity() > 0){ _order.add(ordersausage); } else if (order.getQuantity() == 0) { for (int i = 0; i < _order.size(); i++) { if (_order.get(i).getName().startsWith("Sausage Pizza x")){ _order.remove(i); } } } else { break; } break; case 3: System.out.println("Please enter how many you want to order.\nTo remove order, enter \"0\"."); numIn = input.nextInt(); order.setQuantity(numIn); Menu orderpineapple = new Menu("Pineapple Pizza x" + numIn, 1.35 * numIn); if (order.getQuantity() > 0) { _order.add(orderpineapple); } else if (order.getQuantity() == 0) { for (int i = 0; i < _order.size(); i++) { if (_order.get(i).getName().startsWith("Pineapple Pizza x")){ _order.remove(i); } } } else { break; } break; default: break; } break; case 4: System.out.println("Please enter method of payment: \"credit, debit, or cash\""); input.nextLine(); lineIn = input.nextLine(); transaction.setTransaction(lineIn); break; case 5: System.out.println("Exiting systems..."); break; default: System.out.println("ERROR! Inputted value not accepted... try again."); break; } } while (num1 != 5); orderid++; System.out.printf("Order #: %d.\n", orderid); System.out.printf("Your final customer information: \nFirst Name: %s\nLast Name: %s\nStreet Name: %s\n", cust.getCustFirstName(), cust.getCustLastName(), cust.getStreetName()); System.out.println("Your final orders"); for (int i = 0; i < _order.size(); i++) { System.out.printf("%s\nPrice: %.2f \n", _order.get(i).getName(), _order.get(i).getPrice()); } System.out.printf("Transaction method: %s\n", transaction.getTransaction()); System.out.println("Goodbye please come again!"); } } <file_sep>package psu.edu.ist242; //Order Info public class Order { private int quantity; public void setQuantity(int quantity) { this.quantity = quantity; } public int getQuantity() { return quantity; } public Order (int _quantity){ this.quantity = _quantity; } }
503f520880dacf11f2ea1453295170869f5eae0b
[ "Java" ]
2
Java
dchen275/PizzaMenu
f7f210a0876db904ae724cc62fa9a2528021d236
38a84a989b8adccb658c2c81b473ae2c6439ea13
refs/heads/master
<file_sep>#include "rw_mutex.h" #include <iostream> #include <thread> #include <stdexcept> inline bool can_start_reading(RWMutex_Mode mode) { return mode == MX_READ_ONLY || mode == MX_RELEASED; } inline bool can_start_writing(RWMutex_Mode mode, std::thread::id const& hot, std::thread::id const& me) { return mode == MX_RELEASED || ((mode == MX_HANDOFF_WRITE) && (hot == me)); } inline bool can_start_writing(RWMutex_Mode mode) { return mode == MX_RELEASED; } inline void do_yield() { std::this_thread::yield(); } void rw_mutex::i_add_self() { if(m_users.insert(std::this_thread::get_id()).second == false) throw std::runtime_error("A thread has locked a rw_mutex twice!"); } void rw_mutex::i_rem_self() { auto f_iter = m_users.find(std::this_thread::get_id()); if(f_iter == m_users.end()) throw std::runtime_error("A thread has unlocked a rw_mutex twice!"); m_users.erase(f_iter); } bool rw_mutex::i_has_self() const { return m_users.find(std::this_thread::get_id()) != m_users.end(); } void rw_mutex::i_unlock() { i_rem_self(); switch(m_mode) { case MX_READ_ONLY: case MX_READ_WRITE: if(m_users.empty()) m_mode = MX_RELEASED; break; case MX_READ_WRITE_AWAITING_WRITE: case MX_READ_ONLY_AWAITING_WRITE: if(m_users.empty()) m_mode = MX_HANDOFF_WRITE; break; case MX_RELEASED: case MX_HANDOFF_WRITE: default: throw std::runtime_error("Invalid rw_mutex state!"); } } void rw_mutex::i_lock() { std::thread::id tid = std::this_thread::get_id(); while(!can_start_writing(m_mode, m_handoff_write_thread, tid)) { if(m_mode == MX_READ_ONLY) { m_mode = MX_READ_ONLY_AWAITING_WRITE; m_handoff_write_thread = tid; } else if(m_mode == MX_READ_WRITE) { m_mode = MX_READ_WRITE_AWAITING_WRITE; m_handoff_write_thread = tid; } m_mutex.unlock(); do_yield(); m_mutex.lock(); } i_add_self(); m_mode = MX_READ_WRITE; } void rw_mutex::i_lock_read() { while(!can_start_reading(m_mode)) { m_mutex.unlock(); do_yield(); m_mutex.lock(); } i_add_self(); m_mode = MX_READ_ONLY; } rw_mutex::rw_mutex() : m_mode(MX_RELEASED) {} void rw_mutex::lock_read() { std::lock_guard<spinlock_mutex> lg(m_mutex); i_lock_read(); } bool rw_mutex::trylock_read() { std::lock_guard<spinlock_mutex> lg(m_mutex); if(!can_start_reading(m_mode)) return false; i_add_self(); m_mode = MX_READ_ONLY; return true; } void rw_mutex::lock() { std::lock_guard<spinlock_mutex> lg(m_mutex); i_lock(); } bool rw_mutex::trylock() { std::lock_guard<spinlock_mutex> lg(m_mutex); if(!can_start_writing(m_mode)) { return false; } i_add_self(); m_mode = MX_READ_WRITE; return true; } void rw_mutex::chlock_r() { std::lock_guard<spinlock_mutex> lg(m_mutex); if(!i_has_self()) throw std::runtime_error("A thread has unlocked a rw_mutex twice!"); switch(m_mode) { case MX_READ_WRITE: m_mode = MX_READ_ONLY; break; case MX_READ_WRITE_AWAITING_WRITE: m_mode = MX_READ_ONLY_AWAITING_WRITE; break; case MX_READ_ONLY_AWAITING_WRITE: case MX_READ_ONLY: break; case MX_RELEASED: case MX_HANDOFF_WRITE: default: throw std::runtime_error("Unable to chlock_r. Lock was in an invalid state."); return; } } void rw_mutex::chlock_w() { std::lock_guard<spinlock_mutex> lg(m_mutex); i_unlock(); i_lock(); } void rw_mutex::unlock() { std::lock_guard<spinlock_mutex> lg(m_mutex); i_unlock(); }<file_sep>#include "monitor.h" #include <picosha2.h> // Not a fully featured path simplifier, but it's just a safety measure. // Regular URLs will not be heavily impacted by this function. SimplifiedPath FileMonitor::simplify(std::string const& src, std::string const& root) { SimplifiedPath rval; std::string& dst = rval.m_path; std::string& dir = rval.m_dir; rval.m_root = root; dst.reserve(src.size()); dir.reserve(src.size()-6); // Shortest filename section: /x.lua std::string::size_type i = 0; std::string::size_type len = src.size(); std::string sector; while(i < len) { while(i < len && (src[i] == '/' || src[i] == '\\')) ++i; std::string::size_type begin = i; while(i < len && src[i] != '/' && src[i] != '\\') ++i; if(!sector.empty() && sector != ".." && sector != ".") dir += "/" + sector; sector.assign(src, begin, i-begin); if(sector == ".." || sector == ".") continue; dir = dst; dst += "/" + sector; } return rval; } FileChangeData FileMonitor::getFileStatus(std::ifstream& f) { FileChangeData fcd; if(g_settings.m_useFileChecksum) { // std::ifstream f(path.m_path, std::ios_base::binary); std::vector<std::uint8_t> s(picosha2::k_digest_size); picosha2::hash256(f, s.begin(), s.end()); if(f) { std::swap(fcd.m_hash, s); fcd.m_filesize = f.tellg(); fcd.m_exists = true; } } else { //std::ifstream f(path.m_path, std::ios_base::binary | std::ios_base::ate); f.seekg(0, std::ios_base::end); if(f) { fcd.m_filesize = f.tellg(); fcd.m_exists = true; } } if(f) { f.seekg(0, std::ios_base::beg); f.clear(); } fcd.m_captureTime = FileChangeData::clock_t::now(); return fcd; } std::unique_ptr<std::ifstream> FileMonitor::getFileForLoading(SimplifiedPath const& path, FileChangeData& storage, bool forceReload) { std::unique_ptr<std::ifstream> file; FileChangeData compare; if(forceReload) { file.reset(new std::ifstream(path.m_path, std::ios_base::binary)); compare = FileMonitor::getFileStatus(*file); if(!*file) return std::unique_ptr<std::ifstream>(); } else { if(std::chrono::duration_cast<std::chrono::milliseconds>(FileChangeData::clock_t::now() - storage.m_captureTime).count() <= g_settings.m_fileInfoTime) return std::unique_ptr<std::ifstream>(); file.reset(new std::ifstream(path.m_path, std::ios_base::binary)); compare = FileMonitor::getFileStatus(*file); if( (!*file) || (compare == storage)) return std::unique_ptr<std::ifstream>(); } storage = compare; return file; } <file_sep>#include "lua_fnc.h" #include "settings.h" #include "session.h" template <typename T> struct LenCalcImpl { static std::size_t esize(T const& v) { return v.size(); } }; template <> struct LenCalcImpl<int> { static std::size_t esize(int v) { return static_cast<std::size_t>(v); } }; template <typename ... Args> struct LenCalc { static std::size_t size() { return 0; } }; template <typename T, typename ... Args> struct LenCalc<T, Args...> { static std::size_t size(T&& t, Args&& ... args) { return LenCalcImpl<T>::esize(t) + LenCalc<Args...>::size(std::forward<Args>(args)...); } }; template <typename ... Args> std::size_t total_size(Args&& ... args) { return LenCalc<Args...>::size(std::forward<Args>(args)...); } void rawLuaHeader(LuaRequestData* reqData, std::string const& key, std::string const& val) { reqData->m_cache->headers.reserve(total_size( reqData->m_cache->headers, key, val, 4 )); reqData->m_cache->headers.append(key); reqData->m_cache->headers.append(": "); reqData->m_cache->headers.append(val); reqData->m_cache->headers.append("\r\n"); } static void luaHeader(LuaRequestData* reqData, std::string const& key, Lua::Arg<std::string> const& val) { reqData->m_cache->headers.append(key); if(val) { reqData->m_cache->headers.reserve(total_size( reqData->m_cache->headers, *val, 4 )); reqData->m_cache->headers.append(": "); reqData->m_cache->headers.append(*val); } reqData->m_cache->headers.append("\r\n"); } static void luaPuts(LuaRequestData* reqData, std::string const& data) { if(g_settings.m_bodysectors == 1 && !reqData->m_cache->body.empty()) { reqData->m_cache->body[0].append(data); return; } std::size_t firstAvailable = 0; for(std::size_t i = 0; i < reqData->m_cache->body.size(); ++i) { if(reqData->m_cache->body[i].empty()) { firstAvailable = (i>0)?(i-1):0; break; } } for(std::size_t i = firstAvailable; i < reqData->m_cache->body.size(); ++i) { auto it = &(reqData->m_cache->body[i]); if( it->empty() || (data.size() <= ( it->capacity() - it->size() )) ) { it->append(data); return; } } reqData->m_cache->body.emplace_back(); if(static_cast<int>(data.size()) < g_settings.m_bodysize) reqData->m_cache->body.back().reserve(g_settings.m_bodysize); reqData->m_cache->body.back().append(data); } static void luaReset(LuaRequestData* reqData) { reqData->m_cache->headers.clear(); reqData->m_cache->body.clear(); } static void luaLog(LuaRequestData*, std::string const& data) { LogError(data); } static std::string luaGets(LuaRequestData* reqData) { int const chunk_size = 1024; reqData->m_cache->getsBuffer.clear(); reqData->m_cache->getsBuffer.resize(chunk_size); std::string getsData; int len = 0; do { len = FCGX_GetStr(&(reqData->m_cache->getsBuffer[0]), chunk_size, reqData->m_request->in); if(len > 0) getsData.append(&(reqData->m_cache->getsBuffer[0]), static_cast<std::size_t>(len)); } while(len == chunk_size); return getsData; } static void luaStatus(LuaRequestData* reqData, std::string const& data) { reqData->m_cache->status = data; } static void luaContentType(LuaRequestData* reqData, std::string const& data) { reqData->m_cache->contentType = data; } static Lua::Map<int> luaServerHealth(LuaRequestData*) { Lua::Map<int> d; d.m_data = g_statepool.ServerInfo(); return d; } static std::string luaDir(LuaRequestData* reqData) { return reqData->m_cache->script.dir(); } static void luaSessionStart(LuaRequestData* reqData) { reqData->m_session.Start(); } static bool luaSessionHasRealm(LuaRequestData* reqData, std::string const& realm) { return reqData->m_session.HasRealm(realm); } static void luaSessionDelete(LuaRequestData* reqData) { reqData->m_session.Delete(); } static void luaSessionClear(LuaRequestData* reqData, std::string const& realm) { reqData->m_session.Clear(realm); } static bool luaSessionSetVar(LuaRequestData* reqData, std::string const& realm, std::string const& var, std::shared_ptr<Lua::Variable> data) { return reqData->m_session.SetVar(realm, var, data.get()); } static Lua::ReturnValues luaSessionGetVar(LuaRequestData* reqData, std::string const& realm, std::string const& var) { return reqData->m_session.GetVar(realm, var); } void SetupLuaFunctions(Lua::State& state, LuaRequestData& lrd) { state.luapp_add_translated_function("Header", Lua::Transform(::luaHeader, &lrd)); state.luapp_add_translated_function("Send", Lua::Transform(::luaPuts, &lrd)); state.luapp_add_translated_function("Reset", Lua::Transform(::luaReset, &lrd)); state.luapp_add_translated_function("Log", Lua::Transform(::luaLog, &lrd)); state.luapp_add_translated_function("Receive", Lua::Transform(::luaGets, &lrd)); state.luapp_add_translated_function("RespStatus", Lua::Transform(::luaStatus, &lrd)); state.luapp_add_translated_function("RespContentType", Lua::Transform(::luaContentType, &lrd)); state.luapp_add_translated_function("ThreadData", Lua::Transform(::luaServerHealth, &lrd)); state.luapp_add_translated_function("Dir", Lua::Transform(::luaDir, &lrd)); state.newtable(); state.pushstring("Start"); state.luapp_push_translated_function(Lua::Transform(::luaSessionStart, &lrd)); state.settable(-3); state.pushstring("HasRealm"); state.luapp_push_translated_function(Lua::Transform(::luaSessionHasRealm, &lrd)); state.settable(-3); state.pushstring("Delete"); state.luapp_push_translated_function(Lua::Transform(::luaSessionDelete, &lrd)); state.settable(-3); state.pushstring("Clear"); state.luapp_push_translated_function(Lua::Transform(::luaSessionClear, &lrd)); state.settable(-3); state.pushstring("SetVar"); state.luapp_push_translated_function(Lua::Transform(::luaSessionSetVar, &lrd)); state.settable(-3); state.pushstring("GetVar"); state.luapp_push_translated_function(Lua::Transform(::luaSessionGetVar, &lrd)); state.settable(-3); state.setglobal("Session"); } <file_sep>#ifndef SPINLOCK_MUTEX_H #define SPINLOCK_MUTEX_H #include <atomic> #include <mutex> class spinlock_mutex { std::atomic_flag m_flag; public: inline spinlock_mutex() noexcept : m_flag(ATOMIC_FLAG_INIT) {} inline void lock() noexcept { while(m_flag.test_and_set(std::memory_order_acquire)) ; } inline bool trylock() noexcept { return m_flag.test_and_set(std::memory_order_acquire) == 0; } inline void unlock() noexcept { m_flag.clear(std::memory_order_release); } }; typedef std::lock_guard<spinlock_mutex> spinlock_guard; #endif // SPINLOCK_MUTEX_H <file_sep>#ifndef SETTINGS_H_INCLUDED #define SETTINGS_H_INCLUDED #include <string> #include <vector> #include <mutex> #include <ctime> #include "state.h" class Settings { public: int m_threadCount; int m_states; int m_maxstates; int m_seek_retries; int m_headersize; int m_bodysize; int m_bodysectors; int m_fileInfoTime; bool m_useFileChecksum; std::string m_sessionName; int m_sessionTime; int m_sessionKeyLen; bool m_sessionCookieSecure; bool m_sessionCookieHttpOnly; std::string m_sessionCookieSameSite; int m_sessionIpScore; int m_sessionUserAgentScore; int m_sessionLanguageScore; int m_sessionTargetScore; std::string m_headers; std::string m_defaultHttpStatus; std::string m_defaultContentType; int m_maxPostSize; std::string m_listen; std::string m_logFile; std::string m_luaHeader; std::string m_luaEntrypoint; std::string m_luaLoadData; Lua::State m_luaState; void iPushValueTransfer(Lua::State& dest, int offset); public: Settings(); bool LoadSettings(std::string const& path); void TransferConfig(Lua::State& dest); void TransferLocalConfig(Lua::State& dest, std::string const& domain); }; extern Settings g_settings; extern std::mutex g_errormutex; void LogError(std::string const&); void LogError(char const*); void gmtime_mx(std::time_t const& t, std::tm&); #endif <file_sep>#include "settings.h" // STL #include <stdexcept> #include <algorithm> #include <fstream> #include <iostream> static std::string g_luaHeader = R"====( LUAFCGID=true LUAFCGID_VERSION=2 lf={} function lf.serialize(a)local b=""if type(a)=="table"then local c={}for d,e in pairs(a)do if type(d)=="number"then d=tostring(d)elseif type(d)=="string"then d=string.format("[%q]",d)end;table.insert(c,string.format("%s = %s",d,lf.serialize(e)))end;b='{'..table.concat(c,",")..'}'elseif type(a)=="number"then b=tostring(a)elseif type(a)=="string"then b=string.format("%q",a)elseif type(a)=="boolean"then b=a and"true"or"false"end;return b end function lf.urlencode(a)if a and#a>0 then a=string.gsub(a,"([^%w ])",function(b)return string.format("%%%02X",string.byte(b))end)a=string.gsub(a," ","+")end;return a end function lf.urldecode(a)if a and#a>0 then a=string.gsub(a,"+"," ")a=string.gsub(a,"%%(%x%x)",function(b)return string.char(tonumber(b,16))end)end;return a end function lf.parse_pair(b)local c,d;if b and#b>0 then _,_,c,d=string.find(b,"([^=]*)=([^=]*)")if not d then d=""end end;return lf.urldecode(c),lf.urldecode(d)end function lf.parse(a)local b={}for c in string.gmatch(a,"[^&]*")do if c and#c>0 then local d,e=lf.parse_pair(c)if b[d]then if type(b[d])~="table"then b[d]={b[d]}end;table.insert(b[d],e)else b[d]=e end end end;return b end Response={ [100]="100 Continue",[101]="101 Switching Protocols",[102]="102 Processing",[103]="103 Early Hints", [200]="200 OK",[201]="201 Created",[202]="202 Accepted",[203]="203 Non-Authoritative Information",[204]="204 No Content",[205]="205 Reset Content",[206]="206 Partial Content",[207]="207 Multi-Status",[208]="208 Already Reported",[226]="226 IM Used", [300]="300 Multiple Choices",[301]="301 Moved Permanently",[302]="302 Found",[303]="303 See Other",[304]="304 Not Modified",[305]="305 Use Proxy",[306]="306 Switch Proxy",[307]="307 Temporary Redirect",[308]="308 Permanent Redirect", [400]="400 Bad Request",[401]="401 Unauthorized",[402]="402 Payment Required",[403]="403 Forbidden",[404]="404 Not Found",[405]="405 Method Not Allowed",[406]="406 Not Acceptable",[407]="407 Proxy Authentication Required",[408]="408 Request Timeout",[409]="409 Conflict",[410]="410 Gone",[411]="411 Length Required",[412]="412 Precondition Failed",[413]="413 Payload Too Large",[414]="414 URI Too Long",[415]="415 Unsupported Media Type", [416]="416 Range Not Satisfiable",[417]="417 Expectation Failed",[418]="418 I'm a teapot",[421]="421 Misdirected Request",[422]="422 Unprocessable Entity",[423]="423 Locked",[424]="424 Failed Dependency",[426]="426 Upgrade Required",[428]="428 Precondition Required",[429]="429 Too Many Requests",[431]="431 Request Header Fields Too Large",[451]="451 Unavailable For Legal Reasons", [500]="500 Internal Server Error",[501]="501 Not Implemented",[502]="502 Bad Gateway",[503]="503 Service Unavailable",[504]="504 Gateway Timeout",[505]="505 HTTP Version Not Supported",[506]="506 Variant Also Negotiates",[507]="507 Insufficient Storage",[508]="508 Loop Detected",[510]="510 Not Extended",[511]="511 Network Authentication Required" } )===="; void BindBool(Lua::State& s, const char* variable, bool& def_val) { if(s.getglobal(variable) == Lua::TP_BOOL) { def_val = s.toboolean(-1); } s.pop(1); } void BindNumber(Lua::State& s, const char* variable, int& def_val) { if(s.getglobal(variable) == Lua::TP_NUMBER) { def_val = s.tonumber(-1); } s.pop(1); } void BindString(Lua::State& s, const char* variable, std::string& def_val) { if(s.getglobal(variable) == Lua::TP_STRING) { def_val = s.tostdstring(-1); } s.pop(1); } Settings::Settings() : m_threadCount(4), m_states(3), m_maxstates(5), m_seek_retries(3), m_headersize(256), m_bodysize(2048), m_bodysectors(4), m_fileInfoTime(5000), m_useFileChecksum(true), m_sessionName("XLuaSession"), m_sessionTime(3600), m_sessionKeyLen(24), m_sessionCookieSecure(true), m_sessionCookieHttpOnly(true), m_sessionCookieSameSite(), m_sessionIpScore(3), m_sessionUserAgentScore(2), m_sessionLanguageScore(1), m_sessionTargetScore(3), m_headers("X-Powered-By: luafcgid2\r\n"), m_defaultHttpStatus("200 OK"), m_defaultContentType("text/html"), m_maxPostSize(1024 * 4096), m_listen("/var/tmp/luafcgid2.sock"), m_logFile("/var/log/luafcgid2/luafcgid2.log"), m_luaEntrypoint("main") {} void Settings::iPushValueTransfer(Lua::State& dest, int offset) { // Pop a value from m_luaState // Push a value to dest Lua::Type t = m_luaState.type(offset); switch(t) { case Lua::TP_NONE: case Lua::TP_NIL: default: dest.pushnil(); break; case Lua::TP_BOOL: dest.pushboolean(m_luaState.toboolean(offset)); break; case Lua::TP_NUMBER: if(m_luaState.isinteger(offset)) dest.pushinteger(m_luaState.tointeger(offset)); else dest.pushnumber(m_luaState.tonumber(offset)); break; case Lua::TP_STRING: dest.pushstdstring(m_luaState.tostdstring(offset)); break; case Lua::TP_TABLE: { dest.newtable(); m_luaState.pushnil(); if(offset < 0) --offset; while(m_luaState.next(offset) != 0) { iPushValueTransfer(dest, -2); iPushValueTransfer(dest, -1); dest.rawset(-3); m_luaState.pop(1); } if(offset < 0) ++offset; } break; } } // Setup Config.* std::mutex g_transferMutex; void Settings::TransferConfig(Lua::State& dest) { std::lock_guard<std::mutex> g(g_transferMutex); m_luaState.getglobal("Config"); iPushValueTransfer(dest, -1); dest.setglobal("Config"); m_luaState.pop(1); } // Setup LocalConfig.* void Settings::TransferLocalConfig(Lua::State& dest, std::string const& domain) { std::lock_guard<std::mutex> g(g_transferMutex); m_luaState.getglobal("Config"); m_luaState.pushstdstring(domain); m_luaState.rawget(-2); iPushValueTransfer(dest, -1); dest.setglobal("LocalConfig"); m_luaState.pop(2); } bool Settings::LoadSettings(std::string const& path) { m_luaState = Lua::State::create(); if(m_luaState.loadfile(path.c_str()) == LUA_OK && m_luaState.pcall() == LUA_OK) { BindNumber(m_luaState, "WorkerThreads", m_threadCount); BindNumber(m_luaState, "LuaStates", m_states); BindNumber(m_luaState, "LuaMaxStates", m_maxstates); BindNumber(m_luaState, "LuaMaxSearchRetries", m_seek_retries); BindNumber(m_luaState, "HeadersSize", m_headersize); BindNumber(m_luaState, "BodySize", m_bodysize); BindNumber(m_luaState, "BodySectors", m_bodysectors); BindNumber(m_luaState, "MinFileInfoTime", m_fileInfoTime); BindBool (m_luaState, "UseFileChecksum", m_useFileChecksum); BindString(m_luaState, "SessionName", m_sessionName); BindNumber(m_luaState, "SessionTime", m_sessionTime); BindNumber(m_luaState, "SessionKeyLen", m_sessionKeyLen); BindBool (m_luaState, "SessionCookieSecure", m_sessionCookieSecure); BindBool (m_luaState, "SessionCookieHttpOnly", m_sessionCookieHttpOnly); BindString(m_luaState, "SessionCookieSameSite", m_sessionCookieSameSite); BindNumber(m_luaState, "SessionIpScore", m_sessionIpScore); BindNumber(m_luaState, "SessionUserAgentScore", m_sessionUserAgentScore); BindNumber(m_luaState, "SessionLanguageScore", m_sessionLanguageScore); BindNumber(m_luaState, "SessionTargetScore", m_sessionTargetScore); BindString(m_luaState, "DefaultHeaders", m_headers); BindString(m_luaState, "DefaultHttpStatus", m_defaultHttpStatus); BindString(m_luaState, "DefaultContentType", m_defaultContentType); BindNumber(m_luaState, "MaxPostSize", m_maxPostSize); BindString(m_luaState, "LogFilePath", m_logFile); BindString(m_luaState, "Listen", m_listen); BindString(m_luaState, "StartupScript", m_luaHeader); BindString(m_luaState, "Entrypoint", m_luaEntrypoint); } if(m_threadCount < 1) m_threadCount = 1; if(m_states < 1) m_states = 1; if(m_maxstates < 1) m_maxstates = 1; if(m_seek_retries < 1) m_seek_retries = 1; if(m_headersize < 0) m_headersize = 0; if(m_bodysize < 0) m_bodysize = 0; if(m_bodysectors < 0) m_bodysectors = 0; if(m_maxPostSize < 0) m_maxPostSize = 0; { m_luaLoadData = g_luaHeader; if(!m_luaHeader.empty()) { std::ifstream myScript(m_luaHeader, std::ios::ate | std::ios::binary); if(myScript) { std::streamsize size = myScript.tellg(); if(size > 0) { m_luaLoadData.resize(size + g_luaHeader.size()); myScript.seekg(0, std::ios::beg); if(!myScript.read(&(m_luaLoadData[g_luaHeader.size()]), size)) m_luaLoadData = g_luaHeader; } } } } return true; } void LogError(std::string const& s) { std::lock_guard<std::mutex> lg(g_errormutex); std::cerr << s << std::endl; } void LogError(char const* s) { std::lock_guard<std::mutex> lg(g_errormutex); std::cerr << s << std::endl; } Settings g_settings; std::mutex g_errormutex; static std::mutex g_gmtime_mx; void gmtime_mx(std::time_t const& t, std::tm& r) { std::lock_guard<std::mutex> lg(g_gmtime_mx); r = *std::gmtime(&t); } <file_sep>#ifndef THREAD_H_INCLUDED #define THREAD_H_INCLUDED #include <string> #include <vector> #include <thread> class Thread { int const m_thread_id; int const m_sock; std::thread m_thread; Thread(Thread const&) =delete; Thread& operator= (Thread const&) =delete; public: Thread(int thread_id, int sock); void Spawn(); }; #endif<file_sep># Raspberry Pi Makefile # Target Binary Settings BIN = luafcgid2 OPTIMIZATION ?= -O2 # Installation directories PREFIX ?= /usr BINDIR ?= $(PREFIX)/bin CONFDIR ?= /etc/luafcgid2 INITDIR ?= /etc/init.d # Lua library paths LUAINC = $(PREFIX)/include/lua5.3 LUALIB = $(PREFIX)/lib LLIB = lua5.3 # Project Set-up INC_PATH = include SRC_PATH = source BUILD_PATH = build BIN_PATH = build/bin DEP_PATH = deps # Build Flags CXX ?= g++ CC ?= gcc WARN = -Wall -Wextra -pedantic CXX_V = -std=c++11 CC_V = -std=c11 DEFINES = -DHAVE_STRUCT_STAT_ST_MTIME=1 -DHAVE_CXX_MUTEX=1 -DHAVE_CXX_ATOMIC=1 # Precomputed Build Flags INCLUDES = -I$(PREFIX)/include -I$(LUAINC) -I$(INC_PATH) LDFLAGS = -L$(PREFIX)/lib -L$(LUALIB) $(OPTIMIZATION) LDLIBS = -lm -lpthread -lfcgi -l$(LLIB) DEP_OBJ = CXXFLAGS = $(CXX_V) $(OPTIMIZATION) $(WARN) $(INCLUDES) $(DEFINES) CFLAGS = $(CC_V) $(OPTIMIZATION) $(WARN) $(INCLUDES) $(DEFINES) # Get list of .cpp and .o files. You can add more extensions. SOURCES = $(shell find $(SRC_PATH) -type f \( -name '*.cpp' -o -name '*.c' \) -printf '%T@ %p\n' | sort -k 1nr | cut -d ' ' -f 2) OBJECTS = $(SOURCES:$(SRC_PATH)/%=$(BUILD_PATH)/%.o) DEP_DIRS = $(shell ls -l $(DEP_PATH) | grep '^d' | awk '{ print $$9 }') DEPS = cleandep $(DEP_DIRS:%=$(BUILD_PATH)/%.mk) export OPTIMIZATION PREFIX LUAINC LUALIB LLIB CXX CXX_V CC CC_V WARN DEFINES .PHONY: default_target default_target: all .PHONY: dirs dirs: @echo "Creating directories" @mkdir -p $(dir $(OBJECTS)) $(BIN_PATH) .PHONY: cleandep cleandep: @echo "Deleting dependencies' results..." @rm -f $(DEP_PATH)/include @rm -f $(DEP_PATH)/ldflags @rm -f $(DEP_PATH)/ldlibs @rm -f $(DEP_PATH)/objects .PHONY: clean clean: cleandep @echo "Deleting $(BIN) symlink" @$(RM) $(BIN) @echo "Deleting directories" @$(RM) -r $(BUILD_PATH) @$(RM) -r $(BIN_PATH) # Building dependencies (Run all *.Makefile files in deps/) $(BUILD_PATH)/%.mk: $(DEP_PATH)/%.Makefile $(MAKE) -C $(DEP_PATH) -f $*.Makefile .PHONY: deps deps: $(DEPS) INCLUDES += $(shell cat $(DEP_PATH)/include) LDFLAGS += $(shell cat $(DEP_PATH)/ldflags) LDLIBS += $(shell cat $(DEP_PATH)/ldlibs) DEP_OBJ += $(shell cat $(DEP_PATH)/objects) $(BUILD_PATH)/%.c.o: $(SRC_PATH)/%.c $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ $(BUILD_PATH)/%.cpp.o: $(SRC_PATH)/%.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ # Creation of the executable $(BIN_PATH)/$(BIN): $(OBJECTS) @echo "Linking: $@" $(CXX) $(OBJECTS) $(DEP_OBJ) $(LDFLAGS) $(LDLIBS) -o $@ .PHONY: all all: dirs deps $(BIN_PATH)/$(BIN) @echo "Making symlink: $(BIN_PATH)/$(BIN) -> $(BIN)" @$(RM) $(BIN) @ln -s $(BIN_PATH)/$(BIN) $(BIN) .PHONY: install install: all @mkdir -p $(CONFDIR) install -m 755 $(BIN) $(BINDIR) install -m 644 scripts/luafcgid2-config.lua $(CONFDIR)/config.lua .PHONY: update update: all @mkdir -p $(CONFDIR) install -m 755 $(BIN) $(BINDIR) .PHONY: install-daemon install-daemon: all install -m 755 scripts/luafcgid2-init.d $(INITDIR)/luafcgid2 update-rc.d -f luafcgid2 defaults <file_sep>#ifndef MONITOR_H_INCLUDED #define MONITOR_H_INCLUDED #include "settings.h" #include <fstream> #include <memory> #include <atomic> #include <map> class SimplifiedPath { friend class FileMonitor; std::string m_path; std::string m_dir; std::string m_root; public: // Const only inline std::string const& get() const { return m_path; } inline std::string const& dir() const { return m_dir; } inline std::string const& root() const { return m_root; } }; struct FileChangeData { typedef std::chrono::steady_clock clock_t; inline FileChangeData() : m_exists(false), m_filesize(0) {} inline bool operator == (FileChangeData const& o) const { return m_exists == o.m_exists && m_filesize == o.m_filesize && m_hash == o.m_hash; } inline bool operator != (FileChangeData const& o) const { return !(*this == o); } bool m_exists; std::vector<std::uint8_t> m_hash; std::size_t m_filesize; clock_t::time_point m_captureTime; }; class FileMonitor { static FileChangeData getFileStatus(std::ifstream&); FileMonitor() =delete; public: static SimplifiedPath simplify(std::string const&, std::string const&); static std::unique_ptr<std::ifstream> getFileForLoading( SimplifiedPath const&, FileChangeData&, bool =false); }; #endif <file_sep>#ifndef STATEPOOL_H_INCLUDED #define STATEPOOL_H_INCLUDED #include <list> #include <vector> #include <atomic> #include <string> #include <map> #include <fcgiapp.h> #include "rw_mutex.h" #include "state.h" #include "monitor.h" struct LuaState { std::atomic_flag m_inUse; FileChangeData m_chid; Lua::State m_luaState; }; struct LuaThreadCache { SimplifiedPath script; std::string scriptData; std::string headers; std::vector<std::string> body; std::string getsBuffer; std::string status; std::string contentType; }; class LuaStatePool { typedef std::list<LuaState> LuaStateContainer; typedef std::chrono::high_resolution_clock clock; struct LuaPool { LuaStateContainer m_states; FileChangeData m_mostRecentChange; }; rw_mutex m_poolMutex; std::map<std::string,LuaPool> m_pool; bool ExecRequest(LuaState& state, int sid, int tid, FCGX_Request& request, LuaThreadCache& cache, clock::time_point start); public: bool Start(); bool ExecMT(int tid, FCGX_Request& request, LuaThreadCache& cache); std::map<std::string, int> ServerInfo(); }; extern LuaStatePool g_statepool; #endif <file_sep># Summary luafcgid2 is a multithreaded FastCGI server that runs under BSD/Linux. It manages a number of independent, persistent Lua states, that are then loaded with Lua scripts from the file system. These scripts are loaded/initialized on demand, and held in memory for as long as possible. The Lua scripts are also allowed to interface with the FastCGI libraries: thus providing an extremely fast, streamlined and lightweight platform from which to develop web-centric apps in Lua. # License See the LICENSE file included with the source code # Testing All development testing is done with a Raspberry Pi Zero W, and sometimes on a Debian x64 distro. ## Software: + Debian Stretch + nginx web server + Lua 5.3 # Installation On Debian Stretch (including Raspbian Stretch), simply run the following: # apt-get -y install libfcgi-dev liblua5.3-dev git make build-essential $ git clone --recursive https://github.com/EssGeeEich/luafcgid2.git $ cd luafcgid2 $ make # make install install-daemon You may need to tinker with the Makefile on other distros. If you just want to update the daemon, without touching the configuration files, you can do the following: $ make clean; make # make update ## Webserver (nginx): Add the following lines to your /etc/nginx/sites-available/your-site-here in the server{} section: location ~ \.lua$ { fastcgi_pass unix:/var/tmp/luafcgid2.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } **NOTE:** _make sure your root directive is set correctly, and the DOCUMENT_ROOT variable is set correctly_ # Design luafcgid2 spawns and manages a number of worker threads that each contain an isolated blocking accept loop. The FastCGI libraries provide a connect queue for each worker thread so that transient load spikes can be handled with a minimum of fuss. Lua is then introduced into the picture by created a shared Lua state for each Lua script that is requested. A script will be loaded multiple times. All scripts - including duplicates (clones) - are completely isolated from each other. After a state is initialized and loaded with a script, it is usually kept in memory forever. Each Lua VM is run within a worker thread as needed. The use of on-demand clones allows for multiple workers to run the same popular script. There is a configurable limit to the total number of Lua states that luafcgid will maintain. When this limit is reached, a new state gets generated at runtime. <file_sep>// STL #include <iostream> #include <memory> #include <fstream> // Lua namespace #include <state.h> // fastcgi #include <fcgi_config.h> #include <fcgiapp.h> // getpid //#include <sys/types.h> //#include <unistd.h> // nanosleep #include <time.h> // Config #include "settings.h" #include "thread.h" #include "statepool.h" #include "monitor.h" #include "session.h" int main(int argc, char** argv) { std::unique_ptr<std::ofstream> logFile; //pid_t pid = getpid(); if( !g_settings.LoadSettings((argc > 1 && argv[1]) ? argv[1] : "config.lua") ) { std::cerr << "[PARENT] Unable to load luafcgid2 config!" << std::endl; return 1; } /* redirect stderr to logfile */ if(!g_settings.m_logFile.empty()) { logFile.reset(new std::ofstream(g_settings.m_logFile, std::ios_base::out | std::ios_base::app)); if(*logFile) { std::cerr.rdbuf(logFile->rdbuf()); } else { logFile.reset(); } } if(!g_statepool.Start()) { std::cerr << "[PARENT] Unable to startup lua states pool!" << std::endl; return 1; } FCGX_Init(); int sock = FCGX_OpenSocket(g_settings.m_listen.c_str(), -1); if (!sock) { std::cerr << "[PARENT] Unable to create FCGI socket!" << std::endl; return 1; } std::vector<std::unique_ptr<Thread>> threads; threads.reserve(g_settings.m_threadCount); for(int i = 0; i < g_settings.m_threadCount; ++i) { threads.emplace_back(new Thread(i, sock)); } for(int i = 0; i < g_settings.m_threadCount; ++i) { threads[i]->Spawn(); } timespec tv; tv.tv_sec = 1; tv.tv_nsec = 0; for (int seconds=0;;) { nanosleep(&tv, NULL); (++seconds) %= 60; // Every 60 seconds, clean up the sessions if(seconds == 0) g_sessions.CleanExpiredSessions(); } return 0; }<file_sep>#include "statepool.h" #include "settings.h" #include "lua_fnc.h" #include "monitor.h" #include <fstream> #include <iostream> #include <chrono> #include <limits> // Lua status missing static bool Handle404(std::string const& script, FCGX_Request& request) { std::string str; str = "Status: 404 Not Found\r\nContent-Type: text-plain\r\n\r\nError: Page not found: "; str += script; str += "."; FCGX_PutStr(str.c_str(), str.length(), request.out); return false; } // Load the Lua script file static bool InitData(LuaThreadCache& cache, std::size_t filesize, std::unique_ptr<std::ifstream>& f) { // Load the script file if(!f) return false; cache.scriptData.resize(filesize); if(!f->read(&(cache.scriptData[0]), filesize)) return false; return true; } static void replaceAll(std::string& str, const std::string& from, const std::string& to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } } // Create the Lua status static bool InitState(LuaState& lstate, LuaThreadCache const& cache, FileChangeData const& fcd) { Lua::State& state = lstate.m_luaState; // Load cache.scriptData into lua state state = Lua::State::create(); state.openlibs(); // Make package.path and package.cpath localized and safer state.getglobal("package"); { state.getfield(-1, "path"); std::string path = state.tostdstring(-1); state.pop(1); replaceAll(path, ";./?.lua", ""); replaceAll(path, ";./?/init.lua", ""); path += ";" + cache.script.root() + "/?.lua"; path += ";" + cache.script.root() + "/?/init.lua"; path += ";" + cache.script.dir() + "/?.lua"; path += ";" + cache.script.dir() + "/?/init.lua"; state.pushstdstring(path); state.setfield(-2, "path"); } { state.getfield(-1, "cpath"); std::string cpath = state.tostdstring(-1); state.pop(1); // As a security measure, do not use relative paths for .so libs. replaceAll(cpath, ";./?.", ";" + cache.script.root() + "/?."); state.pushstdstring(cpath); state.setfield(-2, "cpath"); } state.pop(1); state.luapp_register_metatables(); g_settings.TransferConfig(state); if(g_settings.m_luaLoadData.size()) { if(state.loadbuffer( g_settings.m_luaLoadData.c_str(), g_settings.m_luaLoadData.size(), "head") != 0) { if(state.isstring(-1)) LogError(state.tostdstring(-1)); else LogError("Error loading Startup Script file."); state.close(); return false; } if(state.pcall() != 0) { if(state.isstring(-1)) LogError(state.tostdstring(-1)); else LogError("Error running Startup Script file."); state.close(); return false; } } if(state.loadbuffer( cache.scriptData.c_str(), cache.scriptData.size(), cache.script.get().c_str()) != 0) { if(state.isstring(-1)) LogError(state.tostdstring(-1)); else LogError("Error loading script file."); state.close(); return false; } if(state.pcall() != 0) { if(state.isstring(-1)) LogError(state.tostdstring(-1)); else LogError("Error running script file."); state.close(); return false; } lstate.m_chid = fcd; return true; } template <std::size_t Size> static bool is_equal(char const* strBegin, std::size_t len, char const (&compare)[Size]) { return (len == (Size-1)) && strncmp(strBegin,compare,Size-1)==0; } enum { NUM_SIZE = std::numeric_limits<std::size_t>::digits10 + 2 }; static char const g_empty[] = ""; void parseCookies(std::string& str, std::map<char const*, char const*>& data) { data.clear(); char* pos = &*str.begin(); char* sce = nullptr; char* ekill = nullptr; char* equals = nullptr; char* semicolon = nullptr; char old = 0; bool quotes = false; while(pos) { while(' ' == *pos) ++pos; sce = pos; while((*sce != 0) && (*sce != ',') && (*sce != ';') && (*sce != '=')) ++sce; ekill = sce - 1; while((*ekill == ' ') && (ekill >= pos)) *(ekill--) = 0; old = *sce; *sce = 0; if(old != '=') { data[pos] = g_empty; if(old == 0) break; pos = sce + 1; continue; } equals = sce + 1; quotes = false; semicolon = equals; while(semicolon[0] && (quotes || ((semicolon[0] != ';') && (semicolon[0] != ',')) ) ) { if(semicolon[0] == '"') quotes = !quotes; ++semicolon; } if(!semicolon[0]) semicolon = nullptr; if(semicolon) { semicolon[0] = 0; ++semicolon; } int lnEquals = static_cast<int>(strlen(equals))-1; if((equals[0] == '"') && (equals[lnEquals]=='"')) { equals[lnEquals] = 0; ++equals; } data[pos] = equals; pos = semicolon; } } bool LuaStatePool::ExecRequest(LuaState& luaState, int sid, int tid, FCGX_Request& request, LuaThreadCache& cache, clock::time_point start) { Lua::State& state = luaState.m_luaState; cache.headers.clear(); cache.getsBuffer.clear(); cache.status = g_settings.m_defaultHttpStatus; cache.contentType = g_settings.m_defaultContentType; cache.headers.reserve(g_settings.m_headersize); cache.body.resize(g_settings.m_bodysectors); for(auto it = cache.body.begin(); it != cache.body.end(); ++it) { it->resize(0); it->reserve(g_settings.m_bodysize); } std::map<char const*, char const*> cookies; std::string cookie_buffer; LuaRequestData lrd; lrd.m_cache = &cache; lrd.m_request = &request; SessionDetectData sdd; state.newtable(); char const* const* p = lrd.m_request->envp; std::string domain; while(p && *p) { char const* v = strchr(*p, '='); if(v) { char const* const key = *p; std::size_t const size = static_cast<std::size_t>(v - *p); char const* const val = ++v; if(is_equal(key, size, "HTTP_COOKIE")) { cookie_buffer = val; parseCookies(cookie_buffer, cookies); } else if(is_equal(key, size, "REMOTE_ADDR")) sdd.m_address = val; else if(is_equal(key, size, "HTTP_USER_AGENT")) sdd.m_useragent = val; else if(is_equal(key, size, "HTTP_ACCEPT_LANGUAGE")) sdd.m_languages = val; else if(is_equal(key, size, "SERVER_NAME")) domain = val; state.pushlstring(key, size); state.pushstring(val); state.settable(-3); } ++p; } state.setglobal("Env"); g_settings.TransferLocalConfig(state, domain); state.newtable(); for(auto it = cookies.begin(); it != cookies.end(); ++it) { if(!strcmp(it->first, g_settings.m_sessionName.c_str())) sdd.m_sessionKey = it->second; state.pushstring(it->first); state.pushstring(it->second); state.settable(-3); } state.setglobal("Cookies"); state.newtable(); state.pushstring("State"); state.pushinteger(sid); state.settable(-3); state.pushstring("Thread"); state.pushinteger(tid); state.settable(-3); state.setglobal("Info"); lrd.m_session.Init(g_sessions, sdd); SetupLuaFunctions(state, lrd); state.getglobal(g_settings.m_luaEntrypoint.c_str()); if(state.pcall() != 0) { if(state.isstring(-1)) LogError(cache.script.get() + ": " + state.tostdstring(-1)); else LogError(cache.script.get() + ": Unknown error."); state.gc(Lua::GC_COLLECT, 0); return false; } state.gc(Lua::GC_COLLECT, 0); { std::string cookieStr; if(lrd.m_session.getCookieString(cookieStr, domain)) rawLuaHeader(&lrd, "Set-Cookie", cookieStr); } int dur = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start).count(); std::string sDur = std::to_string(dur); std::size_t contentSize = 0; for(auto it = lrd.m_cache->body.begin(); it != lrd.m_cache->body.end(); ++it) { contentSize += it->size(); } char contentSizeStr[NUM_SIZE]; int c = std::snprintf(contentSizeStr, NUM_SIZE, "%zu", contentSize); FCGX_PutStr("Status: ", 8, lrd.m_request->out); FCGX_PutStr(lrd.m_cache->status.c_str(), lrd.m_cache->status.size(), lrd.m_request->out); FCGX_PutStr("\r\nContent-Type: ", 16, lrd.m_request->out); FCGX_PutStr(lrd.m_cache->contentType.c_str(), lrd.m_cache->contentType.size(), lrd.m_request->out); FCGX_PutStr("\r\nX-ElapsedTime: ", 17, lrd.m_request->out); FCGX_PutStr(sDur.c_str(), sDur.size(), lrd.m_request->out); FCGX_PutStr("\r\n", 2, lrd.m_request->out); FCGX_PutStr(g_settings.m_headers.c_str(), g_settings.m_headers.size(), lrd.m_request->out); FCGX_PutStr(lrd.m_cache->headers.c_str(), lrd.m_cache->headers.size(), lrd.m_request->out); FCGX_PutStr("Content-Length: ", 16, lrd.m_request->out); FCGX_PutStr(contentSizeStr, c, lrd.m_request->out); FCGX_PutStr("\r\n\r\n", 4, lrd.m_request->out); for(auto it = lrd.m_cache->body.begin(); it != lrd.m_cache->body.end(); ++it) { FCGX_PutStr(it->c_str(), it->size(), lrd.m_request->out); } return true; } bool LuaStatePool::ExecMT(int tid, FCGX_Request& request, LuaThreadCache& cache) { clock::time_point start = clock::now(); char const* script = FCGX_GetParam("SCRIPT_FILENAME", request.envp); char const* root = FCGX_GetParam("DOCUMENT_ROOT", request.envp); if(!script) { LogError("Invalid FCGI configuration: No SCRIPT_FILENAME variable."); return false; } if(!root) { LogError("Invalid FCGI configuration: No DOCUMENT_ROOT variable."); return false; } cache.script = FileMonitor::simplify(script, root); std::map<std::string,LuaPool>::iterator selIterator; LuaState* selState = nullptr; int selStateNum = -1; std::unique_ptr<LuaState> ownState; // 0 -> Error, can't open file or such. // 1 -> Good, but our cache is outdated. // 2 -> Perfect. The file is up to date. auto LoadScript = [&](FileChangeData& chid, bool brandNew) -> int { std::unique_ptr<std::ifstream> f = FileMonitor::getFileForLoading(cache.script, chid, brandNew); if(!chid.m_exists || (f && !InitData(cache, chid.m_filesize, f))) return 0; // Handle404(cache.script.get(), request); return (f) ? 1 : 2; }; FileChangeData poolChangeData; { m_poolMutex.lock_read(); std::lock_guard<rw_mutex> lg(m_poolMutex, std::adopt_lock); selIterator = m_pool.find(cache.script.get()); if(selIterator == m_pool.end()) { FileChangeData fcd; if(LoadScript(fcd, true) != 1) return Handle404(cache.script.get(), request); // Insert a new pair to std::map and populate it. m_poolMutex.chlock_w(); auto pairResult = m_pool.emplace(std::make_pair(cache.script.get(),LuaStatePool::LuaPool())); selIterator = pairResult.first; selIterator->second.m_mostRecentChange = fcd; // This pair could be already populated if another thread ran chlock_w slightly before. LuaStateContainer& states = selIterator->second.m_states; int targetStates = g_settings.m_states; if(static_cast<int>(states.size()) < targetStates) { while(static_cast<int>(states.size()) < targetStates) { states.emplace_back(); if(!InitState(states.back(), cache, fcd)) { states.pop_back(); return false; } } // Also grab the last generated state for future usage. selState = &(states.back()); selStateNum = states.size(); selState->m_inUse.test_and_set(std::memory_order_acquire); } m_poolMutex.chlock_r(); } // m_poolMutex is in read state // selIterator points to a good pair // selState might already point to a good state. if(!selState) { // We need to find a selState. // Try finding a good state for the required script LuaStateContainer& states = selIterator->second.m_states; int max_retries = g_settings.m_seek_retries; for(int i = 0; !selState && (i < max_retries); ++i) { if(i > 0) std::this_thread::yield(); int x = 0; for(auto it = states.begin(); it != states.end(); ++it, ++x) { if(!it->m_inUse.test_and_set(std::memory_order_acquire)) { selState = &(*it); selStateNum = x; break; } } } } if(!selState) { FileChangeData fcd; if(LoadScript(fcd, true) != 1) return Handle404(cache.script.get(), request); // No selState has been found. // As a last resort, create a new selState (and, if rules allow, store it) m_poolMutex.chlock_w(); selIterator->second.m_mostRecentChange = fcd; LuaStateContainer& states = selIterator->second.m_states; int stateLimit = g_settings.m_maxstates; // Our container can fit another element (maxstates) if(static_cast<int>(states.size()) < stateLimit) { states.emplace_back(); if(!InitState(states.back(), cache, fcd)) { states.pop_back(); return false; } selState = &(states.back()); selStateNum = states.size(); selState->m_inUse.test_and_set(std::memory_order_acquire); } else { // We have already reached maxstates. // Create a temporary LuaState. ownState.reset(new LuaState); if(InitState(*ownState, cache, fcd)) { selState = ownState.get(); selState->m_inUse.test_and_set(std::memory_order_acquire); } else return false; // Error loading script } } poolChangeData = selIterator->second.m_mostRecentChange; selIterator = m_pool.end(); // Giving up the mutex. Don't use selIterator anymore. } bool bForceReload = poolChangeData != selState->m_chid; switch(LoadScript(selState->m_chid, bForceReload)) { case 0: default: return Handle404(cache.script.get(), request); case 1: // InitData has already been called. // All we need is already in the cache. if(!InitState(*selState, cache, selState->m_chid)) return false; break; case 2: // No need to call anything. break; } // At this point, selState is finally valid, loaded and up-to-date. bool rv = false; try { // Elaborate the request here. rv = ExecRequest(*selState, selStateNum, tid, request, cache, start); } catch(std::exception& e) { LogError(cache.script.get() + ": " + e.what()); } catch(...) { LogError(cache.script.get() + ": Unknown exception thrown."); } selState->m_inUse.clear(std::memory_order_release); return rv; } bool LuaStatePool::Start() { // Just a placeholder for possible future implementation return true; } std::map<std::string, int> LuaStatePool::ServerInfo() { m_poolMutex.lock_read(); std::lock_guard<rw_mutex> lg(m_poolMutex, std::adopt_lock); std::map<std::string, int> data; for(auto it = m_pool.begin(); it != m_pool.end(); ++it) { data[it->first] = it->second.m_states.size(); } return data; } LuaStatePool g_statepool;<file_sep>#ifndef LUA_FNC_H_INCLUDED #define LUA_FNC_H_INCLUDED #include "statepool.h" #include "session.h" struct LuaRequestData { LuaThreadCache* m_cache; FCGX_Request* m_request; LuaSessionInterface m_session; }; void rawLuaHeader(LuaRequestData* reqData, std::string const& key, std::string const& val); void SetupLuaFunctions(Lua::State& state, LuaRequestData& lrd); #endif <file_sep>#ifndef RW_MUTEX_H #define RW_MUTEX_H #include "spinlock_mutex.h" #include <thread> #include <string> #include <set> enum RWMutex_Mode { MX_RELEASED = 0, MX_READ_ONLY, MX_READ_ONLY_AWAITING_WRITE, MX_READ_WRITE, MX_READ_WRITE_AWAITING_WRITE, MX_HANDOFF_WRITE }; class rw_mutex { spinlock_mutex m_mutex; RWMutex_Mode m_mode; std::set<std::thread::id> m_users; std::thread::id m_handoff_write_thread; void i_add_self(); void i_rem_self(); bool i_has_self() const; void i_unlock(); void i_lock(); void i_lock_read(); public: rw_mutex(); void lock_read(); bool trylock_read(); void lock(); bool trylock(); // Change from read-lock to write-lock void chlock_w(); // Change from write-lock to read-lock void chlock_r(); void unlock(); }; #endif // RW_MUTEX_H <file_sep>SUBMODULE = rw_mutex SUBMODULE_SOURCE = src SUBMODULE_INCLUDE = include SOURCES = $(shell find $(SUBMODULE)/$(SUBMODULE_SOURCE) -name 'main.*' -prune -o -type f \( -name '*.cpp' -o -name '*.c' \) -printf '%T@ %p\n' | sort -k 1nr | cut -d ' ' -f 2) OBJECTS = $(SOURCES:$(SUBMODULE)/$(SUBMODULE_SOURCE)/%=build/$(SUBMODULE)/%.o) INCLUDES = -I$(LUAINC) -I$(SUBMODULE)/$(SUBMODULE_INCLUDE) CXXFLAGS = $(CXX_V) $(OPTIMIZATION) $(WARN) $(INCLUDES) $(DEFINES) .PHONY: default_target default_target: all dirs: @mkdir -p build/$(SUBMODULE) build/$(SUBMODULE)/%.cpp.o: $(SUBMODULE)/$(SUBMODULE_SOURCE)/%.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@ all: dirs $(OBJECTS) @echo -Ideps/$(SUBMODULE)/$(SUBMODULE_INCLUDE) >>include @echo $(OBJECTS:%=deps/%) >>objects<file_sep>function DumpTable(tbl, prefix) if type(tbl) == "table" then for k,v in pairs(tbl) do if type(k) == "table" then k = "[table]" end DumpTable(v, prefix .. "." .. k) end else Send(string.format("%s = %s\n", prefix, tostring(tbl))) end end function main() Send("<h1>Environment</h1><pre>\n") for n, v in pairs(Env) do Send(string.format("%s = %s\n", n, v)) end Send("</pre>\n") if Env.REQUEST_METHOD == "GET" then -- String tables aren't faster than multiple Send calls anymore. params = lf.parse(Env.QUERY_STRING) Send("<h1>GET Params</h1><pre>\n") for n, v in pairs(params) do Send(string.format("%s = %s\n", n, v)) end Send("</pre>\n") end if Env.REQUEST_METHOD == "POST" then Send("<h1>POST</h1>\n") Send(string.format("<textarea>%s</textarea>", Receive())) end Send("<h1>Info</h1><pre>\n") for k,v in pairs(Info) do Send(string.format("Info.%s = %s\n", k, v)) end Send("</pre><h1>Debug</h1><pre>\n") for k,v in pairs(ThreadData()) do Send(string.format("%s = %s\n", k, v)) end Send("</pre><h1>Config</h1><pre>\n") DumpTable(Config or {}, "Config") Send("</pre>") --[[ These are all the exposed functions/variables: -- VARIABLES -- Env -> FCGI Environment (table) Info -> State and Thread debug info Info.State = Id of Lua State that is "serving" us. Unique for each script. Info.Thread = Id of the thread that is "serving" us. Response -> Table of HTTP Status Codes Response[200] = "200 OK" Response[404] = "404 Not Found" -- FUNCTIONS -- Header("X-PoweredBy", "luafcgid2") -> Function to add a response header Send("abc") -> Function to add something to the response itself Reset() -> Reset the headers and response buffers Log("TODO: Fix this") -> Send something to the error log Receive() -> Read submitted data from the client (eg POST data) RespStatus(Response[403]) -> Change the response status RespContentType("text/plain") -> Change the response content-type ThreadData() -> Debug thread data information. Returns a table in which the keys are script names, and the values are the number of loaded scripts. ]] end <file_sep>--[[ Configuration script for luafcgid2 ]]-- -- Amount of worker threads WorkerThreads = 4 -- Number of default Lua states initially loaded LuaStates = 1 -- Max number of Lua states (will be loaded as needed, but will never unload) LuaMaxStates = 6 -- Max number of times to search for a free Lua state before creating a new ad-hoc one LuaMaxSearchRetries = 3 -- Starting buffer size for custom HTTP headers HeadersSize = 128 -- Starting buffer size for HTTP body BodySize = 2048 -- Starting buffer is split in [BodySectors] number of [BodySize] byte chunks -- Thanks to C++11, this method can vastly improve performance BodySectors = 4 -- Time (in ms) that we consider a file to be unchanged -- It is suggested to increase this value as your server needs to manage more users and is under heavier load -- Having more threads will kind of ignore this variable. MinFileInfoTime = 5000 -- Calculate a file's checksum to see if it changed -- It is only calculated at most every [MinFileInfoTime] ms UseFileChecksum = true -- Sets the cookie name for the session key. Must be lower-case. SessionName = "XLuaSession" -- For how much time should we keep the session data alive for, while unused? -- In seconds. SessionTime = 3600 -- Length (in bytes) of the generated Session Keys SessionKeyLen = 24 -- Transmit the session cookie through HTTPS-only? (Sets the Secure attribute) SessionCookieSecure = true -- Transmit the session cookie through HTTP only, disabling JS access? (Sets the HttpOnly attribute) SessionCookieHttpOnly = true -- Select a SameSite directive for cookies. Allowed values are: Strict, Lax. Leave empty for no SameSite directive. SessionCookieSameSite = "" -- Scoring system for Session Key attribution. This system helps to avoid Session Key hijacking. -- What's our score target? A score of >= SessionTargetScore will allow an user to proceed. -- To disable the Score System, set this variable to <= 0. SessionTargetScore = 3 -- How many "points" does a request gain if the IP address matches? SessionIpScore = 3 -- How many "points" does a request gain if the UserAgent matches? SessionUserAgentScore = 2 -- How many "points" does a request gain if the Language matches? SessionLanguageScore = 1 -- Custom HTTP headers. Will be added to every request. DefaultHeaders = "X-Powered-By: luafcgid2\r\n" -- Default HTTP status. DefaultHttpStatus = "200 OK" -- Default Content-Type DefaultContentType = "text/html" -- Max POST upload size allowed MaxPostSize = 1048576 -- 1MB -- Log File Path LogFilePath = "/var/log/luafcgid2/luafcgid2.log" -- Port or Socket path to listen to listen = "/var/tmp/luafcgid2.sock" -- Load this *file* at the top of all scripts -- Please note that this file is only loaded once. StartupScript = "" -- Entrypoint entrypoint = "main" -- Config table, can be accessed from the scripts. Config = { entrypoint = entrypoint, string_example = "Test config string", table_example = { "abc","def","ghi", number=42 } } <file_sep>#include "thread.h" #include "settings.h" #include "statepool.h" #include <fcgiapp.h> #include <mutex> std::mutex g_acceptMutex; void RunThread(int tid, int sock) { FCGX_Request request; FCGX_InitRequest(&request, sock, 0); LuaThreadCache cache; while(true) { g_acceptMutex.lock(); FCGX_Accept_r(&request); g_acceptMutex.unlock(); try { g_statepool.ExecMT(tid, request, cache); } catch(std::exception& e) { LogError(std::string("Thread-level exception: ") + e.what()); } catch(...) { LogError("Unknown thread-level exception."); } FCGX_Finish_r(&request); } } Thread::Thread(int thread_id, int sock) : m_thread_id(thread_id), m_sock(sock) {} void Thread::Spawn() { if(m_thread.joinable()) return; m_thread = std::thread(RunThread, m_thread_id, m_sock); }<file_sep># This file's only purpose is to shut up make when some folders are conflicting. all: <file_sep>#include "session.h" #include "settings.h" #include <mutex> #include <stdexcept> Session::Session(SessionManager*, std::string session, SessionDetectData const& sdd) : m_sessionKey(std::move(session)), m_sds(sdd) {} Session::RealmIterator Session::GetRealms(std::string const& realm, bool bCreate) { if(realm == "*") return Session::RealmIterator(m_realms.begin(), m_realms.end()); if(bCreate) { auto endIter = m_realms.emplace(std::make_pair(realm, Session::Realm())).first; auto begIter = endIter++; return Session::RealmIterator(begIter, endIter); } auto endIter = m_realms.find(realm); if(endIter == m_realms.end()) return Session::RealmIterator(endIter, endIter); auto begIter = endIter++; return Session::RealmIterator(begIter, endIter); } static inline std::time_t GetCurrentTimeT() { return Session::expiration_clock::to_time_t(Session::expiration_clock::now()); } void Session::Touch() { m_expiration = GetCurrentTimeT() + g_settings.m_sessionTime; } bool Session::IsValid() { return m_expiration.load() >= GetCurrentTimeT(); } void Session::Start() { Touch(); } bool Session::HasRealm(std::string const& realm) { Touch(); m_mutex.lock_read(); std::lock_guard<rw_mutex> mx(m_mutex, std::adopt_lock); return m_realms.find(realm) != m_realms.end(); } void Session::Clear(std::string const& realm) { Touch(); std::lock_guard<rw_mutex> mx(m_mutex); Session::RealmIterator realms = GetRealms(realm, false); std::size_t c = 0; for(auto it = realms.begin(); it != realms.end(); ++it, ++c) { it->second.clear(); } if(c == m_realms.size()) m_realms.clear(); } void Session::Delete() { m_expiration = 0; } bool Session::SetVar(std::string const& realm, std::string const& key, Lua::Variable* var) { Touch(); Lua::Bool* boolVar = nullptr; Lua::Number* numVar = nullptr; Lua::String* strVar = nullptr; Lua::ReturnValues vals; bool has_vals = false; if(!var) {} else if(var->IsBool(boolVar)) { vals = Lua::Return(boolVar->cget()); has_vals = true; } else if(var->IsNumber(numVar)) { vals = Lua::Return(numVar->cget()); has_vals = true; } else if(var->IsString(strVar)) { vals = Lua::Return(strVar->cget()); has_vals = true; } std::lock_guard<rw_mutex> mx(m_mutex); Session::RealmIterator realms = GetRealms(realm, true); if(has_vals) { for(auto it = realms.begin(); it != realms.end(); ++it) { it->second[key] = vals; } } else { for(auto it = realms.begin(); it != realms.end(); ++it) { auto dlk = it->second.find(key); if(dlk != it->second.end()) it->second.erase(dlk); } } return has_vals || (!var) || var->IsNil() || (var->GetType() == Lua::TP_NONE); } Lua::ReturnValues Session::GetVar(std::string const& realm, std::string const& key) { Touch(); m_mutex.lock_read(); std::lock_guard<rw_mutex> mx(m_mutex, std::adopt_lock); Session::RealmIterator realms = GetRealms(realm, false); for(auto it = realms.begin(); it != realms.end(); ++it) { auto itk = it->second.find(key); if(itk != it->second.end()) return itk->second; } return Lua::Return(); } // LuaSessionInterface LuaSessionInterface::LuaSessionInterface() : m_manager(nullptr), m_realSession(nullptr) {} bool LuaSessionInterface::getCookieString(std::string& s, std::string const& domain) const { if(!m_realSession || !m_realSession->IsValid()) { // We didn't have a session key to begin with. if(m_sdd.m_sessionKey.empty()) return false; // We deleted the session. s = g_settings.m_sessionName + "=_; Expires=Thu, 01 Jan 1970 00:00:00 GMT"; return true; } // Calc the expiration... std::tm gmt_time; std::time_t epoch_time = m_realSession->m_expiration.load(); gmtime_mx(epoch_time, gmt_time); char cookie_str_fmt[64]; std::strftime(cookie_str_fmt, sizeof(cookie_str_fmt), "%a, %d %b %Y %H:%M:%S GMT", &gmt_time); // We have a session! s = g_settings.m_sessionName + "=" + m_realSession->m_sessionKey + "; Expires=" + cookie_str_fmt + ";"; if(g_settings.m_sessionCookieHttpOnly) s.append(" HttpOnly;"); if(g_settings.m_sessionCookieSecure) s.append(" Secure;"); if(g_settings.m_sessionCookieSameSite == "Strict") s.append(" SameSite=Strict;"); else if(g_settings.m_sessionCookieSameSite == "Lax") s.append(" SameSite=Lax;"); s.append(" Path=/;"); if(!domain.empty()) { s.append(" Domain="); s.append(domain); s.append(";"); } return true; } void LuaSessionInterface::Init(SessionManager& manager, SessionDetectData const& sdd) { m_manager = &manager; m_realSession = manager.findSession(sdd); m_sdd = sdd; } void LuaSessionInterface::DeleteSessionTicket() { if(!m_realSession) return; if(!m_manager) throw std::runtime_error("No session manager in LuaSessionInterface!"); m_manager->DeleteSession(m_realSession); m_realSession = nullptr; } void LuaSessionInterface::CreateNewSessionTicket() { if(m_realSession) return; if(!m_manager) throw std::runtime_error("No session manager in LuaSessionInterface!"); m_realSession = m_manager->CreateSession(m_sdd); } bool LuaSessionInterface::read() const { return !!m_realSession; } void LuaSessionInterface::write() { CreateNewSessionTicket(); } void LuaSessionInterface::Start() { write(); m_realSession->Start(); } void LuaSessionInterface::Delete() { if(!read()) return; m_realSession->Delete(); DeleteSessionTicket(); } bool LuaSessionInterface::HasRealm(std::string const& realm) { if(!read()) return false; return m_realSession->HasRealm(realm); } void LuaSessionInterface::Clear(std::string const& realm) { if(!read()) return; m_realSession->Clear(realm); } bool LuaSessionInterface::SetVar(std::string const& realm, std::string const& key, Lua::Variable* val) { write(); return m_realSession->SetVar(realm, key, val); } Lua::ReturnValues LuaSessionInterface::GetVar(std::string const& realm, std::string const& key) { if(!read()) return Lua::Return(); return m_realSession->GetVar(realm, key); } // SessionManager SessionManager g_sessions; Session* SessionManager::CreateSession(SessionDetectData const& sdd) { std::lock_guard<rw_mutex> mx(m_mutex); std::string skey; while(true) { SessionManager::CreateSessionKey(skey); auto it = m_sessions.emplace(std::piecewise_construct, std::make_tuple(skey), std::make_tuple(this,skey,sdd)); if(it.second == true) return &(it.first->second); } } void SessionManager::CleanExpiredSessions() { std::lock_guard<rw_mutex> mx(m_mutex); for(auto it = m_sessions.begin(); it != m_sessions.end(); ) { if(!(it->second.IsValid())) { m_sessions.erase(it++); } else ++it; } } void SessionManager::DeleteSession(Session* session) { if(!session) return; std::lock_guard<rw_mutex> mx(m_mutex); auto it = m_sessions.find(session->m_sessionKey); if(it == m_sessions.end()) return; m_sessions.erase(it); } Session* SessionManager::findSession(SessionDetectData const& sdd) { auto it = m_sessions.begin(); { m_mutex.lock_read(); std::lock_guard<rw_mutex> mx(m_mutex, std::adopt_lock); it = m_sessions.find(sdd.m_sessionKey); if(it == m_sessions.end()) return nullptr; } it->second.m_mutex.lock_read(); std::lock_guard<rw_mutex> mx(it->second.m_mutex, std::adopt_lock); if(!sessionMatches(sdd, it->second.m_sds, true)) return nullptr; // Safety measure. The user identity doesn't seem to match! it->second.m_mutex.chlock_w(); it->second.m_sds = sdd; return &(it->second); } #include "randutils.hpp" typedef randutils::mt19937_rng random_generator; typedef std::uniform_int_distribution<char> random_distribution; static char const g_selCharacters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; static int const g_sc_first = 0; static int const g_sc_last = (sizeof(g_selCharacters) / sizeof(*g_selCharacters))-2; void SessionManager::CreateSessionKey(std::string& result) { int const klen = g_settings.m_sessionKeyLen; random_generator generator; result.resize(klen); for(int i = 0; i < klen; ++i) { result[i] = g_selCharacters[generator.uniform(g_sc_first, g_sc_last)]; } } <file_sep>#ifndef SESSION_H_INCLUDED #define SESSION_H_INCLUDED #include <string> #include <chrono> #include <ctime> #include "state.h" #include "rw_mutex.h" #include "settings.h" struct SessionDetectData { inline SessionDetectData() : m_sessionKey(), m_address(nullptr), m_useragent(nullptr), m_languages(nullptr) {} std::string m_sessionKey; char const* m_address; char const* m_useragent; char const* m_languages; }; struct SessionDetectStorage { inline SessionDetectStorage() {} inline SessionDetectStorage(SessionDetectData const& sdd) : m_sessionKey(sdd.m_sessionKey), m_address(sdd.m_address ? sdd.m_address : ""), m_useragent(sdd.m_useragent ? sdd.m_useragent : ""), m_languages(sdd.m_languages ? sdd.m_languages : "") {} std::string m_sessionKey; std::string m_address; std::string m_useragent; std::string m_languages; }; namespace impl { static char const g_empty[] = ""; template <typename T, typename U> struct str_chr_cmp; template <> struct str_chr_cmp<char const*, char const*> { static bool is_equal(char const* a, char const* b) { return ((!a) && (!b)) || ((!a) && b && (!b[0])) || ((!b) && a && (!a[0])) || (a && b && (strcmp(a,b)==0)); } }; template <> struct str_chr_cmp<std::string, char const*> { static bool is_equal(std::string const& a, char const* b) { return b ? a==b : a.empty(); } }; template <> struct str_chr_cmp<char const*, std::string> { static bool is_equal(char const* b, std::string const& a) { return b ? a==b : a.empty(); } }; template <> struct str_chr_cmp<std::string, std::string> { static bool is_equal(std::string const& a, std::string const& b) { return a==b; } }; template <typename A, typename B> bool is_equal(A const& a, B const& b) { return str_chr_cmp<A,B>::is_equal(a,b); } } template <typename T, typename U> bool sessionMatches(T const& a, U const& b, bool skipSessionKey = false) { return (skipSessionKey || impl::is_equal(a.m_sessionKey, b.m_sessionKey)) && (g_settings.m_sessionTargetScore <= 0 || ( ( ((impl::is_equal(a.m_address, b.m_address)) ? g_settings.m_sessionIpScore : 0) + ((impl::is_equal(a.m_useragent, b.m_useragent)) ? g_settings.m_sessionUserAgentScore : 0) + ((impl::is_equal(a.m_languages, b.m_languages)) ? g_settings.m_sessionLanguageScore : 0) ) >= g_settings.m_sessionTargetScore)); } class SessionManager; class LuaSessionInterface; class Session { friend class SessionManager; friend class LuaSessionInterface; public: typedef std::chrono::system_clock expiration_clock; typedef std::map<std::string, Lua::ReturnValues> Realm; private: rw_mutex m_mutex; std::map<std::string, Realm> m_realms; std::atomic<std::time_t> m_expiration; std::string m_sessionKey; SessionDetectStorage m_sds; struct RealmIterator { inline RealmIterator( std::map<std::string, Realm>::iterator beg, std::map<std::string, Realm>::iterator end ) : b(beg), e(end) {} std::map<std::string, Realm>::iterator b; std::map<std::string, Realm>::iterator e; std::map<std::string, Realm>::iterator begin() const { return b; } std::map<std::string, Realm>::iterator end() const { return e; } }; // DOES NOT LOCK! RealmIterator GetRealms(std::string const& realm, bool bCreate); // DOES NOT LOCK! void Touch(); public: Session(SessionManager*, std::string, SessionDetectData const&); bool IsValid(); void Start(); void Delete(); bool HasRealm(std::string const& realm); void Clear(std::string const& realm); bool SetVar(std::string const& realm, std::string const& var, Lua::Variable* data); Lua::ReturnValues GetVar(std::string const& realm, std::string const& var); bool Matches(SessionDetectData*); }; class LuaSessionInterface { SessionManager* m_manager; Session* m_realSession; SessionDetectData m_sdd; void CreateNewSessionTicket(); void DeleteSessionTicket(); void write(); bool read() const; public: LuaSessionInterface(); void Init(SessionManager&, SessionDetectData const&); bool hasRealSession() const; void Start(); void Delete(); bool HasRealm(std::string const& realm); void Clear(std::string const& realm); bool SetVar(std::string const& realm, std::string const& var, Lua::Variable* data); Lua::ReturnValues GetVar(std::string const& realm, std::string const& var); bool getCookieString(std::string&, std::string const& domain) const; }; class SessionManager { rw_mutex m_mutex; std::map<std::string, Session> m_sessions; // Create a new Session Key. static void CreateSessionKey(std::string&); public: // Remove all the expired sessions. void CleanExpiredSessions(); // Create a new empty session Session* CreateSession(SessionDetectData const& sdd); // Delete a session's data void DeleteSession(Session*); // Find an existing session Session* findSession(SessionDetectData const&); }; extern SessionManager g_sessions; #endif
bde98e707e580788b6fcc182b039f667e0a8e267
[ "Markdown", "Makefile", "C++", "Lua" ]
22
C++
EssGeeEich/luafcgid2
1e8f65218769679abe6c928058715449261021f0
450d3b2e54c54c10f263c4a50d638e34854859a6
refs/heads/staging
<file_sep>import alt from "alt-instance"; let ErrorActions = class { emitError(msg: string, callback) { return { msg, callback }; } } ErrorActions = alt.createActions(ErrorActions); export { ErrorActions }; export default ErrorActions;<file_sep>webpackJsonp([3], { 1076: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t), (this._linetool = o), this.prepareLayout(); } var n = o(238), a = n.PropertyPage, r = n.GreateTransformer, l = n.LessTransformer, p = n.ToIntTransformer, s = n.SimpleStringBinder; o(241), inherit(i, a), (i.BarIndexPastLimit = -5e4), (i.BarIndexFutureLimit = 15e3), (i.prototype.bindBarIndex = function(e, t, o, n) { var a = [ p(e.value()), r(i.BarIndexPastLimit), l(i.BarIndexFutureLimit) ]; this.bindControl(this.createStringBinder(t, e, a, !0, o, n)); }), (i.prototype.createPriceEditor = function(e) { var t, o, i, n = this._linetool, a = n.ownerSource().formatter(), r = function(e) { return a.format(e); }, l = function(e) { var t = a.parse(e); if (t.res) return t.price ? t.price : t.value; }, p = $("<input type='text'>"); return ( p.TVTicker({ step: a._minMove / a._priceScale || 1, formatter: r, parser: l }), e && ((t = [ function(t) { var o = l(t); return void 0 === o ? e.value() : o; } ]), (o = "Change " + n.title() + " point price"), (i = this.createStringBinder(p, e, t, !1, this.model(), o)), i.addFormatter(function(e) { return a.format(e); }), this.bindControl(i)), p ); }), (i.prototype._createPointRow = function(e, t, o) { var i, n, a, r, l, p = $("<tr>"), s = $("<td>"); return ( s.html($.t("Price") + o), s.appendTo(p), (i = $("<td>")), i.appendTo(p), (n = this.createPriceEditor(t.price)), n.appendTo(i), (a = $("<td>")), a.html($.t("Bar #")), a.appendTo(p), (r = $("<td>")), r.appendTo(p), (l = $("<input type='text'>")), l.appendTo(r), l.addClass("ticker"), this.bindBarIndex( t.bar, l, this.model(), "Change " + this._linetool.title() + " point bar index" ), p ); }), (i.prototype.prepareLayoutForTable = function(e) { var t, o, i, n, a, r = this._linetool.points(), l = r.length; for (t = 0; t < r.length; t++) (o = r[t]), (i = this._linetool.properties().points[t]) && ((n = t || l > 1 ? " " + (t + 1) : ""), (a = this._createPointRow(o, i, n)), a.appendTo(e)); }), (i.prototype.prepareLayout = function() { (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.prepareLayoutForTable(this._table), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (i.prototype.createStringBinder = function(e, t, o, i, n, a) { return new s(e, t, o, i, n, a); }), (e.exports = i); }, 1078: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.BooleanBinder, p = a.SliderBinder, s = a.ColorBinding, d = a.SimpleComboBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t) { var o, i, n, a, p, d = t || $("<tr>").appendTo(this._table), c = $("<td>"); return ( c.appendTo(d), (o = $("<input type='checkbox' class='visibility-switch'>")), o.appendTo(c), t && o.css("margin-left", "15px"), (i = $("<td>")), i.appendTo(d), (n = $("<input type='text'>")), n.appendTo(i), n.css("width", "70px"), this.bindControl( new r(n, e.coeff, !1, this.model(), "Change Pitchfork Line Coeff") ), (a = $("<td class='colorpicker-cell'>")), a.appendTo(d), (p = h(a)), this.bindControl( new l( o, e.visible, !0, this.model(), "Change Fib Retracement Line Visibility" ) ), this.bindControl( new s( p, e.color, !0, this.model(), "Change Fib Retracement Line Color", 0 ) ), d ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, C, y, g, T, w, _, m, f, L, v, k, S, P, x, B, R, E, F, I, D, A, W, V, O, z, M; for ( this._div = $(document.createElement("div")).addClass( "property-page" ), e = this._linetool.properties().trendline, t = $("<table>") .appendTo(this._div) .css("padding-bottom", "3px"), e && ((o = $("<tr>").appendTo(t)), (i = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(i) .appendTo(o), $("<td>") .append($.t("Trend Line")) .appendTo(o), this.bindControl( new l( i, e.visible, !0, this.model(), "Change Fib Retracement Line Visibility" ) ), (n = $("<td class='colorpicker-cell'>").appendTo(o)), (a = h(n)), this.bindControl( new s( a, e.color, !0, this.model(), "Change Fib Retracement Line Color", 0 ) ), (r = $("<td>").appendTo(o)), (C = b()), C.appendTo(r), this.bindControl( new p( C, e.linewidth, parseInt, this.model(), "Change Fib Retracement Line Width" ) ), (y = $("<td>").appendTo(o)), (g = c()), g.render().appendTo(y), this.bindControl( new d( g, e.linestyle, parseInt, !0, this.model(), "Change Fib Retracement Line Style" ) )), T = this._linetool.properties().levelsStyle, w = $("<tr>").appendTo(t), $("<td>").appendTo(w), $("<td>" + $.t("Levels Line") + "</td>").appendTo(w), $("<td>").appendTo(w), r = $("<td>").appendTo(w), C = b(), C.appendTo(r), this.bindControl( new p( C, T.linewidth, parseInt, this.model(), "Change Fib Retracement Line Width" ) ), y = $("<td>").appendTo(w), g = c(), g.render().appendTo(y), this.bindControl( new d( g, T.linestyle, parseInt, !0, this.model(), "Change Fib Retracement Line Style" ) ), this._table = $(document.createElement("table")).appendTo( this._div ), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), _ = {}, m = 0; m < 24; m++ ) (f = m % 8), (w = _[f]), (L = "level" + (m + 1)), (_[f] = this.addLevelEditor(this._linetool.properties()[L], w)); this.addOneColorPropertyWidget(this._table), (v = $("<table cellpadding=0 cellspacing=0>").appendTo(this._div)), (k = $("<tr>").appendTo(v)), this._linetool.properties().extendLines && ((S = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(S) .append($.t("Extend Lines"))), $("<td>") .append(P) .appendTo(k)), this._linetool.properties().extendLeft && ((x = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(x) .append($.t("Extend Left"))), $("<td>") .append(P) .appendTo(k)), this._linetool.properties().extendRight && ((B = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(B) .append($.t("Extend Right"))), $("<td>") .append(P) .appendTo(k)), this._linetool.properties().reverse && ((R = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(R) .append($.t("Reverse"))), $("<td>") .append(P) .appendTo(k)), (E = $("<tr>").appendTo(v)), (F = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(F) .append($.t("Levels"))), $("<td>") .append(P) .appendTo(E), (I = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(I) .append($.t("Prices"))), $("<td>") .append(P) .appendTo(E), (D = $("<input type='checkbox' class='visibility-switch'>")), (P = $("<label>") .append(D) .append($.t("Percents"))), $("<td>") .append(P) .appendTo(E), (A = $("<table cellspacing='0' cellpadding='0'>").appendTo( this._div )), (W = $( "<select><option value='left'>" + $.t("left") + "</option><option value='center'>" + $.t("center") + "</option><option value='right'>" + $.t("right") + "</option></select>" )), (V = $( "<select><option value='bottom'>" + $.t("top") + "</option><option value='middle'>" + $.t("middle") + "</option><option value='top'>" + $.t("bottom") + "</option></select>" )), (w = $("<tr>")), w .append("<td>" + $.t("Labels") + "</td>") .append(W) .append("<td>&nbsp</td>") .append(V), w.appendTo(A), (O = $("<table cellspacing='0' cellpadding='0'>").appendTo( this._div )), (w = $("<tr>").appendTo(O)), (z = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(z) .appendTo(w), this.createLabeledCell($.t("Background"), z).appendTo(w), (M = u()), $("<td>") .append(M) .appendTo(w), this.bindControl( new l( I, this._linetool.properties().showPrices, !0, this.model(), "Change Gann Fan Prices Visibility" ) ), this.bindControl( new l( F, this._linetool.properties().showCoeffs, !0, this.model(), "Change Gann Fan Levels Visibility" ) ), this.bindControl( new l( z, this._linetool.properties().fillBackground, !0, this.model(), "Change Fib Retracement Background Visibility" ) ), this.bindControl( new p( M, this._linetool.properties().transparency, !0, this.model(), "Change Fib Retracement Background Transparency" ) ), this._linetool.properties().extendLines && this.bindControl( new l( S, this._linetool.properties().extendLines, !0, this.model(), "Change Fib Retracement Extend Lines" ) ), this._linetool.properties().extendLeft && this.bindControl( new l( x, this._linetool.properties().extendLeft, !0, this.model(), "Change Fib Retracement Extend Lines" ) ), this._linetool.properties().extendRight && this.bindControl( new l( B, this._linetool.properties().extendRight, !0, this.model(), "Change Fib Retracement Extend Lines" ) ), this._linetool.properties().reverse && this.bindControl( new l( R, this._linetool.properties().reverse, !0, this.model(), "Change Fib Retracement Reverse" ) ), this.bindControl( new d( W, this._linetool.properties().horzLabelsAlign, null, !0, this.model(), "Change Fib Labels Horizontal Alignment" ) ), this.bindControl( new d( V, this._linetool.properties().vertLabelsAlign, null, !0, this.model(), "Change Fib Labels Vertical Alignment" ) ), this.bindControl( new l( D, this._linetool.properties().coeffsAsPercents, !0, this.model(), "Change Fib Retracement Coeffs As Percents" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._div; }), (e.exports = i); }, 1083: function(e, t, o) { "use strict"; (function(t) { function i(e, t, o) { var i, n, a = t.m_model.properties(); l.call(this, a, t), (i = this._series = t.mainSeries()), (this._chart = t.m_model), (this._model = t), (this._source = o), (this._property = a), (this._seriesProperty = i.properties()), (this._scaleProperty = i.priceScale().properties()), (this._mainSeriesScaleRatioProperty = t.mainSeriesScaleRatioProperty()), (n = null), t.m_model.panes().forEach(function(e) { e.dataSources().forEach(function(t) { if (t === i) return (n = e), !1; }); }), (this._pane = n), this.prepareLayout(), (this._themes = []), (this.supportThemeSwitcher = !1); } var n = o(1234), a = o(1201), r = o(238), l = r.PropertyPage, p = r.GreateTransformer, s = r.LessTransformer, d = r.ToIntTransformer, h = r.SimpleStringBinder, c = r.BooleanBinder, b = r.SliderBinder, u = r.ColorBinding, C = r.SimpleComboBinder, y = r.DisabledBinder, g = r.CheckboxWVBinding, T = r.ToFloatTransformerWithDynamicDefaultValue, w = r.ToFloatLimitedPrecisionTransformer, _ = o(49), m = o(22), f = o(372).addColorPicker, L = o(1197).createLineStyleEditor, v = o(1196).createLineWidthEditor, k = (o(133).bindPopupMenu, o(6).DefaultProperty), S = o(171).availableTimezones, P = o(248), x = (o(112).createConfirmDialog, o(40).trackEvent); inherit(i, l), inherit(i, n), (i.prototype.setScalesOpenTab = function() { this.scalesTab && this.scalesTab.data("layout-tab-open", a.TabOpenFrom.Override); }), (i.prototype.setTmzOpenTab = function() { this.tmzSessTable && this.tmzSessTable.data("layout-tab-open", a.TabOpenFrom.Override); }), (i.prototype.prepareLayout = function() { var e, o, i, n, r, l, k, B, R, E, F, I, D, A, W, V, O, z, M, j, H, G, N, U, q, Y, K, Q, J, Z, X, ee, te, oe, ie, ne, ae, re, le, pe, se, de, he, ce, be, ue, Ce, ye, ge, $e, Te, we, _e, me, fe, Le, ve, ke, Se, Pe, xe, Be, Re, Ee, Fe, Ie, De, Ae, We, Ve, Oe, ze, Me, je, He, Ge, Ne, Ue, qe, Ye, Ke, Qe, Je, Ze, Xe, et, tt, ot, it, nt, at, rt, lt, pt, st, dt, ht, ct, bt, ut, Ct, yt, gt, $t, Tt, wt, _t, mt, ft, Lt, vt, kt, St, Pt, xt, Bt, Rt, Et, Ft, It, Dt, At, Wt, Vt, Ot, zt, Mt, jt = this; if ( (t.enabled("chart_property_page_style") && ((e = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), (o = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), (i = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), this._prepareSeriesStyleLayout(e, o, i, this._seriesProperty), (this._hasSeriesStyleLayout = !0), (l = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), (W = $('<input type="checkbox">')), (V = this.addLabeledRow(l, $.t("Price Line"), W)), $("<td>") .append(W) .prependTo(V), this.bindControl( new c( W, this._seriesProperty.showPriceLine, !0, this.model(), "Change Price Price Line" ) ), (O = f($("<td>").appendTo(V))), this.bindControl( new u( O, this._seriesProperty.priceLineColor, !0, this.model(), "Change Price Line Color" ) ), (z = v()), $('<td colspan="2">') .append(z) .appendTo(V), this.bindControl( new b( z, this._seriesProperty.priceLineWidth, !0, this.model(), "Change Price Line Width" ) ), (B = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), this._pane && (-1 !== this._pane .leftPriceScale() .dataSources() .indexOf(this._series) ? (M = "left") : -1 !== this._pane .rightPriceScale() .dataSources() .indexOf(this._series) ? (M = "right") : this._pane.isOverlay(this._series) && (M = "none")), M && ((j = { left: $.t("Scale Left"), right: $.t("Scale Right") }), jt._pane.actionNoScaleIsEnabled(jt._series) && (j.none = $.t("Screen (No Scale)")), (H = this.createKeyCombo(j) .val(M) .change(function() { switch (this.value) { case "left": jt._model.move( jt._series, jt._pane, jt._pane.leftPriceScale() ); break; case "right": jt._model.move( jt._series, jt._pane, jt._pane.rightPriceScale() ); break; case "none": jt._model.move(jt._series, jt._pane, null); } })), (G = this.addRow(B)), $("<td>" + $.t("Scale") + "</td>").appendTo(G), $("<td>") .appendTo(G) .append(H))), t.enabled("chart_property_page_scales") && ((N = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.scales)), (U = $('<input type="checkbox">').change(function() { this.checked && setTimeout(function() { jt._model.m_model.invalidate(new m(m.LIGHT_UPDATE)); }, 0); })), (q = this.addLabeledRow(N, $.t("Auto Scale"), U)), (Y = function(e) { this._undoModel.setAutoScaleProperty( this._property, e, jt._series.priceScale(), this._undoText ); }), $("<td>") .append(U) .prependTo(q), this.bindControl( new c( U, this._scaleProperty.autoScale, !0, this.model(), "Auto Scale", Y ) ), this.bindControl( new y( U, this._scaleProperty.autoScaleDisabled, !0, this.model(), "Auto Scale" ) ), (K = $('<input type="checkbox">')), (Q = this.addLabeledRow(N, $.t("Percentage"), K)), (J = function(e) { this._undoModel.setPercentProperty( this._property, e, jt._series.priceScale(), this._undoText ); }), $("<td>") .append(K) .prependTo(Q), this.bindControl( new c( K, this._scaleProperty.percentage, !0, this.model(), "Scale Percentage", J ) ), this.bindControl( new y( K, this._scaleProperty.percentageDisabled, !0, this.model(), "Scale Percentage" ) ), (Z = $('<input type="checkbox">')), (X = this.addLabeledRow(N, $.t("Log Scale"), Z)), (ee = function(e) { this._undoModel.setLogProperty( this._property, e, jt._series.priceScale(), this._undoText ); }), $("<td>") .append(Z) .prependTo(X), this.bindControl( new c( Z, this._scaleProperty.log, !0, this.model(), "Log Scale", ee ) ), this.bindControl( new y( Z, this._scaleProperty.logDisabled, !0, this.model(), "Log Scale" ) ), (te = $('<input type="checkbox">').change(function() { this.checked && setTimeout(function() { jt._model.m_model.invalidate(new m(m.LIGHT_UPDATE)); }, 0); })), (oe = this.addLabeledRow(N, $.t("Scale Series Only"), te)), $("<td>") .append(te) .prependTo(oe), this.bindControl( new c( te, this._property.scalesProperties.scaleSeriesOnly, !0, this.model(), "Scale Series Only" ) ), (ie = $("<input type='checkbox'/>")), (ne = this.addLabeledRow(N, $.t("Lock scale"), ie)), (ae = function(e) { this._undoModel.setLockScaleProperty( this._property, e, jt._series, this._undoText ); }), (re = function(e) { ne.toggle(e.value() === _.STYLE_PNF); }), $("<td>") .append(ie) .prependTo(ne), this.bindControl( new c( ie, this._scaleProperty.lockScale, !0, this.model(), "Change lock scale", ae ) ), this._seriesProperty.style.listeners().subscribe(this, re), t.enabled("support_multicharts") && ((le = $("<input type='checkbox'/>")), (pe = this.addLabeledRow(N, $.t("Track time"), le)), $("<td>") .append(le) .prependTo(pe), this.bindControl( new g( le, this._model.trackTime(), null, this.model(), "Change track time" ) )), (se = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.scales)), (de = $( '<input type="text" class="ticker ticker--longer-sign_8">' )), (he = this.addLabeledRow(se, $.t("Top Margin"), de)), $("<td>") .appendTo(he) .append(de), $("<td>%</td>").appendTo(he), (ce = [d(this._property.paneProperties.topMargin.value())]), ce.push(s(25)), ce.push(p(0)), this.bindControl( new h( de, this._property.paneProperties.topMargin, ce, !0, this.model(), "Top Margin" ) ), (be = $( '<input type="text" class="ticker ticker--longer-sign_8">' )), (ue = this.addLabeledRow(se, $.t("Bottom Margin"), be)), $("<td>") .appendTo(ue) .append(be), $("<td>%</td>").appendTo(ue), (Ce = [d(this._property.paneProperties.bottomMargin.value())]), Ce.push(s(25)), Ce.push(p(0)), this.bindControl( new h( be, this._property.paneProperties.bottomMargin, Ce, !0, this.model(), "Bottom Margin" ) ), (ye = $( '<input type="text" class="ticker ticker--longer-sign_8">' )), (ge = this.addLabeledRow(se, $.t("Right Margin"), ye)), $("<td>") .appendTo(ge) .append(ye), $("<td>" + $.t("bars", { context: "margin" }) + "</td>").appendTo( ge ), ($e = this._chart.timeScale()), (Te = [d($e.defaultRightOffsetProperty().value())]), Te.push(s(~~$e.maxRightOffset())), Te.push(p(0)), this.bindControl( new h( ye, $e.defaultRightOffsetProperty(), Te, !0, this.model(), "Right Margin" ) ), (we = $( '<input type="text" class="ticker ticker--longer-sign_8">' )), (ge = this.addLabeledRow(se, $.t("Price/Bar Ratio"), we)), (_e = !0), (me = function(e) { this._undoModel.setScaleRatioProperty( this._property, e, jt._series, this._undoText ), _e && (x("GUI", "Scales", "Edit scale ratio value"), (_e = !1)); }), $("<td>") .appendTo(ge) .append(we), we.TVTicker({ step: this._mainSeriesScaleRatioProperty.getStepChangeValue() }), (fe = w("", 7)), (Le = [ T( this._mainSeriesScaleRatioProperty.value.bind( this._mainSeriesScaleRatioProperty ) ), p(this._mainSeriesScaleRatioProperty.getMinValue()), s(this._mainSeriesScaleRatioProperty.getMaxValue()), fe ]), (ve = new h( we, this._mainSeriesScaleRatioProperty, Le, !1, this.model(), "Price/Bar Ratio", me )), ve.addFormatter(fe), this.bindControl(ve), (ke = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.scales)), (Se = $("<input type='checkbox' />")), (Pe = this.addLabeledRow(ke, $.t("Left Axis"), Se)), $("<td>") .append(Se) .prependTo(Pe), setTimeout( function() { this.bindControl( new c( Se, this._property.scalesProperties.showLeftScale, !0, this.model(), "Show Left Axis" ) ); }.bind(this), 0 ), (xe = $("<input type='checkbox' />")), (Be = this.addLabeledRow(ke, $.t("Right Axis"), xe)), $("<td>") .append(xe) .prependTo(Be), setTimeout( function() { this.bindControl( new c( xe, this._property.scalesProperties.showRightScale, !0, this.model(), "Show Right Axis" ) ); }.bind(this), 0 ), t.enabled("countdown") && ((Re = $("<input type='checkbox'>")), (Ee = this.addLabeledRow(ke, $.t("Countdown"), Re)), $("<td>") .append(Re) .prependTo(Ee), this.bindControl( new c( Re, this._seriesProperty.showCountdown, !0, this.model(), "Change Show Countdown" ) )), (Fe = $('<input type="checkbox">')), (Ie = this.addLabeledRow(ke, $.t("Symbol Last Value"), Fe)), $("<td>") .append(Fe) .prependTo(Ie), this.bindControl( new c( Fe, this._property.scalesProperties.showSeriesLastValue, !0, this.model(), "Change Symbol Last Value Visibility" ) ), (De = $('<input type="checkbox">')), (Ae = this.addLabeledRow(ke, $.t("Indicator Last Value"), De)), $("<td>") .append(De) .prependTo(Ae), this.bindControl( new c( De, this._property.scalesProperties.showStudyLastValue, !0, this.model(), "Change Indicator Last Value Visibility" ) ), (We = $('<input type="checkbox">')), (Ve = this.addLabeledRow(ke, $.t("Symbol Labels"), We)), $("<td>") .append(We) .prependTo(Ve), this.bindControl( new c( We, this._property.scalesProperties.showSymbolLabels, !0, this.model(), "Show Symbol Labels" ) ), (Oe = $('<input type="checkbox">')), (ze = this.addLabeledRow(ke, $.t("Indicator Labels"), Oe)), $("<td>") .append(Oe) .prependTo(ze), this.bindControl( new c( Oe, this._property.scalesProperties.showStudyPlotLabels, !0, this.model(), "Show Study Plots Labels" ) ), (Me = $("<input type='checkbox' />")), (je = this.addLabeledRow(ke, $.t("No Overlapping Labels"), Me)), $("<td>") .append(Me) .prependTo(je), this.bindControl( new c( Me, this._scaleProperty.alignLabels, !0, this.model(), "No Overlapping Labels" ) ), (He = $('<div class="property-page-column-2">') .append(N) .append(se)), (Ge = $('<div class="property-page-column-2">').append(ke)), (R = $("<div>") .css("min-width", "520px") .data("layout-tab", a.TabNames.scales)), R.append(He).append(Ge), (this.scalesTab = R), (k = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.style)), (Ne = this.createSeriesMinTickEditor()), (Ue = $("<tr>")), (qe = $("<tr>").appendTo(ke)), (Ye = $('<td colspan="2">').appendTo(qe)), $("<td>" + $.t("Decimal Places") + "</td>").appendTo(Ue), $("<td>") .append(Ne) .appendTo(Ue), k.append(Ue).appendTo(Ye), this.bindControl( new C( Ne, this._seriesProperty.minTick, null, !0, this.model(), "Change Decimal Places" ) )), t.enabled("chart_property_page_background") && ((Ke = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (Qe = this.createColorPicker({ hideTransparency: !0 })), (Je = this.addLabeledRow(Ke, $.t("Background"))), $('<td colspan="2">') .append(Qe) .appendTo(Je), this.bindControl( new u( Qe, this._property.paneProperties.background, !0, this.model(), "Change Chart Background Color" ) ), (Ze = this.addLabeledRow(Ke, $.t("Vert Grid Lines"))), (Xe = this.createColorPicker()), $("<td>") .append(Xe) .appendTo(Ze), this.bindControl( new u( Xe, this._property.paneProperties.vertGridProperties.color, !0, this.model(), "Change Vert Grid Lines Color" ) ), (et = L()), $('<td colspan="2">') .append(et.render()) .appendTo(Ze), this.bindControl( new C( et, this._property.paneProperties.vertGridProperties.style, parseInt, !0, this.model(), "Change Vert Grid Lines Style" ) ), (tt = this.addLabeledRow(Ke, $.t("Horz Grid Lines"))), (ot = this.createColorPicker()), $("<td>") .append(ot) .appendTo(tt), this.bindControl( new u( ot, this._property.paneProperties.horzGridProperties.color, !0, this.model(), "Change Horz Grid Lines Color" ) ), (it = L()), $('<td colspan="2">') .append(it.render()) .appendTo(tt), this.bindControl( new C( it, this._property.paneProperties.horzGridProperties.style, parseInt, !0, this.model(), "Change Horz Grid Lines Style" ) ), (nt = this.createColorPicker()), (at = this.addLabeledRow(Ke, $.t("Scales Text"))), $("<td>") .append(nt) .appendTo(at), this.bindControl( new u( nt, this._property.scalesProperties.textColor, !0, this.model(), "Change Scales Text Color" ) ), (rt = this.createFontSizeEditor()), $("<td>") .append(rt) .appendTo(at), this.bindControl( new C( rt, this._property.scalesProperties.fontSize, parseInt, !0, this.model(), "Change Scales Font Size" ) ), (lt = this.createColorPicker()), (pt = this.addLabeledRow(Ke, $.t("Scales Lines"))), $('<td colspan="2">') .append(lt) .appendTo(pt), this.bindControl( new u( lt, this._property.scalesProperties.lineColor, !0, this.model(), "Change Scales Lines Color" ) ), (st = this.addLabeledRow(Ke, $.t("Watermark"))), (dt = this.createColorPicker()), $("<td>") .append(dt) .appendTo(st), this.bindControl( new u( dt, this._property.symbolWatermarkProperties.color, !0, this.model(), "Change Symbol Watermark Color", this._property.symbolWatermarkProperties.transparency ) ), (ht = this.addLabeledRow(Ke, $.t("Crosshair"))), (ct = this.createColorPicker()), $("<td>") .append(ct) .appendTo(ht), this.bindControl( new u( ct, this._property.paneProperties.crossHairProperties.color, !0, this.model(), "Change Crosshair Color", this._property.paneProperties.crossHairProperties.transparency ) ), (bt = L()), $("<td>") .append(bt.render()) .appendTo(ht), this.bindControl( new C( bt, this._property.paneProperties.crossHairProperties.style, parseInt, !0, this.model(), "Change Crosshair Style" ) ), (ut = v()), $("<td>") .append(ut) .appendTo(this.addRow(Ke).prepend("<td/><td/>")), this.bindControl( new b( ut, this._property.paneProperties.crossHairProperties.width, !0, this.model(), "Change Crosshair Width" ) ), (Ct = $('<table class="property-page">')), (yt = this.addLabeledRow( Ct, $.t("Navigation Buttons"), null, !0 )), (gt = $(document.createElement("select"))), P.availableValues().forEach(function(e) { $(document.createElement("option")) .attr("value", e.value) .text(e.title) .appendTo(gt); }), $("<td>") .append(gt) .appendTo(yt), this.bindControl( new C( gt, P.property(), null, !0, this.model(), "Change Navigation Buttons Visibility" ) ), ($t = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (Tt = $('<input type="checkbox">')), (wt = this.addLabeledRow($t, $.t("Symbol Description"), Tt)), $("<td>") .append(Tt) .prependTo(wt), this.bindControl( new c( Tt, this._property.paneProperties.legendProperties.showSeriesTitle, !0, this.model(), "Change Symbol Description Visibility" ) ), (_t = $('<input type="checkbox">')), (mt = this.addLabeledRow($t, $.t("OHLC Values"), _t)), $("<td>") .append(_t) .prependTo(mt), this.bindControl( new c( _t, this._property.paneProperties.legendProperties.showSeriesOHLC, !0, this.model(), "Change OHLC Values Visibility" ) ), (ft = $('<input type="checkbox">')), (Lt = this.addLabeledRow($t, $.t("Indicator Titles"), ft)), $("<td>") .append(ft) .prependTo(Lt), this.bindControl( new c( ft, this._property.paneProperties.legendProperties.showStudyTitles, !0, this.model(), "Change Indicator Titles Visibility" ) ), (vt = $('<input type="checkbox">')), (kt = this.addLabeledRow($t, $.t("Indicator Arguments"), vt)), (St = function(e) { vt.prop("disabled", !e.value()); }), $("<td>") .append(vt) .prependTo(kt), this.bindControl( new c( vt, this._property.paneProperties.legendProperties.showStudyArguments, !0, this.model(), "Change Indicator Arguments Visibility" ) ), this._property.paneProperties.legendProperties.showStudyTitles .listeners() .subscribe(this, St), St( this._property.paneProperties.legendProperties.showStudyTitles ), (Pt = $('<input type="checkbox">')), (xt = this.addLabeledRow($t, $.t("Indicator Values"), Pt)), $("<td>") .append(Pt) .prependTo(xt), this.bindControl( new c( Pt, this._property.paneProperties.legendProperties.showStudyValues, !0, this.model(), "Change Indicator Values Visibility" ) ), (Bt = $('<div class="property-page-column-2">').append(Ke)), (Rt = $('<div class="property-page-column-2">').append($t)), (Et = $('<div class="property-page-column-1">').append(Ct)), (E = $("<div>") .css("min-width", "520px") .data("layout-tab", a.TabNames.background)), E.append(Bt) .append(Rt) .append(Et)), t.enabled("chart_property_page_timezone_sessions")) ) { for ( I = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.timezoneSessions), this.tmzSessTable = I, ge = $("<tr>").appendTo(I), Ft = $("<td>").appendTo(ge), It = $('<table cellspacing="0" cellpadding="0">').appendTo(Ft), Dt = $("<tr>"), Dt.appendTo(It), At = $("<td>"), At.appendTo(Dt), At.text($.t("Time Zone")), Wt = $('<td colspan="2" class="tzeditor">'), Wt.appendTo(Dt), Vt = "", Ot = 0; Ot < S.length; Ot++ ) Vt += '<option value="' + S[Ot].id + '">' + S[Ot].title + "</option>"; (zt = $("<select>" + Vt + "</select>")), zt.appendTo(Wt), this.bindControl( new C( zt, this._property.timezone, null, !0, this.model(), "Change Timezone" ) ), this._series.createSessStudy(), this.createSessTable(I); } (Mt = t.enabled("trading_options") || t.enabled("chart_property_page_trading")), Mt && (D = this.createTradingTable()), (n = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (r = $( '<table class="property-page property-page-unpadded" cellspacing="0" cellpadding="0">' ) .css({ width: "100%" }) .data("layout-separated", !0)), (F = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.drawings)), (this._table = $() .add(e) .add(o) .add(i) .add(n) .add(r) .add(l) .add(B) .add(R) .add(E) .add(F) .add(I) .add(D) .add(A)), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (i.prototype.loadData = function() { this.superclass.prototype.loadData.call(this), this.switchStyle(); }), (i.prototype.loadTheme = function(e, t, o) {}), (i.prototype.applyTheme = function(e, t) { this._model._chartWidget._chartWidgetCollection.applyTheme(e, t), this.loadData(); }), (i.prototype.createTemplateButton = function(e) { return t.enabled("chart_property_page_template_button") ? (this, e || (e = {}), $( '<a href="#" class="_tv-button">' + $.t("Template") + '<span class="icon-dropdown"></span></a>' )) : $("<span />"); }), (i.prototype.switchStyle = function() { if (this._hasSeriesStyleLayout) switch ( ($(this._barsTbody) .add(this._barsColorerTbody) .add(this._renkoTbody) .add(this._pbTbody) .add(this._kagiTbody) .add(this._pnfTbody) .add(this._candlesTbody) .add(this._candlesColorerTbody) .add(this._hollowCandlesTbody) .add(this._lineTbody) .add(this._areaTbody) .add(this._haTbody) .add(this._haColorerTbody) .add(this._baselineTbody) .css("display", "none"), this._seriesProperty.style.value()) ) { case _.STYLE_BARS: this._barsTbody.css("display", "table-row-group"), this._barsColorerTbody.css("display", "table-row-group"); break; case _.STYLE_CANDLES: this._candlesTbody.css("display", "table-row-group"), this._candlesColorerTbody.css("display", "table-row-group"); break; case _.STYLE_HOLLOW_CANDLES: this._hollowCandlesTbody.css("display", "table-row-group"); break; case _.STYLE_LINE: this._lineTbody.css("display", "table-row-group"); break; case _.STYLE_AREA: this._areaTbody.css("display", "table-row-group"); break; case _.STYLE_RENKO: this._renkoTbody.css("display", "table-row-group"); break; case _.STYLE_PB: this._pbTbody.css("display", "table-row-group"); break; case _.STYLE_KAGI: this._kagiTbody.css("display", "table-row-group"); break; case _.STYLE_PNF: this._pnfTbody.css("display", "table-row-group"); break; case _.STYLE_HEIKEN_ASHI: this._haTbody.css("display", "table-row-group"), this._haColorerTbody.css("display", "table-row-group"); break; case _.STYLE_BASELINE: this._baselineTbody.css("display", "table-row-group"); } }), (i.prototype.onResoreDefaults = function() { var e, t, o = this._model.model().properties().paneProperties.topMargin, i = this._model.model().properties().paneProperties.bottomMargin; o.listeners().fire(o), i.listeners().fire(i), (e = this._chart.timeScale()), e.restoreRightOffsetPropertyToDefault(), (t = this._model.model().properties().timezone), t.listeners().fire(t); }), (i.prototype.defaultProperties = function() { var e = this, t = [ e._seriesProperty.extendedHours, e._property.scalesProperties.showLeftScale, e._property.scalesProperties.showRightScale ].map(function(e) { return { property: e, previousValue: e.value() }; }); return ( setTimeout(function() { t.forEach(function(e) { e.property.value() !== e.previousValue && e.property.listeners().fire(e.property); }); var o = new k( "chartproperties.paneProperties.rightAxisProperties" ); ["autoScale", "percentage", "log"].forEach(function(t) { var i = e._scaleProperty[t], n = o[t].value(); n !== i.value() && i.setValue(n); }); }, 0), [this._property, this._seriesProperty] ); }), (i.prototype.createSessTable = function(e) { var t, o = this._series.sessionsStudy().properties(), i = this.createTableInTable(e), n = o.name.value(), a = $("<input type='checkbox' />"), r = this.addLabeledRow(i, $.t("Session Breaks"), a), l = L(), p = this.createColorPicker(), s = v(); return ( $("<td>") .append(a) .prependTo(r), $("<td>") .append(p) .appendTo(r), $("<td>") .append(l.render()) .appendTo(r), $("<td>") .append(s) .appendTo(r), this.bindControl( new c( a, o.graphics.vertlines.sessBreaks.visible, !0, this.model(), "Change " + n + " visibility" ) ), this.bindControl( new u( p, o.graphics.vertlines.sessBreaks.color, !0, this.model(), "Change " + n + " color" ) ), this.bindControl( new C( l, o.graphics.vertlines.sessBreaks.style, parseInt, !0, this.model(), "Change " + n + " style" ) ), this.bindControl( new b( s, o.graphics.vertlines.sessBreaks.width, !0, this.model(), "Change " + n + " width" ) ), (t = this._series.isIntradayInterval()), a.prop("disabled", !t), i ); }), (i.prototype._createStudySessRow = function(e, t, o) { var i, n = $("<input type='checkbox' />"), a = this.addLabeledRow(e, t, n), r = f($("<td>").appendTo(a)); return ( this.bindControl( new c( n, o.visible, !0, this.model(), "Change " + t + " visibility" ) ), this.bindControl( new u(r, o.color, !0, this.model(), t + " color", o.transparency) ), (i = $("<td>")), i.append(n).prependTo(a), a.addClass("offset-row"), n ); }), (i.prototype.createTradingTable = function() { var e, t, o, i, n, r, l, u, y, g, T, w = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab", a.TabNames.trading), _ = $("<tr>").appendTo(w), m = $("<td>").appendTo(_), f = $('<table cellspacing="0" cellpadding="0">').appendTo(m), k = $('<input type="checkbox">'); return ( (_ = this.addLabeledRow(f, $.t("Show Positions"), k)), $("<td>") .append(k) .prependTo(_), this.bindControl( new c( k, this._property.tradingProperties.showPositions, !0, this.model(), "Change Positions Visibility" ) ), (e = $('<input type="checkbox">')), (_ = this.addLabeledRow(f, $.t("Show Orders"), e)), $("<td>") .append(e) .prependTo(_), this.bindControl( new c( e, this._property.tradingProperties.showOrders, !0, this.model(), "Change Orders Visibility" ) ), (t = $('<input type="checkbox">')), (o = this.addLabeledRow(f, $.t("Extend Lines Left"), t)), $("<td>") .append(t) .prependTo(o), this.bindControl( new c( t, this._property.tradingProperties.extendLeft, !0, this.model(), "Extend Lines Left" ) ), (i = v()), this.bindControl( new b( i, this._property.tradingProperties.lineWidth, !0, this.model(), "Change Connecting Line Width" ) ), (n = L()), this.bindControl( new C( n, this._property.tradingProperties.lineStyle, parseInt, !0, this.model(), "Change Connecting Line Style" ) ), (r = $('<input type="text" class="ticker">')), (l = [ d(this._property.tradingProperties.lineLength.value()), s(100), p(0) ]), this.bindControl( new h( r, this._property.tradingProperties.lineLength, l, !0, this.model(), "Change Connecting Line Length" ) ), (u = $("<tbody>")), (y = this.addLabeledRow(f, $.t("Connecting Line"), u)), $("<td>").prependTo(y), $("<td>") .append(i) .appendTo(y), $('<td colspan="3">') .append(n.render()) .appendTo(y), $('<td colspan="3">') .append(r) .appendTo(y), $("<td>%</td>").appendTo(y), (g = $('<input type="checkbox">')), (T = this.addLabeledRow(f, $.t("Show Executions"), g)), $("<td>") .append(g) .prependTo(T), this.bindControl( new c( g, this._property.tradingProperties.showExecutions, !0, this.model(), "Change Executions Visibility" ) ), w ); }), (e.exports = i); }.call(t, o(5))); }, 1084: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.ColorBinding, l = a.SliderBinder, p = a.SimpleComboBinder, s = a.BooleanBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c, b; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = d()), (t = this.createColorPicker()), (o = this.createColorPicker()), (i = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (n = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), (a = this.createFontSizeEditor()), (h = this.createFontEditor()), (c = this.addLabeledRow(this._table, "Border")), c.prepend("<td>"), $("<td>") .append(t) .appendTo(c), $("<td>") .append(e) .appendTo(c), (h = this.createFontEditor()), this.bindControl( new r( t, this._linetool.properties().color, !0, this.model(), "Change Pattern Line Color" ) ), this.bindControl( new r( o, this._linetool.properties().textcolor, !0, this.model(), "Change Pattern Text Color" ) ), this.bindControl( new l( e, this._linetool.properties().linewidth, !0, this.model(), "Change Pattern Border Width" ) ), this.bindControl( new p( a, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new p( h, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new s( i, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new s( n, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (b = $( '<table class="property-page" cellspacing="0" cellpadding="2"><tr>' ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(o) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(h) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(a) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .attr({ width: 1 }) .append(i) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .append(n) ) .append($("</tr></table>"))), (c = this.addLabeledRow(this._table, "")), $('<td colspan="5">') .append(b) .appendTo(c), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1085: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = s()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Border")), o.prepend("<td>"), $("<td>") .append(t) .appendTo(o), $("<td>") .append(e) .appendTo(o), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Background", i)), $("<td>") .append(i) .prependTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Arc Filling" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Arc Line Color" ) ), this.bindControl( new l( n, this._linetool.properties().backgroundColor, !0, this.model(), "Change Arc Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Arc Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1086: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleStringBinder, l = a.ColorBinding, p = a.SimpleComboBinder; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).css({ width: "100%" })), (e = $("<input type='text'>").css({ width: "100%" })), (t = $('<div class="property-page-fullwidth-wrapper">').append(e)), (o = this.createColorPicker()), (i = this.createFontEditor()), (n = $("<tr>").appendTo(this._table)), $("<td>") .css({ width: "0" }) .html($.t("Text")) .appendTo(n), $('<td colspan="2">') .append(t) .appendTo(n), (n = this.addLabeledRow(this._table, $.t("Text Font"))), n.children().css({ whiteSpace: "nowrap" }), $("<td>") .append(o) .appendTo(n) .css({ width: "0" }), $("<td>") .append(i) .appendTo(n), this.bindControl( new l( o, this._linetool.properties().color, !0, this.model(), "Change Arrow Mark Text Color" ) ), this.bindControl( new r( e, this._linetool.properties().text, null, !0, this.model(), "Change Arrow Mark Text" ) ), this.bindControl( new p( i, this._linetool.properties().font, null, !0, this.model(), "Change Arrow Mark Font" ) ), this.loadData(), setTimeout(function() { e.select(), e.focus(); }, 20); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1087: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.SimpleStringBinder, s = o(1201).TabOpenFrom; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, d, h, c = $('<table class="property-page" cellspacing="0" cellpadding="0">') .css({ width: "100%" }) .data("layout-tab-open", s.Override), b = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ); (this._table = c.add(b)), (e = $("<input type='text'>").css({ width: "100%" })), (t = this.createColorPicker()), (o = this.createFontSizeEditor()), (i = this.createColorPicker()), (n = this.createColorPicker()), (a = $("<tr>").appendTo(c)), (d = $('<div class="property-page-fullwidth-wrapper">').append(e)), $("<td>") .append(d) .appendTo(a), (h = this.addLabeledRow(b, $.t("Text"))), $("<td>") .append(t) .appendTo(h), $("<td>") .append(o) .appendTo(h), (h = this.addLabeledRow(b, $.t("Background"))), $("<td>") .appendTo(h) .append(i), (h = this.addLabeledRow(b, $.t("Border"))), $("<td>") .appendTo(h) .append(n), $("<td>"), this.bindControl( new p( e, this._linetool.properties().text, null, !0, this.model(), "Change Balloon Text" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Baloon Text Color" ) ), this.bindControl( new r( o, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Balloon Text Font Size" ) ), this.bindControl( new l( i, this._linetool.properties().backgroundColor, !0, this.model(), "Change Balloon Background Color", this._linetool.properties().transparency ) ), this.bindControl( new l( n, this._linetool.properties().borderColor, !0, this.model(), "Change Balloon Border Color" ) ), this.loadData(), setTimeout(function() { e.select(), e.focus(); }, 0); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1088: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } function n(e, t, o) { r.call(this, e, t, o); } var a = o(1195), r = o(1076), l = o(238), p = l.ToFloatTransformer, s = l.SimpleComboBinder, d = l.ColorBinding, h = l.BooleanBinder, c = l.SimpleStringBinder; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = $("<tbody>").appendTo(this._table)), (t = this.createColorPicker()), (o = this.addLabeledRow(e, "Color")), $("<td>") .append(t) .appendTo(o), (i = $( '<select><option value="0">' + $.t("HL Bars") + '</option><option value="2">' + $.t("OC Bars") + '</option><option value="1">' + $.t("Line - Close") + '</option><option value="3">' + $.t("Line - Open") + '</option><option value="4">' + $.t("Line - High") + '</option><option value="5">' + $.t("Line - Low") + '</option><option value="6">' + $.t("Line - HL/2") + "</option></select>" )), (o = this.addLabeledRow(e, "Mode")), $("<td>") .append(i) .appendTo(o), (o = $("<tr>").appendTo(e)), $("<td>" + $.t("Mirrored") + "</td>").appendTo(o), (n = $("<input type='checkbox'>")), $("<td>") .append(n) .appendTo(o), (o = $("<tr>").appendTo(e)), $("<td>" + $.t("Flipped") + "</td>").appendTo(o), (a = $("<input type='checkbox'>")), $("<td>") .append(a) .appendTo(o), this.bindControl( new h( n, this._linetool.properties().mirrored, !0, this.model(), "Change Bars Pattern Mirroring" ) ), this.bindControl( new h( a, this._linetool.properties().flipped, !0, this.model(), "Change Bars Pattern Flipping" ) ), this.bindControl( new d( t, this._linetool.properties().color, !0, this.model(), "Change Bars Pattern Color" ) ), this.bindControl( new s( i, this._linetool.properties().mode, null, !0, this.model(), "Change Bars Pattern Mode" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), inherit(n, r), (n.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, l, s; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = $("<tr>")), e.appendTo(this._table), (t = $("<td>")), t.html($.t("Price")), t.appendTo(e), (o = $("<td>")), o.appendTo(e), (i = $("<input type='text'>")), i.appendTo(o), (n = $("<td>")), n.html($.t("Bar #")), n.appendTo(e), (a = $("<td>")), a.appendTo(e), (r = $("<input type='text'>")), r.appendTo(a), r.addClass("ticker"), (l = this._linetool.properties().points[0]), (s = [p(l.price.value())]), this.bindControl( new c( i, l.price, s, !1, this.model(), "Change " + this._linetool + " point price" ) ), this.bindBarIndex( l.bar, r, this.model(), "Change " + this._linetool + " point bar index" ), this.loadData(); }), (t.LineToolBarsPatternStylesPropertyPage = i), (t.LineToolBarsPatternInputsPropertyPage = n); }, 1089: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.ColorBinding, l = a.SimpleComboBinder, p = a.SliderBinder, s = a.BooleanBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m; (this._block = $("<div>").addClass("property-page")), (e = $('<table cellspacing="0" cellpadding="2">').appendTo( this._block )), (t = $("<tbody>").appendTo(e)), (o = h()), (i = d()), (n = this.createColorPicker()), (a = this.addLabeledRow(t, $.t("Line"))), $("<td>") .append(n) .appendTo(a), $("<td>") .append(o) .appendTo(a), $('<td colspan="3">') .append(i.render()) .appendTo(a), (c = $('<table cellspacing="0" cellpadding="2">').appendTo( this._block )), (a = this.addLabeledRow(c, $.t("Background"), b)), (b = $('<input type="checkbox" class="visibility-switch">')), (u = this.createColorPicker()), $("<td>") .append(b) .prependTo(a), $("<td>") .append(u) .appendTo(a), (C = $('<table cellspacing="0" cellpadding="2">').appendTo( this._block )), (y = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (g = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (T = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (w = $('<input type="checkbox">').appendTo(T)), (_ = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (m = $('<input type="checkbox">').appendTo(_)), (a = this.addLabeledRow(C, $.t("Left End"))), $('<td colspan="3">') .appendTo(a) .append(y) .append(T), (a = this.addLabeledRow(C, $.t("Right End"))), $('<td colspan="3">') .appendTo(a) .append(g) .append(_), this.bindControl( new r( n, this._linetool.properties().linecolor, !0, this.model(), "Change Curve Line Color" ) ), this.bindControl( new l( i, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Curve Line Style" ) ), this.bindControl( new p( o, this._linetool.properties().linewidth, !0, this.model(), "Change Curve Line Width" ) ), this.bindControl( new s( b, this._linetool.properties().fillBackground, !0, this.model(), "Change Curve Filling" ) ), this.bindControl( new r( u, this._linetool.properties().backgroundColor, !0, this.model(), "Change Curve Background Color", this._linetool.properties().transparency ) ), this.bindControl( new l( y, this._linetool.properties().leftEnd, parseInt, !0, this.model(), "Change Curve Line Left End" ) ), this.bindControl( new l( g, this._linetool.properties().rightEnd, parseInt, !0, this.model(), "Change Curve Line Right End" ) ), this.bindControl( new s( w, this._linetool.properties().extendLeft, !0, this.model(), "Change Curve Line Extending Left" ) ), this.bindControl( new s( m, this._linetool.properties().extendRight, !0, this.model(), "Change Curve Line Extending Right" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._block; }), (e.exports = i); }, 1090: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SliderBinder, l = a.BooleanBinder, p = a.ColorBinding, s = a.SimpleComboBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = d()), (t = this.createColorPicker()), (o = $('<input type="checkbox" class="visibility-switch">')), (i = this.createColorPicker()), (n = this.addLabeledRow(this._table, "Line")), $("<td>").prependTo(n), $("<td>") .append(t) .appendTo(n), $("<td>") .append(e) .appendTo(n), (n = this.addLabeledRow(this._table, "Background", o)), $("<td>") .append(o) .prependTo(n), $("<td>") .append(i) .appendTo(n), (a = $("<tbody>").appendTo(this._table)), (h = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (c = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (n = this.addLabeledRow(a, $.t("Left End"))), $("<td>").prependTo(n), $('<td colspan="3">') .appendTo(n) .append(h), (n = this.addLabeledRow(a, $.t("Right End"))), $("<td>").prependTo(n), $('<td colspan="3">') .appendTo(n) .append(c), this.bindControl( new p( t, this._linetool.properties().linecolor, !0, this.model(), "Change Brush Color" ) ), this.bindControl( new r( e, this._linetool.properties().linewidth, !0, this.model(), "Change Brush Line Width" ) ), this.bindControl( new l( o, this._linetool.properties().fillBackground, !0, this.model(), "Change Brush Filling" ) ), this.bindControl( new p( i, this._linetool.properties().backgroundColor, !0, this.model(), "Change Brush Background Color", this._linetool.properties().transparency ) ), this.bindControl( new s( h, this._linetool.properties().leftEnd, parseInt, !0, this.model(), "Change Trend Line Left End" ) ), this.bindControl( new s( c, this._linetool.properties().rightEnd, parseInt, !0, this.model(), "Change Trend Line Right End" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1091: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SimpleComboBinder, s = a.SliderBinder, d = a.SimpleStringBinder, h = o(1196).createLineWidthEditor, c = o(1201).TabOpenFrom; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n = this.createColorPicker(), a = this.createFontSizeEditor(), b = this.createFontEditor(), u = this.createTextEditor(350, 200), C = this.createColorPicker(), y = h(), g = this.createColorPicker(), T = $('<input type="checkbox">'), w = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' ), _ = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' ); this.bindControl( new l( n, this._linetool.properties().color, !0, this.model(), "Change Text Color" ) ), this.bindControl( new p( a, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new p( b, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new d( u, this._linetool.properties().text, null, !0, this.model(), "Change Text" ) ), this.bindControl( new l( C, this._linetool.properties().backgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().transparency ) ), this.bindControl( new l( g, this._linetool.properties().bordercolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new s( y, this._linetool.properties().linewidth, !0, this.model(), "Change Border Width" ) ), this.bindControl( new r( T, this._linetool.properties().wordWrap, !0, this.model(), "Change Text Wrap" ) ), this.bindControl( new r( w, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new r( _, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (e = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ).data("layout-tab-open", c.Override)), (t = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (o = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (this._table = e.add(o).add(t)), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(n) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(b) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(a) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(w) ) .append($(document.createElement("td")).append(_)) .appendTo(e), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ colspan: 5 }) .append(u) ) .appendTo(e), (i = this.addLabeledRow(t, "Text Wrap", T)), $("<td>") .append(T) .prependTo(i), (i = this.addLabeledRow(o, "Background")), $("<td>") .append(C) .appendTo(i), (i = this.addLabeledRow(o, "Border")), $("<td>") .append(g) .appendTo(i), $("<td>") .append(y) .appendTo(i), this.loadData(), setTimeout(function() { u.select(), u.focus(); }, 20); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1092: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1197).createLineStyleEditor, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = d()), (t = s()), (o = this.createColorPicker()), (i = this.addLabeledRow(this._table, "Lines")), $("<td>") .append(o) .appendTo(i), $("<td>") .append(e) .appendTo(i), $("<td>") .append(t.render()) .appendTo(i), this.bindControl( new l( o, this._linetool.properties().linecolor, !0, this.model(), "Change Circle Lines Color" ) ), this.bindControl( new r( t, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Circle Lines Style" ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Circle Lines Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1093: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.BooleanBinder, s = a.SliderBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c, b, u, C, y, g, T; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = d()), (o = this.createColorPicker()), (i = this.addLabeledRow(e, $.t("Line"))), $("<td>").prependTo(i), $("<td>") .append(o) .appendTo(i), $("<td>") .append(t) .appendTo(i), (n = this.createColorPicker()), (a = this.createColorPicker()), (h = this.createFontSizeEditor()), (c = this.createFontEditor()), (b = this.createColorPicker()), (u = $('<input type="checkbox" class="visibility-switch">')), (C = this.createColorPicker()), (y = $('<input type="checkbox" class="visibility-switch">')), this.bindControl( new l( n, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new r( h, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new r( c, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new l( b, this._linetool.properties().labelBackgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().labelBackgroundTransparency ) ), this.bindControl( new p( u, this._linetool.properties().fillLabelBackground, !0, this.model(), "Change Text Background Fill" ) ), this.bindControl( new l( C, this._linetool.properties().backgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().backgroundTransparency ) ), this.bindControl( new p( y, this._linetool.properties().fillBackground, !0, this.model(), "Change Text Background Fill" ) ), this.bindControl( new l( a, this._linetool.properties().borderColor, !0, this.model(), "Change Text Border Color" ) ), (g = this.addLabeledRow(e, $.t("Background"), y)), $("<td>") .append(y) .prependTo(g), $("<td>") .append(C) .appendTo(g), (T = this.addLabeledRow(e, $.t("Label"))), $("<td>").prependTo(T), $("<td>") .append(n) .appendTo(T), $("<td>") .append(c) .appendTo(T), $("<td>") .append(h) .appendTo(T), (g = this.addLabeledRow(e, $.t("Label Background"), u)), $("<td>") .append(u) .prependTo(g), $("<td>") .append(b) .appendTo(g), this.bindControl( new l( o, this._linetool.properties().linecolor, !0, this.model(), "Change Date Range Color" ) ), this.bindControl( new s( t, this._linetool.properties().linewidth, !0, this.model(), "Change Date Range Line Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1094: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.BooleanBinder, s = a.SliderBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c, b, u, C, y, g, T, w, _, m, f, L, v, k, S, P; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = d()), (o = this.createColorPicker()), (i = this.addLabeledRow(e, $.t("Line"))), $("<td>").prependTo(i), $("<td>") .append(o) .appendTo(i), $("<td>") .append(t) .appendTo(i), (n = this.createColorPicker()), (a = this.createColorPicker()), (h = this.createFontSizeEditor()), (c = this.createFontEditor()), (b = this.createColorPicker()), (u = $('<input type="checkbox" class="visibility-switch">')), (C = this.createColorPicker()), (y = $('<input type="checkbox" class="visibility-switch">')), this.bindControl( new l( n, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new r( h, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new r( c, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new l( b, this._linetool.properties().labelBackgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().labelBackgroundTransparency ) ), this.bindControl( new p( u, this._linetool.properties().fillLabelBackground, !0, this.model(), "Change Text Background Fill" ) ), this.bindControl( new l( C, this._linetool.properties().backgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().backgroundTransparency ) ), this.bindControl( new p( y, this._linetool.properties().fillBackground, !0, this.model(), "Change Text Background Fill" ) ), this.bindControl( new l( a, this._linetool.properties().borderColor, !0, this.model(), "Change Text Border Color" ) ), (g = this.addLabeledRow(e, $.t("Background"), y)), $("<td>") .append(y) .prependTo(g), $("<td>") .append(C) .appendTo(g), (T = this.addLabeledRow(e, $.t("Label"))), $("<td>").prependTo(T), $("<td>") .append(n) .appendTo(T), $("<td>") .append(c) .appendTo(T), $("<td>") .append(h) .appendTo(T), (g = this.addLabeledRow(e, $.t("Label Background"), u)), $("<td>") .append(u) .prependTo(g), $("<td>") .append(b) .appendTo(g), this.bindControl( new l( o, this._linetool.properties().linecolor, !0, this.model(), "Change Date Range Color" ) ), this.bindControl( new s( t, this._linetool.properties().linewidth, !0, this.model(), "Change Date Range Line Width" ) ), (w = this._linetool.properties()), void 0 !== w.extendTop && void 0 !== w.extendBottom && ((_ = $('<input type="checkbox">')), (m = $('<input type="checkbox">')), this.bindControl( new p( _, this._linetool.properties().extendTop, !0, this.model(), "Change Extend Top" ) ), this.bindControl( new p( m, this._linetool.properties().extendBottom, !0, this.model(), "Change Extend Bottom" ) ), (f = this.addLabeledRow(e, $.t("Extend Top"), _)), $("<td>") .append(_) .prependTo(f), (L = this.addLabeledRow(e, $.t("Extend Bottom"), m)), $("<td>") .append(m) .prependTo(L)), void 0 !== w.extendLeft && void 0 !== w.extendRight && ((v = $('<input type="checkbox">')), (k = $('<input type="checkbox">')), this.bindControl( new p( v, this._linetool.properties().extendLeft, !0, this.model(), "Change Extend Left" ) ), this.bindControl( new p( k, this._linetool.properties().extendRight, !0, this.model(), "Change Extend Right" ) ), (S = this.addLabeledRow(e, $.t("Extend Left"), v)), $("<td>") .append(v) .prependTo(S), (P = this.addLabeledRow(e, $.t("Extend Right"), k)), $("<td>") .append(k) .prependTo(P)), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1095: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.BooleanBinder, p = a.ColorBinding, s = a.SliderBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m, f, L, v, k, S, P, x, B; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = h()), (o = d()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, $.t("Line"))), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), (n = this.addLabeledRow(e, $.t("Text"))), (a = this.createColorPicker()), (c = this.createFontSizeEditor()), (b = this.createFontEditor()), (u = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (C = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), $("<td>") .append(a) .appendTo(n), $("<td>") .append(b) .appendTo(n), $("<td>") .append(c) .appendTo(n), $("<td>") .append(u) .appendTo(n), $("<td>") .append(C) .appendTo(n), (y = $("<tbody>").appendTo(this._table)), (g = $('<input type="checkbox" class="visibility-switch">')), (T = this.createColorPicker()), (n = this.addLabeledRow(y, $.t("Background"), g)), (w = $("<table>")), $('<td colspan="5">') .append(w) .appendTo(n), (n = $("<tr>").appendTo(w)), $("<td>") .append(g) .appendTo(n), $("<td>") .append(T) .appendTo(n), (_ = $("<tbody>").appendTo(this._table)), (m = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (f = $('<input type="checkbox">').appendTo(m)), (L = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (v = $('<input type="checkbox">').appendTo(L)), (k = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (S = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (n = this.addLabeledRow(_, $.t("Left End"))), $('<td colspan="3">') .appendTo(n) .append(k) .append(m), (n = this.addLabeledRow(_, $.t("Right End"))), $('<td colspan="3">') .appendTo(n) .append(S) .append(L), (P = $("<tbody>").appendTo(this._table)), (n = $("<tr>").appendTo(P)), (x = $("<input type='checkbox'>")), (B = $("<label style='display:block'>") .append(x) .append($.t("Show Prices"))), $("<td colspan='2'>") .append(B) .appendTo(n), this.bindControl( new r( c, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new r( b, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new p( a, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new l( u, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new l( C, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), this.bindControl( new l( x, this._linetool.properties().showPrices, !0, this.model(), "Change Disjoint Angle Show Prices" ) ), this.bindControl( new l( f, this._linetool.properties().extendLeft, !0, this.model(), "Change Disjoint Angle Extending Left" ) ), this.bindControl( new l( v, this._linetool.properties().extendRight, !0, this.model(), "Change Disjoint Angle Extending Right" ) ), this.bindControl( new p( i, this._linetool.properties().linecolor, !0, this.model(), "Change Disjoint Angle Color" ) ), this.bindControl( new r( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Disjoint Angle Style" ) ), this.bindControl( new s( t, this._linetool.properties().linewidth, !0, this.model(), "Change Disjoint Angle Width" ) ), this.bindControl( new r( k, this._linetool.properties().leftEnd, parseInt, !0, this.model(), "Change Disjoint Angle Left End" ) ), this.bindControl( new r( S, this._linetool.properties().rightEnd, parseInt, !0, this.model(), "Change Disjoint Angle Right End" ) ), this.bindControl( new l( g, this._linetool.properties().fillBackground, !0, this.model(), "Change Disjoint Angle Filling" ) ), this.bindControl( new p( T, this._linetool.properties().backgroundColor, !0, this.model(), "Change Disjoint Angle Background Color", this._linetool.properties().transparency ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1096: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n, a, r, l, p, s, d; o(12), (n = o(1195)), (a = o(238)), (r = a.SimpleComboBinder), (l = a.ColorBinding), (p = a.SliderBinder), (s = a.BooleanBinder), (d = o(1196).createLineWidthEditor), inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this._linetool.getDegrees()), (t = this.createKeyCombo(e)), t.width(300), (o = this.createColorPicker()), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.addLabeledRow(this._table, window.t("Degree"))), $("<td>").prependTo(n), $("<td>") .append(t) .appendTo(n), (n = this.addLabeledRow(this._table, window.t("Line Width"))), (a = d()), $("<td>").prependTo(n), $("<td>") .append(a) .appendTo(n), (n = this.addLabeledRow(this._table, window.t("Color"))), $("<td>").prependTo(n), $("<td>") .append(o) .appendTo(n), (n = this.addLabeledRow(this._table, window.t("Show Wave"), i)), $("<td>") .append(i) .prependTo(n), this.bindControl( new l( o, this._linetool.properties().color, !0, this.model(), "Change Elliott Label Color" ) ), this.bindControl( new r( t, this._linetool.properties().degree, parseInt, !0, this.model(), "Change Elliott Wave Size" ) ), this.bindControl( new s( i, this._linetool.properties().showWave, !0, this.model(), "Change Elliott Labels Background" ) ), this.bindControl( new p( a, this._linetool.properties().linewidth, parseInt, this.model(), "Change Elliott Wave Line Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1097: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = s()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, $.t("Border"))), o.prepend("<td>"), $("<td>") .append(t) .appendTo(o), $("<td>") .append(e) .appendTo(o), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, $.t("Background"), i)), $("<td>") .append(i) .prependTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Ellipse Filling" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Ellipse Line Color" ) ), this.bindControl( new l( n, this._linetool.properties().backgroundColor, !0, this.model(), "Change Ellipse Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Ellipse Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1098: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o); } var n = o(1078); inherit(i, n), (e.exports = i); }, 1099: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.SimpleComboBinder, p = a.BooleanBinder, s = a.ColorBinding, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), (i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), e ? ((a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : this.createLabeledCell("Trend Line", n).appendTo(m), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), e || ((w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new l( _, t.linestyle, parseInt, !0, this.model(), "Change Fib Circle Style" ) )), this.bindControl( new p( n, t.visible, !0, this.model(), "Change Fib Circle Visibility" ) ), this.bindControl( new s( y, t.color, !0, this.model(), "Change Fib Circle Line Color", 0 ) ), this.bindControl( new d(T, t.linewidth, !0, this.model(), "Change Fib Circle Width") ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor( null, this._linetool.properties().trendline, !1 ), e = 1; e <= 11; e++ ) (t = "level" + e), this.addLevelEditor( "Level " + e, this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, "Levels", o)), $("<td>") .append(o) .prependTo(i), (n = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, "Coeffs As Percents", n)), $("<td>") .append(n) .prependTo(i), this.bindControl( new p( o, this._linetool.properties().showCoeffs, !0, this.model(), "Change Fib Circle Levels Visibility" ) ), (i = $("<tr>")), i.appendTo(this._table), (a = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(a) .appendTo(i), this.createLabeledCell("Background", a).appendTo(i), (r = u()), $('<td colspan="3">') .append(r) .appendTo(i), this.bindControl( new p( a, this._linetool.properties().fillBackground, !0, this.model(), "Change Pitchfork Background Visibility" ) ), this.bindControl( new d( r, this._linetool.properties().transparency, !0, this.model(), "Change Pitchfork Background Transparency" ) ), this.bindControl( new p( n, this._linetool.properties().coeffsAsPercents, !0, this.model(), "Change Fib Retracement Coeffs As Percents" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1100: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.SimpleComboBinder, p = a.BooleanBinder, s = a.ColorBinding, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), (i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), e ? ((a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : $("<td>" + $.t("Trend Line") + "</td>").appendTo(m), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), e || ((w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new l( _, t.linestyle, parseInt, !0, this.model(), "Change Fib Speed Resistance Arcs Style" ) )), this.bindControl( new p( n, t.visible, !0, this.model(), "Change Fib Speed Resistance Arcs Visibility" ) ), this.bindControl( new s( y, t.color, !0, this.model(), "Change Fib Speed Resistance Arcs Line Color", 0 ) ), this.bindControl( new d( T, t.linewidth, !0, this.model(), "Change Fib Speed Resistance Arcs Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor( null, this._linetool.properties().trendline, !1 ), e = 1; e <= 11; e++ ) (t = "level" + e), this.addLevelEditor( "Level " + e, this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, $.t("Levels"))), $("<td>") .append(o) .prependTo(i), this.bindControl( new p( o, this._linetool.properties().showCoeffs, !0, this.model(), "Change Fib Speed Resistance Arcs Levels Visibility" ) ), (n = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, $.t("Full Circles"))), $("<td>") .append(n) .prependTo(i), this.bindControl( new p( n, this._linetool.properties().fullCircles, !0, this.model(), "Change Fib Speed Resistance Arcs Full Cirlces Mode" ) ), (i = $("<tr>")), i.appendTo(this._table), (a = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(a) .appendTo(i), $("<td>" + $.t("Background") + "</td>").appendTo(i), (r = u()), $('<td colspan="3">') .append(r) .appendTo(i), this.bindControl( new p( a, this._linetool.properties().fillBackground, !0, this.model(), "Change Fib Arcs Background Visibility" ) ), this.bindControl( new d( r, this._linetool.properties().transparency, !0, this.model(), "Change Fib Arcs Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1101: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.FloatBinder, s = a.SimpleComboBinder, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, s, d, c, b = $("<tr>"); b.appendTo(e), (i = $("<td>")), i.appendTo(b), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), (a = $("<td>")), a.appendTo(b), (s = $("<input type='text'>")), s.appendTo(a), s.css("width", "70px"), this.bindControl( new r( n, o.visible, !0, this.model(), "Change Gann Square Line Visibility" ) ), this.bindControl( new p(s, o.coeff, !1, this.model(), "Change Pitchfork Line Coeff") ), (d = $("<td class='colorpicker-cell'>")), d.appendTo(b), (c = h(d)), this.bindControl( new l( c, o.color, !0, this.model(), "Change Gann Square Line Color", 0 ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, p, h, C, y, g, T, w, _, m, f, L, v, k, S, P, x, B; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page property-page-unpadded"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this._table.css({ width: "100%" }), e = $("<tbody>").appendTo(this._table), t = $("<tr>"), t.appendTo(e), o = $('<td width="50%">'), o.appendTo(t), i = $('<td width="50%">'), i.appendTo(t), n = $('<table cellspacing="0" cellpadding="2">'), n.appendTo(o), n.addClass("property-page"), a = $('<table cellspacing="0" cellpadding="2">'), a.appendTo(i), a.addClass("property-page"), $( "<tr><td align='center' colspan='4'>" + $.t("Price Levels") + "</td></tr>" ).appendTo(n), $( "<tr><td align='center' colspan='4'>" + $.t("Time Levels") + "</td></tr>" ).appendTo(a), p = 1; p <= 7; p++ ) (h = "hlevel" + p), this.addLevelEditor( n, "Level " + p, this._linetool.properties()[h] ); for (p = 1; p <= 7; p++) (h = "vlevel" + p), this.addLevelEditor( a, "Level " + p, this._linetool.properties()[h] ); this.addOneColorPropertyWidget(n), i.css({ "vertical-align": "top" }), (C = $("<input type='checkbox' class='visibility-switch'>")), (y = $("<input type='checkbox' class='visibility-switch'>")), (g = $("<input type='checkbox' class='visibility-switch'>")), (T = $("<input type='checkbox' class='visibility-switch'>")), (w = $( '<table class="property-page property-page-unpadded" cellspacing="0" cellpadding="0">' ).css({ width: "100%" })), (_ = $("<tr>").appendTo(w)), (m = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%" }) .appendTo(_) )), (f = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%" }) .appendTo(_) )), (L = this.addLabeledRow(m, $.t("Left Labels"), C)), $("<td>") .append(C) .prependTo(L), (L = this.addLabeledRow(f, $.t("Right Labels"), y)), $("<td>") .append(y) .prependTo(L), (L = this.addLabeledRow(m, $.t("Top Labels"), g)), $("<td>") .append(g) .prependTo(L), (L = this.addLabeledRow(f, $.t("Bottom Labels"), T)), $("<td>") .append(T) .prependTo(L), this.bindControl( new r( C, this._linetool.properties().showLeftLabels, !0, this.model(), "Change Gann Square Left Labels Visibility" ) ), this.bindControl( new r( y, this._linetool.properties().showRightLabels, !0, this.model(), "Change Gann Square Right Labels Visibility" ) ), this.bindControl( new r( g, this._linetool.properties().showTopLabels, !0, this.model(), "Change Gann Square Top Labels Visibility" ) ), this.bindControl( new r( T, this._linetool.properties().showBottomLabels, !0, this.model(), "Change Gann Square Bottom Labels Visibility" ) ), (v = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (k = b()), (S = c()), (P = this.createColorPicker()), (x = $("<input type='checkbox' class='visibility-switch'>")), (L = this.addLabeledRow(v, $.t("Grid"), x)), $("<td>") .append(x) .prependTo(L), $("<td>") .append(P) .appendTo(L), $("<td>") .append(k) .appendTo(L), $("<td>") .append(S.render()) .appendTo(L), this.bindControl( new r( x, this._linetool.properties().grid.visible, !0, this.model(), "Change Fib Speed Resistance Fan Grid Visibility" ) ), this.bindControl( new l( P, this._linetool.properties().grid.color, !0, this.model(), "Change Fib Speed Resistance Fan Grid Line Color", 0 ) ), this.bindControl( new s( S, this._linetool.properties().grid.linestyle, parseInt, !0, this.model(), "Change Fib Speed Resistance Fan Grid Line Style" ) ), this.bindControl( new d( k, this._linetool.properties().grid.linewidth, !0, this.model(), "Change Fib Speed Resistance Fan Grid Line Width" ) ), (this._table = this._table.add(w).add(v)), (L = $("<tr>")), L.appendTo(v), (x = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(x) .appendTo(L), this.createLabeledCell("Background", x).appendTo(L), (B = u()), $('<td colspan="3">') .append(B) .appendTo(L), this.bindControl( new r( x, this._linetool.properties().fillBackground, !0, this.model(), "Change Fib Speed/Resistance Fan Background Visibility" ) ), this.bindControl( new d( B, this._linetool.properties().transparency, !0, this.model(), "Change Fib Speed/Resistance Fan Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1102: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1197).createLineStyleEditor, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = d()), (o = s()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, "Line")), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), this.bindControl( new l( i, this._linetool.properties().linecolor, !0, this.model(), "Change Fib Spiral Line Color" ) ), this.bindControl( new r( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Fib Spiral Line Style" ) ), this.bindControl( new p( t, this._linetool.properties().linewidth, !0, this.model(), "Change Fib Spiral Line Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1103: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.BooleanBinder, p = a.ColorBinding, s = a.SimpleComboBinder, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), (i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), e ? ((a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : this.createLabeledCell($.t("Trend Line"), n).appendTo(m), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), (w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new l( n, t.visible, !0, this.model(), "Change Pitchfork Line Visibility" ) ), this.bindControl( new p( y, t.color, !0, this.model(), "Change Pitchfork Line Color", 0 ) ), this.bindControl( new s( _, t.linestyle, parseInt, !0, this.model(), "Change Pitchfork Line Style" ) ), this.bindControl( new d( T, t.linewidth, parseInt, this.model(), "Change Pitchfork Line Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, p, h; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), e = 1; e <= 11; e++ ) (t = "level" + e), this.addLevelEditor( "Level " + e, this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, $.t("Show Labels"), o)), $("<td>") .append(o) .prependTo(i), (n = $("<table cellspacing='0' cellpadding='0'>")), (a = $( "<select><option value='left'>" + $.t("left") + "</option><option value='center'>" + $.t("center") + "</option><option value='right'>" + $.t("right") + "</option></select>" )), (r = $( "<select><option value='top'>" + $.t("top") + "</option><option value='middle'>" + $.t("middle") + "</option><option value='bottom'>" + $.t("bottom") + "</option></select>" )), (i = $("<tr>")), i .append("<td>" + $.t("Labels") + "</td>") .append(a) .append("<td>&nbsp</td>") .append(r), i.appendTo(n), (i = $("<tr>")), $("<td colspan='5'>") .append(n) .appendTo(i), i.appendTo(this._table), this.bindControl( new s( a, this._linetool.properties().horzLabelsAlign, null, !0, this.model(), "Change Fib Time Zone Labels Alignment" ) ), this.bindControl( new s( r, this._linetool.properties().vertLabelsAlign, null, !0, this.model(), "Change Fib Time Zone Labels Alignment" ) ), (i = $("<tr>")), i.appendTo(this._table), (p = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(p) .appendTo(i), this.createLabeledCell($.t("Background"), p).appendTo(i), (h = u()), $('<td colspan="3">') .append(h) .appendTo(i), this.bindControl( new l( o, this._linetool.properties().showLabels, !0, this.model(), "Change Fib Time Zone Labels Visibility" ) ), this.bindControl( new d( h, this._linetool.properties().transparency, !0, this.model(), "Change Fib Retracement Background Transparency" ) ), this.bindControl( new l( p, this._linetool.properties().fillBackground, !0, this.model(), "Change Fib Retracement Background Visibility" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1104: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.BooleanBinder, p = a.ColorBinding, s = a.SliderBinder, d = o(372).addColorPicker, h = o(1196).createLineWidthEditor, c = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, c, b, u, C, y, g = $("<tr>"); g.appendTo(this._table), (i = $("<td>")), i.appendTo(g), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), e ? ((a = $("<td>")), a.appendTo(g), (c = $("<input type='text'>")), c.appendTo(a), c.css("width", "70px"), this.bindControl( new r( c, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : this.createLabeledCell("Trend Line", n).appendTo(g), (b = $("<td class='colorpicker-cell'>")), b.appendTo(g), (u = d(b)), (C = $("<td>")), C.appendTo(g), (y = h()), y.appendTo(C), this.bindControl( new l(n, t.visible, !0, this.model(), "Change Fib Wedge Visibility") ), this.bindControl( new p( u, t.color, !0, this.model(), "Change Fib Wedge Line Color", 0 ) ), this.bindControl( new s(y, t.linewidth, !0, this.model(), "Change Fib Wedge Width") ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor( null, this._linetool.properties().trendline, !1 ), e = 1; e <= 11; e++ ) (t = "level" + e), this.addLevelEditor( "Level " + e, this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<input type='checkbox' class='visibility-switch'>")), (i = this.addLabeledRow(this._table, "Levels", o)), $("<td>") .append(o) .prependTo(i), this.bindControl( new l( o, this._linetool.properties().showCoeffs, !0, this.model(), "Change Fib Wedge Levels Visibility" ) ), (i = $("<tr>")), i.appendTo(this._table), (n = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(n) .appendTo(i), this.createLabeledCell("Background", n).appendTo(i), (a = c()), $('<td colspan="3">') .append(a) .appendTo(i), this.bindControl( new l( n, this._linetool.properties().fillBackground, !0, this.model(), "Change Wedge Background Visibility" ) ), this.bindControl( new s( a, this._linetool.properties().transparency, !0, this.model(), "Change Wedge Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1105: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.BooleanBinder, s = a.SliderBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m, f, L, v, k, S, P, x, B; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = h()), (o = d()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, $.t("Line"))), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), (n = this.addLabeledRow(e, $.t("Text"))), (a = this.createColorPicker()), (c = this.createFontSizeEditor()), (b = this.createFontEditor()), (u = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (C = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), $("<td>") .append(a) .appendTo(n), $("<td>") .append(b) .appendTo(n), $("<td>") .append(c) .appendTo(n), $("<td>") .append(u) .appendTo(n), $("<td>") .append(C) .appendTo(n), (y = $("<tbody>").appendTo(this._table)), (g = $('<input type="checkbox" class="visibility-switch">')), (T = this.createColorPicker()), (n = this.addLabeledRow(y, $.t("Background"), g)), (w = $("<table>")), $('<td colspan="5">') .append(w) .appendTo(n), (n = $("<tr>").appendTo(w)), $("<td>") .append(g) .appendTo(n), $("<td>") .append(T) .appendTo(n), (_ = $("<tbody>").appendTo(this._table)), (m = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (f = $('<input type="checkbox">').appendTo(m)), (L = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (v = $('<input type="checkbox">').appendTo(L)), (k = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (S = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (n = this.addLabeledRow(_, $.t("Left End"))), $('<td colspan="3">') .appendTo(n) .append(k) .append(m), (n = this.addLabeledRow(_, $.t("Right End"))), $('<td colspan="3">') .appendTo(n) .append(S) .append(L), (P = $("<tbody>").appendTo(this._table)), (n = $("<tr>").appendTo(P)), (x = $("<input type='checkbox'>")), (B = $("<label style='display:block'>") .append(x) .append($.t("Show Prices"))), $("<td colspan='2'>") .append(B) .appendTo(n), this.bindControl( new r( c, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new r( b, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new l( a, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new p( u, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new p( C, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), this.bindControl( new p( x, this._linetool.properties().showPrices, !0, this.model(), "Change Disjoint Angle Show Prices" ) ), this.bindControl( new p( f, this._linetool.properties().extendLeft, !0, this.model(), "Change Disjoint Angle Extending Left" ) ), this.bindControl( new p( v, this._linetool.properties().extendRight, !0, this.model(), "Change Disjoint Angle Extending Right" ) ), this.bindControl( new l( i, this._linetool.properties().linecolor, !0, this.model(), "Change Disjoint Angle Color" ) ), this.bindControl( new r( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Disjoint Angle Style" ) ), this.bindControl( new s( t, this._linetool.properties().linewidth, !0, this.model(), "Change Disjoint Angle Width" ) ), this.bindControl( new r( k, this._linetool.properties().leftEnd, parseInt, !0, this.model(), "Change Disjoint Angle Left End" ) ), this.bindControl( new r( S, this._linetool.properties().rightEnd, parseInt, !0, this.model(), "Change Disjoint Angle Right End" ) ), this.bindControl( new p( g, this._linetool.properties().fillBackground, !0, this.model(), "Change Disjoint Angle Filling" ) ), this.bindControl( new l( T, this._linetool.properties().backgroundColor, !0, this.model(), "Change Disjoint Angle Background Color", this._linetool.properties().transparency ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1106: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.LessTransformer, l = a.GreateTransformer, p = a.ToFloatTransformer, s = a.BooleanBinder, d = a.SliderBinder, h = a.ColorBinding, c = a.SimpleComboBinder, b = a.SimpleStringBinder, u = o(372).addColorPicker, C = o(1196).createLineWidthEditor, y = o(1198).createTransparencyEditor; o(241), inherit(i, n), (i.prototype.addOneColorPropertyWidget = function(e) { var t = this.createOneColorForAllLinesWidget(), o = $("<tr>"); o .append($("<td>")) .append($("<td>")) .append(t.editor) .append($("<td>").append(t.label)), o.appendTo(e); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, g, T, w, _, m, f, L, v, k, S, P, x, B, R, E, F, I, D, A, W, V, O, z, M, j, H, G, N, U, q, Y, K, Q, J, Z; (this._table = $(document.createElement("table"))), this._table.addClass("property-page property-page-unpadded"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this._table.css({ width: "100%" }), (e = $("<tr>")), e.appendTo(this._table), (t = this.model()), (o = this._linetool), (i = o.properties()), (n = $("<table>")), $("<td valign='top'>") .append(n) .appendTo(e), (a = $("<tr>")), $("<td colspan='3'>" + $.t("Levels") + "</td>").appendTo(a), a.appendTo(n); for (g in i.levels._childs) (T = i.levels[g]), (w = $("<tr>")), w.appendTo(n), $("<td>" + g + "</td>").appendTo(w), (_ = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(_) .appendTo(w), (m = $("<td class='colorpicker-cell'>")), m.appendTo(w), (f = u(m)), (L = $("<td>")), L.appendTo(w), (v = C()), v.appendTo(L), this.bindControl( new s(_, T.visible, !0, t, "Change Gann Line Visibility") ), this.bindControl( new h(f, T.color, !0, t, "Change Gann Line Color", 0) ), this.bindControl( new d(v, T.width, !0, t, "Change Gann Line Width") ); (k = $("<table>")), $("<td valign='top'>") .append(k) .appendTo(e), (S = $("<tr>")), $("<td colspan='4'>" + $.t("Fans") + "</td>").appendTo(S), S.appendTo(k); for (g in i.fanlines._childs) (P = i.fanlines[g]), (x = $("<tr>")), x.appendTo(k), (_ = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(_) .appendTo(x), (B = P.x.value() + "x" + P.y.value()), $("<td>" + B + "</td>").appendTo(x), (m = $("<td class='colorpicker-cell'>")), m.appendTo(x), (f = u(m)), (L = $("<td>")), L.appendTo(x), (v = C()), v.appendTo(L), this.bindControl( new s(_, P.visible, !0, t, "Change Gann Line Visibility") ), this.bindControl( new h(f, P.color, !0, t, "Change Gann Fan Color", 0) ), this.bindControl( new d(v, P.width, !0, t, "Change Gann Line Width") ); (R = $("<table>")), $("<td valign='top'>") .append(R) .appendTo(e), (E = $("<tr>")), $("<td colspan='4'>" + $.t("Arcs") + "</td>").appendTo(E), E.appendTo(R); for (g in i.arcs._childs) (F = i.arcs[g]), (I = $("<tr>")), I.appendTo(R), (_ = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(_) .appendTo(I), (B = F.x.value() + "x" + F.y.value()), $("<td>" + B + "</td>").appendTo(I), (m = $("<td class='colorpicker-cell'>")), m.appendTo(I), (f = u(m)), (L = $("<td>")), L.appendTo(I), (v = C()), v.appendTo(L), this.bindControl( new s(_, F.visible, !0, t, "Change Gann Line Visibility") ), this.bindControl( new h(f, F.color, !0, t, "Change Gann Arc Color", 0) ), this.bindControl( new d(v, F.width, !0, t, "Change Gann Line Width") ); this.addOneColorPropertyWidget(R), (D = $("<tbody>").appendTo(this._table)), (A = $('<input type="checkbox" class="visibility-switch">')), (W = y()), (V = $("<tr>").appendTo(D)), (O = $("<table>")), $('<td colspan="3">') .append(O) .appendTo(V), (V = $("<tr>").appendTo(O)), $("<td>") .append(A) .appendTo(V), $("<td>" + $.t("Background") + "</td>").appendTo(V), $("<td>") .append(W) .appendTo(V), i.reverse && ((z = $("<input type='checkbox' class='visibility-switch'>")), (V = this.addLabeledRow(O, $.t("Reverse"), z, !0)), $("<td>") .append(z) .prependTo(V), (M = "Change Gann Square Reverse"), this.bindControl(new s(z, i.reverse, !0, t, M))), this.bindControl( new s( A, i.arcsBackground.fillBackground, !0, t, "Change Gann Square Filling" ) ), this.bindControl( new d( W, i.arcsBackground.transparency, !0, t, "Change Gann Square Background Transparency" ) ), (j = $('<input type="text">')), (V = this.addLabeledRow(O, $.t("Price/Bar Ratio"), j, !0)), $("<td>") .append(j) .appendTo(V), j.TVTicker({ step: o.getScaleRatioStep() }), (M = "Change Gann Square Scale Ratio"), (H = this._getPropertySetter(i.scaleRatio, M)), (G = [p(i.scaleRatio.value()), l(1e-7), r(1e8)]), (N = new b(j, i.scaleRatio, G, !1, t, M, H)), N.addFormatter(function(e) { return o.getScaleRatioFormatter().format(e); }), this.bindControl(N), (U = $('<input type="checkbox">')), (V = this.addLabeledRow(O, $.t("Ranges And Ratio"), U, !1)), $("<td>") .append(U) .prependTo(V), this.bindControl( new s( U, i.showLabels, !0, t, "Change Gann Square Lables Visibility" ) ), (v = C()), (f = this.createColorPicker()), (q = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (Y = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), (K = this.createFontSizeEditor()), (Q = this.createFontEditor()), (J = i.labelsStyle), this.bindControl( new c(K, J.fontSize, parseInt, !0, t, "Change Text Font Size") ), this.bindControl(new c(Q, J.font, null, !0, t, "Change Text Font")), this.bindControl(new s(q, J.bold, !0, t, "Change Text Font Bold")), this.bindControl( new s(Y, J.italic, !0, t, "Change Text Font Italic") ), (Z = $( '<table class="property-page" cellspacing="0" cellpadding="2"><tr>' ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(Q) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(K) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .attr({ width: 1 }) .append(q) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .append(Y) ) .append($("</tr></table>"))), $('<td colspan="5" class="no-left-indent">') .append(Z) .appendTo(V); }), (i.prototype.widget = function() { return this._table; }), (i.prototype._getPropertySetter = function(e, t) { var o = this.model(), i = this._linetool; return function(n) { o.beginUndoMacro(t), o.saveLineToolState(i, "Save Gann Square State"), o.setProperty(e, n, t), o.saveLineToolState(i, "Save Gann Square State"), o.endUndoMacro(); }; }), (e.exports.LineToolGannComplexStylesPropertyPage = i); }, 1107: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.SliderBinder, p = a.ColorBinding, s = o(372).addColorPicker, d = o(1196).createLineWidthEditor, h = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addOneColorPropertyWidget = function(e) { var t = this.createOneColorForAllLinesWidget(), o = $("<tr>"); o .append($("<td>")) .append($("<td>")) .append(t.editor) .append($("<td>").append(t.label)), o.appendTo(e); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m, f, L, v, k, S, P, x, B, R, E, F; (this._table = $(document.createElement("table"))), this._table.addClass("property-page property-page-unpadded"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this._table.css({ width: "100%" }), (e = $("<tr>")), e.appendTo(this._table), (t = this._linetool.properties()), (o = $("<table>")), $("<td valign='top'>") .append(o) .appendTo(e), (i = $("<tr>")), $("<td colspan='3'>" + $.t("Levels") + "</td>").appendTo(i), i.appendTo(o); for (n in t.levels._childs) (a = t.levels[n]), (c = $("<tr>")), c.appendTo(o), $("<td>" + n + "</td>").appendTo(c), (b = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(b) .appendTo(c), (u = $("<td class='colorpicker-cell'>")), u.appendTo(c), (C = s(u)), (y = $("<td>")), y.appendTo(c), (g = d()), g.appendTo(y), this.bindControl( new r( b, a.visible, !0, this.model(), "Change Gann Line Visibility" ) ), this.bindControl( new p(C, a.color, !0, this.model(), "Change Gann Line Color", 0) ), this.bindControl( new l(g, a.width, !0, this.model(), "Change Gann Line Width") ); (T = $("<table>")), $("<td valign='top'>") .append(T) .appendTo(e), (w = $("<tr>")), $("<td colspan='4'>" + $.t("Fans") + "</td>").appendTo(w), w.appendTo(T); for (n in t.fanlines._childs) (_ = t.fanlines[n]), (m = $("<tr>")), m.appendTo(T), (b = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(b) .appendTo(m), (f = _.x.value() + "x" + _.y.value()), $("<td>" + f + "</td>").appendTo(m), (u = $("<td class='colorpicker-cell'>")), u.appendTo(m), (C = s(u)), (y = $("<td>")), y.appendTo(m), (g = d()), g.appendTo(y), this.bindControl( new r( b, _.visible, !0, this.model(), "Change Gann Line Visibility" ) ), this.bindControl( new p(C, _.color, !0, this.model(), "Change Gann Fan Color", 0) ), this.bindControl( new l(g, _.width, !0, this.model(), "Change Gann Line Width") ); (L = $("<table>")), $("<td valign='top'>") .append(L) .appendTo(e), (v = $("<tr>")), $("<td colspan='4'>" + $.t("Arcs") + "</td>").appendTo(v), v.appendTo(L); for (n in t.arcs._childs) (k = t.arcs[n]), (S = $("<tr>")), S.appendTo(L), (b = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(b) .appendTo(S), (f = k.x.value() + "x" + k.y.value()), $("<td>" + f + "</td>").appendTo(S), (u = $("<td class='colorpicker-cell'>")), u.appendTo(S), (C = s(u)), (y = $("<td>")), y.appendTo(S), (g = d()), g.appendTo(y), this.bindControl( new r( b, k.visible, !0, this.model(), "Change Gann Line Visibility" ) ), this.bindControl( new p(C, k.color, !0, this.model(), "Change Gann Arc Color", 0) ), this.bindControl( new l(g, k.width, !0, this.model(), "Change Gann Line Width") ); this.addOneColorPropertyWidget(L), (P = $("<tbody>").appendTo(this._table)), (x = $('<input type="checkbox" class="visibility-switch">')), (B = h()), (R = $("<tr>").appendTo(P)), (E = $("<table>")), $('<td colspan="3">') .append(E) .appendTo(R), (R = $("<tr>").appendTo(E)), $("<td>") .append(x) .appendTo(R), $("<td>" + $.t("Background") + "</td>").appendTo(R), $("<td>") .append(B) .appendTo(R), t.reverse && ((F = $("<input type='checkbox' class='visibility-switch'>")), (R = this.addLabeledRow(E, $.t("Reverse"), F, !0)), $("<td>") .append(F) .prependTo(R), this.bindControl( new r( F, t.reverse, !0, this.model(), "Change Gann Square Reverse" ) )), this.bindControl( new r( x, t.arcsBackground.fillBackground, !0, this.model(), "Change Gann Square Filling" ) ), this.bindControl( new l( B, t.arcsBackground.transparency, !0, this.model(), "Change Gann Square Background Transparency" ) ); }), (i.prototype.widget = function() { return this._table; }), (e.exports.LineToolGannFixedStylesPropertyPage = i); }, 1108: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SimpleComboBinder, s = a.SliderBinder, d = o(372).addColorPicker, h = o(1197).createLineStyleEditor, c = o(1196).createLineWidthEditor, b = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o, i) { var n, a, b, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._tbody), (n = "control-level-" + o + "-" + i), (a = $("<td>")), a.appendTo(m), (b = $( "<input type='checkbox' class='visibility-switch' id='" + n + "'>" )), b.appendTo(a), (u = this.createLabeledCell(e).appendTo(m)), u.find("label").attr("for", n), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = d(C)), (g = $("<td>")), g.appendTo(m), (T = c()), T.appendTo(g), (w = $("<td>")), w.appendTo(m), (_ = h()), _.render().appendTo(w), this.bindControl( new r( b, t.visible, !0, this.model(), "Change Gann Fan Line Visibility" ) ), this.bindControl( new l(y, t.color, !0, this.model(), "Change Gann Fan Line Color", 0) ), this.bindControl( new p( _, t.linestyle, parseInt, !0, this.model(), "Change Gann Fan Line Style" ) ), this.bindControl( new s( T, t.linewidth, !0, this.model(), "Change Gann Fan Line Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, l, p, d, h, c = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), u = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ); for (this._tbody = $("<tbody>").appendTo(c), e = 1; e <= 9; e++) (t = "level" + e), (o = this._linetool.properties()[t]), (i = o.coeff1.value()), (n = o.coeff2.value()), (a = "<sup>" + i + "</sup>&frasl;<sub>" + n + "</sub>"), this.addLevelEditor(a, o, i, n); this.addOneColorPropertyWidget(this._tbody), (l = $("<input type='checkbox' class='visibility-switch'>")), (p = this.addLabeledRow(u, $.t("Labels"), l)), $("<td>") .append(l) .prependTo(p), this.bindControl( new r( l, this._linetool.properties().showLabels, !0, this.model(), "Change Gann Fan Labels Visibility" ) ), (this._table = c.add(u)), (p = $("<tr>")), p.appendTo(this._table), (d = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(d) .appendTo(p), this.createLabeledCell($.t("Background"), d).appendTo(p), (h = b()), $('<td colspan="3">') .append(h) .appendTo(p), this.bindControl( new r( d, this._linetool.properties().fillBackground, !0, this.model(), "Change Pitchfan Background Visibility" ) ), this.bindControl( new s( h, this._linetool.properties().transparency, !0, this.model(), "Change Pitchfan Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1109: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.FloatBinder, p = a.ColorBinding, s = a.SliderBinder, d = o(372).addColorPicker, h = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, s, h, c, b = $("<tr>"); b.appendTo(e), (i = $("<td>")), i.appendTo(b), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), (a = $("<td>")), a.appendTo(b), (s = $("<input type='text'>")), s.appendTo(a), s.css("width", "70px"), this.bindControl( new r( n, o.visible, !0, this.model(), "Change Gann Square Line Visibility" ) ), this.bindControl( new l(s, o.coeff, !1, this.model(), "Change Pitchfork Line Coeff") ), (h = $("<td class='colorpicker-cell'>")), h.appendTo(b), (c = d(h)), this.bindControl( new p( c, o.color, !0, this.model(), "Change Gann Square Line Color", 0 ) ); }), (i.prototype.addFannEditor = function(e) { var t, o, i = $("<tr>").appendTo(e), n = $("<input type='checkbox' class='visibility-switch'>"); n.appendTo($("<td>").appendTo(i)), $("<td>" + $.t("Angles") + "</td>").appendTo(i), (t = $("<td class='colorpicker-cell'>").appendTo(i)), (o = d(t)), this.bindControl( new r( n, this._linetool.properties().fans.visible, !0, this.model(), "Change Gann Square Angles Visibility" ) ), this.bindControl( new p( o, this._linetool.properties().fans.color, !0, this.model(), "Change Gann Square Angles Color", 0 ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, l, p, d, c, b, u, C, y, g, T, w, _, m, f; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page property-page-unpadded"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this._table.css({ width: "100%" }), e = $("<tbody>").appendTo(this._table), t = $("<tr>"), t.appendTo(e), o = $('<td width="50%">'), o.appendTo(t), i = $('<td width="50%">'), i.appendTo(t), n = $('<table cellspacing="0" cellpadding="2">'), n.appendTo(o), n.addClass("property-page"), a = $('<table cellspacing="0" cellpadding="2">'), a.appendTo(i), a.addClass("property-page"), $( "<tr><td align='center' colspan='4'>" + $.t("Price Levels") + "</td></tr>" ).appendTo(n), $( "<tr><td align='center' colspan='4'>" + $.t("Time Levels") + "</td></tr>" ).appendTo(a), l = 1; l <= 7; l++ ) (p = "hlevel" + l), this.addLevelEditor( n, $.t("Level {0}").format(l), this._linetool.properties()[p] ); for (l = 1; l <= 7; l++) (p = "vlevel" + l), this.addLevelEditor( a, $.t("Level {0}").format(l), this._linetool.properties()[p] ); this.addFannEditor(n), this.addOneColorPropertyWidget(a), i.css({ "vertical-align": "top" }), o.css({ "vertical-align": "top" }), (d = $("<input type='checkbox' class='visibility-switch'>")), (c = $("<input type='checkbox' class='visibility-switch'>")), (b = $("<input type='checkbox' class='visibility-switch'>")), (u = $("<input type='checkbox' class='visibility-switch'>")), (C = $( '<table class="property-page property-page-unpadded" cellspacing="0" cellpadding="0">' ).css({ width: "100%" })), (y = $("<tr>").appendTo(C)), (g = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%", "vertical-align": "top" }) .appendTo(y) )), (T = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%", "vertical-align": "top" }) .appendTo(y) )), (w = this.addLabeledRow(g, $.t("Left Labels"), d)), $("<td>") .append(d) .prependTo(w), (w = this.addLabeledRow(T, $.t("Right Labels"), c)), $("<td>") .append(c) .prependTo(w), (w = this.addLabeledRow(g, $.t("Top Labels"), b)), $("<td>") .append(b) .prependTo(w), (w = this.addLabeledRow(T, $.t("Bottom Labels"), u)), $("<td>") .append(u) .prependTo(w), this.bindControl( new r( d, this._linetool.properties().showLeftLabels, !0, this.model(), "Change Gann Square Left Labels Visibility" ) ), this.bindControl( new r( c, this._linetool.properties().showRightLabels, !0, this.model(), "Change Gann Square Right Labels Visibility" ) ), this.bindControl( new r( b, this._linetool.properties().showTopLabels, !0, this.model(), "Change Gann Square Top Labels Visibility" ) ), this.bindControl( new r( u, this._linetool.properties().showBottomLabels, !0, this.model(), "Change Gann Square Bottom Labels Visibility" ) ), (this._table = this._table.add(C)), (w = $("<tr>")), w.appendTo(g), (_ = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(_) .appendTo(w), (m = h()), $("<td>") .append(m) .appendTo(w), this.bindControl( new r( _, this._linetool.properties().fillHorzBackground, !0, this.model(), "Change Gann Square Background Visibility" ) ), this.bindControl( new s( m, this._linetool.properties().horzTransparency, !0, this.model(), "Change Gann Square Background Transparency" ) ), (w = $("<tr>")), w.appendTo(T), (_ = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(_) .appendTo(w), (m = h()), $("<td>") .append(m) .appendTo(w), this.bindControl( new r( _, this._linetool.properties().fillVertBackground, !0, this.model(), "Change Gann Square Background Visibility" ) ), this.bindControl( new s( m, this._linetool.properties().vertTransparency, !0, this.model(), "Change Gann Square Background Transparency" ) ), this._linetool.properties().reverse && ((f = $("<input type='checkbox' class='visibility-switch'>")), (w = this.addLabeledRow(g, $.t("Reverse"), f)), $("<td>") .append(f) .prependTo(w), this.bindControl( new r( f, this._linetool.properties().reverse, !0, this.model(), "Change Gann Box Reverse" ) )), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1110: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238).ColorBinding; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = this.createColorPicker()), (t = $.t("Color") + ":"), (o = this.addLabeledRow(this._table, t)), $("<td>") .append(e) .appendTo(o), (i = this._linetool.properties()), (this._div = $("<div>").append(this._table)), this.bindControl( new a(e, i.color, !0, this.model(), "Change Icon Color") ), this.loadData(); }), (i.prototype.widget = function() { return this._div; }), (e.exports = i); }, 1111: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = a.SimpleComboBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c, b, u, C; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = d()), (t = this.createColorPicker()), (o = this.createColorPicker()), (i = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (n = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), (a = this.createFontSizeEditor()), (h = this.createFontEditor()), (c = this.addLabeledRow(this._table, "Border")), c.prepend("<td>"), $("<td>") .append(t) .appendTo(c), $("<td>") .append(e) .appendTo(c), (b = $('<input type="checkbox" class="visibility-switch">')), (u = this.createColorPicker()), (h = this.createFontEditor()), (c = this.addLabeledRow(this._table, "Background", b)), $("<td>") .append(b) .prependTo(c), $("<td>") .append(u) .appendTo(c), this.bindControl( new r( b, this._linetool.properties().fillBackground, !0, this.model(), "Change Pattern Filling" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Pattern Line Color" ) ), this.bindControl( new l( o, this._linetool.properties().textcolor, !0, this.model(), "Change Pattern Text Color" ) ), this.bindControl( new l( u, this._linetool.properties().backgroundColor, !0, this.model(), "Change Pattern Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Pattern Border Width" ) ), this.bindControl( new s( a, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new s( h, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new r( i, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new r( n, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (C = $( '<table class="property-page" cellspacing="0" cellpadding="2"><tr>' ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(o) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(h) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(a) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .attr({ width: 1 }) .append(i) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .append(n) ) .append($("</tr></table>"))), (c = this.addLabeledRow(this._table, "")), $('<td colspan="5">') .append(C) .appendTo(c), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1112: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } var n = o(8).Point, a = o(1195), r = o(238), l = r.ColorBinding, p = r.SimpleComboBinder, s = r.SimpleStringBinder, d = r.BooleanBinder, h = o(76); inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n = this.createColorPicker(), a = this.createFontSizeEditor(), r = this.createFontEditor(), h = this.createTextEditor(350, 200), c = this.createColorPicker(), b = this.createColorPicker(), u = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' ), C = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' ); this.bindControl( new l( n, this._linetool.properties().textColor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new p( a, this._linetool.properties().fontSize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new p( r, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new s( h, this._linetool.properties().text, null, !0, this.model(), "Change Text" ) ), this.bindControl( new l( c, this._linetool.properties().markerColor, !0, this.model(), "Change Marker and Border Color" ) ), this.bindControl( new l( b, this._linetool.properties().backgroundColor, !0, this.model(), "Change Background Color", this._linetool.properties().backgroundTransparency ) ), this.bindControl( new d( u, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new d( C, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (e = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (t = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (o = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (this._table = e.add(o).add(t)), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(n) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(r) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(a) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(u) ) .append($(document.createElement("td")).append(C)) .appendTo(e), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ colspan: 5 }) .append(h) ) .appendTo(e), (i = this.addLabeledRow(o, $.t("Label"))), $("<td>") .attr("colspan", 2) .append(c) .appendTo(i), (i = this.addLabeledRow(o, $.t("Background"))), $("<td>") .append(b) .appendTo(i), this.loadData(), setTimeout(function() { h.select(), h.focus(); }, 20); }), (i.prototype.widget = function() { return this._table; }), (i.prototype.dialogPosition = function(e, t) { var o, i, a, r, l, p, s, d, c, b; if (e && t) { for ( o = 0, i = this._linetool._model.paneForSource(this._linetool), a = h.getChartWidget(); o < a.paneWidgets().length; o++ ) if (a.paneWidgets()[o]._state === i) { r = $(a.paneWidgets()[o].canvas).offset().left; break; } return ( (l = (this._linetool.paneViews() || [])[0]), (p = new n(0, 0)), l && (p = l._floatPoints[0] || this._linetool._fixedPoints[0] || p), (s = (r || 0) + p.x), (d = this._linetool.getTooltipWidth()), (c = s - d / 2), (b = t.outerWidth()), e.left < c && e.left + b + 10 > c ? ((e.left -= e.left + b + 10 - c), e) : e.left > c && e.left < c + d + 10 ? ((e.left += c + d + 10 - e.left), e) : void 0 ); } }), (e.exports = i); }, 1113: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SimpleComboBinder, s = a.SliderBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m, f; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = $("<tbody>").appendTo(this._table)), (t = h()), (o = d()), (i = this.createColorPicker()), (n = $("<tr>").appendTo(e)), $("<td></td><td>" + $.t("Channel") + "</td>").appendTo(n), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $("<td>") .append(o.render()) .appendTo(n), (n = $("<tr>").appendTo(e)), (a = $("<td>").appendTo(n)), (c = $("<input type='checkbox' class='visibility-switch'>")), c.appendTo(a), this.createLabeledCell("Middle", c).appendTo(n), (b = h()), (u = d()), (C = this.createColorPicker()), $("<td>") .append(C) .appendTo(n), $("<td>") .append(b) .appendTo(n), $("<td>") .append(u.render()) .appendTo(n), (n = $("<tr>").appendTo(e)), (y = $("<td>").appendTo(n)), (g = $("<input type='checkbox' class='visibility-switch'>")), g.appendTo(y), this.createLabeledCell("Background", g).appendTo(n), (T = this.createColorPicker()), $("<td>") .append(T) .appendTo(n), (w = $("<tbody>").appendTo(this._table)), (_ = this.addEditorRow( w, "Extend Left", $("<input type='checkbox'>"), 2 )), (m = this.addEditorRow( w, "Extend Right", $("<input type='checkbox'>"), 2 )), (f = this._linetool.properties()), this.bindControl( new r( g, f.fillBackground, !0, this.model(), "Change Parallel Channel Fill Background" ) ), this.bindControl( new r( c, f.showMidline, !0, this.model(), "Change Parallel Channel Show Center Line" ) ), this.bindControl( new r( _, f.extendLeft, !0, this.model(), "Change Parallel Channel Extending Left" ) ), this.bindControl( new r( m, f.extendRight, !0, this.model(), "Change Parallel Channel Extending Right" ) ), this.bindControl( new l( i, f.linecolor, !0, this.model(), "Change Parallel Channel Color" ) ), this.bindControl( new p( o, f.linestyle, parseInt, !0, this.model(), "Change Parallel Channel Style" ) ), this.bindControl( new s( t, f.linewidth, !0, this.model(), "Change Parallel Channel Width" ) ), this.bindControl( new l( C, f.midlinecolor, !0, this.model(), "Change Parallel Channel Middle Color" ) ), this.bindControl( new p( u, f.midlinestyle, parseInt, !0, this.model(), "Change Parallel Channel Middle Style" ) ), this.bindControl( new s( b, f.midlinewidth, !0, this.model(), "Change Parallel Channel Middle Width" ) ), this.bindControl( new l( T, f.backgroundColor, !0, this.model(), "Change Parallel Channel Back Color", f.transparency ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1114: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.FloatBinder, p = a.ColorBinding, s = a.SimpleComboBinder, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), e ? ((i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), (a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( n, t.visible, !0, this.model(), "Change Pitchfork Line Visibility" ) ), this.bindControl( new l( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : $("<td colspan='2'>" + $.t("Median") + "</td>").appendTo(m), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), (w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new p(y, t.color, !0, this.model(), "Change Pitchfork Line Color"), 0 ), this.bindControl( new s( _, t.linestyle, parseInt, !0, this.model(), "Change Pitchfan Line Style" ) ), this.bindControl( new d( T, t.linewidth, !0, this.model(), "Change Pitchfan Line Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor(null, this._linetool.properties().median, !1), e = 0; e <= 8; e++ ) (t = "level" + e), this.addLevelEditor( $.t("Level {0}").format(e + 1), this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<tr>")), o.appendTo(this._table), (i = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(i) .appendTo(o), this.createLabeledCell($.t("Background"), i).appendTo(o), (n = u()), $('<td colspan="3">') .append(n) .appendTo(o), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Pitchfan Background Visibility" ) ), this.bindControl( new d( n, this._linetool.properties().transparency, !0, this.model(), "Change Pitchfan Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1115: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.FloatBinder, p = a.ColorBinding, s = a.SimpleComboBinder, d = a.SliderBinder, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.onResoreDefaults = function() { this._linetool .properties() .style.listeners() .fire(this._linetool.properties().style); }), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), e ? ((i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), (a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( n, t.visible, !0, this.model(), "Change Pitchfork Line Visibility" ) ), this.bindControl( new l( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : ($("<td></td>").appendTo(m), $("<td>" + $.t("Median") + "</td>").appendTo(m)), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), (w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new p( y, t.color, !0, this.model(), "Change Pitchfork Line Color", 0 ) ), this.bindControl( new s( _, t.linestyle, parseInt, !0, this.model(), "Change Pitchfork Line Style" ) ), this.bindControl( new d( T, t.linewidth, !0, this.model(), "Change Pitchfork Line Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor(null, this._linetool.properties().median, !1), e = 0; e <= 8; e++ ) (t = "level" + e), this.addLevelEditor( $.t("Level {0}").format(e + 1), this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $("<tr>")), o.appendTo(this._table), (i = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(i) .appendTo(o), this.createLabeledCell("Background", i).appendTo(o), (n = u()), $('<td colspan="3">') .append(n) .appendTo(o), (a = $( "<select><option value='0'>" + $.t("Original") + "</option><option value='3'>" + $.t("Schiff") + "</option><option value='1'>" + $.t("Modified Schiff") + "</option><option value='2'>" + $.t("Inside") + "</option></select>" )), (o = $("<tr>")), o.appendTo(this._table), $("<td>" + $.t("Style") + "</td>").appendTo(o), $("<td>") .append(a) .appendTo(o), this.bindControl( new s( a, this._linetool.properties().style, parseInt, !0, this.model(), "Change Pitchfork Style" ) ), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Pitchfork Background Visibility" ) ), this.bindControl( new d( n, this._linetool.properties().transparency, !0, this.model(), "Change Pitchfork Background Transparency" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1116: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = s()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Border")), o.prepend("<td>"), $("<td>") .append(t) .appendTo(o), $("<td>") .append(e) .appendTo(o), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Background", i)), $("<td>") .append(i) .prependTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Polyline Filling" ) ), this.bindControl( new l( t, this._linetool.properties().linecolor, !0, this.model(), "Change Polyline Line Color" ) ), this.bindControl( new l( n, this._linetool.properties().backgroundColor, !0, this.model(), "Change Polyline Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Polyline Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1117: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.ColorBinding, l = a.SliderBinder, p = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, s, d, h, c, b, u, C, y, g, T, w, _, m = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), f = $( '<table class="property-page property-page-unpadded" cellspacing="0" cellpadding="0">' ).css({ width: "100%" }), L = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ); (this._table = m.add(f).add(L)), (e = this.createColorPicker()), (t = p()), (o = this.addLabeledRow(m, "Line")), $("<td>") .append(e) .appendTo(o), $("<td>") .append(t) .appendTo(o), (i = $("<tr>").appendTo(f)), (n = $("<td>") .appendTo(i) .css({ "vertical-align": "top", width: "50%" })), (a = $("<td>") .appendTo(i) .css({ "vertical-align": "top", width: "50%" })), (s = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo(n)), (d = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo(a)), (h = this.addColorPickerRow(s, $.t("Source back color"))), (c = this.addColorPickerRow(s, $.t("Source text color"))), (b = this.addColorPickerRow(s, $.t("Source border color"))), (u = this.addColorPickerRow(s, $.t("Success back color"))), (C = this.addColorPickerRow(s, $.t("Success text color"))), (y = this.addColorPickerRow(d, $.t("Target back color"))), (g = this.addColorPickerRow(d, $.t("Target text color"))), (T = this.addColorPickerRow(d, $.t("Target border color"))), (w = this.addColorPickerRow(d, $.t("Failure back color"))), (_ = this.addColorPickerRow(d, $.t("Failure text color"))), this.bindControl( new r( e, this._linetool.properties().linecolor, !0, this.model(), "Forecast Line Color" ) ), this.bindControl( new l( t, this._linetool.properties().linewidth, !0, this.model(), "Forecast Line Width" ) ), this.bindControl( new r( e, this._linetool.properties().linecolor, !0, this.model(), "Forecast Line Color" ) ), this.bindControl( new l( t, this._linetool.properties().linewidth, !0, this.model(), "Forecast Line Width" ) ), this.bindControl( new r( h, this._linetool.properties().sourceBackColor, !0, this.model(), "Forecast Source Background Color", this._linetool.properties().transparency ) ), this.bindControl( new r( b, this._linetool.properties().sourceStrokeColor, !0, this.model(), "Forecast Source Border Color" ) ), this.bindControl( new r( c, this._linetool.properties().sourceTextColor, !0, this.model(), "Forecast Source Text Color" ) ), this.bindControl( new r( y, this._linetool.properties().targetBackColor, !0, this.model(), "Forecast Target Background Color" ) ), this.bindControl( new r( T, this._linetool.properties().targetStrokeColor, !0, this.model(), "Forecast Target Border Color" ) ), this.bindControl( new r( g, this._linetool.properties().targetTextColor, !0, this.model(), "Forecast Target Text Color" ) ), this.bindControl( new r( u, this._linetool.properties().successBackground, !0, this.model(), "Forecast Success Back Color" ) ), this.bindControl( new r( C, this._linetool.properties().successTextColor, !0, this.model(), "Forecast Success Text Color" ) ), this.bindControl( new r( w, this._linetool.properties().failureBackground, !0, this.model(), "Forecast Failure Back Color" ) ), this.bindControl( new r( _, this._linetool.properties().failureTextColor, !0, this.model(), "Forecast Failure Text Color" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1118: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = this.createColorPicker()), (t = this.createFontSizeEditor()), (o = this.createColorPicker()), (i = this.createColorPicker()), (n = this.addLabeledRow(this._table, $.t("Text"))), $("<td>") .append(e) .appendTo(n), $("<td>") .append(t) .appendTo(n), (n = this.addLabeledRow(this._table, $.t("Background"))), $("<td>") .append(o) .appendTo(n), (n = this.addLabeledRow(this._table, $.t("Border"))), $("<td>") .append(i) .appendTo(n), this.bindControl( new l( e, this._linetool.properties().color, !0, this.model(), "Change Price Text Color" ) ), this.bindControl( new r( t, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Price Text Font Size" ) ), this.bindControl( new l( o, this._linetool.properties().backgroundColor, !0, this.model(), "Change Background Color", this._linetool.properties().transparency ) ), this.bindControl( new l( i, this._linetool.properties().borderColor, !0, this.model(), "Change Border Color" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1119: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SliderBinder, l = a.ColorBinding, p = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = this.createColorPicker()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Background")), $("<td>") .append(e) .appendTo(o), $("<td>") .append(t) .appendTo(o), (i = p()), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Border")), $("<td>") .append(n) .appendTo(o), $("<td>").appendTo(o), $("<td>") .append(i) .appendTo(o), this.bindControl( new l( n, this._linetool.properties().trendline.color, !0, this.model(), "Change Projection Line Color" ) ), this.bindControl( new l( e, this._linetool.properties().color1, !0, this.model(), "Change Projection Background Color", this._linetool.properties().transparency ) ), this.bindControl( new l( t, this._linetool.properties().color2, !0, this.model(), "Change Projection Background Color", this._linetool.properties().transparency ) ), this.bindControl( new r( i, this._linetool.properties().linewidth, !0, this.model(), "Change Projection Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1120: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.ColorBinding, l = a.BooleanBinder, p = a.SliderBinder, s = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = s()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Border")), o.prepend("<td>"), $("<td>") .append(t) .appendTo(o), $("<td>") .append(e) .appendTo(o), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, "Background", i)), $("<td>") .append(i) .prependTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new l( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Rectangle Filling" ) ), this.bindControl( new r( t, this._linetool.properties().color, !0, this.model(), "Change Rectangle Line Color" ) ), this.bindControl( new r( n, this._linetool.properties().backgroundColor, !0, this.model(), "Change Rectangle Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Rectangle Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1121: function(e, t, o) { "use strict"; function i(e, t) { (this._chartWidget = e), (this._undoModel = t); } function n(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } var a = o(1195), r = o(238), l = r.SimpleStringBinder, p = r.SimpleComboBinder, s = r.ColorBinding, d = r.BooleanBinder; (i.prototype.attachSource = function(e, t) { (this._source = e), (this._edit = $("<textarea>")), this._edit.css("width", "300"), this._edit.css("height", "150"), this._edit.appendTo(this._chartWidget._jqMainDiv), this._edit.css("position", "absolute"), this._edit.css("left", t.x + "px"), this._edit.css("top", t.y + "px"), this._edit.val(e.properties().text.value()), this._edit.focus(); var o = this._edit; return ( o.select(), (this._binding = new l( o, e.properties().text, null, !0, this._undoModel, "change line tool text" )), this._edit.focusout(function() { e.properties().text.setValue(o.val()); }), this._edit.mousedown(function(e) { return !0; }), o ); }), inherit(n, a), (n.prototype.prepareLayout = function() { var e, t, o, i, n = this.createColorPicker(), a = this.createColorPicker(), r = this.createFontSizeEditor(), h = this.createFontEditor(), c = this.createTextEditor(350, 200), b = this.createColorPicker(), u = $('<input type="checkbox" class="visibility-switch">'), C = $('<input type="checkbox" class="visibility-switch">'), y = $('<input type="checkbox">'), g = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' ), T = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' ); this.bindControl( new s( n, this._linetool.properties().color, !0, this.model(), "Change Text Color" ) ), this.bindControl( new p( r, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new p( h, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new l( c, this._linetool.properties().text, null, !0, this.model(), "Change Text" ) ), this.bindControl( new s( b, this._linetool.properties().backgroundColor, !0, this.model(), "Change Text Background", this._linetool.properties().backgroundTransparency ) ), this.bindControl( new d( u, this._linetool.properties().fillBackground, !0, this.model(), "Change Text Background Fill" ) ), this.bindControl( new d( C, this._linetool.properties().drawBorder, !0, this.model(), "Change Text Border" ) ), this.bindControl( new s( a, this._linetool.properties().borderColor, !0, this.model(), "Change Text Border Color" ) ), this.bindControl( new d( y, this._linetool.properties().wordWrap, !0, this.model(), "Change Text Wrap" ) ), this.bindControl( new d( g, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new d( T, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (e = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (t = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (o = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (this._table = e.add(o).add(t)), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(n) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(h) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(r) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(g) ) .append($(document.createElement("td")).append(T)) .appendTo(e), $(document.createElement("tr")) .append( $(document.createElement("td")) .attr({ colspan: 5 }) .append(c) ) .appendTo(e), (i = this.addLabeledRow(t, $.t("Text Wrap"), y)), $("<td>") .append(y) .prependTo(i), (i = this.addLabeledRow(o, $.t("Background"), u)), $("<td>") .append(u) .prependTo(i), $("<td>") .append(b) .appendTo(i), (i = this.addLabeledRow(o, $.t("Border"), C)), $("<td>") .append(C) .prependTo(i), $("<td>") .append(a) .appendTo(i), this.loadData(), setTimeout(function() { c.select(), c.focus(); }, 20); }), (n.prototype.widget = function() { return this._table; }), (n.prototype.dialogPosition = function(e, t) { var o, i, n, a, r, l, p, s = 5, d = 0, h = this._linetool, c = h._model.paneForSource(h), b = this._model._chartWidget; return ( $.each(b.paneWidgets(), function(e, t) { if (t._state === c) return (d = $(t.canvas).offset().top), !1; }), e || (e = {}), (i = e.left), (n = e.top), (a = (this._linetool.paneViews() || [])[0]), a && (o = a._floatPoints[0]), o && ((i = o.x), (n = o.y + d)), (r = $(t).outerHeight()), (l = $(window).height()), (p = h.properties().fontsize.value()), (n = n + r + p + s <= l ? n + p + s : n - r - s), { top: n, left: i } ); }), (e.exports = n); }, 1122: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.SliderBinder, s = a.BooleanBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = h()), (o = d()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, $.t("Line"))), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), this._linetool.properties().fillBackground && ($("<td>").prependTo(n), (a = $('<input type="checkbox" class="visibility-switch">')), (c = this.createColorPicker()), (b = $("<tbody>").appendTo(this._table)), (n = $("<tr>").appendTo(b)), $("<td>") .append(a) .appendTo(n), $("<td>") .append($.t("Background")) .appendTo(n), $("<td>") .append(c) .appendTo(n)), this.bindControl( new l( i, this._linetool.properties().linecolor, !0, this.model(), "Change Time Cycles Color" ) ), this.bindControl( new r( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Time Cycles Line Style" ) ), this.bindControl( new p( t, this._linetool.properties().linewidth, !0, this.model(), "Change Time Cycles Line Width" ) ), a && (this.bindControl( new s( a, this._linetool.properties().fillBackground, !0, this.model(), "Change Time Cycles Filling" ) ), this.bindControl( new l( c, this._linetool.properties().backgroundColor, !0, this.model(), "Change Time Cycles Background Color", this._linetool.properties().transparency ) )); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1123: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o); } var n = o(1078); inherit(i, n), (e.exports = i); }, 1124: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.FloatBinder, l = a.BooleanBinder, p = a.SliderBinder, s = a.SimpleComboBinder, d = a.ColorBinding, h = o(372).addColorPicker, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor, u = o(1198).createTransparencyEditor; inherit(i, n), (i.prototype.addLevelEditor = function(e, t, o) { var i, n, a, u, C, y, g, T, w, _, m = $("<tr>"); m.appendTo(this._table), (i = $("<td>")), i.appendTo(m), (n = $("<input type='checkbox' class='visibility-switch'>")), n.appendTo(i), e ? ((a = $("<td>")), a.appendTo(m), (u = $("<input type='text'>")), u.appendTo(a), u.css("width", "70px"), this.bindControl( new r( u, t.coeff, !1, this.model(), "Change Pitchfork Line Coeff" ) )) : this.createLabeledCell($.t("Trend Line"), n).appendTo(m), (C = $("<td class='colorpicker-cell'>")), C.appendTo(m), (y = h(C)), (g = $("<td>")), g.appendTo(m), (T = b()), T.appendTo(g), (w = $("<td>")), w.appendTo(m), (_ = c()), _.render().appendTo(w), this.bindControl( new l( n, t.visible, !0, this.model(), "Change Pitchfork Line Visibility" ) ), this.bindControl( new d( y, t.color, !0, this.model(), "Change Pitchfork Line Color", 0 ) ), this.bindControl( new s( _, t.linestyle, parseInt, !0, this.model(), "Change Pitchfork Line Style" ) ), this.bindControl( new p( T, t.linewidth, parseInt, this.model(), "Change Pitchfork Line Width" ) ); }), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, d, h, c, b; for ( this._table = $(document.createElement("table")), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), this.addLevelEditor( null, this._linetool.properties().trendline, !1 ), e = 1; e <= 11; e++ ) (t = "level" + e), this.addLevelEditor( $.t("Level {0}").format(e), this._linetool.properties()[t], !1 ); this.addOneColorPropertyWidget(this._table), (o = $( '<table class="property-page property-page-unpadded" cellspacing="0" cellpadding="0">' ).css({ width: "100%" })), (i = $("<tr>").appendTo(o)), $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%" }) .appendTo(i) ), $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).appendTo( $("<td>") .css({ width: "50%" }) .appendTo(i) ), (n = $("<input type='checkbox' class='visibility-switch'>")), (a = this.addLabeledRow(this._table, $.t("Show Labels"), n)), $("<td>") .append(n) .prependTo(a), (r = $("<table cellspacing='0' cellpadding='0'>")), (d = $( "<select><option value='left'>" + $.t("left") + "</option><option value='center'>" + $.t("center") + "</option><option value='right'>" + $.t("right") + "</option></select>" )), (h = $( "<select><option value='top'>" + $.t("top") + "</option><option value='middle'>" + $.t("middle") + "</option><option value='bottom'>" + $.t("bottom") + "</option></select>" )), (a = $("<tr>")), a .append("<td>" + $.t("Labels") + "</td>") .append(d) .append("<td>&nbsp</td>") .append(h), a.appendTo(r), (a = $("<tr>")), $("<td colspan='5'>") .append(r) .appendTo(a), a.appendTo(this._table), this.bindControl( new s( d, this._linetool.properties().horzLabelsAlign, null, !0, this.model(), "Change Trend-Based Fib Time Labels Alignment" ) ), this.bindControl( new s( h, this._linetool.properties().vertLabelsAlign, null, !0, this.model(), "Change Trend-Based Fib Time Labels Alignment" ) ), (a = $("<tr>")), a.appendTo(this._table), (c = $("<input type='checkbox' class='visibility-switch'>")), $("<td>") .append(c) .appendTo(a), this.createLabeledCell($.t("Background"), c).appendTo(a), (b = u()), $('<td colspan="3">') .append(b) .appendTo(a), this.bindControl( new l( c, this._linetool.properties().fillBackground, !0, this.model(), "Change Fib Retracement Background Visibility" ) ), this.bindControl( new p( b, this._linetool.properties().transparency, !0, this.model(), "Change Fib Retracement Background Transparency" ) ), this.bindControl( new l( n, this._linetool.properties().showCoeffs, !0, this.model(), "Change Fib Retracement Extend Lines" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1125: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.SimpleComboBinder, l = a.ColorBinding, p = a.BooleanBinder, s = a.SliderBinder, d = o(1197).createLineStyleEditor, h = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g, T, w, _, m, f, L, v, k; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = h()), (o = d()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, $.t("Line"))), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), (a = $("<tbody>").appendTo(this._table)), (c = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (b = $('<input type="checkbox">').appendTo(c)), (u = $("<label>" + $.t("Extend") + " </label>").css({ "margin-left": "8px" })), (C = $('<input type="checkbox">').appendTo(u)), (y = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (g = $( "<select><option value='0'>" + $.t("Normal") + "</option><option value='1'>" + $.t("Arrow") + "</option></select>" )), (n = this.addLabeledRow(a, $.t("Left End"))), $('<td colspan="3">') .appendTo(n) .append(y) .append(c), (n = this.addLabeledRow(a, $.t("Right End"))), $('<td colspan="3">') .appendTo(n) .append(g) .append(u), (n = this.addLabeledRow(a, $.t("Stats Text Color"))), (T = this.createColorPicker()), $("<td>") .append(T) .appendTo(n), this.bindControl( new l( T, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), (w = $('<input type="checkbox">')), (_ = $('<input type="checkbox">')), (m = $('<input type="checkbox">')), (f = $('<input type="checkbox">')), (L = $('<input type="checkbox">')), (v = $('<input type="checkbox">')), (k = $('<input type="checkbox">')), (n = this.addLabeledRow(a, $.t("Show Price Range"))), $('<td colspan="3">') .appendTo(n) .append(w), (n = this.addLabeledRow(a, $.t("Show Bars Range"))), $('<td colspan="3">') .appendTo(n) .append(_), (n = this.addLabeledRow(a, $.t("Show Date/Time Range"))), $('<td colspan="3">') .appendTo(n) .append(m), (n = this.addLabeledRow(a, $.t("Show Distance"))), $('<td colspan="3">') .appendTo(n) .append(f), (n = this.addLabeledRow(a, $.t("Show Angle"))), $('<td colspan="3">') .appendTo(n) .append(L), (n = this.addLabeledRow(a, $.t("Always Show Stats"))), $('<td colspan="3">') .appendTo(n) .append(v), (n = this.addLabeledRow(a, $.t("Show Middle Point"))), $('<td colspan="3">') .appendTo(n) .append(k), this.bindControl( new p( b, this._linetool.properties().extendLeft, !0, this.model(), "Change Trend Line Extending Left" ) ), this.bindControl( new p( C, this._linetool.properties().extendRight, !0, this.model(), "Change Trend Line Extending Right" ) ), this.bindControl( new l( i, this._linetool.properties().linecolor, !0, this.model(), "Change Trend Line Color" ) ), this.bindControl( new r( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Trend Line Style" ) ), this.bindControl( new s( t, this._linetool.properties().linewidth, !0, this.model(), "Change Trend Line Width" ) ), this.bindControl( new r( y, this._linetool.properties().leftEnd, parseInt, !0, this.model(), "Change Trend Line Left End" ) ), this.bindControl( new r( g, this._linetool.properties().rightEnd, parseInt, !0, this.model(), "Change Trend Line Right End" ) ), this.bindControl( new p( w, this._linetool.properties().showPriceRange, !0, this.model(), "Change Trend Line Show Price Range" ) ), this.bindControl( new p( _, this._linetool.properties().showBarsRange, !0, this.model(), "Change Trend Line Show Bars Range" ) ), this.bindControl( new p( m, this._linetool.properties().showDateTimeRange, !0, this.model(), "Change Trend Line Show Date/Time Range" ) ), this.bindControl( new p( f, this._linetool.properties().showDistance, !0, this.model(), "Change Trend Line Show Distance" ) ), this.bindControl( new p( L, this._linetool.properties().showAngle, !0, this.model(), "Change Trend Line Show Angle" ) ), this.bindControl( new p( v, this._linetool.properties().alwaysShowStats, !0, this.model(), "Change Trend Line Always Show Stats" ) ), this.bindControl( new p( k, this._linetool.properties().showMiddlePoint, !0, this.model(), "Change Trend Line Show Middle Point" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1126: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = a.SimpleComboBinder, d = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, h, c, b, u, C; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = d()), (t = this.createColorPicker()), (o = this.createColorPicker()), (i = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (n = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), (a = this.createFontSizeEditor()), (h = this.createFontEditor()), (c = this.addLabeledRow(this._table, "Border")), c.prepend("<td>"), $("<td>") .append(t) .appendTo(c), $("<td>") .append(e) .appendTo(c), (b = $('<input type="checkbox" class="visibility-switch">')), (u = this.createColorPicker()), (h = this.createFontEditor()), (c = this.addLabeledRow(this._table, "Background", b)), $("<td>") .append(b) .prependTo(c), $("<td>") .append(u) .appendTo(c), this.bindControl( new r( b, this._linetool.properties().fillBackground, !0, this.model(), "Change Pattern Filling" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Pattern Line Color" ) ), this.bindControl( new l( o, this._linetool.properties().textcolor, !0, this.model(), "Change Pattern Text Color" ) ), this.bindControl( new l( u, this._linetool.properties().backgroundColor, !0, this.model(), "Change Pattern Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Pattern Border Width" ) ), this.bindControl( new s( a, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new s( h, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new r( i, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new r( n, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), (C = $( '<table class="property-page" cellspacing="0" cellpadding="2"><tr>' ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(o) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(h) ) .append( $(document.createElement("td")) .attr({ width: 1 }) .append(a) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .attr({ width: 1 }) .append(i) ) .append( $(document.createElement("td")) .css("vertical-align", "top") .append(n) ) .append($("</tr></table>"))), (c = this.addLabeledRow(this._table, "")), $('<td colspan="5">') .append(C) .appendTo(c), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1127: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t, o), this.prepareLayout(); } var n = o(1195), a = o(238), r = a.BooleanBinder, l = a.ColorBinding, p = a.SliderBinder, s = o(1196).createLineWidthEditor; inherit(i, n), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = s()), (t = this.createColorPicker()), (o = this.addLabeledRow(this._table, $.t("Border"))), o.prepend("<td>"), $("<td>") .append(t) .appendTo(o), $("<td>") .append(e) .appendTo(o), (i = $('<input type="checkbox" class="visibility-switch">')), (n = this.createColorPicker()), (o = this.addLabeledRow(this._table, $.t("Background"), i)), $("<td>") .append(i) .prependTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new r( i, this._linetool.properties().fillBackground, !0, this.model(), "Change Triangle Filling" ) ), this.bindControl( new l( t, this._linetool.properties().color, !0, this.model(), "Change Triangle Line Color" ) ), this.bindControl( new l( n, this._linetool.properties().backgroundColor, !0, this.model(), "Change Triangle Background Color", this._linetool.properties().transparency ) ), this.bindControl( new p( e, this._linetool.properties().linewidth, !0, this.model(), "Change Triangle Border Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1128: function(e, t, o) { "use strict"; (function(t) { function i(e, t, o) { a.call(this, e, t), (this._linetool = o), this.prepareLayout(); } var n = o(238), a = n.PropertyPage, r = n.BooleanBinder, l = n.RangeBinder; inherit(i, a), (i.prototype.prepareLayout = function() { var e, o, i, n, a, p, s, d, h, c, b, u; (this._block = $('<table class="property-page">')), (e = this._linetool.properties().intervalsVisibilities), t.enabled("seconds_resolution") && ((o = $("<tr>").appendTo(this._block)), (i = $("<label>").append($.t("Seconds"))), (n = $("<input type='checkbox'>") .addClass("visibility-checker") .prependTo(i)), $("<td>") .css("padding-right", "15px") .append(i) .appendTo(o), (a = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(a) .appendTo(o), (p = $("<div>") .addClass("slider-range ui-slider-horizontal") .slider()), $("<td>") .append(p) .appendTo(o), (s = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(s) .appendTo(o), this.bindControl( new r( n, e.seconds, !0, this.model(), "Change Line Tool Visibility On Seconds" ) ), this.bindControl( new l( p, [e.secondsFrom, e.secondsTo], [1, 59], !1, this.model(), [a, s], [$.t("Change Seconds From"), $.t("Change Seconds To")], n ) )), (o = $("<tr>").appendTo(this._block)), (i = $("<label>").append($.t("Minutes"))), (d = $("<input type='checkbox'>") .addClass("visibility-checker") .prependTo(i)), $("<td>") .css("padding-right", "15px") .append(i) .appendTo(o), (a = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(a) .appendTo(o), (p = $("<div>") .addClass("slider-range ui-slider-horizontal") .slider()), $("<td>") .append(p) .appendTo(o), (s = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(s) .appendTo(o), this.bindControl( new r( d, e.minutes, !0, this.model(), "Change Line Tool Visibility On Minutes" ) ), this.bindControl( new l( p, [e.minutesFrom, e.minutesTo], [1, 59], !1, this.model(), [a, s], [$.t("Change Minutes From"), $.t("Change Minutes To")], d ) ), (o = $("<tr>").appendTo(this._block)), (i = $("<label>").append($.t("Hours"))), (h = $("<input type='checkbox'>") .addClass("visibility-checker") .prependTo(i)), $("<td>") .append(i) .appendTo(o), (a = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(a) .appendTo(o), (p = $("<div>") .addClass("slider-range ui-slider-horizontal") .slider()), $("<td>") .append(p) .appendTo(o), (s = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(s) .appendTo(o), this.bindControl( new r( h, e.hours, !0, this.model(), "Change Line Tool Visibility On Hours" ) ), this.bindControl( new l( p, [e.hoursFrom, e.hoursTo], [1, 24], !1, this.model(), [a, s], [$.t("Change Minutes From"), $.t("Change Hours To")], h ) ), (o = $("<tr>").appendTo(this._block)), (i = $("<label>").append($.t("Days"))), (c = $("<input type='checkbox'>") .addClass("visibility-checker") .prependTo(i)), $("<td>") .append(i) .appendTo(o), (a = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(a) .appendTo(o), (p = $("<div>") .addClass("slider-range ui-slider-horizontal") .slider()), $("<td>") .append(p) .appendTo(o), (s = $("<input type='text'>").addClass("ticker-text")), $("<td>") .append(s) .appendTo(o), this.bindControl( new r( c, e.days, !0, this.model(), "Change Line Tool Visibility On Days" ) ), this.bindControl( new l( p, [e.daysFrom, e.daysTo], [1, 366], !1, this.model(), [a, s], [$.t("Change Minutes From"), $.t("Change Days To")], c ) ), (o = $("<tr>") .css("height", "29px") .appendTo(this._block)), (i = $("<label>").append($.t("Weeks"))), (b = $("<input type='checkbox'>").prependTo(i)), $("<td>") .append(i) .appendTo(o), this.bindControl( new r( b, e.weeks, !0, this.model(), "Change Line Tool Visibility On Weeks" ) ), (o = $("<tr>") .css("height", "29px") .appendTo(this._block)), (i = $("<label>").append($.t("Months"))), (u = $("<input type='checkbox'>").prependTo(i)), $("<td>") .append(i) .appendTo(o), this.bindControl( new r( u, e.months, !0, this.model(), "Change Line Tool Visibility On Months" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._block; }), (e.exports = i); }.call(t, o(5))); }, 1129: function(e, t, o) { "use strict"; function i(e, t) { a.call(this, e, t), this.prepareLayout(); } var n = o(238), a = n.PropertyPage, r = n.SimpleComboBinder; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = this.createKeyCombo({ open: $.t("Open"), high: $.t("High"), low: $.t("Low"), close: $.t("Close") })), (t = this.addLabeledRow( this._table, $.t("Source", { context: "compare" }) )), $("<td>") .appendTo(t) .append(e), this.bindControl( new r( e, this._property.inputs.source, null, !0, this.model(), "Change Price Source" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1130: function(e, t, o) { "use strict"; function i(e, t, o) { n.call(this, e, t), (this._linetool = o), this.prepareLayout(); } var n = o(238).PropertyPage, a = o(246).StudyInputsPropertyPage, r = o(1076), l = o(33), p = o(1201); inherit(i, r), (i.prototype.prepareLayout = function() { var e, t, o, i, n, r, s, d, h = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ), c = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).data({ "layout-tab": p.TabNames.inputs, "layout-tab-priority": p.TabPriority.Inputs }); for ( this._table = h.add(c), e = this._linetool.points(), t = 0; t < e.length; t++ ) (o = $("<tr>")), o.appendTo(h), (i = $("<td>")), i.html("Point " + (t + 1) + " Bar #"), i.appendTo(o), (n = $("<td>")), n.appendTo(o), (r = $("<input type='text'>")), r.appendTo(n), r.addClass("ticker"), (s = this._linetool.properties().points[t]), this.bindBarIndex( s.bar, r, this.model(), "Change " + this._linetool + " point bar index" ); (d = l.findStudyMetaInfo( this._model.studiesMetaData(), this._linetool.studyId() )), a.prototype.prepareLayoutImpl.call(this, d, c); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1131: function(e, t, o) { "use strict"; function i(e, t, o) { r.call(this, e, t), (this._study = o), this.prepareLayout(); } var n = o(1234), a = o(238), r = a.PropertyPage, l = a.BooleanBinder, p = a.SimpleComboBinder, s = o(378).StudyStylesPropertyPage, d = o(49); inherit(i, r), inherit(i, n), (i.prototype._isJapaneseChartsAvailable = function() { return !1; }), (i.prototype.prepareLayout = function() { var e, t, o, i, n = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), a = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), r = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), d = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), h = $( '<table class="property-page" cellspacing="0" cellpadding="2">' ), c = this._study.properties(); this._prepareSeriesStyleLayout(n, a, r, c), (this._table = n .add(a) .add(r) .add(d) .add(h)), (e = $('<input type="checkbox">')), (t = this.addLabeledRow(d, "Price Line", e)), $("<td>") .append(e) .prependTo(t), this.bindControl( new l( e, c.showPriceLine, !0, this.model(), "Change Price Price Line" ) ), (o = this.createSeriesMinTickEditor()), (i = $("<tr>")), i.appendTo(h), $("<td>" + $.t("Override Min Tick") + "</td>").appendTo(i), $("<td>") .append(o) .appendTo(i), this.bindControl( new p(o, c.minTick, null, !0, this.model(), "Change MinTick") ), s.prototype._putStudyDefaultStyles.call(this, h); }), (i.prototype.loadData = function() { this.superclass.prototype.loadData.call(this), this.switchStyle(); }), (i.prototype.switchStyle = function() { switch ( ($(this._barsTbody) .add(this._barsColorerTbody) .add(this._candlesTbody) .add(this._candlesColorerTbody) .add(this._hollowCandlesTbody) .add(this._lineTbody) .add(this._areaTbody) .add(this._baselineTbody) .css("display", "none"), this._study.properties().style.value()) ) { case d.STYLE_BARS: this._barsTbody.css("display", "table-row-group"), this._barsColorerTbody.css("display", "table-row-group"); break; case d.STYLE_CANDLES: this._candlesTbody.css("display", "table-row-group"), this._candlesColorerTbody.css("display", "table-row-group"); break; case d.STYLE_HOLLOW_CANDLES: this._hollowCandlesTbody.css("display", "table-row-group"); break; case d.STYLE_LINE: this._lineTbody.css("display", "table-row-group"); break; case d.STYLE_AREA: this._areaTbody.css("display", "table-row-group"); break; case d.STYLE_BASELINE: this._baselineTbody.css("display", "table-row-group"); } }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1132: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t), (this._study = o), this.prepareLayout(); } var n = o(238), a = n.PropertyPage, r = n.SimpleComboBinder, l = n.BooleanBinder, p = n.SliderBinder, s = n.ColorBinding, d = o(378).StudyStylesPropertyPage, h = o(1196).createLineWidthEditor; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, c, b, u, C, y, g = this; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this.createFontSizeEditor()), (t = this.createFontEditor()), (o = $("<input type='checkbox' class='visibility-switch'/>")), (i = this.createTableInTable(this._table)), (n = this.addLabeledRow(i, "Labels Font")), $("<td>") .append(t) .appendTo(n), $("<td>") .append(e) .appendTo(n), (a = this.createTableInTable(this._table)), (n = this.addLabeledRow(a, "Show Labels")), $("<td>") .append(o) .prependTo(n), (this.pivotTypes = { Traditional: { "S5/R5": !0, "S4/R4": !0, "S3/R3": !0, "S2/R2": !0, "S1/R1": !0, P: !0 }, Fibonacci: { "S3/R3": !0, "S2/R2": !0, "S1/R1": !0, P: !0 }, Woodie: { "S4/R4": !0, "S3/R3": !0, "S2/R2": !0, "S1/R1": !0, P: !0 }, Classic: { "S4/R4": !0, "S3/R3": !0, "S2/R2": !0, "S1/R1": !0, P: !0 }, DeMark: { "S1/R1": !0, P: !0 }, Camarilla: { "S4/R4": !0, "S3/R3": !0, "S2/R2": !0, "S1/R1": !0, P: !0 } }), this.bindControl( new r( t, this._study.properties().font, null, !0, this.model(), "Change Pivots Font" ) ), this.bindControl( new r( e, this._study.properties().fontsize, parseInt, !0, this.model(), "Change Pivots Font Size" ) ), this.bindControl( new l( o, this._property.levelsStyle.showLabels, !0, g.model(), "Show Pivot Labels" ) ), (c = this._property.levelsStyle.visibility), (b = this._property.levelsStyle.colors), (u = this._property.levelsStyle.widths), (g._rows = []), (C = function(e, t, o, i) { var n, a, r, l, p; for (n = 0; n < e._childs.length; n++) (a = e._childs[n]), (r = e[a]), (l = t[a]), (p = o[a]), i(r, l, p, a); }), C(c, b, u, function(e, t, o, i) { var n, r, d, c = $("<input type='checkbox' class='visibility-switch'/>"); g.bindControl(new l(c, e, !0, g.model(), "Change " + i)), (n = g.addLabeledRow(a, i, c)), $("<td>") .append(c) .prependTo(n), (r = g.createColorPicker()), $("<td>") .append(r) .appendTo(n), g.bindControl( new s(r, t, !0, g.model(), "Change " + i + " color") ), (d = h()), $("<td>") .append(d) .appendTo(n), g.bindControl( new p(d, o, !0, g.model(), "Change " + i + " width") ), g._rows.push({ row: n, label: i, visibilityEditor: c }); }), (y = g._study._properties.inputs.kind), g.lockNotUsedVisEditors(y.value()), y.subscribe(g, function(e) { g.lockNotUsedVisEditors(e.value()); }), d.prototype._putStudyDefaultStyles.call(this, this._table, 3); }), (i.prototype.lockNotUsedVisEditors = function(e) { var t, o, i, n, a = this; for (t = 0; t < a._rows.length; t++) (o = a._rows[t]), (i = o.label), (n = a.pivotTypes[e][i]), o.visibilityEditor.prop("disabled", !n), o.row.css("opacity", n ? 1 : 0.5); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1133: function(e, t, o) { "use strict"; function i(e, t, o) { r.call(this, e, t), (this._study = o), this.prepareLayout(); } var n = o(9).assert, a = o(238), r = a.PropertyPage, l = a.GreateTransformer, p = a.LessTransformer, s = a.ToIntTransformer, d = a.ToFloatTransformer, h = a.BooleanBinder, c = a.SimpleComboBinder, b = a.SimpleStringBinder, u = o(89).NumericFormatter; inherit(i, r), (i.prototype._getStrategyInputs = function() { for ( var e, t = 0, o = this._study.metaInfo(), i = {}; t < o.inputs.length; t++ ) (e = o.inputs[t]), "strategy_props" === e.groupId && (n( void 0 !== e.internalID, "Strategy input id=" + e.id + " doesn't have an internalID" ), (i[e.internalID] = o.inputs[t])); return TradingView.clone(i); }), (i.prototype._setStdInput = function(e, t, o) { var i, n, a, r, C, y, g, T, w, _, m, f; if (e) { if ( ((i = e.id), (n = "study_input-" + i + "-" + Date.now().toString(36) + "-" + Math.random().toString(36)), (a = $("<tr>").appendTo(this._$table)), (r = "Change " + t), (C = $( '<label for="' + n + '">' + $.t(t, { context: "input" }) + "</label>" )), "bool" === e.type) ) (g = $('<td colspan="3">').appendTo(a)), (y = $('<input id="' + n + '" type="checkbox">').appendTo(g)), C.appendTo(g), !0 !== o && this.bindControl( new h(y, this._property.inputs[i], !0, this.model(), r) ); else if ( ($("<td>") .addClass("propertypage-name-label") .append(C) .appendTo(a), (T = $('<td colspan="2">').appendTo(a)), e.options) ) { for ( y = $('<select id="' + n + '">').appendTo(T), w = 0; w < e.options.length; w++ ) (_ = e.options[w]), _ instanceof jQuery ? _.appendTo(y) : $('<option value="' + _ + '">' + _ + "</option>").appendTo( y ); !0 !== o && this.bindControl( new c(y, this._property.inputs[i], null, !0, this.model(), r) ); } else (y = $('<input id="' + n + '" type="text">').appendTo(T)), !0 !== o && (("integer" !== e.type && "float" !== e.type) || ((m = ["integer" === e.type ? s(e.defval) : d(e.defval)]), (0 === e.min || e.min) && m.push(l(e.min)), (0 === e.max || e.max) && m.push(p(e.max))), (f = new b( y, this._property.inputs[i], m, !1, this.model(), r )), "float" === e.type && f.addFormatter(function(e) { return new u().format(e); }), this.bindControl(f)), y.addClass("ticker"); return y; } }), (i.prototype._setPyramidingInputs = function(e) { var t = e.pyramiding, o = this._property.inputs[t.id], i = this._setStdInput( { id: "pyramiding_switch", type: "bool" }, $.t("Pyramiding"), !0 ), a = this._setStdInput(e.pyramiding, $.t("Allow up to")), r = a.closest("tr"); n(void 0 === this._onAllowUpToChanged), (this._onAllowUpToChanged = function(e) { e.value() > 0 ? (i.prop("checked", !0), a.removeAttr("disabled"), r.removeClass("disabled")) : (i.prop("checked", !1), a.attr("disabled", "disabled"), r.addClass("disabled")); }), o.subscribe(null, this._onAllowUpToChanged), i.change(function() { var e = !i.prop("checked"); o.setValue(e ? 0 : t.defval), e ? a.attr("disabled", "disabled") : a.removeAttr("disabled"), r.toggleClass("disabled", e); }), o.value() > 0 ? i.prop("checked", !0) : (i.prop("checked", !1), a.attr("disabled", "disabled"), r.addClass("disabled")), r .children() .last() .removeAttr("colspan"), $("<td>") .text($.t("orders", { context: "up to ... orders" })) .appendTo(r); }), (i.prototype._setQtyInputs = function(e) { function t(e) { return ( (e = +e), isNaN(e) || e < 0 ? 0 : ("percent_of_equity" !== a.val() ? (e = parseInt(e)) : e > 100 && (e = 100), e) ); } var o, i, n, a, r, l, p = this, s = e.default_qty_value, d = $.extend({}, e.default_qty_type), h = this._property.inputs[s.id], c = this._setStdInput(s, $.t("Order size"), !0), u = new b(c, h, t, !1, this.model(), "Change Order Size"); this.bindControl(u), (o = c.closest("td")), o.removeAttr("colspan"), (i = (this._study.reportData() && this._study.reportData().currency) || "USD"), (n = $('<option value="cash_per_order">' + i + "</option>")), (d.options = [ $('<option value="fixed">' + $.t("Contracts") + "</option>"), n, $( '<option value="percent_of_equity">' + $.t("% of equity") + "</option>" ) ]), (a = this._setStdInput(d, "type")), (r = a.closest("td")), (l = r.closest("tr")), r.removeAttr("colspan"), r.detach().insertAfter(o), l.remove(), this._study.watchedData.subscribe(function() { p.__updateComboCurrency(n, a, "cash_per_order"); }); }), (i.prototype.__updateComboCurrency = function(e, t, o, i) { var n, a = (this._study.reportData() && this._study.reportData().currency) || "USD"; i && (a += i), e.text(a), (n = t.closest("td")), n.find("a[href=#" + o + "]").text(a), e.prop("selected") && n.find(".sbSelector").text(a); }), (i.prototype._setFillLimitsInputs = function(e) { var t = this._setStdInput( e.backtest_fill_limits_assumption, $.t("Verify Price for Limit Orders") ), o = t.closest("td"); o.removeAttr("colSpan"), $("<td>") .text($.t("ticks", { context: "slippage ... ticks" })) .insertAfter(o); }), (i.prototype._setSlippageInputs = function(e) { var t, o; void 0 !== e.slippage && ((t = this._setStdInput(e.slippage, $.t("Slippage"))), (o = t.closest("td")), o.removeAttr("colSpan"), $("<td>") .text($.t("ticks", { context: "slippage ... ticks" })) .insertAfter(o)); }), (i.prototype._setCommissionInputs = function(e) { function t(e) { return ( (e = +e), isNaN(e) || e < 0 ? 0 : ("percent" !== c.val() ? (e = parseFloat(e)) : e > 100 && (e = 100), e) ); } var o, i, n, a, r, l, p, s, d, h, c, u, C; void 0 !== e.commission_value && void 0 !== e.commission_type && ((o = this), (i = e.commission_value), (n = $.extend({}, e.commission_type)), (a = this._property.inputs[i.id]), (r = this._setStdInput(i, $.t("Commission"), !0)), (l = new b(r, a, t, !1, this.model(), "Change Commission value")), this.bindControl(l), (p = r.closest("td")), p.removeAttr("colspan"), (s = (this._study.reportData() && this._study.reportData().currency) || "USD"), (d = $( '<option value="cash_per_order">' + s + $.t(" per order") + "</option>" )), (h = $( '<option value="cash_per_contract">' + s + $.t(" per contract") + "</option>" )), (n.options = [ $('<option value="percent">' + $.t("%") + "</option>"), d, h ]), (c = this._setStdInput(n, "type")), (u = c.closest("td")), (C = u.closest("tr")), u.removeAttr("colspan"), u.detach().insertAfter(p), C.remove(), this._study.watchedData.subscribe(function() { o.__updateComboCurrency(d, c, "cash_per_order", $.t(" per order")), o.__updateComboCurrency( h, c, "cash_per_contract", $.t(" per contract") ); })); }), (i.prototype.prepareLayout = function() { this._$table = $(document.createElement("table")) .addClass("property-page strategy-properties") .attr("cellspacing", "0") .attr("cellpadding", "2"); var e = this._getStrategyInputs(); (e.initial_capital.min = 1), this._setStdInput(e.initial_capital, $.t("Initial capital")), Array.isArray(e.currency.options) && "NONE" === e.currency.options[0] && (e.currency.options[0] = $( '<option value="NONE">' + $.t("Default") + "</option>" )), this._setStdInput(e.currency, $.t("Base currency")), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setPyramidingInputs(e), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setQtyInputs(e), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setStdInput( e.calc_on_order_fills, $.t("Recalculate After Order filled") ), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setStdInput( e.calc_on_every_tick, $.t("Recalculate On Every Tick") ), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setFillLimitsInputs(e), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setSlippageInputs(e), $('<tr class="spacer"><td colspan="3"></td></tr>').appendTo( this._$table ), this._setCommissionInputs(e), this.loadData(); }), (i.prototype.widget = function() { return this._$table; }), (i.prototype.loadData = function() { var e, t, o; r.prototype.loadData.call(this), (e = this._getStrategyInputs()), (t = e.pyramiding), (o = this._property.inputs[t.id]), o.setValue(o.value(), !0); }), (i.prototype.destroy = function() { var e, t, o; r.prototype.destroy.call(this), (e = this._getStrategyInputs()), (t = e.pyramiding), (o = this._property.inputs[t.id]), o.unsubscribe(null, this._onAllowUpToChanged); }), (e.exports = i); }, 1134: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t), (this._study = o), this.prepareLayout(); } var n = o(238), a = n.PropertyPage, r = n.BooleanBinder, l = n.SimpleComboBinder, p = n.SliderBinder, s = n.ColorBinding, d = o(1196).createLineWidthEditor, h = o(1235).createPlotEditor; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, i, n, a, c, b, u, C, y, g, T, w, _, m = this._study.properties(); (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this.addLabeledRow(this._table, "Volume")), (t = h()), $("<td>") .append(t) .appendTo(e), this.bindControl( new l( t, m.styles.vol.plottype, parseInt, !0, this.model(), "Change Volume Plot Style" ) ), (i = this._study.metaInfo().version <= 46 && "transparency" in m ? m.transparency : m.styles.vol.transparency), (n = this.createColorPicker()), $("<td>") .append(n) .appendTo(e), this.bindControl( new s( n, m.palettes.volumePalette.colors[0].color, !0, this.model(), "Change Up Volume color", i ) ), (a = this.createColorPicker()), $("<td>") .append(a) .appendTo(e), this.bindControl( new s( a, m.palettes.volumePalette.colors[1].color, !0, this.model(), "Change Down Volume color", i ) ), (c = $("<input type='checkbox'>")), $("<td>").appendTo(e), $("<td>") .append(c) .appendTo(e), $("<td>" + $.t("Price Line") + "</td>").appendTo(e), this.bindControl( new r( c, m.styles.vol.trackPrice, !0, this.model(), "Change Price Line" ) ), (b = m.styles.vol_ma), (u = this.addLabeledRow(this._table, "Volume MA")), (C = h()), $("<td>") .append(C) .appendTo(u), this.bindControl( new l( C, b.plottype, parseInt, !0, this.model(), "Change Volume MA Plot Style" ) ), $("<td>") .html("&nbsp;") .appendTo(u), (y = this.createColorPicker()), $("<td>") .append(y) .appendTo(u), this.bindControl( new s( y, b.color, !0, this.model(), "Change Volume MA color", b.transparency ) ), (g = d()), $("<td>") .append(g) .appendTo(u), this.bindControl( new p( g, b.linewidth, !0, this.model(), "Change Volume MA Line Width" ) ), (c = $("<input type='checkbox'>")), $("<td>") .append(c) .appendTo(u), $("<td>" + $.t("Price Line") + "</td>").appendTo(u), this.bindControl( new r(c, b.trackPrice, !0, this.model(), "Change Price Line") ), (T = this.createPrecisionEditor()), (w = $("<tr>")), w.appendTo(this._table), $("<td>" + $.t("Precision") + "</td>").appendTo(w), $("<td>") .append(T) .appendTo(w), this.bindControl( new l( T, this._study.properties().precision, null, !0, this.model(), "Change Volume Precision" ) ), (_ = o(378).StudyStylesPropertyPage), _.prototype._putStudyDefaultStyles.call(this, this._table, 8); }), (i.prototype.widget = function() { return this._table; }), (e.exports = i); }, 1195: function(e, t, o) { "use strict"; function i(e) { function t(t, o, i) { e.call(this, t, o, i), (this._linetool = i), (this._templateList = new s( this._linetool._constructor, this.applyTemplate.bind(this) )); } return ( inherit(t, e), (t.prototype.applyTemplate = function(e) { this.model().applyLineToolTemplate( this._linetool, e, "Apply Drawing Template" ), this.loadData(); }), (t.prototype.createTemplateButton = function(e) { var t = this; return ( (e = $.extend({}, e, { getDataForSaveAs: function() { return t._linetool.template(); } })), this._templateList.createButton(e) ); }), t ); } function n(e, t, o) { r.call(this, e, t), (this._linetool = o); } var a = o(238), r = a.PropertyPage, l = a.ColorBinding, p = o(372).addColorPicker, s = o(385); inherit(n, r), (n.prototype.createOneColorForAllLinesWidget = function() { var e = $("<td class='colorpicker-cell'>"); return ( this.bindControl( new l( p(e), this._linetool.properties().collectibleColors, !0, this.model(), "Change All Lines Color", 0 ) ), { label: $("<td>" + $.t("Use one color") + "</td>"), editor: e } ); }), (n.prototype.addOneColorPropertyWidget = function(e) { var t = this.createOneColorForAllLinesWidget(), o = $("<tr>"); o .append($("<td>")) .append(t.label) .append(t.editor), o.appendTo(e); }), (n = i(n)), (n.createTemplatesPropertyPage = i), (e.exports = n); }, 1196: function(e, t, o) { "use strict"; function i() { return $('<div class="linewidth-slider">').slider({ max: 4, min: 1, step: 1 }); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(384), (t.createLineWidthEditor = i); }, 1197: function(e, t, o) { "use strict"; function i() { return new n.Combobox([ { html: '<div class="tv-line-style-option tv-line-style-option--solid"/>', value: a.LINESTYLE_SOLID }, { html: '<div class="tv-line-style-option tv-line-style-option--dotted"/>', value: a.LINESTYLE_DOTTED }, { html: '<div class="tv-line-style-option tv-line-style-option--dashed"/>', value: a.LINESTYLE_DASHED } ]); } var n, a; Object.defineProperty(t, "__esModule", { value: !0 }), (n = o(1259)), (a = o(240)), (t.createLineStyleEditor = i); }, 1198: function(e, t, o) { "use strict"; function i(e) { var t = $( '<div class="transparency-slider"><div class="gradient"></div></div>' ).slider({ max: 100, min: 0, step: 1 }), o = [ "-moz-linear-gradient(left, %COLOR 0%, transparent 100%)", "-webkit-gradient(linear, left top, right top, color-stop(0%,%COLOR), color-stop(100%,transparent))", "-webkit-linear-gradient(left, %COLOR 0%,transparent 100%)", "-o-linear-gradient(left, %COLOR 0%,transparent 100%)", "linear-gradient(to right, %COLOR 0%,transparent 100%)" ]; return ( (t.updateColor = function(e) { var i = t.find(".gradient"); o.forEach(function(t) { i.css("background-image", t.replace(/%COLOR/, e)); }); }), e ? (t.updateColor(e.val() || "black"), e.on("change", function(e) { t.updateColor(e.target.value); })) : t.updateColor("black"), t ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(384), (t.createTransparencyEditor = i); }, 1201: function(e, t, o) { "use strict"; Object.defineProperty(t, "__esModule", { value: !0 }), (function(e) { (e[(e.Coordinates = 100)] = "Coordinates"), (e[(e.Display = 100)] = "Display"), (e[(e.Style = 200)] = "Style"), (e[(e.Inputs = 300)] = "Inputs"), (e[(e.Properties = 250)] = "Properties"); })(t.TabPriority || (t.TabPriority = {})), (function(e) { (e.background = "Background"), (e.coordinates = "Coordinates"), (e.drawings = "Drawings"), (e.events = "Events"), (e.eventsAndAlerts = "Events & Alerts"), (e.inputs = "Inputs"), (e.properties = "Properties"), (e.scales = "Scales"), (e.sourceCode = "Source Code"), (e.style = "Style"), (e.timezoneSessions = "Timezone/Sessions"), (e.trading = "Trading"), (e.visibility = "Visibility"); })(t.TabNames || (t.TabNames = {})), (function(e) { (e[(e.Default = 100)] = "Default"), (e[(e.UserSave = 200)] = "UserSave"), (e[(e.Override = 300)] = "Override"); })(t.TabOpenFrom || (t.TabOpenFrom = {})); }, 1234: function(e, t, o) { "use strict"; (function(t) { function i() {} var n = o(238), a = n.PropertyPage, r = n.GreateTransformer, l = n.LessTransformer, p = n.ToIntTransformer, s = n.ToFloatTransformer, d = n.SimpleStringBinder, h = n.SimpleComboBinder, c = n.ColorBinding, b = n.BooleanBinder, u = n.SliderBinder, C = o(49), y = o(1196).createLineWidthEditor, g = o(1258).createPriceSourceEditor, T = o(89).NumericFormatter; inherit(i, a), (i.prototype.i18nCache = [ window.t("Style"), window.t("Box size assignment method"), window.t("Color bars based on previous close"), window.t("Candles"), window.t("Borders"), window.t("Wick"), window.t("HLC Bars"), window.t("Price Source"), window.t("Type"), window.t( "Show real prices on price scale (instead of Heikin-Ashi price)" ), window.t("Up bars"), window.t("Down bars"), window.t("Projection up bars"), window.t("Projection down bars"), window.t("Line"), window.t("Fill"), window.t("Up Color"), window.t("Down Color"), window.t("Traditional"), window.t("ATR Length"), window.t("Number Of Line"), window.t("Reversal Amount"), window.t("Box Size") ]), (i.prototype.getInputTitle = function(e, t) { return "style" === e ? window.t("Box size assignment method") : "boxSize" === e ? window.t("Box Size") : t.inputInfo ? t.inputInfo[e].name.value() : e.toLowerCase().replace(/\b\w/g, function(e) { return e.toUpperCase(); }); }), (i.prototype.prepareLayoutImpl = function(e, t, o, i) { function n(t) { b.refreshStateControls(c, e.inputs, o.inputs); } function a(e) { return new T().format(e); } var c, b, u, C, y, g, w, _, m, f, L, v, k, S, P, x, B, R; for (i = i || {}, c = {}, b = this, u = 0; u < e.inputs.length; u++) { (C = e.inputs[u]), (y = C.id), (w = "BarSetRenko@<EMAIL>" === e.name || "BarSetKagi@tv-prostudies" === e.name || "BarSetPriceBreak@tv-prostudies" === e.name), "BarSetPnF@tv-prostudies" === e.name && "sources" === y && (C.options = C.options.filter(function(e) { return "HL" === e || "Close" === e; })); try { g = this.getInputTitle(y, o); } catch (e) { continue; } if ( ("BarSetRenko@tv-<EMAIL>" !== e.name || "wicks" !== y) && (!w || "source" !== y) ) { if ( ((_ = $("<tr/>")), C.isHidden || _.appendTo(t), (m = $( "<td" + (i.nameColspan ? ' colspan = "' + i.nameColspan + '"' : "") + "/>" )), m.appendTo(_), m.addClass("propertypage-name-label"), m.text($.t(g)), (f = $( "<td" + (i.valueColspan ? ' colspan = "' + i.valueColspan + '"' : "") + "/>" )), f.appendTo(_), (L = null), C.options) ) for (L = $("<select/>"), v = 0; v < C.options.length; v++) (k = C.options[v]), $( "<option value='" + k + "'>" + $.t(k) + "</option>" ).appendTo(L); else (L = $("<input/>")), "bool" === C.type ? L.attr("type", "checkbox") : L.attr("type", "text"); L.appendTo(f), L.css("width", "100px"), (S = "Change " + g), C.options ? this.bindControl( new h(L, o.inputs[y], null, !0, this.model(), S) ) : "integer" === C.type ? ((P = [p(C.defval)]), C.min && P.push(r(C.min)), C.max && P.push(l(C.max)), this.bindControl( new d(L, o.inputs[y], P, !1, this.model(), S) ), L.addClass("ticker")) : "float" === C.type ? ((P = [s(C.defval)]), C.min && (((("<EMAIL>" === e.id || "Bar<EMAIL>" === e.id) && "boxSize" === C.id) || ("BarSetKagi@<EMAIL>" === e.id && "reversalAmount" === C.id)) && ((B = this._model .model() .mainSeries() .symbolInfo()), (x = B.minmov / B.pricescale)), P.push(r(x || C.min))), C.max && P.push(l(C.max)), (R = new d(L, o.inputs[y], P, !1, this.model(), S)), R.addFormatter(a), this.bindControl(R), L.addClass("ticker")) : "text" === C.type && this.bindControl( new d( L, this._property.inputs[y], null, !1, this.model(), S ) ), L.change(n), (c[C.id] = _); } } this.refreshStateControls(c, e.inputs, o.inputs); }), (i.prototype.getMetaInfo = function(e) { var t, o = this._model.m_model._studiesMetaData; for (t = 0; t < o.length; t++) if (o[t].id === e) return o[t]; return null; }), (i.prototype._isJapaneseChartsAvailable = function() { return !0; }), (i.prototype._prepareSeriesStyleLayout = function(e, o, i, n) { var a, s, T, w, _, m, f, L, v, k, S, P, x, B, R, E, F, I, D, A, W, V, O, z, M, j, H, G, N, U, q, Y, K, Q, J, Z, X, ee, te, oe, ie, ne, ae, re, le, pe, se, de, he, ce, be, ue, Ce, ye, ge, $e, Te, we, _e, me, fe, Le, ve, ke, Se, Pe, xe, Be, Re, Ee, Fe, Ie, De, Ae, We, Ve, Oe, ze, Me, je = $("<tbody>").appendTo(e), He = (this._candlesColorerTbody = $("<tbody>").appendTo(o)), Ge = (this._barsColorerTbody = $("<tbody>").appendTo(o)), Ne = (this._haColorerTbody = $("<tbody>").appendTo(o)), Ue = (this._candlesTbody = $("<tbody>").appendTo(i)), qe = (this._hollowCandlesTbody = $("<tbody>").appendTo(i)), Ye = (this._haTbody = $("<tbody>").appendTo(i)), Ke = (this._barsTbody = $("<tbody>").appendTo(i)), Qe = (this._lineTbody = $("<tbody>").appendTo(i)), Je = (this._areaTbody = $("<tbody>").appendTo(i)), Ze = (this._renkoTbody = $("<tbody>").appendTo(i)), Xe = (this._pbTbody = $("<tbody>").appendTo(i)), et = (this._kagiTbody = $("<tbody>").appendTo(i)), tt = (this._pnfTbody = $("<tbody>").appendTo(i)), ot = (this._baselineTbody = $("<tbody>").appendTo(i)), it = this.addLabeledRow(je, "Style"), nt = $(document.createElement("td")).appendTo(it); nt.addClass("property-wide-select"), (a = $(document.createElement("select"))), $( "<option value=" + C.STYLE_BARS + ">" + $.t("Bars") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_CANDLES + ">" + $.t("Candles") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_HOLLOW_CANDLES + ">" + $.t("Hollow Candles") + "</option>" ).appendTo(a), this._isJapaneseChartsAvailable() && $( "<option value=" + C.STYLE_HEIKEN_ASHI + ">" + $.t("Heikin Ashi") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_LINE + ">" + $.t("Line") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_AREA + ">" + $.t("Area") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_BASELINE + ">" + $.t("Baseline") + "</option>" ).appendTo(a), a.css("width", "100px").appendTo(nt), this.switchStyle(), (s = function(e) { this._undoModel.setChartStyleProperty( this._property, e, this._undoText ); }), this.bindControl( new h( a, n.style, parseInt, !0, this.model(), "Change Series Style", s ) ), n.style.listeners().subscribe(this, this.switchStyle), (T = this.createColorPicker()), (w = this.createColorPicker()), (_ = this.createColorPicker()), (m = this.createColorPicker()), (f = this.createColorPicker()), (L = this.createColorPicker()), (v = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(f).add(L) )), (k = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(_).add(m) )), (S = $("<input type='checkbox'/>")), (P = this.addLabeledRow( He, "Color bars based on previous close", S )), $("<td>") .append(S) .prependTo(P), (P = this.addLabeledRow(Ue, "Candles")), $("<td>").prependTo(P), $("<td>") .append(T) .appendTo(P), $("<td>") .append(w) .appendTo(P), (P = this.addLabeledRow(Ue, "Borders", v)), $("<td>") .append(v) .prependTo(P), $("<td>") .append(f) .appendTo(P), $("<td>") .append(L) .appendTo(P), (P = this.addLabeledRow(Ue, "Wick", k)), $("<td>") .append(k) .prependTo(P), $("<td>") .append(_) .appendTo(P), $("<td>") .append(m) .appendTo(P), this.bindControl( new c( T, n.candleStyle.upColor, !0, this.model(), "Change Candle Up Color" ) ), this.bindControl( new c( w, n.candleStyle.downColor, !0, this.model(), "Change Candle Down Color" ) ), this.bindControl( new b( k, n.candleStyle.drawWick, !0, this.model(), "Change Candle Wick Visibility" ) ), this.bindControl( new c( _, n.candleStyle.wickUpColor, !0, this.model(), "Change Candle Wick Up Color" ) ), this.bindControl( new c( m, n.candleStyle.wickDownColor, !0, this.model(), "Change Candle Wick Down Color" ) ), this.bindControl( new b( v, n.candleStyle.drawBorder, !0, this.model(), "Change Candle Border Visibility" ) ), this.bindControl( new c( f, n.candleStyle.borderUpColor, !0, this.model(), "Change Candle Up Border Color" ) ), this.bindControl( new c( L, n.candleStyle.borderDownColor, !0, this.model(), "Change Candle Down Border Color" ) ), this.bindControl( new b( S, n.candleStyle.barColorsOnPrevClose, !0, this.model(), "Change Color Bars Based On Previous Close" ) ), (x = this.createColorPicker()), (B = this.createColorPicker()), (R = this.createColorPicker()), (E = this.createColorPicker()), (F = this.createColorPicker()), (I = this.createColorPicker()), (D = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(F).add(I) )), (A = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(R).add(E) )), (P = this.addLabeledRow(qe, "Candles")), $("<td>").prependTo(P), $("<td>") .append(x) .appendTo(P), $("<td>") .append(B) .appendTo(P), (P = this.addLabeledRow(qe, "Borders", D)), $("<td>") .append(D) .prependTo(P), $("<td>") .append(F) .appendTo(P), $("<td>") .append(I) .appendTo(P), (P = this.addLabeledRow(qe, "Wick", A)), $("<td>") .append(A) .prependTo(P), $("<td>") .append(R) .appendTo(P), $("<td>") .append(E) .appendTo(P), this.bindControl( new c( x, n.hollowCandleStyle.upColor, !0, this.model(), "Change Hollow Candle Up Color" ) ), this.bindControl( new c( B, n.hollowCandleStyle.downColor, !0, this.model(), "Change Hollow Candle Down Color" ) ), this.bindControl( new b( A, n.hollowCandleStyle.drawWick, !0, this.model(), "Change Hollow Candle Wick Visibility" ) ), this.bindControl( new c( R, n.hollowCandleStyle.wickUpColor, !0, this.model(), "Change Hollow Candle Wick Up Color" ) ), this.bindControl( new c( E, n.hollowCandleStyle.wickDownColor, !0, this.model(), "Change Hollow Candle Down Wick Color" ) ), this.bindControl( new b( D, n.hollowCandleStyle.drawBorder, !0, this.model(), "Change Hollow Candle Border Visibility" ) ), this.bindControl( new c( F, n.hollowCandleStyle.borderUpColor, !0, this.model(), "Change Hollow Candle Up Border Color" ) ), this.bindControl( new c( I, n.hollowCandleStyle.borderDownColor, !0, this.model(), "Change Hollow Candle Down Border Color" ) ), (W = $("<input type='checkbox'/>")), (P = this.addLabeledRow( Ge, "Color bars based on previous close", W )), $("<td>") .append(W) .prependTo(P), (V = $("<input type='checkbox'/>")), (P = this.addLabeledRow(Ge, "HLC Bars", V)), $("<td>") .append(V) .prependTo(P), (O = this.addColorPickerRow(Ke, "Up Color")), (z = this.addColorPickerRow(Ke, "Down Color")), this.bindControl( new c( O, n.barStyle.upColor, !0, this.model(), "Change Bar Up Color" ) ), this.bindControl( new c( z, n.barStyle.downColor, !0, this.model(), "Change Bar Down Color" ) ), this.bindControl( new b( W, n.barStyle.barColorsOnPrevClose, !0, this.model(), "Change Color Bars Based On Previous Close" ) ), this.bindControl( new b( V, n.barStyle.dontDrawOpen, !0, this.model(), "Change HLC Bars" ) ), (M = g()), (P = this.addLabeledRow(Qe, "Price Source")), $('<td colspan="3">') .append(M) .appendTo(P), (j = this.addLabeledRow(Qe, "Type")), (H = $('<td colspan="3">').appendTo(j)), H.addClass("property-wide-select"), (G = $(document.createElement("select"))), $( "<option value=" + C.STYLE_LINE_TYPE_SIMPLE + ">" + $.t("Simple") + "</option>" ).appendTo(G), $( "<option value=" + C.STYLE_LINE_TYPE_MARKERS + ">" + $.t("With Markers") + "</option>" ).appendTo(G), $( "<option value=" + C.STYLE_LINE_TYPE_STEP + ">" + $.t("Step") + "</option>" ).appendTo(G), G.appendTo(H), (P = this.addLabeledRow(Qe, "Line")), (N = this.createColorPicker()), (U = y()), $("<td>") .append(N) .appendTo(P), $("<td>") .append(U) .appendTo(P), this.bindControl( new h( M, n.lineStyle.priceSource, null, !0, this.model(), "Change Price Source" ) ), this.bindControl( new h( G, n.lineStyle.styleType, parseInt, !0, this.model(), "Change Line Type" ) ), this.bindControl( new c(N, n.lineStyle.color, !0, this.model(), "Change Line Color") ), this.bindControl( new u( U, n.lineStyle.linewidth, !0, this.model(), "Change Line Width" ) ), n.haStyle && ((q = this.createColorPicker()), (Y = this.createColorPicker()), (K = this.createColorPicker()), (Q = this.createColorPicker()), (J = this.createColorPicker()), (Z = this.createColorPicker()), (X = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(J).add(Z) )), (ee = $( "<input type='checkbox' class='visibility-switch'/>" ).data("hides", $(K).add(Q))), (te = $("<input type='checkbox'/>")), (P = this.addLabeledRow( Ne, $.t("Color bars based on previous close"), te )), $("<td>") .append(te) .prependTo(P), (P = this.addLabeledRow(Ye, $.t("Candles"))), $("<td>").prependTo(P), $("<td>") .append(q) .appendTo(P), $("<td>") .append(Y) .appendTo(P), (P = this.addLabeledRow(Ye, $.t("Borders"), X)), $("<td>") .append(X) .prependTo(P), $("<td>") .append(J) .appendTo(P), $("<td>") .append(Z) .appendTo(P), (P = this.addLabeledRow(Ye, $.t("Wick"), ee)), $("<td>") .append(ee) .prependTo(P), $("<td>") .append(K) .appendTo(P), $("<td>") .append(Q) .appendTo(P), this.bindControl( new c( q, n.haStyle.upColor, !0, this.model(), "Change Heikin Ashi Up Color" ) ), this.bindControl( new c( Y, n.haStyle.downColor, !0, this.model(), "Change Heikin Ashi Down Color" ) ), this.bindControl( new b( ee, n.haStyle.drawWick, !0, this.model(), "Change Heikin Ashi Wick Visibility" ) ), this.bindControl( new c( K, n.haStyle.wickUpColor, !0, this.model(), "Change Heikin Ashi Wick Up Color" ) ), this.bindControl( new c( Q, n.haStyle.wickDownColor, !0, this.model(), "Change Heikin Ashi Wick Down Color" ) ), this.bindControl( new b( X, n.haStyle.drawBorder, !0, this.model(), "Change Heikin Ashi Border Visibility" ) ), this.bindControl( new c( J, n.haStyle.borderUpColor, !0, this.model(), "Change Heikin Ashi Up Border Color" ) ), this.bindControl( new c( Z, n.haStyle.borderDownColor, !0, this.model(), "Change Heikin Ashi Down Border Color" ) ), this.bindControl( new b( te, n.haStyle.barColorsOnPrevClose, !0, this.model(), "Change Color Bars Based On Previous Close" ) )), this._isJapaneseChartsAvailable() && t.enabled("japanese_chart_styles") && ($( "<option value=" + C.STYLE_RENKO + ">" + $.t("Renko") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_PB + ">" + $.t("Line Break") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_KAGI + ">" + $.t("Kagi") + "</option>" ).appendTo(a), $( "<option value=" + C.STYLE_PNF + ">" + $.t("Point & Figure") + "</option>" ).appendTo(a), (oe = this.createColorPicker()), (ie = this.createColorPicker()), (P = this.addLabeledRow(Ze, "Up bars")), $("<td>").prependTo(P), $('<td class="some-colorpicker">') .append(oe) .append(ie) .appendTo(P), (ne = this.createColorPicker()), (ae = this.createColorPicker()), (P = this.addLabeledRow(Ze, "Down bars")), $("<td>").prependTo(P), $('<td class="some-colorpicker">') .append(ne) .append(ae) .appendTo(P), (re = this.createColorPicker()), (le = this.createColorPicker()), (P = this.addLabeledRow(Ze, "Projection up bars")), $("<td>").prependTo(P), $('<td class="some-colorpicker">') .append(re) .append(le) .appendTo(P), (pe = this.createColorPicker()), (se = this.createColorPicker()), (P = this.addLabeledRow(Ze, "Projection down bars")), $("<td>").prependTo(P), $('<td class="some-colorpicker">') .append(pe) .append(se) .appendTo(P), this.prepareLayoutImpl( this.getMetaInfo("BarSetRenko@tv-prostudies"), Ze, n.renkoStyle, { nameColspan: 2 } ), this.bindControl( new c( oe, n.renkoStyle.upColor, !0, this.model(), "Change Bar Up Color" ) ), this.bindControl( new c( ne, n.renkoStyle.downColor, !0, this.model(), "Change Bar Down Color" ) ), this.bindControl( new c( re, n.renkoStyle.upColorProjection, !0, this.model(), "Change Projection Bar Up Color" ) ), this.bindControl( new c( pe, n.renkoStyle.downColorProjection, !0, this.model(), "Change Projection Bar Down Color" ) ), this.bindControl( new c( ie, n.renkoStyle.borderUpColor, !0, this.model(), "Change Border Bar Up Color" ) ), this.bindControl( new c( ae, n.renkoStyle.borderDownColor, !0, this.model(), "Change Border Bar Down Color" ) ), this.bindControl( new c( le, n.renkoStyle.borderUpColorProjection, !0, this.model(), "Change Projection Border Bar Up Color" ) ), this.bindControl( new c( se, n.renkoStyle.borderDownColorProjection, !0, this.model(), "Change Projection Border Bar Down Color" ) ), (de = this.createColorPicker()), (he = this.createColorPicker()), (P = this.addLabeledRow(Xe, "Up bars")), $('<td class="some-colorpicker">') .append(de) .append(he) .appendTo(P), (ce = this.createColorPicker()), (be = this.createColorPicker()), (P = this.addLabeledRow(Xe, "Down bars")), $('<td class="some-colorpicker">') .append(ce) .append(be) .appendTo(P), (ue = this.createColorPicker()), (Ce = this.createColorPicker()), (P = this.addLabeledRow(Xe, "Projection up bars")), $('<td class="some-colorpicker">') .append(ue) .append(Ce) .appendTo(P), (ye = this.createColorPicker()), (ge = this.createColorPicker()), (P = this.addLabeledRow(Xe, "Projection down bars")), $('<td class="some-colorpicker">') .append(ye) .append(ge) .appendTo(P), this.prepareLayoutImpl( this.getMetaInfo("BarSetPriceBreak@tv-prostudies"), Xe, n.pbStyle, { valueColspan: 2 } ), this.bindControl( new c( de, n.pbStyle.upColor, !0, this.model(), "Change Bar Up Color" ) ), this.bindControl( new c( ce, n.pbStyle.downColor, !0, this.model(), "Change Bar Down Color" ) ), this.bindControl( new c( ue, n.pbStyle.upColorProjection, !0, this.model(), "Change Projection Bar Up Color" ) ), this.bindControl( new c( ye, n.pbStyle.downColorProjection, !0, this.model(), "Change Projection Bar Down Color" ) ), this.bindControl( new c( he, n.pbStyle.borderUpColor, !0, this.model(), "Change Border Bar Up Color" ) ), this.bindControl( new c( be, n.pbStyle.borderDownColor, !0, this.model(), "Change Border Bar Down Color" ) ), this.bindControl( new c( Ce, n.pbStyle.borderUpColorProjection, !0, this.model(), "Change Projection Border Bar Up Color" ) ), this.bindControl( new c( ge, n.pbStyle.borderDownColorProjection, !0, this.model(), "Change Projection Border Bar Down Color" ) ), ($e = this.addColorPickerRow(et, "Up bars")), (Te = this.addColorPickerRow(et, "Down bars")), (we = this.addColorPickerRow(et, "Projection up bars")), (_e = this.addColorPickerRow(et, "Projection down bars")), this.prepareLayoutImpl( this.getMetaInfo("BarSetKagi@tv-prostudies"), et, n.kagiStyle ), this.bindControl( new c( $e, n.kagiStyle.upColor, !0, this.model(), "Change Bar Up Color" ) ), this.bindControl( new c( Te, n.kagiStyle.downColor, !0, this.model(), "Change Bar Down Color" ) ), this.bindControl( new c( we, n.kagiStyle.upColorProjection, !0, this.model(), "Change Projection Bar Up Color" ) ), this.bindControl( new c( _e, n.kagiStyle.downColorProjection, !0, this.model(), "Change Projection Bar Down Color" ) ), (me = this.addColorPickerRow(tt, "Up bars")), (fe = this.addColorPickerRow(tt, "Down bars")), (Le = this.addColorPickerRow(tt, "Projection up bars")), (ve = this.addColorPickerRow(tt, "Projection down bars")), this.prepareLayoutImpl( this.getMetaInfo("BarSetPnF@tv-prostudies"), tt, n.pnfStyle ), this.bindControl( new c( me, n.pnfStyle.upColor, !0, this.model(), "Change Bar Up Color" ) ), this.bindControl( new c( fe, n.pnfStyle.downColor, !0, this.model(), "Change Bar Down Color" ) ), this.bindControl( new c( Le, n.pnfStyle.upColorProjection, !0, this.model(), "Change Projection Bar Up Color" ) ), this.bindControl( new c( ve, n.pnfStyle.downColorProjection, !0, this.model(), "Change Projection Bar Down Color" ) )), (ke = g()), (P = this.addLabeledRow(Je, "Price Source")), $('<td colspan="3">') .appendTo(P) .append(ke), (Se = this.createColorPicker()), (Pe = y()), (P = this.addLabeledRow(Je, "Line")), $("<td>") .appendTo(P) .append(Se), $('<td colspan="2">') .appendTo(P) .append(Pe), (xe = this.createColorPicker()), (Be = this.createColorPicker()), (P = this.addLabeledRow(Je, "Fill")), $("<td>") .appendTo(P) .append(xe), $("<td>") .appendTo(P) .append(Be), this.bindControl( new h( ke, n.areaStyle.priceSource, null, !0, this.model(), "Change Price Source" ) ), this.bindControl( new c( Se, n.areaStyle.linecolor, !0, this.model(), "Change Line Color" ) ), this.bindControl( new u( Pe, n.areaStyle.linewidth, !0, this.model(), "Change Line Width" ) ), this.bindControl( new c( xe, n.areaStyle.color1, !0, this.model(), "Change Line Color", n.areaStyle.transparency ) ), this.bindControl( new c( Be, n.areaStyle.color2, !0, this.model(), "Change Line Color", n.areaStyle.transparency ) ), (Re = g()), (P = this.addLabeledRow(ot, window.t("Price Source"))), $('<td colspan="3">') .appendTo(P) .append(Re), this.bindControl( new h( Re, n.baselineStyle.priceSource, null, !0, this.model(), "Change Price Source" ) ), (Ee = this.createColorPicker()), (Fe = y()), (P = this.addLabeledRow(ot, window.t("Top Line"))), $("<td>") .appendTo(P) .append(Ee), $("<td>") .appendTo(P) .append(Fe), this.bindControl( new c( Ee, n.baselineStyle.topLineColor, !0, this.model(), "Change Top Line Color" ) ), this.bindControl( new u( Fe, n.baselineStyle.topLineWidth, !0, this.model(), "Change Top Line Width" ) ), (Ie = this.createColorPicker()), (De = y()), (P = this.addLabeledRow(ot, window.t("Bottom Line"))), $("<td>") .appendTo(P) .append(Ie), $("<td>") .appendTo(P) .append(De), this.bindControl( new c( Ie, n.baselineStyle.bottomLineColor, !0, this.model(), "Change Bottom Line Color" ) ), this.bindControl( new u( De, n.baselineStyle.bottomLineWidth, !0, this.model(), "Change Bottom Line Width" ) ), (Ae = this.createColorPicker()), (We = this.createColorPicker()), (P = this.addLabeledRow(ot, window.t("Fill Top Area"))), $("<td>") .appendTo(P) .append(Ae), $("<td>") .appendTo(P) .append(We), this.bindControl( new c( Ae, n.baselineStyle.topFillColor1, !0, this.model(), "Change Fill Top Area Color 1" ), n.baselineStyle.transparency ), this.bindControl( new c( We, n.baselineStyle.topFillColor2, !0, this.model(), "Change Fill Top Area Color 2" ), n.baselineStyle.transparency ), (Ve = this.createColorPicker()), (Oe = this.createColorPicker()), (P = this.addLabeledRow(ot, window.t("Fill Bottom Area"))), $("<td>") .appendTo(P) .append(Ve), $("<td>") .appendTo(P) .append(Oe), this.bindControl( new c( Ve, n.baselineStyle.bottomFillColor1, !0, this.model(), "Change Fill Bottom Area Color 1" ), n.baselineStyle.transparency ), this.bindControl( new c( Oe, n.baselineStyle.bottomFillColor2, !0, this.model(), "Change Fill Bottom Area Color 2" ), n.baselineStyle.transparency ), (P = this.addLabeledRow(ot, window.t("Base Level"))), (ze = $('<input type="text" class="ticker">')), $('<td colspan="2">') .appendTo(P) .append($("<span></span>").append(ze)) .append($('<span class="percents-label">%</span>')), (Me = [ p(n.baselineStyle.baseLevelPercentage.value()), l(100), r(0) ]), this.bindControl( new d( ze, n.baselineStyle.baseLevelPercentage, Me, !0, this.model(), "Change Base Level" ) ); }), (e.exports = i); }.call(t, o(5))); }, 1235: function(e, t, o) { "use strict"; function i() { var e = $("<select />"); return ( $( '<option value="' + n.PlotType.Line + '">' + $.t("Line") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.LineWithBreaks + '">' + $.t("Line With Breaks") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.StepLine + '">' + $.t("Step Line") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.Histogram + '">' + $.t("Histogram") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.Cross + '">' + $.t("Cross", { context: "chart_type" }) + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.Area + '">' + $.t("Area") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.AreaWithBreaks + '">' + $.t("Area With Breaks") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.Columns + '">' + $.t("Columns") + "</option>" ).appendTo(e), $( '<option value="' + n.PlotType.Circles + '">' + $.t("Circles") + "</option>" ).appendTo(e), e ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(12); var n = o(111); t.createPlotEditor = i; }, 1258: function(e, t, o) { "use strict"; function i() { var e = $("<select>"); return ( $('<option value="open">' + $.t("Open") + "</option>").appendTo(e), $('<option value="high">' + $.t("High") + "</option>").appendTo(e), $('<option value="low">' + $.t("Low") + "</option>").appendTo(e), $('<option value="close">' + $.t("Close") + "</option>").appendTo(e), $('<option value="hl2">' + $.t("(H + L)/2") + "</option>").appendTo(e), $( '<option value="hlc3">' + $.t("(H + L + C)/3") + "</option>" ).appendTo(e), $( '<option value="ohlc4">' + $.t("(O + H + L + C)/4") + "</option>" ).appendTo(e), e ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(12), (t.createPriceSourceEditor = i); }, 1259: function(e, t, o) { "use strict"; var i, n; Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(389), (i = (function() { function e(e, t) { (this.value = e), (this.html = t), (this.jqItem = this._render()); } return ( (e.prototype.eq = function(e) { return this.value === e; }), (e.prototype.width = function() { return this.jqItem.width(); }), (e.prototype.render = function() { return this.jqItem; }), (e.prototype.select = function(e) { this.jqItem.toggleClass("selected", !!e); }), (e.prototype.selectAndReturnIfValueMatch = function(e) { return this.eq(e) ? (this.select(!0), this) : (this.select(!1), null); }), (e.prototype._render = function() { return $('<div class="item">').append($("<span>").html(this.html)); }), e ); })()), (t.ComboboxItem = i), (n = (function() { function e(e) { var t = this; (this._disabled = !1), (this._closeCb = null), (this.opened = !1), (this._value = null), (this.items = []), (this.width = 0), (this._jqWrapper = $('<div class="custom-select">')), this._jqWrapper.data({ disable: this.disable.bind(this), enable: this.enable.bind(this) }), this._jqWrapper.selectable(!1), (this._jqSwitcher = $('<div class="switcher">').appendTo( this._jqWrapper )), this._jqSwitcher.on("click", function() { t.toggleItems(); }), (this._jqTitle = $('<span class="title">').appendTo( this._jqSwitcher )), $('<span class="icon">').appendTo(this._jqSwitcher), (this._jqItems = $('<div class="items js-hidden">').appendTo( this._jqWrapper )), (this._callback = null), e && this.addItems(e); } return ( (e.prototype.toggleItems = function() { this.opened ? this._close() : this._open(); }), (e.prototype.setWidth = function() { this._jqWrapper.width(this.width); }), (e.prototype.render = function() { return this._jqWrapper; }), (e.prototype.selectItemByValue = function(e) { var t, o, i, n, a = null; for (t = 0, o = this.items; t < o.length; t++) (i = o[t]), (n = i.selectAndReturnIfValueMatch(e)) && (a = n); return a; }), (e.prototype.setValue = function(e) { if (this._value !== e) { var t = this.selectItemByValue(e); t && ((this._value = e), this._jqTitle.html(t.html), this.change()); } }), (e.prototype.change = function(e) { if (e) return void (this._callback = e); this._callback && this._callback.call(this); }), (e.prototype.value = function() { return this._value; }), (e.prototype.val = function(e) { return void 0 !== e ? void this.setValue(e) : this.value(); }), (e.prototype.addItems = function(e) { var t, o, i; for (t = 0, o = e; t < o.length; t++) (i = o[t]), this.addItem(i.value, i.html); }), (e.prototype.addItem = function(e, t) { var o, n = this, a = new i(e, t); this.items.push(a), (o = a.render()), o.on("click", function() { n.setValue(e), n.toggleItems(); }), this._jqItems.append(o), null === this.value() && this.setValue(e); }), (e.prototype.disable = function() { this._disabled = !0; }), (e.prototype.enable = function() { this._disabled = !1; }), (e.prototype.disabled = function() { return this._disabled; }), (e.prototype._open = function() { var e = this; console.debug("_OPEN"); this._disabled || (this._jqItems.removeClass("js-hidden"), this._jqSwitcher.addClass("open"), (this.opened = !0), this._closeCb || ((this._closeCb = { host: this._jqSwitcher.prop("ownerDocument"), cb: function(t) { e._jqWrapper[0].contains(t.target) || e._close(); } }), this._closeCb.host.addEventListener( "mousedown", this._closeCb.cb, !1 ))); }), (e.prototype._close = function() { console.debug("_CLOSE"); this._jqItems.addClass("js-hidden"), this._jqSwitcher.removeClass("open"), (this.opened = !1), this._closeCb && (this._closeCb.host.removeEventListener( "mousedown", this._closeCb.cb, !1 ), (this._closeCb = null)); }), e ); })()), (t.Combobox = n); }, 1260: function(e, t) {}, 1261: function(e, t) {}, 1262: function(e, t, o) { "use strict"; function i() { return $( '<select><option value="' + n.MARKLOC_ABOVEBAR + '">' + $.t("Above Bar") + '</option><option value="' + n.MARKLOC_BELOWBAR + '">' + $.t("Below Bar") + '</option><option value="' + n.MARKLOC_TOP + '">' + $.t("Top") + '</option><option value="' + n.MARKLOC_BOTTOM + '">' + $.t("Bottom") + '</option><option value="' + n.MARKLOC_ABSOLUTE + '">' + $.t("Absolute") + "</option></select>" ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(12); var n = o(240); t.createShapeLocationEditor = i; }, 1263: function(e, t, o) { "use strict"; function i() { var e = "<select>"; return ( Object.keys(n.plotShapesData).forEach(function(t) { var o = n.plotShapesData[t]; e += '<option value="' + o.id + '">' + o.guiName + "</option>"; }), (e += "</select>"), $(e) ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13); var n = o(111); t.createShapeStyleEditor = i; }, 1264: function(e, t, o) { "use strict"; function i() { return $('<input type="checkbox" class="visibility-switch"/>'); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), (t.createVisibilityEditor = i); }, 1265: function(e, t, o) { "use strict"; function i() { var e = $("<select />"); return ( $( '<option value="' + n.HHISTDIR_LEFTTORIGHT + '">' + $.t("Left") + "</option>" ).appendTo(e), $( '<option value="' + n.HHISTDIR_RIGHTTOLEFT + '">' + $.t("Right") + "</option>" ).appendTo(e), e ); } Object.defineProperty(t, "__esModule", { value: !0 }), o(13), o(12); var n = o(240); t.createHHistDirectionEditor = i; }, 378: function(e, t, o) { "use strict"; function i(e, t, o) { r.call(this, e, t), (this._study = o), this.prepareLayout(); } function n(e, t, o) { r.call(this, e, t), (this._study = o), (this._property = e), this.prepareLayout(); } var a = o(238), r = a.PropertyPage, l = a.GreateTransformer, p = a.LessTransformer, s = a.ToIntTransformer, d = a.ToFloatTransformer, h = a.SimpleComboBinder, c = a.BooleanBinder, b = a.DisabledBinder, u = a.ColorBinding, C = a.SliderBinder, y = a.SimpleStringBinder, g = o(372).addColorPicker, T = o(1197).createLineStyleEditor, w = o(1262).createShapeLocationEditor, _ = o(1263).createShapeStyleEditor, m = o(1196).createLineWidthEditor, f = o(1264).createVisibilityEditor, L = o(1265).createHHistDirectionEditor, v = o(1235).createPlotEditor, k = o(89).NumericFormatter, S = o(33), P = o(111).PlotType, x = o(7).getLogger("Chart.Study.PropertyPage"); inherit(i, r), (i.prototype.prepareLayout = function() { function e(e) { return new k().format(e); } var t, o, n, a, r, l, p, s, b, w, _, f, L, v, P, B, R, E, F, I, D, A, W, V, O, z, M, j, H, G, N, U, q, Y, K, Q; for ( this._table = $("<table/>"), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), t = this._study.metaInfo(), o = {}, n = 0; n < t.plots.length; ++n ) if ( !( this._study.isSelfColorerPlot(n) || this._study.isTextColorerPlot(n) || this._study.isDataOffsetPlot(n) || this._study.isOHLCColorerPlot(n) ) ) { if (((l = t.plots[n]), t.styles)) { if (t.styles[l.id]) a = t.styles[l.id].isHidden; else if (!this._study.isOHLCSeriesPlot(n)) continue; if (this._study.isOHLCSeriesPlot(n)) { if (((r = t.plots[n].target), o[r])) continue; (a = t.ohlcPlots[r].isHidden), (o[r] = r); } if (a) continue; } this._study.isLinePlot(n) || this._study.isBarColorerPlot(n) || this._study.isBgColorerPlot(n) ? this._prepareLayoutForPlot(n, l) : this._study.isPlotArrowsPlot(n) ? this._prepareLayoutForArrowsPlot(n, l) : this._study.isPlotCharsPlot(n) ? this._prepareLayoutForCharsPlot(n, l) : this._study.isPlotShapesPlot(n) ? this._prepareLayoutForShapesPlot(n, l) : this._study.isOHLCSeriesPlot(n) ? ((p = { id: r, type: "ohlc" }), this._study.isOHLCBarsPlot(n) ? this._prepareLayoutForBarsPlot(n, p) : this._study.isOHLCCandlesPlot(n) && this._prepareLayoutForCandlesPlot(n, p)) : x.logError("Unknown plot type: " + l.type); } if ((s = this._study.properties().bands) && s.childCount() > 0) for (n = 0; n < s.childCount(); n++) (b = s[n]), (b.isHidden && b.isHidden.value()) || ((w = $('<tr class="line"/>')), w.appendTo(this._table), (_ = $("<td/>")), _.appendTo(w), (f = $("<input type='checkbox' class='visibility-switch'/>")), f.appendTo(_), (L = $.t(b.name.value(), { context: "input" })), (v = this.createLabeledCell(L, f) .appendTo(w) .addClass("propertypage-name-label")), (P = $("<td/>")), P.appendTo(w), P.addClass("colorpicker-cell"), (B = g(P)), (R = $("<td/>")), R.appendTo(w), (E = m()), E.appendTo(R), (F = $('<td colspan="4">').css({ whiteSpace: "nowrap" })), F.appendTo(w), (I = T()), I.render().appendTo(F), (D = $("<input class='property-page-bandwidth' type='text'/>")), D.appendTo(F), (A = [d(b.value.value())]), (W = "Change band"), (V = new y(D, b.value, A, !1, this.model(), W)), V.addFormatter(e), this.bindControl(V), this.bindControl(new c(f, b.visible, !0, this.model(), W)), this.bindControl(new u(B, b.color, !0, this.model(), W)), this.bindControl( new h(I, b.linestyle, parseInt, !0, this.model(), W) ), this.bindControl(new C(E, b.linewidth, !0, this.model(), W))); if ( (this._study.properties().bandsBackground && ((b = this._study.properties().bandsBackground), (O = $.t("Background")), (W = $.t("Change band background")), (w = this._prepareFilledAreaBackground( b.fillBackground, b.backgroundColor, b.transparency, O, W )), w.appendTo(this._table)), this._study.properties().areaBackground && ((b = this._study.properties().areaBackground), (O = $.t("Background")), (W = $.t("Change area background")), (w = this._prepareFilledAreaBackground( b.fillBackground, b.backgroundColor, b.transparency, O, W )), w.appendTo(this._table)), void 0 !== (z = t.filledAreas)) ) for (n = 0; n < z.length; ++n) (M = z[n]), M.isHidden || ((W = "Change " + O), (b = this._study.properties().filledAreasStyle[M.id]), (O = M.title || $.t("Background")), M.palette ? ((w = $('<tr class="line"/>')), (_ = $("<td/>")), _.appendTo(w), (f = $( "<input type='checkbox' class='visibility-switch'/>" )), f.appendTo(_), this.bindControl( new c(f, b.visible, !0, this.model(), W + " visibility") ), this.createLabeledCell(O, f) .appendTo(w) .addClass("propertypage-name-label"), w.appendTo(this._table), (j = this._findPlotPalette(n, M)), (H = j.palette), (G = j.paletteProps), this._prepareLayoutForPalette(0, M, H, G, W)) : ((w = this._prepareFilledAreaBackground( b.visible, b.color, b.transparency, O, W )), w.appendTo(this._table))); for (N in t.graphics) { U = t.graphics[N]; for (q in U) (b = this._property.graphics[N][q]), i["_createRow_" + N].call(this, this._table, b); } (Y = this._table.find(".visibility-switch.plot-visibility-switch")), 1 === Y.length && ((_ = Y.parent()), _.css("display", "none"), (v = this._table.find(".propertypage-plot-with-palette")), 1 === v.length ? v.css("display", "none") : ((v = this._table.find(".propertypage-name-label")), v.css("padding-left", 0), v.find("label").attr("for", ""))), (K = this._prepareStudyPropertiesLayout()), (this._table = this._table.add(K)), S.isScriptStrategy(t) && ((Q = this._prepareOrdersSwitches()), (this._table = this._table.add(Q))), this.loadData(); }), (i.prototype._prepareOrdersSwitches = function() { var e, t, o, i, n, a, r, l = $( '<table class="property-page study-strategy-properties" cellspacing="0" cellpadding="2">' ), p = "chart-orders-switch_" + Date.now().toString(36), s = $("<tr>").appendTo(l), d = $('<input id="' + p + '" type="checkbox">').appendTo( $("<td>").appendTo(s) ); return ( $( '<label for="' + p + '">' + $.t("Trades on Chart") + "</label>" ).appendTo($("<td>").appendTo(s)), (e = "chart-orders-labels-switch_" + Date.now().toString(36)), (t = $("<tr>").appendTo(l)), (o = $('<input id="' + e + '" type="checkbox">').appendTo( $("<td>").appendTo(t) )), $( '<label for="' + e + '">' + $.t("Signal Labels") + "</label>" ).appendTo($("<td>").appendTo(t)), (i = "chart-orders-qty-switch_" + Date.now().toString(36)), (n = $("<tr>").appendTo(l)), (a = $('<input id="' + i + '" type="checkbox">').appendTo( $("<td>").appendTo(n) )), $('<label for="' + i + '">' + $.t("Quantity") + "</label>").appendTo( $("<td>").appendTo(n) ), (r = this._study.properties()), this.bindControl( new c( d, r.strategy.orders.visible, !0, this.model(), "Trades on chart visibility" ) ), this.bindControl( new c( o, r.strategy.orders.showLabels, !0, this.model(), "Signal labels visibility" ) ), this.bindControl( new b( o, r.strategy.orders.visible, !0, this.model(), "Signal labels visibility", !0 ) ), this.bindControl( new c( a, r.strategy.orders.showQty, !0, this.model(), "Quantity visibility" ) ), this.bindControl( new b( a, r.strategy.orders.visible, !0, this.model(), "Quantity visibility", !0 ) ), l ); }), (i.prototype._prepareLayoutForPlot = function(e, t) { var o, i, n, a, r, l, p, s, d, b, y, T, w = t.id, _ = this._study.properties().styles[w], f = this._findPlotPalette(e, t), L = f.palette, k = f.paletteProps, S = "Change " + w; L ? ((o = $('<tr class="line"/>')), o.appendTo(this._table), (i = $("<td/>")), i.appendTo(o), i.addClass("visibility-cell"), (n = $( "<input type='checkbox' class='visibility-switch plot-visibility-switch'/>" )), n.appendTo(i), this.bindControl(new c(n, _.visible, !0, this.model(), S)), (a = $.t(_.title.value(), { context: "input" })), this.createLabeledCell(a, n) .appendTo(o) .addClass( "propertypage-name-label propertypage-plot-with-palette" ), this._prepareLayoutForPalette(e, t, L, k, S)) : ((o = $('<tr class="line"/>')), o.appendTo(this._table), (i = $("<td/>")), i.appendTo(o), i.addClass("visibility-cell"), (n = $( "<input type='checkbox' class='visibility-switch plot-visibility-switch'/>" )), n.appendTo(i), (a = $.t(this._study.properties().styles[w].title.value(), { context: "input" })), this.createLabeledCell(a, n) .appendTo(o) .addClass("propertypage-name-label"), (r = $("<td/>")), r.appendTo(o), r.addClass("colorpicker-cell"), (l = g(r)), (p = $("<td/>")), p.appendTo(o), (s = m()), s.appendTo(p), (d = $("<td>")), d.appendTo(o), (b = v()), b.appendTo(d), (y = $("<td>")), y.appendTo(o), (T = $("<input type='checkbox'>")), T.appendTo(y), this.createLabeledCell("Price Line", T).appendTo(o), this.bindControl(new c(n, _.visible, !0, this.model(), S)), this.bindControl( new u(l, _.color, !0, this.model(), S, _.transparency) ), this.bindControl( new C( s, _.linewidth, !0, this.model(), S, this._study.metaInfo().isTVScript ) ), this.bindControl( new h(b, _.plottype, parseInt, !0, this.model(), S) ), this.bindControl( new c(T, _.trackPrice, !0, this.model(), "Change Price Line") )); }), (i.prototype._prepareLayoutForBarsPlot = function(e, t) { var o, i, n, a, r, l, p = t.id, s = this._study.properties().ohlcPlots[p], d = this._findPlotPalette(e, t), h = d.palette, b = d.paletteProps, C = "Change " + p, y = $('<tr class="line"/>'); y.appendTo(this._table), (o = $("<td/>")), o.appendTo(y), o.addClass("visibility-cell"), (i = $("<input type='checkbox' class='visibility-switch'/>")), i.appendTo(o), this.bindControl(new c(i, s.visible, !0, this.model(), C)), (n = s.title.value()), this.createLabeledCell(n, i) .appendTo(y) .addClass("propertypage-name-label"), h ? ((a = !0), this._prepareLayoutForPalette(e, t, h, b, C, a)) : ((r = $("<td/>")), r.appendTo(y), r.addClass("colorpicker-cell"), (l = g(r)), this.bindControl(new u(l, s.color, !0, this.model(), C))); }), (i.prototype._prepareLayoutForCandlesPlot = function(e, t) { var o, i, n, a, r, l, p, s, d; this._prepareLayoutForBarsPlot(e, t), (o = t.id), (i = this._study.properties().ohlcPlots[o]), (n = "Change " + o), (a = $('<tr class="line"/>')), a.appendTo(this._table), (r = $("<td/>")), r.appendTo(a), r.addClass("visibility-cell"), (l = $("<input type='checkbox' class='visibility-switch'/>")), l.appendTo(r), this.bindControl(new c(l, i.drawWick, !0, this.model(), n)), (p = "Wick"), this.createLabeledCell(p, l).appendTo(a), (s = $("<td/>")), s.appendTo(a), s.addClass("colorpicker-cell"), (d = g(s)), this.bindControl(new u(d, i.wickColor, !0, this.model(), n)); }), (i.prototype._prepareLayoutForShapesPlot = function(e, t) { var o, i, n, a, r, l, p, s, d, b = t.id, C = this._study.properties().styles[b], y = this._findPlotPalette(e, t), T = y.palette, m = y.paletteProps, f = "Change " + b, L = $('<tr class="line"/>'); L.appendTo(this._table), (o = $("<td/>")), o.appendTo(L), o.addClass("visibility-cell"), (i = $("<input type='checkbox' class='visibility-switch'/>")), i.appendTo(o), this.bindControl(new c(i, C.visible, !0, this.model(), f)), (n = $.t(this._study.properties().styles[b].title.value(), { context: "input" })), this.createLabeledCell(n, i) .appendTo(L) .addClass("propertypage-name-label"), (a = $("<td/>")), a.appendTo(L), (r = _()), r.appendTo(a), this.bindControl(new h(r, C.plottype, null, !0, this.model(), f)), (l = $("<td/>")), l.appendTo(L), (p = w()), p.appendTo(l), this.bindControl(new h(p, C.location, null, !0, this.model(), f)), T ? this._prepareLayoutForPalette(e, t, T, m, f) : ((L = $('<tr class="line"/>')), L.appendTo(this._table), $("<td/>").appendTo(L), $("<td/>").appendTo(L), (s = $("<td/>")), s.appendTo(L), s.addClass("colorpicker-cell"), (d = g(s)), this.bindControl( new u(d, C.color, !0, this.model(), f, C.transparency) )); }), (i.prototype._prepareLayoutForCharsPlot = function(e, t) { var o, i, n, a, r, l, p, s, d, b = t.id, C = this._study.properties().styles[b], T = this._findPlotPalette(e, t), _ = T.palette, m = T.paletteProps, f = "Change " + b, L = $('<tr class="line"/>'); L.appendTo(this._table), (o = $("<td/>")), o.appendTo(L), o.addClass("visibility-cell"), (i = $("<input type='checkbox' class='visibility-switch'/>")), i.appendTo(o), this.bindControl(new c(i, C.visible, !0, this.model(), f)), (n = $.t(this._study.properties().styles[b].title.value(), { context: "input" })), this.createLabeledCell(n, i) .appendTo(L) .addClass("propertypage-name-label"), (a = $("<td/>")), a.appendTo(L), (r = $('<input type="text"/>')), r.appendTo(a), r.keyup(function() { var e = $(this), t = e.val(); t && (e.val(t.split("")[t.length - 1]), e.change()); }), this.bindControl(new y(r, C.char, null, !1, this.model(), f)), (l = $("<td/>")), l.appendTo(L), (p = w()), p.appendTo(l), this.bindControl(new h(p, C.location, null, !0, this.model(), f)), _ ? this._prepareLayoutForPalette(e, t, _, m, f) : ((L = $('<tr class="line"/>')), L.appendTo(this._table), $("<td/>").appendTo(L), $("<td/>").appendTo(L), (s = $("<td/>")), s.appendTo(L), s.addClass("colorpicker-cell"), (d = g(s)), this.bindControl( new u(d, C.color, !0, this.model(), f, C.transparency) )); }), (i.prototype._isStyleNeedsConnectPoints = function(e) { return [P.Cross, P.Circles].indexOf(e) >= 0; }), (i.prototype._prepareLayoutForPalette = function(e, t, o, i, n, a) { var r, l, p, s, d, b, y, T, w, _, f, L, k, S, P, x = e, B = t.id, R = null, E = B.startsWith("fill"); (R = a ? this._study.properties().ohlcPlots[B] : E ? this._study.properties().filledAreasStyle[B] : this._study.properties().styles[B]), (r = 0); for (l in o.colors) (p = i.colors[l]), (s = $('<tr class="line"/>')), s.appendTo(this._table), $("<td/>").appendTo(s), (d = $("<td/>")), d.appendTo(s), d.addClass("propertypage-name-label"), d.html($.t(p.name.value(), { context: "input" })), (b = $("<td/>")), b.appendTo(s), b.addClass("colorpicker-cell"), (y = g(b)), this.bindControl( new u(y, p.color, !0, this.model(), n, R.transparency) ), !E && this._study.isLinePlot(x) && ((T = $("<td/>")), T.appendTo(s), (w = m()), w.appendTo(T), this.bindControl( new C( w, p.width, !0, this.model(), n, this._study.metaInfo().isTVScript ) ), (_ = $("<td>")), _.appendTo(s), 0 === r && ((f = v()), f.appendTo(_), this.bindControl( new h(f, R.plottype, parseInt, !0, this.model(), n) ), (L = $("<input type='checkbox'>")), (k = $('<td colspan="4">').css({ whiteSpace: "nowrap" })), (S = $("<span>").html($.t("Price Line"))), (P = $("<span>")), P.append(L), k .append(P) .append(S) .appendTo(s), this.bindControl( new c(L, R.trackPrice, !0, this.model(), "Change Price Line") ))), r++; }), (i.prototype._prepareLayoutForArrowsPlot = function(e, t) { var o, i, n, a, r, l, p, s = t.id, d = this._study.properties().styles[s], h = "Change " + s, b = $('<tr class="line"/>'); b.appendTo(this._table), (o = $("<td/>")), o.appendTo(b), o.addClass("visibility-cell"), (i = $("<input type='checkbox' class='visibility-switch'/>")), i.appendTo(o), (n = $.t(this._study.properties().styles[s].title.value(), { context: "input" })), this.createLabeledCell(n, i) .appendTo(b) .addClass("propertypage-name-label"), (a = $("<td/>")), a.appendTo(b), a.addClass("colorpicker-cell"), (r = g(a)), (l = $("<td/>")), l.appendTo(b), l.addClass("colorpicker-cell"), (p = g(l)), this.bindControl(new c(i, d.visible, !0, this.model(), h)), this.bindControl( new u(r, d.colorup, !0, this.model(), h, d.transparency) ), this.bindControl( new u(p, d.colordown, !0, this.model(), h, d.transparency) ); }), (i.prototype._findPlotPalette = function(e, t) { var o, i = e, n = t.id, a = null, r = null, l = this._study.metaInfo().plots; if (this._study.isBarColorerPlot(i) || this._study.isBgColorerPlot(i)) (a = this._study.metaInfo().palettes[t.palette]), (r = this._study.properties().palettes[t.palette]); else for (o = 0; o < l.length; o++) if ( l[o].target === n && (this._study.isSelfColorerPlot(o) || this._study.isOHLCColorerPlot(o)) ) { (a = this._study.metaInfo().palettes[l[o].palette]), (r = this._study.properties().palettes[l[o].palette]); break; } return { palette: a, paletteProps: r }; }), (i.prototype._prepareStudyPropertiesLayout = function() { var e, t, o = $( '<table class="property-page study-properties" cellspacing="0" cellpadding="2">' ); return ( this._study.metaInfo().is_price_study || ((e = this.createPrecisionEditor()), (t = $("<tr>")), t.appendTo(o), $("<td>" + $.t("Precision") + "</td>").appendTo(t), $("<td>") .append(e) .appendTo(t), this.bindControl( new h( e, this._study.properties().precision, null, !0, this.model(), "Change Precision" ) )), "Compare@tv-basicstudies" === this._study.metaInfo().id && ((e = this.createSeriesMinTickEditor()), (t = $("<tr>")), t.appendTo(o), $("<td>" + $.t("Override Min Tick") + "</td>").appendTo(t), $("<td>") .append(e) .appendTo(t), this.bindControl( new h( e, this._study.properties().minTick, null, !0, this.model(), "Change MinTick" ) )), this._putStudyDefaultStyles(o), o ); }), (i.prototype._putStudyDefaultStyles = function(e, t) { var o, i, n, a, r, l, p = null, s = this._study; return ( (!s.properties().linkedToSeries || !s.properties().linkedToSeries.value()) && ($.each(this._model.m_model.panes(), function(e, t) { $.each(t.dataSources(), function(e, o) { if (o === s) return (p = t), !1; }); }), (this._pane = p), this._pane && (-1 !== this._pane .leftPriceScale() .dataSources() .indexOf(this._study) ? (o = "left") : -1 !== this._pane .rightPriceScale() .dataSources() .indexOf(this._study) ? (o = "right") : this._pane.isOverlay(this._study) && (o = "none")), o && ((i = this), (n = { left: $.t("Scale Left"), right: $.t("Scale Right") }), i._pane.actionNoScaleIsEnabled(s) && (n.none = $.t("Screen (No Scale)")), (a = this.createKeyCombo(n) .val(o) .change(function() { switch (this.value) { case "left": i._model.move(i._study, i._pane, i._pane.leftPriceScale()); break; case "right": i._model.move(i._study, i._pane, i._pane.rightPriceScale()); break; case "none": i._model.move(i._study, i._pane, null); } })), (r = this.addRow(e)), $("<td>" + $.t("Scale") + "</td>").appendTo(r), (l = $("<td>") .appendTo(r) .append(a)), t && t > 2 && l.attr("colspan", t - 1)), e) ); }), (i.prototype.widget = function() { return this._table; }), (i.prototype._prepareFilledAreaBackground = function(e, t, o, i, n) { var a, r, l, p = $('<tr class="line"/>'), s = $("<td/>"); return ( s.appendTo(p), (a = $("<input type='checkbox' class='visibility-switch'/>")), a.appendTo(s), this.createLabeledCell(i, a) .appendTo(p) .addClass("propertypage-name-label"), (r = $("<td/>")), r.appendTo(p), r.addClass("colorpicker-cell"), (l = g(r)), this.bindControl(new c(a, e, !0, this.model(), n + " visibility")), this.bindControl(new u(l, t, !0, this.model(), n + " color", o)), p ); }), inherit(n, r), (n.prototype.prepareLayout = function() { if ( this._study.properties().linkedToSeries && this._study.properties().linkedToSeries.value() ) return void (this._table = $()); this._table = $(); }), (n.prototype.widget = function() { return this._table; }), (i._createRow_horizlines = function(e, t) { var o = this.addRow(e), i = t.name.value(), n = $("<input type='checkbox' class='visibility-switch'/>"), a = this.createColorPicker(), r = m(), l = T(); $("<td>") .append(n) .appendTo(o), this.createLabeledCell(i, n).appendTo(o), $("<td>") .append(a) .appendTo(o), $("<td>") .append(r) .appendTo(o), $("<td>") .append(l.render()) .appendTo(o), this.bindControl( new c(n, t.visible, !0, this.model(), "Change " + i + " visibility") ), this.bindControl( new u(a, t.color, !0, this.model(), "Change " + i + " color") ), this.bindControl( new h( l, t.style, parseInt, !0, this.model(), "Change " + i + " style" ) ), this.bindControl( new C(r, t.width, !0, this.model(), "Change " + i + " width") ); }), (i._createRow_vertlines = function(e, t) { var o = this.addRow(e), i = t.name.value(), n = $("<input type='checkbox' class='visibility-switch'/>"), a = this.createColorPicker(), r = m(), l = T(); $("<td>") .append(n) .appendTo(o), this.createLabeledCell(i, n).appendTo(o), $("<td>") .append(a) .appendTo(o), $("<td>") .append(r) .appendTo(o), $("<td>") .append(l.render()) .appendTo(o), this.bindControl( new c(n, t.visible, !0, this.model(), "Change " + i + " visibility") ), this.bindControl( new u(a, t.color, !0, this.model(), "Change " + i + " color") ), this.bindControl( new h( l, t.style, parseInt, !0, this.model(), "Change " + i + " style" ) ), this.bindControl( new C(r, t.width, !0, this.model(), "Change " + i + " width") ); }), (i._createRow_lines = function(e, t) { var o = this.addRow(e), i = t.title.value(), n = $("<input type='checkbox' class='visibility-switch'/>"), a = this.createColorPicker(), r = m(), l = T(); $("<td>") .append(n) .appendTo(o), this.createLabeledCell(i, n).appendTo(o), $("<td>") .append(a) .appendTo(o), $("<td>") .append(r) .appendTo(o), $("<td>") .append(l.render()) .appendTo(o), this.bindControl( new c(n, t.visible, !0, this.model(), "Change " + i + " visibility") ), this.bindControl( new u(a, t.color, !0, this.model(), "Change " + i + " color") ), this.bindControl( new h( l, t.style, parseInt, !0, this.model(), "Change " + i + " style" ) ), this.bindControl( new C(r, t.width, !0, this.model(), "Change " + i + " width") ); }), (i._createRow_hlines = function(e, t) { var o, i, n, a = this.addRow(e), r = t.name.value(), l = $("<input type='checkbox' class='visibility-switch'/>"), p = this.createColorPicker(), s = m(), d = T(), b = $("<input type='checkbox'>"); $("<td>") .append(l) .appendTo(a), this.createLabeledCell(r, l).appendTo(a), $("<td>") .append(p) .appendTo(a), $("<td>") .append(s) .appendTo(a), $("<td>") .append(d.render()) .appendTo(a), $("<td>").appendTo(a), $("<td>") .append(b) .appendTo(a), this.createLabeledCell("Show Price", b).appendTo(a), this.bindControl( new c(l, t.visible, !0, this.model(), "Change " + r + " visibility") ), this.bindControl( new u(p, t.color, !0, this.model(), "Change " + r + " color") ), this.bindControl( new h( d, t.style, parseInt, !0, this.model(), "Change " + r + " style" ) ), this.bindControl( new C(s, t.width, !0, this.model(), "Change " + r + " width") ), this.bindControl( new c( b, t.showPrice, !0, this.model(), "Change " + r + " show price" ) ), t.enableText.value() && ((a = this.addRow(e)), $('<td colspan="2">').appendTo(a), (o = $("<input type='checkbox'>")), $('<td class="text-center">') .append(o) .appendTo(a), this.createLabeledCell("Show Text", o).appendTo(a), this.bindControl( new c( o, t.showText, !0, this.model(), "Change " + r + " show text" ) ), (i = TradingView.createTextPosEditor()), $("<td>") .append(i.render()) .appendTo(a), this.bindControl( new h( i, t.textPos, parseInt, !0, this.model(), "Change " + r + " text position" ) ), (n = this.createFontSizeEditor()), $('<td colspan="2">') .append(n) .appendTo(a), this.bindControl( new h( n, t.fontSize, parseInt, !0, this.model(), "Change " + r + " font size" ) )); }), (i._createRow_hhists = function(e, t) { var o, i, n, a, r, d, b = t.title.value(), C = [], g = [], T = this.addRow(e), w = f(); $("<td>") .append(w) .appendTo(T), this.createLabeledCell(b, w).appendTo(T), this.bindControl( new c(w, t.visible, !0, this.model(), "Change " + b + " Visibility") ), (T = this.addRow(e)), (o = $("<input/>")), o.attr("type", "text"), o.addClass("ticker"), this.createLabeledCell($.t("Width (% of the Box)"), o).appendTo(T), $("<td>") .append(o) .appendTo(T), (i = [s(40)]), i.push(l(0)), i.push(p(100)), this.bindControl( new y( o, t.percentWidth, i, !1, this.model(), "Change Percent Width" ) ), (T = this.addLabeledRow(e, "Placement")), (n = L()), $("<td>") .append(n) .appendTo(T), this.bindControl( new h( n, t.direction, null, !0, this.model(), "Change " + b + " Placement" ) ), (T = this.addRow(e)), (a = $("<input type='checkbox'>")), $("<td>") .append(a) .appendTo(T), this.createLabeledCell($.t("Show Values"), a).appendTo(T), this.bindControl( new c( a, t.showValues, !0, this.model(), "Change " + b + " Show Values" ) ), (T = this.addRow(e)), (r = this.createColorPicker()), this.createLabeledCell($.t("Text Color"), r).appendTo(T), $("<td>") .append(r) .appendTo(T), this.bindControl( new u( r, t.valuesColor, !0, this.model(), "Change " + b + " Text Color" ) ); for (d in t.colors) isNumber(parseInt(d, 10)) && ((T = this.addRow(e)), (C[d] = t.titles[d].value()), (g[d] = this.createColorPicker()), $("<td>") .append(C[d]) .appendTo(T), $("<td>") .append(g[d]) .appendTo(T), this.bindControl( new u( g[d], t.colors[d], !0, this.model(), "Change " + C[d] + " color" ) )); }), (i._createRow_backgrounds = function(e, t) { var o = this.addRow(e), i = $("<input type='checkbox' class='visibility-switch'/>"), n = t.name.value(), a = this.createColorPicker(); $("<td>") .append(i) .appendTo(o), this.createLabeledCell(n, i).appendTo(o), $("<td>") .append(a) .appendTo(o), this.bindControl( new c(i, t.visible, !0, this.model(), "Change " + n + " visibility") ), this.bindControl( new u( a, t.color, !0, this.model(), "Change " + n + " color", t.transparency ) ); }), (i._createRow_polygons = function(e, t) { var o = this.addRow(e), i = t.name.value(), n = this.createColorPicker(); $("<td>") .append(i) .appendTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new u(n, t.color, !0, this.model(), "Change " + i + " color") ); }), (i._createRow_trendchannels = function(e, t) { var o = this.addRow(e), i = t.name.value(), n = this.createColorPicker(); $("<td>") .append(i) .appendTo(o), $("<td>") .append(n) .appendTo(o), this.bindControl( new u( n, t.color, !0, this.model(), "Change " + i + " color", t.transparency ) ); }), (i._createRow_textmarks = function(e, t) { var o = this.addLabeledRow(e), i = t.name.value(), n = this.createColorPicker(), a = this.createColorPicker(), r = this.createFontEditor(), l = this.createFontSizeEditor(), p = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' ), s = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' ); $("<td>") .append(i) .appendTo(o), "rectangle" !== t.shape.value() && $("<td>") .append(n) .appendTo(o), $("<td>") .append(a) .appendTo(o), $("<td>") .append(r) .appendTo(o), $("<td>") .append(l) .appendTo(o), $("<td>") .append(p) .appendTo(o), $("<td>") .append(s) .appendTo(o), this.bindControl( new u( n, t.color, !0, this.model(), "Change " + i + " color", t.transparency ) ), this.bindControl( new u( a, t.fontColor, !0, this.model(), "Change " + i + " text color", t.transparency ) ), this.bindControl( new h( l, t.fontSize, parseInt, !0, this.model(), "Change " + i + " font size" ) ), this.bindControl( new h( r, t.fontFamily, null, !0, this.model(), "Change " + i + " font" ) ), this.bindControl( new c(p, t.fontBold, !0, this.model(), "Change Text Font Bold") ), this.bindControl( new c(s, t.fontItalic, !0, this.model(), "Change Text Font Italic") ); }), (i._createRow_shapemarks = function(e, t) { var o = this.addRow(e), i = $("<input type='checkbox' class='visibility-switch'/>"), n = t.name.value(), a = this.createColorPicker(), r = $("<input/>"); r.attr("type", "text"), r.addClass("ticker"), $("<td>") .append(i) .appendTo(o), this.createLabeledCell(n, i).appendTo(o), $("<td>") .append(a) .appendTo(o), this.createLabeledCell("Size", r).appendTo(o), $("<td>") .append(r) .appendTo(o), this.bindControl( new c(i, t.visible, !0, this.model(), "Change " + n + " visibility") ), this.bindControl( new u( a, t.color, !0, this.model(), "Change " + n + " back color", t.transparency ) ), this.bindControl( new y(r, t.size, null, !1, this.model(), "Change size") ); }), (t.StudyStylesPropertyPage = i), (t.StudyDisplayPropertyPage = n); }, 400: function(e, t, o) { "use strict"; function i(e, t, o) { p.call(this, e, t), (this._linetool = o), this.prepareLayout(); } function n(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } var a = o(1195), r = o(1076), l = o(238), p = l.PropertyPage, s = l.SliderBinder, d = o(1198).createTransparencyEditor, h = o(1201); inherit(i, r), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, l = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ), p = $( '<table class="property-page" cellspacing="0" cellpadding="0">' ).data({ "layout-tab": h.TabNames.inputs, "layout-tab-priority": h.TabPriority.Inputs }); (this._table = l.add(p)), r.prototype.prepareLayoutForTable.call(this, l), (e = $("<tr>").appendTo(p)), $("<td>") .append($.t("Avg HL in minticks")) .appendTo(e), (t = $("<td>").appendTo(e)), (o = $("<input type='text'>") .addClass("ticker") .appendTo(t)), (e = $("<tr>").appendTo(p)), $("<td>") .append($.t("Variance")) .appendTo(e), (i = $("<td>").appendTo(e)), (n = $("<input type='text'>") .addClass("ticker") .appendTo(i)), (a = this._linetool.properties()), this.bindInteger( o, a.averageHL, $.t("Change Average HL value"), 1, 5e4 ), this.bindInteger(n, a.variance, $.t("Change Variance value"), 1, 100), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), inherit(n, a), (n.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, l, p, h, c; (this._widget = $("<div>")), (e = $("<table cellspacing=4>").appendTo(this._widget)), (t = this.createColorPicker()), (o = this.createColorPicker()), (i = this.createColorPicker()), (n = this.createColorPicker()), (a = this.createColorPicker()), (r = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(n).add(a) )), (l = $("<input type='checkbox' class='visibility-switch'/>").data( "hides", $(i) )), (p = this.addLabeledRow(e, $.t("Candles"))), $("<td>").prependTo(p), $("<td>") .append(t) .appendTo(p), $("<td>") .append(o) .appendTo(p), (p = this.addLabeledRow(e, $.t("Borders"), r)), $("<td>") .append(r) .prependTo(p), $("<td>") .append(n) .appendTo(p), $("<td>") .append(a) .appendTo(p), $("<td>").appendTo(p), (p = this.addLabeledRow(e, $.t("Wick"), l)), $("<td>") .append(l) .prependTo(p), $("<td>") .append(i) .appendTo(p), $("<td>").appendTo(p), (e = $("<table>").appendTo(this._widget)), (p = $("<tr>").appendTo(e)), $("<td colspan='2'>") .append($.t("Transparency")) .appendTo(p), (h = d()), $("<td colspan='2'>") .append(h) .appendTo(p), (c = this._linetool.properties()), this.bindColor(t, c.candleStyle.upColor, "Change Candle Up Color"), this.bindColor( o, c.candleStyle.downColor, "Change Candle Down Color" ), this.bindBoolean( l, c.candleStyle.drawWick, "Change Candle Wick Visibility" ), this.bindColor( i, c.candleStyle.wickColor, "Change Candle Wick Color" ), this.bindBoolean( r, c.candleStyle.drawBorder, "Change Candle Border Visibility" ), this.bindColor( n, c.candleStyle.borderUpColor, "Change Candle Up Border Color" ), this.bindColor( a, c.candleStyle.borderDownColor, "Change Candle Down Border Color" ), this.bindControl( new s( h, c.transparency, !0, this.model(), "Change Guest Feed Transparency" ) ); }), (n.prototype.widget = function() { return this._widget; }), (t.LineToolGhostFeedInputsPropertyPage = i), (t.LineToolGhostFeedStylesPropertyPage = n); }, 401: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } function n(e, t, o) { r.call(this, e, t, o); } var a = o(1195), r = o(1076), l = o(238), p = l.BooleanBinder, s = l.SimpleComboBinder, d = l.SimpleStringBinder, h = l.ColorBinding, c = l.SliderBinder, b = o(1197).createLineStyleEditor, u = o(1196).createLineWidthEditor; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, l, C, y, g, T, w, _; (this._res = $("<div>")), (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2" style="width:100%"></table>' ).appendTo(this._res)), (e = u()), (t = b()), (o = this.createColorPicker()), (i = this.addLabeledRow(this._table, "Line")), $("<td>") .append(o) .appendTo(i), $("<td>") .append(e) .appendTo(i), $('<td colspan="3">') .append(t.render().css("display", "block")) .appendTo(i), (n = $("<input type='checkbox' class='visibility-switch'>")), (i = $("<tr>").appendTo(this._table)), $('<td colspan="3">') .append( $("<label>") .append(n) .append($.t("Show Price")) ) .prependTo(i), (a = $("<input type='checkbox'>")), (i = $("<tr>").appendTo(this._table)), $('<td colspan="3">') .append( $("<label>") .append(a) .append($.t("Show Text")) ) .prependTo(i), (i = this.addLabeledRow(this._table, "Text:")), (r = this.createColorPicker()), (l = this.createFontSizeEditor()), (C = this.createFontEditor()), (y = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (g = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), $("<td>") .append(r) .appendTo(i), $("<td>") .append(C) .appendTo(i), $("<td>") .append(l) .appendTo(i), $("<td>") .append(y) .appendTo(i), $("<td>") .append(g) .appendTo(i), (i = $("<tr>").appendTo(this._table)), $("<td colspan='2'>") .append($.t("Text Alignment:")) .appendTo(i), (T = $( "<select><option value='left'>" + $.t("left") + "</option><option value='center'>" + $.t("center") + "</option><option value='right'>" + $.t("right") + "</option></select>" )), (w = $( "<select><option value='bottom'>" + $.t("top") + "</option><option value='middle'>" + $.t("middle") + "</option><option value='top'>" + $.t("bottom") + "</option></select>" ).data("selectbox-css", { display: "block" })), $("<td>") .append(T) .appendTo(i), $("<td colspan='3'>") .append(w) .appendTo(i), (_ = $("<textarea rows='7' cols='60'>").css("width", "100%")), (i = $("<tr>").appendTo(this._table)), $("<td colspan='7'>") .append(_) .appendTo(i), this.bindControl( new p( a, this._linetool.properties().showLabel, !0, this.model(), "Change Horz Line Text Visibility" ) ), this.bindControl( new s( T, this._linetool.properties().horzLabelsAlign, null, !0, this.model(), "Change Horz Line Labels Alignment" ) ), this.bindControl( new s( w, this._linetool.properties().vertLabelsAlign, null, !0, this.model(), "Change Horz Line Labels Alignment" ) ), this.bindControl( new d( _, this._linetool.properties().text, null, !0, this.model(), "Change Text" ) ), this.bindControl( new p( n, this._linetool.properties().showPrice, !0, this.model(), "Change Horz Line Price Visibility" ) ), this.bindControl( new h( o, this._linetool.properties().linecolor, !0, this.model(), "Change Horz Line Color" ) ), this.bindControl( new s( t, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Horz Line Style" ) ), this.bindControl( new c( e, this._linetool.properties().linewidth, !0, this.model(), "Change Horz Line Width" ) ), this.bindControl( new s( l, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new s( C, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new h( r, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new p( y, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new p( g, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._res; }), inherit(n, r), (n.prototype.prepareLayout = function() { var e, t, o, i; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this._linetool.points()[0]) && ((t = this._linetool.properties().points[0]), (o = this.createPriceEditor(t.price)), (i = $("<tr>").appendTo(this._table)), $("<td>" + $.t("Price") + "</td>").appendTo(i), $("<td>") .append(o) .appendTo(i), this.loadData()); }), (t.LineToolHorzLineStylesPropertyPage = i), (t.LineToolHorzLineInputsPropertyPage = n); }, 402: function(e, t, o) { "use strict"; function i(e, t, o) { r.call(this, e, t, o), this.prepareLayout(); } function n(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } var a = o(1195), r = o(1076), l = o(238), p = l.LessTransformer, s = l.GreateTransformer, d = l.ToIntTransformer, h = l.ToFloatTransformer, c = l.SimpleStringBinder, b = l.ColorBinding, u = l.SliderBinder, C = l.SimpleComboBinder, y = l.BooleanBinder, g = o(1196).createLineWidthEditor, T = o(89).NumericFormatter; inherit(i, r), (i.prototype.prepareLayout = function() { function e(e) { return new T().format(e); } var t, o, i, n, a, r, l, b, u, C, y, g; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (t = $("<tbody>").appendTo(this._table)), (o = this.addLabeledRow(t, $.t("Stop Level. Ticks:"))), (i = $('<input type="text">')), $("<td>") .append(i) .appendTo(o), i.addClass("ticker"), (n = $('<input type="text" class="ticker">')), $("<td>" + $.t("Price:") + "</td>").appendTo(o), $("<td>") .append(n) .appendTo(o), (a = this.addLabeledRow(t, $.t("Entry price:"))), (r = $('<input type="text" class="ticker">')), $('<td colspan="2">') .append(r) .appendTo(a), (l = this.addLabeledRow(t, $.t("Profit Level. Ticks:"))), (b = $('<input type="text" class="ticker">')), $("<td>") .append(b) .appendTo(l), (u = $('<input type="text" class="ticker">')), $("<td>" + $.t("Price:") + "</td>").appendTo(l), $("<td>") .append(u) .appendTo(l), "LineToolRiskRewardLong" === this._linetool.getConstructor() && (o.detach().appendTo(t), l.detach().prependTo(t)), (C = [ d(this._linetool.properties().stopLevel.value()), s(0), p(1e9) ]), this.bindControl( new c( i, this._linetool.properties().stopLevel, C, !1, this.model(), "Change " + this._linetool + " stop level" ) ), (C = [ d(this._linetool.properties().profitLevel.value()), s(0), p(1e9) ]), this.bindControl( new c( b, this._linetool.properties().profitLevel, C, !1, this.model(), "Change " + this._linetool + " profit level" ) ), (C = [h(this._linetool.properties().entryPrice.value())]), (y = new c( r, this._linetool.properties().entryPrice, C, !1, this.model(), "Change " + this._linetool + " entry price" )), y.addFormatter(e), this.bindControl(y), (g = this), (C = [ h(this._linetool.properties().stopPrice.value()), function(e) { return g._linetool.preparseStopPrice(e); } ]), (y = new c( n, this._linetool.properties().stopPrice, C, !1, this.model(), "Change " + this._linetool + " stop price" )), y.addFormatter(e), this.bindControl(y), (C = [ h(this._linetool.properties().targetPrice.value()), function(e) { return g._linetool.preparseProfitPrice(e); } ]), (y = new c( u, this._linetool.properties().targetPrice, C, !1, this.model(), "Change " + this._linetool + " stop price" )), y.addFormatter(e), this.bindControl(y); }), (i.prototype.widget = function() { return this._table; }), inherit(n, a), (n.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, l, d, T, w, _, m, f, L, v = this._linetool, k = v.properties(); (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = g()), (o = this.createColorPicker()), (i = this.addLabeledRow(e, $.t("Lines:"))), $("<td>") .append(o) .appendTo(i), $("<td>") .append(t) .appendTo(i), (i = this.addLabeledRow(e, $.t("Stop Color:"))), (n = this.createColorPicker()), $("<td>") .append(n) .appendTo(i), (i = this.addLabeledRow(e, $.t("Target Color:"))), (a = this.createColorPicker()), $("<td>") .append(a) .appendTo(i), (i = this.addLabeledRow(e, $.t("Text:"))), (r = this.createColorPicker()), (l = this.createFontSizeEditor()), (d = this.createFontEditor()), $("<td>") .append(r) .appendTo(i), $("<td>") .append(d) .appendTo(i), $("<td>") .append(l) .appendTo(i), (i = $("<tr>").appendTo(e)), (T = $("<label>").text($.t("Compact"))), (w = $('<input type="checkbox">').prependTo(T)), $("<td>") .append(T) .appendTo(i), (i = this.addLabeledRow(e, $.t("Account Size"))), (_ = $('<input type="text" class="ticker">')), $("<td>") .append(_) .appendTo(i), (i = this.addLabeledRow(e, $.t("Risk"))), (this._riskEdit = $('<input type="text" class="ticker">')), $("<td>") .append(this._riskEdit) .appendTo(i), this._riskEdit.data("step", v.getRiskStep(k.riskDisplayMode.value())), k.riskDisplayMode.subscribe(this, this._onRiskDisplayModeChange), (m = this.createKeyCombo({ percents: $.t("%"), money: $.t("Cash") })), $("<td>") .append(m) .appendTo(i), this.bindControl( new b( o, k.linecolor, !0, this.model(), "Change Risk/Reward line Color" ) ), this.bindControl( new u( t, k.linewidth, !0, this.model(), "Change Risk/Reward line width" ) ), this.bindControl( new b( n, k.stopBackground, !0, this.model(), "Change stop color", k.stopBackgroundTransparency ) ), this.bindControl( new b( a, k.profitBackground, !0, this.model(), "Change target color", k.profitBackgroundTransparency ) ), this.bindControl( new C( l, k.fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new C(d, k.font, null, !0, this.model(), "Change Text Font") ), this.bindControl( new b(r, k.textcolor, !0, this.model(), "Change Text Color") ), this.bindControl( new y(w, k.compact, !0, this.model(), "Compact mode") ), (f = [h(k.accountSize.value()), s(1), p(1e9)]), this.bindControl( new c( _, k.accountSize, f, !1, this.model(), "Change " + this._linetool + " Account Size" ) ), this.bindControl( new C(m, k.riskDisplayMode, null, !0, this.model(), "% / Cash") ), (L = [ h(k.risk.value()), s(1), function(e) { var t, o = k.riskDisplayMode.value(); return ( "percents" === o ? (e = e > 100 ? 100 : e) : ((t = k.accountSize.value()), (e = e > t ? t : e)), v.riskFormatter(o).format(e) ); } ]), this.bindControl( new c( this._riskEdit, k.risk, L, !1, this.model(), "Change " + this._linetool + " Risk" ) ), this.loadData(); }), (n.prototype._onRiskDisplayModeChange = function() { var e = this._linetool, t = e.properties(), o = t.riskDisplayMode.value(), i = e.riskFormatter(o); this._riskEdit.data("TVTicker", { step: e.getRiskStep(o), formatter: i.format.bind(i) }); }), (n.prototype.destroy = function() { this._linetool .properties() .riskDisplayMode.unsubscribe(this, this._onRiskDisplayModeChange), a.prototype.destroy.call(this); }), (n.prototype.onResoreDefaults = function() { this._linetool.recalculate(); }), (n.prototype.widget = function() { return this._table; }), (t.LineToolRiskRewardInputsPropertyPage = i), (t.LineToolRiskRewardStylesPropertyPage = n); }, 403: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } function n(e, t, o) { r.call(this, e, t, o); } var a = o(1195), r = o(1076), l = o(238), p = l.GreateTransformer, s = l.LessTransformer, d = l.ToFloatTransformer, h = l.ColorBinding, c = l.BooleanBinder, b = l.SimpleComboBinder, u = l.SimpleStringBinder, C = l.SliderBinder, y = o(1197).createLineStyleEditor, g = o(1196).createLineWidthEditor, T = o(89).NumericFormatter; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n, a, r, l, p, s, d, u, T, w, _, m, f; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = $("<tbody>").appendTo(this._table)), (t = g()), (o = y()), (i = this.createColorPicker()), (n = this.addLabeledRow(e, $.t("Line"))), $("<td>") .append(i) .appendTo(n), $("<td>") .append(t) .appendTo(n), $('<td colspan="3">') .append(o.render()) .appendTo(n), (a = $("<tbody>").appendTo(this._table)), (n = this.addLabeledRow(a, $.t("Text"))), (r = this.createColorPicker()), (l = this.createFontSizeEditor()), (p = this.createFontEditor()), (s = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-bold"></span></span>' )), (d = $( '<span class="_tv-button _tv-button-fontstyle"><span class="icon-fontstyle-italic"></span></span>' )), (u = $('<input type="checkbox">')), $("<td>") .append(r) .appendTo(n), $("<td>") .append(p) .appendTo(n), $("<td>") .append(l) .appendTo(n), $("<td>") .append(s) .appendTo(n), $("<td>") .append(d) .appendTo(n), (T = $('<input type="checkbox">')), (w = $('<input type="checkbox">')), (n = this.addLabeledRow(a, $.t("Extend Right End"))), $('<td colspan="3">') .appendTo(n) .append(T), (n = this.addLabeledRow(a, $.t("Extend Left End"))), $('<td colspan="3">') .appendTo(n) .append(w), (_ = $('<input type="checkbox">')), (m = $('<input type="checkbox">')), (f = $('<input type="checkbox">')), (n = this.addLabeledRow(a, $.t("Show Price Range"))), $('<td colspan="3">') .appendTo(n) .append(_), (n = this.addLabeledRow(a, $.t("Show Bars Range"))), $('<td colspan="3">') .appendTo(n) .append(m), (n = this.addLabeledRow(a, $.t("Always Show Stats"))), $('<td colspan="3">') .appendTo(n) .append(f), (n = this.addLabeledRow(a, $.t("Show Middle Point"))), $('<td colspan="3">') .appendTo(n) .append(u), this.bindControl( new c( _, this._linetool.properties().showPriceRange, !0, this.model(), "Change Trend Line Show Price Range" ) ), this.bindControl( new c( m, this._linetool.properties().showBarsRange, !0, this.model(), "Change Trend Line Show Bars Range" ) ), this.bindControl( new b( l, this._linetool.properties().fontsize, parseInt, !0, this.model(), "Change Text Font Size" ) ), this.bindControl( new b( p, this._linetool.properties().font, null, !0, this.model(), "Change Text Font" ) ), this.bindControl( new h( r, this._linetool.properties().textcolor, !0, this.model(), "Change Text Color" ) ), this.bindControl( new c( s, this._linetool.properties().bold, !0, this.model(), "Change Text Font Bold" ) ), this.bindControl( new c( d, this._linetool.properties().italic, !0, this.model(), "Change Text Font Italic" ) ), this.bindControl( new h( i, this._linetool.properties().linecolor, !0, this.model(), "Change Trend Line Color" ) ), this.bindControl( new b( o, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Trend Line Style" ) ), this.bindControl( new C( t, this._linetool.properties().linewidth, !0, this.model(), "Change Trend Line Width" ) ), this.bindControl( new c( T, this._linetool.properties().extendRight, !0, this.model(), "Change Trend Angle Extending Right" ) ), this.bindControl( new c( w, this._linetool.properties().extendLeft, !0, this.model(), "Change Trend Angle Extending Left" ) ), this.bindControl( new c( f, this._linetool.properties().alwaysShowStats, !0, this.model(), "Change Trend Line Always Show Stats" ) ), this.bindControl( new c( u, this._linetool.properties().showMiddlePoint, !0, this.model(), "Change Trend Line Show Middle Point" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), inherit(n, r), (n.prototype.prepareLayout = function() { var e, t, o, i, n, a; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this._linetool.points()[0]), (t = this._linetool.properties().points[0]), e && t && ((o = this._createPointRow(e, t, "")), this._table.append(o), (o = $("<tr>").appendTo(this._table)), $("<td>") .append($.t("Angle")) .appendTo(o), (i = $("<input type='text'>")), $("<td>") .append(i) .appendTo(o), (n = [d(t.price.value()), p(-360), s(360)]), (a = new u( i, this._linetool.properties().angle, n, !1, this.model(), "Change angle" )), a.addFormatter(function(e) { return new T().format(e); }), this.bindControl(a), this.loadData()); }), (n.prototype.widget = function() { return this._table; }), (t.LineToolTrendAngleStylesPropertyPage = i), (t.LineToolTrendAngleInputsPropertyPage = n); }, 404: function(e, t, o) { "use strict"; function i(e, t, o) { a.call(this, e, t, o), this.prepareLayout(); } function n(e, t, o) { r.call(this, e, t, o); } var a = o(1195), r = o(1076), l = o(238), p = l.BooleanBinder, s = l.SimpleComboBinder, d = l.SliderBinder, h = l.ColorBinding, c = o(1197).createLineStyleEditor, b = o(1196).createLineWidthEditor; inherit(i, a), (i.prototype.prepareLayout = function() { var e, t, o, i, n; (this._table = $(document.createElement("table"))), this._table.addClass("property-page"), this._table.attr("cellspacing", "0"), this._table.attr("cellpadding", "2"), (e = b()), (t = c()), (o = this.createColorPicker()), (i = this.addLabeledRow(this._table, "Line")), $("<td>").prependTo(i), $("<td>") .append(o) .appendTo(i), $("<td>") .append(e) .appendTo(i), $("<td>") .append(t.render()) .appendTo(i), (n = $("<input type='checkbox' class='visibility-switch'>")), (i = $("<tr>").appendTo(this._table)), $("<td>") .append(n) .prependTo(i), this.createLabeledCell(2, "Show Time", n).appendTo(i), this.bindControl( new p( n, this._linetool.properties().showTime, !0, this.model(), "Change Vert Line Time Visibility" ) ), this.bindControl( new h( o, this._linetool.properties().linecolor, !0, this.model(), "Change Vert Line Color" ) ), this.bindControl( new s( t, this._linetool.properties().linestyle, parseInt, !0, this.model(), "Change Vert Line Style" ) ), this.bindControl( new d( e, this._linetool.properties().linewidth, !0, this.model(), "Change Vert Line Width" ) ), this.loadData(); }), (i.prototype.widget = function() { return this._table; }), inherit(n, r), (n.prototype.prepareLayout = function() { var e, t, o, i; (this._table = $( '<table class="property-page" cellspacing="0" cellpadding="2">' )), (e = this._linetool.points()[0]) && ((t = $('<input type="text" class="ticker">')), (o = $("<tr>").appendTo(this._table)), $("<td>" + $.t("Bar #") + "</td>").appendTo(o), $("<td>") .append(t) .appendTo(o), (i = this._linetool.properties().points[0]), this.bindBarIndex( i.bar, t, this.model(), "Change " + this._linetool + " point bar index" ), this.loadData()); }), (t.LineToolVertLineStylesPropertyPage = i), (t.LineToolVertLineInputsPropertyPage = n); } }); <file_sep>Owner permissions define who has control over the account. Owners may overwrite all keys and change any account settings. See [permissions](accounts/permissions) for more details. **If you have vesting/lockup balances, please make sure that the don't remove the permission which the balances belong to. If you remove the public connecting with a vesting/lockup balance, you'll not be able to claim that balance by any means.**<file_sep>var React = require("react"); var ActionSheetButton = React.createClass({ displayName: "ActionSheetButton", toggle: function() { this.props.setActiveState(!this.props.active); }, render: function() { var Title = null; if (this.props.title.length > 0) { Title = <a className="button">{this.props.title}</a>; } return ( <div onClick={this.toggle}> {Title} <div>{this.props.children}</div> </div> ); } }); module.exports = ActionSheetButton; <file_sep>import { EtoProject } from "../../services/eto"; import { EtoState } from "../../stores/EtoStore"; import * as moment from "moment"; import BigNumber from "bignumber.js"; export const enum Locale { ZH = "zh", EN = "en", VN = "vn" } export const selectProjects = (eto: EtoState) => eto.projects; export const selectProject = (eto: EtoState) => (id: string) => selectProjects(eto).find(project => project.id === id); export const selectBanners = (eto: EtoState) => eto.banners; export const selectIsUserStatus = (eto: EtoState, projectID: string) => eto.userInSet[projectID] || {}; export const selectUserProjectStatus = (eto: EtoState, projectID: string) => eto.userProjectStatus[projectID] || { current_base_token_count: 0 }; export const selectIsUserInProject = (eto: EtoState, projectID: string) => eto.userInSet[projectID] && eto.userInSet[projectID].status === "ok"; export const selectProjectStatus = (etoProject: EtoProject.ProjectDetail) => etoProject.status === EtoProject.EtoStatus.Unstart ? moment.utc(etoProject.start_at).isAfter(moment()) ? EtoProject.EtoStatus.Unstart : EtoProject.EtoStatus.Running : etoProject.status === EtoProject.EtoStatus.Running ? EtoProject.EtoStatus.Running : etoProject.status === EtoProject.EtoStatus.Finished ? EtoProject.EtoStatus.Finished : EtoProject.EtoStatus.Failed; export const selectProjectIsActive = (etoProject: EtoProject.ProjectDetail) => selectProjectStatus(etoProject) === EtoProject.EtoStatus.Running; // export const selectProjectStatus = (etoProject: EtoProject.ProjectDetail) => // etoProject.finish_at // ? EtoProject.EtoStatus.Finish // : moment.utc(etoProject.start_at).isAfter(moment()) // ? EtoProject.EtoStatus.Uninit // : EtoProject.EtoStatus.Running; export const selectBanner = (eto: EtoProject.Banner, locale = Locale.ZH) => ({ imgUrl: locale === Locale.ZH ? eto.adds_banner : eto.adds_banner__lang_en, projectLink: eto.id } as EtoProject.SelectedBanner); export const selectAdv = (eto: EtoProject.ProjectDetail, locale = Locale.ZH) => locale === Locale.ZH ? eto.adds_advantage : eto.adds_advantage__lang_en; export const selectTokenTotal = ( eto: EtoProject.ProjectDetail, locale = Locale.ZH ) => locale === Locale.ZH ? eto.adds_token_total : eto.adds_token_total__lang_en; export const selectProjectKeywords = ( eto: EtoProject.ProjectDetail, locale = Locale.ZH ) => (Locale.ZH ? eto.adds_keyword : eto.adds_keyword__lang_en); export class EtoRate { rate: BigNumber; baseAsset: string; quoteAsset: string; base: number; quote = 1; constructor(public project: EtoProject.ProjectDetail) { let rate = (this.rate = new BigNumber(project.base_token_count).div( new BigNumber(project.quote_token_count) )); this.baseAsset = project.base_token; this.quoteAsset = project.token; this.base = rate.toNumber(); } convertBaseToQuote(baseValue: number) { return new BigNumber(baseValue).div(this.rate).toNumber(); } convertQuoteToBase(quote: number) { return this.rate.times(quote).toNumber(); } } export const projectRate = (project: EtoProject.ProjectDetail) => { let rate = new BigNumber(project.base_token_count).div( new BigNumber(project.quote_token_count) ); return { baseAsset: project.base_token, quoteAsset: project.token, base: rate.toNumber(), quote: 1 }; }; <file_sep>var assert = require('assert'); var time = require('time'); var translate = require('./'); var Translator = translate.Translator; describe('translate', () => { var instance; beforeEach(() => { instance = new Translator(); }); it('is a function', () => { assert.isFunction(t.translate); }); it('is backward-compatible', () => { assert.isFunction(translate); assert.isFunction(translate.translate); }); describe('#withLocale', () => { it('temporarily changes the current locale within the callback', () => { var locale = t.getLocale(); t.withLocale(locale + 'x', () => { expect(t.getLocale()).toBe(locale + 'x'); }); expect(t.getLocale()).toBe(locale); }); it('allows a custom callback context to be set', () => { t.withLocale('foo', () => { expect(this.bar).toBe('baz'); }, { bar: 'baz' }) }); it('does not emit a "localechange" event', function(done) { var handler = () => { done('event was emitted'); }; t.onLocaleChange(handler); t.withLocale(t.getLocale() + 'x', () => {}); t.offLocaleChange(handler); setTimeout(done, 100); }); it('returns the return value of the callback', () => { var result = t.withLocale('foo', () => { return 'bar'; }); expect(result).toBe('bar'); }); }); describe('#withScope', () => { it('is a function', () => { assert.isFunction(t.withScope); }); it('temporarily changes the current scope within the callback', () => { var scope = t._registry.scope; t.withScope(scope + 'x', () => { expect(t._registry.scope).toBe(scope + 'x'); }); expect(t._registry.scope).toBe(scope); }); it('allows a custom callback context to be set', () => { t.withScope('foo', () => { expect(this.bar).toBe('baz'); }, { bar: 'baz' }) }); it('returns the return value of the callback', () => { var result = t.withScope('foo', () => { return 'bar'; }); expect(result).toBe('bar'); }); }); describe('#withSeparator', () => { it('is a function', () => { assert.isFunction(t.withSeparator); }); it('temporarily changes the current separator within the callback', () => { var separator = t.getSeparator(); t.withSeparator(separator + 'x', () => { expect(t.getSeparator()).toBe(separator + 'x'); }); expect(t.getSeparator()).toBe(separator); }); it('allows a custom callback context to be set', () => { t.withSeparator('foo', () => { expect(this.bar).toBe('baz'); }, { bar: 'baz' }) }); it('returns the return value of the callback', () => { var result = t.withSeparator('foo', () => { return 'bar'; }); expect(result).toBe('bar'); }); }); describe('#onLocaleChange', () => { it('is called when the locale changes', function(done) { var handler = () => { done(); }; t.onLocaleChange(handler); t.setLocale(t.getLocale() + 'x'); t.offLocaleChange(handler); }); it('is not called when the locale does not change', function(done) { var handler = () => { done('function was called'); }; t.onLocaleChange(handler); t.setLocale(t.getLocale()); t.offLocaleChange(handler); setTimeout(done, 100); }); describe('when called', () => { it('exposes both the new and old locale as arguments', function(done) { var oldLocale = t.getLocale(); var newLocale = oldLocale + 'x'; var handler = function(locale, previousLocale) { expect(locale).toBe(newLocale); expect(previousLocale).toBe(oldLocale); done(); }; t.onLocaleChange(handler); t.setLocale(newLocale); t.offLocaleChange(handler); }); }); describe('when called more than 10 times', () => { it('does not let Node issue a warning about a possible memory leak', () => { var oldConsoleError = console.error; console.error = function(message) { if (/EventEmitter memory leak/.test(message)) { assert.fail(null, null, 'Node issues a warning about a possible memory leak', null); } else { oldConsoleError.apply(console, arguments); } }; var handlers = [], handler, i; for (i = 0; i < 11; i++) { handler = () => {}; t.onLocaleChange(handler); handlers.push(handler); } for (i = 0; i < 11; i++) { t.offLocaleChange(handlers[i]); } console.error = oldConsoleError }); }) }); describe('#offLocaleChange', () => { it('stops the emission of events to the handler', function(done) { var count = 0; var handler = () => { count++; }; t.onLocaleChange(handler); t.setLocale(t.getLocale() + 'x'); t.setLocale(t.getLocale() + 'x'); t.offLocaleChange(handler); t.setLocale(t.getLocale() + 'x'); setTimeout(() => { assert.equal(count, 2, 'handler was called although deactivated'); done(); }, 100); }); }); describe('#onTranslationNotFound', () => { it('is a function', () => { assert.isFunction(t.onTranslationNotFound); }); it('is called when the translation is missing and a fallback is provided as option', function(done) { var handler = () => { done(); }; t.onTranslationNotFound(handler); t.translate('foo', { fallback: 'bar' }); t.offTranslationNotFound(handler); }); it('is not called when the translation is missing and no fallback is provided as option', function(done) { var handler = () => { done('function was called'); }; t.onTranslationNotFound(handler); t.translate('foo', { fallback: undefined }); t.offTranslationNotFound(handler); setTimeout(done, 100); }); it('is not called when a translation exists', function(done) { var handler = () => { done('function was called'); }; t.registerTranslations('xx', { foo: 'bar' }); t.onTranslationNotFound(handler); t.translate('foo', { locale: 'xx', fallback: 'baz' }); t.offTranslationNotFound(handler); setTimeout(done, 100); }); describe('when called', () => { it('exposes the current locale, key, and fallback as arguments', function(done) { var handler = function(locale, key, fallback) { expect('yy').toBe(locale); expect('foo').toBe(key); expect('bar').toBe(fallback); done(); }; t.onTranslationNotFound(handler); t.translate('foo', { locale: 'yy', fallback: 'bar' }); t.offTranslationNotFound(handler); }); }); }); describe('#offTranslationNotFound', () => { it('is a function', () => { assert.isFunction(t.offTranslationNotFound); }); it('stops the emission of events to the handler', function(done) { var count = 0; var handler = () => { count++; }; t.onTranslationNotFound(handler); t.translate('foo', { fallback: 'bar' }); t.translate('foo', { fallback: 'bar' }); t.offTranslationNotFound(handler); t.translate('foo', { fallback: 'bar' }); setTimeout(() => { assert.equal(count, 2, 'handler was called although deactivated'); done(); }, 100); }); }); describe('#setKeyTransformer', () => { var transformer = function(key, options) { assert.deepEqual({ locale: 'xx', bingo: 'bongo' }, options); return key.toLowerCase(); }; it('uses the custom key transformer when translating', () => { t.registerTranslations('xx', { foo: 'bar' }); var translation = t.translate('FOO', { locale: 'xx', bingo: 'bongo' }); assert.matches(translation, /missing translation/); t.setKeyTransformer(transformer); translation = t.translate('FOO', { locale: 'xx', bingo: 'bongo' }); expect('bar').toBe(translation); }); }); describe('#translate', () => { it('is a function', () => { assert.isFunction(t.translate); }); }); describe('when called', () => { describe('with a non-empty string or an array as first argument', () => { it('does not throw an invalid argument error', () => { assert.doesNotThrow(() => { t.translate('foo'); }, /invalid argument/); assert.doesNotThrow(() => { t.translate(['foo']); }, /invalid argument/); }); describe('with the default locale present', () => { describe('without a current scope or provided scope option', () => { it('generates the correct normalized keys', () => { expect(t.translate('foo')).toBe('missing translation: en.foo'); }); }); describe('with a current scope present', () => { it('generates the correct normalized keys', () => { t.withScope('other', () => { expect(t.translate('foo')).toBe('missing translation: en.other.foo'); }); }); }); describe('with a scope provided as option', () => { it('generates the correct normalized keys', () => { assert.equal(t.translate('foo', { scope: 'other' }), 'missing translation: en.other.foo'); }); }); }); describe('with a different locale present', () => { describe('without a current scope or provided scope option', () => { it('generates the correct normalized keys', () => { t.withLocale('de', () => { expect(t.translate('foo')).toBe('missing translation: de.foo'); }); }); }); describe('with a current scope present', () => { it('generates the correct normalized keys', () => { t.withLocale('de', () => { t.withScope('other', () => { expect(t.translate('foo')).toBe('missing translation: de.other.foo'); }); }); }); }); describe('with a scope provided as option', () => { it('generates the correct normalized keys', () => { t.withLocale('de', () => { assert.equal(t.translate('foo', { scope: 'other' }), 'missing translation: de.other.foo'); }); }); }); }); describe('with a locale provided as option', () => { describe('without a current scope or provided scope option', () => { it('generates the correct normalized keys', () => { assert.equal(t.translate('foo', { locale: 'de' }), 'missing translation: de.foo'); }); }); describe('with a current scope present', () => { it('generates the correct normalized keys', () => { t.withScope('other', () => { assert.equal(t.translate('foo', { locale: 'de' }), 'missing translation: de.other.foo'); }); }); }); describe('with a scope provided as option', () => { it('generates the correct normalized keys', () => { assert.equal(t.translate('foo', { locale: 'de', scope: 'other' }), 'missing translation: de.other.foo'); }); }); }); describe('with options provided', () => { it('does not mutate these options', () => { var options = { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }; t.translate('boing', options); assert.deepEqual(options, { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }); }); }); describe('with a translation for the key present', () => { it('returns that translation', () => { t.registerTranslations('en', { foo: { bar: { baz: { bam: 'boo' } } } }); // strings expect(t.translate('foo.bar.baz.bam')).toBe('boo'); assert.equal(t.translate('bar.baz.bam', { scope: 'foo' }), 'boo'); assert.equal(t.translate('baz.bam', { scope: 'foo.bar' }), 'boo'); assert.equal(t.translate('bam', { scope: 'foo.bar.baz' }), 'boo'); // arrays assert.equal(t.translate(['foo', 'bar', 'baz', 'bam']), 'boo'); assert.equal(t.translate(['bar', 'baz', 'bam'], { scope: ['foo'] }), 'boo'); assert.equal(t.translate(['baz', 'bam'], { scope: ['foo', 'bar'] }), 'boo'); assert.equal(t.translate(['bam'], { scope: ['foo', 'bar', 'baz'] }), 'boo'); // mixed assert.equal(t.translate(['foo.bar', 'baz', 'bam']), 'boo'); assert.equal(t.translate(['bar', 'baz.bam'], { scope: 'foo' }), 'boo'); assert.equal(t.translate(['baz', 'bam'], { scope: 'foo.bar' }), 'boo'); assert.equal(t.translate('bam', { scope: ['foo.bar', 'baz'] }), 'boo'); // strange looking assert.equal(t.translate(['..foo.bar', 'baz', '', 'bam']), 'boo'); assert.equal(t.translate(['bar', 'baz..bam.'], { scope: '.foo' }), 'boo'); assert.equal(t.translate(['baz', null, 'bam'], { scope: 'foo.bar.' }), 'boo'); assert.equal(t.translate('bam...', { scope: [null, 'foo..bar', '', 'baz'] }), 'boo'); }); describe('with a `count` provided as option', () => { it('correctly pluralizes the translated value', () => { t.registerTranslations('en', { foo: { zero: 'no items', one: 'one item', other: '%(count)s items' } }); assert.equal(t.translate('foo', { count: 0 }), 'no items'); assert.equal(t.translate('foo', { count: 1 }), 'one item'); assert.equal(t.translate('foo', { count: 2 }), '2 items'); assert.equal(t.translate('foo', { count: 42 }), '42 items'); }); }); describe('with a `separator` provided as option', () => { it('correctly returns single array with key', () => { t.registerTranslations('en', { 'long.key.with.dots.in.name': 'Key with dots doesn\'t get split and returns correctly', another: { key: 'bar' }, mixed: { 'dots.and': { separator: 'bingo' } } }); assert.equal(t.translate('long.key.with.dots.in.name', { separator: '-' }), 'Key with dots doesn\'t get split and returns correctly'); assert.equal(t.translate('long.key.with.dots.in.name.not-found', { separator: '-' }), 'missing translation: en-long.key.with.dots.in.name.not-found'); assert.equal(t.translate('another-key', { separator: '-' }), 'bar'); assert.equal(t.translate('mixed-dots.and-separator', { separator: '-' }), 'bingo'); }); it('correctly returns nested key when using `*` as seperator', () => { t.registerTranslations('en', { "long": { key: { "with": { dots: { "in": { name: 'boo' } } } }} }); assert.equal(t.translate('long*key*with*dots*in*name', { separator: '*' }), 'boo'); }); }); describe('with other options provided', () => { describe('by default', () => { it('interpolates these options into the translated value', () => { t.registerTranslations('en', { foo: 'Hi %(name)s! See you %(when)s!' }); assert.equal(t.translate('foo', { name: 'Paul', when: 'later', where: 'home' }), 'Hi Paul! See you later!'); t.registerTranslations('en', { foo: 'Hello %(users[0].name)s and %(users[1].name)s!' }); assert.equal(t.translate('foo', { users: [{ name: 'Molly' }, { name: 'Polly' }] }), 'Hello Molly and Polly!'); }); it('interpolates the registered interpolations into the translated value', () => { var current = t._registry.interpolations; t.registerTranslations('en', {'hello':'Hello from %(brand)s!'}); t.registerInterpolations({brand:'Z'}); expect(t.translate('hello')).toBe('Hello from Z!'); t._registry.interpolations = current; t.registerInterpolations({ app_name: 'My Cool App', question: 'How are you today?' }); t.registerTranslations('en', { greeting: 'Welcome to %(app_name)s, %(name)s! %(question)s' }); assert.equal(t.translate('greeting', { name: 'Martin' }), 'Welcome to My Cool App, Martin! How are you today?'); assert.equal(t.translate('greeting', { name: 'Martin', app_name: 'The Foo App' }), 'Welcome to The Foo App, Martin! How are you today?'); t._registry.interpolations = current; }); }); describe('with the `interpolate` options set to `false`', () => { it('interpolates these options into the translated value', () => { t.registerTranslations('en', { foo: 'Hi %(name)s! See you %(when)s!' }); assert.equal(t.translate('foo', { interpolate: false, name: 'Paul', when: 'later', where: 'home' }), 'Hi %(name)s! See you %(when)s!'); }); }); }); describe('with the keepTrailingDot setting set to true', () => { it('returns the translation for keys that contain a trailing dot', () => { t.registerTranslations('fr', { foo: { bar: 'baz', 'With a dot.': 'Avec un point.' }, 'dot.': 'point.' }); t._registry.keepTrailingDot = true; t.withLocale('fr', () => { expect(t.translate('foo.bar')).toBe('baz'); expect(t.translate('foo.With a dot.')).toBe('Avec un point.'); expect(t.translate('dot.')).toBe('point.'); expect(t.translate('foo..bar')).toBe('baz'); expect(t.translate('foo..With a dot.')).toBe('Avec un point.'); expect(t.translate('.dot.')).toBe('point.'); expect(t.translate('foo.bar.')).toBe('missing translation: fr.foo.bar.'); expect(t.translate('foo.With a dot..')).toBe('missing translation: fr.foo.With a dot..'); expect(t.translate('foo.With. a dot.')).toBe('missing translation: fr.foo.With. a dot.'); expect(t.translate('dot..')).toBe('missing translation: fr.dot..'); }); }); }); }); describe('with a translation for a prefix of the key present', () => { it('returns the remaining translation part', () => { t.registerTranslations('en', { foo: { bar: { baz: { zero: 'no items', one: 'one item', other: '%(count)s items' } } } }); assert.deepEqual(t.translate('baz', { scope: ['foo', 'bar'] }), { zero: 'no items', one: 'one item', other: '%(count)s items' }); }); }); describe('with an array-type translation for the key present', () => { it('returns the array that key points to', () => { t.registerTranslations('en', { foo: { bar: { baz: [1, 'A', 0.42] } } }); assert.deepEqual(t.translate(['bar', 'baz'], { scope: 'foo' }), [1, 'A', 0.42]); }); }); describe('with a function-type translation for the key present', () => { it('returns the array that key points to', () => { var myFunc = () => {}; t.registerTranslations('en', { foo: { bar: { baz: myFunc } } }); assert.equal(t.translate(['bar', 'baz'], { scope: 'foo' }), myFunc); }); }); describe('with a function-type fallback present', () => { it('returns the array that key points to', () => { var myFunc = () => { return 'Here I am!'; }; var myFunc2 = function(x) { return 'Here ' + x + ' are!'; }; var fallbacks = [':i_dont_exist_either', myFunc, 'Should not be returned']; assert.equal(t.translate('i_dont_exist', { fallback: myFunc }), 'Here I am!'); assert.equal(t.translate('i_dont_exist', { fallback: myFunc2, object: 'you' }), 'Here you are!'); assert.equal(t.translate('i_dont_exist', { fallback: myFunc2 }), 'Here i_dont_exist are!'); assert.equal(t.translate('i_dont_exist', { fallback: fallbacks }), 'Here I am!'); }); }); describe('without a translation for the key present', () => { it('returns a string "missing translation: %(locale).%(scope).%(key)"', () => { assert.deepEqual(t.translate('bar', { locale: 'unknown', scope: 'foo' }), 'missing translation: unknown.foo.bar'); }); describe('with a `fallback` provided as option', () => { it('returns the fallback', () => { assert.equal(t.translate('baz', { locale: 'foo', scope: 'bar', fallback: 'boom' }), 'boom'); assert.equal(t.translate('baz', { locale: 'foo', scope: 'bar', fallback: 'Hello, %(name)s!', name: 'Martin' }), 'Hello, Martin!'); assert.equal(t.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 0 }), 'no items'); assert.equal(t.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 1 }), 'one item'); assert.equal(t.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 2 }), '2 items'); assert.deepEqual(t.translate('baz', { locale: 'foo', scope: 'bar', fallback: { oh: 'yeah' } }), { oh: 'yeah' }); assert.deepEqual(t.translate('baz', { locale: 'foo', scope: 'bar', fallback: [1, 'A', 0.42] }), 1); }); it('translates the fallback if given as "symbol" or array', () => { t.registerTranslations('en', { foo: { bar: 'bar', baz: 'baz' } }); assert.equal(t.translate('missing', { fallback: 'default' }), 'default'); assert.equal(t.translate('missing', { fallback: ':foo.bar' }), 'bar'); assert.equal(t.translate('missing', { fallback: ':bar', scope: 'foo' }), 'bar'); assert.equal(t.translate('missing', { fallback: [':also_missing', ':foo.bar'] }), 'bar'); assert.matches(t.translate('missing', { fallback: [':also_missing', ':foo.missed'] }), /missing translation/); }); }); describe('with a global `fallbackLocale` present', () => { it('returns the entry of the fallback locale', () => { t.registerTranslations('de', { bar: { baz: 'bam' } }); t.registerTranslations('de', { hello: 'Hallo %(name)s!' }); assert.equal(t.translate('baz', { locale: 'foo', scope: 'bar' }), 'missing translation: foo.bar.baz'); assert.equal(t.translate('hello', { locale: 'foo', name: 'Martin' }), 'missing translation: foo.hello'); var previousFallbackLocale = t.setFallbackLocale('de'); assert.equal(t.translate('baz', { locale: 'foo', scope: 'bar' }), 'bam'); assert.equal(t.translate('hello', { locale: 'foo', name: 'Martin' }), 'Hallo Martin!'); t.setFallbackLocale(previousFallbackLocale); }); }); describe('with a `fallbackLocale` provided as option', () => { it('returns the entry of the fallback locale', () => { t.registerTranslations('en', { bar: { baz: 'bam' } }); t.registerTranslations('en', { hello: 'Hello, %(name)s!' }); assert.equal(t.translate('baz', { locale: 'foo', scope: 'bar', fallbackLocale: 'en' }), 'bam'); assert.equal(t.translate('hello', { locale: 'foo', fallbackLocale: 'en', name: 'Martin' }), 'Hello, Martin!'); }); }); }); }); describe('without a valid key as first argument', () => { it('throws an invalid argument error', () => { var keys = [undefined, null, 42, {}, new Date(), /./, () => {}, [], '']; for (var i = 0, ii = keys.length; i < ii; i++) { assert.throws(() => { t.translate(keys[i]); }, /invalid argument/); } }); }); describe('with global interpolate setting set to false', () => { it('will not interpolate', () => { var current = t._registry.interpolations; t.registerTranslations('en', { 'hello':'Hello from %(brand)s!' }); t.registerInterpolations({ brand: 'Z' }); expect(t.translate('hello')).toBe('Hello from Z!'); var prev = t.setInterpolate(false); assert.equal(t.translate('hello'), 'Hello from %(brand)s!'); assert.equal(t.translate('hello', { interpolate: true }), 'Hello from %(brand)s!'); t.setInterpolate(prev); t._registry.interpolations = current; }); }); }); describe('#localize', () => { before(() => { t.setLocale('en'); }); it('is a function', () => { assert.isFunction(t.localize); }); it('does not mutate these options', () => { var options = { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }; t.localize(new Date(), options); assert.deepEqual(options, { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }); }); describe('when called without a date as first argument', () => { it('throws an invalid argument error', () => { assert.throws(() => { t.localize('foo'); }, /invalid argument/); }); }); describe('when called with a date as first argument', () => { var date = new time.Date('Thu Feb 6 2014 05:09:04 GMT+0100 (CET)'); date.setTimezone('America/Chicago'); describe('without providing options as second argument', () => { it('returns the default localization for that date', () => { var result = t.localize(date); expect(result).toBe('Wed, 5 Feb 2014 22:09'); }); }); describe('providing a `format` key in the options', () => { describe('with format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { format: 'default' }); expect(result).toBe('Wed, 5 Feb 2014 22:09'); }); }); describe('with format = "short"', () => { it('returns the short localization for that date', () => { var result = t.localize(date, { format: 'short' }); expect(result).toBe('5 Feb 22:09'); }); }); describe('with format = "long"', () => { it('returns the long localization for that date', () => { var result = t.localize(date, { format: 'long' }); expect(result).toBe('Wednesday, February 5th, 2014 22:09:04 -06:00'); }); }); describe('with an unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', () => { describe('with type = "datetime"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime' }); expect(result).toBe('Wed, 5 Feb 2014 22:09'); }); }); describe('with type = "date"', () => { it('returns the date localization for that date', () => { var result = t.localize(date, { type: 'date' }); expect(result).toBe('Wed, 5 Feb 2014'); }); }); describe('with type = "time"', () => { it('returns the time localization for that date', () => { var result = t.localize(date, { type: 'time' }); expect(result).toBe('22:09'); }); }); describe('with an unknown type', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', () => { describe('with type = "datetime" and format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'default' }); expect(result).toBe('Wed, 5 Feb 2014 22:09'); }); }); describe('with type = "datetime" and format = "short"', () => { it('returns the short datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'short' }); expect(result).toBe('5 Feb 22:09'); }); }); describe('with type = "datetime" and format = "long"', () => { it('returns the long datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'long' }); expect(result).toBe('Wednesday, February 5th, 2014 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', () => { it('returns the default time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'default' }); expect(result).toBe('22:09'); }); }); describe('with type = "time" and format = "short"', () => { it('returns the short time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'short' }); expect(result).toBe('22:09'); }); }); describe('with type = "time" and format = "long"', () => { it('returns the long time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'long' }); expect(result).toBe('22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', () => { it('returns the default date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'default' }); expect(result).toBe('Wed, 5 Feb 2014'); }); }); describe('with type = "date" and format = "short"', () => { it('returns the short date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'short' }); expect(result).toBe('Feb 5'); }); }); describe('with type = "date" and format = "long"', () => { it('returns the long date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'long' }); expect(result).toBe('Wednesday, February 5th, 2014'); }); }); describe('with unknown type and unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('with locale set to "de"', () => { var prev; beforeEach(() => { t.registerTranslations('de', require('./locales/de')); prev = t.setLocale('de'); }); afterEach(() => { t.setLocale(prev); }); describe('without providing options as second argument', () => { it('returns the default localization for that date', () => { var result = t.localize(date); expect(result).toBe('Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('providing a `format` key in the options', () => { describe('with format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { format: 'default' }); expect(result).toBe('Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with format = "short"', () => { it('returns the short localization for that date', () => { var result = t.localize(date, { format: 'short' }); expect(result).toBe('05.02.14 22:09'); }); }); describe('with format = "long"', () => { it('returns the long localization for that date', () => { var result = t.localize(date, { format: 'long' }); expect(result).toBe('Mittwoch, 5. Februar 2014, 22:09:04 -06:00'); }); }); describe('with an unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', () => { describe('with type = "datetime"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime' }); expect(result).toBe('Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with type = "date"', () => { it('returns the date localization for that date', () => { var result = t.localize(date, { type: 'date' }); expect(result).toBe('Mi, 5. Feb 2014'); }); }); describe('with type = "time"', () => { it('returns the time localization for that date', () => { var result = t.localize(date, { type: 'time' }); expect(result).toBe('22:09 Uhr'); }); }); describe('with an unknown type', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', () => { describe('with type = "datetime" and format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'default' }); expect(result).toBe('Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with type = "datetime" and format = "short"', () => { it('returns the short datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'short' }); expect(result).toBe('05.02.14 22:09'); }); }); describe('with type = "datetime" and format = "long"', () => { it('returns the long datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'long' }); expect(result).toBe('Mittwoch, 5. Februar 2014, 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', () => { it('returns the default time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'default' }); expect(result).toBe('22:09 Uhr'); }); }); describe('with type = "time" and format = "short"', () => { it('returns the short time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'short' }); expect(result).toBe('22:09'); }); }); describe('with type = "time" and format = "long"', () => { it('returns the long time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'long' }); expect(result).toBe('22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', () => { it('returns the default date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'default' }); expect(result).toBe('Mi, 5. Feb 2014'); }); }); describe('with type = "date" and format = "short"', () => { it('returns the short date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'short' }); expect(result).toBe('05.02.14'); }); }); describe('with type = "date" and format = "long"', () => { it('returns the long date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'long' }); expect(result).toBe('Mittwoch, 5. Februar 2014'); }); }); describe('with unknown type and unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); }); describe('with locale set to "pt-br"', () => { var prev; beforeEach(() => { t.registerTranslations('pt-br', require('./locales/pt-br')); prev = t.setLocale('pt-br'); }); afterEach(() => { t.setLocale(prev); }); describe('without providing options as second argument', () => { it('returns the default localization for that date', () => { var result = t.localize(date); expect(result).toBe('Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('providing a `format` key in the options', () => { describe('with format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { format: 'default' }); expect(result).toBe('Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with format = "short"', () => { it('returns the short localization for that date', () => { var result = t.localize(date, { format: 'short' }); expect(result).toBe('05/02/14 às 22:09'); }); }); describe('with format = "long"', () => { it('returns the long localization for that date', () => { var result = t.localize(date, { format: 'long' }); expect(result).toBe('Quarta-feira, 5 de Fevereiro de 2014 às 22:09:04 -06:00'); }); }); describe('with an unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', () => { describe('with type = "datetime"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime' }); expect(result).toBe('Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with type = "date"', () => { it('returns the date localization for that date', () => { var result = t.localize(date, { type: 'date' }); expect(result).toBe('Qua, 5 de Fev de 2014'); }); }); describe('with type = "time"', () => { it('returns the time localization for that date', () => { var result = t.localize(date, { type: 'time' }); expect(result).toBe('22:09'); }); }); describe('with an unknown type', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', () => { describe('with type = "datetime" and format = "default"', () => { it('returns the default localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'default' }); expect(result).toBe('Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with type = "datetime" and format = "short"', () => { it('returns the short datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'short' }); expect(result).toBe('05/02/14 às 22:09'); }); }); describe('with type = "datetime" and format = "long"', () => { it('returns the long datetime localization for that date', () => { var result = t.localize(date, { type: 'datetime', format: 'long' }); expect(result).toBe('Quarta-feira, 5 de Fevereiro de 2014 às 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', () => { it('returns the default time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'default' }); expect(result).toBe('22:09'); }); }); describe('with type = "time" and format = "short"', () => { it('returns the short time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'short' }); expect(result).toBe('22:09'); }); }); describe('with type = "time" and format = "long"', () => { it('returns the long time localization for that date', () => { var result = t.localize(date, { type: 'time', format: 'long' }); expect(result).toBe('22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', () => { it('returns the default date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'default' }); expect(result).toBe('Qua, 5 de Fev de 2014'); }); }); describe('with type = "date" and format = "short"', () => { it('returns the short date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'short' }); expect(result).toBe('05/02/14'); }); }); describe('with type = "date" and format = "long"', () => { it('returns the long date localization for that date', () => { var result = t.localize(date, { type: 'date', format: 'long' }); expect(result).toBe('Quarta-feira, 5 de Fevereiro de 2014'); }); }); describe('with unknown type and unknown format', () => { it('returns a string containing "missing translation"', () => { var result = t.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); }); }); }); describe('#registerTranslations', () => { it('is a function', () => { assert.isFunction(t.registerTranslations); }); it('returns the passed arguments as an object structure', () => { var locale = 'foo'; var data = { bar: { baz: 'bingo' } }; var actual = t.registerTranslations(locale, data); var expected = { foo: { bar: { baz: 'bingo' }}}; assert.deepEqual(actual, expected); }); it('merges the passed arguments correctly into the registry', () => { t._registry.translations = {}; t.registerTranslations('foo', { bar: { baz: 'bingo' } }); var expected = { foo: { bar: { baz: 'bingo' } } }; assert.deepEqual(t._registry.translations, expected); t.registerTranslations('foo', { bar: { bam: 'boo' } }); var expected = { foo: { bar: { baz: 'bingo', bam: 'boo' } } }; assert.deepEqual(t._registry.translations, expected); t.registerTranslations('foo', { bing: { bong: 'beng' } }); var expected = { foo: { bar: { baz: 'bingo', bam: 'boo' }, bing: { bong: 'beng' } } }; assert.deepEqual(t._registry.translations, expected); // clean up t._registry.translations = {}; t.registerTranslations('en', require('./locales/en')); }); }); describe('#registerInterpolations', () => { it('is a function', () => { assert.isFunction(t.registerInterpolations); }); it('merges the passed arguments correctly into the registry', () => { t._registry.interpolations = {}; t.registerInterpolations({ foo: 'yes', bar: 'no' }); assert.deepEqual(t._registry.interpolations, { foo: 'yes', bar: 'no' }); t.registerInterpolations({ baz: 'hey' }); assert.deepEqual(t._registry.interpolations, { foo: 'yes', bar: 'no', baz: 'hey' }); // clean up t._registry.interpolations = {}; }); }); describe('explicitly checking the examples of the README', () => { it('passes all tests', () => { translate.registerTranslations('en', { damals: { about_x_hours_ago: { one: 'about one hour ago', other: 'about %(count)s hours ago' } } }); assert.deepEqual(translate('damals'), { about_x_hours_ago: { one: 'about one hour ago', other: 'about %(count)s hours ago' } }); expect(translate('damals.about_x_hours_ago.one')).toBe('about one hour ago'); assert.equal(translate(['damals', 'about_x_hours_ago', 'one']), 'about one hour ago'); assert.equal(translate(['damals', 'about_x_hours_ago.one']), 'about one hour ago'); assert.equal(translate('about_x_hours_ago.one', { scope: 'damals' }), 'about one hour ago'); assert.equal(translate('one', { scope: 'damals.about_x_hours_ago' }), 'about one hour ago'); assert.equal(translate('one', { scope: ['damals', 'about_x_hours_ago'] }), 'about one hour ago'); assert.equal(translate('damals.about_x_hours_ago.one', { separator: '*' }), 'missing translation: en*damals.about_x_hours_ago.one'); translate.registerTranslations('en', { foo: 'foo %(bar)s' }); assert.equal(translate('foo', { bar: 'baz' }), 'foo baz'); translate.registerTranslations('en', { x_items: { zero: 'No items.', one: 'One item.', other: '%(count)s items.' } }); assert.equal(translate('x_items', { count: 0 }), 'No items.'); assert.equal(translate('x_items', { count: 1 }), 'One item.'); assert.equal(translate('x_items', { count: 42 }), '42 items.'); assert.equal(translate('baz', { fallback: 'default' }), 'default'); translate.registerTranslations('de', require('./locales/de')); translate.registerTranslations('de', JSON.parse('{"my_project": {"greeting": "Hallo, %(name)s!","x_items": {"one": "1 Stück", "other": "%(count)s Stücke"}}}')); assert.equal(translate.withLocale('de', () => { return translate('greeting', { scope: 'my_project', name: 'Martin' }); }), '<NAME>!'); assert.equal(translate.withLocale('de', () => { return translate('x_items', { scope: 'my_project', count: 1 }); }), '1 Stück'); var date = new time.Date('Fri Feb 21 2014 13:46:24 GMT+0100 (CET)'); date.setTimezone('Europe/Amsterdam'); expect(translate.localize(date) ).toBe('Fri, 21 Feb 2014 13:46'); assert.equal(translate.localize(date, { format: 'short' }) , '21 Feb 13:46'); assert.equal(translate.localize(date, { format: 'long' }) , 'Friday, February 21st, 2014 13:46:24 +01:00'); assert.equal(translate.localize(date, { type: 'date' }) , 'Fri, 21 Feb 2014'); assert.equal(translate.localize(date, { type: 'date', format: 'short' }) , 'Feb 21'); assert.equal(translate.localize(date, { type: 'date', format: 'long' }) , 'Friday, February 21st, 2014'); assert.equal(translate.localize(date, { type: 'time' }) , '13:46'); assert.equal(translate.localize(date, { type: 'time', format: 'short' }) , '13:46'); assert.equal(translate.localize(date, { type: 'time', format: 'long' }) , '13:46:24 +01:00'); assert.equal(translate.localize(date, { locale: 'de' }) , 'Fr, 21. Feb 2014, 13:46 Uhr'); translate.registerTranslations('en', { my_namespace: { greeting: 'Welcome to %(app_name)s, %(visitor)s!' } }); translate.registerInterpolations({ app_name: 'My Cool App' }); assert.equal(translate('my_namespace.greeting', { visitor: 'Martin' }), 'Welcome to My Cool App, Martin!'); assert.equal(translate('my_namespace.greeting', { visitor: 'Martin', app_name: 'The Foo App' }), 'Welcome to The Foo App, Martin!'); }); }); }); /* Helper Functions */ assert.isString = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object String]', message || (value + ' is not a string')); }; assert.isFunction = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Function]', message || (value + ' is not a function')); }; assert.isObject = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Object]', message || (value + ' is not an object')); }; assert.isUndefined = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Undefined]', message || (value + ' is not undefined')); }; assert.matches = function(actual, expected, message) { if (!expected.test(actual)) { assert.fail(actual, expected, message, '!~'); } }; <file_sep>declare var __DEV__; export const EXPLORER_URLS = __TEST__ ? { BTC: "https://live.blockcypher.com/btc-testnet/tx/#{txid}", ETH: "https://kovan.etherscan.io/tx/#{txid}", GAS: "https://scan.nel.group/#testnet/transaction/#{txid}", LTC: "https://chain.so/tx/LTCTEST/#{txid}", QTUM: "https://testnet.qtum.org/tx/#{txid}" } : { BTC: "https://live.blockcypher.com/btc/tx/#{txid}", USDT: "https://www.omniexplorer.info/tx/#{txid}", ETH: "https://etherscan.io/tx/#{txid}", XRP: "https://xrpcharts.ripple.com/#/transactions/#{txid}", GAS: "https://neotracker.io/tx/#{txid}", EOS: "https://eosflare.io/tx/#{txid}", LTC: "https://chain.so/tx/LTC/#{txid}", VET: "https://explore.veforge.com/transactions/#{txid}", QTUM: "https://explorer.qtum.org/tx/#{txid}", ZEC: "https://zcashnetwork.info/tx/#{txid}", PCX: "https://scan.chainx.org/txs/#{txid}" }; export const CONTRACT_URLS = __TEST__ ? { ERC20: "https://kovan.etherscan.io/token/#{contract}" } : { ERC20: "https://etherscan.io/token/#{contract}" }; declare const __TEST__; export const GATEWAY_URI = __TEST__ ? "https://gatewaytest.cybex.io/gateway" : "https://gateway.cybex.io/gateway"; export const GATEWAY_QUERY_URI = !__DEV__ ? "https://gateway-query.cybex.io/" : "///localhost:5684/"; export const GATEWAY_ID = __TEST__ ? "CybexGatewayDev" : "CybexGateway"; export type JadeBody = { status: JadeStatus; message: string; result: JadeBodyResult; }; type JadeBodyResult = { id: string; state: JadeState; coinType: JadeCoinType; bizType: JadeBizType; to: string; value: string; fee: number; extraData: string; create_at: number; update_at: number; data: { type: JadeDataType; hash: string; state: JadeState; from: [JadeResultAddress]; to: [JadeResultAddress]; fee: number; blockNumber: number; blockHash: string; confirmations: number; timestampBegin: number; timestampFinish: number; }; } & { type: string; address: string; state: string; }; type JadeResultAddress = { address: string; value: string; txid: string | null; n: string | null; }; type JadeState = "done" | "pending" | "init" | "online" | "failed"; type JadeBizType = "DEPOSIT" | "WITHDRAW"; type JadeCoinType = "BTC" | "ETH"; type JadeDataType = "Bitcoin"; type JadeStatus = | 0 //成功 | 10000 //必选参数不能为空 | 10001 //系统错误 | 10002 //非法参数 | 20000 //不支持该地址类型 | 20001 //地址错误,首字母不对 | 20002 //地址错误,长度不对 | 20000; // 提币地址与类型不匹配 export const CALLBACK_URL = "http://cybex.io"; export enum ProtocolType { ERC20, ETH, BTC, USDT, EOS, LTC, QTUM, NEO, XRP, COSMOS, IRIS, VET, ZEC, PCX } export class GatewayAssetOptions { specificExplorer?: string; specificContractExplorer?: string; name?: string; contractAddress?; allowDeposit? = true; allowWithdraw? = true; isDisabled? = false; } export class GatewayAsset { static ExplorerAddress = { [ProtocolType.BTC]: EXPLORER_URLS.BTC, [ProtocolType.USDT]: EXPLORER_URLS.USDT, [ProtocolType.ERC20]: EXPLORER_URLS.ETH, [ProtocolType.ETH]: EXPLORER_URLS.ETH, [ProtocolType.EOS]: EXPLORER_URLS.EOS, [ProtocolType.LTC]: EXPLORER_URLS.LTC, [ProtocolType.QTUM]: EXPLORER_URLS.QTUM, [ProtocolType.XRP]: EXPLORER_URLS.XRP, [ProtocolType.NEO]: EXPLORER_URLS.GAS, [ProtocolType.ZEC]: EXPLORER_URLS.ZEC, [ProtocolType.PCX]: EXPLORER_URLS.PCX }; static ContractAddress = { [ProtocolType.ERC20]: CONTRACT_URLS.ERC20 // [ProtocolType.NEO]: EXPLORER_URLS.GAS }; isDisabled = false; contractExplorer: string; allowDeposit = true; allowWithdraw = true; constructor( public asset: string, public type: string, public protocol: ProtocolType, public options: GatewayAssetOptions = new GatewayAssetOptions() ) { this.contractExplorer = options.contractAddress ? this.getExplorerUrlByContract(options.contractAddress) : ""; this.allowDeposit = options.allowDeposit !== undefined ? options.allowDeposit : this.allowDeposit; this.allowWithdraw = options.allowWithdraw !== undefined ? options.allowWithdraw : this.allowWithdraw; this.isDisabled = options.isDisabled !== undefined ? options.isDisabled : this.isDisabled; } getExplorerUrlByTx(tx: string): string { if (!GatewayAsset.ExplorerAddress[this.protocol]) return ""; try { return ( this.options.specificExplorer || GatewayAsset.ExplorerAddress[this.protocol] || "" ).replace("#{txid}", tx); } catch { return ""; } } getExplorerUrlByContract(contractAddress: string): string { if (!GatewayAsset.ContractAddress[this.protocol]) return ""; try { return ( this.options.specificContractExplorer || GatewayAsset.ContractAddress[this.protocol] ).replace("#{contract}", contractAddress); } catch { return ""; } } } export const JadePool: { GATEWAY_ACCOUNT: string; ADDRESS_TYPES: { [asset: string]: GatewayAsset }; } = __TEST__ ? { GATEWAY_ACCOUNT: "jade-gateway", // Cybex资产: 外部资产 ADDRESS_TYPES: { "TEST.ETH": new GatewayAsset("TEST.ETH", "ETH", ProtocolType.ETH, { name: "Ethereum" }), "TEST.BTC": new GatewayAsset("TEST.BTC", "BTC", ProtocolType.BTC, { name: "Bitcoin" }), "TEST.VET": new GatewayAsset("TEST.VET", "VET", ProtocolType.ETH, { name: "VeChain" }), // "TEST.EOS": new GatewayAsset("TEST.EOS", "EOS", ProtocolType.ETH), "TEST.USDT": new GatewayAsset("TEST.USDT", "USDT", ProtocolType.BTC), "TEST.BAT": new GatewayAsset("TEST.BAT", "BAT", ProtocolType.ETH), "TEST.OMG": new GatewayAsset("TEST.OMG", "OMG", ProtocolType.ETH), "TEST.SNT": new GatewayAsset("TEST.SNT", "SNT", ProtocolType.ETH), "TEST.NAS": new GatewayAsset("TEST.NAS", "NAS", ProtocolType.ETH), "TEST.KNC": new GatewayAsset("TEST.KNC", "KNC", ProtocolType.ETH), "TEST.MT": new GatewayAsset("TEST.MT", "MT", ProtocolType.ETH), "TEST.PAY": new GatewayAsset("TEST.PAY", "PAY", ProtocolType.ETH), "TEST.GET": new GatewayAsset("TEST.GET", "GET", ProtocolType.ETH), "TEST.TCT": new GatewayAsset("TEST.TCT", "TCT", ProtocolType.ETH), "TEST.LTC": new GatewayAsset("TEST.LTC", "LTC", ProtocolType.LTC, { name: "Litecoin" }), "TEST.EOS": new GatewayAsset("TEST.EOS", "EOS", ProtocolType.EOS, { name: "EOS" }), // "TEST.SDT": new GatewayAsset("TEST.SDT", "SDT", ProtocolType.ETH), // "TEST.GNT": new GatewayAsset("TEST.GNT", "GNT", ProtocolType.ETH), // "TEST.BTM": new GatewayAsset("TEST.BTM", "BTM", ProtocolType.ETH), "TEST.DPY": new GatewayAsset("TEST.DPY", "DPY", ProtocolType.ETH), "TEST.MAD": new GatewayAsset("TEST.MAD", "MAD", ProtocolType.ETH), "TEST.GNX": new GatewayAsset("TEST.GNX", "GNX", ProtocolType.ETH), "TEST.KEY": new GatewayAsset("TEST.KEY", "KEY", ProtocolType.ETH), // "TEST.LST": new GatewayAsset("TEST.LST", "LST", ProtocolType.ETH), "TEST.ENG": new GatewayAsset("TEST.ENG", "ENG", ProtocolType.ETH) } } : { GATEWAY_ACCOUNT: "cybex-jadegateway", // Cybex资产: 外部资产 ADDRESS_TYPES: { "JADE.ETH": new GatewayAsset("JADE.ETH", "ETH", ProtocolType.ETH, { name: "Ethereum" }), "JADE.BTC": new GatewayAsset("JADE.BTC", "BTC", ProtocolType.BTC, { name: "Bitcoin" }), "JADE.LTC": new GatewayAsset("JADE.LTC", "LTC", ProtocolType.LTC, { name: "Litecoin" }), "JADE.EOS": new GatewayAsset("JADE.EOS", "EOS", ProtocolType.EOS, { name: "EOS" }), "JADE.LC": new GatewayAsset("JADE.LC", "LC", ProtocolType.EOS, { name: "LC" }), "JADE.XRP": new GatewayAsset("JADE.XRP", "XRP", ProtocolType.XRP, { name: "Ripple" }), "JADE.USDT": new GatewayAsset("JADE.USDT", "USDT", ProtocolType.USDT, { name: "Tether" }), "JADE.LHT": new GatewayAsset("JADE.LHT", "LHT", ProtocolType.ERC20, { name: "LongHash" }), "JADE.INK": new GatewayAsset("JADE.INK", "INK", ProtocolType.ERC20, { name: "Ink [QTUM]", contractAddress: "0xf4c90e18727c5c76499ea6369c856a6d61d3e92e" }), "JADE.BAT": new GatewayAsset("JADE.BAT", "BAT", ProtocolType.ERC20, { name: "Basic Attention Token", contractAddress: "0x0d8775f648430679a709e98d2b0cb6250d2887ef" }), "JADE.OMG": new GatewayAsset("JADE.OMG", "OMG", ProtocolType.ERC20, { name: "OmiseGO", contractAddress: "0xd26114cd6ee289accf82350c8d8487fedb8a0c07" }), "JADE.SNT": new GatewayAsset("JADE.SNT", "SNT", ProtocolType.ERC20, { name: "Status", contractAddress: "0x744d70fdbe2ba4cf95131626614a1763df805b9e" }), "JADE.NAS": new GatewayAsset("JADE.NAS", "NAS", ProtocolType.ERC20, { name: "Nebulas", contractAddress: "0x5d65d971895edc438f465c17db6992698a52318d" }), "JADE.KNC": new GatewayAsset("JADE.KNC", "KNC", ProtocolType.ERC20, { name: "Kyber Network", contractAddress: "0xdd974d5c2e2928dea5f71b9825b8b646686bd200" }), "JADE.PAY": new GatewayAsset("JADE.PAY", "PAY", ProtocolType.ERC20, { name: "TenX", contractAddress: "0xb97048628db6b661d4c2aa833e95dbe1a905b280" }), "JADE.GET": new GatewayAsset("JADE.GET", "GET", ProtocolType.ERC20, { name: "Global Escrow Token, Themis", contractAddress: "0x60c68a87be1e8a84144b543aacfa77199cd3d024" }), "JADE.MAD": new GatewayAsset("JADE.MAD", "MAD", ProtocolType.ERC20, { name: "MAD Network", contractAddress: "0x5b09a0371c1da44a8e24d36bf5deb1141a84d875" }), "JADE.TCT": new GatewayAsset("JADE.TCT", "TCT", ProtocolType.ERC20, { name: "TokenClub", contractAddress: "0x4824a7b64e3966b0133f4f4ffb1b9d6beb75fff7" }), "JADE.POS": new GatewayAsset("JADE.POS", "POS", ProtocolType.ERC20, { name: "WePoS", contractAddress: "0x73c0d0abe065acdbb52b25412593c9600366f78b" }), "JADE.ATOM": new GatewayAsset( "JADE.ATOM", "ATOM", ProtocolType.COSMOS, { name: "COSMOS(ATOM)" // isDisabled: true } ), "JADE.IRIS": new GatewayAsset("JADE.IRIS", "IRIS", ProtocolType.IRIS, { name: "IRIS Network (IRIS)" // isDisabled: true }), "JADE.RING": new GatewayAsset("JADE.RING", "RING", ProtocolType.ERC20, { name: "Evolution Land Global Token", contractAddress: "0x9469D013805bFfB7D3DEBe5E7839237e535ec483" }), "JADE.MXC": new GatewayAsset("JADE.MXC", "MXC", ProtocolType.ERC20, { name: "Machine Xchange Coin", contractAddress: "0x5Ca381bBfb58f0092df149bD3D243b08B9a8386e" }), "JADE.CENNZ": new GatewayAsset( "JADE.CENNZ", "CENNZ", ProtocolType.ERC20, { name: "Centrality", contractAddress: "0x1122b6a0e00dce0563082b6e2953f3a943855c1f" } ), "JADE.NASH": new GatewayAsset("JADE.NASH", "NASH", ProtocolType.ERC20, { name: "NeoWorld Cash", contractAddress: "0x4b94c8567763654101f690cf4d54957206383b75" }), "JADE.NWT": new GatewayAsset("JADE.NWT", "NWT", ProtocolType.ERC20, { name: "NeoWorld Token", contractAddress: "0x179201b6d8f1d984fae733313a5035e20d4f4869" }), "JADE.POLY": new GatewayAsset("JADE.POLY", "POLY", ProtocolType.ERC20, { name: "Polymath", contractAddress: "0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC" }), "JADE.MCO": new GatewayAsset("JADE.MCO", "MCO", ProtocolType.ERC20, { name: "Monaco", contractAddress: "0xb63b606ac810a52cca15e44bb630fd42d8d1d83d" }), "JADE.JCT": new GatewayAsset("JADE.JCT", "JCT", ProtocolType.ERC20, { name: "JCT", contractAddress: "0x7Fe92EC600F15cD25253b421bc151c51b0276b7D" }), "JADE.HER": new GatewayAsset("JADE.HER", "HER", ProtocolType.ERC20, { name: "Herdius", contractAddress: "0x9ae559ac062de221eb5198d90c27e45e85fcaab2" }), "JADE.CTXC": new GatewayAsset("JADE.CTXC", "CTXC", ProtocolType.ERC20, { name: "Cortex", contractAddress: "0xea11755ae41d889ceec39a63e6ff75a02bc1c00d" }), "JADE.NES": new GatewayAsset("JADE.NES", "NES", ProtocolType.ERC20, { name: "Genesis Space", contractAddress: "0xa74ae2d3a4c3f6d9454634fee91dc7aab6724cf9" }), "JADE.PPT": new GatewayAsset("JADE.PPT", "PPT", ProtocolType.ERC20, { name: "Populous", contractAddress: "0xd4fa1460f537bb9085d22c7bccb5dd450ef28e3a" }), "JADE.RHOC": new GatewayAsset("JADE.RHOC", "RHOC", ProtocolType.ERC20, { name: "RChain", contractAddress: "0x168296bb09e24a88805cb9c33356536b980d3fc5" }), "JADE.MKR": new GatewayAsset("JADE.MKR", "MKR", ProtocolType.ERC20, { name: "Maker", contractAddress: "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2" }), "JADE.FUN": new GatewayAsset("JADE.FUN", "FUN", ProtocolType.ERC20, { name: "FunFair", contractAddress: "0x419d0d8bdd9af5e606ae2232ed285aff190e711b" }), "JADE.VET": new GatewayAsset("JADE.VET", "VET", ProtocolType.VET, { name: "VeChain" }), "JADE.MVP": new GatewayAsset("JADE.MVP", "MVP", ProtocolType.ERC20, { name: "Merculet", contractAddress: "0x8a77e40936bbc27e80e9a3f526368c967869c86d" }), "JADE.GNT": new GatewayAsset("JADE.GNT", "GNT", ProtocolType.ERC20, { name: "Golem", contractAddress: "0xa74476443119a942de498590fe1f2454d7d4ac0d" }), "JADE.DPY": new GatewayAsset("JADE.DPY", "DPY", ProtocolType.ERC20, { name: "Delphy", contractAddress: "0x6c2adc2073994fb2ccc5032cc2906fa221e9b391" }), "JADE.GNX": new GatewayAsset("JADE.GNX", "GNX", ProtocolType.ERC20, { name: "Gen<NAME>", contractAddress: "0x6ec8a24cabdc339a06a172f8223ea557055adaa5" }), "JADE.KEY": new GatewayAsset("JADE.KEY", "KEY", ProtocolType.ERC20, { name: "Bi<NAME>", contractAddress: "0x4cd988afbad37289baaf53c13e98e2bd46aaea8c" }), "JADE.MT": new GatewayAsset("JADE.MT", "MT", ProtocolType.ERC20, { name: "MyToken", contractAddress: "0x9b4e2b4b13d125238aa0480dd42b4f6fc71b37cc" }), // "JADE.LST": new GatewayAsset("JADE.LST", "LST", ProtocolType.ETH), "JADE.ENG": new GatewayAsset("JADE.ENG", "ENG", ProtocolType.ERC20, { name: "Enigma", contractAddress: "0xf0ee6b27b759c9893ce4f094b49ad28fd15a23e4" }), "JADE.QLC": new GatewayAsset("JADE.QLC", "QLC", ProtocolType.NEO, { name: "QLC Chain", contractAddress: "<KEY>" }), "JADE.ZEC": new GatewayAsset("JADE.ZEC", "ZEC", ProtocolType.ZEC, { name: "Zcash" }), "JADE.PCX": new GatewayAsset("JADE.PCX", "PCX", ProtocolType.PCX, { name: "ChainX" }), } }; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; const HelpWindow = class extends React.Component { render() { return ( <div> Toggle </div> ); } } export default HelpWindow;<file_sep>import { JadePool, CALLBACK_URL, JadeBody, GATEWAY_URI, GATEWAY_QUERY_URI, GATEWAY_ID } from "./GatewayConfig"; import { debugGen } from "utils"; import gql from "graphql-tag"; import { ApolloClient } from "apollo-client"; import { HttpLink } from "apollo-link-http"; import { InMemoryCache } from "apollo-cache-inmemory"; import { CustomTx } from "CustomTx"; import { LoginBody, Result as GatewayQueryResult, FundRecordRes } from "./GatewayModels"; const debug = debugGen("GatewayService"); // Config Headers const headers = new Headers(); headers.append("Content-Type", "application/x-www-form-urlencoded"); // Convert Params Object to serilized string; const serilize: (params: { [key: string]: any }) => string = params => Object.keys(params) .reduce( (paramsArray, nextParam) => [ ...paramsArray, `${nextParam}=${params[nextParam]}` ], [] ) .join("&"); // Generate common request will be used to communicate with Jadepool const genRequestInit: (body: any) => RequestInit = body => ({ mode: "cors", headers, method: "POST", body }); // Configure Apollo const httpLink = new HttpLink({ uri: GATEWAY_URI }); const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }); export async function getDepositInfo( accountName, asset: string, needNew? ): Promise<{ address; accountName; asset; time }> { debug("Get Deposit: ", accountName, asset, needNew); let mutation = gql` mutation GenNewAddress($accountName: String!, $asset: String!) { newDepositAddress(accountName: $accountName, asset: $asset) { address accountName asset type createAt } } `; let query = gql` query GetAddress($accountName: String!, $asset: String!) { getDepositAddress(accountName: $accountName, asset: $asset) { address accountName asset type createAt projectInfo { projectName logoUrl contractAddress contractExplorerUrl } } } `; return needNew ? await impl( "mutate", { mutation, variables: { accountName, asset } }, "newDepositAddress" ) : await impl( "query", { query, variables: { accountName, asset } }, "getDepositAddress" ); } export async function getWithdrawInfo( type: string ): Promise<{ fee; minValue }> { let query = gql` query WithdrawInfo($type: String!) { withdrawInfo(type: $type) { fee minValue precision asset type gatewayAccount } } `; return await impl( "query", { query, variables: { type } }, "withdrawInfo" ); } export async function verifyAddress( address: string, accountName: string, asset: string ): Promise<{ valid; error? }> { let query = gql` query VerifyAddress( $asset: String! $accountName: String! $address: String! ) { verifyAddress( asset: $asset accountName: $accountName address: $address ) { valid asset } } `; return await impl( "query", { query, variables: { asset, accountName, address } }, "verifyAddress" ); } export async function queryFundRecords(tx: CustomTx): Promise<FundRecordRes> { return await queryImpl("records", tx).then(res => res.data); } export async function loginQuery(tx: CustomTx): Promise<LoginBody> { return await queryImpl("login", tx).then(res => res.data); } async function queryImpl( api: string, tx: CustomTx ): Promise<GatewayQueryResult> { let headers = new Headers(); headers.append("Content-Type", "application/json"); let init = { headers, method: "POST", body: JSON.stringify(tx) }; return await fetch(`${GATEWAY_QUERY_URI}${api}`, init) .then(res => res.json()) .catch(e => { return { code: 400, error: e.message }; }); } async function impl(method: string, params: any, dataName: string) { if (dataName === "newDepositAddress") { await client.resetStore(); } try { return (await client[method](params)).data[dataName]; } catch (error) { console.error("GatewayError: ", error); throw error; } } export const GatewayService = { getDepositInfo, getWithdrawInfo, verifyAddress }; <file_sep>var React = require("react"); var classnames = require("classnames"); // var LayerMixin = require('react-layer-mixin'); var foundationApi = require("../utils/foundation-api"); var Offcanvas = React.createClass({ // mixins: [LayerMixin], getInitialState: function() { return { open: false }; }, getDefaultProps: function() { return { position: "left" }; }, componentDidMount: function() { foundationApi.subscribe( this.props.id, function(name, msg) { if (msg === "open") { this.setState({ open: true }); } else if (msg === "close") { this.setState({ open: false }); } else if (msg === "toggle") { this.setState({ open: !this.state.open }); } }.bind(this) ); }, componentWillUnmount: function() { foundationApi.unsubscribe(this.props.id); }, render: function() { var classes = { "off-canvas": true, "is-active": this.state.open }; classes[this.props.position] = true; if (this.props.className) { classes[this.props.className] = true; } return ( <div id={this.props.id} data-closable={true} className={classnames(classes)} > {this.props.children} </div> ); } }); module.exports = Offcanvas; <file_sep>import types from "./types"; import Serializer from "./serializer"; var { //id_type, //varint32, uint8, uint16, uint32, int64, uint64, string, bytes, bool, array, fixed_array, protocol_id_type, object_id_type, vote_id, future_extensions, static_variant, map, set, public_key, address, time_point_sec, optional } = types; // future_extensions = types.void; /* When updating generated code Replace: operation = static_variant [ with: operation.st_operations = [ Delete: public_key = new Serializer( "public_key" key_data: bytes 33 ) */ // Place-holder, their are dependencies on "operation" .. The final list of // operations is not avialble until the very end of the generated code. // See: operation.st_operations = ... var operation = static_variant(); // module.exports["operation"] = operation; export { operation }; // For module.exports export var void_ext = new Serializer("void_ext"); var cybex_ext_vesting = new Serializer("cybex_ext_vesting", { vesting_period: uint64, public_key: public_key }); var cybex_ext_transfer_vesting = new Serializer("cybex_ext_transfer_vesting", { vesting_cliff: uint64, vesting_duration: uint64 }); var cybex_ext_swap = new Serializer("cybex_ext_swap", { cybex_ext_swap: string }); var cybex_ext_xfer_to_name = new Serializer("cybex_ext_xfer_to_name", { name: string, asset_sym: string, fee_asset_sym: string, hw_cookie: uint8 }); var cybex_xfer_item = new Serializer("cybex_xfer_item", { name: string, amount: string }); var cybex_ext_xfer_to_many = new Serializer("cybex_ext_xfer_to_many", { list: array(cybex_xfer_item) }); var future_extensions = static_variant([ void_ext, cybex_ext_vesting, cybex_ext_swap, cybex_ext_transfer_vesting, cybex_ext_xfer_to_name, cybex_ext_xfer_to_many ]); // Custom-types follow Generated code: // ## Generated code follows // # programs/js_operation_serializer > npm i -g decaffeinate // ## ------------------------------- export const transfer_operation_fee_parameters = new Serializer( "transfer_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const limit_order_create_operation_fee_parameters = new Serializer( "limit_order_create_operation_fee_parameters", { fee: uint64 } ); export const limit_order_cancel_operation_fee_parameters = new Serializer( "limit_order_cancel_operation_fee_parameters", { fee: uint64 } ); export const call_order_update_operation_fee_parameters = new Serializer( "call_order_update_operation_fee_parameters", { fee: uint64 } ); export const fill_order_operation_fee_parameters = new Serializer( "fill_order_operation_fee_parameters", { fee: uint64 } ); export const account_create_operation_fee_parameters = new Serializer( "account_create_operation_fee_parameters", { basic_fee: uint64, premium_fee: uint64, price_per_kbyte: uint32 } ); export const account_update_operation_fee_parameters = new Serializer( "account_update_operation_fee_parameters", { fee: int64, price_per_kbyte: uint32 } ); export const account_whitelist_operation_fee_parameters = new Serializer( "account_whitelist_operation_fee_parameters", { fee: int64 } ); export const account_upgrade_operation_fee_parameters = new Serializer( "account_upgrade_operation_fee_parameters", { membership_annual_fee: uint64, membership_lifetime_fee: uint64 } ); export const account_transfer_operation_fee_parameters = new Serializer( "account_transfer_operation_fee_parameters", { fee: uint64 } ); export const asset_create_operation_fee_parameters = new Serializer( "asset_create_operation_fee_parameters", { symbol3: uint64, symbol4: uint64, long_symbol: uint64, price_per_kbyte: uint32 } ); export const asset_update_operation_fee_parameters = new Serializer( "asset_update_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const asset_update_bitasset_operation_fee_parameters = new Serializer( "asset_update_bitasset_operation_fee_parameters", { fee: uint64 } ); export const asset_update_feed_producers_operation_fee_parameters = new Serializer( "asset_update_feed_producers_operation_fee_parameters", { fee: uint64 } ); export const asset_issue_operation_fee_parameters = new Serializer( "asset_issue_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const initiate_crowdfund_operation_fee_parameters = new Serializer( "initiate_crowdfund_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const participate_crowdfund_operation_fee_parameters = new Serializer( "participate_crowdfund_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const withdraw_crowdfund_operation_fee_parameters = new Serializer( "withdraw_crowdfund_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const htlc_create_operation_fee_parameters = new Serializer( "htlc_create_operation_fee_parameters", { fee: uint64, fee_per_day: uint64 } ); export const htlc_redeem_operation_fee_parameters = new Serializer( "htlc_redeem_operation_fee_parameters", { fee: uint64, fee_per_kb: uint64 } ); export const asset_reserve_operation_fee_parameters = new Serializer( "asset_reserve_operation_fee_parameters", { fee: uint64 } ); export const asset_fund_fee_pool_operation_fee_parameters = new Serializer( "asset_fund_fee_pool_operation_fee_parameters", { fee: uint64 } ); export const asset_settle_operation_fee_parameters = new Serializer( "asset_settle_operation_fee_parameters", { fee: uint64 } ); export const asset_global_settle_operation_fee_parameters = new Serializer( "asset_global_settle_operation_fee_parameters", { fee: uint64 } ); export const asset_publish_feed_operation_fee_parameters = new Serializer( "asset_publish_feed_operation_fee_parameters", { fee: uint64 } ); export const witness_create_operation_fee_parameters = new Serializer( "witness_create_operation_fee_parameters", { fee: uint64 } ); export const witness_update_operation_fee_parameters = new Serializer( "witness_update_operation_fee_parameters", { fee: int64 } ); export const proposal_create_operation_fee_parameters = new Serializer( "proposal_create_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const proposal_update_operation_fee_parameters = new Serializer( "proposal_update_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const proposal_delete_operation_fee_parameters = new Serializer( "proposal_delete_operation_fee_parameters", { fee: uint64 } ); export const withdraw_permission_create_operation_fee_parameters = new Serializer( "withdraw_permission_create_operation_fee_parameters", { fee: uint64 } ); export const withdraw_permission_update_operation_fee_parameters = new Serializer( "withdraw_permission_update_operation_fee_parameters", { fee: uint64 } ); export const withdraw_permission_claim_operation_fee_parameters = new Serializer( "withdraw_permission_claim_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const withdraw_permission_delete_operation_fee_parameters = new Serializer( "withdraw_permission_delete_operation_fee_parameters", { fee: uint64 } ); export const committee_member_create_operation_fee_parameters = new Serializer( "committee_member_create_operation_fee_parameters", { fee: uint64 } ); export const committee_member_update_operation_fee_parameters = new Serializer( "committee_member_update_operation_fee_parameters", { fee: uint64 } ); export const committee_member_update_global_parameters_operation_fee_parameters = new Serializer( "committee_member_update_global_parameters_operation_fee_parameters", { fee: uint64 } ); export const vesting_balance_create_operation_fee_parameters = new Serializer( "vesting_balance_create_operation_fee_parameters", { fee: uint64 } ); export const vesting_balance_withdraw_operation_fee_parameters = new Serializer( "vesting_balance_withdraw_operation_fee_parameters", { fee: uint64 } ); export const worker_create_operation_fee_parameters = new Serializer( "worker_create_operation_fee_parameters", { fee: uint64 } ); export const custom_operation_fee_parameters = new Serializer( "custom_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const assert_operation_fee_parameters = new Serializer( "assert_operation_fee_parameters", { fee: uint64 } ); export const balance_claim_operation_fee_parameters = new Serializer( "balance_claim_operation_fee_parameters" ); export const override_transfer_operation_fee_parameters = new Serializer( "override_transfer_operation_fee_parameters", { fee: uint64, price_per_kbyte: uint32 } ); export const transfer_to_blind_operation_fee_parameters = new Serializer( "transfer_to_blind_operation_fee_parameters", { fee: uint64, price_per_output: uint32 } ); export const blind_transfer_operation_fee_parameters = new Serializer( "blind_transfer_operation_fee_parameters", { fee: uint64, price_per_output: uint32 } ); export const transfer_from_blind_operation_fee_parameters = new Serializer( "transfer_from_blind_operation_fee_parameters", { fee: uint64 } ); export const exchange_participate_fee_parameters = new Serializer( "exchange_participate_fee_parameters", { fee: uint64 } ); export const asset_settle_cancel_operation_fee_parameters = new Serializer( "asset_settle_cancel_operation_fee_parameters" ); export const asset_claim_fees_operation_fee_parameters = new Serializer( "asset_claim_fees_operation_fee_parameters", { fee: uint64 } ); var fee_parameters = static_variant([ transfer_operation_fee_parameters, limit_order_create_operation_fee_parameters, limit_order_cancel_operation_fee_parameters, call_order_update_operation_fee_parameters, fill_order_operation_fee_parameters, account_create_operation_fee_parameters, account_update_operation_fee_parameters, account_whitelist_operation_fee_parameters, account_upgrade_operation_fee_parameters, account_transfer_operation_fee_parameters, asset_create_operation_fee_parameters, // 10 asset_update_operation_fee_parameters, asset_update_bitasset_operation_fee_parameters, asset_update_feed_producers_operation_fee_parameters, asset_issue_operation_fee_parameters, asset_reserve_operation_fee_parameters, asset_fund_fee_pool_operation_fee_parameters, asset_settle_operation_fee_parameters, asset_global_settle_operation_fee_parameters, asset_publish_feed_operation_fee_parameters, witness_create_operation_fee_parameters, // 20 witness_update_operation_fee_parameters, proposal_create_operation_fee_parameters, proposal_update_operation_fee_parameters, proposal_delete_operation_fee_parameters, withdraw_permission_create_operation_fee_parameters, // 25 withdraw_permission_update_operation_fee_parameters, withdraw_permission_claim_operation_fee_parameters, withdraw_permission_delete_operation_fee_parameters, committee_member_create_operation_fee_parameters, committee_member_update_operation_fee_parameters, // 30 committee_member_update_global_parameters_operation_fee_parameters, vesting_balance_create_operation_fee_parameters, vesting_balance_withdraw_operation_fee_parameters, worker_create_operation_fee_parameters, custom_operation_fee_parameters, // 35 assert_operation_fee_parameters, balance_claim_operation_fee_parameters, override_transfer_operation_fee_parameters, transfer_to_blind_operation_fee_parameters, blind_transfer_operation_fee_parameters, // 40 transfer_from_blind_operation_fee_parameters, asset_settle_cancel_operation_fee_parameters, asset_claim_fees_operation_fee_parameters, asset_settle_cancel_operation_fee_parameters, initiate_crowdfund_operation_fee_parameters, // 45 participate_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, // 50 withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, // 55 withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters, // 60 withdraw_crowdfund_operation_fee_parameters, // 61 withdraw_crowdfund_operation_fee_parameters, // 62 exchange_participate_fee_parameters, // 63 htlc_create_operation_fee_parameters, // 64 htlc_create_operation_fee_parameters, // 65 htlc_redeem_operation_fee_parameters, // 66 withdraw_crowdfund_operation_fee_parameters, withdraw_crowdfund_operation_fee_parameters ]); export const fee_schedule = new Serializer("fee_schedule", { parameters: set(fee_parameters), scale: uint32 }); export const void_result = new Serializer("void_result"); export const asset = new Serializer("asset", { amount: int64, asset_id: protocol_id_type("asset") }); var operation_result = static_variant([void_result, object_id_type, asset]); export const processed_transaction = new Serializer("processed_transaction", { ref_block_num: uint16, ref_block_prefix: uint32, expiration: time_point_sec, operations: array(operation), extensions: set(future_extensions), signatures: array(bytes(65)), operation_results: array(operation_result) }); export const signed_block = new Serializer("signed_block", { previous: bytes(20), timestamp: time_point_sec, witness: protocol_id_type("witness"), transaction_merkle_root: bytes(20), extensions: set(future_extensions), witness_signature: bytes(65), transactions: array(processed_transaction) }); export const block_header = new Serializer("block_header", { previous: bytes(20), timestamp: time_point_sec, witness: protocol_id_type("witness"), transaction_merkle_root: bytes(20), extensions: set(future_extensions) }); export const signed_block_header = new Serializer("signed_block_header", { previous: bytes(20), timestamp: time_point_sec, witness: protocol_id_type("witness"), transaction_merkle_root: bytes(20), extensions: set(future_extensions), witness_signature: bytes(65) }); export const memo_data = new Serializer("memo_data", { from: public_key, to: public_key, nonce: uint64, message: bytes() }); export const transfer = new Serializer("transfer", { fee: asset, from: protocol_id_type("account"), to: protocol_id_type("account"), amount: asset, memo: optional(memo_data), extensions: set(future_extensions) }); export const limit_order_create = new Serializer("limit_order_create", { fee: asset, seller: protocol_id_type("account"), amount_to_sell: asset, min_to_receive: asset, expiration: time_point_sec, fill_or_kill: bool, extensions: set(future_extensions) }); export const limit_order_cancel = new Serializer("limit_order_cancel", { fee: asset, fee_paying_account: protocol_id_type("account"), order: protocol_id_type("limit_order"), extensions: set(future_extensions) }); export const call_order_update = new Serializer("call_order_update", { fee: asset, funding_account: protocol_id_type("account"), delta_collateral: asset, delta_debt: asset, extensions: set(future_extensions) }); export const fill_order = new Serializer("fill_order", { fee: asset, order_id: object_id_type, account_id: protocol_id_type("account"), pays: asset, receives: asset }); export const authority = new Serializer("authority", { weight_threshold: uint32, account_auths: map(protocol_id_type("account"), uint16), key_auths: map(public_key, uint16), address_auths: map(address, uint16) }); export const account_options = new Serializer("account_options", { memo_key: public_key, voting_account: protocol_id_type("account"), num_witness: uint16, num_committee: uint16, votes: set(vote_id), extensions: set(future_extensions) }); export const account_create = new Serializer("account_create", { fee: asset, registrar: protocol_id_type("account"), referrer: protocol_id_type("account"), referrer_percent: uint16, name: string, owner: authority, active: authority, options: account_options, extensions: set(future_extensions) }); export const account_update = new Serializer("account_update", { fee: asset, account: protocol_id_type("account"), owner: optional(authority), active: optional(authority), new_options: optional(account_options), extensions: set(future_extensions) }); export const account_whitelist = new Serializer("account_whitelist", { fee: asset, authorizing_account: protocol_id_type("account"), account_to_list: protocol_id_type("account"), new_listing: uint8, extensions: set(future_extensions) }); export const account_upgrade = new Serializer("account_upgrade", { fee: asset, account_to_upgrade: protocol_id_type("account"), upgrade_to_lifetime_member: bool, extensions: set(future_extensions) }); export const account_transfer = new Serializer("account_transfer", { fee: asset, account_id: protocol_id_type("account"), new_owner: protocol_id_type("account"), extensions: set(future_extensions) }); export const price = new Serializer("price", { base: asset, quote: asset }); export const asset_options = new Serializer("asset_options", { max_supply: int64, market_fee_percent: uint16, max_market_fee: int64, issuer_permissions: uint16, flags: uint16, core_exchange_rate: price, whitelist_authorities: set(protocol_id_type("account")), blacklist_authorities: set(protocol_id_type("account")), whitelist_markets: set(protocol_id_type("asset")), blacklist_markets: set(protocol_id_type("asset")), description: string, extensions: set(future_extensions) }); export const bitasset_options = new Serializer("bitasset_options", { feed_lifetime_sec: uint32, minimum_feeds: uint8, force_settlement_delay_sec: uint32, force_settlement_offset_percent: uint16, maximum_force_settlement_volume: uint16, short_backing_asset: protocol_id_type("asset"), extensions: set(future_extensions) }); export const asset_create = new Serializer("asset_create", { fee: asset, issuer: protocol_id_type("account"), symbol: string, precision: uint8, common_options: asset_options, bitasset_opts: optional(bitasset_options), is_prediction_market: bool, extensions: set(future_extensions) }); export const asset_update = new Serializer("asset_update", { fee: asset, issuer: protocol_id_type("account"), asset_to_update: protocol_id_type("asset"), new_issuer: optional(protocol_id_type("account")), new_options: asset_options, extensions: set(future_extensions) }); export const asset_update_bitasset = new Serializer("asset_update_bitasset", { fee: asset, issuer: protocol_id_type("account"), asset_to_update: protocol_id_type("asset"), new_options: bitasset_options, extensions: set(future_extensions) }); export const asset_update_feed_producers = new Serializer( "asset_update_feed_producers", { fee: asset, issuer: protocol_id_type("account"), asset_to_update: protocol_id_type("asset"), new_feed_producers: set(protocol_id_type("account")), extensions: set(future_extensions) } ); export const asset_issue = new Serializer("asset_issue", { fee: asset, issuer: protocol_id_type("account"), asset_to_issue: asset, issue_to_account: protocol_id_type("account"), memo: optional(memo_data), extensions: set(future_extensions) }); export const asset_reserve = new Serializer("asset_reserve", { fee: asset, payer: protocol_id_type("account"), amount_to_reserve: asset, extensions: set(future_extensions) }); export const asset_fund_fee_pool = new Serializer("asset_fund_fee_pool", { fee: asset, from_account: protocol_id_type("account"), asset_id: protocol_id_type("asset"), amount: int64, extensions: set(future_extensions) }); export const asset_settle = new Serializer("asset_settle", { fee: asset, account: protocol_id_type("account"), amount: asset, extensions: set(future_extensions) }); export const asset_global_settle = new Serializer("asset_global_settle", { fee: asset, issuer: protocol_id_type("account"), asset_to_settle: protocol_id_type("asset"), settle_price: price, extensions: set(future_extensions) }); export const participate_crowdfund = new Serializer("participate_crowdfund", { fee: asset, buyer: protocol_id_type("account"), valuation: int64, cap: int64, // pubkey: address, crowdfund: protocol_id_type("crowdfund") // extensions: set(future_extensions) }); export const withdraw_crowdfund = new Serializer("withdraw_crowdfund", { fee: asset, buyer: protocol_id_type("account"), crowdfund_contract: protocol_id_type("crowdfund_contract") }); export const initiate_crowdfund = new Serializer("initiate_crowdfund", { fee: asset, owner: protocol_id_type("account"), asset_id: protocol_id_type("asset"), t: uint64, u: uint64 // v: uint64, // extensions: set(future_extensions) }); export const price_feed = new Serializer("price_feed", { settlement_price: price, maintenance_collateral_ratio: uint16, maximum_short_squeeze_ratio: uint16, core_exchange_rate: price }); export const asset_publish_feed = new Serializer("asset_publish_feed", { fee: asset, publisher: protocol_id_type("account"), asset_id: protocol_id_type("asset"), feed: price_feed, extensions: set(future_extensions) }); export const witness_create = new Serializer("witness_create", { fee: asset, witness_account: protocol_id_type("account"), url: string, block_signing_key: public_key }); export const witness_update = new Serializer("witness_update", { fee: asset, witness: protocol_id_type("witness"), witness_account: protocol_id_type("account"), new_url: optional(string), new_signing_key: optional(public_key) }); export const op_wrapper = new Serializer("op_wrapper", { op: operation }); export const proposal_create = new Serializer("proposal_create", { fee: asset, fee_paying_account: protocol_id_type("account"), expiration_time: time_point_sec, proposed_ops: array(op_wrapper), review_period_seconds: optional(uint32), extensions: set(future_extensions) }); export const proposal_update = new Serializer("proposal_update", { fee: asset, fee_paying_account: protocol_id_type("account"), proposal: protocol_id_type("proposal"), active_approvals_to_add: set(protocol_id_type("account")), active_approvals_to_remove: set(protocol_id_type("account")), owner_approvals_to_add: set(protocol_id_type("account")), owner_approvals_to_remove: set(protocol_id_type("account")), key_approvals_to_add: set(public_key), key_approvals_to_remove: set(public_key), extensions: set(future_extensions) }); export const proposal_delete = new Serializer("proposal_delete", { fee: asset, fee_paying_account: protocol_id_type("account"), using_owner_authority: bool, proposal: protocol_id_type("proposal"), extensions: set(future_extensions) }); export const withdraw_permission_create = new Serializer( "withdraw_permission_create", { fee: asset, withdraw_from_account: protocol_id_type("account"), authorized_account: protocol_id_type("account"), withdrawal_limit: asset, withdrawal_period_sec: uint32, periods_until_expiration: uint32, period_start_time: time_point_sec } ); export const withdraw_permission_update = new Serializer( "withdraw_permission_update", { fee: asset, withdraw_from_account: protocol_id_type("account"), authorized_account: protocol_id_type("account"), permission_to_update: protocol_id_type("withdraw_permission"), withdrawal_limit: asset, withdrawal_period_sec: uint32, period_start_time: time_point_sec, periods_until_expiration: uint32 } ); export const withdraw_permission_claim = new Serializer( "withdraw_permission_claim", { fee: asset, withdraw_permission: protocol_id_type("withdraw_permission"), withdraw_from_account: protocol_id_type("account"), withdraw_to_account: protocol_id_type("account"), amount_to_withdraw: asset, memo: optional(memo_data) } ); export const withdraw_permission_delete = new Serializer( "withdraw_permission_delete", { fee: asset, withdraw_from_account: protocol_id_type("account"), authorized_account: protocol_id_type("account"), withdrawal_permission: protocol_id_type("withdraw_permission") } ); export const committee_member_create = new Serializer( "committee_member_create", { fee: asset, committee_member_account: protocol_id_type("account"), url: string } ); export const committee_member_update = new Serializer( "committee_member_update", { fee: asset, committee_member: protocol_id_type("committee_member"), committee_member_account: protocol_id_type("account"), new_url: optional(string) } ); export const chain_parameters = new Serializer("chain_parameters", { current_fees: fee_schedule, block_interval: uint8, maintenance_interval: uint32, maintenance_skip_slots: uint8, committee_proposal_review_period: uint32, maximum_transaction_size: uint32, maximum_block_size: uint32, maximum_time_until_expiration: uint32, maximum_proposal_lifetime: uint32, maximum_asset_whitelist_authorities: uint8, maximum_asset_feed_publishers: uint8, maximum_witness_count: uint16, maximum_committee_count: uint16, maximum_authority_membership: uint16, reserve_percent_of_fee: uint16, network_percent_of_fee: uint16, lifetime_referrer_percent_of_fee: uint16, cashback_vesting_period_seconds: uint32, cashback_vesting_threshold: int64, count_non_member_votes: bool, allow_non_member_whitelists: bool, witness_pay_per_block: int64, worker_budget_per_day: int64, max_predicate_opcode: uint16, fee_liquidation_threshold: int64, accounts_per_fee_scale: uint16, account_fee_scale_bitshifts: uint8, max_authority_depth: uint8, extensions: set(future_extensions) }); export const committee_member_update_global_parameters = new Serializer( "committee_member_update_global_parameters", { fee: asset, new_parameters: chain_parameters } ); export const linear_vesting_policy_initializer = new Serializer( "linear_vesting_policy_initializer", { begin_timestamp: time_point_sec, vesting_cliff_seconds: uint32, vesting_duration_seconds: uint32 } ); export const cdd_vesting_policy_initializer = new Serializer( "cdd_vesting_policy_initializer", { start_claim: time_point_sec, vesting_seconds: uint32 } ); var vesting_policy_initializer = static_variant([ linear_vesting_policy_initializer, cdd_vesting_policy_initializer ]); export const vesting_balance_create = new Serializer("vesting_balance_create", { fee: asset, creator: protocol_id_type("account"), owner: protocol_id_type("account"), amount: asset, policy: vesting_policy_initializer }); export const vesting_balance_withdraw = new Serializer( "vesting_balance_withdraw", { fee: asset, vesting_balance: protocol_id_type("vesting_balance"), owner: protocol_id_type("account"), amount: asset } ); export const refund_worker_initializer = new Serializer( "refund_worker_initializer" ); export const vesting_balance_worker_initializer = new Serializer( "vesting_balance_worker_initializer", { pay_vesting_period_days: uint16 } ); export const burn_worker_initializer = new Serializer( "burn_worker_initializer" ); var worker_initializer = static_variant([ refund_worker_initializer, vesting_balance_worker_initializer, burn_worker_initializer ]); export const worker_create = new Serializer("worker_create", { fee: asset, owner: protocol_id_type("account"), work_begin_date: time_point_sec, work_end_date: time_point_sec, daily_pay: int64, name: string, url: string, initializer: worker_initializer }); export const custom = new Serializer("custom", { fee: asset, payer: protocol_id_type("account"), required_auths: set(protocol_id_type("account")), id: uint16, data: bytes() }); export const account_name_eq_lit_predicate = new Serializer( "account_name_eq_lit_predicate", { account_id: protocol_id_type("account"), name: string } ); export const asset_symbol_eq_lit_predicate = new Serializer( "asset_symbol_eq_lit_predicate", { asset_id: protocol_id_type("asset"), symbol: string } ); export const block_id_predicate = new Serializer("block_id_predicate", { id: bytes(20) }); var predicate = static_variant([ account_name_eq_lit_predicate, asset_symbol_eq_lit_predicate, block_id_predicate ]); export const assert = new Serializer("assert", { fee: asset, fee_paying_account: protocol_id_type("account"), predicates: array(predicate), required_auths: set(protocol_id_type("account")), extensions: set(future_extensions) }); export const balance_claim = new Serializer("balance_claim", { fee: asset, deposit_to_account: protocol_id_type("account"), balance_to_claim: protocol_id_type("balance"), balance_owner_key: public_key, total_claimed: asset }); export const override_transfer = new Serializer("override_transfer", { fee: asset, issuer: protocol_id_type("account"), from: protocol_id_type("account"), to: protocol_id_type("account"), amount: asset, memo: optional(memo_data), extensions: set(future_extensions) }); export const stealth_confirmation = new Serializer("stealth_confirmation", { one_time_key: public_key, to: optional(public_key), encrypted_memo: bytes() }); export const blind_output = new Serializer("blind_output", { commitment: bytes(33), range_proof: bytes(), owner: authority, stealth_memo: optional(stealth_confirmation) }); export const transfer_to_blind = new Serializer("transfer_to_blind", { fee: asset, amount: asset, from: protocol_id_type("account"), blinding_factor: bytes(32), outputs: array(blind_output) }); export const blind_input = new Serializer("blind_input", { commitment: bytes(33), owner: authority }); export const blind_transfer = new Serializer("blind_transfer", { fee: asset, inputs: array(blind_input), outputs: array(blind_output) }); export const transfer_from_blind = new Serializer("transfer_from_blind", { fee: asset, amount: asset, to: protocol_id_type("account"), blinding_factor: bytes(32), inputs: array(blind_input) }); export const asset_settle_cancel = new Serializer("asset_settle_cancel", { fee: asset, settlement: protocol_id_type("force_settlement"), account: protocol_id_type("account"), amount: asset, extensions: set(future_extensions) }); export const asset_claim_fees = new Serializer("asset_claim_fees", { fee: asset, issuer: protocol_id_type("account"), amount_to_claim: asset, extensions: set(future_extensions) }); /////////// export const exchange_check_amount = new Serializer("exchange_check_amount", { asset_id: protocol_id_type("asset"), floor: int64, ceil: int64 }); export const exchange_check_once_amount = new Serializer( "exchange_check_once_amount", { asset_id: protocol_id_type("asset"), floor: int64, ceil: int64 } ); export const exchange_check_divisible = new Serializer( "exchange_check_divisible", { divisor: asset } ); export const exchange_vesting_policy_wrapper = new Serializer( "exchange_vesting_policy_wrapper", { policy: vesting_policy_initializer } ); const eto_extensions = static_variant([ exchange_check_amount, exchange_check_once_amount, exchange_check_divisible, exchange_vesting_policy_wrapper ]); export const exchange_options = new Serializer("exchange_options", { rate: price, owner_permissions: uint32, flags: uint32, whitelist_authorities: set(protocol_id_type("account")), blacklist_authorities: set(protocol_id_type("account")), extensions: set(eto_extensions), description: string }); export const exchange_participate = new Serializer("exchange_participate", { fee: asset, payer: protocol_id_type("account"), exchange_to_pay: protocol_id_type("exchange"), amount: asset, extensions: set(eto_extensions) }); export const exchange_create = new Serializer("exchange_create", { fee: asset, name: string, owner: protocol_id_type("account"), options: exchange_options, extensions: set(eto_extensions) }); export const exchange_update = new Serializer("exchange_update", { fee: asset, owner: protocol_id_type("account"), exchange_to_update: protocol_id_type("exchange"), new_owner: optional(protocol_id_type("account")), new_options: exchange_options, extensions: set(eto_extensions) }); export const exchange_withdraw = new Serializer("exchange_withdraw", { fee: asset, owner: protocol_id_type("account"), exchange_to_withdraw: protocol_id_type("exchange"), amount: asset, extensions: set(eto_extensions) }); export const exchange_deposit = new Serializer("exchange_deposit", { fee: asset, owner: protocol_id_type("account"), exchange_to_deposit: protocol_id_type("exchange"), amount: asset, extensions: set(eto_extensions) }); export const exchange_remove = new Serializer("exchange_remove", { fee: asset, owner: protocol_id_type("account"), exchange_to_remove: protocol_id_type("exchange"), amount: asset, extensions: set(eto_extensions) }); export const exchange_fill = new Serializer("exchange_fill", { fee: asset, payer: protocol_id_type("account"), exchange: protocol_id_type("exchange"), pay: asset, receive: asset, extensions: set(eto_extensions) }); //////// /** HTLC */ const htlc_hash = static_variant([bytes(20), bytes(20), bytes(32)]); export const htlc_create = new Serializer("htlc_create", { fee: asset, from: protocol_id_type("account"), to: protocol_id_type("account"), amount: asset, preimage_hash: htlc_hash, preimage_size: uint16, claim_period_seconds: uint32, extensions: set(future_extensions) }); export const htlc_redeem = new Serializer("htlc_redeem", { fee: asset, htlc_id: protocol_id_type("htlc"), redeemer: protocol_id_type("account"), preimage: bytes(), extensions: set(future_extensions) }); export const htlc_redeemed = new Serializer("htlc_redeemed", { fee: asset, htlc_id: protocol_id_type("htlc"), redeemer: protocol_id_type("account"), from: protocol_id_type("account"), to: protocol_id_type("account"), extensions: set(future_extensions) }); export const htlc_extend = new Serializer("htlc_extend", { fee: asset, htlc_id: protocol_id_type("htlc"), update_issuer: protocol_id_type("account"), seconds_to_add: uint32, extensions: set(future_extensions) }); export const htlc_refund = new Serializer("htlc_refund", { fee: asset, htlc_id: protocol_id_type("htlc"), to: protocol_id_type("account") }); operation.st_operations = [ transfer, // 0 limit_order_create, // 1 limit_order_cancel, // 2 call_order_update, // 3 fill_order, // 4 account_create, // 5 account_update, // 6 account_whitelist, // 7 account_upgrade, // 8 account_transfer, asset_create, asset_update, asset_update_bitasset, asset_update_feed_producers, asset_issue, asset_reserve, // 15 asset_fund_fee_pool, asset_settle, asset_global_settle, asset_publish_feed, witness_create, // 20 witness_update, proposal_create, proposal_update, proposal_delete, withdraw_permission_create, // 25 withdraw_permission_update, withdraw_permission_claim, withdraw_permission_delete, committee_member_create, committee_member_update, // 30 committee_member_update_global_parameters, vesting_balance_create, vesting_balance_withdraw, worker_create, custom, // 35 assert, balance_claim, override_transfer, transfer_to_blind, blind_transfer, // 40 transfer_from_blind, asset_settle_cancel, asset_claim_fees, asset_settle_cancel, initiate_crowdfund, // 45 participate_crowdfund, withdraw_crowdfund, withdraw_crowdfund, withdraw_crowdfund, // withdraw_crowdfund, // 50 withdraw_crowdfund, // 51 withdraw_crowdfund, // 52 withdraw_crowdfund, // 53 withdraw_crowdfund, // 54 withdraw_crowdfund, // 55 withdraw_crowdfund, // 56 withdraw_crowdfund, // 57 exchange_create, // 58, exchange_update, // 59 exchange_withdraw, // 60 exchange_deposit, // 61 exchange_remove, // 62 exchange_participate, // 63, exchange_fill, htlc_create, // 65 htlc_redeem, htlc_redeemed, htlc_extend, htlc_refund ]; export const transaction = new Serializer("transaction", { ref_block_num: uint16, ref_block_prefix: uint32, expiration: time_point_sec, operations: array(operation), extensions: set(future_extensions) }); export const signed_transaction = new Serializer("signed_transaction", { ref_block_num: uint16, ref_block_prefix: uint32, expiration: time_point_sec, operations: array(operation), extensions: set(future_extensions), signatures: array(bytes(65)) }); //# ------------------------------- //# Generated code end //# ------------------------------- // Custom Types export const stealth_memo_data = new Serializer("stealth_memo_data", { from: optional(public_key), amount: asset, blinding_factor: bytes(32), commitment: bytes(33), check: uint32 }); export const fund_query = new Serializer("fund_query", { accountName: string, asset: optional(string), fundType: optional(string), size: optional(uint32), offset: optional(uint32), expiration: time_point_sec }); // var stealth_confirmation = new Serializer( // "stealth_confirmation", { // one_time_key: public_key, // to: optional( public_key ), // encrypted_memo: stealth_memo_data // }) <file_sep>import Apis from "./ApiInstances"; import ChainWebSocket from "./ChainWebSocket"; class Manager { constructor({ url, urls }) { this.url = url; this.urls = urls.filter(a => a !== url); } static close() { return Apis.close(); } logFailure(url, err) { console.error( "Skipping to next full node API server. Error: " + (err ? JSON.stringify(err.message) : "") ); } connect(connect = true, url = this.url, enableCrypto = false) { return new Promise((resolve, reject) => { Apis.instance(url, connect, undefined, enableCrypto) .init_promise.then(res => { this.url = url; resolve(res); }) .catch(err => { Apis.close().then(() => { reject( new Error( "Unable to connect to node: " + url + ", error:" + JSON.stringify(err && err.message) ) ); }); }); }); } connectWithFallback( connect = true, url = this.url, index = 0, resolve = null, reject = null, enableCrypto ) { if (reject && index > this.urls.length) return reject( new Error( "Tried " + index + " connections, none of which worked: " + JSON.stringify(this.urls.concat(this.url)) ) ); const fallback = (err, resolve, reject) => { this.logFailure(url, err); return this.connectWithFallback( connect, this.urls[index], index + 1, resolve, reject, enableCrypto ); }; if (resolve && reject) { return this.connect( connect, url, enableCrypto ) .then(resolve) .catch(err => { fallback(err, resolve, reject); }); } else { return new Promise((resolve, reject) => { this.connect( connect, undefined, enableCrypto ) .then(resolve) .catch(err => { fallback(err, resolve, reject); }); }); } } checkConnections( rpc_user = "", rpc_password = "", resolve, reject, race = false ) { let connectionStartTimes = {}; const checkFunction = (resolve, reject) => { let fullList = this.urls.concat(this.url); let connectionPromises = []; fullList.forEach(url => { let conn = new ChainWebSocket(url, () => {}); connectionStartTimes[url] = new Date().getTime(); connectionPromises.push(() => { return conn .login(rpc_user, rpc_password) .then(data => { let result = { [url]: new Date().getTime() - connectionStartTimes[url] }; conn.close(); return result; }) .catch(err => { if (url === this.url) { this.url = this.urls[0]; } else { this.urls = this.urls.filter(a => a !== url); } return conn.close().then(() => null); }); }); }); let promises = connectionPromises.map(a => a()); let doPromise = race ? () => Promise.race(promises).then(res => [res]) : () => Promise.all(promises); doPromise() .then(res => { resolve( res.filter(a => !!a).reduce((f, a) => { let key = Object.keys(a)[0]; f[key] = a[key]; return f; }, {}) ); }) .catch(e => { console.error("CheckConnectionError: ", e); return this.checkConnections(rpc_user, rpc_password, resolve, reject); }); }; if (resolve && reject) { checkFunction(resolve, reject); } else { return new Promise(checkFunction); } } } export default Manager; <file_sep>import { Set } from "immutable"; import alt from "alt-instance"; import { debugGen } from "utils//Utils"; import { AbstractStore } from "./AbstractStore"; import VolumeActions, { PriceSetByYuan } from "actions/VolumeActions"; interface VolumnState { totalVolumn: number; priceState: PriceSetByYuan; } class VolumnStore extends AbstractStore<VolumnState> { state = { details: [], sum: 0, totalVolumn: 0, priceState: {} }; constructor(props) { super(); this.bindListeners({ handleVolUpdate: VolumeActions.updateVol, handlePriceUpdate: VolumeActions.updatePriceData }); } handleVolUpdate(volState) { if (volState) { this.setState(volState); } } handlePriceUpdate(priceState) { if ("ETH" in priceState) { this.setState({ priceState }); } } handleAddMarket() {} handleRemoveMarket() {} handleMarketUpdate() {} } const StoreWrapper = alt.createStore(VolumnStore, "VolumnStore") as VolumnStore; export { StoreWrapper as VolumnStore }; export default StoreWrapper; <file_sep>let _this; const ADDRESS_PREFIX = "CYB"; // 修改此处会修改包括各种key生成在内的前缀; const PREFIX_OF_CHAIN = { "<KEY>": "CYB", "59e27e3883fc5ec4dbff68855f83961303157df9a64a3ecf49982affd8e8d490": "CYB" }; const Network = class { constructor(chain_id, core_asset) { this.chain_id = chain_id; this.core_asset = core_asset; } get address_prefix() { let _global = global || window || {}; return ( (_global && _global.localStorage && _global.localStorage.getItem(`PREFIX_${this.chain_id}`)) || PREFIX_OF_CHAIN[this.chain_id] || this.core_asset ); } }; let ecc_config = { address_prefix: ADDRESS_PREFIX }; _this = { core_asset: "CORE", address_prefix: ADDRESS_PREFIX, expire_in_secs: 30, expire_in_secs_proposal: 24 * 60 * 60, review_in_secs_committee: 24 * 60 * 60, networks: { Cybex: new Network( "<KEY>", "CYB" ), CybexOpen: new Network( "59e27e3883fc5ec4dbff68855f83961303157df9a64a3ecf49982affd8e8d490", "CYB" ) }, /** Set a few properties for known chain IDs. */ setChainId: function(chain_id) { let i, len, network, network_name, ref; ref = Object.keys(_this.networks); for (i = 0, len = ref.length; i < len; i++) { network_name = ref[i]; network = _this.networks[network_name]; if (network.chain_id === chain_id) { _this.network_name = network_name; if (network.address_prefix) { _this.address_prefix = network.address_prefix; ecc_config.address_prefix = network.address_prefix; } // console.log("INFO Configured for", network_name, ":", network.address_prefix, "\n"); return { network_name: network_name, network: network }; } } if (!_this.network_name) { console.log("Unknown chain id (this may be a testnet)", chain_id); } }, reset: function() { _this.core_asset = "CORE"; _this.address_prefix = ADDRESS_PREFIX; ecc_config.address_prefix = ADDRESS_PREFIX; _this.expire_in_secs = 30; _this.expire_in_secs_proposal = 24 * 60 * 60; console.log("Chain config reset"); }, setProposalExpire: function(time) { if (!time) return; return (_this.expire_in_secs_proposal = time); }, setPrefix: function(prefix = ADDRESS_PREFIX) { _this.address_prefix = prefix; ecc_config.address_prefix = prefix; } }; export default _this; <file_sep>export const BaseColors = { // Colors $colorWhite: "#ffffff", $colorWhiteOp8: "rgba(255, 255, 255, 0.8)", $colorWhiteOp3: "rgba(255, 255, 255, 0.3)", $colorOrange: "#ff9143", $colorOrangeLight: "#ffc478", $colorCrimson: "#d2323e", $colorGrass: "#6dbb49", $colorGrassLight: "#A9E06E", $colorBlue: "#2e5be2", $colorLight: "#f7f8fa", $colorGrey: "#78819a", $colorGreyLightWhite: "rgba(120, 129, 154, 0.3)", $colorGreyLight: "rgba(216, 216, 216, 0.3)", $colorDark: "#171d2a", $colorMask: "rgba(23, 30, 42, 0.8)", // Sub Colors $colorRosset: "#c87b41", $colorBronze: "#c86443", $colorFlame: "#d24632", $colorFlameLight: "#d96250", // $colorWarn: "#c12121", $colorMahogany: "#502d2d", $colorBlush: "#ff787c", // $colorCyan: "#2b756c", $colorPine: "#2d4134", // $colorAegean: "#356da4", $colorCobalt: "#2e51b0", $colorLapis: "#3d5bb2", $colorpurple: "#7b44ae", $colorporcelain: "#eff1f4", // $colorLilac: "#8f9ab9", $colorFossil: "#707481", // $colorLead: "#1b2230", $colorAnchor: "#212939", $colorIndependence: "#293246", $colorNoir: "#111621" // }; export const GridentColors = { $colorGradientFoilex: "linear-gradient(-135deg, #e7ac5f, #e76536)", $colorGradientGoldex: "linear-gradient(-131deg, #ffc478, #ff9143)", $colorGradientFlame: `linear-gradient(90deg, ${ BaseColors.$colorFlameLight }, ${BaseColors.$colorFlame})`, $colorGradientGrass: `linear-gradient(90deg, ${ BaseColors.$colorGrassLight }, ${BaseColors.$colorGrass})`, $colorGradientSilvex: "linear-gradient(to right, rgba(120, 129, 154, 0.5), #78819a)", $colorGradientGreyex: "linear-gradient(48deg,rgba(120, 129, 154, 0.5),rgba(120, 129, 154, 1))" }; export const Colors = { ...BaseColors, ...GridentColors }; export enum CommonType { Primary, Secondary } export default Colors; <file_sep>import { FetchChain } from "cybexjs"; import { Price, Asset } from "common/MarketClasses"; import utils from "common/utils"; function estimateFee(type, options = null) { return new Promise((res, rej) => { FetchChain("getObject", "2.0.0").then(obj => { res(utils.estimateFee(type, options, obj)); }).catch(rej); }); } function checkFeePool({assetID, type = "transfer", options = null} = {}) { return new Promise(res => { if (assetID === "1.3.0") { res(true); } else { Promise.all([ estimateFee(type, options), FetchChain("getAsset", assetID) ]) .then(result => { const [fee, feeAsset] = result; res(parseInt(feeAsset.getIn(["dynamic", "fee_pool"]), 10) >= fee); }); } }); } function checkFeePayment({accountID, feeID = "1.3.0", type = "transfer", options = null} = {}) { return new Promise((res, rej) => { Promise.all([ estimateFee(type, options), checkFeePool({assetID: feeID, type, options}), FetchChain("getAccount", accountID), FetchChain("getAsset", "1.3.0"), feeID !== "1.3.0" ? FetchChain("getAsset", feeID) : null ]) .then(result => { let [coreFee, hasPoolBalance, account, coreAsset, feeAsset] = result; if (feeID === "1.3.0") feeAsset = coreAsset; FetchChain("getObject", account.getIn(["balances", feeID])).then(balance => { let hasBalance = false; let fee = new Asset({amount: coreFee}); /* ** If the fee is to be paid in a non-core asset, check the fee ** pool and convert the amount using the CER */ if (feeID !== "1.3.0") { // Check the fee pool of the asset // if (parseInt(feeAsset.getIn(["dynamic", "fee_pool"]), 10) >= coreFee) hasPoolBalance = true; // Convert the amount using the CER let cer = feeAsset.getIn(["options", "core_exchange_rate"]); let b = cer.get("base").toJS(); b.precision = b.asset_id === feeID ? feeAsset.get("precision") : coreAsset.get("precision"); let base = new Asset(b); let q = cer.get("quote").toJS(); q.precision = q.asset_id === feeID ? feeAsset.get("precision") : coreAsset.get("precision"); let quote = new Asset(q); let price = new Price({base, quote}); fee = fee.times(price, true); } else { hasPoolBalance = true; // Core asset needs no pool balance, set to true for logic } if (balance.get("balance") >= fee.getAmount()) hasBalance = true; res({fee, hasBalance, hasPoolBalance}); }); }).catch(rej); }); } export { estimateFee, checkFeePool, checkFeePayment }; <file_sep>import { Store } from "alt-instance"; export class AbstractStore<S> implements Store<S> { state: S; listen(stateListener): void; unlisten(stateListener): void; getState(): S; setState(state: any): S; bindListeners(listenerBinder: { [method: string]: Function }): void; exportPublicMethods; _export = (...methods) => { let publicMethods = {}; methods.forEach(method => { this[method] = this[method].bind(this); publicMethods[method] = this[method]; }); this.exportPublicMethods(publicMethods); }; } export default AbstractStore; <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import SettingsStore from "stores/SettingsStore"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; import { NotificationActions } from "actions//NotificationActions"; import { ops, PrivateKey, Signature, TransactionBuilder } from "cybexjs"; import { Map } from "immutable"; import { CustomTx } from "CustomTx"; import { LockC } from "services/lockC"; import WalletUnlockActions from "actions/WalletUnlockActions"; import { EDGE_LOCK } from "api/apiConfig"; import TransactionConfirmActions from "actions/TransactionConfirmActions"; import { Htlc } from "../services/htlc"; import { calcAmount } from "../utils/Asset"; import { HASHED_PREIMAGE } from "./EtoActions"; const debug = debugGen("LockCActions"); export const DEPOSIT_MODAL_ID = "DEPOSIT_MODAL_ID"; export const WITHDRAW_MODAL_ID = "WITHDRAW_MODAL_ID"; export const HASHED_PREIMAGE_FOR_LOCK_CYB = "b5fc0b94782e68a2982fb76f63a915ff0a899c2dbf032e2a2ff1696a5696e741"; export const ORIGIN_TIME = "2019-07-31T16:00:00Z"; // export const DEST_TIME = "2019-07-31T16:00:00Z"; export const DEST_TIME = "2020-07-13T03:59:00Z"; // export const RECEIVER = "ldw-format"; export const RECEIVER = "ksma-airdrop"; const headers = new Headers(); headers.append("Content-Type", "application/json"); const pickKeys = (keys: string[], count = 1) => { let res: any[] = []; for (let key of keys) { let privKey = WalletDb.getPrivateKey(key); if (privKey) { res.push(privKey); if (res.length >= count) { break; } } } return res; }; const ProjectServer = __DEV__ ? "https://EDGEapi.cybex.io/api" : "https://EDGEapi.cybex.io/api"; const fetchUnwrap = <T = any>(url: string) => fetch(url) .then(res => res.json()) .then(res => { if (res.code === 0) { return res.result as T; } else { throw new Error(res.code); } }); type AccountMap = Map<string, any>; class LockCActions { /// LockC 锁仓查询部分 queryInfo(account: AccountMap, onReject?) { this.addLoading(); return dispatch => { Promise.resolve({ accountName: account.get("name"), accountID: account.get("id"), basic: {} }) .then(res => Apis.instance() .db_api() .exec("get_htlc_by_from", [account.get("id"), "1.21.0", 100]) .then(records => ({ ...res, records: records.filter( (record: Htlc.HtlcRecord) => record.conditions.hash_lock.preimage_hash[1] === HASHED_PREIMAGE_FOR_LOCK_CYB || record.conditions.hash_lock.preimage_hash[1] === HASHED_PREIMAGE ) })) ) .then(res => new LockC.LockCInfo(res)) .then(info => { dispatch(info); this.removeLoading(); return info; }) .catch(err => { if (onReject) { onReject(err); } console.error(err); return new LockC.LockCInfo(); }); }; } applyLock(value: number, account: AccountMap, onResolve?) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS(); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } return { privKey, pubKey: privKey.toPublicKey().toPublicKeyString() }; }) .then(async ({ privKey, pubKey }) => { let tx = new TransactionBuilder(); let destAccount = await Apis.instance() .db_api() .exec("get_account_by_name", [RECEIVER]); let htlc = new Htlc.HtlcCreateByHashedPreimage( account.get("id"), destAccount.id, { asset_id: "1.3.0", amount: calcAmount(value.toString(), 5) }, Htlc.HashAlgo.Sha256, 45, HASHED_PREIMAGE_FOR_LOCK_CYB, moment(DEST_TIME).diff(moment(), "seconds") ); tx.add_type_operation("htlc_create", htlc); await tx.set_required_fees(); await tx.finalize(); await tx.add_signer(privKey); await tx.sign(); return new Promise((resolve, reject) => TransactionConfirmActions.confirm(tx, resolve, reject, null) ); }) .then(tx => { console.debug("TX: ", tx); dispatch(tx); if (onResolve) { onResolve(); } this.removeLoading(); return tx; }) .catch(err => { console.error(err); this.removeLoading(); }); }; } // 其他 addLoading() { return 1; } removeLoading() { return 1; } } const LockCActionsWrapped: LockCActions = alt.createActions(LockCActions); export { LockCActionsWrapped as LockCActions }; export default LockCActionsWrapped; <file_sep>import { Set } from "immutable"; import alt, { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; import { RteActions } from "actions/RteActions"; import { AbstractStore } from "./AbstractStore"; import { Map } from "immutable"; type RteMsg = { type: string; sym: string }; type Ticker = { px: string; qty: string; cymQty: string } & RteMsg; type OrderBook = {}; type RteState = { [channel: string]: Map<string, Ticker | OrderBook> }; class RteStore extends AbstractStore<RteState> { constructor() { super(); console.debug("RTE Store Constructor"); this.state = { ticker: Map(), depth: Map() } as any; this.bindListeners({ onUpdateMarket: RteActions.onMarketMsg }); console.debug("RTE Store Constructor Done"); } onUpdateMarket({ channel, market, data }) { if(this.state[channel]){ let n = this.state[channel].set(market, data); this.setState({ [channel]: n }); } } } const StoreWrapper: Store<RteState> = alt.createStore(RteStore, "RteStore"); export { StoreWrapper as RteStore }; export default StoreWrapper; <file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var InstallationDocs = React.createClass({ render: function() { return ( <div className="grid-content"> <h4 className="subheader"> React Foundation Apps is a react port of Foundation Apps </h4> <Highlight innerHTML={true} languages={["xml", "javascript", "bash"]}> {require("./install.md")} </Highlight> </div> ); } }); module.exports = InstallationDocs; <file_sep>export class CustomTx { signer = ""; constructor(public op: any) {} addSigner(signer) { this.signer = signer; } } <file_sep>import * as PropTypes from "prop-types"; import * as React from "react"; var _createClass = (function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x4, _x5, _x6) { var _again = true; _function: while (_again) { var object = _x4, property = _x5, receiver = _x6; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x4 = parent; _x5 = property; _x6 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError( "Super expression must either be null or a function, not " + typeof superClass ); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : (subClass.__proto__ = superClass); } var _react = require("react"); var _react2 = _interopRequireDefault(_react); var Connect = (function(_React$Component) { _inherits(Connect, _React$Component); function Connect() { _classCallCheck(this, Connect); _get(Object.getPrototypeOf(Connect.prototype), "constructor", this).apply( this, arguments ); } _createClass( Connect, [ { key: "setConnections", value: function setConnections(props, context) { var config = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; this.flux = props.flux || context.flux; this.stores = this.flux ? this.flux.stores : {}; this.config = typeof config === "function" ? config(this.stores, this.flux) : config; } }, { key: "componentWillMount", value: function componentWillMount() { if (this.config.willMount) this.call(this.config.willMount); } }, { key: "componentDidMount", value: function componentDidMount() { var _this = this; var stores = this.config.listenTo ? this.call(this.config.listenTo) : []; this.storeListeners = stores.map(function(store) { return store.listen(function() { return _this.forceUpdate(); }); }); if (this.config.didMount) this.call(this.config.didMount); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.storeListeners.forEach(function(unlisten) { return unlisten(); }); if (this.config.willUnmount) this.call(this.config.willUnmount); } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (this.config.willReceiveProps) this.call(this.config.willReceiveProps); } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps) { return this.config.shouldComponentUpdate ? this.call(this.config.shouldComponentUpdate, nextProps) : true; } }, { key: "getNextProps", value: function getNextProps() { var nextProps = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; return this.config.getProps ? this.call(this.config.getProps, nextProps) : nextProps; } }, { key: "call", value: function call(f) { var props = arguments.length <= 1 || arguments[1] === undefined ? this.props : arguments[1]; return f(props, this.context, this.flux); } }, { key: "render", value: function render() { throw new Error("Render should be defined in your own class"); } } ], [ { key: "contextTypes", value: { flux: PropTypes.object }, enumerable: true } ] ); return Connect; })(_react2["default"].Component); export default Connect; <file_sep>var React = require("react"); var Router = require("react-router-dom"); var Link = Router.Link; var Route = Router.Route; var DefaultRoute = Router.DefaultRoute; var RouteHandler = Router.RouteHandler; var Offcanvas = require("../lib/offcanvas"); var Trigger = require("../lib/trigger"); var Panel = require("../lib/panel"); var Docs = React.createClass({ render: function() { return ( <div className="wrapper"> <Offcanvas id="top-offcanvas" position="top"> <Trigger close="top-offcanvas"> <a className="close-button">&times;</a> </Trigger> <br /> <p>This is Top offcanvas menu</p> </Offcanvas> <Offcanvas id="right-offcanvas" position="right"> <Trigger close="right-offcanvas"> <a className="close-button">&times;</a> </Trigger> <br /> <p>This is Right offcanvas menu</p> </Offcanvas> <Offcanvas id="bottom-offcanvas" position="bottom"> <Trigger close="bottom-offcanvas"> <a className="close-button">&times;</a> </Trigger> <br /> <p>This is Bottom offcanvas menu</p> </Offcanvas> <Offcanvas id="left-offcanvas"> <Trigger close="left-offcanvas"> <a className="close-button">&times;</a> </Trigger> <br /> <p>This is Left offcanvas menu</p> </Offcanvas> <div className="vertical grid-frame"> <div className="title-bar primary"> <span className="title">React Foundation Apps</span> </div> <div className="grid-block"> <Panel id="sidebar" className="medium-3 large-2 medium-grid-block sidebar vertical" > <div className="grid-content collapse"> <Trigger close="sidebar"> <a className="close-button hide-for-medium">&times;</a> </Trigger> <section> <ul className="menu-bar vertical"> <li> <Link to="install">Installation &amp; Usage</Link> </li> <li> <Link to="trigger">Trigger</Link> </li> <li> <Link to="modal">Modal</Link> </li> <li> <Link to="panel">Panel</Link> </li> <li> <Link to="offcanvas">Off-canvas Menu</Link> </li> <li> <Link to="notification">Notification</Link> </li> <li> <Link to="action-sheet">Action Sheet</Link> </li> <li> <Link to="tabs">Tabs</Link> </li> <li> <Link to="iconic">Iconic</Link> </li> <li> <Link to="accordion">Accordion</Link> </li> <li> <Link to="interchange">Interchange</Link> </li> <li> <Link to="popup">Popup</Link> </li> </ul> </section> </div> </Panel> <div className="medium-9 large-10 grid-content"> <div className="grid-container main-docs-section"> <Trigger toggle="sidebar"> <a className="small secondary expand button hide-for-medium"> Show Components </a> </Trigger> <RouteHandler /> </div> </div> </div> </div> </div> ); } }); module.exports = Docs; <file_sep>[Workers](introduction/workers) are a unique concept to Cybex. They are proposals to provide services in return for a salary from the blockchain itself. A proposal should include a link to a website or forum thread that explains the purpose of the proposal, a collection of proposals can be found here: [Cybextalk - Stakeholder Proposals Board](https://Cybextalk.org/index.php/board,75.0.html). <file_sep>## [v2.0.0] > Nov 1, 2016 Please see `/upgrade-guides/v2.0.0.md` [v2.0.0]: https://github.com/reactjs/react-router/compare/v0.17.6...v2.0.0 <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import SettingsStore from "stores/SettingsStore"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; import { NotificationActions } from "actions//NotificationActions"; import { ops, PrivateKey, Signature, TransactionBuilder } from "cybexjs"; import { Map } from "immutable"; import { CustomTx } from "CustomTx"; import { Eto, etoTx, EtoProject } from "services/eto"; import WalletUnlockActions from "actions/WalletUnlockActions"; import { ETO_LOCK } from "api/apiConfig"; import TransactionConfirmActions from "actions/TransactionConfirmActions"; import { EtoMock } from "../components/Eto/mock"; import { Htlc } from "../services/htlc"; import { calcAmount } from "../utils/Asset"; const debug = debugGen("EtoActions"); export const DEPOSIT_MODAL_ID = "DEPOSIT_MODAL_ID"; export const WITHDRAW_MODAL_ID = "WITHDRAW_MODAL_ID"; export const HASHED_PREIMAGE = "da22691374e5427715038e80344fa55f258c2a45b42cafbb088cd8d455c9e059"; const headers = new Headers(); headers.append("Content-Type", "application/json"); const pickKeys = (keys: string[], count = 1) => { let res: any[] = []; for (let key of keys) { let privKey = WalletDb.getPrivateKey(key); if (privKey) { res.push(privKey); if (res.length >= count) { break; } } } return res; }; const DestTimeOfLock = "2019-07-29T00:00:00Z"; const EndTimeOfLock = "2019-07-15T10:20:00Z"; const ProjectServer = __DEV__ ? "https://etoapi.cybex.io/api" : "https://etoapi.cybex.io/api"; const ProjectUrls = { banner() { return `${ProjectServer}/cybex/projects/banner`; }, projects(limit = 10) { return `${ProjectServer}/cybex/projects?limit=${limit}`; }, projectDetail(projectID: string) { return `${ProjectServer}/cybex/project/detail?project=${projectID}`; }, projectDetailUpdate(projectID: string) { return `${ProjectServer}/cybex/project/current?project=${projectID}`; }, userState(projectID: string, accountName: string) { return `${ProjectServer}/cybex/user/check_status?cybex_name=${accountName}&project=${projectID}`; }, user(projectID: string, accountName: string) { return `${ProjectServer}/cybex/user/current?cybex_name=${accountName}&project=${projectID}`; }, userTradeList(accountName: string, page = 1, limit = 1) { return `${ProjectServer}/cybex/trade/list?cybex_name=${accountName}&page=${page}&limit=${limit}`; } }; const fetchUnwrap = <T = any>(url: string) => fetch(url) .then(res => res.json()) .then(res => { if (res.code === 0) { return res.result as T; } else { throw new Error(res.code); } }); type AccountMap = Map<string, any>; class EtoActions { /// Eto 锁仓查询部分 queryInfo(account: AccountMap, onReject?) { this.addLoading(); return dispatch => { this.signTx(0, "query", account) .then(tx => fetch( `${ETO_LOCK}api/v1/info/${account.get("name")}?expiration=${ tx.expiration }&signer=${tx.signer}` ) .then(res => res.json()) .then(res => Apis.instance() .db_api() .exec("get_htlc_by_from", [account.get("id"), "1.21.0", 100]) .then(records => ({ ...res, records: records.filter( (record: Htlc.HtlcRecord) => record.conditions.hash_lock.preimage_hash[1] === HASHED_PREIMAGE ) })) ) .then(res => new Eto.EtoInfo(res)) .then(info => { dispatch(info); this.removeLoading(); return info; }) .catch(err => { if (onReject) { onReject(err); } console.error(err); return new Eto.EtoInfo(); }) ) .catch(err => { if (onReject) { onReject(err); } console.error(err); return new Eto.EtoInfo(); }); }; } queryRank(onReject?) { this.addLoading(); return dispatch => { fetch(`${ETO_LOCK}api/v1/rank`) .then(res => res.json()) .then(rank => { dispatch(rank); this.removeLoading(); }) .catch(err => { this.removeLoading(); if (onReject) { onReject(err); } console.error(err); }); }; } applyLock(value: number, account: AccountMap, onResolve?) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { console.debug("Account: ", account); let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS(); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } return { privKey, pubKey: privKey.toPublicKey().toPublicKeyString() }; }) .then(async ({ privKey, pubKey }) => { let tx = new TransactionBuilder(); let htlc = new Htlc.HtlcCreateByHashedPreimage( account.get("id"), account.get("id"), { asset_id: "1.3.0", amount: calcAmount(value.toString(), 5) }, Htlc.HashAlgo.Sha256, 45, HASHED_PREIMAGE, moment(DestTimeOfLock).diff(moment(), "seconds") ); tx.add_type_operation("htlc_create", htlc); await tx.set_required_fees(); await tx.finalize(); await tx.add_signer(privKey); await tx.sign(); return new Promise((resolve, reject) => TransactionConfirmActions.confirm(tx, resolve, reject, null) ); }) .then(tx => { console.debug("TX: ", tx); dispatch(tx); if (onResolve) { onResolve(); } this.removeLoading(); return tx; }) .catch(err => { console.error(err); this.removeLoading(); }); }; } putBasic(basic: Eto.Info, account: AccountMap, onResolve?) { this.addLoading(); return dispatch => { this.signTx(1, basic, account) .then(tx => fetch( `${ETO_LOCK}api/v1/info/${account.get("name")}/${Eto.Fields.basic}`, { headers, method: "PUT", body: JSON.stringify(tx) } ) .then(res => res.json()) .then(res => new Eto.EtoInfo(res)) ) .then(info => { dispatch(info); this.removeLoading(); if (onResolve) { onResolve(); } return info; }) .catch(err => { console.error(err); return; }); }; } putSurvey(survey: Eto.Survey, account: AccountMap) { this.addLoading(); return dispatch => { this.signTx(2, survey, account) .then(tx => fetch( `${ETO_LOCK}api/v1/info/${account.get("name")}/${ Eto.Fields.survey }`, { headers, method: "PUT", body: JSON.stringify(tx) } ) .then(res => res.json()) .then(res => new Eto.EtoInfo(res)) ) .then(info => { dispatch(info); this.removeLoading(); return info; }) .catch(err => { console.error(err); return new Eto.EtoInfo(); }); }; } putToken(token: Eto.Token, account: AccountMap, onResolve?) { this.addLoading(); return dispatch => { this.signTx(3, token, account) .then(tx => fetch( `${ETO_LOCK}api/v1/info/${account.get("name")}/${Eto.Fields.token}`, { headers, method: "PUT", body: JSON.stringify(tx) } ) .then(res => res.json()) .then(res => new Eto.EtoInfo(res)) ) .then(info => { dispatch({ info, onResolve }); // setTimeout(() => { // if (onResolve) { // onResolve(); // } // }, 1000); this.removeLoading(); return info; }) .catch(err => { this.removeLoading(); console.error(err); return; }); }; } setApplyDone() { return true; } /** * 注册一个查询签名 * * @param {Map<string, any>} account * @memberof EtoActions */ async signTx(opOrder: Eto.OpsOrder, op: Eto.Ops, account: AccountMap) { // await WalletUnlockActions.unlock().catch(e => console.debug("Unlock Error")); await WalletUnlockActions.unlock(); debug("[LoginEtoQuery]", account); debug("[LoginEtoQuery]", SettingsStore.getSetting("walletLockTimeout")); const tx: Eto.Request = { op: [opOrder, op], expiration: Date.now() + SettingsStore.getSetting("walletLockTimeout") * 1000 }; // Pick approps key let weight_threshold = account.getIn(["active", "weight_threshold"]); let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() .concat( account .getIn(["owner", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() ); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } debug( "[LoginEtoQuery privKey]", account.getIn(["options", "memo_key"]), privKey ); let buffer = etoTx.toBuffer(tx); let signedHex = Signature.signBuffer(buffer, privKey).toHex(); debug("[LoginEtoQuery Signed]", signedHex); (tx as Eto.RequestWithSigner).signer = signedHex; return tx as Eto.RequestWithSigner; } // 认购项目部分 updateBanner() { return dispatch => fetchUnwrap<EtoProject.Banner[]>(ProjectUrls.banner()).then(dispatch); // return dispatch => Promise.resolve(EtoMock.banner).then(dispatch); } updateProjectList() { // return dispatch => Promise.resolve(EtoMock.details).then(dispatch); return dispatch => fetchUnwrap<EtoProject.ProjectDetail[]>(ProjectUrls.projects()).then( dispatch ); } loadProjectDetail(id: string) { // return dispatch => Promise.resolve(EtoMock.detail).then(dispatch); return dispatch => fetchUnwrap<EtoProject.ProjectDetail>(ProjectUrls.projectDetail(id)).then( dispatch ); } updateProject(id: string) { // return dispatch => // Promise.resolve(EtoMock.current) // .then(p => ({ ...p, id })) // .then(dispatch); return dispatch => fetchUnwrap<EtoProject.ProjectDetail>(ProjectUrls.projectDetailUpdate(id)) .then(p => ({ ...p, id })) .then(dispatch); } updateProjectByUser(id: string, accountName: string) { // return dispatch => // Promise.resolve(EtoMock.current) // .then(p => ({ ...p, id })) // .then(dispatch); return dispatch => fetchUnwrap<EtoProject.ProjectDetail>(ProjectUrls.user(id, accountName)) .then(p => ({ ...p, id })) .then(dispatch); } queryUserIn(id: string, accountName: string) { // return dispatch => // Promise.resolve(EtoMock.current) // .then(p => ({ ...p, id })) // .then(dispatch); return dispatch => fetchUnwrap<EtoProject.ProjectDetail>( ProjectUrls.userState(id, accountName) ) .then(p => ({ ...p, id })) .then(res => { dispatch(res); }); } applyEto( projectID: string, fee: { asset_id: string; amount: number }, amount: { asset_id: string; amount: number }, account: AccountMap, append: any, onResolve? ) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { console.debug("Account: ", account); let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS(); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } return { privKey, pubKey: privKey.toPublicKey().toPublicKeyString() }; }) .then(async ({ privKey, pubKey }) => { let tx = new TransactionBuilder(); let op = tx.get_type_operation("exchange_participate", { fee, payer: account.get("id"), exchange_to_pay: projectID, amount }); tx.add_operation(op); await tx.update_head_block(); await tx.set_required_fees(); await tx.update_head_block(); tx.add_signer(privKey); await tx.finalize(); await tx.sign(); return new Promise((resolve, reject) => TransactionConfirmActions.confirm(tx, resolve, reject, append) ).then(tx => { dispatch(tx); this.removeLoading(); return tx; }); }) .catch(err => { console.error(err); this.removeLoading(); }); }; } // 其他 addLoading() { return 1; } removeLoading() { return 1; } } const EtoActionsWrapped: EtoActions = alt.createActions(EtoActions); export { EtoActionsWrapped as EtoActions }; export default EtoActionsWrapped; <file_sep>[理事会成员](introduction/committee) 可以提议修改区块链的动态参数,比如手续费,区块间隔时间以及其他很多参数。这是一个需要对Cybex系统如何运作有很深理解,需要有很强责任感的职位。<file_sep># npm install coffee-script # npm install webpack # Also install from packages.json cd $TRAVIS_BUILD_DIR npm install <file_sep>import { Serializer, types } from "cybexjs"; import { calcValue } from "../utils/Asset"; import { BigNumber } from "bignumber.js"; const { static_variant, string, time_point_sec, array, bool, optional, uint64 } = types; export namespace Eto { export enum Fields { basic = "basic", accountName = "accountName", accountID = "accountID", token = "token", survey = "survey", records = "records", result = "result" } export enum Token { CYB = "CYB", USDT = "USDT" } export enum EtoPersonalState { Uninit, Basic, Survey, Lock, ApplyDone } export type Info = { email: string; wechat: string; refer: string; }; export type Survey = any[]; export type Records = any[]; export type Result = [boolean, boolean, boolean, boolean]; export type FullInfo = { [Fields.basic]: Info; [Fields.accountID]: string; [Fields.accountName]: string; [Fields.token]: Token; [Fields.survey]: Survey; [Fields.records]: Records; [Fields.result]?: Result; }; export type LockApply = { pubKey: string; value: number }; export type Query = "query"; export type Ops = Query | Info | Survey | Token | LockApply; export enum OpsOrder { Query = 0, Info, Survey, Token, LockApply } export interface Request<T = Ops> { op: [number, T]; expiration: number; } export interface RequestWithSigner<T = Ops> { op: [number, T]; expiration: number; signer: string; } export type Rank = { coinAge: [string, number][]; lock: [string, number][]; timeStamp: Date; }; export class EtoInfo { state: EtoPersonalState = EtoPersonalState.Basic; sum = 0; info: FullInfo | null = null; constructor(info?: FullInfo) { if (info) { this.info = info; if (info[Fields.basic]) { this.state = EtoPersonalState.Survey; } if (info[Fields.survey]) { this.state = EtoPersonalState.Lock; } try { this.sum = calcValue( (info.records || []).reduce( (sum, next) => new BigNumber(sum).add(next.transfer.amount).toNumber(), 0 ), 5 ); } catch (e) { this.sum = 0; } } } } } export namespace EtoProject { export type Banner = { adds_banner: string; adds_banner__lang_en: string; adds_banner_mobile: string; adds_banner_mobile__lang_en: string; banner: number; // 排序 id: string; // 关联项目 index: number; }; export type SelectedBanner = { imgUrl: string; projectLink: string; }; export interface ProjectDetail { eto_rate: string; quote_accuracy: number; user_buy_token: string; lock_at: null; update_at: string; base_token: string; type: string; base_soft_cap: null; base_min_quota: number; status: string; token: string; quote_token_count: string; receive_address: string; offer_at: null; current_user_count: number; id: string; base_token_count: number; base_token_name: string; finish_at: string; close_at: null; token_name: string; start_at: string; token_count: number; base_accuracy: number; base_max_quota: number; end_at: string; control_status: string; current_base_token_count: number; deleted: number; created_at: string; name: string; score: number; control: string; banner: number; is_user_in: string; _id: string; account: string; project: string; timestamp: string; __v: number; parent: string; t_total_time: string; create_user_type: string; adds_logo: string; adds_advantage: string; adds_advantage__lang_en: string; adds_token_total__lang_en: string; adds_website__lang_en: string; adds_whitepaper: string; adds_website: string; adds_banner_mobile: string; adds_banner__lang_en: string; adds_logo_mobile: string; adds_keyword: string; adds_buy_desc__lang_en: string; adds_detail: string; adds_buy_desc: string; adds_whitepaper__lang_en: string; adds_token_total: string; adds_logo__lang_en: string; adds_keyword__lang_en: string; adds_detail__lang_en: string; adds_logo_mobile__lang_en: string; adds_banner: string; adds_banner_mobile__lang_en: string; current_percent: number; index: number; rate: string; current_remain_quota_count: number; } export type UserInStatus = { kyc_status: string; status: string; reason: string; }; export type UserProjectStatus = { current_base_token_count: number }; export const enum EtoStatus { Unstart = "pre", Running = "ok", Finished = "finish", Failed = "fail" } } const etoOps = { Query: string, Token: string, Survey: array(bool), Info: new Serializer("Info", { email: string, wechat: optional(string), refer: optional(string) }), Lock: new Serializer("LockApply", { pubKey: string, value: uint64 }) }; const etoOp = static_variant([ etoOps.Query, etoOps.Info, etoOps.Survey, etoOps.Token, etoOps.Lock ]); export const etoTx = new Serializer("EtoTx", { op: etoOp, expiration: time_point_sec }); export const EtoRefer = "$#ETO_REFER"; // import { Serializer } from "../cybex/serializer"; export namespace EtoOps { export enum exchange_owner_permission_flags { exchange_allow_quote_to_base = 1 << 0 /** allow get base */, exchange_allow_base_to_quote = 1 << 1 /** allow get quote */, exchange_allow_deposit_base = 1 << 2 /** allow can deposit base */, exchange_allow_withdraw_base = 1 << 3 /** allow can withdraw base */, exchange_allow_deposit_quote = 1 << 4 /** allow can deposit quote */, exchange_allow_withdraw_quote = 1 << 5 /** allow can withdraw quote */, exchange_allow_charge_market_fee = 1 << 6 /** allow charge market fee when pays out */, exchange_allow_modify_rate = 1 << 7 /** allow modify rate */, exchange_allow_only_white_list = 1 << 8 /** allow only account in whitelist to participate */ } export const EXCHANGE_OWNER_PERMISSION_MASK = exchange_owner_permission_flags.exchange_allow_quote_to_base | exchange_owner_permission_flags.exchange_allow_base_to_quote | exchange_owner_permission_flags.exchange_allow_deposit_base | exchange_owner_permission_flags.exchange_allow_withdraw_base | exchange_owner_permission_flags.exchange_allow_deposit_quote | exchange_owner_permission_flags.exchange_allow_withdraw_quote | exchange_owner_permission_flags.exchange_allow_charge_market_fee | exchange_owner_permission_flags.exchange_allow_modify_rate | exchange_owner_permission_flags.exchange_allow_only_white_list; export enum EtoOpsOrder { "create_exchange" = 58, "update_exchange" = 59, "withdraw_exchange" = 60, "deposit_exchange" = 61, "remove_exchange" = 62, "participate_exchange" = 63 } export type Asset = { asset_id: string; amount: number | string; }; export type Price = { base: Asset; quote: Asset; }; export type ExchangeCheckAmount = { asset_id: string; floor: number; ceil: number; }; export type ExchangeVestingPolicyWrapper = { policy: any; }; export type ExchangeCheckOnceAmount = ExchangeCheckAmount; export type ExchangeCheckDivisible = { divisor: Asset }; export type Extensions = | [0, ExchangeCheckAmount] | [1, ExchangeCheckOnceAmount] | [2, ExchangeCheckDivisible] | [3, ExchangeVestingPolicyWrapper]; export type ExchangeOptions = { rate: Price; owner_permissions: number; flags: number; whitelist_authorities: string[]; blacklist_authorities: string[]; extensions: Extensions[]; description: string; }; export type exchange_create = { name: string; owner?: string; options: ExchangeOptions; }; export type ExchangeObj = exchange_create & { id: string; dynamic_exchange_data_id: string; baseAsset: Cybex.Asset; quoteAsset: Cybex.Asset; }; export type ExchangeObjDym = { id: string; base_balance: string | number; base_balance_value: number; quote_balance: string | number; quote_balance_value: number; rate: number; }; export type Exchange = { ex: ExchangeObj; exd: ExchangeObjDym }; export const DefaultFee = { asset_id: "1.3.0", amount: 0 }; export type exchange_update = { owner?: string; options: ExchangeOptions; }; export type exchange_withdraw = { name: string; owner?: string; exchange_to_withdraw: string; amount: Asset; }; export type exchange_deposit = { name: string; owner?: string; exchange_to_deposit: string; amount: Asset; }; } <file_sep>// The translations in this file can be added with: // #registerTranslations('ru', require('counterpart/locales/ru'); 'use strict'; module.exports = { counterpart: { names: require('date-names/ru'), pluralize: require('pluralizers/ru'), formats: { date: { 'default': '%d.%m.%Y', long: 'A%, %d.%m.%Y', short: '%d.%m.%Y' }, time: { 'default': '%H:%M', long: '%H:%M:%S', short: '%H:%M' }, datetime: { 'default': '%d.%m.%Y, %H:%M', long: 'A%, %d.%m.%Y, %H:%M:%S', short: '%d.%m.%Y %H:%M' } } } }; <file_sep>'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _connect = require('./connect'); var _connect2 = _interopRequireDefault(_connect); var _supplyFluxContext = require('./supplyFluxContext'); var _supplyFluxContext2 = _interopRequireDefault(_supplyFluxContext); exports['default'] = { connect: _connect2['default'], supplyFluxContext: _supplyFluxContext2['default'] }; module.exports = exports['default'];<file_sep>var numeral = require("numeral"); let id_regex = /\b\d+\.\d+\.(\d+)\b/; import { Apis } from "cybexjs-ws"; import { ChainTypes } from "cybexjs"; var { object_type, operations } = ChainTypes; let replacedName = {}; var Utils = { get_object_id: obj_id => { let id_regex_res = id_regex.exec(obj_id); return id_regex_res ? Number.parseInt(id_regex_res[1]) : 0; }, getChainKey: key => { const chainId = Apis.instance().chain_id; return key + (chainId ? `_${chainId.substr(0, 8)}` : ""); }, is_object_id: obj_id => { if ("string" != typeof obj_id) return false; let match = id_regex.exec(obj_id); return match !== null && obj_id.split(".").length === 3; }, is_object_type: (obj_id, type) => { let prefix = object_type[type]; if (!prefix || !obj_id) return null; prefix = "1." + prefix.toString(); return obj_id.substring(0, prefix.length) === prefix; }, get_satoshi_amount(amount, asset) { let precision = asset.toJS ? asset.get("precision") : asset.precision; let assetPrecision = this.get_asset_precision(precision); amount = typeof amount === "string" ? amount : amount.toString(); let decimalPosition = amount.indexOf("."); if (decimalPosition === -1) { return parseInt(amount, 10) * assetPrecision; } else { let amountLength = amount.length, i; amount = amount.replace(".", ""); amount = amount.substr(0, decimalPosition + precision); for (i = 0; i < precision; i++) { decimalPosition += 1; if (decimalPosition > amount.length) { amount += "0"; } } return parseInt(amount, 10); } }, get_asset_precision: precision => { precision = precision.toJS ? precision.get("precision") : precision; return Math.pow(10, precision); }, get_asset_amount: function(amount, asset) { if (amount === 0) return amount; if (!amount) return null; return ( amount / this.get_asset_precision( asset.toJS ? asset.get("precision") : asset.precision ) ); }, get_asset_price: function( quoteAmount, quoteAsset, baseAmount, baseAsset, inverted = false ) { if (!quoteAsset || !baseAsset) { return 1; } var price = this.get_asset_amount(quoteAmount, quoteAsset) / this.get_asset_amount(baseAmount, baseAsset); return inverted ? 1 / price : price; }, round_number: function(number, asset) { let assetPrecision = asset.toJS ? asset.get("precision") : asset.precision; let precision = this.get_asset_precision(assetPrecision); return Math.round(number * precision) / precision; }, format_volume(amount) { if (amount < 10000) { return this.format_number(amount, 3); } else if (amount < 1000000) { return (Math.round(amount / 10) / 100).toFixed(2) + "k"; } else { return (Math.round(amount / 10000) / 100).toFixed(2) + "M"; } }, format_number: (number, decimals, trailing_zeros = true) => { if (number.toString().includes("e-")) { // console.debug("Float: ", number, decimals, parseFloat(number.toString()).toFixed(decimals)) return parseFloat(number.toString()).toFixed(decimals); } if ( isNaN(number) || !isFinite(number) || number === undefined || number === null ) return ""; let zeros = "."; for (var i = 0; i < decimals; i++) { zeros += "0"; } let num = numeral(number).format("0,0" + zeros); if (num.indexOf(".") > 0 && !trailing_zeros) return num.replace(/0+$/, "").replace(/\.$/, ""); return num; }, format_asset: function(amount, asset, noSymbol, trailing_zeros = true) { let symbol; let digits = 0; if (asset === undefined) return undefined; if ("symbol" in asset) { // console.log( "asset: ", asset ) symbol = asset.symbol; digits = asset.precision; } else { // console.log( "asset: ", asset.toJS() ) symbol = asset.get("symbol"); digits = asset.get("precision"); } let precision = this.get_asset_precision(digits); // console.log( "precision: ", precision ) return `${this.format_number(amount / precision, digits, trailing_zeros)}${ !noSymbol ? " " + symbol : "" }`; }, format_price: function( quoteAmount, quoteAsset, baseAmount, baseAsset, noSymbol, inverted = false, trailing_zeros = true ) { if (quoteAsset.size) quoteAsset = quoteAsset.toJS(); if (baseAsset.size) baseAsset = baseAsset.toJS(); let precision = this.get_asset_precision(quoteAsset.precision); let basePrecision = this.get_asset_precision(baseAsset.precision); if (inverted) { if ( parseInt(quoteAsset.id.split(".")[2], 10) < parseInt(baseAsset.id.split(".")[2], 10) ) { return `${this.format_number( quoteAmount / precision / (baseAmount / basePrecision), Math.max(5, quoteAsset.precision), trailing_zeros )}${!noSymbol ? "" + quoteAsset.symbol + "/" + baseAsset.symbol : ""}`; } else { return `${this.format_number( baseAmount / basePrecision / (quoteAmount / precision), Math.max(5, baseAsset.precision), trailing_zeros )}${!noSymbol ? "" + baseAsset.symbol + "/" + quoteAsset.symbol : ""}`; } } else { if ( parseInt(quoteAsset.id.split(".")[2], 10) > parseInt(baseAsset.id.split(".")[2], 10) ) { return `${this.format_number( quoteAmount / precision / (baseAmount / basePrecision), Math.max(5, quoteAsset.precision), trailing_zeros )}${!noSymbol ? "" + quoteAsset.symbol + "/" + baseAsset.symbol : ""}`; } else { return `${this.format_number( baseAmount / basePrecision / (quoteAmount / precision), Math.max(5, baseAsset.precision), trailing_zeros )}${!noSymbol ? "" + baseAsset.symbol + "/" + quoteAsset.symbol : ""}`; } } }, price_text: function(price, base, quote) { let maxDecimals = 8; let priceText; let quoteID = quote.toJS ? quote.get("id") : quote.id; let quotePrecision = quote.toJS ? quote.get("precision") : quote.precision; let baseID = base.toJS ? base.get("id") : base.id; let basePrecision = base.toJS ? base.get("precision") : base.precision; let fixedPrecisionAssets = { "1.3.113": 5, // bitCNY "1.3.121": 5 // bitUSD }; if (quoteID === "1.3.0") { priceText = this.format_number(price, quotePrecision); } else if (baseID === "1.3.0") { priceText = this.format_number( price, Math.min(maxDecimals, quotePrecision + 2) ); } else if (fixedPrecisionAssets[quoteID]) { priceText = this.format_number(price, fixedPrecisionAssets[quoteID]); } else { priceText = this.format_number( price, Math.min(maxDecimals, Math.max(quotePrecision + basePrecision, 2)) ); } return priceText; }, compared_price_text:function(price, base, quote, forcePrecision, previous){ let priceText; if (forcePrecision) { priceText = this.format_number(price, forcePrecision); } else { priceText = this.price_text(price, base, quote); } let dec = ""; let trailing = priceText let previousPriceText; if (forcePrecision) { previousPriceText = this.format_number(previous, forcePrecision); } else { previousPriceText = this.price_text(previous, base, quote); } const start = 0;//priceText.indexOf("."); for(var j=start;j<priceText.length;j++){ if(previousPriceText[j]!=priceText[j]){ dec = priceText.slice(start,j); trailing = priceText.slice(j); break; } } return { text: priceText, dec: dec, trailing: trailing, full: price }; }, price_to_text: function(price, base, quote, forcePrecision = null) { if (typeof price !== "number" || !base || !quote) { return; } if (price === Infinity) { price = 0; } let priceText; if (forcePrecision) { priceText = this.format_number(price, forcePrecision); } else { priceText = this.price_text(price, base, quote); } let price_split = priceText.split("."); let int = price_split[0]; let dec = price_split[1]; let i; let zeros = 0; if (dec) { if (price > 1) { let l = dec.length; for (i = l - 1; i >= 0; i--) { if (dec[i] !== "0") { break; } zeros++; } } else { let l = dec.length; for (i = 0; i < l; i++) { if (dec[i] !== "0") { i--; break; } zeros++; } } } let trailing = zeros ? dec.substr(Math.max(0, i + 1), dec.length) : null; if (trailing) { if (trailing.length === dec.length) { dec = null; } else if (trailing.length) { dec = dec.substr(0, i + 1); } } return { text: priceText, int: int, dec: dec, trailing: trailing, full: price }; }, get_op_type: function(object) { let type = parseInt(object.split(".")[1], 10); for (let id in object_type) { if (object_type[id] === type) { return id; } } }, add_comma: function(value) { if (typeof value === "number") { value = value.toString(); } value = value.trim(); value = value.replace(/,/g, ""); if (value == "." || value == "") { return value; } else if (value.length) { // console.log( "before: ",value ) let n: number | string = Number(value); if (isNaN(n)) return; let parts = value.split("."); // console.log( "split: ", parts ) n = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); if (parts.length > 1) n += "." + parts[1]; // console.log( "after: ",transfer.amount ) return n; } }, parse_float_with_comma: function(value) { // let value = new_state.transfer.amount value = value.replace(/,/g, ""); let fvalue = parseFloat(value); if (value.length && isNaN(fvalue) && value != ".") throw "parse_float_with_comma: must be a number"; else if (fvalue < 0) return 0; return fvalue; }, are_equal_shallow: function(a, b) { if ((!a && b) || (a && !b)) { return false; } if (Array.isArray(a) && Array.isArray(a)) { if (a.length > b.length) { return false; } } for (var key in a) { if (!(key in b) || a[key] !== b[key]) { return false; } } for (var key in b) { if (!(key in a) || a[key] !== b[key]) { return false; } } return true; }, format_date: function(date_str) { if (!/Z$/.test(date_str)) { date_str += "Z"; } let date = new Date(date_str); return date.toLocaleDateString(); }, format_time: function(time_str) { if (!/Z$/.test(time_str)) { time_str += "Z"; } let date = new Date(time_str); return date.toLocaleString(); }, limitByPrecision: function(value, assetPrecision) { let valueString = value.toString(); let splitString = valueString.split("."); if ( splitString.length === 1 || (splitString.length === 2 && splitString[1].length <= assetPrecision) ) { return valueString; } else { return splitString[0] + "." + splitString[1].substr(0, assetPrecision); } // let precision = this.get_asset_precision(assetPrecision); // value = Math.floor(value * precision) / precision; // if (isNaN(value) || !isFinite(value)) { // return 0; // } // return value; }, getFee: function({ opType, options, globalObject, asset, coreAsset, balances }) { let coreFee: { [a: string]: any } = { asset: "1.3.0" }; coreFee.amount = this.estimateFee(opType, options, globalObject) || 0; if (!asset || asset.get("id") === "1.3.0") return coreFee; // Desired fee is in core asset let cer = asset.getIn(["options", "core_exchange_rate"]).toJS(); if (!coreAsset || cer.base.asset_id === cer.quote.asset_id) return coreFee; let price = this.convertPrice(coreAsset, cer, null, asset.get("id")); let eqValue = this.convertValue(price, coreFee.amount, coreAsset, asset); let fee = { amount: Math.floor(eqValue + 0.5), asset: asset.get("id") }; let useCoreFee = true; // prefer CORE fee by default if (balances && balances.length) { balances.forEach(b => { if ( b.get("asset_type") === "1.3.0" && b.get("balance") < coreFee.amount ) { // User has sufficient CORE, use it (cheapeest) useCoreFee = false; } }); balances.forEach(b => { if ( b.get("asset_type") === fee.asset && b.get("balance") < fee.amount ) { // User has insufficient {asset}, use CORE instead useCoreFee = true; } }); } return useCoreFee ? coreFee : fee; }, convertPrice: function(fromRate, toRate, fromID?, toID?) { if (!fromRate || !toRate) { return null; } // Handle case of input simply being a fromAsset and toAsset if (fromRate.toJS && this.is_object_type(fromRate.get("id"), "asset")) { fromID = fromRate.get("id"); fromRate = fromRate.get("bitasset") ? fromRate .getIn(["bitasset", "current_feed", "settlement_price"]) .toJS() : fromRate.getIn(["options", "core_exchange_rate"]).toJS(); } if (toRate.toJS && this.is_object_type(toRate.get("id"), "asset")) { toID = toRate.get("id"); toRate = toRate.get("bitasset") ? toRate.getIn(["bitasset", "current_feed", "settlement_price"]).toJS() : toRate.getIn(["options", "core_exchange_rate"]).toJS(); } let fromRateQuoteID = fromRate.quote.asset_id; let toRateQuoteID = toRate.quote.asset_id; let fromRateQuoteAmount, fromRateBaseAmount, finalQuoteID, finalBaseID; if (fromRateQuoteID === fromID) { fromRateQuoteAmount = fromRate.quote.amount; fromRateBaseAmount = fromRate.base.amount; } else { fromRateQuoteAmount = fromRate.base.amount; fromRateBaseAmount = fromRate.quote.amount; } let toRateQuoteAmount, toRateBaseAmount; if (toRateQuoteID === toID) { toRateQuoteAmount = toRate.quote.amount; toRateBaseAmount = toRate.base.amount; } else { toRateQuoteAmount = toRate.base.amount; toRateBaseAmount = toRate.quote.amount; } let baseRatio, finalQuoteAmount, finalBaseAmount; if (toRateBaseAmount > fromRateBaseAmount) { baseRatio = toRateBaseAmount / fromRateBaseAmount; finalQuoteAmount = fromRateQuoteAmount * baseRatio; finalBaseAmount = toRateQuoteAmount; } else { baseRatio = fromRateBaseAmount / toRateBaseAmount; finalQuoteAmount = fromRateQuoteAmount; finalBaseAmount = toRateQuoteAmount * baseRatio; } return { quote: { amount: finalQuoteAmount, asset_id: toID }, base: { amount: finalBaseAmount, asset_id: fromID } }; }, convertValue: function(priceObject, amount, fromAsset, toAsset) { priceObject = priceObject.toJS ? priceObject.toJS() : priceObject; let quotePrecision = this.get_asset_precision(fromAsset.get("precision")); let basePrecision = this.get_asset_precision(toAsset.get("precision")); let assetPrice = this.get_asset_price( priceObject.quote.amount, fromAsset, priceObject.base.amount, toAsset ); let eqValue = fromAsset.get("id") !== toAsset.get("id") ? (basePrecision * (amount / quotePrecision)) / assetPrice : amount; if (isNaN(eqValue) || !isFinite(eqValue)) { return null; } return eqValue; }, isValidPrice(rate) { if (!rate || !rate.toJS) { return false; } let base = rate.get("base").toJS(); let quote = rate.get("quote").toJS(); if ( base.amount > 0 && quote.amount > 0 && base.asset_id !== quote.asset_id ) { return true; } else { return false; } }, sortText(a, b, inverse = false) { if (a > b) { return inverse ? 1 : -1; } else if (a < b) { return inverse ? -1 : 1; } else { return 0; } }, sortID(a, b, inverse = false) { // inverse = false => low to high let intA = parseInt(a.split(".")[2], 10); let intB = parseInt(b.split(".")[2], 10); return inverse ? intB - intA : intA - intB; }, calc_block_time(block_number, globalObject, dynGlobalObject) { if (!globalObject || !dynGlobalObject) return null; const block_interval = globalObject.get("parameters").get("block_interval"); const head_block = dynGlobalObject.get("head_block_number"); const head_block_time: Date | number = new Date( dynGlobalObject.get("time") + "Z" ); const seconds_below = (head_block - block_number) * block_interval; return new Date((head_block_time as any) - seconds_below * 1000); }, get_translation_parts(str) { let result = []; let toReplace = {}; let re = /{(.*?)}/g; let interpolators = str.split(re); // console.log("split:", str.split(re)); return str.split(re); // var str = '{{azazdaz}} {{azdazd}}'; // var m; // while ((m = re.exec(str)) !== null) { // if (m.index === re.lastIndex) { // re.lastIndex++; // } // console.log("m:", m); // // View your result using the m-variable. // // eg m[0] etc. // // // toReplace[m[1]] = m[0] // result.push(m[1]) // } // return result; }, get_percentage(a, b) { return Math.round((a / b) * 100) + "%"; }, replaceName(_name, isBitAsset = false) { if (replacedName[_name]) { return replacedName[_name]; } let toReplace = [ "JADE.", "TEST.", "TRADE.", "OPEN.", "METAEX.", "BRIDGE.", "RUDEX." ]; const toHidden = { "JADE.": true, "TEST.": true }; let suffix = ""; let i; let name = _name; for (i = 0; i < toReplace.length; i++) { if (_name.indexOf(toReplace[i]) !== -1) { name = _name.replace(toReplace[i], "") + suffix; break; } } let prefix = isBitAsset ? "cyb." : toReplace[i] && !toHidden[toReplace[i]] ? toReplace[i].toLowerCase() : null; // if (prefix === "open.") prefix = ""; let res = { name, prefix }; replacedName[_name] = res; return res; }, getAccountFullHistory: async (accountId, numOfRecord = 100) => { let res = await Apis.instance() .history_api() .exec("get_account_history", [ accountId, "1.11.1", numOfRecord, "1.11.0" ]); if (res.length < numOfRecord) { return res; } let then; do { let lastId = parseInt(res[res.length - 1].id.split(".")[2]) - 1; then = await Apis.instance() .history_api() .exec("get_account_history", [ accountId, "1.11.1", numOfRecord, "1.11." + lastId ]); res = [...res, ...then]; } while (then.length); return res; } }; export default Utils; <file_sep>```html <Trigger open="top-offcanvas"> <a className="button">Open Top Off-canvas</a> </Trigger> <Offcanvas id="top-offcanvas" position="top"> <Trigger close=""> <a className="close-button">&times;</a> </Trigger> <br /> <p>This is Top offcanvas menu</p> </Offcanvas> ``` <file_sep>// import ee from "event-emitter"; let ee = require('event-emitter'); var _emitter; export default function emitter () { if ( !_emitter ) { _emitter = ee({}); } return _emitter; } <file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var BasicTabs = require("./basic"); var TabsDocs = React.createClass({ render: function() { return ( <div> <h2>Tabs</h2> <h4 className="subheader"> Tabs are elements that help you organize and navigate multiple documents in a single container. They can be used for switching between items in the container. </h4> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./basic.md")} </Highlight> </div> <div className="grid-content"> <BasicTabs /> </div> </div> <hr /> </div> ); } }); module.exports = TabsDocs; <file_sep>const BITSHARES_NODE = "wss://fake.automatic-selection.com"; const DEFAULT_FAUCET = __TEST__ ? "http://uatfaucet.51nebula.com" : "https://faucet.cybex.io/"; class ApiNode { url = ""; location = ""; constructor(host, name) { // let schema = // location && location.protocol.indexOf("https") !== -1 // ? "wss://" // : "wss://"; let schema = "wss://"; let url = schema + host; this.url = url; this.location = name; } } const WS_NODE_LIST = __TEST__ || __FOR_SECURITY__ ? [new ApiNode("uatfn.51nebula.com/", "UAT")] : [ // new ApiNode("shanghai.51nebula.com/", "shanghai"), // new ApiNode("shanghai.51nebula.com/", "Shanghai"), // new ApiNode("beijing.51nebula.com/", "Beijing"), new ApiNode("hongkong.cybex.io/", "Hongkong"), new ApiNode("hongkong01.cybex.io/", "Hongkong01"), new ApiNode("hongkong-gce01.cybex.io/", "Hongkonggce"), // new ApiNode("tokyo-01.cybex.io/", "Tokyo"), // new ApiNode("singapore-01.cybex.io/", "Singapore"), // new ApiNode("europe01.cybex.io/", "Europe"), // new ApiNode("korea-01.cybex.io/", "Korea") ]; export const blockTradesAPIs = { BASE: "https://api.blocktrades.us/v2", BASE_OL: "https://ol-api1.openledger.info/api/v0/ol/support", COINS_LIST: "/coins", ACTIVE_WALLETS: "/active-wallets", TRADING_PAIRS: "/trading-pairs", DEPOSIT_LIMIT: "/deposit-limits", ESTIMATE_OUTPUT: "/estimate-output-amount", ESTIMATE_INPUT: "/estimate-input-amount" }; export const rudexAPIs = { BASE: "https://gateway.rudex.org/api/v0_1", COINS_LIST: "/coins", NEW_DEPOSIT_ADDRESS: "/new-deposit-address" }; export const IEO_API = __FOR_SECURITY__ ? "//eto-pre.cybex.io/api" : __STAGING__ ? "///eto.cybex.io/api" : __DEV__ || __TEST__ ? "https://ieo-apitest.cybex.io/api" : "///eto.cybex.io/api"; export const ETO_LOCK = __FOR_SECURITY__ ? "https://eto-lock.cybex.io/" : __STAGING__ ? "https://eto-lock.cybex.io/" : __DEV__ || __TEST__ ? // ? "https://eto-lock.cybex.io/" "http://127.0.0.1:5557/" : "https://eto-lock.cybex.io/"; export const EDGE_LOCK = __FOR_SECURITY__ ? "https://edge-lock.cybex.io/" : __STAGING__ ? "https://edge-lock.cybex.io/" : __DEV__ || __TEST__ ? // ? "https://eto-lock.cybex.io/" "https://edge-lock.cybex.io/" : // "http://10.18.120.155:5558/" // "http://10.18.120.155:5558/" "https://edge-lock.cybex.io/"; export const PRICE_API = "https://app.cybex.io/price"; export const settingsAPIs = { DEFAULT_WS_NODE: BITSHARES_NODE, WS_NODE_LIST, DEFAULT_FAUCET, TESTNET_FAUCET: DEFAULT_FAUCET, RPC_URL: __TEST__ ? "wss://shenzhen.51nebula.com:8092/api/" : "wss://hongkong.cybex.io:8092/api/" }; <file_sep>import {LimitOrderCreate, Price, FeedPrice, Asset, limitByPrecision, precisionToRatio, LimitOrder, SettleOrder, CallOrder} from "../lib/common/MarketClasses"; import assert from "assert"; console.log("**** Starting market tests here ****"); const asset1 = {asset_id: "1.3.0", precision: 5}; const asset2 = {asset_id: "1.3.121", precision: 4}; // bitUSD const asset3 = {asset_id: "1.3.113", precision: 4}; // bitCNY const assets = {"1.3.0": asset1, "1.3.121": asset2, "1.3.113": asset3}; describe("Utility functions", function() { describe("limitByPrecision", function() { it("Limits to precision without rounding", function() { assert.equal(limitByPrecision(1.23236, 4), 1.2323, "Value should be equal to 1.2323"); }); it("Does not add extra digits", function() { let num = limitByPrecision(1.23236, 8); assert.equal(num, 1.23236, "Value should be equal to 1.23236"); assert.equal(num.toString().length, 7, "Length should be equal to 7"); }); }); describe("precisionToRatio", function() { it("Returns the multiplier for an integer precision", function() { assert.equal(precisionToRatio(2), 100, "Value should equal 100"); assert.equal(precisionToRatio(5), 100000, "Value should equal 100000"); assert.equal(precisionToRatio(8), 100000000, "Value should equal 100000000"); }); }); }); describe("Asset", function() { it("Instantiates empty", function() { let asset = new Asset(); assert.equal(asset.asset_id, "1.3.0", "Default asset should be 1.3.0"); assert.equal(asset.amount, 0, "Default amount should be 0"); assert.equal(asset.satoshi, 100000, "Satoshi should be 100000"); }); it("Instantiates with values", function() { let asset = new Asset({asset_id: "1.3.121", amount: 242, precision: 4}); assert.equal(asset.asset_id, "1.3.121", "Asset should be 1.3.121"); assert.equal(asset.amount, 242, "Amount should be 242"); assert.equal(asset.satoshi, 10000, "Satoshi should be 10000"); }); it("Instantiates from real number", function() { let asset = new Asset({asset_id: "1.3.0", real: 1}); assert.equal(asset.asset_id, "1.3.0", "Asset should be 1.3.0"); assert.equal(asset.amount, 100000, "Amount should be 242"); assert.equal(asset.satoshi, 100000, "Satoshi should be 10000"); let asset2 = new Asset({asset_id: "1.3.861", real: "0.00030", precision: 8}); assert.equal(asset2.asset_id, "1.3.861", "Asset should be 1.3.861"); assert.equal(asset2.amount, 30000, "Amount should be 30000"); assert.equal(asset2.satoshi, 100000000, "Satoshi should be 100000000"); }); it("Can be added", function() { let asset = new Asset({asset_id: "1.3.121", amount: 242}); let asset2 = new Asset({asset_id: "1.3.121", amount: 242}); asset.plus(asset2); assert.equal(asset.asset_id, "1.3.121", "Asset should be 1.3.121"); assert.equal(asset.amount, 484, "Amount should be 484"); }); it("Can be subtracted", function() { let asset = new Asset({asset_id: "1.3.121", amount: 242}); let asset2 = new Asset({asset_id: "1.3.121", amount: 242}); asset.minus(asset2); assert.equal(asset.asset_id, "1.3.121", "Asset should be 1.3.121"); assert.equal(asset.amount, 0, "Amount should be 0"); }); it("Throws when adding or subtracting unequal assets", function() { let asset = new Asset({asset_id: "1.3.121", amount: 242}); let asset2 = new Asset({asset_id: "1.3.0", amount: 242}); assert.throws(function() { asset.plus(asset2); }, Error); assert.throws(function() { asset.minus(asset2); }, Error); }); it("Can be updated with real or satoshi amounts", function() { let asset = new Asset(); asset.setAmount({real: 1.2323}); assert.equal(asset.getAmount({}), 123230, "Amount should equal 123230"); assert.equal(asset.getAmount({real: true}), 1.2323, "Amount should equal 1.2323"); asset.setAmount({sats: 232223}); assert.equal(asset.getAmount(), 232223, "Amount should equal 232223"); assert.equal(asset.getAmount({real: true}), 2.32223, "Amount should equal 2.32223"); asset.setAmount({real: 2.3212332223}); // assert.equal(asset.getAmount(), 232223, "Amount should equal 232223"); assert.equal(asset.getAmount({real: true}), 2.32123, "Amount should equal 2.32123"); }); it("Returns true if amount > 0", function() { let asset = new Asset({amount: 232}); assert.equal(asset.hasAmount(), true, "Price should be valid"); }); it("Returns false if amount is 0", function() { let asset = new Asset(); assert.equal(asset.hasAmount(), false, "Price should not be valid"); }); it("Parses string amounts to numbers", function() { let asset = new Asset(); asset.setAmount({sats: "123"}); assert.equal(asset.getAmount(), 123); asset.setAmount({real: "123.23223"}); assert.equal(asset.getAmount(), 12323223); }); it("Throws when setAmount args are not set or incorrect", function() { let asset = new Asset(); assert.throws(function() { asset.setAmount(); }, Error); assert.throws(function() { asset.setAmount({}); }, Error); assert.throws(function() { asset.setAmount({real: undefined}); }, Error); }); it("Can be multiplied with a price", function() { let asset = new Asset({asset_id: "1.3.0", real: 100}); let asset2 = new Asset({asset_id: "1.3.121", precision: 4, real: 55}); let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 200 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.121", precision: 4}), quote: new Asset({asset_id: "1.3.0"}), real: 0.001 }); let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 250 }); let result1 = asset.times(price1); assert.equal(result1.asset_id, "1.3.121", "Asset id should be 1.3.121"); // 100 CYB * 200 CYB/USD = 100 CYB * (1/200) USD/CYB = 0.5 USD assert.equal(result1.getAmount({real: true}), 0.5, "Asset amount should be 0.5"); let result2 = asset.times(price2); assert.equal(result2.asset_id, "1.3.121", "Asset id should be 1.3.121"); // 100 CYB * 0.001 USD / CYB = 0.1 USD assert.equal(result2.getAmount({real: true}), 0.1, "Asset amount should be 0.1"); // 55 USD * 250 CYB / USD = 13750 CYB assert.equal(asset2.times(price3).getAmount({real: true}), 13750, "Asset amount should equal 13750"); }); it("Rounds up when multiplying for bid orders", function() { let forSale = new Asset({ amount: 40000, asset_id: "1.3.22", precision: 4 }); let price = new Price({ base: new Asset({asset_id: "1.3.22", amount: 150000, precision: 4}), quote: new Asset({amount: 535406800}) }); let toReceive = forSale.times(price, true); assert.equal(toReceive.getAmount(), 142775147); }); it("Throws when multiplied with an incorrect price", function() { let asset = new Asset({asset_id: "1.3.0", amount: 100}); let price = new Price({ base: new Asset({asset_id: "1.3.12", amount: 25}), quote: new Asset({asset_id: "1.3.121", amount: 500}) }); assert.throws(function() { asset.times(price); }, Error); }); it("Can be converted to object", function() { let asset = new Asset({amount: 2323}); let obj = asset.toObject(); assert.equal(Object.keys(obj).length, 2, "Object should have 2 keys"); assert.equal("asset_id" in obj, true, "Object should have asset_id key"); assert.equal("amount" in obj, true, "Object should have amount key"); }); it("Can be divided by another asset to give a price", function() { let asset = new Asset({amount: 2323}); let asset2 = new Asset({amount: 10, precision: 4, asset_id: "1.3.121"}); let price = asset.divide(asset2); assert.equal(price.toReal(), 23.23, "Price should equal 23.23"); }); }); describe("Price", function() { let base = new Asset({asset_id: "1.3.0", amount: 50}); let quote = new Asset({asset_id: "1.3.121", amount: 250, precision: 4}); it("Instantiates", function() { let price = new Price({base, quote}); assert.equal(price.base.asset_id, "1.3.0", "Base asset should be 1.3.0"); assert.equal(price.base.amount, 50, "Base amount should be 50"); assert.equal(price.quote.asset_id, "1.3.121", "Quote asset should be 1.3.121"); assert.equal(price.quote.amount, 250, "Quote amount should be 250"); assert.equal(price.toReal(), 0.02, "Real price should be 0.02"); }); it("Returns true if valid", function() { let price = new Price({base, quote}); assert.equal(price.isValid(), true, "Price should be valid"); }); it("Returns false if not valid", function() { let price = new Price({base: new Asset({amount: 0}), quote}); assert.equal(price.isValid(), false, "Price should not be valid"); }); it("Instantiates from real number", function() { let priceNum = 250; let price = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: priceNum }); assert.equal(price.toReal(), priceNum, "Real price should equal " + priceNum); assert.equal(price.base.amount, 2500, "Base amount should equal 2500"); assert.equal(price.quote.amount, 1, "Quote amount should equal 1"); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); assert.equal(price2.toReal().toFixed(5), "212.23323", "Real price should equal 212.23323"); assert.equal(price2.base.amount, 212233230, "Base amount should equal 212233230"); assert.equal(price2.quote.amount, 100000, "Quote amount should equal 100000"); priceNum = 121000.52323231; let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.103", precision: 8}), real: priceNum }); assert.equal(price3.toReal(), priceNum.toFixed(5), "Real price should equal " + priceNum.toFixed(5)); priceNum = 0.00000321; for (var i = 0; i < 100000; i+=100) { priceNum += i; if (priceNum > 10000) { priceNum = limitByPrecision(priceNum, 5); } priceNum = parseFloat(priceNum.toFixed(8)); price3 = new Price({ base: new Asset({asset_id: "1.3.103", precision: 8}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: priceNum }); assert.equal(price3.toReal(), priceNum, "Real price should equal " + priceNum); } }); it("Can be output as a real number", function() { let price = new Price({base, quote}); let real = price.toReal(); assert.equal(real, 0.02, "Real price should be 0.02"); }); it("Throws if inputs are invalid", function() { assert.throws(function() { let price = new Price({base: null, quote}); }); assert.throws(function() { let price = new Price({base, quote: null}); }); assert.throws(function() { let price = new Price({base: null, quote: null}); }); }); it("Throws if base and quote assets are the same", function() { assert.throws(function() { let price = new Price({base, quote: base}); }); }); it("Can be compared with equals", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 2312.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 2312.151 }); assert.equal(price1.equals(price2), false, "Prices are not equal"); assert.equal(price1.equals(price3), true, "Prices are equal"); }); it("Can be compared with less than", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 2312.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); assert.equal(price1.lt(price2), false, "Price1 is not less than price2"); assert.equal(price2.lt(price1), true, "Price2 is less than price1"); }); it("Can be compared with less than or equal", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.151 }); assert.equal(price1.lte(price2), true, "Price1 is less than or equal"); assert.equal(price2.lte(price1), false, "Price2 is not less than price1"); assert.equal(price3.lte(price1), true, "Price3 is equal to price1"); }); it("Can be compared with not equal", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); assert(price1.ne(price2)); }); it("Can be compared with greater than", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); assert.equal(price1.gt(price2), false, "Price1 is not greater than price2"); assert.equal(price2.gt(price1), true, "Price2 is greater than price1"); assert.equal(price2.gt(price3), false, "Price2 is equal to price3"); }); it("Can be compared with greater than or equal", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.151 }); let price2 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); let price3 = new Price({ base: new Asset({asset_id: "1.3.0"}), quote: new Asset({asset_id: "1.3.121", precision: 4}), real: 212.23323 }); assert.equal(price1.gte(price2), false, "Price1 is not greater than price2"); assert.equal(price2.gte(price1), true, "Price2 is greater than price1"); assert.equal(price2.gte(price3), true, "Price2 is equal to price3"); }); it("Can be inverted", function() { let price1 = new Price({ base: new Asset({asset_id: "1.3.0", amount: 10000}), quote: new Asset({asset_id: "1.3.121", precision: 4, amount: 500}), }); price1 = price1.invert(); let price2 = new Price({ base: new Asset({asset_id: "1.3.121", precision: 4, amount: 500}), quote: new Asset({asset_id: "1.3.0", amount: 10000}), }); assert(price1.equals(price2)); }); }); describe("FeedPrice", function() { let base = new Asset({asset_id: "1.3.121", amount: 36, precision: 4}); let quote = new Asset({asset_id: "1.3.0", amount: 86275}); it("Instantiates", function() { let price = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.0", sqr: 1100, assets}); let price2 = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.121", sqr: 1100, assets}); assert.equal(price.base.asset_id, "1.3.121", "Base asset should be 1.3.121"); assert.equal(price.base.amount, 36, "Base amount should be 36"); assert.equal(price.quote.asset_id, "1.3.0", "Quote asset should be 1.3.0"); assert.equal(price.quote.amount, 86275, "Quote amount should be 86275"); assert.equal(price.toReal(), 0.0041727, "Real price should be 0.0041727"); assert.equal(price2.toReal(), 239.65277778, "Real price should be 239.65277778"); }); it("Returns short squeeze price", function() { let price = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.121", sqr: 1100, assets}); let price2 = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.0", sqr: 1100, assets}); assert.equal(price.getSqueezePrice({real: true}), 263.61666667, "Squeeze price should equal 263.61666667"); assert.equal(price2.getSqueezePrice({real: true}), 0.00379339, "Squeeze price should equal 0.00379339"); }); it("Returns the settlement price", function() { let price = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.121", sqr: 1100, assets}); let price2 = new FeedPrice({priceObject: {base, quote}, market_base: "1.3.0", sqr: 1100, assets}); assert.equal(price.toReal(), 239.65277778, "Squeeze price should equal 239.65277778"); assert.equal(price2.toReal(), 0.0041727, "Squeeze price should equal 0.0041727"); }); }); describe("LimitOrderCreate", function() { let USD = new Asset({ precision: 4, asset_id: "1.3.121", real: 5.232 }); let CYB = new Asset({ real: 1045.5 }); it("Instantiates", function() { let order = new LimitOrderCreate({ to_receive: USD, for_sale: CYB }); assert(order !== null); }); it("Can be converted to object", function() { let order = new LimitOrderCreate({ to_receive: USD, for_sale: CYB }); let obj = order.toObject(); assert.equal(Object.keys(obj).length, 6, "Object should have 6 keys"); assert.equal("min_to_receive" in obj, true, "Object should have min_to_receive key"); assert.equal("amount_to_sell" in obj, true, "Object should have amount_to_sell key"); assert.equal("expiration" in obj, true, "Object should have expiration key"); assert.equal("fill_or_kill" in obj, true, "Object should have fill_or_kill key"); assert.equal("seller" in obj, true, "Object should have seller key"); }); it("Throws if inputs are invalid", function() { assert.throws(function() { new LimitOrderCreate({ to_receive: null, for_sale: CYB }); }); assert.throws(function() { new LimitOrderCreate({ to_receive: USD, for_sale: null }); }); assert.throws(function() { new LimitOrderCreate({ to_receive: null, for_sale: null }); }); }); it("Throws if assets are the same", function() { assert.throws(function() { new LimitOrderCreate({ to_receive: CYB, for_sale: CYB }); }); }); }); /* Order types */ describe("LimitOrder", function() { const o = { "id":"1.7.937674", "expiration":"2017-12-13T14:14:09", "seller":"1.2.132823", "for_sale":600548, "sell_price": { "base": { "amount":40652748, "asset_id":"1.3.0" }, "quote":{ "amount":16186, "asset_id":"1.3.121" } } ,"deferred_fee":14676 }; const o2 = { "id":"1.7.937674", "expiration":"2017-12-13T14:14:09", "seller":"1.2.132823", "for_sale":600548, "sell_price": { "base": { "amount":16186, "asset_id":"1.3.121" }, "quote":{ "amount":40652748, "asset_id":"1.3.0" } } ,"deferred_fee":14676 }; const o3 = { "id":"1.7.937674", "expiration":"2017-12-13T14:14:09", "seller":"1.2.132823", "for_sale":1, "sell_price": { "base": { "amount":47554, "asset_id":"1.3.121" }, "quote":{ "amount": 150000000, "asset_id":"1.3.0" } } ,"deferred_fee":14676 }; const o4 = { "id":"1.7.937674", "expiration":"2017-12-13T14:14:09", "seller":"1.2.132823", "for_sale":3154, "sell_price": { "base":{ "amount": 150000000, "asset_id":"1.3.0" }, "quote": { "amount":47554, "asset_id":"1.3.121" }, } ,"deferred_fee":14676 }; const o5 = { "id":"1.7.69372", "expiration":"2017-12-13T14:14:09", "seller":"1.2.132823", "for_sale":1, "sell_price": { "base":{ "amount": 6470, "asset_id":"1.3.0" }, "quote": { "amount":20113, "asset_id":"1.3.121" }, } ,"deferred_fee":14676 }; it("Instantiates", function() { let order = new LimitOrder(o, assets, "1.3.0"); assert(order.id === o.id); assert(order.seller === o.seller); assert(order.for_sale === o.for_sale); assert(order.fee === o.deferred_fee); }); it("Returns the price of the order", function() { let order = new LimitOrder(o, assets, "1.3.121"); assert.equal(order.getPrice(), 251.15994069, "Price should equal 251.15994069"); let order2 = new LimitOrder(o, assets, "1.3.0"); assert.equal(order2.getPrice(), 0.00398153, "Price should equal 0.00398153"); }); it("Returns the amount for sale as an asset", function() { let order = new LimitOrder(o, assets, "1.3.0"); let forSale = order.amountForSale(); assert.equal(forSale.getAmount(), 600548, "Satoshi amount for sale should equal 600548"); assert.equal(forSale.getAmount({real: true}), 6.00548, "Real amount for sale should equal 6.00548"); }); it("Returns the amount to receive as an asset", function() { let order = new LimitOrder(o, assets, "1.3.0"); let toReceive = order.amountToReceive(); assert.equal(toReceive.getAmount(), 239, "Satoshi amount to receive should equal 239"); assert.equal(toReceive.getAmount({real: true}), 0.0239, "Real amount for sale should equal 0.0239"); let order3 = new LimitOrder(o3, assets, "1.3.121"); let order4 = new LimitOrder(o4, assets, "1.3.121"); let order5 = new LimitOrder(o3, assets, "1.3.0"); let order6 = new LimitOrder(o4, assets, "1.3.0"); let order7 = new LimitOrder(o5, assets, "1.3.121"); assert.equal(order3.amountToReceive().getAmount(), 3154, "As an ask, amountToReceive should equal 3154"); assert.equal(order4.amountToReceive().getAmount(), 1, "Order4 should equal 1"); assert.equal(order5.amountToReceive().getAmount(), 3155, "As a bid, amountToReceive should equal 3155"); assert.equal(order6.amountToReceive().getAmount(), 1, "Order6 should equal 1"); assert.equal(order7.amountToReceive().getAmount(), 4, "Order7 should equal 4"); }); it("Returns the order type", function() { let order = new LimitOrder(o, assets, "1.3.0"); let order2 = new LimitOrder(o2, assets, "1.3.0"); assert.equal(order.isBid(), false, "Order type should be ASK/false"); assert.equal(order2.isBid(), true, "Order type should be BID/true"); }); it("Can be summed with another order", function() { let o1 = new LimitOrder(o, assets, "1.3.0"); let o2 = new LimitOrder(o, assets, "1.3.0"); let o3 = o1.sum(o2); assert.equal(o3.amountForSale().getAmount(), 600548*2, "The amount should equal 1201096"); }); it("Can be compared to another order with equals / ne", function() { let o1 = new LimitOrder(o, assets, "1.3.0"); let o2 = new LimitOrder(o, assets, "1.3.0"); assert.equal(o1.ne(o2), false, "Orders are the same"); assert.equal(o1.equals(o2), true, "Orders are the same"); }); }); describe("CallOrder", function() { let base = { amount: 31, asset_id: "1.3.113" }; let quote = { amount: 10624, asset_id: "1.3.0" }; let settlePrice_0 = new FeedPrice({ priceObject: { base, quote }, market_base: "1.3.0", sqr: 1100, assets }); let settlePrice_113 = new FeedPrice({ priceObject: { base, quote }, market_base: "1.3.113", sqr: 1100, assets }); const o = { "id": "1.8.2317", "borrower": "1.2.115227", "collateral": "338894366025", "debt": 498820000, "call_price": { "base": { "amount": "13558072233" ,"asset_id": "1.3.0" }, "quote": { "amount": 34930000, "asset_id": "1.3.113" } } }; const o2 = { "id": "1.8.2317", "borrower": "1.2.115227", "collateral": "338894366025", "debt": 498820000, "call_price": { "base": { "amount": "13558072233" ,"asset_id": "1.3.0" }, "quote": { "amount": 349300000, "asset_id": "1.3.113" } } }; it("Instantiates", function() { let order = new CallOrder(o, assets, "1.3.0", settlePrice_0); assert.equal(order.id, o.id, "Id should be 1.8.2317"); assert.equal(order.for_sale, o.collateral); assert.equal(order.to_receive, o.debt); }); it("Returns the call price of the order", function() { let order = new CallOrder(o, assets, "1.3.113", settlePrice_113); assert.equal(order.getPrice(false), 38.8149792, "Price should equal 38.8149792"); let order2 = new CallOrder(o, assets, "1.3.0", settlePrice_0); assert.equal(order2.getPrice(false), 0.02576325, "Price should equal 0.02576325"); }); it("Returns the order type", function() { let order = new CallOrder(o, assets, "1.3.0", settlePrice_0); assert.equal(order.isBid(), false, "Order type should be ASK/false"); let order2 = new CallOrder(o, assets, "1.3.113", settlePrice_113); assert.equal(order2.isBid(), true, "Order type should be BID/true"); }); it("Returns margin call status", function() { let order = new CallOrder(o, assets, "1.3.113", settlePrice_113); let order2 = new CallOrder(o2, assets, "1.3.113", settlePrice_113); assert.equal(order.isMarginCalled(), false, "Order is not margin called: " + order.getPrice() + " > " + settlePrice_113.toReal()); assert.equal(order2.isMarginCalled(), true, "Order2 is margin called: " + order2.getPrice() + " < " + settlePrice_113.toReal()); let order3 = new CallOrder(o, assets, "1.3.0", settlePrice_0); let order4 = new CallOrder(o2, assets, "1.3.0", settlePrice_0); assert.equal(order3.isMarginCalled(), false, "order3 is not margin called: " + order3.getPrice() + " < " + settlePrice_0.toReal()); assert.equal(order4.isMarginCalled(), true, "Order4 is margin called: " + order4.getPrice() + " > " + settlePrice_0.toReal()); }); it("Returns the amount for sale as an asset", function() { let order = new CallOrder(o, assets, "1.3.0", settlePrice_0); let forSale = order.amountForSale(); assert.equal(forSale.getAmount(), 188039049032, "Satoshi amount for sale should equal 188039049032"); assert.equal(forSale.getAmount({real: true}), 1880390.49032, "Real amount for sale should equal 1880390.49032"); }); it("Returns the amount to receive as an asset based on squeeze price", function() { let order = new CallOrder(o, assets, "1.3.0", settlePrice_0); let toReceive = order.amountToReceive(); assert.equal(toReceive.getAmount(), 498820000, "Satoshi amount to receive should equal 498820000"); assert.equal(toReceive.getAmount({real: true}), 49882.0000, "Real amount for sale should equal 49882.0000"); }); it("Can be summed with another order", function() { let o1 = new CallOrder(o, assets, "1.3.0", settlePrice_0); let o2 = new CallOrder(o, assets, "1.3.0", settlePrice_0); const o3 = o1.sum(o2); assert.equal(o3.amountForSale().getAmount(), 188039049032*2, "The amount should equal 376078098064"); }); it("Can be compared to another order with equals / ne", function() { let o1 = new CallOrder(o, assets, "1.3.0", settlePrice_0); let o2 = new CallOrder(o, assets, "1.3.0", settlePrice_0); assert.equal(o1.ne(o2), false, "Orders are the same"); assert.equal(o1.equals(o2), true, "Orders are the same"); }); }); describe("Settle Order", function() { let base = { amount: 31, asset_id: "1.3.113" }; let quote = { amount: 10624, asset_id: "1.3.0" }; let settlePrice_0 = new FeedPrice({ priceObject: { base, quote }, market_base: "1.3.0", sqr: 1100, assets }); let settlePrice_113 = new FeedPrice({ priceObject: { base, quote }, market_base: "1.3.113", sqr: 1100, assets }); const so = { "id": "1.4.625", "owner":"1.2.117444", "balance": { "amount": 50000000, "asset_id": "1.3.113" }, "settlement_date": "2017-01-06T13:41:36" }; const so2 = { "id": "1.4.625", "owner":"1.2.117444", "balance": { "amount": 50000000, "asset_id": "1.3.113" }, "settlement_date": "2017-01-04T13:41:36" }; const bitasset_options = {force_settlement_offset_percent: 150}; it("Instantiates", function() { new SettleOrder(so, assets, "1.3.0", settlePrice_0, bitasset_options); }); it("Can be compared by date with isBefore", function() { let order = new SettleOrder(so, assets, "1.3.0", settlePrice_0, bitasset_options); let order2 = new SettleOrder(so2, assets, "1.3.0", settlePrice_0, bitasset_options); assert.equal(order.isBefore(order2), false, "Order 1 settles after order 2"); assert.equal(order2.isBefore(order), true, "Order 2 settles before order 1"); }); it("Returns the settle order price", function() { let order = new SettleOrder(so, assets, "1.3.0", settlePrice_0, bitasset_options); let order2 = new SettleOrder(so, assets, "1.3.113", settlePrice_113, bitasset_options); assert.equal(order.getPrice(), 0.02917922, "Price should be 0.02917922"); assert.equal(order2.getPrice(), 34.27096774, "Price should be 34.27096774"); }); it("Returns the amount for sale", function() { let order = new SettleOrder(so, assets, "1.3.113", settlePrice_113, bitasset_options); assert.equal(order.amountForSale().asset_id, "1.3.113", "Asset for sale should be 1.3.113"); assert.equal(order.amountForSale().getAmount(), 50000000, "Amount should be 50000000") assert.equal(order.amountForSale().getAmount({real: true}), 5000, "Amount should be 5000") }); it("Returns the amount to receive using offset percent", function() { let order = new SettleOrder(so, assets, "1.3.113", settlePrice_113, bitasset_options); assert.equal(order.amountToReceive().asset_id, "1.3.0", "Asset to receive should be 1.3.0"); assert.equal(order.amountToReceive().getAmount(), 16878451611, "Amount should be 16878451611") assert.equal(order.amountToReceive().getAmount({real: true}), 168784.51611, "Amount should be 168784.51611") }); it("Returns the order type", function() { let order = new SettleOrder(so, assets, "1.3.113", settlePrice_113, bitasset_options); let order2 = new SettleOrder(so, assets, "1.3.0", settlePrice_0, bitasset_options); assert.equal(order.isBid(), false, "Order is not a a bid"); assert.equal(order2.isBid(), true, "Order is a bid"); }) }); <file_sep>import alt from "alt-instance"; class DrawerActions { toggleDrawer(open = undefined) { return dispatch => dispatch(open) } } export default alt.createActions(DrawerActions);<file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import utils from "common/utils"; import WalletApi from "api/WalletApi"; import ApplicationApi from "api/ApplicationApi"; import WalletDb from "stores/WalletDb"; import { ChainStore } from "cybexjs"; import big from "bignumber.js"; class EoActions { demo() { return {demo:123}; } } export default alt.createActions(EoActions); <file_sep>import BaseStore from "./BaseStore"; import { List, Set, Map, fromJS } from "immutable"; import alt from "alt-instance"; import { Store } from "alt-instance"; import { EtoActions } from "actions/EtoActions"; import { debugGen } from "utils//Utils"; import AccountActions from "actions/AccountActions"; import ls from "lib/common/localStorage"; import { AbstractStore } from "./AbstractStore"; import { Eto, EtoProject } from "services/eto"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("EtoStore"); type UserInStatus = { [projectId: string]: EtoProject.UserInStatus; }; type UserProjectStatus = { [projectId: string]: EtoProject.UserProjectStatus; }; export type EtoState = Eto.EtoInfo & { loading: number; rank: null | Eto.Rank; projects: EtoProject.ProjectDetail[]; banners: EtoProject.Banner[]; userInSet: UserInStatus; userProjectStatus: UserProjectStatus; }; class EtoStore extends AbstractStore<EtoState> { state: EtoState = { state: Eto.EtoPersonalState.Uninit, info: null, sum: 0, loading: 0, rank: null, projects: [], banners: [], userInSet: {}, userProjectStatus: {} }; constructor() { super(); this.bindListeners({ reset: AccountActions.setCurrentAccount, handleAddLoading: EtoActions.addLoading, handleRemoveLoading: EtoActions.removeLoading, handleInfoUpdate: EtoActions.queryInfo, handleSurveyUpdate: EtoActions.putSurvey, handleApplyDone: EtoActions.setApplyDone, handleApplyLockImpl: EtoActions.applyLock, handleTokenUpdate: EtoActions.putToken, handleBasicUpdate: EtoActions.putBasic, handleRankUpdate: EtoActions.queryRank, handleBannerUpdate: EtoActions.updateBanner, handleProjectListUpdate: EtoActions.updateProjectList, handleProjectDetailUpdate: EtoActions.updateProject, handleUserProjectDetail: EtoActions.updateProjectByUser, handleUserIn: EtoActions.queryUserIn, handleProjectDetail: EtoActions.loadProjectDetail }); } handleRankUpdate(rank) { this.setState({ rank }); } reset() { this.setState({ state: Eto.EtoPersonalState.Uninit, info: null, sum: 0, loading: 0, userProjectStatus: {}, projects: [] }); } handleAddLoading(count) { this.setState({ loading: 1 }); } handleRemoveLoading(count) { this.setState({ loading: 0 }); } handleApplyDone() { console.debug("GetState: ", this, (this as any).getInstance().getState()); let state = { ...(this as any).getInstance().getState(), state: Eto.EtoPersonalState.Lock }; this.setState(state); } handleInfoUpdate(info: Eto.EtoInfo) { console.debug("Personal Info: ", info); this.setState({ ...(this as any).getInstance().getState(), ...info }); } handleApplyLockImpl(info) { console.debug("handleApplyLockImpl: ", info); } handleBasicUpdate(info: Eto.EtoInfo) { console.debug("Personal Info: ", info); this.setState({ ...(this as any).getInstance().getState(), ...info }); } handleTokenUpdate({ info, onResolve }: { info: Eto.EtoInfo; onResolve? }) { console.debug("Personal Info: ", info); this.setState({ ...(this as any).getInstance().getState(), ...info, state: (this as any).getInstance().getState().state }); if (onResolve) { setTimeout(onResolve, 500); } } handleSurveyUpdate(info: Eto.EtoInfo) { console.debug("Personal Info: ", info); info.state = Eto.EtoPersonalState.ApplyDone; this.setState({ ...(this as any).getInstance().getState(), ...info }); } handleBannerUpdate(banners: EtoProject.Banner[]) { this.setState({ banners }); } handleProjectListUpdate(projects: EtoProject.ProjectDetail[]) { let oldProjects = ((this as any).getInstance().getState() .projects as EtoProject.ProjectDetail[]) || []; let newProjects = projects.map(p => { let op = oldProjects.find(op => op.id === p.id); return op ? { ...op, ...p, current_percent: Math.max( Number(p.current_percent), Number(op.current_percent) ) } : p; }); this.setState({ projects: newProjects }); } handleProjectDetailUpdate(project: EtoProject.ProjectDetail) { let newProjects = ((this as any).getInstance().getState() .projects as EtoProject.ProjectDetail[]).map(oldP => project.id === oldP.id ? { ...oldP, ...project, current_percent: Math.max( Number(project.current_percent), Number(oldP.current_percent) ) } : oldP ); if (!newProjects.find(p => p.id === project.id)) { newProjects = [project]; } this.setState({ projects: newProjects }); } handleProjectDetail(project: EtoProject.ProjectDetail) { this.handleProjectDetailUpdate(project); } handleUserProjectDetail(project: EtoProject.ProjectDetail) { this.setState({ userProjectStatus: { ...((this as any).getInstance().getState() .userProjectStatus as UserProjectStatus), [project.id]: project } }); } handleUserIn(project: EtoProject.ProjectDetail) { this.setState({ userInSet: { ...((this as any).getInstance().getState().userInSet as UserInStatus), [project.id]: project } }); } } const StoreWrapper = alt.createStore(EtoStore, "EtoStore"); export { StoreWrapper as EtoStore }; export default StoreWrapper; <file_sep>import BaseStore from "./BaseStore"; import { List } from "immutable"; import alt from "alt-instance"; import CrowdFundActions from "actions/CrowdFundActions"; import { debugGen } from "utils//Utils"; const debug = debugGen("CrowdFundStore"); class CrowdFundStore extends BaseStore { bindListeners; setState; state = { allFunds: List(), initCrowds: [], partiCrowds: [] }; constructor() { super(); this.bindListeners({ onAllFundsFetched: CrowdFundActions.allFundsFetched, onAccountPartiFundsFetched: CrowdFundActions.accountPartiFundsFetched, onAccountInitFundsFetched: CrowdFundActions.accountInitFundsFetched, }); } onAllFundsFetched({ res, start, size }) { let allFunds = this.state.allFunds.take(start); allFunds = allFunds.concat(res); this.setState({ allFunds }); debug("onAllFundsFetched: ", this); } onAccountInitFundsFetched(initCrowds) { this.setState({ initCrowds }); debug("onAccountInitFundsFetched: ", this); } onAccountPartiFundsFetched(partiCrowds) { this.setState({ partiCrowds }); debug("onAccountPartiFundsFetched: ", this); } } export default alt.createStore(CrowdFundStore, "CrowdFundStore");<file_sep>var path = require("path"); var webpack = require("webpack"); var express = require("express"); var devMiddleware = require("webpack-dev-middleware"); var hotMiddleware = require("webpack-hot-middleware"); var feathers = require("feathers"); const https = require("https"); const fs = require("fs"); const compress = require("compression"); const expressproxy = require('express-http-proxy'); // let proxyUrl = 'http://ieo-apitest.nbltrust.com:3049/'; let proxyUrl = 'https://ieo-apitest.cybex.io/'; // https://ieo-apitest.nbltrust.com/api/cybex/projects?limit=4&offset=0 var ProgressPlugin = require("webpack/lib/ProgressPlugin"); var config = require("./config/webpack.dev.js"); var app = express(); app.use(compress()); app.use('/api/', expressproxy(proxyUrl, { proxyReqPathResolver: function(req,res) { return '/api' + require('url').parse(req.url).path; } })); var compiler = webpack(config); compiler.apply( new ProgressPlugin(function(percentage, msg) { process.stdout.write( (percentage * 100).toFixed(2) + "% " + msg + " \033[0G" ); }) ); app.use( devMiddleware(compiler, { publicPath: config.output.publicPath }) ); app.use(hotMiddleware(compiler)); app.use("*", function(req, res, next) { var filename = path.join(compiler.outputPath, "index.html"); compiler.outputFileSystem.readFile(filename, function(err, result) { if (err) { return next(err); } res.set("content-type", "text/html"); res.send(result); res.end(); }); }); app.listen(8080, function(err) { if (err) { return console.error(err); } console.log("Listening at http://localhost:8080/"); }); const options = { key: fs.readFileSync(path.resolve(__dirname, "ssl/private.pem")), cert: fs.readFileSync(path.resolve(__dirname, "ssl/cert.crt")) }; const httpsServer = https.createServer(options, app); httpsServer.listen(8081); // new WebpackDevServer(compiler, { // publicPath: config.output.publicPath, // hot: true, // historyApiFallback: true, // quiet: false, // stats: {colors: true}, // port: 8080 // }).listen(8080, '0.0.0.0', function (err, result) { // if (err) { // console.log(err); // } // console.log('Listening at 0.0.0.0:8080'); // }); <file_sep>### 投票 在Cybex系统中,投票是非常重要的一项特性,不仅事关网络安全,同时也能影响系统的后续开发方向。如果你愿意的话,你可以将你的投票权交由代理投票账户执行。如果你设定了代理投票账户,则手动投票将相应关闭。<file_sep>```html <Panel id="example-left-panel"> <Trigger close=""> <a className="close-button">&times;</a> </Trigger> Basic Left Panel content </Panel> ```<file_sep>const icons = { add: { base: require("./icons/ic_star.svg") }, star: { base: require("./icons/ic_star.svg") }, exchange: { base: require("./icons/ic_exchange.svg"), active: require("./icons/ic_exchange_active.svg") }, explorer: { base: require("./icons/ic_explorer.svg"), active: require("./icons/ic_explorer_active.svg") }, gateway: { base: require("./icons/ic_gateway.svg"), active: require("./icons/ic_gateway_active.svg") }, settings: { base: require("./icons/ic_settings.svg"), active: require("./icons/ic_settings_active.svg") }, faq: { base: require("./icons/ic_faq.svg"), active: require("./icons/ic_faq_active.svg") }, logout: { base: require("./icons/ic_logout.svg") }, refresh: { base: require("./icons/ic_refresh.png") }, back: { base: require("./icons/ic_back.png") }, checkbox: { base: require("./icons/ic_check_box.svg"), active: require("./icons/ic_check_box_active.svg"), master: require("./icons/ic_add_box_active.svg"), disabledAcitve: require("./icons/ic_check_box_active_disabled.svg") }, radio: { base: require("./icons/ic_radio.svg"), active: require("./icons/ic_radio_active.svg"), disabledAcitve: require("./icons/ic_radio_active_disabled.svg") }, help: { base: require("./icons/ic_help_outline.svg"), active: require("./icons/ic_help_outline_active.svg") }, lock: { base: require("./icons/ic_lock_outline.svg") }, book: { base: require("./icons/ic_book.png") }, lockWhite: { base: require("./icons/ic_info_outline_white.svg") }, info: { base: require("./icons/ic_info_outline_orange.svg") }, time: { base: require("./icons/ic_time.svg") }, avatarWhite: { base: require("./icons/ic_avatar_white.svg"), error: require("./icons/ic_avatar_red.svg") }, avatar: { base: require("./icons/ic_avatar_24px.svg"), error: require("./icons/ic_avatar_red.svg") }, visibility: { base: require("./icons/ic_visibility_on.svg"), off: require("./icons/ic_visibility_off.svg") }, cloudWallet: { base: require("./icons/Icon_Cloud_Wallet.svg") }, localWallet: { base: require("./icons/Icon_Local_Wallet.svg") }, singleAccount: { base: require("./icons/Icon_Single_Account.svg") }, polkaCheck: { base: require("./icons/polka_check.png") }, pokerHeart: { base: require("./icons/heart-normal.svg") }, pokerSpade: { base: require("./icons/spade-normal.svg") }, pokerDiamond: { base: require("./icons/diamond-normal.svg") }, pokerClub: { base: require("./icons/club-normal.svg") } }; export const getIcon = (icon, type = "base") => icons[icon] && icons[icon][type] ? icons[icon][type] : icons[icon] ? icons[icon]["base"] : icons["add"]["base"]; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import FormattedAsset from "../Utility/FormattedAsset"; import FormattedPrice from "../Utility/FormattedPrice"; import Translate from "react-translate-component"; import ChainTypes from "../Utility/ChainTypes"; import BindToChainState from "../Utility/BindToChainState"; import utils from "common/utils"; class MarketCard extends React.Component { static propTypes = { quote: ChainTypes.ChainAsset.isRequired, base: ChainTypes.ChainAsset.isRequired, core: ChainTypes.ChainAsset.isRequired }; static defaultProps = { core: "1.3.0" }; static contextTypes = { router: PropTypes.object.isRequired }; _onClick(marketID) { this.context.router.history.push(`/market/${marketID}`); } render() { let { quote, base } = this.props; if (!quote || !base) { return null; } let marketID = quote.get("symbol") + "_" + base.get("symbol"); let marketName = quote.get("symbol") + " : " + base.get("symbol"); let dynamic_data = quote.get("dynamic"); let base_dynamic_data = base.get("dynamic"); let price = utils.convertPrice(quote, base); return ( <div style={{ padding: "0.5em 0.5em" }} className="grid-content account-card" > <div className="card"> <div onClick={this._onClick.bind(this, marketID)}> <div style={{ padding: "5px" }} /> <div className="card-divider text-center info"> <span>{marketName}</span> </div> <div className="card-section"> <ul> <li> <Translate content="markets.core_rate" />:&nbsp; <FormattedPrice style={{ fontWeight: "bold" }} quote_amount={price.quoteAmount} quote_asset={quote.get("id")} base_amount={price.baseAmount} base_asset={base.get("id")} /> </li> <li> <Translate content="markets.supply" />:&nbsp; {dynamic_data ? ( <FormattedAsset style={{ fontWeight: "bold" }} amount={parseInt(dynamic_data.get("current_supply"), 10)} asset={quote.get("id")} /> ) : null} </li> <li> <Translate content="markets.supply" />:&nbsp; {base_dynamic_data ? ( <FormattedAsset style={{ fontWeight: "bold" }} amount={parseInt( base_dynamic_data.get("current_supply"), 10 )} asset={base.get("id")} /> ) : null} </li> </ul> </div> </div> <span style={{ marginBottom: "6px", marginRight: "6px", zIndex: 999 }} onClick={this.props.removeMarket} className="text float-right remove" > – </span> </div> </div> ); } } export default BindToChainState(MarketCard, { show_loader: true }); <file_sep>import ByteBuffer from "bytebuffer"; import EC from "./error_with_cause"; const HEX_DUMP = process.env.npm_config__graphene_serializer_hex_dump; class Serializer<T> { keys: string[] = []; static printDebug: boolean; constructor(public operation_name, public types?) { if (this.types) this.keys = Object.keys(types); Serializer.printDebug = true; } fromByteBuffer(b) { var object = {}; var field: any = null; try { var iterable = this.keys; for (var i = 0, field; i < iterable.length; i++) { field = iterable[i]; var type = this.types[field]; try { if (HEX_DUMP) { if (type.operation_name) { console.error(type.operation_name); } else { var o1 = b.offset; type.fromByteBuffer(b); var o2 = b.offset; b.offset = o1; //b.reset() var _b = b.copy(o1, o2); console.error(`${this.operation_name}.${field}\t`, _b.toHex()); } } object[field] = type.fromByteBuffer(b); } catch (e) { if (Serializer.printDebug) { console.error( `Error reading ${this.operation_name}.${field} in data:` ); b.printDebug(); } throw e; } } } catch (error) { EC.throw(this.operation_name + "." + field, error); } return object; } appendByteBuffer(b, object) { var field: any = null; try { var iterable = this.keys; for (var i = 0, field; i < iterable.length; i++) { field = iterable[i]; var type = this.types[field]; type.appendByteBuffer(b, object[field]); } } catch (error) { try { EC.throw( this.operation_name + "." + field + " = " + JSON.stringify(object[field]), error ); } catch (e) { // circular ref EC.throw( this.operation_name + "." + field + " = " + object[field], error ); } } return; } fromObject(serialized_object) { var result = {}; var field: any = null; try { var iterable = this.keys; for (var i = 0, field; i < iterable.length; i++) { field = iterable[i]; var type = this.types[field]; var value = serialized_object[field]; //DEBUG value = value.resolve if value.resolve //DEBUG console.log('... value',field,value) var object = type.fromObject(value); result[field] = object; } } catch (error) { EC.throw(this.operation_name + "." + field, error); } return result; } /** @arg {boolean} [debug.use_default = false] - more template friendly @arg {boolean} [debug.annotate = false] - add user-friendly information */ toObject( serialized_object = {}, debug = { use_default: false, annotate: false } ) { var result = {}; var field: any = null; try { if (!this.types) return result; var iterable = this.keys; for (var i = 0, field; i < iterable.length; i++) { field = iterable[i]; var type = this.types[field]; var object = type.toObject( typeof serialized_object !== "undefined" && serialized_object !== null ? serialized_object[field] : undefined, debug ); result[field] = object; if (HEX_DUMP) { var b = new ByteBuffer( ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN ); type.appendByteBuffer( b, typeof serialized_object !== "undefined" && serialized_object !== null ? serialized_object[field] : undefined ); b = b.copy(0, b.offset); console.error(this.operation_name + "." + field, b.toHex()); } } } catch (error) { EC.throw(this.operation_name + "." + field, error); } return result; } /** Sort by the first element in a operation */ compare(a, b) { let first_key = this.keys[0]; let first_type = this.types[first_key]; console.log("Compare: ", a, b, this.keys); let valA = a[first_key]; let valB = b[first_key]; if (first_type.compare) return first_type.compare(valA, valB); if (typeof valA === "number" && typeof valB === "number") return valA - valB; let encoding; if (Buffer.isBuffer(valA) && Buffer.isBuffer(valB)) { // A binary string compare does not work. If localeCompare is well supported that could replace HEX. Performanance is very good so comparing HEX works. encoding = "hex"; } let strA = valA.toString(encoding); let strB = valB.toString(encoding); return strA > strB ? 1 : strA < strB ? -1 : 0; } // <helper_functions> fromHex(hex) { var b = ByteBuffer.fromHex(hex, ByteBuffer.LITTLE_ENDIAN); return this.fromByteBuffer(b); } fromBuffer(buffer) { var b = ByteBuffer.fromBinary( buffer.toString("binary"), ByteBuffer.LITTLE_ENDIAN ); return this.fromByteBuffer(b); } toHex(object) { // return this.toBuffer(object).toString("hex") var b = this.toByteBuffer(object); return b.toHex(); } toByteBuffer(object) { var b = new ByteBuffer( ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN ); this.appendByteBuffer(b, object); return b.copy(0, b.offset); } toBuffer(object) { return new Buffer(this.toByteBuffer(object).toBinary(), "binary"); } } export default Serializer; <file_sep>import alt from "alt-instance"; import IntlActions from "actions/IntlActions"; import SettingsActions from "actions/SettingsActions"; import counterpart from "counterpart"; // var locale_en = require("assets/locales/locale-en.json"); var locale_cn = require("assets/locales/locale-zh.json"); import ls from "common/localStorage"; let ss = new ls("__graphene__"); counterpart.registerTranslations("zh", locale_cn); // counterpart.registerTranslations("en", locale_en); counterpart.setFallbackLocale("zh"); import { addLocaleData } from "react-intl"; import localeCodes from "assets/locales"; import { AbstractStore } from "./AbstractStore"; import * as en from "react-intl/locale-data/en"; import * as zh from "react-intl/locale-data/zh"; addLocaleData([...en, ...zh]); const langSet = { en: "en-US", zh: "zh-CN" // vn: "vi-VN" }; type Locale = { [lang: string]: string; }; const getLangFromNavi = () => navigator.language.toLocaleLowerCase().startsWith("zh") ? "zh" : "en"; class IntlStore extends AbstractStore<{ currentLocale }> { locales = [ "zh", "en" // , "vn" ]; localesObject: { [locale: string]: any } = { zh: locale_cn }; currentLocale; constructor() { super(); // 初始化默认语言 let currentLocale = (this.currentLocale = ss.has("settings_v3") ? ss.get("settings_v3").locale : getLangFromNavi()); this.switchLocale(currentLocale); this.bindListeners({ onSwitchLocale: IntlActions.switchLocale, onGetLocale: IntlActions.getLocale, onClearSettings: SettingsActions.clearSettings }); } hasLocale(locale) { return this.locales.indexOf(locale) !== -1; } getCurrentLocale() { return this.currentLocale; } onSwitchLocale({ locale, localeData }: { locale; localeData? }) { if (!this.localesObject[locale] && localeData) { this.localesObject[locale] = localeData; } switch (locale) { case "en": counterpart.registerTranslations("en", this.localesObject.en); break; case "zh": counterpart.registerTranslations("zh", this.localesObject.zh); break; // case "vn": // counterpart.registerTranslations("vn", this.localesObject.vn); // break; default: counterpart.registerTranslations(locale, localeData); break; } counterpart.setLocale(locale); this.currentLocale = locale; if (document) { document.documentElement.lang = langSet[locale]; } } switchLocale(locale: string) { if (locale in this.localesObject) { counterpart.registerTranslations(locale, this.localesObject[locale]); counterpart.setLocale(locale); this.currentLocale = locale; } } onGetLocale(locale) { if (this.locales.indexOf(locale) === -1) { this.locales.push(locale); } } onClearSettings() { this.onSwitchLocale({ locale: "zh" }); } } export default alt.createStore(IntlStore, "IntlStore"); <file_sep>import { Set } from "immutable"; import alt, { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; import { TradeHistoryActions } from "actions/TradeHistoryActions"; import { AbstractStore } from "./AbstractStore"; import { Map } from "immutable"; const MAX_SIZE = 600; type TradeHistoryState = { [marketPair: string]: Cybex.Trade[] }; class TradeHistoryStore extends AbstractStore<TradeHistoryState> { constructor() { super(); // console.debug("TradeHistory Store Constructor"); this.state = {}; this.bindListeners({ onHistoryPatched: TradeHistoryActions.onHistoryPatched }); // console.debug("TradeHistory Store Constructor Done"); } onHistoryPatched({ market, history }) { // // console.debug("TradeHistoryStore: ", market, this.state[market], history); let h = [ ...(this.state[market] || []), ...(history || []) ] as Cybex.Trade[]; this.setState({ [market]: h.slice(0, MAX_SIZE) }); // // console.debug("TradeHistoryStore Patched: ", this.state); } } const StoreWrapper: Store<TradeHistoryState> = alt.createStore( TradeHistoryStore, "TradeHistoryStore" ); export { StoreWrapper as TradeHistoryStore }; export default StoreWrapper; <file_sep>import { Set } from "immutable"; import alt from "alt-instance"; import { debugGen } from "utils//Utils"; import { LoadingActions } from "actions/LoadingActions"; import { AbstractStore } from "./AbstractStore"; const debug = debugGen("LoadingStore"); type LoadingState = { currentLoading: Set<any>; }; class LoadingStore extends AbstractStore<LoadingState> { constructor() { super(); this.state = { currentLoading: Set() }; this.bindListeners({ addLoadingId: LoadingActions.enterLoading, removeLoadingId: LoadingActions.quitLoading }); } addLoadingId(id: string) { this.setState({ currentLoading: this.state.currentLoading.add(id) }); } removeLoadingId(id: string) { this.setState({ currentLoading: this.state.currentLoading.remove(id) }); } resetLoadingSet() { this.setState({ currentLoading: Set() }); } } const StoreWrapper = alt.createStore(LoadingStore, "LoadingStore"); export { StoreWrapper as LoadingStore }; export default StoreWrapper; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import { Link } from "react-router-dom"; import ChainTypes from "../Utility/ChainTypes"; import BindToChainState from "../Utility/BindToChainState"; class LinkToAssetById extends React.Component { static propTypes = { asset: ChainTypes.ChainObject.isRequired }; render() { let symbol = this.props.asset.get("symbol"); return <Link to={`/asset/${symbol}/`}>{symbol}</Link>; } } export default BindToChainState(LinkToAssetById); <file_sep>export { Set } from "./set"; export { NotificationStatic as Static } from "./static"; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import BaseComponent from "../BaseComponent"; import { FormattedDate } from "react-intl"; import Immutable from "immutable"; import BlockchainActions from "actions/BlockchainActions"; import Transaction from "./Transaction"; import Translate from "react-translate-component"; import ChainTypes from "../Utility/ChainTypes"; import BindToChainState from "../Utility/BindToChainState"; import LinkToWitnessById from "../Utility/LinkToWitnessById"; class TransactionList extends React.Component { shouldComponentUpdate(nextProps) { return nextProps.block.id !== this.props.block.id; } render() { let { block } = this.props; let transactions = null; transactions = []; if (block.transactions.length > 0) { transactions = []; block.transactions.forEach((trx, index) => { transactions.push(<Transaction key={index} trx={trx} index={index} />); }); } return <div>{transactions}</div>; } } class Block extends BaseComponent { static propTypes = { dynGlobalObject: ChainTypes.ChainObject.isRequired, blocks: PropTypes.object.isRequired, height: PropTypes.number.isRequired }; static defaultProps = { dynGlobalObject: "2.1.0", blocks: {}, height: 1 }; constructor(props) { super(props); this._bind("_previousBlock", "_nextBlock"); } shouldComponentUpdate(nextProps) { return ( !Immutable.is(nextProps.blocks, this.props.blocks) || nextProps.height !== this.props.height || nextProps.dynGlobalObject !== this.props.dynGlobalObject ); } _getBlock(height) { if (height) { height = parseInt(height, 10); if (!this.props.blocks.get(height)) { BlockchainActions.getBlock(height); } } } componentWillReceiveProps(nextProps) { if (nextProps.height !== this.props.height) { this._getBlock(nextProps.height); } } _nextBlock() { let height = this.props.match.params.height; let nextBlock = Math.min( this.props.dynGlobalObject.get("head_block_number"), parseInt(height, 10) + 1 ); this.props.history.push(`/block/${nextBlock}`); } _previousBlock() { let height = this.props.match.params.height; let previousBlock = Math.max(1, parseInt(height, 10) - 1); this.props.history.push(`/block/${previousBlock}`); } componentDidMount() { this._getBlock(this.props.height); } render() { let { blocks } = this.props; let height = parseInt(this.props.height, 10); let block = blocks.get(height); // console.debug("Block Height: ", block); return ( <div className="grid-block"> <div className="grid-content"> <div className="grid-content no-overflow medium-offset-2 medium-8 large-offset-3 large-6 small-12"> <h4 className="text-center"> <Translate style={{ textTransform: "uppercase" }} component="span" content="explorer.block.title" />{" "} #{height} </h4> <ul> <li> <Translate component="span" content="explorer.block.date" />:{" "} {block ? ( <FormattedDate value={block.timestamp} format="full" /> ) : null} </li> <li> <Translate component="span" content="explorer.block.witness" />:{" "} {block ? <LinkToWitnessById witness={block.witness} /> : null} </li> <li> <Translate component="span" content="explorer.block.previous" />:{" "} {block ? block.previous : null} </li> <li> <Translate component="span" content="explorer.block.transactions" />: {block ? block.transactions.length : null} </li> </ul> <div className="clearfix" style={{ marginBottom: "1rem" }}> <div className="button float-left outline" onClick={this._previousBlock.bind(this)} > &#8592; </div> <div className="button float-right outline" onClick={this._nextBlock.bind(this)} > &#8594; </div> </div> {block ? <TransactionList block={block} /> : null} </div> </div> </div> ); } } export default BindToChainState(Block, { keep_updating: true }); <file_sep>All development happens on GitHub. When [creating a pull request](https://help.github.com/articles/creating-a-pull-request/), please make sure that all of the following apply: - The tests pass. The test suite will automatically run when you create the PR. All you need to do is wait a few minutes to see the result in the PR. - Each commit in your PR should describe a significant piece of work. Work that was done in one commit and then undone later should be squashed into a single commit. Also, please make sure the CHANGELOG.md document contains a short note about the nature of your change. Just follow the format of the existing entries in that document. If the most recent entry is a release, please start a new section under a `## HEAD` heading. Thank you for your contribution! <file_sep>[见证人](introduction/witness) 是Cybex系统中区块的生产者。他们验证交易数据并维护网络安全。你可以投票选举你信任的人成为见证人。投票时,你选择的候选人将获得你投出的相同票数。见证人的竞选帖可在这里找到[Cybextalk - Stakeholder Proposals Board](https://Cybextalk.org/index.php/board,75.0.html)。 <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import SettingsStore from "stores/SettingsStore"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; import { getDepositInfo, getWithdrawInfo, queryFundRecords as queryFundRecordsImpl, loginQuery as loginQueryImpl } from "services//GatewayService"; import { NotificationActions } from "actions//NotificationActions"; import { JadePool } from "services/GatewayConfig"; import { ops, PrivateKey, Signature } from "cybexjs"; import { Map } from "immutable"; import { CustomTx } from "CustomTx"; const debug = debugGen("GatewayActions"); export const DEPOSIT_MODAL_ID = "DEPOSIT_MODAL_ID"; export const WITHDRAW_MODAL_ID = "WITHDRAW_MODAL_ID"; const pickKeys = (keys: string[], count = 1) => { let res: any[] = []; for (let key of keys) { let privKey = WalletDb.getPrivateKey(key); if (privKey) { res.push(privKey); if (res.length >= count) { break; } } } return res; }; class GatewayActions { async showDepositModal(account, asset, modalId = DEPOSIT_MODAL_ID) { let type = JadePool.ADDRESS_TYPES[asset] && JadePool.ADDRESS_TYPES[asset].type; if (!type) { return NotificationActions.error( `No suitable asset for ${asset} to be deposited` ); } let valid = await this.updateDepositAddress(account, type); if (!valid) return; this.openModal(modalId); } async showWithdrawModal(asset) { debug("Withdraw: ", asset); let type = JadePool.ADDRESS_TYPES[asset] && JadePool.ADDRESS_TYPES[asset].type; if (!type) { return NotificationActions.error( `No suitable asset for ${asset} to be withdrawn` ); } let valid = await this.updateWithdrawInfo(asset, type); if (!valid) return; this.openModal(WITHDRAW_MODAL_ID); } async updateDepositAddress(account, type, needNew = false) { let res; debug("Update Deposit Address: ", account, type, needNew); try { let { address } = (res = await getDepositInfo(account, type, needNew)); debug("Address: ", address); // NotificationActions.info(address); } catch (e) { debug(e); NotificationActions.error(e.message); return false; } this.afterUpdateDepositInfo(res); return res; } async updateWithdrawInfo(asset, type) { let res; try { res = await getWithdrawInfo(type); debug("WithdrawLimit: ", res); // NotificationActions.info(res.fee.toString()); } catch (e) { debug(e); NotificationActions.error(e.message); return false; } this.afterUpdateWithdrawInfo({ asset, ...res }); return true; } async queryFundRecords( account: Map<string, any>, login, offset = 0, size = 200 ) { debug("[QueryFundRecord]", account); const tx = new CustomTx({ accountName: account.get("name"), offset, size }); // let { login } = GatewayStore.getState(); if (login.accountName === account.get("name") && login.signer) { tx.addSigner(login.signer); } // 尝试获取记录 let records = await queryFundRecordsImpl(tx); // 如果获取不成功,重新登录并再次尝试获取 if (!records) { let { signer } = await this.loginGatewayQuery(account); tx.addSigner(signer); records = await queryFundRecordsImpl(tx); } // 如果最终获取,更新记录 if (records) { this.updateFundRecords(records); } } updateFundRecords(records) { return records; } /** * 注册一个查询签名 * * @param {Map<string, any>} account * @memberof GatewayActions */ async loginGatewayQuery(account: Map<string, any>) { debug("[LoginGatewayQuery]", account); debug("[LoginGatewayQuery]", SettingsStore.getSetting("walletLockTimeout")); const tx = new CustomTx({ accountName: account.get("name"), expiration: Date.now() + SettingsStore.getSetting("walletLockTimeout") * 1000 }); const op = ops.fund_query.fromObject(tx.op); // Pick approps key let weight_threshold = account.getIn(["active", "weight_threshold"]); let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS(); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } debug( "[LoginGatewayQuery privKey]", account.getIn(["options", "memo_key"]), privKey ); // let privKey = PrivateKey.fromWif(privKeyWif); let buffer = ops.fund_query.toBuffer(op); let signedHex = Signature.signBuffer(buffer, privKey).toHex(); debug("[LoginGatewayQuery Signed]", signedHex); // tx.addSigner(1); tx.addSigner(signedHex); let loginRes = await loginQueryImpl(tx); debug("[LoginGatewayQuery LoginRes]", loginRes); if (loginRes) { this.updateLogin(loginRes); } return loginRes; } updateLogin(loginRes) { return loginRes; } afterUpdateWithdrawInfo(limit: { asset; type; fee; minValue }) { // for mock return limit; } afterUpdateDepositInfo(depositInfo) { return depositInfo; } closeModal(modalId) { return modalId; } openModal(modalId) { return modalId; } } const GatewayActionsWrapped: GatewayActions = alt.createActions(GatewayActions); export { GatewayActionsWrapped as GatewayActions }; export default GatewayActionsWrapped; <file_sep>var React = require("react"); var Modal = require("../../lib/modal"); var Trigger = require("../../lib/trigger"); var SimpleModal = React.createClass({ render: function() { return ( <div> <Trigger open="basicModal"> <a className="button">Open Modal</a> </Trigger> <Modal id="basicModal" overlay={true}> <Trigger close=""> <a href="#" className="close-button"> &times; </a> </Trigger> <section className="grid-content"> <p> This is modal content </p> </section> </Modal> </div> ); } }); module.exports = SimpleModal; <file_sep>import createClass from "create-react-class"; import * as PropTypes from "prop-types"; import * as React from "react"; React.createClass = createClass; React.PropTypes = PropTypes; require("./assets/loader"); if (!window.Intl) { // Safari polyfill require.ensure(["intl"], require => { window.Intl = require("intl"); Intl.__addLocaleData(require("./assets/intl-data/en.json")); require("index.js"); }); } else { require("index.js"); } <file_sep>'use strict'; var dateNames = require('date-names'); function strftime(date, format, names) { var timestamp = date.getTime(); names = names || dateNames; return format.replace(/%([-_0]?.)/g, function(_, c) { var padding = null; if (c.length == 2) { switch (c[0]) { case '-': padding = ''; break; case '_': padding = ' '; break; case '0': padding = '0'; break; default: return _; // should never reach this one } c = c[1]; } switch (c) { case 'A': return names.days[date.getDay()]; case 'a': return names.abbreviated_days[date.getDay()]; case 'B': return names.months[date.getMonth()]; case 'b': return names.abbreviated_months[date.getMonth()]; case 'C': return pad(Math.floor(date.getFullYear() / 100), padding); case 'D': return strftime(date, '%m/%d/%y'); case 'd': return pad(date.getDate(), padding); case 'e': return date.getDate(); case 'F': return strftime(date, '%Y-%m-%d'); case 'H': return pad(date.getHours(), padding); case 'h': return names.abbreviated_months[date.getMonth()]; case 'I': return pad(hours12(date), padding); case 'j': return pad(Math.ceil((date.getTime() - (new Date(date.getFullYear(), 0, 1)).getTime()) / (1000 * 60 * 60 * 24)), 3); case 'k': return pad(date.getHours(), padding === null ? ' ' : padding); case 'L': return pad(Math.floor(timestamp % 1000), 3); case 'l': return pad(hours12(date), padding === null ? ' ' : padding); case 'M': return pad(date.getMinutes(), padding); case 'm': return pad(date.getMonth() + 1, padding); case 'n': return '\n'; case 'o': return String(date.getDate()) + ordinal(date.getDate()); case 'P': return date.getHours() < 12 ? names.am.toLowerCase() : names.pm.toLowerCase(); case 'p': return date.getHours() < 12 ? names.am.toUpperCase() : names.pm.toUpperCase(); case 'R': return strftime(date, '%H:%M'); case 'r': return strftime(date, '%I:%M:%S %p'); case 'S': return pad(date.getSeconds(), padding); case 's': return Math.floor(timestamp / 1000); case 'T': return strftime(date, '%H:%M:%S'); case 't': return '\t'; case 'U': return pad(weekNumber(date, 'sunday'), padding); case 'u': return date.getDay() === 0 ? 7 : date.getDay(); case 'v': return strftime(date, '%e-%b-%Y'); case 'W': return pad(weekNumber(date, 'monday'), padding); case 'w': return date.getDay(); case 'Y': return date.getFullYear(); case 'y': var y = String(date.getFullYear()); return y.slice(y.length - 2); case 'Z': var tzString = date.toString().match(/\((\w+)\)/); return tzString && tzString[1] || ''; case 'z': var off = date.getTimezoneOffset(); return (off > 0 ? '-' : '+') + pad(Math.round(Math.abs(off / 60)), 2) + ':' + pad(off % 60, 2); default: return c; } }); } function pad(n, padding, length) { if (typeof padding === 'number') { length = padding; padding = '0'; } if (padding === null) { padding = '0'; } length = length || 2; var s = String(n); if (padding) { while (s.length < length) { s = padding + s; } } return s; } function hours12(date) { var hour = date.getHours(); if (hour === 0) { hour = 12; } else if (hour > 12) { hour -= 12; } return hour; } function ordinal(n) { var i = n % 10, ii = n % 100; if ((ii >= 11 && ii <= 13) || i === 0 || i >= 4) { return 'th'; } switch (i) { case 1: return 'st'; case 2: return 'nd'; case 3: return 'rd'; } } function weekNumber(date, firstWeekday) { firstWeekday = firstWeekday || 'sunday'; var wday = date.getDay(); if (firstWeekday == 'monday') { if (wday === 0) { // Sunday wday = 6; } else { wday--; } } var firstDayOfYear = new Date(date.getFullYear(), 0, 1), yday = (date - firstDayOfYear) / 86400000, weekNum = (yday + 7 - wday) / 7; return Math.floor(weekNum); } module.exports = strftime; <file_sep>import ls from "./localStorage"; import {blockTradesAPIs} from "api/apiConfig"; const blockTradesStorage = new ls(""); export function fetchCoins(url = (blockTradesAPIs.BASE_OL + blockTradesAPIs.COINS_LIST)) { return fetch(url).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching blocktrades list of coins", err, url); }); } export function fetchCoinsSimple(url = (blockTradesAPIs.BASE_OL + blockTradesAPIs.COINS_LIST)) { return fetch(url).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching simple list of coins", err, url); }); } export function fetchBridgeCoins(baseurl = (blockTradesAPIs.BASE)) { let url = baseurl + blockTradesAPIs.TRADING_PAIRS; return fetch(url, {method: "get", headers: new Headers({"Accept": "application/json"})}).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching blocktrades list of coins", err, url); }); } export function getDepositLimit(inputCoin, outputCoin, url = (blockTradesAPIs.BASE + blockTradesAPIs.DEPOSIT_LIMIT)) { return fetch(url + "?inputCoinType=" + encodeURIComponent(inputCoin) + "&outputCoinType=" + encodeURIComponent(outputCoin), {method: "get", headers: new Headers({"Accept": "application/json"})}).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching deposit limit of", inputCoin, outputCoin, err); }); } export function estimateOutput(inputAmount, inputCoin, outputCoin, url = (blockTradesAPIs.BASE + blockTradesAPIs.ESTIMATE_OUTPUT)) { return fetch(url + "?inputAmount=" + encodeURIComponent(inputAmount) +"&inputCoinType=" + encodeURIComponent(inputCoin) + "&outputCoinType=" + encodeURIComponent(outputCoin), {method: "get", headers: new Headers({"Accept": "application/json"})}).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching deposit limit of", inputCoin, outputCoin, err); }); } export function estimateInput(outputAmount, inputCoin, outputCoin, url = (blockTradesAPIs.BASE + blockTradesAPIs.ESTIMATE_INPUT)) { return fetch(url + "?outputAmount=" + encodeURIComponent(outputAmount) +"&inputCoinType=" + encodeURIComponent(inputCoin) + "&outputCoinType=" + encodeURIComponent(outputCoin), { method: "get", headers: new Headers({"Accept": "application/json"})}).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching deposit limit of", inputCoin, outputCoin, err); }); } export function getActiveWallets(url = (blockTradesAPIs.BASE_OL + blockTradesAPIs.ACTIVE_WALLETS)) { return fetch(url).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching blocktrades active wallets", err, url); }); } let depositRequests = {}; export function requestDepositAddress({inputCoinType, outputCoinType, outputAddress, url = blockTradesAPIs.BASE_OL, stateCallback}) { let body = { inputCoinType, outputCoinType, outputAddress }; let body_string = JSON.stringify(body); if (depositRequests[body_string]) return; depositRequests[body_string] = true; fetch( url + "/simple-api/initiate-trade", { method:"post", headers: new Headers( { "Accept": "application/json", "Content-Type":"application/json" } ), body: body_string }).then( reply => { reply.json() .then( json => { delete depositRequests[body_string]; // console.log( "reply: ", json ) let address = {"address": json.inputAddress || "unknown", "memo": json.inputMemo, error: json.error || null}; if (stateCallback) stateCallback(address); }, error => { // console.log( "error: ",error ); delete depositRequests[body_string]; if (stateCallback) stateCallback(null); }); }, error => { // console.log( "error: ",error ); delete depositRequests[body_string]; if (stateCallback) stateCallback(null); }).catch(err => { console.log("fetch error:", err); delete depositRequests[body_string]; }); } export function getBackedCoins({allCoins, tradingPairs, backer}) { let coins_by_type = {}; allCoins.forEach(coin_type => coins_by_type[coin_type.coinType] = coin_type); let allowed_outputs_by_input = {}; tradingPairs.forEach(pair => { if (!allowed_outputs_by_input[pair.inputCoinType]) allowed_outputs_by_input[pair.inputCoinType] = {}; allowed_outputs_by_input[pair.inputCoinType][pair.outputCoinType] = true; }); let blocktradesBackedCoins = []; allCoins.forEach(coin_type => { if (coin_type.walletSymbol.startsWith(backer + ".") && coin_type.backingCoinType && coins_by_type[coin_type.backingCoinType]) { let isDepositAllowed = allowed_outputs_by_input[coin_type.backingCoinType] && allowed_outputs_by_input[coin_type.backingCoinType][coin_type.coinType]; let isWithdrawalAllowed = allowed_outputs_by_input[coin_type.coinType] && allowed_outputs_by_input[coin_type.coinType][coin_type.backingCoinType]; blocktradesBackedCoins.push({ name: coins_by_type[coin_type.backingCoinType].name, intermediateAccount: coins_by_type[coin_type.backingCoinType].intermediateAccount, gateFee: coins_by_type[coin_type.backingCoinType].gateFee, walletType: coins_by_type[coin_type.backingCoinType].walletType, backingCoinType: coins_by_type[coin_type.backingCoinType].walletSymbol, symbol: coin_type.walletSymbol, supportsMemos: coins_by_type[coin_type.backingCoinType].supportsOutputMemos, depositAllowed: isDepositAllowed, withdrawalAllowed: isWithdrawalAllowed }); }}); return blocktradesBackedCoins; } export function validateAddress({url = blockTradesAPIs.BASE, walletType, newAddress}) { if (!newAddress) return new Promise((res) => res()); return fetch( url + "/wallets/" + walletType + "/address-validator?address=" + encodeURIComponent(newAddress), { method: "get", headers: new Headers({"Accept": "application/json"}) }).then(reply => reply.json().then( json => json.isValid)) .catch(err => { console.log("validate error:", err); }); } let _conversionCache = {}; export function getConversionJson(inputs) { const { input_coin_type, output_coin_type, url, account_name } = inputs; if (!input_coin_type || !output_coin_type) return Promise.reject(); const body = JSON.stringify({ inputCoinType: input_coin_type, outputCoinType: output_coin_type, outputAddress: account_name, inputMemo: "blocktrades conversion: " + input_coin_type + "to" + output_coin_type }); const _cacheString = url + input_coin_type + output_coin_type + account_name; return new Promise((resolve, reject) => { if (_conversionCache[_cacheString]) return resolve(_conversionCache[_cacheString]); fetch(url + "/simple-api/initiate-trade", { method:"post", headers: new Headers({"Accept": "application/json", "Content-Type": "application/json"}), body: body }).then(reply => { reply.json() .then( json => { _conversionCache[_cacheString] = json; resolve(json); }, reject) .catch(reject); }).catch(reject); }); } function hasWithdrawalAddress(wallet) { return blockTradesStorage.has(`history_address_${wallet}`); } function setWithdrawalAddresses({wallet, addresses}) { blockTradesStorage.set(`history_address_${wallet}`, addresses); } function getWithdrawalAddresses(wallet) { return blockTradesStorage.get(`history_address_${wallet}`, []); } function setLastWithdrawalAddress({wallet, address}) { blockTradesStorage.set(`history_address_last_${wallet}`, address); } function getLastWithdrawalAddress(wallet) { return blockTradesStorage.get(`history_address_last_${wallet}`, ""); } export const WithdrawAddresses = { has: hasWithdrawalAddress, set: setWithdrawalAddresses, get: getWithdrawalAddresses, setLast: setLastWithdrawalAddress, getLast: getLastWithdrawalAddress }; <file_sep>var React = require("react"); var foundationApi = require("../utils/foundation-api"); var PopupToggle = React.createClass({ clickHandler: function(id, e) { e.preventDefault(); foundationApi.publish(this.props.popupToggle, ["toggle", id]); }, render: function() { var child = React.Children.only(this.props.children); var id = this.props.id || foundationApi.generateUuid(); return React.cloneElement(child, { id: id, onClick: this.clickHandler.bind(this, id) }); } }); module.exports = PopupToggle; <file_sep>```html <ActionSheet> <ActionSheet.Button title="Action Sheet" /> <ActionSheet.Content> <p>Tap to share</p> <ul> <li><a href="#">Twitter</a></li> <li><a href="#">Facebook</a></li> <li><a href="#">Mail</a></li> </ul> </ActionSheet.Content> </ActionSheet> ```<file_sep>[预算项目](introduction/workers) 是Cybex系统中独有的概念。他们是一些期望通过提供服务来从区块链获得奖金的工作项目提案。一项提案包含一个指向网站或论坛帖子的链接,在其中详细解释了工作项目的介绍。在这里[Cybextalk - Stakeholder Proposals Board](https://Cybextalk.org/index.php/board,75.0.html)可以看到一些提案。 <file_sep>declare module "cybexjs-ws" { class GrapheneApi { constructor(ws_rpc, api_name); init(): Promise<any>; exec(method: any, params: any): Promise<any>; } class ApisInstance { connect(): void; close(): void; db_api(): GrapheneApi; history_api(): GrapheneApi; network_api(): GrapheneApi; crypto_api(): GrapheneApi; init_promise: Promise<any>; chain_id?: string; setRpcConnectionStatusCallback(handler: (status: any) => any): void; } const Apis: { setRpcConnectionStatusCallback(handler: (status: any) => any): void; instance( cs?: string, connect?: boolean, connectTimeout?: number, enableCrypto?: boolean ): ApisInstance; close: Promise<any>; reset: Promise<any>; setAutoReconnect(auto: boolean): void; }; const ChainConfig: { core_asset: string; address_prefix: string; expire_in_secs: number; expire_in_secs_proposal: number; review_in_secs_committee: number; networks: any; setChainId(chainID: string): { network_name: string; network: any } | void; reset(): void; setProposalExpire(time: number): number; setPrefix(address: string): string; }; } <file_sep>/** * 排列属性 */ export const arrangeProperties = { //列数 maxColumns: 5, //间距(像素) spacing: 10, //最后一列属性 finalColumns: null, //父级容器宽度 parentWidth: null, //机器人父级容器高度 containerHeight:0, //列宽 columnsWidth: null, //可视区域高度 160为默认值 windowViewHeight: 0, //left 值 locationLeft: null, //请求图片数量 requestImgNum:40 } /** * 机器人、队列属性 */ export const robot = { /** * key 屏幕下标 * value 元素队列 */ locationInfo: { ['0']: [] }, /** * 机器人的top位置,每次排列一排之后完成后,根据这一排的信息获取下一排的top * null为初始状态,根据父级组件完成渲染后而改变 */ robotTopLocation: null } /** * 屏幕属性 */ export const screen = { //屏幕总数量 个数 allNum: 1, //当前第几屏幕 下标 numIng: 0, //上一次所在屏幕 下标 oldNum: 0, //当前加载的屏幕队 loadingScreen: [0] }; <file_sep>export interface Result { code: number; data?: any; error?: string; } export interface LoginBody { accountName: string; signer: string; } export interface FundRecordRes { total: number; records: FundRecordEntry[]; offset: number; size: number; } export type FundRecordEntry = { accountName: string; address: string; amount: number; asset: string; coinType: string; fee: number; fundType: string; state: string; hash?: string; updateAt: string; details: FundRecordDetail[]; }; export type FundRecordDetail = { bizType: "WITHDRAW" | "DEPOSIT"; coinType: string; confirmations: number; create_at: number; data: {}; extraData: any; fee: string; from: string; hash: string; id: string; sendAgain: boolean; state: string; to: string; update_at: number; value: string; }; export class QueryResult implements Result { constructor(public data: FundRecordRes, public code = 200) {} } export class LoginResult implements Result { constructor(public data: LoginBody, public code = 200) {} } <file_sep>```html <Interchange> <img media="small" src="/img/small.jpg" /> <img media="medium" src="/img/medium.jpg" /> <img media="large" src="/img/large.jpg" /> </Interchange> ``` <file_sep>import alt from "alt-instance"; class LoadingActions { enterLoading(loadingId) { return loadingId; } quitLoading(loadingId) { return loadingId; } } const LoadingActionsWrapped: LoadingActions = alt.createActions(LoadingActions); export { LoadingActionsWrapped as LoadingActions }; export default LoadingActionsWrapped; <file_sep>import * as React from "react"; import Animation from "../utils/animation"; var classnames = require("classnames"); var foundationApi = require("../utils/foundation-api"); var Panel = React.createClass({ getInitialState: function() { return { open: false }; }, getDefaultProps: function() { return { position: "left" }; }, componentDidMount: function() { foundationApi.subscribe( this.props.id, function(name, msg) { if (msg === "open") { this.setState({ open: true }); } else if (msg === "close") { this.setState({ open: false }); } else if (msg === "toggle") { this.setState({ open: !this.state.open }); } }.bind(this) ); }, componentWillUnmount: function() { foundationApi.unsubscribe(this.props.id); }, render: function() { var animationIn, animationOut; var classes = "panel panel-" + this.props.position; if (this.props.className) { classes += " " + this.props.className; } if (this.props.position === "left") { animationIn = this.props.animationIn || "slideInRight"; animationOut = this.props.animationOut || "slideOutLeft"; } else if (this.props.position === "right") { animationIn = this.props.animationIn || "slideInLeft"; animationOut = this.props.animationOut || "slideOutRight"; } else if (this.props.position === "top") { animationIn = this.props.animationIn || "slideInDown"; animationOut = this.props.animationOut || "slideOutUp"; } else if (this.props.position === "bottom") { animationIn = this.props.animationIn || "slideInUp"; animationOut = this.props.animationOut || "slideOutBottom"; } return ( <Animation active={this.state.open} animationIn={animationIn} animationOut={animationOut} > <div data-closable={true} id={this.props.id} className={classes}> {this.props.children} </div> </Animation> ); } }); // module.exports = Panel; export default Panel; export { Panel }; <file_sep>// The translations in this file are added by default. 'use strict'; module.exports = { counterpart: { names: require('date-names/en'), pluralize: require('pluralizers/en'), formats: { date: { 'default': '%a, %e %b %Y', long: '%A, %B %o, %Y', short: '%b %e' }, time: { 'default': '%H:%M', long: '%H:%M:%S %z', short: '%H:%M' }, datetime: { 'default': '%a, %e %b %Y %H:%M', long: '%A, %B %o, %Y %H:%M:%S %z', short: '%e %b %H:%M' } } } }; <file_sep>import createHash from "create-hash"; import createHmac from "create-hmac"; /** @arg {string|Buffer} data @arg {string} [digest = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when digest is null, or string */ function sha1(data, encoding?) { return createHash("sha1") .update(data) .digest(encoding); } /** @arg {string|Buffer} data @arg {string} [digest = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when digest is null, or string */ function sha256(data, encoding?) { return createHash("sha256") .update(data) .digest(encoding); } /** @arg {string|Buffer} data @arg {string} [digest = null] - 'hex', 'binary' or 'base64' @return {string|Buffer} - Buffer when digest is null, or string */ function sha512(data, encoding?) { return createHash("sha512") .update(data) .digest(encoding); } function HmacSHA256(buffer, secret) { return createHmac("sha256", secret) .update(buffer) .digest(); } function ripemd160(data) { return createHash("rmd160") .update(data) .digest(); } // function hash160(buffer) { // return ripemd160(sha256(buffer)) // } // // function hash256(buffer) { // return sha256(sha256(buffer)) // } // // function HmacSHA512(buffer, secret) { // return crypto.createHmac('sha512', secret).update(buffer).digest() // } export { sha1, sha256, sha512, HmacSHA256, ripemd160 }; <file_sep>'use strict'; var SPACE = ' '; var RE_CLASS = /[\n\t\r]/g; var norm = function (elemClass) { return (SPACE + elemClass + SPACE).replace(RE_CLASS, SPACE); }; module.exports = { addClass(elem, className) { elem.className += ' ' + className; }, removeClass(elem, needle) { var elemClass = elem.className.trim(); var className = norm(elemClass); needle = needle.trim(); needle = SPACE + needle + SPACE; while (className.indexOf(needle) >= 0) { className = className.replace(needle, SPACE); } elem.className = className.trim(); } };<file_sep>```html <Trigger open="basicModal"> <a className="button">Open Modal</a> </Trigger> <Modal id="basicModal" overlay={true}> <Trigger close=""> <a href="#" className="close-button">&times;</a> </Trigger> <section className="grid-content"> <p> This is modal content </p> </section> </Modal> ``` <file_sep>'use strict'; var extend = require('extend'); var isArray = require('util').isArray; var isDate = require('util').isDate; var sprintf = require("sprintf-js").sprintf; var events = require('events'); var except = require('except'); var strftime = require('./strftime'); var translationScope = 'counterpart'; function isString(val) { return typeof val === 'string' || Object.prototype.toString.call(val) === '[object String]'; } function isFunction(val) { return typeof val === 'function' || Object.prototype.toString.call(val) === '[object Function]'; } function isPlainObject(val) { //Deal with older browsers (IE8) that don't return [object Null] in this case. if (val === null) { return false; } return Object.prototype.toString.call(val) === '[object Object]'; } function isSymbol(key) { return isString(key) && key[0] === ':'; } function hasOwnProp(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function getEntry(translations, keys) { return keys.reduce(function(result, key) { if (isPlainObject(result) && hasOwnProp(result, key)) { return result[key]; } else { return null; } }, translations); } function Counterpart() { this._registry = { locale: 'en', interpolate: true, fallbackLocales: [], scope: null, translations: {}, interpolations: {}, normalizedKeys: {}, separator: '.', keepTrailingDot: false, keyTransformer: function(key) { return key; } }; this.registerTranslations('en', require('./locales/en')); this.setMaxListeners(0); } extend(Counterpart.prototype, events.EventEmitter.prototype); Counterpart.prototype.getLocale = function() { return this._registry.locale; }; Counterpart.prototype.setLocale = function(value) { var previous = this._registry.locale; if (previous != value) { this._registry.locale = value; this.emit('localechange', value, previous); } return previous; }; Counterpart.prototype.getFallbackLocale = function() { return this._registry.fallbackLocales; }; Counterpart.prototype.setFallbackLocale = function(value) { var previous = this._registry.fallbackLocales; this._registry.fallbackLocales = [].concat(value || []); return previous; }; Counterpart.prototype.getAvailableLocales = function() { return this._registry.availableLocales || Object.keys(this._registry.translations); }; Counterpart.prototype.setAvailableLocales = function(value) { var previous = this.getAvailableLocales(); this._registry.availableLocales = value; return previous; }; Counterpart.prototype.getSeparator = function() { return this._registry.separator; }; Counterpart.prototype.setSeparator = function(value) { var previous = this._registry.separator; this._registry.separator = value; return previous; }; Counterpart.prototype.setInterpolate = function(value) { var previous = this._registry.interpolate; this._registry.interpolate = value; return previous; }; Counterpart.prototype.getInterpolate = function() { return this._registry.interpolate; }; Counterpart.prototype.setKeyTransformer = function(value) { var previous = this._registry.keyTransformer; this._registry.keyTransformer = value; return previous; }; Counterpart.prototype.getKeyTransformer = function() { return this._registry.keyTransformer; }; Counterpart.prototype.registerTranslations = function(locale, data) { var translations = {}; translations[locale] = data; extend(true, this._registry.translations, translations); return translations; }; Counterpart.prototype.registerInterpolations = function(data) { return extend(true, this._registry.interpolations, data); }; Counterpart.prototype.onLocaleChange = Counterpart.prototype.addLocaleChangeListener = function(callback) { this.addListener('localechange', callback); }; Counterpart.prototype.offLocaleChange = Counterpart.prototype.removeLocaleChangeListener = function(callback) { this.removeListener('localechange', callback); }; Counterpart.prototype.onTranslationNotFound = Counterpart.prototype.addTranslationNotFoundListener = function(callback) { this.addListener('translationnotfound', callback); }; Counterpart.prototype.offTranslationNotFound = Counterpart.prototype.removeTranslationNotFoundListener = function(callback) { this.removeListener('translationnotfound', callback); }; Counterpart.prototype.translate = function(key, options) { if (!isArray(key) && !isString(key) || !key.length) { throw new Error('invalid argument: key'); } if (isSymbol(key)) { key = key.substr(1); } key = this._registry.keyTransformer(key, options); options = extend(true, {}, options); var locale = options.locale || this._registry.locale; delete options.locale; var scope = options.scope || this._registry.scope; delete options.scope; var separator = options.separator || this._registry.separator; delete options.separator; var fallbackLocales = [].concat(options.fallbackLocale || this._registry.fallbackLocales); delete options.fallbackLocale; var keys = this._normalizeKeys(locale, scope, key, separator); var entry = getEntry(this._registry.translations, keys); if (entry === null) { this.emit('translationnotfound', locale, key, options.fallback, scope); if (options.fallback) { entry = this._fallback(locale, scope, key, options.fallback, options); } } if (entry === null && fallbackLocales.length > 0 && fallbackLocales.indexOf(locale) === -1) { for (var ix in fallbackLocales) { var fallbackLocale = fallbackLocales[ix]; var fallbackKeys = this._normalizeKeys(fallbackLocale, scope, key, separator); entry = getEntry(this._registry.translations, fallbackKeys); if (entry) { locale = fallbackLocale; break; } } } if (entry === null) { entry = 'missing translation: ' + keys.join(separator); } entry = this._pluralize(locale, entry, options.count); if (this._registry.interpolate !== false && options.interpolate !== false) { entry = this._interpolate(entry, options); } return entry; }; Counterpart.prototype.localize = function(object, options) { if (!isDate(object)) { throw new Error('invalid argument: object must be a date'); } options = extend(true, {}, options); var locale = options.locale || this._registry.locale; var scope = options.scope || translationScope; var type = options.type || 'datetime'; var format = options.format || 'default'; options = { locale: locale, scope: scope, interpolate: false }; format = this.translate(['formats', type, format], extend(true, {}, options)); return strftime(object, format, this.translate('names', options)); }; Counterpart.prototype._pluralize = function(locale, entry, count) { if (typeof entry !== 'object' || entry === null || typeof count !== 'number') { return entry; } var pluralizeFunc = this.translate('pluralize', { locale: locale, scope: translationScope }); if (Object.prototype.toString.call(pluralizeFunc) !== '[object Function]') { return pluralizeFunc; } return pluralizeFunc(entry, count); }; Counterpart.prototype.withLocale = function(locale, callback, context) { var previous = this._registry.locale; this._registry.locale = locale; var result = callback.call(context); this._registry.locale = previous; return result; }; Counterpart.prototype.withScope = function(scope, callback, context) { var previous = this._registry.scope; this._registry.scope = scope; var result = callback.call(context); this._registry.scope = previous; return result; }; Counterpart.prototype.withSeparator = function(separator, callback, context) { var previous = this.setSeparator(separator); var result = callback.call(context); this.setSeparator(previous); return result; }; Counterpart.prototype._normalizeKeys = function(locale, scope, key, separator) { var keys = []; keys = keys.concat(this._normalizeKey(locale, separator)); keys = keys.concat(this._normalizeKey(scope, separator)); keys = keys.concat(this._normalizeKey(key, separator)); return keys; }; Counterpart.prototype._normalizeKey = function(key, separator) { this._registry.normalizedKeys[separator] = this._registry.normalizedKeys[separator] || {}; this._registry.normalizedKeys[separator][key] = this._registry.normalizedKeys[separator][key] || (function(key) { if (isArray(key)) { var normalizedKeyArray = key.map(function(k) { return this._normalizeKey(k, separator); }.bind(this)); return [].concat.apply([], normalizedKeyArray); } else { if (typeof key === 'undefined' || key === null || !key.split) { return []; } var keys = key.split(separator); for (var i = keys.length - 1; i >= 0; i--) { if (keys[i] === '') { keys.splice(i, 1); if (this._registry.keepTrailingDot === true && i == keys.length) { keys[keys.length - 1] += '' + separator; } } } return keys; } }.bind(this))(key); return this._registry.normalizedKeys[separator][key]; }; Counterpart.prototype._interpolate = function(entry, values) { if (typeof entry !== 'string') { return entry; } return sprintf(entry, extend({}, this._registry.interpolations, values)); }; Counterpart.prototype._resolve = function(locale, scope, object, subject, options) { options = options || {}; if (options.resolve === false) { return subject; } var result; if (isSymbol(subject)) { result = this.translate(subject, extend({}, options, { locale: locale, scope: scope })); } else if (isFunction(subject)) { var dateOrTime; if (options.object) { dateOrTime = options.object; delete options.object; } else { dateOrTime = object; } result = this._resolve(locale, scope, object, subject(dateOrTime, options)); } else { result = subject; } return /^missing translation:/.test(result) ? null : result; }; Counterpart.prototype._fallback = function(locale, scope, object, subject, options) { options = except(options, 'fallback'); if (isArray(subject)) { for (var i = 0, ii = subject.length; i < ii; i++) { var result = this._resolve(locale, scope, object, subject[i], options); if (result) { return result; } } return null; } else { return this._resolve(locale, scope, object, subject, options); } }; var instance = new Counterpart(); function translate() { return instance.translate.apply(instance, arguments); } extend(translate, instance, { Instance: Counterpart, Translator: Counterpart }); module.exports = translate; <file_sep># Cybex Web Client ## How to start 1. Clone the repo; 2. Install the dependencies with `npm i` or `yarn`; 3. For development, just run the start script with `npm start` or `yarn start`; 4. A *webpack-dev-server* should be launched and listening the local port **8080**; ## Addition * This client app is original coded with Javascript with the frontend framework React 15.6; For some well-known reasons, the new features has been switching to be written by Typescript. And the upgrading of React is around the corner. * The web client relies on the utilities - [cybexjs](https://github.com/CybexDex/cybexjs) & [cybexjs-ws](https://github.com/CybexDex/cybexjs-ws) ## System requirements * Node.js >= 8.9 * npm >= 5.5 <file_sep>import immutable from 'immutable'; import { screen } from '../defaultData'; module.exports = (state = immutable.fromJS(screen), action) => { switch (action.type) { /** * 增加屏幕 */ case 'ADD_screen': return state.update('allNum', allNum => allNum += 1); /** * 增加当前加载的屏幕队 */ case 'ADD_loadingScreen': //屏幕总数 let subscript = action.data - 1; //返回新的显示数组 return state.update('loadingScreen', loadingScreenList => { //最多显示4个屏幕 for (let i = 0; i < 4; i++) { let showScreen = subscript - i; if (showScreen < 0) { break; } loadingScreenList = loadingScreenList.set(i, showScreen); } return loadingScreenList; }); case 'UP_loadingScreen': return state.set('oldNum', action.data); case 'UP_changeScreen': return state.set('numIng', action.data); case 'CHANGE_downChange': return state.update('loadingScreen', list => { list = list.set(0, action.data - 1); list = list.set(1, action.data); list = list.set(2, action.data + 1); list = list.set(3, action.data + 2); return list; }); case 'CHANGE_upChange': return state.update('loadingScreen', list => { list = list.set(0, action.data - 2); list = list.set(1, action.data - 1); list = list.set(2, action.data); list = list.set(3, action.data + 1); return list; }); default: return state; } }<file_sep>```html <Trigger notify="id-of-target-notification" title="My notification" content="Notification example" color="success" position="top-left"> <a className="button">Dynamic Notification</a> </Trigger> ```<file_sep>var React = require("react"); var Router = require("react-router-dom"); var Route = Router.Route; var DefaultRoute = Router.DefaultRoute; var Install = require("./install"); var Accordion = require("./accordion"); var Interchange = require("./interchange"); var Offcanvas = require("./offcanvas"); var Notification = require("./notification"); var Modal = require("./modal"); var Panel = require("./panel"); var ActionSheet = require("./action-sheet"); var Tabs = require("./tabs"); var Trigger = require("./trigger"); var Popup = require("./popup"); var Iconic = require("./iconic"); var Docs = require("./docs"); var path = process.env.NODE_ENV === "dev_docs" ? "/" : "/opensource/react-foundation-apps"; var routes = ( <Route name="app" path={path} handler={Docs}> <Route name="install" handler={Install} /> <Route name="trigger" handler={Trigger} /> <Route name="modal" handler={Modal} /> <Route name="panel" handler={Panel} /> <Route name="offcanvas" handler={Offcanvas} /> <Route name="notification" handler={Notification} /> <Route name="action-sheet" handler={ActionSheet} /> <Route name="tabs" handler={Tabs} /> <Route name="iconic" handler={Iconic} /> <Route name="accordion" handler={Accordion} /> <Route name="interchange" handler={Interchange} /> <Route name="popup" handler={Popup} /> <DefaultRoute handler={Install} /> </Route> ); module.exports = routes; <file_sep>import { Map } from "immutable"; import SettingsStore, {preferredBases} from "stores/SettingsStore"; export type Market = { quote: string; base: string; marketId: string; id: string; }; export type GroupedMarkets = { [market: string]: Market[] }; class MarketPair { constructor(public base?, public quote?) {} } const correctMarketPair = (symbolOfA?, symbolOfB?) => { let indexOfA = preferredBases.indexOf(symbolOfA); let indexOfB = preferredBases.indexOf(symbolOfB); if ( (indexOfA > indexOfB && indexOfB > -1) || (indexOfA === -1 && indexOfB !== -1) ) { return new MarketPair(symbolOfB, symbolOfA); } else if ( (indexOfA < indexOfB && indexOfA > -1) || (indexOfA !== -1 && indexOfB === -1) ) { return new MarketPair(symbolOfA, symbolOfB); } return new MarketPair(...[symbolOfA, symbolOfB].sort()); }; const correctMarketPairMap = ( assetA: Map<string, any>, assetB: Map<string, any> ) => { let [base, quote] = correctMarketPair(assetA.get("symbol"), assetB.get("symbol")).base === assetA.get("symbol") ? [assetA, assetB] : [assetB, assetA]; return { base, quote }; }; const getMarketWithId: (quote: string, base: string) => Market = ( quote, base ) => ({ quote, base, marketId: `${quote}_${base}`, id: `${quote}_${base}` }); const getMarketFromId: (id: string, separator?: string) => Market = ( id, separator = "_" ) => { let afterSplit = id.split(separator)[1]; return { id, marketId: id, base: afterSplit[1], quote: afterSplit[0] }; }; const getGroupedMarkets: (markets: Market[]) => GroupedMarkets = markets => markets.reduce( (groupedMarkets, nextMarket) => groupedMarkets[nextMarket.base] ? { ...groupedMarkets, [nextMarket.base]: [...groupedMarkets[nextMarket.base], nextMarket] } : { ...groupedMarkets, [nextMarket.base]: [nextMarket] }, {} ); const getGroupedMarketsFromMap: ( markets: Map<string, { quote: string; base: string }> ) => GroupedMarkets = markets => getGroupedMarkets( markets.toArray().map(map => getMarketWithId(map.quote, map.base)) ); export { correctMarketPair, correctMarketPairMap, getMarketFromId, getMarketWithId, getGroupedMarkets, getGroupedMarketsFromMap }; export default { correctMarketPair, correctMarketPairMap, getMarketFromId, getMarketWithId, getGroupedMarkets, getGroupedMarketsFromMap }; <file_sep>import alt from "alt-instance"; export type ModalHandlers = { onResolve: any; onReject: any; }; export type ModalResult = { data: any; }; export type ModalCloseParams = { modal_id: string; result: ModalResult; }; class ModalActions { showModal( modal_id: string, onlyOnce: boolean = false, handlers = { onResolve: () => void 0 as any, onReject: () => void 0 as any } ) { console.debug("Show Modal Actions: ", modal_id); return { modal_id, onlyOnce, handlers }; } hideModal(modal_id: string) { return modal_id; } closeModalWithResolve(closeResult: { modal_id: string; result: ModalResult; }) { return closeResult; } closeModalWithReject(closeResult: ModalCloseParams) { return closeResult; } neverShow(modal_id, neverShow) { return { modal_id, neverShow }; } } const ModalActionsWrapped: ModalActions = alt.createActions(ModalActions); export { ModalActionsWrapped as ModalActions }; export default ModalActionsWrapped; <file_sep>var React = require("react"); var BasicAccordion = require("./basic"); var AdvancedAccordion = require("./advanced"); var Highlight = require("react-highlight/optimized"); var Accordion = React.createClass({ render: function() { return ( <div className="grid-content"> <h2>Accordion</h2> <h4 className="subheader"> Accordion allows you to create a collapsible content blocks </h4> <hr /> <BasicAccordion /> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./basic.md")} </Highlight> </div> <div className="grid-content"> <BasicAccordion /> </div> </div> <hr /> <h3>Advanced</h3> <div className="grid-block"> <div className="grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./advanced.md")} </Highlight> </div> <div className="grid-content"> <AdvancedAccordion /> </div> </div> </div> ); } }); module.exports = Accordion; <file_sep>```html <Trigger open='id-of-target'> <a className='button'>Open Target</a> <Trigger> ```<file_sep>var React = require("react"); var classnames = require("classnames"); var Tab = React.createClass({ select: function() { var options = { selectedTab: this.props.index }; this.props.selectTab(options); }, render: function() { var classes = { "tab-item": true, "is-active": this.props.active }; return ( <div className={classnames(classes)} onClick={this.select}> {this.props.title} </div> ); } }); module.exports = Tab; <file_sep>export type HistoryDatum = { "id": string, "key": { "base": string, "quote": string, "seconds": number, "open": string }, "high_base": number, "high_quote": number, "low_base": number, "low_quote": number, "open_base": number, "open_quote": number, "close_base": number, "close_quote": number, "base_volume": number, "quote_volume": number };<file_sep>export * from "./VestedBalancesList";<file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import Translate from "react-translate-component"; import SettingsActions from "actions/SettingsActions"; import SettingsStore from "stores/SettingsStore"; import { settingsAPIs } from "../../api/apiConfig"; import willTransitionTo from "../../routerTransition"; import { withRouter } from "react-router-dom"; import { connect } from "alt-react"; import { ChainConfig, Apis } from "cybexjs-ws"; const URL_FRAGMENT_OF_TESTNET = "121.40"; const autoSelectAPI = "wss://fake.automatic-selection.com"; const testnetAPI = settingsAPIs.WS_NODE_LIST.find( a => a.url.indexOf(URL_FRAGMENT_OF_TESTNET) !== -1 ) || {}; class ApiNode extends React.Component { constructor(props) { super(props); this.state = { hovered: false }; } setHovered() { this.setState({ hovered: true }); } clearHovered() { this.setState({ hovered: false }); } activate(url) { SettingsActions.changeSetting({ setting: "apiServer", value: url }); if ( SettingsStore.getSetting("activeNode") != SettingsStore.getSetting("apiServer") ) { setTimeout( function() { willTransitionTo(false); }.bind(this), 50 ); } } remove(url, name, e) { this.props.triggerModal(e, url, name); } render() { const { props, state } = this; const { allowActivation, allowRemoval, automatic, autoActive, name, url, displayUrl, ping, up } = props; let color; let green = "#00FF00"; let yellow = "yellow"; let red = "red"; let latencyKey; if (ping < 400) { color = green; latencyKey = "low_latency"; } else if (ping >= 400 && ping < 800) { color = yellow; latencyKey = "medium_latency"; } else { color = red; latencyKey = "high_latency"; } /* * The testnet latency is not checked in the connection manager, * so we force enable activation of it even though it shows as 'down' */ const isTestnet = url === testnetAPI.url; var Status = isTestnet && !ping ? null : ( <div className="api-status"> <Translate style={{ color: up ? green : red, marginBottom: 0 }} component="h3" content={"settings." + (up ? "node_up" : "node_down")} /> {up && ( <Translate content={`settings.${latencyKey}`} style={{ color }} /> )} {!up && <span style={{ color: "red" }}>__</span>} </div> ); return ( <div className="api-node card" onMouseEnter={this.setHovered.bind(this)} onMouseLeave={this.clearHovered.bind(this)} > <h3 style={{ marginBottom: 0, marginTop: 0 }}>{name}</h3> <p style={{ marginBottom: 0 }}>{displayUrl}</p> {automatic && autoActive && ( <div className="api-status"> <Translate content="account.votes.active_short" component="h3" /> </div> )} {!allowActivation && !allowRemoval && !automatic && Status} {allowActivation && !automatic && !state.hovered && Status} {allowRemoval && state.hovered && !(automatic && autoActive) && ( <div className="button" onClick={this.remove.bind(this, url, name)}> <Translate id="remove" content="settings.remove" /> </div> )} {allowActivation && state.hovered && !(automatic && autoActive) && (automatic || isTestnet ? true : true) && ( <div className="button" onClick={this.activate.bind(this, url)}> <Translate content="settings.activate" /> </div> )} </div> ); } } ApiNode.defaultProps = { name: "<NAME>", url: "wss://testnode.net/wss", displayUrl: "wss://testnode.net/wss", up: true, ping: null, allowActivation: false, allowRemoval: false }; const ApiNodeWithRouter = withRouter(ApiNode); class AccessSettings extends React.Component { constructor(props) { super(props); let isDefaultNode = {}; settingsAPIs.WS_NODE_LIST.forEach(node => { isDefaultNode[node.url] = true; }); this.isDefaultNode = isDefaultNode; this.chain = ChainConfig.address_prefix; } getNodeIndexByURL(url) { const { props } = this; var index = null; for (var i = 0; i < props.nodes.length; i++) { let node = props.nodes[i]; if (node.url == url) { index = i; break; } } return index; } getCurrentNodeIndex() { const { props } = this; let currentNode = this.getNodeIndexByURL.call(this, props.currentNode); return currentNode; } getNode(node) { const { props } = this; return { name: node.location || "Unknown location", url: node.url, up: node.url in props.apiLatencies, ping: props.apiLatencies[node.url] }; } setPrefix() { let e = document.getElementById("setPrefix"); // console.debug("SetPrefix: ", e); if (!e || !e.value) return; let value = e.value; let chainKey = "PREFIX_" + Apis.instance().chain_id; if (localStorage) { localStorage.setItem(chainKey, value); } location.reload(); } renderNode(node, allowActivation) { const { props } = this; let automatic = node.url === autoSelectAPI; let displayUrl = automatic ? "..." : node.url; let name = !!node.name && typeof node.name === "object" && "translate" in node.name ? ( <Translate component="span" content={node.name.translate} /> ) : ( node.name ); let allowRemoval = !automatic && !this.isDefaultNode[node.url] ? true : false; return ( <ApiNodeWithRouter {...node} autoActive={props.currentNode === autoSelectAPI} automatic={automatic} allowActivation={allowActivation} allowRemoval={allowActivation && allowRemoval} key={node.url} name={name} displayUrl={displayUrl} triggerModal={props.triggerModal} /> ); } render() { const { props } = this; let getNode = this.getNode.bind(this); let renderNode = this.renderNode.bind(this); let currentNodeIndex = this.getCurrentNodeIndex.call(this); let nodes = props.nodes.map(node => { return getNode(node); }); let activeNode = getNode(props.nodes[currentNodeIndex] || props.nodes[0]); if (activeNode.url == autoSelectAPI) { let nodeUrl = props.activeNode; currentNodeIndex = this.getNodeIndexByURL.call(this, nodeUrl); activeNode = getNode(props.nodes[currentNodeIndex]); } // console.debug("Nodes: ", nodes); // nodes = nodes.slice(0, currentNodeIndex).concat(nodes.slice(currentNodeIndex+1)).sort(function(a,b){ nodes = nodes .filter((node, index) => index !== currentNodeIndex && node.url) .sort(function(a, b) { // console.debug("A: ", a, "; Test: ", testnetAPI); let isTestnet = a.url === testnetAPI.url; if (a.url == autoSelectAPI) { return -1; } else if (a.up && b.up) { return a.ping - b.ping; } else if (!a.up && !b.up) { if (isTestnet) return -1; return 1; } else if (a.up && !b.up) { return -1; } else if (b.up && !a.up) { return 1; } return 0; }); return ( <div className="nodes-wrapper" style={{ paddingTop: "1em" }}> <Translate component="p" content="settings.active_node" /> <div className="active-node">{renderNode(activeNode, false)}</div> <div className="available-nodes"> <Translate component="p" content="settings.available_nodes" /> {nodes.map(node => { return renderNode(node, true); })} </div> <div className="button-wrapper"> <Translate id="add" onClick={props.triggerModal.bind(this)} component="button" className="button" content="settings.add_api" /> </div> {/* <div className="form-group grid-block grid-x-padding full-container"> Specified Prefix - {Apis.instance().chain_id} <input className="small-10 medium-10" id="setPrefix" type="text" value={this.nodePrefix} /> <button className="small-2 medium-2" onClick={this.setPrefix.bind(this)}>Confirm</button> </div> */} </div> ); } } AccessSettings = connect( AccessSettings, { listenTo() { return [SettingsStore]; }, getProps() { return { currentNode: SettingsStore.getState().settings.get("apiServer"), activeNode: SettingsStore.getState().settings.get("activeNode"), apiLatencies: SettingsStore.getState().apiLatencies }; } } ); export default AccessSettings; <file_sep>import alt from "alt-instance"; import { ChainStore } from "stores/ChainStore"; import { Apis } from "cybexjs-ws"; import { debugGen } from "utils//Utils"; import { correctMarketPair } from "utils/Market"; import { PRICE_API } from "api/apiConfig"; import { MARKETS } from "stores/SettingsStore"; type OuterPrice = { name: string; value: number; time: number; }; export type PriceSetByYuan = { [asset: string]: number; }; type OuterPriceData = { code: number; prices: OuterPrice[]; }; const debug = debugGen("VolActions"); const isId = str => /[12]\..+\..+/.test(str); async function getObject(id = "1.1.1") { console.log(`Get object ${id}`); return await Apis.instance() .db_api() .exec("get_objects", [[id]]); } async function getAsset(...assets) { if (isId(assets[0])) { return await Promise.all(assets.map(id => getObject(id))); } return await Apis.instance() .db_api() .exec("lookup_asset_symbols", [assets]); } async function getLatestPrice(_base = "1.3.0", _quote = "1.3.2") { let [base, quote] = await getAsset(_base, _quote); let d = new Date().toISOString().slice(0, 19); let latestTrade = (await Apis.instance() .db_api() .exec( "get_trade_history", [ base.id || _base, quote.id || _quote, d, // start, `2018-02-24T00:00:00`, // stop, 1 ] ))[0] || { price: 0 }; // console.debug("Get Latest Price: ", base.id, quote.id); return latestTrade.price; } async function getVol(quote?, base?) { return await Apis.instance() .db_api() .exec("get_24_volume", [quote, base]); } async function statVolume() { if (!Apis.instance().db_api()) return; // let assets = await Apis.instance() // .db_api() // .exec("list_assets", ["", 100]); // let assets = MARKETS; // console.debug("Asest: ", assets); let assetSymbols = MARKETS; let rawPairs = assetSymbols.reduce((allPairs, next, i, arr) => { arr.forEach(symbol => { if (symbol !== next) { allPairs.push([symbol, next]); } }); return allPairs; }, []); let orderedPairs = rawPairs .map(pair => correctMarketPair(...pair)) .map(pair => `${pair.quote}_${pair.base}`); let validMarkets = Array.from(new Set(orderedPairs) as Set<string>); let marketsVol = await Promise.all( validMarkets.map(pair => getVol(...pair.split("_"))) ); let marketsVolByAsset = marketsVol.reduce((summary, vol) => { if (vol.base in summary) { summary[vol.base] += Number(vol.base_volume); } else { summary[vol.base] = Number(vol.base_volume); } if (vol.quote in summary) { summary[vol.quote] += Number(vol.quote_volume); } else { summary[vol.quote] = Number(vol.quote_volume); } return summary; }, {}); let priceOfCybEth = await getLatestPrice("JADE.ETH", "CYB"); let volByEth = await Promise.all( Object.getOwnPropertyNames(marketsVolByAsset).map(async asset => { let res: { [key: string]: any } = { asset, vol: marketsVolByAsset[asset] }; let price = await getLatestPrice("JADE.ETH", asset); if (!price) { price = (await getLatestPrice("CYB", asset)) * priceOfCybEth; res.byCYB = true; } res.volByEther = price * marketsVolByAsset[asset].toFixed(6); return res; }) ); let res = { details: volByEth, sum: volByEth.reduce((acc, next) => acc + Number(next.volByEther), 0) }; return res; } class VolumnActions { async subMarket(_base, _quote) { let [base, quote] = await Promise.all([ ChainStore.getAsset(_base), ChainStore.getAsset(_quote) ]); debug("[Sub]", base, quote); Apis.instance() .db_api() .exec("subscribe_to_market", [this.updateHandler, base.id, quote.id]); } async fetchPriceData() { // console.debug("Start To Fetch"); let data: PriceSetByYuan = await fetch(PRICE_API) .then(res => res.json()) .then(async (outer: OuterPriceData) => { // console.debug("Fetchd: ", outer); if (outer.code !== 0) { throw Error("Price Api Error!" + JSON.stringify(outer)); } else { let priceSet = {}; for (let price of outer.prices) { priceSet[price.name] = parseFloat(price.value.toFixed(2)); } return priceSet; } }) .catch(err => { console.error(err); return {}; }); this.updatePriceData(data); } updatePriceData(data: PriceSetByYuan) { return data; } async unSubMarket(_base, _quote) { let [base, quote] = await Promise.all([ ChainStore.getAsset(_base), ChainStore.getAsset(_quote) ]); Apis.instance() .db_api() .exec("unsubscribe_from_market", [ this.updateHandler, base.get("id"), quote.get("id") ]); } async queryVol() { let vol = await statVolume(); this.updateVol(vol); } updateVol(vol) { return vol; } updateHandler = async change => { debug("[UpdateHandler]", change); }; updateMarket(modal_id, neverShow) { return { modal_id, neverShow }; } } const VolumnActionsWrapper: VolumnActions = alt.createActions(VolumnActions); export { VolumnActionsWrapper as VolumnActions }; export default VolumnActionsWrapper; <file_sep>import ls from "./localStorage"; import {rudexAPIs} from "api/apiConfig"; const rudexStorage = new ls(""); export function fetchCoinList(url = (rudexAPIs.BASE + rudexAPIs.COINS_LIST)) { return fetch(url, {method:"post"}).then(reply => reply.json().then(result => { return result; })).catch(err => { console.log("error fetching rudex list of coins", err, url); }); } export function requestDepositAddress({inputCoinType, outputCoinType, outputAddress, url = rudexAPIs.BASE, stateCallback}) { let body = { inputCoinType, outputCoinType, outputAddress }; let body_string = JSON.stringify(body); fetch( url + rudexAPIs.NEW_DEPOSIT_ADDRESS, { method:"post", headers: new Headers( { "Accept": "application/json", "Content-Type":"application/json" } ), body: body_string }).then( reply => { reply.json() .then( json => { // console.log( "reply: ", json ) let address = {"address": json.inputAddress || "unknown", "memo": json.inputMemo, error: json.error || null}; if (stateCallback) stateCallback(address); }, error => { // console.log( "error: ",error ); if (stateCallback) stateCallback({"address": "unknown", "memo": null}); }); }, error => { // console.log( "error: ",error ); if (stateCallback) stateCallback({"address": "unknown", "memo": null}); }).catch(err => { console.log("fetch error:", err); }); } export function validateAddress({url = rudexAPIs.BASE, walletType, newAddress}) { if (!newAddress) return new Promise((res) => res()); return fetch( url + "/wallets/" + walletType + "/check-address", { method: "post", headers: new Headers({"Accept": "application/json", "Content-Type": "application/json"}), body: JSON.stringify({address: newAddress}) }).then(reply => reply.json().then( json => json.isValid)) .catch(err => { console.log("validate error:", err); }) } function hasWithdrawalAddress(wallet) { return rudexStorage.has(`history_address_${wallet}`); } function setWithdrawalAddresses({wallet, addresses}) { rudexStorage.set(`history_address_${wallet}`, addresses); } function getWithdrawalAddresses(wallet) { return rudexStorage.get(`history_address_${wallet}`, []); } function setLastWithdrawalAddress({wallet, address}) { rudexStorage.set(`history_address_last_${wallet}`, address); } function getLastWithdrawalAddress(wallet) { return rudexStorage.get(`history_address_last_${wallet}`, ""); } export const WithdrawAddresses = { has: hasWithdrawalAddress, set: setWithdrawalAddresses, get: getWithdrawalAddresses, setLast: setLastWithdrawalAddress, getLast: getLastWithdrawalAddress }; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import WalletChangePassword from "../Wallet/WalletChangePassword"; export default class PasswordSettings extends React.Component { render() { return <WalletChangePassword />; } } <file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var StaticNotification = require("./static"); var AdvancedNotification = require("./advanced"); var NotificationDocs = React.createClass({ render: function() { return ( <div> <h2>Notification</h2> <h4 className="subheader"> This component allows you to create notifications or alerts to user </h4> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="small-8 grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./static.md")} </Highlight> </div> <div className="grid-content"> <StaticNotification /> </div> </div> </div> ); } }); module.exports = NotificationDocs; <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; const debug = debugGen("CrowdFundActions"); class CrowdFundActions { async queryAllCrowdFunds(start: number = 0, size: number = 20, accountId?) { let startId = "1.16." + start.toString() let res = await Apis.instance().db_api().exec("list_crowdfund_objects", [startId, size]); res = res.map(crow => ({ ...crow, beginMoment: moment.utc(crow.begin) })); if (accountId) { let accountCrowds = await Promise.all([ this.queryAccountInitCrowds(accountId), this.queryAccountPartiCrowds(accountId) ]); debug("AccountCrowd: ", accountCrowds); } debug("Query All Funds RES: ", res); this.allFundsFetched({ start, size, res }); } async queryAccountInitCrowds(accountId) { let res = await Apis.instance().db_api().exec("get_crowdfund_objects", [accountId]); debug("Query Init RES: ", res); this.accountInitFundsFetched(res); return (res); } async queryAccountPartiCrowds(accountId) { let res = await Apis.instance().db_api().exec("get_crowdfund_contract_objects", [accountId]); res = res.map(partCrowd => ({ ...partCrowd, whenM: moment.utc(partCrowd.when) })); debug("Query Fund RES: ", res); this.accountPartiFundsFetched(res); return (res); } async initCrowdFund(crowdParams: { u: number, t: number, owner: string, asset_id: string }) { let operation = { fee: { asset_id: 0, amount: 0 }, ...crowdParams }; let tr = WalletApi.new_transaction(); tr.add_type_operation("initiate_crowdfund", operation); try { await WalletDb.process_transaction(tr, null, true); return dispatch => dispatch(true); } catch { return dispatch => dispatch(false); } } async partiCrowd(crowdParams: { valuation: number, cap: number, buyer: string, crowdfund: string }) { let operation = { fee: { asset_id: 0, amount: 0 }, ...crowdParams }; let tr = WalletApi.new_transaction(); tr.add_type_operation("participate_crowdfund", operation); try { await WalletDb.process_transaction(tr, null, true); return dispatch => dispatch(true); } catch { return dispatch => dispatch(false); } } async withdrawCrowdFund( buyer: string, crowdfund_contract: string ) { let operation = { fee: { amount: 0, asset_id: "1.3.0" }, buyer, crowdfund_contract, }; let tr = WalletApi.new_transaction(); tr.add_type_operation("withdraw_crowdfund", operation); try { await WalletDb.process_transaction(tr, null, true); return dispatch => dispatch(true); } catch { return dispatch => dispatch(false); } } allFundsFetched(fetchedData) { return fetchedData; } accountInitFundsFetched(fetchedData) { return fetchedData; } accountPartiFundsFetched(fetchedData) { return fetchedData; } } const CrowdFundActionsWrapped = alt.createActions(CrowdFundActions); export default CrowdFundActionsWrapped;<file_sep>var React = require("react"); var Tabs = React.createClass({ getInitialState: function() { return { selectedTab: 0 }; }, selectTab: function(options) { this.setState(options); }, render: function() { var content = null; var children = React.Children.map( this.props.children, function(child, index) { if (index === this.state.selectedTab) content = child.props.children; return React.cloneElement(child, { active: index === this.state.selectedTab, index: index, selectTab: this.selectTab }); }.bind(this) ); return ( <div> <div className="tabs">{children}</div> <div className="content">{content}</div> </div> ); } }); module.exports = Tabs; Tabs.Tab = require("./tab"); <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import SettingsStore from "stores/SettingsStore"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; import { NotificationActions } from "actions//NotificationActions"; import { ops, PrivateKey, Signature, TransactionBuilder } from "cybexjs"; import { Map } from "immutable"; import { CustomTx } from "CustomTx"; import { Edge, edgeTx, EdgeProject } from "services/edge"; import WalletUnlockActions from "actions/WalletUnlockActions"; import { EDGE_LOCK } from "api/apiConfig"; import TransactionConfirmActions from "actions/TransactionConfirmActions"; import { Htlc } from "../services/htlc"; import { calcAmount } from "../utils/Asset"; const debug = debugGen("EdgeActions"); export const DEPOSIT_MODAL_ID = "DEPOSIT_MODAL_ID"; export const WITHDRAW_MODAL_ID = "WITHDRAW_MODAL_ID"; export const HASHED_PREIMAGE_FOR_LOCK_BTC = "0dafe1579c1d37054d466ac6f8b40378e3cb4978160d87c8a947cd3a9edbcf92"; export const DEST_TIME = "2019-09-27T16:00:00Z"; export const RECEIVER = "btc-lock"; const headers = new Headers(); headers.append("Content-Type", "application/json"); const pickKeys = (keys: string[], count = 1) => { let res: any[] = []; for (let key of keys) { let privKey = WalletDb.getPrivateKey(key); if (privKey) { res.push(privKey); if (res.length >= count) { break; } } } return res; }; const ProjectServer = __DEV__ ? "https://EDGEapi.cybex.io/api" : "https://EDGEapi.cybex.io/api"; const ProjectUrls = { banner() { return `${ProjectServer}/cybex/projects/banner`; }, projects(limit = 10) { return `${ProjectServer}/cybex/projects?limit=${limit}`; }, projectDetail(projectID: string) { return `${ProjectServer}/cybex/project/detail?project=${projectID}`; }, projectDetailUpdate(projectID: string) { return `${ProjectServer}/cybex/project/current?project=${projectID}`; }, userState(projectID: string, accountName: string) { return `${ProjectServer}/cybex/user/check_status?cybex_name=${accountName}&project=${projectID}`; }, user(projectID: string, accountName: string) { return `${ProjectServer}/cybex/user/current?cybex_name=${accountName}&project=${projectID}`; }, userTradeList(accountName: string, page = 1, limit = 1) { return `${ProjectServer}/cybex/trade/list?cybex_name=${accountName}&page=${page}&limit=${limit}`; } }; const fetchUnwrap = <T = any>(url: string) => fetch(url) .then(res => res.json()) .then(res => { if (res.code === 0) { return res.result as T; } else { throw new Error(res.code); } }); type AccountMap = Map<string, any>; class EdgeActions { /// Edge 锁仓查询部分 queryInfo(account: AccountMap, onReject?) { this.addLoading(); return dispatch => { this.signTx(0, "query", account) .then(tx => Promise.resolve({ accountName: account.get("name"), accountID: account.get("id"), basic: {} }) .then(res => Apis.instance() .db_api() .exec("get_htlc_by_from", [account.get("id"), "1.21.0", 100]) .then(records => ({ ...res, records: records.filter( (record: Htlc.HtlcRecord) => record.conditions.hash_lock.preimage_hash[1] === HASHED_PREIMAGE_FOR_LOCK_BTC ) })) ) .then(res => new Edge.EdgeInfo(res)) .then(info => { dispatch(info); this.removeLoading(); return info; }) .catch(err => { if (onReject) { onReject(err); } console.error(err); return new Edge.EdgeInfo(); }) ) .catch(err => { if (onReject) { onReject(err); } console.error(err); return new Edge.EdgeInfo(); }); }; } queryRank(onReject?) { this.addLoading(); return dispatch => { fetch(`${EDGE_LOCK}api/v1/rank`) .then(res => res.json()) .then(rank => { dispatch(rank); this.removeLoading(); }) .catch(err => { this.removeLoading(); if (onReject) { onReject(err); } console.error(err); }); }; } applyLock(value: number, account: AccountMap, onResolve?) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS(); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } return { privKey, pubKey: privKey.toPublicKey().toPublicKeyString() }; }) .then(async ({ privKey, pubKey }) => { let tx = new TransactionBuilder(); let destAccount = await Apis.instance() .db_api() .exec("get_account_by_name", [RECEIVER]); let htlc = new Htlc.HtlcCreateByHashedPreimage( account.get("id"), destAccount.id, { asset_id: "1.3.3", amount: calcAmount(value.toString(), 8) }, Htlc.HashAlgo.Sha256, 45, HASHED_PREIMAGE_FOR_LOCK_BTC, moment(DEST_TIME).diff(moment(), "seconds") ); tx.add_type_operation("htlc_create", htlc); await tx.set_required_fees(); await tx.finalize(); await tx.add_signer(privKey); await tx.sign(); return new Promise((resolve, reject) => TransactionConfirmActions.confirm(tx, resolve, reject, null) ); }) .then(tx => { console.debug("TX: ", tx); dispatch(tx); if (onResolve) { onResolve(); } this.removeLoading(); return tx; }) .catch(err => { console.error(err); this.removeLoading(); }); }; } // applyLock(value: number, period: number, account: AccountMap, onResolve?) { // this.addLoading(); // return dispatch => { // WalletUnlockActions.unlock() // .then(() => { // console.debug("Account: ", account); // let availKeys = account // .getIn(["active", "key_auths"]) // .filter(key => key.get(1) >= 1) // .map(key => key.get(0)) // .toJS(); // let privKey = pickKeys(availKeys)[0]; // if (!privKey) { // throw Error("Privkey Not Found"); // } // return { privKey, pubKey: privKey.toPublicKey().toPublicKeyString() }; // }) // .then(({ privKey, pubKey }) => // this.signTx(4, { value, pubKey, period }, account) // .then(tx => // fetch(`${EDGE_LOCK}api/v1/apply/${account.get("name")}`, { // headers, // method: "POST", // body: JSON.stringify(tx) // }).then(res => res.json()) // ) // .then(tx => { // let newTx = TransactionBuilder.fromTx(tx); // newTx.add_signer(privKey); // return new Promise((resolve, reject) => // TransactionConfirmActions.confirm(newTx, resolve, reject, null) // ); // }) // .then(tx => { // console.debug("TX: ", tx); // dispatch(tx); // if (onResolve) { // onResolve(); // } // this.removeLoading(); // return tx; // }) // ) // .catch(err => { // console.error(err); // this.removeLoading(); // }); // }; // } /** * 注册一个查询签名 * * @param {Map<string, any>} account * @memberof EdgeActions */ async signTx(opOrder: Edge.OpsOrder, op: Edge.Ops, account: AccountMap) { // await WalletUnlockActions.unlock().catch(e => console.debug("Unlock Error")); await WalletUnlockActions.unlock(); debug("[LoginEdgeQuery]", account); debug("[LoginEdgeQuery]", SettingsStore.getSetting("walletLockTimeout")); const tx: Edge.Request = { op: [opOrder, op], expiration: Date.now() + SettingsStore.getSetting("walletLockTimeout") * 1000 }; // Pick approps key let weight_threshold = account.getIn(["active", "weight_threshold"]); let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() .concat( account .getIn(["owner", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() ); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } debug( "[LoginEdgeQuery privKey]", account.getIn(["options", "memo_key"]), privKey ); let buffer = edgeTx.toBuffer(tx); let signedHex = Signature.signBuffer(buffer, privKey).toHex(); debug("[LoginEdgeQuery Signed]", signedHex); (tx as Edge.RequestWithSigner).signer = signedHex; return tx as Edge.RequestWithSigner; } // 其他 addLoading() { return 1; } removeLoading() { return 1; } } const EdgeActionsWrapped: EdgeActions = alt.createActions(EdgeActions); export { EdgeActionsWrapped as EdgeActions }; export default EdgeActionsWrapped; <file_sep>import alt from "alt-instance"; // import localeCodes from "assets/locales"; const loadzh = () => import(/* webpackChunkName: "locale-zh" */ "assets/locales/locale-zh.json"); const loaden = () => import(/* webpackChunkName: "locale-en" */ "assets/locales/locale-en.json"); class IntlActions { switchLocale(locale) { // var locale = "cn" // console.debug("[IntlStore]Translate: ", locale); // if (/cn|zh/.test(locale)) { // return { locale }; // } return dispatch => { (locale === "cn" || locale === "zh" ? loadzh : loaden)() .then(result => { dispatch({ locale, localeData: result.default }); }) .catch(err => { console.log("fetch locale error:", err); return dispatch => { // Translate: 异常返回 // dispatch({locale: ""}); dispatch({ locale: "zh" }); }; }); }; } getLocale(locale) { return locale; } } export default alt.createActions(IntlActions); <file_sep>var React = require("react"); var Accordion = React.createClass({ getInitialState: function() { return { sections: [] }; }, getDefaultProps: function() { return { autoOpen: true, multiOpen: false, collapsible: false }; }, componentWillMount: function() { var sections = []; React.Children.forEach(this.props.children, function(child, index) { sections.push({ active: false }); }); if (this.props.autoOpen) { sections[0].active = true; } this.setState({ sections: sections }); }, select: function(selectSection) { var sections = this.state.sections; sections.forEach( function(section, index) { if (this.props.multiOpen) { if (index === selectSection) { section.active = !section.active; } } else { if (index === selectSection) { section.active = this.props.collapsible === true ? !section.active : true; } else { section.active = false; } } }.bind(this) ); this.setState({ sections: sections }); }, render: function() { var children = React.Children.map( this.props.children, function(child, index) { return React.cloneElement(child, { active: this.state.sections[index] ? this.state.sections[index].active : false, activate: this.select.bind(this, index) }); }.bind(this) ); return <div className="accordion">{children}</div>; } }); module.exports = Accordion; Accordion.Item = require("./item"); <file_sep>import BaseStore from "./BaseStore"; import { Set } from "immutable"; import alt from "alt-instance"; import { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; const debug = debugGen("NetworkStore"); interface NetworkInformation extends EventTarget { readonly downlink: number; readonly downlinkMax: number; readonly effectiveType: "slow-2g" | "2g" | "3g" | "4g"; readonly rtt: number; readonly type: | "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown"; onchange: any; } const connect = <NetworkInformation>(navigator as any).connection; type ApiStatus = "online" | "blocked" | "offline"; class NetworkStore extends BaseStore implements Store<{ online: boolean; apiStatus: ApiStatus; initDone: boolean }> { bindListeners; setState; state; constructor() { super(); this.state = { online: navigator.onLine, apiStatus: "offline", initDone: false }; try { if (typeof window !== undefined) { window.ononline = this.onChangeHandler; window.onoffline = this.onChangeHandler; } } catch (e) {} super._export("setInitDone", "updateApiStatus"); } setInitDone = (initDone = true) => { this.setState({ initDone }); }; updateApiStatus = apiStatus => { this.setState({ apiStatus }); }; onChangeHandler = online => { debug("beforeStateChange", this.state); this.setState({ online: navigator.onLine }); }; } const StoreWrapper = alt.createStore(NetworkStore, "NetworkStore"); export { StoreWrapper as NetworkStore }; export default StoreWrapper; <file_sep>import BaseStore from "./BaseStore"; import { List, Set, Map, fromJS } from "immutable"; import alt from "alt-instance"; import { Store } from "alt-instance"; import { EdgeActions } from "actions/EdgeActions"; import { debugGen } from "utils//Utils"; import AccountActions from "actions/AccountActions"; import ls from "lib/common/localStorage"; import { AbstractStore } from "./AbstractStore"; import { Edge, EdgeProject } from "services/edge"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("EdgeStore"); type UserInStatus = { [projectId: string]: EdgeProject.UserInStatus; }; type UserProjectStatus = { [projectId: string]: EdgeProject.UserProjectStatus; }; export type EdgeState = Edge.EdgeInfo & { loading: number; rank: null | Edge.Rank; projects: EdgeProject.ProjectDetail[]; banners: EdgeProject.Banner[]; userInSet: UserInStatus; userProjectStatus: UserProjectStatus; }; class EdgeStore extends AbstractStore<EdgeState> { state: EdgeState = { state: Edge.EdgePersonalState.Uninit, info: null, sum: 0, loading: 0, rank: null, projects: [], banners: [], userInSet: {}, userProjectStatus: {} }; constructor() { super(); this.bindListeners({ reset: AccountActions.setCurrentAccount, handleAddLoading: EdgeActions.addLoading, handleRemoveLoading: EdgeActions.removeLoading, handleInfoUpdate: EdgeActions.queryInfo }); } handleRankUpdate(rank) { this.setState({ rank }); } reset() { this.setState({ state: Edge.EdgePersonalState.Uninit, info: null, sum: 0, loading: 0, userProjectStatus: {}, projects: [] }); } handleAddLoading(count) { this.setState({ loading: 1 }); } handleRemoveLoading(count) { this.setState({ loading: 0 }); } handleInfoUpdate(info: Edge.EdgeInfo) { console.debug("Personal Info: ", info); this.setState({ ...(this as any).getInstance().getState(), ...info }); } } const StoreWrapper = alt.createStore(EdgeStore, "EdgeStore"); export { StoreWrapper as EdgeStore }; export default StoreWrapper; <file_sep>import utils from "./utils"; import { ChainStore, ChainTypes } from "cybexjs"; let { object_type } = ChainTypes; let opTypes = Object.keys(object_type); import { correctMarketPairMap } from "utils/Market"; import { BigNumber } from "bignumber.js"; const MarketUtils = { order_type(id) { if (typeof id !== "string") { return false; } let type = id.split(".")[1]; return opTypes[type]; }, isAsk(order, base) { let baseId = base.toJS ? base.get("id") : base.id; if (order.sell_price) { return order.sell_price.quote.asset_id === baseId; } else if (order.call_price) { return order.call_price.quote.asset_id === baseId; } }, isAskOp(op) { return op.amount_to_sell.asset_id !== op.fee.asset_id; }, limitByPrecision(value, asset, floor = true) { let assetPrecision = asset.toJS ? asset.get("precision") : asset.precision; let valueString = value.toString(); let splitString = valueString.split("."); if ( splitString.length === 1 || (splitString.length === 2 && splitString[1].length <= assetPrecision) ) { return value; } let precision = utils.get_asset_precision(assetPrecision); value = floor ? Math.floor(value * precision) / precision : Math.round(value * precision) / precision; if (isNaN(value) || !isFinite(value)) { return 0; } return value; }, getFeedPrice(settlement_price, invert = false) { let quoteAsset = ChainStore.getAsset( settlement_price.getIn(["quote", "asset_id"]) ); let baseAsset = ChainStore.getAsset( settlement_price.getIn(["base", "asset_id"]) ); let price = utils.get_asset_price( settlement_price.getIn(["quote", "amount"]), quoteAsset, settlement_price.getIn(["base", "amount"]), baseAsset ); if (invert) { return 1 / price; } else { return price; } }, parseOrder(order, base, quote, invert = false) { let ask = this.isAsk(order, base); let quotePrecision = utils.get_asset_precision( quote.toJS ? quote.get("precision") : quote.precision ); let basePrecision = utils.get_asset_precision( base.toJS ? base.get("precision") : base.precision ); let pricePrecision = order.call_price ? quote.toJS ? quote.get("precision") : quote.precision : base.toJS ? base.get("precision") : base.precision; let buy, sell; let callPrice; if (order.sell_price) { buy = ask ? order.sell_price.base : order.sell_price.quote; sell = ask ? order.sell_price.quote : order.sell_price.base; } else if (order.call_price) { buy = order.call_price.base; sell = order.call_price.quote; let marginPrice = buy.amount / basePrecision / (sell.amount / quotePrecision); if (!invert) { callPrice = marginPrice; } else { callPrice = 1 / marginPrice; } } if (typeof sell.amount !== "number") { sell.amount = parseInt(sell.amount, 10); } if (typeof buy.amount !== "number") { buy.amount = parseInt(buy.amount, 10); } let fullPrice = callPrice ? callPrice : sell.amount / basePrecision / (buy.amount / quotePrecision); let price = utils.price_to_text( fullPrice, order.call_price ? base : quote, order.call_price ? quote : base ); let amount, value; // We need to figure out a better way to set the number of decimals // let price_split = utils.format_number(price.full, Math.max(5, pricePrecision)).split("."); // price.int = price_split[0]; // price.dec = price_split[1]; if (order.debt) { if (invert) { // Price in USD/CYB, amount should be in CYB, value should be in USD, debt is in USD // buy is in USD, sell is in CYB // quote is USD, base is CYB value = order.debt / quotePrecision; amount = this.limitByPrecision(value / price.full, base); } else { // Price in CYB/USD, amount should be in USD, value should be in CYB, debt is in USD // buy is in USD, sell is in CYB // quote is USD, base is CYB amount = this.limitByPrecision(order.debt / quotePrecision, quote); value = price.full * amount; } } else if (!ask) { amount = this.limitByPrecision( ((buy.amount / sell.amount) * order.for_sale) / quotePrecision, quote ); value = order.for_sale / basePrecision; } else { amount = this.limitByPrecision(order.for_sale / quotePrecision, quote); value = price.full * amount; } value = this.limitByPrecision(value, base); if (!ask && order.for_sale) { value = this.limitByPrecision(price.full * amount, base); } return { value: value, price: price, amount: amount }; }, parse_order_history(order, paysAsset, receivesAsset, isAsk, flipped) { let isCall = order.order_id.split(".")[1] == object_type.limit_order ? false : true; let receivePrecision = utils.get_asset_precision( receivesAsset.get("precision") ); let payPrecision = utils.get_asset_precision(paysAsset.get("precision")); let receives = Number.parseFloat( new BigNumber(order.receives.amount).div(receivePrecision).toString() ); receives = utils.format_number(receives, receivesAsset.get("precision")); let pays = new BigNumber(order.pays.amount).div(payPrecision).toNumber(); pays = utils.format_number(pays, paysAsset.get("precision")); // let price_full = utils.get_asset_price( // order.receives.amount, // receivesAsset, // order.pays.amount, // paysAsset, // isAsk // ); // Todo check the price is right or not let [fillRec, fillPay] = order.fill_price.base.asset_id === order.receives.asset_id ? [order.fill_price.base, order.fill_price.quote] : [order.fill_price.quote, order.fill_price.base]; let price_full = utils.get_asset_price( fillRec.amount, receivesAsset, fillPay.amount, paysAsset, isAsk ); // price_full = !flipped ? (1 / price_full) : price_full; // let {int, dec} = this.split_price(price_full, isAsk ? receivesAsset.get("precision") : paysAsset.get("precision")); let { int, dec, trailing } = utils.price_to_text( price_full, isAsk ? receivesAsset : paysAsset, isAsk ? paysAsset : receivesAsset ); let className = isCall ? "orderHistoryCall" : isAsk ? "orderHistoryBid" : "orderHistoryAsk"; let time; if (order.time) { time = order.time.split("T")[1]; let now = new Date(); let offset = now.getTimezoneOffset() / 60; let date = utils.format_date(order.time).split(/\W/); let hour = time.substr(0, 2); let hourNumber = parseInt(hour, 10); let localHour = hourNumber - offset; if (localHour >= 24) { localHour -= 24; } else if (localHour < 0) { localHour += 24; } let hourString = localHour.toString(); if (parseInt(hourString, 10) < 10) { hourString = "0" + hourString; } time = date[0] + "/" + date[1] + " " + time.replace(hour, hourString); } return { receives: isAsk ? receives : pays, pays: isAsk ? pays : receives, full: price_full, int: int, dec: dec, trailing: trailing, className: className, time: time }; }, split_price(price, pricePrecision) { // We need to figure out a better way to set the number of decimals let price_split = utils .format_number(price, Math.max(5, pricePrecision)) .split("."); let int = price_split[0]; let dec = price_split[1]; return { int: int, dec: dec }; }, // flatten_orderbookchart(array, sumBoolean, inverse, precision) { // inverse = inverse === undefined ? false : inverse; // let orderBookArray = []; // let maxStep, arrayLength = array.length; // // Sum orders at same price // // if (arrayLength > 1) { // // for (var i = arrayLength - 2; i >= 0; i--) { // // if (array[i].x === array[i + 1].x) { // // console.log("found order to sum"); // // array[i].y += array[i + 1].y; // // array.splice(i + 1, 1); // // } // // } // // } // // arrayLength = array.length; // if (inverse) { // if (array && arrayLength) { // arrayLength = arrayLength - 1; // orderBookArray.unshift({ // x: array[arrayLength].x, // y: array[arrayLength].y // }); // if (array.length > 1) { // for (let i = array.length - 2; i >= 0; i--) { // // maxStep = Math.min((array[i + 1].x - array[i].x) / 2, 0.1 / precision); // orderBookArray.unshift({ // x: array[i].x + maxStep, // y: array[i + 1].y // }); // if (sumBoolean) { // array[i].y += array[i + 1].y; // } // orderBookArray.unshift({ // x: array[i].x, // y: array[i].y // }); // } // } else { // orderBookArray.unshift({ // x: 0, // y: array[arrayLength].y // }); // } // } // } else { // if (array && arrayLength) { // orderBookArray.push({ // x: array[0].x, // y: array[0].y // }); // if (array.length > 1) { // for (let i = 1; i < array.length; i++) { // // maxStep = Math.min((array[i].x - array[i - 1].x) / 2, 0.1 / precision); // orderBookArray.push({ // x: array[i].x - maxStep, // y: array[i - 1].y // }); // if (sumBoolean) { // array[i].y += array[i - 1].y; // } // orderBookArray.push({ // x: array[i].x, // y: array[i].y // }); // } // } else { // orderBookArray.push({ // x: array[0].x * 1.5, // y: array[0].y // }); // } // } // } // return orderBookArray; // } flatten_orderbookchart_highcharts(array, sumBoolean, inverse, precision) { inverse = inverse === undefined ? false : inverse; let orderBookArray = []; let arrayLength; if (inverse) { if (array && array.length) { arrayLength = array.length - 1; orderBookArray.unshift([array[arrayLength][0], array[arrayLength][1]]); if (array.length > 1) { for (let i = array.length - 2; i >= 0; i--) { if (sumBoolean) { array[i][1] += array[i + 1][1]; } orderBookArray.unshift([array[i][0], array[i][1]]); } } else { orderBookArray.unshift([0, array[arrayLength][1]]); } } } else { if (array && array.length) { orderBookArray.push([array[0][0], array[0][1]]); if (array.length > 1) { for (var i = 1; i < array.length; i++) { if (sumBoolean) { array[i][1] += array[i - 1][1]; } orderBookArray.push([array[i][0], array[i][1]]); } } else { orderBookArray.push([array[0][0] * 1.5, array[0][1]]); } } } return orderBookArray; }, priceToObject(x, type) { let tolerance = 1.0e-8; let h1 = 1; let h2 = 0; let k1 = 0; let k2 = 1; let b = x; do { let a = Math.floor(b); let aux = h1; h1 = a * h1 + h2; h2 = aux; aux = k1; k1 = a * k1 + k2; k2 = aux; b = 1 / (b - a); } while (Math.abs(x - h1 / k1) > x * tolerance); if (type === "ask") { return { base: h1, quote: k1 }; } else if (type === "bid") { return { quote: h1, base: k1 }; } else { throw "Unknown type"; } }, isMarketAsset(quote, base) { let isMarketAsset = false, marketAsset, inverted = false; if ( quote.get("bitasset") && base.get("id") === quote.getIn(["bitasset", "options", "short_backing_asset"]) ) { isMarketAsset = true; marketAsset = { id: quote.get("id") }; } else if ( base.get("bitasset") && quote.get("id") === base.getIn(["bitasset", "options", "short_backing_asset"]) ) { inverted = true; isMarketAsset = true; marketAsset = { id: base.get("id") }; } return { isMarketAsset, marketAsset, inverted }; }, getMarketID(_base, _quote) { if (!_base || !_quote) return { marketId: "_" }; let { base, quote } = correctMarketPairMap(_base, _quote); let baseID = parseInt(base.get("id").split(".")[2], 10); let quoteID = parseInt(quote.get("id").split(".")[2], 10); const marketID = `${quote.get("symbol")}_${base.get("symbol")}`; return { baseID, quoteID, marketID, first: quote, second: base }; } }; export default MarketUtils; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import Trigger from "react-foundation-apps/src/trigger"; import BaseModal from "../Modal/BaseModal"; import ZfApi from "react-foundation-apps/src/utils/foundation-api"; import PasswordInput from "../Forms/PasswordInput"; import { Button } from "components/Common"; import notify from "actions/NotificationActions"; import Translate from "react-translate-component"; import counterpart from "counterpart"; import AltContainer from "alt-container"; import WalletDb from "stores/WalletDb"; import WalletUnlockStore from "stores/WalletUnlockStore"; import AccountStore from "stores/AccountStore"; import WalletUnlockActions from "actions/WalletUnlockActions"; import AccountActions from "actions/AccountActions"; import SettingsActions from "actions/SettingsActions"; import { Apis } from "cybexjs-ws"; import utils from "common/utils"; import AccountSelector from "../Account/AccountSelector"; import { Gtag } from "services/Gtag"; var logo = require("assets/cybex-logo.png"); class WalletUnlockModal extends React.Component { static contextTypes = { router: PropTypes.object }; constructor(props) { super(); this.state = this._getInitialState(props); this.onPasswordEnter = this.onPasswordEnter.bind(this); } _getInitialState(props = this.props) { return { password_error: null, password_input_reset: Date.now(), account_name: props.passwordAccount, account: null }; } reset() { this.setState(this._getInitialState()); } componentWillReceiveProps(np) { if (np.passwordAccount && !this.state.account_name) { this.setState({ account_name: np.passwordAccount }); } if (np.resolve != this.props.resolve) { try { this.refs.password_input.clear(); } catch (e) {} } } shouldComponentUpdate(np, ns) { return ( !utils.are_equal_shallow(np, this.props) || !utils.are_equal_shallow(ns, this.state) ); } componentDidMount() { ZfApi.subscribe(this.props.modalId, (name, msg) => { if (name !== this.props.modalId) return; if (msg === "close") { //if(this.props.reject) this.props.reject() this.refs.password_input.clear(); WalletUnlockActions.cancel(); } else if (msg === "open") { if (!this.props.passwordLogin) { if (this.refs.password_input) { this.refs.password_input.focus(); this.refs.password_input.clear(); } if ( WalletDb.getWallet() && Apis.instance().chain_id !== WalletDb.getWallet().chain_id ) { notify.error( "This wallet was intended for a different block-chain; expecting " + WalletDb.getWallet() .chain_id.substring(0, 4) .toUpperCase() + ", but got " + Apis.instance() .chain_id.substring(0, 4) .toUpperCase() ); ZfApi.publish(this.props.modalId, "close"); return; } } } }); if (this.props.passwordLogin) { // this.refs.password_input.clear(); if (this.state.account_name) { this.refs.password_input.focus(); } else if ( this.refs.account_input && this.refs.account_input.refs.bound_component ) { // this.refs.account_input.refs.bound_component.refs.user_input.focus(); } } } componentDidUpdate() { //DEBUG console.log('... componentDidUpdate this.props.resolve', this.props.resolve) if (this.props.resolve) { if (WalletDb.isLocked()) ZfApi.publish(this.props.modalId, "open"); else this.props.resolve(); } } onPasswordEnter(e) { const { passwordLogin } = this.props; e.preventDefault(); const password = this.refs.password_input.value(); const account = passwordLogin ? this.state.account && this.state.account.get("name") : null; this.setState({ password_error: null }); WalletDb.validatePassword( password || "", true, //unlock account ); if (WalletDb.isLocked()) { this.setState({ password_error: true }); return false; } else { this.refs.password_input.clear(); if (passwordLogin) { AccountActions.setPasswordAccount(account); } ZfApi.publish(this.props.modalId, "close"); this.props.resolve(); WalletUnlockActions.change(); this.setState({ password_input_reset: Date.now(), password_error: false }); try { Gtag.eventUnlock(account, passwordLogin ? "cloud" : "bin"); } catch (e) {} } return false; } _toggleLoginType() { SettingsActions.changeSetting({ setting: "passwordLogin", value: !this.props.passwordLogin }); } _onCreateWallet() { ZfApi.publish(this.props.modalId, "close"); this.context.router.history.push("/create-account/wallet"); } renderWalletLogin() { if (!WalletDb.getWallet()) { return ( <div> <Translate content="wallet.no_wallet" component="p" /> <div className="button-group"> <div className="button" onClick={this._onCreateWallet.bind(this)}> <Translate content="wallet.create_wallet" /> </div> </div> {/* <div onClick={this._toggleLoginType.bind(this)} className="button small outline float-right"><Translate content="wallet.switch_model_password" /></div> */} </div> ); } return ( <form className="full-width" onSubmit={this.onPasswordEnter} noValidate style={{ paddingTop: 20, margin: "0 3.5rem " }} > <PasswordInput ref="password_input" onEnter={this.onPasswordEnter} key={this.state.password_input_reset} wrongPassword={<PASSWORD>.password_error} noValidation /> <div> <div className="button-group" style={{ width: "100%", display: "flex" }} > <button className="button primary" style={{ flex: 1 }} data-place="bottom" data-html data-tip={counterpart.translate("tooltip.login")} onClick={this.onPasswordEnter} > <Translate content="header.unlock_short" /> </button> <Trigger close={this.props.modalId}> <Translate component="div" style={{ flex: 1 }} className="button" content="account.perm.cancel" /> </Trigger> </div> {/* <div onClick={this._toggleLoginType.bind(this)} className="button small outline float-right"><Translate content="wallet.switch_model_password" /></div> */} </div> </form> ); } accountChanged(account_name) { if (!account_name) this.setState({ account: null }); this.setState({ account_name, error: null }); } onAccountChanged(account) { this.setState({ account, error: null }); } renderPasswordLogin() { let { account_name, from_error } = this.state; let tabIndex = 1; return ( <form onSubmit={this.onPasswordEnter} noValidate style={{ paddingTop: 20 }} > {/* Dummy input to trick Chrome into disabling auto-complete */} <input type="text" className="no-padding no-margin" style={{ visibility: "hidden", height: 0 }} /> <div className="form-wrapper" style={{ marginRight: "3.5rem" }}> <div className="content-block"> <AccountSelector label="account.name" ref="account_input" accountName={account_name} onChange={this.accountChanged.bind(this)} onAccountChanged={this.onAccountChanged.bind(this)} account={account_name} size={60} styleSize="normal" error={from_error} tabIndex={tabIndex++} /> </div> <div className="content-block"> <div className="account-selector"> <div className="content-area"> <div className="header-area"> <label className="left-label"> <Translate content="settings.password" /> </label> </div> <div className="input-area" style={{ marginLeft: "3.5rem" }}> <PasswordInput ref="password_input" name="password" id="password" wrongPassword={this.state.password_error} noValidation noLabel checkStrength showStrengthTip isSimple /> {/* <input ref="password_input" name="password" id="password" type="password" tabIndex={tabIndex++} /> */} </div> {/* {this.state.password_error ? ( <div className="error-area"> <Translate content="wallet.pass_incorrect" /> </div> ) : null} */} </div> </div> </div> </div> <div className="grid-block shrink"> <div className="grid-block full-width-content" style={{ alignItems: "center" }} > <Button type="primary" onClick={this.onPasswordEnter}> <Translate content="header.unlock_password" /> </Button> <Trigger close={this.props.modalId}> <Button type="secondary" onClick={this.onPasswordEnter}> <Translate content="account.perm.cancel" /> </Button> </Trigger> </div> {/* <div onClick={this._toggleLoginType.bind(this)} className="button small outline float-right"><Translate content="wallet.switch_model_wallet" /></div> */} </div> </form> ); } render() { const { passwordLogin } = this.props; // DEBUG console.log('... U N L O C K',this.props) // Modal overlayClose must be false pending a fix that allows us to detect // this event and clear the password (via this.refs.password_input.clear()) // https://github.com/akiran/react-foundation-apps/issues/34 return ( // U N L O C K <BaseModal id={this.props.modalId} ref="modal" overlay={true} overlayClose={false} > <div className="text-center"> <img src={logo} /> <div style={{ marginTop: "1rem" }}> <Translate component="h4" content={"header.unlock" + (passwordLogin ? "_password" : "")} /> </div> </div> {passwordLogin ? this.renderPasswordLogin() : this.renderWalletLogin()} </BaseModal> ); } } WalletUnlockModal.defaultProps = { modalId: "unlock_wallet_modal2" }; class WalletUnlockModalContainer extends React.Component { render() { return ( <AltContainer stores={[WalletUnlockStore, AccountStore]} inject={{ resolve: () => { return WalletUnlockStore.getState().resolve; }, reject: () => { return WalletUnlockStore.getState().reject; }, locked: () => { return WalletUnlockStore.getState().locked; }, passwordLogin: () => { return WalletUnlockStore.getState().passwordLogin; }, passwordAccount: () => { return AccountStore.getState().passwordAccount || ""; } }} > <WalletUnlockModal {...this.props} /> </AltContainer> ); } } export default WalletUnlockModalContainer; <file_sep>require("./stylesheets/chunk-1.scss"); require("./stylesheets/app.scss"); // require("./stylesheets/chunk-0.scss"); require("react-table/react-table.css"); // Temp For Asset Symbols <file_sep>var React = require("react"); var ActionSheet = require("../../lib/action-sheet"); var BasicActionSheet = React.createClass({ render: function() { return ( <ActionSheet> <ActionSheet.Button title="Action Sheet" /> <ActionSheet.Content> <p>Tap to share</p> <ul> <li> <a href="#">Twitter</a> </li> <li> <a href="#">Facebook</a> </li> <li> <a href="#">Mail</a> </li> </ul> </ActionSheet.Content> </ActionSheet> ); } }); module.exports = BasicActionSheet; <file_sep>import Apis from "./src/ApiInstances"; import Manager from "./src/ConnectionManager"; import ChainConfig from "./src/ChainConfig"; export {Apis, ChainConfig, Manager}; <file_sep>> React Foundation Apps is a react port of Foundation Apps Foundation Apps is a new framework for building web apps. It has awesome new features like flexbox based grid, motion-ui, and several core components for building web apps. But, javascript components of foundation-apps are built with angular. Try React Foundation Apps, if you want to use react. React Foundation Apps lets you avail the benefits of both React and Foundation Apps. Checkout [documentation](http://webrafter.com/opensource/react-foundation-apps) ### Installation ```bash npm install react-foundation-apps ``` Don't forget to install foundation-apps for css components ```bash bower install foundation-apps ``` ### Usage Currently, built tools like browserify or webpack are required for using react-foundation-apps. All the components are in react-foundation-apps/lib. You can import the required components like so ```javascript var Accordion = require('react-foundation-apps/lib/accordion'); ``` ### Example ```javascript var React = require('react'); var Accordion = require('react-foundation-apps/lib/accordion'); var SampleAccordion = React.createClass({ render: function () { return ( <Accordion> <Accordion.Item title='First item title'> First item content </Accordion.Item> <Accordion.Item title='Second item title'> Second item content </Accordion.Item> <Accordion.Item title='Third item title'> Third item content </Accordion.Item> </Accordion> ); } }); module.exports = SampleAccordion; ``` ### Sponsors If your company likes to sponsor this project, contact me. <file_sep>import alt from "alt-instance"; type notification = { message: string, level?: string, autoDismiss?: number } const normalize = (notification: notification, level?) => { if (typeof notification == "string") notification = { message: notification }; if (level) notification.level = level; // Adjust the css position for notices.. bottom messages can't be seen //if(notification.level === "success" && ! notification.position) // notification.position = 'br' //bottom right return notification; }; class NotificationActions { addNotification(notification) { notification = normalize(notification); return notification; } // Creating aliases: success, error, warning and info success(notification) { notification = normalize(notification, "success"); return notification; } error(notification) { notification = normalize(notification, "error"); return notification; } warning(notification) { notification = normalize(notification, "warning"); return notification; } info(notification) { notification = normalize(notification, "info"); return notification; } } let NotificationActionsWrapper: NotificationActions = alt.createActions(NotificationActions); export { NotificationActionsWrapper as NotificationActions } export default NotificationActionsWrapper <file_sep>type AssetSymbol = string; type Priority = number; type Markets = { base_markets: AssetSymbol[]; quote_markets: AssetSymbol[]; special_markets: { [AssetSymbol: string]: Priority }; //{ "JADE.MT": { "JADE.ETH": 0, CYB: 1, "JADE.BTC": 2 } } /* { CYB: { "JADE.DPY": -1 }, "JADE.ETH": { "JADE.DPY": -1 }, // "JADE.BTC": { "JADE.GNX": -1 }, // "JADE.EOS": { "JADE.GNX": -1 } }; */ fixed_markets: { [AssetSymbol: string]: { [AssetSymbol: string]: Priority; }; }; }; <file_sep>let ids = { id: -1 }; export const getId = (prefix = "id") => { if (!(prefix in ids)) { ids[prefix] = -1; } return `$${prefix}__${++ids[prefix]}`; }; <file_sep>import BaseStore from "./BaseStore"; import Immutable from "immutable"; import alt from "alt-instance"; import EoActions from "actions/EoActions"; class AssetStore extends BaseStore { constructor() { super(); this.bindListeners({ getList: EoActions.getList }); } onGetAssetList(payload) { } onLookupAsset(payload) { } } export default alt.createStore(EoStore, "EoStore"); <file_sep>var React = require('react'); var foundationApi = require('../utils/foundation-api'); var ActionSheet = React.createClass({ getInitialState: function () { return {active: false}; }, setActiveState: function (active) { this.setState({active: active}); }, onBodyClick: function (e) { var el = e.target; var insideActionSheet = false; do { if(el.classList && el.classList.contains('action-sheet-container') && el.id === this.props.id) { insideActionSheet = true; break; } } while ((el = el.parentNode)); if(!insideActionSheet) { this.setActiveState(false); } }, componentDidMount: function () { if(this.props.id) { foundationApi.subscribe(this.props.id, function (name, msg) { if (msg === 'open') { this.setState({active: true}); } else if (msg === 'close') { this.setState({active: false}); } else if (msg === 'toggle') { this.setState({active: !this.state.active}); } }.bind(this)); } document.body.addEventListener('click', this.onBodyClick); }, componentWillUnmount: function () { if(this.props.id) foundationApi.unsubscribe(this.props.id); document.body.removeEventListener('click', this.onBodyClick); }, render: function () { var children = React.Children.map(this.props.children, function (child, index) { var extraProps = {active: this.state.active}; if (child.type.displayName === 'ActionSheetButton') { extraProps.setActiveState = this.setActiveState; } return React.cloneElement(child, extraProps); }.bind(this)); return ( <div id={this.props.id} data-closable={true} className='action-sheet-container'> {children} </div> ); } }); module.exports = ActionSheet; ActionSheet.Button = require('./button'); ActionSheet.Content = require('./content'); <file_sep>declare module "cybexjs" { class Serializer { constructor(operation_name: string, types: { [p: string]: any }); fromByteBuffer(b); appendByteBuffer(b, object); fromObject(serialized_object); toObject( serialized_object, debug: { use_default?: boolean; annotate?: boolean } ); compare(a, b); fromHex(hex); fromBuffer(buffer); toHex(object); toByteBuffer(objectt); toBuffer(object); } const ops: { [op: string]: Serializer }; class Signature { constructor(r1, s1, i1); static fromBuffer(buf): Signature; toBuffer(); recoverPublicKeyFromBuffer(buffer); static signBuffer(buf, private_key); static signBufferSha256(buf_sha256, private_key); static sign(string, private_key); verifyBuffer(buf, public_key); verifyHash(hash, public_key); toByteBuffer(); static fromHex(hex); toHex(); static signHex(hex, private_key); verifyHex(hex, public_key); } type ParamsOfCheck = { accountName: string; password: string; auths: { [x: string]: [string, number][] }; }; class AccountLogin { checkKeys: (paramsToCheck: ParamsOfCheck) => boolean; generateKeys( accountName: string, password: string, roles?: string[], prefix?: string ): any; signTransaction(tr: any): void; } const Login: AccountLogin; class ChainStoreClass { resetCache(): void; getObjectByVoteID: any; getWitnessById: any; getCommitteeMemberById: any; init: () => Promise<any>; subscribe(handler: (obj: object) => any): void; unsubscribe(handler: (obj: object) => any): void; fetchFullAccount: any; getEstimatedChainTimeOffset: any; subError: any; subscribed: any; getObject(id: string, ...args): any; getAsset(symbolOrId: string): any; getBalanceObjects(id: string | string[]): any; getAccount(name_or_id: string, autosubscribe?: boolean): any; } const ChainStore: ChainStoreClass; const TransactionBuilder: any; const FetchChain: (apiMethod: string, ...args: any[]) => Promise<any>; const TransactionHelper: any; const Aes: any; const PublicKey: any; const FetchChainObjects: any; const PrivateKey: any; const ChainTypes: any; const ChainValidation: { is_account_name: (value, allow_too_short?) => boolean; is_object_id: (id: string) => boolean; is_empty: (value, allow_too_short?) => boolean; is_account_name_error: (value, allow_too_short?) => boolean; is_cheap_name: (value, allow_too_short?) => boolean; is_empty_user_input: (value) => boolean; is_valid_symbol_error: (value, arg?) => boolean; required: (value, field_name?) => boolean; }; const key: { addresses(pubkey: any): string[]; get_random_key: any; }; const EmitterInstance: any; const types: any; } <file_sep>var React = require("react"); var ReactDOM = require("react-dom"); var ExecutionEnvironment = require("react/lib/ExecutionEnvironment"); var IconicJs = ExecutionEnvironment.canUseDOM && require("../vendor/iconic.min"); var Iconic = React.createClass({ inject: function() { var ico = IconicJs(); ico.inject(ReactDOM.findDOMNode(this)); }, componentDidMount: function() { this.inject(); }, componentDidUpdate: function() { this.inject(); }, render: function() { return React.Children.only(this.props.children); } }); module.exports = Iconic; <file_sep>export const DATETIME_FORMAT_FULL = "YYYY-MM-DD HH:mm:ss";<file_sep>import { debugGen } from "utils"; import alt from "alt-instance"; const debug = debugGen("GatewayActions"); import { NotificationActions } from "actions//NotificationActions"; import SettingsStore from "stores/SettingsStore"; class IEOActions { async updateAccountIEORecord(account: Cybex.Account) { if (!account || !account.get) return; } onIEORecordUpdate(records: ETO.ETORecord[]) { return records; } } const IEOActionsWrapper: IEOActions = alt.createActions(IEOActions); export { IEOActionsWrapper as IEOActions }; export default IEOActions; <file_sep>const { loaders, resolve, plugins, BASE_URL, outputPath, externals, defines } = require("./webpack.config"); const CompressionPlugin = require("compression-webpack-plugin"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer") .BundleAnalyzerPlugin; const HtmlWebpackPlugin = require("html-webpack-plugin"); const Clean = require("clean-webpack-plugin"); const PreloadWebpackPlugin = require("preload-webpack-plugin"); const path = require("path"); console.log("Webpack Config for Prod"); const webpack = require("webpack"); const UglifyPlugin = require("uglifyjs-webpack-plugin"); var OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const MomentLocalesPlugin = require("moment-locales-webpack-plugin"); const cssLoaders = [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader" }, { loader: "postcss-loader", options: { plugins: [require("autoprefixer")] } } ] }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader" }, { loader: "postcss-loader", options: { plugins: [require("autoprefixer")], options: { minimize: true, debug: false } } }, { loader: "sass-loader", options: { outputStyle: "expanded", minimize: true, debug: false } } ] } ]; // PROD OUTPUT PATH let outputDir = "dist"; // outputPath = // DIRECTORY CLEANER var cleanDirectories = [outputDir]; const prodPlugins = plugins.concat([ new HtmlWebpackPlugin({ filename: "index.html", template: path.resolve(BASE_URL, "app/assets/index.html") }), new Clean(cleanDirectories, { root: BASE_URL }), new PreloadWebpackPlugin({}), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") }, __DEV__: false, __PERFORMANCE_DEVTOOL__: false, __DEPRECATED__: false, ...defines }), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name]-[hash:7].css", chunkFilename: "[id]-[hash:7].css" }), new BundleAnalyzerPlugin(), // Here is useful when use some spec lib, eg. Rxjs6 new webpack.optimize.ModuleConcatenationPlugin(), new CompressionPlugin(), new MomentLocalesPlugin({ localesToKeep: ["es-us", "zh-cn", "vi"] }) ]); const config = { entry: { styles: path.resolve(BASE_URL, "app/assets/style-loader.js"), app: path.resolve(BASE_URL, "app/Main.js") }, context: path.resolve(BASE_URL, "app"), output: { publicPath: "/", path: path.join(BASE_URL, outputDir), filename: "[name]-[hash:7].js", chunkFilename: "[name]-[chunkhash:7].js" }, mode: "production", devtool: "none", module: { rules: loaders.concat(cssLoaders) }, resolve, // externals, plugins: prodPlugins, node: { fs: "empty" }, optimization: { splitChunks: { cacheGroups: { styles: { name: "styles", test: /\.css$/, chunks: "all", enforce: true }, "components-account": { test: /components\/Account/, name: "components-account", chunks: "initial", enforce: true }, "components-blockchain": { test: /components\/Blockchain/, name: "components-blockchain", chunks: "initial", enforce: true }, "components-common": { test: /components\/Common/, name: "components-common", chunks: "initial", enforce: true }, "components-exchange": { test: /components\/Exchange/, name: "components-exchange", chunks: "initial", enforce: true }, "components-explorer": { test: /components\/Explorer/, name: "components-explorer", chunks: "initial", enforce: true }, "components-settings": { test: /components\/Settings/, name: "components-settings", chunks: "initial", enforce: true }, "components-wallet": { test: /components\/Wallet/, name: "components-wallet", chunks: "initial", enforce: true }, "components-utility": { test: /components\/Utility/, name: "components-utility", chunks: "initial", enforce: true }, "components-login": { test: /components\/Login/, name: "components-login", chunks: "initial", enforce: true }, "components-layout": { test: /components\/Layout/, name: "components-layout", chunks: "initial", enforce: true }, "lib-cybex": { test: /cybexjs|cybexjs-ws/, name: "lib-cybex", chunks: "initial", enforce: true }, "lib-common": { test: /lib\/common/, name: "lib-common", chunks: "initial", enforce: true }, "lib-translate": { test: /lib\/counterpart/, name: "lib-translate", chunks: "initial", enforce: true }, "lib-chart": { test: /react-stockcharts/, name: "lib-chart", chunks: "initial", enforce: true }, "lib-chart-base": { test: /highcharts/, name: "lib-chart-base", chunks: "all", enforce: true }, "lib-container": { test: /lib\/alt-react/, name: "lib-container", chunks: "initial", enforce: true }, "lib-theme": { test: /lib\/react-foundation-apps|radium/, name: "lib-theme", chunks: "initial", enforce: true }, "lib-crypto": { test: /core-js|elliptic/, name: "lib-crypto", chunks: "initial", enforce: true }, "lib-moment": { test: /moment/, name: "lib-moment", chunks: "all", enforce: true }, react: { test: /react-dom/, name: "react-dom", chunks: "initial", enforce: true }, reactdom: { test: /^react$/, name: "react", chunks: "initial", enforce: true }, // asset: { // test: /asset/, // name: "asset", // chunks: "all" // // enforce: true // }, d3: { test: /d3/, name: "d3", chunks: "all", enforce: true } // commons: { // test: /node_modules/, // name: "commons", // chunks: "initial", // enforce: true, // priority: -20 // } } }, minimizer: [ new UglifyPlugin({ cache: true, parallel: true, extractComments: true, sourceMap: false // set to true if you want JS source maps }), new OptimizeCssAssetsPlugin({ // assetNameRegExp: /\.optimize\.css$/g, cssProcessor: require("cssnano"), cssProcessorOptions: { discardComments: { removeAll: true } }, canPrint: true }) ] } }; module.exports = config; <file_sep># 用户发行的资产 除了之前提到的 *市场锚定资产* 外,Cybex允许个人或公司用户创建和发行各种自定义资产凭证(UIA)。相关的应用场景数不胜数。比如,UIA可被用来代替简单的活动门票,存入合格用户的手机钱包中,在进入活动现场时进行实时验证。同样,UIA可被用来进行众筹、所有权追踪,甚至是代表公司的股权。 显然,适用于不同凭证使用场景的法律法规可能天差地别,尤其是在不同国家时。所以,Cybex提供了一组工具来帮助发行人来合规发行和管理UIA。<file_sep>const path = require("path"); const GitRevisionPlugin = require("git-revision-webpack-plugin"); const git = require("git-rev-sync"); const CopyWebpackPlugin = require("copy-webpack-plugin"); require("es6-promise").polyfill(); // BASE APP DIR let gitRevisionPlugin = new GitRevisionPlugin({ branch: true }); const isTest = JSON.stringify(gitRevisionPlugin.branch()).indexOf("test") !== -1 || (process.env.NODE_ENV_TEST && process.env.NODE_ENV_TEST.toLowerCase() === "test"); const isTestStaging = process.env.NODE_ENV_TEST && process.env.NODE_ENV_TEST.toLowerCase() === "staging"; const isForSecruity = process.env.NODE_ENV_TEST && process.env.NODE_ENV_TEST.toLowerCase() === "security"; const BASE_URL = path.resolve(__dirname, "./.."); let root_dir = BASE_URL; console.log("ROOT: ", root_dir); const defines = { APP_VERSION: JSON.stringify(git.tag()), __TEST__: isTest, __FOR_SECURITY__: isForSecruity, __STAGING__: isTestStaging, __ICOAPE__: isTestStaging ? JSON.stringify("https://www.icoape.com/") : isTest ? JSON.stringify("http://172.16.58.3:8083/") : JSON.stringify("https://www.icoape.com/"), __BASE_URL__: JSON.stringify("/") }; var outputPath = path.join(BASE_URL, "assets"); var plugins = [ // new webpack.optimize.OccurrenceOrderPlugin(), new CopyWebpackPlugin([ { from: path.join(root_dir, "charting_library"), to: "charting_library" } ]) ]; const loaders = [ { test: /\.tsx|\.ts$/, include: [path.join(root_dir, "app")], use: [ { loader: "babel-loader", options: { compact: false, cacheDirectory: true, plugins: ["react-hot-loader/babel"] } }, { loader: "awesome-typescript-loader", options: { useCache: true, transpileOnly: true } } ] }, { test: /\.js$|\.jsx$/, include: [path.join(root_dir, "app")], exclude: [/node_modules/], loader: "babel-loader", options: { compact: false, cacheDirectory: true, plugins: ["react-hot-loader/babel"] } }, { test: /\.json/, loader: "json-loader", type: "javascript/auto" }, { test: /\.png/, include: [path.resolve(root_dir, "app/assets/asset-symbols")], use: [ { loader: "file-loader", options: { name: "[path][name].[ext]" } } ] }, { test: /\.coffee$/, loader: "coffee-loader" }, { test: /\.(coffee\.md|litcoffee)$/, loader: "coffee-loader?literate" }, { test: /\.(gif|jpg|woff|woff2|eot|ttf|svg)(\?.*$|$)/, include: [path.resolve(root_dir, "app/assets/")], use: [ { loader: "url-loader", options: { limit: 8192 } } ] }, { test: /\.(gif|jpg|woff|woff2|eot|ttf|svg)$/, include: [path.resolve(root_dir, "app/components/Common")], use: [ { loader: "url-loader", options: { limit: 8192 } } ] }, { test: /\.png$/, exclude: [ path.resolve(root_dir, "app/assets/asset-symbols"), path.resolve(root_dir, "app/assets/images"), path.resolve(root_dir, "app/assets/language-dropdown/img") ], use: [ { loader: "url-loader", options: { limit: 8192 } } ] }, { test: /\.woff$/, use: [ { loader: "url-loader", options: { limit: 100000, mimetype: "application/font-woff" } } ] }, { test: /.*\.svg$/, exclude: [path.resolve(root_dir, "app/components/Common")], use: [ { loader: "svg-inline-loader" }, { loader: "svgo-loader", options: { plugins: [ { cleanupAttrs: true }, { removeMetadata: true }, { removeXMLNS: true }, { removeViewBox: false } ] } } ] }, { test: /\.md/, use: [ { loader: "html-loader", options: { removeAttributeQuotes: false } }, { loader: "markdown-loader", options: { // preset: "full", // typographer: true } } ] } ]; const resolve = { alias: { iconfont: path.resolve(root_dir, "app/assets/stylesheets/iconfont"), assets: path.resolve(root_dir, "app/assets"), counterpart: path.resolve(root_dir, "app/lib/counterpart"), "react-stockcharts": path.resolve(root_dir, "app/lib/react-stockcharts"), "alt-react": path.resolve(root_dir, "app/lib/alt-react"), "react-foundation-apps": path.resolve( root_dir, "app/lib/react-foundation-apps" ), app: path.resolve(root_dir, "app") }, modules: [ path.resolve(root_dir, "app"), path.resolve(root_dir, "app/lib"), path.resolve(root_dir, "app/cybex"), "node_modules" ], extensions: [ ".ts", ".tsx", ".js", ".jsx", ".coffee", ".json", ".scss", ".ttf", ".eot", ".woff", ".json", ".woff2" ] }; module.exports = { BASE_URL, outputPath, defines, loaders, resolve, plugins, externals: {} }; <file_sep>```html <Tabs> <Tabs.Tab title='Tab 1'> Tab 1 content </Tabs.Tab> <Tabs.Tab title='Tab 2'> Tab 2 content </Tabs.Tab> <Tabs.Tab title='Tab 3'> Tab 3 content </Tabs.Tab> </Tabs> ```<file_sep>import alt from "alt-instance"; import {Component} from "react"; export type ContextMenuItem = Component | HTMLElement; export type ContextMenuList = ContextMenuItem[]; let menuId = 0; export const getMenuId = () => `$menuId#${menuId++}`; class ContextMenuActions { addMenu(menuId: string, menuList: ContextMenuList) { return { menuId, menuList }; } detachMenu(menuId: string) { return menuId; } clearMenu(trueClear = true) { return trueClear; } } const ContextMenuActionsWrapped = alt.createActions(ContextMenuActions); export default ContextMenuActionsWrapped; <file_sep># alt-react * Connect your react component to your flux store. * Automatically pass the flux instance to your component. * Has hooks for shouldComponentUpdate, didMount, willMount, etc. * Can be extended to create your own connectors. Example ```js import { connect } from 'alt-react' import React from 'react' import UserStore from '../stores/UserStore' class MyComponent extends React.Component { render() { return <div>Hello, {this.props.userName}!</div> } } connect(MyComponent, { listenTo() { return [UserStore] }, getProps() { return { userName: UserStore.getUserName(), } }, }) ``` and providing the flux context at your root component ```js import { supplyFluxContext } from 'alt-react' export default supplyFluxContext(alt)(Root) ``` <file_sep>```html <Trigger popupToggle='basic-popup'> <a className='button'>popup</a> </Trigger> <Popup id='basic-popup'> <p>some popup content</p> </Popup> ```<file_sep>export enum EdgeStage { Apply, Locking, Result } let currentTimestamp = new Date(); const LockingTime = new Date(); export const setCurrentTimestamp = (timeStamp: Date) => (currentTimestamp = timeStamp); // export const getCurrentEdgeStage = <file_sep>// require("file-loader?name=images/[name].png!./icon_home_1.png"); // require("file-loader?name=images/[name].png!./icon_home_2.png"); // require("file-loader?name=images/[name].png!./icon_home_3.png"); // require("file-loader?name=images/[name].png!./icon_home_4.png"); require("file-loader?name=images/[name].png!./logo-main.png");<file_sep>活跃权限用来设定拥有花费本账户资金权限的账户名或公钥。 可方便的架设多重签名机制,参见 [权限](accounts/permissions) 了解更新信息。 **如果您的账户中有锁定期资产,请务必谨慎删除您的相关有效公钥。锁定期资产与特定公钥相关联,一旦您移除了锁定期资产关联的公钥,您的锁定期资产将无发申领。如果您不能确定锁定期资产所关联的公钥,请解锁您的账户并在锁定期资产页面查看对应公钥**<file_sep>//Foundation-apps/js/services/foundation.core.js function headerHelper(classArray) { var i = classArray.length; while(i--) { var meta = document.createElement('meta'); meta.className = classArray[i]; document.head.appendChild(meta); } return; } function getStyle(selector, styleName) { var elem = document.querySelectorAll(selector)[0]; var style = window.getComputedStyle(elem, null); return style.getPropertyValue('font-family'); } // https://github.com/sindresorhus/query-string function parseStyleToObject(str) { var styleObject = {}; if (typeof str !== 'string') { return styleObject; } str = str.trim().slice(1, -1); // browsers re-quote string style values if (!str) { return styleObject; } styleObject = str.split('&').reduce(function(ret, param) { var parts = param.replace(/\+/g, ' ').split('='); var key = parts[0]; var val = parts[1]; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (!ret.hasOwnProperty(key)) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } return ret; }, {}); return styleObject; } module.exports = { headerHelper: headerHelper, getStyle: getStyle, parseStyleToObject: parseStyleToObject }; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import Panel from "react-foundation-apps/src/panel"; import Trigger from "react-foundation-apps/src/trigger"; import { Link } from "react-router-dom"; import ZfApi from "react-foundation-apps/src/utils/foundation-api"; import Translate from "react-translate-component"; import AccountStore from "stores/AccountStore"; import { connect } from "alt-react"; import WalletUnlockStore from "stores/WalletUnlockStore"; import WalletManagerStore from "stores/WalletManagerStore"; import SettingsStore from "stores/SettingsStore"; import { Apis } from "cybexjs-ws"; class MobileMenu extends React.Component { constructor() { super(); this.state = {}; } static contextTypes = { router: PropTypes.object }; onClick() { ZfApi.publish("mobile-menu", "close"); } _onNavigate(route, e) { e.preventDefault(); this.context.router.history.push(route); ZfApi.publish("mobile-menu", "close"); } render() { let { id, currentAccount, linkedAccounts } = this.props; let accounts = null; if (linkedAccounts.size > 1) { accounts = linkedAccounts.map(a => { return ( <li key={a} onClick={this.onClick}> <Link to={`/account/${a}/overview`}>{a}</Link> </li> ); }); } else if (linkedAccounts.size === 1) { accounts = ( <li key="account" onClick={this.onClick}> <Link to={`/account/${linkedAccounts.first()}/overview`}> <Translate content="header.account" /> </Link> </li> ); } let linkToAccountOrDashboard; if (linkedAccounts.size > 1) linkToAccountOrDashboard = ( <a onClick={this._onNavigate.bind(this, "/dashboard")}> <Translate content="header.dashboard" /> </a> ); else if (currentAccount) linkToAccountOrDashboard = ( <a onClick={this._onNavigate.bind( this, `/account/${currentAccount}/overview` )} > <Translate content="header.account" /> </a> ); // else linkToAccountOrDashboard = <Link to="/create-account">Create Account</Link>; else linkToAccountOrDashboard = ( <a onClick={this._onNavigate.bind(this, "/create-account")}> <Translate content="account.create_login" /> </a> ); let tradeLink = this.props.lastMarket ? ( <a onClick={this._onNavigate.bind( this, `/market/${this.props.lastMarket}` )} > <Translate content="header.exchange" /> </a> ) : ( <a onClick={this._onNavigate.bind(this, "/market/CYB_JADE.ETH")}> <Translate content="header.exchange" /> </a> ); return ( <Panel id={id} position="right"> <div className="grid-content"> <Trigger close={id}> <a className="close-button">&times;</a> </Trigger> <section style={{ marginTop: "3rem" }} className="block-list"> <ul> <li>{linkToAccountOrDashboard}</li> <li> <a onClick={this._onNavigate.bind(this, "/transfer")}> <Translate content="header.payments" /> </a> </li> {/* <li> <a onClick={this._onNavigate.bind(this, "/eto")}> <Translate content="nav.eto_apply" /> </a> </li> */} {/* <li> <a onClick={this._onNavigate.bind(this, "/lockdrop")}> <Translate content="nav.lockdrop" /> </a> </li> */} <li> <a onClick={this._onNavigate.bind(this, "/lockc")}> <Translate content="nav.lockc" /> </a> </li> {/* <li> <a onClick={this._onNavigate.bind(this, "/eto/projects")}> ETO </a> </li> */} {/* {linkedAccounts.size === 0 && !currentAccount ? null : ( <li>{tradeLink}</li> )} */} {/* {linkedAccounts.size === 0 && !currentAccount ? null : ( <li> <a onClick={this._onNavigate.bind(this, "/gateway")}> <Translate content="nav.gateway" /> </a> </li> )} */} {/* {currentAccount && myAccounts.indexOf(currentAccount) !== -1 ? <li onClick={this.onClick}><Link to={"/deposit-withdraw/"}><Translate content="account.deposit_withdraw" /></Link></li> : null} */} <li> <a onClick={this._onNavigate.bind(this, "/explorer")}> <Translate content="header.explorer" /> </a> </li> <li> <a onClick={this._onNavigate.bind(this, "/settings")}> <Translate content="header.settings" /> </a> </li> </ul> </section> <section style={{ marginTop: "3rem" }} className="block-list"> <header> <Translate content="account.accounts" /> </header> <ul>{accounts}</ul> </section> </div> </Panel> ); } } MobileMenu = connect( MobileMenu, { listenTo() { return [ AccountStore, WalletUnlockStore, WalletManagerStore, SettingsStore ]; }, getProps() { const chainID = Apis.instance().chain_id; return { linkedAccounts: AccountStore.getState().linkedAccounts, currentAccount: AccountStore.getState().currentAccount, locked: WalletUnlockStore.getState().locked, current_wallet: WalletManagerStore.getState().current_wallet, lastMarket: SettingsStore.getState().viewSettings.get( `lastMarket${chainID ? "_" + chainID.substr(0, 8) : ""}` ), myAccounts: AccountStore.getMyAccounts() }; } } ); export default class WidthWrapper extends React.Component { constructor() { super(); let width = window && window.innerWidth; this.state = { visible: width <= 640 }; this._checkWidth = this._checkWidth.bind(this); } componentDidMount() { window.addEventListener("resize", this._checkWidth, { capture: false, passive: true }); } componentWillUnmount() { window.removeEventListener("resize", this._checkWidth); } _checkWidth() { let width = window && window.innerWidth; let visible = width <= 640; if (visible !== this.state.visible) { this.setState({ visible }); } } render() { if (!this.state.visible) return null; return <MobileMenu {...this.props} />; } } <file_sep> #### Accordion Options ##### `autoOpen = true` open the first accordion item initially. if `autoOpen = false`, close all the accordion items initially ##### `multiOpen = false` open one accordion item at a time. if `multiOpen = true`, open multi items based on selection. #### Accordion Item Options ##### `title = String` Title of the accordion item <file_sep>module.exports = require('./lib/FluxContext') <file_sep># Cybex Graphene(石墨烯)旨在实现一种*区块链技术*或*协议*。然而,与具体的区块链整合后,比如Bitshares和Cybex,它逐渐进化为一种生态系统。 Cybex 不断寻求拓展区块链应用技术创新,为所有通过互联网提供服务的行业提供基础支持。无论是银行、证券交易、博彩、投票、音乐、拍卖或其他很多行业,一个数字公共账簿使得分布式自治公司(简称DACs)的创建相对于传统的中心化的方式成本更低,从而带来更佳的服务质量。 分布式自治公司的出现引领了一种崭新的公司组织结构的变革,公司不再需要"人类"的管理,并在一系列不可腐化的业务规则下运行。 这些运营规则编码入公开可审计的开源软件系统中,分布运行于公司股东用户的电脑中,从而保证公司的运作不受独断控制。 Cybex 为商业而生,如同 Bitcoin 为货币而生。两者皆采用分布式共识机制来创建与生俱来的具有全球性、透明性、可信赖的、更高效的系统,更重要的是能为企业带来更多利润。 ## 钱包软件 通过在浏览器中运行本钱包软件,你可以使用 Cybex 网络提供的各种服务和功能,包括但不限于 [比特资产](../assets/mpa.md),[用户发行资产](../assets/uia.md) 和 [去中心化交易所](../dex/introduction.md). <file_sep># 手续费率 在Cybex系统中,每一种操作都将花费*相应*手续费。手续费率可能发生变化。然而,手续费的调整需要获得股东的授权。所以每一位持有Cybex核心资产(CYB)的股东对费率的构成都有话语权。如果股东确信某种手续费的降低将带来好处,并且达成共识,那么该种手续费则由区块链自动进行调低。区块链参数的改变由理事会成员提出动议。这些成员由全体股东投票选举产生,以提高系统灵活性和响应率。<file_sep>import BigNumber from "bignumber.js"; export const calcAmount = (value: string, precision: number) => Math.floor(parseFloat(value) * Math.pow(10, precision)); export const calcValue = (amount: number, precision: number) => new BigNumber(amount).dividedBy(new BigNumber(10).pow(precision)).toNumber(); <file_sep>import alt from "alt-instance"; import WalletApi from "api/WalletApi"; import WalletDb from "stores/WalletDb"; import { ChainStore } from "cybexjs"; import { Apis } from "cybexjs-ws"; import marketUtils from "common/market_utils"; import accountUtils from "common/account_utils"; import * as Immutable from "immutable"; import { TradeHistoryActions } from "./TradeHistoryActions"; import { TradeHistoryStore } from "stores/TradeHistoryStore"; import { MarketHistoryActions } from "./MarketHistoryActions"; import { MarketHistoryStore } from "stores/MarketHistoryStore"; declare const __DEV__; let subs = {}; let currentBucketSize; let marketStats = {}; let statTTL = 2 * 1000; // 2 minutes // let statTTL = 60 * 2 * 1000; // 2 minutes let cancelBatchIDs: any = Immutable.List(); let dispatchCancelTimeout = null; let cancelBatchTime = 500; let subBatchResults: any = Immutable.List(); let dispatchSubTimeout = null; let subBatchTime = 500; function clearBatchTimeouts() { clearTimeout(dispatchCancelTimeout); clearTimeout(dispatchSubTimeout); dispatchCancelTimeout = null; dispatchSubTimeout = null; } class MarketsActions { changeBase(market) { clearBatchTimeouts(); return market; } changeBucketSize(size) { return size; } getMarketStats(base, quote) { return dispatch => { let market = quote.get("id") + "_" + base.get("id"); let marketName = quote.get("symbol") + "_" + base.get("symbol"); let now = new Date(); let refresh = false; if (marketStats[market]) { if ((now as any) - marketStats[market].lastFetched < statTTL) { return false; } else { refresh = true; } } if (!marketStats[market] || refresh) { marketStats[market] = { lastFetched: new Date() }; Apis.instance() .db_api() .exec("get_ticker", [base.get("id"), quote.get("id")]) .then(result => { dispatch({ market: marketName, base, quote, latest: result }); }); } }; } switchMarket() { return true; } subscribeMarket(base, quote, bucketSize) { clearBatchTimeouts(); let subID = quote.get("id") + "_" + base.get("id"); let { isMarketAsset, marketAsset, inverted } = marketUtils.isMarketAsset( quote, base ); const bucketCount = 200; // let lastLimitOrder = null; return dispatch => { let subscription = subResult => { /* In the case of many market notifications arriving at the same time, * we queue them in a batch here and dispatch them all at once at a frequency * defined by "subBatchTime" */ if (!dispatchSubTimeout) { subBatchResults = subBatchResults.concat(subResult); dispatchSubTimeout = setTimeout(() => { let hasLimitOrder = false; let onlyLimitOrder = true; let hasFill = false; // // We get two notifications for each limit order created, ignore the second one // if (subResult.length === 1 && subResult[0].length === 1 && subResult[0][0] === lastLimitOrder) { // return; // } // Check whether the market had a fill order, and whether it only has a new limit order subBatchResults.forEach(result => { result.forEach(notification => { if (typeof notification === "string") { let split = notification.split("."); if (split.length >= 2 && split[1] === "7") { hasLimitOrder = true; } else { onlyLimitOrder = false; } } else { onlyLimitOrder = false; if ( notification.length === 2 && notification[0] && notification[0][0] === 4 ) { hasFill = true; } } }); }); // MarketHistoryActions.patchMarketHistory( // quote, // base, // bucketSize, // MarketHistoryStore // ); let callPromise = null, settlePromise = null; // Only check for call and settle orders if either the base or quote is the CORE asset if (isMarketAsset) { callPromise = Apis.instance() .db_api() .exec("get_call_orders", [marketAsset.id, 300]); settlePromise = Apis.instance() .db_api() .exec("get_settle_orders", [marketAsset.id, 300]); } subBatchResults = subBatchResults.clear(); dispatchSubTimeout = null; // Selectively call the different market api calls depending on the type // of operations received in the subscription update Promise.all([ Apis.instance() .db_api() .exec("get_limit_orders", [ base.get("id"), quote.get("id"), 300 ]), // Limits onlyLimitOrder ? null : callPromise, // Calls onlyLimitOrder ? null : settlePromise, // Settles null, !hasFill // [4]Filled History ? null : Apis.instance() .history_api() .exec("get_fill_order_history", [ base.get("id"), quote.get("id"), 200 ]), Apis.instance() // [5] latest state .db_api() .exec("get_ticker", [base.get("id"), quote.get("id")]), null, null ]) .then(results => { dispatch({ limits: results[0], calls: !onlyLimitOrder && results[1], settles: !onlyLimitOrder && results[2], history: hasFill && results[4], stat: results[5], market: subID, base, quote }); }) .catch(error => { console.log("Error in MarketsActions.subscribeMarket: ", error); }); }, subBatchTime); } else { subBatchResults = subBatchResults.concat(subResult); } }; if (!subs[subID] || currentBucketSize !== bucketSize) { dispatch({ switchMarket: true }); currentBucketSize = bucketSize; let callPromise = null, settlePromise = null; if (isMarketAsset) { callPromise = Apis.instance() .db_api() .exec("get_call_orders", [marketAsset.id, 300]); settlePromise = Apis.instance() .db_api() .exec("get_settle_orders", [marketAsset.id, 300]); } let startDate = new Date(); let startDate2 = new Date(); let startDate3 = new Date(); let endDate = new Date(); let startDateShort = new Date(); startDate = new Date( startDate.getTime() - bucketSize * bucketCount * 1000 ); startDate2 = new Date( startDate2.getTime() - bucketSize * bucketCount * 2000 ); startDate3 = new Date( startDate3.getTime() - bucketSize * bucketCount * 3000 ); startDateShort = new Date(startDateShort.getTime() - 3600 * 50 * 1000); endDate.setDate(endDate.getDate() + 1); if (__DEV__) console.time("Fetch market data"); // MarketHistoryActions.patchMarketHistory( // quote, // base, // bucketSize, // MarketHistoryStore // ); return Promise.all([ Apis.instance() // 0 .db_api() .exec("subscribe_to_market", [ subscription, base.get("id"), quote.get("id") ]), Apis.instance() // 1 .db_api() .exec("get_limit_orders", [base.get("id"), quote.get("id"), 300]), callPromise, // 2 settlePromise, // 3 null, Apis.instance() // 5 .history_api() .exec("get_market_history_buckets", []), Apis.instance() // 6 .history_api() .exec("get_fill_order_history", [ base.get("id"), quote.get("id"), 200 ]), Apis.instance() // [7] latest state .db_api() .exec("get_ticker", [base.get("id"), quote.get("id")]), ]) .then(results => { subs[subID] = subscription; if (__DEV__) console.timeEnd("Fetch market data"); dispatch({ limits: results[1], calls: results[2], settles: results[3], buckets: results[5], history: results[6], stat: results[7], market: subID, base: base, quote: quote, }); }) .catch(error => { console.log("Error in MarketsActions.subscribeMarket: ", error); }); } return Promise.resolve(true); }; } clearMarket() { clearBatchTimeouts(); return true; } unSubscribeMarket(quote, base) { let subID = quote + "_" + base; clearBatchTimeouts(); return dispatch => { if (subs[subID]) { return Apis.instance() .db_api() .exec("unsubscribe_from_market", [subs[subID], quote, base]) .then(unSubResult => { delete subs[subID]; dispatch({ unSub: true }); }) .catch(error => { subs[subID] = true; console.log("Error in MarketsActions.unSubscribeMarket: ", error); dispatch({ unSub: true, market: subID }); // dispatch({ unSub: false, market: subID }); }); } return Promise.resolve(true); }; } createLimitOrder( account, sellAmount, sellAsset, buyAmount, buyAsset, expiration, isFillOrKill, fee_asset_id ) { var tr = WalletApi.new_transaction(); let feeAsset = ChainStore.getAsset(fee_asset_id); if ( feeAsset.getIn(["options", "core_exchange_rate", "base", "asset_id"]) === "1.3.0" && feeAsset.getIn(["options", "core_exchange_rate", "quote", "asset_id"]) === "1.3.0" ) { fee_asset_id = "1.3.0"; } tr.add_type_operation("limit_order_create", { fee: { amount: 0, asset_id: fee_asset_id }, seller: account, amount_to_sell: { amount: sellAmount, asset_id: sellAsset.get("id") }, min_to_receive: { amount: buyAmount, asset_id: buyAsset.get("id") }, expiration: expiration, fill_or_kill: isFillOrKill }); return dispatch => { return WalletDb.process_transaction(tr, null, true) .then(result => { dispatch(true); return true; }) .catch(error => { console.log("order error:", error); dispatch({ error }); return { error }; }); }; } createLimitOrder2(order) { var tr = WalletApi.new_transaction(); // let feeAsset = ChainStore.getAsset(fee_asset_id); // if( feeAsset.getIn(["options", "core_exchange_rate", "base", "asset_id"]) === "1.3.0" && feeAsset.getIn(["options", "core_exchange_rate", "quote", "asset_id"]) === "1.3.0" ) { // fee_asset_id = "1.3.0"; // } order.setExpiration(); order = order.toObject(); tr.add_type_operation("limit_order_create", order); return WalletDb.process_transaction(tr, null, true) .then(result => { return true; }) .catch(error => { console.log("order error:", error); return { error }; }); } createPredictionShort( order, collateral, account, sellAmount, sellAsset, buyAmount, collateralAmount, buyAsset, expiration, isFillOrKill, fee_asset_id = "1.3.0" ) { var tr = WalletApi.new_transaction(); // Set the fee asset to use fee_asset_id = accountUtils.getFinalFeeAsset( order.seller, "call_order_update", order.fee.asset_id ); order.setExpiration(); tr.add_type_operation("call_order_update", { fee: { amount: 0, asset_id: fee_asset_id }, funding_account: order.seller, delta_collateral: collateral.toObject(), delta_debt: order.amount_for_sale.toObject(), expiration: order.getExpiration() }); tr.add_type_operation("limit_order_create", order.toObject()); return WalletDb.process_transaction(tr, null, true) .then(result => { return true; }) .catch(error => { console.log("order error:", error); return { error }; }); } cancelLimitOrder(accountID, orderID) { // Set the fee asset to use let fee_asset_id = accountUtils.getFinalFeeAsset( accountID, "limit_order_cancel" ); var tr = WalletApi.new_transaction(); tr.add_type_operation("limit_order_cancel", { fee: { amount: 0, asset_id: fee_asset_id }, fee_paying_account: accountID, order: orderID }); return WalletDb.process_transaction(tr, null, true).catch(error => { console.log("cancel error:", error); }); } cancelLimitOrderSuccess(ids) { return dispatch => { /* In the case of many cancel orders being issued at the same time, * we batch them here and dispatch them all at once at a frequency * defined by "dispatchCancelTimeout" */ if (!dispatchCancelTimeout) { cancelBatchIDs = cancelBatchIDs.concat(ids); dispatchCancelTimeout = setTimeout(() => { dispatch(cancelBatchIDs.toJS()); dispatchCancelTimeout = null; cancelBatchIDs = cancelBatchIDs.clear(); }, cancelBatchTime); } else { cancelBatchIDs = cancelBatchIDs.concat(ids); } }; } closeCallOrderSuccess(orderID) { return orderID; } callOrderUpdate(order) { return order; } feedUpdate(asset) { return asset; } settleOrderUpdate(asset) { return dispatch => { Apis.instance() .db_api() .exec("get_settle_orders", [asset, 100]) .then(result => { dispatch({ settles: result }); }); }; } toggleStars() { return true; } } export default alt.createActions(MarketsActions); <file_sep>import { isNotDefined, isDefined } from "react-stockcharts/es/lib/utils"; export function saveInteractiveNode(chartId) { return node => { this[`node_${chartId}`] = node; }; } export function handleSelection(type, chartId) { return selectionArray => { const key = `${type}_${chartId}`; const interactive = this.state[key].map((each, idx) => { return { ...each, selected: selectionArray[idx] }; }); this.setState({ [key]: interactive }); }; } export function saveInteractiveNodes(type, chartId) { return node => { if (isNotDefined(this.interactiveNodes)) { this.interactiveNodes = {}; } const key = `${type}_${chartId}`; if (isDefined(node) || isDefined(this.interactiveNodes[key])) { this.interactiveNodes = { ...this.interactiveNodes, [key]: { type, chartId, node }, }; } }; } export function getInteractiveNodes() { return this.interactiveNodes; }<file_sep>import alt from "alt-instance"; import { string, number } from "prop-types"; import { correctMarketPair, correctMarketPairMap } from "utils/Market"; import { Apis } from "cybexjs-ws"; import utils from "common/utils"; import { EventEmitter } from "events"; import { FetchChain } from "cybexjs"; function findMax(a, b) { if (a !== Infinity && b !== Infinity) { return Math.max(a, b); } else if (a === Infinity) { return b; } else { return a; } } function findMin(a, b) { if (a !== 0 && b !== 0) { return Math.min(a, b); } else if (a === 0) { return b; } else { return a; } } export const MarketHistoryStore = {}; const marketHistorySanitizer = (baseAsset, quoteAsset, interval) => ( current: Cybex.MarketHistory, index: number, allHistory: Cybex.MarketHistory[] ) => { let high, low, open, close, volume; if (!/Z$/.test(current.key.open)) { current.key.open += "Z"; } let date = new Date(current.key.open); if (quoteAsset.get("id") === current.key.quote) { high = utils.get_asset_price( current.high_base, baseAsset, current.high_quote, quoteAsset ); low = utils.get_asset_price( current.low_base, baseAsset, current.low_quote, quoteAsset ); open = utils.get_asset_price( current.open_base, baseAsset, current.open_quote, quoteAsset ); close = utils.get_asset_price( current.close_base, baseAsset, current.close_quote, quoteAsset ); volume = utils.get_asset_amount(current.quote_volume, quoteAsset); } else { low = utils.get_asset_price( current.high_quote, baseAsset, current.high_base, quoteAsset ); high = utils.get_asset_price( current.low_quote, baseAsset, current.low_base, quoteAsset ); open = utils.get_asset_price( current.open_quote, baseAsset, current.open_base, quoteAsset ); close = utils.get_asset_price( current.close_quote, baseAsset, current.close_base, quoteAsset ); volume = utils.get_asset_amount(current.base_volume, quoteAsset); } if (low === 0) { low = findMin(open, close); } if (isNaN(high) || high === Infinity) { high = findMax(open, close); } if (close === Infinity || close === 0) { close = open; } if (open === Infinity || open === 0) { open = close; } // if (high > 1.3 * ((open + close) / 2)) { // high = findMax(open, close); // } // if (low < 0.7 * ((open + close) / 2)) { // low = findMin(open, close); // } return { date, open, high, low, close, volume, interval, time: date.getTime(), base: baseAsset.get("symbol"), quote: quoteAsset.get("symbol") }; }; const getMarketKey = (quoteSymbol, baseSymbol, interval) => `${quoteSymbol}${baseSymbol}${interval}`; const getTimeSet = ( currentHistory: Cybex.SanitizedMarketHistory[] = [], interval: number, loadLatest = true ) => { // 计算合适的接口区间 // 当没有当前数据时,时间节点为 当前时间 与 当前时间 - 200 * interval * 1000; // 当有当前数据时,判断是否为获取最新数据,如果是,时间节点为 当前时间 与 当前数据 的 最新时间, // 如不获取最新数据,为 当前数据的最旧时间 与 当前数据的最旧时间 - 200 * interval * 1000; let nowDate = new Date(); let nowIsoString = nowDate.toISOString(); let newDate = currentHistory.length ? loadLatest ? nowDate : currentHistory[currentHistory.length - 1].date : nowDate; let oldDate = currentHistory.length ? loadLatest ? currentHistory[0].date : currentHistory[currentHistory.length - 1].date : nowDate; oldDate = currentHistory.length && loadLatest ? oldDate : new Date(oldDate.getTime() - interval * 1000 * 200); return { newDate, oldDate, nowDate, nowIsoString }; }; export const getMarketHistory = async ( baseAsset, quoteAsset, interval, timeEarlier, timeLatest, patchEmpty = true ) => { type StartTime = Date; type EndTime = Date; type TimePair = [StartTime, EndTime]; let maxInterval = 200 * interval * 1000; let now = new Date(); timeLatest = timeLatest > now ? now : timeLatest; let timeGroup: TimePair[] = (function() { let group: TimePair[] = []; let start = new Date(timeEarlier); while (true) { let stop = new Date(Math.min(start.valueOf() + maxInterval, timeLatest)); // let stop = new Date(Math.min(start.valueOf() + maxInterval, Date.now())); group.push([start, stop]); if (stop >= timeLatest) { break; } start = stop; } return group; })(); return await Promise.all( timeGroup.map((timePair: TimePair) => { return getMarketHistoryImpl( baseAsset, quoteAsset, interval, timePair[0], timePair[1], patchEmpty ); }) ).then(res => { return res.reduce((prev, next) => prev.concat(next)); }); }; export const getMarketHistoryImpl = async ( baseAsset, quoteAsset, interval, timeEarlier, timeLatest, patchEmpty = true ) => { if (!baseAsset || !quoteAsset) return []; let loaderCount = 0; let history: Cybex.SanitizedMarketHistory[] = []; let oldDate = new Date(timeEarlier); let newDate = new Date(timeLatest); let nowIsoString = new Date().toISOString(); while ( !history.length && loaderCount < Math.ceil((86400 * 2) / 200 / interval) ) { history = (await Apis.instance() .history_api() .exec("get_market_history", [ baseAsset.get("id"), quoteAsset.get("id"), interval, oldDate.toISOString().substring(0, nowIsoString.length - 5), newDate.toISOString().substring(0, nowIsoString.length - 5) ])).map(marketHistorySanitizer(baseAsset, quoteAsset, interval)); oldDate = new Date(oldDate.getTime() - interval * 1000 * 200); loaderCount++; } history = history .map((data, i, historyArray) => { let finalDate = i !== historyArray.length - 1 ? historyArray[i + 1].date : newDate; let suffix = i !== historyArray.length - 1 ? 1 : 0; let numToPatch = Math.max( 0, Math.floor( ((finalDate as any) - (data.date as any)) / interval / 1000 ) - 1 ); // console.debug( // "Get Market History: Got", // "Now Patch Empty Date", // i, // numToPatch // ); return [ data, ...new Array(numToPatch).fill(1).map((e, i) => { let date = new Date(data.date.getTime() + (i + 1) * interval * 1000); return { date, time: date.getTime(), open: data.close, close: data.close, high: data.close, low: data.close, volume: 0, interval, base: data.base, quote: data.quote }; }) ]; }) .reduce((all, next) => [...all, ...next], []) .sort( (prev, next) => prev.date > next.date ? -1 : prev.date < next.date ? 1 : 0 ); return history; }; export const supportedResolutions = { "15S": 15, "1": 60, "5": 300, "60": 3600, "1D": 86400, D: 86400 }; export class SubStore extends EventEmitter { subCounterMap: { [symbolUID: string]: number } = {}; timer; constructor(public updateInterval = 3000) { super(); this.startTimer(); } static encodeSubSymbol = (quoteId, baseId, interval) => `${quoteId}/${baseId}_${interval}`; static decodeSubSymbol = (subStr: string) => subStr .split("_") .map( (market, i) => i === 0 ? market.split("/") : [supportedResolutions[market]] ) .reduce((prev, next) => prev.concat(next)); startTimer() { this.timer = setInterval(() => { Object.keys(this.subCounterMap) .filter(symbolUID => this.subCounterMap[symbolUID] > 0) .forEach(async symbolUID => { let [quoteSymbol, baseSymbol, interval] = SubStore.decodeSubSymbol( symbolUID ); let [quote, base] = await Promise.all( [quoteSymbol, baseSymbol].map(symbol => FetchChain("getAsset", symbol) ) ); let stop = new Date(); let start = new Date(stop.valueOf() - parseInt(interval) * 10 * 1000); let data = await getMarketHistory(base, quote, interval, start, stop, false); this.emit(symbolUID, data); }); }, this.updateInterval); } stopUpdateTimer() { if (this.timer) { clearInterval(this.timer); } } addSub(symbolUID: string) { if (symbolUID in this.subCounterMap) { this.subCounterMap[symbolUID]++; } else { this.subCounterMap[symbolUID] = 1; } } removeSub(symbolUID: string) { if (symbolUID in this.subCounterMap) { this.subCounterMap[symbolUID]--; } } } class MarketHistoryActions { /** * * * @param {*} assetA * @param {*} assetB * @param {number} interval * @param {} [currentHistory=[]] A trade history array, with descending order on the time * @param {boolean} [loadLatest=true] * @param {string} [requestID="COMMON"] * @memberof MarketHistoryActions */ async patchMarketHistory( assetA, assetB, interval: number, historyStore, loadLatest = true, requestID = "COMMON" ) { let market = correctMarketPairMap(assetA, assetB); let { base, quote } = market; let marketKey = getMarketKey( quote.get("symbol"), base.get("symbol"), interval ); let currentHistory = (historyStore.getState()[marketKey] || []).sort( (prev, next) => prev.date > next.date ? -1 : prev.date < next.date ? 1 : 0 ); let history: Cybex.SanitizedMarketHistory[] = []; let loaderCount = 0; let { oldDate, newDate, nowIsoString } = getTimeSet( currentHistory, interval, loadLatest ); while ( (loaderCount === 0 && loadLatest && currentHistory.length) || (!history.length && loaderCount < Math.ceil((86400 * 2) / 200 / interval)) ) { history = (await Apis.instance() .history_api() .exec("get_market_history", [ base.get("id"), quote.get("id"), interval, oldDate.toISOString().substring(0, nowIsoString.length - 5), newDate.toISOString().substring(0, nowIsoString.length - 5) ])).map(marketHistorySanitizer(base, quote, interval)); oldDate = new Date(oldDate.getTime() - interval * 1000 * 200); loaderCount++; } if (history.length === 0 && currentHistory.length && loadLatest) { history.push(currentHistory[0]); } history = history .map((data, i, historyArray) => { let finalDate = i !== historyArray.length - 1 ? historyArray[i + 1].date : newDate; let suffix = i !== historyArray.length - 1 ? 1 : 0; let numToPatch = Math.max( 0, Math.floor( ((finalDate as any) - (data.date as any)) / interval / 1000 ) - 1 ); // console.debug( // "Get Market History: Got", // "Now Patch Empty Date", // i, // numToPatch // ); return [ data, ...new Array(numToPatch).fill(1).map((e, i) => { let date = new Date( data.date.getTime() + (i + 1) * interval * 1000 ); return { date, time: date.getTime(), open: data.close, close: data.close, high: data.close, low: data.close, volume: 0, interval, base: data.base, quote: data.quote }; }) ]; }) .reduce((all, next) => [...all, ...next], []) .sort( (prev, next) => prev.date > next.date ? -1 : prev.date < next.date ? 1 : 0 ); // console.debug("Get Market History: Got: ", history); this.onHistoryPatched({ market: marketKey, history, loadLatest, requestID }); } onHistoryPatched({ market, history, loadLatest, requestID }: { market: string; history: Cybex.SanitizedMarketHistory[]; loadLatest: boolean; requestID; }) { return { market, history, loadLatest, requestID }; } } const MarketHistoryActionsWrapped: MarketHistoryActions = alt.createActions( MarketHistoryActions ); export { MarketHistoryActionsWrapped as MarketHistoryActions }; export default MarketHistoryActionsWrapped; <file_sep>import alt from "alt-instance"; import SettingsActions from "actions/SettingsActions"; import IntlActions from "actions/IntlActions"; import { Map, List } from "immutable"; import { merge } from "lodash"; import ls from "common/localStorage"; import { Apis } from "cybexjs-ws"; import { settingsAPIs } from "api/apiConfig"; import { AbstractStore } from "./AbstractStore"; import { FetchChain } from "cybexjs"; export const preferredBases = List([ "JADE.USDT", "JADE.ETH", "JADE.BTC", "CYB" ]); export const MARKETS = [ // Main Net "CYB", "JADE.MT", "JADE.ETH", "JADE.BTC", "JADE.EOS", "JADE.LC", "JADE.LTC", "JADE.LHT", "JADE.INK", "JADE.BAT", "JADE.OMG", "JADE.SNT", "JADE.NAS", "JADE.KNC", "JADE.PAY", "JADE.GET", "JADE.MAD", "JADE.GNX", "JADE.KEY", "JADE.TCT", "JADE.POS", "JADE.ATOM", "JADE.IRIS", "JADE.RING", "JADE.XRP", "JADE.QLC", "JADE.MXC", "JADE.CENNZ", "JADE.NASH", "JADE.NWT", "JADE.POLY", "JADE.JCT", "JADE.MCO", // "JADE.HER", "JADE.CTXC", "JADE.VET", "JADE.NES", "JADE.RHOC", "JADE.PPT", "JADE.MKR", "JADE.FUN", // "JADE.SDT", "JADE.MVP", // "JADE.ICX", // "JADE.BTM", "JADE.GNT", // "JADE.NKN", "JADE.MVP", "JADE.USDT", "JADE.DPY" // "JADE.LST", // "JADE.ENG" ]; const CORE_ASSET = "CYB"; // Setting this to CYB to prevent loading issues when used with CYB chain which is the most usual case currently const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const SETTING_VERSION = "defaults_v2"; class SettingsStore extends AbstractStore<any> { initDone = false; defaultSettings = Map(); settings; defaults; viewSettings; marketDirections; hiddenAssets; apiLatencies; mainnet_faucet; testnet_faucet; starredKey; marketsKey; preferredBases; allDefaultMarkets; defaultMarkets; starredMarkets; userMarkets; fp; constructor() { super(); this.exportPublicMethods({ init: this.init.bind(this), getSetting: this.getSetting.bind(this), getLastBudgetObject: this.getLastBudgetObject.bind(this), setLastBudgetObject: this.setLastBudgetObject.bind(this) }); this.bindListeners({ onChangeSetting: SettingsActions.changeSetting, onChangeViewSetting: SettingsActions.changeViewSetting, onChangeMarketDirection: SettingsActions.changeMarketDirection, onAddStarMarket: SettingsActions.addStarMarket, onRemoveStarMarket: SettingsActions.removeStarMarket, onClearStarredMarkets: SettingsActions.clearStarredMarkets, onAddWS: SettingsActions.addWS, onRemoveWS: SettingsActions.removeWS, onHideAsset: SettingsActions.hideAsset, onClearSettings: SettingsActions.clearSettings, onSwitchLocale: IntlActions.switchLocale, onSetUserMarket: SettingsActions.setUserMarket, // onSetGuideMode: SettingsActions.setGuideMode, onUpdateLatencies: SettingsActions.updateLatencies, onToggleNav: SettingsActions.toggleNav }); this.initDone = false; this.defaultSettings = Map({ locale: "zh", apiServer: settingsAPIs.DEFAULT_WS_NODE, faucet_address: settingsAPIs.DEFAULT_FAUCET, unit: CORE_ASSET, showSettles: false, showAssetPercent: false, walletLockTimeout: 60 * 10, themes: "cybexDarkTheme", disableChat: false, advancedMode: false, navState: true, passwordLogin: true }); // If you want a default value to be translated, add the translation to settings in locale-xx.js // and use an object {translate: key} in the defaults array let apiServer = settingsAPIs.WS_NODE_LIST; let defaults = { locale: [ "zh", "en" // , "vn" ], apiServer: [], unit: [CORE_ASSET, "JADE.ETH", "JADE.USDT", "BTC"], showSettles: [{ translate: "yes" }, { translate: "no" }], showAssetPercent: [{ translate: "yes" }, { translate: "no" }], advancedMode: [{ translate: "yes" }, { translate: "no" }], themes: ["cybexDarkTheme"], passwordLogin: [ { translate: "cloud_login" }, { translate: "local_wallet" } ] // confirmMarketOrder: [ // {translate: "confirm_yes"}, // {translate: "confirm_no"} // ] }; // this.settings = Immutable.Map(merge(this.defaultSettings.toJS(), ss.get("settings_v3"))); // TODO for Online this.settings = Map( merge(this.defaultSettings.toJS(), ss.get("settings_v3")) ); let savedDefaults = ss.get(SETTING_VERSION, {}); /* Fix for old clients after changing cn to zh */ if (savedDefaults && savedDefaults.locale) { let cnIdx = savedDefaults.locale.findIndex(a => a === "cn"); if (cnIdx !== -1) savedDefaults.locale[cnIdx] = "zh"; } this.defaults = merge({}, defaults, savedDefaults); (savedDefaults.apiServer || []).forEach(api => { let hasApi = false; if (typeof api === "string") { api = { url: api, location: null }; } this.defaults.apiServer.forEach(server => { if (server.url === api.url) { hasApi = true; } }); if (!hasApi) { this.defaults.apiServer.push(api); } }); if ( !savedDefaults || (savedDefaults && (!savedDefaults.apiServer || !savedDefaults.apiServer.length)) ) { for (let i = apiServer.length - 1; i >= 0; i--) { let hasApi = false; this.defaults.apiServer.forEach(api => { if (api.url === apiServer[i].url) { hasApi = true; } }); if (!hasApi) { this.defaults.apiServer.unshift(apiServer[i]); } } } this.viewSettings = Map(ss.get("viewSettings_v1")); this.marketDirections = Map(ss.get("marketDirections")); this.hiddenAssets = List(ss.get("hiddenAssets", [])); this.apiLatencies = ss.get("apiLatencies", {}); this.mainnet_faucet = ss.get("mainnet_faucet", settingsAPIs.DEFAULT_FAUCET); this.testnet_faucet = ss.get("testnet_faucet", settingsAPIs.TESTNET_FAUCET); } init() { return new Promise(async resolve => { if (this.initDone) resolve(); this.starredKey = this._getChainKey("markets"); this.marketsKey = this._getChainKey("userMarkets"); this.fp = Math.floor(Math.random() * 100) + Date.now(); let allDefaultMarkets = new Set(); const DefaultM = { "1.3.0": { code: 0, data: [ "1.3.28", "1.3.5", "1.3.4", "1.3.6", "1.3.11", "1.3.9", "1.3.23", "1.3.24", "1.3.21", "1.3.506", "1.3.999", "1.3.1001", "1.3.998" ] }, "1.3.2": { code: 0, data: [ "1.3.0", "1.3.302", "1.3.19", "1.3.4", "1.3.24", "1.3.499", "1.3.23", "1.3.21", "1.3.430", "1.3.481", "1.3.482", "1.3.502", "1.3.506", "1.3.654", "1.3.8", "1.3.996", "1.3.997", "1.3.501", "1.3.999", "1.3.998", "1.3.1001", "1.3.1382", "1.3.1383", "1.3.1386" ] }, "1.3.3": { code: 0, data: ["1.3.26", "1.3.1000", "1.3.1391"] }, "1.3.27": { code: 0, data: [ "1.3.0", "1.3.2", "1.3.3", "1.3.4", "1.3.26", "1.3.999", "1.3.1000", "1.3.1001", "1.3.1002", "1.3.1386", "1.3.1382", "1.3.1385", "1.3.1391", "1.3.1392", "1.3.1393" ] } }; let defaultMarkets = await Promise.all( [ // Main Net "1.3.0", "1.3.2", "1.3.3", "1.3.27" ].map(baseId => Promise.resolve(DefaultM[baseId]) .then(res => res.data) .then((quoteIds: string[]) => Promise.all([ FetchChain("getAsset", baseId), ...quoteIds.map(quoteId => FetchChain("getAsset", quoteId)) ]) ) .then(([baseAsset, ...quoteAssets]) => quoteAssets.map(marketAsset => { try { allDefaultMarkets.add(marketAsset.get("symbol")); allDefaultMarkets.add(baseAsset.get("symbol")); return [ `${marketAsset.get("symbol")}_${baseAsset.get("symbol")}`, { quote: marketAsset.get("symbol"), base: baseAsset.get("symbol") } ]; } catch (err) { console.error(err); } }) ) ) ).then(groupedMarkets => groupedMarkets.reduce((prev, next) => prev.concat(next)) ); let coreAsset = "CYB"; this.defaults.unit[0] = coreAsset; this.allDefaultMarkets = allDefaultMarkets; this.preferredBases = List(["CYB", "JADE.BTC", "JADE.ETH", "JADE.USDT"]); this.defaultMarkets = Map(defaultMarkets); this.starredMarkets = Map(ss.get(this.starredKey, [])); this.userMarkets = Map(ss.get(this.marketsKey, {})); this.initDone = true; resolve(); }); } getSetting(setting) { return this.settings.get(setting); } onChangeSetting(payload) { this.settings = this.settings.set(payload.setting, payload.value); switch (payload.setting) { case "faucet_address": if (payload.value.indexOf("testnet") === -1) { this.mainnet_faucet = payload.value; ss.set("mainnet_faucet", payload.value); } else { this.testnet_faucet = payload.value; ss.set("testnet_faucet", payload.value); } break; case "apiServer": let faucetUrl = payload.value.indexOf("testnet") !== -1 ? this.testnet_faucet : this.mainnet_faucet; this.settings = this.settings.set("faucet_address", faucetUrl); break; case "walletLockTimeout": ss.set("lockTimeout", payload.value); break; default: break; } ss.set("settings_v3", this.settings.toJS()); } onChangeViewSetting(payload) { for (let key in payload) { this.viewSettings = this.viewSettings.set(key, payload[key]); } ss.set("viewSettings_v1", this.viewSettings.toJS()); } onChangeMarketDirection(payload) { for (let key in payload) { this.marketDirections = this.marketDirections.set(key, payload[key]); } ss.set("marketDirections", this.marketDirections.toJS()); } onHideAsset(payload) { if (payload.id) { if (!payload.status) { this.hiddenAssets = this.hiddenAssets.delete( this.hiddenAssets.indexOf(payload.id) ); } else { this.hiddenAssets = this.hiddenAssets.push(payload.id); } } ss.set("hiddenAssets", this.hiddenAssets.toJS()); } onAddStarMarket(market) { let marketID = market.quote + "_" + market.base; if (!this.starredMarkets.has(marketID)) { this.starredMarkets = this.starredMarkets.set(marketID, { quote: market.quote, base: market.base }); ss.set(this.starredKey, this.starredMarkets.toJS()); } else { return false; } } onSetUserMarket(payload) { let marketID = payload.quote + "_" + payload.base; if (payload.value) { this.userMarkets = this.userMarkets.set(marketID, { quote: payload.quote, base: payload.base }); } else { this.userMarkets = this.userMarkets.delete(marketID); } ss.set(this.marketsKey, this.userMarkets.toJS()); } onRemoveStarMarket(market) { let marketID = market.quote + "_" + market.base; this.starredMarkets = this.starredMarkets.delete(marketID); ss.set(this.starredKey, this.starredMarkets.toJS()); } onClearStarredMarkets() { this.starredMarkets = Map({}); ss.set(this.starredKey, this.starredMarkets.toJS()); } onAddWS(ws) { if (typeof ws === "string") { ws = { url: ws, location: null }; } this.defaults.apiServer.push(ws); ss.set(SETTING_VERSION, this.defaults); } onRemoveWS(index) { if (index !== 0) { // Prevent removing the default apiServer this.defaults.apiServer.splice(index, 1); ss.set(SETTING_VERSION, this.defaults); } } onClearSettings(resolve) { ss.remove("settings_v3"); this.settings = this.defaultSettings; ss.set("settings_v3", this.settings.toJS()); if (resolve) { resolve(); } } onSwitchLocale({ locale }) { this.onChangeSetting({ setting: "locale", value: locale }); } onSetGuideMode(isEnabled) { this.settings.set("guideMode", !!isEnabled); } onToggleNav(targetState) { this.onChangeSetting({ setting: "navState", value: !this.settings.get("navState") }); } _getChainKey(key) { const chainId = Apis.instance().chain_id; return key + (chainId ? `_${chainId.substr(0, 8)}` : ""); } onUpdateLatencies(latencies) { ss.set("apiLatencies", latencies); this.apiLatencies = latencies; } getLastBudgetObject() { return ss.get(this._getChainKey("lastBudgetObject"), "2.13.1"); } setLastBudgetObject(value) { ss.set(this._getChainKey("lastBudgetObject"), value); } } export default alt.createStore(SettingsStore, "SettingsStore") as SettingsStore; <file_sep>export * from "./constants"; import { QTB_ASSETS, OPERATIONS } from "./constants"; export const pickPrefix = str => str.indexOf(".") === -1 ? null : str.slice(0, str.indexOf(".")); export const isFootballAsset = marketSymbol => QTB_ASSETS.has(pickPrefix(marketSymbol)); export const pickContent = (marketSymbol: string, operation, fallback) => { if (QTB_ASSETS.has(pickPrefix(marketSymbol))) { return OPERATIONS[operation] || fallback; } return fallback; }; <file_sep>import EventEmitter from 'events'; import Translator from '../'; describe('Translator', () => { let t; beforeEach(() => { t = new Translator({}); }); it('subclasses EventEmitter', () => { expect(t).toBeInstanceOf(EventEmitter); }); describe('getTranslations()', () => { it('returns the translations provided to the constructor', () => { const translations = { foo: { bar: 'baz' } }; t = new Translator(translations); expect(t.getTranslations()).toBe(translations); }); }); describe('setTranslations()', () => { it('replaces the current translations', () => { const translations = { foo: { bar: 'baz' } }; t.setTranslations(translations); expect(t.getTranslations()).toBe(translations); }); }); describe('mergeTranslations()', () => { it('merges provided translations into the existing', () => { t = new Translator({ a: { x: 1, y: 2 }, b: { z: 3 } }); t.mergeTranslations({ a: { y: 4, z: 5 }, c: { w: 6 } }); expect(t.getTranslations()).toEqual({ a: { x: 1, y: 4, z: 5 }, b: { z: 3 }, c: { w: 6 } }) }); it('does not alter the existing or new translations', () => { const existing = { a: 1 }; const toMerge = { b: 2 }; t = new Translator(existing); t.mergeTranslations(toMerge); expect(existing).toEqual({ a: 1 }); expect(toMerge).toEqual({ b: 2 }); }); }); describe('getInterpolations()', () => { it('returns the interpolations provided as option to the constructor', () => { const interpolations = { foo: { bar: 'baz' } }; t = new Translator({}, { interpolations }); expect(t.getInterpolations()).toBe(interpolations); }); }); describe('setInterpolations()', () => { it('replaces the current interpolations', () => { const interpolations = { foo: { bar: 'baz' } }; t.setInterpolations(interpolations); expect(t.getInterpolations()).toBe(interpolations); }); }); describe('mergeInterpolations()', () => { it('merges provided interpolations into the existing', () => { t = new Translator({}, { interpolations: { a: { x: 1, y: 2 }, b: { z: 3 } } }); t.mergeInterpolations({ a: { y: 4, z: 5 }, c: { w: 6 } }); expect(t.getInterpolations()).toEqual({ a: { x: 1, y: 4, z: 5 }, b: { z: 3 }, c: { w: 6 } }) }); it('does not alter the existing or new interpolations', () => { const existing = { a: 1 }; const toMerge = { b: 2 }; t = new Translator({}, { interpolations: existing }); t.mergeInterpolations(toMerge); expect(existing).toEqual({ a: 1 }); expect(toMerge).toEqual({ b: 2 }); }); }); describe('getLocale()', () => { it('returns en by default', () => { expect(t.getLocale()).toBe('en'); }); it('returns the locale provided as option to the constructor', () => { t = new Translator({}, { locale: 'foo' }); expect(t.getLocale()).toBe('foo'); }); }); describe('setLocale()', () => { it('changes the locale used', () => { t.setLocale('foo'); expect(t.getLocale()).toBe('foo'); }); it('returns the previously stored locale', () => { const current = t.getLocale(); expect(t.setLocale(current + 'x')).toBe(current); }); describe('when called with a locale that is distinct from the current', () => { it('emits a localechange event', () => { t.emit = jest.fn(); const current = t.getLocale(); t.setLocale(current + 'x'); expect(t.emit).toHaveBeenCalledWith('localechange', current + 'x', current); }); }); describe('when called with the current locale', () => { it('does not emit a localechange event', () => { t.emit = jest.fn(); t.setLocale(t.getLocale()); expect(t.emit).not.toHaveBeenCalled(); }); }); }); describe('getFallbackLocale()', () => { it('returns null by default', () => { expect(t.getFallbackLocale()).toBe(null); }); it('returns the fallback locale provided as option to the constructor', () => { t = new Translator({}, { fallbackLocale: 'foo' }); expect(t.getFallbackLocale()).toBe('foo'); }); }); describe('setFallbackLocale()', () => { it('changes the fallback locale used', () => { t.setFallbackLocale('foo'); expect(t.getFallbackLocale()).toBe('foo'); }); it('returns the previously stored fallback locale', () => { const current = t.getFallbackLocale(); expect(t.setFallbackLocale(current + 'x')).toBe(current); }); }); describe('getAvailableLocales()', () => { it('returns the locales of the registered translations', () => { t = new Translator({ en: {}, de: {} }); expect(t.getAvailableLocales()).toEqual(['en', 'de']); }); }); describe('setAvailableLocales()', () => { it('sets the locales available', () => { t.setAvailableLocales(['ru', 'it']); expect(t.getAvailableLocales()).toEqual(['ru', 'it']); }); it('returns the previous available locales', () => { t = new Translator({ en: {}, de: {} }); const current = t.getAvailableLocales(); const previous = t.setAvailableLocales(current.concat('ru')); expect(previous).toEqual(current); }); }); describe('getSeparator()', () => { it('returns . by default', () => { expect(t.getSeparator()).toBe('.'); }); it('returns the separator provided as option to the constructor', () => { t = new Translator({}, { separator: '/' }); expect(t.getSeparator()).toBe('/'); }); }); describe('setSeparator()', () => { it('changes the separator used', () => { t.setSeparator('*'); expect(t.getSeparator()).toBe('*'); }); it('returns the previously stored separator', () => { const current = t.getSeparator(); expect(t.setSeparator(current + 'x')).toBe(current); }); }); describe('getInterpolate()', () => { it('returns true by default', () => { expect(t.getInterpolate()).toBe(true); }); it('returns the interpolate flag provided as option to the constructor', () => { t = new Translator({}, { interpolate: false }); expect(t.getInterpolate()).toBe(false); }); }); describe('setInterpolate()', () => { it('changes the interpolate flag used', () => { t.setInterpolate(false); expect(t.getInterpolate()).toBe(false); }); it('returns the previously stored interpolate flag', () => { const current = t.getInterpolate(); expect(t.setInterpolate(!current)).toBe(current); }); }); describe('getKeyTransformer()', () => { it('returns the identity function by default', () => { const transform = t.getKeyTransformer(); const key = ['foo', 'bar']; expect(transform(key)).toBe(key); }); it('returns the key transformer provided as option to the constructor', () => { const keyTransformer = (k) => `${k}${k}`; t = new Translator({}, { keyTransformer }); expect(t.getKeyTransformer()).toBe(keyTransformer); }); }); describe('setKeyTransformer()', () => { it('changes the key transformer used', () => { const transformer = (k) => `${k}${k}`; t.setKeyTransformer(transformer); expect(t.getKeyTransformer()).toBe(transformer); }); it('returns the previously stored key transformer', () => { const current = t.getKeyTransformer(); expect(t.setKeyTransformer((k) => null)).toBe(current); }); }); describe('onLocaleChange()', () => { it('adds a listener for the localechange event', () => { t.addListener = jest.fn(); const callback = () => {}; t.onLocaleChange(callback); expect(t.addListener).toHaveBeenCalledWith('localechange', callback); }); }); describe('offLocaleChange()', () => { it('removes a listener for the localechange event', () => { t.removeListener = jest.fn(); const callback = () => {}; t.offLocaleChange(callback); expect(t.removeListener).toHaveBeenCalledWith('localechange', callback); }); }); describe('onTranslationNotFound()', () => { it('adds a listener for the localechange event', () => { t.addListener = jest.fn(); const callback = () => {}; t.onTranslationNotFound(callback); expect(t.addListener).toHaveBeenCalledWith('translationnotfound', callback); }); }); describe('offTranslationNotFound()', () => { it('removes a listener for the localechange event', () => { t.removeListener = jest.fn(); const callback = () => {}; t.offTranslationNotFound(callback); expect(t.removeListener).toHaveBeenCalledWith('translationnotfound', callback); }); }); describe('withLocale()', () => { it('temporarily changes the current locale within the callback', () => { const locale = t.getLocale(); t.withLocale(locale + 'x', () => { expect(t.getLocale()).toBe(locale + 'x'); }); expect(t.getLocale()).toBe(locale); }); it('allows a custom callback context to be set', () => { t.withLocale('foo', function() { expect(this.bar).toBe('baz'); }, { bar: 'baz' }) }); it('does not emit a localechange event', () => { t.emit = jest.fn(); t.withLocale(t.getLocale() + 'x', () => {}); expect(t.emit).not.toHaveBeenCalled(); }); it('returns the return value of the callback', () => { expect(t.withLocale('foo', () => 'bar')).toBe('bar'); }); }); }); <file_sep>var React = require("react"); var Iconic = require("../../lib/iconic"); var BasicIconic = React.createClass({ render: function() { var baseUrl = ""; if (process.env.NODE_ENV === "production") { baseUrl = "http://static.webrafter.com"; } return ( <Iconic> <img data-src={baseUrl + "/img/iconic/thumb.svg"} className="iconic-md" /> </Iconic> ); } }); module.exports = BasicIconic; <file_sep>export const EtoMock = { details: [ { eto_rate: "1DOT=98USDT", quote_accuracy: 15, user_buy_token: "<PASSWORD>", lock_at: null, update_at: "2018-09-17 07:17:53", base_token: "J<PASSWORD>", type: "nomal", base_soft_cap: null, base_min_quota: 1470, status: "finish", token: "J<PASSWORD>", quote_token_count: "75", receive_address: "1.20.13", offer_at: null, current_user_count: 2, id: "1.20.13", base_token_count: 7350, base_token_name: "USDT", finish_at: "2019-05-31 08:49:02", close_at: null, token_name: "DOT", start_at: "2019-05-31 07:50:00", token_count: 0, base_accuracy: 0, base_max_quota: 1470, end_at: "2019-06-31 08:00:00", control_status: "ok", current_base_token_count: 7350, deleted: 0, created_at: "2018-09-17 07:16:51", name: "ETO2-usdt", score: 9, control: "online", banner: 2, is_user_in: "1", _id: "5b9f54e33da6b77f37c48764", account: "yangroot", project: "波卡 Polkadot", timestamp: "2018-09-17 15:16:51", __v: 0, parent: "1067", t_total_time: "", create_user_type: "code", adds_logo: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_advantage: "Polkadot(波卡)是一个跨链项目,是由以太坊隐形大脑的Gavin Wood领军的项目,G<NAME>ood是以太坊技术黄皮书的撰写者,Partiy的创始人;Polkadot被誉为“区块链3.0”,其由多条区块链,异构组成的区块链集合,用来连接不同公有链,私有链,及传统公司的数据和服务。旨在将现在各自独立的区块链连接起来,把不同区块链之间可以进行通信和数据的传递,是下一代价值互联网的基石。", adds_advantage__lang_en: "Polkadot is a cross-chain project, created by Ethereum (ETH) co-founder <NAME>, who is the author of Ethereum Yellow Paper and also the founder of Parity.Polkadot is known as “Blockchain 3.0”. It integrates multiple blockchains and heterogeneous to connect public and private chains, data and services of the traditional companies. It aims to connect independent blockchains which can communicate and transfer the data. It is also the cornerstone of the next generation of the Internet of value.", adds_token_total__lang_en: "6000万", adds_website__lang_en: "http://herdius.com", adds_whitepaper: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1_cn.pdf", adds_website: "http://herdius.com", adds_banner_mobile: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/polkadot-iou-banner-CN.jpeg", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_logo_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_keyword: "跨链通讯/高匿名性/分红机制", adds_buy_desc__lang_en: "You are participating in the ETO with USDT/CYB in your Cybex account. Please make sure that they are sufficient in the account to charge fees.\nThe assets will be released to your account after the successful subscription.\nYour actual participation amount will be confirmed by the project party. You can view it in the “ETO Project Record”. If there is any unconfirmed share due to exceeding the maximum personal amount or ultra-raised funds of the project, the excess will be returned to your account after the end of the project.\nPlease be patient and wait for the final confirmation of the ETO participation results. Any questions, please contact the assistant (Wechat: CybexServiceA).\n", adds_detail: "http://ieo-apitest.nbltrust.com:3000/projects", adds_buy_desc: "您正在使用您Cybex账号内的USDT/CYB参与本次ETO,本操作将消耗一定手续费,请您保证账号里留有足够的手续费;\n该资产将于您成功认购后发放到您的账号中;\n您的实际成功参与额度以项目方最终确认结果为准,您可在“ETO项目记录”中进行查看。如有因超出个人额度或项目整体超募等情况产生的未确认份额,超出部分将在项目结束后统一退回至您的Cybex帐号;\n最终确认ETO参与结果需要一定时间,请耐心等待,如有疑问请联系客服小助手,微信:CybexServiceA。\n", adds_whitepaper__lang_en: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1.pdf", adds_token_total: "6000万", adds_logo__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_keyword__lang_en: "Cross-chain interoperability / High anonymity / Dividend mechanism", adds_detail__lang_en: "http://ieo-apitest.nbltrust.com:3000/projects", adds_logo_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png", current_percent: 1, index: 0, rate: "0.01", current_remain_quota_count: 0 }, { eto_rate: "1DOT=98USDT", quote_accuracy: 1, user_buy_token: "J<PASSWORD>", lock_at: null, update_at: "2018-09-17 07:17:53", base_token: "J<PASSWORD>", type: "nomal", base_soft_cap: null, base_min_quota: 98, status: "finish", token: "J<PASSWORD>", quote_token_count: "100", receive_address: "1.20.14", offer_at: null, current_user_count: 2, id: "1.20.14", base_token_count: 9800, base_token_name: "USDT", finish_at: "", close_at: null, token_name: "DOT", start_at: "2019-05-31 07:50:00", token_count: 0, base_accuracy: 0, base_max_quota: 4900, end_at: "2019-06-01 08:00:00", control_status: "ok", current_base_token_count: 9800, deleted: 0, created_at: "2018-09-17 07:16:51", name: "ETO3-usdt", score: 8, control: "online", banner: 0, is_user_in: "1", _id: "5b9f54e33da6b77f37c48764", account: "yangroot", project: "波卡 Polkadot", timestamp: "2018-09-17 15:16:51", __v: 0, parent: "1067", t_total_time: "", create_user_type: "code", adds_logo: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_advantage: "Polkadot(波卡)是一个跨链项目,是由以太坊隐形大脑的Gavin Wood领军的项目,Gavin Wood是以太坊技术黄皮书的撰写者,Partiy的创始人;Polkadot被誉为“区块链3.0”,其由多条区块链,异构组成的区块链集合,用来连接不同公有链,私有链,及传统公司的数据和服务。旨在将现在各自独立的区块链连接起来,把不同区块链之间可以进行通信和数据的传递,是下一代价值互联网的基石。", adds_advantage__lang_en: "Polkadot is a cross-chain project, created by Ethereum (ETH) co-founder <NAME>, who is the author of Ethereum Yellow Paper and also the founder of Parity.Polkadot is known as “Blockchain 3.0”. It integrates multiple blockchains and heterogeneous to connect public and private chains, data and services of the traditional companies. It aims to connect independent blockchains which can communicate and transfer the data. It is also the cornerstone of the next generation of the Internet of value.", adds_token_total__lang_en: "6000万", adds_website__lang_en: "http://herdius.com", adds_whitepaper: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1_cn.pdf", adds_website: "http://herdius.com", adds_banner_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E4%B8%AD%E6%96%871.png", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_logo_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_keyword: "跨链通讯/高匿名性/分红机制", adds_buy_desc__lang_en: "You are participating in the ETO with USDT/CYB in your Cybex account. Please make sure that they are sufficient in the account to charge fees.\nThe assets will be released to your account after the successful subscription.\nYour actual participation amount will be confirmed by the project party. You can view it in the “ETO Project Record”. If there is any unconfirmed share due to exceeding the maximum personal amount or ultra-raised funds of the project, the excess will be returned to your account after the end of the project.\nPlease be patient and wait for the final confirmation of the ETO participation results. Any questions, please contact the assistant (Wechat: CybexServiceA).\n", adds_detail: "http://ieo-apitest.nbltrust.com:3000/projects", adds_buy_desc: "您正在使用您Cybex账号内的USDT/CYB参与本次ETO,本操作将消耗一定手续费,请您保证账号里留有足够的手续费;\n该资产将于您成功认购后发放到您的账号中;\n您的实际成功参与额度以项目方最终确认结果为准,您可在“ETO项目记录”中进行查看。如有因超出个人额度或项目整体超募等情况产生的未确认份额,超出部分将在项目结束后统一退回至您的Cybex帐号;\n最终确认ETO参与结果需要一定时间,请耐心等待,如有疑问请联系客服小助手,微信:CybexServiceA。\n", adds_whitepaper__lang_en: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1.pdf", adds_token_total: "6000万", adds_logo__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_keyword__lang_en: "Cross-chain interoperability / High anonymity / Dividend mechanism", adds_detail__lang_en: "http://ieo-apitest.nbltrust.com:3000/projects", adds_logo_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png", current_percent: 1, index: 0, rate: "0.01", current_remain_quota_count: 0 }, { eto_rate: "1DOT=98USDT", quote_accuracy: 3, user_buy_token: "JADE.DOT", lock_at: null, update_at: "2018-09-17 07:17:53", base_token: "J<PASSWORD>", type: "nomal", base_soft_cap: null, base_min_quota: 294, status: "finish", token: "<PASSWORD>", quote_token_count: "15", receive_address: "1.20.12", offer_at: null, current_user_count: 2, id: "1.20.12", base_token_count: 1470, base_token_name: "USDT", finish_at: "", close_at: null, token_name: "DOT", start_at: "2019-05-29 10:00:00", token_count: 0, base_accuracy: 0, base_max_quota: 294, end_at: "2019-06-15 11:45:00", control_status: "ok", current_base_token_count: 1470, deleted: 0, created_at: "2018-09-17 07:16:51", name: "ETO1-usdt", score: 6, control: "online", banner: 1, is_user_in: "1", _id: "5b9f54e33da6b77f37c48764", account: "yangroot", project: "", timestamp: "2018-09-17 15:16:51", __v: 0, parent: "1067", t_total_time: "", create_user_type: "code", adds_logo: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_advantage: "Polkadot(波卡)是一个跨链项目,是由以太坊隐形大脑的Gavin Wood领军的项目,Gavin Wood是以太坊技术黄皮书的撰写者,Partiy的创始人;Polkadot被誉为“区块链3.0”,其由多条区块链,异构组成的区块链集合,用来连接不同公有链,私有链,及传统公司的数据和服务。旨在将现在各自独立的区块链连接起来,把不同区块链之间可以进行通信和数据的传递,是下一代价值互联网的基石。", adds_advantage__lang_en: "Polkadot is a cross-chain project, created by Ethereum (ETH) co-founder <NAME>, who is the author of Ethereum Yellow Paper and also the founder of Parity.Polkadot is known as “Blockchain 3.0”. It integrates multiple blockchains and heterogeneous to connect public and private chains, data and services of the traditional companies. It aims to connect independent blockchains which can communicate and transfer the data. It is also the cornerstone of the next generation of the Internet of value.", adds_token_total__lang_en: "6000万", adds_website__lang_en: "http://herdius.com", adds_whitepaper: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1_cn.pdf", adds_website: "http://herdius.com", adds_banner_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E4%B8%AD%E6%96%871.png", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_logo_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_keyword: "跨链通讯/高匿名性/分红机制", adds_buy_desc__lang_en: "You are participating in the ETO with USDT/CYB in your Cybex account. Please make sure that they are sufficient in the account to charge fees.\nThe assets will be released to your account after the successful subscription.\nYour actual participation amount will be confirmed by the project party. You can view it in the “ETO Project Record”. If there is any unconfirmed share due to exceeding the maximum personal amount or ultra-raised funds of the project, the excess will be returned to your account after the end of the project.\nPlease be patient and wait for the final confirmation of the ETO participation results. Any questions, please contact the assistant (Wechat: CybexServiceA).\n", adds_detail: "http://ieo-apitest.nbltrust.com:3000/projects", adds_buy_desc: "您正在使用您Cybex账号内的USDT/CYB参与本次ETO,本操作将消耗一定手续费,请您保证账号里留有足够的手续费;\n该资产将于您成功认购后发放到您的账号中;\n您的实际成功参与额度以项目方最终确认结果为准,您可在“ETO项目记录”中进行查看。如有因超出个人额度或项目整体超募等情况产生的未确认份额,超出部分将在项目结束后统一退回至您的Cybex帐号;\n最终确认ETO参与结果需要一定时间,请耐心等待,如有疑问请联系客服小助手,微信:CybexServiceA。\n", adds_whitepaper__lang_en: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1.pdf", adds_token_total: "6000万", adds_logo__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_keyword__lang_en: "Cross-chain interoperability / High anonymity / Dividend mechanism", adds_detail__lang_en: "http://ieo-apitest.nbltrust.com:3000/projects", adds_logo_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png", current_percent: 1, index: 0, rate: "0.01", current_remain_quota_count: 0 } ], detail: { eto_rate: "1DOT=98USDT", quote_accuracy: 15, user_buy_token: "<PASSWORD>", lock_at: null, update_at: "2018-09-17 07:17:53", base_token: "<PASSWORD>", type: "nomal", base_soft_cap: null, base_min_quota: 1470, status: "finish", token: "<PASSWORD>", quote_token_count: "75", receive_address: "1.20.13", offer_at: null, current_user_count: 2, id: "1.20.13", base_token_count: 7350, base_token_name: "USDT", finish_at: "", close_at: null, token_name: "DOT", start_at: "2019-05-31 07:50:00", token_count: 0, base_accuracy: 0, base_max_quota: 1470, end_at: "2019-06-31 08:00:00", control_status: "ok", current_base_token_count: <PASSWORD>, deleted: 0, created_at: "2018-09-17 07:16:51", name: "ETO2-usdt", score: 9, control: "online", banner: 2, is_user_in: "1", _id: "5b9f54e33da6b77f37c48764", account: "yangroot", project: "波卡 Polkadot", timestamp: "2018-09-17 15:16:51", __v: 0, parent: "1067", t_total_time: "", create_user_type: "code", adds_logo: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_advantage: "Polkadot(波卡)是一个跨链项目,是由以太坊隐形大脑的Gavin Wood领军的项目,Gavin Wood是以太坊技术黄皮书的撰写者,Partiy的创始人;Polkadot被誉为“区块链3.0”,其由多条区块链,异构组成的区块链集合,用来连接不同公有链,私有链,及传统公司的数据和服务。旨在将现在各自独立的区块链连接起来,把不同区块链之间可以进行通信和数据的传递,是下一代价值互联网的基石。", adds_advantage__lang_en: "Polkadot is a cross-chain project, created by Ethereum (ETH) co-founder <NAME>, who is the author of Ethereum Yellow Paper and also the founder of Parity.Polkadot is known as “Blockchain 3.0”. It integrates multiple blockchains and heterogeneous to connect public and private chains, data and services of the traditional companies. It aims to connect independent blockchains which can communicate and transfer the data. It is also the cornerstone of the next generation of the Internet of value.", adds_token_total__lang_en: "6000万", adds_website__lang_en: "http://herdius.com", adds_whitepaper: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1_cn.pdf", adds_website: "http://herdius.com", adds_banner_mobile: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/polkadot-iou-banner-CN.jpeg", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_logo_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_keyword: "跨链通讯/高匿名性/分红机制", adds_buy_desc__lang_en: "You are participating in the ETO with USDT/CYB in your Cybex account. Please make sure that they are sufficient in the account to charge fees.\nThe assets will be released to your account after the successful subscription.\nYour actual participation amount will be confirmed by the project party. You can view it in the “ETO Project Record”. If there is any unconfirmed share due to exceeding the maximum personal amount or ultra-raised funds of the project, the excess will be returned to your account after the end of the project.\nPlease be patient and wait for the final confirmation of the ETO participation results. Any questions, please contact the assistant (Wechat: CybexServiceA).\n", adds_detail: "http://ieo-apitest.nbltrust.com:3000/projects", adds_buy_desc: "您正在使用您Cybex账号内的USDT/CYB参与本次ETO,本操作将消耗一定手续费,请您保证账号里留有足够的手续费;\n该资产将于您成功认购后发放到您的账号中;\n您的实际成功参与额度以项目方最终确认结果为准,您可在“ETO项目记录”中进行查看。如有因超出个人额度或项目整体超募等情况产生的未确认份额,超出部分将在项目结束后统一退回至您的Cybex帐号;\n最终确认ETO参与结果需要一定时间,请耐心等待,如有疑问请联系客服小助手,微信:CybexServiceA。\n", adds_whitepaper__lang_en: "https://herdius.com/whitepaper/Herdius_Whitepaper_1.1.pdf", adds_token_total: "6000万", adds_logo__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-logo/Herdius_logo0809.jpeg", adds_keyword__lang_en: "Cross-chain interoperability / High anonymity / Dividend mechanism", adds_detail__lang_en: "http://ieo-apitest.nbltrust.com:3000/projects", adds_logo_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/logo.png", adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png", current_percent: 1, index: 0, rate: "0.01", current_remain_quota_count: 0 }, current: { real: true, current_percent: 1, current_base_token_count: 7350, current_remain_quota_count: 0, current_user_count: 0, status: "finish", finish_at: "" }, user: { real: true, current_base_token_count: 1470 }, banner: [ { index: 0, id: "", banner: 2, adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_banner_mobile: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/polkadot-iou-banner-CN.jpeg", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png" }, { index: 0, id: "", banner: 1, adds_banner: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-CN.jpeg", adds_banner__lang_en: "https://ieo.oss-cn-hangzhou.aliyuncs.com/ETO-banner/Herdius_banner0809-EN.jpeg", adds_banner_mobile: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E4%B8%AD%E6%96%871.png", adds_banner_mobile__lang_en: "https://ieo-test.oss-cn-hangzhou.aliyuncs.com/%E8%8B%B1%E6%96%871.png" } ] }; <file_sep>export const API_ROOT = !__DEV__ ? "https://game_api.cybex.io/api/" : "https://game_api.cybex.io/api/"; <file_sep>import alt from "alt-instance"; import { Apis } from "cybexjs-ws"; import WalletDb from "stores/WalletDb"; import SettingsStore from "stores/SettingsStore"; import WalletApi from "api/WalletApi"; import { debugGen } from "utils"; import * as moment from "moment"; import { NotificationActions } from "actions//NotificationActions"; import { ops, PrivateKey, Signature, TransactionBuilder } from "cybexjs"; import { Map } from "immutable"; import { CustomTx } from "CustomTx"; import WalletUnlockActions from "actions/WalletUnlockActions"; import { ETO_LOCK } from "api/apiConfig"; import TransactionConfirmActions from "actions/TransactionConfirmActions"; import { Htlc } from "../services/htlc"; import { htlc_create } from "../cybex/cybexjs/serializer/src/operations"; const debug = debugGen("HtlcActions"); const headers = new Headers(); headers.append("Content-Type", "application/json"); const pickKeys = (keys: string[], count = 1) => { let res: any[] = []; for (let key of keys) { let privKey = WalletDb.getPrivateKey(key); if (privKey) { res.push(privKey); if (res.length >= count) { break; } } } return res; }; type AccountMap = Map<string, any>; class HtlcActions { /// Htlc 锁仓查询部分 queryRank(onReject?) { this.addLoading(); return dispatch => { fetch(`${ETO_LOCK}api/v1/rank`) .then(res => res.json()) .then(rank => { dispatch(rank); this.removeLoading(); }) .catch(err => { this.removeLoading(); if (onReject) { onReject(err); } console.error(err); }); }; } /** * 注册一个查询签名 * * @param {Map<string, any>} account * @memberof HtlcActions */ async signTx(opName: string, op: Htlc.Ops, account: AccountMap) { // await WalletUnlockActions.unlock().catch(e => console.debug("Unlock Error")); await WalletUnlockActions.unlock(); debug("[LoginHtlcQuery]", account); debug("[LoginHtlcQuery]", SettingsStore.getSetting("walletHtlcTimeout")); // Pick approps key let availKeys = account .getIn(["active", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() .concat( account .getIn(["owner", "key_auths"]) .filter(key => key.get(1) >= 1) .map(key => key.get(0)) .toJS() ); let privKey = pickKeys(availKeys)[0]; if (!privKey) { throw Error("Privkey Not Found"); } debug( "[LoginHtlcQuery privKey]", account.getIn(["options", "memo_key"]), privKey ); let tx = new TransactionBuilder(); tx.add_type_operation(opName, op); tx.add_signer(privKey); await tx.set_required_fees(); await tx.finalize(); await tx.sign(); return new Promise((resolve, reject) => TransactionConfirmActions.confirm(tx, resolve, reject) ).then(tx => { this.removeLoading(); return tx; }); } createRawHtlc( from: string, to: string, amount: { asset_id: string; amount: number }, account: AccountMap, preimage: string, algo: Htlc.HashAlgo = Htlc.HashAlgo.Sha256, claimPeriodSecond: number, append: any, onResolve? ) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { let htlc = { from, to, amount }; let htlcCreate = new Htlc.HtlcCreateByRawPreimage( from, to, amount, preimage, algo, claimPeriodSecond ); debug("[HtlcCreate]", htlcCreate); return this.signTx("htlc_create", htlcCreate, account); }) .catch(err => { console.error(err); this.removeLoading(); }); }; } redeemHtlc( htlc_id: string, redeemer: string, preimage: string, account: any, append?: any, onResolve? ) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { let htlcRedeem = new Htlc.HtlcRedeem(htlc_id, redeemer, preimage); debug("[HtlcRedeem]", htlcRedeem); return this.signTx("htlc_redeem", htlcRedeem, account).then(res => { if (onResolve) { setTimeout(() => { onResolve(); }, 0); } return res; }); }) .catch(err => { console.error(err); this.removeLoading(); }); }; } extendHtlc( htlc_id: string, update_issuer: string, seconds_to_add: number, account: any, append?: any, onResolve? ) { this.addLoading(); return dispatch => { WalletUnlockActions.unlock() .then(() => { let htlcExtend = new Htlc.HtlcExtend( htlc_id, update_issuer, seconds_to_add ); debug("[HtlcExtends]", htlcExtend); return this.signTx("htlc_extend", htlcExtend, account).then(res => { if (onResolve) { setTimeout(() => { onResolve(); }, 0); } return res; }); }) .catch(err => { console.error(err); this.removeLoading(); }); }; } updateHtlcRecords(accountID: string) { return dispatch => Promise.all([ Apis.instance() .db_api() .exec("get_htlc_by_from", [accountID, "1.21.0", 100]), Apis.instance() .db_api() .exec("get_htlc_by_to", [accountID, "1.21.0", 100]) ]) .then(([from, to]) => Object.entries( [...from, ...to].reduce( (dict, next) => ({ ...dict, [next.id]: next }), {} ) ).map(record => record[1]) ) .then(records => dispatch({ accountID, records })); } // 其他 addLoading() { return 1; } removeLoading() { return 1; } } const HtlcActionsWrapped: HtlcActions = alt.createActions(HtlcActions); export { HtlcActionsWrapped as HtlcActions }; export default HtlcActionsWrapped; <file_sep>import { Set } from "immutable"; import alt, { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; import { RouterActions } from "actions/RouterActions"; import { AbstractStore } from "./AbstractStore"; import { Map } from "immutable"; type RouterMsg = { type: string; sym: string }; type Ticker = { px: string; qty: string; cymQty: string } & RouterMsg; type OrderBook = {}; type RouterState = { deferRedirect: null | string }; class RouterStore extends AbstractStore<RouterState> { constructor() { super(); console.debug("Router Store Constructor"); this.state = { deferRedirect: null }; this.bindListeners({ onSetDeferRedirect: RouterActions.setDeferRedirect }); console.debug("Router Store Constructor Done"); } onSetDeferRedirect(path: string) { this.setState({ deferRedirect: path }); } } const StoreWrapper: Store<RouterState> = alt.createStore( RouterStore, "RouterStore" ); export { StoreWrapper as RouterStore }; export default StoreWrapper; <file_sep>import BaseStore from "./BaseStore"; import { List, Set, Map, fromJS } from "immutable"; import alt from "alt-instance"; import { Store } from "alt-instance"; import { GatewayActions } from "actions/GatewayActions"; import { JadePool } from "services/GatewayConfig"; import { debugGen } from "utils//Utils"; import { LoginBody, Result as GatewayQueryResult, FundRecordRes, FundRecordEntry } from "services/GatewayModels"; import ls from "lib/common/localStorage"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("GatewayStore"); type State = { backedCoins: Map<any, any>; bridgeCoins: Map<any, any>; bridgeInputs: Array<string>; login: LoginBody; records: FundRecordRes; down: Map<any, any>; modals: Map<string, boolean>; depositInfo?; withdrawInfo?; }; declare const __TEST__; export const JADE_COINS = JadePool.ADDRESS_TYPES; class GatewayStore extends BaseStore implements Store<State> { static findHash = (record: FundRecordEntry) => { if (!record.details || !record.details.length) return null; return record.details[record.details.length - 1].hash; }; bindListeners; setState; state: State = { backedCoins: Map({ JADE: JADE_COINS }), bridgeCoins: Map(fromJS(ss.get("bridgeCoins", {}))), bridgeInputs: ["btc", "dash", "eth", "steem"], login: { accountName: "", signer: "" }, records: { total: 0, records: [], offset: 0, size: 20 }, down: Map({}), modals: Map(), depositInfo: {}, withdrawInfo: {} }; constructor() { super(); this.bindListeners({ handleDepositUpdate: GatewayActions.afterUpdateDepositInfo, handleWithdrawUpdate: GatewayActions.afterUpdateWithdrawInfo, handleLogin: GatewayActions.updateLogin, handleRecordsUpdate: GatewayActions.updateFundRecords, openModal: GatewayActions.openModal, closeModal: GatewayActions.closeModal }); } handleDepositUpdate(_depositInfo) { let meta = JADE_COINS[_depositInfo.asset] || {}; let depositInfo = { ..._depositInfo, meta }; debug("Open: ", JADE_COINS, depositInfo); this.setState({ depositInfo }); } handleWithdrawUpdate(withdrawInfo) { this.setState({ withdrawInfo }); } handleLogin(login: LoginBody) { this.setState({ login }); } handleRecordsUpdate(records: FundRecordRes) { records.records.forEach(record => { if (!record.hash) { record.hash = GatewayStore.findHash(record); } }); this.setState({ records }); } openModal(id) { this.setState({ modals: this.state.modals.set(id, true) }); } closeModal(id) { this.setState({ modals: this.state.modals.set(id, false) }); } } const StoreWrapper = alt.createStore( GatewayStore, "GatewayStore" ) as GatewayStore & Store<State>; export { StoreWrapper as GatewayStore }; export default StoreWrapper; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import Modal from "react-foundation-apps/src/modal"; import Trigger from "react-foundation-apps/src/trigger"; import foundationApi from "react-foundation-apps/src/utils/foundation-api"; // import Button from "../../Common/Button"; import BindToChainState from "../../Utility/BindToChainState"; import AccountInfo from "../../Account/AccountInfo"; import { Button } from "components/Common/Button"; // import AccountStore from "../../../stores/AccountStore"; import AccountStore from "stores/AccountStore"; import { connect } from "alt-react"; import "./LegalModal.scss"; import Translate from "react-translate-component"; import * as fetchJson from "../service"; export class AlertModal extends React.Component { constructor(props) { super(props); this.state = { fadeOut: false }; } onClose = () => { this.setState({ fadeOut: true }); // setTimeout(() => { // ModalActions.hideModal(this.props.modalId); // }, 300); // if (this.props.onClose) { // this.props.onClose(); // } }; componentDidMount(){ // console.log(Trigger); } componentWillReceiveProps(n){ this.setState({ isShow: n.isShow }); } cao = () => { foundationApi.publish(this.props.id, "close"); } submits() { this.sentdata({ user:this.props.accountsWithAuthState[0], project: this.props.project, msg: { code: this.refs.codeInput.value } }); } sentdata(data){ fetchJson.fetchCreatUser(data, (res)=>{ if(res.code == -1){ this.setState({ errorMsg: res.result }); } this.props.cb(); }); } render() { // let { fade, overlay, noCloseBtn, overlayClose } = this.props; // let { fadeOut, isShow } = this.state; return ( <Modal id={this.props.id} // overlay={props.overlay} // onClose={props.onClose} // className={props.className} // overlayClose={props.overlayClose} > <Trigger close={this.props.id}> <a href="#" className="close-button"> &times; </a> </Trigger> <div className="modal-container"> <div className="modal-content"> <div className="title-holder"> <h3 className="center title">服务条款与条件</h3> <p>本条款由您与数字资产交易平台运营商Cybex共同缔结,并具有合同效力。</p> <p>CYBEX SYSTEM PTE. LTD.,一家根据新加坡共和国法律正式建立的公司,运营去中心化的数字资产交易平台,允许注册用户(以下简称“用户”)认购Cybex和/或发行方(以下简称“发行方”)提供的数字货币,硬币和通证(以下简称“数字资产”),并自愿参与早鸟通证发行计划(以下简称“ETO”)(以下简称“服务”)。我们包括我们的合作伙伴,官员,员工,董事或代理人,特制定本条款,包括我们的免责声明(以下简称“免责声明”),以充分披露使用服务过程中的风险,并明确说明我们的责任限制。</p> <p>在本条款中,“我们”,“我们的”和“Cybex”指代CYBEX SYSTEM PTE. LTD.,及其所有者,董事,投资者,员工,相关法人团体或其他相关方。 “Cybex”也可以根据上下文要求提及Cybex提供的服务、产品、网站、内容或其他材料。</p> <p>本网站(www.cybex.io)由Cybex拥有并运营。通过访问我们的网站和平台,进一步通过注册使用我们的服务,您同意并接受本平台发布的全部条款以及免责声明。你应该仔细阅读我们的免责声明和其他条款和条件,如果你不同意任何条款,应立即停止使用我们的服务。 </p> <p>我们郑重提醒:任何访问我们平台或使用我们服务的组织或个人都被视为已完全理解,承认并接受本条款的全部内容。 Cybex保留修改和解释本条款包括但不限于我们的免责声明的权利。</p> <h3 className="center title-sub">内容及签署</h3> <ol> <li>1. 本条款包括所有Cybex已经发布的或将来可能发布的各类规则(下称“有关规则”)。所有有关规则为本条款不可分割的 组成部分,与本条款具有同等法律效力。除另行明确声明外,任何平台、Cybex及其关联方提供本条款项下的服务均受本条款约束。 </li><li>2. 您应当在使用服务之前认真阅读全部条款内容。如您对条款有任何疑问的,应向我们咨询(邮箱地址:<EMAIL>)。但无论您事实上是否在使用服务之前认真阅读了条款内容,只要您使用服务,则本条款即对您产生约束,届时您不应以未阅读本条款的内容或者未获得我们对您问询的解答等理由,主张本条款无效或要求撤销本条款。 </li><li>3. Cybex有权根据需要不时地制订、修改本条款及/或任何有关规则,并以平台公示的方式进行公告,不再单独通知您。变更后的协议和有关规则一经在平台公布后,立即自动生效。如您不同意相关变更,应当立即停止使用服务。您继续使用服务的,即表示您接受经修订的条款和有关规则。如果您不同意修订后的条款,则不应访问平台或我们的服务,您应通过以下电子邮件地址与我们联系以关闭您的帐户:<EMAIL>ex.io。 请不时查看此页面,以了解我们所做的任何更改,因为它们对您具有约束力。 </li><li>4. 对于某些广告、促销或竞赛,可能会适用其他的条款和条件。 如果您想参加此类广告、促销或竞赛,则需要同意适用于该广告、促销或竞赛的相关条款和条件。 如果该等条款和条件与本条款之间存在任何不一致,则以该等条款和条件为准。 </li><li>5. 您可能会下载其他和/或可选软件,以便我们向您提供一些服务。 其他的条款和条件可能适用于这些软件。 如果您下载这些软件,则需要同意适用于它们的相关条款和条件。 如果这些条款和条件与这些条款之间存在任何不一致,则以这些条款和条件为准。 </li></ol> <ol> <h3 className="center title-sub">注册与账户</h3> <li>1. 用户资格 <br /> 您确认,在以Cybex允许的方式实际使用服务时,您应当是:<br /> (a) 自然人(年满18岁)、法人或其他组织;<br /> (b) 具备完全的法律权利和能力与我们签订具有法律约束力的协议;<br /> (c) 同意并保证按照本条款和条件使用服务;和<br /> (d)(如有)符合适用法律和法规的合格投资者。<br /> 若您不具备前述资格要求,则您应承担因此而导致的一切后果,且Cybex有权注销或永久冻结您的账户,并向您索偿。</li> <li>2. 注册及账户<br /> (a) 在您第一次使用我们平台,阅读并同意本条款后,或您以Cybex允许的方式实际使用服务时,您即受本条款及所有有关规则的约束。 <br />(b) 除非有法律规定或司法裁定,或者符合Cybex公布的条件,否则您的登录名和密码不得以任何方式转让、赠与或继承,并且转让、赠与或继承需提供我们要求的合格的文件材料并根据我们制定的操作流程办理。 </li><li>3. 用户信息<br /> (a) 在使用服务时,您应不时更新您的用户资料,以使之真实、及时、完整和准确。如有合理理由怀疑您提供的资料错误、不实、过时或不完整的,Cybex有权向您发出询问及/或要求改正的通知,并有权直接做出删除相应资料的处理,直至中止、终止对您提供部分或全部服务。Cybex对此不承担任何责任,您将承担因此产生的任何直接或间接损失及不利后果。 <br />(b) 您应当准确填写并及时更新您提供的电子邮件地址、联系电话、联系地址等联系方式,以便Cybex在需要时与您进行有效联系,因通过这些联系方式无法与您取得联系,导致您在使用服务过程中产生任何损失或增加费用的,应由您完全独自承担。您了解并同意,您有义务保持你提供的联系方式的有效性,如有变更或需要更新的,您应按Cybex的要求进行操作。 </li><li>4. 账户安全<br /> 您须自行负责对您的登录名和密码保密,且须对您在该登录名和密码下发生的所有活动(包括但不限于信息披露、发布信息或使用服务等)承担责任。您同意: <br />(a) 如发现任何人未经授权使用您的登录名和密码,或发生违反您与Cybex的任何保密规定的任何其他情况,您会立即通知我们,并授权Cybex将该信息同步到平台;及  <br />(b) 确保您在每个上网时段结束时,以正确步骤离开平台/服务。我们不能也不会对因您未能遵守本款规定而发生的任何损失负责。</li> </ol> <h3 className="center title-sub">服务使用规范</h3> <ol> <li>1. 在使用平台服务过程中,您承诺遵守以下约定:  <br />(a)在使用服务过程中实施的所有行为均遵守所有适用的国家的相关法律、法规的规定和要求,不违背社会公共利益或公共道德,不损害他人的合法权益,不违反本条款及有关规则。您如果违反前述承诺,产生任何法律后果的,您应以自己的名义独立承担所有的法律责任,并确保Cybex及其关联方免于因此产生任何损失。   <br />(b)在与其他会员交易过程中,遵守诚实信用原则,不采取不正当竞争行为,不扰乱交易的正常秩序,不从事与交易无关的行为。 <br />(c)不对平台上的任何数据作商业性利用,包括但不限于在未经Cybex事先书面同意的情况下,以复制、传播等任何方式使用平台上展示的资料。  <br />(d)不使用任何装置、软件或日常程序干扰或试图干扰平台的正常运作或正在平台上进行的任何交易或活动。您不得采取任何将导致庞大数据负载加诸平台网络系统的行动。</li> <li>2. 您了解并同意: <br />(a)Cybex有权对您是否违反上述承诺做出单方认定,并根据单方认定结果的适用有关规则予以处理或终止向您提供服务,且无须征得您的同意或提前通知予您。 <br />(b)经任何国家的行政或司法机关生效的法律文书确认您存在违法或侵权行为的,或者Cybex根据自身的判断,认为您的行为涉嫌违反本条款和/或有关规则的规定或涉嫌违反任何适用法律法规的规定的,则Cybex有权在平台上公示您的该等涉嫌违法或违约行为及Cybex已对您采取的措施。 <br />(c)对于您在平台上实施的行为,包括您未在平台上实施但已经对平台及其他用户产生影响的行为,Cybex有权单方认定您行为的性质及是否构成对本条款和/或有关规则的违反,并据此作出相应处罚。您应自行保存与您行为有关的全部证据,并应对无法提供充要证据而承担的不利后果。 <br />(d)对于您涉嫌违反承诺的行为对任何第三方造成损害的,您均应当以自己的名义独立承担所有的法律责任,并应确保Cybex及其关联方免于因此产生损失或增加费用。 <br />(e)如您涉嫌违反有关法律、本条款或任何有关规则之规定,使Cybex遭受任何损失,或受到任何第三方的索赔,或受到任何政府部门的处罚,您应当赔偿Cybex因此遭受的损失及(或)发生的费用,包括合理的律师费用。  </li></ol> <h3 className="center title-sub">特别授权</h3> <p>您完全理解并不可撤销地授予Cybex及其关联方下列权利:</p> <ol> <li>1. 一旦您向Cybex和/或关联方作出任何形式的承诺,且相关公司已确认您违反了该承诺,则Cybex有权立即按您的承诺或条款约定的方式对您的账户采取限制措施,包括中止或终止向您提供服务,并公示相关公司确认的您的违约情况。您了解并同意,Cybex无须就相关确认与您核对事实或另行征得您的同意,且Cybex无须就此限制措施或公示行为向您承担任何的责任。 </li><li>2. 一旦您违反本条款或任何有关规则,或与Cybex和/或关联方签订的其他协议的约定,Cybex有权以任何方式通知关联方,要求其对您的权益采取限制措施,包括但不限于要求有关公司中止、终止对您提供部分或全部服务、在其经营或实际控制的任何网站公示您的违约情况等。    </li><li>3. 对于您提供的数据信息,您授予Cybex及其关联方独家的、全球通用的、永久的、免费的许可使用权利(并有权在多个层面对该权利进行再授权)。 此外,Cybex及其关联方有权(全部或部份地)使用、复制、修订、改写、发布、翻译、分发、执行和展示您的全部资料数据(包括但不限于注册资料、交易行为数据及全部展示于平台的各类信息)或制作其衍生作品,并以现在已知或日后开发的任何形式、媒体或技术,将上述信息纳入其它作品内。 </li></ol> <h3 className="center title-sub">陈述及保证</h3> <ol> <li> 1. 用户特此同意并承诺:<br /> (a)您只会按照本条款规定并以订购数字资产为目的,操作一个帐户和使用本平台; <br />(d)您已获正式授权,并有能力在平台上进行所有交易; <br />(c)您负责持有或交易的数字资产所产生的任何纳税义务,并对我们进行补偿,如我们根据义务代表您对您帐户中或您持有的任何数字资产进行缴税。您授权我们根据任何适用的税法要求预扣任何应纳税额; <br />(d)您将就您在平台上上传、发布、传播和发送的任何内容完全负责,包括任何文本、文件、图像、照片、视频、音频、音乐和任何其他信息(包括通过电子邮件进行的通信)。 <br />(e)您将遵守所有您试图进行账户操作所在地的任何司法管辖区所适用的法律; <br />(f)所有存入您帐户的数字资产或金额,均来源合法,你拥有或以其他方式拥有完全法律权利进行处置;和 <br />(g)您承认您明白并接受通过平台参与的数字资产交易所涉及的风险; <br />(h)参与ETO是一项高风险活动,意味着你可能会失去所有投资金钱或数字资产; <br />(i)你持有的数字资产可能没有任何流动性、买家或未来买家; <br />(j)由于法律或法规的改变,数字资产可能被禁止兑换其他数字资产或法定货币; <br />(k)我们不会就平台上列出的任何数字资产的未来表现、未来盈利能力或回报作出任何陈述或保证; </li><li> 2. 发行人特此同意并承诺如下: <br />(a)您对使用本平台不侵犯任何第三方的权利或违反任何适用法律; <br />(d)您已获正式授权,并有能力在平台上进行所有交易; <br />(c)您对您在平台上进行的任何商业活动或促销活动自行负责; <br />(d)您对您在平台上提供的关于数字资产的任何文件或白皮书所含信息的准确性负责; <br />(e)您对您与用户之间的任何协议、条款、保证和声明负责; <br />(f)如果我们因用户就您的数字资产向我们提出索赔而为自己辩护,您将全额赔偿我们的所有费用,包括产生的法律费用; 和 <br />(g)您不会使用平台进行任何形式的非法活动,包括但不限于非法融资、洗钱或恐怖主义融资。 </li><li> 3. Cybex同意: <br />(a)在法律允许的最大范围内,我们不对本平台或内容做出任何保证或陈述,包括但不限于陈述并保证其完整性、准确性或及时性,访问将不会中断或错误,无差错或免于病毒或本网站安全。 <br />(d)我们保留在任何时候且无需通知您的情况下限制、暂停或终止您对平台或任何内容的访问,我们将不承担任何可能导致的损失、成本、损害或责任。 </li> </ol> <h3 className="center title-sub"> 免责声明 </h3> <ol> <li>1. 独立性 <br />Cybex,包括其合作伙伴,高级职员,员工,董事,代理人或任何其他相关方,将始终保持与任何发行人和用户的独立性,并且不与我们平台上线的任何项目相关联或对其表示认可或赞助。 虽然Cybex可能会因提供服务而收取服务费,但通过我们平台发行或预购任何数字资产的行为均不得被解释为与我们建立任何形式的合伙,合资或任何其他类似关系。 </li><li>2. 无推荐和建议 <br />在发布有关发行人及其项目信息前,我们将会对发行人的基本信息及其项目进行一定程度的审查,但在任何情况下,Cybex都不应被视为提供任何投资、法律、税务、财务或其他方面的推荐和建议,或考虑任何个人情况。你关于参与ETO以及购买、出售或持有任何数字资产的决定所涉及的风险,应基于自己判断或合格金融专业人士的建议。 </li><li>3. 无盈利保证 <br />Cybex不是经纪交易商或财务顾问,也不隶属于任何投资咨询公司。使用任何Cybex或平台提供的有关ETO及其他相关的数据或信息,不会也不能保证您将获利或不会产生损失。 您必须依赖自己的判断或咨询专业人士以获取有关此类事项的建议。您必须根据您的财务状况和承担财务风险的能力,仔细考虑信息是否适合您。 </li><li>4. 项目信息 <br />所有与发行人及其项目有关的信息、数据、白皮书和其他材料(“信息”)系由发行方自行提供且可能存在风险和瑕疵,发行方对其全部所作陈述和提供信息的准确性负全部责任。Cybex仅作为获取发行人和项目信息及开展交易的平台,无法控制项目的质量、安全或合法性,发行人信息的真实性或准确性,以及不同发行人履行其交易义务的能力。Cybex不做任何陈述并且不承担任何明示或暗示的保证,包括但不限于对任何项目的准确性、及时性、完整性、适销性或适用性,且不对任何因信息不准确或遗漏,或基于或依赖信息的任何决定、作为或不作为而引起的任何损失或损害承担责任(无论是侵权还是合同或其他方式)。 </li><li>5. 监管措施 <br />根据您居住的国家,您可能无法使用平台的所有服务。您有义务遵守您所在的国家和/或您访问我们平台和服务的国家的规则和法律。此外,由于监管政策可能不时变化,任何司法管辖区现有的监管许可或包容可能只是暂时的。如果您在法律上不被允许或不符合这些规则和法律所要求的资格,您应该立即停止使用我们的平台和服务。 </li><li>6. 个人信息 <br />虽然Cybex是一个去中心化的数字资产交易平台,但我们可能仍需要根据适用法律法规的相关要求进行“了解您的客户”调查(以下简称“KYC”)。我们可能会要求个人信息(如驾驶执照,身份证,政府签发的照片识别,水电费,银行账户信息或类似信息),以减少洗钱和恐怖主义融资事件。在使用服务时,您应根据我们的要求提供相关的个人信息,并不时更新您的个人信息,以确保其真实、更新、完整、准确。如果有合理理由怀疑您提供的信息是错误,不实,过时或不完整,Cybex向您发出询问及/或要求改正的通知,并有权直接做出删除相应资料的处理,直至中止、终止对您提供部分或全部服务。Cybex对此不承担任何责任,您将承担因此产生的任何直接或间接损失及不利后果。 </li><li>7. 有效性 <br />鉴于Cybex是一个去中心化的交易平台,如果用户不通过我们要求和提供的官方渠道(ETO 网页前端入口)参与众筹,例如通过API方式直接转账到众筹地址,这在技术层面上暂时无法预防。但是,我们作为平台运营方不承认通过不正当方式进行的众筹是有效的,也不退还任何通过非正式途径进行的众筹资金。无效的众筹包括但不限于:(a)非众筹币种的募资;(b)超过个人限额的募资;(c)非项目正常众筹周期内的筹资;(d)非白名单用户的筹款。 </li><li>8. 流动性 <br />任何在我们的平台上线或交易的数字资产(以下简称“上线资产”)不是任何个人,实体,中央银行或国家,超国家或准国家组织发行的货币,也不具备任何硬资产或其他信贷支持。 上线资产的价值在很大程度上取决于其项目的受欢迎程度。 最糟糕的情况是上线资产甚至可能在长期内被边缘化,仅吸引极小部分的用户。 上线资产的交易仅取决于相关市场参与者对其价值的共识。 Cybex将不会(也没有义务或责任)稳定或以其他方式影响上线资产的市场价格,且不对任何上线资产价格作出保证。 </li><li>9. 波动性 <br />参与、购买和销售数字资产通常不涉及与官方法定货币或市场中的商品或商品相同的重大风险。不同于大多数法定货币,这些数字资产基于技术和信任,没有中央银行或其他实体可以采取纠正措施来保护数字资产的价值或调整数字资产的供需。数字资产的价格可能会受到大幅波动,并可能变得毫无价值。Cybex将不会(也没有义务或责任)稳定或以其他方式影响数字资产的市场价格,且不对任何数字资产价格作出保证。您应仔细评估您的目标、财务状况、需求、经验和风险承受能力是否适合参与、购买或出售数字资产。 </li></ol> <h3 className="center title-sub">责任范围和责任限制 </h3> <ol> <li>1. Cybex负责按"现状"和"可得到"的状态向您提供服务。但Cybex对服务不作任何明示或暗示的保证,包括但不限于服务的适用性、无差错或疏漏、持续性、准确性、可靠性、适用于某一特定用途。同时,Cybex也不对服务所涉及的技术及信息的有效性、准确性、正确性、可靠性、质量、稳定、完整和及时性作出任何承诺和保证。 </li><li>2. 在法律允许的最大范围内,在任何情况下,我们均不对任何直接和间接的损失,损害或费用承担责任,包括您可能因使用我们的服务或我们的平台和/或其中包含的信息或材料,或由于本平台无法访问和/或其中包含的某些信息或材料不正确,不完整或不及时而遭受的损失而无论其如何发生。 </li><li>3. 在不限制上述规定的前提下,我们不承担以下责任: <br />(a)无论是根据合同法,侵权法或其他,任何商业损失、收入损失、收入、利润、机会或预期收益、合同或业务关系损失、声誉或商誉损失以及任何其他间接、特殊或后果性损失。 <br />(b)任何由于您使用我们平台,或您下载任何内容,或任何链接网站而引起的可能影响您的计算机设备,计算机程序,数据或其他专有材料的病毒、信息或数据损坏、病毒、信息或数据损坏或其他技术有害材料所导致的损失或损害。 </li><li>4. 即使损失是可预见的,或我们已明确告知潜在损失,责任限制依然适用。 </li><li>5. 本条款中的任何内容均不排除或限制任何一方因其疏忽,违反法律规定的条件或任何其他法律规定不得限制或排除的责任而导致的欺诈,死亡或人身伤害责任。 </li><li>6. 除上述规定外,我们对于任何用户或发行人使用本平台和/或服务而引起或与之相关事件的索赔的总赔偿责任,无论是合同或侵权行为(包括疏忽)还是其他方面,在任何情况下均不超过以下两者中较大者: <br />(a)索赔用户或发行人的账户上的总金额扣除任何适用的提取费用; 或 <br />(b)作为索赔标的交易金额的100%减去该等交易任何可能到期和应付佣金; <br />且我们对每个用户或发行人的赔偿责任不超过5,000美元。 </li> </ol> <h3 className="center title-sub">终止 </h3> <ol> <li>1. 您同意,Cybex有权自行全权决定以任何理由不经事先通知的中止、终止向您提供部分或全部服务,暂时冻结或永久冻结(注销)您的账户在平台的权限,且无须为此向您或任何第三方承担任何责任。 </li><li>2. 出现以下情况时,Cybex有权直接终止本协议,并有权永久冻结(注销)您的账户在平台的权限: <br />(a)您提供的电子邮箱不存在或无法接收电子邮件,且没有其他方式可以与您进行联系,或Cybex以其它联系方式通知您更改电子邮件信息,而您在我们通知后三个工作日内仍未更改为有效的电子邮箱的; <br />(b)您提供的个人信息中的主要内容不真实或不准确或不及时或不完整; <br />(c)本条款(含有关规则)变更时,您明示并通知公司不愿接受经修改的协议或有关规则的;及 <br />(d)其它公司认为应当终止任何服务的情况。 </li><li>3. 您的账户被终止或者账户在平台的权限被永久冻结(注销)后,Cybex没有义务为您保留或向您披露您账户中的任何信息,也没有义务向您或第三方转发任何您未曾阅读或发送过的信息。 </li><li>4. 您同意,您与Cybex的合同关系终止后,Cybex仍享有下列权利: <br />(a)继续保存您的个人信息及您使用服务期间的所有交易信息; <br />(b)您在使用服务期间存在违法行为或违反本条款和/或有关规则的行为的,Cybex仍可依据本条款向您主张权利。 </li> </ol> <h3 className="center title-sub">隐私权政策 </h3> <p>Cybex将在平台上公布并不时修订隐私权政策,隐私权政策构成本条款的有效组成部分。</p> <h3 className="center title-sub">法律适用、争议处理 </h3> <p>本条款之效力、解释、变更、执行与争议解决均适用新加坡法律,任何新加坡的法律冲突规则或原则不适用于本条款。凡因本条款引起的或与之相关的争议、纠纷或索赔、包括违约、协议的效力和终止,均应提交新加坡国际仲裁中心(以下简称“SIAC”),按仲裁通知时有效的SIAC规则解决。</p> </div> </div> </div> {/* {!props.noCloseBtn && ( <Trigger close={props.id}> <a href="#" className="close-button"> &times; </a> </Trigger> )} {props.children} */} </Modal> // <div className={`detail-modal${isShow ? ` show`:` hide`}`}> // <div className="modal-container"> // <div className="modal-title">123</div> // <div className="modal-content">456</div> // <div className="modal-footer">789</div> // </div> // <div className={`over-lay${isShow ? ` show`:` hide`}`}></div> // </div> ); } } // console.log(BindToChainState(BaseModal)); // export default BaseModal; // const Cao = BindToChainState(BaseModal); export default AlertModal; // export default connect(BaseModal,{ // listenTo() { // return [AccountStore]; // }, // getProps(props) { // return { // myAccounts: AccountStore.getMyAccounts(), // accountsWithAuthState: AccountStore.getMyAccountsWithAuthState(), // isMyAccount: AccountStore.getState() // } // let assets = Map(), // assetsList = List(); // if (props.account.get("assets", []).size) { // props.account.get("assets", []).forEach(id => { // assetsList = assetsList.push(id); // }); // } else { // assets = AssetStore.getState().assets; // } // let crowdsInited = CrowdFundStore.getState().initCrowds; // return { // assets, // assetsList, // notification: NotificationStore.getState().notification, // crowdsInited // }; // } // }) // export default BindToChainState(BaseModal); <file_sep>import { sha256, sha1, ripemd160 } from "../cybex/cybexjs/ecc/src/hash"; export namespace Htlc { export enum HashAlgo { Ripemd160 = 0, Sha1 = 1, Sha256 = 2 } export type HtlcRecord = { id: string; transfer: { from: string; to: string; amount: number; asset_id: string; }; conditions: { hash_lock: { preimage_hash: [number, string]; preimage_size: 5; }; time_lock: { expiration: "2019-07-09T10:01:09" }; }; }; export class HtlcCreateByRawPreimage { preimage_size: number; preimage_hash: [number, string]; constructor( public from: string, public to: string, public amount: Cybex.Amount, public preimage: string, public hashAlgo: HashAlgo, public claim_period_seconds: number ) { this.preimage_size = preimage.length; this.preimage_hash = [ hashAlgo, (function(preimage: string, algo: HashAlgo) { switch (algo) { case HashAlgo.Ripemd160: return ripemd160(preimage); case HashAlgo.Sha1: return sha1(preimage); case HashAlgo.Sha256: return sha256(preimage); } })(preimage, hashAlgo) ]; } } export class HtlcCreateByHashedPreimage { preimage_hash: [number, string]; constructor( public from: string, public to: string, public amount: Cybex.Amount, public hashAlgo: HashAlgo, public preimage_size: number, public preimage_hashed: string, public claim_period_seconds: number ) { this.preimage_hash = [hashAlgo, preimage_hashed]; } } export class HtlcRedeem { preimage: string; constructor( public htlc_id: string, public redeemer: string, preimage: string // public preimage: string ) { this.preimage = Buffer.from(preimage).toString("hex"); } } export class HtlcExtend { constructor( public htlc_id: string, public update_issuer: string, public seconds_to_add: number // public preimage: string ) {} } export type Ops = | HtlcCreateByRawPreimage | HtlcCreateByHashedPreimage | HtlcExtend | HtlcRedeem; } <file_sep>import { EdgeProject } from "../../services/edge"; import { EdgeState } from "../../stores/EdgeStore"; import * as moment from "moment"; import BigNumber from "bignumber.js"; export const enum Locale { ZH = "zh", EN = "en", VN = "vn" } export const selectProjects = (eto: EdgeState) => eto.projects; export const selectProject = (eto: EdgeState) => (id: string) => selectProjects(eto).find(project => project.id === id); export const selectBanners = (eto: EdgeState) => eto.banners; export const selectIsUserStatus = (eto: EdgeState, projectID: string) => eto.userInSet[projectID] || {}; export const selectUserProjectStatus = (eto: EdgeState, projectID: string) => eto.userProjectStatus[projectID] || { current_base_token_count: 0 }; export const selectIsUserInProject = (eto: EdgeState, projectID: string) => eto.userInSet[projectID] && eto.userInSet[projectID].status === "ok"; export const selectProjectStatus = (etoProject: EdgeProject.ProjectDetail) => etoProject.status === EdgeProject.EdgeStatus.Unstart ? moment.utc(etoProject.start_at).isAfter(moment()) ? EdgeProject.EdgeStatus.Unstart : EdgeProject.EdgeStatus.Running : etoProject.status === EdgeProject.EdgeStatus.Running ? EdgeProject.EdgeStatus.Running : etoProject.status === EdgeProject.EdgeStatus.Finished ? EdgeProject.EdgeStatus.Finished : EdgeProject.EdgeStatus.Failed; export const selectProjectIsActive = (etoProject: EdgeProject.ProjectDetail) => selectProjectStatus(etoProject) === EdgeProject.EdgeStatus.Running; // export const selectProjectStatus = (etoProject: EdgeProject.ProjectDetail) => // etoProject.finish_at // ? EdgeProject.EdgeStatus.Finish // : moment.utc(etoProject.start_at).isAfter(moment()) // ? EdgeProject.EdgeStatus.Uninit // : EdgeProject.EdgeStatus.Running; export const selectBanner = (eto: EdgeProject.Banner, locale = Locale.ZH) => ({ imgUrl: locale === Locale.ZH ? eto.adds_banner : eto.adds_banner__lang_en, projectLink: eto.id } as EdgeProject.SelectedBanner); export const selectAdv = (eto: EdgeProject.ProjectDetail, locale = Locale.ZH) => locale === Locale.ZH ? eto.adds_advantage : eto.adds_advantage__lang_en; export const selectTokenTotal = ( eto: EdgeProject.ProjectDetail, locale = Locale.ZH ) => locale === Locale.ZH ? eto.adds_token_total : eto.adds_token_total__lang_en; export const selectProjectKeywords = ( eto: EdgeProject.ProjectDetail, locale = Locale.ZH ) => (Locale.ZH ? eto.adds_keyword : eto.adds_keyword__lang_en); export class EdgeRate { rate: BigNumber; baseAsset: string; quoteAsset: string; base: number; quote = 1; constructor(public project: EdgeProject.ProjectDetail) { let rate = (this.rate = new BigNumber(project.base_token_count).div( new BigNumber(project.quote_token_count) )); this.baseAsset = project.base_token; this.quoteAsset = project.token; this.base = rate.toNumber(); } convertBaseToQuote(baseValue: number) { return new BigNumber(baseValue).div(this.rate).toNumber(); } convertQuoteToBase(quote: number) { return this.rate.times(quote).toNumber(); } } export const projectRate = (project: EdgeProject.ProjectDetail) => { let rate = new BigNumber(project.base_token_count).div( new BigNumber(project.quote_token_count) ); return { baseAsset: project.base_token, quoteAsset: project.token, base: rate.toNumber(), quote: 1 }; }; <file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var TriggersDocs = React.createClass({ render: function() { return ( <div> <h2>Trigger</h2> <h4 className="subheader"> Trigger component publish actions such as open, close to the target components. Unique id of target component should be passed to the corresponding action attribute </h4> <hr /> <h3>Open</h3> <p>Open the target component</p> <Highlight innerHTML={true} languages={["xml"]}> {require("./open.md")} </Highlight> <hr /> <h3>Close</h3> <p>Close the target component</p> <Highlight innerHTML={true} languages={["xml"]}> {require("./close.md")} </Highlight> <hr /> <h3>Toggle</h3> <p>Toggle the target component</p> <Highlight innerHTML={true} languages={["xml"]}> {require("./toggle.md")} </Highlight> <hr /> <h3>Hard Toggle</h3> <p> Close all the opened components except target component and then toggle the target component </p> <Highlight innerHTML={true} languages={["xml"]}> {require("./hard-toggle.md")} </Highlight> <hr /> <h3>Notify</h3> <p>Send a notification</p> <Highlight innerHTML={true} languages={["xml"]}> {require("./notify.md")} </Highlight> </div> ); } }); module.exports = TriggersDocs; <file_sep>import alt from "alt-instance"; import { string } from "prop-types"; class RouterActions { setDeferRedirect(path: string) { return path; } } const RouterActionsWrapped: RouterActions = alt.createActions(RouterActions); export { RouterActionsWrapped as RouterActions }; export default RouterActionsWrapped; <file_sep>import * as React from "react"; var Notification = React.createClass({ getDefaultProps: function() { return { position: "top-right", color: "success", title: null, image: null, content: null, wrapperElement: "p" }; }, render: function() { var classes = "notification " + this.props.position + " " + this.props.color; classes += " " + (this.props.className || ""); var imageNode = null; if (this.props.image) { imageNode = ( <div className="notification-icon"> <img src="{{ image }}" /> </div> ); } return ( <div id={this.props.id} data-closable={true} className={classes}> <a href="#" className="close-button" onClick={this.props.closeHandler}> &times; </a> {imageNode} <div className="notification-content"> <h1>{this.props.title}</h1> {React.createElement( this.props.wrapperElement, null, this.props.children )} </div> </div> ); } }); export default Notification; export { Notification }; <file_sep>import { NetworkStore } from "stores/NetworkStore"; // import ReconnectingWebSocket from "reconnecting-websocket"; // let WebSocketClient = ReconnectingWebSocket; let WebSocketClient = WebSocket; var SOCKET_DEBUG = false; function getWebSocketClient(autoReconnect) { if ( !autoReconnect && (typeof WebSocket !== "undefined" && typeof document !== "undefined") ) { return WebSocket; } return WebSocketClient; } let keep_alive_interval = 5000; let max_send_life = 2; // let max_send_life = 5; let max_recv_life = max_send_life * 4; type CallbackMap = { [id: string]: any; }; class ChainWebSocket { url: string; statusCb: any; connectionTimeout: NodeJS.Timeout; keepalive_timer: NodeJS.Timeout | undefined; current_reject: any; on_reconnect: any; closed: boolean; send_life: number; recv_life: number; keepAliveCb: CallableFunction | null; ws: WebSocket | undefined; connect_promise: Promise<any>; cbId = 0; responseCbId = 0; cbs: CallbackMap = {}; subs: CallbackMap = {}; unsub: CallbackMap = {}; closeCb: undefined | CallableFunction; _closeCb: undefined | CallableFunction; on_close: undefined | CallableFunction | null; constructor( ws_server, statusCb, connectTimeout = 5000, autoReconnect = true, keepAliveCb: any = null ) { this.url = ws_server; this.statusCb = statusCb; this.connectionTimeout = setTimeout(() => { if (this.current_reject) { var reject = this.current_reject; this.current_reject = null; this.close(); reject( new Error( "Connection attempt timed out after " + connectTimeout / 1000 + "s" ) ); } }, connectTimeout); this.current_reject = null; this.on_reconnect = null; this.closed = false; this.send_life = max_send_life; this.recv_life = max_recv_life; this.keepAliveCb = keepAliveCb; (NetworkStore as any).updateApiStatus("connecting"); this.connect_promise = new Promise((resolve, reject) => { this.current_reject = reject; let WsClient = getWebSocketClient(autoReconnect); try { this.ws = new WsClient(ws_server); } catch (error) { this.ws = { readyState: 3, close: () => {} } as any; // DISCONNECTED reject(new Error("Invalid url" + ws_server + " closed")); // return this.close().then(() => { // console.log("Invalid url", ws_server, " closed"); // // throw new Error("Invalid url", ws_server, " closed") // // return this.current_reject(Error("Invalid websocket url: " + ws_server)); // }) } (this.ws as WebSocket).onopen = () => { (NetworkStore as any).updateApiStatus("online"); clearTimeout(this.connectionTimeout); if (this.statusCb) this.statusCb("open"); if (this.on_reconnect) this.on_reconnect(); this.keepalive_timer = setInterval(() => { this.recv_life--; // console.debug("RecvLife: ", this.recv_life); if (this.recv_life === max_recv_life - 1) { (NetworkStore as any).updateApiStatus("online"); } if (this.recv_life < max_recv_life - 2) { (NetworkStore as any).updateApiStatus("blocked"); } if (this.recv_life == 0) { console.error(this.url + " connection is dead, terminating ws"); (NetworkStore as any).updateApiStatus("offline"); if (this.ws && (this.ws as any).terminate) { (this.ws as any).terminate(); } else { this.ws && this.ws.close(); } this.close(); // clearInterval(this.keepalive_timer); // this.keepalive_timer = undefined; return; } this.send_life--; if (this.send_life == 0) { // this.ws.ping('', false, true); this.call([2, "get_objects", [["2.1.0"]]]); if (this.keepAliveCb) { this.keepAliveCb(this.closed); } this.send_life = max_send_life; } }, keep_alive_interval); this.current_reject = null; resolve(); }; this.ws && (this.ws.onerror = error => { if (this.keepalive_timer) { clearInterval(this.keepalive_timer); this.keepalive_timer = undefined; } clearTimeout(this.connectionTimeout); if (this.statusCb) this.statusCb("error"); (NetworkStore as any).updateApiStatus("error"); if (this.current_reject) { this.current_reject(error); } }); this.ws && (this.ws.onmessage = message => { this.recv_life = max_recv_life; this.listener(JSON.parse(message.data)); }); this.ws && (this.ws.onclose = () => { this.closed = true; if (this.keepalive_timer) { clearInterval(this.keepalive_timer); this.keepalive_timer = undefined; } var err = new Error("connection closed"); for (var cbId = this.responseCbId + 1; cbId <= this.cbId; cbId += 1) { this.cbs[cbId] && this.cbs[cbId].reject && this.cbs[cbId].reject(err); } (NetworkStore as any).updateApiStatus("error"); if (this.statusCb) this.statusCb("closed"); if (this.closeCb) this.closeCb(); if (this._closeCb) this._closeCb(); if (this.on_close) this.on_close(); }); }); this.cbId = 0; this.responseCbId = 0; this.cbs = {}; this.subs = {}; this.unsub = {}; } call(params) { if (this.ws && this.ws.readyState !== 1) { return Promise.reject( new Error("websocket state error:" + this.ws.readyState) ); } let method = params[1]; if (SOCKET_DEBUG) console.log( '[ChainWebSocket] >---- call -----> "id":' + (this.cbId + 1), JSON.stringify(params) ); this.cbId += 1; if ( method === "set_subscribe_callback" || method === "subscribe_to_market" || method === "broadcast_transaction_with_callback" || method === "set_pending_transaction_callback" ) { // Store callback in subs map this.subs[this.cbId] = { callback: params[2][0] }; // Replace callback with the callback id params[2][0] = this.cbId; } if ( method === "unsubscribe_from_market" || method === "unsubscribe_from_accounts" ) { if (typeof params[2][0] !== "function") { // throw new Error( // "First parameter of unsub must be the original callback" // ); console.error("First parameter of unsub must be the original callback"); return new Promise(resolve => { setTimeout(() => { resolve(); }); }); } let unSubCb = params[2].splice(0, 1)[0]; // Find the corresponding subscription for (let id in this.subs) { if (this.subs[id].callback === unSubCb) { this.unsub[this.cbId] = id; break; } } } var request = { id: 0, method: "call", params: params }; request.id = this.cbId; this.send_life = max_send_life; return new Promise((resolve, reject) => { this.cbs[this.cbId] = { time: new Date(), resolve: resolve, reject: reject }; this.ws && this.ws.send(JSON.stringify(request)); }); } listener(response) { if (SOCKET_DEBUG) console.log( "[ChainWebSocket] <---- reply ----<", JSON.stringify(response) ); let sub = false, callback = null; if (response.method === "notice") { sub = true; response.id = response.params[0]; } if (!sub) { callback = this.cbs[response.id]; this.responseCbId = response.id; } else { callback = this.subs[response.id].callback; } if (callback && !sub) { if (response.error) { callback.reject(response.error); } else { callback.resolve(response.result); } delete this.cbs[response.id]; if (this.unsub[response.id]) { delete this.subs[this.unsub[response.id]]; delete this.unsub[response.id]; } } else if (callback && sub) { callback(response.params[1]); } else { console.log("Warning: unknown websocket response: ", response); } } login(user, password) { return this.connect_promise.then(() => { return this.call([1, "login", [user, password]]); }); } close() { return new Promise(res => { clearInterval(this.keepalive_timer); this.keepalive_timer = undefined; this._closeCb = () => { res(); this._closeCb = null; }; if (!this.ws) { console.log("Websocket already cleared", this); return res(); } if (this.ws.terminate) { this.ws.terminate(); } else { this.ws.close(); } if (this.ws.readyState === 3) res(); }); } } export default ChainWebSocket; <file_sep># counterpart [![Travis][build-badge]][build] [![npm package][npm-badge]][npm] [build-badge]: https://img.shields.io/travis/martinandert/counterpart/master.svg?style=flat-square [build]: https://travis-ci.org/martinandert/counterpart [npm-badge]: https://img.shields.io/npm/v/counterpart.svg?style=flat-square [npm]: https://www.npmjs.com/package/counterpart TODO: introduction goes here... ## Installation Using [npm](https://www.npmjs.com/): ``` $ npm install --save counterpart ``` or using [yarn][https://yarnpkg.com/]: ``` $ yarn add counterpart ``` Then with a module bundler like [webpack](https://webpack.github.io/), use as you would anything else: ```js // using an ES6 transpiler, like babel import Translator from 'counterpart'; // not using an ES6 transpiler var Translator = require('counterpart').Translator; ``` The UMD build is also available on [unpkg](https://unpkg.com): ```html <script src="https://unpkg.com/martinandert/umd/counterpart.min.js"></script> ``` You can find the library on `window.Translator`. ## Usage TODO: add instructions... ## License Released under The MIT License. <file_sep>```html <Trigger open="advancedModal"> <a className="button">Open Modal</a> </Trigger> <Modal id="advancedModal" overlay={true} overlayClose={true}> <div className="grid-block vertical"> <div className="shrink grid-content"> <img src="http://fc07.deviantart.net/fs70/i/2012/014/b/e/snowy_peak_by_cassiopeiaart-d4mb6aq.jpg" /> </div> <div className="grid-content button-group"> <Trigger close=""> <a className="button">Ok</a> </Trigger> <Trigger close=""> <a className="button">Cancel</a> </Trigger> </div> </div> </Modal> ``` <file_sep>var React = require("react"); var Interchange = require("../../lib/interchange"); var BasicInterchange = React.createClass({ render: function() { var baseUrl = ""; if (process.env.NODE_ENV === "production") { baseUrl = "http://static.webrafter.com"; } return ( <div> <Interchange> <img media="small" src={baseUrl + "/img/small.jpg"} /> <img media="medium" src={baseUrl + "/img/medium.jpg"} /> <img media="large" src={baseUrl + "/img/large.jpg"} /> </Interchange> </div> ); } }); module.exports = BasicInterchange; <file_sep>import { Set } from "immutable"; import alt, { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; import { MarketHistoryActions } from "actions/MarketHistoryActions"; import { AbstractStore } from "./AbstractStore"; import { Map } from "immutable"; import EventEmitter from "event-emitter"; const MAX_SIZE = 1500; export const marketEvent = new EventEmitter(); type MarketHistoryState = { [marketPairWithInterval: string]: Cybex.SanitizedMarketHistory[]; }; class MarketHistoryStore extends AbstractStore<MarketHistoryState> { constructor() { super(); // console.debug("MarketHistory Store Constructor"); this.state = {}; this.bindListeners({ onHistoryPatched: MarketHistoryActions.onHistoryPatched }); // console.debug("MarketHistory Store Constructor Done"); } onHistoryPatched({ market, history = [], loadLatest, requestID }) { // console.debug("MarketHistoryStore: ", market, this.state[market], history); let currentData = this.state[market] || []; let concatData = history.length ? history[history.length - 1] : null; if (concatData) { currentData = currentData.filter(data => data.date < concatData.date); } let h: Cybex.SanitizedMarketHistory[] = !loadLatest ? [...currentData, ...history] : [...history, ...currentData]; // .slice(0, MAX_SIZE); this.setState({ [market]: h }); console.debug("MarketHistoryStore Patched: ", this.state); requestID && marketEvent.emit(requestID, h); } } const StoreWrapper: Store<MarketHistoryState> = alt.createStore( MarketHistoryStore, "MarketHistoryStore" ); export { StoreWrapper as MarketHistoryStore }; export default StoreWrapper; <file_sep>var assert = require('assert'); var time = require('time'); var translate = require('./'); var Translator = translate.Translator; describe('translate', function() { var instance; beforeEach(function() { instance = new Translator(); }); it('is a function', function() { assert.isFunction(instance.translate); }); it('is backward-compatible', function() { assert.isFunction(translate); assert.isFunction(translate.translate); }); describe('when called', function() { describe('with a non-empty string or an array as first argument', function() { it('does not throw an invalid argument error', function() { assert.doesNotThrow(function() { instance.translate('foo'); }, /invalid argument/); assert.doesNotThrow(function() { instance.translate(['foo']); }, /invalid argument/); }); describe('with the default locale present', function() { describe('without a current scope or provided scope option', function() { it('generates the correct normalized keys', function() { assert.equal(instance.translate('foo'), 'missing translation: en.foo'); }); }); describe('with a current scope present', function() { it('generates the correct normalized keys', function() { instance.withScope('other', function() { assert.equal(instance.translate('foo'), 'missing translation: en.other.foo'); }); }); }); describe('with a scope provided as option', function() { it('generates the correct normalized keys', function() { assert.equal(instance.translate('foo', { scope: 'other' }), 'missing translation: en.other.foo'); }); }); }); describe('with a different locale present', function() { describe('without a current scope or provided scope option', function() { it('generates the correct normalized keys', function() { instance.withLocale('de', function() { assert.equal(instance.translate('foo'), 'missing translation: de.foo'); }); }); }); describe('with a current scope present', function() { it('generates the correct normalized keys', function() { instance.withLocale('de', function() { instance.withScope('other', function() { assert.equal(instance.translate('foo'), 'missing translation: de.other.foo'); }); }); }); }); describe('with a scope provided as option', function() { it('generates the correct normalized keys', function() { instance.withLocale('de', function() { assert.equal(instance.translate('foo', { scope: 'other' }), 'missing translation: de.other.foo'); }); }); }); }); describe('with a locale provided as option', function() { describe('without a current scope or provided scope option', function() { it('generates the correct normalized keys', function() { assert.equal(instance.translate('foo', { locale: 'de' }), 'missing translation: de.foo'); }); }); describe('with a current scope present', function() { it('generates the correct normalized keys', function() { instance.withScope('other', function() { assert.equal(instance.translate('foo', { locale: 'de' }), 'missing translation: de.other.foo'); }); }); }); describe('with a scope provided as option', function() { it('generates the correct normalized keys', function() { assert.equal(instance.translate('foo', { locale: 'de', scope: 'other' }), 'missing translation: de.other.foo'); }); }); }); describe('with options provided', function() { it('does not mutate these options', function() { var options = { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }; instance.translate('boing', options); assert.deepEqual(options, { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }); }); }); describe('with a translation for the key present', function() { it('returns that translation', function() { instance.registerTranslations('en', { foo: { bar: { baz: { bam: 'boo' } } } }); // strings assert.equal(instance.translate('foo.bar.baz.bam'), 'boo'); assert.equal(instance.translate('bar.baz.bam', { scope: 'foo' }), 'boo'); assert.equal(instance.translate('baz.bam', { scope: 'foo.bar' }), 'boo'); assert.equal(instance.translate('bam', { scope: 'foo.bar.baz' }), 'boo'); // arrays assert.equal(instance.translate(['foo', 'bar', 'baz', 'bam']), 'boo'); assert.equal(instance.translate(['bar', 'baz', 'bam'], { scope: ['foo'] }), 'boo'); assert.equal(instance.translate(['baz', 'bam'], { scope: ['foo', 'bar'] }), 'boo'); assert.equal(instance.translate(['bam'], { scope: ['foo', 'bar', 'baz'] }), 'boo'); // mixed assert.equal(instance.translate(['foo.bar', 'baz', 'bam']), 'boo'); assert.equal(instance.translate(['bar', 'baz.bam'], { scope: 'foo' }), 'boo'); assert.equal(instance.translate(['baz', 'bam'], { scope: 'foo.bar' }), 'boo'); assert.equal(instance.translate('bam', { scope: ['foo.bar', 'baz'] }), 'boo'); // strange looking assert.equal(instance.translate(['..foo.bar', 'baz', '', 'bam']), 'boo'); assert.equal(instance.translate(['bar', 'baz..bam.'], { scope: '.foo' }), 'boo'); assert.equal(instance.translate(['baz', null, 'bam'], { scope: 'foo.bar.' }), 'boo'); assert.equal(instance.translate('bam...', { scope: [null, 'foo..bar', '', 'baz'] }), 'boo'); }); describe('with a `count` provided as option', function() { it('correctly pluralizes the translated value', function() { instance.registerTranslations('en', { foo: { zero: 'no items', one: 'one item', other: '%(count)s items' } }); assert.equal(instance.translate('foo', { count: 0 }), 'no items'); assert.equal(instance.translate('foo', { count: 1 }), 'one item'); assert.equal(instance.translate('foo', { count: 2 }), '2 items'); assert.equal(instance.translate('foo', { count: 42 }), '42 items'); }); }); describe('with a `separator` provided as option', function() { it('correctly returns single array with key', function() { instance.registerTranslations('en', { 'long.key.with.dots.in.name': 'Key with dots doesn\'t get split and returns correctly', another: { key: 'bar' }, mixed: { 'dots.and': { separator: 'bingo' } } }); assert.equal(instance.translate('long.key.with.dots.in.name', { separator: '-' }), 'Key with dots doesn\'t get split and returns correctly'); assert.equal(instance.translate('long.key.with.dots.in.name.not-found', { separator: '-' }), 'missing translation: en-long.key.with.dots.in.name.not-found'); assert.equal(instance.translate('another-key', { separator: '-' }), 'bar'); assert.equal(instance.translate('mixed-dots.and-separator', { separator: '-' }), 'bingo'); }); it('correctly returns nested key when using `*` as seperator', function() { instance.registerTranslations('en', { "long": { key: { "with": { dots: { "in": { name: 'boo' } } } }} }); assert.equal(instance.translate('long*key*with*dots*in*name', { separator: '*' }), 'boo'); }); }); describe('with other options provided', function() { describe('by default', function() { it('interpolates these options into the translated value', function() { instance.registerTranslations('en', { foo: 'Hi %(name)s! See you %(when)s!' }); assert.equal(instance.translate('foo', { name: 'Paul', when: 'later', where: 'home' }), 'Hi Paul! See you later!'); instance.registerTranslations('en', { foo: 'Hello %(users[0].name)s and %(users[1].name)s!' }); assert.equal(instance.translate('foo', { users: [{ name: 'Molly' }, { name: 'Polly' }] }), 'Hello Molly and Polly!'); }); it('interpolates the registered interpolations into the translated value', function() { var current = instance._registry.interpolations; instance.registerTranslations('en', {'hello':'Hello from %(brand)s!'}); instance.registerInterpolations({brand:'Z'}); assert.equal(instance.translate('hello'), 'Hello from Z!'); instance._registry.interpolations = current; instance.registerInterpolations({ app_name: 'My Cool App', question: 'How are you today?' }); instance.registerTranslations('en', { greeting: 'Welcome to %(app_name)s, %(name)s! %(question)s' }); assert.equal(instance.translate('greeting', { name: 'Martin' }), 'Welcome to My Cool App, Martin! How are you today?'); assert.equal(instance.translate('greeting', { name: 'Martin', app_name: 'The Foo App' }), 'Welcome to The Foo App, Martin! How are you today?'); instance._registry.interpolations = current; }); }); describe('with the `interpolate` options set to `false`', function() { it('interpolates these options into the translated value', function() { instance.registerTranslations('en', { foo: 'Hi %(name)s! See you %(when)s!' }); assert.equal(instance.translate('foo', { interpolate: false, name: 'Paul', when: 'later', where: 'home' }), 'Hi %(name)s! See you %(when)s!'); }); }); }); describe('with the keepTrailingDot setting set to true', function() { it('returns the translation for keys that contain a trailing dot', function() { instance.registerTranslations('fr', { foo: { bar: 'baz', 'With a dot.': 'Avec un point.' }, 'dot.': 'point.' }); instance._registry.keepTrailingDot = true; instance.withLocale('fr', function() { assert.equal(instance.translate('foo.bar'), 'baz'); assert.equal(instance.translate('foo.With a dot.'), 'Avec un point.'); assert.equal(instance.translate('dot.'), 'point.'); assert.equal(instance.translate('foo..bar'), 'baz'); assert.equal(instance.translate('foo..With a dot.'), 'Avec un point.'); assert.equal(instance.translate('.dot.'), 'point.'); assert.equal(instance.translate('foo.bar.'), 'missing translation: fr.foo.bar.'); assert.equal(instance.translate('foo.With a dot..'), 'missing translation: fr.foo.With a dot..'); assert.equal(instance.translate('foo.With. a dot.'), 'missing translation: fr.foo.With. a dot.'); assert.equal(instance.translate('dot..'), 'missing translation: fr.dot..'); }); }); }); }); describe('with a translation for a prefix of the key present', function() { it('returns the remaining translation part', function() { instance.registerTranslations('en', { foo: { bar: { baz: { zero: 'no items', one: 'one item', other: '%(count)s items' } } } }); assert.deepEqual(instance.translate('baz', { scope: ['foo', 'bar'] }), { zero: 'no items', one: 'one item', other: '%(count)s items' }); }); }); describe('with an array-type translation for the key present', function() { it('returns the array that key points to', function() { instance.registerTranslations('en', { foo: { bar: { baz: [1, 'A', 0.42] } } }); assert.deepEqual(instance.translate(['bar', 'baz'], { scope: 'foo' }), [1, 'A', 0.42]); }); }); describe('with pure strings as keys', function() { it('works', function() { instance.registerTranslations('de', { 'Hello, %(user)s!': 'Hallo %(user)s!' }); assert.deepEqual(instance.translate('Hello, %(user)s!', { locale: 'de', user: 'Martin' }), '<NAME>!'); }); }); describe('with a function-type translation for the key present', function() { it('returns the array that key points to', function() { var myFunc = function() {}; instance.registerTranslations('en', { foo: { bar: { baz: myFunc } } }); assert.equal(instance.translate(['bar', 'baz'], { scope: 'foo' }), myFunc); }); }); describe('with a function-type fallback present', function() { it('returns the array that key points to', function() { var myFunc = function() { return 'Here I am!'; }; var myFunc2 = function(x) { return 'Here ' + x + ' are!'; }; var fallbacks = [':i_dont_exist_either', myFunc, 'Should not be returned']; assert.equal(instance.translate('i_dont_exist', { fallback: myFunc }), 'Here I am!'); assert.equal(instance.translate('i_dont_exist', { fallback: myFunc2, object: 'you' }), 'Here you are!'); assert.equal(instance.translate('i_dont_exist', { fallback: myFunc2 }), 'Here i_dont_exist are!'); assert.equal(instance.translate('i_dont_exist', { fallback: fallbacks }), 'Here I am!'); }); }); describe('without a translation for the key present', function() { it('returns a string "missing translation: %(locale).%(scope).%(key)"', function() { assert.deepEqual(instance.translate('bar', { locale: 'unknown', scope: 'foo' }), 'missing translation: unknown.foo.bar'); }); describe('with a `fallback` provided as option', function() { it('returns the fallback', function() { assert.equal(instance.translate('baz', { locale: 'foo', scope: 'bar', fallback: 'boom' }), 'boom'); assert.equal(instance.translate('baz', { locale: 'foo', scope: 'bar', fallback: 'Hello, %(name)s!', name: 'Martin' }), 'Hello, Martin!'); assert.equal(instance.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 0 }), 'no items'); assert.equal(instance.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 1 }), 'one item'); assert.equal(instance.translate('bazz', { locale: 'en', scope: 'bar', fallback: { zero: 'no items', one: 'one item', other: '%(count)s items' }, count: 2 }), '2 items'); assert.deepEqual(instance.translate('baz', { locale: 'foo', scope: 'bar', fallback: { oh: 'yeah' } }), { oh: 'yeah' }); assert.deepEqual(instance.translate('baz', { locale: 'foo', scope: 'bar', fallback: [1, 'A', 0.42] }), 1); }); it('translates the fallback if given as "symbol" or array', function() { instance.registerTranslations('en', { foo: { bar: 'bar', baz: 'baz' } }); assert.equal(instance.translate('missing', { fallback: 'default' }), 'default'); assert.equal(instance.translate('missing', { fallback: ':foo.bar' }), 'bar'); assert.equal(instance.translate('missing', { fallback: ':bar', scope: 'foo' }), 'bar'); assert.equal(instance.translate('missing', { fallback: [':also_missing', ':foo.bar'] }), 'bar'); assert.matches(instance.translate('missing', { fallback: [':also_missing', ':foo.missed'] }), /missing translation/); }); }); describe('with a global `fallbackLocale` present', function() { it('returns the entry of the fallback locale', function() { instance.registerTranslations('de', { bar: { baz: 'bam' } }); instance.registerTranslations('de', { hello: 'Hallo %(name)s!' }); assert.equal(instance.translate('baz', { locale: 'foo', scope: 'bar' }), 'missing translation: foo.bar.baz'); assert.equal(instance.translate('hello', { locale: 'foo', name: 'Martin' }), 'missing translation: foo.hello'); var previousFallbackLocale = instance.setFallbackLocale('de'); assert.equal(instance.translate('baz', { locale: 'foo', scope: 'bar' }), 'bam'); assert.equal(instance.translate('hello', { locale: 'foo', name: 'Martin' }), '<NAME>!'); instance.setFallbackLocale(previousFallbackLocale); }); }); describe('with a `fallbackLocale` provided as option', function() { it('returns the entry of the fallback locale', function() { instance.registerTranslations('en', { bar: { baz: 'bam' } }); instance.registerTranslations('en', { hello: 'Hello, %(name)s!' }); assert.equal(instance.translate('baz', { locale: 'foo', scope: 'bar', fallbackLocale: 'en' }), 'bam'); assert.equal(instance.translate('hello', { locale: 'foo', fallbackLocale: 'en', name: 'Martin' }), 'Hello, Martin!'); }); }); }); }); describe('without a valid key as first argument', function() { it('throws an invalid argument error', function() { var keys = [undefined, null, 42, {}, new Date(), /./, function() {}, [], '']; for (var i = 0, ii = keys.length; i < ii; i++) { assert.throws(function() { instance.translate(keys[i]); }, /invalid argument/); } }); }); describe('with global interpolate setting set to false', function() { it('will not interpolate', function() { var current = instance._registry.interpolations; instance.registerTranslations('en', { 'hello':'Hello from %(brand)s!' }); instance.registerInterpolations({ brand: 'Z' }); assert.equal(instance.translate('hello'), 'Hello from Z!'); var prev = instance.setInterpolate(false); assert.equal(instance.translate('hello'), 'Hello from %(brand)s!'); assert.equal(instance.translate('hello', { interpolate: true }), 'Hello from %(brand)s!'); instance.setInterpolate(prev); instance._registry.interpolations = current; }); }); }); describe('#translate', function() { it('is a function', function() { assert.isFunction(instance.translate); }); }); describe('#getLocale', function() { it('is a function', function() { assert.isFunction(instance.getLocale); }); it('returns the locale stored in the registry', function() { assert.equal(instance.getLocale(), instance._registry.locale); }); it('returns "en" by default', function() { assert.equal(instance.getLocale(), 'en'); }); }); describe('#setLocale', function() { it('is a function', function() { assert.isFunction(instance.setLocale); }); it('sets the locale stored in the registry', function() { instance.setLocale('foo'); assert.equal(instance._registry.locale, 'foo'); }); it('returns the previous locale that was stored in the registry', function() { var current = instance.getLocale(); var previous = instance.setLocale(current + 'x'); assert.equal(previous, current); }); describe('when called with a locale that differs from the current one', function() { it('emits a "localechange" event', function(done) { var handler = function() { done() }; instance.onLocaleChange(handler); instance.setLocale(instance.getLocale() + 'x'); instance.offLocaleChange(handler); }); }); describe('when called with the current locale', function() { it('does not emit a "localechange" event', function(done) { var handler = function() { done('event was emitted'); }; instance.onLocaleChange(handler); instance.setLocale(instance.getLocale()); instance.offLocaleChange(handler); setTimeout(done, 100); }); }); }); describe('#getFallbackLocale', function() { it('is a function', function() { assert.isFunction(instance.getFallbackLocale); }); it('returns the fallback locale stored in the registry', function() { assert.equal(instance.getFallbackLocale(), instance._registry.fallbackLocale); }); it('returns null by default', function() { assert.strictEqual(instance.getFallbackLocale(), null); }); }); describe('#setFallbackLocale', function() { it('is a function', function() { assert.isFunction(instance.setFallbackLocale); }); it('sets the fallback locale stored in the registry', function() { instance.setFallbackLocale('foo'); assert.equal(instance._registry.fallbackLocale, 'foo'); }); it('returns the previous fallback locale that was stored in the registry', function() { var current = instance.getFallbackLocale(); var previous = instance.setFallbackLocale(current + 'x'); assert.equal(previous, current); }); }); describe('#getAvailableLocales', function() { it('is a function', function() { assert.isFunction(instance.getAvailableLocales); }); it('returns the locales of the registered translations by default', function() { assert.deepEqual(instance.getAvailableLocales(), Object.keys(instance._registry.translations)); }); }); describe('#setAvailableLocales', function() { it('is a function', function() { assert.isFunction(instance.setAvailableLocales); }); it('sets the locales available', function() { instance.setAvailableLocales(['foo', 'bar']); assert.deepEqual(instance._registry.availableLocales, ['foo', 'bar']); }); it('returns the previous available locales', function() { var current = instance.getAvailableLocales(); var previous = instance.setAvailableLocales(current.concat('x')); assert.deepEqual(previous, current); }); }); describe('#withLocale', function() { it('is a function', function() { assert.isFunction(instance.withLocale); }); it('temporarily changes the current locale within the callback', function() { var locale = instance.getLocale(); instance.withLocale(locale + 'x', function() { assert.equal(instance.getLocale(), locale + 'x'); }); assert.equal(instance.getLocale(), locale); }); it('allows a custom callback context to be set', function() { instance.withLocale('foo', function() { assert.equal(this.bar, 'baz'); }, { bar: 'baz' }) }); it('does not emit a "localechange" event', function(done) { var handler = function() { done('event was emitted'); }; instance.onLocaleChange(handler); instance.withLocale(instance.getLocale() + 'x', function() {}); instance.offLocaleChange(handler); setTimeout(done, 100); }); it('returns the return value of the callback', function() { var result = instance.withLocale('foo', function() { return 'bar'; }); assert.equal(result, 'bar'); }); }); describe('#withScope', function() { it('is a function', function() { assert.isFunction(instance.withScope); }); it('temporarily changes the current scope within the callback', function() { var scope = instance._registry.scope; instance.withScope(scope + 'x', function() { assert.equal(instance._registry.scope, scope + 'x'); }); assert.equal(instance._registry.scope, scope); }); it('allows a custom callback context to be set', function() { instance.withScope('foo', function() { assert.equal(this.bar, 'baz'); }, { bar: 'baz' }) }); it('returns the return value of the callback', function() { var result = instance.withScope('foo', function() { return 'bar'; }); assert.equal(result, 'bar'); }); }); describe('#onLocaleChange', function() { it('is a function', function() { assert.isFunction(instance.onLocaleChange); }); it('is called when the locale changes', function(done) { var handler = function() { done(); }; instance.onLocaleChange(handler); instance.setLocale(instance.getLocale() + 'x'); instance.offLocaleChange(handler); }); it('is not called when the locale does not change', function(done) { var handler = function() { done('function was called'); }; instance.onLocaleChange(handler); instance.setLocale(instance.getLocale()); instance.offLocaleChange(handler); setTimeout(done, 100); }); describe('when called', function() { it('exposes both the new and old locale as arguments', function(done) { var oldLocale = instance.getLocale(); var newLocale = oldLocale + 'x'; var handler = function(locale, previousLocale) { assert.equal(locale, newLocale); assert.equal(previousLocale, oldLocale); done(); }; instance.onLocaleChange(handler); instance.setLocale(newLocale); instance.offLocaleChange(handler); }); }); describe('when called more than 10 times', function() { it('does not let Node issue a warning about a possible memory leak', function() { var oldConsoleError = console.error; console.error = function(message) { if (/EventEmitter memory leak/.test(message)) { assert.fail(null, null, 'Node issues a warning about a possible memory leak', null); } else { oldConsoleError.apply(console, arguments); } }; var handlers = [], handler, i; for (i = 0; i < 11; i++) { handler = function() {}; instance.onLocaleChange(handler); handlers.push(handler); } for (i = 0; i < 11; i++) { instance.offLocaleChange(handlers[i]); } console.error = oldConsoleError }); }) }); describe('#offLocaleChange', function() { it('is a function', function() { assert.isFunction(instance.offLocaleChange); }); it('stops the emission of events to the handler', function(done) { var count = 0; var handler = function() { count++; }; instance.onLocaleChange(handler); instance.setLocale(instance.getLocale() + 'x'); instance.setLocale(instance.getLocale() + 'x'); instance.offLocaleChange(handler); instance.setLocale(instance.getLocale() + 'x'); setTimeout(function() { assert.equal(count, 2, 'handler was called although deactivated'); done(); }, 100); }); }); describe('#onTranslationNotFound', function() { it('is a function', function() { assert.isFunction(instance.onTranslationNotFound); }); it('is called when the translation is missing and a fallback is provided as option', function(done) { var handler = function() { done(); }; instance.onTranslationNotFound(handler); instance.translate('foo', { fallback: 'bar' }); instance.offTranslationNotFound(handler); }); it('is not called when the translation is missing and no fallback is provided as option', function(done) { var handler = function() { done('function was called'); }; instance.onTranslationNotFound(handler); instance.translate('foo', { fallback: undefined }); instance.offTranslationNotFound(handler); setTimeout(done, 100); }); it('is not called when a translation exists', function(done) { var handler = function() { done('function was called'); }; instance.registerTranslations('xx', { foo: 'bar' }); instance.onTranslationNotFound(handler); instance.translate('foo', { locale: 'xx', fallback: 'baz' }); instance.offTranslationNotFound(handler); setTimeout(done, 100); }); describe('when called', function() { it('exposes the current locale, key, and fallback as arguments', function(done) { var handler = function(locale, key, fallback) { assert.equal('yy', locale); assert.equal('foo', key); assert.equal('bar', fallback); done(); }; instance.onTranslationNotFound(handler); instance.translate('foo', { locale: 'yy', fallback: 'bar' }); instance.offTranslationNotFound(handler); }); }); }); describe('#offTranslationNotFound', function() { it('is a function', function() { assert.isFunction(instance.offTranslationNotFound); }); it('stops the emission of events to the handler', function(done) { var count = 0; var handler = function() { count++; }; instance.onTranslationNotFound(handler); instance.translate('foo', { fallback: 'bar' }); instance.translate('foo', { fallback: 'bar' }); instance.offTranslationNotFound(handler); instance.translate('foo', { fallback: 'bar' }); setTimeout(function() { assert.equal(count, 2, 'handler was called although deactivated'); done(); }, 100); }); }); describe('#getSeparator', function() { it('is a function', function() { assert.isFunction(instance.getSeparator); }); it('returns the separator stored in the registry', function() { assert.equal(instance.getSeparator(), instance._registry.separator); }); it('returns "." by default', function() { assert.equal(instance.getSeparator(), '.'); }); }); describe('#setSeparator', function() { it('is a function', function() { assert.isFunction(instance.setSeparator); }); it('sets the separator stored in the registry', function() { var prev = instance._registry.separator; instance.setSeparator('*'); assert.equal(instance._registry.separator, '*'); instance._registry.separator = prev; }); it('returns the previous separator that was stored in the registry', function() { var current = instance.getSeparator(); var previous = instance.setSeparator(current + 'x'); assert.equal(previous, current); instance.setSeparator(current); }); }); describe('#getInterpolate', function() { it('is a function', function() { assert.isFunction(instance.getInterpolate); }); it('returns the setting stored in the registry', function() { assert.equal(instance.getInterpolate(), instance._registry.interpolate); }); it('returns true by default', function() { assert.equal(instance.getInterpolate(), true); }); }); describe('#setInterpolate', function() { it('is a function', function() { assert.isFunction(instance.setInterpolate); }); it('sets the interpolate stored in the registry', function() { var prev = instance._registry.interpolate; instance.setInterpolate(true); assert.equal(instance._registry.interpolate, true); instance._registry.interpolate = prev; }); it('returns the previous interpolate that was stored in the registry', function() { var current = instance.getInterpolate(); var previous = instance.setInterpolate(true); assert.equal(previous, current); instance.setInterpolate(current); }); }); describe('#getKeyTransformer', function() { it('is a function', function() { assert.isFunction(instance.getKeyTransformer); }); it('returns the setting stored in the registry', function() { assert.equal(instance.getKeyTransformer(), instance._registry.keyTransformer); }); }); describe('#setKeyTransformer', function() { var transformer = function(key, options) { assert.deepEqual({ locale: 'xx', bingo: 'bongo' }, options); return key.toLowerCase(); }; it('is a function', function() { assert.isFunction(instance.setKeyTransformer); }); it('sets the keyTransformer stored in the registry', function() { var prev = instance._registry.keyTransformer; instance.setKeyTransformer(transformer); assert.equal(instance._registry.keyTransformer, transformer); instance._registry.keyTransformer = prev; }); it('returns the previous keyTransformer that was stored in the registry', function() { var current = instance.getKeyTransformer(); var previous = instance.setKeyTransformer(transformer); assert.equal(previous, current); instance.setKeyTransformer(current); }); it('uses the custom key transformer when translating', function() { instance.registerTranslations('xx', { foo: 'bar' }); var translation = instance.translate('FOO', { locale: 'xx', bingo: 'bongo' }); assert.matches(translation, /missing translation/); instance.setKeyTransformer(transformer); translation = instance.translate('FOO', { locale: 'xx', bingo: 'bongo' }); assert.equal('bar', translation); }); }); describe('#withSeparator', function() { it('is a function', function() { assert.isFunction(instance.withSeparator); }); it('temporarily changes the current separator within the callback', function() { var separator = instance.getSeparator(); instance.withSeparator(separator + 'x', function() { assert.equal(instance.getSeparator(), separator + 'x'); }); assert.equal(instance.getSeparator(), separator); }); it('allows a custom callback context to be set', function() { instance.withSeparator('foo', function() { assert.equal(this.bar, 'baz'); }, { bar: 'baz' }) }); it('returns the return value of the callback', function() { var result = instance.withSeparator('foo', function() { return 'bar'; }); assert.equal(result, 'bar'); }); }); describe('#localize', function() { before(function() { instance.setLocale('en'); }); it('is a function', function() { assert.isFunction(instance.localize); }); it('does not mutate these options', function() { var options = { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }; instance.localize(new Date(), options); assert.deepEqual(options, { locale: 'en', scope: ['foo1', 'foo2'], count: 3, bar: { baz: 'bum' } }); }); describe('when called without a date as first argument', function() { it('throws an invalid argument error', function() { assert.throws(function() { instance.localize('foo'); }, /invalid argument/); }); }); describe('when called with a date as first argument', function() { var date = new time.Date('Thu Feb 6 2014 05:09:04 GMT+0100 (CET)'); date.setTimezone('America/Chicago'); describe('without providing options as second argument', function() { it('returns the default localization for that date', function() { var result = instance.localize(date); assert.equal(result, 'Wed, 5 Feb 2014 22:09'); }); }); describe('providing a `format` key in the options', function() { describe('with format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { format: 'default' }); assert.equal(result, 'Wed, 5 Feb 2014 22:09'); }); }); describe('with format = "short"', function() { it('returns the short localization for that date', function() { var result = instance.localize(date, { format: 'short' }); assert.equal(result, '5 Feb 22:09'); }); }); describe('with format = "long"', function() { it('returns the long localization for that date', function() { var result = instance.localize(date, { format: 'long' }); assert.equal(result, 'Wednesday, February 5th, 2014 22:09:04 -06:00'); }); }); describe('with an unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', function() { describe('with type = "datetime"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime' }); assert.equal(result, 'Wed, 5 Feb 2014 22:09'); }); }); describe('with type = "date"', function() { it('returns the date localization for that date', function() { var result = instance.localize(date, { type: 'date' }); assert.equal(result, 'Wed, 5 Feb 2014'); }); }); describe('with type = "time"', function() { it('returns the time localization for that date', function() { var result = instance.localize(date, { type: 'time' }); assert.equal(result, '22:09'); }); }); describe('with an unknown type', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', function() { describe('with type = "datetime" and format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'default' }); assert.equal(result, 'Wed, 5 Feb 2014 22:09'); }); }); describe('with type = "datetime" and format = "short"', function() { it('returns the short datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'short' }); assert.equal(result, '5 Feb 22:09'); }); }); describe('with type = "datetime" and format = "long"', function() { it('returns the long datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'long' }); assert.equal(result, 'Wednesday, February 5th, 2014 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', function() { it('returns the default time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'default' }); assert.equal(result, '22:09'); }); }); describe('with type = "time" and format = "short"', function() { it('returns the short time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'short' }); assert.equal(result, '22:09'); }); }); describe('with type = "time" and format = "long"', function() { it('returns the long time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'long' }); assert.equal(result, '22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', function() { it('returns the default date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'default' }); assert.equal(result, 'Wed, 5 Feb 2014'); }); }); describe('with type = "date" and format = "short"', function() { it('returns the short date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'short' }); assert.equal(result, 'Feb 5'); }); }); describe('with type = "date" and format = "long"', function() { it('returns the long date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'long' }); assert.equal(result, 'Wednesday, February 5th, 2014'); }); }); describe('with unknown type and unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('with locale set to "de"', function() { var prev; beforeEach(function() { instance.registerTranslations('de', require('./locales/de')); prev = instance.setLocale('de'); }); afterEach(function() { instance.setLocale(prev); }); describe('without providing options as second argument', function() { it('returns the default localization for that date', function() { var result = instance.localize(date); assert.equal(result, 'Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('providing a `format` key in the options', function() { describe('with format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { format: 'default' }); assert.equal(result, 'Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with format = "short"', function() { it('returns the short localization for that date', function() { var result = instance.localize(date, { format: 'short' }); assert.equal(result, '05.02.14 22:09'); }); }); describe('with format = "long"', function() { it('returns the long localization for that date', function() { var result = instance.localize(date, { format: 'long' }); assert.equal(result, 'Mittwoch, 5. Februar 2014, 22:09:04 -06:00'); }); }); describe('with an unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', function() { describe('with type = "datetime"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime' }); assert.equal(result, 'Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with type = "date"', function() { it('returns the date localization for that date', function() { var result = instance.localize(date, { type: 'date' }); assert.equal(result, 'Mi, 5. Feb 2014'); }); }); describe('with type = "time"', function() { it('returns the time localization for that date', function() { var result = instance.localize(date, { type: 'time' }); assert.equal(result, '22:09 Uhr'); }); }); describe('with an unknown type', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', function() { describe('with type = "datetime" and format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'default' }); assert.equal(result, 'Mi, 5. Feb 2014, 22:09 Uhr'); }); }); describe('with type = "datetime" and format = "short"', function() { it('returns the short datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'short' }); assert.equal(result, '05.02.14 22:09'); }); }); describe('with type = "datetime" and format = "long"', function() { it('returns the long datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'long' }); assert.equal(result, 'Mittwoch, 5. Februar 2014, 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', function() { it('returns the default time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'default' }); assert.equal(result, '22:09 Uhr'); }); }); describe('with type = "time" and format = "short"', function() { it('returns the short time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'short' }); assert.equal(result, '22:09'); }); }); describe('with type = "time" and format = "long"', function() { it('returns the long time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'long' }); assert.equal(result, '22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', function() { it('returns the default date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'default' }); assert.equal(result, 'Mi, 5. Feb 2014'); }); }); describe('with type = "date" and format = "short"', function() { it('returns the short date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'short' }); assert.equal(result, '05.02.14'); }); }); describe('with type = "date" and format = "long"', function() { it('returns the long date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'long' }); assert.equal(result, 'Mittwoch, 5. Februar 2014'); }); }); describe('with unknown type and unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); }); describe('with locale set to "pt-br"', function() { var prev; beforeEach(function() { instance.registerTranslations('pt-br', require('./locales/pt-br')); prev = instance.setLocale('pt-br'); }); afterEach(function() { instance.setLocale(prev); }); describe('without providing options as second argument', function() { it('returns the default localization for that date', function() { var result = instance.localize(date); assert.equal(result, 'Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('providing a `format` key in the options', function() { describe('with format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { format: 'default' }); assert.equal(result, 'Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with format = "short"', function() { it('returns the short localization for that date', function() { var result = instance.localize(date, { format: 'short' }); assert.equal(result, '05/02/14 às 22:09'); }); }); describe('with format = "long"', function() { it('returns the long localization for that date', function() { var result = instance.localize(date, { format: 'long' }); assert.equal(result, 'Quarta-feira, 5 de Fevereiro de 2014 às 22:09:04 -06:00'); }); }); describe('with an unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing a `type` key in the options', function() { describe('with type = "datetime"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime' }); assert.equal(result, 'Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with type = "date"', function() { it('returns the date localization for that date', function() { var result = instance.localize(date, { type: 'date' }); assert.equal(result, 'Qua, 5 de Fev de 2014'); }); }); describe('with type = "time"', function() { it('returns the time localization for that date', function() { var result = instance.localize(date, { type: 'time' }); assert.equal(result, '22:09'); }); }); describe('with an unknown type', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); describe('providing both a `type` key and a `format` key in the options', function() { describe('with type = "datetime" and format = "default"', function() { it('returns the default localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'default' }); assert.equal(result, 'Qua, 5 de Fev de 2014 às 22:09'); }); }); describe('with type = "datetime" and format = "short"', function() { it('returns the short datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'short' }); assert.equal(result, '05/02/14 às 22:09'); }); }); describe('with type = "datetime" and format = "long"', function() { it('returns the long datetime localization for that date', function() { var result = instance.localize(date, { type: 'datetime', format: 'long' }); assert.equal(result, 'Quarta-feira, 5 de Fevereiro de 2014 às 22:09:04 -06:00'); }); }); describe('with type = "time" and format = "default"', function() { it('returns the default time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'default' }); assert.equal(result, '22:09'); }); }); describe('with type = "time" and format = "short"', function() { it('returns the short time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'short' }); assert.equal(result, '22:09'); }); }); describe('with type = "time" and format = "long"', function() { it('returns the long time localization for that date', function() { var result = instance.localize(date, { type: 'time', format: 'long' }); assert.equal(result, '22:09:04 -06:00'); }); }); describe('with type = "date" and format = "default"', function() { it('returns the default date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'default' }); assert.equal(result, 'Qua, 5 de Fev de 2014'); }); }); describe('with type = "date" and format = "short"', function() { it('returns the short date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'short' }); assert.equal(result, '05/02/14'); }); }); describe('with type = "date" and format = "long"', function() { it('returns the long date localization for that date', function() { var result = instance.localize(date, { type: 'date', format: 'long' }); assert.equal(result, 'Quarta-feira, 5 de Fevereiro de 2014'); }); }); describe('with unknown type and unknown format', function() { it('returns a string containing "missing translation"', function() { var result = instance.localize(date, { type: '__invalid__', format: '__invalid__' }); assert.matches(result, /missing translation/); }); }); }); }); }); }); describe('#registerTranslations', function() { it('is a function', function() { assert.isFunction(instance.registerTranslations); }); it('returns the passed arguments as an object structure', function() { var locale = 'foo'; var data = { bar: { baz: 'bingo' } }; var actual = instance.registerTranslations(locale, data); var expected = { foo: { bar: { baz: 'bingo' }}}; assert.deepEqual(actual, expected); }); it('merges the passed arguments correctly into the registry', function() { instance._registry.translations = {}; instance.registerTranslations('foo', { bar: { baz: 'bingo' } }); var expected = { foo: { bar: { baz: 'bingo' } } }; assert.deepEqual(instance._registry.translations, expected); instance.registerTranslations('foo', { bar: { bam: 'boo' } }); var expected = { foo: { bar: { baz: 'bingo', bam: 'boo' } } }; assert.deepEqual(instance._registry.translations, expected); instance.registerTranslations('foo', { bing: { bong: 'beng' } }); var expected = { foo: { bar: { baz: 'bingo', bam: 'boo' }, bing: { bong: 'beng' } } }; assert.deepEqual(instance._registry.translations, expected); // clean up instance._registry.translations = {}; instance.registerTranslations('en', require('./locales/en')); }); }); describe('#registerInterpolations', function() { it('is a function', function() { assert.isFunction(instance.registerInterpolations); }); it('merges the passed arguments correctly into the registry', function() { instance._registry.interpolations = {}; instance.registerInterpolations({ foo: 'yes', bar: 'no' }); assert.deepEqual(instance._registry.interpolations, { foo: 'yes', bar: 'no' }); instance.registerInterpolations({ baz: 'hey' }); assert.deepEqual(instance._registry.interpolations, { foo: 'yes', bar: 'no', baz: 'hey' }); // clean up instance._registry.interpolations = {}; }); }); describe('explicitly checking the examples of the README', function() { it('passes all tests', function() { translate.registerTranslations('en', { damals: { about_x_hours_ago: { one: 'about one hour ago', other: 'about %(count)s hours ago' } } }); assert.deepEqual(translate('damals'), { about_x_hours_ago: { one: 'about one hour ago', other: 'about %(count)s hours ago' } }); assert.equal(translate('damals.about_x_hours_ago.one'), 'about one hour ago'); assert.equal(translate(['damals', 'about_x_hours_ago', 'one']), 'about one hour ago'); assert.equal(translate(['damals', 'about_x_hours_ago.one']), 'about one hour ago'); assert.equal(translate('about_x_hours_ago.one', { scope: 'damals' }), 'about one hour ago'); assert.equal(translate('one', { scope: 'damals.about_x_hours_ago' }), 'about one hour ago'); assert.equal(translate('one', { scope: ['damals', 'about_x_hours_ago'] }), 'about one hour ago'); assert.equal(translate('damals.about_x_hours_ago.one', { separator: '*' }), 'missing translation: en*damals.about_x_hours_ago.one'); translate.registerTranslations('en', { foo: 'foo %(bar)s' }); assert.equal(translate('foo', { bar: 'baz' }), 'foo baz'); translate.registerTranslations('en', { x_items: { zero: 'No items.', one: 'One item.', other: '%(count)s items.' } }); assert.equal(translate('x_items', { count: 0 }), 'No items.'); assert.equal(translate('x_items', { count: 1 }), 'One item.'); assert.equal(translate('x_items', { count: 42 }), '42 items.'); assert.equal(translate('baz', { fallback: 'default' }), 'default'); translate.registerTranslations('de', require('./locales/de')); translate.registerTranslations('de', JSON.parse('{"my_project": {"greeting": "Hallo, %(name)s!","x_items": {"one": "1 Stück", "other": "%(count)s Stücke"}}}')); assert.equal(translate.withLocale('de', function() { return translate('greeting', { scope: 'my_project', name: 'Martin' }); }), 'Hallo, Martin!'); assert.equal(translate.withLocale('de', function() { return translate('x_items', { scope: 'my_project', count: 1 }); }), '1 Stück'); var date = new time.Date('Fri Feb 21 2014 13:46:24 GMT+0100 (CET)'); date.setTimezone('Europe/Amsterdam'); assert.equal(translate.localize(date) , 'Fri, 21 Feb 2014 13:46'); assert.equal(translate.localize(date, { format: 'short' }) , '21 Feb 13:46'); assert.equal(translate.localize(date, { format: 'long' }) , 'Friday, February 21st, 2014 13:46:24 +01:00'); assert.equal(translate.localize(date, { type: 'date' }) , 'Fri, 21 Feb 2014'); assert.equal(translate.localize(date, { type: 'date', format: 'short' }) , 'Feb 21'); assert.equal(translate.localize(date, { type: 'date', format: 'long' }) , 'Friday, February 21st, 2014'); assert.equal(translate.localize(date, { type: 'time' }) , '13:46'); assert.equal(translate.localize(date, { type: 'time', format: 'short' }) , '13:46'); assert.equal(translate.localize(date, { type: 'time', format: 'long' }) , '13:46:24 +01:00'); assert.equal(translate.localize(date, { locale: 'de' }) , 'Fr, 21. Feb 2014, 13:46 Uhr'); translate.registerTranslations('en', { my_namespace: { greeting: 'Welcome to %(app_name)s, %(visitor)s!' } }); translate.registerInterpolations({ app_name: 'My Cool App' }); assert.equal(translate('my_namespace.greeting', { visitor: 'Martin' }), 'Welcome to My Cool App, Martin!'); assert.equal(translate('my_namespace.greeting', { visitor: 'Martin', app_name: 'The Foo App' }), 'Welcome to The Foo App, Martin!'); }); }); }); /* Helper Functions */ assert.isString = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object String]', message || (value + ' is not a string')); }; assert.isFunction = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Function]', message || (value + ' is not a function')); }; assert.isObject = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Object]', message || (value + ' is not an object')); }; assert.isUndefined = function(value, message) { assert.equal(Object.prototype.toString.call(value), '[object Undefined]', message || (value + ' is not undefined')); }; assert.matches = function(actual, expected, message) { if (!expected.test(actual)) { assert.fail(actual, expected, message, '!~'); } }; <file_sep>import { Fraction } from "fractional"; import { BigNumber } from "bignumber.js"; const BnFrDown = BigNumber.another({ ROUNDING_MODE: BigNumber.ROUND_DOWN }); const BnFrUp = BigNumber.another({ ROUNDING_MODE: BigNumber.ROUND_UP }); const GRAPHENE_100_PERCENT = 10000; function limitByPrecision(value, p = 8) { if (typeof p !== "number") throw new Error("Input must be a number"); let valueString = value.toString(); let splitString = valueString.split("."); if ( splitString.length === 1 || (splitString.length === 2 && splitString[1].length <= p) ) { return parseFloat(valueString); } else { return parseFloat(splitString[0] + "." + splitString[1].substr(0, p)); } } function precisionToRatio(p) { if (typeof p !== "number") throw new Error("Input must be a number"); return Math.pow(10, p); } function didOrdersChange(newOrders, oldOrders) { let changed = oldOrders && oldOrders.size !== newOrders.size; if (changed) return changed; newOrders.forEach((a, key) => { let oldOrder = oldOrders.get(key); if (!oldOrder) { changed = true; } else { if (a.market_base === oldOrder.market_base) { changed = changed || a.ne(oldOrder); } } }); return changed; } class Asset { satoshi; asset_id; precision; amount; _real_amount; constructor({ asset_id = "1.3.0", amount = 0, precision = 5, real = null } = {}) { this.satoshi = precisionToRatio(precision); this.asset_id = asset_id; this.setAmount({ sats: amount, real }); this.precision = precision; } hasAmount() { return this.amount > 0; } toSats(amount = 1) { // Return the full integer amount in 'satoshis' // Round to prevent floating point math errors return Math.round(amount * this.satoshi); } setAmount({ sats, real }) { if (typeof sats === "string") sats = parseInt(sats, 10); if (typeof real === "string") real = parseFloat(real); if (typeof sats !== "number" && typeof real !== "number") { throw new Error("Invalid arguments for setAmount"); } if (typeof real === "number") { this.amount = this.toSats(real); this._clearCache(); } else if (typeof sats === "number") { this.amount = Math.floor(sats); this._clearCache(); } else { throw new Error("Invalid setAmount input"); } } _clearCache() { this._real_amount = null; } getAmount({ real = false } = {}) { if (real) { if (this._real_amount) return this._real_amount; return (this._real_amount = limitByPrecision( this.amount / this.toSats(), this.precision )); } else { return Math.floor(this.amount); } } plus(asset) { if (asset.asset_id !== this.asset_id) throw new Error("Assets are not the same type"); this.amount += asset.amount; this._clearCache(); } minus(asset) { if (asset.asset_id !== this.asset_id) throw new Error("Assets are not the same type"); this.amount -= asset.amount; this.amount = Math.max(0, this.amount); this._clearCache(); } equals(asset) { return ( this.asset_id === asset.asset_id && this.getAmount() === asset.getAmount() ); } ne(asset) { return !this.equals(asset); } gt(asset) { return this.getAmount() > asset.getAmount(); } lt(asset) { return this.getAmount() < asset.getAmount(); } times(p, isBid = false) { // asset amount times a price p let temp, amount; if (this.asset_id === p.base.asset_id) { temp = (this.amount * p.quote.amount) / p.base.amount; amount = Math.floor(temp); /* * Sometimes prices are inexact for the relevant amounts, in the case * of bids this means we need to round up in order to pay 1 sat more * than the floored price, if we don't do this the orders don't match */ if (isBid && temp !== amount) { amount += 1; } if (amount === 0) amount = 1; return new Asset({ asset_id: p.quote.asset_id, amount, precision: p.quote.precision }); } else if (this.asset_id === p.quote.asset_id) { temp = (this.amount * p.base.amount) / p.quote.amount; amount = Math.floor(temp); /* * Sometimes prices are inexact for the relevant amounts, in the case * of bids this means we need to round up in order to pay 1 sat more * than the floored price, if we don't do this the orders don't match */ if (isBid && temp !== amount) { amount += 1; } if (amount === 0) amount = 1; return new Asset({ asset_id: p.base.asset_id, amount, precision: p.base.precision }); } throw new Error("Invalid asset types for price multiplication"); } divide(quote, base = this) { return new Price({ base, quote }); } toObject() { return { asset_id: this.asset_id, amount: this.amount }; } clone(amount = this.amount) { return new Asset({ amount, asset_id: this.asset_id, precision: this.precision }); } } enum FrDirection { Normal, Up, Down } /** * @brief The price struct stores asset prices in the Graphene system. * * A price is defined as a ratio between two assets, and represents a possible exchange rate between those two * assets. prices are generally not stored in any simplified form, i.e. a price of (1000 CORE)/(20 USD) is perfectly * normal. * * The assets within a price are labeled base and quote. Throughout the Graphene code base, the convention used is * that the base asset is the asset being sold, and the quote asset is the asset being purchased, where the price is * represented as base/quote, so in the example price above the seller is looking to sell CORE asset and get USD in * return. */ class Price { base; quote; constructor({ base, quote, real = false }: { base?; quote?; real? } = {}) { if (!base || !quote) { throw new Error("Base and Quote assets must be defined"); } if (base.asset_id === quote.asset_id) { throw new Error("Base and Quote assets must be different"); } base = base.clone(); quote = quote.clone(); if (real && typeof real === "number") { /* * In order to make large numbers work properly, we assume numbers * larger than 100k do not need more than 5 decimals. Without this we * quickly encounter JavaScript floating point errors for large numbers. */ if (real > 100000) { real = limitByPrecision(real, 5); } let frac = new Fraction(real); let baseSats = base.toSats(), quoteSats = quote.toSats(); let numRatio = baseSats / quoteSats, denRatio = quoteSats / baseSats; if (baseSats >= quoteSats) { denRatio = 1; } else { numRatio = 1; } base.amount = frac.numerator * numRatio; quote.amount = frac.denominator * denRatio; } else if (real === 0) { base.amount = 0; quote.amount = 0; } if ( !base.asset_id || !("amount" in base) || !quote.asset_id || !("amount" in quote) ) throw new Error("Invalid Price inputs"); this.base = base; this.quote = quote; } getUnits() { return this.base.asset_id + "_" + this.quote.asset_id; } isValid() { return ( this.base.amount !== 0 && this.quote.amount !== 0 && !isNaN(this.toReal()) && isFinite(this.toReal()) ); } toReal(sameBase = false, digits = 8, frDirection = FrDirection.Normal) { const key = digits.toString() + (sameBase ? "_samebase_real" : "_not_samebase_real"); if (this[key]) { return this[key]; } // Todo // Trying to be more accurate let real = sameBase ? (this.quote.amount * this.base.toSats()) / (this.base.amount * this.quote.toSats()) : (this.base.amount * this.quote.toSats()) / (this.quote.amount * this.base.toSats()); // this[key] = parseFloat(real.toFixed(digits)); this[key] = parseFloat( frDirection === FrDirection.Down ? new BnFrDown(real.toString()).toFixed(digits) : frDirection === FrDirection.Up ? new BnFrUp(real.toString()).toFixed(digits) : new BigNumber(real.toString()).toFixed(digits) ); return this[key]; // toFixed and parseFloat helps avoid floating point errors for really big or small numbers } invert() { return new Price({ base: this.quote, quote: this.base }); } clone(real = null) { return new Price({ base: this.base, quote: this.quote, real }); } equals(b) { if ( this.base.asset_id !== b.base.asset_id || this.quote.asset_id !== b.quote.asset_id ) { // console.error("Cannot compare prices for different assets"); return false; } const amult = b.quote.amount * this.base.amount; const bmult = this.quote.amount * b.base.amount; return amult === bmult; } lt(b) { if ( this.base.asset_id !== b.base.asset_id || this.quote.asset_id !== b.quote.asset_id ) { throw new Error("Cannot compare prices for different assets"); } const amult = b.quote.amount * this.base.amount; const bmult = this.quote.amount * b.base.amount; return amult < bmult; } lte(b) { return this.equals(b) || this.lt(b); } ne(b) { return !this.equals(b); } gt(b) { return !this.lte(b); } gte(b) { return !this.lt(b); } toObject() { return { base: this.base.toObject(), quote: this.quote.toObject() }; } times(p, common = "1.3.0") { const p2 = (p.base.asset_id === common && this.quote.asset_id === common) || (p.quote.asset_id === common && this.base.asset_id === common) ? p.clone() : p.invert(); const np = p2.toReal() * this.toReal(); return new Price({ base: p2.base, quote: this.quote, real: np }); } } class FeedPrice extends Price { _squeeze_price; sqr; inverted; constructor({ priceObject, assets, market_base, sqr, real = false }) { if ( !priceObject || typeof priceObject !== "object" || !market_base || !assets || !sqr ) { throw new Error("Invalid FeedPrice inputs"); } if (priceObject.toJS) { priceObject = priceObject.toJS(); } const inverted = market_base === priceObject.base.asset_id; const base = new Asset({ asset_id: priceObject.base.asset_id, amount: priceObject.base.amount, precision: assets[priceObject.base.asset_id].precision }); const quote = new Asset({ asset_id: priceObject.quote.asset_id, amount: priceObject.quote.amount, precision: assets[priceObject.quote.asset_id].precision }); super({ base: inverted ? quote : base, quote: inverted ? base : quote, real }); this.sqr = parseInt(sqr, 10) / 1000; this.inverted = inverted; } getSqueezePrice({ real = false } = {}) { if (!this._squeeze_price) { this._squeeze_price = this.clone(); if (this.inverted) this._squeeze_price.base.amount = Math.floor( this._squeeze_price.base.amount * this.sqr ); if (!this.inverted) this._squeeze_price.quote.amount = Math.floor( this._squeeze_price.quote.amount * this.sqr ); } if (real) { return this._squeeze_price.toReal(); } return this._squeeze_price; } } class LimitOrderCreate { fill_or_kill; min_to_receive; amount_for_sale; seller; fee; expiration; constructor({ for_sale, to_receive, seller = "", expiration = new Date(), fill_or_kill = false, fee = { amount: 0, asset_id: "1.3.0" } } = {}) { if (!for_sale || !to_receive) { throw new Error("Missing order amounts"); } if (for_sale.asset_id === to_receive.asset_id) { throw new Error("Order assets cannot be the same"); } this.amount_for_sale = for_sale; this.min_to_receive = to_receive; this.setExpiration(expiration); this.fill_or_kill = fill_or_kill; this.seller = seller; this.fee = fee; } setExpiration(expiration = null) { if (!expiration) { expiration = new Date(); expiration.setYear(expiration.getFullYear() + 5); } this.expiration = expiration; } getExpiration() { return this.expiration; } toObject() { return { seller: this.seller, min_to_receive: this.min_to_receive.toObject(), amount_to_sell: this.amount_for_sale.toObject(), expiration: this.expiration, fill_or_kill: this.fill_or_kill, fee: this.fee }; } } type RteOrderPrice = string; type RteOrderAmount = string; type RteOrder = [RteOrderPrice, RteOrderAmount]; class LimitOrder { order; assets; market_base; id; sellers; expiration; seller; for_sale; sell_price; fee; _real_price = {}; _for_sale; _to_receive; _total_for_sale; _total_to_receive; total_to_receive; total_for_sale; init_for_sale; constructor(order, assets, market_base) { if (!market_base) { throw new Error("LimitOrder requires a market_base id"); } this.order = order; this.assets = assets; this.market_base = market_base; this.id = order.id; this.sellers = [order.seller]; this.expiration = order.expiration && new Date(order.expiration); this.seller = order.seller; this.for_sale = parseInt(order.for_sale, 10); // asset id is sell_price.base.asset_id this.init_for_sale = parseInt(order.sell_price.base.amount, 10); let base = new Asset({ asset_id: order.sell_price.base.asset_id, amount: this.init_for_sale, precision: assets[order.sell_price.base.asset_id].precision }); let quote = new Asset({ asset_id: order.sell_price.quote.asset_id, amount: parseInt(order.sell_price.quote.amount, 10), precision: assets[order.sell_price.quote.asset_id].precision }); this.sell_price = new Price({ base, quote }); this.fee = order.deferred_fee; } /** * * order = { id: '1.7.108864616', * expiration: '2023-08-27T05:34:23', * seller: '1.2.7581', * for_sale: 21717, * sell_price: * { base: { amount: 21717, asset_id: '1.3.2' }, * quote: { amount: 22200000, asset_id: '1.3.0' } }, * deferred_fee: 100 } * * * @param rteOrder * @param baseAsset * @param quoteAsset * @param isRteBid */ static fromRteOrder( rteOrder: RteOrder, marketBaseAsset, marketQuoteAsset, isRteBid: boolean = false ) { // Todo adjust precision; To more accurate, uncomment this let priceDigits = marketBaseAsset.get("precision") + marketQuoteAsset.get("precision") + 2; // let value = isRteBid // ? new BigNumber(rteOrder[1]) // : new BigNumber(rteOrder[0]).mul(new BigNumber(rteOrder[1])); // let qty = isRteBid // ? new BigNumber(rteOrder[0]).mul(new BigNumber(rteOrder[1])) // : new BigNumber(rteOrder[1]); // let for_sale = isRteBid // ? qty.mul(Math.pow(10, marketBaseAsset.get("precision"))) // : qty.mul(Math.pow(10, marketQuoteAsset.get("precision"))); // let base = qty.mul(Math.pow(10, priceDigits)); // let quote = value.mul(Math.pow(10, priceDigits)); // ----------- // No accurate for temporary // let priceDigits = isRteBid // ? marketBaseAsset.get("precision") // : marketQuoteAsset.get("precision"); let value = isRteBid ? new BigNumber(rteOrder[1]) : new BigNumber(rteOrder[0]).mul(new BigNumber(rteOrder[1])); let qty = isRteBid ? new BigNumber(rteOrder[0]).mul(new BigNumber(rteOrder[1])) : new BigNumber(rteOrder[1]); let for_sale = isRteBid ? qty.mul(Math.pow(10, marketBaseAsset.get("precision"))) : qty.mul(Math.pow(10, marketQuoteAsset.get("precision"))); let base = for_sale; let quote = isRteBid ? value.mul(Math.pow(10, marketQuoteAsset.get("precision"))) : value.mul(Math.pow(10, marketBaseAsset.get("precision"))); let order = { id: "1.7.0", seller: "1.2.0", for_sale: parseInt(for_sale.toFixed(0)), sell_price: { base: { amount: parseInt(base.toFixed(0)), asset_id: isRteBid ? marketBaseAsset.get("id") : marketQuoteAsset.get("id") }, quote: { amount: parseInt(quote.toFixed(0)), asset_id: isRteBid ? marketQuoteAsset.get("id") : marketBaseAsset.get("id") } } }; return new LimitOrder( order, { [marketQuoteAsset.get("id")]: marketQuoteAsset.toJS(), [marketBaseAsset.get("id")]: marketBaseAsset.toJS() }, marketQuoteAsset.get("id") ); } getPrice(p = this.sell_price, d = 8) { if (this._real_price[d]) { return this._real_price[d]; } this._real_price[d] = p.toReal( p.base.asset_id === this.market_base, d, this.isBid() ? FrDirection.Down : FrDirection.Up ); return this._real_price[d]; } isBid() { return !(this.sell_price.base.asset_id === this.market_base); } isCall() { return false; } sellPrice() { return this.sell_price; } amountForSale() { if (this._for_sale) return this._for_sale; return (this._for_sale = new Asset({ asset_id: this.sell_price.base.asset_id, amount: this.for_sale, precision: this.assets[this.sell_price.base.asset_id].precision })); } amountToReceive(isBid = this.isBid()) { if (this._to_receive) return this._to_receive; this._to_receive = this.amountForSale().times(this.sell_price, isBid); return this._to_receive; } sum(order) { let newOrder = this.clone(); delete newOrder._to_receive; delete this._to_receive; if (newOrder.sellers.indexOf(order.seller) === -1) { newOrder.sellers.push(order.seller); } newOrder.for_sale += order.for_sale; newOrder.init_for_sale += order.init_for_sale; newOrder.sell_price.base.amount = order.sell_price.base.amount + this.sell_price.base.amount; newOrder.sell_price.quote.amount = order.sell_price.quote.amount + this.sell_price.quote.amount; return newOrder; } isMine(id) { return this.sellers.indexOf(id) !== -1; } clone() { let thisOrder = { ...this.order, for_sale: this.for_sale }; return new LimitOrder(thisOrder, this.assets, this.market_base); } ne(order) { return ( this.sell_price.ne(order.sell_price) || this.for_sale !== order.for_sale ); } equals(order) { return !this.ne(order); } setTotalToReceive(total) { this.total_to_receive = total; } setTotalForSale(total) { this.total_for_sale = total; this._total_to_receive = null; } totalToReceive({ noCache = false } = {}) { if (!noCache && this._total_to_receive) return this._total_to_receive; this._total_to_receive = ( this.total_to_receive || this.amountToReceive() ).clone(); return this._total_to_receive; } totalForSale({ noCache = false } = {}) { if (!noCache && this._total_for_sale) return this._total_for_sale; return (this._total_for_sale = ( this.total_for_sale || this.amountForSale() ).clone()); } } class CallOrder { call_price; order; assets; market_base; is_prediction_market; inverted; id; borrower; borrowers; for_sale; for_sale_id; to_receive; to_receive_id; feed_price; _real_price = {}; _feed_price; _squeeze_price; _collateral; total_for_sale; _for_sale; _to_receive; _total_to_receive; _total_for_sale; total_to_receive; constructor(order, assets, market_base, feed, is_prediction_market = false) { if (!order || !assets || !market_base || !feed) { throw new Error("CallOrder missing inputs"); } this.order = order; this.assets = assets; this.market_base = market_base; this.is_prediction_market = is_prediction_market; this.inverted = market_base === order.call_price.base.asset_id; this.id = order.id; this.borrower = order.borrower; this.borrowers = [order.borrower]; /* Collateral asset type is call_price.base.asset_id */ this.for_sale = parseInt(order.collateral, 10); this.for_sale_id = order.call_price.base.asset_id; /* Debt asset type is call_price.quote.asset_id */ this.to_receive = parseInt(order.debt, 10); this.to_receive_id = order.call_price.quote.asset_id; let base = new Asset({ asset_id: order.call_price.base.asset_id, amount: parseInt(order.call_price.base.amount, 10), precision: assets[order.call_price.base.asset_id].precision }); let quote = new Asset({ asset_id: order.call_price.quote.asset_id, amount: parseInt(order.call_price.quote.amount, 10), precision: assets[order.call_price.quote.asset_id].precision }); /* * The call price is DEBT * MCR / COLLATERAL. This calculation is already * done by the witness_node before returning the orders so it is not necessary * to deal with the MCR (maintenance collateral ratio) here. */ this.call_price = new Price({ base: this.inverted ? quote : base, quote: this.inverted ? base : quote }); if (feed.base.asset_id !== this.call_price.base.asset_id) { throw new Error( "Feed price assets and call price assets must be the same" ); } this.feed_price = feed; } clone(f = this.feed_price) { return new CallOrder(this.order, this.assets, this.market_base, f); } setFeed(f) { this.feed_price = f; this._clearCache(); } getPrice(squeeze = true, p = this.call_price, d = 8) { if (squeeze) { return this.getSqueezePrice(); } if (this._real_price[d]) { return this._real_price[d]; } this._real_price[d] = p.toReal(p.base.asset_id === this.market_base, d); return this._real_price[d]; } getFeedPrice(f = this.feed_price) { if (this._feed_price) { return this._feed_price; } return (this._feed_price = f.toReal(f.base.asset_id === this.market_base)); } getSqueezePrice(f = this.feed_price) { if (this._squeeze_price) { return this._squeeze_price; } return (this._squeeze_price = f.getSqueezePrice().toReal()); } isMarginCalled() { if (this.is_prediction_market) return false; return this.isBid() ? this.call_price.lt(this.feed_price) : this.call_price.gt(this.feed_price); } isBid() { return !this.inverted; } isCall() { return true; } sellPrice(squeeze = true) { if (squeeze) { return this.isBid() ? this.feed_price.getSqueezePrice() : this.feed_price.getSqueezePrice().invert(); } return this.call_price; } getCollateral() { if (this._collateral) return this._collateral; return (this._collateral = new Asset({ amount: this.for_sale, asset_id: this.for_sale_id, precision: this.assets[this.for_sale_id].precision })); } /* * Assume a USD:CYB market * The call order will always be selling CYB in order to buy USD * The asset being sold is always the collateral, which is call_price.base.asset_id. * The amount being sold depends on how big the debt is, only enough * collateral will be sold to cover the debt */ amountForSale(isBid = this.isBid()) { if (this._for_sale) return this._for_sale; // return this._for_sale = new Asset({ // asset_id: this.for_sale_id, // amount: this.for_sale, // precision: this.assets[this.for_sale_id].precision // }); return (this._for_sale = this.amountToReceive().times( this.feed_price.getSqueezePrice(), isBid )); } amountToReceive() { if (this._to_receive) return this._to_receive; // return this._to_receive = this.amountForSale().times(this.feed_price.getSqueezePrice(), isBid); return (this._to_receive = new Asset({ asset_id: this.to_receive_id, amount: this.to_receive, precision: this.assets[this.to_receive_id].precision })); } sum(order) { let newOrder = this.clone(); if (newOrder.borrowers.indexOf(order.borrower) === -1) { newOrder.borrowers.push(order.borrower); } newOrder.to_receive += order.to_receive; newOrder.for_sale += order.for_sale; newOrder._clearCache(); return newOrder; } _clearCache() { this._for_sale = null; this._to_receive = null; this._feed_price = null; this._squeeze_price = null; this._total_to_receive = null; this._total_for_sale = null; } ne(order) { return ( this.call_price.ne(order.call_price) || this.feed_price.ne(order.feed_price) || this.to_receive !== order.to_receive || this.for_sale !== order.for_sale ); } equals(order) { return !this.ne(order); } setTotalToReceive(total) { this.total_to_receive = total; } setTotalForSale(total) { this.total_for_sale = total; } totalToReceive({ noCache = false } = {}) { if (!noCache && this._total_to_receive) return this._total_to_receive; this._total_to_receive = ( this.total_to_receive || this.amountToReceive() ).clone(); return this._total_to_receive; } totalForSale({ noCache = false } = {}) { if (!noCache && this._total_for_sale) return this._total_for_sale; return (this._total_for_sale = ( this.total_for_sale || this.amountForSale() ).clone()); } getRatio() { return ( this.getCollateral().getAmount({ real: true }) / this.amountToReceive().getAmount({ real: true }) / this.getFeedPrice() ); } getStatus() { const mr = this.assets[this.to_receive_id].bitasset.current_feed .maintenance_collateral_ratio / 1000; const cr = this.getRatio(); if (isNaN(cr)) return null; if (cr < mr) { return "danger"; } else if (cr < mr + 0.5) { return "warning"; } else { return ""; } } isMine(id) { return this.borrowers.indexOf(id) !== -1; } } class SettleOrder extends LimitOrder { offset_percent; settlement_date; inverted; feed_price; constructor(order, assets, market_base, feed_price, bitasset_options) { if (!feed_price || !bitasset_options) { throw new Error( "SettleOrder needs feed_price and bitasset_options inputs" ); } order.sell_price = feed_price.toObject(); order.seller = order.owner; super(order, assets, market_base); this.offset_percent = bitasset_options.force_settlement_offset_percent; this.settlement_date = new Date(order.settlement_date); this.for_sale = new Asset({ amount: order.balance.amount, asset_id: order.balance.asset_id, precision: assets[order.balance.asset_id].precision }); this.inverted = this.for_sale.asset_id === market_base; this.feed_price = feed_price[this.inverted ? "invert" : "clone"](); } isBefore(order) { return this.settlement_date < order.settlement_date; } amountForSale() { return this.for_sale; } amountToReceive() { let to_receive = this.for_sale.times(this.feed_price, this.isBid()); to_receive.setAmount({ sats: to_receive.getAmount() * ((GRAPHENE_100_PERCENT - this.offset_percent) / GRAPHENE_100_PERCENT) }); return (this._to_receive = to_receive); } isBid() { return !this.inverted; } } export { Asset, Price, FeedPrice, LimitOrderCreate, limitByPrecision, precisionToRatio, LimitOrder, CallOrder, SettleOrder, didOrdersChange }; <file_sep>export const getClassName: (defaultClass: string, appendClass?: { [className: string]: boolean }) => string = (defaultClass, appendClass) => { if (!appendClass) return defaultClass; let res = [defaultClass]; res = [ ...res, ...Object .keys(appendClass) .filter(className => appendClass[className]) ]; return res.join(" "); };<file_sep>cd $TRAVIS_BUILD_DIR unamestr=`uname` if [[ "$unamestr" == 'Linux' && -n $TRAVIS_TAG ]] then npm run build-github npm run build-hash fi npm run-script package <file_sep>// require("file-loader?name=index.html!./" + ((__ELECTRON__ || __HASH_HISTORY__) ? "index-electron" : "index") + ".html"); require("file-loader?name=favicon.ico!./favicon.ico"); // require("file-loader?name=dictionary.json!common/dictionary_en.json"); // require("file-loader?name=insiders.json!./insiders.json"); ///// require("babel-polyfill"); // require("whatwg-fetch"); require("indexeddbshim"); //// require("./stylesheets/app.scss"); // require("./asset-symbols/symbols.js"); require("./language-dropdown/flags.js"); require("./images/images.js"); require("file-loader?name=cybex_rainbow.png!./cybex_rainbow.png"); require("file-loader?name=googleea83a29cf8ae4d2a.html!./googleea83a29cf8ae4d2a.html"); require("file-loader?name=do_not_delete!./do_not_delete"); require("file-loader?name=cybex_rainbow_lg.png!./cybex_rainbow_lg.png"); // import locales from "assets/locales"; // for (let locale of locales) { // require(`file-loader?name=[name].[ext]!./locales/locale-${locale}.json`); // } <file_sep>import * as moment from "moment"; import BigNumber from "bignumber.js"; export const zonePoints = [ { value: 1.35, point: moment("2019-06-30T00:00:00.000Z") }, { value: 1.23, point: moment("2019-07-14T23:59:59.999Z") } ]; let con = new BigNumber(0.97); export const calcBonusCoefficient = (moment: moment.Moment, weight: number) => { let coefficient = zonePoints.find(v => v.point.isAfter(moment)); if (!coefficient) { return 1; } return new BigNumber(weight) .times(new BigNumber(coefficient.value)) .times(con) .toFixed(2, BigNumber.ROUND_DOWN); }; <file_sep>var React = require("react"); var Accordion = require("../../lib/accordion"); var SingleSelect = React.createClass({ render: function() { return ( <Accordion collapsible={false}> <Accordion.Item title="First item title"> {" "} First item content{" "} </Accordion.Item> <Accordion.Item title="Second item title"> {" "} Second item content{" "} </Accordion.Item> <Accordion.Item title="Third item title"> {" "} Third item content{" "} </Accordion.Item> </Accordion> ); } }); module.exports = SingleSelect; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import ChainTypes from "../Utility/ChainTypes"; import BindToChainState from "../Utility/BindToChainState"; import utils from "common/utils"; import Icon from "../Icon/Icon"; import LinkToAccountById from "../Utility/LinkToAccountById"; import pu from "common/permission_utils"; import { cloneDeep } from "lodash"; import { ChainStore } from "cybexjs"; class AccountPermissionTree extends React.Component { static propTypes = { account: ChainTypes.ChainAccount.isRequired, accounts: ChainTypes.ChainAccountsList, indent: PropTypes.number.isRequired }; static defaultProps = { indent: 0 }; render() { let { account, available, availableKeys, permission, threshold } = this.props; let isOK = permission.isAvailable(available); let isNested = permission.isNested(); let isMultiSig = permission.isMultiSig(); let status = []; let notNestedWeight = threshold && threshold > 10 ? utils.get_percentage(permission.weight, this.props.threshold) : permission.weight; let nestedWeight = permission && permission.threshold > 10 ? `${utils.get_percentage( permission.getStatus(available, availableKeys), permission.threshold )} / 100%` : `${permission.getStatus(available, availableKeys)} / ${ permission.threshold }`; // if (!account || typeof account === "string") return null; status.push( <div key={account.get("id")} style={{ textAlign: "left", width: "100%", clear: "both", paddingBottom: 5 }} > <div className="inline-block" style={{ paddingLeft: `${5 * this.props.indent}%` }} > <LinkToAccountById subpage="permissions" account={account.get("id")} /> {!isNested && notNestedWeight ? `${ notNestedWeight && notNestedWeight.length === 2 ? "\u00A0\u00A0" : "" }(${notNestedWeight}) ` : null} </div> <div className="float-right" style={{ paddingLeft: 20, marginRight: 10 }} > {!isNested && !isMultiSig ? ( <span> {isOK ? ( <Icon name="checkmark-circle" size="1x" className="success" /> ) : ( <Icon name="cross-circle" size="1x" className="error" /> )} </span> ) : ( <span className={isOK ? "success-text" : ""}>{nestedWeight}</span> )} </div> </div> ); if (isNested || isMultiSig) { permission.accounts.forEach(subAccount => { status.push( <BoundAccountPermissionTree key={subAccount.id} indent={this.props.indent + 1} account={subAccount.id} accounts={subAccount.accounts} permission={subAccount} available={available} availableKeys={availableKeys} threshold={permission.threshold} /> ); }); if (permission.keys.length) { permission.keys.forEach(key => { status.push( <KeyPermissionBranch key={key.id} permission={key} available={availableKeys} indent={this.props.indent + 1} /> ); }); } } return <div>{status}</div>; } } const BoundAccountPermissionTree = BindToChainState(AccountPermissionTree); class KeyPermissionBranch extends React.Component { static propTypes = { indent: PropTypes.number.isRequired }; static defaultProps = { indent: 0 }; render() { let { available, permission } = this.props; let isOK = permission.isAvailable(available); let status = []; status.push( <div key={permission.id} style={{ textAlign: "left", width: "100%", paddingBottom: 5 }} > <div className="inline-block" style={{ paddingLeft: `${5 * this.props.indent}%` }} > <span> {permission.id.substr(0, 20 - 4 * this.props.indent)}... ({ permission.weight }) </span> </div> <div className="float-right" style={{ paddingLeft: 20, marginRight: 10 }} > <span> {isOK ? ( <Icon name="checkmark-circle" size="1x" className="success" /> ) : ( <Icon name="cross-circle" size="1x" className="error" /> )} </span> </div> </div> ); return <div>{status}</div>; } } class SecondLevel extends React.Component { render() { let { requiredPermissions, available, availableKeys, type } = this.props; let status = []; requiredPermissions.forEach(account => { status.push( <BoundAccountPermissionTree key={account.id} account={account.id} accounts={account.accounts} permission={account} available={available} availableKeys={availableKeys} /> ); }); return <div>{status}</div>; } } class FirstLevel extends React.Component { static propTypes = { required: ChainTypes.ChainAccountsList, available: ChainTypes.ChainAccountsList }; static defaultProps = { type: "active", added: null, removed: null }; constructor() { super(); this.state = { requiredPermissions: [] }; this._updateState = this._updateState.bind(this); } componentWillMount() { this._updateState(); ChainStore.subscribe(this._updateState); } componentWillUnmount() { ChainStore.unsubscribe(this._updateState); } _updateState() { let required = pu.listToIDs(this.props.required); let available = pu.listToIDs(this.props.available); this.setState({ requiredPermissions: pu.unnest(required, this.props.type), required, available }); } render() { let { type, proposal, added, removed, availableKeys } = this.props; let { requiredPermissions, required, available } = this.state; available = cloneDeep(available); availableKeys = availableKeys.toJS(); if (added) { available.push(added); availableKeys.push(added); } if (removed) { if (available.indexOf(removed) !== -1) { available.splice(available.indexOf(removed), 1); } if (availableKeys.indexOf(removed) !== -1) { availableKeys.splice(availableKeys.indexOf(removed), 1); } } return ( <SecondLevel type={type} added={added} removed={removed} required={required} available={available} availableKeys={availableKeys} requiredPermissions={requiredPermissions} /> ); } } FirstLevel = BindToChainState(FirstLevel, { keep_updating: true }); class ProposalWrapper extends React.Component { static propTypes = { proposal: ChainTypes.ChainObject.isRequired, type: PropTypes.string.isRequired }; static defaultProps = { type: "active", added: null }; render() { let { proposal, type } = this.props; let available = proposal.get(`available_${type}_approvals`); let availableKeys = proposal.get("available_key_approvals"); let required = proposal.get(`required_${type}_approvals`); return ( <FirstLevel {...this.props} required={required} available={available} availableKeys={availableKeys} /> ); } } export default BindToChainState(ProposalWrapper, { keep_updating: true }); <file_sep>```html <Accordion autoOpen={false} multiOpen={true}> <Accordion.Item title='First item title'> First item content </Accordion.Item> <Accordion.Item title='Second item title'> Second item content </Accordion.Item> <Accordion.Item title='Third item title'> Third item content </Accordion.Item> </Accordion> ```<file_sep>import counterpart from "counterpart"; const ERROR_MAP = { is_lifetime_member: "is_lifetime_member", is_authorized_asset: "is_authorized_asset", is_market_issued: "is_market_issued", unknown_error: "unknown_error", insufficient_balance: "insufficient_balance", faucet_is_out_of_money: "faucet_is_out_of_money", incorrect_verify_code: "incorrect_verify_code", only_one_account: "only_one_account", max_supply: "max_supply", }; const ERROR_LIST = Object.getOwnPropertyNames(ERROR_MAP); const findKey = (str: string) => { for (let key of ERROR_LIST) { if (str.indexOf(key) !== -1) return key; } return null; }; export const getErrorTrans: (errStr: string | undefined) => string = errStr => !errStr ? null : findKey(errStr.toLowerCase().replace(/\s/g, "_")); export const getErrorTranslated: (errStr: string | undefined) => string = errStr => { let key = getErrorTrans(errStr); return key ? counterpart.translate("error_details." + key) : key; } <file_sep>Here are some files that in case of that you want to develop with sims of ssl.<file_sep>import { Set, Map } from "immutable"; import alt from "alt-instance"; import { AbstractStore } from "./AbstractStore"; import { debugGen } from "utils//Utils"; import { Apis } from "cybexjs-ws"; import * as assert from "assert"; import { ChainValidation } from "cybexjs"; type CommonType = { [property: string]: any; }; type Asset = { precision: number; symbol: string; id: string; } & CommonType; interface ChainData { assets: Map<string, Asset>; } class ChainStore extends AbstractStore<ChainData> { state = { assets: Map<string, Asset>() }; constructor(props) { super(); this.bindListeners({}); this._export(["getAsset"]) } async getAssets(idsOrSymbols: string[]) { assert(idsOrSymbols && idsOrSymbols.length); let assets = ChainValidation.is_object_id(idsOrSymbols[0]) ? await Promise.all(idsOrSymbols.map(id => this.getObject(id))) : await Apis.instance() .db_api() .exec("lookup_asset_symbols", [idsOrSymbols]); return assets; } async getAsset(idOrSymbol: string) { assert(idOrSymbol); let asset: Asset = this.state.assets.get(idOrSymbol, null); if (!asset) { asset = ChainValidation.is_object_id(idOrSymbol) ? await this.getObject(idOrSymbol) : (await this.getAssets([idOrSymbol]))[0]; this.setState({ assets: this.state.assets.set(asset.symbol, asset).set(asset.id, asset) }); } return asset; } async getObject(id: string) { assert(id && ChainValidation.is_object_id(id)); return await this.getObjects([id])[0]; } async getObjects(ids: string[]) { assert(ids && ids.length && ChainValidation.is_object_id(ids[0])); return await Apis.instance() .db_api() .exec("get_objects", [ids]); } } const StoreWrapper = alt.createStore(ChainStore, "ChainStore") as ChainStore; export { StoreWrapper as ChainStore }; export default StoreWrapper; <file_sep>```html <Trigger close='id-of-target'> <a className='button'>Close Target</a> <Trigger> ``` Id need not be passed to close if close trigger is used inside a target component. ```html <Modal id='modal-id'> <Trigger close=''> <a className='button'>Close Target</a> <Trigger> <p>Modal content</p> </Modal> ```<file_sep>import * as PropTypes from "prop-types"; import * as React from "react"; export default function(flux) { return function(Component) { return class extends React.Component { static childContextTypes = { flux: PropTypes.object }; getChildContext() { return { flux: flux }; } render() { return React.createElement(Component, this.props); } }; }; } <file_sep>/// < reference types="node" /> declare module "types" { // Some common types type PublicKeys = { [x: string]: string | string[] }; type PublicKeysToCheck = { [x: string]: [string, number][] }; type TransferObject = { from_account: string, to_account: string, amount: number, asset: string, memo?: string }; }<file_sep>```html <Trigger open="fixed-panel"> <a className="button">Fixed Panel</a> </Trigger> <Panel id="fixed-panel" className="panel-fixed"> <Trigger close=""> <a className="close-button">&times;</a> </Trigger> <p>Fixed Panel content</p> </Panel> ```<file_sep>import Loadable from "react-loadable"; import LoadingIndicator from "components/LoadingIndicator"; import { Route, Switch } from "react-router-dom"; export const LoadComponent = (uri: string) => Loadable({ loader: () => import(uri), loading: LoadingIndicator }); <file_sep>declare var __DEV__; import { flattenDeep } from "lodash"; import { getHexColorByString } from "./ColorUtils"; const getExtension = (extensions, field) => { for (let options of flattenDeep(extensions).filter(o => typeof o === "object")) { if (options[field]) { return options[field]; } } return null; } const getObjectExtensionField = (object: any, field: string) => { if (!object || !object.extensions) { return null; } else { return getExtension(object.extensions, field); } } const debugGen: (logTag: string, colorRgba?: string) => (...toPrint) => void = (logTag, colorRgba = `#${getHexColorByString(logTag)}`) => __DEV__ ? (...toPrint) => console.debug(`%c[${logTag}]:`, `color: ${colorRgba};`, ...toPrint) : () => void (0); export { debugGen, getExtension, getObjectExtensionField };<file_sep>[Witnesses](introduction/witness) are the block producers of Cybex. They validate transactions and ensure the safety of the network. You may vote for as many witnesses as you'd like, and they will all receive the same amount of votes. Witness proposals can be found here: [Cybextalk - Stakeholder Proposals Board](https://Cybextalk.org/index.php/board,75.0.html). <file_sep>import alt from "alt-instance"; import { LockCActions } from "actions/LockCActions"; import { debugGen } from "utils//Utils"; import AccountActions from "actions/AccountActions"; import ls from "lib/common/localStorage"; import { AbstractStore } from "./AbstractStore"; import { LockC, LockCProject } from "services/lockC"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("LockCStore"); export type LockCState = LockC.LockCInfo & { loading: number; }; class LockCStore extends AbstractStore<LockCState> { state: LockCState = { state: LockC.LockCPersonalState.Uninit, info: null, sum: 0, loading: 0 }; constructor() { super(); this.bindListeners({ reset: AccountActions.setCurrentAccount, handleAddLoading: LockCActions.addLoading, handleRemoveLoading: LockCActions.removeLoading, handleInfoUpdate: LockCActions.queryInfo }); } reset() { this.setState({ state: LockC.LockCPersonalState.Uninit, info: null, sum: 0, loading: 0, userProjectStatus: {}, projects: [] }); } handleAddLoading(count) { this.setState({ loading: 1 }); } handleRemoveLoading(count) { this.setState({ loading: 0 }); } handleInfoUpdate(info: LockC.LockCInfo) { console.debug("Personal Info: ", info); this.setState({ ...(this as any).getInstance().getState(), ...info }); } } const StoreWrapper = alt.createStore(LockCStore, "LockCStore"); export { StoreWrapper as LockCStore }; export default StoreWrapper; <file_sep>账户权限设定谁可以控制本账户。控制人(账户名或公钥)可修改账户相关的各种设置,包括权限设置。 参见 [权限](accounts/permissions) 了解更多信息。 **如果您的账户中有锁定期资产,请务必谨慎删除您的相关有效公钥。锁定期资产与特定公钥相关联,一旦您移除了锁定期资产关联的公钥,您的锁定期资产将无发申领。如果您不能确定锁定期资产所关联的公钥,请解锁您的账户并在锁定期资产页面查看对应公钥**<file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import { FormattedDate } from "react-intl"; import FormattedAsset from "../Utility/FormattedAsset"; // import Ps from "perfect-scrollbar"; import utils from "common/utils"; import Translate from "react-translate-component"; import AssetName from "../Utility/AssetName"; import TimeAgo from "../Utility/TimeAgo"; class TableHeader extends React.Component { render() { let { baseSymbol, quoteSymbol } = this.props; return ( <thead> <tr> <th style={{ textAlign: "center" }}> <Translate content="exchange.price" />&nbsp;{baseSymbol ? ( <span className="header-sub-title"> (<AssetName name={baseSymbol} />/<AssetName name={quoteSymbol} />) </span> ) : null} </th> <th style={{ textAlign: "center" }}> <Translate content="transfer.amount" />&nbsp;{quoteSymbol ? ( <span className="header-sub-title"> (<AssetName name={quoteSymbol} />) </span> ) : null} </th> <th style={{ textAlign: "center" }}> <Translate content="transaction.settlement_date" />&nbsp;<span style={{ visibility: "hidden" }} className="header-sub-title" > d </span> </th> </tr> </thead> ); } } TableHeader.defaultProps = { quoteSymbol: null, baseSymbol: null }; class SettleOrderRow extends React.Component { // shouldComponentUpdate(nextProps) { // return ( // nextProps.order.for_sale !== this.props.order.for_sale || // nextProps.order.id !== this.props.order.id // ); // } render() { let { quote, order, showSymbols } = this.props; let amountSymbol = showSymbols ? " " + quote.get("symbol") : null; return ( <tr> <td> {utils.format_number(order.getPrice(), quote.get("precision"))}{" "} {amountSymbol} </td> <td> <FormattedAsset amount={order[ !order.isBid() ? "amountForSale" : "amountToReceive" ]().getAmount()} asset={ order[!order.isBid() ? "amountForSale" : "amountToReceive"]() .asset_id } /> </td> <td> <TimeAgo time={order.settlement_date} /> </td> </tr> ); } } SettleOrderRow.defaultProps = { showSymbols: false, invert: false }; class OpenSettleOrders extends React.Component { shouldComponentUpdate(nextProps) { return ( nextProps.currentAccount !== this.props.currentAccount || nextProps.orders !== this.props.orders ); } // componentDidMount() { // let orderContainer = this.refs.orders; // Ps.initialize(orderContainer); // } render() { let { orders, base, quote, quoteSymbol, baseSymbol } = this.props; let activeOrders = null; if (orders.size > 0 && base && quote) { let index = 0; activeOrders = orders .sort((a, b) => { return a.isBefore(b) ? -1 : 1; }) .map(order => { return ( <SettleOrderRow key={index++} order={order} base={base} quote={quote} /> ); }) .toArray(); } else { return null; } return ( <div key="open_orders" className="grid-block no-overflow small-12 no-padding vertical medium-horizontal middle-content" > <div className="small-12 order-1" style={{ paddingBottom: "1rem" }}> <div className="exchange-bordered"> {this.props.withHeader && ( <div className="exchange-content-header"> <Translate content="exchange.settle_orders" /> </div> )} <div className="grid-block" style={{ maxHeight: "400px", overflow: "hidden" }} ref="orders" > <table className="table order-table text-right table-hover"> <TableHeader type="buy" baseSymbol={baseSymbol} quoteSymbol={quoteSymbol} /> <tbody ref="orders">{activeOrders}</tbody> </table> </div> </div> </div> </div> ); } } OpenSettleOrders.defaultProps = { base: {}, quote: {}, orders: {}, quoteSymbol: "", baseSymbol: "" }; OpenSettleOrders.propTypes = { base: PropTypes.object.isRequired, quote: PropTypes.object.isRequired, orders: PropTypes.object.isRequired, quoteSymbol: PropTypes.string.isRequired, baseSymbol: PropTypes.string.isRequired }; export default OpenSettleOrders; <file_sep># This script clones an existing gh-pages repository and pushes updates # from the newly compiled version into github. # The GITHUB_TOKEN for authentication is stored in the encrypted # variable in .travis.yml # Clone Repo ############ #echo "Cloning wallet repo" unamestr=`uname` echo $unamestr echo $TRAVIS_TAG if [[ "$unamestr" == 'Linux' && -n $TRAVIS_TAG ]] then ## bitshares.github.io (bitshares.org main site) git clone https://github.com:${GITHUB_TOKEN}@github.com/${ORGANIZATION_REPO} $TRAVIS_BUILD_DIR/bitshares.org # Copy new compile files ######################## #echo "Copying compiled files over to repo" #ls -al $TRAVIS_BUILD_DIR/web/dist/ #ls -al /gh-pages/ rm -rf $TRAVIS_BUILD_DIR/bitshares.org/wallet/* cp -Rv $TRAVIS_BUILD_DIR/build/hash-history_wallet/* $TRAVIS_BUILD_DIR/bitshares.org/wallet/ # Commit Changes ################ echo "Pushing new wallet folder" cd $TRAVIS_BUILD_DIR/bitshares.org #git config user.email "<EMAIL>" #git config user.name "BitShares Wallet Build Automation" git add -A git commit -a -m "Update wallet by Travis: v$TRAVIS_TAG" git push ## wallet.bitshares.org subdomain (independent repo) echo "Pushing new wallet subdomain repo" git clone https://github.com:${GITHUB_TOKEN}@github.com/${WALLET_REPO} $TRAVIS_BUILD_DIR/wallet.bitshares.org cd $TRAVIS_BUILD_DIR/wallet.bitshares.org git checkout gh-pages rm -rf ./* git checkout ./CNAME cp -Rv $TRAVIS_BUILD_DIR/build/hash-history_/* . git add -A git commit -a -m "Update wallet by Travis: v$TRAVIS_TAG" git push fi <file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var SimpleModal = require("./simple"); var AdvancedModal = require("./advanced"); var ModalDocs = React.createClass({ render: function() { return ( <div className="grid-content"> <h2>Modal</h2> <h4 className="subheader"> Modal allows you to create dialogs or pop-up windows that focuses the user on the content. </h4> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="small-8 grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./simple.md")} </Highlight> </div> <div className="grid-content"> <SimpleModal /> </div> </div> <hr /> <h3>Advanced</h3> <div className="grid-block"> <div className="small-8 grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./advanced.md")} </Highlight> </div> <div className="grid-content"> <AdvancedModal /> </div> </div> </div> ); } }); module.exports = ModalDocs; <file_sep>export type MarketColor = { color: string; bgColor: string; }; type ColorProfile = MarketColor; export function getHexColorByString(colorString: string) { let string = ["R", "G", "B"] .map(c => addZero(getColorIndex(c + colorString, 196).toString(16))) .join(""); return string; } export function addZero(str: string) { return str.length === 1 ? "0" + str : str; } /** * * * @export * @param {string} colorString The string used to calc the color index; * @param {number} radix Commonly it's the length of the array of colors; * @returns {number} */ export function getColorIndex(colorString: string, radix: number): number { return Array .prototype .map .call(colorString, s => s.codePointAt(0)) .map(num => parseInt(num, 16)) .reduce((sum, next) => sum + next) % radix; } /** * * * @export * @param {ColorProfile[]} colorList * @returns {(marketId: string) => ColorProfile} A generator */ export function getColorGenerator(colorList: ColorProfile[]): (marketId: string) => ColorProfile { return marketId => colorList[getColorIndex(marketId, colorList.length)]; } export default getColorGenerator;<file_sep>Contributing ============ Graphene-UI is open source and anyone is free to contribute. PR's are welcomed and will be reviewed in a timely manner, and long-term contributors will be given access to the repo. If you would like to get involved, we have a Slack channel where you can ask questions and get help. Development process ------------------- - Bugs are always worked before enhancements - Developers should work each issue according to a numbered branch corresponding to the issue using ``git checkout -b 123`` Github issues are being used to track bugs and feature requests. - Project Coordinator (@wmbutler) reads through new issues and requests clarification if needed - Issues get assigned to Milestones - Milestones are typically 1 week long ending on Wednesday - All devs are expected to install `Zenhub <https://zenhub.io>`_. Zenhub creates viewable pipelines and allows for issue estimation. Estimates are based on anticipated hours to complete. Categorization of issues ~~~~~~~~~~~~~~~~~~~~~~~~ - **New issues** have not been categorized yet or are tagged as question when seeking clarification. - **Backlog issues** have been assigned to a Milestone and are waiting for a dev to estimate and claim. - **In Progress issues** are being actively worked on. - **Testing issues** are waiting for independent tests. (Methodology fully defined as of yet, so devs test their own work for now) - **Closed issues** are complete Milestones ---------- - Project Coordinator announces the number of issues and requests them to be claimed and estimated - Presents a burndown chart for the week Sunday ~~~~~~ - Project Coordinator summarizes progress with burndown chart - Ensures that all items are claimed and estimated - Escalates to @valzav for unestimated and/or unclaimed items Wednesday ~~~~~~~~~ - Testing is completed - Release notes completed by @valzav - Project Coordinator announces release on Cybextalk and provides link to release notes Thursday ~~~~~~~~ - Incomplete items are moved to new Milestone - Old Milestone is closed - New Milestone is activated (rinse lather repeat) Coding style guideline ---------------------- Our style guideline is based on `Airbnb JavaScript Style Guide <https://github.com/airbnb/javascript>`_, with few exceptions: - Strings are double quoted - Additional trailing comma (in arrays and objects declaration) is optional - 4 spaces tabs - Spaces inside curly braces are optional We strongly encourage to use _eslint_ to make sure the code adhere to our style guidelines. To install eslint and its dependencies, run:: npm install -g eslint-config-airbnb eslint-plugin-react eslint babel-eslint Testing ------- Jest currently doesn't work with node (see `<https://github.com/facebook/jest/issues/243>`_), so in order to run the tests you need to install iojs. Under Ubuntu instructions can be found here: `Nodesource <https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories>`_ Ubuntu io.js installation. In order for jest to correctly follow paths it is necessary to add a local path to your NODE_PATH variable. Under Ubuntu, you can do so by running the following from the web directory:: export NODE_PATH=$NODE_PATH:. Tests are then run using:: npm test <file_sep># DEX去中心化交易所简介 Cybex 去中心化交易所(简称*DEX*)允许用户在Cybex系统中直接进行数字商品的交易。 去中心化交易所相对于传统的中心化交易所拥有很多优势,文档中对其中一些特性进行简单介绍。Cybex DEX拥有的众多特性,用户可以根据自身需求来选择利用全部或者部分功能。 * **权力分离**: 由同一个实体来发行资产(IOU)和处理订单是不合理,也是不必要的。在Cybex系统中,订单撮合是由网络协议执行,并不关心相关资产的内涵。 * **全球整合的买卖盘**: 全世界任何人只要能访问互联网就能访问Cybex,并使用DEX进行交易。这使得全球的流动性汇聚到同一个去中心化的买卖盘市场。 * **交易几乎任何标的**: Cybex DEX可交易的资产是不受限的。你可以交易**任何**交易对。尽管有些交易对市场深度可能很低,比如白银:黄金(SILVER:GOLD),而有些交易对则会非常活跃,交易量很大,比如外汇交易美元:欧元(USD:EUR)。 * **乐趣无限**: Cybex协议将无法限制你的交易体验。 * **去中心化**: DEX在全球都是去中心化的。这不仅意味着不存在单点失败,而且Cybex交易所全年无休,7/24开放交易,因为任何时间,在世界上总有一个地方是白天交易时间。 * **安全性**: 你的资金和交易订单都由工业级别的椭圆曲线加密算法进行加密保护。没有人能够在未经你许可的情况下访问这些信息。我们还为用户提供了担保和多重签名机制进一步提高安全性。 * **快捷**: 与其他去中心化网络相比,Cybex DEX可以实现实时交易,速度仅受制于光速和地球的大小。 * **可自证的订单撮合算法**: 使Cybex DEX独一无二的是可自证的订单撮合算法。给定的一组交易订单,你总是可以验证这些订单是被正确的撮合,而不存在欺诈。 * **抵押担保的智能资产(Smartcoins)**: Cybex一个最重要的特性是*智能资产(smartcoins)*,比如比特美元(bitUSD)、比特欧元(bitEUR)、比特人民币(bitCNY)等等。为了方便起见,系统中这些资产直接已美元(USD),欧元(EUR),人民币(CNY)表示。这些数字资产代表其对应物理货币的价值。钱包中的1比特美元等价于$1,可自由兑换。这些数字资产由Cybex公司股份(CYB)冻结抵押进行担保,并可按市价进行清算。 <file_sep>import BaseStore from "./BaseStore"; import { List, Set, Map, fromJS } from "immutable"; import alt from "alt-instance"; import { Store } from "alt-instance"; import { HtlcActions } from "actions/HtlcActions"; import { debugGen } from "utils//Utils"; import AccountActions from "actions/AccountActions"; import ls from "lib/common/localStorage"; import { AbstractStore } from "./AbstractStore"; import { Htlc } from "../services/htlc"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("HtlcStore"); export type HtlcState = { records: { [id: string]: Htlc.HtlcRecord[] }; }; class HtlcStore extends AbstractStore<HtlcState> { state: HtlcState = { records: [] as any }; constructor() { super(); this.bindListeners({ handleRecordUpdate: HtlcActions.updateHtlcRecords }); } handleRecordUpdate({ accountID, records }) { this.setState({ records: { ...this.state.records, [accountID]: records } }); } } const StoreWrapper = alt.createStore(HtlcStore, "HtlcStore"); export { StoreWrapper as HtlcStore }; export default StoreWrapper; <file_sep>import * as React from "react"; import { Link } from "react-router-dom"; import { connect } from "alt-react"; import WalletActions from "actions/WalletActions"; import BackupActions from "actions/BackupActions"; import WalletManagerStore from "stores/WalletManagerStore"; import Translate from "react-translate-component"; import cname from "classnames"; import counterpart from "counterpart"; import { withRouter } from "react-router-dom"; import "./WalletManager.scss"; const connectObject = { listenTo() { return [WalletManagerStore]; }, getProps() { return WalletManagerStore.getState(); } }; class WalletManager extends React.Component { getTitle() { switch (this.props.location.pathname) { case "/wallet/create": return "wallet.create_wallet"; break; case "/wallet/backup/create": return "wallet.create_backup"; break; case "/wallet/backup/restore": return "wallet.restore_backup"; break; case "/wallet/backup/brainkey": return "wallet.backup_brainkey"; break; case "/wallet/delete": return "wallet.delete_wallet"; break; case "/wallet/change-password": return "wallet.change_password"; break; case "/wallet/import-keys": return "wallet.import_keys"; break; default: return "wallet.console"; break; } } _renderCancel = () => { if (this.props.location.pathname === "/wallet") { return null; } return ( <a href="javascripts:;" onClick={() => window.history.back()} style={{ position: "absolute", right: 0, top: "50%" }} > <Translate content="transfer.back" /> </a> ); }; render() { return ( <div className="grid-block vertical"> <div className="grid-container" style={{ maxWidth: "40rem" }}> <div className="content-block center-content"> <div className="page-header" style={{ position: "relative" }}> <Translate component="h3" content={this.getTitle()} /> {this._renderCancel()} </div> <div className="content-block">{this.props.children}</div> </div> </div> </div> ); } } WalletManager = connect( WalletManager, connectObject ); WalletManager = withRouter(WalletManager); class WalletOptions extends React.Component { render() { let has_wallet = !!this.props.current_wallet; let has_wallets = this.props.wallet_names.size > 1; let current_wallet = this.props.current_wallet ? this.props.current_wallet.toUpperCase() : ""; return ( <div className="wallet-options"> <div className="grid-block"> <div className="grid-content"> <div className="card"> <div className="card-content"> <label> <Translate content="wallet.active_wallet" />: </label> <div>{current_wallet}</div> <br /> {has_wallets ? ( <Link to="/wallet/change" className="button outline success"> <Translate content="wallet.change_wallet" /> </Link> ) : null} </div> </div> </div> <div className="grid-content"> <div className="card"> <div className="card-content"> <label> <Translate content="wallet.import_keys_tool" /> </label> {/* <div style={{ visibility: "hidden" }}>Dummy</div> */} {/* <br /> */} {has_wallet ? ( <Link to="/wallet/import-keys"> <div className="button outline success readable container"> <Translate content="wallet.import_keys" /> </div> </Link> ) : null} </div> </div> </div> {has_wallet ? ( <div className="grid-content"> <div className="card"> <div className="card-content"> <label> <Translate content="wallet.balance_claims" /> </label> {/* <div style={{ visibility: "hidden" }}>Dummy</div> */} {/* <br /> */} <Link to="wallet/balance-claims"> <div className="button outline success readable container"> <Translate content="wallet.balance_claim_lookup" /> </div> </Link> {/*<BalanceClaimByAsset> <br/> <div className="button outline success"> <Translate content="wallet.balance_claims" /></div> </BalanceClaimByAsset> */} </div> </div> </div> ) : null} </div> <div className="backup-links"> {has_wallet ? ( <Link to="wallet/backup/create" className="button outline success"> <Translate content="wallet.create_backup" /> </Link> ) : null} {has_wallet ? ( <Link to="wallet/backup/brainkey" className="button outline success" > <Translate content="wallet.backup_brainkey" /> </Link> ) : null} <Link to="wallet/backup/restore" className="button outline success"> <Translate content="wallet.restore_backup" /> </Link> <Link to="wallet/create" className="button outline success"> <Translate content="wallet.new_wallet" /> </Link> {has_wallet ? ( <Link to="wallet/delete" className="button outline success"> <Translate content="wallet.delete_wallet" /> </Link> ) : null} {has_wallet ? ( <Link to="wallet/change-password" className="button outline success" > <Translate content="wallet.change_password" /> </Link> ) : null} </div> </div> ); } } WalletOptions = connect( WalletOptions, connectObject ); class ChangeActiveWallet extends React.Component { constructor() { super(); this.state = {}; } componentWillMount() { let current_wallet = this.props.current_wallet; this.setState({ current_wallet }); } componentWillReceiveProps(np) { if (np.current_wallet !== this.state.current_wallet) { this.setState({ current_wallet: np.current_wallet }); } } render() { let state = WalletManagerStore.getState(); let options = []; state.wallet_names.forEach(wallet_name => { options.push( <option key={wallet_name} value={wallet_name}> {wallet_name.toLowerCase()} </option> ); }); let is_dirty = this.state.current_wallet !== this.props.current_wallet; return ( <div> <section className="block-list"> <header> <Translate content="wallet.active_wallet" />: </header> <ul> <li className="with-dropdown"> {state.wallet_names.count() <= 1 ? ( <div style={{ paddingLeft: 10 }}> {this.state.current_wallet} </div> ) : ( <select value={this.state.current_wallet} onChange={this.onChange.bind(this)} > {options} </select> )} </li> </ul> </section> <Link to="wallet/create"> <div className="button outline"> <Translate content="wallet.new_wallet" /> </div> </Link> {is_dirty ? ( <div className="button outline" onClick={this.onConfirm.bind(this)}> <Translate content="wallet.change" name={this.state.current_wallet} /> </div> ) : null} </div> ); } onConfirm() { WalletActions.setWallet(this.state.current_wallet); BackupActions.reset(); // if (window.electron) { // window.location.hash = ""; // window.remote.getCurrentWindow().reload(); // } // else window.location.href = "/"; } onChange(event) { let current_wallet = event.target.value; this.setState({ current_wallet }); } } ChangeActiveWallet = connect( ChangeActiveWallet, connectObject ); class WalletDelete extends React.Component { constructor() { super(); this.state = { selected_wallet: null, confirm: 0 }; } _onCancel() { this.setState({ confirm: 0, selected_wallet: null }); } render() { if (this.state.confirm === 1) { return ( <div style={{ paddingTop: 20 }}> <h4> <Translate content="wallet.delete_confirm_line1" /> </h4> <Translate component="p" content="wallet.delete_confirm_line3" /> <br /> <div className="button outline" onClick={this.onConfirm2.bind(this)}> <Translate content="wallet.delete_confirm_line4" name={this.state.selected_wallet} /> </div> <div className="button outline" onClick={this._onCancel.bind(this)}> <Translate content="wallet.cancel" /> </div> </div> ); } // this.props.current_wallet // let placeholder = <option key="placeholder" value="" disabled={this.props.wallet_names.size > 1}></option> // if (this.props.wallet_names.size > 1) { // placeholder = <option value="" disabled>{placeholder}</option>; // } // else { // //When disabled and list_size was 1, chrome was skipping the // //placeholder and selecting the 1st item automatically (not shown) // placeholder = <option value="">{placeholder}</option>; // } let options = []; // let options = [placeholder] options.push( <option key="select_option" value=""> {counterpart.translate("settings.delete_select")}&hellip; </option> ); this.props.wallet_names.forEach(wallet_name => { options.push( <option key={wallet_name} value={wallet_name}> {wallet_name.toLowerCase()} </option> ); }); let is_dirty = !!this.state.selected_wallet; return ( <div style={{ paddingTop: 20 }}> <section className="block-list"> <header> <Translate content="wallet.delete_wallet" /> </header> <ul> <li className="with-dropdown"> <select value={this.state.selected_wallet || ""} style={{ margin: "0 auto" }} onChange={this.onChange.bind(this)} > {options} </select> </li> </ul> </section> <div className={cname("button outline", { disabled: !is_dirty })} onClick={this.onConfirm.bind(this)} > <Translate content={ this.state.selected_wallet ? "wallet.delete_wallet_name" : "wallet.delete_wallet" } name={this.state.selected_wallet} /> </div> </div> ); } onConfirm() { this.setState({ confirm: 1 }); } onConfirm2() { WalletActions.deleteWallet(this.state.selected_wallet); if (this.props.afterDelete) { this.props.afterDelete(this.state.selected_wallet); } this._onCancel(); // window.history.back() } onChange(event) { let selected_wallet = event.target.value; this.setState({ selected_wallet }); } } WalletDelete = connect( WalletDelete, connectObject ); import WalletChangePassword from "components/Wallet/WalletChangePassword"; import ImportKeys from "components/Wallet/ImportKeys"; import Brainkey from "components/Wallet/Brainkey"; import { WalletCreate } from "components/Wallet/WalletCreate"; import { BalanceClaimActive } from "components/Wallet/BalanceClaimActive"; import Backup from "components/Wallet/Backup"; import { Switch, Route } from "react-router-dom"; export const WalletWrapper = () => ( <WalletManager style={{ margin: "1em auto" }}> <Switch> <Route path="/wallet/" exact component={WalletOptions} /> <Route path="/wallet/change" component={ChangeActiveWallet} /> <Route path="/wallet/change-password" component={WalletChangePassword} /> <Route path="/wallet/import-keys" component={ImportKeys} /> <Route path="/wallet/balance-claims" component={BalanceClaimActive} /> <Route path="/wallet/brainkey" component={Brainkey} /> <Route path="/wallet/create" component={WalletCreate} /> <Route path="/wallet/delete" component={WalletDelete} /> <Route path="/wallet/backup" component={Backup} /> </Switch> </WalletManager> ); export default WalletWrapper; export { WalletManager, WalletOptions, ChangeActiveWallet, WalletDelete }; <file_sep>Active permissions define the accounts that have permission to spend funds for this account. They can be used to easily setup a multi-signature scheme, see [permissions](accounts/permissions) for more details. **If you have vesting/lockup balances, please make sure that the don't remove the permission which the balances belong to. If you remove the public connecting with a vesting/lockup balance, you'll not be able to claim that balance by any means.**<file_sep>var helpers = require("./mq-helpers"); var foundationApi = require("./foundation-api"); var assign = require("object-assign"); function throttleUtil(func, delay) { var timer = null; return function() { var context = this, args = arguments; if (timer === null) { timer = setTimeout(function() { func.apply(context, args); timer = null; }, delay); } }; } function init() { var mediaQueries; var extractedMedia; var mediaObject; var namedQueries = { default: "only screen", landscape: "only screen and (orientation: landscape)", portrait: "only screen and (orientation: portrait)", retina: "only screen and (-webkit-min-device-pixel-ratio: 2)," + "only screen and (min--moz-device-pixel-ratio: 2)," + "only screen and (-o-min-device-pixel-ratio: 2/1)," + "only screen and (min-device-pixel-ratio: 2)," + "only screen and (min-resolution: 192dpi)," + "only screen and (min-resolution: 2dppx)" }; helpers.headerHelper(["foundation-mq"]); extractedMedia = helpers.getStyle(".foundation-mq", "font-family"); mediaQueries = helpers.parseStyleToObject(extractedMedia); for (var key in mediaQueries) { mediaQueries[key] = "only screen and (min-width: " + mediaQueries[key].replace("rem", "em") + ")"; } foundationApi.modifySettings({ mediaQueries: assign(mediaQueries, namedQueries) }); window.addEventListener( "resize", throttleUtil(function() { foundationApi.publish("resize", "window resized"); }, 50) ); } module.exports = init; <file_sep>var React = require("react"); var ReactDOM = require("react-dom"); var foundationApi = require("../utils/foundation-api"); var PopupToggle = require("../popup/toggle"); var Trigger = React.createClass({ getDefaultProps: function() { return { open: null, close: null, toggle: null, hardToggle: null, popupToggle: null, notify: null }; }, getCloseId: function() { if (this.props.close) { return this.props.close; } else { var parentElement = false; var tempElement = ReactDOM.findDOMNode(this).parentNode; while (parentElement === false) { if (tempElement.nodeName == "BODY") { parentElement = ""; } if ( typeof tempElement.getAttribute("data-closable") !== "undefined" && tempElement.getAttribute("data-closable") !== false ) { parentElement = tempElement; } tempElement = tempElement.parentNode; } return parentElement.getAttribute("id"); } }, clickHandler: function(e) { e.preventDefault(); if (this.props.open) { foundationApi.publish(this.props.open, "open"); } else if (this.props.close !== null) { foundationApi.publish(this.getCloseId(), "close"); } else if (this.props.toggle) { foundationApi.publish(this.props.toggle, "toggle"); } else if (this.props.hardToggle) { foundationApi.closeActiveElements({ exclude: this.props.hardToggle }); foundationApi.publish(this.props.hardToggle, "toggle"); } else if (this.props.notify) { foundationApi.publish(this.props.notify, { title: this.props.title, content: this.props.content, position: this.props.position, color: this.props.color, image: this.props.image }); } }, render: function() { if (this.props.popupToggle) { return <PopupToggle {...this.props} />; } else { var child = React.Children.only(this.props.children); return React.cloneElement(child, { onClick: this.clickHandler }); } } }); export default Trigger; export { Trigger }; <file_sep>// var { List } = require("immutable"); import ChainWebSocket from "./ChainWebSocket"; import GrapheneApi from "./GrapheneApi"; import ChainConfig from "./ChainConfig"; let inst; let autoReconnect = false; // by default don't use reconnecting-websocket /** Configure: configure as follows `Apis.instance("ws://localhost:8090").init_promise`. This returns a promise, once resolved the connection is ready. Import: import { Apis } from "@graphene/chain" Short-hand: Apis.db("method", "parm1", 2, 3, ...). Returns a promise with results. Additional usage: Apis.instance().db_api().exec("method", ["method", "parm1", 2, 3, ...]). Returns a promise with results. */ export const ApiInst = { statusCb: null, setRpcConnectionStatusCallback: function(callback) { this.statusCb = callback; if (inst) inst.setRpcConnectionStatusCallback(callback); }, /** @arg {boolean} auto means automatic reconnect if possible( browser case), default true */ setAutoReconnect: function(auto) { autoReconnect = auto; }, /** @arg {string} cs is only provided in the first call @return {Apis} singleton .. Check Apis.instance().init_promise to know when the connection is established */ // reset: function( // cs = "ws://localhost:8090", // connect, // connectTimeout = 4000, // optionalApis, // closeCb // ) { // return this.close().then(() => { // inst = new ApisInstance(); // inst.setRpcConnectionStatusCallback(this.statusCb); // if (inst && connect) { // inst.connect(cs, connectTimeout, optionalApis, closeCb); // } // return inst; // }); // }, instance: function( cs = "ws://localhost:8090", connect?, connectTimeout = 4000, optionalApis?, closeCb? ) { if (!inst) { inst = new ApisInstance(); // inst = new ApisInstance(cs); inst.setRpcConnectionStatusCallback(this.statusCb); } if (inst && connect) { inst.connect(cs, connectTimeout, optionalApis); } if (closeCb) inst.closeCb = closeCb; return inst; }, close: () => { if (inst) { return new Promise(res => { inst.close().then(() => { inst = null; res(); }); }); } return Promise.resolve(); } // db: (method, ...args) => Apis.instance().db_api().exec(method, toStrings(args)), // network: (method, ...args) => Apis.instance().network_api().exec(method, toStrings(args)), // history: (method, ...args) => Apis.instance().history_api().exec(method, toStrings(args)), // crypto: (method, ...args) => Apis.instance().crypto_api().exec(method, toStrings(args)) // orders: (method, ...args) => Apis.instance().orders_api().exec(method, toStrings(args)) }; export default ApiInst; class ApisInstance { url: string = ""; chain_id: string | undefined; ws_rpc: ChainWebSocket | undefined | null; _db: GrapheneApi | undefined; _net: GrapheneApi | undefined; _hist: GrapheneApi | undefined; statusCb: CallableFunction | undefined; closeCb: CallableFunction | undefined; init_promise: Promise<any> | undefined; connectTimeout = 3000; // constructor(cs: string) { // this.url = cs; // this.ws_rpc = new ChainWebSocket( // cs, // this.statusCb, // 60 * 1000, // autoReconnect, // closed => { // if (this._db && !closed) { // this._db.exec("get_objects", [["2.1.0"]]).catch(e => {}); // } // } // ); // this._db = new GrapheneApi(this.ws_rpc, "database"); // this._net = new GrapheneApi(this.ws_rpc, "network_broadcast"); // this._hist = new GrapheneApi(this.ws_rpc, "history"); // } /** @arg {string} connection .. */ connect( cs, connectTimeout, optionalApis = { enableCrypto: false, enableOrders: false } ) { // console.log("INFO\tApiInstances\tconnect\t", cs); this.url = cs; this.connectTimeout = connectTimeout; let rpc_user = "", rpc_password = ""; if ( typeof window !== "undefined" && window.location && window.location.protocol === "https:" && cs.indexOf("wss://") < 0 ) { throw new Error("Secure domains require wss connection"); } if (this.ws_rpc) { this.ws_rpc.statusCb = null; this.ws_rpc.keepAliveCb = null; this.ws_rpc.on_close = null; this.ws_rpc.on_reconnect = null; } this.ws_rpc = new ChainWebSocket( cs, this.statusCb, connectTimeout, autoReconnect, closed => { if (this._db && !closed) { this._db.exec("get_objects", [["2.1.0"]]).catch(e => {}); } } ); console.debug("[Timing] Init RPC"); this.init_promise = this.ws_rpc .login(rpc_user, rpc_password) .then(() => { console.log("Connected to API node:", cs); this._db = new GrapheneApi(this.ws_rpc, "database"); this._net = new GrapheneApi(this.ws_rpc, "network_broadcast"); this._hist = new GrapheneApi(this.ws_rpc, "history"); // if (optionalApis.enableOrders) // this._orders = new GrapheneApi(this.ws_rpc, "orders"); // if (optionalApis.enableCrypto) // this._crypt = new GrapheneApi(this.ws_rpc, "crypto"); var db_promise = this._db.init().then(() => { //https://github.com/cryptonomex/graphene/wiki/chain-locked-tx return this._db.exec("get_chain_id", []).then(_chain_id => { this.chain_id = _chain_id; return ChainConfig.setChainId(_chain_id); //DEBUG console.log("chain_id1",this.chain_id) }); }); if (!this.ws_rpc) { throw new Error("No Wsrpc client"); } this.ws_rpc.on_reconnect = () => { if (!this.ws_rpc) return; this.ws_rpc.login("", "").then(() => { this._db.init().then(() => { if (this.statusCb) this.statusCb("reconnect"); }); this._net.init(); this._hist.init(); // if (optionalApis.enableOrders) this._orders.init(); // if (optionalApis.enableCrypto) this._crypt.init(); }); }; this.ws_rpc.on_close = () => { (this.close as any)().then(() => { if (this.closeCb) this.closeCb(); }); }; let initPromises = [db_promise, this._net.init(), this._hist.init()]; // if (optionalApis.enableOrders) initPromises.push(this._orders.init()); // if (optionalApis.enableCrypto) initPromises.push(this._crypt.init()); return Promise.all(initPromises); }) .then(res => { initPromise = null; return res; }) .catch(err => { console.error( cs, "Failed to initialize with error", err && err.message ); return (this.close as any)().then(() => { throw err; }); }); } close() { if (!this.ws_rpc || !this.ws_rpc.ws) { return; } if (this.ws_rpc && this.ws_rpc.ws.readyState === 1) { return this.ws_rpc.close().then(() => { this.ws_rpc = null; }); } this.ws_rpc = null; return Promise.resolve(); } get wsReady() { // console.debug( // "Check WsReady: ", // this.ws_rpc, // this.ws_rpc && this.ws_rpc.ws, // this.ws_rpc && this.ws_rpc.ws && this.ws_rpc.ws.readyState === 1, // this._db, // this._db && this._db.exec // ); return !!( this.ws_rpc && this.ws_rpc.ws && this.ws_rpc.ws.readyState === 1 && this._db && this._db.exec ); } db_api() { return (this.wsReady && this._db) || new DeferedApi(ApiType.Database, this); } network_api() { return (this.wsReady && this._net) || new DeferedApi(ApiType.Network, this); } history_api() { return ( (this.wsReady && this._hist) || new DeferedApi(ApiType.History, this) ); } // crypto_api() { // return this._crypt; // } // orders_api() { // return this._orders; // } setRpcConnectionStatusCallback(callback) { this.statusCb = callback; } } enum ApiType { Database = "database", Network = "network_broadcast", History = "history" } let initPromise: null | Promise<any> = null; class DeferedApi { constructor(public apiType: ApiType, public apiInstance: ApisInstance) {} exec(...args) { return new Promise(async (resolve, reject) => { let _this = this; let count = 0; (async function impl() { if (!ApiInst.instance().wsReady && !_this.apiInstance.wsReady) { if (!initPromise && ApiInst.instance().url) { initPromise = ApiInst.instance( ApiInst.instance().url, true, ApiInst.instance().connectTimeout ).init_promise.catch(err => { initPromise = null; }); } } await initPromise; let instance = ApiInst.instance().wsReady ? ApiInst.instance() : _this.apiInstance; if (instance.wsReady) { switch (_this.apiType) { case ApiType.Database: return instance .db_api() .exec(...args) .then(resolve); case ApiType.Network: return instance .network_api() .exec(...args) .then(resolve); case ApiType.History: return instance .history_api() .exec(...args) .then(resolve); } } else if (count++ < 5) { setTimeout(impl, 750); } else { reject(); } })(); }); } } <file_sep>export * from "./Tabs";<file_sep>/// <reference types="react"/> declare module "react-translate-component" { const Translate: React.ComponentFactory<any, any>; export default Translate; } declare module "rc-queue-anim" { class QueueAnim extends React.Component<any, any> {} export default QueueAnim; } declare module "react-scroll-up" { class QueueAnim extends React.Component<any, any> {} export default QueueAnim; } declare module "alt-container" { const AltContainer: React.ClassicFactory<any>; export default AltContainer; } declare module "alt-react" { const supplyFluxContext: any; function connect<P, NP extends P>( Component, injector: { listenTo?(): any[]; getProps?(props: any): { [propName: string]: any }; } ): React.ComponentClass<P>; } declare namespace CommonUtils { const price_text: (price: string, base: any, quote: any) => string; const replaceName: ( name: string, isBitAsset?: boolean ) => { name: string; prefix: string; }; const format_volume: (amount: number) => string; const are_equal_shallow: (...args) => boolean; } // declare module "common/utils" { // export default CommonUtils; // } type Action<T> = {} | T; declare module "alt-instance" { class alt { static createActions(actionClass): Action<typeof actionClass>; static createStore(storeClass, storeName: string): Store<any>; } class BaseStore<S> { listen?(cb: (state: S) => void): void; } export type Store<S> = { state: S; getState(): S; listen(stateListener): void; unlisten(stateListener): void; setState(state: any): S; bindListeners(listenerBinder: { [method: string]: Function }): void; }; export default alt; } declare var __ELECTRON__; <file_sep># Counterpart A translation and localization library for Node.js and the browser. The project is inspired by Ruby's famous [I18n gem](https://github.com/svenfuchs/i18n). Features: - translation and localization - interpolation of values to translations (sprintf-style with named arguments) - pluralization (CLDR compatible) ## Installation Install via npm: ```bash % npm install counterpart ``` ## Usage Require the counterpart module to get a reference to the `translate` function: ```js var translate = require('counterpart'); ``` This function expects a `key` and `options` as arguments and translates, pluralizes and interpolates a given key using a given locale, scope, and fallback, as well as interpolation values. ### Lookup Translation data is organized as a nested object using the top-level key as namespace. *E.g.*, the [damals package](https://github.com/martinandert/damals) ships with the translation: ```js { damals: { about_x_hours_ago: { one: 'about one hour ago', other: 'about %(count)s hours ago' } /* ... */ } } ``` Translations can be looked up at any level of this object using the `key` argument and the `scope` option. *E.g.*, in the following example, a whole translation object is returned: ```js translate('damals') // => { about_x_hours_ago: { one: '...', other: '...' } } ``` The `key` argument can be either a single key, a dot-separated key or an array of keys or dot-separated keys. So these examples will all look up the same translation: ```js translate('damals.about_x_hours_ago.one') // => 'about one hour ago' translate(['damals', 'about_x_hours_ago', 'one']) // => 'about one hour ago' translate(['damals', 'about_x_hours_ago.one']) // => 'about one hour ago' ``` The `scope` option can be either a single key, a dot-separated key or an array of keys or dot-separated keys. Keys and scopes can be combined freely. Again, these examples will all look up the same translation: ```js translate('damals.about_x_hours_ago.one') translate('about_x_hours_ago.one', { scope: 'damals' }) translate('one', { scope: 'damals.about_x_hours_ago' }) translate('one', { scope: ['damals', 'about_x_hours_ago'] }) ``` The `separator` option allows you to change what the key gets split via for nested objects. It also allows you to stop counterpart splitting keys if you have a flat object structure: ```js translate('damals.about_x_hours_ago.one', { separator: '*' }) // => 'missing translation: en*damals.about_x_hours_ago.one' ``` Since we changed what our key should be split by counterpart will be looking for the following object structure: ```js { 'damals.about_x_hours_ago.one': 'about one hour ago' } ``` The `setSeparator` function allows you to globally change the default separator used to split translation keys: ```js translate.setSeparator('*') // => '.' (returns the previous separator) ``` There is also a `getSeparator` function which returns the currently set default separator. ### Interpolation Translations can contain interpolation variables which will be replaced by values passed to the function as part of the options object, with the keys matching the interpolation variable names. *E.g.*, with a translation `{ foo: 'foo %(bar)s' }` the option value for the key `bar` will be interpolated into the translation: ```js translate('foo', { bar: 'baz' }) // => 'foo baz' ``` ### Pluralization Translation data can contain pluralized translations. Pluralized translations are provided as a sub-object to the translation key containing the keys `one`, `other` and optionally `zero`: ```js { x_items: { zero: 'No items.', one: 'One item.', other: '%(count)s items.' } } ``` Then use the `count` option to select a specific pluralization: ```js translate('x_items', { count: 0 }) // => 'No items.' translate('x_items', { count: 1 }) // => 'One item.' translate('x_items', { count: 42 }) // => '42 items.' ``` The name of the option to select a pluralization is always `count`, don't use `itemsCount` or anything like that. Note that this library currently only supports an algorithm for English-like pluralization rules (see [locales/en.js](locales/en.js). You can easily add pluralization algorithms for other locales by [adding custom translation data](#adding-translation-data) to the "counterpart" namespace. Pull requests are welcome. As seen above, the `count` option can be used both for pluralization and interpolation. ### Fallbacks If for a key no translation could be found, `translate` returns an error string of the form "translation missing: %(key)s". To mitigate this, provide the `fallback` option with an alternate text. The following example returns the translation for "baz" or "default" if no translation was found: ```js translate('baz', { fallback: 'default' }) ``` ### Dealing with missing translations When a translation key cannot be resolved to a translation, regardless of whether a fallback is provided or not, `translate` will emit an event you can listen to: ```js translate.onTranslationNotFound(function(locale, key, fallback, scope) { // do important stuff here... }); ``` Use `translate.offTranslationNotFound(myHandler)` to stop listening to missing key events. ### Locales The default locale is English ("en"). To change this, call the `setLocale` function: ```js translate.getLocale() // => 'en' translate.setLocale('de') // => 'en' (returns the previous locale) translate.getLocale() // => 'de' ``` Note that it is advised to call `setLocale` only once at the start of the application or when the user changes her language preference. A library author integrating the counterpart package in a library should not call `setLocale` at all and leave that to the developer incorporating the library. In case of a locale change, the `setLocale` function emits an event you can listen to: ```js translate.onLocaleChange(function(newLocale, oldLocale) { // do important stuff here... }, [callbackContext]); ``` Use `translate.offLocaleChange(myHandler)` to stop listening to locale changes. You can temporarily change the current locale with the `withLocale` function: ```js translate.withLocale(otherLocale, myCallback, [myCallbackContext]); ``` `withLocale` does not emit the locale change event. The function returns the return value of the supplied callback argument. Another way to temporarily change the current locale is by using the `locale` option on `translate` itself: ```js translate('foo', { locale: 'de' }); ``` There are also `withScope` and `withSeparator` functions that behave exactly the same as `withLocale`. ### Fallback Locales You can provide entire fallback locales as alternatives to hard-coded fallbacks. ```js translate('baz', { fallbackLocale: 'en' }); ``` Fallback locales can also contain multiple potential fallbacks. These will be tried sequentially until a key returns a successful value, or the fallback locales have been exhausted. ```js translate('baz', { fallbackLocale: [ 'foo', 'bar', 'default' ] }) ``` Globally, fallback locales can be set via the `setFallbackLocale` method. ```js translate.setFallbackLocale('en') translate.setFallbackLocale([ 'bar', 'en' ]) // Can also take multiple fallback locales ``` ### Adding Translation Data You can use the `registerTranslations` function to deep-merge data for a specific locale into the global translation object: ```js translate.registerTranslations('de', require('counterpart/locales/de')); translate.registerTranslations('de', require('./locales/de.json')); ``` The data object to merge should contain a namespace (e.g. the name of your app/library) as top-level key. The namespace ensures that there are no merging conflicts between different projects. Example (./locales/de.json): ```json { "my_project": { "greeting": "Hallo, %(name)s!", "x_items": { "one": "1 Stück", "other": "%(count)s Stücke" } } } ``` The translations are instantly made available: ```js translate('greeting', { scope: 'my_project', name: 'Martin' }) // => 'Hallo, Martin!' ``` Note that library authors should preload their translations only for the default ("en") locale, since tools like [webpack](http://webpack.github.io/) or [browserify](http://browserify.org/) will recursively bundle up all the required modules of a library into a single file. This will include even unneeded translations and so unnecessarily bloat the bundle. Instead, you as a library author should advise end-users to on-demand-load translations for other locales provided by your package: ```js // Execute this code to load the 'de' translations: require('counterpart').registerTranslations('de', require('my_package/locales/de')); ``` ### Registering Default Interpolations Since v0.11, Counterpart allows you to register default interpolations using the `registerInterpolations` function. Here is an example: ```js translate.registerTranslations('en', { my_namespace: { greeting: 'Welcome to %(app_name)s, %(visitor)s!' } }); translate.registerInterpolations({ app_name: 'My Cool App' }); translate('my_namespace.greeting', { visitor: 'Martin' }) // => 'Welcome to My Cool App, Martin!' translate('my_namespace.greeting', { visitor: 'Martin', app_name: 'The Foo App' }) // => 'Welcome to The Foo App, Martin!' ``` As you can see in the last line of the example, interpolations you give as options to the `translate` function take precedence over registered interpolations. ### Using a key transformer Sometimes it is necessary to adjust the given translation key before the actual translation is made, e.g. when keys are passed in mixed case and you expect them to be all lower case. Use `setKeyTransformer` to provide your own transformation function: ```js translate.setKeyTransformer(function(key, options) { return key.toLowerCase(); }); ``` Counterpart's built-in key transformer just returns the given key argument. ### Localization The counterpart package comes with support for localizing JavaScript Date objects. The `localize` function expects a date and options as arguments. The following example demonstrates the possible options. ```js var date = new Date('Fri Feb 21 2014 13:46:24 GMT+0100 (CET)'); translate.localize(date) // => 'Fri, 21 Feb 2014 13:46' translate.localize(date, { format: 'short' }) // => '21 Feb 13:46' translate.localize(date, { format: 'long' }) // => 'Friday, February 21st, 2014 13:46:24 +01:00' translate.localize(date, { type: 'date' }) // => 'Fri, 21 Feb 2014' translate.localize(date, { type: 'date', format: 'short' }) // => 'Feb 21' translate.localize(date, { type: 'date', format: 'long' }) // => 'Friday, February 21st, 2014' translate.localize(date, { type: 'time' }) // => '13:46' translate.localize(date, { type: 'time', format: 'short' }) // => '13:46' translate.localize(date, { type: 'time', format: 'long' }) // => '13:46:24 +01:00' translate.registerTranslations('de', require('counterpart/locales/de')); translate.localize(date, { locale: 'de' }) // => 'Fr, 21. Feb 2014, 13:46 Uhr' ``` Sure, you can integrate custom localizations by adding to or overwriting the "counterpart" namespace. See [locales/en.js](locales/en.js) and [locales/de.js](locales/de.js) for example localization files. ### As an instance You can invoke an instance of Counterpart should you need various locales displayed at once in your application: ```js var Counterpart = require('counterpart').Instance; var instance = new Counterpart(); instance.registerTranslations('en', { foo: 'bar' }); instance.translate('foo'); ``` ## Contributing Here's a quick guide: 1. Fork the repo and `make install`. 2. Run the tests. We only take pull requests with passing tests, and it's great to know that you have a clean slate: `make test`. 3. Add a test for your change. Only refactoring and documentation changes require no new tests. If you are adding functionality or are fixing a bug, we need a test! 4. Make the test pass. 5. Push to your fork and submit a pull request. ## License Released under The MIT License. <file_sep>```html <Trigger toggle='id-of-target'> <a className='button'>Toggle Target</a> <Trigger> ```<file_sep>import { Colors } from "./Colors"; import chroma from "chroma-js"; import { GlobalsString, GlobalsNumber } from "csstype"; import { $breakpointSmall } from "./Breakpoints"; const TypedStyles = { base: { control: { backgroundColor: Colors.$colorAnchor } }, orderbook: { control: { backgroundColor: "transparent" } } }; export const $styleSelect = (type = "base") => ({ container: styles => ({ ...styles, zIndex: 5 }), valueContainer: styles => ({ ...styles, height: "100%", padding: 0 }), dropdownIndicator: styles => ({ ...styles, padding: "0 8px" }), control: (styles, { data, isDisabled, isFocused, isSelected }) => ({ ...styles, ...TypedStyles[type].control, color: Colors.$colorWhite, height: "2em", minHeight: "2em", minWidth: "5rem", width: "8rem", alignSelf: "flex-start", borderWidth: 0, opacity: isDisabled ? 0.04 : 1 }), menu: (styles, state) => { return { ...styles, backgroundColor: Colors.$colorAnchor }; }, placeholder: (styles, state) => { return { ...styles, color: Colors.$colorWhite }; }, singleValue: (styles, state) => { return { ...styles, color: Colors.$colorWhite }; }, option: (styles, state) => { let { data, isDisabled, isFocused, isSelected } = state; return { ...styles, height: "2rem", minHeight: "2rem", backgroundColor: isDisabled ? null : isFocused ? Colors.$colorIndependence : isSelected ? Colors.$colorLead : Colors.$colorAnchor, color: isSelected ? Colors.$colorWhite : Colors.$colorWhiteOp8, cursor: isDisabled ? "not-allowed" : "default" }; } }); type FlexLayout = | "stretch" | "center" | "flex-start" | "flex-end" | "space-between"; type FlexParams = number | "auto" | GlobalsNumber; export const $styleFlexContainer = ( flexDirection: "row" | "column" = "row", justifyContent: FlexLayout = "stretch", alignItems: FlexLayout = "stretch" ) => ({ display: "flex", flexDirection, justifyContent, alignItems }); export const $styleFlexAutoWrap = { [`@media (max-width: ${$breakpointSmall})`]: { flexWrap: "wrap" } }; export const $styleFlexItem = ( flexGrow: FlexParams = "auto", flexShrink: FlexParams = "auto", flexBasis = "auto", alignSelf: FlexLayout = "stretch" ) => ({ flexGrow, flexShrink, flexBasis, alignSelf }); export const $styleSecondaryText = { color: Colors.$colorWhiteOp8 }; <file_sep>``` <Iconic> <img data-src="/img/iconic/thumb.svg" className="iconic-md" /> </Iconic> ```<file_sep>var React = require("react"); var classnames = require("classnames"); var AccordionItem = React.createClass({ render: function() { var itemClasses = { "accordion-item": true, "is-active": this.props.active }; return ( <div className={classnames(itemClasses)}> <div className="accordion-title" onClick={this.props.activate}> {this.props.title} </div> <div className="accordion-content">{this.props.children}</div> </div> ); } }); module.exports = AccordionItem; <file_sep>export * from "./DrawerToggle"; export * from "./HelpDrawer"; import HelpDrawer from "./HelpDrawer"; export default HelpDrawer;<file_sep>import * as React from "react"; import Animation from "../utils/animation"; var classnames = require("classnames"); var foundationApi = require("../utils/foundation-api"); import Notification from "./notification"; var NotificationStatic = React.createClass({ getInitialState: function() { return { open: false }; }, componentDidMount: function() { foundationApi.subscribe( this.props.id, function(name, msg) { if (msg === "open") { this.setState({ open: true }); } else if (msg === "close") { this.setState({ open: false }); } }.bind(this) ); }, componentWillUnmount: function() { foundationApi.unsubscribe(this.props.id); }, closeHandler: function(e) { this.setState({ open: false }); e.preventDefault(); e.stopPropagation(); }, render: function() { return ( <Animation active={this.state.open} animationIn="fadeIn" animationOut="fadeOut" > <Notification {...this.props} closeHandler={this.closeHandler}> {this.props.children} </Notification> </Animation> ); } }); export default NotificationStatic; export { NotificationStatic }; <file_sep>/** Generic set of components for dealing with data in the ChainStore */ import React, {Component, Children} from "react"; import { connect } from "alt-react"; import ChainTypes from "components/Utility/ChainTypes"; import BindToChainState from "components/Utility/BindToChainState"; import AccountStore from "stores/AccountStore"; import {pairs} from "lodash"; class ResolveLinkedAccountsChainState extends React.Component { static propTypes = { linkedAccounts: ChainTypes.ChainAccountsList.isRequired } render() { let linkedAccounts = []; pairs(this.props.linkedAccounts).forEach( account => { if( !account[1]) return; console.log("... account.toJS()", account[1].toJS()); linkedAccounts.push(account[1]); }); let child = Children.only(this.props.children); if( ! child) return <span>{linkedAccounts.map(a => <br>{a.toJS()}</br>)}</span>; // Pass the list to a child reactjs component as this.props.resolvedLinkedAccounts child = React.cloneElement(child, { linkedAccounts }); return <span>{child}</span>; } } ResolveLinkedAccountsChainState = BindToChainState(ResolveLinkedAccountsChainState); class ResolveLinkedAccounts extends React.Component { render() { return <ResolveLinkedAccountsChainState linkedAccounts={this.props.linkedAccounts} children={this.props.children} />; } } ResolveLinkedAccounts = connect(ResolveLinkedAccounts, { listenTo() { return [AccountStore]; }, getProps() { return AccountStore.getState(); } }); export default ResolveLinkedAccounts; <file_sep>export function fetchJson(options) { let option = options || {}; return new Promise(function(resolve, reject) { setTimeout(() => { resolve({ data: { name: "yang1", //项目名字 token: "j<PASSWORD>", // 内部代号 token_name: "YY", // token 名字 adds: { name: 1 }, // 额外参数 status: "pre", // 状态 pre , ok, pause ,finish base_token_count: 2000, // 众筹金额 base_token: "j<PASSWORD>", // 众筹币代号 base_token_name: "ETH", // 众筹使用货币 rate: 100, // 兑换比例 token:base = 100 base_min_quota: 0.1, //单人最小众筹量 base_max_quota: 9.9, //单人最大众筹量 base_accuracy: 0.1, //精度 recieve_address: "adadada", //收取众筹金的地址 start_at: "2018-07-01", //开始时间 end_at: "2018-08-01", //结束时间 current_base_token_count: "aaa", //当前募资数 current_user_count: "aaa" //当前参与人数 } }); }, 500); }); } <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import { Route, IndexRoute, Redirect } from "react-router-dom"; import willTransitionTo from "./routerTransition"; import App from "./App"; /* * Electron does not support async loading of components via import, * so we make sure they're bundled already by including them here */ class Auth extends React.Component { render() { return null; } } function loadRoute(cb, moduleName = "default") { return module => cb(null, module[moduleName]); } function errorLoading(err) { console.error("Dynamic page loading failed", err); } const routes = ( <Route path="/" component={App} onEnter={willTransitionTo}> <IndexRoute getComponent={(location, cb) => { import("components/Dashboard/DashboardContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/auth/:data" component={Auth} /> <Route path="/dashboard" getComponent={(location, cb) => { import("components/Dashboard/DashboardContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/login" getComponent={(location, cb) => { import("components/Login/Login") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="contact" getComponent={(location, cb) => { import("components/HelpDrawer/Contact") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="explorer" getComponent={(location, cb) => { import("components/Explorer/Explorer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="bazaar" getComponent={(location, cb) => { import("components/Exchange/Bazaar") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="ledger" getComponent={(location, cb) => { import("components/Explorer/BlocksContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/fees" getComponent={(location, cb) => { import("components/Blockchain/FeesContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/blocks" getComponent={(location, cb) => { import("components/Explorer/BlocksContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/assets" getComponent={(location, cb) => { import("components/Explorer/AssetsContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/accounts" getComponent={(location, cb) => { import("components/Explorer/AccountsContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/witnesses" getComponent={(location, cb) => { import("components/Explorer/Witnesses") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/explorer/committee-members" getComponent={(location, cb) => { import("components/Explorer/CommitteeMembers") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/swap" getComponent={(location, cb) => { import("components/Swap/SwapContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="wallet" getComponent={(location, cb) => { import("components/Wallet/WalletManager") .then(loadRoute(cb, "WalletManager")) .catch(errorLoading); }} > {/* wallet management console */} <IndexRoute getComponent={(location, cb) => { import("components/Wallet/WalletManager") .then(loadRoute(cb, "WalletOptions")) .catch(errorLoading); }} /> <Route path="change" getComponent={(location, cb) => { import("components/Wallet/WalletManager") .then(loadRoute(cb, "ChangeActiveWallet")) .catch(errorLoading); }} /> <Route path="change-password" getComponent={(location, cb) => { import("components/Wallet/WalletChangePassword") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="import-keys" getComponent={(location, cb) => { import("components/Wallet/ImportKeys") .then(loadRoute(cb, "ExistingAccountOptions")) .catch(errorLoading); }} /> <Route path="brainkey" getComponent={(location, cb) => { import("components/Wallet/Brainkey") .then(loadRoute(cb, "ExistingAccountOptions")) .catch(errorLoading); }} /> <Route path="create" getComponent={(location, cb) => { import("components/Wallet/WalletCreate") .then(loadRoute(cb, "WalletCreate")) .catch(errorLoading); }} /> <Route path="delete" getComponent={(location, cb) => { import("components/Wallet/WalletManager") .then(loadRoute(cb, "WalletDelete")) .catch(errorLoading); }} /> <Route path="backup/restore" getComponent={(location, cb) => { import("components/Wallet/Backup") .then(loadRoute(cb, "BackupRestore")) .catch(errorLoading); }} /> <Route path="backup/create" getComponent={(location, cb) => { import("components/Wallet/Backup") .then(loadRoute(cb, "BackupCreate")) .catch(errorLoading); }} /> <Route path="backup/brainkey" getComponent={(location, cb) => { import("components/Wallet/BackupBrainkey") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="balance-claims" getComponent={(location, cb) => { import("components/Wallet/BalanceClaimActive") .then(loadRoute(cb)) .catch(errorLoading); }} /> </Route> <Route path="create-wallet" getComponent={(location, cb) => { import("components/Wallet/WalletCreate") .then(loadRoute(cb, "WalletCreate")) .catch(errorLoading); }} /> <Route path="create-wallet-brainkey" getComponent={(location, cb) => { import("components/Wallet/WalletCreate") .then(loadRoute(cb, "CreateWalletFromBrainkey")) .catch(errorLoading); }} /> <Route path="transfer" getComponent={(location, cb) => { import("components/Transfer/Transfer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="eto-static" getComponent={(location, cb) => { import("components/StaticPages/EtoStatic") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="invoice/:data" getComponent={(location, cb) => { import("components/Transfer/Invoice") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="explorer/markets" getComponent={(location, cb) => { import("components/Exchange/MarketsContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="market/:marketID" getComponent={(location, cb) => { import("components/Exchange/ExchangeContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="settings" getComponent={(location, cb) => { import("components/Settings/SettingsContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="block/:height" getComponent={(location, cb) => { import("components/Blockchain/BlockContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="asset/:symbol" getComponent={(location, cb) => { import("components/Blockchain/AssetContainer") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="create-account" getComponent={(location, cb) => { import("components/Login/CreateSelector") .then(loadRoute(cb)) .catch(errorLoading); }} > <Route path="wallet" getComponent={(location, cb) => { import("components/Account/CreateAccount") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="password" getComponent={(location, cb) => { import("components/Account/CreateAccountPassword") .then(loadRoute(cb)) .catch(errorLoading); }} /> </Route> <Route path="existing-account" getComponent={(location, cb) => { import("components/Wallet/ExistingAccount") .then(loadRoute(cb, "ExistingAccount")) .catch(errorLoading); }} > <IndexRoute getComponent={(location, cb) => { import("components/Wallet/Backup") .then(loadRoute(cb, "BackupRestore")) .catch(errorLoading); }} /> <Route path="import-backup" getComponent={(location, cb) => { import("components/Wallet/ExistingAccount") .then(loadRoute(cb, "ExistingAccountOptions")) .catch(errorLoading); }} /> <Route path="import-keys" getComponent={(location, cb) => { import("components/Wallet/ImportKeys") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="brainkey" getComponent={(location, cb) => { import("components/Wallet/Brainkey") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="balance-claim" getComponent={(location, cb) => { import("components/Wallet/BalanceClaimActive") .then(loadRoute(cb)) .catch(errorLoading); }} /> </Route> <Route path="/account/:account_name" getComponent={(location, cb) => { import("components/Account/AccountPage") .then(loadRoute(cb)) .catch(errorLoading); }} > <IndexRoute getComponent={(location, cb) => { import("components/Account/AccountOverview") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="overview" getComponent={(location, cb) => { import("components/Account/AccountOverview") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="assets" getComponent={(location, cb) => { import("components/Account/AccountAssets") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="create-asset" getComponent={(location, cb) => { import("components/Account/AccountAssetCreate") .then(loadRoute(cb, "AccountAssetCreate")) .catch(errorLoading); }} /> <Route path="update-asset/:asset" getComponent={(location, cb) => { import("components/Account/AccountAssetUpdate") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="member-stats" getComponent={(location, cb) => { import("components/Account/AccountMembership") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="vesting" getComponent={(location, cb) => { import("components/Account/AccountVesting") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="permissions" getComponent={(location, cb) => { import("components/Account/AccountPermissions") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="voting" getComponent={(location, cb) => { import("components/Account/AccountVoting") .then(loadRoute(cb)) .catch(errorLoading); }} /> {/* <Route path="deposit-withdraw" getComponent={(location, cb) => { import("components/Account/AccountDepositWithdraw").then(loadRoute(cb)).catch(errorLoading); }}/> */} <Route path="orders" getComponent={(location, cb) => { import("components/Account/AccountOrders") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="whitelist" getComponent={(location, cb) => { import("components/Account/AccountWhitelist") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Redirect from="dashboard" to="overview" /> }}/> <Route path="signedmessages" getComponent={(location, cb) => { import("components/Account/AccountSignedMessages") .then(loadRoute(cb)) .catch(errorLoading); }} /> </Route> <Route path="deposit-withdraw" getComponent={(location, cb) => { import("components/Account/AccountDepositWithdraw") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="create-worker" getComponent={(location, cb) => { import("components/Account/CreateWorker") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="gateway" getComponent={(location, cb) => { import("components/Gateway/Gateway") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/init-error" getComponent={(location, cb) => { import("components/InitError") .then(loadRoute(cb)) .catch(errorLoading); }} /> <Route path="/help" getComponent={(location, cb) => { import("components/Help") .then(loadRoute(cb)) .catch(errorLoading); }} > <Route path=":path1" getComponent={(location, cb) => { import("components/Help") .then(loadRoute(cb)) .catch(errorLoading); }} > <Route path=":path2" getComponent={(location, cb) => { import("components/Help") .then(loadRoute(cb)) .catch(errorLoading); }} > <Route path=":path3" getComponent={(location, cb) => { import("components/Help") .then(loadRoute(cb)) .catch(errorLoading); }} /> </Route> </Route> </Route> <Redirect from="*" to="/" /> </Route> ); export default routes; <file_sep>import ContextMenuActions, { ContextMenuList, ContextMenuItem, getMenuId } from "actions/ContextMenuActions"; import alt from "alt-instance"; import BaseStore from "stores/BaseStore"; import * as Immutable from "immutable"; type MenuStore = { [x: string]: ContextMenuList }; class ContextMenuStore extends BaseStore { // abstract method for alt bindListeners; // menuStore: MenuStore = {}; constructor() { super(); this.bindListeners({ addMenu: ContextMenuActions.addMenu, detachMenu: ContextMenuActions.detachMenu, clearMenu: ContextMenuActions.clearMenu }); } addMenu({menuId, menuList}) { if (!menuId) { throw new Error("A menu list must be used with an id as the first param"); } if (menuId in this.menuStore) { throw new Error("Multiple context menu exist. The menu id: " + menuId); } this.menuStore[menuId] = menuList; } detachMenu(menuId: string) { delete this.menuStore[menuId]; } clearMenu(forceClear) { this.menuStore = {}; } } export var ContextMenuStoreWrapper = alt.createStore(ContextMenuStore, "ContextMenuStore"); export default ContextMenuStoreWrapper<file_sep>//滚动条在Y轴上的滚动距离 export function getScrollTop() { let bodyScrollTop = 0, documentScrollTop = 0; if (document.body) { bodyScrollTop = document.body.scrollTop; } if (document.documentElement) { documentScrollTop = document.documentElement.scrollTop; } return (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop; } //文档的总高度 export function getScrollHeight() { return document.documentElement.scrollTop == 0 ? document.body.scrollHeight : document.documentElement.scrollHeight } //浏览器视口的高度 export const getWindowHeight = () => (document.documentElement.scrollTop == 0 ? document.body.clientHeight : document.documentElement.clientHeight);<file_sep>var React = require("react"); var Highlight = require("react-highlight/optimized"); var BasicActionSheet = require("./basic"); var ActionSheetDocs = React.createClass({ render: function() { return ( <div> <h2> Action Sheet </h2> <h4 className="subheader"> Action sheets can be triggered in your app view to providing contextual actions on a component. They act as slide up menus on small devices and drop downs on larger screens. </h4> <hr /> <BasicActionSheet /> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./basic.md")} </Highlight> </div> <div className="grid-content"> <BasicActionSheet /> </div> </div> </div> ); } }); module.exports = ActionSheetDocs; <file_sep>import { Link } from "react-router-dom"; import * as React from "react"; import * as PropTypes from "prop-types"; import Translate from "react-translate-component"; const RestoreWallet = (props) => ( <div style={{"paddingTop": "1em"}}> <label> <Link to="/existing-account"> <Translate content="wallet.restore" /> </Link> </label> <label> <Link to="/create-wallet-brainkey"> <Translate content="settings.backup_brainkey" /> </Link> </label> </div> ); export default RestoreWallet;<file_sep>```html <Trigger hardToggle='example-top-panel'> <a className="button">Top Panel</a> </Trigger> ```<file_sep>var React = require("react"); var Tabs = require("../../lib/tabs"); var BasicTabs = React.createClass({ render: function() { return ( <Tabs> <Tabs.Tab title="Tab 1">Tab 1 content</Tabs.Tab> <Tabs.Tab title="Tab 2">Tab 2 content</Tabs.Tab> <Tabs.Tab title="Tab 3">Tab 3 content</Tabs.Tab> </Tabs> ); } }); module.exports = BasicTabs; <file_sep>import { debugGen } from "utils"; const $w = window as typeof window & { gtag }; const debug = debugGen("Gtag"); const EVENT_CATE = { ACCOUNT: "ACCOUNT", ACTIVITY: "ACTIVITY", TRANSACTION: "TRANSACTION" }; /** * 主动触发谷歌分析工具特定方法 * * @export * @class Gtag */ export class Gtag { static eventRegisterDone(accountName: string, method: string) { Gtag.reportEvent( `REGISTER_DONE:${method}`, EVENT_CATE.ACCOUNT, accountName ); } static eventLoginDone(accountName: string, method: string) { Gtag.reportEvent( `LOGIN_DONE:${method}`, EVENT_CATE.ACCOUNT, accountName ); } static eventActivity(name: string, subContent: string) { Gtag.reportEvent( `${EVENT_CATE.ACTIVITY}:${name}`, EVENT_CATE.ACTIVITY, subContent ); } static reportEvent( eventName: string, category: string, label: string, value = 1 ) { debug("[Event]", eventName, label); if ("gtag" in $w) { $w.gtag("event", eventName.toUpperCase(), { event_category: category.toUpperCase(), event_label: label, value }); } } static eventUnlock(accountName: string, method: string) { Gtag.reportEvent(`UNLOCK:${method}`, EVENT_CATE.ACCOUNT, accountName); } static eventTracactionBroadcast(accountName: string, operation: string) { Gtag.reportEvent( `BROADCAST:${operation}`, EVENT_CATE.TRANSACTION, accountName ); } static eventTracactionBroadcastFailed( accountName: string, operation: string ) { Gtag.reportEvent( `BROADCAST_FAILED:${operation}`, EVENT_CATE.TRANSACTION, accountName ); } static eventRegisterFailed(accountName: string) { Gtag.reportEvent("REGISTER_FAILED", EVENT_CATE.ACCOUNT, accountName); } } export default Gtag; <file_sep>import alt from "alt-instance"; import { Store } from "alt-instance"; import { debugGen } from "utils//Utils"; import { AbstractStore } from "./AbstractStore"; import ls from "lib/common/localStorage"; const STORAGE_KEY = "__graphene__"; let ss = new ls(STORAGE_KEY); const debug = debugGen("TimerStore"); type State = { begin: number; basicTimer: number; }; class TimerStore extends AbstractStore<State> { state: State = { begin: Date.now(), basicTimer: Date.now() }; constructor() { super(); setInterval(() => { this.setState({ basicTimer: Date.now() }); }, 100); } } const StoreWrapper = alt.createStore(TimerStore, "TimerStore") as TimerStore & Store<State>; export { StoreWrapper as TimerStore }; export default StoreWrapper; <file_sep>import * as React from "react"; import * as PropTypes from "prop-types"; import ZfApi from "react-foundation-apps/src/utils/foundation-api"; import { Link } from "react-router-dom"; import BaseModal from "../Modal/BaseModal"; import Trigger from "react-foundation-apps/src/trigger"; import utils from "common/utils"; import Translate from "react-translate-component"; export default class BackupModal extends React.Component { constructor(props) { super(props); this.modalId = "modal_backup"; this.show = this.show.bind(this); this.hide = this.hide.bind(this); } show() { ZfApi.publish(this.modalId, "open"); } hide() { ZfApi.publish(this.modalId, "close"); } render() { return ( <BaseModal id="modal_backup" overlay={true}> <Translate component="h3" content="backup.title" /> <div className="grid-block vertical text-justify"> <Translate content={"backup.content"} /> <div className="button-group" style={{ paddingTop: "2rem" }}> <button onClick={this.hide} className="button" type="submit"> <Link to="/wallet/backup/create"> <Translate style={{ color: "white" }} content={"backup.go_backup"} /> </Link> </button> <Trigger close="modal_backup"> <button className="button info"> <Translate content={"backup.no_backup"} /> </button> </Trigger> </div> </div> </BaseModal> ); } } <file_sep>import alt from "alt-instance"; import { string } from "prop-types"; import { correctMarketPair, correctMarketPairMap } from "utils/Market"; import { Apis } from "cybexjs-ws"; // Todo Review this class class TradeHistoryActions { /** * * @param {string} assetA * @param {string} assetB * @param {Cybex.Trade[]} currentHistory A trade history array, with descending order on the time * @param {boolean} [loadLatest=true] * @memberof TradeHistoryActions */ async patchTradeHistory( assetA, assetB, currentHistory: Cybex.Trade[] = [], loadLatest = true ) { let market = correctMarketPairMap(assetA, assetB); let { base, quote } = market; let nowTrade: Cybex.Trade = { date: new Date().toISOString(), sequence: 0, price: "", amount: "", value: "", side1_account_id: "", side2_account_id: "" }; let earlyTrade: Cybex.Trade = { date: new Date(Date.now() - 86400 * 1000 * 10000).toISOString(), sequence: 0, price: "", amount: "", value: "", side1_account_id: "", side2_account_id: "" }; let currentLatest: Cybex.Trade = currentHistory.length ? currentHistory[0] : earlyTrade; let currentOldest: Cybex.Trade = currentHistory.length ? currentHistory[currentHistory.length - 1] : nowTrade; let startTime = loadLatest ? nowTrade.date : currentOldest.date; let stopTime = loadLatest ? currentLatest.date : earlyTrade.date; let history: Cybex.Trade[] = await Apis.instance() .db_api() .exec("get_trade_history", [ base.get("id"), quote.get("id"), startTime.substring(0, startTime.length - 1), stopTime.substring(0, stopTime.length - 1), 100 ]); return this.onHistoryPatched({ market: `${market.quote.get("symbol")}${market.base.get("symbol")}`, history }); } onHistoryPatched({ market, history }: { market: string; history: Cybex.Trade[]; }) { return { market, history }; } } const TradeHistoryActionsWrapped: TradeHistoryActions = alt.createActions( TradeHistoryActions ); export { TradeHistoryActionsWrapped as TradeHistoryActions }; export default TradeHistoryActionsWrapped; <file_sep>```html <Trigger hardToggle='id-of-target'> <a className='button'>Hard Toggle Target</a> <Trigger> ```<file_sep>///<reference types="immutable" /> declare const __FOR_SECURITY__; declare const __STAGING__; declare const __TEST__; declare const __DEV__; declare const __BASE_URL__; declare const __GATEWAY_URL__; declare const __ICOAPE__; declare namespace ETO { type AccountStatus = { base_received: number; base_received_invalid: number; base_received_invalid_other: number; delay: number; fail: number; freezing: number; project_id: string; sent: number; stop: number; user_id: string; verify: number; }; type Record = { token: string; project_id: string; project_name: string; block_num: number; memo?: string; user_id: string; created_at: string; update_at: string; ieo_type: string; id: string; ieo_status: string; trade_num: 0; //block里面的第几个index token_count: number; reason: string; }; type Optional = string | number | null; type EtoBase = { base_token: string; base_min: number; accuracy: number; rate: number; base_token_name: string; }; type ProjectDetail = { account: "testroot"; banner: 0; // base_accuracy: 1; base_max_quota: 20; base_min_quota: 0.5; base_soft_cap: null; // base_token: "J<PASSWORD>"; base_token_count: 1000; base_token_name: "ETH"; close_at: null; control: "online"; // control_status: "unstart"; // created_at: "2018-07-21 05:22:12"; // current_base_token_count: 0; current_percent: 0; current_user_count: 0; deleted: 0; // end_at: "2018-08-28 04:00:00"; finish_at: null; id: "1004"; is_user_in: "1"; lock_at: null; name: "会员组"; offer_at: null; parent: "1000"; // project: "1004"; rate: 5000; receive_address: ""; score: 5; // start_at: "2018-07-08 12:00:00"; status: "ok"; timestamp: "2018-07-21 13:22:12"; // token: "J<PASSWORD>"; token_count: 0; token_name: "TCT"; type: "nomal"; update_at: "2018-07-21 05:22:12"; }; type CurrentState = | { current_base_token_count: number; current_percent: number; current_user_count: number; real: boolean; status: "pre"; } | {}; type ETORecord = { block_num: number | null; created_at: string; id: string; ieo_status: string; ieo_type: string; lock_at: null; memo: string; project_id: number; project_name: string; reason: string; token: string; token_count: number; trade_num: number | null; update_at: string; user_id: string; }; // type ProjectDetail = { // soft_cap: Optional; // created_at: string; // token_name: string; // lock_at: Optional; // base_tokens: EtoBase[]; // update_at: string; // status: "ok"; // close_at: Optional; // max: number; // current_user_count: number; // type: string; // end_at: string; // receive_address: string; // current_token_count: number; // control_status: "ok"; // start_at: string; // id: string; // offer_at: Optional; // name: string; // default_base_token: string; // finish_at: Optional; // token_count: number; // token: string; // deleted: 0; // score: 0; // control: string; // banner: 0; // is_user_in: "1"; // _id: string; // project: string; // timestamp: string; // __v: 0; // adds_erc20: boolean; // current_percent: number; // }; } declare namespace Cybex { type Ticker = { close: null; price: string; change: string; volumeBase: number; volumeQuote: number; volumeBaseAsset: Asset; volumeQuoteAsset: Asset; }; type Trade = { sequence: number; date: string; price: string; amount: string; value: string; side1_account_id: string; side2_account_id: string; }; type MarketHistory = { id: "5.1.722298"; key: { base: "1.3.2"; quote: "1.3.27"; seconds: 86400; open: "2018-06-01T00:00:00"; }; high_base: 63100; high_quote: 35643676; low_base: 99000; low_quote: 58341825; open_base: 163700; open_quote: 94686640; close_base: 131800; close_quote: 76553309; base_volume: 587892479; quote_volume: "338732823145"; }; type SanitizedMarketHistory = { date: Date; open: number; high: number; low: number; close: number; volume: number; base: string; quote: string; interval: number; time: number; }; type Amount = { amount: string | number; asset_id: string; }; type Asset = { satoshi; asset_id; precision; amount; _real_amount; constructor({ asset_id, amount, precision, real }: { asset_id: string; amount: number; precision: number; real: boolean | null; }); hasAmount(): boolean; toSats(amount: number): number; }; type AccountProperty = | "id" | "name" | "active" | "active_special_authority" | "assets" | "balances" | "blacklisted_accounts"; type Account = Map<AccountProperty, any>; } type Auth = [string, number]; type AccountOptions = { memo_key: string; num_committee: number; num_witness: number; votes: any[]; voting_account: AccountId; }; type AccountAuth = { account_auths: Auth[]; address_auths: Auth[]; key_auths: Auth[]; weight_threshold: number; }; type AccountId = string; type Account = { active: AccountAuth; active_special_authority: any; assets: any[]; balances: { [asset_id: string]: string }; blacklisted_accounts: AccountId[]; blacklisting_accounts: AccountId[]; call_orders: any[]; history: any[]; id: AccountId; level: 2; lifetime_referrer: AccountId; lifetime_referrer_fee_percentage: number; lifetime_referrer_name: AccountId; membership_expiration_date: string; name: string; network_fee_percentage: number; options: AccountOptions; orders: any[]; owner: AccountAuth; owner_special_authority: any; proposals: any[]; referrer: AccountId; referrer_name: AccountId; referrer_rewards_percentage: 0; registrar: string; registrar_name: AccountId; statistics: string; top_n_control_flags: number; vesting_balances: any[]; whitelisted_accounts: any[]; whitelisting_accounts: AccountId[]; }; declare namespace GameCenter { interface DepositConfig { depositAccount: string | null; asset: string | null; exchangeRate: number | null; } interface WithdrawConfig { ceil: number | null; exchangeRate: number | null; } } <file_sep>export * from "./ClassName"; export * from "./Utils"; export * from "./Chart"; export * from "./ErrorTrans";<file_sep>var React = require("react"); var BasicIconic = require("./basic"); var Highlight = require("react-highlight/optimized"); var IconicDocs = React.createClass({ render: function() { return ( <div> <h2>Iconic</h2> <hr /> <h3>Basic</h3> <div className="grid-block"> <div className="small-8 grid-content"> <Highlight innerHTML={true} languages={["xml"]}> {require("./basic.md")} </Highlight> </div> <div className="grid-content"> <BasicIconic /> </div> </div> </div> ); } }); module.exports = IconicDocs; <file_sep>import * as Immutable from "immutable"; import alt from "alt-instance"; import MarketsActions from "actions/MarketsActions"; import market_utils from "common/market_utils"; import ls from "common/localStorage"; import { ChainStore } from "cybexjs"; import utils from "common/utils"; import { LimitOrder, CallOrder, FeedPrice, SettleOrder, Asset, didOrdersChange, Price } from "common/MarketClasses"; // import { // SettleOrder // } // from "./tcomb_structs"; const nullPrice = { getPrice: () => { return 0; }, sellPrice: () => { return 0; } }; let marketStorage = new ls("__graphene__"); class MarketsStore { [props: string]: any; constructor() { this.markets = Immutable.Map(); this.asset_symbol_to_id = {}; this.pendingOrders = Immutable.Map(); this.marketLimitOrders = Immutable.Map(); this.marketCallOrders = Immutable.Map(); this.allCallOrders = []; this.feedPrice = null; this.marketSettleOrders = Immutable.OrderedSet(); this.activeMarketHistory = Immutable.OrderedSet(); this.marketData = { bids: [], asks: [], calls: [], combinedBids: [], highestBid: nullPrice, combinedAsks: [], lowestAsk: nullPrice, flatBids: [], flatAsks: [], flatCalls: [], flatSettles: [] }; this.totals = { bid: 0, ask: 0, call: 0 }; this.priceData = []; this.volumeData = []; this.pendingCreateLimitOrders = []; this.activeMarket = null; this.quoteAsset = null; this.pendingCounter = 0; this.buckets = [15, 60, 300, 3600, 86400]; this.bucketSize = this._getBucketSize(); this.priceHistory = []; this.lowestCallPrice = null; this.marketBase = "CYB"; this.marketStats = Immutable.Map({ change: 0, volumeBase: 0, volumeQuote: 0 }); this.marketReady = false; this.allMarketStats = Immutable.Map(); this.lowVolumeMarkets = Immutable.Map( marketStorage.get("lowVolumeMarkets", {}) ); this.onlyStars = marketStorage.get("onlyStars", false); this.baseAsset = { id: "1.3.0", symbol: "CYB", precision: 5 }; this.coreAsset = { id: "1.3.0", symbol: "CORE", precision: 5 }; this.bindListeners({ onSubscribeMarket: MarketsActions.subscribeMarket, onUnSubscribeMarket: MarketsActions.unSubscribeMarket, onChangeBase: MarketsActions.changeBase, onChangeBucketSize: MarketsActions.changeBucketSize, onCancelLimitOrderSuccess: MarketsActions.cancelLimitOrderSuccess, onCloseCallOrderSuccess: MarketsActions.closeCallOrderSuccess, onCallOrderUpdate: MarketsActions.callOrderUpdate, onClearMarket: MarketsActions.clearMarket, onGetMarketStats: MarketsActions.getMarketStats, onSettleOrderUpdate: MarketsActions.settleOrderUpdate, onSwitchMarket: MarketsActions.switchMarket, onFeedUpdate: MarketsActions.feedUpdate, onToggleStars: MarketsActions.toggleStars }); const supportedResolutions = ["1", "5", "60", "1D", "1W", "1M"]; this.Datafeed = { onReady: cb => { console.log("=====onReady running"); setTimeout( () => cb({ supported_resolutions: supportedResolutions }), 0 ); }, calculateHistoryDepth: (resolution, resolutionBack, intervalBack) => { //optional console.log("=====calculateHistoryDepth running"); // while optional, this makes sure we request 24 hours of minute data at a time // CryptoCompare's minute data endpoint will throw an error if we request data beyond 7 days in the past, and return no data return resolution < 60 ? { resolutionBack: "D", intervalBack: "1" } : undefined; }, resolveSymbol: (symbolName, onSymbolResolvedCallback) => { // expects a symbolInfo object in response console.debug("======resolveSymbol running", symbolName); // console.log('resolveSymbol:',{symbolName}) const symbolStub = { name: symbolName, description: symbolName, type: "crypto", session: "24x7", timezone: "Asia/Shanghai", ticker: symbolName, exchange: "Cybex", minmov: 1, // TODO: set this later pricescale: 100000000, has_intraday: true, intraday_multipliers: ["1", "60"], supported_resolution: supportedResolutions, // TODO: set this later volume_precision: 8, data_status: "streaming" }; setTimeout(function() { onSymbolResolvedCallback(symbolStub); console.log("Resolving that symbol....", symbolStub); }, 0); }, unsubscribeBars: subscriberUID => { console.log("=====unsubscribeBars running"); // stream.unsubscribeBars(subscriberUID) } }; } onGetCollateralPositions(payload) { this.borrowMarketState = { totalDebt: payload.totalDebt, totalCollateral: payload.totalCollateral }; } _getBucketSize() { return parseInt(marketStorage.get("bucketSize", 4 * 3600)); } _setBucketSize(size) { this.bucketSize = size; marketStorage.set("bucketSize", size); } onChangeBase(market) { this.marketBase = market; } onChangeBucketSize(size) { this._setBucketSize(size); } onToggleStars() { this.onlyStars = !this.onlyStars; marketStorage.set("onlyStars", this.onlyStars); } onUnSubscribeMarket(payload) { // Optimistic removal of activeMarket if (payload.unSub) { this.activeMarket = null; } else { // Unsub failed, restore activeMarket this.activeMarket = payload.market; } } onSwitchMarket() { this.marketReady = false; } onClearMarket() { this.activeMarket = null; this.is_prediction_market = false; this.marketLimitOrders = this.marketLimitOrders.clear(); this.marketCallOrders = this.marketCallOrders.clear(); this.allCallOrders = []; this.feedPrice = null; this.marketSettleOrders = this.marketSettleOrders.clear(); this.activeMarketHistory = this.activeMarketHistory.clear(); this.marketData = { bids: [], asks: [], calls: [], combinedBids: [], highestBid: nullPrice, combinedAsks: [], lowestAsk: nullPrice, flatBids: [], flatAsks: [], flatCalls: [], flatSettles: [] }; this.totals = { bid: 0, ask: 0, call: 0 }; this.lowestCallPrice = null; this.pendingCreateLimitOrders = []; this.priceHistory = []; this.marketStats = Immutable.Map({ change: 0, volumeBase: 0, volumeQuote: 0 }); } _marketHasCalls() { const { quoteAsset, baseAsset } = this; if ( quoteAsset.has("bitasset") && quoteAsset.getIn(["bitasset", "options", "short_backing_asset"]) === baseAsset.get("id") ) { return true; } else if ( baseAsset.has("bitasset") && baseAsset.getIn(["bitasset", "options", "short_backing_asset"]) === quoteAsset.get("id") ) { return true; } return false; } onSubscribeMarket(result) { if (result.switchMarket) { this.marketReady = false; return this.emitChange(); } let limitsChanged = false, callsChanged = false; this.invertedCalls = result.inverted; // Get updated assets every time for updated feed data this.quoteAsset = ChainStore.getAsset(result.quote.get("id")); this.baseAsset = ChainStore.getAsset(result.base.get("id")); const assets = { [this.quoteAsset.get("id")]: { precision: this.quoteAsset.get("precision") }, [this.baseAsset.get("id")]: { precision: this.baseAsset.get("precision") } }; if (result.market && result.market !== this.activeMarket) { console.debug("switch active market from", this.activeMarket, "to", result.market); // Todo find why this fragment works fine if (this.activeMarket) { return; } this.onClearMarket(); this.activeMarket = result.market; } /* Set the feed price (null if not a bitasset market) */ this.feedPrice = this._getFeed(); if (result.buckets) { this.buckets = result.buckets; if (result.buckets.indexOf(this.bucketSize) === -1) { this.bucketSize = result.buckets[result.buckets.length - 1]; } } if (result.buckets) { this.buckets = result.buckets; } if (result.limits) { // Keep an eye on this as the number of orders increases, it might not scale well const oldmarketLimitOrders = this.marketLimitOrders; this.marketLimitOrders = this.marketLimitOrders.clear(); // console.time("Create limit orders " + this.activeMarket); result.limits.forEach(order => { // ChainStore._updateObject(order, false, false); if (typeof order.for_sale !== "number") { order.for_sale = parseInt(order.for_sale, 10); } order.expiration = new Date(order.expiration); this.marketLimitOrders = this.marketLimitOrders.set( order.id, new LimitOrder(order, assets, this.quoteAsset.get("id")) ); }); limitsChanged = didOrdersChange( this.marketLimitOrders, oldmarketLimitOrders ); // Loop over pending orders to remove temp order from orders map and remove from pending for (let i = this.pendingCreateLimitOrders.length - 1; i >= 0; i--) { let myOrder = this.pendingCreateLimitOrders[i]; let order = this.marketLimitOrders.find(order => { return ( myOrder.seller === order.seller && myOrder.expiration === order.expiration ); }); // If the order was found it has been confirmed, delete it from pending if (order) { this.pendingCreateLimitOrders.splice(i, 1); } } // console.timeEnd("Create limit orders " + this.activeMarket); if (this.pendingCreateLimitOrders.length === 0) { this.pendingCounter = 0; } // console.log("time to process limit orders:", new Date() - limitStart, "ms"); } if (result.calls) { const oldmarketCallOrders = this.marketCallOrders; this.allCallOrders = result.calls; this.marketCallOrders = this.marketCallOrders.clear(); result.calls.forEach(call => { // ChainStore._updateObject(call, false, false); try { let callOrder = new CallOrder( call, assets, this.quoteAsset.get("id"), this.feedPrice, this.is_prediction_market ); if (callOrder.isMarginCalled()) { this.marketCallOrders = this.marketCallOrders.set( call.id, callOrder ); } } catch (err) { console.error( "Unable to construct calls array, invalid feed price or prediction market?" ); } }); callsChanged = didOrdersChange( this.marketCallOrders, oldmarketCallOrders ); } this.updateSettleOrders(result); if (result.history && result.history.length) { console.debug("Result: history: ", result.history); this.activeMarketHistory = this.activeMarketHistory.clear(); result.history.forEach(order => { if (!/Z$/.test(order.time)) { order.time += "Z"; } order.op.time = order.time; /* Only include history objects that aren't 'something for nothing' to avoid confusion */ if (!(order.op.receives.amount == 0 || order.op.pays.amount == 0)) { this.activeMarketHistory = this.activeMarketHistory.add(order.op); } }); } if (result.fillOrders) { result.fillOrders.forEach(fill => { // console.log("fill:", fill); this.activeMarketHistory = this.activeMarketHistory.add(fill[0][1]); }); } if (result.stat) { let stats = result.stat; this.marketStats = this.marketStats.set("change", stats.percent_change); this.marketStats = this.marketStats.set("volumeBase", stats.base_volume); this.marketStats = this.marketStats.set("volumeQuote", stats.quote_volume); this.marketStats = this.marketStats.set("price", stats.latest); if (stats.volumeBase) { this.lowVolumeMarkets = this.lowVolumeMarkets.delete(result.market); } } if (callsChanged || limitsChanged) { // Update orderbook this._orderBook(limitsChanged, callsChanged); // Update depth chart data this._depthChart(); } this.marketReady = true; this.emitChange(); } onCancelLimitOrderSuccess(cancellations) { if (cancellations && cancellations.length) { let didUpdate = false; cancellations.forEach(orderID => { if (orderID && this.marketLimitOrders.has(orderID)) { didUpdate = true; this.marketLimitOrders = this.marketLimitOrders.delete(orderID); } }); if (this.marketLimitOrders.size === 0) { this.marketData.bids = []; this.marketData.flatBids = []; this.marketData.asks = []; this.marketData.flatAsks = []; } if (didUpdate) { // Update orderbook this._orderBook(true, false); // Update depth chart data this._depthChart(); } } else { return false; } } onCloseCallOrderSuccess(orderID) { if (orderID && this.marketCallOrders.has(orderID)) { this.marketCallOrders = this.marketCallOrders.delete(orderID); if (this.marketCallOrders.size === 0) { this.marketData.calls = []; this.marketData.flatCalls = []; } // Update orderbook this._orderBook(false, true); // Update depth chart data this._depthChart(); } else { return false; } } onCallOrderUpdate(call_order) { if (call_order && this.quoteAsset && this.baseAsset) { if ( call_order.call_price.quote.asset_id === this.quoteAsset.get("id") || call_order.call_price.quote.asset_id === this.baseAsset.get("id") ) { const assets = { [this.quoteAsset.get("id")]: { precision: this.quoteAsset.get("precision") }, [this.baseAsset.get("id")]: { precision: this.baseAsset.get("precision") } }; try { let callOrder = new CallOrder( call_order, assets, this.quoteAsset.get("id"), this.feedPrice ); // console.log("**** onCallOrderUpdate **", call_order, "isMarginCalled:", callOrder.isMarginCalled()); if (callOrder.isMarginCalled()) { this.marketCallOrders = this.marketCallOrders.set( call_order.id, callOrder ); // Update orderbook this._orderBook(false, true); // Update depth chart data this._depthChart(); } } catch (err) { console.error( "Unable to construct calls array, invalid feed price or prediction market?" ); } } } else { return false; } } // onFeedUpdate(asset) { if (!this.quoteAsset || !this.baseAsset) { return false; } if ( asset.get("id") === this[this.invertedCalls ? "baseAsset" : "quoteAsset"].get("id") ) { this[this.invertedCalls ? "baseAsset" : "quoteAsset"] = asset; } else { return false; } let feedChanged = false; let newFeed = this._getFeed(); if ( (newFeed && !this.feedPrice) || (this.feedPrice && this.feedPrice.ne(newFeed)) ) { feedChanged = true; } if (feedChanged) { this.feedPrice = newFeed; const assets = { [this.quoteAsset.get("id")]: { precision: this.quoteAsset.get("precision") }, [this.baseAsset.get("id")]: { precision: this.baseAsset.get("precision") } }; /* * If the feed price changed, we need to check whether the orders * being margin called have changed and filter accordingly. To do so * we recreate the marketCallOrders map from scratch using the * previously fetched data and the new feed price. */ this.marketCallOrders = this.marketCallOrders.clear(); this.allCallOrders.forEach(call => { // ChainStore._updateObject(call, false, false); try { let callOrder = new CallOrder( call, assets, this.quoteAsset.get("id"), this.feedPrice, this.is_prediction_market ); if (callOrder.isMarginCalled()) { this.marketCallOrders = this.marketCallOrders.set( call.id, new CallOrder( call, assets, this.quoteAsset.get("id"), this.feedPrice ) ); } } catch (err) { console.error( "Unable to construct calls array, invalid feed price or prediction market?" ); } }); // this.marketCallOrders = this.marketCallOrders.withMutations(callOrder => { // if (callOrder && callOrder.first()) { // callOrder.first().setFeed(this.feedPrice); // } // }); // this.marketCallOrders = this.marketCallOrders.filter(callOrder => { // if (callOrder) { // return callOrder.isMarginCalled(); // } else { // return false; // } // }); // Update orderbook this._orderBook(true, true); // Update depth chart data this._depthChart(); } } _getFeed() { if (!this._marketHasCalls()) { this.bitasset_options = null; this.is_prediction_market = false; return null; } const assets = { [this.quoteAsset.get("id")]: { precision: this.quoteAsset.get("precision") }, [this.baseAsset.get("id")]: { precision: this.baseAsset.get("precision") } }; let settlePrice = this[ this.invertedCalls ? "baseAsset" : "quoteAsset" ].getIn(["bitasset", "current_feed", "settlement_price"]); try { let sqr = this[this.invertedCalls ? "baseAsset" : "quoteAsset"].getIn([ "bitasset", "current_feed", "maximum_short_squeeze_ratio" ]); this.is_prediction_market = this[ this.invertedCalls ? "baseAsset" : "quoteAsset" ].getIn(["bitasset", "is_prediction_market"], false); this.bitasset_options = this[ this.invertedCalls ? "baseAsset" : "quoteAsset" ] .getIn(["bitasset", "options"]) .toJS(); /* Prediction markets don't need feeds for shorting, so the settlement price can be set to 1:1 */ if ( this.is_prediction_market && settlePrice.getIn(["base", "asset_id"]) === settlePrice.getIn(["quote", "asset_id"]) ) { const backingAsset = this.bitasset_options.short_backing_asset; if (!assets[backingAsset]) assets[backingAsset] = { precision: this.quoteAsset.get("precision") }; settlePrice = settlePrice.setIn(["base", "amount"], 1); settlePrice = settlePrice.setIn(["base", "asset_id"], backingAsset); settlePrice = settlePrice.setIn(["quote", "amount"], 1); settlePrice = settlePrice.setIn( ["quote", "asset_id"], this.quoteAsset.get("id") ); sqr = 1000; } const feedPrice = new FeedPrice({ priceObject: settlePrice, market_base: this.quoteAsset.get("id"), sqr, assets }); return feedPrice; } catch (err) { console.error( this.activeMarket, "does not have a properly configured feed price" ); return null; } } _orderBook(limitsChanged = true, callsChanged = false) { // Loop over limit orders and return array containing bids let constructBids = orderArray => { let bids = orderArray .filter(a => { return a.isBid(); }) .sort((a, b) => { return a.getPrice() - b.getPrice(); }) .map(order => { return order; }) .toArray(); // Sum bids at same price if (bids.length > 1) { for (let i = bids.length - 2; i >= 0; i--) { if (bids[i].getPrice() === bids[i + 1].getPrice()) { bids[i] = bids[i].sum(bids[i + 1]); bids.splice(i + 1, 1); } } } return bids; }; // Loop over limit orders and return array containing asks let constructAsks = orderArray => { let asks = orderArray .filter(a => { return !a.isBid(); }) .sort((a, b) => { return a.getPrice() - b.getPrice(); }) .map(order => { return order; }) .toArray(); // Sum asks at same price if (asks.length > 1) { for (let i = asks.length - 2; i >= 0; i--) { if (asks[i].getPrice() === asks[i + 1].getPrice()) { asks[i] = asks[i].sum(asks[i + 1]); asks.splice(i + 1, 1); } } } return asks; }; // Assign to store variables if (limitsChanged) { if (__DEV__) console.time("Construct limit orders " + this.activeMarket); this.marketData.bids = constructBids(this.marketLimitOrders); this.marketData.asks = constructAsks(this.marketLimitOrders); if (!callsChanged) { this._combineOrders(); } if (__DEV__) console.timeEnd("Construct limit orders " + this.activeMarket); } if (callsChanged) { if (__DEV__) console.time("Construct calls " + this.activeMarket); this.marketData.calls = this.constructCalls(this.marketCallOrders); this._combineOrders(); if (__DEV__) console.timeEnd("Construct calls " + this.activeMarket); } // console.log("time to construct orderbook:", new Date() - orderBookStart, "ms"); } constructCalls(callsArray) { let calls = []; if (callsArray.size) { calls = callsArray .sort((a, b) => { return a.getPrice() - b.getPrice(); }) .map(order => { if (this.invertedCalls) { this.lowestCallPrice = !this.lowestCallPrice ? order.getPrice(false) : Math.max(this.lowestCallPrice, order.getPrice(false)); } else { this.lowestCallPrice = !this.lowestCallPrice ? order.getPrice(false) : Math.min(this.lowestCallPrice, order.getPrice(false)); } return order; }) .toArray(); // Sum calls at same price if (calls.length > 1) { for (let i = calls.length - 2; i >= 0; i--) { calls[i] = calls[i].sum(calls[i + 1]); calls.splice(i + 1, 1); } } } else { this.lowestCallPrice = null; } return calls; } _combineOrders() { const hasCalls = !!this.marketCallOrders.size; const isBid = hasCalls && this.marketCallOrders.first().isBid(); let combinedBids, combinedAsks; if (isBid) { combinedBids = this.marketData.bids.concat(this.marketData.calls); combinedAsks = this.marketData.asks.concat([]); } else { combinedBids = this.marketData.bids.concat([]); combinedAsks = this.marketData.asks.concat(this.marketData.calls); } let totalToReceive = new Asset({ asset_id: this.quoteAsset.get("id"), precision: this.quoteAsset.get("precision") }); let totalForSale = new Asset({ asset_id: this.baseAsset.get("id"), precision: this.baseAsset.get("precision") }); combinedBids .sort((a, b) => { return b.getPrice() - a.getPrice(); }) .forEach(a => { totalToReceive.plus(a.amountToReceive(true)); totalForSale.plus(a.amountForSale()); a.setTotalForSale(totalForSale.clone()); a.setTotalToReceive(totalToReceive.clone()); }); totalToReceive = new Asset({ asset_id: this.baseAsset.get("id"), precision: this.baseAsset.get("precision") }); totalForSale = new Asset({ asset_id: this.quoteAsset.get("id"), precision: this.quoteAsset.get("precision") }); combinedAsks .sort((a, b) => { return a.getPrice() - b.getPrice(); }) .forEach(a => { totalForSale.plus(a.amountForSale()); totalToReceive.plus(a.amountToReceive(false)); a.setTotalForSale(totalForSale.clone()); a.setTotalToReceive(totalToReceive.clone()); }); this.marketData.lowestAsk = !combinedAsks.length ? nullPrice : combinedAsks[0]; this.marketData.highestBid = !combinedBids.length ? nullPrice : combinedBids[0]; this.marketData.combinedBids = combinedBids; this.marketData.combinedAsks = combinedAsks; } _depthChart() { let bids = [], asks = [], calls = [], totalBids = 0, totalAsks = 0, totalCalls = 0; let flat_bids = [], flat_asks = [], flat_calls = [], flat_settles = []; if (this.marketLimitOrders.size) { this.marketData.bids.forEach(order => { bids.push([ order.getPrice(), order.amountToReceive().getAmount({ real: true }) ]); totalBids += order.amountForSale().getAmount({ real: true }); }); this.marketData.asks.forEach(order => { asks.push([ order.getPrice(), order.amountForSale().getAmount({ real: true }) ]); }); // Make sure the arrays are sorted properly asks.sort((a, b) => { return a[0] - b[0]; }); bids.sort((a, b) => { return a[0] - b[0]; }); // Flatten the arrays to get the step plot look flat_bids = market_utils.flatten_orderbookchart_highcharts( bids, true, true, 1000 ); if (flat_bids.length) { flat_bids.unshift([0, flat_bids[0][1]]); } flat_asks = market_utils.flatten_orderbookchart_highcharts( asks, true, false, 1000 ); if (flat_asks.length) { flat_asks.push([ flat_asks[flat_asks.length - 1][0] * 1.5, flat_asks[flat_asks.length - 1][1] ]); totalAsks = flat_asks[flat_asks.length - 1][1]; } } /* Flatten call orders if there any */ if (this.marketData.calls.length) { let callsAsBids = this.marketData.calls[0].isBid(); this.marketData.calls.forEach(order => { calls.push([ order.getSqueezePrice(), order[ order.isBid() ? "amountToReceive" : "amountForSale" ]().getAmount({ real: true }) ]); }); // Calculate total value of call orders calls.forEach(call => { if (this.invertedCalls) { totalCalls += call[1]; } else { totalCalls += call[1] * call[0]; } }); if (callsAsBids) { totalBids += totalCalls; } else { totalAsks += totalCalls; } // Make sure the array is sorted properly calls.sort((a, b) => { return a[0] - b[0]; }); // Flatten the array to get the step plot look if (this.invertedCalls) { flat_calls = market_utils.flatten_orderbookchart_highcharts( calls, true, false, 1000 ); if ( flat_asks.length && flat_calls[flat_calls.length - 1][0] < flat_asks[flat_asks.length - 1][0] ) { flat_calls.push([ flat_asks[flat_asks.length - 1][0], flat_calls[flat_calls.length - 1][1] ]); } } else { flat_calls = market_utils.flatten_orderbookchart_highcharts( calls, true, true, 1000 ); if (flat_calls.length > 0) { flat_calls.unshift([0, flat_calls[0][1]]); } } } /* Flatten settle orders if there are any */ if (this.marketSettleOrders.size) { flat_settles = this.marketSettleOrders.reduce((final, a) => { if (!final) { return [ [ a.getPrice(), a[!a.isBid() ? "amountForSale" : "amountToReceive"]().getAmount({ real: true }) ] ]; } else { final[0][1] = final[0][1] + a[!a.isBid() ? "amountForSale" : "amountToReceive"]().getAmount({ real: true }); return final; } }, null); if (!this.feedPrice.inverted) { flat_settles.unshift([0, flat_settles[0][1]]); } else { flat_settles.push([ flat_asks[flat_asks.length - 1][0], flat_settles[0][1] ]); } } // Assign to store variables this.marketData.flatAsks = flat_asks; this.marketData.flatBids = flat_bids; this.marketData.flatCalls = flat_calls; this.marketData.flatSettles = flat_settles; this.totals = { bid: totalBids, ask: totalAsks, call: totalCalls }; } onGetMarketStats(payload) { let price = new Price({ base: new Asset({ amount: 1 * payload.latest.latest * Math.pow(10, payload.base.get("precision")), asset_id: payload.base.get("id"), precision: payload.base.get("precision") }), quote: new Asset({ amount: 1 * Math.pow(10, payload.quote.get("precision")), asset_id: payload.quote.get("id"), precision: payload.quote.get("precision") }) }); if (payload) { let stats = { close: null, // price: payload.latest.latest, price, change: payload.latest.percent_change, volumeBase: parseInt(payload.latest.base_volume), volumeQuote: parseInt(payload.latest.quote_volume), volumeBaseAsset: new Asset({ amount: payload.latest.base_volume, asset_id: payload.base.get("id"), precision: payload.base.get("precision") }), volumeQuoteAsset: new Asset({ amount: payload.latest.base_volume, asset_id: payload.quote.get("id"), precision: payload.quote.get("precision") }) }; this.allMarketStats = this.allMarketStats.set(payload.market, stats); } } onSettleOrderUpdate(result) { this.updateSettleOrders(result); } updateSettleOrders(result) { if (result.settles && result.settles.length) { const assets = { [this.quoteAsset.get("id")]: { precision: this.quoteAsset.get("precision") }, [this.baseAsset.get("id")]: { precision: this.baseAsset.get("precision") } }; this.marketSettleOrders = this.marketSettleOrders.clear(); result.settles.forEach(settle => { // let key = settle.owner + "_" + settle.balance.asset_id; settle.settlement_date = new Date(settle.settlement_date); this.marketSettleOrders = this.marketSettleOrders.add( new SettleOrder( settle, assets, this.quoteAsset.get("id"), this.feedPrice, this.bitasset_options ) ); }); } } } export default alt.createStore(MarketsStore, "MarketsStore"); <file_sep>import { IEO_API as API_URL } from "./../api/apiConfig"; // export const API_URL = __DEV__ // ? "https://ieo-apitest.cybex.io/api/cybex/" // : __TEST__ // ? "https://ieo-apitest.cybex.io/api/cybex/" // : "//eto.cybex.io/api/cybex/"; export const PERSONAL_TRADE = `${API_URL}/cybex/trade/list?cybex_name=alec-2216&page=1&limit=1`; export const getTradeUrl = account => `${API_URL}/cybex/trade/list?cybex_name=${account}&page=1&limit=1000`; export const getProjects = () => {}; <file_sep>import DashboardContainer from "./components/Dashboard/DashboardContainer"; import Witnesses from "./components/Explorer/Witnesses"; import CommitteeMembers from "./components/Explorer/CommitteeMembers"; import FeesContainer from "./components/Blockchain/FeesContainer"; import BlocksContainer from "./components/Explorer/BlocksContainer"; import AssetsContainer from "./components/Explorer/AssetsContainer"; import AccountsContainer from "./components/Explorer/AccountsContainer"; import Explorer from "components/Explorer/Explorer"; import AccountPage from "./components/Account/AccountPage"; import AccountOverview from "./components/Account/AccountOverview"; import AccountAssets from "./components/Account/AccountAssets"; import {AccountAssetCreate} from "./components/Account/AccountAssetCreate"; import AccountAssetUpdate from "./components/Account/AccountAssetUpdate"; import AccountMembership from "./components/Account/AccountMembership"; import AccountVesting from "./components/Account/AccountVesting"; import AccountDepositWithdraw from "./components/Account/AccountDepositWithdraw"; import AccountPermissions from "./components/Account/AccountPermissions"; import AccountWhitelist from "./components/Account/AccountWhitelist"; import AccountVoting from "./components/Account/AccountVoting"; import AccountOrders from "./components/Account/AccountOrders"; import ExchangeContainer from "./components/Exchange/ExchangeContainer"; import MarketsContainer from "./components/Exchange/MarketsContainer"; import Transfer from "./components/Transfer/Transfer"; import SettingsContainer from "./components/Settings/SettingsContainer"; import BlockContainer from "./components/Blockchain/BlockContainer"; import Asset from "./components/Blockchain/Asset"; import CreateAccount from "./components/Account/CreateAccount"; import CreateAccountPassword from "./components/Account/CreateAccountPassword"; import CreateSelector from "./components/CreateSelector"; import {ExistingAccount, ExistingAccountOptions} from "./components/Wallet/ExistingAccount"; import { WalletCreate, CreateWalletFromBrainkey } from "./components/Wallet/WalletCreate"; import ImportKeys from "./components/Wallet/ImportKeys"; import Invoice from "./components/Transfer/Invoice"; import {BackupCreate, BackupRestore} from "./components/Wallet/Backup"; import WalletChangePassword from "./components/Wallet/WalletChangePassword"; import {WalletManager, WalletOptions, ChangeActiveWallet, WalletDelete} from "./components/Wallet/WalletManager"; import BalanceClaimActive from "./components/Wallet/BalanceClaimActive"; import BackupBrainkey from "./components/Wallet/BackupBrainkey"; import Brainkey from "./components/Wallet/Brainkey"; import Help from "./components/Help"; import InitError from "./components/InitError"; import CreateWorker from "./components/Account/CreateWorker"; <file_sep>const endEvents = []; const EVENTS = { transitionend: { transition: "transitionend", WebkitTransition: "webkitTransitionEnd", MozTransition: "mozTransitionEnd", msTransition: "MSTransitionEnd", OTransition: "oTransitionEnd" }, animationend: { animation: "animationend", WebkitAnimation: "webkitAnimationEnd", MozAnimation: "mozAnimationEnd", msAnimation: "MSAnimationEnd", OAnimation: "oAnimationEnd" } }; if (typeof window !== "undefined") { const style = document.createElement("div").style; for (let eventType in EVENTS) { if (!EVENTS.hasOwnProperty(eventType)) { continue; } const prefixes = EVENTS[eventType]; for (let styleProp in prefixes) { if (prefixes.hasOwnProperty(styleProp) && styleProp in style) { endEvents.push(prefixes[styleProp]); break; } } } } const TransitionEvents = { addEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { setTimeout(eventListener, 0); return; } endEvents.forEach(function(event) { node.addEventListener(event, eventListener, false); }); }, removeEndEventListener: function(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function(event) { node.removeEventListener(event, eventListener, false); }); } }; export default TransitionEvents; <file_sep>```html <Trigger open='my-notify'> <a className='button'>Static notifications</a> </Trigger> <Notification.Static id='my-notify' title="My static notification" image=""> <p>This notification is static, it works similarly to a programmatic with some subtle differences</p> </Notification.Static> ```<file_sep>export const QTB_ASSETS = new Set([ "1.3.674", "QTBHDP", "QTBGLN", "QTBNST", "QTBSOU", "QTBWON", "WON", "CYBET", "HDP", "GLN" ]); export const OPERATIONS = { fill_order: "operation.qtb.fill_order", asset_global_settle: "operation.qtb.asset_global_settle", call_order_update: "operation.qtb.call_order_update", asset_settle: "operation.qtb.asset_settle", limit_order_create: "operation.qtb.limit_order_create", limit_order_cancel: "operation.qtb.limit_order_cancel" }; <file_sep>export * from "./Button"; export * from "./LabelOption"; export * from "./TabLink"; export * from "./Icon"; export * from "./Checkbox"; export * from "./Radio"; export * from "./NavItem"; export * from "./Colors"; export * from "./Styles"; export * from "./FlexGrowDivider"; export * from "./Input"; export * from "./Panel"; export * from "./ProgressBar"; export * from "./TipMark"; export * from "./utils";<file_sep>function parseData(parse) { return function(d) { d.date = parse(d.date); d.open = +d.open; d.high = +d.high; d.low = +d.low; d.close = +d.close; d.volume = +d.volume; // console.debug("D: ", d); return d; }; } const parseDate = date => new Date(date); // const parseDate = timeFormat("%Y-%m-%d %H:%M"); // const parseDate = timeFormat("%Y-%m-%d"); export function handleStockData(data) { return data.map(parseData(parseDate)); // return tsvParse(data, parseData(parseDate)); } <file_sep>import * as React from "react"; import Animation from "../utils/animation"; var foundationApi = require("../utils/foundation-api"); var Notification = require("./notification"); var NotificationSet = React.createClass({ getInitialState: function() { return { notifications: [] }; }, componentDidMount: function() { foundationApi.subscribe( this.props.id, function(name, msg) { if (msg === "clearall") { this.clearAll(); } else { this.addNotification(msg); } }.bind(this) ); }, addNotification: function(notification) { notification.id = foundationApi.generateUuid(); var notifications = this.state.notifications.concat(notification); this.setState({ notifications: notifications }); }, removeNotifcation: function(id) { return function(e) { var notifications = []; this.state.notifications.forEach(function(notification) { if (notification.id !== id) { notifications.push(notification); } }); this.setState({ notifications: notifications }); e.preventDefault(); }.bind(this); }, clearAll: function() { this.setState({ notifications: [] }); }, render: function() { var notifications = this.state.notifications.map( function(notification) { return ( <Notification key={notification.id} {...notification} closeHandler={this.removeNotifcation(notification.id)} className="is-active" > {notification.content} </Notification> ); }.bind(this) ); return <div>{notifications}</div>; } }); export default NotificationSet; export { NotificationSet }; <file_sep>export const DEFAULT_LOGOUT_MODAL_ID = "cybexLogoutModal"; export const DEFAULT_SUPPORT_MODAL = "support_modal"; export const DEFAULT_ETO_CHECK_TOKEN = "DEFAULT_ETO_CHECK_TOKEN"; export const DEFAULT_HTLC_REDEEM_MODAL = "DEFAULT_HTLC_REDEEM_MODAL"; <file_sep>import * as PropTypes from "prop-types"; import * as React from "react"; var _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError( "Super expression must either be null or a function, not " + typeof superClass ); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : (subClass.__proto__ = superClass); } var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _ConnectBase2 = require("./ConnectBase"); var _ConnectBase3 = _interopRequireDefault(_ConnectBase2); export default function(Component) { var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; return (function(_ConnectBase) { _inherits(_class, _ConnectBase); _createClass(_class, null, [ { key: "displayName", value: "Stateful" + (Component.displayName || Component.name) + "Container", enumerable: true }, { key: "contextTypes", value: Component.contextTypes || config.contextTypes || {}, enumerable: true } ]); function _class(props, context) { _classCallCheck(this, _class); _get(Object.getPrototypeOf(_class.prototype), "constructor", this).call( this, props, context ); this.setConnections(props, context, config); } _createClass(_class, [ { key: "render", value: function render() { return _react2["default"].createElement( Component, _extends( { flux: this.flux }, this.props, this.getNextProps() ) ); } } ]); return _class; })(_ConnectBase3["default"]); }
da61e0e8c333602d90af8efb9ffe9bc34cee452b
[ "reStructuredText", "JavaScript", "Markdown", "TypeScript", "Shell" ]
222
TypeScript
CybexDex/cybex-web
edac7da6764a50e400e214d8d2ec370d1c5a1fec
e26c3f1af250c7b2149d31d1d029389bd806d07f
refs/heads/master
<repo_name>Omyun/OMY<file_sep>/README.md #-*-coding:utf8-*-<br> import requests<br> import pymysql<br> import time<br> import colorama<br> import urllib.parse<br> <br> 所有包含的外部库文件<br> class Mysql<br> db_list数据库配置 #lib.db_list调用<br> run_sql(sql) 运行sql语句。 #不返回结果<br> run_sql_beark(sql) 运行sql语句返回查询结果<br> <br><br> class Url<br> url_code(list) 把元组存入,返回url编码机构后的数据 {"aa":"bb","cc":123} 返回 aa=bb&cc=123<br> str_pure(str) 把str字符串格式化去掉特殊符号。返回格式化后的结果 ["'","(",")","\\","*","|","/","-",";"]<br> <br> class Web GET(url,head,pro) 3个参数分别为url,head头部,pro是否代理,不使用代理传0,使用代理传本地代理的端口号<br> POST(url,head,data,pro) 比get多一个post data,需要post提交的数据从这里传入。<br> download_img(url,file) 下载图片,url,存放路径(需要包含文件名)<br> download_video(url,file) 下载视频 如上<br><br> class heart:<br> run_heart("lib\open.txt",20,"close.txt") #一个简易的心跳监测 <br><file_sep>/lib/Cat.py #-*-coding:utf8-*- import requests import pymysql import time import colorama import urllib.parse import base64 colorama.init(autoreset=True) lettime = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) #requests.packages.urllib3.disable_warnings() #抑制ssl错误 db_list ={ "localhost":"127.0.0.1", "port":3306, "db":"jingdong", "user":"root", "pass":"<PASSWORD>", } class Mysql: def run_sql(self,sqlx):#不返回查询结果 self.conn = pymysql.connect(host=db_list['localhost'],port=db_list['port'],user=db_list['user'],password=db_list['pass'],database=db_list['db'],charset="utf8") #链接数据库 self.cursor = self.conn.cursor()#创建数据库游标 self.cursor.execute(sqlx)#载入sql self.conn.commit()#执行sql self.cursor.close()#关闭mysql def run_sql_beark(self,sql): #会返回查询结果。 self.conn = pymysql.connect(host=db_list['localhost'],port=db_list['port'],user=db_list['user'],password=db_list['pass'],database=db_list['db'],charset="utf8") #链接数据库 self.cursor = self.conn.cursor()#创建数据库游标 self.sql = sql self.cursor.execute(sql) self.results = self.cursor.fetchall() self.conn.commit()#执行sql self.cursor.close()#关闭mysql return self.results class Url: def url_code(self,data): self.list = str(urllib.parse.urlencode(data)) self.list = self.list.replace("+", "") self.list = self.list.replace("/", '%2f') return self.list def str_pure(self,x): self.tempr = str(x) self.list = ["'","(",")","\\","*","|","/","-",";"] for self.key in self.list: self.tempr = self.tempr.replace(self.key, " ") return str(self.tempr) def base64x(self,strx,code): self.data = "" if code ==1: self.data = base64.b64encode(bytes(strx.encode('utf-8'))) if code ==2: self.data = base64.b64decode(strx) self.data = self.data.decode("utf-8") return str(self.data) class Web: def GET(self,url,head,pro): if pro!=0: self.proxies = {'http': 'http://localhost:'+pro, 'https':'http://localhost:'+pro} self.httpdata = requests.get(url,headers=head,verify=False,proxies=self.proxies) else: self.httpdata = requests.get(url,headers=head,verify=False) return self.httpdata.text def POST(self,url,head,data,pro): if pro!=0: self.proxies = {'http': 'http://localhost:'+pro, 'https':'http://localhost:'+pro} self.httpdata = requests.post(url,headers=head,data=data,verify=False,proxies=self.proxies) else: self.httpdata = requests.post(url,headers=head,data=data,verify=False) return self.httpdata.text def download_img(self,url,file): self.r = requests.get(url, stream=True) self.status = self.r.status_code if self.status == 200: open(str(file), 'wb').write(self.r.content) # 将内容输出到文件 del self.r return self.status def download_video(self,url,file): self.r = requests.get(url, stream=True) self.status = self.r.status_code if self.status == 200: open(str(file), 'wb').write(self.r.content) # 将内容输出到文件 del self.r return self.status class heart: #run_heart("lib\open.txt",20,"close.txt") def run_heart(self,filex):#心跳 self.tims = str(time.time())#时间戳心跳包 self.filename = filex with open(self.filename, 'w') as self.file_object: self.file_object.write(self.tims) def wlop(self,text,jg): self.filename = jg with open(self.filename, 'w+') as self.file_object: self.file_object.write(str(text)) def run_heart_see(self,filec,nx,jg): #监测的文件,判定掉线的次数,一次为3秒推荐20次(60秒),结果输出文件 self.rk = "" self.n = 1 self.f = open(filec,'r') self.rk = str(self.f.read()) self.f.close self.wlop("open",jg) #初始化结果状态 while True: self.f = open(filec,'r') self.rks = str(self.f.read()) if self.rk == self.rks: print("\033[33m[一致状态]",self.rks,self.n,"次") self.n += 1 else: self.n = 1 print("\033[32m[心跳]",self.rks) self.rk = self.rks self.f.close if self.n > nx: print("\033[31m[进程结束]判定无心跳") self.wlop("close",jg) #修改结果状态 exit() time.sleep(3)
d005f784c260bf1f2b313b5194d2e403bae79627
[ "Markdown", "Python" ]
2
Markdown
Omyun/OMY
e6d54cb784dce537b5c688ab6a3e5aab4fbec192
7e393be5d47d1e3b14231a81f1b1f08f53f13694
refs/heads/master
<repo_name>caraya/static-gen<file_sep>/src/pages/voice-ui-agent.md # building a conversation agent I love the idea of talking to my phone for more than just making calls. Tools like Alexa, Google Assistant and others allow you to create voice interactions, either one off or repeating. In this post I'll use Google Assistant to create a voice search interface for this blog as an Google Assistant agent. We'll explore Voice User Interfaces, How to integrate the blog's search functionality with Assistant and how well it works. ## Voice User Interface Tools like Siri, Google Assistant and Alexa provide 2 way voice conversation between the app and the user through custom actions or programs to accomplish single or groups of tasks. This is different than using [Speech Recognition](https://w3c.github.io/speech-api/#speechreco-section) and [Speech Synthesis API](https://developers.google.com/web/updates/2014/01/Web-apps-that-talk-Introduction-to-the-Speech-Synthesis-API) to create communication between users and the apps ## Google Assistant, Actions on Google, and Dialog Flow I will concentrate in Google Assistant, the Google competitor to Cortana (from Microsoft) and Alexa (from Amazon) for these examples. Before we start we'll define some of the technologies and products that we'll use in this project and <dl> <dt>Assistant</dt> <dd>The application that we use actions with, either with voice of the keyboard</dd> <dt>Actions On Google</dt> <dd>Actions on Google is the platform that lets you create software (actions) to extend the functionality of the Google Assistant</dd> <dt>Action</dt> <dd>The actual applications that provide conversational interfaces to products or services.<dd> <dd>The entry point into an interaction that you build for the Assistant. Users can request your Action by typing or speaking to the Assistant.</dd> <dt>Dialog Flow</dt> <dd>The tool used to build actions for Google Assistant</dd> <dd>You can code the functions entirely on Dialog Flow using built-in intents or you can create web hooks to connect to third party services <dt>Cloud Functions</dt> <dd>Google Cloud Functions is a serverless execution environment for building and connecting cloud services. Your Cloud Function is triggered when an event being watched is fired and it executes in a fully managed environment</dd> <dd>In this project I've chosen to work with <a href="https://firebase.google.com/products/functions/?gclid=Cj0KCQiAwc7jBRD8ARIsAKSUBHLyvGIXm5EmR1z9fie2EOhz0RjOh4sIqRrXxV01t_nh0c9DsrBWprAaAo3FEALw_wcB">Cloud Functions for Firebase</a> rather than host my own server to host them</dd> </dl> ## Building the action The high-level concept for the action is as follows: 1. The user requests the action 1. The action replies with an acknowledgment and an initial request for words to search 1. The user speaks or types the term they want to search 1. The action triggers the cloud function and the function provides a response including the search results 1. The action replies with the results from the function ## To Publish or not to publish ## Conclusion ## Links and resources * [Designing for Interaction Modes](https://alistapart.com/article/designing-for-interaction-modes) * [Designing Voice User Interfaces](https://books.google.com/books/about/Designing_Voice_User_Interfaces.html?id=MmnEDQAAQBAJ&printsec=frontcover#v=onepage&q&f=false) &mdash; <NAME> &mdash; O'Reilly * [Conversational Design](https://abookapart.com/products/conversational-design) &mdash; Erika Hall &mdash; A Book Apart * [Conversations with Robots: Voice, Smart Agents & the Case for Structured Content](https://alistapart.com/article/conversations-with-robots) <file_sep>/src/pages/javascript-dom.md # Using Javascript to manipulate the DOM ## Inserting new elements: The simple version ```html <div id="container"></div> ``` ```js const button = document.createElement("button"); const container = document.getElementById("container"); button.id = "clicky"; button.innerHTML = "Click Me"; container.appendChild(button); ``` * you can’t currently add an attribute to the element when it's created; you must use `setAttribute` or similar method elsewhere on the script * You may think about adding an `id` attribute to the element, but it’s unlikely that you need to do so. You already have a reference to the element when you create it. * Only reason why you may need an id or class is if you'll reference the element from a separate script * Once you add the element to the page, it will follow all the rules you apply via CSS, either a stylesheet, or Javascript ## Inserting new elements: insertAdjacentHTML ```html <aside id="sidecontent"></aside> ``` ```js const sidecontent = document.getElementById("sidecontent"); sidecontent.insertAdjacentHTML("beforebegin", "<p>Day after day</p>"); sidecontent.insertAdjacentHTML("afterbegin", "<h1>Add It Up</h1>"); sidecontent.insertAdjacentHTML("beforeend", "<p>But the day after today</p>"); sidecontent.insertAdjacentHTML("afterend", "<p>I will stop</p>"); ``` <file_sep>/src/pages/latex-to-web.md # Using Latex to build web content Latex is an old-school language for document typesetting. It was created by <NAME> to typeset his book The Art of Computer Science. You still see LaTex in scientific articles and papers If you're only familiar with HTML, Latex syntax will look strange. Rather than tags and attributes we have a preamble, package declarations and intructions. A basic LaTex article, set to print in portrait mode with a body text size of 12 points looks like this: ```tex \usepackage{amssymb} \usepackage{epstopdf} % Broken into two lines for readability. In production % the command would go in one line \DeclareGraphicsRule{.tif}{png}{.png} {`convert #1 `dirname #1`/`basename #1 .tif`.png} \title{Brief Article} \author{The Author} %\date{} % Activate to display a given date or no date \begin{documen \maketitle \section{} \subsection{} \end{document} ``` `documentclass` indicates what type of document we want to creaate the parameters (font size in this case) is in square brackets `[]` `\usepackage{}` loads modules for use into the document Commands that start with a backslash, like `\geometry{}` and `\DeclareGraphhicsRule{}` are instructions that will generate output of some kind for the document. ## Converting Latex to HTML I like LaTex but I'm still a fan of the web and I want to make sure that whatever I create in LaTex is also available on the web, assuming the publisher allows me to :) There are two ways to create HTML content from LaTex files. The first one is `tex4ht` or `htlatex` and the second one is `make4ht`, an abstraction on top of tex4ht that simplifies adding options to the different pieces of the configuration. <p>The rest of the article uses the tex file from <a href="https://gist.github.com/caraya/69a45d08d03214d78779a7d0a60da083">this gist</a> as the source for the commands.</p> <div class="message info"> </div> ### tex4ht tex4ht converts LaTex sources into one or more HTML documents with a very (and I mean very) basic style sheet that you can customize and expand as needed. The most basic command will create a single page for all the content along with the corresponding image ```bash htlatex article.tex ``` For shorter articlles the single-file approach may be ok (with customized styles) but for larger files or articles with larger sections it may prove harder to read online. We can break the arcile down into multiple files based on the headings on the document. The example below will generate mutliple files and it will also generate navigation links within the pages of the document. The styles, as with the previous document can definitely be enchanced. ```bash htlatex article.tex "html,index=2,3,next" ``` For those interested, you can also convert your LaTex to Docbook 5.0. While you can also convert it to TEI, it fails to convert the file successfully and I'm not certain why as the document converts succesfully to Docbook. ```bash # Conversion to Docbook htlatex article.tex "xhtml,docbook" " -cunihtf" "-cdocbk" # Conversion to TEI htlatex article.tex "xhtml,tei" " -cunihtf" "-cdocbk" ``` ### make4ht As we've discussed `tex4ht` system supports several output formats with multiple steps and multiple parameters possible for each step and format combination. I just want to make sure this is visible as it'll save a lot of time if you know it exists and where you can find its documentation. The most basic version of the htlatex command will convert the TeX file into HTML using UTF-8 as the encoding: ```bash make4ht -uf html5 filename.tex ``` When you just add new text to your TeX document, without cross-references, or new additions to the table of contents, you can use `draft` mode which will invoke LaTeX only once. It can save quite a lot of the compilation time: ```bash make4ht -um draft -f html5 filename.tex ``` As with many things in the TeX universe there are a lot of configuratuion options. I'm deliberately not covering them both to keep the post from balloning in size and to avoid confusion; I'll assume that you know where to find the documentation if you need it. ## Items to research and conclusion Using LaTeX as the source for documents presents some clear advantages and some interesting challenges. TeX and LaTeX were designed from the start to work as print typesetting languages and the quality of the printed result is clearly better than what we can get from HTML alone. Particularly with `make4ht` there are many questions left to answer. Sone of the questions that merit additional research: * Would the output of the tool using the `staticsite` extension be good enough for static sites other than Jekyll? * Is the output in `Tei` and `Docbook` good enough to feed to their corresponding processing toolchains? If not what additional changes do we need to make? * Is it worth learning Lua just to automate one type of task for one tool? ## Links and resources * [tex4ht](https://www.tug.org/tex4ht/) * [Tex4ht: HTML Production](https://www.tug.org/TUGboat/tb25-1/gurari.pdf) * [make4ht](https://github.com/michal-h21/make4ht/blob/master/README.md) * [tex4ebook](https://github.com/michal-h21/tex4ebook/blob/master/README.md) <file_sep>/src/pages/from-markdown-to-html.md # Different Options for generating HTML from Markdown [Markdown](https://en.wikipedia.org/wiki/Markdown) is my favorite way to write. It is lightweight, regquiring a few characters to convey the meaning of the text, it's supported in both many places, including Github and Wordpress (via Jetpack) so I don't need to change the way I write to publish in different places and it only needs a text editor to create (for me, so does HTML but that's another story). In this article we'll look at different ways to take Markdown input and convert it to HTML for web view. ## Markdown to HTML in a build process This process is part of the build for my writing process and covers both HTML and PDF generation from the same Markdown source. I've created an HTML template to place the Markdown-produced HTML Inside of. It does three things: 1. Defines the CSS that the document will load 2. Defines the document metadata: charset, viewport and title 3. Defines the container and the placeholder for the generated HTML 4. Defines the scripts we want the page to run at the bottom of the document. We could also place them on the head and use `defer` but we don't really need to ```html <html lang="en" dir="ltr" class="no-js lazy"> <head> <!-- 1 --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/image-load.css"> <link rel="stylesheet" href="css/video-load.css"> <link rel="stylesheet" href="css/prism.css"> <!-- 2 --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <!-- 3 --> <article class="container"> <%= contents %> </article> <!-- 4 --> <script src="scripts/lazy-load.js"></script> <script src="scripts/vendor/clipboard.min.js"></script> <script src="scripts/vendor/prism.js"></script> <script src="scripts/vendor/fontfaceobserver.standalone.js"></script> <script src="scripts/load-fonts.js"></script> <script src="scripts/lazy-load-video.js"></script> </body> </html> ``` Before we run the build file we need to make sure that all the dependcies for [Gulp](https://gulpjs.com/) are installed and updated. I'm lazy and haven't updated the code to work with Gulp 4.0 so I'm sticking to 3.9 for this example. ```bash npm install gulp@3.9.1 gulp-newer gulp-remarkable \ gulp-wrap gulp-exec remarkable ``` The first step is to load the plugins as we would in any other Gulp file or Node project ```js const gulp = require('gulp'); // Gulp const newer = require('gulp-newer'); // Newer const markdown = require('gulp-remarkable'); // Markdown plugin const wrap = require('gulp-wrap'); // Wrap const exec = require('gulp-exec'); // Exec ``` Then we define the first task, `markdown`, to generate HTML from our Markdown sources. We take all the Markdown files and, if they are newer than files in the target directory, we run them through the [Remarkable](https://github.com/jonschlinkert/remarkable) Gulp Plugin. ```js gulp.task('markdown', () => { return gulp.src('src/md-content/*.md') .pipe(newer('src/html-content/')) .pipe(markdown({ preset: 'commonmark', typographer: true, remarkableOptions: { typographer: true, linkify: true, breaks: false, }, })) .pipe(gulp.dest('src/html-content/')); }); ``` Remarkable doesn't generate full or well-formed docs, it just converts the Markdown into HTML and, since we don't have a well-formed HTML document in Markdown (not what it was designed for), we only get the body of the document. To make it into a well-formed HTML document we need to put the Markdown inside an HTML document. We use the `gulp-wrap` plugin to do so. The result is that for each Markdown file we converted to HTML we now have a well-formed HTML document with links to stylesheets and scripts ready to be put in production. ```js gulp.task('build-template', ['markdown'], () => { gulp.src('./src/html-content/*.html') .pipe(wrap({src: './src/templates/template.html'})) .pipe(gulp.dest('./src/')); }); ``` ## PDF? Why Not? We can use a similar technique to generate PDF files from our content. We'll leverage the same framework than we did for generating HTML with a different template and using third party tools. _We need to be careful not to insert HTML markup into the Markdown we want to use to generate PDF as the PDF generators tend to not be very happy with videos and, to my not very happy face, fail completely rather than ignoring the markup they don't understand._ The template is smaller as it doesn't require the same number of scripts and stylesheets. Two things to note: * We're using a different syntax highlighter (Highlight.js instead of Prism) * We chose not to add the stylesheet here ```html <html lang="en"> <head> <link rel="stylesheet" href="../paged-media/highlight/styles/solarized-light.css"> <script src="../paged-media/highlight/highlight.pack.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1"> <title></title> </head> <body data-type="article"> <div class="container"> <%= contents %> </div> </body> </html> ``` The first step is to create the HTML files using the appropriate template after we generate the HTML from the Markdown content. ```js gulp.task('build-pm-template', () => { gulp.src('./src/html-content/*.html') .pipe(wrap({src: './src/templates/template-pm.html'})) .pipe(gulp.dest('./src/pm-content')); }); ``` The next step is where the differences lie. Instead of just generating the HTML and being done with it, we have to push the HTML through a CSS paged media processor. I've used [PrinceXML](https://www.princexml.com/) to generate PDF from multiple sources with different inputs (XML, HTML and XSL-FO) so we're sticking with it for this project. I use a second stylesheet that has all the font definitions and styles for the document. I've made [article-styles.css](https://gist.github.com/caraya/8d12c8bbfb07681b4d5b56dfeecc88bc) available as Github GIST The final bit is how we run PrinceXML in the build process. I know that `gulp-exec` is not well liked in the Gulp community but none of the alternatives I've found don't do quite what I needed to, so `gulp-exec` it is. The idea is that, for each file in the source directory, we run prince with the command given. ```js gulp.task('build-pdf', ['build-pm-template'], () => { return gulp.src('./src/pm-content/*.html') .pipe(newer('src/pdf/')) .pipe(exec('prince --verbose --input=html --javascript --style ./src/css/article-styles.css <%= file.path %> ')) .pipe(exec.reporter()); }); ``` So we've gone from Markdown to HTML and Markdown to PDF. A next step may be how we can populate Handlebar or Dust templates from our Markdown sources. <file_sep>/src/pages/css-containment.md # CSS Containment <figure> <img src="http://publishing-project.rivendellweb.net/wp-content/uploads/2019/03/css-is-awesome.jpg" alt=""> <figcaption>Containment may help prevent this and make CSS even more awesome :)</figcaption> </figure> Whenever we insert HTML elements after the document loads by inserting new CCSS rules or new elements via Javascript, we may be slowing down the rendering of the page because every change means the browser has to navigate all the elements in scope and re-render them as needed, they may have been moved or changed their dimensions when our target element grew smaller or larger; **Layout is almost always scoped to the entire document** meaning that the browser will navigate all the way to the begnning of the document to calculate sizes and layout for the document. If you have a lot of elements, it’s going to take a long time to figure out their locations and dimensions. The `contain` CSS property allows an author to indicate that an element and its contents are, **as much as possible**, independent of the rest of the document tree. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page. It can take one or more of the following values: <dl> <dt><code>size</code></dt> <dd>The size of the element can be computed without checking its children, the element dimensions are independent of its contents.</dd> <dt><code>layout</code></dt> <dd>The internal layout of the element is totally isolated from the rest of the page, it’s not affected by anything outside and its contents cannot have any effect on the ancestors.</dd> <dt><code>style</code></dt> <dd>Indicates that, for properties that can have effects on more than just an element and its descendants, those effects don't escape the containing element.</dd> <dd>The style values has been marked <code>at risk</code> and, as such, it may not make it to the final recomendation. Mozilla has already dropped it from Firefox.</dd> <dt><code>paint</code></dt> <dd>Descendants of the element cannot be displayed outside its bounds, nothing will overflow this element (or if it does it won’t be visible).</dd> </dl> In addition there are two grouping values that shorten what you type as the value of the attribute: <dl> <dt>strict</dt> <dd>This value turns on all forms of containment except style contain for the element. It behaves the same as <code>contain: size layout paint</code></dd> <dt>content</dt> <dd>This value turns on all forms of containment <em>except</em> size containment and style containment for the element. It behaves the same as <code>contain: layout paint;</code>. </dl> When we add the `newly-added-element` element to the page, it will trigger styles, layout and paint but, one thing we need to consider, is that the DOM for the whole document is in scope. The browser will have to consider all the elements irrespective of whether or not they were changed when it comes to styles layouts and paint. The bigger the DOM, the more computation work the browser has to do, meaning that your app may become unresponsive to user input in lager documents. In addition to what the browser already does to help with scoping of your CCSS, you can use the scope property of CSS as an additional indicator of how the browser should handle layout, size and paint containment. In the example below adding the `new-element` div will cause styles, layout and paint redraw of the whole document tree. For illustration we haven't added content to the HTML but you can imagine how large it can become, particularly in a single page application. ```html <section class="view"> Home </section> <section class="view container"> About <div class="new-element">Check me out!</div> </section> <section class="view"> Contact </section> ``` In CSS we can use containmnet to help the browser out with optimizations. It would be temmpting to use `strict` for all items that we want to use containment for but we need to know the dimensions ahead of time and include them in our CSS otherwise the element might be rendered as a 0px by 0px box. Test everything thoroughly both in browsers that support containment and those that don't support it. Content containment (`contains: content`) offers significant scope improvements, without having to specify the dimensions of the element ahead of time. You should look at `contain: content` as your default and treat `contain: strict` as an escape hatch when `contain: content` doesn't quite cut the mustard. To make sure that the layout and paint for our `new-element` div don't affect the rest of the document, we can use a rule like this: ```css .new-element { contain: content; /* the rest of the rules for the class */ } ``` ## Links and resources * [An introduction to CSS Containment](https://blogs.igalia.com/mrego/2019/01/11/an-introduction-to-css-containment/) * [CSS Containment Module Level 1](https://www.w3.org/TR/css-contain-1/) * [Can I use: CSS containment](https://caniuse.com/#feat=css-containment) * [CSS Triggers](https://csstriggers.com/) &mdash; What gets triggered by mutating a given property * [CSS Containment in Chrome 52](https://developers.google.com/web/updates/2016/06/css-containment) * [Avoid Large, Complex Layouts and Layout Thrashing](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing) * [CSS Contain](https://developer.mozilla.org/en-US/docs/Web/CSS/contain) <file_sep>/gulpfile.js /* eslint no-unused-vars: 0, max-len: 0, no-trailing-spaces: 0 */ 'use strict'; // Require Gulp first const gulp = require('gulp'); // packageJson = require('./package.json'), const runSequence = require('run-sequence'); const del = require('del'); const extReplace = require('gulp-ext-replace'); // Markdown and templates const markdown = require('gulp-remarkable'); const wrap = require('gulp-wrap'); // CSS stuff const sass = require('node-sass'); // postcss const postcss = require('gulp-postcss'); const autoprefixer = require('autoprefixer'); // JS Stuff const babel = require('gulp-babel'); const sourcemaps = require('gulp-sourcemaps'); // Imagemin and Plugins const imagemin = require('gulp-imagemin'); const mozjpeg = require('imagemin-mozjpeg'); const webp = require('imagemin-webp'); // Static Web Server stuff const browserSync = require('browser-sync'); // const reload = browserSync.reload; const historyApiFallback = require('connect-history-api-fallback'); /** * @name markdown * @description converts markdown to HTML */ /** * @name markdown * @description converts markdown to HTML */ gulp.task('markdown', () => { return gulp.src('src/pages/*.md') .pipe(markdown({ preset: 'commonmark', html: true, remarkableOptions: { html: true, typographer: true, linkify: true, breaks: false, }, })) .pipe(gulp.dest('src/converted-md/')); }); gulp.task('build-template', ['markdown'], () => { return gulp.src('./src/converted-md/*.{md}') .pipe(wrap({ src: './src/templates/template.html', })) .pipe(extReplace('.html')) .pipe(gulp.dest('docs/')); }); gulp.task('build-html-template', () => { return gulp.src('./src/pages/*.html') .pipe(wrap({ src: './src/templates/template.html', })) .pipe(gulp.dest('docs/')); }); // SCSS conversion and CSS processing /** * @name sass * @description SASS conversion task to produce development css with expanded syntax. * * We run this task agains Ruby SASS, not lib SASS. As such it requires the SASS Gem to be installed * * @see {@link http://sass-lang.com|SASS} * @see {@link http://sass-compatibility.github.io/|SASS Feature Compatibility} */ gulp.task('sass', function() { return gulp.src('src/sass/**/*.scss') .pipe(sass({ sourcemap: true, style, expanded, }) .on('error', sass.logError)) .pipe(gulp.dest('./css')); }); /** * @name processCSS * * @description Run autoprefixer on the CSS files under src/css * * Moved from gulp-autoprefixer to postcss. It may open other options in the future * like cssnano to compress the files * * @see {@link https://github.com/postcss/autoprefixer|autoprefixer} */ gulp.task('processCSS', function() { // What processors/plugins to use with PostCSS const PROCESSORS = [ autoprefixer({ browsers: ['last 3 versions'], }), ]; return gulp.src('src/css/**/*.css') .pipe(sourcemaps.init()) .pipe(postcss(PROCESSORS)) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('docs/css')); }); /** * @name babel * @description Transpiles ES6 to ES5 using Babel. As Node and browsers support more of the spec natively this will move to supporting ES2016 and later transpilation * * It requires the `@babel/core`, and `@babel/preset-env` * * @see {@link http://babeljs.io/|Babel} * @see {@link http://babeljs.io/docs/learn-es2015/|Learn ES2015} * @see {@link http://www.ecma-international.org/ecma-262/6.0/|ECMAScript 2015 specification} */ gulp.task('babel', function() { return gulp.src('src/es6/**/*.js') .pipe($.sourcemaps.init()) .pipe($.babel({ presets: ['@babel/preset-env'], })) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest('src/js/')); }); /** * @name imagemin * @description Reduces image file sizes. Doubly important if we'll choose to play with responsive images. * * Imagemin will compress jpg (using mozilla's mozjpeg), SVG (using SVGO) GIF, WebP and PNG images but WILL NOT create multiple versions for use with responsive images * * @see {@link processImages} */ gulp.task('imagemin', function() { return gulp.src('src/images/**/*') .pipe(imagemin([ imagemin.gifsicle({ interlaced: true, }), imagemin.optipng({ optimizationLevel: 5, }), imagemin.svgo({ plugins: [{removeViewBox: true}, {cleanupIDs: false}, ], }), webp({ quality: 80, }), mozjpeg(), ])) .pipe(gulp.dest('docs/images')); }); /** * @name clean * @description deletes specified files */ gulp.task('clean', function() { return del.sync([ 'docs/', 'src/converted-md/*.{html, md}', ]); }); gulp.task('serve', function() { browserSync({ port: 2509, notify: false, snippetOptions: { rule: { match: '<span id="browser-sync-binding"></span>', fn: (snippet) => { return snippet; }, }, }, server: { baseDir: ['.tmp', 'docs'], middleware: [historyApiFallback()], }, }); }); /** * @name default * @description uses clean, processCSS, build-template, imagemin to build the HTML content from Markdown source */ gulp.task('default', function() { runSequence('clean', 'processCSS', 'build-template', 'build-html-template', 'imagemin'); });
5d1d4bb7019b7b22dd07bc5fde377ee2dc92eb1b
[ "Markdown", "JavaScript" ]
6
Markdown
caraya/static-gen
dd314e16ac86d74bd076b16b8cd6275d4c6d1e9e
5bc9d0b8e1f1af7c7b889c6e0628cdf4dfe87f5d
refs/heads/master
<repo_name>1483795887/costmgnweb<file_sep>/src/dao/contractDAO.js import post from '../common/post' export default { getContracts(type, callback) { post('/api/contract/getContracts', type, callback); }, getContract(id, callback) { post('/api/contract/getContract', id, callback); }, addContract(contract, callback) { post('/api/contract/addContract', contract, callback); }, updateContract(value, callback) { post('/api/contract/updateContract', value, callback); }, submitContracts(idList, callback) { post('/api/contract/submitContract', idList, callback); }, approveContracts(value, callback) { post('/api/contract/approveContract', value, callback); }, refuseContracts(value, callback) { post('/api/contract/refuseContract', value, callback); } }<file_sep>/src/dao/userDAO.js const user1 = { id: 1, userid: "20200300001", name: '张三', department: '生产', post: '业务员' } const user2 = { id: 2, userid: "20200300002", name: '李四', department: '生产', post: '部门经理' } const user3 = { id: 3, userid: "20200300003", name: '王五', department: '管理', post: '系统管理员' } const user4 = { id: 4, userid: "20200300004", name: '赵六', department: '财务', post: '会计' } const users = [ user1, user2, user3, user4 ] import post from '../common/post' export default { getDummyUsers() { return users; }, getUsers(callback) { post('/api/user/getUserList', null, callback); }, addUser(user, callback) { post('/api/user/addUser', user, callback); }, login(userid, password, callback) { post('/api/user/login', { userid: userid, password: password }, callback); }, updatePassword(data, callback) { post('/api/user/updatePassword', data, callback); }, removeUser(data, callback) { post('/api/user/removeUser', data, callback); } }<file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import account from './modules/account' import createVuexAlong from 'vuex-along' Vue.use(Vuex) export default new Vuex.Store({ modules: { account }, plugins: [createVuexAlong({ name: "hello-vuex-along", session: { list: ["account"] } })] })<file_sep>/src/common/contract.js export default { payMethods: { PAY_METHOD_CASH: '现金支付', PAY_METHOD_RECEIPT: '支票支付', PAY_METHOD_CARD: '银行卡支付', }, payRequests: { PAY_REQUEST_ONCE:'一次付清', PAY_REQUEST_INSTALL:'分期付款' } }<file_sep>/babel.config.js module.exports = { "env": { "development": { "sourceMaps": true, "retainLines": true } }, presets: ["@vue/app"], plugins: [ [ "import", { libraryName: "ant-design-vue", libraryDirectory: "es", style: "css" } ] ] } <file_sep>/src/router/routes.js import Vue from 'vue' import VueRouter from 'vue-router' import Main from '../layout/MainLayout.vue' import UpdatePassword from '../pages/user/UpdatePassword' import Login from '../pages/login/Login' import WorkCur from '../pages/main/WorkCur' import WorkToDo from '../pages/main/WorkToDo' import PlanManage from '../pages/plan/PlanManage' import PlanView from '../pages/plan/PlanView' import PlanInfo from '../pages/plan/PlanInfo' import PlanAudit from '../pages/plan/PlanAudit' import PlanAdd from '../pages/plan/PlanAdd' import PlanUpdate from '../pages/plan/PlanUpdate' import ContractManage from '../pages/contract/ContractManage' import ContractView from '../pages/contract/ContractView' import ContractAudit from '../pages/contract/ContractAudit' import ContractAdd from '../pages/contract/ContractAdd' import ContractUpdate from '../pages/contract/ContractUpdate' import ContractInfo from '../pages/contract/ContractInfo' import PageView from '../layout/PageView' import WelcomeView from '../layout/WelcomeView' import BudgetManage from '../pages/budget/BudgetManage' import BudgetView from '../pages/budget/BudgetView' import BudgetAudit from '../pages/budget/BudgetAudit' import BudgetAdd from '../pages/budget/BudgetAdd' import BudgetUpdate from '../pages/budget/BudgetUpdate' import BudgetCost from '../pages/budget/BudgetCost' import BudgetOccupy from '../pages/budget/BudgetOccupy' import CostView from '../pages/cost/CostView' import CostAdd from '../pages/cost/CostAdd' import CostUpdate from '../pages/cost/CostUpdate' import CostAudit from '../pages/cost/CostAudit' import CostManage from '../pages/cost/CostManage' import UserList from '../pages/user/UserList' import UserAdd from '../pages/user/UserAdd' import Result404 from '../pages/results/404' import NoPower from '../pages/results/noPower' import Result500 from '../pages/results/500' Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', base: __dirname, linkActiveClass: "active", routes: [ { name: '登录页', path: '/login', component: Login }, { name: 'Main', path: '/', redirect: '/login', component: Main, children: [ { path: '/work', name: '主页', redirect: '/work/workCur', component: WelcomeView, children: [ { path: '/work/workCur', name: '当前事务', component: WorkCur }, { path: '/work/workToDo', name: '待办事务', component: WorkToDo } ] }, { path: '/user', name: 'user', component: PageView, children: [ { path: '/user/changePassword', name: '修改密码', component: UpdatePassword }, { meta: { post: [2] }, path: '/user/userList', name: '员工列表', component: UserList }, { meta: { post: [2] }, path: '/user/userAdd', name: '增加员工', component: UserAdd } ] }, { path: '/plan', name: '方案', component: PageView, children: [ { meta: { post: [0] }, path: '/plan/planManage', name: '方案维护', component: PlanManage }, { meta: { post: [1] }, path: '/plan/planAudit', name: '方案审计', component: PlanAudit }, { path: '/plan/planView', name: '查看方案', component: PlanView }, { meta: { post: [0] }, path: '/plan/planUpdate/:id', name: '方案更新', component: PlanUpdate }, { path: '/plan/planInfo/:id', name: '方案详情', component: PlanInfo }, { meta: { post: [0] }, path: '/plan/planAdd', name: '方案新增', component: PlanAdd } ] }, { path: '/contract', name: '合同', component: PageView, children: [ { meta: { post: [0] }, path: '/contract/contractManage', name: '合同维护', component: ContractManage }, { meta: { post: [1] }, path: '/contract/contractAudit', name: '合同审计', component: ContractAudit }, { path: '/contract/contractView', name: '查看合同', component: ContractView }, { meta: { post: [0] }, path: '/contract/contractUpdate/:id', name: '合同更新', component: ContractUpdate }, { path: '/contract/contractInfo/:id', name: '合同详情', component: ContractInfo }, { meta: { post: [0] }, path: '/contract/contractAdd', name: '新增合同', component: ContractAdd } ] }, { path: '/budget', name: '预算', component: PageView, children: [ { meta: { post: [1] }, path: '/budget/budgetManage', name: '预算维护', component: BudgetManage }, { meta: { post: [2] }, path: '/budget/budgetAudit', name: '预算审计', component: BudgetAudit }, { meta: { post: [1, 2] }, path: '/budget/budgetView', name: '查看预算', component: BudgetView }, { meta: { post: [1] }, path: '/budget/budgetUpdate/:id', name: '预算更新', component: BudgetUpdate }, { meta: { post: [1] }, path: '/budget/budgetAdd', name: '新增预算', component: BudgetAdd }, { meta: { post: [1, 2] }, path: '/budget/budgetCost/:id', name: '预算费用', component: BudgetCost }, { meta: { post: [1] }, path: '/budget/budgetOccupy', name: '预算占用', component: BudgetOccupy } ] }, { path: '/cost', name: '费用', component: PageView, children: [ { path: '/cost/costView', name: '查看费用', component: CostView }, { meta: { post: [1] }, path: '/cost/costAudit', name: '费用审计', component: CostAudit }, { meta: { post: [0] }, path: '/cost/costManage', name: '费用维护', component: CostManage }, { pmeta: { post: [0] }, path: '/cost/costCostAdd/:id', name: '费用更新', component: CostUpdate }, { meta: { post: [0] }, path: '/cost/costAdd', name: '新增费用', component: CostAdd } ] } ] }, { path: "/error/404", name: "404", component: Result404 }, { path: "/error/noPower", name: "noPower", component: NoPower }, { path: "/error/500", name: "500", component: Result500 } ] }) router.beforeEach((to, from, next) => { let user = JSON.parse(sessionStorage.getItem("user")); if (to.path == '/login') { if (user) { next({ name: '主页' }) } else { next(); } } else { if (!user) { next({ name: '登录页' }) } else { if (to.matched.length != 0) { //next(); if (to.meta.post != null && to.meta.post.indexOf(user.post) == -1) { next({ name: 'noPower' }); } else { next(); } } else { next({ name: '404' }) } } } }) export default router;<file_sep>/src/components/menu/Menu.js const commonMenuItem = { name: 'work', icon: 'home', title: '工作', children: [ { name: 'workCur', to: '当前事务', title: "事务状态" }, { name: 'workToDo', to: '待办事务', title: "待办事务" } ] } export default { SalesmanMenu: [ commonMenuItem, { name: 'plan', icon: 'bulb', title: '方案', children: [ { name: 'planManage', to: '方案维护', title: '方案维护' }, { name: 'planView', to: '查看方案', title: '查看方案' } ] }, { name: 'contract', icon: 'solution', title: '合同', children: [ { name: 'contractManage', to: '合同维护', title: '合同维护' }, { name: 'contractView', to: '查看合同', title: '查看合同' } ] }, { name: 'cost', icon: 'transaction', title: '费用', children: [ { name: 'costManage', to: '费用维护', title: '费用维护' }, { name: 'costView', to: '查看费用', title: '查看费用' } ] } ], DepartmentManagerMenu: [ commonMenuItem, { name: 'plan', icon: 'bulb', title: '方案', children: [ { name: 'planAudit', to: '方案审计', title: '方案审计' }, { name: 'planView', to: '查看方案', title: '查看方案' } ] }, { name: 'contract', icon: 'solution', title: '合同', children: [ { name: 'contractAudit', to: '合同审计', title: '合同审计' }, { name: 'contractView', to: '查看合同', title: '查看合同' } ] }, { name: 'budget', icon: 'account-book', title: '预算', children: [ { name: 'budgetManage', to: '预算维护', title: '预算维护' }, { name: 'budgetView', to: '查看预算', title: '查看预算' } ] }, { name: 'cost', icon: 'transaction', title: '费用', children: [ { name: 'costAudit', to: '费用审计', title: '费用审计' }, { name: 'costView', to: '查看费用', title: '查看费用' } ] } ], SystemManagerMenu: [ commonMenuItem, { name: 'plan', icon: 'bulb', title: '方案', children: [ { name: 'planView', to: '查看方案', title: '查看方案' } ] }, { name: 'contract', icon: 'solution', title: '合同', children: [ { name: 'contractView', to: '查看合同', title: '查看合同' } ] }, { name: 'budget', icon: 'account-book', title: '预算', children: [ { name: 'budgetAudit', to: '预算审计', title: '预算审计' }, { name: 'budgetView', to: '查看预算', title: '查看预算' } ] }, { name: 'cost', icon: 'transaction', title: '费用', children: [ { name: 'costView', to: '查看费用', title: '查看费用' } ] }, { name: 'user', icon: 'idcard', title: '员工管理', children: [ { name: 'userList', to: '员工列表', title: '员工列表' } ] } ], getMenu(user) { switch (user.post) { case 0: return this.SalesmanMenu; case 1: return this.DepartmentManagerMenu; case 2: return this.SystemManagerMenu; } } }<file_sep>/src/common/post.js import request from './request' export default function post(url, data, onSuccess) { request({ url: url, method: 'post', data: JSON.stringify(data) }).then(result => { if (result.status == 200) onSuccess(result.data); else console.log(result.statusText); }).catch(error => { console.log(error); }) }<file_sep>/src/dao/workDAO.js import post from '../common/post' export default { getCurWorks(callback) { post('/api/work/getCurWorks', null, callback); }, getToDoWorks(callback) { post('/api/work/getToDoWorks', null, callback); } }<file_sep>/src/common/const.js import UserData from "./user" export default { getDepartment(no) { return UserData.postDepartmentOption[no].label; }, getPost(no) { switch (no) { case 0: return '业务员'; case 1: return "部门经理"; case 2: return "系统管理员"; } }, getStatus(no) { switch (no) { case 0: return "未提交"; case 1: return "未审核"; case 2: return "未通过"; case 3: return "被退回"; case 4: return "已通过"; } }, getType(no) { switch (no) { case 0: return "方案"; case 1: return "合同"; case 2: return "预算"; case 3: return "费用"; } } }<file_sep>/src/common/user.js const normalPost = [ { value: 0, label: '业务员' }, { value: 1, label: '部门经理' } ] export default { postDepartmentOption: [ { value: 0, label: '生产', children: normalPost }, { value: 1, label: '营销', children: normalPost }, { value:2, label: '管理', children: [ { value: 0, label: '系统管理员' } ] } ] }<file_sep>/src/common/Date.js export function datedifference(sDate1, sDate2) { //sDate1和sDate2是2006-12-18格式 var dateSpan; sDate1 = Date.parse(sDate1); sDate2 = Date.parse(sDate2); dateSpan = sDate2 - sDate1; dateSpan = Math.abs(dateSpan); var iDays = Math.floor(dateSpan / (24 * 3600 * 1000)); return iDays; } export function getDateFromString(strDate){ var dateArr = strDate.split('-'); var year = parseInt(dateArr[0]); var month = parseInt(dateArr[1]); var day = parseInt(dateArr[2]); return getRealDate(year, month, day); } export function formatDate(date) { let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); return year + '-' + (month < 10 ? ('0' + month) : month) + '-' + (day < 10 ? ('0' + day) : day); } export function getRealDate(year, month, day) { return new Date(year, month - 1, day); } export function getToday() { return new Date(); } export function getLastYearDate(date) { return getRealDate(date.getFullYear() - 1, date.getMonth() + 1, date.getDate()); } export function getThisSunday(date) { return getRealDate(date.getFullYear(), date.getMonth() + 1, date.getDate() - date.getDay()); } export function getThisMonth(date) { return getRealDate(date.getFullYear(), date.getMonth() + 1, 1); }
cebda69c8454d690c23ecdf6c05a3d07549ea117
[ "JavaScript" ]
12
JavaScript
1483795887/costmgnweb
dfa2893902c98c073e8ff00209b6a22af4bb4844
67de538708cd2a5589000c81790eb8b8476adb6f
refs/heads/main
<repo_name>elegomf/TcpDiscoveryAdapter<file_sep>/tcpDiscoverAdapter.go package main import ( "encoding/binary" "fmt" "net" "os" "os/signal" "strings" "sync" "syscall" "time" ) var TIME time.Duration = 10000000000 var Reset = "\033[0m" var Red = "\033[31m" var Green = "\033[32m" var Yellow = "\033[33m" var Blue = "\033[34m" var Purple = "\033[35m" var Cyan = "\033[36m" var Gray = "\033[37m" var White = "\033[97m" var verbose = false var warnings = false func main() { if containsLower(os.Args, "help") || containsLower(os.Args, "--help") { println("Usage: exeName 80 [-v] [-w]") return } if containsLower(os.Args, "v") || containsLower(os.Args, "-v") { verbose = true } if containsLower(os.Args, "w") || containsLower(os.Args, "-w") { warnings = true } SetupCloseHandler() println("\n\tSearching network responses on port " + os.Args[1] + "\n") wg := sync.WaitGroup{} ifaces, err := net.Interfaces() if err != nil { println("Error ocurred on get adapters: " + err.Error()) os.Exit(1) } for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { println("Error ocurred on get adapter address: " + err.Error()) continue } // handle err for _, addr := range addrs { ScanNetwork(addr.String(), os.Args[1], &wg) } } wg.Wait() os.Exit(0) } func ScanNetwork(network string, port string, wg *sync.WaitGroup) { if strings.HasPrefix(network, "169.254.") || strings.HasPrefix(network, "127.0") { return } _, ipv4Net, err := net.ParseCIDR(network) if err != nil { println("Error: ." + network + ". - " + err.Error()) println(strings.Join(os.Args, ",")) return } mask := binary.BigEndian.Uint32(ipv4Net.Mask) start := binary.BigEndian.Uint32(ipv4Net.IP) finish := (start & mask) | (mask ^ 0xffffffff) for i := start; i < finish; i++ { ip := make(net.IP, 4) binary.BigEndian.PutUint32(ip, i) wg.Add(1) go TestPort(ip.String(), os.Args[1], wg) } for i := 1; i < 255; i++ { } } func TestPort(addr string, port string, wg *sync.WaitGroup) { defer wg.Done() start := time.Now() tcpAddr, err := net.ResolveTCPAddr("tcp", addr+":"+os.Args[1]) if err != nil { if verbose { println(Gray + "[!] " + addr + " - " + Reset + " Is warning") } return } conn, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { if verbose || warnings { show := verbose elapsed := time.Since(start) color := Red symbol := "-" if elapsed < TIME { color = Yellow symbol = "!" show = warnings } if show { println(color + "[" + symbol + "] " + port + " - Is closed " + Reset + addr) } } return } else { println(Green + "[+] " + port + " Is Open " + Reset + addr) } conn.Close() } func containsLower(s []string, e string) bool { for _, a := range s { if strings.ToLower(a) == e { return true } } return false } func SetupCloseHandler() { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c fmt.Println("\n\r- Ctrl+C pressed in Terminal") os.Exit(0) }() } <file_sep>/README.md # TcpDiscoveryAdapter Simple network discover using a tcp port and response time Usage: exeName 80 [-v] [-w] Example: Usage: tcpDiscover.exe 80 -w
90da5705d81dab864e1288db13a455b33065834c
[ "Markdown", "Go" ]
2
Go
elegomf/TcpDiscoveryAdapter
85d85be9dc7c14084af23c867bb53c06667a16a4
8264527384809b5c1e03eb2e0c30ecf3867e62a5