text stringlengths 7 3.69M |
|---|
// the variables...
// let b = color('blue');
// let g = color('green');
// let r = color('red');
function setup() {
createCanvas(400, 400);
}
function draw() {
background(500);
let b = color("lightblue");
//fill the shape with color
fill(b);
// the shape length and width and type
rect(100, 100, 100, 100);
let g = color("purple");
fill(g);
circle(50, 50, 50);
let r = color("pink");
fill(r);
rect(50, 200, 50, 200);
}
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
main: {
files: [{
expand: true,
src: ['jquery.selectric.js'],
dest: 'dist/',
filter: 'isFile'
}]
}
},
usebanner: {
dist: {
options: {
position: 'top',
banner: '\/*!\r\n * ,\/\r\n * ,\'\/\r\n * ,\' \/\r\n * ,\' \/_____,\r\n * .\'____ ,\'\r\n * \/ ,\'\r\n * \/ ,\'\r\n * \/,\'\r\n * \/\'\r\n *\r\n * Selectric \u03DE v<%= pkg.version %> - http:\/\/lcdsantos.github.io\/jQuery-Selectric\/\r\n *\r\n * Copyright (c) <%= grunt.template.today("yyyy") %> Leonardo Santos; Dual licensed: MIT\/GPL\r\n *\r\n *\/\n',
linebreak: true
},
files: {
src: 'dist/jquery.selectric.js'
}
}
},
uglify: {
build: {
options: {
report: 'gzip',
banner: '/*! Selectric ϟ v<%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd") %>) - git.io/tjl9sQ - Copyright (c) <%= grunt.template.today("yyyy") %> Leonardo Santos - Dual licensed: MIT/GPL */\n'
},
files: {
'dist/jquery.selectric.min.js': ['jquery.selectric.js']
}
}
},
jquerymanifest: {
options: {
source: grunt.file.readJSON('package.json'),
overrides: {
name: "selectric",
title: "jQuery Selectric",
author: {
name: "Leonardo Santos",
email: "leocs.1991@gmail.com"
},
keywords: [ "select", "selectbox", "dropdown", "form", "input", "ui" ],
description: "Fast, simple and light jQuery plugin to customize HTML selects",
licenses: [
{
type: "MIT",
url: "http://opensource.org/licenses/MIT"
},
{
type: "GPL-3.0",
url: "http://opensource.org/licenses/GPL-3.0"
}
],
bugs: "https://github.com/lcdsantos/jQuery-Selectric/issues",
homepage: "http://lcdsantos.github.io/jQuery-Selectric/",
docs: "http://lcdsantos.github.io/jQuery-Selectric/",
demo: "http://lcdsantos.github.io/jQuery-Selectric/demo.html",
dependencies: {
"jquery": ">=1.7"
}
}
}
},
sass: {
dist: {
options: {
outputStyle: 'compressed'
},
files: {
'dist/selectric.css': 'selectric.scss'
}
}
},
cssbeautifier: {
options : {
indent: ' '
},
files : ['dist/selectric.css']
}
});
// Javascript
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-banner');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-jquerymanifest');
// CSS
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-cssbeautifier');
grunt.registerTask('default', ['copy', 'usebanner', 'uglify', 'sass', 'cssbeautifier', 'jquerymanifest']);
};
|
define(['src/util/ui', './getViewInfo'], function (UI, getViewInfo) {
let baseUrl = require.s.contexts._.config.baseUrl;
let pagesURL = `${baseUrl}../../docs/eln/uuid/`;
async function addFullHelp(options = {}) {
const { iconSize = 'fa-3x' } = options;
let target = document.getElementById('modules-grid');
let div = document.createElement('DIV');
div.innerHTML = `
<i style="color: lightgrey; cursor: pointer;" class="fa fa-question-circle ${iconSize}"></i>
`;
div.style.zIndex = 99;
div.style.position = 'fixed';
div.addEventListener('click', async () => {
window.open('https://docs.c6h6.org', 'ELN documentation');
});
target.prepend(div);
}
async function addPageHelp(options = {}) {
const { iconSize = 'fa-3x' } = options;
const info =
options._id === undefined ? await getViewInfo() : { _id: options._id };
if (!info._id) return;
const response = await fetch(`${pagesURL + info._id + '/'}`, {
method: 'HEAD'
});
if (response.status !== 200) return;
let target = document.getElementById('modules-grid');
let div = document.createElement('DIV');
div.innerHTML = `
<i style="color: lightgrey; cursor: pointer;" class="fa fa-question-circle ${iconSize}"></i>
`;
div.style.zIndex = 99;
div.style.position = 'fixed';
div.addEventListener('click', () => {
UI.dialog(
`
<iframe frameBorder="0" width="100%" height="100%" allowfullscreen="true"
src="${pagesURL + info._id + '/'}">
`,
{ width: 950, height: 800, title: 'Information about the page' }
).css('overflow', 'hidden');
});
target.prepend(div);
}
return {
addPageHelp,
addFullHelp
};
});
|
export const ADD_TODO = 'ADD_TODO'
export const COMPLETE_TODO = 'COMPLETE_TODO'
export const DESTROY_TODO = 'DESTROY_TODO'
export const EDIT_TODO = 'EDIT_TODO'
export const TOGGLE_ALL_TODOS = 'TOGGLE_ALL_TODOS'
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
export const CHANGE_FILTER = 'CHANGE_FILTER'
export const FILTERS = {
SHOW_ALL: 'SHOW_ALL',
SHOW_ACTIVE: 'SHOW_ACTIVE',
SHOW_COMPLETED: 'SHOW_COMPLETED'
} |
"use strict";
let ValidateUtils = require("../utils/ValidateUtils");
let CaptchaUtils = require("../utils/CaptchaUtils");
let validate = new ValidateUtils();
let captchaUtils = new CaptchaUtils();
/**
* 验证用户操作时,传入的参数是否合法
* @constructor
*/
function UsersHelp() {
}
//------------------------------------ 根据不同方法进行一次性验证 start ↓ ------------------------------------
// 验证登录数据
UsersHelp.prototype.validateLogin = function (user) {
let UNMsg = this.userNameV(user.userName);
if (UNMsg) {
return UNMsg;
}
let PWDMsg = this.passwordV(user.password);
if (PWDMsg) {
return PWDMsg;
}
return null;
};
//验证注册数据
// username pwd confPWD email phone
UsersHelp.prototype.validateRegister = function (user, req) {
let msg = this.validateLogin(user); // 需要验证的参数有部分和登录验证的一样,这里共用
if (msg) {
return msg;
}
let confPwdMsg = this.confPasswordV(user.password, user.confPassword);
if (confPwdMsg) {
return confPwdMsg;
}
let phoneMsg = this.phoneNumberV(user.phoneNumber);
if (phoneMsg) {
return phoneMsg;
}
let emailMsg = this.emailV(user.email);
if (emailMsg) {
return emailMsg;
}
let captchaMsg = this.captchaCodeV(user.captchaCode, req);
return null;
};
UsersHelp.prototype.validateForgetPWD = function (user, req) {
let msg = this.validateLogin(user); // 需要验证的参数有部分和登录验证的一样,这里共用
if (msg) {
return msg;
}
let confPwdMsg = this.confPasswordV(user.password, user.confPassword);
if (confPwdMsg) {
return confPwdMsg;
}
let smsMsg = this.smsCodeV(user.SMSCode);
if (smsMsg) {
return smsMsg;
}
return null;
};
//------------------------------------ 根据不同方法进行一次性验证 end ↑ ------------------------------------
//------------------------------------ 每个属性分开验证 start ↓ ------------------------------------
UsersHelp.prototype.captchaCodeV = (captchaCode, req) => {
if (captchaCode !== captchaUtils.getCaptchaCode(req)) {
return "图形验证码错误!!";
}
return null;
};
UsersHelp.prototype.smsCodeV = (smsCode) => {
if (smsCode.length !== 4) {
return "短信验证码错误!!!";
}
return null;
};
UsersHelp.prototype.emailV = (email) => {
if (validate.emailCheck(email)) {
return "邮箱格式错误!!";
}
return null;
};
UsersHelp.prototype.phoneNumberV = (phone) => {
if (validate.phoneNumberCheck(phone)) {
return "手机号码错误!!";
}
return null;
};
UsersHelp.prototype.confPasswordV = (pwd, confPWd) => {
if (pwd !== confPWd) {
return "两次密码不一致!!"
}
return null;
};
UsersHelp.prototype.passwordV = (pwd) => {
if (validate.inNull(pwd)) {
return "密码不能为空";
} else if (pwd.length < 6 || pwd.length > 18) {
return "密码格式错误!";
}
return null;
};
UsersHelp.prototype.userNameV = (userName) => {
if (validate.inNull(userName)) {
return "账号不能为空";
} else if (validate.containsSpecialCharacters(userName)) {
return "账号不能有特殊字符";
} else if (userName.length < 8 || userName.length > 18) {
return "账号在8至18位之间!";
}
return null;
};
//------------------------------------ 每个属性分开验证 end ↑ ------------------------------------
module.exports = UsersHelp; |
import express from 'express';
import {createProject, getProjects} from "../services/project.service";
const router = express.Router({});
router.get('/', getProjects);
router.post('/', createProject);
export default router;
|
import { LoginManager, GraphRequest, GraphRequestManager, AccessToken } from 'react-native-fbsdk'
export function FacebookProfile(token) {
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest(
'/me',
{
accessToken: token,
parameters: {
fields: {
string: 'email,name,picture',
},
},
},
(error: ?Object, result: ?Object) => {
if (error) {
// console.log(`Error fetching data: ${error.toString()}`)
return reject(new Error(error.toString()))
}
// console.log('I MIEI DATI !:', result)
return resolve(result)
},
)
new GraphRequestManager().addRequest(infoRequest).start()
})
}
// Attempt a login using the Facebook login dialog,
// asking for default permissions.
export function facebookLoginManager() {
return new Promise((resolve, reject) => {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
// eslint-disable-next-line consistent-return
(result) => {
if (result.isCancelled) {
// console.log('Login was cancelled')
return reject(new Error('Login was cancelled'))
}
// console.log(`Login was successful with permissions:
// ${result.grantedPermissions.toString()}`)
AccessToken.getCurrentAccessToken().then((data) => {
FacebookProfile(data.accessToken)
.then(profileResult => resolve(profileResult))
.catch((err) => {
reject(new Error(err))
})
})
},
(error) => {
// console.log(`Login failed with error: ${error}`)
reject(new Error(error))
},
)
})
}
|
import { before, GET, POST, route } from 'awilix-express'
import { authenticate, verifyAction } from '../ApiController';
import AuthMapper from '../feature/auth/mapper/AuthMapper';
@route('/auth')
export default class AuthController {
constructor(
{
verifyPasswordUseCase,
verifyPinUseCase,
setAuthUseCase,
logoutUseCase,
keepAliveUseCase,
getInfoUseCase,
registerUseCase
}
) {
this.verifyPasswordUseCase = verifyPasswordUseCase;
this.setAuthUseCase = setAuthUseCase;
this.verifyPinUseCase = verifyPinUseCase;
this.logoutUseCase = logoutUseCase;
this.keepAliveUseCase = keepAliveUseCase;
this.getInfoUseCase = getInfoUseCase;
this.registerUseCase = registerUseCase;
}
@POST()
async login(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.getBody(req.body)
const result = await this.verifyPasswordUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/register')
@POST()
async register(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.registerBody(req.body)
await this.registerUseCase.execute(param);
res.status(201).send()
} catch (err) {
next(err)
}
}
@route('/set-password')
@POST()
@before([verifyAction])
async setPassword(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.setPassword(req.body, req.userRefId)
await this.setAuthUseCase.execute(param);
res.status(201).send()
} catch (err) {
next(err)
}
}
@route('/action-info')
@GET()
@before([verifyAction])
async actionInfo(req, res, next) {
try {
const result = await this.getInfoUseCase.execute({userRefId: req.userRefId});
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/verify-password')
@POST()
@before([authenticate])
async verifyPassword(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.verifyPassword(req.body, req.decoded.username)
const result = await this.verifyPasswordUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/keep-alive')
@GET()
@before([authenticate])
async keepAlive(req, res, next) {
try {
const result = await this.keepAliveUseCase.execute({username: req.decoded.username});
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/pin')
@POST()
async loginPin(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.getPinBody(req.body)
const result = await this.verifyPinUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/set-pin')
@POST()
@before([verifyAction])
async setPin(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.setPin(req.body, req.userRefId)
await this.setAuthUseCase.execute(param);
res.status(201).send()
} catch (err) {
next(err)
}
}
@route('/verify-pin')
@POST()
@before([authenticate])
async verifyPin(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.verifyPin(req.body, req.decoded.username)
const result = await this.verifyPinUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
@route('/logout')
@GET()
@before([authenticate])
async logout(req, res, next) {
try {
const mapper = new AuthMapper()
const param = mapper.getUserId(req.decoded._id)
const result = await this.logoutUseCase.execute(param);
res.status(200).send(result)
} catch (err) {
next(err)
}
}
}
|
import {useState} from 'react'
function DisplayArtists(props){
const [artistChoice, setArtistChoice] = useState()
// When the user selects an artist, log the selected artist's/button's ID into artistChoice state
const artistSelect = (event) => {
setArtistChoice(event.target.id)
}
// the selected button will also submit the form, which will take the new artistChoice value & use it as param in getSong API Call
const handleArtistChoice = (event) => {
event.preventDefault()
props.getSong(artistChoice)
}
return (
<div className="bandContainer">
<form action=""
onSubmit={handleArtistChoice}>
<img src={props.photo} alt={props.name} />
<button type='submit' id={props.id} onClick={artistSelect} value={artistChoice} name="artistChoice"> {props.name}</button>
</form>
</div>
)
}
export default DisplayArtists |
import * as types from './types';
import router from '../plugins/router.config'
export default {
[types.VIEW_FOOT]:({state,commit},payload)=>commit(types.VIEW_FOOT,payload),
[types.VIEW_LOADING]:({state,commit},payload)=>commit(types.VIEW_LOADING,payload)
} |
import React, { Component } from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import Modal from "@material-ui/core/Modal";
import history from "../history";
function getModalStyle() {
const top = 50;
const left = 50;
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`
};
}
const styles = theme => ({
paper: {
position: "absolute",
width: theme.spacing.unit * 50,
backgroundColor: theme.palette.background.paper,
boxShadow: theme.shadows[5],
padding: theme.spacing.unit * 4,
outline: "none"
}
});
class StreamModal extends Component {
escFunction = event => {
if (event.keyCode === 27) {
history.push("/");
}
};
componentDidMount() {
document.addEventListener("keydown", this.escFunction, false);
}
render() {
const { paper } = this.props.classes;
return ReactDOM.createPortal(
<div onClick={this.props.onDismiss}>
<Modal
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
open
>
<div
onClick={e => e.stopPropagation()}
style={getModalStyle()}
className={paper}
>
<Typography variant="h6" id="modal-title">
{this.props.title}
</Typography>
<Typography variant="subtitle1" id="simple-modal-description">
{this.props.description}
</Typography>
{this.props.actions}
</div>
</Modal>
</div>,
document.querySelector("#modal")
);
}
}
StreamModal.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(StreamModal);
|
function scroll_windowScrollPercent() {
return window.scrollY / (document.body.offsetHeight - window.innerHeight);
}
function scroll_windowScrollDirection(scroll, scrollLast) {
if (scroll > scrollLast) {
return 1;
} else if (scroll < scrollLast) {
return -1;
} else {
return 0;
}
}
function scroll_linear(scroll, start, stop) {
return (scroll - start) / (stop - start);
}
function scroll_tangent(scroll, start, stop) {
let k = 0.9;
let x = ((scroll - start) / (stop - start)) * (k * Math.PI) - (k * Math.PI / 2);
let shiftY = Math.tan(k * Math.PI / 2);
let rangeY = shiftY * 2;
return (Math.tan(x) + shiftY) / rangeY;
}
|
import React from "react";
import Meta from "components/Meta";
import TextLayout from "layouts/TextLayout";
export default function Terms() {
return (
<TextLayout title={"Privacy Policy"}>
<Meta title={"Privacy Policy"} />
<div className="text-page m-bottom-12 privacy-policy">
<div className="m-bottom-6">
<small>Last updated: May 23, 2018</small>
</div>
<h5>Table of contents:</h5>
<ul className="m-bottom-5">
<li>
<a
href="#introduction"
className="feature-link">
Introduction
</a>
</li>
<li>
<a
href="#usage-information"
className="feature-link">
Usage information
</a>
</li>
<li>
<a
href="#log-information"
className="feature-link">
Log information
</a>
</li>
<li>
<a
href="#account-information"
className="feature-link">
Account information
</a>
</li>
<li>
<a
href="#billing-information"
className="feature-link">
Billing information and Payment details
</a>
</li>
<li>
<a
href="#contact-information"
className="feature-link">
Contact information
</a>
</li>
<li>
<a
href="#sensitive-information"
className="feature-link">
Sensitive information
</a>
</li>
<li>
<a
href="#cookies"
className="feature-link">
Cookies
</a>
</li>
<li>
<a
href="#protect-information"
className="feature-link">
How do we protect your personal information?
</a>
</li>
<li>
<a
href="#legal-rights"
className="feature-link">
Your legal rights
</a>
</li>
<li>
<a
href="#changes"
className="feature-link">
Can this Privacy Policy change?
</a>
</li>
</ul>
<h5 id="introduction">Introduction</h5>
<p>
Resumes are deeply personal documents which reveal a lot about you. Enhancv
values your privacy, so we've developed an easy to understand Privacy Policy
that covers how we collect and use your information.
</p>
<p>
Depending on your relationship with Enhancv, this info may include usage
information, log information, account or billing information, payment details,
contact information. You can understand when we collect and how we treat each
type of data in the sections below.
</p>
<p>
When we refer to “we” and “us”, we mean Enhancv Ltd. which controls the
information collected when you use our services on the Enhancv platform (also
called "service", “product” within this document) to create your resume (or, as
better known in other parts of the world, a CV) or any other document.
</p>
<p>
Keep in mind we never share the information you provide with third parties,
except for chosen partners that are used for the purpose of providing you with a
stable and enjoyable experience when using Enhancv. We have tried to outline
here the main points of how these partners and third party services collect and
use data, but for the most detailed and up-to-date information you should review
their own privacy policies.
</p>
<p>
You always remain in control of your data. You may edit or erase your data from
our services at any time or ask us to update or erase information we store, as
long as this erasure is not in conflict with any legal obligations we may hold
to national and international regulators.
</p>
<p>
By providing us with your data, you warrant to us that you are over 13 years of
age. If this is not the case, you need to contact us immediately to delete any
personally identifiable information from our records.
</p>
<p>
Depending on your relationship with Enhancv, we’d collect different types of
information, as outlined below.
</p>
<h5 id="usage-information">Usage information</h5>
<div className="sub-title">What is it?</div>
<p>
When visiting one of our domains, we will collect information about your
interaction with the site, like pages you visit and specific actions you take
like signing up or sharing one of our{" "}
<a
href="https://enhancv.com/successful-resumes.html"
className="feature-link"
target="_blank">
resume examples.
</a>
</p>
<p>
When using the Enhancv platform for creating your resume, we will collect
information about the way our platform is used, including features used, resume
sections used, number of resumes created, design elements used, etc. All
information you knowingly include in your resume, including email, address,
telephone number, is also stored in our database.
</p>
<p>
This information is collected in combination with data like user location,
Internet browser type, device, operating system, your language preference, or
the referring website you came to us through.
</p>
<p>
If, during the usage of Enhancv, you decide to take advantage of our Invite
Friends feature and decide to invite friends by email, we will collect and store
the email addresses of those friends in order to show you whether they have
subscribed through your link or not, to provide you with the option of resending
the invitation and to remind you which of your friends you’ve already invited.
In all other cases when using the feature (e.g. sharing the link on social media
or as a link in direct messaging platforms), we will only collect referral data,
showing us a person came through your invite link, so that we can assign your
earned credit.
</p>
<div className="sub-title">How do we use it?</div>
<p>
Usage information is used primarily in aggregate for statistical purposes. It
helps us understand which parts of our product are of greatest interest and also
provides information used to improve our platform and develop exciting new
features. This information is shared with our third-party analytics services
(including{" "}
<a
href="http://analytics.google.com/"
className="feature-link"
target="_blank">
Google Analytics
</a>,{" "}
<a
href="http://amplitude.com/"
className="feature-link"
target="_blank">
Amplitude
</a>,{" "}
<a
href="http://intercom.com/"
className="feature-link"
target="_blank">
Intercom
</a>{" "}
and{" "}
<a
href="http://attributionapp.com/"
className="feature-link"
target="_blank">
Attribution App
</a>). Those services operate either within the EU or in accordance with the{" "}
<a
href="https://ec.europa.eu/info/law/law-topic/data-protection/data-transfers-outside-eu/eu-us-privacy-shield_en"
className="feature-link"
target="_blank">
EU-US Privacy Shield
</a>, ensuring the secure transfer of information.
</p>
<p>
Resume content is stored for the purpose of providing you with the primary
service of Enhancv - creating, storing, displaying, and rendering your resume.
This information is stored in JSON format in{" "}
<a
href="https://mlab.com/company/legal/privacy/"
className="feature-link"
target="_blank">
mLab
</a>{" "}
database hosting.
</p>
<p>
Information about your invited friends is sent to{" "}
<a
href="http://mandrillapp.com/"
className="feature-link"
target="_blank">
Mandrill
</a>{" "}
for the purpose of sending out the email invitations.
</p>
<div className="sub-title">Data retention</div>
<p>
Usage information stored in{" "}
<a
href="http://analytics.google.com/"
className="feature-link"
target="_blank">
Google Analytics
</a>{" "}
is kept up to 26 months after your last visit and afterwards used only in
aggregate reports. Usage information in Amplitude, Intercom, and Attribution App
is kept for an indefinite period of time and used only in aggregate to analyze
usage patterns.
</p>
<p>
Resume content is stored for the duration of that resume being kept on our
platform. If you delete your resume or delete your account, all resume content
is instantaneously removed from our database.
</p>
<p>
Information about invited friends is kept within the{" "}
<a
href="http://mandrillapp.com/"
className="feature-link"
target="_blank">
Mandrill
</a>{" "}
platform for 30 days after email sendout.
</p>
<h5 id="log-information">Log information</h5>
<div className="sub-title">What is it?</div>
<p>
Log data contain data about the nature of each access of our services, including
originating Internet Protocol (IP) addresses and endpoint (the requested files
on our platform), as well as timestamps for this activity. Web servers usually
keep log files that record data each time a device accesses those servers.
</p>
<p>
We will also collect error logs which may collect more system data needed to fix
known platform bugs.
</p>
<div className="sub-title">How do we use it?</div>
<p>
Log data is used to analyze platform usage, improve performance and eliminate
any bugs. We primarily look at this information in aggregate, but we might
review individual logs when looking for the cause of a specific issues. This may
happen either by our own initiative or in relation to a request you log with our
customer success team.
</p>
<p>
Only a small part of our engineering team has access to the full platform logs.
</p>
<div className="sub-title">Data retention</div>
<p>
Log data stored on our platform is kept for an indefinite period of time to help
us review potential recurrence of bugs and user issues, and to monitor any
attempts for unauthorised access to our services.
</p>
<h5 id="account-information">Account information</h5>
<div className="sub-title">What is it?</div>
<p>
When you create an account on the Enhancv platform, you may register with your
name, email address and a password you choose. Those are stored in our platform.
</p>
<p>
If you choose to register by using a third-party account (<a
href="http://linkedin.com/"
className="feature-link"
target="_blank">
LinkedIn
</a>{" "}
or{" "}
<a
href="http://facebook.com/"
className="feature-link"
target="_blank">
Facebook
</a>), we receive your personal information (name, profile photo, email, and
work experience information that can be included in your resume) from third
parties if you give permission to those third parties to share your information
with us. Your password for those third-party services is never shared with us.
</p>
<div className="sub-title">How do we use it?</div>
<p>
Account information is used to create your Enhancv account and identify you when
logging into our platform to provide your account’s content.
</p>
<div className="sub-title">Data retention</div>
<p>
Your account information is kept during your account’s lifetime in order to
identify you when logging to the platform. If you delete your account, we keep
your email address in order to resolve following billing issues for the same
user.
</p>
<h5 id="billing-information">Billing information and Payment details</h5>
<div className="sub-title">What is it?</div>
<p>
If you are using one of our{" "}
<a
href="https://enhancv.com/pricing.html"
className="feature-link"
target="_blank">
paid plans
</a>, you need to provide billing information and payment details (credit card
or Paypal account).
</p>
<p>
Payments are processed by{" "}
<a
href="https://www.braintreepayments.com/"
className="feature-link"
target="_blank">
Braintree
</a>, a Level 1 PCI DSS compliant third-party and your credit card info is
safely stored with them. Our partners never share with us payment details - we
never receive your credit card or Paypal account information under any
circumstances.
</p>
<p>
We analyze and review payment trends with the help of{" "}
<a
href="https://baremetrics.com/"
className="feature-link"
target="_blank">
Baremetrics
</a>. Information contains name, user email addresses, information about plan
types and sums paid.
</p>
<div className="sub-title">How do we use it?</div>
<p>
We use your billing information to log payments submitted as part of your plan.
You can view information about all payments you’ve made to us on the{" "}
<a
href="https://app.enhancv.com/billing"
className="feature-link"
target="_blank">
Billing page
</a>{" "}
of your account. You are also able to update your details whenever you need to.
</p>
<p>
Aggregate information about payments is used with statistical purposes and to
execute our legitimate interest of making our business more sustainable.
</p>
<div className="sub-title">Data retention</div>
<p>
We store billing information and a full history of your payments even if you
cancel your subscription or delete your account. This is part of our legal
obligation to keep transaction records for local or international authorities.
We also store your IP address together with your invoice data, so that we pay
tax accordingly and comply with European Tax Law.
</p>
<p>
We never receive or store any payment details - they are kept with our payment
partners. For further information you may refer to{" "}
<a
href="http://www.braintreepayments.com/en-gb/legal/braintree-privacy-policy"
className="feature-link"
target="_blank">
Braintree’s privacy policy
</a>.
</p>
<h5 id="contact-information">Contact information</h5>
<div className="sub-title">What is it?</div>
<p>
If you contact us with a question, through any of our communication channels,
like our{" "}
<a
href="https://help.enhancv.com/"
className="feature-link"
target="_blank">
Help Center
</a>, email, or through our social media accounts on{" "}
<a
href="https://www.facebook.com/enhancv/"
className="feature-link"
target="_blank">
Facebook
</a>,{" "}
<a
href="https://twitter.com/Enhancv"
className="feature-link"
target="_blank">
Twitter
</a>, or{" "}
<a
href="https://www.linkedin.com/company/enhancv/"
className="feature-link"
target="_blank">
LinkedIn
</a>, we will receive and store your contact details, like email, name, or
social media account link.
</p>
<p>
In the case of support queries, we might need additional information to help you
with your request - this will depend on the nature of your query and issue at
hand. We will aim to ask for the minimal additional information needed to solve
your request.
</p>
<p>
You may also provide us with your contact details when subscribing to our
newsletter or product news list. We might also collect information about
categories of interests you provide us with, such as what types of content do
you want to receive from us.
</p>
<div className="sub-title">How do we use it?</div>
<p>
We use your contact information to communicate regarding your query, in the case
of support request, or to send you product updates and helpful materials that
will help you get the most of Enhancv and create a resume you’re proud of.
</p>
<p>
Before we send you any promotional messages or content, we will collect your
explicit consent for doing so. We may send you product news and updates about
our latest features on rare occasions, as this is in line with our commitment
for bringing value to our users, as well as our legitimate interests as service
provider. You can unsubscribe from both types of communication - you will find
an unsubscribe link in the footer of each promotional email we send out. You can
also manage those settings from your{" "}
<a
href="https://app.enhancv.com/profile"
className="feature-link"
target="_blank">
Enhancv Account
</a>. All our email communication is managed through our partners{" "}
<a
href="http://intercom.com"
className="feature-link"
target="_blank">
Intercom
</a>.
</p>
<p>
If you are a registered user of our platform, we will continue sending high
priority information about your account, billing status, changes to our terms of
service and other important topics. This information is an integral part of
providing you our service and is managed either through{" "}
<a
href="http://intercom.com"
className="feature-link"
target="_blank">
Intercom
</a>{" "}
or{" "}
<a
href="http://mandrillapp.com/"
className="feature-link"
target="_blank">
Mandrill
</a>. If you delete your account, you will stop receiving further communication
from us.
</p>
<div className="sub-title">Data retention</div>
<p>
All communication history through our official communication channels between
you and our team is kept in Intercom for future reference, even if your account
is deleted. This is done in order to be able to answer complaints or any future
questions you might have.
</p>
<p>
Contact information used for subscribing to promotional emails or product news
is kept in our active subscriber lists. If you unsubscribe, we will still keep
your contact information on file to prevent future email send-outs.
</p>
<p>
For all types of communication information, you can request that we delete your
data and we’ll do so within a 30 day period.
</p>
<h5 id="sensitive-information">Sensitive information</h5>
<p>
We do not knowingly collect any Sensitive Data about you. Sensitive data refers
to data that includes details about your race or ethnicity, religious or
philosophical beliefs, sex life, sexual orientation, political opinions, trade
union membership, information about your health and genetic and biometric data.
We do not collect any information about criminal convictions and offences. If
you include such information as part of the content of your resume, we would
still not purposefully collect and store this information or disclose to anyone.
</p>
<h5 id="cookies">Cookies</h5>
<div className="sub-title">What is it?</div>
<p>
A "cookie" is a piece of information that is stored on your computer and which
records how you move your way around a website, so that when you revisit that
website, it can present tailored options based on the information stored about
your last visit. Cookies can also be used to analyse traffic and for advertising
and marketing purposes. Cookies are used by nearly all websites and do not harm
your system.
</p>
<p>
Cookies can be session-based - only stored on your computer during your web
session and are automatically deleted when you close your browser - or
persistent - remaining even after you close your browser. Persistent cookies are
stored as a file on your computer and can be read only by the website that
created them when you visit that website again.
</p>
<div className="sub-title">How do we use it?</div>
<p>
We use cookies to track your use of our website. This enables us to understand
how you use the site and track any patterns with regards how you are using our
website. This helps us to develop and improve our platform in response to what
you might need or want.
</p>
<p>
For registered users, our platform uses cookies and HTML5 browser local storage
to save your preferences and authenticate you. The third-party services we use
might also use cookies, pixel tags and other similar technologies.
</p>
<p>
Cookies are also used to pursue our legitimate interests of improving marketing
performance by analyzing the effectiveness of advertising and other promotional
efforts.
</p>
<p>
We use cookies in{" "}
<a
href="http://analytics.google.com/"
className="feature-link"
target="_blank">
Google Analytics
</a>,{" "}
<a
href="http://amplitude.com/"
className="feature-link"
target="_blank">
Amplitude
</a>{" "}
and{" "}
<a
href="http://attributionapp.com/"
className="feature-link"
target="_blank">
Attribution App
</a>{" "}
to analyze aggregate data for the purposes outlined above. We also cookies or
pixel tags for services such as{" "}
<a
href="https://www.facebook.com/"
className="feature-link"
target="_blank">
Facebook
</a>,{" "}
<a
href="http://linkedin.com/"
className="feature-link"
target="_blank">
LinkedIn
</a>, or{" "}
<a
href="https://twitter.com"
className="feature-link"
target="_blank">
Twitter
</a>{" "}
in order to create and manage marketing campaigns
</p>
<div className="sub-title">Deactivating cookies</div>
<p>
You can set your browser to refuse all or some browser cookies, or to alert you
when websites set or access cookies. If you disable or refuse cookies, please
note that some parts of this website may not function properly. You can visit{" "}
<a
href="http://www.aboutcookies.org/"
className="feature-link"
target="_blank">
this page
</a>{" "}
for more information on how to manage and remove cookies across a number of
different internet browsers.
</p>
<p>
You can also deactivate specific 3rd party cookies through the{" "}
<a
href="http://www.youronlinechoices.com"
className="feature-link"
target="_blank">
following page
</a>{" "}
managed by the EDAA (European Interactive Digital Advertising Alliance).
</p>
<p>
<div className="m-bottom-1">
Information and opt-out options for some common cookie providers used by us
can be found here:
</div>
<ul>
<li>
<a
href="https://tools.google.com/dlpage/gaoptout?hl=en"
className="feature-link"
target="_blank">
Google Analytics
</a>
</li>
<li>
<a
href="https://www.google.com/settings/u/0/ads"
className="feature-link"
target="_blank">
Google AdWords
</a>
</li>
<li>
<a
href="https://www.facebook.com/help/568137493302217"
className="feature-link"
target="_blank">
Facebook
</a>
</li>
<li>
<a
href="https://support.twitter.com/articles/20170514-twitters-use-of-cookies-and-similar-technologies"
className="feature-link"
target="_blank">
Twitter
</a>
</li>
</ul>
</p>
<h5 id="protect-information">How do we protect your personal information?</h5>
<p>
Enhancv Ltd. and its authorized partners shall take appropriate organizational
and technical measures to protect your Information and traffic data provided to
us/them or collected by us/them, and shall not retain it any longer than
permitted in order to perform its Services or as required under relevant
legislation. Your personal data can only be accessed by authorized employees of
Enhancv, or by Enhancv authorized partners' employees needing to access this
data to fulfill their given duties.
</p>
<p>
<div className="m-bottom-1">
Whenever possible, we will keep any information you provide us with limited
to our own databases and systems. We may have to share your personal data in
the following limited circumstances:
</div>
<ul>
<li>Allow our customers to pay for our Services.</li>
<li>Facilitate communication with you.</li>
<li>Manage our customer support services to you.</li>
<li>
Manage our general business operation with the help of professional
advisers including lawyers, bankers, auditors and insurers.
</li>
<li>
Abide by local and international regulations by providing information to
government bodies that require us to report processing activities.
</li>
<li>
Track our service’s usage and provide reports to help us improve our
services and conversions.
</li>
</ul>
</p>
<p>
We require all third parties to whom we transfer your data to respect the
security of your personal data and to treat it in accordance with the law. We
only allow such third parties to process your personal data for specified
purposes and in accordance with our instructions as outlined in mutual
agreements and those third parties’ privacy policies.
</p>
<h5 id="legal-rights">How do we protect your personal information?</h5>
<p>
Under data protection laws you have rights in relation to your personal data
that include the right to request access, correction, erasure, restriction,
transfer, to object to processing, to portability of data and (where the lawful
ground of processing is consent) to withdraw consent.
</p>
<p>
If you wish to exercise any of the rights set out above, please email us at{" "}
<a
href="mailto:help@enhancv.com"
className="feature-link">
help@enhancv.com
</a>.
</p>
<p>
You will not have to pay a fee to access your personal data (or to exercise any
of the other rights). We may need to request specific information from you to
help us confirm your identity and ensure your right to access your personal data
(or to exercise any of your other rights). This is a security measure to ensure
that personal data is not disclosed to any person who has no right to receive
it. We may also contact you to ask you for further information in relation to
your request to speed up our response.
</p>
<p>
We try to respond to all legitimate requests within one month. Occasionally it
may take us longer than a month if your request is particularly complex or you
have made a number of requests. In this case, we will notify you.
</p>
<p>
We may need to request specific information from you to help us confirm your
identity and ensure your right to access your personal data (or to exercise any
of your other rights). This is a security measure to ensure that personal data
is not disclosed to any person who has no right to receive it.
</p>
<h5 id="changes">Can this Privacy Policy change?</h5>
<p>
We may update our Privacy Policy from time to time. We will notify you whenever
we change the policy in a material way by contacting you through email and
publishing the updated privacy policy on this same URL address.
</p>
<p>
If you have any questions or concerns regarding this policy or the Enhancv
service, please contact us at{" "}
<a
href="mailto:help@enhancv.com"
className="feature-link">
help@enhancv.com
</a>.
</p>
</div>
</TextLayout>
);
}
|
const uuid = require('node-uuid');
const randomstring = require('randomstring');
const crypto = require('crypto');
const User = require('../redis/user');
const register = function(session, username, password) {
return session.query('MATCH (user:User {username: $username}) RETURN user', { username })
.then((results) => {
if (results.hasNext()) {
throw { username: 'username already in use', status: 400 };
} else {
return session.query('CREATE (user:User {id: $id, username: $username, password: $password, api_key: $api_key}) RETURN user',
{
id: uuid.v4(),
username,
password: hashPassword(username, password),
api_key: randomstring.generate({
length: 20,
charset: 'hex'
})
})
.then((createdUser) => {
while (createdUser.hasNext()) {
const record = createdUser.next();
return new User(record.get('user'));
}
});
}
});
};
const me = function(session, apiKey) {
return session.query('MATCH (user:User {api_key: $api_key}) RETURN user', { api_key: apiKey })
.then((foundedUser) => {
if (!foundedUser.hasNext()) {
throw { message: 'invalid authorization key', status: 401 };
}
while (foundedUser.hasNext()) {
const record = foundedUser.next();
return new User(record.get('user'));
}
});
};
const login = function(session, username, password) {
return session.query('MATCH (user:User {username: $username}) RETURN user', { username })
.then((foundedUser) => {
if (!foundedUser.hasNext()) {
throw { username: 'username does not exist', status: 400 };
} else {
while (foundedUser.hasNext()) {
const record = foundedUser.next();
const dbUser = (record.get('user')).properties;
if (dbUser.password !== hashPassword(username, password)) {
throw { password: 'wrong password', status: 400 };
}
return { token: dbUser.api_key };
}
}
});
};
function hashPassword(username, password) {
const s = `${username}:${password}`;
return crypto.createHash('sha256').update(s).digest('hex');
}
module.exports = {
register,
me,
login
};
|
$(document).ready(function () {
//translator functions
$.html5Translate = function (dict, lang) {
$('[data-translate-key]').each(function () {
$(this).html(dict[lang][$(this).data('translateKey')]);
});
};
var translate = 0;
$('#btn').on('click', function () {
if (translate == 0) {
$.html5Translate(dict, 'en');
translate = 1;
}
else {
$.html5Translate(dict, 'ru');
translate = 0;
}
});
//media functions
$("#click-left").click(function () {
$("#container-left").hide(450);
$("#container-right").show(450);
});
$("#click-right").click(function () {
$("#container-left").show(450);
$("#container-right").hide(450);
});
// modal popup
$('.js-button-campaign').click(function () {
$('.js-overlay-campaign').fadeIn();
$('.js-overlay-campaign').addClass('disabled');
});
// закрыть на крестик
$('.js-close-campaign').click(function () {
$('.js-overlay-campaign').fadeOut();
});
// закрыть по клику вне окна
$(document).mouseup(function (e) {
var popup = $('.js-popup-campaign');
if (e.target != popup[0] && popup.has(e.target).length === 0) {
$('.js-overlay-campaign').fadeOut();
}
});
// my typed js
var typed = new Typed(".hero-typed-text", {
strings: ["var mySrc = myImage.getAttribute('src');</br>\ if(mySrc === 'images/firefox-icon.png')</br> \
\myImage.setAttribute('src','img/i.png');</br> \ } </br>else {</br> \ myImage.setAttribute('src','img/i.png');</br>\
}\
}</br> \ var i = document.querySelector('span');</br>\ var y = document.querySelector('h1');</br>\
var z = document.querySelector('h2');</br>\
var u = document.getElementById('icon')</br>\
var w = document.getElementById('block')"],
typeSpeed: 80,//Время набора текста
backSpeed: 80,//Время стерания текста
loop: true,//Зацыкливает набор текста
showCursor: false,
});
// my body scrolbar
$(function () {
//The passed argument has to be at least a empty object or a object with your desired options
$("body").overlayScrollbars({
sizeAutoCapable: false,
resize: "vertical"
});
});
$('.block__text').overlayScrollbars({
sizeAutoCapable: false,
resize: "vertical"
});
});
|
import React from "react"
import axios from "../../axios-orders"
import { connect } from "react-redux";
import playlist from '../../store/actions/general';
import InfiniteScroll from "react-infinite-scroll-component";
import LoadMore from "../LoadMore/Index"
import EndContent from "../LoadMore/EndContent"
import Release from "../LoadMore/Release"
import VideoItem from "../Video/Item"
import ShortNumber from "short-number"
import Rating from "../Rating/Index"
import ChannelItem from "../Channel/Item"
import TopView from "./TopView"
import Comment from "../Comments/Index"
import Translate from "../../components/Translate/Index"
import Photos from "./Photos"
import Router from "next/router";
class Artist extends React.Component {
constructor(props) {
super(props)
this.state = {
page: 2,
artist: props.pageInfoData.artist,
items: props.pageInfoData.items.results,
pagging: props.pageInfoData.items.pagging,
photos:props.pageInfoData.photos,
tabType:props.pageInfoData.tabType ? props.pageInfoData.tabType : "about"
}
this.refreshContent = this.refreshContent.bind(this)
this.loadMoreContent = this.loadMoreContent.bind(this)
}
getItemIndex(item_id) {
const items = [...this.state.items];
const itemIndex = items.findIndex(p => p[this.state.artist.type == "video" ? "video_id" : "channel_id"] == item_id);
return itemIndex;
}
componentDidMount() {
this.props.socket.on('unfollowUser', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.artist.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.items]
const changedItem = items[itemIndex]
changedItem.follow_count = changedItem.follow_count - 1
if (this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.follower_id = null
}
this.setState({ localUpdate:true, items: items })
}
}
});
this.props.socket.on('followUser', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.artist.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.items]
const changedItem = items[itemIndex]
changedItem.follow_count = data.follow_count + 1
if (this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.follower_id = 1
}
this.setState({ localUpdate:true, items: items })
}
}
});
this.props.socket.on('unfavouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.artist.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.items]
const changedItem = items[itemIndex]
changedItem.favourite_count = changedItem.favourite_count - 1
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.favourite_id = null
}
this.setState({ localUpdate:true, items: items })
}
}
});
this.props.socket.on('favouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.artist.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.items]
const changedItem = items[itemIndex]
changedItem.favourite_count = changedItem.favourite_count + 1
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.favourite_id = 1
}
this.setState({ localUpdate:true, items: items })
}
}
});
this.props.socket.on('likeDislike', data => {
let itemId = data.itemId
let itemType = data.itemType
let ownerId = data.ownerId
let removeLike = data.removeLike
let removeDislike = data.removeDislike
let insertLike = data.insertLike
let insertDislike = data.insertDislike
if (itemType == this.state.artist.type + "s") {
const itemIndex = this.getItemIndex(itemId)
if (itemIndex > -1) {
const items = [...this.state.items]
const changedItem = items[itemIndex]
let loggedInUserDetails = {}
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails) {
loggedInUserDetails = this.props.pageInfoData.loggedInUserDetails
}
if (removeLike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = null
changedItem['like_count'] = parseInt(changedItem['like_count']) - 1
}
if (removeDislike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = null
changedItem['dislike_count'] = parseInt(changedItem['dislike_count']) - 1
}
if (insertLike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = "like"
changedItem['like_count'] = parseInt(changedItem['like_count']) + 1
}
if (insertDislike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = "dislike"
changedItem['dislike_count'] = parseInt(changedItem['dislike_count']) + 1
}
this.setState({ localUpdate:true, items: items })
}
}
});
}
refreshContent() {
this.setState({ localUpdate:true, page: 1, items: [] })
this.loadMoreContent()
}
loadMoreContent() {
this.setState({ localUpdate:true, loading: true })
let formData = new FormData();
formData.append('page', this.state.page)
const config = {
headers: {
'Content-Type': 'multipart/form-data',
}
};
let url = "/artist-view"
formData.append("id", this.state.artist.custom_url)
axios.post(url, formData, config)
.then(response => {
if (response.data.items) {
let pagging = response.data.pagging
this.setState({ localUpdate:true, page: this.state.page + 1, pagging: pagging, items: [...this.state.items, ...response.data.items], loading: false })
} else {
this.setState({ localUpdate:true, loading: false })
}
}).catch(err => {
this.setState({ localUpdate:true, loading: false })
});
}
linkify(inputText) {
return inputText;
inputText = inputText.replace(/<br\/>/g, ' <br/>')
inputText = inputText.replace(/<br \/>/g, ' <br/>')
inputText = inputText.replace(/<br>/g, ' <br/>')
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank" rel="nofollow">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank" rel="nofollow">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1" rel="nofollow">$1</a>');
return replacedText;
}
pushTab = (type) => {
if(this.state.tabType == type){
return
}
this.setState({tabType:type,localUpdate:true})
Router.push(`/artist?artistId=${this.state.artist.custom_url}`, `/artist/${this.state.artist.custom_url}?type=${type}`,{ shallow: true })
}
render() {
let content = null
if (this.state.artist.type == "video") {
content = this.state.items.map(video => {
return (
<div key={video.video_id} className="gridColumn">
<VideoItem {...this.props} video={video} {...video} />
</div>
)
})
} else {
content = this.state.items.map(channel => {
return (
<div key={channel.channel_id} className="gridColumn">
<ChannelItem {...this.props} channel={channel} {...channel} />
</div>
)
})
}
return (
<React.Fragment>
<TopView {...this.props} type={this.state.artist.type} artist={this.state.artist} />
<div className="userDetailsWraps">
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="details-tab">
<ul className="nav nav-tabs" id="myTab" role="tablist">
<li className="nav-item">
<a className={`nav-link${this.state.tabType == "about" ? " active" : ""}`} onClick={
(e) => { e.preventDefault(); this.pushTab("about") }
} data-bs-toggle="tab" href="#" role="tab" aria-controls="about" aria-selected="true">{Translate(this.props, "About")}</a>
</li>
<li className="nav-item">
<a className={`nav-link${this.state.tabType == "items" ? " active" : ""}`} onClick={
(e) => { e.preventDefault(); this.pushTab("items") }
} data-bs-toggle="tab" href="#" role="tab" aria-controls="items" aria-selected="true">{Translate(this.props, this.state.artist.type == "video" ? "Videos" : "Channels")}</a>
</li>
{
this.props.pageInfoData.appSettings[`${this.state.artist.type + "_artist_comment"}`] == 1 ?
<li className="nav-item">
<a className={`nav-link${this.state.tabType == "comments" ? " active" : ""}`} onClick={
(e) => { e.preventDefault(); this.pushTab("comments") }
} data-bs-toggle="tab" href="#" role="tab" aria-controls="comments" aria-selected="true">{`${Translate(this.props,"Comments")}`}</a>
</li>
: null
}
{
this.state.photos && this.state.photos.results.length > 0 ?
<li className="nav-item">
<a className={`nav-link${this.state.tabType == "photos" ? " active" : ""}`} onClick={
(e) => { e.preventDefault(); this.pushTab("photos") }
} data-bs-toggle="tab" href="#" role="tab" aria-controls="photos" aria-selected="true">{Translate(this.props, "Photos")}</a>
</li>
: null
}
</ul>
<div className="tab-content" id="myTabContent">
<div className={`tab-pane fade${this.state.tabType == "about" ? " active show" : ""}`} id="about" role="tabpanel">
<div className="details-tab-box">
<React.Fragment>
{
this.props.pageInfoData.appSettings[`${this.state.artist.type + "_artist_rating"}`] == 1 ?
<div className="tabInTitle">
<h6>{Translate(this.props,'Rating')}</h6>
<div className="owner_name">
<React.Fragment>
<div className="animated-rater rating">
<Rating {...this.props} rating={this.state.artist.rating} type="artist" id={this.state.artist.artist_id} />
</div>
</React.Fragment>
</div>
</div>
: null
}
<div className="tabInTitle">
<h6>{this.props.t("view_count", { count: this.state.artist.view_count ? this.state.artist.view_count : 0 })}</h6>
<div className="owner_name">
<React.Fragment>
{`${ShortNumber(this.state.artist.view_count ? this.state.artist.view_count : 0)}`}{" "}{this.props.t("view_count", { count: this.state.artist.view_count ? this.state.artist.view_count : 0 })}
</React.Fragment>
</div>
</div>
{
this.state.artist.age ?
<div className="tabInTitle">
<h6>{Translate(this.props,"Age")}</h6>
<div className="owner_name">
{this.state.artist.age}
</div>
</div>
: null
}
{
this.state.artist.gender ?
<div className="tabInTitle">
<h6>{Translate(this.props,"Gender")}</h6>
<div className="owner_name">
{this.state.artist.gender}
</div>
</div>
: null
}
{
this.state.artist.birthplace ?
<div className="tabInTitle">
<h6>{Translate(this.props,"Birth Place")}</h6>
<div className="owner_name">
{this.state.artist.birthplace}
</div>
</div>
: null
}
<div className="tabInTitle">
<h6>{Translate(this.props, "Description")}</h6>
<div className="channel_description">
<div className="channel_description" id="VideoDetailsDescp" style={{ ...this.state.styles, whiteSpace: "pre-line" }} dangerouslySetInnerHTML={{__html:this.linkify(this.state.artist.description)}}></div>
{/* <Linkify properties={{ target: '_blank' }}>{<CensorWord {...this.props} text={this.state.artist.description} />}</Linkify> */}
</div>
</div>
</React.Fragment>
</div>
</div>
<div className={`tab-pane fade${this.state.tabType == "items" ? " active show" : ""}`} id="items" role="tabpanel">
<div className="details-tab-box">
<InfiniteScroll
dataLength={this.state.items.length}
next={this.loadMoreContent}
hasMore={this.state.pagging}
loader={<LoadMore {...this.props} page={this.state.page} loading={true} itemCount={this.state.items.length} />}
endMessage={
<EndContent {...this.props} text={this.state.artist.type == "channel" ? Translate(this.props, "No channel created for this artist.") : Translate(this.props, "No video created for this artist.")} itemCount={this.state.items.length} />
}
pullDownToRefresh={false}
pullDownToRefreshContent={<Release release={false} {...this.props} />}
releaseToRefreshContent={<Release release={true} {...this.props} />}
refreshFunction={this.refreshContent}
>
<div className="gridContainer gridArtist">
{content}
</div>
</InfiniteScroll>
</div>
</div>
{
this.props.pageInfoData.appSettings[`${this.state.artist.type + "_artist_comment"}`] == 1 ?
<div className={`tab-pane fade${this.state.tabType == "comments" ? " active show" : ""}`} id="comments" role="tabpanel">
<div className="details-tab-box">
<Comment {...this.props} owner_id="artist" hideTitle={true} subtype={this.state.artist.type + "_"} appSettings={this.props.pageInfoData.appSettings} commentType="artist" type="artists" id={this.state.artist.artist_id} />
</div>
</div>
: null
}
{
this.state.photos && this.state.photos.results.length > 0 ?
<div className={`tab-pane fade${this.state.tabType == "photos" ? " active show" : ""}`} id="photos" role="tabpanel">
<div className="details-tab-box">
<Photos {...this.props} photos={this.state.photos} artist={this.state.artist} />
</div>
</div>
: null
}
</div>
</div>
</div>
</div>
</div>
</div>
</React.Fragment>
)
}
}
const mapStateToProps = state => {
return {
pageInfoData: state.general.pageInfoData
};
};
const mapDispatchToProps = dispatch => {
return {
openPlaylist: (open, video_id) => dispatch(playlist.openPlaylist(open, video_id)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Artist) |
//
function notify(message, customOpts)
{
var opts =
{
type: 'info',
placement:
{
from: 'top',
align: 'center'
},
animate:
{
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
}
}
if (customOpts)
{
Object.assign(opts, customOpts)
}
return $.notify(message, opts)
}
function reloadAndNotify (message)
{
Cookies.set('notification', message)
window.location.reload(true)
}
function pollForChanges()
{
// !!! This API doesn't work on the Dropbox backend (was never tested and has been b0rken for 9+ months).
// See: https://github.com/dropbox/dropbox-sdk-js/issues/85
//
console.log("Polling for changes")
dbx.filesListFolderLongpoll({ cursor: cursor, timeout: 30 }).then( function(response)
{
if (!inOperation)
{
if (response.changes)
{
reloadAndNotify("Folder contents changed, reloaded")
}
else
{
pollForChanges()
}
}
else
{
console.log("In operation, terminating polling")
}
})
.catch(function(error)
{
console.error(error)
})
}
function onLoad ()
{
console.log('Page loaded, path: "%s"', path);
var notification = Cookies.get('notification')
if (notification)
{
console.log('notification: ' + notification)
notify(notification)
Cookies.remove('notification')
}
$('#moveCopyModalOk').click(function (e)
{
onMoveCopyOk()
})
$('#search').on('keydown', function (event)
{
if (event.keyCode === 13)
{
event.preventDefault()
onSearch($('#search').val())
return false
}
})
$('#searchButton').click(function (e)
{
onSearch($('#search').val())
})
$('#files').on('change', function()
{
// The form field returns a FileList object, which has the same functionality as an array,
// but is not an array, so we have to convert it to one...
//
var fileList = $('#files')[0].files
var files = []
for (var i = 0; i < fileList.length; i++)
{
files.push(fileList[i])
}
uploadFiles(files)
})
$('#filesTable').show();
// Update initial command state
//
selectionChanged()
pollForChanges()
}
function selectionChanged ()
{
var selections = $('#filesTable').bootstrapTable('getSelections')
console.log("Selection changed, selection count: " + selections.length)
selections.forEach(function(element)
{
console.log("Selection: " + element._data.path)
})
if (selections.length == 0)
{
$('#btnCreateFolder').show()
$('#btnUploadFile').show()
$('#btnRename').hide()
$('#btnMove').hide()
$('#btnCopy').hide()
$('#btnDelete').hide()
}
else if (selections.length == 1)
{
$('#btnCreateFolder').hide()
$('#btnUploadFile').hide()
$('#btnRename').show()
$('#btnMove').show()
$('#btnCopy').show()
$('#btnDelete').show()
}
else
{
$('#btnCreateFolder').hide()
$('#btnUploadFile').hide()
$('#btnRename').hide()
$('#btnMove').show()
$('#btnCopy').show()
$('#btnDelete').show()
}
}
function onSearch (query)
{
console.log("Search for:", query)
window.location.href = '/search?query=' + encodeURIComponent(query)
}
var inOperation
function onCreateFolder ()
{
bootbox.prompt('Create Folder', function (result)
{
if (result)
{
notify('Creating folder: ' + result )
inOperation = true
dbx.filesCreateFolder({ path: path + '/' + result }).then(function (response)
{
console.log('Created folder:', response)
reloadAndNotify('Created folder: ' + result)
})
.catch(function(error)
{
console.error(error)
})
}
})
}
function onUploadFile ()
{
$('#files').click();
}
var cancelUpload = false
function onCancelUpload ()
{
console.log("Upload cancelled")
cancelUpload = true
}
// File(s) upload
//
// The Dropbox JavaScript API uses SuperAgent internally, and SuperAgent in turns uses the XMLHttpReuest (XHR).
// That internal XHR has progress notification (and cancel) support, but it is not exposed to us here (the
// Dropbox JavaScript API doesn't even have access to it). So there does not appear to be a way to get status
// or to cancel a Dropbox upload via the Dropbox JavaScript API.
//
// That being said, we can report status and support cancel on multipart upload, or a multi-file upload (which
// is easier and more sensible when we do them serially, as below).
//
const maxBlob = 8 * 1000 * 1000 // 8Mb - Dropbox JavaScript API suggested max file / chunk size
function uploadFiles (files)
{
console.log("Upload files: %o", files)
inOperation = true
var workItems = []
var workItemsSize = 0
files.forEach( function(file)
{
if (file.size < maxBlob)
{
// Single part upload - use filesUpload API
//
// { file: file1, chunk: false, size: 6969 }
//
workItems.push({ file: file, chunk: false, size: file.size })
workItemsSize += file.size
}
else
{
// Multipart upload - use filesUploadSession APIs
//
// { file: file2, chunk: true, start: 0, end: 8191, size: 8192 }
// { file: file2, chunk: true, start: 8192, end: 9192, close: true, size: 1000 }
//
var offset = 0
while (offset < file.size)
{
var chunkSize = Math.min(maxBlob, file.size - offset)
workItems.push({ file: file, chunk: true, offset: offset, end: offset + chunkSize, size: chunkSize })
workItemsSize += chunkSize
offset += chunkSize
}
workItems[workItems.length-1].close = true
}
})
console.log("Workitems:", workItems)
if (workItems.length === 1)
{
// Uploading a single file in one chunk
//
// The only reason we process this separately here is to support the different UX - as there
// is no status/cancel with a single file, single part upload.
//
var file = workItems[0].file
notify('Uploading file: ' + file.name);
dbx.filesUpload({ path: path + '/' + file.name, contents: file }).then(function(response)
{
console.log(response);
reloadAndNotify('Completed uploading of file: ' + file.name)
})
.catch(function(error)
{
console.error(error);
})
}
else
{
// Uploading multiple files and/or chunks
//
// You could easily process multiple workItems in parallel if desired. In our case, we want
// to show a nice progress UX with cancel, so we're going to process the workItems serially.
//
var msg = (files.length === 1) ? 'Uploading file: ' + files[0].name : 'Uploading files'
var notification = notify(msg,
{
showProgressbar: true,
delay: 0,
template: // Added "cancel" button to default template
'<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
' <button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
' <span data-notify="icon"></span>' +
' <span data-notify="title">{1}</span>' +
' <span data-notify="message">{2}</span>' +
' <div class="progress" data-notify="progressbar">' +
' <div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
' </div>' +
' <button id="btnCancel" type="button" class="btn btn-primary btn-sm btn-action" onclick="onCancelUpload();"><span class="glyphicon glyphicon-stop"></span> Cancel</button>' +
' <a href="{3}" target="{4}" data-notify="url"></a>' +
'</div>'
});
var sessionId
var bytesUploaded = 0
var result = Promise.resolve()
workItems.forEach( function (workItem)
{
var file = workItem.file
result = result.then( function ()
{
if (cancelUpload)
{
return(Promise.resolve())
}
if (!workItem.chunk)
{
console.log("Uploading file:", file.name)
return dbx.filesUpload({ path: path + '/' + file.name, contents: file }).then(function(response)
{
console.log(response);
console.log('Completed uploading of file: ' + file.name)
bytesUploaded += workItem.size
notification.update('progress', bytesUploaded/workItemsSize * 100)
})
}
else if (workItem.offset === 0)
{
console.log("Starting multipart upload of file:", file.name)
var blob = file.slice(workItem.offset, workItem.end)
return dbx.filesUploadSessionStart({ close: false, contents: blob}).then(function (response)
{
sessionId = response.session_id;
console.log("Complete multipart upload start, sessionId:", sessionId)
bytesUploaded += workItem.size
notification.update('progress', bytesUploaded/workItemsSize * 100)
})
}
else if (!workItem.close)
{
console.log("Putting chunk in multipart upload of file:", file.name)
var cursor = { session_id: sessionId, offset: workItem.offset }
var blob = file.slice(workItem.offset, workItem.end)
return dbx.filesUploadSessionAppendV2({ cursor: cursor, close: false, contents: blob }).then( function (response)
{
console.log("Complete multipart upload append")
bytesUploaded += workItem.size
notification.update('progress', bytesUploaded/workItemsSize * 100)
})
}
else
{
console.log("Completing multipart upload of file:", file.name)
var cursor = { session_id: sessionId, offset: workItem.offset }
var commit = { path: path + '/' + file.name, mode: 'add', autorename: true, mute: false }
var blob = file.slice(workItem.offset, workItem.end)
return dbx.filesUploadSessionFinish({ cursor: cursor, commit: commit, contents: blob }).then(function (response)
{
console.log("Complete multipart upload finish")
sessionId = null
bytesUploaded += workItem.size
notification.update('progress', bytesUploaded/workItemsSize * 100)
})
}
})
})
result.then( function()
{
if (cancelUpload)
{
console.log("Upload of workitem(s) cancelled")
notification.close()
notify("Upload cancelled")
cancelUpload = false
}
else
{
console.log("Complete upload of workitem(s)")
if (files.length === 1)
{
reloadAndNotify('Completed uploading of file: ' + files[0].name)
}
else
{
reloadAndNotify('Completed uploading of multiple files')
}
}
})
.catch( function(reason)
{
console.log("ERR:", reason )
notification.close()
notify("Error on upload: " + reason.user_message);
})
}
}
function onRename ()
{
inOperation = true
var selections = $('#filesTable').bootstrapTable('getSelections')
var type = 'file'
if (selections[0]._data.isfolder)
{
type = 'folder'
}
message = 'Rename ' + type + ': "' + selections[0]._data.name + '" to:'
bootbox.prompt(message, function (result)
{
var src = selections[0]._data.path
var dst = path + '/' + result
console.log('Rename ' + src + ' to ' + dst)
dbx.filesMove({ from_path: src, to_path: dst }).then(function(response)
{
console.log('Entry renamed:', response)
reloadAndNotify('Renamed ' + type + ': ' + selections[0]._data.name + ' to ' + result)
})
.catch(function(error)
{
console.error(error)
})
})
}
function populateFolder (parentPath, parentId, depth)
{
depth--
dbx.filesListFolder({ path: parentPath, recursive: false }).then(function(response)
{
console.log('Folder list:', response)
response.entries.forEach(function(entry)
{
if (entry['.tag'] === 'folder')
{
console.log("Found folder:", entry.name)
var node = $('#tree').treeview('addNode', [parentId, { text: entry.name, path: entry.path_display }])
if (node.nodeId === 1)
{
// This is kind of a hack, but once we've added the first non-root node (nodeId == 1), we
// need to expand the root node (nodeId == 0).
//
$('#tree').treeview('expandNode', [ 0, { levels: 2, silent: true } ]);
}
if (depth)
{
populateFolder(node.path, node.nodeId, depth)
}
}
var parentNode = $('#tree').treeview('getNode', [parentId]);
parentNode.populated = true
})
})
.catch(function(error)
{
console.error(error)
})
}
function populateFolderPicker ()
{
var tree = [
{
text: "Home",
path: "/",
}]
var tree = $('#tree').treeview(
{
data: tree,
nodeIcon: "glyphicon glyphicon-folder-close"
})
tree.on('nodeSelected', function (event, node)
{
console.log("Node selected:", node)
$('#moveCopyModalDest').val(node.path)
})
tree.on('nodeExpanded', function (event, node)
{
// The idea here is the if we have only populated to a certain depth, then
// when we expand a node, we need to ensure that its children have been
// populated (so that its children will show expandability appropriately).
//
console.log("Node expanded:", node)
node.nodes.forEach(function (childNode)
{
if (!childNode.populated)
{
populateFolder(childNode.path, childNode.nodeId, 1)
}
})
})
populateFolder('', 0, 2)
}
function onMove ()
{
jQuery.data($('#moveCopyModal')[0], 'operation', 'move')
$('#moveCopyModalTitle').text('Move')
$('#moveCopyModalDest').val('')
populateFolderPicker()
$('#moveCopyModal').modal()
}
function onCopy ()
{
jQuery.data($('#moveCopyModal')[0], 'operation', 'copy')
$('#moveCopyModalTitle').text('Copy')
$('#moveCopyModalDest').val('')
populateFolderPicker()
$('#moveCopyModal').modal()
}
function moveFile (params, successMessage)
{
inOperation = true
dbx.filesMove(params)
.then(function(response)
{
console.log('File moved:', response)
reloadAndNotify(successMessage)
})
.catch(function(error)
{
console.error(error)
})
}
function moveFiles (params)
{
console.log('Moving entries:', params.entries)
inOperation = true
dbx.filesMoveBatch(params).then(function (response)
{
console.log('Batch move underway:', response)
if (response['.tag'] === 'async_job_id')
{
(function pollForJobCompletion()
{
console.log('Polling for move batch completion')
dbx.filesDeleteBatchCheck({ async_job_id: response.async_job_id}).then(function (response)
{
console.log('Got response to checking batch move completion:', response)
if (response['.tag'] === 'complete')
{
console.log('Batch move complete:', response)
reloadAndNotify('Moved selected entries')
}
else if (response['.tag'] === 'in_progress')
{
setTimeout(pollForJobCompletion, 1000)
}
else
{
console.log('Batch job failed:', response)
}
})
}())
}
else
{
console.log('Error starting batch move:', response)
}
})
.catch(function(error)
{
console.error(error)
})
}
function copyFile (params, successMessage)
{
inOperation = true
dbx.filesCopy(params)
.then(function(response)
{
console.log('File copied:', response)
reloadAndNotify(successMessage)
})
.catch(function(error)
{
console.error(error)
})
}
function copyFiles (params)
{
console.log('Copying entries:', params.entries)
inOperation = true
dbx.filesCopyBatch(params).then(function (response)
{
console.log('Batch copy underway:', response)
if (response['.tag'] === 'async_job_id')
{
(function pollForJobCompletion()
{
console.log('Polling for copy batch completion')
dbx.filesCopyBatchCheck({ async_job_id: response.async_job_id}).then(function (response)
{
console.log('Got response to checking batch copy completion:', response)
if (response['.tag'] === 'complete')
{
console.log('Batch copy complete:', response)
reloadAndNotify('Copied selected entries')
}
else if (response['.tag'] === 'in_progress')
{
setTimeout(pollForJobCompletion, 1000)
}
else
{
console.log('Batch job failed:', response)
}
})
}())
}
else
{
console.log('Error starting batch copy:', response)
}
})
.catch(function(error)
{
console.error(error)
})
}
function deleteFile (params, successMessage)
{
inOperation = true
dbx.filesDelete(params).then(function(response)
{
console.log('Entry deleted:', response)
reloadAndNotify(successMessage)
})
.catch(function(error)
{
console.error(error)
})
}
function deleteFiles (params)
{
console.log('Delete entries:', params.entries)
inOperation = true
dbx.filesDeleteBatch(params).then(function (response)
{
console.log('Batch deletion underway:', response)
if (response['.tag'] === 'async_job_id')
{
(function pollForJobCompletion()
{
console.log('Polling for delete batch completion')
dbx.filesDeleteBatchCheck({ async_job_id: response.async_job_id}).then(function (response)
{
console.log('Got response to checking batch delete completion:', response)
if (response['.tag'] === 'complete')
{
console.log('Batch deletion complete:', response)
reloadAndNotify('Deleted selected entries')
}
else if (response['.tag'] === 'in_progress')
{
setTimeout(pollForJobCompletion, 1000)
}
else
{
console.log('Batch job failed:', response)
}
})
}())
}
else
{
console.log('Error starting batch delete:', response)
}
})
.catch(function(error)
{
console.error(error)
})
}
function onMoveCopyOk ()
{
var operation = jQuery.data($('#moveCopyModal')[0], 'operation')
var dest = $('#moveCopyModalDest').val()
console.log('User clicked OK, operation is %s, dest is:', operation, dest)
$('#moveCopyModal').modal('hide')
if (!dest)
{
console.log("No destination entered, %s operation not completed", operation)
return
}
var action = (operation === 'move' ? "Moving" : "Copying")
var completedAction = (operation === 'move' ? "Moved" : "Copied")
var selections = $('#filesTable').bootstrapTable('getSelections')
if (selections.length === 1)
{
// Single item operation (interactive)
//
var params = { from_path: selections[0]._data.path, to_path: dest + "/" + selections[0]._data.name }
console.log("Do interactive %s with params: %o", operation, params);
var type = (selections[0]._data.isfolder ? 'folder' : 'file')
notify(action + ' ' + type + ': ' + selections[0]._data.name);
if (operation === 'move')
{
moveFile(params, completedAction + ' ' + type + ': ' + selections[0]._data.name)
}
else
{
copyFile(params, completedAction + ' ' + type + ': ' + selections[0]._data.name)
}
}
else
{
// Multi-item operation (batch)
//
var entries = []
selections.forEach(function(element)
{
entries.push({ from_path: element._data.path, to_path: dest + "/" + element._data.name })
})
var params = { entries: entries }
console.log("Do bulk %s with params: %o", operation, params);
notify(action + ' selected entries');
if (operation === 'move')
{
moveFiles(params)
}
else
{
copyFiles(params)
}
}
}
function onDelete ()
{
var selections = $('#filesTable').bootstrapTable('getSelections')
var message = 'Delete selected entries?'
var type = 'entries'
if (selections.length == 1)
{
if (selections[0]._data.isfolder)
{
type = 'folder'
}
else
{
type = 'file'
}
message = 'Delete ' + type + ': "' + selections[0]._data.name + '" ?'
}
bootbox.confirm(message, function (result)
{
console.log('Delete confirm result: ' + result)
if (result)
{
if (selections.length === 1)
{
// Single item operation (interactive)
//
notify('Deleting ' + type + ': ' + selections[0]._data.name);
var params = { path: selections[0]._data.path }
deleteFile(params, 'Deleted ' + type + ': ' + selections[0]._data.name);
}
else
{
// Multi-item operation (batch)
//
notify('Deleting selected entries')
var entries = []
selections.forEach(function(element)
{
entries.push({ path: element._data.path })
})
var params = { entries: entries }
deleteFiles(params)
}
}
})
}
//
// Drag / drop support
//
// Note: We probably want to prevent drop altogether on search results page, see:
// https://stackoverflow.com/questions/6756583/prevent-browser-from-loading-a-drag-and-dropped-file
//
function drop_handler(ev)
{
console.log("Drop")
ev.preventDefault()
var files = []
// If dropped items aren't files, reject them
var dt = ev.dataTransfer
if (dt.items)
{
// Use DataTransferItemList interface to access the file(s)
for (var i=0; i < dt.items.length; i++)
{
if (dt.items[i].kind == "file")
{
var f = dt.items[i].getAsFile();
console.log("... file[" + i + "].name = " + f.name)
files.push(f)
}
}
}
else
{
// Use DataTransfer interface to access the file(s)
for (var i=0; i < dt.files.length; i++)
{
console.log("... file[" + i + "].name = " + dt.files[i].name)
files.push(f)
}
}
if (files.length)
{
console.log("Uploading dropped files:", files)
uploadFiles(files)
}
}
function dragover_handler(ev)
{
console.log("dragOver")
// Prevent default select and drag behavior
ev.preventDefault()
}
function dragend_handler(ev)
{
console.log("dragEnd")
// Remove all of the drag data
var dt = ev.dataTransfer
if (dt.items)
{
// Use DataTransferItemList interface to remove the drag data
for (var i = 0; i < dt.items.length; i++)
{
dt.items.remove(i)
}
}
else
{
// Use DataTransfer interface to remove the drag data
ev.dataTransfer.clearData()
}
}
|
console.log('Externel File') |
/** Hex coordinate mapping system **/
function Hex (q, r, opts) {
// pass in q, r to get a location.
// opts are used for additional terrain based things etc.
if (!(this instanceof Hex)) {
return new Hex(q, r, opts);
}
var priv = {};
this.q = q;
this.r = r;
this.terrain = (opts && opts.terrain) || TERRAIN.PLAINS;
this.owner_id = (opts && opts.owner_id) || 0; // defaults to 0 being UNCLAIMED
}
Hex.prototype.toString = function() {
return ("{ " + this.q + "," + this.r + " }");
};
Hex.prototype.toCube = function() {
// casts this hex to a cube coordinate
var x = this.q;
var z = this.r;
var y = -x-z;
return new Cube([x, y, z]);
};
Hex.prototype.toOffset = function(offset_type) {
// casts the hex to a q, r offset grid position
return (this.toCube().toOffset(offset_type));
};
var TERRAIN = {
PLAINS: ".",
WATER: "~",
FOREST: "#",
};
module.exports = Hex;
// circular dependency defined below
var Cube = require("./cube.js");
|
import React from "react"
export default ({ width, height, fill }) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 38 26"
width={width}
height={height}
fill="none"
>
<path
d="M32.8 25H5.10001C3.10001 25 1.39999 23.3 1.39999 21.3V4.70001C1.39999 2.70001 3.10001 1 5.10001 1H32.8C34.8 1 36.5 2.70001 36.5 4.70001V21.3C36.5 23.3 34.9 25 32.8 25Z"
stroke={fill}
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M11.6 11.3C13.2569 11.3 14.6 10.0016 14.6 8.39999C14.6 6.79837 13.2569 5.5 11.6 5.5C9.94315 5.5 8.60001 6.79837 8.60001 8.39999C8.60001 10.0016 9.94315 11.3 11.6 11.3Z"
stroke={fill}
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M15.6 20.4H7.60001C6.80001 20.4 6.10001 19.7 6.10001 18.9V16.3C6.10001 14.2 7.79999 12.5 9.89999 12.5H13.3C15.4 12.5 17.1 14.2 17.1 16.3V18.9C17.2 19.7 16.5 20.4 15.6 20.4Z"
stroke={fill}
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M21.8 7.5H31.9"
stroke={fill}
strokeLinecap="round"
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M21.8 11.2H31.9"
stroke={fill}
strokeLinecap="round"
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M21.8 14.8H31.9"
stroke={fill}
strokeLinecap="round"
strokemitterlimit="10"
strokeWidth="1"
/>
<path
d="M21.8 18.5H31.9"
stroke={fill}
strokeLinecap="round"
strokemitterlimit="10"
strokeWidth="1"
/>
</svg>
)
}
|
import React, { Component } from "react";
import Dropdown from "react-dropdown";
import "react-dropdown/style.css";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import BarChart from "../components/BarChart";
import styles from "./BuildingStatistics.module.css";
class BuildingStatistics extends Component {
constructor(props) {
super(props);
let nameToSet = this.props.match.params.name;
let dateToSet = this.props.match.params.date;
let calledAsAPI = true;
if (!(nameToSet && dateToSet)){
nameToSet = "";
dateToSet = new Date().toDateString();
calledAsAPI = false;
}
this.state = {
calledAsAPI: calledAsAPI,
configuration: "",
values: [],
selectedBuilding: nameToSet,
date: new Date(dateToSet),
chartData: [],
show: false,
};
}
onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
formatDate(date) {
var d = new Date(date),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
componentDidMount() {
fetch(
"http://localhost:8888/web-project-2020-FMI/backend/services/export.php"
)
.then((response) => response.json())
.then((json) => {
var names = [];
for (var k in json) {
names.push(json[k]["building_name"]);
}
this.setState({
configuration: json,
values: names.filter(this.onlyUnique),
});
if(this.state.calledAsAPI){
let date = this.state.date.setDate(this.state.date.getDate() + 1);
this.func(this.state.selectedBuilding,this.formatDate(date),json);
this.setState({show:true, date:date});
}
});
}
handleSelectBuilding = (option) => {
const selectedBuilding = option.value;
this.setState({ selectedBuilding });
};
setStartDate = (dateToSet) => {
this.setState({
date: dateToSet,
});
};
onSelect = (e) => {
e.preventDefault();
};
statisticPercentOfBookedHalls = (buidlingName, selectedDate, fetchedData) => {
let bookings = new Map();
let halls = new Set();
for (var record in fetchedData) {
let currentBuildingName = fetchedData[record]["building_name"];
let currentDuration = fetchedData[record]["duration"];
let currentDateAsArray = fetchedData[record]["start_time"].split(" ");
if (currentBuildingName === buidlingName) {
halls.add(fetchedData[record]["hall_name"]);
}
if (
currentBuildingName === buidlingName &&
currentDateAsArray[0] === selectedDate
) {
let currentHour = currentDateAsArray[1].split(":")[0];
for (let i = 0; i < currentDuration; i++) {
if (bookings.has(parseInt(currentHour) + i)) {
bookings.set(
parseInt(currentHour) + i,
bookings.get(parseInt(currentHour) + i) + 1
);
} else {
bookings.set(parseInt(currentHour) + i, 1);
}
}
}
}
let info = [];
let size = halls.size;
for (let [k, v] of bookings) {
info.push({
label: k + " - " + (k + 1) + " часа",
value: (v / size) * 100,
});
}
return info;
};
statisticsPercentOfBookedBuilding(buidlingName, selectedDate, fetchedData) {
let bookings = new Map();
let buildingSize = 0;
for (var record in fetchedData) {
let currentBuildingName = fetchedData[record]["building_name"];
let currentDuration = fetchedData[record]["duration"];
let currentDateAsArray = fetchedData[record]["start_time"].split(" ");
let capacity = fetchedData[record]["hall_capacity"];
if (
currentBuildingName === buidlingName &&
currentDateAsArray[0] === selectedDate
) {
buildingSize = fetchedData[record]["building_capacity"];
let currentHour = currentDateAsArray[1].split(":")[0];
for (let i = 0; i < currentDuration; i++) {
if (bookings.has(parseInt(currentHour) + i)) {
bookings.set(
parseInt(currentHour) + i,
bookings.get(parseInt(currentHour) + i) + parseInt(capacity)
);
} else {
bookings.set(parseInt(currentHour) + i, parseInt(capacity));
}
}
}
}
let info = [];
for (let [k, v] of bookings) {
info.push({
label: k + " - " + (k + 1) + " часа",
value: (v / buildingSize) * 100,
});
}
return info;
}
func = (buidlingName,selectedDate,fetchedData) =>{
let percentBookedHalls = this.statisticPercentOfBookedHalls(
buidlingName,
selectedDate,
fetchedData
);
let percentBookedBuilding = this.statisticsPercentOfBookedBuilding(
buidlingName,
selectedDate,
fetchedData
);
let current = [];
current.push({
title: "Процент на заети зали",
data: percentBookedHalls,
});
current.push({
title: "Процентна заетост по часове на сградата",
data: percentBookedBuilding,
});
this.setState({ chartData: current });
}
handleOnClick = () => {
this.setState({ show: true });
let buidlingName = this.state.selectedBuilding;
let selectedDate = this.formatDate(this.state.date);
var fetchedData = this.state.configuration;
this.func(buidlingName,selectedDate,fetchedData);
};
render() {
return (
<div>
<div className={styles.dropdown}>
<Dropdown
onChange={this.handleSelectBuilding}
value={this.state.selectedBuilding}
options={this.state.values}
placeholder="Select building"
/>
</div>
<div>
<button
type="submit"
className={styles.btn}
onClick={this.handleOnClick}
>
Choose
</button>
</div>
<div className={styles.datepicker}>
<DatePicker
selected={this.state.date}
onChange={(date) => this.setStartDate(date)}
/>
</div>
{this.state.show && (
<div className={styles.chart1}>
<BarChart
data={this.state.chartData[0].data}
title={this.state.chartData[0].title}
color="#70CAD1"
/>
</div>
)}
{this.state.show && (
<div className={styles.chart2}>
<BarChart
data={this.state.chartData[1].data}
title={this.state.chartData[1].title}
color="#59124d"
/>
</div>
)}
</div>
);
}
}
export default BuildingStatistics;
|
let aa = "123";
let buttons=document.getElementsByClassName('easyui-linkbutton');
for(let i=0;i<buttons.length;i++){
buttons[i].innerHTML
}
|
import Link from "next/link";
import Page from "../../components/Page";
export default () => {
const title = "pottery";
return (
<Page title={title}>
<h2 className="entry-title">{title}</h2>
<section className="clearfix landing-page-posts">
<article>
<Link href="pottery/sculptures">
<a href="pottery/sculptures" rel="bookmark">
<img
width="125"
height="125"
src="/static/images/2012/03/sculpt1-125x125.jpg"
className="attachment-125x125 size-125x125 wp-post-image"
alt=""
/>
</a>
</Link>
<h2>
<Link href="pottery/sculptures">
<a href="pottery/sculptures" title="sculptures" rel="bookmark">
sculptures
</a>
</Link>
</h2>
</article>
<article>
<Link href="pottery/vases-glazed">
<a href="pottery/vases-glazed" rel="bookmark">
<img
width="125"
height="125"
src="/static/images/2012/03/glazd1-125x125.jpg"
className="attachment-125x125 size-125x125 wp-post-image"
alt=""
/>
</a>
</Link>
<h2>
<Link href="pottery/vases-glazed">
<a
href="pottery/vases-glazed"
title="vases glazed"
rel="bookmark"
>
vases glazed
</a>
</Link>
</h2>
</article>
<article>
<Link href="pottery/vases-unglazed-bw">
<a href="pottery/vases-unglazed-bw" rel="bookmark">
{" "}
<img
width="125"
height="125"
src="/static/images/2012/03/ungl-v1-125x125.jpg"
className="attachment-125x125 size-125x125 wp-post-image"
alt=""
/>
</a>
</Link>
<h2>
<Link href="pottery/vases-unglazed-bw">
<a
href="pottery/vases-unglazed-bw"
title="vases unglazed b&w"
rel="bookmark"
>
vases unglazed b&w
</a>
</Link>
</h2>
</article>
</section>
</Page>
);
};
|
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testPathIgnorePatterns: ["/build/", "/node_modules/"],
transform: {
'^.+\\.tsx?$': ['ts-jest', {
tsconfig: 'tsconfig.test.json',
}]
},
moduleNameMapper: {
'tiny-lru': require.resolve('tiny-lru')
},
collectCoverage: true
};
|
var x = [50,75,100,125,150];
var y = [50,75,100,125,150];
var speedY = [3,8,10,16,18];
var speedX = [4,6,12,17,23];
/**
* setup
* de code in deze functie wordt één keer uitgevoerd door
* de p5 library, zodra het spel geladen is in de browser
*/
function setup() {
// Maak een canvas (rechthoek) waarin je je speelveld kunt tekenen
createCanvas(1280, 720);
// Kleur de achtergrond blauw, zodat je het kunt zien
background('blue');
}
/**
* draw
* de code in deze functie wordt meerdere keren per seconde
* uitgevoerd door de p5 library, nadat de setup functie klaar is
*/
function draw() {
background('blue');
// teken een cirkel en kleur ze in
fill(100, 100, 255);
ellipse(x[0],y[0],80,80);
fill(100, 100, 255);
ellipse(x[1],y[1],80,80);
fill(0, 255, 255);
ellipse(x[2],y[2],80,80);
fill(100, 0, 255);
ellipse(x[3],y[3],80,80);
fill(255, 100, 0);
ellipse(x[4],y[4],80,80);
// bal op snelheid laten bewegen
X[0]= X[0] + speedX[0]
X[1]= X[1] + speedX[1]
X[2]= X[2] + speedX[2]
X[3]= X[3] + speedX[3]
X[4]= X[4] + speedX[4]
Y[0]= Y[0] + speedY[0]
Y[1]= Y[1] + speedY[1]
Y[2]= Y[2] + speedY[2]
Y[3]= Y[3] + speedY[3]
Y[4]= Y[4] + speedY[4]
// bal 1
if (y[0] > 680) {
speedY[0] = speedY[0] * -1;
}
if (y[0] < 40) {
speedY[0] = speedY[0] * -1;
}
if (x[0] > 40) {
speedY[0] = speedY[0] * -1;
}
if (x[0] < 1240 {
speedY[0] = speedY[0] * -1;
}
// bal 2
if (y[1] > 680) {
speedY[1] = speedY[1] * -1;
}
if (y[1] < 0) {
speedY[1] = speedY[1] * -1;
}
if (x[1] > 730) {
speedY[1] = speedY[1] * -1;
}
if (x[1] < 0) {
speedY[1] = speedY[1] * -1;
}
// bal 3
if (y[2] > 730) {
speedY[2] = speedY[2] * -1;
}
if (y[2] < 0) {
speedY[2] = speedY[2] * -1;
}
if (x[2] > 730) {
speedY[2] = speedY[2] * -1;
}
if (x[2] < 0) {
speedY[2] = speedY[2] * -1;
}
// bal 4
if (y[3] > 730) {
speedY[3] = speedY[3] * -1;
}
if (y[3] < 0) {
speedY[3] = speedY[3] * -1;
}
if (x[3] > 730) {
speedY[3] = speedY[3] * -1;
}
if (x[3] < 0) {
speedY[3] = speedY[3] * -1;
}
// bal 5
if (y[4] > 730) {
speedY[4] = speedY[4] * -1;
}
if (y[4] < 0) {
speedY[4] = speedY[4] * -1;
}
if (x[4] > 730) {
speedY[4] = speedY[4] * -1;
}
if (x[4] < 0) {
speedY[4] = speedY[4] * -1;
} |
/**
* Expose `pixcha`.
*/
module.exports = pixcha;
/**
* Services.
*/
var services = require('./lib/services');
/**
* @param {String} url
* @param {Object} options
* @return {String}
*/
function pixcha(url, options) {
options = options || {};
var service = pixcha.service(url);
if (!service) return null;
var replace = options.thumbnail
? services[service].thumbnail
: (services[service].larger || services[service].thumbnail);
if ('function' === typeof replace) {
return replace.call(null, url);
}
return url.replace.apply(url, replace);
}
/**
* @param {String} url
* @return {String}
*/
pixcha.thumbnail = function(url) {
return pixcha(url, { thumbnail: true });
};
/**
* @param {String} url
* @return {String}
*/
pixcha.service = function(url) {
for (var service in services) {
var match = url.match(services[service].pattern);
if (match) return service;
}
return null;
};
/**
* @param {String} name
* @param {}
*/ |
'use strict';
const initRadius = 30;
const initWallFriction = 0.075;
const initBallFriction = 0.05;
const initGravity = 0.45;
const initKineticLoss = 1/3;
const initKineticGain = 2/3;
const rectangleColor = "black";
const initBallCnt = 100;
function getRandomColor(){
let red = Math.floor(Math.random() * 3) * 127;
let green = Math.floor(Math.random() * 3) * 127;
let blue = Math.floor(Math.random() * 3) * 127;
let rc = "rgb(" + red + ", " + green + ", " + blue + ")";
return rc;
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
class BallPen extends React.Component{
constructor(props){
super(props);
this.state = {
height: 0,
width: 0,
hasGravity: true,
hasWallFriction: true,
hasBallFriction: true,
hasKineticTransfer: true,
isLeavingTrails: false,
isShowingLabels: false,
};
this.balls = [];
this.friction = initWallFriction;
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.shrinkBalls = this.shrinkBalls.bind(this);
this.accelerateBalls = this.accelerateBalls.bind(this);
this.decelerateBalls = this.decelerateBalls.bind(this);
this.resetBalls = this.resetBalls.bind(this);
}
updateBackground(){
const canvas = this.canvasRef;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.fillStyle = rectangleColor;
ctx.fillRect(0,0, this.state.width, this.state.height);
ctx.closePath();
}
initDisplay(){
this.setState({
hasGravity: false,
hasWallFriction: false,
hasBallFriction: false,
hasKineticTransfer: true,
isLeavingTrails: true,
isShowingLabels: false,
});
for(let i=0; i<initBallCnt; i++){
//Going to make 100 small balls and accelerate them;
let newBall = this.makeRandomBall();
let cnt = 0;
while(newBall === false){
newBall = this.makeRandomBall();
cnt += 1;
if(cnt === 50)
return false;
}
this.balls.push(newBall);
}//end i-for
this.setState({
ballCnt: initBallCnt
});
return true;
}//End initDisplay
makeRandomBall(){
const randomRadius = getRandomInt(3,7);
const randomX = getRandomInt(0+randomRadius, this.state.width - randomRadius);
const randomY = getRandomInt(0+randomRadius, this.state.height - randomRadius);
const randomDX = getRandomInt(5, 20);
const randomDY = getRandomInt(5, 20);
for(let i=0; i<this.balls.length; i++){
const otherBall = this.balls[i];
const minDistance = otherBall.radius + randomRadius;
const currDistance = otherBall.distanceTo(randomX, randomY);
if(currDistance < minDistance){
return false;
}
}
const newBall = new Ball({
ballID: this.balls.length,
color: getRandomColor(),
xCord: randomX,
yCord: randomY,
radius: randomRadius,
dx: randomDX,
dy: randomDY,
});
return newBall;
}//end makeRandomBall
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
//Makes a POST element on submit;
this.setState({
[name]: value
});
}
handleCanvasClick(canvas, xClick, yClick){
const rect = canvas;
const xMousePos = xClick;
const yMousePos = yClick;;
const xCanvasPos = xMousePos - rect.left;
const yCanvasPos = yMousePos - rect.top;
let isLegalBall = true; //Will try to make false;
let didClickBall = false;
for(let i=0; i<this.balls.length; i++){
//See if ball is clicked;
//If ball not clicked, see if new ball is still possible;
const ball = this.balls[i];
const xBall = ball.xCord;
const yBall = ball.yCord;
const xDiff = xCanvasPos - xBall;
const yDiff = yCanvasPos - yBall;
const radius = this.balls[i].radius;
const ballMouseDistance = Math.sqrt(xDiff**2 + yDiff**2);
const clickedBall = ballMouseDistance <= radius;
if (isLegalBall)
isLegalBall = ballMouseDistance >= (radius + initRadius);
if(clickedBall){
ball.accelerate(4*initGravity, 20*initGravity);
didClickBall = true;
break;
}
}//end i-for
if(isLegalBall){
//Check with top, bottom, and sides;
if (xCanvasPos - initRadius < 0)
isLegalBall = false;
else if (xCanvasPos + initRadius > this.state.width)
isLegalBall = false;
else if (yCanvasPos - initRadius < 0)
isLegalBall = false;
else if (yCanvasPos + initRadius > this.state.height)
isLegalBall = false;
}
if(!didClickBall){
//Make new ball;
if(isLegalBall){
console.log('Making new ball' + this.balls.length)
const newBall = new Ball({
ballID: this.balls.length,
color: getRandomColor(),
xCord: xCanvasPos,
yCord: yCanvasPos,
radius: initRadius,
dx: 2,
dy: 2
});
this.balls.push(newBall);
this.setState({
ballCnt: this.state.ballCnt + 1,
});
}
else
console.log('Not legal ball');
}
}
componentDidMount() {
this.updateWindowDimensions();
this.updateCanvas();
this.timerID = setInterval(
()=>this.updateCanvas(),
25
);
window.addEventListener('resize', this.updateWindowDimensions);
}
componentWillUnmount(){
clearInterval(this.timerID);
window.removeEventListener('resize', this.updateWindowDimensions);
}
componentDidUpdate() {
this.updateCanvas();
}
updateWindowDimensions() {
let width = window.innerWidth;
if (width && width >575)
width -= 320; //Buffer for not x-small
else
width -= 120; //Buffer for x-small
let height = window.innerHeight;
height -= 280; //Buffer...
if (height < 0)
height = 0;
this.setState({
width: width,
height: height
});
//Move balls around if conflict;
//Change radius if conflict;
for(let i=0; i<this.balls.length; i++){
let ball = this.balls[i];
let ballBottom = ball.yCord + ball.radius;
let ballTop = ball.yCord - ball.radius;
if(ballBottom > height){
ball.yCord = height - ball.radius;
ball.accelerate(4*initGravity, 20*initGravity);
ball.shrink();
}
if(ballTop <= 0){
ball.shrink();
}
for(let j=i+1; j<this.balls.length; j++){
let otherBall = this.balls[j];
const minDistance = ball.radius + otherBall.radius;
const curDistance = ball.distanceBetween(
ball.xCord,
ball.yCord,
otherBall.xCord,
otherBall.yCord,
);
if(curDistance < minDistance)
ball.shrink();
}
}//end i-for
if(this.state.isLeavingTrails === true && width && width >575){
//Do not change the size if on mobile;
this.updateBackground();
}
return;
}
updateCanvas(){
const canvas = this.canvasRef;
const ctx = canvas.getContext('2d');
if(this.state.width !== 0){
if(this.balls.length === 0){
this.updateBackground();
this.initDisplay();
}// End first ball init;
if(this.state.isLeavingTrails === false){
this.updateBackground();
}
}//end if state.width clarity check;
for(let i=0; i<this.balls.length; i++){
let ball = this.balls[i];
if(!this.state.hasWallFriction)
this.friction = 0;
else
this.friction = initWallFriction;
if(!this.state.hasBallFriction)
ball.friction = 0;
else
ball.friction = initBallFriction;
if(!this.state.hasKineticTransfer){
ball.kineticGain = 1;
ball.kineticLoss = 0;
}
else{
ball.kineticLoss = initKineticLoss;
ball.kineticGain = initKineticGain;
}
//Assume we can go any direction first; Change values on `handle`*;
ball.canGoUp = true;
ball.canGoDown = true;
ball.canGoLeft = true;
ball.canGoRight = true;
//Set wanted coordinates based off of previous movement;
if(ball.isGoingUp)
ball.nextY = ball.yCord - ball.dy;
else if(ball.isGoingDown)
ball.nextY = ball.yCord + ball.dy;
if(ball.isGoingLeft)
ball.nextX = ball.xCord - ball.dx;
else if(ball.isGoingRight)
ball.nextX = ball.xCord + ball.dx;
//See if expected coordinates will prevent us from going certain directions;
ball.handleBoundaries(this.state.width, this.state.height, this.balls);
ball.handleWallCollisions(this.state.width, this.state.height, this.friction);
ball.handleBallCollisions(this.balls);
ball.handleMovement(this.friction);
ball.updateCoordinates();
if( this.state.hasGravity ){
ball.gravity = initGravity;
ball.applyGravity();
}
else{
ball.gravity = 0;
}
ball.draw(ctx);
if(this.state.isShowingLabels)
ball.label(ctx);
}//end i-for
}//End updateCanvas()
shrinkBalls(event){
for(let i=0; i<this.balls.length; i++){
if(Math.random() >=0.5)
this.balls[i].shrink();
}//end i-for
}//end shrinkBalls
accelerateBalls(event){
for(let i=0; i<this.balls.length; i++){
this.balls[i].accelerate( getRandomInt(5,12), getRandomInt(10,20) );
}//end i-for
}//end accelerateBalls
decelerateBalls(event){
for(let i=0; i<this.balls.length; i++){
this.balls[i].decelerate( getRandomInt(1,5), getRandomInt(5,10) );
}//end i-for
}//end accelerateBalls
resetBalls(event){
this.balls = [];
this.setState({
hasGravity: true,
hasWallFriction: true,
hasBallFriction: true,
hasKineticTransfer: true,
isLeavingTrails: false,
isShowingLabels: true,
});
let newBall = this.makeRandomBall();
newBall.radius = 30;
newBall.color = "blue";
this.balls.push(newBall);
this.setState({
ballCnt: 1
});
}//end resetBalls
render(){
const penStyle = {
border: "1px solid #000000"
};
const totalStyle = {
textAlign: "right"
};
return (
<div>
<p style={totalStyle}>
Ball Count: {this.state.ballCnt}
</p>
<canvas
ref={canvas => this. canvasRef = canvas}
width={this.state.width}
height={this.state.height}
style={penStyle}
onClick={e => {
const canvas = this.canvasRef.getBoundingClientRect();
const xClick = e.clientX;
const yClick = e.clientY;
this.handleCanvasClick(canvas, xClick, yClick);
}}
/>
<table width={this.state.width}>
<tbody>
<tr>
<td>
<label>
Has Gravity:
<input
name="hasGravity"
type="checkbox"
checked={this.state.hasGravity}
onChange={this.handleInputChange} />
</label>
</td>
<td>
<label>
Has Wall Friction:
<input
name="hasWallFriction"
type="checkbox"
checked={this.state.hasWallFriction}
onChange={this.handleInputChange} />
</label>
</td>
<td>
<label>
Has Ball Friction:
<input
name="hasBallFriction"
type="checkbox"
checked={this.state.hasBallFriction}
onChange={this.handleInputChange} />
</label>
</td>
</tr>
<tr>
<td>
<label>
Has Kinetic Transfer:
<input
name="hasKineticTransfer"
type="checkbox"
checked={this.state.hasKineticTransfer}
onChange={this.handleInputChange} />
</label>
</td>
<td>
<label>
Leave Trails:
<input
name="isLeavingTrails"
type="checkbox"
checked={this.state.isLeavingTrails}
onChange={this.handleInputChange} />
</label>
</td>
<td>
<label>
Turn on Lables:
<input
name="isShowingLabels"
type="checkbox"
checked={this.state.isShowingLabels}
onChange={this.handleInputChange} />
</label>
</td>
</tr>
<tr>
<td>
<button onClick={this.shrinkBalls}>
Shrink Some Balls
</button>
</td>
<td>
<button onClick={this.accelerateBalls}>
Accelerate Balls
</button>
</td>
<td>
<button onClick={this.decelerateBalls}>
Decelerate Balls
</button>
</td>
</tr>
<tr>
<td>
<button onClick={this.resetBalls}>
Reset Balls
</button>
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(
<BallPen />,
document.getElementById('ball-pen-11')
);
|
import React from 'react';
import { FaArrowLeft } from 'react-icons/fa';
import { useHistory } from 'react-router-dom';
const HeaderWithBack = () => {
let history = useHistory();
const handleBack = () => {
history.goBack();
};
return (
<div className="bg-blue-500 p-4 text-xl text-center text-white font-bold">
<FaArrowLeft
style={{ color: 'white' }}
className="cursor-pointer"
onClick={handleBack}
/>
<div></div>
<div></div>
</div>
);
};
export default HeaderWithBack;
|
import { BadRequestError } from 'error-middleware/errors'
import { getBlockById } from '../../services/db/blocks'
export const showBlock = async (req, res) => {
const { id } = req.params
if (!id) throw new BadRequestError('id is required query params')
const block = await getBlockById(id)
res.json(block)
}
|
import { useForm } from 'react-hook-form';
import { useRouter } from 'next/router';
import { useMutation, useQuery } from '@apollo/react-hooks';
import { UPDATE_ITEM } from './productsMutations';
import { GET_ITEM } from './productsQueries';
const EditProduct = ({ productId }) => {
const { register, handleSubmit } = useForm();
const router = useRouter();
const { loading, error, data } = useQuery(GET_ITEM, {
variables: { id: productId }
});
const [updateItem, { loading: editLoading }] = useMutation(UPDATE_ITEM);
const onSubmit = async args => {
const { data } = await updateItem({
variables: {
...args,
id: productId
}
});
if (data)
router.push({
pathname: '/product',
query: { id: data.updateItem.id }
});
};
if (loading) return <h1>Loading...</h1>;
return (
<fieldset disabled={editLoading}>
<form onSubmit={handleSubmit(onSubmit)}>
<input
ref={register}
type='text'
name='title'
placeholder='Title...'
defaultValue={data.item.title}
/>
<input
ref={register}
type='text'
name='description'
placeholder='Description...'
defaultValue={data.item.description}
/>
<input
ref={register}
type='number'
name='price'
placeholder='Price'
defaultValue={data.item.price}
/>
<input type='submit' value='Update' />
</form>
</fieldset>
);
};
export default EditProduct;
|
function makeScroll() {
$('#bullets').click();
}
setInterval(makeScroll, secs * 1000); |
var base = new Environment("base");
var meterBar = new Environment("meterBar");
var meterOverlay = new Environment("meterOverlay");
var msg = new Entity("msg");
var player = new Entity("player");
var ai = new Entity("ai");
var brain = new Currency("Brain");
var heart = new Currency("Heart");
var hammer = new Currency("Hammer");
var meterLimit = new Currency("meterLimit");
var meter = new Currency("Meter");
var question;
var flag;
var answered;
var optionIndex = 0;
$(function() {
initTheme();
observers();
// parent.setGameAttempt(parent.currentIntegratedGame, parent.currentUid);
// playGame();
window.ondragstart = function() { return false; }
});
function initTheme() {
loadConfig(base);
loadConfig(meterBar);
loadConfig(meterOverlay);
initQuiz();
loadConfig(player);
player.setState('1');
loadConfig(ai);
ai.setState('1');
$("#base img").attr("id", "qt-base-img");
$("#ai img").attr("id", "qt-ai-img");
$("#player img").attr("id", "qt-player-img");
$("#logo img").attr("id", "qt-game-logo");
$("#qt-base-img").attr("src", getImg("qt-background"));
$("#qt-player-img").attr("src", getImg("qt-player"));
$("#qt-ai-img").attr("src", getImg("qt-ai"));
$(".qt-bot-overlay-img").attr("src", getImg("qt-bottom-overlay"));
$("#qt-meter-empty").css({background: "url('" + getImg("qt-meter-bar-empty") + "')"});
$("#qt-meter-filled").css({background: "url('" + getImg("qt-meter-bar-filled") + "')"});
$("#qt-meter-indicator span").text(getText("qt-text-meter"));
$("#leftOpt").attr("src", getImg("qt-arrow-left"));
$("#rightOpt").attr("src", getImg("qt-arrow-right"));
$("#qt-say-button").attr("src", getImg("qt-button-say-this"));
$("#qt-know-more").attr("src", getImg("qt-button-know-more"));
$("#qt-speech-bubble-2").attr("src", getImg("qt-options-back"));
$("#qt-speech-bubble-1").attr("src", getImg("qt-statement-back"));
$("#message-box-bg").attr("src", getImg("qt-message-box-back"));
initGame();
$("#qt-meter-filled").css({width: ai.meter.is()+"%"});
$("#limit").css({left: ai.meterlimit.is()+"%"});
}
function initGame() {
showInstructions();
var random = randBetween(0, game.ai.length-1);
ai.createWallet(brain, 0, 10, game.ai[random].brain);
ai.createWallet(heart, 0, 10, game.ai[random].heart);
ai.createWallet(hammer, 0, 10, game.ai[random].hammer);
ai.createWallet(meterLimit, 0, 100, game.ai[random].limit);
random = randBetween(10,20);
ai.createWallet(meter, 0, 100, random);
ai.points = [];
console.log(ai.brain.is());
console.log(ai.heart.is());
console.log(ai.hammer.is());
ai.points.push(random);
flag = 1;
answered = true;
}
function showInstructions() {
$("#message").css({padding: "2%"});
$("#message").append(
'<div id="game-logo"><img src='+getImg("qt-logo")+' /></div>' +
'<div id="instructions">' +
'<div id="inst-header"></div>' +
'<div id="inst-content" class="mCustomScrollbar"></div>' +
'</div>' +
'<img id="start-game" />'
);
$()
$("#inst-header").text(getText("qt-text-instruction-header"));
$("#inst-content").html(getText("qt-text-instructions"));
$("#start-game").attr('src', getImg("qt-button-start"));
$("#start-game").unbind('mouseover').on('mouseover', function() {
$("#start-game").attr('src', getImg("qt-button-start-hover"));
});
$("#start-game").unbind('mouseout').on('mouseout', function() {
$("#start-game").attr('src', getImg("qt-start"))
});
$("#start-game").unbind('click').on('click', function() {
$("#message-box").fadeOut ();
playGame();
$("#message").css({padding: "7%"});
$("#game-logo").remove();
$("#instructions").remove();
$("#start-game").remove();
});
}
function playGame() {
question = getQuestion();
setTimeout(function() {answered = false;}, 500)
Question.showQuizPanel(quiz, question);
$(".option-block").hide();
optionScroller(0);
}
function getQuestion() {
var question = Question.getByWeight(flag);
// parent.setQuestionAttempt(question.id);
console.log(question);
return question;
}
function processAnswer(data) {
// parent.markQuestionAttemptCorrect();
var points = data.points;
var brain = parseInt(points[0]);
var heart = parseInt(points[1]);
var hammer = parseInt(points[2]);
points = (ai.brain.is()*brain)+(ai.heart.is()*heart)+(ai.hammer.is()*hammer);
ai.meter.is(ai.meter.is() + points);
$(ai.meter).unbind().on('max', function(value, max) {
ai.meter.is(ai.meter.max);
});
$("#qt-meter-filled").animate({
width: ai.meter.is()+"%"
}, 500);
ai.points.push(points);
flag++;
console.log(flag)
if(flag > 10)
endGame();
else
playGame();
return true;
}
function endGame() {
$("*").unbind('click');
$("#qt-meter-filled").fadeOut(250).delay(100).fadeIn(250).delay(100).fadeOut(250).delay(100).fadeIn(250);
setTimeout(function() {
// $("#player").css({opacity: 0.9});
// $("#ai").css({opacity: 0.9});
if(ai.meter.is() > ai.meterlimit.is())
victory();
else
defeat();
}, 2500);
}
function victory() {
$("#message-box").fadeIn();
$("#message").append("<span>You Win!</span>");
}
function defeat() {
$("#message-box").fadeIn();
$("#message").append("<span>You Lose!</span>");
}
function observers() {
var checkEndOfList = function() {
if(optionIndex==0)
$("#leftOpt").css({visibility: "hidden"});
else if(optionIndex==3)
$("#rightOpt").css({visibility: "hidden"});
else
{
$("#leftOpt").css({visibility: "visible"});
$("#rightOpt").css({visibility: "visible"});
}
}
checkEndOfList();
$("#leftOpt").unbind('click').on('click', function() {
changeOption($(".option-show").attr("id"), "left");
checkEndOfList();
});
$("#rightOpt").unbind('click').on('click', function() {
changeOption($(".option-show").attr("id"), "right");
checkEndOfList();
});
$("#qt-say-button").unbind('click').on('click', function() {
if(answered == false) {
$(".option-block:first").trigger('click');
$("#leftOpt").css({visibility: "hidden"});
$("#rightOpt").css({visibility: "visible"});
optionIndex = 0;
$(question).unbind('answered').on('answered', function (e, data) {
answered = true;
processAnswer(data);
});
}
});
}
function changeOption(id, direction) {
optionIndex = parseInt(id.charAt(id.length-1));
console.log(optionIndex);
switch(direction) {
case "left":
if(optionIndex != 0)
optionIndex--;
else
optionIndex = question.options.length - 1;
optionScroller(optionIndex);
break;
case "right":
if(optionIndex != question.options.length - 1)
optionIndex++;
else if(optionIndex==1)
$("#leftOpt").css({visibility: "hidden"});
else
optionIndex = 0;
optionScroller(optionIndex);
break;
}
}
function optionScroller(optionIndex) {
$(".option-block").removeClass("option-show");
$("#option-block-"+optionIndex).addClass("option-show");
$("#option-block-"+optionIndex).hide();
$("#option-block-"+optionIndex).fadeIn(500);
}
|
import React from 'react'
import Result from './components/Result'
import MathOperations from './components/MathOperations'
import Functions from './components/Functions'
import Numbers from './components/Numbers'
import './App.css'
const App = () => (
<main className="react-calculator">
<Result value={ '0' }/>
<Numbers onClickNumber={ number => console.log(number) }/>
<Functions
onContentClear={ clear => console.log(clear) }
onDelete={ del => console.log(del) } />
<MathOperations
onClickOperation={ operation => console.log(operation) }
onClickEqual={ equal => console.log(equal) }/>
</main>
)
export default App |
const express = require('express');
const router = express.Router();
const genericService = require('../services/genericService')
/**
* @swagger
* /api/generic/getLeftMenu:
* get:
* description: Get Left Menu
* responses:
* '200':
* description: Success
*/
router.get('/getLeftMenu', function (req, res) {
genericService.getLeftMenu(req, function (lstMenu) {
res.send(lstMenu);
})
});
router.get('/autocomplete/:widget/:field/:code?', function (req, res) {
genericService.getAutoComplete(req, function (autocompleteList) {
res.send(autocompleteList);
})
});
router.get('/autocompletelabel/:widget/:field/:code', function (req, res) {
genericService.getAutoCompleteLabel(req, function (autocompleteMap) {
res.send(autocompleteMap);
})
});
router.post('/uploadProfilePic', function (req, res) {
genericService.uploadProfilePic(req, function (profile) {
res.send(profile);
})
});
router.post('/attachment/upload/:fileType/:moduleName/:moduleCode', function (req, res) {
genericService.upload(req, function (lstUploads) {
res.send(lstUploads);
})
});
router.all('/widget/:widget?/:action?/:term1?/:term2?/:term3?/:term4?', function (req, res) {
genericService.getWidget(req, function (retObj) {
if (retObj.file != null) {
res.status(200);
res.set({
'Cache-Control': 'no-cache',
'Content-Type': "application/octet-stream",
'Content-Length': retObj.fileSize,
'Content-Disposition': 'inline; filename=' + retObj.fileName
});
res.send(retObj.file);
}
else {
res.send(retObj);
}
})
});
module.exports = router;
|
const lib = require("blib");
require("turret/T2duo");
require("turret/T3duo");
require("turret/hurricane");
require("turret/ms");
require("turret/T2lancer");
require("turret/stinger");
require("turret/miniswarmer");
require("turret/T2swarmer");
require("turret/T2ripple");
require("turret/T3ripple");
require("turret/T2fuse");
require("turret/T3fuse");
require("turret/RG");
require("block/he");
require("power/png");
require("power/T2steam");
require("block/drill");
require("block/T2PC");
require("block/T2PF");
require("block/T2CM");
require("block/T2SA");
require("block/T2IB");
require("block/IN");
require("block/LB");
require("block/core");
require("block/cure");
require("block/unitA");
require("unit/UF");
require("unit/tera");
require("unit/nebula");
require("tree");
lib.mod.meta.displayName = lib.getMessage('mod', 'displayName');
lib.mod.meta.description = lib.getMessage('mod', 'description');
|
/*
Kinda a silly example of how to use a helper module
Let's say you had multiple components that need to calculate
the average and standard deviation for a chunk of data.
You could define these functions once in a helper module,
and then import that into whatever component needs it.
*/
const allCaps = (string) => {
return string.toUpperCase();
}
module.exports = {
allCaps,
} |
import './b.css';
import Vue from 'vue';
// import upperCamelCase from 'uppercamelcase';
export default {
name: 'Async module',
say() {
console.log('Vue is ', Vue);
}
};
|
var assert = require('assert');
var sinon = require('sinon');
var MiniJest = require('../index.js');
var testThing = new MiniJest.Base();
var beforeSpy = sinon.spy();
var afterSpy = sinon.spy();
testThing.fn.beforeAll = beforeSpy;
testThing.fn.afterAll = afterSpy;
describe('beforeAll', function() {
it('runs', function() {
testThing.run({ noExit: true });
assert(beforeSpy.called);
});
});
describe('afterAll', function() {
it('runs', function() {
testThing.run({ noExit: true });
assert(afterSpy.called);
});
});
|
import Bookshelf from 'bookshelf';
import Knex from 'knex';
import plaidConfig from 'plaid.config';
const dbSettings = plaidConfig.db.mysql;
const knexInstance = Knex({
client: 'mysql',
connection: {
host: dbSettings.host,
port: dbSettings.port,
database: dbSettings.database,
user: dbSettings.user,
password: dbSettings.password,
},
pool: {
min: 10,
max: dbSettings.connectionLimit,
},
debug: plaidConfig.server.isDevMode,
});
const bookshelfInstance = Bookshelf(knexInstance);
bookshelfInstance.plugin('registry');
export default bookshelfInstance;
export const knex = bookshelfInstance.knex;
|
import {checkLogin,onUserInfoUpdate,login,logout,} from './user/index';
export default {
checkLogin,
onUserInfoUpdate,
login,
logout,
}; |
const fs = require('fs');
const path = require('path');
const reload = require('require-reload')(require);
module.exports = class CommandLoader {
constructor(client, cPath) {
this.commands = [];
this.path = path.resolve(cPath);
this.client = client;
}
/**
* Loads commands from a folder
* @param {String} folderPath
*/
iterateFolder(folderPath) {
const files = fs.readdirSync(folderPath);
files.map(file => {
const filePath = path.join(folderPath, file);
const stat = fs.lstatSync(filePath);
if (stat.isSymbolicLink()) {
const realPath = fs.readlinkSync(filePath);
if (stat.isFile() && file.endsWith('.js')) {
this.load(realPath);
} else if (stat.isDirectory()) {
this.iterateFolder(realPath);
}
} else if (stat.isFile() && file.endsWith('.js'))
this.load(filePath);
else if (stat.isDirectory())
this.iterateFolder(filePath);
});
}
/**
* Loads a command
* @param {string} commandPath
*/
load(commandPath) {
console.fileload('Loading command', commandPath);
const cls = reload(commandPath);
const cmd = new cls(this.client);
cmd.path = commandPath;
this.commands.push(cmd);
return cmd;
}
/**
* Reloads all commands
*/
reload() {
this.commands = [];
this.iterateFolder(this.path);
}
/**
* Gets a command based on it's name or alias
* @param {string} name The command's name or alias
*/
get(name) {
let cmd = this.commands.find(c => c.name === name);
if (cmd) return cmd;
this.commands.forEach(c => {
if (c.options.aliases.includes(name)) cmd = c;
});
return cmd;
}
/**
* Preloads a command
* @param {string} name The command's name or alias
*/
preload(name) {
if (!this.get(name)) return;
this.get(name)._preload();
}
/**
* Preloads all commands
*/
preloadAll() {
this.commands.forEach(c => c._preload());
}
/**
* Processes the cooldown of a command
* @param {Message} message
* @param {Command} command
*/
async processCooldown(message, command) {
if (this.client.config.elevated.includes(message.author.id)) return true;
const now = Date.now() - 1;
const cooldown = command.cooldownAbs;
let userCD = await this.client.db.hget(`cooldowns:${message.author.id}`, command.name) || 0;
if (userCD) userCD = parseInt(userCD);
if (userCD + cooldown > now) return false;
await this.client.db.hset(`cooldowns:${message.author.id}`, command.name, now);
return true;
}
};
|
const Config = {
server:{
host: 'http://localhost:44330'
},
localStorage:{
user:'stack_overflow_user',
token: 'stack_overflow_token'
}
}
export default Config; |
var request = require("request");
var pjson = require('../../conf.json');
var base_url = "https://" + pjson.appName + "." + pjson.zoneName
describe("Retrieve app metadata", function() {
describe("GET /metadata", function() {
it("returns status code 200", function(done) {
request.get(base_url, function(error, response, body) {
expect(response.statusCode).toBe(200);
done();
});
});
it("returns app metadata", function(done) {
request.get(base_url + "/metadata", function(error, response, body) {
expect(body).toContain("statistics-lambda-app");
done();
});
});
});
});
|
module.exports = require('./lib/util.js').default;
|
const deleteHandler = e => {
$(e.target).parent().attr("data-id");
};
const genPair = pair =>
`<div data-id=${pair.id} class="container--center g--12">
<div contenteditable class="card g--2">${pair.name}</div>
<div contenteditable class="card g--4">${pair.value}</div>
<div class="icon-holder">
<i class="material-icons md-48">close</i>
</div>
</div>`;
const render = html => {
$("body").html(html);
};
$(() => {
render(genPair({ name: "PATH", value: "/usr/local/bin" }));
});
|
import './ui.data_grid.editor_factory';
import gridCore from './ui.data_grid.core';
import { editingModule } from '../grid_core/ui.grid_core.editing';
import { extend } from '../../core/utils/extend';
gridCore.registerModule('editing', extend(true, {}, editingModule, {
extenders: {
controllers: {
data: {
_changeRowExpandCore: function _changeRowExpandCore(key) {
var editingController = this._editingController;
if (Array.isArray(key)) {
editingController && editingController.refresh();
}
return this.callBase.apply(this, arguments);
}
}
}
}
})); |
import DefaultSpinner from "common/components/Spinner"
import React from "react"
import { Card, ListGroup } from "react-bootstrap"
import { useSelector } from "react-redux"
import { useParams } from "react-router-dom"
import { selectUserById, selectUsersFetching } from "./usersSlice"
export default function UserInfo(props) {
const { userId } = useParams()
const user = useSelector((state) => selectUserById(state, { id: userId }))
const fetching = useSelector(selectUsersFetching)
return (
<>
{!fetching && user ? (
<Card className="mt-3 mb-3">
<Card.Header>User Info</Card.Header>
<Card.Body>
<Card.Text>
<ListGroup variant="flush">
<ListGroup.Item>
<strong>Name:</strong> {user.name}
</ListGroup.Item>
<ListGroup.Item>
<strong>Address:</strong> {user.address.city},{" "}
{user.address.street} {user.address.suite},{" "}
{user.address.zipcode}
</ListGroup.Item>
<ListGroup.Item>
<strong>Phone:</strong> {user.phone}
</ListGroup.Item>
<ListGroup.Item>
<strong>Website:</strong>{" "}
<a href={`https://${user.website}`}>{user.website}</a>
</ListGroup.Item>
<ListGroup.Item>
<strong>Company:</strong> {user.company.name}
</ListGroup.Item>
</ListGroup>
</Card.Text>
</Card.Body>
</Card>
) : (
<DefaultSpinner />
)}
</>
)
}
|
import React, { useRef, useState } from 'react'
import { usePayment } from '../../context/PaymentProvider';
import { Formik, Form } from "formik";
import * as Yup from 'yup';
import MaskedInput from 'react-text-mask'
import { useHistory } from 'react-router-dom';
import Resume from '../../components/Resume';
import { Title } from '../../components/Title';
import { Section } from '../../components/Section';
import { useOrder } from '../../context/OrderContext';
import { MainContent } from '../../components/MainContent';
import Button from '../../components/Button';
import InputField from '../../components/InputField';
import { Card } from '../../components/Card';
import { SplitContainer } from './style'
function Payment() {
const { setPaymentData } = usePayment();
const { loading, order } = useOrder();
const [ disableBtn, setDisableBtn ] = useState(false);
const history = useHistory();
const formRef = useRef()
const schema = Yup.object({
cardNumber: Yup.string()
.min(19,'O cartão precisa ter 16 números')
.required('Campo obrigatório.'),
cardName: Yup.string()
.min(3,'O nome do cartão precisa ter no minimo 3 letras')
.required('Campo obrigatório.'),
cardExpiress: Yup.string()
.matches(/^((0[1-9])|(1[0-2]))\/(\d{4})$/, 'Data Incorreta')
.required('Campo obrigatório.'),
cvv: Yup.string().
min(3,'O Código CCV precisa ter 3 números').
required('Campo obrigatório.'),
})
const initialValues = {
cardNumber: '',
cardName: '',
cardExpiress: '',
cvv: ''
}
const masks = {
creditCard: [/\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/],
cardExpiress: [/\d/,/\d/, '/', /\d/,/\d/,/\d/,/\d/],
cvv: [/\d/,/\d/,/\d/]
}
const handleSubmit = () => {
formRef.current.submitForm()
}
const onSubmit = ( values, { setSubmitting, resetForm }) => {
setDisableBtn(true)
setPaymentData({ ...values, empty: false })
history.push('/order-placed')
}
return (
<Section data-testid="payment">
{loading
? <span> carregando... </span>
: (
<>
<MainContent>
<Title> Cartão de crédito </Title>
<Card>
<Formik
initialValues={initialValues}
validationSchema={schema}
innerRef={formRef}
onSubmit={onSubmit}
>
{({ status, isSubmitting, submitForm }) => (
<Form data-testid="form">
<InputField
as={MaskedInput}
name="cardNumber"
type="text"
label="Número do Cartão:"
placeholder="____.____.____.____"
mask={masks.creditCard}
guide={false}
data-testid="input-cardNumber"
/>
<InputField
name="cardName"
type="text"
label="Nome do titular:"
placeholder="Como no cartão"
data-testid="input-cardName"
/>
<SplitContainer >
<InputField
as={MaskedInput}
column={1.6}
name="cardExpiress"
type="text"
label="Validade mês/ano:"
placeholder="__/____"
mask={masks.cardExpiress}
guide={false}
data-testid="input-cardExpiress"
/>
<InputField
as={MaskedInput}
column={3}
name="cvv"
type="text"
label="CVV:"
placeholder="___"
guide={false}
mask={masks.cvv}
data-testid="input-cvv"
/>
</SplitContainer>
</Form>
)}
</Formik>
</Card>
</ MainContent>
<Resume data={order}>
<Button disabled={disableBtn} onClick={handleSubmit}> FINALIZAR O PEDIDO </Button>
</Resume>
</>
)}
</Section>
)
}
export default Payment
|
const displayEvents = (name, batch) => {
fetch(`/getEvents/${name}/${batch}/${dateDisplay}`, {
method: "Get",
}).then((res) => {
res.json().then((result) => {
const events = Array.from(result.results);
events.forEach((event) => {
const { teacher_name, batch_name, start_time, end_time, task } = event;
const divBlock = document.createElement("div");
divBlock.className = "flex-item temp";
const Tname = document.createElement("div");
Tname.className = "flex-sub-item";
Tname.innerText = teacher_name;
divBlock.appendChild(Tname);
const Bname = document.createElement("div");
Bname.className = "flex-sub-item";
Bname.innerText = batch_name;
divBlock.appendChild(Bname);
const ST = document.createElement("div");
ST.className = "flex-sub-item";
ST.innerText = start_time;
divBlock.appendChild(ST);
const ET = document.createElement("div");
ET.className = "flex-sub-item";
ET.innerText = end_time;
divBlock.appendChild(ET);
const Task = document.createElement("div");
Task.className = "flex-sub-item";
Task.innerText = task;
divBlock.appendChild(Task);
const delD = document.createElement("div");
const del = document.createElement("i");
delD.className = "flex-sub-item";
del.className = "fas fa-trash-alt cursor";
delD.appendChild(del);
divBlock.appendChild(delD);
const editD = document.createElement("div");
const edit = document.createElement("i");
editD.className = "flex-sub-item";
edit.className = "fas fa-pencil-alt cursor";
editD.appendChild(edit);
divBlock.appendChild(editD);
main.appendChild(divBlock);
const modalBg = document.querySelector(".modal-bg");
const modalClose = document.querySelector(".modal-close");
edit.addEventListener("click", () => {
modalBg.classList.add("bg-active");
updateBtn.addEventListener("click", () => {
modalBg.classList.remove("bg-active");
const prevData = {
pTname: teacher_name,
pBname: batch_name,
pST: start_time,
pET: end_time,
pTask: task,
};
const nTname = document.querySelector("#newTName").value;
const nBname = document.querySelector("#newBName").value;
const nST = document.querySelector("#newST").value;
const nET = document.querySelector("#newET").value;
const nTask = document.querySelector("#newTask").value;
if (nTname.length > 0) Tname.innerText = nTname;
if (nBname.length > 0) Bname.innerText = nBname;
if (nST.length > 0) ST.innerText = nST;
if (nET.length > 0) ET.innerText = nET;
if (nTask.length > 0) Task.innerText = nTask;
const newData = {
nTname,
nBname,
nST,
nET,
nTask,
};
updateData(prevData, newData, ST, ET);
});
});
modalClose.addEventListener("click", () => {
modalBg.classList.remove("bg-active");
});
del.addEventListener("click", () => {
deleteData(event, divBlock);
});
divBlock.setAttribute("draggable", "true");
divBlock.addEventListener("dragstart", () => {
setTimeout(() => {
divBlock.className += " hide";
}, 10);
dragAndDrop(divBlock, event, events);
console.log("dragstart");
});
});
});
});
};
|
var contractPlanType_js = [];
var app = angular.module('luckLog', []);
//定义合约列表控制器
app.controller('luckLog', function ($rootScope, $scope, $http, $timeout) {
var path = window.location.protocol + '//' + window.location.host;
var defaultPageSize = 10;
$scope.luckList = [];
$scope.pageSizeList = [5,10,20];
$scope.name = "";
$scope.isNotNull = function (param) {
if (param == undefined || param === "") {
return false;
}
return true;
};
$scope.getCurrentDate = function(){
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
return currentdate;
};
$scope.pageData = function (pageObj) {
console.log("name---------"+$scope.name);
console.log(pageObj.pageNum+"-------"+pageObj.pageSize);
$http({
method: "post",
url: path + "/admin/user_info/pageLuckLog?pageNum="+pageObj.pageNum+"&pageSize="+pageObj.pageSize+"&name="+encodeURIComponent($("#name").val())+"&startDate="+$("#startDate").val()+"&endDate="+$("#endDate").val(),
data: {}
}).success(function (rs) {
if (rs && rs.code == 0) {
console.log(rs);
$scope.luckList = rs.data.list;
$scope.page = {
pageCount: rs.data.pages,
pageNum: rs.data.pageNum,
pageSize: rs.data.pageSize,
pageSizeList: $scope.pageSizeList,
total: rs.data.total
};
} else {
console.log("获取红包数据异常!");
console.log(rs);
}
}).error(function (rs) {
console.log("获取红包数据异常!");
console.log(rs);
});
};
$scope.initData = function () {
$("#startDate").val($scope.getCurrentDate());
$("#endDate").val($scope.getCurrentDate());
$scope.pageData({"pageNum":1,"pageSize":defaultPageSize});
};
$scope.initData();
});
//获取URL带的参数
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
|
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const users = [
{
'phoneNumber': 89115068341,
'waitingDocuments': [1, 2, 3],
'signedDocuments': [1, 2, 3]
}
];
const documents = [
{
'id': 1,
'createUser': 89115068341,
'img': null,
'createDate': 'test',
'termMonth': 3,
'signStatus': false,
'signerFirst': {
'phoneNumber': 89999999999,
'signStatus': false,
},
'signerSecond': {
'phoneNumber': 87777777777,
'signStatus': true,
}
},
{
'id': 2,
'createUser': 89115068341,
'img': null,
'createDate': 'test',
'termMonth': 3,
'signStatus': false,
'signerFirst': {
'phoneNumber': 89999999999,
'signStatus': true,
},
'signerSecond': {
'phoneNumber': 87777777777,
'signStatus': false,
}
},
{
'id': 3,
'createUser': 89115068341,
'img': null,
'createDate': 'test',
'termMonth': 3,
'signStatus': false,
'signerFirst': {
'phoneNumber': 89999999999,
'signStatus': true,
},
'signerSecond': {
'phoneNumber': 87777777777,
'signStatus': true,
}
},
{
'id': 4,
'createUser': 89115068341,
'img': null,
'createDate': 'test',
'termMonth': 3,
'signStatus': true,
'signerFirst': {
'phoneNumber': 89999999999,
'signStatus': true,
},
'signerSecond': {
'phoneNumber': 87777777777,
'signStatus': true,
}
},
{
'id': 5,
'createUser': 89115068341,
'img': null,
'createDate': 'test',
'termMonth': 3,
'signStatus': false,
'signerFirst': {
'phoneNumber': 89999999999,
'signStatus': false,
},
'signerSecond': {
'phoneNumber': 87777777777,
'signStatus': true,
}
},
]
app.get('/documents/waiting', (req, res) => {
const phoneNumber = req.header('phoneNumber');
const result = [];
if (documents.length > 0) {
documents.forEach(item => {
if (item.createUser == phoneNumber && item.signerFirst.signStatus && item.signerSecond.signStatus && !item.signStatus) {
result.push(item)
} else if (item.signerFirst.phoneNumber == phoneNumber && !item.signerFirst.signStatus) {
result.push(item)
} else if (item.signerSecond.phoneNumber == phoneNumber && !item.signerSecond.signStatus) {
result.push(item)
}
})
}
res.send(result);
})
app.get('/documents/signed', (req, res) => {
const result = [];
if (documents.length > 0) {
documents.forEach(item => {
if (item.signStatus) {
result.push(item)
}
})
}
res.send(result);
})
app.get('/document', (req, res) => {
let document;
documents.forEach(doc => {
if (doc.id == req.query.id) document = doc;
})
res.send(document);
})
app.post('/documents/create', (req, res) => {
let data = JSON.parse(JSON.stringify(req.body))
let max = 0;
documents.forEach(doc => {
if(doc.id > max) max = doc.id;
})
data.id = max + 1;
documents.push(data);
res.send('');
})
app.post('/document/sign', (req, res) => {
let data = JSON.parse(JSON.stringify(req.body));
documents.forEach(doc => {
if(doc.id == data.id){
if(doc.createUser == data.phoneNumber){
doc.signStatus = true;
}else if(doc.signerFirst.phoneNumber == data.phoneNumber){
doc.signerFirst.signStatus = true;
}else if(doc.signerSecond.phoneNumber == data.phoneNumber){
doc.signerSecond.signStatus = true;
}
}
})
res.send('');
})
app.post('/login', (req, res) => {
res.send('');
})
app.listen(8888); |
import { Meteor } from 'meteor/meteor';
import Folders from '../api/folders/folders';
import Bookmarks from '../api/bookmarks/bookmarks';
export const can = ({
delete: ({
bookmark(bookmarkId) {
return userOwnsOrInvitedBookmark(bookmarkId);
},
folder(folderId) {
return userOwnsFolder(folderId);
}
}),
edit: ({
bookmark(bookmarkId) {
return userOwnsOrInvitedBookmark(bookmarkId);
},
bookmarks(folderId) {
return userOwnsOrInvitedFolder(folderId);
},
folder(folderId) {
return userOwnsOrInvitedFolder(folderId);
},
privacy(folderId) {
return userOwnsFolder(folderId);
}
}),
create: ({
bookmark(folderId) {
return userOwnsOrInvitedFolder(folderId);
},
multipleBookmarks(folderId) {
return userOwnsFolder(folderId);
},
folder() {
if(Meteor.userId()) return true;
else return false;
}
}),
view: ({
folder(folderId) {
return userOwnsOrInvitedOrPublicFolder(folderId);
}
}),
})
const userOwnsBookmark = (bookmarkId) => {
const bookmark = Bookmarks.findOne(bookmarkId);
const folder = Folders.findOne(bookmark.folderId);
return (folder && folder.createdBy === Meteor.userId());
}
const userOwnsOrInvitedBookmark = (bookmarkId) => {
const bookmark = Bookmarks.findOne(bookmarkId);
const folder = Folders.findOne(bookmark.folderId);
return (folder && folder.createdBy === Meteor.userId()
|| _.contains(folder.invitedMembers, Meteor.userId()));
}
const userOwnsFolder = (folderId) => {
const folder = Folders.findOne(folderId);
return (folder && folder.createdBy === Meteor.userId());
}
const userOwnsOrPublicFolder = (folderId) => {
const folder = Folders.findOne(folderId);
return (folder && (!folder.private || folder.createdBy === Meteor.userId()));
}
const userOwnsOrInvitedFolder = (folderId) => {
const folder = Folders.findOne(folderId);
return (folder && (folder.createdBy === Meteor.userId()
|| _.contains(folder.invitedMembers, Meteor.userId())));
}
const userOwnsOrInvitedOrPublicFolder = (folderId) => {
const folder = Folders.findOne(folderId);
return (folder && (!folder.private
|| folder.createdBy === Meteor.userId()
|| _.contains(folder.invitedMembers, Meteor.userId())));
}
|
jQuery(document).ready(function() {
//all those containers we need to overflow, lets do it here faq
jQuery("#container, #everything, .my_overflow, #left, #my_content_here, #main_center, .box_with_title").css("overflow", "auto");
$(".add_notice1").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 920, height : 570, type : 'iframe', title : 'Add Notice', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".edit_profile").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 920, height : 480, type : 'iframe', title : 'Edit Profile', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".post").click(function()
{
var url = $(this).attr("href");
TopUp.display ('assets/user_status.php',
{width : 920, height : 250, type : 'iframe', title : 'Post Message', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".add_notice").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 920, height : 570, type : 'iframe', title : 'Add Notice', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_response").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 920, height : 570, type : 'iframe', title : 'Add Topic Response', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_qresponse").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 920, height : 570, type : 'iframe', title : 'Add Query Response', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_topic").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 720, height : 350, type : 'iframe', title : 'Add Forum', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_forum").click(function()
{ TopUp.display ('assets/forum_addforum.php',
{width : 620, height : 300, type : 'iframe', title : 'Add Forum', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_help").click(function()
{ TopUp.display ('assets/forum_addhelp.php',
{width : 620, height : 300, type : 'iframe', title : 'Add Query', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".add_event").click(function()
{ TopUp.display ('assets/news_addevent.php',
{width : 820, height : 600, type : 'iframe', title : 'Add Event', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".user_add_gallery").click(function()
{
var t = $(this).attr("id");
if (t != "") url = 'assets/user_addgallery.php?albumtype=public';
else url = 'assets/user_addgallery.php?albumtype=private';
TopUp.display (url,
{width : 720, height : 350, type : 'iframe', title : 'Add Album', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".user_edit_gallery").click(function()
{
var url = $(this).attr("href");
TopUp.display (url,
{width : 720, height : 350, type : 'iframe', title : 'Edit Album', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".add_images").click(function()
{
var t = $(this).attr("id");
url = 'assets/ga_addimages.php?albumid='+t;
TopUp.display (url,
{width : 820, height : 950, type : 'iframe', title : 'Add Photos', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".user_status").click(function()
{ TopUp.display ('assets/user_status.php',
{width : 620, height : 310, type : 'iframe', title : 'Update Status', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".user_post").click(function()
{ TopUp.display ('assets/user_post.php',
{width : 620, height : 310, type : 'iframe', title : 'Post Message', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".forum_add_category").click(function()
{ TopUp.display ('assets/dl_addcategory.php',
{width : 620, height : 240, type : 'iframe', title : 'Add download Category', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
$(".change_profile_picture").click(function()
{ TopUp.display ('assets/user_profile_picture.php',
{width : 620, height : 390, type : 'iframe', title : 'Change Profile Picture', layout : 'dashboard', shaded: 1, effect:'fade', onclose:"refresh_page()"});
return false;
});
//used to select all checkboxes or clear them
$("#checkboxall").click(function()
{
var sta = $('#checkboxall').is(':checked');
$("input[type='checkbox']:not([disabled='disabled'])").attr('checked', sta);
});
});
function increase_height(){
jQuery(document).ready(function() {
});
}
function refresh_page(){
window.location.reload();
}
//used to confrm a delete before proceeding
function confirmfirst(url)
{
var answer = confirm("This action is not reversable, are you sure you want to delete this item?")
if (answer){
window.location = url;
}
return false;
}
//used to submit the form when multiple check items are selected
function submitform()
{
var answer = confirm("This action is not reversable, are you sure you want to delete the selected items?")
if (answer){
document.forms["selected_form"].submit();
}
}
//our tabs code
jQuery(document).ready(function(){
// When user clicks on tab, this code will be executed
jQuery("#tabs li").click(function() {
// First remove class "active" from currently active tab
jQuery("#tabs li").removeClass('active');
// Now add class "active" to the selected/clicked tab
jQuery(this).addClass("active");
// Hide all tab content
jQuery(".tab_content").hide();
// Here we get the href value of the selected tab
var selected_tab = jQuery(this).find("a").attr("href");
// Show the selected tab content
jQuery(selected_tab).fadeIn();
// At the end, we add return false so that the click on the link is not executed
return false;
});
});
/*default text */
jQuery(document).ready(function()
{
jQuery(".defaultText").focus(function(srcc)
{
if (jQuery(this).val() == jQuery(this)[0].title)
{
jQuery(this).removeClass("defaultTextActive");
jQuery(this).val("");
}
});
jQuery(".defaultText").blur(function()
{
if (jQuery(this).val() == "")
{
jQuery(this).addClass("defaultTextActive");
jQuery(this).val(jQuery(this)[0].title);
}
});
jQuery(".defaultText").blur();
});
|
import * as React from "react";
import Popover from "@mui/material/Popover";
import { useDispatch, useSelector } from "react-redux";
import Typography from "@mui/material/Typography";
import ImageListItem from "@mui/material/ImageListItem";
import RemoveRedEyeOutlinedIcon from "@mui/icons-material/RemoveRedEyeOutlined";
import Button from "@mui/material/Button";
export default function BasicPopover(props) {
const [anchorEl, setAnchorEl] = React.useState(null);
const dispatch = useDispatch();
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const open = Boolean(anchorEl);
const id = open ? "simple-popover" : undefined;
return (
<div>
<Button
aria-describedby={id}
style={{ color: "blue" }}
onClick={handleClick}
>
<RemoveRedEyeOutlinedIcon />
</Button>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: "center",
horizontal: "center",
}}
>
<img
src={`http://localhost:3000/uploads/${props.file}`}
style={{
borderRadius: "50%",
border:"5px dashed #666",
width: "300px",
objectFit: "center",
height: "250px",
}}
alt={props.file}
/>
</Popover>
</div>
);
}
|
// express and mongoose
const expressLoader = require('./express');
const mongooseLoader = require('./mongoose');
module.exports = async(app) => {
// db
const mongoConnection = await mongooseLoader();
console.log("MongoDB has initialized !");
// express
await expressLoader(app).then((result) => console.log('Express has initialized !'));
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const GameSettingsResource_1 = require("../data/GameSettingsResource");
class GameSettingsEditor {
constructor(container, projectClient) {
this.fields = {};
this.onResourceReceived = (resourceId, resource) => {
this.resource = resource;
this._setupCustomLayers();
for (const setting in resource.pub) {
if (setting === "formatVersion" || setting === "customLayers")
continue;
if (setting === "startupSceneId")
this._setStartupScene(resource.pub.startupSceneId);
else
this.fields[setting].value = resource.pub[setting];
}
};
this.onResourceEdited = (resourceId, command, propertyName) => {
if (propertyName === "customLayers")
this._setupCustomLayers();
else if (propertyName === "startupSceneId")
this._setStartupScene(this.resource.pub.startupSceneId);
else
this.fields[propertyName].value = this.resource.pub[propertyName];
};
this.onCustomLayerFieldChange = (event) => {
const index = parseInt(event.target.dataset["customLayerIndex"], 10);
if (index > this.customLayers.length)
return;
if (index === this.customLayers.length) {
if (event.target.value === "")
return;
this.customLayers.push(event.target.value);
}
else {
if (event.target.value === "") {
if (index === this.customLayers.length - 1) {
this.customLayers.pop();
}
else {
new SupClient.Dialogs.InfoDialog("Layer name cannot be empty");
event.target.value = this.customLayers[index];
return;
}
}
else {
this.customLayers[index] = event.target.value;
}
}
this.projectClient.editResource("gameSettings", "setProperty", "customLayers", this.customLayers);
};
this.projectClient = projectClient;
const { tbody } = SupClient.table.createTable(container);
this.startupSceneRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("settingsEditors:Game.startupScene"));
this.sceneFieldSubscriber = SupClient.table.appendAssetField(this.startupSceneRow.valueCell, this.sceneAssetId, "scene", projectClient);
this.sceneFieldSubscriber.on("select", (assetId) => {
this.projectClient.editResource("gameSettings", "setProperty", "startupSceneId", assetId);
});
this.fpsRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("settingsEditors:Game.framesPerSecond"));
this.fields["framesPerSecond"] = SupClient.table.appendNumberField(this.fpsRow.valueCell, "", { min: 1 });
this.ratioRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("settingsEditors:Game.screenRatio"));
const ratioContainer = document.createElement("div");
ratioContainer.className = "";
this.ratioRow.valueCell.appendChild(ratioContainer);
[this.fields["ratioNumerator"], this.fields["ratioDenominator"]] = SupClient.table.appendNumberFields(this.ratioRow.valueCell, ["", ""]);
this.fields["ratioNumerator"].placeholder = SupClient.i18n.t("settingsEditors:Game.width");
this.fields["ratioDenominator"].placeholder = SupClient.i18n.t("settingsEditors:Game.height");
this.customLayersRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("settingsEditors:Game.layers"));
this.layerContainers = document.createElement("div");
this.layerContainers.className = "list";
this.customLayersRow.valueCell.appendChild(this.layerContainers);
this.fields["defaultLayer"] = SupClient.table.appendTextField(this.layerContainers, "Default");
this.fields["defaultLayer"].readOnly = true;
for (let i = 0; i < GameSettingsResource_1.default.schema["customLayers"].maxLength; i++) {
const field = this.fields[`customLayer${i}`] = SupClient.table.appendTextField(this.layerContainers, "");
field.dataset["customLayerIndex"] = i.toString();
field.addEventListener("change", this.onCustomLayerFieldChange);
}
this.fields["framesPerSecond"].addEventListener("change", (event) => {
this.projectClient.editResource("gameSettings", "setProperty", "framesPerSecond", parseInt(event.target.value, 10));
});
this.fields["ratioNumerator"].addEventListener("change", (event) => {
this.projectClient.editResource("gameSettings", "setProperty", "ratioNumerator", parseInt(event.target.value, 10));
});
this.fields["ratioDenominator"].addEventListener("change", (event) => {
this.projectClient.editResource("gameSettings", "setProperty", "ratioDenominator", parseInt(event.target.value, 10));
});
this.projectClient.subResource("gameSettings", this);
}
_setStartupScene(id) {
this.sceneAssetId = id;
this.sceneFieldSubscriber.onChangeAssetId(id);
}
_setupCustomLayers() {
this.customLayers = this.resource.pub.customLayers.slice(0);
for (let i = 0; i < GameSettingsResource_1.default.schema["customLayers"].maxLength; i++) {
const field = this.fields[`customLayer${i}`];
if (i === this.customLayers.length) {
field.placeholder = SupClient.i18n.t("settingsEditors:Game.newLayer");
field.value = "";
}
else {
field.placeholder = "";
}
if (i > this.customLayers.length) {
if (field.parentElement != null)
this.layerContainers.removeChild(field);
}
else {
if (field.parentElement == null)
this.layerContainers.appendChild(field);
if (i < this.customLayers.length)
field.value = this.customLayers[i];
}
}
}
}
exports.default = GameSettingsEditor;
|
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const merge = require("webpack-merge");
const common = require("./webpack.common");
module.exports = merge(common, {
mode: "development",
entry: {
app: ["./src/index", "webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true"]
},
devtool: "inline-source-map",
devServer: {
historyApiFallback: true,
contentBase: "./dist"
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Webpack with React",
favicon: "./src/img/favicon.png",
template: path.resolve(__dirname, "src/index.html")
}),
new MiniCssExtractPlugin({
filename: "[name].css"
}),
new webpack.HotModuleReplacementPlugin(),
// Replacing PRODUCTION to true in compile time
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(false)
})
]
});
|
const localeGetter = (locales) => {
let currentIndex = 0;
return () => {
if (currentIndex + 1 === locales.length) {
currentIndex = 0;
return locales[currentIndex];
}
currentIndex++;
return locales[currentIndex];
};
};
const keyLayout = [
{
value: '1',
eventCode: 'Digit1',
},
{
value: '2',
eventCode: 'Digit2',
},
{
value: '3',
eventCode: 'Digit3',
},
{
value: '4',
eventCode: 'Digit4',
},
{
value: '5',
eventCode: 'Digit5',
},
{
value: '6',
eventCode: 'Digit6',
},
{
value: '7',
eventCode: 'Digit7',
},
{
value: '8',
eventCode: 'Digit8',
},
{
value: '9',
eventCode: 'Digit9',
},
{
value: '0',
eventCode: 'Digit0',
},
{
value: 'backspace',
eventCode: 'Backspace',
},
{
value: { en: 'q', ru: 'й' },
eventCode: 'KeyQ',
},
{
value: { en: 'w', ru: 'ц' },
eventCode: 'KeyW',
},
{
value: { en: 'e', ru: 'у' },
eventCode: 'KeyE',
},
{
value: { en: 'r', ru: 'к' },
eventCode: 'KeyR',
},
{
value: { en: 't', ru: 'е' },
eventCode: 'KeyT',
},
{
value: { en: 'y', ru: 'н' },
eventCode: 'KeyY',
},
{
value: { en: 'u', ru: 'г' },
eventCode: 'KeyU',
},
{
value: { en: 'i', ru: 'ш' },
eventCode: 'KeyI',
},
{
value: { en: 'o', ru: 'щ' },
eventCode: 'KeyO',
},
{
value: { en: 'p', ru: 'з' },
eventCode: 'KeyP',
},
{
value: { en: '[', ru: 'х' },
eventCode: 'BracketLeft',
},
{
value: { en: ']', ru: 'ъ' },
eventCode: 'BracketRight',
},
{
value: 'caps',
eventCode: 'CapsLock',
},
{
value: { en: 'a', ru: 'ф' },
eventCode: 'KeyA',
},
{
value: { en: 's', ru: 'ы' },
eventCode: 'KeyS',
},
{
value: { en: 'd', ru: 'в' },
eventCode: 'KeyD',
},
{
value: { en: 'f', ru: 'а' },
eventCode: 'KeyF',
},
{
value: { en: 'g', ru: 'п' },
eventCode: 'KeyG',
},
{
value: { en: 'h', ru: 'р' },
eventCode: 'KeyH',
},
{
value: { en: 'j', ru: 'о' },
eventCode: 'KeyJ',
},
{
value: { en: 'k', ru: 'л' },
eventCode: 'KeyK',
},
{
value: { en: 'l', ru: 'д' },
eventCode: 'KeyL',
},
{
value: { en: ';', ru: 'ж' },
eventCode: 'Semicolon',
},
{
value: { en: "''", ru: 'э' },
eventCode: 'Quote',
},
{
value: 'enter',
eventCode: 'Enter',
},
{
value: 'shift',
eventCode: 'ShiftLeft',
},
{
value: { en: 'z', ru: 'я' },
eventCode: 'KeyZ',
},
{
value: { en: 'x', ru: 'ч' },
eventCode: 'KeyX',
},
{
value: { en: 'c', ru: 'с' },
eventCode: 'KeyC',
},
{
value: { en: 'v', ru: 'м' },
eventCode: 'KeyV',
},
{
value: { en: 'b', ru: 'и' },
eventCode: 'KeyB',
},
{
value: { en: 'n', ru: 'т' },
eventCode: 'KeyN',
},
{
value: { en: 'm', ru: 'ь' },
eventCode: 'KeyM',
},
{
value: { en: ',', ru: 'б' },
eventCode: 'Comma',
},
{
value: { en: '.', ru: 'ю' },
eventCode: 'Period',
},
{
value: { en: '/', ru: '.' },
eventCode: 'Slash',
},
{
value: 'ctrl',
eventCode: 'ControlLeft',
},
{
value: 'alt',
eventCode: 'AltLeft',
},
{
value: 'space',
eventCode: 'Space',
},
];
class Keyboard {
constructor() {
this.elements = {
main: null,
keysContainer: null,
input: null,
keys: [],
};
this.eventHandlers = {
oninput: null,
onclose: null,
};
this.properties = {
value: ' ',
capsLock: false,
locale: '',
};
this.capslockCode = 'CapsLock';
}
init() {
this._getNextLocale = localeGetter(['en', 'ru']);
this.properties.locale = this._getNextLocale();
// Create main elements
this.elements.input = document.createElement('textarea');
this.elements.main = document.createElement('div');
this.elements.keysContainer = document.createElement('div');
// Setup main elements
this.elements.main.classList.add('keyboard');
this.elements.keysContainer.classList.add('keyboard__keys');
this.elements.keysContainer.appendChild(this._createKeys());
this.elements.keys = this.elements.keysContainer.querySelectorAll('.keyboard__key');
// Add to DOM
this.elements.main.appendChild(this.elements.keysContainer);
document.body.appendChild(this.elements.input);
document.body.appendChild(this.elements.main);
// Automatically use keyboard for elements with .use-keyboard-input
document.querySelectorAll('.use-keyboard-input').forEach((element) => {
element.addEventListener('focus', () => {
this.open(element.value, (currentValue) => {
element.value = currentValue;
});
});
});
this._initKeyboardEventListeners();
}
_getNextLocale() {}
_initKeyboardEventListeners() {
window.addEventListener('keydown', (event) => {
const pressedKey = document.querySelector(`#${event.code}`);
if (!pressedKey) return;
this._manageKeyCombinations(event);
pressedKey.classList.add('keyboard__key--active');
});
window.addEventListener('keyup', (event) => {
const pressedKey = document.querySelector(`#${event.code}`);
if (!pressedKey) return;
event.preventDefault();
if (event.code === this.capslockCode) {
this._toggleCapsLock();
pressedKey.classList.toggle('keyboard__key--active', this.properties.capsLock);
} else {
pressedKey.classList.remove('keyboard__key--active');
}
});
}
_manageKeyCombinations(event) {
if (event.altKey && event.shiftKey) {
this._toggleLocaleChange();
}
}
_createKeys() {
const fragment = document.createDocumentFragment();
keyLayout.forEach((key) => {
const keyElement = document.createElement('button');
const keyValue = (typeof key.value) === 'object' ? key.value[this.properties.locale] : key.value;
const insertLineBreak = ['backspace', 'ъ', 'enter', '/'].indexOf(keyValue) !== -1;
// Add attributes/classes
keyElement.setAttribute('type', 'button');
keyElement.classList.add('keyboard__key');
keyElement.setAttribute('id', key.eventCode);
switch (keyValue) {
case 'backspace':
keyElement.classList.add('keyboard__key--wide');
keyElement.innerHTML = keyValue;
keyElement.addEventListener('click', () => {
this.properties.value = this.properties.value.substring(0, this.properties.value.length - 1);
this._triggerEvent('oninput');
});
break;
case 'caps':
keyElement.classList.add('keyboard__key--wide', 'keyboard__key--activatable');
keyElement.innerHTML = keyValue;
keyElement.addEventListener('click', () => {
this._toggleCapsLock();
keyElement.classList.toggle('keyboard__key--active', this.properties.capsLock);
});
break;
case 'enter':
keyElement.classList.add('keyboard__key--wide');
keyElement.innerHTML = keyValue;
keyElement.addEventListener('click', () => {
this.properties.value += '\n';
this._triggerEvent('oninput');
});
break;
case 'space':
keyElement.classList.add('keyboard__key--extra-wide');
keyElement.innerHTML = keyValue;
keyElement.addEventListener('click', () => {
this.properties.value += ' ';
this._triggerEvent('oninput');
});
break;
case 'shift':
keyElement.classList.add('keyboard__key--wide');
keyElement.innerHTML = keyValue;
break;
case 'alt':
keyElement.classList.add('keyboard__key');
keyElement.innerHTML = keyValue;
break;
default:
keyElement.textContent = keyValue.toLowerCase();
keyElement.addEventListener('click', () => {
this.properties.value += this.properties.capsLock ? keyValue.toUpperCase() : keyValue.toLowerCase();
this._triggerEvent('oninput');
});
break;
}
fragment.appendChild(keyElement);
if (insertLineBreak) {
fragment.appendChild(document.createElement('br'));
}
});
return fragment;
}
_triggerEvent(handlerName) {
if (typeof this.eventHandlers[handlerName] === 'function') {
this.eventHandlers[handlerName](this.properties.value);
}
}
_toggleCapsLock() {
this.properties.capsLock = !this.properties.capsLock;
for (const key of this.elements.keys) {
if (key.childElementCount === 0) {
key.textContent = this.properties.capsLock ? key.textContent.toUpperCase() : key.textContent.toLowerCase();
}
}
}
_toggleLocaleChange() {
this.properties.locale = this._getNextLocale();
for (const key of this.elements.keys) {
const foundKey = keyLayout.find((keyData) => (keyData.eventCode === key.id));
key.textContent = (typeof foundKey.value) === 'object' ? foundKey.value[this.properties.locale] : foundKey.value;
}
}
open(initialValue, oninput, onclose) {
this.properties.value = initialValue || '';
this.eventHandlers.oninput = oninput;
this.eventHandlers.onclose = onclose;
}
close() {
this.properties.value = '';
this.eventHandlers.oninput = oninput;
this.eventHandlers.onclose = onclose;
}
}
window.addEventListener('DOMContentLoaded', () => {
const virtualKeyboard = new Keyboard();
virtualKeyboard.init();
});
|
var reverseString = function (s) {
let temp;
for (let left = 0, right = s.length - 1; left < right; left++, right--) {
temp = s[left];
s[left] = s[right];
s[right] = temp;
}
}; |
import React from 'react';
import { Row, Col, Image } from 'react-bootstrap';
import EditIcon from '@material-ui/icons/EditOutlined';
import LockIcon from '@material-ui/icons/Lock';
import LockOpenIcon from '@material-ui/icons/LockOpen';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import Popover from '@material-ui/core/Popover';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import Button from '@material-ui/core/Button';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import { withRouter } from 'react-router-dom';
import moment from 'moment';
import { connect } from 'react-redux';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import * as actions from '../../../redux/actions/index';
import QueryBuilderIcon from '@material-ui/icons/QueryBuilder';
import CancelIcon from '@material-ui/icons/Cancel';
import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline';
import './VirtualTradeItem.scss';
import download from 'downloadjs';
import { Input, ClickAwayListener } from '@material-ui/core';
import ShareIcon from '@material-ui/icons/Share';
import ShareVirtualTrade from './ShareVirtualTrade';
// import nodeHtmlToImage from 'node-html-to-image'
import DeleteIcon from '@material-ui/icons/DeleteOutlined';
const useStyles = makeStyles(theme => ({
typography: {
padding: 10
}
}));
const IOSSwitch = withStyles(theme => ({
root: {
width: 36,
height: 20,
padding: 0,
margin: theme.spacing(1)
},
switchBase: {
padding: 1,
'&$checked': {
transform: 'translateX(16px)',
color: theme.palette.common.white,
'& + $track': {
backgroundColor: '#52d869',
opacity: 1,
border: 'none'
}
},
'&$focusVisible $thumb': {
color: '#52d869',
border: '6px solid #fff'
}
},
thumb: {
width: 18,
height: 18,
borderRadius: 26 / 2,
border: `1px solid ${theme.palette.grey[400]}`,
backgroundColor: theme.palette.grey[100],
opacity: 1,
transition: theme.transitions.create(['background-color', 'border'])
},
track: {
borderRadius: 26 / 2,
border: `1px solid ${theme.palette.grey[400]}`,
backgroundColor: theme.palette.grey[50],
opacity: 1,
transition: theme.transitions.create(['background-color', 'border'])
},
checked: {},
focusVisible: {}
}))(({ classes, ...props }) => {
return (
<Switch
focusVisibleClassName={classes.focusVisible}
disableRipple
classes={{
root: classes.root,
switchBase: classes.switchBase,
thumb: classes.thumb,
track: classes.track,
checked: classes.checked
}}
{...props}
/>
);
});
const VirtualTradeItem = props => {
const { data, message } = props;
const [openDialog, setOpenDialog] = React.useState(false);
React.useEffect(() => {
if (props.message) {
props.setMessage(props.message);
}
}, [props.message]);
// console.log('@@@@@@@@@@@@@@@@@@@@', data);
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
// const [allow, setAllow] = React.useState(
// data.status === 'EXPIRED' || data.status === 'CANCELLED' || data.status === 'CLOSED'
// ? false
// : data.status === 'OPEN' || data.status === 'EXECUTED'
// ? true
// : null
// );
const [allow, setAllow] = React.useState(data && data.allow_entry);
const [showDialog, setDialog] = React.useState(false);
const handleCancelClick = event => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleSwitch = event => {
console.log('clicked!!!!');
const params = {
record_id: props.data.record_id,
allow_entry: !props.data.allow_entry
};
props.allowTradeEntry({
params: params
});
setAllow(!allow);
};
const open = Boolean(anchorEl);
const id = open ? 'simple-popover' : undefined;
const [error, setError] = React.useState();
const [isEdit, setEdit] = React.useState(false);
// console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@', props);
return (
<>
{/* <div style={{ width: '100%', border: '1px solid #eeeeee', padding: '15px 15px 0px', marginBottom: '10px' }}> */}
<div
onClick={() => {
setDialog(true);
setEdit(true);
}}
>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
onClose={handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center'
}}
>
<Row>
<Typography className={classes.typography}>Are you sure you want to cancel the trade?</Typography>
</Row>
<Row style={{ padding: '10px', justifyContent: 'flex-end', margin: '0px' }}>
<Button onClick={handleClose}>No</Button>
<Button
onClick={() => {
handleClose();
const recordData = new FormData();
recordData.append('record_id', data.record_id);
props.cancelTrade({
record_id: recordData
});
}}
style={{ color: 'red' }}
>
Yes
</Button>
</Row>
</Popover>
<div className='col'>
<Row>
<div className='col-6'>
<div style={{ color: '#212121', fontSize: '12px', paddingLeft: '2rem' }}>
{moment(data.order_placement_time).format('DD/MM')}
{moment(data.order_placement_time).format('HH:mm')}
</div>
</div>
<div className='col-6' style={{ position: 'absolute', right: '0px', top: '-0.5rem', paddingLeft: '3rem', paddingRight: '0.5rem' }}>
{data.status === 'OPEN' && (
<div
style={{
color: '#101010',
backgroundColor: '#FFCF55',
borderRadius: '1.5rem',
paddingTop: '0.5rem',
height: '6rem',
fontSize: '12px',
textAlign: 'center',
paddingTop: '0.5rem'
}}
>
<p className='mb-0 mx-auto'>
<LockOpenIcon style={{ fontSize: '10px' }} className='mb-1' /> {data.status}
</p>
</div>
)}
{data.status === 'CLOSED' && (
<div
style={{
color: '#101010',
backgroundColor: '#B1AEC1',
borderRadius: '1.5rem',
paddingTop: '0.5rem',
height: '6rem',
fontSize: '12px',
textAlign: 'center',
}}
>
<p className='mb-0 mx-auto'>
<LockIcon style={{ fontSize: '10px' }} className='mb-1' /> {data.status}
</p>
</div>
)}
{data.status === 'EXPIRED' && (
<div
style={{
color: '#101010',
backgroundColor: '#B1AEC1',
borderRadius: '1.5rem',
paddingTop: '0.5rem',
height: '6rem',
fontSize: '12px',
textAlign: 'center',
}}
>
<p className='mb-0 mx-auto'>
<QueryBuilderIcon style={{ fontSize: '10px' }} className='mb-1' /> {data.status}
</p>
</div>
)}
{data.status === 'CANCELLED' && (
<div
style={{
color: '#101010',
backgroundColor: '#B1AEC1',
borderRadius: '1.5rem',
paddingTop: '0.5rem',
height: '6rem',
fontSize: '10px',
textAlign: 'center',
}}
>
<p className='mb-0 mx-auto'>
<CancelIcon style={{ fontSize: '10px' }} className='mb-1' /> {data.status}
</p>
</div>
)}
{data.status === 'EXECUTED' && (
<div
style={{
color: '#101010',
backgroundColor: '#54E2B1',
borderRadius: '1.5rem',
paddingTop: '0.5rem',
height: '6rem',
fontSize: '12px',
textAlign: 'center',
}}
>
<p className='mb-0 mx-auto'>
<CheckCircleOutlineIcon style={{ fontSize: '10px' }} className='mb-1' /> ACTIVE
{/* <ArrowUpwardIcon style={{ fontSize: '10px' }} /> */}
</p>
</div>
)}
</div>
</Row>
<Col
style={{
marginBottom: '1.5rem',
border: '1px solid grey',
borderRadius: '3rem',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
padding: '1rem',
backgroundColor: 'white'
}}
>
<Row
style={{
paddingLeft: '1rem',
paddingRight: '1rem',
color: '#212121',
fontSize: '16px',
marginBottom: '1rem'
}}
>
<strong style={{display: 'block'}}>{data.instrument && data.instrument.trading_symbol}</strong>
</Row>
<Col
style={{
paddingLeft: '1rem',
paddingRight: '1rem',
marginBottom: '1rem'
}}
>
<Row
style={{
backgroundColor: data.gains >= 0 ? '#54E2B1' : '#f44336da',
paddingTop: '0.5rem',
paddingBottom: '0.5rem',
marginBottom: '0px',
fontSize: '14px',
fontWeight: '550',
width: '100%',
marginBottom: '1rem',
borderRadius: '3rem'
}}
>
<div className="col-3" style={{textAlign: 'left'}}>{data.gains >= 0 ? <>GAIN</> : <>LOSS</>}</div>
<div className="col-2"></div>
<div className="col-7" style={{textAlign: 'right'}}>
{Number(data.gains).toFixed(2)} ({Number(data.gains_percentage).toFixed(2) + '%'})
</div>
</Row>
<Row
style={{
border: '1px solid black',
borderColor:
data.reward === data.risk
? '#B1AEC1'
: data.reward > data.risk
? '#54E2B1'
: data.reward < data.risk
? '#f44336da'
: 'rgba(20, 19, 19, 0.938)',
paddingTop: '0.5rem',
paddingBottom: '0.5rem',
marginBottom: '0px',
fontSize: '14px',
fontWeight: '550',
width: '100%',
borderRadius: '3rem'
}}
>
<div className="col-7" style={{textAlign: 'left'}}>RISK : REWARD</div>
<div className="col-1" style={{padding: '0px'}}></div>
<div className="col-4" style={{textAlign: 'right'}}>
{`1: ${(data.reward / data.risk).toFixed(2)}`}
</div>
</Row>
</Col>
<Row
style={{
color: '#616161',
fontSize: '12px',
fontWeight: 'bold',
marginBottom: '2rem',
paddingLeft: '1rem',
paddingRight: '1rem',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-evenly'
}}
>
<div>{data.segment && data.segment.name.toUpperCase()}</div>
<div>{' | '}</div>
<div>{data.trade_type && data.trade_type.toUpperCase()}</div>
<div>{' | '}</div>
<div>{data.order_type && data.order_type.toUpperCase()}</div>
<div>{' | '}</div>
<div>{data.complexity && data.complexity.toUpperCase()}</div>
</Row>
<Col
style={{
paddingLeft: '1rem',
paddingRight: '1rem'
}}
>
<div className='row'>
<div className="col-6"
style={{
alignItems: 'center',
borderRight: '.3px solid #B1AEC1',
borderBottom: '.3px solid #B1AEC1',
padding: '.5rem',
paddingLeft: '1rem',
paddingTop: '1rem',
width: '10rem'
}}
>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center', fontWeight: '500' }}>
<b>₹{data.price}</b>
</div>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center' }}>Order Price</div>
</div>
<div className="col-6"
style={{
alignItems: 'center',
borderLeft: '.3px solid #B1AEC1',
borderBottom: '.3px solid #B1AEC1',
padding: '.5rem',
paddingLeft: '1rem',
paddingTop: '1rem',
width: '10rem'
}}
>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center', fontWeight: '500' }}>
<b>₹{data.target}</b>
</div>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center' }}>Target Price</div>
</div>
</div>
<div className='row'>
<div className="col-6"
style={{
alignItems: 'center',
borderRight: '.3px solid #B1AEC1',
borderTop: '.3px solid #B1AEC1',
padding: '.5rem',
paddingLeft: '1rem',
paddingTop: '1rem',
width: '10rem'
}}
>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center', fontWeight: '500' }}>
<b>{data.quantity}</b>
</div>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center' }}>Quantity</div>
</div>
<div className="col-6"
style={{
alignItems: 'center',
borderLeft: '.3px solid #B1AEC1',
borderTop: '.3px solid #B1AEC1',
padding: '.5rem',
paddingLeft: '1rem',
paddingTop: '1rem',
width: '10rem'
}}
>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center', fontWeight: '500' }}>
<b>{data.stop_loss}</b>
</div>
<div style={{ color: '#2B2B2B', fontSize: '12px', textAlign: 'center' }}>Stop Loss</div>
</div>
</div>
</Col>
{data.status === 'EXECUTED' ? (
<Col style={{
paddingLeft: '1rem',
paddingRight: '1rem'
}}>
<Row style={{ textAlign: 'center' }}>
<div style={{ width: '100%', height: '2px', borderBottom: '1px solid #eeeeee', marginTop: '0.7rem' }} />
</Row>
<Row>
{/* <FormControlLabel
control={<IOSSwitch checked={allow} onChange={handleSwitch} name='allow' />}
#565EBFbel='Allow entry'
labelPlacement='start'
style={{
fontSize: '1rem'
}}
/> */}
<div className='col-6' style={{padding: '0px', marginLeft: '1rem'}}>
<Row>
<div className='col-7' style={{padding: '1.3rem 0px 0px 0rem'}}>
<span style={{ fontSize: '1rem', color: '#565EBF' }}>Allow Entry</span>
</div>
<div className='col-4' style={{padding: '1.1rem 0px 0px 0px'}}>
<IOSSwitch checked={allow} onChange={handleSwitch} name='allow' />
</div>
</Row>
</div>
<div className='col-3'
style={{
padding: '0px',
paddingTop: '0.4rem',
marginBottom: '0px',
fontSize: '2rem',
textAlign: 'center',
cursor: !data.stop_loss_hit && !data.target_hit ? 'pointer' : 'default'
}}
onClick={() => {
if (!data.stop_loss_hit && !data.target_hit) {
// props.changeHomeState(1);
props.setTradeItem(data);
// props.history.push('/new-trade');
props.setCheck(true);
}
}}
>
<EditIcon
style={{
fontSize: '2rem',
textAlign: 'center',
color: '#565EBF'
}}
/>
</div>
<div className='col-2' style={{padding: '0px',}}>
<div
style={{
padding: '0px',
paddingTop: '0.4rem',
marginBottom: '0px',
fontSize: '2rem',
textAlign: 'center',
cursor: 'pointer'
}}
onClick={handleCancelClick}
className='ml-2'
>
<DeleteIcon
style={{
fontSize: '2rem',
textAlign: 'center'
}}
/>
</div>
</div>
</Row>
</Col>
) : data.status === 'OPEN' ? (
<Col style={{
paddingLeft: '1rem',
paddingRight: '1rem'
}}>
<Row style={{ textAlign: 'center' }}>
<div style={{ width: '100%', height: '2px', borderBottom: '1px solid #eeeeee', marginTop: '0.7rem' }} />
</Row>
<Row>
{/* <FormControlLabel
control={<IOSSwitch checked={allow} onChange={handleSwitch} name='allow' />}
#565EBFbel='Allow entry'
labelPlacement='start'
style={{
fontSize: '1rem'
}}
/> */}
<div className='col-6' style={{padding: '0px'}}>
<Row>
<div className='col-7' style={{padding: '1.3rem 0px 0px 0rem'}}>
<span style={{ fontSize: '1rem', color: '#565EBF' }}>Allow Entry</span>
</div>
<div className='col-4' style={{padding: '1.1rem 0px 0px 0px'}}>
<IOSSwitch checked={allow} onChange={handleSwitch} name='allow' />
</div>
</Row>
</div>
<div className='col-3'
style={{
padding: '0px',
paddingTop: '0.4rem',
marginBottom: '0px',
fontSize: '2rem',
textAlign: 'center',
cursor: !data.stop_loss_hit && !data.target_hit ? 'pointer' : 'default'
}}
onClick={() => {
if (!data.stop_loss_hit && !data.target_hit) {
// props.changeHomeState(1);
props.setTradeItem(data);
// props.history.push('/new-trade');
props.setCheck(true);
}
}}
>
<EditIcon
style={{
fontSize: '2rem',
textAlign: 'center',
color: '#565EBF'
}}
/>
</div>
<div className='col-2' style={{padding: '0px',}}>
<div
style={{
padding: '0px',
paddingTop: '0.4rem',
marginBottom: '0px',
fontSize: '2rem',
textAlign: 'center',
cursor: 'pointer'
}}
onClick={handleCancelClick}
className='ml-2'
>
<DeleteIcon
style={{
fontSize: '2rem',
textAlign: 'center'
}}
/>
</div>
</div>
</Row>
</Col>
) : (
<div style={{ padding: '5px 0' }}></div>
)}
</Col>
</div>
</div>
<Dialog
open={openDialog}
onClose={() => setOpenDialog(false)}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>{props.message}</DialogTitle>
<DialogActions>
<Button
onClick={() => {
setOpenDialog(false);
props.setMessage(null);
}}
color='primary'
autoFocus
>
OK
</Button>
</DialogActions>
</Dialog>
{data.status === 'CLOSED' && data.analyst ? (
<ShareVirtualTrade data={data} id={props.id} showDialog={showDialog} setDialog={setDialog} />
) : null}
</>
);
};
const mapStateToProps = state => ({
signinData: state.auth.signinData,
message: state.auth.message,
allowEntry: state.analyst.allowEntry
});
const mapDispatchToProps = dispatch => ({
cancelTrade: payload => dispatch(actions.cancelTrade(payload)),
changeHomeState: params => dispatch(actions.changeHomeState(params)),
setTradeItem: params => dispatch(actions.setTradeItem(params)),
allowTradeEntry: params => dispatch(actions.allowTradeEntry(params)),
setMessage: message => dispatch(actions.setMessage(message))
});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(VirtualTradeItem));
|
import flatten from 'lodash/flatten'
import isEmpty from 'lodash/isEmpty'
import chapterRepository from '../domain/repositories/chapter-repository'
import DropboxClient from '../infrastructure/external_services/dropbox-client'
import FileReader from '../infrastructure/external_services/file-reader'
async function sync({ dropboxId, chapterPosition }) {
function _updateTitleAndExtractChaptersFromArticleContent(dropboxFilesPath) {
return Promise.all([
DropboxClient.getFrTextFileStream(dropboxId),
DropboxClient.getEnTextFileStream(dropboxId),
])
.then(files => Promise.all([
FileReader.read(files[0]),
FileReader.read(files[1]),
]))
.then(articleContents => _serializeArticleContentsAndReturnOneChapter(articleContents, dropboxFilesPath))
.then(articleInfos => _shareChapterImages(articleInfos))
.then(({ chapters }) => chapters)
}
function _serializeArticleContentsAndReturnOneChapter(rawArticles, dropboxFilesPath) {
const cuttedArticles = rawArticles.map(rawArticle => rawArticle
.split('*')
.map(row => row.trim()))
const chapters = _generateOnlyOneChapter(cuttedArticles, dropboxFilesPath)
return {
chapters,
}
}
function buildFullTitle(title, subtitle) {
if ((title && subtitle) || (!title && !subtitle)) {
return [title, subtitle].join(' - ').trim()
}
return [title, subtitle].join('')
}
function _generateOnlyOneChapter(cuttedArticles, dropboxFilesPath) {
const frenchArticle = cuttedArticles[0]
const englishArticle = cuttedArticles[1]
const chapters = []
const i = chapterPosition
const imgLink = dropboxFilesPath.filter(imgPath => imgPath.match(`[iI]mg-?${i}.jpg$`))[0]
const frenchTitle = frenchArticle[(3 * i) - 2]
const frenchSubtitle = frenchArticle[(3 * i) - 1]
const englishTitle = englishArticle[(3 * i) - 2]
const englishSubtitle = englishArticle[(3 * i) - 1]
const frTitle = buildFullTitle(frenchTitle, frenchSubtitle)
const enTitle = buildFullTitle(englishTitle, englishSubtitle)
chapters[0] = {
position: i,
dropboxId,
frTitle,
enTitle,
imgLink,
frText: frenchArticle[3 * i],
enText: englishArticle[3 * i],
}
return chapters
}
function _shareChapterImages(articleInfos) {
const chaptersWithSharableLink = articleInfos.chapters.reduce((promises, chapter) => {
if (isEmpty(chapter.imgLink)) {
console.error('Problème avec les données fournies dans cet article : ')
console.error(chapter)
return promises
}
const promise = _shareChapterImage(chapter.imgLink)
promises.push(promise)
return promises
}, [])
return Promise.all(chaptersWithSharableLink)
.then(imgLinks => {
const newArticleInfos = articleInfos
for (let i = 0; i < imgLinks.length; i += 1) {
newArticleInfos.chapters[i].imgLink = imgLinks[i]
}
return newArticleInfos
})
}
function _shareChapterImage(imgLink) {
return DropboxClient.createSharedLink(imgLink)
.then(_transformToImgLink)
}
function _transformToImgLink(response) {
if (isEmpty(response)) {
console.error('img link is empty again')
return ''
}
const split = response.url.replace(/....$/, '').split('/s/')
return `${split[0]}/s/raw/${split[1].split('?')[0]}`
}
await chapterRepository.deleteChapterOfArticle(dropboxId, chapterPosition) // ok
const dropboxFilesPath = await DropboxClient.getFilesFolderPaths(dropboxId)
const imageZero = dropboxFilesPath
.filter(path => path.match('[Ii]mg-?0.jpg$'))[0]
const report = {
addedArticles: [
{
dropboxId,
imgPath: imageZero,
galleryPath: `/${dropboxId}`,
},
],
}
await _updateTitleAndExtractChaptersFromArticleContent(dropboxFilesPath)
.then(allChapters => flatten(allChapters))
.then(chapters => chapterRepository.createArticleChapters(chapters))
return report
}
export default {
sync,
}
|
import {Icon, Input} from 'react-native-elements';
import React from 'react';
import {StyleSheet} from 'react-native';
export const FormInput = (props) => {
const {icon, refInput, error, ...otherProps} = props;
const stylesInputContainerErr = props.stylesInputContainerErr
? props.stylesInputContainerErr
: styles.inputContainerErr;
const stylesInputContainer = props.stylesInputContainer
? props.stylesInputContainer
: styles.inputContainer;
const stylesInputStyle = props.inputStyle
? props.inputStyle
: styles.inputStyle;
const stylesErrorInputStyle = props.errorInputStyle
? props.errorInputStyle
: styles.errorInputStyle;
const iconColor = props.iconColor ? props.iconColor : '#5ae2ad';
const placeholderTextColor = props.placeholderTextColor
? props.placeholderTextColor
: '#5ae2ad';
return (
<Input
{...otherProps}
ref={refInput}
inputContainerStyle={
error ? stylesInputContainerErr : stylesInputContainer
}
leftIcon={
<Icon
name={icon}
type={'simple-line-icon'}
color={iconColor}
size={18}
/>
}
inputStyle={stylesInputStyle}
autoFocus={false}
autoCapitalize="none"
keyboardAppearance="dark"
errorStyle={stylesErrorInputStyle}
autoCorrect={false}
blurOnSubmit={false}
placeholderTextColor={placeholderTextColor}
/>
);
};
const styles = StyleSheet.create({
inputContainer: {
paddingLeft: 8,
borderRadius: 40,
borderWidth: 1,
borderColor: '#5ae2ad',
height: 45,
marginVertical: 3,
},
inputContainerErr: {
paddingLeft: 8,
borderRadius: 40,
borderWidth: 1,
borderColor: '#ec5673',
height: 45,
marginVertical: 3,
},
inputStyle: {
flex: 1,
marginLeft: 10,
color: 'white',
fontSize: 16,
},
errorInputStyle: {
marginTop: 0,
textAlign: 'center',
color: '#F44336',
},
});
|
// @ts-check
// eslint-disable-next-line import/no-extraneous-dependencies
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const isDev = require('electron-is-dev');
const execa = require('execa');
/** @type {BrowserWindow} */
let win;
function createMainWindow() {
win = new BrowserWindow({
width: 600,
height: 600,
webPreferences: {
nodeIntegration: true,
}
});
const filepath = path.resolve(__dirname, '../render/index.html');
win.loadURL(`file://${filepath}`);
if (isDev) {
win.webContents.openDevTools();
}
win.once('closed', () => {
win = null;
});
}
function initIpc() {
ipcMain.on('channelCmd', async (event, args) => {
const { command, options, argument } = typeof args === 'string' ? JSON.parse(args) : args;
try {
const { stdout, stderr } = await execa(command, [options, argument].filter((x) => typeof x === 'string' && /\S/.test(x)));
console.log(stdout);
console.log(stderr);
event.reply('channelCmd', stdout || stderr);
} catch (err) {
console.log(err);
event.reply('channelCmd', err.stack || err.message);
}
});
}
app.on('ready', () => {
createMainWindow();
initIpc();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
|
import React from 'react';
import './OurTeam.css';
import OurTeamCard from './OurTeamCard';
import OurTeamDatabase from './OurTeamDatabase.json';
function OurTeam() {
const teamCards = OurTeamDatabase.filter(
(teamMember) => teamMember.isDisplayed === true,
);
return (
<div>
<div className="team-titles-div">
<p className="our-team-subtitle">DEDICATED</p>
<h2 className="our-team-title"> OUR TEAM </h2>
</div>
<div className="team-cards-container">
{teamCards.map((teamCard) => (
<OurTeamCard {...teamCard} />
))}
</div>
</div>
);
}
export default OurTeam;
|
import axios from 'axios'
const instance = axios.create({
baseURL: 'http://localhost:3000/api/v1'
})
instance.defaults.headers.common['Accept'] = 'application/json'
export default instance
|
/**
* @param {knex} knex
*/
exports.up = function (knex) {
return knex.schema.createTable("devices", ($t) => {
$t.increments("id");
$t.integer('user_id');
$t.string("name").nullable();
$t.string("code");
$t.string("api_key");
$t.integer("hits").defaultTo(0);
$t.boolean("used").defaultTo(false);
$t.string("used_by").nullable();
$t.boolean("enabled").defaultTo(false);
$t.timestamps(true, true);
});
};
/**
* @param {knex} knex
*/
exports.down = function (knex) {
return knex.schema.dropTableIfExists("devices");
};
|
import React, { useState } from 'react'
import PropTypes from 'prop-types'
const AddCategory = ({setCategories}) => {
const [value, setValue] = useState('')
const handleChange = (e) => {
setValue(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
if(value.trim().length > 0) {
setCategories(cats => [value, ...cats ]) // callback function to get access to the component where is copying the arr
setValue('')
}
!value && alert('Please type something!')
}
return (
<form onSubmit={handleSubmit}>
<input
onChange={handleChange}
type="text"
value={value}
/>
</form>
)
}
AddCategory.propTypes = {
setCategories: PropTypes.func.isRequired
}
export default AddCategory
|
const fs = require("fs");
function addMapping (router,mapping) {
for(var url in mapping){
if(url.startsWith('GET ')){
let path = url.substring(4);
router.get(path,mapping[url]);
console.log(`GET path: ${path}`);
}else if(url.startsWith('POST ')){
let path = url.substring(5);
router.post(path,mapping[url]);
console.log(`POST path : ${path}`);
}else if(url.startsWith('PUT ')){
let path = url.substring('4');
router.put(path,mapping[url]);
console.log(`PUT path : ${path}`);
}else if(url.startsWith('DELETE ')){
let path = url.substring(7);
router.del(path,mapping[url]);
console.log(`DELETE path : ${path}`);
}else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers (router,dir) {
fs.readdirSync(__dirname+'/'+dir).filter((f) => {
return f.endsWith('.js');
}).forEach((f) => {
console.log(`current_dir :: ${f}`);
let mapping = require(__dirname+'/'+dir+'/'+f);
addMapping(mapping);
});
}
module.exports = function(dir){
let
controllers_dir = dir || 'controllers'
router = require('koa-router')();
addControllers(router,controllers_dir);
return router.routes();
} |
import React, {Component} from 'react'
import {getMasterCourses} from '../parser'
import Grades from './Grades'
export default class Master extends Component{
constructor(props){
super(props)
}
componentDidMount(){
console.log(this.props.index);
console.log(this.props.courses.length);
for(let i = this.props.index; i<this.props.courses.length; i++){
fetch('/api/courseInfo/'+this.props.courses[i].code+'/'+this.props.selectedYear)
.then(res => res.json())
.then(course => this.props.addMasterCourse(course));
}
}
render(){
return(
<div>
<div className="masterHolder">
{this.props.masterCourses.length>0 && this.props.masterCourses.map((course) =>
<div>
<div className="masterLeft">{course.title}, {course.points}HP</div>
<Grades master/>
</div>
)}
</div>
{!this.props.masterCourses.length>0 &&
<div className="loading">
Fetching master courses
</div>
}
</div>
)
}
}
|
require('dotenv').config()
module.exports = {
firebase_creds: process.env.GOOGLE_APPLICATION_CREDENTIALS,
oauth_client_id: process.env.GOOGLE_OAUTH_CLIENT_ID,
oauth_client_secret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
port: process.env.PORT,
}
|
import React, { PureComponent } from "react";
import "./signup.css";
export default class SignupForm extends PureComponent {
state = {
firstName: "",
lastName: "",
email: "",
city: "",
password: ""
};
handleSubmit = e => {
e.preventDefault();
this.props.onSubmit(this.state);
};
handleChange = event => {
const { name, value } = event.target;
this.setState({
[name]: value
});
};
render() {
return (
<form className="signup form-group pt-5" onSubmit={this.handleSubmit}>
<h3 className="text-center">Sign up</h3>
<label>First Name</label>
<input
className="form-control"
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.handleChange}
/>
<label className="mt-2">Last Name</label>
<input
className="form-control"
type="text"
name="lastName"
value={this.state.lastName}
onChange={this.handleChange}
/>
<label className="mt-2">Email</label>
<input
className="form-control"
type="text"
name="email"
value={this.state.email}
onChange={this.handleChange}
/>
<label className="mt-2">City</label>
<input
className="form-control"
type="text"
name="city"
value={this.state.city}
onChange={this.handleChange}
/>
<label className="mt-2">Password</label>
<input
className="form-control"
type="password"
name="password"
value={this.state.password}
onChange={this.handleChange}
/>
<button
className=" mt-3 btn btn-outline-secondary btn-block"
type="submit"
>
Sign up
</button>
</form>
);
}
}
|
const babel = require("@babel/core");
const fs = require("fs");
import plugin from "./plugin";
const code = fs.readFileSync(`${__dirname}/in.js`).toString();
const transformedCode = babel.transform(code, {
plugins: [plugin],
code: true,
ast: false
}).code;
fs.writeFileSync(`${__dirname}/out.js`, transformedCode);
|
// server.js
// where your nodvar url = 'mongodb://localhoste app starts
// init project
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var validUrl = require('valid-url');
var getIP = require('ipware')().get_ip;
// we've started you off with Express,
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
//var MongoClient = mongodb.MongoClient;
var url = 'mongodb://' + process.env.MONGO_USER + ':' + process.env.MONGO_PASSWORD + '@ds153392.mlab.com:53392/url-shortener-microservice-db';
var client = null;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
client = db;
}
});
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
app.get("/new/*", function(request, response) {
getNextSequenceValue(function(count){
var ua = request.headers['user-agent'];
var ip = getIP(request);
var url = request.params[0];
var site = {ip: ip['clientIp'], url: url, createdAt: new Date(), url_count:count};
if(validUrl.isUri(url)){
writedb(site);
response.send({original_url: url, short_url: "https://cloudy-crib.glitch.me/" + count});
}
else{
response.send(request.params[0] + " is an invalid url: Please enter a url in the format of http://www.example.com");
}
});
});
app.get("/*", function(request, response){
if(typeof parseInt(request.params[0]) == 'number' && request.params[0] != null){
var query = {url_count: parseInt(request.params[0])};
client.collection("microservice").findOne(query, function(err,doc){
if(err) throw err;
else{
if(doc != null)
response.redirect(doc.url);
}
});
}
});
var writedb = function (site){
var collection = client.collection('microservice');
collection.insert(site, function(err, data){
if(err) throw err;
console.log(JSON.stringify(site));
});
}
var getNextSequenceValue = function(callback){
var query = {_id: "url_counter"};
client.collection("counters").findOneAndUpdate(query, {"$inc":{sequence_value:1}}, {upsert: true}, function(err,doc) {
if (err) { throw err; }
else {
console.log("Updated");
console.log(doc.value.sequence_value);
callback(doc.value.sequence_value)
}
});
}
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
|
import $ from '../../core/renderer';
import { extend } from '../../core/utils/extend';
import devices from '../../core/devices';
import { deferRender } from '../../core/utils/common';
import { isDefined } from '../../core/utils/type';
import * as inkRipple from '../widget/utils.ink_ripple';
import registerComponent from '../../core/component_registrator';
import CollectionWidget from '../collection/ui.collection_widget.edit';
import DataExpressionMixin from '../editor/ui.data_expression';
import Editor from '../editor/editor';
import { Deferred } from '../../core/utils/deferred'; // STYLE radioGroup
var RADIO_BUTTON_CHECKED_CLASS = 'dx-radiobutton-checked';
var RADIO_BUTTON_CLASS = 'dx-radiobutton';
var RADIO_BUTTON_ICON_CHECKED_CLASS = 'dx-radiobutton-icon-checked';
var RADIO_BUTTON_ICON_CLASS = 'dx-radiobutton-icon';
var RADIO_BUTTON_ICON_DOT_CLASS = 'dx-radiobutton-icon-dot';
var RADIO_GROUP_HORIZONTAL_CLASS = 'dx-radiogroup-horizontal';
var RADIO_GROUP_VERTICAL_CLASS = 'dx-radiogroup-vertical';
var RADIO_VALUE_CONTAINER_CLASS = 'dx-radio-value-container';
var RADIO_GROUP_CLASS = 'dx-radiogroup';
var RADIO_FEEDBACK_HIDE_TIMEOUT = 100;
class RadioCollection extends CollectionWidget {
_focusTarget() {
return this.$element().parent();
}
_nullValueSelectionSupported() {
return true;
}
_getDefaultOptions() {
var defaultOptions = super._getDefaultOptions();
return extend(defaultOptions, DataExpressionMixin._dataExpressionDefaultOptions(), {
_itemAttributes: {
role: 'radio'
}
});
}
_initMarkup() {
super._initMarkup();
deferRender(() => {
this.itemElements().addClass(RADIO_BUTTON_CLASS);
});
}
_keyboardEventBindingTarget() {
return this._focusTarget();
}
_postprocessRenderItem(args) {
var {
itemData: {
html
},
itemElement
} = args;
if (!html) {
var $radio = $('<div>').addClass(RADIO_BUTTON_ICON_CLASS);
$('<div>').addClass(RADIO_BUTTON_ICON_DOT_CLASS).appendTo($radio);
var $radioContainer = $('<div>').append($radio).addClass(RADIO_VALUE_CONTAINER_CLASS);
$(itemElement).prepend($radioContainer);
}
super._postprocessRenderItem(args);
}
_processSelectableItem($itemElement, isSelected) {
super._processSelectableItem($itemElement, isSelected);
$itemElement.toggleClass(RADIO_BUTTON_CHECKED_CLASS, isSelected).find(".".concat(RADIO_BUTTON_ICON_CLASS)).first().toggleClass(RADIO_BUTTON_ICON_CHECKED_CLASS, isSelected);
this.setAria('checked', isSelected, $itemElement);
}
_refreshContent() {
this._prepareContent();
this._renderContent();
}
_supportedKeys() {
var parent = super._supportedKeys();
return extend({}, parent, {
enter: function enter(e) {
e.preventDefault();
return parent.enter.apply(this, arguments);
},
space: function space(e) {
e.preventDefault();
return parent.space.apply(this, arguments);
}
});
}
_itemElements() {
return this._itemContainer().children(this._itemSelector());
}
}
class RadioGroup extends Editor {
_clean() {
delete this._inkRipple;
super._clean();
}
_dataSourceOptions() {
return {
paginate: false
};
}
_defaultOptionsRules() {
var defaultOptionsRules = super._defaultOptionsRules();
return defaultOptionsRules.concat([{
device: {
tablet: true
},
options: {
layout: 'horizontal'
}
}, {
device: () => devices.real().deviceType === 'desktop' && !devices.isSimulator(),
options: {
focusStateEnabled: true
}
}]);
}
_fireContentReadyAction(force) {
force && super._fireContentReadyAction();
}
_focusTarget() {
return this.$element();
}
_getAriaTarget() {
return this.$element();
}
_getDefaultOptions() {
var defaultOptions = super._getDefaultOptions();
return extend(defaultOptions, extend(DataExpressionMixin._dataExpressionDefaultOptions(), {
hoverStateEnabled: true,
activeStateEnabled: true,
layout: 'vertical',
useInkRipple: false
}));
}
_getItemValue(item) {
return this._valueGetter ? this._valueGetter(item) : item.text;
}
_getSubmitElement() {
return this._$submitElement;
}
_init() {
super._init();
this._activeStateUnit = ".".concat(RADIO_BUTTON_CLASS);
this._feedbackHideTimeout = RADIO_FEEDBACK_HIDE_TIMEOUT;
this._initDataExpressions();
}
_initMarkup() {
this.$element().addClass(RADIO_GROUP_CLASS);
this._renderSubmitElement();
this.setAria('role', 'radiogroup');
this._renderRadios();
this.option('useInkRipple') && this._renderInkRipple();
this._renderLayout();
super._initMarkup();
}
_itemClickHandler(_ref) {
var {
itemElement,
event,
itemData
} = _ref;
if (this.itemElements().is(itemElement)) {
var newValue = this._getItemValue(itemData);
if (newValue !== this.option('value')) {
this._saveValueChangeEvent(event);
this.option('value', newValue);
}
}
}
_getSelectedItemKeys() {
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.option('value');
var isNullSelectable = this.option('valueExpr') !== 'this';
var shouldSelectValue = isNullSelectable && value === null || isDefined(value);
return shouldSelectValue ? [value] : [];
}
_setSelection(currentValue) {
var value = this._unwrappedValue(currentValue);
this._setCollectionWidgetOption('selectedItemKeys', this._getSelectedItemKeys(value));
}
_optionChanged(args) {
var {
name,
value
} = args;
this._dataExpressionOptionChanged(args);
switch (name) {
case 'useInkRipple':
case 'dataSource':
this._invalidate();
break;
case 'focusStateEnabled':
case 'accessKey':
case 'tabIndex':
this._setCollectionWidgetOption(name, value);
break;
case 'disabled':
super._optionChanged(args);
this._setCollectionWidgetOption(name, value);
break;
case 'valueExpr':
this._setCollectionWidgetOption('keyExpr', this._getCollectionKeyExpr());
break;
case 'value':
this._setSelection(value);
this._setSubmitValue(value);
super._optionChanged(args);
break;
case 'items':
this._setSelection(this.option('value'));
break;
case 'itemTemplate':
case 'displayExpr':
break;
case 'layout':
this._renderLayout();
this._updateItemsSize();
break;
default:
super._optionChanged(args);
}
}
_render() {
super._render();
this._updateItemsSize();
}
_renderInkRipple() {
this._inkRipple = inkRipple.render({
waveSizeCoefficient: 3.3,
useHoldAnimation: false,
isCentered: true
});
}
_renderLayout() {
var layout = this.option('layout');
var $element = this.$element();
$element.toggleClass(RADIO_GROUP_VERTICAL_CLASS, layout === 'vertical');
$element.toggleClass(RADIO_GROUP_HORIZONTAL_CLASS, layout === 'horizontal');
}
_renderRadios() {
this._areRadiosCreated = new Deferred();
var $radios = $('<div>').appendTo(this.$element());
var {
displayExpr,
accessKey,
focusStateEnabled,
itemTemplate,
tabIndex
} = this.option();
this._createComponent($radios, RadioCollection, {
onInitialized: _ref2 => {
var {
component
} = _ref2;
this._radios = component;
},
onContentReady: e => {
this._fireContentReadyAction(true);
},
onItemClick: this._itemClickHandler.bind(this),
displayExpr,
accessKey,
dataSource: this._dataSource,
focusStateEnabled,
itemTemplate,
keyExpr: this._getCollectionKeyExpr(),
noDataText: '',
scrollingEnabled: false,
selectionByClick: false,
selectionMode: 'single',
selectedItemKeys: this._getSelectedItemKeys(),
tabIndex
});
this._areRadiosCreated.resolve();
}
_renderSubmitElement() {
this._$submitElement = $('<input>').attr('type', 'hidden').appendTo(this.$element());
this._setSubmitValue();
}
_setOptionsByReference() {
super._setOptionsByReference();
extend(this._optionsByReference, {
value: true
});
}
_setSubmitValue(value) {
var _value;
value = (_value = value) !== null && _value !== void 0 ? _value : this.option('value');
var submitValue = this.option('valueExpr') === 'this' ? this._displayGetter(value) : value;
this._$submitElement.val(submitValue);
}
_setCollectionWidgetOption() {
this._areRadiosCreated.done(this._setWidgetOption.bind(this, '_radios', arguments));
}
_toggleActiveState($element, value, e) {
super._toggleActiveState($element, value, e);
if (this._inkRipple) {
var event = {
element: $element.find(".".concat(RADIO_BUTTON_ICON_CLASS)),
event: e
};
value ? this._inkRipple.showWave(event) : this._inkRipple.hideWave(event);
}
}
_updateItemsSize() {
if (this.option('layout') === 'horizontal') {
this.itemElements().css('height', 'auto');
} else {
var itemsCount = this.option('items').length;
this.itemElements().css('height', 100 / itemsCount + '%');
}
}
focus() {
var _this$_radios;
(_this$_radios = this._radios) === null || _this$_radios === void 0 ? void 0 : _this$_radios.focus();
}
itemElements() {
var _this$_radios2;
return (_this$_radios2 = this._radios) === null || _this$_radios2 === void 0 ? void 0 : _this$_radios2.itemElements();
}
}
RadioGroup.include(DataExpressionMixin);
registerComponent('dxRadioGroup', RadioGroup);
export default RadioGroup; |
"use strict";
module.exports = {
rules: {
"google-camelcase": require("./lib/rules/google-camelcase"),
},
rulesConfig: {
"google-camelcase": 2,
}
};
|
X.define("modules.account.password", function () {
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.account.tpl.password
});
var ctrl = X.controller.newOne({
view: view
});
ctrl.load = function() {
view.render(function() {
})
}
return ctrl
}) |
function ListInstantiatedWithAnEmptyArray() {
var notelist = new NoteList();
assert.isTrue(notelist.list.length === 0, "empty-array");
}
ListInstantiatedWithAnEmptyArray();
function CreatesANewNote(){
var notelist = new NoteList();
notelist.create("Hi")
console.log(notelist)
assert.isTrue(notelist.list[0].text == "Hi", "Creates-a-new-note")
}
CreatesANewNote()
function DisplaysAllNotes(){
var notelist = new NoteList();
notelist.create("Hi")
notelist.create("Hey")
var notes = notelist.displayall();
console.log(notes)
assert.isTrue(notes[0].text == "Hi", "Displays-all-notes")
assert.isTrue(notes[1].text == "Hey", "Displays-all-notes")
}
DisplaysAllNotes()
|
// using mysql
var mysql = require("mysql");
// using inquirer
var inquirer = require("inquirer");
var connection = mysql.createConnection({
host: "localhost",
// Your port;
port: 3306,
// Your username
user: "root",
// Your password
password: "root",
database: "bamazon_DB"
});
// connect the connection
connection.connect(function (err) {
if (err) throw err;
});
// creating buy function
var buy = function () {
// using user inputs
inquirer.prompt([
{
type: "input",
message: " please enter ID of the product they would like to buy",
name: "id"
},
{
type: "input",
message: "how many units of the product they would like to buy",
name: "stock_quantity"
},
// then function
]).then(function (ans) {
// using query statment
connection.query("SELECT * FROM products WHERE item_id=" + ans.id, function (err, res) {
// creating new qunt varriable
var qunt;
// creating new price varriable
var price;
if (err) throw err;
// using for loops
for (var i = 0; i < res.length; i++) {
// taking all value from the database
console.log("item id :" + res[i].item_id, " product_name :" + res[i].product_name, " department_name :" + res[i].department_name, " price :" + res[i].price, " stock_quantity :" + res[i].stock_quantity)
qunt = res[i].stock_quantity;
price = res[i].price;
}
var newqunt = qunt - ans.stock_quantity;
var newprice = price * ans.stock_quantity;
var query = connection.query(
// using the update query
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: newqunt
},
{
item_id: ans.id
}
],
function (err, res) {
console.log(res.affectedRows + " products updated!\n");
console.log("New quantity is :" + newqunt + "\n Total your bill is " + newprice);
}
);
// connection.end()function
connection.end();
});
});
}
// creating display fuction
var display = function () {
// select query
connection.query("SELECT * FROM products", function (err, res) {
if (err) throw err;
// for loop
for (var i = 0; i < res.length; i++) {
console.log(res[i].item_id, res[i].product_name, res[i].department_name, res[i].price, res[i].stock_quantity)
}
// Log all results of the SELECT statement
// connection.end function
connection.end();
});
}
// creating productsale function
var productSale = function(){
// using select query
connection.query("SELECT * FROM products", function (err, res) {
if (err) throw err;
for (var i = 0; i < res.length; i++) {
console.log(res[i].item_id, res[i].product_name, res[i].price, res[i].stock_quantity)
}
// Log all results of the SELECT statement
connection.end();
});
}
// creating lowinventory function
var lowinventory=function(){
connection.query("SELECT * FROM products WHERE stock_quantity <= 5" , function (err, res){
if (err) throw err;
// using for loops
for (var i = 0; i < res.length; i++) {
console.log("item id :" + res[i].item_id, " product_name :" + res[i].product_name, " department_name :" + res[i].department_name, " price :" + res[i].price, " stock_quantity :" + res[i].stock_quantity)
}
}
)};
// creating addinventory function
var addinventory=function(){
// using user input
inquirer.prompt([
{
type: "input",
message: " please enter ID of the product they would like to buy",
name: "id"
},
{
type: "input",
message: "how many units of the product they would like to buy",
name: "stock_quantity"
},
// then function
]).then(function(stock) {
// using query statment
connection.query("SELECT * FROM products WHERE item_id =" + stock.id, function (err, res) {
// creating new qunt varriable
var qunt;
if (err) throw err;
// using for loops
for (var i = 0; i < res.length; i++) {
// taking all value from the database
console.log("item id :" + res[i].item_id, " product_name :" + res[i].product_name, " department_name :" + res[i].department_name, " price :" + res[i].price, " stock_quantity :" + res[i].stock_quantity)
qunt = res[i].stock_quantity;
}
// creating new varriable and using parseInt statment
var newqunt = parseInt(qunt) + parseInt(stock.stock_quantity);
var query = connection.query(
// using the update query
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: newqunt
},
{
item_id: stock.id
}
],
function (err, res) {
console.log(res.affectedRows + " products updated!\n");
console.log("now quantity is :" + newqunt);
}
);
}
)}
)};
// creating newproduct function
var newproduct=function(){
// user inputs
inquirer.prompt([
{
type: "input",
message: "please enter product Id",
name: "item_id"
},
{
type: "input",
message: "please enter product name",
name: "product_name"
},
{
type: "input",
message: "please enter department name",
name: "department_name"
},
{
type: "input",
message: "please enter price",
name: "price"
},
{
type: "input",
message: "please enter stock_quantity",
name: "stock_quantity"
}
// then function
]).then(function(stock){
// using user input
var query=connection.query("INSERT INTO products SET ?",
{
item_id:stock.item_id,
product_name: stock.product_name,
product_name: stock.product_name,
department_name:stock.department_name,
price:stock.price,
stock_quantity:stock.stock_quantity,
function(err, res) {
console.log(res.affectedRows + " product inserted!\n");
}
})
connection.end();
}
)}
// module exports
module.exports = {
buy: buy,
display: display,
productSale:productSale,
lowinventory:lowinventory,
addinventory:addinventory,
newproduct:newproduct
} |
var config = {
apiKey: "AIzaSyDUHiaKVkTqU5Q5mshH3qdPcFGRbg8w9V0",
authDomain: "projectprototype-7868f.firebaseapp.com",
databaseURL: "https://projectprototype-7868f.firebaseio.com",
storageBucket: "projectprototype-7868f.appspot.com",
messagingSenderId: "290189100132"
};
firebase.initializeApp(config);
const rtdb = firebase.database();
const messaging = firebase.messaging();
|
'use-strict'
const API_V1_SCHEMA = 'http://'
export const API_V1_DOMAIN = 'ecd.cnsnt.io'
const API_V1_PREFIX = '/api/v1'
export const API_V1_BASE = API_V1_SCHEMA + API_V1_DOMAIN + API_V1_PREFIX
export const REQUEST_OPTIONS = (req, uri, method, body) => {
// proxy
let options = {
method,
uri,
headers: {
'Accept': req.headers['accept'],
'Content-Type': req.headers['content-type'],
'Authorization': req.headers['authorization'],
},
json: true,
simple: false,
gzip: true,
resolveWithFullResponse: true,
}
options.headers.host = API_V1_DOMAIN
if (method !== 'GET' && body)
options.body = body
return options
}
|
__resources__["/__builtin__/painter/index.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) {
exports.HonestPainter = require("./honestpainter").HonestPainter;
}}; |
const Redis = require('ioredis');
const redis = new Redis({
port: 6379, // Redis port
host: '127.0.0.1', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: process.env.REDIS_PASSWORD,
db: 0
})
module.exports = redis; |
import { combineReducers } from 'redux'
import { reducer as form } from 'redux-form'
import editor from '../components/editor/reducer'
import menu from '../components/menu-bar/reducer'
import user from '../components/user/reducer'
export default combineReducers({
editor,
form,
menu,
user,
})
|
import React from 'react';
import './Footer.scss';
const Footer = () => {
return (
<div className="footer">
<div className="right">
<div className="aboutIndia">
<div className="about">
<h1 className="head1">Incredible!ndia</h1>
</div>
<div className="discription">
<br></br>
<br></br>
<h2 className="head2">About India</h2>
<div>
<br></br>
<div className="theory">
India has a myriad of landscapes, great heritage and culture,
varied flora and fauna. The country is the most preferred
tourist destinations for tourists from all across the world for
its picturesque landscapes, spectacular waterfalls, habitat of
the country's largest tiger reserve and home to the warmest
people on earth.
</div>
</div>
</div>
</div>
<div className="tag">
<div className="stateTourism">
<div className="heading">
<h3 className="head3">State Tourism Websites</h3>
<div className="line"></div>
</div>
<div>
<br></br>
<br></br>
<div className="ul-li">
<ul className="inline">
<div className="box">
<li>
<a
href="https://tourism.ap.gov.in/"
title="Andhra Pradesh"
target="_blank"
rel="noreferrer"
>
Andhra Pradesh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.arunachaltourism.com"
title="Arunachal Pradesh"
target="_blank"
rel="noreferrer"
>
Arunachal Pradesh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://tourism.assam.gov.in/"
title="Assam"
target="_blank"
rel="noreferrer"
>
Assam{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.bihartourism.gov.in/"
title="Bihar"
target="_blank"
rel="noreferrer"
>
Bihar{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://cggovttourism.ddns.net/"
title="Chhattisgarh"
target="_blank"
rel="noreferrer"
>
Chhattisgarh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://goa-tourism.com/"
title="Goa"
target="_blank"
rel="noreferrer"
>
Goa{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.gujarattourism.com/"
title="Gujarat"
target="_blank"
rel="noreferrer"
>
Gujarat{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://haryanatourism.gov.in/"
title="Haryana"
target="_blank"
rel="noreferrer"
>
Haryana{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://himachaltourism.gov.in/"
title="Himachal Pradesh"
target="_blank"
rel="noreferrer"
>
Himachal Pradesh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://jharkhandtourism.gov.in/"
title="Jharkhand"
target="_blank"
rel="noreferrer"
>
Jharkhand{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.karnatakatourism.org/"
title="Karnataka"
target="_blank"
rel="noreferrer"
>
Karnataka{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.keralatourism.org/"
title="Kerala"
target="_blank"
rel="noreferrer"
>
Kerala{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.mptourism.com/"
title="Madhya Pradesh"
target="_blank"
rel="noreferrer"
>
Madhya Pradesh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.maharashtratourism.gov.in/"
title="Maharashtra"
target="_blank"
rel="noreferrer"
>
Maharashtra{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://manipurtourism.gov.in/"
title="Manipur"
target="_blank"
rel="noreferrer"
>
Manipur{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://megtourism.gov.in/"
title="Meghalaya"
target="_blank"
rel="noreferrer"
>
Meghalaya{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://tourism.mizoram.gov.in/"
title="Mizoram"
target="_blank"
rel="noreferrer"
>
Mizoram{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://tourism.nagaland.gov.in/"
title="Nagaland"
target="_blank"
rel="noreferrer"
>
Nagaland{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://odishatourism.gov.in/"
title="Odisha"
target="_blank"
rel="noreferrer"
>
Odisha{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://punjabtourism.gov.in"
title="Punjab"
target="_blank"
rel="noreferrer"
>
Punjab{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://tourism.rajasthan.gov.in/"
title="Rajasthan"
target="_blank"
rel="noreferrer"
>
Rajasthan{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.sikkimtourism.gov.in"
title="Sikkim"
target="_blank"
rel="noreferrer"
>
Sikkim{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.tamilnadutourism.org/"
title="Tamil Nadu"
target="_blank"
rel="noreferrer"
>
Tamil Nadu{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.telanganatourism.gov.in/"
title="Telangana"
target="_blank"
rel="noreferrer"
>
Telangana{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://tripuratourism.gov.in/"
title="Tripura"
target="_blank"
rel="noreferrer"
>
Tripura{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.uptourism.gov.in/"
title="Uttar Pradesh"
target="_blank"
rel="noreferrer"
>
Uttar Pradesh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://uttarakhandtourism.gov.in/"
title="Uttarakhand"
target="_blank"
rel="noreferrer"
>
Uttarakhand{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.wbtourismgov.in/"
title="West Bengal"
target="_blank"
rel="noreferrer"
>
West Bengal{' '}
</a>
</li>
</div>
</ul>
</div>
</div>
</div>
<div className="utTourism">
<div className="heading">
<h3 className="head3">UT Tourism Websites</h3>
<div className="line"></div>
<br></br>
<br></br>
</div>
<div>
<ul>
<div className="box">
<li>
<a
href="https://www.andaman.gov.in/"
title="Andaman and Nicobar"
target="_blank"
rel="noreferrer"
>
Andaman and Nicobar{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://chandigarhtourism.gov.in/"
title="Chandigarh"
target="_blank"
rel="noreferrer"
>
Chandigarh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.tourismdddnh.in"
title="Dadra and Nagar Haveli"
target="_blank"
rel="noreferrer"
>
Dadra and Nagar Haveli{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.tourismdddnh.in"
title="Daman and Diu"
target="_blank"
rel="noreferrer"
>
Daman and Diu{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.delhitourism.gov.in"
title="Delhi"
target="_blank"
rel="noreferrer"
>
Delhi{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.jktourism.jk.gov.in/"
title="Jammu and Kashmir"
target="_blank"
rel="noreferrer"
>
Jammu and Kashmir{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.jktourism.jk.gov.in/"
title="Ladakh"
target="_blank"
rel="noreferrer"
>
Ladakh{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="https://www.lakshadweeptourism.com/"
title="Lakshadweep"
target="_blank"
rel="noreferrer"
>
Lakshadweep{' '}
</a>
</li>
</div>
<div className="box">
<li>
<a
href="http://www.pondytourism.in/"
title="Puducherry"
target="_blank"
rel="noreferrer"
>
Puducherry{' '}
</a>
</li>
</div>
</ul>
</div>
</div>
</div>
</div>
<div className="bottom">
<div className="lines"></div>
</div>
</div>
);
};
export default Footer;
|
const bcrypt = require("bcrypt-nodejs");
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
email: {
type : String,
required : true,
unique: true
},
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
profile_pic: {
type: String
},
created_at: {
type: Date,
default: Date.now
}
});
userSchema.pre("save", function (done) {
let user = this;
if (!user.isModified("password")) {
return done();
}
bcrypt.hash(user.password, null, null, function (err, hased_password) {
if (err) {
return done(err);
}
user.password = hased_password;
return done();
});
});
userSchema.methods.checkPassword = function (guess, done) {
bcrypt.compare(guess, this.password, function (err, isMatch) {
if(err) {
return done(err);
}
done(null, isMatch);
});
};
userSchema.methods.fullname = function () {
return this.first_name + " " + this.last_name;
};
userSchema.methods.name = function(){
return this.username;
};
let User = mongoose.model("User", userSchema);
module.exports = User; |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ITcomLogo extends Component {
render() {
const space = this.props.height / 24.5;
const unit = space * 5;
const totalWidth = Math.ceil(unit * 3 + space * 2);
const totalHeight = this.props.height;
const rectProps = {
shapeRendering: 'optimizeQuality'
};
return (
<div style={this.props.style}>
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
x="0px"
y="0px"
width={totalWidth}
height={totalHeight}
viewBox={`0 0 ${totalWidth} ${totalHeight}`}
className="itcom-logo"
style={{
enableBackground: `new 0 0 ${totalWidth} ${totalHeight}`,
fill: this.props.fill
}}
>
<g>
<rect
className="i base"
y={unit * 2 + space * 2}
width={unit}
height={Math.floor(unit * 2.5 + space * 2)}
{...rectProps}
/>
<rect className="i" width={unit} height={unit} {...rectProps} />
<rect
className="t"
y={unit + space}
width={unit}
height={unit}
{...rectProps}
/>
<rect
className="t"
x={unit + space}
y={unit + space}
width={unit}
height={unit}
{...rectProps}
/>
<rect
className="t"
x={unit * 2 + space * 2}
y={unit + space}
width={unit}
height={unit}
{...rectProps}
/>
<rect
className="t"
x={unit + space}
y={unit * 2 + space * 2}
width={unit}
height={Math.floor(unit * 2.5 + space * 2)}
{...rectProps}
/>
</g>
</svg>
</div>
);
}
}
ITcomLogo.propTypes = {
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
fill: PropTypes.string,
style: PropTypes.object
};
ITcomLogo.defaultProps = {
height: 35,
fill: '#fff',
style: {}
};
export default ITcomLogo;
|
'use strict';
var Dog = function(name) {
Animal.call(this, name);
this.bark = function () {
return "Dog " + this.getName() + " is barking";
}
};
|
const mongoose = require('mongoose');
const config = require('config');
const URI = `mongodb://${config.db.host}:${config.db.port}/${config.db.database}`;
mongoose.connect(URI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
.then(() => console.log('connection successful!'))
.catch((error) => console.log(error));
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
mongoose.Promise = global.Promise;
mongoose.set('debug', process.env.NODE_ENV === 'development');
const models = {};
models.UserWobjects = require('./schemas/UserWobjectsSchema');
models.CommentRef = require('./schemas/CommentRefSchema');
models.ObjectType = require('./schemas/ObjectTypeSchema');
models.WObject = require('./schemas/wObjectSchema');
models.Comment = require('./schemas/CommentSchema');
models.User = require('./schemas/UserSchema');
models.Post = require('./schemas/PostSchema');
models.App = require('./schemas/AppSchema');
models.Campaign = require('./schemas/CampaignSchema');
models.paymentHistory = require('./schemas/paymentHistorySchema');
module.exports = {
Mongoose: mongoose,
models,
};
|
import React from 'react'
class Home extends React.Component{
constructor(){
super()
this.state={
show: false
}
}
showOrHide=()=>{
this.setState({show: !this.state.show})
}
render(){
return <React.Fragment>
<button id='toggle' onClick={this.showOrHide}>toggle!</button>
{this.state.show ? <div>Hello</div> :null}
</React.Fragment>
}
}
export default Home |
import React from 'react';
import {connect} from 'react-redux';
import LoaderActions from './LoaderActions'
import store from '../../store/configureStore'
class Loader extends React.Component{
constructor(props){
super(props);
}
// componentWillReceiveProps(nextProps) {
// console.log('componentWillReceiveProps --> loader');
// const {show} = nextProps;
// if(show==1){
// this.props.visible;
// }
// else
// this.props.hide;
// }
render(){
//console.log(this.props.isLoading);
return(
this.props.isLoading == 1 ?
<div className="loader">
{/*<img src="assets/img/ajax-loader.gif" // place your logo here
alt="SmartAdmin"/>*/}
<div className="sk-cube-grid">
<div className="sk-cube sk-cube1"></div>
<div className="sk-cube sk-cube2"></div>
<div className="sk-cube sk-cube3"></div>
<div className="sk-cube sk-cube4"></div>
<div className="sk-cube sk-cube5"></div>
<div className="sk-cube sk-cube6"></div>
<div className="sk-cube sk-cube7"></div>
<div className="sk-cube sk-cube8"></div>
<div className="sk-cube sk-cube9"></div>
</div>
</div>
:
<div></div>
);
}
}
function mapStateToProps(state) {
return {
isLoading: state.loader,
};
}
// function mapDispatchToProps(dispatch) {
// return {
// visible: () => dispatch(LoaderActions.visible()),
// hide: () => dispatch(LoaderActions.hide())
// };
// }
//export default connect(mapStateToProps,mapDispatchToProps)(Loader);
export default connect(mapStateToProps, null)(Loader);
export function Visibility(visible){
if(visible){
store.dispatch(LoaderActions.visible());
}
else{
store.dispatch(LoaderActions.hide());
}
} |
import React from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
import AdminPanel from '../components/adminPanel/adminPanel'
import '../static/style/style.scss'
import Head from './../components/Head'
const adminPanel = () => {
return (
<>
<Head title="Admin Panel" />
<Header />
<AdminPanel />
<Footer />
</>
)
}
export default adminPanel
|
const discord = require('discord.js');
const path = require('path');
const { config } = require('..');
module.exports = class Canvas {
/**
* @param {Object} statData pre-fetched stats data object
* @param {Object} message message object to retrieve channel and message data
*/
constructor(statData, message){
this.statData = statData
this.message = message
}
async overview(){
let stats = await this.statData
const Canvas = require('canvas')
Canvas.registerFont(path.join(__dirname, '../', 'assets', 'BurbankBigCondensed-Bold.otf'), { family: 'BurbankBigCondensed-Bold' })
const canvas = Canvas.createCanvas(600, 400)
const ctx = canvas.getContext('2d')
const template = await Canvas.loadImage(path.join(__dirname, '../', 'assets', 'overviewTemplate.jpg'))
if(!stats.lifetime.all)
return this.message.reply(`Error when retrieving data, this could be due to not having enough data to display for **${stats.user.displayName}** or there was an error parsing the display name. Try again using EPIC ID instead`)
let compWins = 0
let compMatches = 0
let compTime = 0
let compKd = 0
let compWinrate = 0
let compKills = 0
let defaultWins = 0
let defaultMatches = 0
let defaultTime = 0
let defaultKd = 0
let defaultWinrate = 0
let defaultKills = 0
let amountofentries = 0
for (const [key, value] of Object.entries(stats.lifetime.all)) {
if(key.includes('showdown')){
Object.entries(value).forEach(function(e) {
amountofentries++
if(e.includes(`placetop1`)){
compWins += e[1];
}
if(e.includes(`matchesplayed`)){
compMatches += e[1];
}
if(e.includes(`minutesplayed`)){
compTime += e[1];
}
if(e.includes(`kdr`)){
compKd += (e[1] * 100);
}
if(e.includes(`winrate`)){
compWinrate += (e[1] * 100);
}
if(e.includes(`kills`)){
compKills += (e[1]);
}
})
}
if(key.includes('default')){
Object.entries(value).forEach(function(e) {
amountofentries++
if(e.includes(`placetop1`)){
defaultWins += e[1];
}
if(e.includes(`matchesplayed`)){
defaultMatches += e[1];
}
if(e.includes(`minutesplayed`)){
defaultTime += e[1];
}
if(e.includes(`kdr`)){
defaultKd += (e[1] * 100);
}
if(e.includes(`winrate`)){
defaultWinrate += (e[1] * 100);
}
if(e.includes(`kills`)){
defaultKills += (e[1]);
}
})
}
}
let overallwins = compWins + defaultWins
let overallmatches = compMatches + defaultMatches
let overalltimeplayed = Math.floor((compTime + defaultTime) / 60)
let overallwinrate = ((overallwins / overallmatches) * 100).toFixed(2)
let overallkills = compKills + defaultKills
let overallkd = ((overallkills / ((overallmatches - overallwins > 0) ? overallmatches - overallwins : 1))).toFixed(2)
let ltmwins = parseInt(stats.lifetime.all.all.placetop1 - (overallwins))
let ltmmatches = parseInt(stats.lifetime.all.all.matchesplayed - overallmatches)
ctx.drawImage(template, 0, 0, canvas.width, canvas.height);
let checkLength = function CheckLength(value){
if(value.toString().length > 4){
ctx.font = '22px Burbank Big Cd Bd'
return value;
} else if(value.toString().length > 6){
ctx.font = '16px Burbank Big Cd Bd'
return value;
} else {
ctx.font = '26px Burbank Big Cd Bd'
return value;
}
}
// display name
ctx.font = '40px Burbank Big Cd Bd'
ctx.fillStyle = '#ffffff'
ctx.textAlign = 'left'
ctx.fillText(stats.user.displayName, 40, 65)
// main stats
ctx.font = '36px Burbank Big Cd Bd'
ctx.fillStyle = '#ffffff'
ctx.textAlign = 'center'
ctx.fillText(overallwins, 55, 146)
ctx.fillText(overallkd, 145, 146)
ctx.fillText(`${overallwinrate}%`, 245, 146)
ctx.fillText(overallmatches, 367, 146)
ctx.fillText(`${overalltimeplayed}hr`, 503, 146)
ctx.font = '26px Burbank Big Cd Bd'
ctx.fillStyle = '#ffffff'
ctx.textAlign = 'center'
// solos
if(stats.lifetime.all.defaultsolo){
ctx.fillText(checkLength(stats.lifetime.all.defaultsolo.placetop1), 60, 255)
ctx.fillText(checkLength(stats.lifetime.all.defaultsolo.kdr), 110, 255)
ctx.fillText(`${checkLength(stats.lifetime.all.defaultsolo.winrate.toFixed(1))}%`, 175, 255)
ctx.fillText(checkLength(stats.lifetime.all.defaultsolo.matchesplayed), 248, 255)}
// duos
if(stats.lifetime.all.defaultduo){
ctx.fillText(checkLength(stats.lifetime.all.defaultduo.placetop1), 60 + 273, 255)
ctx.fillText(checkLength(stats.lifetime.all.defaultduo.kdr), 110 + 273, 255)
ctx.fillText(`${checkLength(stats.lifetime.all.defaultduo.winrate.toFixed(1))}%`, 175 + 273, 255)
ctx.fillText(checkLength(stats.lifetime.all.defaultduo.matchesplayed), 248 + 273, 255)}
// squads
if(stats.lifetime.all.defaultsquad){
ctx.fillText(checkLength(stats.lifetime.all.defaultsquad.placetop1), 60, 354)
ctx.fillText(checkLength(stats.lifetime.all.defaultsquad.kdr), 110, 354)
ctx.fillText(`${checkLength(stats.lifetime.all.defaultsquad.winrate.toFixed(1))}%`, 175, 354)
ctx.fillText(checkLength(stats.lifetime.all.defaultsquad.matchesplayed), 248, 354)}
// ltms
ctx.fillText(checkLength(ltmwins), 60 + 273, 354)
ctx.fillText(`${stats.lifetime.all.all.minutesplayed ? checkLength(Math.floor(stats.lifetime.all.all.minutesplayed / 60 - overalltimeplayed)) : 0}hr`, 117 + 273, 354)
ctx.fillText(`${checkLength(stats.lifetime.all.all.kills - ((stats.lifetime.defaultsolo ? stats.lifetime.defaultsolo.kills : 0) +
(stats.lifetime.defaultduo ? stats.lifetime.defaultduo.kills : 0) +
(stats.lifetime.defaultsquad ? stats.lifetime.defaultsquad.kills : 0)))}`, 180 + 273, 354)
ctx.fillText(ltmmatches ? checkLength(ltmmatches) : 0, 248 + 273, 354)
const embed = new discord.MessageEmbed()
.setDescription(`**[Add this bot to your server.](${config.discord.invite})**`)
.setImage(`attachment://season_${stats.user.displayName}.jpg`)
.setFooter(`Note: If you provided an Xbox, Switch or PSN name instead of EPIC, your stats will not be accurate.`)
.setColor(config.discord.colors.success)
function attFile(){
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve(embed.attachFiles([{attachment: canvas.toBuffer(), name: `season_${stats.user.displayName}.jpg`}]));
}, 1200);
});
}
attFile().then(async a => await this.message.channel.send(embed))
}
} |
export function setMap(map) {
console.log('DISPATCH INIT_MAP');
return {
type: 'INIT_MAP',
map
}
}
export function updateMap(yPos, xPos, value) {
return {
type: 'UPDATE_MAP',
xPos,
yPos,
value
}
}
export function updateMapEnemy(yPos, xPos, health) {
return {
type: 'UPDATE_MAP_ENEMY',
xPos,
yPos,
health
}
}
export function updateCurrentEnemyHealth(health) {
return {
type: 'UPDATE_CURRENT_ENEMY_HEALTH',
health
}
}
export function updateCurrentEnemyDamage(damage) {
return {
type: 'UPDATE_CURRENT_ENEMY_DAMAGE',
damage
}
}
export function updatePlayerPos(yPos, xPos) {
return {
type: 'UPDATE_PLAYER_POS',
xPos,
yPos
}
}
export function updatePlayerFacing(facing) {
return {
type: 'UPDATE_PLAYER_FACING',
facing
}
}
export function updatePlayerHealth(health) {
return {
type: 'UPDATE_PLAYER_HEALTH',
health
}
}
export function updatePlayerWeapon(name, damage) {
console.log('DISPATCH UPDATE_PLAYER_WEAPON');
return {
type: 'UPDATE_PLAYER_WEAPON',
name,
damage
}
}
export function updatePlayerLevel(level) {
console.log('DISPATCH UPDATE_PLAYER_LVL');
return {
type: 'UPDATE_PLAYER_LVL',
level
}
}
export function updateView(view) {
return {
type: 'UPDATE_VIEW',
view
}
}
export function addMessage(message) {
return {
type: 'ADD_MESSAGE',
message
}
}
export function updateStatus(status) {
return {
type: 'UPDATE_STATUS',
status
}
} |
/**
* Author: Iancu George-Alexandru
* Created: 02.11.2019
*
* (c) Copyright by Iancu George-Alexandru.
**/
$("[data-intro='slide-block-1'").css('display', 'none');
$(".u-loading").css('display', 'none');
setTimeout(function () {
$("[data-intro='slide-block-0']").css('display', 'none');
$("[data-intro='slide-block-1']").css('display', 'inline-block');
}, 5000);
$("#checkName").on('keyup', function() {
if(this.value) {
$("[data-intro='button-start']").addClass('animated infinite pulse');
} else if(this.value == ""){
$("[data-intro='button-start']").removeClass('animated infinite pulse');
}
});
async function getKidName() {
return localStorage.getItem('name');
}
$("[data-intro='button-start']").on("click", async function() {
// magic happends here
var kidName = $("#checkName").val();
localStorage.setItem('name', kidName);
let nameSaved = await getKidName();
$('.u-loading').css('display', 'initial');
$('.u-loading .intro-loading-text').html(`
<h1>Buna `+ nameSaved + `!</h1>
<h1>Construim terenul de joaca pentru tine !</h1>
`);
setTimeout(function () {
window.location = "/de-la-comuna-noastra-la-planeta-albastra/pages/carte.html";
}, 4000);
})
|
const readlineSync = require("readline-sync");
let min = Number(readlineSync.question('un chiffre minimum?'));
let max = Number(readlineSync.question('un chiffre maximum plus grand que le minimum?'));
let current = Number(readlineSync.question('et choisis un chiffre au hazard?'));
if (current >= min && current <= max){
console.log(current);
}
if (min > max ){
console.log("ton chiffre au hazard se situe pas entre le minimum et le maximum");
} |
import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux'
class Status extends Component {
componentDidMount= () => {
setTimeout(() => {
this.props.dispatch({type: 'timesUp'})
}, 1000)
}
render= () => {
if (this.props.lost) {
return (<div> You lost </div>)
}
if (this.props.won) {
return (<div> You won </div>)
}
return (<div> Click as fast as possible! </div>)
}
}
let mapStateToProps = function(state) {
return {
lost: state.playerLost,
won: state.playerWon
}
}
let ConnectedStatus = connect(mapStateToProps)(Status)
export default ConnectedStatus;
|
import React from 'react';
import { Helmet } from 'react-helmet';
import styled, { ThemeProvider, createGlobalStyle } from 'styled-components';
import { colors, shadows, typography } from 'src/utils';
import Navbar from 'src/components/Navbar';
import HomeSection from 'src/sections/HomeSection';
import ServicesSection from 'src/sections/ServicesSection';
import AboutSection from 'src/sections/AboutSection';
import ContactSection from 'src/sections/ContactSection';
const pageContent = {
home: {
heading:
'Nawyk zarządzania pieniędzmi jest ważniejszy niż ilość posiadanych pieniędzy',
author: 'T. Harv Eker',
},
services: {
cards: [
'Optymalizacja Podatkowa',
'Rozliczenia',
'Ubezpieczenia',
'Dokumenty Urzędowe',
'Księgi Rachunkowe',
],
detailed: [
{
heading: 'Ksiegowość',
paragraph:
'Zajmujemy się szeroko pojętą księgowością. Prowadzimy działalności takie jak m.in.: usługi budowlane, usługi transportowe , produkcja maszyn i sprzedaży samochodów.',
},
{
heading: 'Ubezpieczenia',
paragraph:
'Zabezpieczymy cały Twój majątek. Oferujemy m. in. ubezpieczenia komunikacyjne i majątkowe. Kompleksowa obsługa floty.',
},
],
},
about: {
heading: 'O nas',
paragraph:
'Biurem rachunkowo- ubezpieczeniowym. Swoją ofertę kierujemy do małych i średnich firm. Dzięki wieloletniemu doświadczeniu usługi, które świadczymy są na największym poziomie. Za nasz największy sukces uznajemy zaufanie, jakim nas Państwo obdarzacie.',
},
contact: {
name: 'Agnieszka Tułowiecka',
email: 'agnieszkatul2@wp.pl',
phone: '+48 503 155 242',
adress: (
<span>
ul. Okrzei 3 lok. 3
<br />
07-300 Ostrów Mazowiecka
</span>
),
},
};
const GlobalStyle = createGlobalStyle`
*, *::before, *::after {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
font-weight: ${({ theme }) => theme.fontWeight.medium};
background-color: ${colors.primary};
color: ${colors.secondary};
}
`;
const RootWrapper = styled.main`
position: relative;
width: 100%;
overflow: hidden;
`;
const IndexPage = () => (
<ThemeProvider theme={{ ...colors, ...shadows, ...typography }}>
<Helmet>
<html lang="pl" />
<meta charSet="utf-8" />
<title>Agnieszka Tułowiecka</title>
</Helmet>
<GlobalStyle />
<Navbar />
<RootWrapper id="root">
<HomeSection content={pageContent.home} />
<ServicesSection content={pageContent.services} />
<AboutSection content={pageContent.about} />
<ContactSection content={pageContent.contact} />
</RootWrapper>
</ThemeProvider>
);
export default IndexPage;
|
var geschichte = {
situationen: [
{
id: 0,
auswahlText: "Im Museum",
"text":
"<br> *** Die Mumie des Schreckens ***<br>\
Ein Textadventure<br>Version 2.16 Pug-Software",
ziele: [1]
},
{
id: 1,
auswahlText: "Du betrittst das Museum",
text: "Du bist viel zu spät in das alte Museum gekommen. \
Dir bleibt nur noch wenig Zeit, bis das Museum schließt.\
Der erste Gong ist ertönt, Zeit, sich zum Ausgang zu begeben.",
ziele: [2, 3]
},
{
id: 2,
auswahlText: "Du schaust Dir ganz schnell noch den Nebenraum an?",
text: "Du gehst noch schnell in den Gang, der von dem Hauptraum abzweigt. \
Zahlreiche Artefakte einer vergangenen Epoche sind ausgestellt.\
Du vergisst die Zeit und überhörst sogar den letzten Gong. \
Plötzlich wird es dunkel, als alle Lichter ausgeschaltet werden.",
ziele: [4]
},
{
id: 3,
auswahlText: "Du gehst zum Ausgang?",
text: "Du machst dich schnellen Schrittes auf den Weg zum Ausgang. \
Du willst dich beeilen, doch durch deine große Hast rutscht du aus und stürzt.\
Du schlägst mit dem Kopf auf und wirst bewusstlos.",
ziele: [4]
},
{
id: 4,
auswahlText: "In die Dunkelheit?",
text: "Es ist vollkommen dunkel. Für einen Moment bist du orientierungslos. \
Du willst Dein Handy herausholen um Licht zu machen, als du Geräusche hörst.\
Sie kommen offenbar aus einem Nebenraum. Es hört sich an, als würde jemand \
schwere Gegenstände verschieben oder einen schweren Sack über den Boden \
schleifen?",
ziele: [5, 6]
},
{
id: 5,
auswahlText: "Du machst das Licht an?",
text: "Du holst Dein Handy aus der Gesäßtasche und aktivierst die Beleuchtung.\
Wenigstens kannst Du jetzt sehen was sich direkt in der Nähe befindet. Die Geräusche aus dem \
Nebenraum sind nicht mehr zu hören.",
ziele: [7, 8]
},
{
id: 6,
auswahlText: "Du rufst um Hilfe?",
text: "Erst leise, dann immer lauter rufst Du \"Hallo, hallo?! Ist da jemand?\"\
Niemand antwortet, auch die Geräusche aus dem Nebenraum sind nicht mehr zu hören.",
ziele: [7, 8]
},
{
id: 7,
auswahlText: "Du gehst langsam und vorsichtig zum Ausgang?",
text: "Du gehst leise und vorsichtig in Richtung Ausgang. Du hast das Gefühl, \
als wärst Du nicht alleine, aber Du kannst niemanden sehen oder hören. \
<br>Du erreichst den Ausgang und schaffst es eine Fluchttür zu öffnen, die laut \
hinter Dir zuschlägt. Du atmest tief durch, die Luft ist kalt.\
<br>Du bist froh aus dem Museum herausgekommen zu sein, aber Du fragst Dich was diese \
seltsamen Geräusche verursacht haben mag. Es fröstelt Dich beim Gedanken daran. \
Leider wirst Du es wohl nie herausfinden.<br><br>\
Das ist das Ende der Geschichte...",
ziele: []
},
{
id: 8,
auswahlText: "Du gehst in den Raum aus dem die Geräusche kamen?",
text: "Es ist dunkel als Du den Raum betrittst. Dein Handy leuchtet den Raum \
kaum aus. Auf den ersten Blick fällt Dir nur auf, dass einige Vitrinen scheinbar \
etwas verrückt sind. \
Erst nach einem Moment bemerkst Du, dass \
der Deckel eines alten ägyptischen Sarkophags verschoben ist und den Blick in \
das leere Innere ermöglicht.",
ziele: [7, 9]
},
{
id: 9,
auswahlText: "Du durchsuchst den Raum weiter?",
text: "Du kannst in der Dunkelheit kaum etwas erkennen. Das Licht Deines Handys \
leuchtet kaum zwei, drei Meter weit. Plötzlich wird Dir wird schwindelig \
und alles vor Dir scheint sich zu drehen. Weiter hinten im Raum kannst Du schemenhaft eine große \
Gestalt erkennen.",
ziele: [10, 20]
},
{
id: 10,
auswahlText: "Du gehst in die Richtung der Gestalt?",
text: "Langsam gehst Du auf die Gestalt zu, als Du plötzlich erkennen kannst wer da steht. \
Ein dicker Mann im Weihnachtskostüm steht vor Dir. Zu seinen Füßen steht ein \
großer Sack. Mit einem lauten \"Hohoho\" hält er Dir grinsend ein großes \
Paket entgegen. Er sieht genauso aus, wie Du Dir als Kind den Weihnachtsmann \
vorgestellt hast.",
ziele: [12, 11]
},
{
id: 11,
auswahlText: "Du reibst Dir verwundert die Augen?",
text: "Verwundert reibst Du Dir die Augen. Da stimmt etwas nicht. \
Es gibt keine Weihnachtsmänner, die nachts in einem geschlossenen Museum \
Geschenke verteilen. Und da ist immer noch dieses seltsame Schwindelgefühl. \
Das kann alles nicht sein! Als Du wieder zu dem Weihnachtsmann blickst, \
ist er verschwunden. Zu Deinem Entsetzen siehst Du eine lebendige Mumie, dort \
wo gerade noch der Weihnachtsmann stand. Statt eines Geschenks, greifen lange \
Arme nach Dir.",
ziele: [20, 30]
},
{
id: 12,
auswahlText: "Du nimmst das Geschenk?",
text: "Oh, wie wundervoll! Freudig willst Du das Geschenk nehmen, aber das Schwindelgefühl \
wird immer schlimmer. Du sackst bewusstlos in Dich zusammen.<br>Am nächsten Morgen wird man \
eine mumifizierte Leiche in diesem Raum finden.<br>\
Das ist das Ende - das ist Dein Ende!",
ziele: []
},
{
id: 20,
auswahlText: "Du rennst panisch davon?",
text: "Du rennst panisch in Richtung der Tür. Fast hast Du die Tür erreicht, als Du seltsame \
Laute hinter Dir hörst, fast so als würde etwas in einer alten Sprache gerufen. \
Du sackst bewusstlos in Dich zusammen.<br>Am nächsten Morgen wird man \
eine mumifizierte Leiche in diesem Raum finden.<br>\
Das ist das Ende - das ist Dein Ende!",
ziele: []
},
{
id: 20,
auswahlText: "Du gehst drehst Dich um und gehst zum Ausgang?",
text: "Du gehst rasch in Richtung Ausgang. Als Du durch die Gänge gehst, hast Du das Gefühl \
als ob Dir jemand folgen würde, aber Du kannst niemanden sehen oder hören. \
<br>Du erreichst den Ausgang und schaffst es eine Fluchttür zu öffnen, die laut \
hinter Dir zuschlägt. Müde kommst Du schließlich zu Hause an.\
<br>Auch wenn Du froh bist aus dem Museum herausgekommen zu sein, fragst Du Dich was diese \
seltsamen Geräusche verursacht haben mag. Nun, leider wirst Du es wohl nie herausfinden denn... <br><br>\
...das ist das Ende der Geschichte.",
ziele: []
},
{
id: 30,
auswahlText: "Du musst Dir ganz schnell etwas Originelles überlegen?",
text: "Du überlegst fieberhaft was Du tun könntest, als Dir ein großes, \
rot schimmerndes Amulett auffällt, dass um den Hals der Mumie hängt.",
ziele: [31, 40]
},
{
id: 31,
auswahlText: "Du greifst nach dem Amulett?",
text: "Du stürzt Dich nach vorne um der Mumie die Kette mit dem Amulett vom Hals zu reißen. \
Die Mumie bewegt sich erschreckend schnell, aber Du bist schneller. Du ergreifst das Amulett.\
Als Du es berührst spürst Du eine unglaubliche Hitze, die von dem roten Stein auszugehen scheint.",
ziele: [40, 32]
},
{
id: 32,
auswahlText: "Du greifst trotzdem nach dem Amulett?",
text: "Als Du das Amulett der Mumie von Hals reißt, durchströmt Dich eine unglaubliche Hitze \
und alles ist in ein strahlend helles Licht getaucht. Ein Licht \
so hell, dass Du glaubst es körperlich zu spüren.\
Es erscheint Dir als wäre eine Ewigkeit vergangen, als es plötzlich wieder dunkel wird. \
Die Mumie ist verschwunden und als Du Dich umblickst ist auch der Sarkophag \
verschlossen. Alle Gegenstände und Vitrinen stehen scheinbar unberührt im Raum.",
ziele: [35, 36]
},
{
id: 35,
auswahlText: "Du gehst drehst Dich um und gehst zum Ausgang?",
text: "Du gehst rasch in Richtung Ausgang. \
<br>Du erreichst den Ausgang und öffnest eine Fluchttür, die laut \
hinter Dir zuschlägt. Müde kommst Du schließlich zu Hause an.\
<br>Du bist froh unversehrt aus dem Museum herausgekommen zu sein... <br><br>\
...das ist das Ende der Geschichte.",
ziele: []
},
{
id: 36,
auswahlText: "Du öffnest den Sarkophag der Mumie?",
text: "Du musst wissen was hier passiert ist und was hier vor sich geht!\
\"Koste es was es wolle\", aber bei diesem Gedanken bekommst Du Angst vor Dir selbst.\
Das muss ein unheilvoller Einfluss sein, der von dem Sarkophag ausgeht. Du atmest \
tief ein und beschließt zu gehen.",
ziele: [35]
},
{
id: 40,
auswahlText: "Du rennst zu dem offenen Sarkophag der Mumie?",
text: "Du rennst zu dem offenen Sarkophag, denn hier hat das Übel seinen Ursprung und \
hier muss es auch wieder zu einem Ende gebracht werden. Du blickst zur Mumie, doch sie ist \
nicht mehr zu sehen - als Du plötzlich eine Berührung auf Deiner Schulter spürst. Entsetzt \
blickst Du Dich um und blickst in die toten Augen der Mumie. <br>\
Du sackst bewusstlos in Dich zusammen.<br>Am nächsten Morgen wird man \
eine mumifizierte Leiche in diesem Raum finden.<br>\
Das ist das Ende - das ist Dein Ende!",
ziele: []
},
]
};
|
const cv = require('opencv4nodejs');
//1.相机标定
// 1.1相机内参
const cameraMatrix = new cv.Mat([
[3215.626082522419, 0, 1471.556444548214],
[0, 3222.051668804792, 1927.086879135644],
[0, 0, 1]
], cv.CV_32F);
//1.2相机畸变系数
const distCoeffs = [0.4829911929113178, -2.098554567754686, -0.004550508970407664, -0.003201260898451633, 2.290223376487714];
exports.param={
matrix:cameraMatrix,
dist:distCoeffs,
}
|
// match `menu` block
block('menu')( // this.ctx
content()(function() {
return ({
block: 'menu',
mods: { section: 'learning' },
content: [
{ elem: 'title', content: this.ctx.title },
{ elem: 'list', content: this.ctx.items.map(
function(item) { return { elem: 'item', url: item.url, title: item.title }; })
}
]
});
})
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.