text
stringlengths 7
3.69M
|
|---|
import Grid from '@material-ui/core/Grid'
import Typography from '@material-ui/core/Typography'
import {withTheme,withStyles} from '@material-ui/core/styles'
import classes from '../../../static/styles/styles'
import classNames from 'classnames'
let mockData = require('../../../static/mockDB/instaReview.json')
const Headercomponent= (props)=>(
<Grid item xs={12} id="headingDiv" className={props.classes.wireframeBorderPink}>
{/* imageDiv */}
<Grid container item id="imageDiv" justify="center" direction="row" className={props.classes.wireframeBorderPink} >
<Grid item className={props.classes.wireframeBorderBlue} xs={12} sm={12} md={6} lg={6}>
<img className={props.classes.responsiveImage} src={mockData.header.image} alt="" />
</Grid>
<Grid item container={true} alignContent='center' className={props.classes.wireframeBorderBlue} xs={12} sm={12} md={6} lg={6} >
{/* header item */}
< Grid item lg={12} md={12} sm={12}>
<Typography align="center" variant='h2' style={{ marginBottom: '3%' }}>
{`${mockData.header.title}`}
</Typography>
</Grid >
{/* header content item */}
< Grid item id={`headerContentOne`}>
<Typography align="center" variant='body1'>
{`${mockData.header.contentOne}`}
</Typography>
</Grid >
</Grid>
</Grid >
{/* heading content */}
< Grid container={true} justify="center" id="headingContentDiv" direction="column" className={props.classes.wireframeBorderPink} display="block" alignItems="center">
{/* header content Two */}
< Grid md={10} item style={{ margin: '15px' }} className={props.classes.wireframeBorderBlue} id={'headerContentTwo'}>
<Typography align="center" variant='body1'>
{`${mockData.header.contentTwo}`}
</Typography>
</Grid >
</Grid >
</Grid>
)
let HeaderComponentWithStyle = withStyles(classes)(Headercomponent)
export default HeaderComponentWithStyle
|
import React from 'react'
import Button from '../../components/Button/Button'
export default function Navbar(props) {
return (
<div className="navbar">
<div>Navbar text</div>
<Button title="Sample button" />
</div>
)
}
|
import React from 'react';
import '../styles.css';
import ImageView from './imageView/imageView';
import ItemDetailsView from './itemDetailsView/itemDetailsView';
export default class App extends React.Component {
constructor() {
super();
this.state = {
product: {},
};
}
componentWillMount() {
const path = window.location.pathname.split('/');
const id = Number(path[2]);
this.getProductInfo(id);
}
getProductInfo(id) {
const url = `http://localhost:8004/api/product/${id}`;
fetch(url)
.then(res => res.json())
.then((res) => {
this.setState({ product: res });
})
.catch(e => console.error(e));
}
render() {
const { image_url: images, ...details } = this.state.product;
if (this.state.product.id === undefined) {
return <div />;
}
return (
<div id="item-detail-module">
<ImageView
images={images}
title={details.name}
/>
<ItemDetailsView details={details} />
</div>
);
}
}
|
$(document).ready(function(){
let CustomerData = JSON.parse(localStorage["CustomerData"]);
$("#first").text(CustomerData.first); //GETTING THE VALUE FROM THE DATA WERE ID IS FIRST
console.log(CustomerData);
$("#email").text(CustomerData.email);//GETTING THE VALUE FROM THE DATA WERE ID IS EMAIL
$("#products").text(CustomerData.products);//GETTING THE VALUE FROM THE DATA WERE ID IS PRODUCTS
$("#quantity").text(CustomerData.quantity);//GETTING THE VALUE FROM THE DATA WERE ID IS QUANTITY
var price = (CustomerData.quantity)*2; //CALACULATION FOR PRICE
$("#total").text(price);
//THIS FOLLOWING ARE ALL ARE THE GETITEM FUCTION OF LOCALSTROAGE TO GET THE VALUE OF EACH INPUT
document.getElementById('name').innerHTML = localStorage.getItem('first');
document.getElementById('email').innerHTML = localStorage.getItem('email');
document.getElementById('quantity').innerHTML = localStorage.getItem('quantity');
document.getElementById('products').innerHTML = localStorage.getItem('products');
document.getElementById('final').innerHTML = final;
});
|
/**
* @param {*} arr
* @return {Boolean}
*/
var isArray = module.exports.isArray = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
};
/**
* @param {*} arr
* @return {Boolean}
*/
var isNonEmptyArray = module.exports.isNonEmptyArray = function (arr) {
return isArray(arr) && arr.length;
};
/**
* @param {Array.<Number>} p1
* @param {Array.<Number>} p2
* @return {Boolean}
*/
module.exports.equals = function equals(p1, p2) {
return p1[0] === p2[0] && p1[1] === p2[1];
};
/**
* @param {*} coordinates
* @param {Number=} depth
* @return {*}
*/
module.exports.orientRings = function orientRings(coordinates, depth, isHole) {
depth = depth || 0;
var i, len;
if (isNonEmptyArray(coordinates) && typeof coordinates[0][0] === 'number') {
var area = 0;
var ring = coordinates;
for (i = 0, len = ring.length; i < len; i++) {
var pt1 = ring[i];
var pt2 = ring[(i + 1) % len];
area += pt1[0] * pt2[1];
area -= pt2[0] * pt1[1];
}
if ((!isHole && area > 0) || (isHole && area < 0)) {
ring.reverse();
}
} else {
for (i = 0, len = coordinates.length; i < len; i++) {
orientRings(coordinates[i], depth + 1, i > 0);
}
}
if (depth === 0 && isNonEmptyArray(coordinates) && isNonEmptyArray(coordinates[0]) && typeof coordinates[0][0][0] === 'number') {
var clone = coordinates[0].slice(0, 1)[0];
coordinates[0].pop();
coordinates[0].push([clone[0], clone[1]]);
}
return coordinates;
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet } from 'react-native';
import { sizes, colors } from '../../../constants/theme';
import dropShadowStyle from '../../../utils/dropShadowStyle';
const handlePaddingAndMargin = (type, value) => {
const { horizontal, vertical, top, bottom, left, right } = value;
if (typeof value === 'number') {
return {
[`${type}`]: value,
};
}
return {
[`${type}Horizontal`]: horizontal,
[`${type}Vertical`]: vertical,
[`${type}Top`]: top,
[`${type}Bottom`]: bottom,
[`${type}Left`]: left,
[`${type}Right`]: right,
};
};
const Block = (props) => {
const {
card,
container,
flex,
row,
rowReverse,
wrap,
column,
columnReverse,
center,
middle,
left,
right,
top,
bottom,
align,
justify,
space,
color,
padding,
margin,
width,
w100,
maxWidth,
elevation,
radius,
children,
style,
blockRef,
relative,
...viewProps
} = props;
const blockStyles = [
styles.block,
flex && { flex: flex === true ? 1 : flex },
card && styles.card,
container && styles.container,
row && styles.row,
rowReverse && styles.rowReverse,
wrap && styles.wrap,
column && styles.column,
columnReverse && styles.columnReverse,
center && styles.center,
middle && styles.middle,
left && styles.left,
right && styles.right,
top && styles.top,
bottom && styles.bottom,
align && { alignItems: align },
justify && { justifyContent: justify },
space && { justifyContent: `space-${space}` },
color && styles[color],
color && !styles[color] && { backgroundColor: color },
padding && handlePaddingAndMargin('padding', padding),
margin && handlePaddingAndMargin('margin', margin),
width && { width },
maxWidth && { maxWidth },
w100 && { width: '100%' },
elevation && { ...dropShadowStyle(elevation) },
radius && { borderRadius: radius },
relative && { position: 'relative' },
style,
];
return (
<View ref={blockRef} style={blockStyles} {...viewProps}>
{children}
</View>
);
};
const styles = StyleSheet.create({
block: {},
card: {
padding: sizes.base,
borderRadius: sizes.radius,
backgroundColor: colors.white,
...dropShadowStyle(sizes.elevation),
},
container: { paddingHorizontal: sizes.base },
row: { flexDirection: 'row' },
rowReverse: { flexDirection: 'row-reverse' },
wrap: { flexWrap: 'wrap' },
column: { flexDirection: 'column' },
columnReverse: { flexDirection: 'column-reverse' },
center: { alignItems: 'center' },
right: { alignItems: 'flex-end' },
left: { alignItems: 'flex-start' },
middle: { justifyContent: 'center' },
top: { justifyContent: 'flex-start' },
bottom: { justifyContent: 'flex-end' },
primary: { backgroundColor: colors.primary },
secondary: { backgroundColor: colors.secondary },
black: { backgroundColor: colors.black },
black1: { backgroundColor: colors.black1 },
black2: { backgroundColor: colors.black2 },
white: { backgroundColor: colors.white },
gray: { backgroundColor: colors.gray },
gray2: { backgroundColor: colors.gray2 },
gray3: { backgroundColor: colors.gray3 },
});
Block.propTypes = {
children: PropTypes.node,
flex: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
card: PropTypes.bool,
container: PropTypes.bool,
row: PropTypes.bool,
rowReverse: PropTypes.bool,
wrap: PropTypes.bool,
column: PropTypes.bool,
columnReverse: PropTypes.bool,
center: PropTypes.bool,
left: PropTypes.bool,
right: PropTypes.bool,
middle: PropTypes.bool,
top: PropTypes.bool,
bottom: PropTypes.bool,
align: PropTypes.oneOf([
false,
'flex-start',
'flex-end',
'center',
'stretch',
'baseline',
]),
justify: PropTypes.oneOf([
false,
'flex-start',
'flex-end',
'center',
'space-between',
'space-around',
'space-evenly',
]),
space: PropTypes.oneOf([false, 'between', 'around', 'evenly']),
color: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
padding: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
top: PropTypes.number,
right: PropTypes.number,
left: PropTypes.number,
bottom: PropTypes.number,
horizontal: PropTypes.number,
vertical: PropTypes.number,
}),
]),
margin: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
top: PropTypes.number,
right: PropTypes.number,
left: PropTypes.number,
bottom: PropTypes.number,
horizontal: PropTypes.number,
vertical: PropTypes.number,
}),
]),
w100: PropTypes.bool,
elevation: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
radius: PropTypes.number,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
};
Block.defaultProps = {
children: null,
card: false,
container: false,
flex: 0,
row: false,
rowReverse: false,
wrap: false,
column: false,
columnReverse: false,
center: false,
middle: false,
left: false,
right: false,
top: false,
bottom: false,
align: false,
justify: false,
space: false,
color: 'transparent',
padding: 0,
margin: 0,
w100: false,
elevation: false,
radius: 0,
style: {},
};
export default Block;
|
function do_refract(state) {
// state has n_in, n_out, v_in. Assumes ray hits surf at [0,0]
// returns v_out, Reff, Teff
let sin_theta_in = v2.sin(state.normal, state.v_in), // from normal to v_in
sin_theta_out = state.n_in*sin_theta_in/state.n_out,
theta_out,
v_out,
T, R
if (Math.abs(sin_theta_out)<1) {
// we have (some) refraction
theta_out = Math.asin(sin_theta_out) // from normal to v_out
v_out = v2.rotate(state.normal,theta_out)
// work out Fresnel reflections
let cos_theta_in = Math.sqrt(1-sin_theta_in**2),
nrat = (state.n_in*sin_theta_in/state.n_out)**2,
n1cos = state.n_in*cos_theta_in,
n2sqrt = state.n_out*Math.sqrt(1-nrat),
Rs = ( (n1cos-n2sqrt)/(n1cos+n2sqrt) )**2,
n1sqrt = state.n_in*Math.sqrt(1-nrat),
n2cos = state.n_out*cos_theta_in,
Rp = ( (n1sqrt-n2cos)/(n1sqrt+n2cos) )**2
R = (Rs+Rp)/2
} else {
R = 1
}
// compute reflected ray
let v = v2.decompose(state.v_in, state.normal)
v_reflect = v2.sub(v[1], v[0]),
theta_in = Math.asin(sin_theta_in)
return {theta_in, theta_out, v_out, R, v_reflect}
}
|
function checkpPrice(){
var pprice=$("input[name='pprice']").val();
var reg = /^[0-9]*$/;
if(pprice==""){
alert("商品价格不能为空");
// $("input[name='pprice']").focus();
return false;
}else if(!reg.test(pprice)){
alert("您输入的商品价格不符合要求,请重新输入");
// $("input[name='pprice']").focus();
return false;
}
}
function checkpCount(){
var pcount=$("input[name='pcount']").val();
var reg = "^\\d+$";
if(pcount==""){
alert("商品数量不能为空");
// $("input[name='pcount']").focus();
return false;
}else if(!reg.test(pcount)){
alert("您输入的商品数量不符合要求,请重新输入");
// $("input[name='pcount']").focus();
return false;
}
}
function checkpStandard(){
var pstandard=$("input[name='pstandard']").val();
if(pstandard==""){
alert("商品规格不能为空");
// $("input[name='pstandard']").focus();
return false;
}else if(pstandard.length>32){
alert("商品规格输入的长度过长,请重新输入");
// $("input[name='pstandard']").focus();
return false;
}
}
function checkpDesc(){
var pdesc=$("input[name='pdesc']").val();
if(pdesc==""){
alert("商品描述不能为空");
// $("input[name='pdesc']").focus();
return false;
}
}
function savePro(){
checkpName();
//checkpPrice();
checkpCount();
checkpStandard();
checkpDesc();
}
|
import { AdminPage } from '../../pages/admin/admin';
const admin = new AdminPage();
describe( 'Admin', () => {
beforeEach( () => {
admin.open();
admin.login();
} );
it( 'should login', () => {
cy.contains( 'Welcome' );
} );
it( 'should be able to edit a page', () => {
admin.openMostRecentPage();
admin.publishPage();
admin.successBanner().should( 'be.visible' );
} );
it( 'should be able to open the image gallery', () => {
admin.openImageGallery();
admin.getImages().should( 'be.visible' );
admin.tags().should( 'contain', 'Mortgages' );
} );
it( 'should be able to open the document library', () => {
admin.openDocumentsLibrary();
admin.getFirstDocument().should( 'be.visible' );
} );
it( 'should support our snippet libraries', () => {
admin.openContacts();
admin.addContact();
admin.successBanner().should( 'be.visible' );
} );
it( 'should have mortage constants stored', () => {
admin.openMortgageConstants();
admin.addMortgageConstant();
admin.successBanner().should( 'be.visible' );
} );
it( 'should have mortgage metadata', () => {
admin.openMortgageMetadata();
admin.addMortgageMetadata();
admin.successBanner().should( 'be.visible' );
} );
it( 'should edit an existing regulation', () => {
admin.openRegulations();
admin.editRegulation();
admin.successBanner().should( 'be.visible' );
} );
it( 'should copy an existing regulation', () => {
admin.openRegulations();
admin.copyRegulation();
admin.successBanner().should( 'be.visible' );
admin.cleanUpRegulations();
admin.successBanner().should( 'be.visible' );
} );
it( 'should edit the Mega Menu', () => {
admin.openMegaMenu();
admin.editMegaMenu();
admin.successBanner().should( 'be.visible' );
} );
it( 'should be able to modify tdp activities', () => {
admin.openBuildingBlockActivity();
admin.editBuildingBlock();
admin.successBanner().should( 'be.visible' );
} );
it( 'should be able to modify Applicant Types', () => {
admin.openApplicantTypes();
admin.editApplicantType();
admin.successBanner().should( 'be.visible' );
} );
it( 'should be able to toggle a flag', () => {
admin.openFlag();
admin.toggleFlag();
admin.flagHeading().should( 'contain', 'enabled for all requests' );
admin.toggleFlag();
admin.flagHeading().should( 'contain', 'enabled when any condition is met.' );
} );
it( 'should support the block inventory', () => {
admin.openBlockInventory();
admin.searchBlocks();
admin.searchResults().should( 'be.visible' );
} );
it( 'Should support external links', () => {
admin.openExternalLinks();
admin.searchExternalLink( 'https://www.federalreserve.gov' );
admin.searchResults().should( 'be.visible' );
} );
it( 'should open the django admin', () => {
admin.openDjangoAdmin();
cy.url().should( 'contain', 'django-admin' );
} );
it( 'should include the page metadata report', () => {
admin.getPageMetadataReports().its( 'length' ).should( 'be.gt', 2 );
} );
describe( 'Editor Table', () => {
beforeEach( () => {
admin.openCFGovPage();
admin.addBlogChildPage();
admin.addFullWidthTextElement();
admin.addTable();
} );
it( 'should be able to create and edit a table', () => {
admin.selectFirstTableCell();
admin.selectTableEditorTextbox();
admin.selectTableEditorButton( 'unordered-list-item' );
admin.typeTableEditorTextbox( 'test cell text' );
admin.saveTableEditor();
admin.searchFirstTableCell( 'test cell text' ).should( 'be.visible' );
} );
it( 'should be able to select all standard edit buttons in table', () => {
admin.selectFirstTableCell();
admin.selectTableEditorTextbox();
admin.selectTableEditorButton( 'BOLD' );
admin.selectTableEditorButton( 'ITALIC' );
admin.selectTableEditorButton( 'header-three' );
admin.selectTableEditorButton( 'header-four' );
admin.selectTableEditorButton( 'header-five' );
admin.selectTableEditorButton( 'ordered-list-item' );
admin.selectTableEditorButton( 'unordered-list-item' );
admin.selectTableEditorButton( 'undo' );
admin.selectTableEditorButton( 'redo' );
} );
it( 'should be able to use link button', () => {
admin.selectFirstTableCell();
admin.selectTableEditorButton( 'LINK' );
admin.selectInternalLink( 'CFGov' );
admin.saveTableEditor();
cy.get( 'td' ).contains( 'CFGov' ).should( 'be.visible' );
} );
it( 'should be able to use document button', () => {
const documentName = 'cfpb_interested-vendor-instructions_fy2020.pdf';
admin.selectFirstTableCell();
admin.selectTableEditorButton( 'DOCUMENT' );
admin.selectDocumentLink( documentName );
admin.saveTableEditor();
cy.get( 'td' ).contains( documentName ).should( 'be.visible' );
} );
it( 'should be able to save an empty cell', () => {
const initialText = 'hi';
admin.selectFirstTableCell();
admin.selectTableEditorTextbox();
admin.typeTableEditorTextbox( initialText );
admin.saveTableEditor();
admin.getFirstTableCell().should( 'not.be.empty' );
admin.selectFirstTableCell();
admin.selectTableEditorTextbox();
for ( let x = 0; x < initialText.length; x++ ) {
admin.backspaceTableEditorTextbox();
}
admin.saveTableEditor();
admin.getFirstTableCell().should( 'be.empty' );
} );
} );
} );
|
const assert = require("assert");
const { TonClient, signerNone, signerKeys, signerExternal, abiContract,
builderOpInteger, builderOpCell, builderOpCellBoc, builderOpBitString } = require("@tonclient/core");
const { Account } = require("@tonclient/appkit");
const { libNode } = require("@tonclient/lib-node");
const fs = require('fs');
const path = require('path');
const keysFile = path.join(__dirname, '../keys.json');
const { get_tokens_from_giver } = require('../giverConfig.js')
const config = require('../config');
const { LighthouseContract } = require('../../artifacts/LighthouseContract.js');
const { RootContract } = require('../../artifacts/RootContract.js');
const { XRTContract } = require('../../artifacts/XRTContract.js');
const { SimpleWalletContract } = require('../../artifacts/SimpleWalletContract.js')
const { MultiValidatorExampleContract } = require('../../artifacts/MultiValidatorExampleContract.js')
const { constructContracts, getLighthouseAddress } = require('../common.js')
const u = (size, x) => {
if (size === 256) {
return builderOpBitString(`x${BigInt(x).toString(16).padStart(64, "0")}`)
} else {
return builderOpInteger(size, x);
}
}
const u8 = x => u(8, x);
const u32 = x => u(32, x);
const u64 = x => u(64, x);
const u128 = x => u(128, x);
const u256 = x => u(256, x);
const b0 = u(1, 0);
const b1 = u(1, 1);
const bits = x => builderOpBitString(x);
const bytes = x => builderOpCell([bits(x.toString("hex"))]);
const str = x => bytes(Buffer.from(x, "utf8"));
const addrStdFixed = (x) => {
let parts = x.split(":");
const wid = parts.length < 2 ? "00" : Number.parseInt(parts[0]).toString(16).padStart(2, "0");
const addr = parts[parts.length < 2 ? 0 : 1].padStart(64, "0");
return bits(`${wid}${addr}`);
};
const addrInt = (x) => {
let parts = x.split(":");
let [wid, addr] = parts.length < 2 ? ["0", parts[0]] : parts;
wid = Number.parseInt(wid).toString(2).padStart(8, "0");
addr = BigInt(`0x${addr}`).toString(2).padStart(256, "0");
return bits(`n100${wid}${addr}`);
};
async function signHash(client, hash, keys) {
const data = Buffer.from(hash, 'hex').toString('base64')
const signature = (await client.crypto.sign({ unsigned: data, keys: keys})).signature
return (await client.boc.encode_boc({
builder: [
builderOpBitString('x' + signature)
]
})).boc;
}
async function main(client, liabilityHash) {
const keys = JSON.parse(fs.readFileSync(keysFile, "utf8"));
const simpleWallet = new Account(SimpleWalletContract, {signer: signerKeys(keys), client: client, initData: {nonce: 0} });
const { root, xrt } = await constructContracts(client, keys)
const lighthouse = new Account(LighthouseContract, { address: await getLighthouseAddress(client, root, xrt, 'Lighthouse'), client: client })
const validator = new Account(MultiValidatorExampleContract,
{signer: signerKeys(keys), client: client,
initData: {
lighthouse: await lighthouse.getAddress(),
k: 2,
pubkeys: {
1: '0x' + keys.public,
2: '0x' + keys.public,
3: '0x' + keys.public
}
}
});
// now it is taken from CL agruments
//const liabilityHash = '0x501a89e93fdd70cfec3eb42fa9e8a5a2bbb5ce2ff785fe505f708597dc17a493'
var dataCell = (await client.boc.encode_boc({
builder: [
addrInt(await validator.getAddress()),
u32(42),
bytes(Buffer.from('Super result')),
u256(liabilityHash),
b1
]
})).boc;
var dataHash = Buffer.from((await client.boc.get_boc_hash({boc : dataCell})).hash, 'hex')
var signature = await signHash(client, dataHash, keys)
await client.net.subscribe_collection({
collection: "messages",
filter: {
src: { eq: await lighthouse.getAddress() },
},
result: "id, src, dst, msg_type, value, boc, body",
}, async (params, responseType) => {
try{
if (params.result.msg_type == 2) {
const decoded = (await client.abi.decode_message({
abi: abiContract(LighthouseContract.abi),
message: params.result.boc,
}));
console.log('>>> ', decoded);
}
} catch(err) {
console.log(err)
}
});
await client.net.subscribe_collection({
collection: "messages",
filter: {
src: { eq: await validator.getAddress() },
},
result: "id, src, dst, msg_type, value, boc, body",
}, async (params, responseType) => {
try {
if (params.result.msg_type == 2) {
const decoded = (await client.abi.decode_message({
abi: abiContract(MultiValidatorExampleContract.abi),
message: params.result.boc,
}));
console.log('>>> ', decoded);
}
} catch(err) {
console.log(err)
}
});
validator.run('addProposal', {pubkey_id : 1, dataCell: dataCell, signature: signature});
dataCell = (await client.boc.encode_boc({
builder: [
addrInt(await validator.getAddress()),
u32(42),
]
})).boc;
dataHash = Buffer.from((await client.boc.get_boc_hash({boc : dataCell})).hash, 'hex')
signature = await signHash(client, dataHash, keys)
validator.run('signProposal', {pubkey_id : 2, dataCell: dataCell, signature: signature});
console.log('Now waiting 5 sec...')
await new Promise(resolve => setTimeout(resolve, 5000));
}
(async () => {
try {
TonClient.useBinaryLibrary(libNode);
const client = new TonClient({
network: {
endpoints: config['network']['endpoints'],
}
});
console.log("Hello TON!");
if (process.argv.length < 3) {
console.log('Please specify liability hash as CLI agrument')
process.exit(1);
}
await main(client, process.argv[2]);
process.exit(0);
} catch (error) {
console.error(error);
}
})();
|
import React, {Fragment} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableOpacity,
Image,
TextInput,
Modal,
} from 'react-native';
import {SvgXml} from 'react-native-svg';
import SVG from '../components/SvgComponent';
import LabelInput from '../components/atom/LabelInput';
const EvaluationRegist = ({navigation}) => {
return (
<Fragment>
<StatusBar barStyle="dark-content" />
<SafeAreaView />
<ScrollView style={{backgroundColor: 'white'}}>
<View style={{backgroundColor: '#f3f3f3'}}>
{/* */}
<View
style={{
flexDirection: 'row',
padding: 24,
marginBottom: 4,
backgroundColor: 'white',
}}>
{/* 이미지 */}
<View style={{width: 60, height: 60, marginRight: 12}}>
<Image
source={require('../images/1.jpeg')}
resizeMode="contain"
style={{width: 60, height: 60}}
/>
</View>
{/* 이름 */}
<View style={{justifyContent: 'center'}}>
<Text style={{color: 'gray', fontSize: 13, marginBottom: 5}}>
존슨즈 베이비
</Text>
<Text style={{fontSize: 15}}>
수딩내추럴 인텐스 모이스처 크림
</Text>
</View>
</View>
{/* */}
<View style={{backgroundColor: 'white', flex: 1}}>
<LabelInput placeholder={'홍길동'} label={'이름'} />
<LabelInput placeholder={'000-0000-0000'} label={'전화번호'} />
<LabelInput
placeholder={'대전광역시 유성구 덕명로 97번길 19'}
label={'주소지입력'}
/>
<LabelInput placeholder={'(직접입력)'} label={false} />
{/* */}
<Text>상품선택</Text>
{/* */}
<Text>이용자 동의</Text>
{/* */}
<Text>개인정보처리방침 및 위탁통의(필수)</Text>
{/* */}
</View>
{/* */}
</View>
</ScrollView>
</Fragment>
);
};
const styles = StyleSheet.create({});
export default EvaluationRegist;
|
//1- Imprimir por consola un mensaje guardado en una variable usando la función console.log()
var hola = "Hola";
console.log(hola);
|
/**
*
* customOrbitControls.
*
* @project localhost_panoplayer
* @datetime 01:13 - 30/07/2015
* @author Thonatos.Yang <thonatos.yang@gmail.com>
* @copyright Thonatos.Yang <https://www.thonatos.com>
*
*/
exports.dragControls = function (object,domElement,mobile) {
this.object = object;
this.mobile = mobile;
this.enabled = true;
this.domElement = (domElement !== undefined) ? domElement : document;
this.object.target = new THREE.Vector3(0, 0, 0);
/**
* 旋转角度计算方法
*
* 容器: 宽度作为X,容器高度为Y;
* 屏幕: 水平移动距离为dX,垂直移动距离为dY;
* 角度: degreeX = dX/X * 180 ( |degreeX| < 360), degreeY = dY/Y * 90 ( |degreeY| < 90 );
*
*/
var scope = this;
var X,Y;
var lastPoint = {
x:0,
y:0
},
currentPoint = {
x:0,
y:0
};
var lon = 0,
lat = 0,
fov = 200 / 3,
isUserInteracting = false;
function getFov(scale){
var newFOV = 2 * Math.atan(Math.tan((fov * Math.PI / 180) / 2) / scale) * 180 / Math.PI;
return newFOV;
}
var mobileEvent = function () {
var mc = new Hammer(scope.domElement);
mc.add(new Hammer.Pan({ threshold: 0, pointers: 0, domEvents: true }));
mc.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([mc.get('pan')]);
mc.on("pinchstart pinchmove", onPinch);
mc.on("panstart", onPanStart);
mc.on("panmove", onPanMove);
mc.on("panend", onPanEnd);
var initScale = 1;
var targetScale = 1;
function onPinch(ev) {
if(ev.type == 'pinchstart') {
initScale = targetScale || 1;
}
initScale = ev.scale > 1 ? ev.scale : (ev.scale - 1);
}
function onPanStart(ev) {
isUserInteracting = true;
lastPoint = {
x:ev.center.x,
y:ev.center.y
};
}
function onPanEnd(ev) {
isUserInteracting = false;
}
function onPanMove(ev) {
if (isUserInteracting) {
currentPoint = {
x:ev.center.x,
y:ev.center.y
};
//lon = onPointerDownLon + (ev.center.x - onPointerDownPointerX) * 0.8;
//lat = onPointerDownLat - (ev.center.y - onPointerDownPointerY) * 0.2;
if(typeof ev.stopPropagation === "function"){
ev.stopPropagation();
}
}
}
};
var desktopEvent = function () {
function onDocumentMouseDown(event) {
event.preventDefault();
isUserInteracting = true;
lastPoint = {
x:event.clientX,
y:event.clientY
};
}
function onDocumentMouseMove(event) {
if (isUserInteracting) {
//lon = onPointerDownLon + (event.clientX - onPointerDownPointerX) * 0.1;
//lat = onPointerDownLat - (event.clientY - onPointerDownPointerY) * 0.1;
currentPoint = {
x:event.clientX,
y:event.clientY
};
}
}
function onDocumentMouseUp(event) {
isUserInteracting = false;
}
function onDocumentMouseWheel(event) {
//// WebKit
//if (event.wheelDeltaY) {
// distance -= event.wheelDeltaY * 0.5;
//
// // Opera / Explorer 9
//} else if (event.wheelDelta) {
// distance -= event.wheelDelta * 0.5;
//
// // Firefox
//} else if (event.detail) {
// distance += event.detail * 10;
//
//}
//
//distance = Math.max(300, Math.min(distance, 1200));
//
////mtlog(distance);
//scope.object.projectionMatrix.makePerspective(fov, window.innerWidth / window.innerHeight, 1, 10000);
}
// document event
scope.domElement.addEventListener('mousedown', onDocumentMouseDown, false);
scope.domElement.addEventListener('mousemove', onDocumentMouseMove, false);
scope.domElement.addEventListener('mouseup', onDocumentMouseUp, false);
scope.domElement.addEventListener('mousewheel', onDocumentMouseWheel, false);
scope.domElement.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
};
this.connect = function () {
X = scope.domElement.clientWidth;
Y = scope.domElement.clientHeight;
if(scope.mobile){
mobileEvent();
}else{
desktopEvent();
}
};
this.update = function () {
if(!scope.enabled) return;
var mx = (currentPoint.x - lastPoint.x)/X;
var my = (currentPoint.y - lastPoint.y)/Y;
console.log(mx,my);
lon = mx * 2 * Math.PI;
lat = Math.min(Math.max(-Math.PI / 2, my * Math.PI), Math.PI / 2);
//var rotm = new THREE.Quaternion().setFromEuler(
// new THREE.Euler(lat, lon, 0, "YXZ"));
//scope.object.quaternion.copy(rotm);
scope.object.rotation.y = scope.object.rotation.y - lon;
scope.object.rotation.x = scope.object.rotation.x + lat;
lastPoint = currentPoint;
//degreeX = dX/X * 180; // ( |degreeX| < 360)
//degreeY = dY/Y * 90; // ( |degreeY| < 90 )
};
this.connect();
};
|
import React,{Component} from 'react'
import PropTypes from 'prop-types';
import './index.css'
import AuthProvider from '../../../funStore/AuthProvider'
import promiseFile from '../../../funStore/UploadXHR'
import {API_PATH} from '../../../constants/OriginName'
import {sendEvent} from '../../../funStore/CommonFun'
export default class UploadFile extends Component {
constructor(props){
super(props)
this.state = {
imgUrl: props.imgUrl,
loading: false,
num: 0
}
}
clickHandle=()=> {
let fileContainer = document.createElement("input")
fileContainer.type = 'file'
fileContainer.onchange = (e) => {
this.uploadEvent(e.target.files[0],e.target.value)
}
fileContainer.click()
}
uploadEvent=(file,value) =>{
const index = value.lastIndexOf('.')
const finalName = value.substr(index+1)
const format = this.props.limitFormat
const size = file.size
const formData = new FormData()
formData.append('file',file)
if(!format.includes(finalName.toLowerCase())){
// 图片格式错误或大小超过限制
sendEvent('message', {txt: '图片格式错误!', code: 1004})
return
}
if(size>this.props.limitSize){
// 图片格式错误或大小超过限制
sendEvent('message', {txt: '图片大小超过限制!', code: 1004})
return
}
this.getImageSize(file, (w,h,data)=>{
this.setState({
imgUrl: data
})
this.successHandle(formData).then(res => {
this.props.onChange(res)
})
})
}
successHandle=(formData)=>{
const self = this
// const url = API_PATH+'/gridfs-api/noauth/s3-media'
const url = API_PATH+'/gridfs-api/noauth/media'
this.startLoading()
return promiseFile(url,formData)
.then(res => {
this.endLoading()
if(self.props.clear){
this.setState({
imgUrl: ''
})
}
return res.resultContent
})
}
getImageSize = (file,callback) => {
let reader=new FileReader()
reader.onload=function (e) {
let data=e.target.result//读取的结果
let image=new Image()
image.onload=() => {
let width=image.width,
height=image.height;
callback(width,height,data)
};
image.src=data
};
reader.readAsDataURL(file);
}
startLoading = () => {
this.setState({
loading: true
})
let timecount =()=> {
let num = this.state.num
num+=1
if(num<100){
this.setState({
num: num
})
}else{
clearInterval(this.timer)
}
}
this.timer = setInterval(timecount,10)
}
endLoading = () => {
clearInterval(this.timer)
this.setState({
loading: false,
num: 0
})
}
deleteHandle = (e) =>{
e.stopPropagation()
this.setState({
imgUrl: ''
})
this.props.onDelete('')
}
render(){
const {imgUrl,loading,num} = this.state
const {text,propsStyle,limitSize} = this.props
return (
<div className="public-uploadFile" onClick={this.clickHandle} style={propsStyle}>
{
imgUrl
?<div className="preview" style={{backgroundImage:'url('+imgUrl+')'}}>
{
loading
?<div className="loadModal" style={{height:(100-num)+'%'}}>
</div>
:<div className="icon-del" onClick={this.deleteHandle}></div>
}
{
loading?<span>{num}%</span>:''
}
</div>
:<div className="noPic">
<div className="icon-add"></div>
<div>{text}</div>
</div>
}
</div>
)
}
}
UploadFile.defaultProps={
text: '',//图片不超过4M
limitSize: 4194304,
imgUrl:'',
limitFormat:["jpg","png","jpeg"]
}
UploadFile.propTypes = {
// optionalArray: PropTypes.array,
// optionalBool: PropTypes.bool,
// optionalFunc: PropTypes.func,
// optionalNumber: PropTypes.number,
// optionalObject: PropTypes.object,
// optionalString: PropTypes.string,
// optionalSymbol: PropTypes.symbol,
text: PropTypes.string,
limitSize: PropTypes.number,
limitFormat: PropTypes.array,
propsStyle: PropTypes.object,
imgUrl: PropTypes.string,
onChange: PropTypes.func,
onDelete: PropTypes.func
}
|
/*var x = 0;
while(x < 10){
document.write("Numero: " + x + "</br>");
x ++;
}
document.write("Finalizando o loop...");
for (x = 0; x < 10; x++) {
document.write("Numero: " + x +"</br>");
}
*/
function verificar(){
var n1 = document.getElementById("n1").innerHTML;
var n2 = document.getElementById("n2").value;
if(n1 == n2){
alert("Parabens, você acertou!!");
}else{
alert("Infelizmente você errou :/");
}
resetar();
}
function resetar(){
document.getElementById("n2").value = "";
var r = Math.floor(Math.random() *100);
document.getElementById("n1").innerHTML = r;
}
|
import styles from "../styles/scoreboard.module.scss";
const Scoreboard = ({ score }) => {
return (
<div className={styles.scoreBoard}>
<div className={styles.title}>
<img src="./images/title.png" />
</div>
<div className={styles.score}>
<p>SCORE</p>
<h1 className="score-count">{score}</h1>
</div>
</div>
);
};
export default Scoreboard;
|
'use strict';
// Use application configuration module to register a new module
ApplicationConfiguration.registerModule('grid', ['ui.grid']);
|
import { createSelector } from 'reselect';
// Selector
const getBalance = state => state.balance;
// Reselect function
export const getBalanceState = createSelector(
[getBalance],
balance => balance
);
|
'use strict';
//Constantes de VIP.
const Attributes = require('../Classes/Attributes');
const Libraries = require('../Base/Libraries');
/**
* Función getLaunchRequestMessage: encargada de devolver el mensaje de bienvenida.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getLaunchRequestMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getLaunchRequestMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.LaunchRequestSpeakText);
console.VIPLog('getLaunchRequestMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getLaunchRequestMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getSessionEndedRequestMessage: encargada de devolver el mensaje de despedida.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getSessionEndedRequestMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getSessionEndedRequestMessage INIT');
attributes.clear();
attributes.session.withShouldEndSession = true;
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.SessionEndedSpeakText);
console.VIPLog('getSessionEndedRequestMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getSessionEndedRequestMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getRestartMessage: encargada de devolver el mensaje de reinicio del flujo.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getRestartMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getRestartMessage INIT');
attributes.clear();
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.RestartSpeakText);
console.VIPLog('getRestartMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getRestartMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getHelpMessage: encargada de devolver el mensaje de ayuda.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getHelpMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getHelpMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.HelpSpeakText);
console.VIPLog('getHelpMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getHelpMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getRepeatMessage: encargada de devolver el mensaje anterior.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getRepeatMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getRepeatMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, attributes.voiceResponse.speakText, attributes.voiceResponse.repromptText, attributes.voiceResponse.speakTextScreen, attributes.voiceResponse.repromptTextScreen);
console.VIPLog('getRepeatMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getRepeatMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getSillyStuffMessage: encargada de devolver el mensaje del fallback.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getSillyStuffMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getSillyStuffMessage INIT');
if (attributes.session.errorRepeatTimes == 0) {
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.SillyStuffSpeakText[0]);
}
else {
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.SillyStuffSpeakText[1]);
}
attributes.session.errorRepeatTimes += 1;
console.VIPLog('getSillyStuffMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getSillyStuffMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getGratitudeMessage: encargada de devolver el mensaje de agradecimiento.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getGratitudeMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getGratitudeMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.GratitudeSpeakText);
console.VIPLog('getGratitudeMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getGratitudeMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getHateMessage: encargada de devolver el mensaje de odio.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getHateMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getHateMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.HateSpeakText);
console.VIPLog('getHateMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getHateMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getComingSoonMessage: encargada de devolver el mensaje de futuras funcionalidades.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getComingSoonMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getComingSoonMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.ComingSoonSpeakText);
console.VIPLog('getComingSoonMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getComingSoonMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getNoFutureFuncionalitiesMessage: encargada de devolver el mensaje de funcionalidades que no soportará la Skill.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getNoFutureFuncionalitiesMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getNoFutureFuncionalitiesMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.NoFutureFuncionalitiesSpeakText);
console.VIPLog('getNoFutureFuncionalitiesMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getNoFutureFuncionalitiesMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getGreetingsMessage: encargada de devolver el mensaje de saludos.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getGreetingsMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog('getGreetingsMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.GreetingsSpeakText);
console.VIPLog('getGreetingsMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getGreetingsMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getLegRoutineMessage: encargada de devolver el mensaje de saludos.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getLegRoutineMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
if (attributes.session.currentIntent != 'NextExercise' && attributes.session.currentIntent != 'NeedSupport') {
attributes.exerciseCounter = 0;
}
let currentExerciseMessage = '';
let currentExerciseRepromptMessage = '';
console.VIPError("ERROR IN LEG ROUTINE: "+ attributes.exerciseCounter);
attributes.session.currentIntent = 'LegRoutine';
switch (attributes.exerciseCounter){
case 0:
attributes.exerciseCounter = 1;
attributes.apl.title = 'LegRoutineExercise1';
currentExerciseMessage = Libraries.TextConstants.LegRoutineSpeakText + Libraries.TextConstants.LegRoutineExercise1Text;
currentExerciseRepromptMessage = Libraries.TextConstants.LegRoutineRepromptText + Libraries.TextConstants.LegRoutineExercise1Text;
break;
case 1:
attributes.exerciseCounter = 2;
attributes.apl.title = 'LegRoutineExercise2';
currentExerciseMessage = Libraries.TextConstants.LegRoutineExercise2Text;
currentExerciseRepromptMessage = Libraries.TextConstants.LegRoutineExercise2RepromptText;
break;
case 2:
attributes.exerciseCounter = 0;
attributes.apl.title = 'Congratulations';
currentExerciseMessage = Libraries.TextConstants.LegRoutineEndText;
currentExerciseRepromptMessage = Libraries.TextConstants.LegRoutineEndRepromptText;
break;
default:
attributes.exerciseCounter = 0;
attributes.apl.title = 'Index';
currentExerciseMessage = Libraries.TextConstants.LegRoutineDefaultText;
currentExerciseRepromptMessage = Libraries.TextConstants.LegRoutineDefaultRepromptText;
break;
}
console.VIPLog('getLegRoutineMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes,
currentExerciseMessage,
currentExerciseRepromptMessage);
console.VIPLog('getLegRoutineMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getLegRoutineMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getArmRoutineMessage: encargada de devolver el mensaje de saludos.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getArmRoutineMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
if (attributes.session.currentIntent != 'NextExercise' && attributes.session.currentIntent != 'NeedSupport') {
attributes.exerciseCounter = 0;
}
let currentExerciseMessage = '';
let currentExerciseRepromptMessage = '';
console.VIPLog("Current exercise: "+ attributes.exerciseCounter);
attributes.session.currentIntent = 'ArmRoutine';
switch (attributes.exerciseCounter){
case 0:
attributes.exerciseCounter = 1;
attributes.apl.title = 'ArmRoutineExercise1';
currentExerciseMessage = Libraries.TextConstants.ArmRoutineSpeakText + Libraries.TextConstants.ArmRoutineExercise1Text;
currentExerciseRepromptMessage = Libraries.TextConstants.ArmRoutineRepromptText + Libraries.TextConstants.ArmRoutineExercise1Text;
break;
case 1:
attributes.exerciseCounter = 2;
attributes.apl.title = 'ArmRoutineExercise2';
currentExerciseMessage = Libraries.TextConstants.ArmRoutineExercise2Text;
currentExerciseRepromptMessage = Libraries.TextConstants.ArmRoutineExercise2RepromptText;
break;
case 2:
attributes.exerciseCounter = 0;
attributes.apl.title = 'Congratulations';
currentExerciseMessage = Libraries.TextConstants.ArmRoutineEndText;
currentExerciseRepromptMessage = Libraries.TextConstants.ArmRoutineEndRepromptText;
break;
default:
attributes.exerciseCounter = 0;
attributes.apl.title = 'Index';
currentExerciseMessage = Libraries.TextConstants.ArmRoutineDefaultText;
currentExerciseRepromptMessage = Libraries.TextConstants.ArmRoutineDefaultRepromptText;
break;
}
console.VIPLog('getArmRoutineMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes,
currentExerciseMessage,
currentExerciseRepromptMessage);
console.VIPLog('getArmRoutineMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getArmRoutineMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
async function getNextExerciseMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
console.VIPLog("PREV:"+attributes.session.previousIntent + " CURR:"+ attributes.session.currentIntent);
if (attributes.session.currentIntent != 'NextExercise' && attributes.session.currentIntent != 'NeedSupport') {
attributes.exerciseCounter = 0;
}
switch(attributes.session.previousIntent){
case 'LegRoutine':
return await getLegRoutineMessage(attributes);
break;
case 'ArmRoutine':
return await getArmRoutineMessage(attributes);
break;
default:
console.VIPLog('getNextExerciseMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes,
Libraries.TextConstants.NextExerciseDefaultText,
Libraries.TextConstants.NextExerciseDefaultRepromptText);
console.VIPLog('getNextExerciseMessage ENDED');
return Promise.resolve(attributes);
break;
}
} catch (error) {
console.VIPError('getNextExerciseMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getBreakRoutineMessage: encargada de devolver el mensaje de saludos.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getBreakRoutineMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
attributes.exerciseCounter = 0;
attributes.apl.title = 'Index';
console.VIPLog('getBreakRoutineMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes, Libraries.TextConstants.BreakRoutineText, Libraries.TextConstants.BreakRoutineRepromptText);
console.VIPLog('getBreakRoutineMessage ENDED');
return Promise.resolve(attributes);
} catch (error) {
console.VIPError('getBreakRoutineMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
/**
* Función getNeedSupportMessage: encargada de devolver el mensaje de saludos.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
async function getNeedSupportMessage(attributes = new Attributes().init(attributes)) {
console.VIPLog('attributes: ' + JSON.stringify(attributes, null, 4));
try {
try {
if (attributes.exerciseCounter > 0){
attributes.exerciseCounter--;
}
switch(attributes.session.previousIntent){
case 'LegRoutine':
return await getLegRoutineMessage(attributes);
break;
case 'ArmRoutine':
return await getArmRoutineMessage(attributes);
break;
default:
console.VIPLog('getNeedSupportMessage INIT');
await Libraries.UtilsVIP.getSpeakText(attributes,
Libraries.TextConstants.NeedSupportText,
Libraries.TextConstants.NeedSupportRepromptText);
console.VIPLog('getNeedSupportMessage ENDED');
return Promise.resolve(attributes);
break;
}
} catch (error) {
console.VIPError('getNeedSupportMessage try error: ' + error);
throw new Error(error);
};
} catch (error) {
await Libraries.UtilsVIP.getErrorText(attributes);
return Promise.resolve(attributes);
}
}
module.exports.getLaunchRequestMessage = getLaunchRequestMessage;
module.exports.getSessionEndedRequestMessage = getSessionEndedRequestMessage;
module.exports.getRestartMessage = getRestartMessage;
module.exports.getHelpMessage = getHelpMessage;
module.exports.getRepeatMessage = getRepeatMessage;
module.exports.getSillyStuffMessage = getSillyStuffMessage;
module.exports.getGratitudeMessage = getGratitudeMessage;
module.exports.getHateMessage = getHateMessage;
module.exports.getComingSoonMessage = getComingSoonMessage;
module.exports.getNoFutureFuncionalitiesMessage = getNoFutureFuncionalitiesMessage;
module.exports.getGreetingsMessage = getGreetingsMessage;
module.exports.getLegRoutineMessage = getLegRoutineMessage;
module.exports.getArmRoutineMessage = getArmRoutineMessage;
module.exports.getNextExerciseMessage = getNextExerciseMessage;
module.exports.getBreakRoutineMessage = getBreakRoutineMessage;
module.exports.getNeedSupportMessage = getNeedSupportMessage;
|
//TODO - change functions to use args rather than list of params
var nodes = new Array();
var player = new Player();
var worldVars = [];
worldVars['mummy-asleep'] = true;
worldVars['daddy-asleep'] = true;
function init ()
{
goNode('start');
player.update();
console.log("OK");
}
function goNode (nodeId)
{
var node = getNodeById(nodeId);
$('#text').html(node.getText());
$('#options').html(node.getOptions());
// node actions?
if (node.action) {
eval(node.action);
}
}
function getNodeById (nodeId)
{
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.id == nodeId) { return node; }
}
return new Node();
}
//
|
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Table from "react-bootstrap/Table";
import Card from "react-bootstrap/Card";
const Orders = () => {
const [orderData, setOrderData] = useState([]);
const { id } = useParams();
useEffect(() => {
fetch(`https://fast-escarpment-60313.herokuapp.com/orders`)
.then((res) => res.json())
.then((data) => {
const userOrder = data.filter((order) => order.userId === id);
setOrderData(userOrder);
});
}, [id]);
return (
<Card className="container my-5">
<Card.Body>
<h5>Placed Orders</h5>
<hr />
<Table striped bordered responsive>
<thead>
<tr>
<th>Product Id</th>
<th>Delivery Address</th>
<th>Order for</th>
<th>Order Date</th>
</tr>
</thead>
<tbody>
{orderData.map((order) => (
<tr key={order._id}>
<td>{order.bookId}</td>
<td>{order.address}</td>
<td>{order.name}</td>
<td>{order.date}</td>
</tr>
))}
</tbody>
</Table>
</Card.Body>
</Card>
);
};
export default Orders;
|
var errorFactory = require('error-factory');
var objectUtil = require('./object');
var resources = require('./resources');
var ModuleContextException = errorFactory('beyo.ModuleContextException', [ 'message', 'messageData' ]);
module.exports = createModuleContext;
/**
Create a module context
*/
function createModuleContext(module, config) {
var context = new ModuleContext();
if (arguments.length === 0) {
throw ModuleContextException('No module specified');
} else if (!module || module.constructor !== Object) {
throw ModuleContextException('Invalid module argument');
} else if (!('name' in module)) {
throw ModuleContextException('Module has no name');
} else if ((typeof module.name !== 'string') || !resources.isModuleNameValid(module.name)) {
throw ModuleContextException('Invalid module name: {{moduleName}}', { moduleName: module.name });
}
Object.defineProperties(context, {
'_module': {
configurable: false,
enumerable: false,
writable: false,
value: module
},
'_config': {
configurable: false,
enumerable: false,
writable: false,
value: config || {}
},
'config': {
configurable: false,
enumerable: true,
writable: false,
value: readConfigValue
}
});
return context;
}
/**
Module context constructor
*/
function ModuleContext() {}
/**
Return a configuration value from the specified path
*/
function readConfigValue(path, defValue) {
return objectUtil.getValue(this._config, path, defValue);
}
|
const exphbs = require('express-handlebars');
const path = require('path');
const helpers = {
ifeq: function(a, b, options) {
if (a === b) {
return options.fn(this);
}
return options.inverse(this);
},
};
const hbs = exphbs.create({
helpers,
extname: '.hbs',
partialsDir: path.resolve(__dirname, '../shared/templates/mail'),
});
module.exports = hbs;
|
module.exports = function () {
// document用于测试浏览器端
let div = document.createElement('div')
div.innerHTML = 'Hello world'
document.body.appendChild(div)
return 'Hello World'
}
|
module.exports = {
devServer: {
host: 'test-ssxl.speiyou.com',
port: 5555
}
}
|
// Route Search
import React, { useState } from "react";
import Jumbotron from "../components/Jumbotron";
import { Col, Row, Container } from "../components/Grid";
import { Input, FormBtn, LogoutBtn } from "../components/Form";
import { Link } from "react-router-dom";
import Searches from "../components/Searched";
import API from "../utils/API";
function RouteSearch() {
const [place, setPlace] = useState({ city: "", state: "" });
const [routes, setRoutes] = useState({});
const { city, state } = place;
const handleInputChange = event => {
// # name => name of state to update || value => what to update it to
const { name, value } = event.target;
setPlace({
...place,
[name]: value
});
}
const handleFormSubmit = event => {
event.preventDefault();
API.getMountainRoutes(city, state)
.then(res => {
setRoutes(res.data)
})
.catch(err => console.log(err));
setPlace({
...place,
city: "",
state: ""
})
}
const handleAddRoute = key => {
const filtered = routes.filter(a => {
return a.id === key
})
console.log(filtered[0])
API.saveRoute({
routeID: filtered[0].id,
routeName: filtered[0].name,
routeType: filtered[0].type,
routeImage: filtered[0].imgSmall,
routePitch: filtered[0].pitches,
routeLocation: {
lat: filtered[0].latitude,
long: filtered[0].longitude,
location: filtered[0].location
},
routeDifficulty: filtered[0].rating,
})
.then(res => {
// res.json(res)
console.log("Route saved")
})
.catch(err => console.log(err));
}
const handleLogout = (e) => {
e.preventDefault();
API.logout()
.then(() => {
window.location.assign("/");
})
.catch(e => {
console.log("error!", e);
});
}
return (
<Container fluid>
<Row>
<Col size="md-9">
<Jumbotron>
<h1>Search Page</h1>
<Link to="/routes" >
<button type="button" className="btn btn-success">
Saved Routes
</button>
</Link>
<LogoutBtn onClick={handleLogout}>
Logout
</LogoutBtn>
</Jumbotron>
<form>
<Input
city={city}
state={state}
handleInputChange={handleInputChange}
/>
<FormBtn
// disabled={!(formObject.location)}
handleFormSubmit={handleFormSubmit}
>
Search Location
</FormBtn>
</form>
{routes.length ? (
<div>
{routes.map(route => (
<Searches key={route.id}
image={route.imgSmall}
name={route.name}
type={route.type}
rating={route.rating}
pitches={route.pitches}
location={route.location}
lat={route.longitude}
long={route.latitude}
handleAddRoute={() => handleAddRoute(route.id)}
/>
))}
</div>
) : (
<h3>No Results to Display</h3>
)}
</Col>
</Row>
</Container>
);
}
export default RouteSearch;
|
import React from 'react'
const Specials = () => {
return(
<h3 className="specials-banner">
Friday Special -- 10% off ALL Miso Ramen
</h3>
)
}
export default Specials
|
// a partir do useState é possível usar estados nos componentes
import React, { useState} from 'react';
import IndiretaFilho from './IndiretaFilho';
export default props => {
// useState gera um array com o valor passado como parametro e uma função
// para alterar o valor (que será chamada a partir de setNome por causa do destruct)
let [nome, setNome] = useState('?');
let [idade, setIdade] = useState(0);
let [nerd, setNerd] = useState(false);
// cria a função no pai e passa pro filho via props
function fornecerInfo(nome, idade, nerd) {
// isso altera o valor mas não reflete no que é renderizado
// nome = nomeParam;
// idade = idadeParam;
// nerd = nerdParam;
setNome(nome);
setIdade(idade);
setNerd(nerd);
}
return (
<div>
<div>Pai</div>
<div>
<span>Nome: {nome} | </span>
<span>Idade: {idade} | </span>
<span>Nerd: {nerd ? 'Sim' : 'Não'}</span>
</div>
<IndiretaFilho quandoClicar={fornecerInfo}/>
</div>
)
}
|
/*global syncRequest, Meteor */
var request = Meteor.npmRequire('request');
var makeErrorByStatus = function(statusCode, content) {
var MAX_LENGTH = 500; // if you change this, also change the appropriate test
var truncate = function(str, length) {
return str.length > length ? str.slice(0, length) + '...' : str;
};
var contentToCheck = typeof content === 'string' ? content : content.toString();
var message = 'failed [' + statusCode + ']';
if (contentToCheck) {
message += ' ' + truncate(contentToCheck.replace(/\n/g, ' '), MAX_LENGTH);
}
return new Error(message);
};
var populateData = function(response) {
var contentType, err;
contentType = (response.headers['content-type'] || ';').split(';')[0];
if (_.include(['application/json', 'text/javascript'], contentType)) {
try {
response.data = JSON.parse(response.content);
} catch (error1) {
err = error1;
response.data = null;
}
} else {
response.data = null;
}
};
var normalizeOptions = function(uri, options, callback) {
if (!uri) {
throw new Error('undefined is not a valid uri or options object.');
}
if ((typeof options === 'function') && !callback) {
callback = options;
}
if (options && typeof options === 'object') {
options.uri = uri;
} else if (typeof uri === 'string') {
options = {
uri: uri
};
} else {
options = uri;
}
return {
options: options,
callback: callback
};
};
var normalizeResponse = function(error, res, body) {
var response;
response = null;
if (!error) {
response = {};
response.statusCode = res.statusCode;
response.content = body;
response.headers = res.headers;
populateData(response);
if (response.statusCode >= 400) {
error = makeErrorByStatus(response.statusCode, response.content);
}
}
return {
error: error,
response: response
};
};
var wrappedRequest = function(uri, options, callback) {
var ref;
ref = normalizeOptions(uri, options, callback);
options = ref.options;
callback = ref.callback;
return request(options, function(error, res, body) {
var ref1, response;
ref1 = normalizeResponse(error, res, body);
error = ref1.error;
response = ref1.response;
return callback(error, response);
});
};
var wrappedCall = function(method, uri, options, callback) {
options.method = method;
return wrappedRequest(uri, options, callback);
};
var wrappedGet = function(uri, options, callback) {
return wrappedCall('GET', uri, options, callback);
};
var wrappedPost = function(uri, options, callback) {
return wrappedCall('POST', uri, options, callback);
};
var wrappedPut = function(uri, options, callback) {
return wrappedCall('PUT', uri, options, callback);
};
var wrappedDelete = function(uri, options, callback) {
return wrappedCall('DELETE', uri, options, callback);
};
/* jshint -W020 */
syncRequest = Meteor.wrapAsync(wrappedRequest);
syncRequest.call = Meteor.wrapAsync(wrappedCall);
syncRequest.get = Meteor.wrapAsync(wrappedGet);
syncRequest.post = Meteor.wrapAsync(wrappedPost);
syncRequest.put = Meteor.wrapAsync(wrappedPut);
syncRequest['delete'] = Meteor.wrapAsync(wrappedDelete);
syncRequest.del = syncRequest['delete'];
// create request's jar
syncRequest.jar = request.jar;
|
import React, {useState, useEffect, useContext} from "react";
//import { userContext } from "../../utils/Context.js";
//components
import Row from '../Row';
import Col from '../Col';
import { Thumbnail } from "./Thumbnail";
import { Snippet } from "./Snippet";
import { SaveBtn } from "./SaveBtn";
//style
import './style.css'
export function ResultListItem(props) {
//const [currentUser, setCurrentUser] = useContext(userContext);
const [selectShelf, setSelectShelf] = useState();
const selectEl = document.querySelector('#select-shelf');
function HandleShelfChange (e){
const {value} = e.target;
setSelectShelf(value);
}
return (
<div className='container-fluid list-item'>
<Row>
<Col size='sm-2'>
<Thumbnail
alt={props.title}
src={props.thumbnail}
/>
</Col>
<Col size='sm-3'>
<h4>{props.title}</h4>
<p>{props.author}</p>
</Col>
<Col size='sm-5'>
<Snippet
snippet={props.snippet}
/>
</Col>
<Col size='sm-2'>
<select id='select-shelf' className="form-select select-shelf" aria-label="Shelf select" onChange={HandleShelfChange}>
<option>Select a shelf</option>
{props.shelves.map((shelf, index)=>
<option key={index} value={shelf._id}>{shelf.name}</option>
)}
</select>
<SaveBtn
className='save-btn'
data-bookid= {props.bookId}
data-shelfid={selectShelf}
data-index={props.index}
onClick= {props.onClick}
/>
</Col>
</Row>
</div>
);
}
|
var node = new Node({ id:"start" });
node.addText("It's Saturday morning. <br /><br /> You wake up early and can hear lots of noise downstairs.");
node.addText("What do you do?");
node.addOption('Go back to sleep', "back-to-sleep");
node.addOption("Go into Mummy and Daddy's room", "mummy-and-daddy-room");
node.addOption("Go downstairs and investigate", "go-downstairs");
nodes.push(node);
var node = new Node({ id:"back-to-sleep" });
node.addText("You try and go back to sleep but the noise is keeping you awake.");
node.addText("You decide to get up.");
node.addOption("Go into Mummy and Daddy's room", "mummy-and-daddy-room");
node.addOption("Go downstairs and investigate", "go-downstairs");
nodes.push(node);
var node = new Node({ id:"mummy-and-daddy-room" });
node.addText("Mummy and Daddy are both asleep.<br /><br />What do you want to do?");
node.addOption("Leave them alone and go downstairs", "go-downstairs");
node.addOption("Wake Mummy", "wake-mummy");
node.addOption("Wake Daddy", "wake-daddy");
nodes.push(node);
var node = new Node({ id:"wake-daddy" });
node.addText("You poke Daddy in the face.");
node.addText("\"Ow!\" he says. \"What's the matter?\"");
node.addText("You explain about the noise. Daddy gives you his torch and tells you to go and investigate.");
node.addOption("Go downstairs", "go-downstairs");
node.addOption("Wake Mummy", "wake-mummy", { condition:"worldVars['mummy-asleep']" });
node.action = "player.giveItem('torch');worldVars['daddy-asleep'] = false;";
nodes.push(node);
var node = new Node({ id:"wake-mummy" });
node.addText("You shake Mummy.<br /><br />She groans and then does a really loud and smelly fart!");
node.addText("The smell is terrible and you lose 10 health points.");
node.action = "player.injure(10);worldVars['mummy-asleep'] = false;";
node.addOption("Go downstairs", "go-downstairs");
node.addOption("Wake Daddy", "wake-daddy", { condition:"worldVars['daddy-asleep']" });
nodes.push(node);
var node = new Node();
node.id = "go-downstairs";
node.addText("You stand at the top of the stairs but is too dark to see.");
node.addText("You press the light switch but nothing happens. You decide to go down anyway.");
node.addText("Luckily, daddy gave you a torch and you get downstairs safely.", { condition:"player.hasItem('torch')" });
node.addText("You struggle to see and trip on a toy. You fall down and bash your head. Lose 10 health points.", { condition:"!player.hasItem('torch')", action:"player.injure(10)" });
node.addText("The noise seems to be comming from the lounge, but the kitchen light is on.");
node.addOption("Go into the lounge", "go-in-lounge");
node.addOption("Go into the kitchen", "go-in-kitchen");
nodes.push(node);
var node = new Node({ id:"go-in-kitchen" });
node.addText("The kitchen is a complete mess. There is food everywhere and it looks like someone has tried to make some toast.");
node.addText("You see a water pistol on the worktop.");
node.addOption("Pick up the water pistol and go to the lounge", "pick-up-water-pistol");
node.addOption("Go to the lounge", "go-in-lounge");
nodes.push(node);
var node = new Node({ id:"pick-up-water-pistol" });
node.action = "player.giveItem('water-pistol');player.injure(10);";
node.addText("You carefully tip-toe to the worktop, trying to avoid all the food on the floor.");
node.addText("Suddenly you feel something cold and wet under your foot.");
node.addText("You have stepped in some soggy cornflakes, yuk! You slip and bang your head. Lose 10 health points.");
node.addText("You pick yourself up, grab the water pistol and head to the lounge.");
node.addOption("Go to the lounge", "go-in-lounge");
nodes.push(node);
var node = new Node({ id:"go-in-lounge" });
node.addText("You slowly open the lounge door and peer in. Netflix is blasting out episodes of Friends.");
node.addText("There is a girl asleep on the sofa. She is face down and you can't tell who it is.");
node.addOption("Squirt her with the water pistol", "squirt-girl", { condition:"player.hasItem('water-pistol')" });
node.addOption("Poke her", "poke-girl");
node.addOption("Turn Netflix off and go back to bed.", "turn-netflix-off");
nodes.push(node);
var node = new Node({ id:"turn-netflix-off" });
node.addText("You turn Netflix off. The sleeping girl stirs and rolls over - it's your sister!");
node.addText("You are glad that you didn't squirt her.", { condition:"player.hasItem('water-pistol')" });
node.addText("Your sister settles down again and continues to sleep.");
node.addText("Now it's quiet you head back upstairs to get some more sleep.");
node.addText("You get into bed and feel warm and snuggly. You drift off to sleep and dream of further adventures.");
nodes.push(node);
var node = new Node({ id:"squirt-girl" });
node.addText("You point the water pistol at the girl and start squirting like a mad-man.");
node.addText("The girl wakes with a start and screams. She is not happy...");
node.addText("She starts kicking and punching at you. Lose 20 health points.", { action:"player.injure(20)" });
node.addText("You realize that the girl is your sister, oh no!");
node.addOption("Run back to your bedroom", "run-to-bedroom");
node.addOption("Stop squirting and say sorry", "stop-squirting");
nodes.push(node);
var node = new Node({ id:"stop-squirting" });
node.addText("You stop squirting and say 'sorry, sorry, sorry'.");
node.addText("Your sister calms down and you both start laughing - what a way to be woken up!");
node.addText("You both snuggle up on the sofa and start binge-watching Netflix.");
nodes.push(node);
var node = new Node({ id:"poke-girl" });
node.addText("You poke the girl and she rolls over - It's your sister!");
node.addOption("Squirt her in the face!", "squirt-girl", { condition:"player.hasItem('water-pistol')" });
node.addOption("Turn Netflix off", "turn-netflix-off-2");
node.addOption("Sit down and watch Netflix", "watch-netflix");
nodes.push(node);
var node = new Node({ id:"watch-netflix" });
node.addText("You start watching Friends and laugh loudly at Joey doing jazz-hands.");
node.addText("You feel a rumble in your tummy, and need to fart.");
node.addOption("Let rip", "do-a-fart");
node.addOption("Go to the toilet", "go-to-toilet");
nodes.push(node);
var node = new Node({ id:"go-to-toilet" });
node.addText("You sit on the toilet and start to poo.");
node.addText("You do lots of squidgy, smelly poos and fill the toilet.");
node.addText("Oh no! There is no toilet paper.");
node.addOption("Don't wipe", "dont-wipe");
node.addOption("Shout out and ask for some paper", "shout-out");
nodes.push(node);
var node = new Node({ id:"dont-wipe" });
node.addText("You don't wipe - you don't care if you smell.");
node.addText("You lose 30 health points.");
node.addText("You go back into the lounge and settle down with your sister.");
node.addOption("Go back into the lounge", "watch-friends");
node.action = "player.injure(30);";
nodes.push(node);
var node = new Node({ id:"shout-out" });
node.addText("\"Help, I need bum-wipe!\", you shout.");
node.addText("No one comes to help.");
node.addOption("Don't wipe", "dont-wipe");
nodes.push(node);
var node = new Node({ id:"do-a-fart" });
node.addText("You lean on one bum-cheeck and let a ripper go.");
node.addText("You wake up the girl - it's your sister!");
node.addText("You both laugh and hold your noses - it was a stinker!");
node.addOption("Watch Friends with your sister", "watch-friends");
nodes.push(node);
var node = new Node({ id:"watch-friends" });
node.addText("You snuggle up with your sister and enjoy a marathon session of Friends.");
node.addText("I wonder what adventures you will have tomorrow.");
nodes.push(node);
var node = new Node({ id:"turn-netflix-off-2" });
node.addText("You decide to leave your sister to sleep, she looks so cute.");
node.addText("You turn Netflix off and head back up to bed.");
node.addText("You get into bed and feel warm and snuggly. You drift off to sleep and dream of further adventures.");
nodes.push(node);
var node = new Node({ id:"run-to-bedroom" });
node.addText("You run back up to your bedroom and get back into bed.");
node.addText("you can hear your sister downstairs, she is really cross but she eventually settles down and goes quiet.");
node.addText("The noise from the telly is still bothering you and you can't get back to sleep.");
node.addOption("Go into Mummy and Daddy's room", "mummy-and-daddy-room");
node.addOption("Go downstairs and investigate", "go-downstairs");
nodes.push(node);
//
|
let priceRanges = [
{ label: '$', tooltip: 'Inexpensive', minPerPerson: 0, maxPerPerson: 10},
{ label: '$$', tooltip: 'Moderate', minPerPerson: 10, maxPerPerson: 25},
{ label: '$$$', tooltip: 'expensive', minPerPerson: 25, maxPerPerson: 35}
];
let restaurants = [
{ averagePerPerson: 5 }
]
|
(function(window,document,undefined) {
// only run this code if there is a google map component on the page
var gMapEl = document.querySelector('.js-google-map');
if(typeof gMapEl === 'undefined'){
return;
}
// after the api is loaded this function is called
window.initMap = function() {
// get the maps data
// this could be replaced with an api
var rawData = googleMapData[0];
// var initMapData = {
// scrollwheel: false
// }
// var mapData = Object.assign({}, rawData.map, initMapData);
// *** Create the Map *** //
// map defaults
var mapData = rawData.map;
mapData.scrollwheel = false;
// create map Data by combining the rawData with the defaults
var map = new google.maps.Map(gMapEl, mapData);
var markers = [];
// *** Add Markers with popups *** //
rawData.markers.forEach(function(d,i){
var markerData = {};
markerData.infoWindow = d.infoWindow;
markerData.position = d.position;
markerData.label = d.label;
markerData.map = map;
// var markerData = Object.assign({map},d);
var marker = new google.maps.Marker(markerData);
var template = [
'<section class="info-window">',
'<h3 class="info-window__name">'+ markerData.infoWindow.name +'</h3>',
'<div class="ma__info-window__address">' + markerData.infoWindow.address + '</div>',
'</section>'
].join(" ");
var infoWindow = new google.maps.InfoWindow({
content: template
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
marker.showInfo = function() {
infoWindow.open(map, marker);
}
markers.push(marker);
});
}
// load Google's api
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyDNDQepPfh0XsEXA0_S2UOFR852dlr1WUg&callback=initMap";
document.getElementsByTagName('head')[0].appendChild(script);
}(window,document));
|
const db = require('../config/db');
Locations = new Object();
Locations.benson = [];
Locations.case_ = [];
Locations.engineering = [];
Locations.gemmill = [];
Locations.koelbel = [];
Locations.norlin = [];
Locations.wise = [];
Locations.bensonCount = 0;
Locations.case_Count = 0;
Locations.engineeringCount = 0;
Locations.gemmillCount = 0;
Locations.koelbelCount = 0;
Locations.norinCount = 0;
Locations.wiseCount = 0;
Locations.getGroupInfo = function(callback) {
console.log('Locations.getGroupInfo');
Locations.benson = [];
Locations.case_ = [];
Locations.engineering = [];
Locations.gemmill = [];
Locations.koelbel = [];
Locations.norlin = [];
Locations.wise = [];
db.query('SELECT * FROM groups ORDER BY location', null, function(err, result) {
if (err){
return callback(err,this);
}if(result.rows.length > 0){
for (var i = 0; i < result.rows.length; i++) {
if(result.rows[i]['location'] == 1){
Locations.benson.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.bensonCount += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 2){
Locations.case_.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.case_Count += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 3){
Locations.engineering.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.engineeringCount += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 4){
Locations.gemmill.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.gemmillCount += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 5){
Locations.koelbel.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.koelbelCount += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 6){
Locations.norlin.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.norlinCount += result.rows[i]['members'].length;
}
if(result.rows[i]['location'] == 7){
Locations.wise.push(result.rows[i]['members'].length + ' people studying ' + result.rows[i]['subject'] );
Locations.wiseCount += result.rows[i]['members'].length;
}
}
}
return callback(false, Locations);
});
};
Locations.getGroupId = function(subject, id,callback) {
console.log('Locations.getGroupId');
var currentGroup = false
db.query('SELECT * FROM groups WHERE subject=$1 AND location=$2',[subject, id], function(err, result) {
if (err) {
console.log(err);
return callback(currentGroup,null);
} if (result.rows.length>0) {
currentGroup = true;
var group_id = result.rows[0]['group_id'];
console.log('group_id: ',group_id);
return callback(currentGroup, group_id);
}
else{
return callback(currentGroup, null);
}
});
};
module.exports = Locations;
|
define('main', ['application', 'blockUI','rd.controls.BasicSelector','rd.controls.Selector',
'rd.controls.FoldSelector','rd.containers.Accordion','rd.controls.Input','rd.controls.Table',
'rd.controls.TabSelect','rd.controls.ComboSelect','rd.controls.TabSelector','rd.controls.Graph',
'rd.containers.Tab','rd.controls.Map','rd.controls.Scroller','rd.containers.Panel'],
function(application) {
// 创建一个RDK的应用
var app = angular.module("rdk_app", ['rd.core', 'blockUI','rd.controls.BasicSelector','rd.controls.Selector',
'rd.controls.FoldSelector','rd.containers.Accordion','rd.controls.Input','rd.controls.Table',
'rd.controls.TabSelect','rd.controls.ComboSelect','rd.controls.TabSelector','rd.controls.Graph',
'rd.containers.Tab','rd.controls.Map','rd.controls.Scroller','rd.containers.Panel']);
app.config(['blockUIConfig', function(blockUIConfig) {
// blockUI默认只要有ajax请求在进行,就会自动启动,阻止页面响应鼠标事件
// 使用下面代码可以阻止自动模式,启用手动模式
// blockUIConfig.autoBlock=false
// 然后在需要阻止页面相应鼠标事件的时候,使用下面代码
// blockUI.start();
// 在需要继续相应页面相应鼠标事件的时候,使用下面代码
// blockUI.stop();
// blockUI的详细用法参考 https://github.com/McNull/angular-block-ui
blockUIConfig.template = '<div class="block-ui-message-container">\
<img src="images/loding.gif" />\
</div>';
}]);
// 创建一个控制器
app.controller('rdk_ctrl', ['$scope', 'DataSourceService', 'blockUI','EventService','EventTypes',
function(scope, DSService, blockUI,EventService,EventTypes) {
application.initDataSourceService(DSService);
/************************ 应用的代码逻辑开始 ************************/
scope.accordions=[
{
rowDescriptor: ['最高气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[11, 13, 15, 18, 15, 12, 10]
]
},
{
rowDescriptor: ['最低气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[1, 4, 6, 4, 9, 6, 3]
]
}
];
scope.scrollerData=[
{
rowDescriptor: ['最高气温', '最低气温','平均气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[11, 13, 15, 18, 15, 12, 10],
[1, 4, 6, 4, 9, 6, 3],
[6,8.5,10.5,11,12,9,6.5]
],
id:'scroller_graph0'
},
{
rowDescriptor: ['最高气温', '最低气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[12, 14, 16, 19, 16, 13, 11],
[1, 4, 6, 4, 9, 6, 3],
],
id:'scroller_graph1'
}
];
//
scope.multipleData=[
{
rowDescriptor: ['最高气温', '最低气温','平均气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[11, 13, 15, 18, 15, 12, 10],
[1, 4, 6, 4, 9, 6, 3],
[6,8.5,10.5,11,12,9,6.5]
],
id:'multiple_graph0'
},
{
rowDescriptor: ['最高气温', '最低气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[12, 14, 16, 19, 16, 13, 11],
[1, 4, 6, 4, 9, 6, 3],
],
id:'multiple_graph1'
}
];
scope.panelData={
rowDescriptor: ['最高气温', '最低气温','平均气温'],
header: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
data: [
[11, 13, 15, 18, 15, 12, 10],
[1, 4, 6, 4, 9, 6, 3],
[6,8.5,10.5,11,12,9,6.5]
]
};
var ids=['accordion_0','accordion_1','combo_graph','tab1_graph','tab2_graph',
'panel_graph','scroller_graph0','scroller_graph1','multiple_graph0','multiple_graph1'];
for(var i=0;i<ids.length;i++){
EventService.register(ids[i],'click',function(event,data){
console.log(data);
scope.name=data.name;
scope.series=data.seriesName;
scope.temperature=data.value;
});
}
/************************ 应用的代码逻辑结束 ************************/
}]);
/********************************************************************
应用如果将代码写在此处,可能会导致双向绑定失效
需要手工调用 scope.$apply() 函数
若非有特别的需要,否则请不要将代码放在这个区域
********************************************************************/
});
/********************************************************************
这个区域不要添加任何代码
********************************************************************/
|
const TestCollectionsJson={
"collections": [
{
"extent": {
"vertical": {
"vrs": "VERTCS[\"WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PARAMETER[\"Vertical_Shift\",0.0],PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]],AXIS[\"Up\",UP]",
"name": "name",
"interval": [
[
"850"
],
[
"850"
]
]
},
"spatial": {
"crs": "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]",
"bbox": [
-180,
-90,
180,
90
],
"name": "name"
},
"temporal": {
"trs": "TIMECRS[\"DateTime\",TDATUM[\"Gregorian Calendar\"],CS[TemporalDateTime,1],AXIS[\"Time (T)\",future]",
"name": "name",
"interval": [
[
"2020-11-12T12:15Z,2020-11-12T12:30Z,2020-11-12T12:45Z"
],
[
"2020-11-12T12:15Z,2020-11-12T12:30Z,2020-11-12T12:45Z"
]
]
}
},
"parameter_names": {
"key": "{}"
},
"keywords": [
"keywords",
"keywords"
],
"crs": [
"crs",
"crs"
],
"output_formats": [
"CoverageJSON",
"GeoJSON",
"IWXXM",
"GRIB"
],
"description": "Last 24 hours Metar observations",
"links": [
{
"href": "https://wlocalhost:8080/service/description.html",
"hreflang": "en",
"rel": "service-doc",
"type": "text/html",
"title": ""
},
{
"href": "https://localhost:8080/service/licence.html",
"hreflang": "en",
"rel": "licence",
"type": "text/html",
"title": ""
},
{
"href": "https://localhost:8080/service/terms-and-conditions.html",
"hreflang": "en",
"rel": "restrictions",
"type": "text/html",
"title": ""
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/",
"hreflang": "en",
"rel": "collection",
"type": "collection",
"title": "Collection"
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/position",
"hreflang": "en",
"rel": "data",
"type": "position",
"title": "Position"
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/area",
"hreflang": "en",
"rel": "data",
"type": "area",
"title": "Area"
}
],
"id": "Metar data",
"title": "Metar observations",
"data_queries": "{}"
},
{
"extent": {
"vertical": {
"vrs": "VERTCS[\"WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PARAMETER[\"Vertical_Shift\",0.0],PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]],AXIS[\"Up\",UP]",
"name": "name",
"interval": [
[
"850"
],
[
"850"
]
]
},
"spatial": {
"crs": "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]",
"bbox": [
-180,
-90,
180,
90
],
"name": "name"
},
"temporal": {
"trs": "TIMECRS[\"DateTime\",TDATUM[\"Gregorian Calendar\"],CS[TemporalDateTime,1],AXIS[\"Time (T)\",future]",
"name": "name",
"interval": [
[
"2020-11-12T12:15Z,2020-11-12T12:30Z,2020-11-12T12:45Z"
],
[
"2020-11-12T12:15Z,2020-11-12T12:30Z,2020-11-12T12:45Z"
]
]
}
},
"parameter_names": {
"key": "{}"
},
"keywords": [
"keywords",
"keywords"
],
"crs": [
"crs",
"crs"
],
"output_formats": [
"CoverageJSON",
"GeoJSON",
"IWXXM",
"GRIB"
],
"description": "Last 24 hours Metar observations",
"links": [
{
"href": "https://wlocalhost:8080/service/description.html",
"hreflang": "en",
"rel": "service-doc",
"type": "text/html",
"title": ""
},
{
"href": "https://localhost:8080/service/licence.html",
"hreflang": "en",
"rel": "licence",
"type": "text/html",
"title": ""
},
{
"href": "https://localhost:8080/service/terms-and-conditions.html",
"hreflang": "en",
"rel": "restrictions",
"type": "text/html",
"title": ""
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/",
"hreflang": "en",
"rel": "collection",
"type": "collection",
"title": "Collection"
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/position",
"hreflang": "en",
"rel": "data",
"type": "position",
"title": "Position"
},
{
"href": "http://localhost:8080/edr/collections/the_collection_id/area",
"hreflang": "en",
"rel": "data",
"type": "area",
"title": "Area"
}
],
"id": "Metar data",
"title": "Metar observations",
"data_queries": "{}"
}
],
"links": [
{
"href": "http://localhost:8080/edr/collections",
"hreflang": "en",
"rel": "self",
"type": "application/yaml"
},
{
"href": "http://localhost:8080/edr/collections?f=html",
"hreflang": "en",
"rel": "alternate",
"type": "text/html"
},
{
"href": "http://localhost:8080/edr/collections?f=xml",
"hreflang": "en",
"rel": "alternate",
"type": "application/xml"
}
]
};
module.exports = TestCollectionsJson;
|
const URI = require('uri-js');
const getUrls = (content) => {
// get all urls in the content string
const host = content
.split('htt')
.filter(string => string[0] === 'p')
.map(element => {
const [string] = element.split(' ');
// just for case
if (!string) {
return null;
}
// if not correct url
if (!string.startsWith('p://') && !string.startsWith('ps://')) {
return null;
}
return `htt${string}`;
})
.filter(url => url);
return host;
};
const convertToHost = url => {
if (!url.includes('http')) {
return url;
}
return URI.parse(url).host;
};
const isEqual = (host1, host2) => {
return URI.equal(host1, host2);
};
module.exports = {
getUrls,
convertToHost,
isEqual,
};
|
// Arcanoid type game by kamilczerwinski22
/// VARIABLES
// Make canvas
const cvs = document.getElementById("arcanoid_canvas");
const cvs_ctx = cvs.getContext("2d");
cvs_ctx.lineWidth = 2;
// Ending screen div`s
const game_over = document.getElementById("game_over");
const game_win = document.getElementById("win");
const restart = document.getElementById("play_again");
const game_score = document.getElementById("score");
const game_start = document.getElementById("start");
const game_progress = document.getElementById("game_progress");
// Variables and consts
const PADDLE_WIDTH = 100;
const PADDLE_BOTTOM_MARGIN = 50;
const PADDLE_HEIGHT = 5;
const BALL_RADIUS = 8;
const SCORE_INC = 10;
const WIN_LVL = 3;
let ball_speed = 6;
let current_game_lifes = 3;
let current_game_score = 0;
let current_game_level = 1;
let hot_brick_counter = 0;
let game_in_progress = false;
let game_is_over = false;
// PADDLE AND BALL
// Make paddle
const paddle = {
pos_x: cvs.width/2 - PADDLE_WIDTH/2, // starting x
pos_y: cvs.height - PADDLE_HEIGHT - PADDLE_BOTTOM_MARGIN, // starting y
height: PADDLE_HEIGHT,
width: PADDLE_WIDTH,
delta_x: 7 // amout of pixels paddle will move when pressed
}
const ball = {
pos_x: cvs.width/2, // starting x
pos_y: paddle.pos_y - BALL_RADIUS, // ball starts at paddle
speed: ball_speed,
radius: BALL_RADIUS,
delta_x: -(ball_speed * 0.75), // ball movement x (x++ - to the right; x-- - to the left)
delta_y: -(ball_speed * 0.75), // ball movement y (y++ - to the bottom; y-- to the top)
}
const brick = {
width : 60,
height : 25,
fill_color : "#98b000",
stroke_color : "#212F3D"
}
const hot_brick = {
width : 60,
height : 25,
fill_color : "#A21D00",
stroke_color : "#4A0D00"
}
const obstacle = {
fill_color : "#3E0303",
stroke_color : "#212F3D"
}
// GAME LOGIC
// Drawing
function draw_paddle(){
cvs_ctx.fillStyle = "#212F3D";
cvs_ctx.fillRect(paddle.pos_x, paddle.pos_y, paddle.width, paddle.height);
cvs_ctx.strokeStyle = "#7B241C";
cvs_ctx.strokeRect(paddle.pos_x, paddle.pos_y, paddle.width, paddle.height);
}
function draw_ball(){
cvs_ctx.beginPath(); // used to draw circle, creating new path, which is not subpath (so everything after `cvs_ctx.` will be applied to ball, not full canvas)
cvs_ctx.arc(ball.pos_x, ball.pos_y, ball.radius, 0, Math.PI * 2);
cvs_ctx.fillStyle = "#98b000";
cvs_ctx.fill();
cvs_ctx.strokeStyle = "#212F3D";
cvs_ctx.stroke();
cvs_ctx.closePath(); // closing current arc
}
function draw_bricks(lvl){
for (let idx = 0; idx < lvl.length; idx += 1){
let current_brick = lvl[idx];
if (current_brick.status){
cvs_ctx.fillStyle = brick.fill_color;
cvs_ctx.fillRect(current_brick.pos_x, current_brick.pos_y, brick.width, brick.height);
cvs_ctx.strokeStyle = brick.stroke_color;
cvs_ctx.strokeRect(current_brick.pos_x, current_brick.pos_y, brick.width, brick.height);
}
}
}
function draw_hot_bricks(lvl){
for (let idx = 0; idx < lvl.length; idx += 1){
let current_brick = lvl[idx];
if (current_brick.status){
cvs_ctx.fillStyle = hot_brick.fill_color;
cvs_ctx.fillRect(current_brick.pos_x, current_brick.pos_y, hot_brick.width, hot_brick.height);
cvs_ctx.strokeStyle = hot_brick.stroke_color;
cvs_ctx.strokeRect(current_brick.pos_x, current_brick.pos_y, hot_brick.width, hot_brick.height);
}
}
}
// Paddle and ball movement
let left_arrow = false;
let right_arrow = false;
// pressing key
document.addEventListener("keydown", function(event){
if (event.code == "ArrowLeft"){
left_arrow = true;
} else if (event.code == "ArrowRight"){
right_arrow = true;
}
});
// releasingkey
document.addEventListener("keyup", function(event){
if (event.code == "ArrowLeft"){
left_arrow = false;
} else if (event.code == "ArrowRight"){
right_arrow = false;
}
});
// moving paddle
function move_paddle(){
if(right_arrow && paddle.pos_x + paddle.width < cvs.width){ // don't let paddle go beyond canvas
paddle.pos_x += paddle.delta_x;
}else if(left_arrow && paddle.pos_x > 0){
paddle.pos_x -= paddle.delta_x;
}
}
// moving ball
function move_ball(){
ball.pos_x += ball.delta_x;
ball.pos_y += ball.delta_y;
}
// Collisions
function wall_collision(){
// right wall
if (ball.pos_x + ball.radius > cvs.width){
ball.delta_x = -ball.delta_x;
}
// top wall
if (ball.pos_y - ball.radius < 0){
ball.delta_y = -ball.delta_y;
}
// left wall
if (ball.pos_x - ball.radius < 0){
ball.delta_x = -ball.delta_x;
}
// bottom wall (lose)
if (ball.pos_y + ball.radius > cvs.height){
current_game_lifes--;
reset_positions();
}
}
function paddle_collision(){
if ((ball.pos_y + ball.radius > paddle.pos_y) &&
(ball.pos_x > paddle.pos_x) &&
(ball.pos_x < paddle.pos_x + paddle.width &&
(paddle.pos_y < paddle.pos_y + paddle.height))){
let collide_point = (ball.pos_x - (paddle.pos_x + paddle.width/2)) / (paddle.width/2); // collide point in respect of paddle middle point and normalized to [-1, 1]
let angle = collide_point * (Math.PI/2.4); // [-1, 1] * 60 degrees
ball.delta_x = ball.speed * Math.sin(angle); // new delta_x depending on angle and speed
ball.delta_y = - ball.speed * Math.cos(angle); // new delta_y depending on angle and speed. Multiply by -1 for correct delta_y.
// It needs to be <0 for going up, because top of the canvas is 0, and bottom is >0 (opposite to classic way)
}
}
function brick_collision(lvl){
for (let idx = 0; idx < lvl.length; idx += 1){
let current_brick = lvl[idx];
// if brick isn't broke make hitbox, otherwise go through it
// console.log(current_brick.status);
if (current_brick.status){
// check hitbox
if (ball.pos_x + ball.radius > current_brick.pos_x && // brick left side - ball right side
ball.pos_x - ball.radius < current_brick.pos_x + brick.width && // brick right side - ball left side
ball.pos_y + ball.radius > current_brick.pos_y && // brick top side - ball bottom side
ball.pos_y - ball.radius < current_brick.pos_y + brick.height){ // brick bottom side - ball top side
current_brick.status = false;
ball.delta_y = -ball.delta_y;
current_game_score += SCORE_INC;
}
}
}
}
function hot_brick_collision(lvl){
for (let idx = 0; idx < lvl.length; idx += 1){
let current_brick = lvl[idx];
// if brick isn't broke make hitbox, otherwise go through it
// console.log(current_brick.status);
if (current_brick.status){
// check hitbox
if (ball.pos_x + ball.radius > current_brick.pos_x && // brick left side - ball right side
ball.pos_x - ball.radius < current_brick.pos_x + hot_brick.width && // brick right side - ball left side
ball.pos_y + ball.radius > current_brick.pos_y && // brick top side - ball bottom side
ball.pos_y - ball.radius < current_brick.pos_y + hot_brick.height){ // brick bottom side - ball top side
current_brick.status = false;
ball.delta_y = -ball.delta_y;
current_game_score -= current_game_level * SCORE_INC;
}
}
}
}
function reset_positions(){
// start position same as before
paddle.pos_x = cvs.width/2 - PADDLE_WIDTH/2;
paddle.pos_y = cvs.height - PADDLE_HEIGHT - PADDLE_BOTTOM_MARGIN;
ball.pos_x = cvs.width/2;
ball.pos_y = paddle.pos_y - BALL_RADIUS;
ball.delta_y = -(ball.speed * 0.75); // going up same as before
ball.delta_x = Math.floor(Math.random() * ((ball.speed * 0.75) - (-ball.speed * 0.75) + 1)) + (-ball.speed * 0.75); // random between [-3, 3]
if (!check_lose() && !check_win()){
game_in_progress = false;
game_progress.style.display = "block";
}
}
//........................................................................
//.LLLL.......EEEEEEEEEEEEEVV....VVVVVVEEEEEEEEEE.ELLL........SSSSSSS.....
//.LLLL.......EEEEEEEEEEEEEVV....VVVV.VEEEEEEEEEE.ELLL.......LSSSSSSSS....
//.LLLL.......EEEEEEEEEEEEEVV....VVVV.VEEEEEEEEEE.ELLL.......LSSSSSSSSS...
//.LLLL.......EEEE.......EEVVV..VVVV..VEEE........ELLL......LLSSS..SSSS...
//.LLLL.......EEEE........EVVV..VVVV..VEEE........ELLL......LLSSS.........
//.LLLL.......EEEEEEEEEE..EVVV..VVVV..VEEEEEEEEE..ELLL.......LSSSSSS......
//.LLLL.......EEEEEEEEEE..EVVVVVVVV...VEEEEEEEEE..ELLL........SSSSSSSSS...
//.LLLL.......EEEEEEEEEE...VVVVVVVV...VEEEEEEEEE..ELLL..........SSSSSSS...
//.LLLL.......EEEE.........VVVVVVVV...VEEE........ELLL.............SSSSS..
//.LLLL.......EEEE.........VVVVVVV....VEEE........ELLL......LLSS....SSSS..
//.LLLLLLLLLL.EEEEEEEEEEE...VVVVVV....VEEEEEEEEEE.ELLLLLLLLLLLSSSSSSSSSS..
//.LLLLLLLLLL.EEEEEEEEEEE...VVVVVV....VEEEEEEEEEE.ELLLLLLLLL.LSSSSSSSSS...
//.LLLLLLLLLL.EEEEEEEEEEE...VVVVV.....VEEEEEEEEEE.ELLLLLLLLL..SSSSSSSS....
//........................................................................
// BRICKS
// Create array of arrays, where each internal array is current level bricks (lvl 1 == index 0)
let brick_lvls = create_bricks_levels();
// console.log(brick_lvls);
function create_bricks_levels(){
let levels = [lvl_1(), lvl_2(), lvl_3(), lvl_4()];
function lvl_1(){
// 14 bricks, 7 per row; brick = 60px * 7; spaces between = 22.5px * 6; sum = 600px (canvas length)
let current_lvl = []; // main array for all current lvl brick
for (let row = 0; row < 2; row += 1){
for (let col = 0; col < 7; col += 1){
let current_brick = {
pos_x: col * (brick.width + 22.5) + 22.5, // pos in col
pos_y: row * (brick.height + 20) + 20 + 40, // pos in row
status: true // starting status true, as brick is not broken
}
current_lvl.push(current_brick);
}
}
return current_lvl;
}
function lvl_2(){
let current_lvl = []; // main array for all current lvl brick
for (let row = 0; row < 3; row += 1){
for (let col = 0; col < 7; col += 1){
let current_brick = {
pos_x: col * (brick.width + 22.5) + 22.5, // pos in col
pos_y: row * (brick.height + 20) + 20 + 40, // pos in row
status: true // starting status true, as brick is not broken
}
current_lvl.push(current_brick);
}
}
return current_lvl;
}
function lvl_3(){
let current_lvl = []; // main array for all current lvl brick
for (let row = 0; row < 3; row += 1){
for (let col = 0; col < 7; col += 1){
let current_brick = {
pos_x: col * (brick.width + 22.5) + 22.5, // pos in col
pos_y: row * (brick.height + 20) + 20 + 40, // pos in row
status: true // starting status true, as brick is not broken
}
current_lvl.push(current_brick);
}
}
current_lvl.splice(0, 1); // delete bricks at the corner
current_lvl.splice(5, 1);
return current_lvl;
}
function lvl_4(){
let current_lvl = []; // main array for all current lvl brick
for (let row = 1; row < 4; row += 1){
for (let col = 0; col < 7; col += 1){
let current_brick = {
pos_x: col * (brick.width + 22.5) + 22.5, // pos in col
pos_y: row * (brick.height + 20) + 20 + 40, // pos in row
status: true // starting status true, as brick is not broken
}
current_lvl.push(current_brick);
}
}
return current_lvl;
}
return levels;
}
// Create array of arrays, where each internal array is current level hot spots (lvl 1 == index 0). If you hit hotspot, you lose points. Hit it 3 times and you lose a life
let hot_bricks_lvls = create_hot_bricks_levels();
// console.log(hot_bricks_lvls);
function create_hot_bricks_levels(){
let levels = [[], [], lvl_3(), lvl_4()];
function lvl_3(){
let current_lvl = []; // main array for all current lvl brick
let hot_brick_1 = {
pos_x: 22.5,
pos_y: 60,
status: true
}
let hot_brick_2 = {
pos_x: 517.5,
pos_y: 60,
status: true
}
current_lvl.push(hot_brick_1);
current_lvl.push(hot_brick_2);
return current_lvl;
}
function lvl_4(){
let current_lvl = []; // main array for all current lvl brick
for (let row = 0; row < 1; row += 1){
for (let col = 0; col < 7; col += 1){
let current_brick = {
pos_x: col * (brick.width + 22.5) + 22.5, // pos in col
pos_y: row * (brick.height + 20) + 20 + 40, // pos in row
status: true // starting status true, as brick is not broken
}
current_lvl.push(current_brick);
}
}
return current_lvl;
}
return levels;
}
// /LEVELS
function level_checker(lvl){
let lvl_done = true;
// check if all the bricks are broken
for (let idx = 0; idx < lvl.length; idx += 1){
lvl_done = lvl_done && !lvl[idx].status;
}
// if all bricks are destroyed, lvl up
if (lvl_done) {
ball.speed += 1.5;
current_game_level += 1;
hot_brick_counter = 0;
reset_positions();
}
}
// GAME STATS
function show_game_score(score, lifes, level){
let text_score = "SCORE: " + score;
let text_live = "LIFES: " + lifes;
let text_lvl = "LEVEL: " + level;
cvs_ctx.font = "18px Arial";
cvs_ctx.fillStyle = "#ffffff";
cvs_ctx.strokeStyle = "#000000";
cvs_ctx.lineWidth = 2.5;
// Stroke first
// score
cvs_ctx.textAlign = "left";
cvs_ctx.strokeText(text_score, 15, 25);
cvs_ctx.fillText(text_score, 15, 25);
// level
cvs_ctx.textAlign = "center";
cvs_ctx.strokeText(text_lvl, cvs.width/2, 25);
cvs_ctx.fillText(text_lvl, cvs.width/2, 25);
// lives
cvs_ctx.textAlign = "right";
cvs_ctx.strokeText(text_live, cvs.width - 15, 25);
cvs_ctx.fillText(text_live, cvs.width - 15, 25);
}
//
function check_win(){
return (current_game_level == WIN_LVL + 1);
}
function check_lose(){
return (current_game_lifes <= 0);
}
// Make final score
function make_final_score(){
document.getElementById("score").innerHTML = "Score: " + current_game_score;
game_score.style.display = "block";
}
// Play again
function play_again(){
restart.style.display = "block"; // show play again
restart.addEventListener("click", function(){
location.reload(); // reload the page if user wants to play again
});
}
// Darken the canvas
function darken_canvas(){
cvs_ctx.globalAlpha = 0.85;
cvs_ctx.fillStyle = "#2b2b2b";
cvs_ctx.fillRect(0, 0, cvs.width, cvs.height);
}
// Game win and over
function show_game_results(status){
// darken the canvas
darken_canvas();
game_is_over = true;
status.style.display = "block"; // show the div
make_final_score();
play_again();
}
// Game start
function start_game_screen(){
darken_canvas();
game_start.addEventListener("click", function(){
game_start.style.display = "none"; // don't show the div anymore
game_progress.style.display = "block";
main_loop();
})
}
// MAIN GAME LOOP
function game_draw(){
draw_paddle();
show_game_score(current_game_score, current_game_lifes, current_game_level);
draw_ball();
draw_bricks(brick_lvls[current_game_level - 1]); // draw current lvl bricks (lvl 1 = index 0)
draw_hot_bricks(hot_bricks_lvls[current_game_level - 1]); // -||-
// draw_obstacles(obstacles_lvls[current_game_level - 1]); // -||-
// console.log("detla y = " + ball.delta_y);
// console.log("detla x = " + ball.delta_x);
}
function game_update(){
move_ball();
move_paddle();
paddle_collision();
// obstacle_collision(obstacles_lvls[current_game_level - 1]); // -||-
brick_collision(brick_lvls[current_game_level - 1]); // use current lvl bricks (lvl 1 = index 0)
hot_brick_collision(hot_bricks_lvls[current_game_level - 1]); // -||-
wall_collision();
level_checker(brick_lvls[current_game_level - 1]);
}
function main_loop(){
// game lose
// clear canvas each loop
cvs_ctx.clearRect(0, 0, cvs.width, cvs.height);
game_draw();
if (game_in_progress){
game_update();
} else {
darken_canvas();
document.addEventListener("keydown", function(event){
// console.log(event);
if (event.code == "Enter"){
game_in_progress = true;
game_progress.style.display = "none";
}
});
}
let req_id = requestAnimationFrame(main_loop); // better than interval
if (check_lose()){
cancelAnimationFrame(req_id);
show_game_results(game_over);
}
// game win
if (check_win()){
cancelAnimationFrame(req_id);
show_game_results(game_win);
}
}
start_game_screen();
// setInterval(main_loop, 100);
|
/* eslint-disable new-cap, prefer-destructuring */
const router = require('express').Router({ strict: true });
const logger = require('winston').loggers.get('scheduler-logger');
// const TopicManager = require('../models/redis/topics-manager');
// const mysql = require('mysql');
const startConnection = require('../utils').startConnection;
router.get('/', async (req, res) => {
/* eslint-disable no-unused-vars */
logger.info(`GET /api/v1/projects`);
const query = 'SELECT * FROM Projects';
const connection = await startConnection();
connection.query(query, (error, results, fields) => {
if (error) {
logger.error(error);
res.status(500).json({ success: false, error });
return;
}
res.json({ success: true, projects: results });
});
});
router.post('/', (req, res) => {
/* eslint-disable camelcase */
// TopicManager.store(req.body.topics).then(
// num_topics => {
// res.json({ success: true, num_topics });
// },
// err => {
// res.json({
// success: false,
// error: {
// name: err.name,
// message: err.message,
// },
// });
// },
// );
res.json({ success: true });
});
module.exports = router;
|
import mailgun from "mailgun-js";
const transporter = mailgun({
apiKey: process.env.MAILER_API_KEY,
domain: process.env.MAILER_DOMAIN
});
export default async (email, url) => {
const data = {
from: "<support@instagram-clone.ml>",
to: email,
subject: "Instagram-clone",
html: `<a href="${url}">${url}</a>`
};
transporter.messages().send(data, function(error, body) {
if (error) console.log(error);
console.log(body);
});
};
|
import React from "react";
import { withFirebase } from "../Firebase";
import { compose } from "recompose";
//import { withRouter } from "react-router-dom";
import { AuthUserContext } from "../Session";
//import "./searchbar.scss";
class Popover extends React.Component {
render() {
return (
<div className="modal-wrapper-postarticle1">
<div className="dialogstyle devedit-form">
<button
className=" dialogCloseButonStayle"
onClick={this.props.closePopup}
>
X
</button>
<div className="diglog_inner">
<h4>{this.props.children}</h4>
</div>
</div>
</div>
);
}
}
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
showPopup: false
};
}
togglePopup = () => {
this.setState({
showPopup: !this.state.showPopup
});
};
render() {
return (
<AuthUserContext.Consumer>
{authUser => (
<div className="mainsearch">
<div className="popover__wrapper">
<div className="input-icons">
<i className="fa fa-search"></i>
<input
className="input-field"
type="search"
placeholder="search..."
onChange={this.props.handleInput}
/>
</div>
<div className="popover__content">
<div className="popover__message">
Search by
<p>Title</p>
<p>Tags</p>
<p>Description</p>
</div>
</div>
</div>
</div>
)}
</AuthUserContext.Consumer>
);
}
}
export default compose(withFirebase)(SearchBar);
|
//Base
import React, { Component } from 'react';
//Component
import ContactForm from '../../../molecules/ContactForm';
class MapOrganism extends Component {
render() {
return (
<ContactForm
linktype="btn"
submitText="Submit"
headinglevel = "2"
titleStyle = "article-heading"
title = "Talk To Me"
icon = "far fa-hand-point-right"
/>
)
}
}
export default MapOrganism;
|
/* eslint-disable no-console */
import { call, put } from 'redux-saga/effects';
import { NotificationError, NotificationSuccess } from '../../utils/notification';
import api from '../../services/api';
import ToolsActions from '../ducks/tools';
export function* getToolsRequest({ searchText, searchTagOnly }) {
try {
let endpoint = '/tools';
if (searchText) {
if (searchTagOnly) {
endpoint = `${endpoint}?tags_like=${searchText}`;
} else {
endpoint = `${endpoint}?q=${searchText}`;
}
}
const { data } = yield call(api.get, endpoint);
yield put(ToolsActions.getToolsSuccess(data));
} catch (error) {
console.error(error);
NotificationError('An unexpected error has occurred!');
yield put(ToolsActions.getToolsFailure());
}
}
export function* addToolRequest({
title, link, description, tags,
}) {
try {
const { data } = yield call(api.post, '/tools', {
title,
link,
description,
tags,
});
yield put(ToolsActions.addToolSuccess(data));
NotificationSuccess('Tool registered successfully!');
} catch (error) {
console.error(error);
NotificationError('An unexpected error has occurred!');
yield put(ToolsActions.getToolsFailure());
}
}
export function* deleteToolRequest({ id }) {
try {
yield call(api.delete, `/tools/${id}`);
yield put(ToolsActions.deleteToolSuccess(id));
NotificationSuccess('Tool removed successfully!');
} catch (error) {
console.error(error);
NotificationError('An unexpected error has occurred!');
yield put(ToolsActions.getToolsFailure());
}
}
|
const jwt = require('jsonwebtoken')
const User = require('../models/user')
const Address = require('../models/address')
const {module: config} = require('../config')
const Order = require('../models/order')
exports.addUser = async (newUser) =>
{
const user = new User(newUser)
try
{
return await user.save()
}
catch(error)
{
return console.log(error.message)
}
}
exports.addAddress = async (address, user) =>
{
const addressInfo =
{
address,
owner: user._id
}
const newAddress = new Address(addressInfo)
try
{
return await newAddress.save()
}
catch(error)
{
return console.log(error.message)
}
}
exports.getUsers = async () =>
{
try
{
const users = await User.find({})
const userList = users.map((user) =>
{
const {name, usermane, email, phone, isAdmin, isActive} = user
return {name, usermane, email, phone, isAdmin, isActive}
})
return userList
}
catch(error)
{
return console.log(error.message)
}
}
exports.getAddressList = async (user) =>
{
try
{
const addresses = await Address.find({owner: user._id})
if(addresses.length > 0)
{
const userAddresses = addresses.map((element) =>
{
return {address: element.address, option: element.option}
})
return userAddresses
}
else
{
return 'You do not have addresses saved.'
}
}
catch(error)
{
return console.log(error.message)
}
}
exports.userLogIn = async (user) =>
{
try
{
const token = jwt.sign({_id: user._id.toString()}, config.SECRET_PASS)
user.token = token
await user.save()
return token
}
catch(error)
{
return console.log(error.message)
}
}
exports.userLogOut = async (user) =>
{
try
{
user.token = ''
return await user.save()
}
catch(error)
{
return console.log(error.message)
}
}
exports.suspendUser = async (user, order) =>
{
try
{
user.isActive = !user.isActive
user.token = ''
const hasOpenOrder = await Order.findOne({owner: user._id})
if(hasOpenOrder)
{
hasOpenOrder.state = 'cancelled'
await hasOpenOrder.save()
}
const success = await user.save()
const message = user.isActive ? 'unsuspended.' : 'suspended.'
return {success, message}
}
catch(error)
{
return console.log(error.message)
}
}
|
import React, { Component } from "react";
import mapboxgl from "mapbox-gl";
import "./Map.css";
import { MAPBOX_TOKEN } from "./config";
mapboxgl.accessToken = MAPBOX_TOKEN;
export class Map extends Component {
componentDidMount() {
new mapboxgl.Map({
container: this.mapContainer,
style: "mapbox://styles/mapbox/streets-v11",
center: [this.props.lng, this.props.lat],
zoom: this.props.zoom || 8,
});
}
// componentDidUpdate() {
// let map = new mapboxgl.Map({
// container: this.mapContainer,
// style: "mapbox://styles/mapbox/light-v10",
// center: [this.props.lng || 0, this.props.lat || 0],
// zoom: this.props.zoom || 8,
// });
// if (this.props.markers) {
// // console.log(this.props.markers);
// for (let marker of this.props.markers) {
// new mapboxgl.Marker().setLngLat([marker[0], marker[1]]).addTo(map);
// }
// }
// }
render() {
return (
<div>
<div ref={(el) => (this.mapContainer = el)} className="mapContainer" />
</div>
);
}
}
export default Map;
|
'use strict';
const { MongoClient } = require('mongodb');
// Uri for the Docker setup
//const mongoUri = `mongodb://mongodb:27017/novoresume`;
//console.log("entered db connection");
// Uri for the localhost setup
const mongoUri = `mongodb://localhost:27017/novoresume`;
//mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false
const mongoClient = new MongoClient(mongoUri, { useUnifiedTopology: true });
mongoClient.connect();
const mongodb = mongoClient.db();
const collection = mongodb.collection('users');
// Find some documents
collection.find({}).toArray(function(err, docs) {
//assert.equal(err, null);
//console.log("Found the following records");
//console.log(docs)
//callback(docs);
});
//mongodb.collections('users').then( data => console.log(data));
module.exports = mongodb;
|
// @flow
import { hylo } from "static-land-recursion-schemes/lib/schemes";
import type { ExprF, Expr } from "./expression-ast";
import {
Plus, Times, Paren, Num, exprFunctor, prj
} from "./expression-ast";
const evalAlg = expression => {
const ex = prj(expression);
return (
ex instanceof Plus ? ex.left + ex.right
: ex instanceof Times ? ex.left * ex.right
: ex instanceof Paren ? ex.contents
: /* ex is a Num */ ex.value);
};
const factorialCoalg =
x => x instanceof Num ? x
: x === 1 ? new Num(1)
: /* otherwise */ new Times(new Num(x), x - 1);
function factorial(x: number) : number {
return hylo(exprFunctor, evalAlg, factorialCoalg, x);
}
console.log(factorial(4));
const fibonacciCoalg = x =>
x <= 2 ? new Num(1) : new Plus(x - 1, x - 2);
function fibonacci(x: number) : number {
return hylo(exprFunctor, evalAlg, fibonacciCoalg, x);
}
console.log([5, 6, 7, 8].map(fibonacci));
function recursiveFibonacci(x: number) : number {
return x <= 2 ?
1 :
recursiveFibonacci(x - 1) + recursiveFibonacci(x - 2);
}
console.log(recursiveFibonacci(4));
|
/*
*
* SignUpForm
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { Field, reduxForm } from 'redux-form/immutable';
import { submitSignupUser } from 'containers/App/actions';
import makeSelectSignUpForm from './selectors';
import messages from './messages';
const renderField = ({ id, input, label, type, meta: { touched, error, warning } }) => (
<div>
<label htmlFor={id}>{label}</label>
<div>
<input id={id} {...input} placeholder={label} type={type} />
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
</div>
);
renderField.propTypes = {
id: PropTypes.string.isRequired,
input: PropTypes.object.isRequired,
label: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
meta: PropTypes.object.isRequired,
};
export class SignUpForm extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<FormattedMessage {...messages.header} />
<Field
name="name"
type="text"
id="name"
component={renderField} label="Name"
/>
<Field
name="password"
type="text"
id="password"
component={renderField} label="Password"
/>
<button type="submit">Sign Up</button>
</form>
);
}
}
SignUpForm.propTypes = {
handleSubmit: PropTypes.func,
};
const mapStateToProps = createStructuredSelector({
SignUpForm: makeSelectSignUpForm(),
});
function mapDispatchToProps(dispatch) {
return {
onSubmit: (userInfo) => dispatch(submitSignupUser(userInfo)),
};
}
const SingupReduxForm = reduxForm({
form: 'signUpForm', // a unique identifier for this form
})(SignUpForm);
export default connect(mapStateToProps, mapDispatchToProps)(SingupReduxForm);
|
var xSelector = function (selector) {
return {
selector: selector,
locateStrategy: "xpath",
};
};
module.exports = {
// can be string or function
url: "",
elements: {
// shorthand, specifies selector
playSpace: ".css-1842iib.e6jvphj1",
aboutSpace: ".css-5hcn91.em284gv0",
forPlayersSpace: "#for-players",
forCreatorsSpace: "#for-creators",
downloadAppSpace: "#download-app",
loginTab: ".css-6msegl.e6jvphj4",
registerTab: ".css-18t3gjt.e6jvphj4",
loginGoogleButton: "#google-icon",
loginFacebookButton: ".css-mps5rv",
loginEmailButton: ".css-1tvacqz.eqfwhcm1",
registerEmailButton: ".css-1tvacqz.eqfwhcm1"
// full
// myTextInput: {
// selector: 'input[type=text]',
// locateStrategy: 'css selector'
// }
},
commands: [
{
},
],
};
|
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
$(document).ready(function(){
$('button.inputWordBtn').click(function(event){
event.preventDefault();
var inputWord = $('input.inputWord').val();
var word = inputWord;
var wordSec = inputWord;
var wordPartial; //This is what the next letter is added to
var length = inputWord.length;
var finalPermutations = []; //All created combos
var intermediatePermutations = []; //This holds the partial words that are added to
var tempPermutations = []; //This holds the newly created combos that will take the place of intermediatePermutations
var uniquePermutations = [];
for(var timesPrimLoop = length; timesPrimLoop > 0; timesPrimLoop --){
var primaryLetter = word.charAt(0);
finalPermutations.push(primaryLetter);
intermediatePermutations.push(primaryLetter);
for(var timesSecLoop = length - 1; timesSecLoop > 0; timesSecLoop --){
var secLetter = wordSec.charAt(1);
wordSec = (wordSec.substr(1) + wordSec.slice(0,1));
for(var addLetterToWord = intermediatePermutations.length; addLetterToWord > 0; addLetterToWord --){
wordPartial = intermediatePermutations[addLetterToWord - 1];
for(var secLetterInsertPositionLoop = wordPartial.length +1; secLetterInsertPositionLoop > 0; secLetterInsertPositionLoop --){
var tempCombo = wordPartial.splice(secLetterInsertPositionLoop -1, 0, secLetter);
tempPermutations.push(tempCombo);
finalPermutations.push(tempCombo);
}
}
intermediatePermutations = tempPermutations;
tempPermutations = []
}
intermediatePermutations = [];
word = (word.substr(1) + word.slice(0,1));
wordSec = word;
}
//gets unigue values
var finalLength = finalPermutations.length;
for(i = 0; i < finalLength; i++){
var permutation = finalPermutations[i];
if(uniquePermutations.indexOf(permutation) === -1){
uniquePermutations.push(permutation);
}
}
var uniqueLength = uniquePermutations.length;
$('.result').show();
$('span.inputWord').text(inputWord);
$('span.permutationLength').text(uniqueLength);
$('.finalPermutations').text(uniquePermutations);
$('input.inputWord').val('');
});
});
//recursion?
var words = [];
var arr = [];
var fn = function(rem) {
console.log(rem);
if(rem.length === 0) {
arr.push(rem[i]);
words.push(arr.join(''));
arr = [];
}
for(var i = 0; i < rem.length; i++) {
arr.push(rem[i]);
fn(arr, rem.slice(i + 1))
}
}
|
const removeDom = (e) => {
if (e) {
e.parentNode.removeChild(e);
}
}
module.exports = {
removeDom
};
|
import React from "react";
function Formacao({ obj }) {
return (
<div className="sidebar">
<h3>Educação</h3>
{obj.map((obj) => (
<div key={obj.id} className="lista-de-formacao">
<li >
<h4>{obj.instituicao}</h4>
<p>{obj.curso}</p>
<p>{obj.situacao}</p>
</li>
</div>
))}
</div>
);
}
export default Formacao;
|
module.exports = function(app, io) {
var chat = new Chat(io);
// io.on('connection', function(socket) {
// console.log('User ' + socket.id + ' has connected!');
//
// socket.on('disconnect', function() {
// console.log('user ' + socket.id + ' has disconnected!');
// });
//
// socket.on('message', function(msg) {
// console.log('user ' + socket.id + ' has sent a message ' + msg + '!')
// });
// });
}
|
/*!
* jQuery FitTitle Plugin
* Original author: Eric Wafford
*
* Licensed under the MIT license
*/
;(function ( $ ) {
$.fn.twFitTitle = function( options ) {
// Setup options
var pluginName = 'twFitTitle',
settings = $.extend(
{
'minFontSize' : Number.NEGATIVE_INFINITY,
'maxFontSize' : Number.POSITIVE_INFINITY
}, options);
return this.each( function() {
if ( !$.data( this, 'plugin_' + pluginName ) ) {
$.data(this, 'plugin_' + pluginName);
var $this = $( this ),
$parent = $this.parent();
var resizeText = function() {
$this.css({
'display' : 'inline-block',
'white-space' : 'nowrap',
'font-size' : Math.round( Math.max( Math.min( $parent.width() * parseInt( $this.css( 'font-size' ) ) / $this.width(), parseFloat( settings.maxFontSize ) ), parseFloat( settings.minFontSize ) ) )
});
};
resizeText();
$( window ).on( 'resize.fittext orientationchange.fittext', resizeText );
}
});
};
})( jQuery );
|
import React from "react";
import { Container, Jumbotron, Row } from "react-bootstrap";
const About = () => {
return (
<>
<div className="container">
<div className="divSpacing"></div>
<Row>
<Jumbotron>
<Container>
<div>
<p>
Skupina entuzijasta koji slobodno vrijeme provode u
restauriranju uređaja u ispravno stanje. Vodi nas želja za
učenjem i usavršavanjem u područjima elektronike,
elektrotehnike, mehanike, mehatronike i sličnim granama.
</p>
<p>
Organiziramo radionice i seminare u područjima informacijskih
tehnologija.
</p>
<p>Kontakt broj: 01/666-6666</p>
<p>Mail adresa: info@quickfix.com</p>
</div>
</Container>
</Jumbotron>
</Row>
<Row>
<iframe
src="http://maps.google.com/maps?q=45.814277, 15.977370&z=15&output=embed"
width="100%"
height="600px"
class="container center-block"
title="Map"
></iframe>
</Row>
</div>
<div className="divSpacing"></div>
</>
);
};
export default About;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
Alert,
Button,
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import MapView from './MapView.js';
import { NativeEventEmitter, NativeModules } from 'react-native';
const { ObjectCAPI, SwiftAPI } = NativeModules;
export default class App extends Component {
constructor() {
super();
this.objectCEmitter = new NativeEventEmitter(ObjectCAPI)
this.state = {
lbs: {
lat: 30,
lng: 104,
}
}
}
componentDidMount() {
this.subscription = this.objectCEmitter.addListener('LBSChanged',
lbs => {
console.log(lbs);
this.setState({
lbs: { lat: lbs.lat, lng: lbs.lng }
});
}
)
}
componentWillUnmount() {
this.subscription.remove();//不要的时候记得清除
}
render() {
const region = {
latitude: 30.67,
longitude: 104.06,
latitudeDelta: 0.1,
longitudeDelta: 0.1,
};
// return <MapView
// style={{ flex: 1 }}
// region={region}
// zoomEnabled={false}
// onRegionChange={event => console.log('拖动地图', event)}
// />
return (
<View style={styles.container}>
<Button title="获取Swift常量"
onPress={() => {
SwiftAPI.add(1, 0, (...result) => console.log(result));
}}
/>
<Button title="获取Swift常量"
onPress={() => {
console.log(SwiftAPI.x, SwiftAPI.y, SwiftAPI.z)
}}
/>
<Button title="模拟LBS位置切换"
onPress={() => {
setInterval(() => ObjectCAPI.mockChangeLBS(
this.state.lbs.lat + Math.random(),
this.state.lbs.lng + Math.random())
, 1000);
}}
/>
<Text>lbsInfo: lat: {this.state.lbs.lat}, lng: {this.state.lbs.lng}</Text>
<Button title="访问ObjectCAPI"
onPress={() => {
ObjectCAPI.nativeFunc('this is a message from js.');
}}
/>
<Button title="访问ObjectCAPI通过callback获得结果"
onPress={() => {
ObjectCAPI.resultFromNativeByCallback(1, 2, (err, result) => {
console.log('err: ' + err + ' result: ' + typeof (result) + JSON.stringify(result))
this.setState({
result,
})
});
}}
/>
<Button title="访问ObjectCAPI通过Promise获得结果async/await"
onPress={async () => {
try {
const result = await ObjectCAPI.resultFromNativeByPromise(1, 5)
console.log('result: ' + typeof (result) + JSON.stringify(result))
this.setState({
result,
})
} catch (error) {
console.log('error: ', error);
this.setState({
error: error.code
})
};
}}
/>
<Button title="访问ObjectCAPI通过Promise获得结果"
onPress={() => {
ObjectCAPI.resultFromNativeByPromise(1, 0)
.then(result => {
console.log('result: ' + typeof (result) + JSON.stringify(result))
this.setState({
result,
})
})
.catch(error => {
console.log('error: ', error);
this.setState({
error: error.code
})
});
}}
/>
<Button title="访问ObjectCAPI常量"
onPress={() => {
Alert.alert('name: ' + ObjectCAPI.name + " age: " + ObjectCAPI.age);
}}
/>
<Text>result from native: {this.state.result}</Text>
<Text>error: {this.state.error}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
|
function PlaySound(melody) {
var snd = new Audio(melody);
snd.play();
}
|
import React from 'react';
import {DataTable} from 'primereact/components/datatable/DataTable';
import {Column} from 'primereact/components/column/Column';
const PhoneBook = (props) => {
return(
<div>
<DataTable value={props.phoneBook}>
<Column field="name" header="Full Name" />
<Column field="mobileNumber" header="Mobile Number" />
</DataTable>
</div>
)
}
export default PhoneBook;
|
var singlePlayerPausedState = {
create: function(){
drawPatternBG("#000088", "#944d94");
buttonTint = 0xeeaffe;
music.stop();
var titleLabel = game.add.text(80, 80, getText("SinglePlayerPaused", 0),getStyle("title"));
var buttonStyle = getStyle("button_regular");
btnResume = game.add.button(game.world.width / 2, (game.world.height / 2) - 60, 'big_button', goBack, this, 1, 2, 0);
btnResume.anchor.setTo(0.5, 0.5);
btnResume.tint = buttonTint;
lblResume = game.add.text(game.world.width / 2, (game.world.height / 2) - 60, getText("SinglePlayerPaused",1) , buttonStyle);
lblResume.anchor.setTo(0.5, 0.5);
btnNewGame = game.add.button(game.world.width / 2, game.world.height / 2, 'big_button', function (){show('changeBgSt')}, this, 1, 2, 0);
btnNewGame.anchor.setTo(0.5, 0.5);
btnNewGame.tint = buttonTint;
lblNewGame = game.add.text(game.world.width / 2, game.world.height / 2, getText("Settings",2), buttonStyle);
lblNewGame.anchor.setTo(0.5, 0.5);
btnSettings = game.add.button(game.world.width / 2, (game.world.height / 2) + 60, 'big_button', function(){show('soundMenu')}, this, 1, 2, 0);
btnSettings.anchor.setTo(0.5, 0.5);
btnSettings.tint = buttonTint;
lblSettings = game.add.text(game.world.width / 2, (game.world.height / 2) + 60, getText("Settings",3), buttonStyle);
lblSettings.anchor.setTo(0.5, 0.5);
btnCredits = game.add.button(game.world.width / 2, (game.world.height / 2) + 120, 'big_button', function(){show('controls')}, this, 1, 2, 0);
btnCredits.anchor.setTo(0.5, 0.5);
btnCredits.tint = buttonTint;
lblCredits = game.add.text(game.world.width / 2, (game.world.height / 2) + 120, getText("Settings",4), buttonStyle);
lblCredits.anchor.setTo(0.5, 0.5);
btnQuit = game.add.button(game.world.width / 2, (game.world.height / 2) + 180, 'big_button', function(){show('menu')}, this, 1, 2, 0);
btnQuit.anchor.setTo(0.5, 0.5);
btnQuit.tint = buttonTint;
lblQuit = game.add.text(game.world.width / 2, (game.world.height / 2) + 180, getText("Gameover",1), buttonStyle);
lblQuit.anchor.setTo(0.5, 0.5);
}
};
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
class Support extends Component {
constructor (props) {
super(props)
this.state = {
first: '',
last: '',
email: '',
question: '',
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange (e) {
const target = e.target
const value = target.value
const name = target.name
this.setState({
[name]: value
})
}
handleSubmit (e) {
e.preventDefault()
const { first, last, email } = this.state
console.log('submitting', first, last, email)
}
render () {
return (
<div className="support">
<h1>Support details</h1>
<h2>Need some help?</h2>
<p>Start with our <Link to='/settings/faq'>FAQ</Link>. Most, if not all, commonly asked question should be addressed there.</p>
<h2>Contact us. We usually respond within 24 – 48 hours.</h2>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="first"
value={this.state.first}
placeholder="First name"
onChange={this.handleChange}
/>
<input
type="text"
name="last"
value={this.state.last}
placeholder="Last name"
onChange={this.handleChange}
/>
<input
type="text"
name="email"
value={this.state.email}
placeholder="Email"
onChange={this.handleChange}
/>
<textarea
value={this.state.question}
name="question"
placeholder="Enter your question here."
onChange={this.handleChange}
/>
<button>Submit</button>
</form>
</div>
)
}
}
export default Support
|
$(document).ready(function () {
function superhero() {
var queryURL = "https://superheroapi.com/api.php/10164273699360858/search/batman"
$.ajax({
url: queryURL,
method: "GET",
}).then(function (response) {
console.log(response)
console.log(response.results[0].image.url)
console.log(response.results[0].biography)
var image = document.getElementById("characterimage")
var imageURL = response.results[0].image.url
var name = response.results[0].name
//Variable need for the Character Details
var description = response.results[0].biography
$('#characterimage').append("<img src=" +imageURL+"></img>")
$('#characterName').append("<h1>"+name+"</h1>")
$('#characterDetails').append("<p>"+description+"</p>")
$('#characterDetails').append("<p>"+appearance+"</p>")
});
}
superhero()
})
//VARIABLES
//Number entered by user.
//4 is just a placeholder until we create the input and get the value.
var userNumber = 4;
//FUNCTIONS
//Function to get the superhero from the superhero api by id
//Must be between 1 and 731
function getSuperHero(id) {
var queryURL = "https://superheroapi.com/api.php/10164273699360858/" + id;
$.ajax({
url: queryURL,
method: "GET",
}).then(function (response) {
console.log(response);
var name = response.name;
getBooks(name);
});
}
//Function to get books and comics related to the superhero from goodreads api
function getBooks(name) {
var queryURL = "https://v1.nocodeapi.com/shelboc/gr/dIBrccmAYkfwiAFv/search?q=" + name;
$.ajax({
url: queryURL,
method: "GET",
}).then(function (response) {
console.log(response);
var books = response.results;
});
}
// FUNCTION CALLS
getSuperHero(userNumber);
// EVENT LISTENERS
|
const userSignup = document.getElementById('signup');
const signupBtn = document.getElementById('register');
const api = 'https://deferral-banka-app-1.herokuapp.com/api/v1/auth/signup';
const firstNameError = document.getElementById('firstNameError');
const lastNameError = document.getElementById('lastNameError');
const emailError = document.getElementById('emailError');
const passwordError = document.getElementById('passwordError');
const otherError = document.getElementById('otherErrorContainer');
userSignup.addEventListener('submit', (event) => {
event.preventDefault();
signupBtn.value = 'loading..';
const firstname = document.getElementById('firstname').value;
const lastname = document.getElementById('lastname').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
fetch(api, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstname,
lastname,
email,
password,
}),
})
.then(res => res.json())
.then((response) => {
if (response.status === 400) {
firstNameError.innerHTML = response.error.firstname;
firstNameError.style.display = 'block';
lastNameError.innerHTML = response.error.lastname;
lastNameError.style.display = 'block';
emailError.innerHTML = response.error.email;
emailError.style.display = 'block';
passwordError.innerHTML = response.error.password;
passwordError.style.display = 'block';
signupBtn.value = 'REGISTER';
setTimeout(() => {
window.location.reload();
}, 4000);
}
if (response.status === 201) {
window.sessionStorage.banka_token = JSON.stringify(response.data.token);
window.location = './dashboard.html';
localStorage.setItem('userInfo', JSON.stringify(response.data));
}
if (response.status === 409) {
otherError.innerHTML = response.error;
signupBtn.value = 'REGISTER';
setTimeout(() => {
window.location.reload();
}, 4000);
}
})
.catch((error) => {
otherError.innerHTML = 'Failed to connect, please try again!' || error.message;
setTimeout(() => {
window.location.reload();
}, 4000);
});
});
|
import event from './event'
import map from 'ramda/src/map'
import toPairs from 'ramda/src/toPairs'
export const formEvent = (ev) => (el, values) => {
const mockEvent = {
target: map(([name, value]) => ({ value, name }), toPairs(values)),
preventDefault: () => {}
}
return event(ev, mockEvent)(el)
}
/**
* Calls `reset` of a form
*
* @usage
* reset(form, { name: 'Morgenbesser' })
*/
export const reset = formEvent('reset')
/**
* Calls `submit` of a form
*
* @usage
* submit(form, { name: 'Nagel' })
*/
export const submit = formEvent('submit')
|
import React, { useCallback, useEffect, useRef, useState } from "react"
import { LayoutChangeEvent, StyleSheet, View, TouchableWithoutFeedback, Animated, Text } from "react-native"
import Icon from "react-native-vector-icons/MaterialCommunityIcons"
import { colors } from "../theme"
export const PLAYER_HEIGHT = 50
const POLLING_PERIOD_SECONDS = 10
const OFFSET = 150
const StickyPlayer = ({ barHeight }) => {
const [shown, setShown] = useState(false)
const [isSaved, setIsSaved] = useState(false)
const [isPlaying, setIsPlaying] = useState(false)
const [trackWidth, setTrackWidth] = useState(0)
// const { getTrackData, trackState } = useCurrentPlayingTrack()
// const {
// title,
// artist,
// currentProgressPct,
// intervalAmountPct,
// isPlaying,
// isSaved,
// id,
// } = trackState
useEffect(() => {
const timeout = setTimeout(() => {
setShown(true)
}, 1000)
return () => {
clearTimeout(timeout)
}
}, [])
// const timingTo = currentProgressPct + intervalAmountPct
// const progressValue = concat(animatedProgress, "%")
// const titleIsTooLong = (`${title} • ` + artist).length > 44
// const validTrackWidth = trackWidth > 0
const handlePlay = useCallback(async () => {
try {
} catch (e) {
}
}, [])
const handlePause = useCallback(async () => {
try {
} catch (e) {
}
}, [])
const nextTrack = useCallback(async () => {
}, [])
const handleSave = useCallback(async () => {
}, [])
const handleRemove = useCallback(async () => {
}, [])
// if (title.length === 0) return null
return (
<View
style={[
styles.bar,
{
bottom: barHeight,
opacity: shown ? 1 : 0,
},
]}>
<Animated.View
style={[
styles.progressBar,
{
width: 20,
},
]}
/>
<View style={styles.progressBarBackground} />
{/* <Animated.View
style={[styles.iconContainer, { transform: [{ scale: heartScale }] }]}> */}
<View
style={[styles.iconContainer]}>
<TouchableWithoutFeedback
onPress={isSaved ? handleRemove : handleSave}
onPressIn={() =>
Animated.timing(heartScale, UIHelper.heartScaleAnim.in).start()
}
onPressOut={() =>
Animated.timing(heartScale, UIHelper.heartScaleAnim.out).start()
}>
<Icon
name={isSaved ? "heart" : "heart-outline"}
size={24}
style={[
styles.heartIcon,
{
color: isSaved ? colors.green : colors.white,
},
]}
/>
</TouchableWithoutFeedback>
</View>
{/* </Animated.View> */}
<Text style={[
styles.title]}>
{`${'title'} • `}
</Text>
<Text style={[
styles.artist]}>
{`${'artist'} • `}
</Text>
{/* <Animated.Text
onLayout={captureTitleWidth}
style={[
styles.title,
{
transform: [{ translateX }],
},
]}>
{`${title} • `}
</Animated.Text>
<Animated.Text
onLayout={captureTotalWidth}
style={[
styles.artist,
{
transform: [{ translateX }],
},
]}>
{artist}
</Animated.Text>
{titleIsTooLong && (
<>
<Animated.Text
style={[
styles.title,
{
left: OFFSET,
transform: [{ translateX }],
},
]}>
{`${title} • `}
</Animated.Text>
<Animated.Text
style={[
styles.artist,
{
transform: [{ translateX }],
},
]}>
{artist}
</Animated.Text>
</>
)} */}
<View style={styles.controlsContainer}>
<View style={styles.iconContainer}>
<Icon
onPress={nextTrack}
name="skip-previous"
size={28}
style={styles.playIcon}
/>
</View>
<View style={styles.iconContainer}>
<Icon
onPress={isPlaying ? handlePause : handlePlay}
name={isPlaying ? "pause" : "play"}
size={28}
style={styles.playIcon}
/>
</View>
<View style={styles.iconContainer}>
<Icon
onPress={nextTrack}
name="skip-next"
size={28}
style={styles.playIcon}
/>
</View>
</View>
</View>
)
}
const initialTrackState = {
currentProgressPct: 0,
intervalAmountPct: 0,
title: "",
artist: "",
isPlaying: false,
isSaved: false,
id: "",
}
// const useCurrentPlayingTrack = () => {
// const [trackState, setTrackState] = useState(initialTrackState)
// const isFirstRender = useRef(true)
// const dispatch = useDispatch()
// useEffect(() => {
// const getLastPlayedTrack = async () => {
// const trackData = await SpotifyAsyncStoreService.getTrackData()
// if (trackData) {
// setTrackState(JSON.parse(trackData))
// }
// }
// getLastPlayedTrack()
// }, [])
// const getTrackData = useCallback(async () => {
// try {
// const trackData = await SpotifyApiService.getPlayingTrack()
// if (
// typeof trackData === "object" &&
// "item" in trackData &&
// trackData.item
// ) {
// const [isSaved] = await SpotifyApiService.getSavedStateForTracks(
// trackData.item.id,
// )
// const currentProgressPct =
// (trackData.progress_ms / trackData.item.duration_ms) * 100
// const intervalAmountPct =
// ((POLLING_PERIOD_SECONDS * 1000) / trackData.item.duration_ms) * 100
// if (trackState.currentProgressPct != currentProgressPct) {
// // if track is not paused
// const newState = {
// currentProgressPct,
// intervalAmountPct,
// title: trackData.item.name,
// artist: trackData.item.artists[0].name,
// isPlaying: trackData.is_playing,
// isSaved: isSaved,
// id: trackData.item.id,
// }
// setTrackState(newState)
// await SpotifyAsyncStoreService.putTrackData(
// JSON.stringify({ ...newState, isPlaying: false }),
// )
// }
// } else {
// // paused
// setTrackState((state) => ({
// ...state,
// isPlaying: false,
// }))
// }
// } catch (e) {
// if (SpotifyApiService.sessionIsExpired(e)) {
// dispatch(redoLogin())
// } else {
// console.warn(e)
// }
// }
// }, [trackState.currentProgressPct, dispatch])
// useEffect(() => {
// if (isFirstRender.current) {
// getTrackData()
// isFirstRender.current = false
// }
// const fetchInterval = setInterval(
// getTrackData,
// POLLING_PERIOD_SECONDS * 1000,
// )
// return () => {
// clearInterval(fetchInterval)
// }
// }, [getTrackData, trackState.currentProgressPct, trackState.title, dispatch])
// return { trackState, getTrackData }
// }
const styles = StyleSheet.create({
bar: {
backgroundColor: colors.tabBar,
height: PLAYER_HEIGHT,
width: "100%",
position: "absolute",
zIndex: 1,
borderBottomColor: colors.tabBar,
borderBottomWidth: StyleSheet.hairlineWidth,
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.18,
shadowRadius: 1.0,
elevation: 1,
flexDirection: "row",
alignItems: "center",
},
iconContainer: {
width: PLAYER_HEIGHT,
height: PLAYER_HEIGHT,
justifyContent: "center",
alignItems: "center",
backgroundColor: colors.tabBar,
zIndex: -1,
},
heartIcon: {
right: 2,
bottom: 1,
},
title: {
color: "white",
fontWeight: "bold",
fontSize: 12,
marginLeft: 2,
letterSpacing: 0.4,
zIndex: -2,
},
artist: {
fontWeight: "normal",
fontSize: 11,
color: colors.lightGrey,
zIndex: -2,
},
playIcon: {
color: colors.white,
top: -2,
right: -4,
},
controlsContainer: {
flexDirection: "row",
position: "absolute",
right: 0,
zIndex: -1,
},
progressBar: {
position: "absolute",
top: -2,
backgroundColor: colors.white,
height: 2,
zIndex: 2,
},
progressBarBackground: {
position: "absolute",
top: -2,
backgroundColor: "#3E3E3E",
width: "100%",
height: 3,
},
})
export default StickyPlayer
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
var Jet = function(){
var _jetImageWidth = null;
var _jetImageHeight = null;
var _jetPositionX = null;
var _jetPositionY = null;
var _moveSpeed = null;
var _context = null;
var _imageObj = null;
var obj;
this.initialise = function(context, imageObj, jetWidth, jetHeight, jetPositionX, jetPositionY, jetMoveSpeed)
{
_jetImageWidth = jetWidth;
_jetImageHeight = jetHeight;
_jetPositionX = jetPositionX;
_jetPositionY = jetPositionY;
_moveSpeed = jetMoveSpeed;
_context = context;
_imageObj = imageObj;
};
this.createJet = function()
{
_context.drawImage(_imageObj, _jetPositionX, _jetPositionY, _jetImageWidth, _jetImageHeight);
};
this.moveJet = function(event)
{
if(event.keyCode == 37 && _jetPositionX > 20)
{
_jetPositionX -= _moveSpeed;
obj = _context.getImageData(0, 0, _jetImageWidth, _jetImageHeight);
_context.putImageData(obj, _jetPositionX+_moveSpeed, _jetPositionY);
_context.drawImage(_imageObj, _jetPositionX, _jetPositionY, _jetImageWidth, _jetImageHeight);
}
if(event.keyCode == 39 && _jetPositionX < (window.innerWidth-80))
{
_jetPositionX += _moveSpeed;
obj = _context.getImageData(0, 0, _jetImageWidth, _jetImageHeight);
_context.putImageData(obj, _jetPositionX-_moveSpeed, _jetPositionY);
_context.drawImage(_imageObj, _jetPositionX, _jetPositionY, _jetImageWidth, _jetImageHeight);
}
};
this.shoot = function(event)
{
if(event.keyCode == 32)
{
}
};
};
|
export const cards = [
{
image:
'https://vader.news/__export/1592538255681/sites/gadgets/img/2020/06/19/cabecera-breaking-bad.jpg_1889316708.jpg',
title: 'Seasons',
link: '/seasons',
},
{
image: 'https://i.blogs.es/16e585/breaking-bad/1366_2000.jpg',
title: 'Characters',
link: '/characters',
},
{
image:
'https://cdn.hobbyconsolas.com/sites/navi.axelspringer.es/public/media/image/2020/07/gus-fring-breaking-bad-1995127.jpeg',
title: 'Killers',
link: 'killers',
},
]
|
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/ListA">ListA</Link>
</li>
<li>
<Link to="/ListB">ListB</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/ListA" component={ListA} />
<Route path="/ListB" component={ListB} />
</div>
</Router>
);
const Home = () => (
<div>
<h2>Welcome to List A and List B's homeworld.</h2>
</div>
);
const ListA = ({ match }) => (
<div>
<h2>ListA</h2>
<ul>
<li>
<Link to={`${match.url}/A1`}>1</Link>
</li>
<li>
<Link to={`${match.url}/A2`}>2</Link>
</li>
<li>
<Link to={`${match.url}/A3`}>3</Link>
</li>
</ul>
<Route path={`${match.url}/:ListId`} component={List} />
<Route
exact
path={match.url}
render={() => <h3>Choose a List A Item</h3>}
/>
</div>
);
const ListB = ({ match }) => (
<div>
<h2>ListB</h2>
<ul>
<li>
<Link to={`${match.url}/B1`}>1</Link>
</li>
<li>
<Link to={`${match.url}/B2`}>2</Link>
</li>
<li>
<Link to={`${match.url}/B3`}>3</Link>
</li>
</ul>
<Route path={`${match.url}/:ListId`} component={List} />
<Route
exact
path={match.url}
render={() => <h3>Choose a List B Item</h3>}
/>
</div>
);
const List = ({ match }) => (
<div>
<h3>{match.params.ListId}</h3>
</div>
);
export default BasicExample;
|
console.log("Hello from Javascript");
var dayjs = require('dayjs')
// //import dayjs from 'dayjs' // ES 2015
console.log(dayjs().format());
var equal = require('fast-deep-equal');
// Babel Input: ES2015 arrow function
console.log(equal({foo: 'pig'}, {foo: 'waffle'})); // true
|
var log = function(s) {
document.getElementById('text').innerHTML = '' + s;
}
|
define('app/views/common/sitenav', [
'jquery',
'underscore',
'magix',
'app/util/index'
], function($, _, Magix, Util) {
return Magix.View.extend({tmpl:"<div class=sitenav> <div class=\"sitenav-bd wrap\" bx-name=\"components/sitenav\"></div> </div>", init: function() {
var me = this
me.observeLocation({
path: true
})
},
render: function() {
var me = this
this.data = this.data || {}
me.setView(function () {
me._extendSiteNav()
}).then(function () {
me._refreshSiteNav()
})
},
_extendSiteNav: function () {
var me = this
if (!window.MMSiteNav) {
window.MMSiteNav = {}
}
window.MMSiteNav['afterMainNavRender'] = function () {
$('.login-menu').append([
'<li class="menu menu-account">',
'<div class="menu-hd">',
'<a href="//' + Magix.local('pubHost') + '/myunion.htm">我的联盟</a> ',
'<em class="top-nav-down"></em>',
'</div>',
'<div class="menu-bd">',
'<div class="menu-bd-panel-wrap">',
'<div class="menu-bd-panel">',
'<ul class="platform-list">',
'<li><a href="/manage/selection/list.htm">我的选品库</a></li>',
'<li><a href="/manage/zhaoshang/list.htm">我的招商需求</a></li>',
'<li><a href="//' + Magix.local('pubHost') + '/myunion.htm#!/report/site/site" data-login="true">效果报表</a></li>',
'<li><a href="http://' + Magix.local('wwwHost') + '/account/overview.htm" target="_blank">结算中心</a></li>',
'</ul>',
'</div>',
'</div>',
'</div>',
'</li>',
'<li class="menu menu-backhome">',
'<div class="menu-hd">',
'<a href="/">返回联盟首页</a> ',
'</div>',
'</li>'
].join(''))
$('#J_nav_help').attr('href', 'http://help.alimama.com/#!/u/index')
$('#J_nav_rule').attr('href', 'http://rule.alimama.com/#!/announce/business/announce-list?id=8307063')
me._refreshSiteNav()
}
window.MMSiteNav['afterProductListRender'] = function () {
$('#J_products_selected_pannel').prepend([
'<ul class="menu-info-list">',
'<li>账户ID:<strong>' + Magix.local('memberid') + '</strong></li>',
'<li>账户等级:' + Util.getTkLevel(Magix.local('tkMemberRank')) + '</li>',
'</ul>'
].join(''))
}
},
_refreshSiteNav: function () {
var me = this
var loc = me.location
var pn = loc.path
var $backhome = $('.menu-backhome')
if (pn == '/') {
$backhome.hide()
} else {
$backhome.show()
}
}
})
})
|
export default async function handler(req, res) {
const { shapeId } = req.query;
let sql = `SELECT s.likes FROM tryshape.shapes s WHERE s.shape_id='${shapeId}'`;
const request = await fetch(process.env.NEXT_PUBLIC_DB_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${process.env.NEXT_PUBLIC_DB_AUTHORIZATION}`,
},
body: JSON.stringify({
operation: "sql",
sql: sql,
}),
});
const data = await request.json();
res.status(200).json(data);
}
|
import { X_WINS, O_WINS, TIE } from '../helpers/actionTypes'
import { checkVictory } from '../helpers/resultHelper'
export function checkResult(board) {
if (checkVictory(board, 'X')) {
return {
type: X_WINS
}
} else if (checkVictory(board, 'O')) {
return {
type: O_WINS
}
} else {
const check = board.filter(symbol => symbol === null)
if (check.length === 0) {
return {
type: TIE
}
} else {
return {
type: 'RANDOM'
}
}
}
}
|
import React from "react";
import { Story } from "storybook/assets/styles/common.styles";
import Modal from "@paprika/modal";
import ProgressBar from "../../src";
export default function ProgressBarModal() {
return (
<Story>
<Modal isOpen>
<Modal.Content>
<ProgressBar
header="Preparing your file..."
bodyText="Control attributes are getting updated. This might take more than 15secs."
completed={30}
/>
</Modal.Content>
</Modal>
</Story>
);
}
|
import React from 'react'
import { Link, Redirect} from 'react-router-dom';
class SessionForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
};
this.handleSubmit = this.handleSubmit.bind(this)
}
update(field) {
return e => this.setState({ [field]: e.currentTarget.value})
}
handleSubmit(e) {
e.preventDefault();
const user = Object.assign({}, this.state);
this.props.processForm(user).then(()=> this.props.history.push('/'));
}
render() {
const formType = this.props.formType;
const oppFormType = formType === "Login" ? "signup" : "login"
const errors = this.props.errors.map( error => {
return (
<li>{error}</li>
)
})
return (
<div>
<h2>{formType}</h2>
<Link to={`/${oppFormType}`}> {oppFormType} </Link>
<ul>{errors}</ul>
<form onSubmit={this.handleSubmit}>
<label>
Username:
<input
type="text"
value={this.state.username}
onChange={this.update("username")}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={this.state.password}
onChange={this.update("password")}
/>
</label>
<br />
<button value={formType}> Enter </button>
</form>
</div>
);
}
}
export default SessionForm;
|
import React, { Component } from 'react';
import {Map, Marker, GoogleApiWrapper} from 'google-maps-react';
import Modal from 'react-responsive-modal';
import ImagesAP from './ImagesAP.js';
const map_Key = "AIzaSyAD282YtNT5yIr79A9vtGC-qBC2c0WXUdk";
export class MapContainer extends React.Component {
state = {
zoom: 12,
activeMarker: {markerName:'none'},
animation: null,
open: false,
}
// Animation effect with marker on click
onMarkerClick = (props, marker, e) =>
this.setState({
selectedMarker: props,
activeMarker: marker,
open: true,
});
onMapClicked = (props) => {
if (this.state.showingInfoWindow) {
this.setState({
activeMarker: {markerName:'none'}
})
}
};
onOpenModal = () => {
this.setState({
open: true });
};
onCloseModal = () => {
this.setState({ open: false,
activeMarker: {markerName:'none'}
});
};
render() {
return (
<div>
<Map
aria-label="map"
role="application"
google={this.props.google}
initialCenter={{
lat: 39.1031,
lng: -84.5120
}}
zoom={this.state.zoom}
onClick = {this.onMapClicked}
>
{this.props.places.map((marker) =>
<Marker
key={marker.id}
markerName={marker.name}
name = {marker.name}
position={{ lat: marker.latitude, lng: marker.longitude }}
onClick={this.onMarkerClick}
animation={this.state.activeMarker.markerName === marker.name &&this.props.google.maps.Animation.BOUNCE}
/>
)}
</Map>
<div>
<Modal open={this.state.open} onClose={this.onCloseModal} center tabIndex='0'>
<div><ImagesAP name2={this.state.activeMarker.name}/></div>
</Modal>
</div>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: map_Key
})(MapContainer)
|
var CameraViewer=CameraViewer||{};
var globalviewer = {};
var camera = [];
var leftClickHandler = null;
var leftDownHandler = null;
/**
* [init 地球容器ID]
* @param {[type]} earthId [description]
* @return {[type]} [description]
*/
CameraViewer.init=function(earthId,baseImageryProvider)
{
this.container=this.container||{};//未来保存加载的模型的容器,便于快速访问
this.viewer=this.viewer||{}; //场景对象
this.pickedModels=[]; //保存用户所选择的模型,颜色半透
this.viewer = this.viewer|| {};
//初始化地球
this.viewer = new Freedo.Viewer(earthId,{
animation : false,
baseLayerPicker : false,
fullscreenButton : false,
geocoder : false,
homeButton : false,
infoBox :false,
sceneModePicker : false,
selectionIndicator : false,
timeline : false,
navigationHelpButton : false,
navigationInstructionsInitiallyVisible : false,
selectedImageryProviderViewModel : false,
scene3DOnly : true,
clock : null,
showRenderLoopErrors : false,
automaticallyTrackDataSourceClocks:false,
imageryProvider : baseImageryProvider || this.getTiandituGloble()
});
this.viewer.imageryLayers.addImageryProvider(new FreeDo.WebMapTileServiceImageryProvider({
url : "http://{s}.tianditu.com/cia_w/wmts?service=WMTS&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet={TileMatrixSet}&TileMatrix={TileMatrix}&TileRow={TileRow}&Tilecol={TileCol}&style={style}&format=tiles",
style:"default",
tileMatrixSetID:"w",
maximumLevel:17,
subdomains : ["t7","t6","t5","t4","t3","t2","t1","t0"]
}));
this.viewer._cesiumWidget._creditContainer.style.display = "none";
modelTile = this.viewer.scene.primitives.add(new FreeDo.FreedoPModelset({
url: "./static/model/tanggu_new"
}));
//3D视角
this.viewer.camera.setView({
destination :new FreeDo.Cartesian3(-2302826.1170741096,4394667.942996659,3994924.9447827702),
orientation: {
heading : 0.25211600100558673,
pitch : -1.5707961712222063,
roll : 0
}
});
modelTile.readyPromise.then(function() {
moveModel(modelTile,-80,20,-23,15,0,0,1,1,1);
});
new Compass(this.viewer);
var camera1 = this.viewer.entities.add( {
name : '摄像头1',
position : FreeDo.Cartesian3.fromDegrees(117.65375541701634, 39.02874722501288,1),
label : { //文字标签
text : '南门1',
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量
},
billboard : { //图标
image : "static/page/shigongguanli/camera/img/camera.svg",
width : 50,
height : 50
}
} );
var camera2 = this.viewer.entities.add( {
name : '摄像头2',
position : FreeDo.Cartesian3.fromDegrees(117.65429737156501, 39.02880876433644,-2),
label : { //文字标签
text : '南门2',
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量
},
billboard : { //图标
image : "static/page/shigongguanli/camera/img/camera.svg",
width : 50,
height : 50
}
} );
var camera3 = this.viewer.entities.add( {
name : '摄像头3',
position : FreeDo.Cartesian3.fromDegrees(117.65447907157001, 39.028964593410294,-2),
label : { //文字标签
text : '三门',
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量
},
billboard : { //图标
image : "static/page/shigongguanli/camera/img/camera.svg",
width : 50,
height : 50
}
} );
var camera4 = this.viewer.entities.add( {
name : '摄像头4',
position : FreeDo.Cartesian3.fromDegrees(117.65491829534002, 39.02880064474932,-2),
label : { //文字标签
text : '站厅扶梯口',
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量
},
billboard : { //图标
image : "static/page/shigongguanli/camera/img/camera.svg",
width : 50,
height : 50
}
} );
var camera5 = this.viewer.entities.add( {
name : '摄像头5',
position : FreeDo.Cartesian3.fromDegrees(117.65520604234463, 39.028678589254206,-2),
label : { //文字标签
text : '土体口',
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -18 ) //偏移量
},
billboard : { //图标
image : "static/page/shigongguanli/camera/img/camera.svg",
width : 50,
height : 50
}
} );
camera.push(camera1);
camera.push(camera2);
camera.push(camera3);
camera.push(camera4);
camera.push(camera5);
globalviewer = this.viewer;
}
CameraViewer.getTiandituGloble =function() {
var tg = new Freedo.WebMapTileServiceImageryProvider({
url : "http://{s}.tianditu.com/img_c/wmts?service=WMTS&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet={TileMatrixSet}&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style={style}&format=tiles",
style:"default",
tileMatrixSetID:"c",
tilingScheme:new Freedo.GeographicTilingScheme(),
tileMatrixLabels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"],
maximumLevel:17,
subdomains : ["t0","t1","t2","t3","t4","t5","t6","t7"]
});
return tg;
}
/**
* 左键点击事件
*/
CameraViewer.initLeftClick = function(viewer,callback) {
leftClickHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas);
leftClickHandler.setInputAction(function(movement){
var picked = viewer.scene.pick(movement.position);
callback(picked,movement.position);
/*var pick= new FreeDo.Cartesian2(movement.position.x,movement.position.y);
var cartesian = viewer.camera.pickEllipsoid(pick, viewer.scene.globe.ellipsoid);
var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
var point=[cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];*/
//输出相机位置
/* var cartesian = new FreeDo.Cartesian3(viewer.camera.position.x, viewer.camera.position.y, viewer.camera.position.z)
var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
console.log(cartographic.longitude +","+cartographic.latitude+","+viewer.camera.heading+","+viewer.camera.pitch+","+viewer.camera.roll);*/
//输出点击位置的经纬度
//console.log(point);
}, FreeDo.ScreenSpaceEventType.LEFT_CLICK);
}
//移除原有的监听事件
CameraViewer.removeListener = function(){
leftClickHandler.removeInputAction(FreeDo.ScreenSpaceEventType.LEFT_CLICK);
leftDownHandler.removeInputAction(FreeDo.ScreenSpaceEventType.LEFT_DOWN);
}
CameraViewer.initLeftDown = function(viewer,callback){
leftDownHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas);
leftDownHandler.setInputAction(function(movement){
var picked = viewer.scene.pick(movement.position);
if(picked==null||picked instanceof FreeDo.FreedoPModelFeature){
callback();
}
}, FreeDo.ScreenSpaceEventType.LEFT_DOWN);
}
|
import { Grid } from '@material-ui/core';
import { Forward } from '@material-ui/icons';
import { Fragment } from 'react-is';
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { getQuery } from "../action/query";
import DailyCard from './DailyCard';
import { makeStyles } from '@material-ui/core/styles';
import useWidthSize from '../hooks/useWidthSize';
import { useState, useEffect } from 'react';
import QueryInputBuilder from '../model/QueryInput';
import { requestNames } from '../constants/requestUrls';
import QueryTypeEnum from '../model/QueryTypeEnum';
import { APP_ID, FORECAST_COUNT, LOCATION } from '../constants';
import { prepareForecastList } from '../utils/prepareResponse';
const DailyCards = () => {
const [numberOfCards, setNumberOfCards] = useState(undefined);
const [cardFirstIndex, setCardFirstIndex] = useState(0);
const dispatch = useDispatch();
const unit = useSelector(state => state.ui.unit, shallowEqual);
const dateWeatherInfos = useSelector(state => state.query[requestNames.forecast], shallowEqual);
const widthSize = useWidthSize();
useEffect(() => {
let ftqueryInput = new QueryInputBuilder(requestNames.forecast, QueryTypeEnum.GET)
.withRequestParams({
APPID: APP_ID,
cnt: FORECAST_COUNT,
q: LOCATION,
units: unit
})
.withCallBackPrepare(prepareForecastList)
.withSpin()
.build();
dispatch(getQuery(ftqueryInput));
}, []);
useEffect(() => {
console.log(widthSize);
if (widthSize < 600)
setNumberOfCards(1);
else if (widthSize < 960)
setNumberOfCards(2);
else if (widthSize < 1280)
setNumberOfCards(3);
else if (widthSize < 1920)
setNumberOfCards(4);
else
setNumberOfCards(6);
}, [widthSize]); // Empty array ensures that effect is only run on mount
return <Fragment>
{dateWeatherInfos && <ul className="ulIconGruop" style={cardFirstIndex == 0 ? { justifyContent: "flex-end" } : {}}>
{cardFirstIndex != 0 && <Forward className="rotate180 prevNextIcon" onClick={() => setCardFirstIndex(cardFirstIndex - 1)} />}
{cardFirstIndex + numberOfCards < dateWeatherInfos.length && <Forward className="prevNextIcon" onClick={() => setCardFirstIndex(cardFirstIndex + 1)} />}
</ul>}
<Grid container spacing={0} style={{
padding: 10,
width: '100%'
}}>
{dateWeatherInfos && dateWeatherInfos.slice(cardFirstIndex, cardFirstIndex + numberOfCards).map(dw =>
<Grid style={{ padding: 10 }} item xs={12} sm={6} md={4} lg={3} xl={2}>
<DailyCard weatherInfo={dw} />
</Grid>
)}
</Grid>
</Fragment>
}
export default DailyCards;
|
import { GET_POSTS, UPDATE_DIMENSIONS, GET_POST_BY_ID, GET_COMMENTS_BY_POST_ID, TOGGLE_ADMIN_VIEW, TOGGLE_ADMIN_USER_VIEW, TOGGLE_FILTER, UPDATE_SEARCH,GET_USERS } from '../actions/types'
const initialState = {
posts: [],
users: [],
activePost: {
_id: '',
createur: {
_id: '',
pseudo: ''
},
dateCreation: '',
texte: '',
reactions: [],
signaler: [],
numCommentaires: ''
},
activeCommentaires: {
id: '',
commentaires: []
},
height: window.innerHeight,
width: window.innerWidth,
adminView: false,
adminUserView: false,
filter: {
type: 'date',
directionDate: true,
directionLike: true
},
commentFilter: {
type: 'date',
directionDate: true,
directionLike: true
},
searchValue: ''
}
export default function (state = initialState, action) {
switch (action.type) {
case GET_POSTS:
return {
...state,
posts: action.payload.posts
}
case GET_USERS:
return {
...state,
users: action.payload.users
}
case GET_POST_BY_ID:
return {
...state,
activePost: action.payload.post
}
case GET_COMMENTS_BY_POST_ID:
return {
...state,
activeCommentaires: {
id: action.payload.id,
commentaires: action.payload.commentaires
}
}
case UPDATE_DIMENSIONS:
return {
...state,
height: action.payload.height,
width: action.payload.width
}
case TOGGLE_ADMIN_VIEW:
return {
...state,
adminView: !state.adminView
}
case TOGGLE_ADMIN_USER_VIEW:
return {
...state,
adminUserView: !state.adminUserView
}
case TOGGLE_FILTER:
if (action.payload.comment)
return {
...state,
commentFilter: {
type: action.payload.filter.type,
directionDate: action.payload.filter.directionDate,
directionLike: action.payload.filter.directionLike
}
}
return {
...state,
filter: {
type: action.payload.filter.type,
directionDate: action.payload.filter.directionDate,
directionLike: action.payload.filter.directionLike
}
}
case UPDATE_SEARCH:
return {
...state,
searchValue: action.payload.searchValue
}
default: return state;
}
}
|
import { connect } from 'react-redux';
// TODO: Eventually this will get followed playlists as well
// it's currently gonna get playlists by current user id
|
'use strict';
const crypto = require('crypto'),
parseToken = /^[\w+/]{84}\|(\d+)/,
vowels = 'aeiouy'.split(''),
consonents = 'bcdfghjklmnpqrstvwxz'.split('');
function sanitizeAccount(item) {
item._writable = true;
item._username = item.__username;
delete item.__auth;
return item;
}
function generatePassword(length) {
return (Array.prototype.map.call(crypto.randomBytes(length), function (random, index) {
return ((index % 2 === 0) ?
consonents[random % consonents.length]:
vowels[random % vowels.length]);
}).join(''));
}
module.exports = {
mixins: [require('./base.controller')],
hash: function (login, password) {
return crypto
.createHash('sha512')
.update(login, 'utf8')
.update(password, 'utf8')
.update(this.secret.account, 'utf8')
.digest('base64');
},
getNewPassword: function () {
return generatePassword(6, true);
},
generateToken: function (minutes) {
var token = this.fibers.wait(crypto, 'randomBytes', 63).toString('base64') + '|' + (Math.ceil(Date.now() / 60000) + minutes);
setTimeout(function () {
this.redis.getset(token, '');
}.bind(this), 60000);
return token;
},
getPermissions: function (accountId) {
accountId = this.models.validoid.bind(this)(accountId);
const permissions = {};
this.mongo.get('accounts_permissions').find({__removed: null, __expired: { $gt: Date.now()}, accounts_id: accountId}).wait()
.forEach(function (permission) { permissions[permission.value] = permission.__expired; });
return permissions;
},
renewPermissions: function (accountId) {
accountId = this.models.validoid.bind(this)(accountId);
const keys = this.redis.keys('portal,session,' + accountId + ',*').wait(),
sessions = this.redis.mget(keys);
session.user._permissions = this.getPermissions(accountId);
const sessionString = JSON.stringify(session);
this.fibers.wait(keys.map(function (key) {
return this.redis.setex(key, 604800, sessionString);
}.bind(this)));
},
available: function (email) {
if (this.mongo.get(this.collection).findOne({ __username: email, __removed: null }).wait()) {
throw new this.ClientError('error:availability:accounts');
}
return [email];
},
models: {
validpassword: function (password, args, index) {
if ('string' === typeof password && password.length >= 6) {
return password;
}
throw new this.ClientError('error:validation:password');
},
validtoken: function (token, args, index) {
if (parseToken.test(token) && (((parseToken.exec(token) || [])[1]|0) * 60000) > Date.now()) {
return token;
}
throw new this.ClientError('error:validation:token');
}
},
methods: {
login: function (email, password) {
var user = this.mongo.get('accounts').findOne({
__auth: this.hash(email, password),
__username: email,
__removed: null,
}).wait();
if (!user) { throw new this.ClientError('error:login:accounts'); }
user._gravatar = crypto.createHash('md5').update(user.__username, 'utf8').digest('hex');
user._permissions = this.getPermissions(user._id);
this.xSessionKey = 'portal,session,' + user._id + ',' + this.fibers.wait(crypto, 'randomBytes', 513).toString('base64');
delete user.__auth;
this.redis.setex(this.xSessionKey, 604800, JSON.stringify({user:user, key: this.xSessionKey}));
return [user];
}
},
api: {
session: ['authenticate', function () {
return [this.session.user];
}],
logout: [function () {
this.redis.del(this.session.key);
return [];
}],
token: ['authenticate', function () {
var token = this.fibers.wait(crypto, 'randomBytes', 63).toString('base64') + '|' + Math.ceil(Date.now() / 60000);
this.redis.setex('portal,token,'+ token, 300000, this.sessionKey);
return [token];
}],
find: ['admin', 'adminfind'],
create: [['object'], function (document) {
this.models.validemail.bind(this)(document.email);
var email = this.available(document.email.trim().toLowerCase())[0],
permissionsCollection = this.mongo.get('accounts_permissions'),
password, id, account;
if(typeof document.password1 === 'string') {
if (document.password1.length < 6 || document.password1 !== document.password2) {
throw new this.ClientError('error:validation:password');
}
password = document.password1;
} else {
password = this.getNewPassword();
}
id = document._id = this.mongo.oid();
delete document.password1;
delete document.password2;
document.__username = email;
document.__auth = this.hash(email, password);
document.__permissions = ['read:account:' + id, 'write:account:' + id];
document._created = Date.now();
document._updated = Date.now();
document.email = email;
document.name = (document.name ? ('' + document.name) : '') || email.split('@')[0];
account = this.mongo.get(this.collection).insert(document).wait();
this.fibers.wait(['read:account:' + id, 'write:account:' + id, 'read:account:all', 'write:account:all']
.map(function (permission) {
return permissionsCollection.insert({
accounts_id: id,
value: permission,
__permissions: ['read:account:' + id],
__created: Date.now(),
__updated: Date.now(),
__expired: 32503701600000,
__removed: null
});
}.bind(this)));
this.ses('/accounts/create', {
to: email,
user: account,
link: 'http://' + this.host + '/accounts/login/',
password: password,
});
return [email, password];
}, ['validemail', 'validpassword'], 'login'],
login: [['validemail', 'validpassword'], 'login'],
update: ['authenticate', ['defined'], ['query', 'object'], 'update', function () {
const account = this.mongo.get('accounts').findOne({
_id: this.session.user._id
}).wait();
if(!account) { throw new this.ServerError('Account Not Found. Account: ' + this.session.user._id); }
account._permissions = this.getPermissions(account._id);
account._gravatar = crypto.createHash('md5').update(account.__username, 'utf8').digest('hex');
this.redis.setex(this.session.key, 604800, JSON.stringify({ user: account, key: this.session.key}));
return [account];
}],
resetpasswordemail: [['validemail'], function (email) {
const accounts = this.mongo.get('accounts'),
result = accounts.update({ __username: email, __removed: null, }, { $set: { __token: this.generateToken(24 * 60), }}).wait();
if (result > 0) {
const user = accounts.findOne({ __username: email, __removed: null, }).wait();
this.ses('/accounts/resetpasswordemail', {
to: email,
user: user,
link: 'http://' + this.host + '/resetpassword#token=' + encodeURIComponent(user.__token) + '&email=' + encodeURIComponent(user.__username) + '&action=resetpassword',
});
}
return [];
}],
resetpassword: [['validemail', 'validtoken'], function (email, token) {
const password = this.getNewPassword(),
accounts = this.mongo.get('accounts'),
result = accounts.update({
__username: email,
__token: token,
__removed: null
}, {
$set: {
__token: null,
__auth: this.hash(email, password)
}
}).wait();
if (result > 0) {
const user = accounts.findOne({ __username: email, __auth: this.hash(email, password), __removed: null, }).wait();
this.ses('/accounts/resetpassword', {
to: email,
user: user,
link: 'http://' + this.host + '/',
password: password,
});
return [];
}
throw new this.ClientError('error:validation:token');
}],
changepassword: ['authenticate', ['validemail', 'validpassword', 'validpassword'], function (email, password, changePassword) {
const result = this.mongo.get('accounts').update({
_id: this.session.user._id,
__username: email,
__auth: this.hash(email, password),
__removed: null,
}, {
$set: {
__token: null,
__auth: this.hash(email, changePassword),
}
}).wait();
if (result === 0) { throw new this.ClientError('error:validation:credentials'); }
return [];
}],
changeusernameemail: ['authenticate', ['validemail', 'validpassword', 'validemail'], function (email, password, changeUsername) {
this.available(changeUsername);
const account = this.mongo.get('accounts'),
result = account.update({
_id: this.session.user._id,
__username: email,
__auth: this.hash(email, password),
__removed: null,
}, {
$set: {
__token: this.generateToken(24 * 60) + '|' + changeUsername,
}
}).wait();
if (result === 0) { throw new this.ClientError('error:validation:credentials'); }
const user = account.findOne({ __username: email, __removed: null }).wait();
this.ses('/accounts/changeusername', {
to: changeUsername,
user: user,
link: 'http://' + this.host + '/changeusername#token=' + encodeURIComponent(user.__token)+ '&email=' + encodeURIComponent(user.__username) + '&action=changeusername',
});
return [];
}],
changeusername: [['validemail', 'validpassword', 'validtoken'], function (email, password, token) {
const changeUsername = (/[^\|]+$/.exec(token)||{})[0],
result = this.mongo.get('accounts').update({
__username: email,
__auth: this.hash(email, password),
__token: token,
__removed: null,
}, {
$set: {
__token: null,
__username: changeUsername,
__auth: this.hash(changeUsername, password),
}
}).wait();
if (result === 0) { throw new this.ClientError('error:credentials:accounts'); }
return [];
}]
}
};
|
function entropy(grid, p) {
return grid[p].length;
}
function getBest(grid) {
let best = [];
minEntropy = 1000;
for (let p = 0; p < grid.length; p++) {
const options = grid[p];
if (options.length == 1) {
continue;
}
const e = options.length;
if (e < minEntropy) {
minEntropy = e;
best = [];
}
if (e <= minEntropy) {
best.push(p);
}
}
const i = Math.floor(Math.random() * best.length);
return best[i];
}
function getAny(grid) {
let l = [];
for (let p = 0; p < grid.length; p++) {
const options = grid[p];
if (options.length != 1) {
l.push(p);
}
}
const i = Math.floor(Math.random() * l.length);
return l[i];
}
function weightedChoice(options) {
let sum = 0;
for (const t of options) {
sum += weights[fromNumber[t]];
}
let i = Math.floor(Math.random() * sum);
for (const t of options) {
i -= weights[fromNumber[t]];
if (i < 0) {
return t;
}
}
}
function collapse(grid, p) {
// const i = Math.floor(Math.random() * grid.get(p).length);
// grid.set(p, grid.get(p)[i]);
grid[p] = [weightedChoice(grid[p])];
}
|
/* eslint-disable linebreak-style */
const express = require('express');
const router = express.Router();
const Init = require('../../controllers/init');
router.get('/', Init.info);
router.post('/validate-rule', Init.ruleValidation);
module.exports = router;
|
import BsNavLinkToComponent from 'ember-bootstrap/components/bs-nav/link-to';
import defaultValue from 'ember-bootstrap/utils/default-decorator';
/**
* Extended `{{link-to}}` component for use within Navbars.
*
* @class NavbarLinkTo
* @namespace Components
* @extends Components.NavLinkTo
* @public
*/
export default class NavbarLinkTo extends BsNavLinkToComponent {
/**
* @property collapseNavbar
* @type {Boolean}
* @default true
* @public
*/
@defaultValue
collapseNavbar = true;
/**
* @event onCollapse
* @private
*/
onCollapse() {
}
click() {
if (this.get('collapseNavbar')) {
this.onCollapse();
}
}
}
|
import React from "react";
export class Search extends React.Component {
state = {
search: '',
type: 'all',
}
handleKey = (event) => {
if (event.key === 'Enter') {
this.props.searchMovies(this.state.search, this.state.type);
}
}
handleRadio = (event) => {
this.setState(
() =>
({ type: event.target.value })
,
() => {
this.props.searchMovies(this.state.search, this.state.type);
}
);
}
render() {
return (
<div className="row">
<div className="input-field col s6">
<input
placeholder="Movie"
type="search"
className="validate"
value={this.state.search}
onChange={(e) => this.setState({ search: e.target.value })}
onKeyDown={this.handleKey}
/>
<div className='checkboxes'>
<label>
<input
className="with-gap"
name="group1"
type="radio"
value="all"
onChange={this.handleRadio}
сhecked={this.state.type === "all"}
/>
<span>All</span>
</label>
<label>
<input
className="with-gap"
name="group1"
type="radio"
value="movie"
onChange={this.handleRadio}
сhecked={this.state.type === "movie"}
/>
<span>Movies Only</span>
</label>
<label>
<input
className="with-gap"
name="group1"
type="radio"
value="series"
onChange={this.handleRadio}
сhecked={this.state.type === 'series'}
/>
<span>Series Only</span>
</label>
</div>
<label className="active" htmlFor="first_name2">You find</label>
</div>
</div>
)
}
}
|
import React, { Component } from 'react';
import Navigation from './Navigation';
import Header from './Header';
import Projects from './Projects';
import About from './About';
import Contact from './Contact';
import Footer from './Footer';
import '../style/main.css';
import content from '../content.json';
class Portfolio extends Component {
state = {
language: 'pl',
content: {},
mobile: true,
scrollY: 0
};
getData = (lang = 'pl') => {
const translation = content.filter(element => element.language === lang);
this.setState({ content: translation[0] });
};
checkDevice() {
const deviceWidth = window.innerWidth > 0 ? window.innerWidth : '640';
const deviceHeight = window.innerHeight > 0 ? window.innerHeight : '360';
if (deviceHeight >= 768 && deviceWidth >= 1024) {
this.setState({ mobile: false });
} else {
this.setState({ mobile: true });
}
}
naviHandler = e => {
if (
e.target.className === 'naviBurger' ||
e.target.className === 'naviBurgerSpan' ||
e.target.className.includes('naviListButton')
) {
document.querySelector('.navigation').classList.toggle('active');
}
};
langHandler = e => {
const language = e.target.value;
this.setState({ language });
};
handleScroll = e => {
const scrollY = window.scrollY;
this.setState({ scrollY });
};
componentDidMount() {
this.getData();
this.checkDevice();
window.addEventListener('scroll', this.handleScroll);
}
componentDidUpdate() {
if (this.state.language !== this.state.content.language) {
this.getData(this.state.language);
}
}
render() {
const { language, content, mobile, scrollY } = this.state;
return (
<>
<Navigation
naviHandler={this.naviHandler}
langHandler={this.langHandler}
language={language}
content={content}
scrollY={scrollY}
/>
<Header />
<main>
<Projects content={content} mobile={mobile} />
<About content={content} scrollY={scrollY} mobile={mobile} />
<Contact content={content} language={language} />
</main>
<Footer />
</>
);
}
}
export default Portfolio;
|
import {html} from '../../node_modules/lit-html/lit-html.js';
import {getArticles} from "../api/data.js";
const topicTemplate = (topic) => html`
<a class="article-preview" href="/details/${topic._id}">
<article>
<h3>Topic: <span>${topic.title}</span></h3>
<p>Category: <span>${topic.category}</span></p>
</article>
</a>`;
const catalogTemplate = (topics) => html`
<section id="catalog-page" class="content catalogue">
<h1>All Articles</h1>
${topics.length !== 0 ? topics.map(topicTemplate) : html`<h3 class="no-articles">No articles yet</h3>`}
</section>`;
export async function catalogPage(context) {
const topics = await getArticles();
context.render(catalogTemplate(topics));
}
|
//账号名重复
$.extend($.fn.validatebox.defaults.rules, {
existAccount: {
validator: function (value, param) {
$.ajax({
url: param[0],
type: 'post',
data: {
"name": value
},
success: function (data) {
return data.result
},
fail: function (err, status) {
console.log(err)
}
})
},
message: '已存在用户名'
},
equals: {
validator: function (value, param) {
return value == $(param[0]).val();
},
message: '密码不相同!'
}
});
|
import Swal from "sweetalert2";
const GET_USER_LOGIN = "GET_USER_LOGIN";
const getUserLogin = (data) => {
return {
type: GET_USER_LOGIN,
data,
};
};
const loginAdmin = (formData, history) => async (dispatch) => {
try {
const url = `${process.env.REACT_APP_BACKEND_ENDPOINT}/api/admin/login`;
const options = {
method: "POST",
body: JSON.stringify(formData),
headers: {
"Content-type": "application/json",
},
};
const response = await fetch(url, options);
const result = await response.json();
console.log(result, 'result');
if (response.status === 200) {
Swal.fire({
title: "Login Success",
text: "",
icon: "success",
confirmButtonText: "Success",
});
localStorage.setItem("token", JSON.stringify(result));
dispatch(getUserLogin(result));
history.push("/pageAdmin");
} else if (response.status === 403) {
Swal.fire({
title: "Email or Password Incorrect!",
text: "",
icon: "error",
confirmButtonText: "Back",
});
}
} catch (error) {
console.log(error)
}
};
const logout = (history) => async () => {
Swal.fire({
icon: "success",
title: "Logout succes",
});
localStorage.removeItem("token");
history.push("/");
};
export {
getUserLogin,
GET_USER_LOGIN,
loginAdmin,
logout,
};
|
import React, { Component } from 'react';
class RoomList extends Component {
constructor(props) {
super(props);
this.setRoomName = this.setRoomName.bind(this);
this.createRoom = this.createRoom.bind(this);
this.state = {
room: {
name: null,
},
player: {
name: null,
},
};
}
createRoom() {
this.props.onAddRoom(this.state.room);
}
setRoomName(event) {
this.setState({
room: {
name: event.target.value,
},
});
}
setPlayerName(event) {
this.setState({
player: {
name: event.target.value,
},
});
}
render() {
const {
rooms,
} = this.props;
return (
<div className="container">
<div className="roomList--header">
<h2>You can join {rooms.length} room(s)</h2>
<div className="create-room">
<input type="text" placeholder="Room name" onChange={this.setRoomName} />
<button onClick={this.createRoom}>Create room</button>
</div>
</div>
<div>
{rooms.map((room, i) => {
return (
<div key={i} className="room">
<h1 className="room--name">{room.name}</h1>
<span className="room--playerNumber">{room.players.length} player(s)</span>
<button className="room--joinRoomButton" onClick={event => this.props.onJoinRoom(room)}>Join room</button>
</div>
);
})}
</div>
</div>
);
}
}
export default RoomList;
|
import React, {Component} from "react"
class Product extends Component {
render() {
let {name,price,img_url,id} = this.props
return (
<article className="product">
<img src={img_url} />
<h3>{name}</h3>
<h4>{price}</h4>
<button onClick={() => this.props.removeProduct(id)}>Delete</button>
<button onClick={() => this.props.selectProduct({name,price,img_url,id})}>Edit</button>
</article >
)
}
}
export default Product;
|
const express = require('express')
const app = express();
const bodyParser = require('body-parser');
const path = require('path')
const routes = require('./backend/config/routes')
const {Client} = require('pg')
const PORT = process.env.PORT || 1979
const log = (stuff) => console.log(stuff)
const client = new Client({ connectionString: process.env.DATABASE_URL });
client.connect( (error) => {
if (error) { log('error yo: ', error) } else { log('connected to db') }
});
//body-parser functionality
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : false }));
app.use(express.static(path.join(__dirname, 'client/build')));
app.use('/', routes)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
app.listen(PORT, () => log('Shakedown ' + PORT));
|
var keystone = require('keystone');
var Types = keystone.Field.Types;
/**
* Logo Model
* =============
*/
var Logo = new keystone.List('Logo', {
autokey: { from: 'name', path: 'key', unique: true },
track: true
});
Logo.add({
name: { type: String, required: true, index: true },
publishedDate: { type: Date, default: Date.now },
imageUrl: { type: Types.Text, initial: true },
HausaImageUrl: { type: Types.Text, initial: true },
YourubeImageUrl: { type: Types.Text, initial: true },
igboImageUrl: { type: Types.Text, initial: true },
description: { type: Types.Text, initial: true },
/*image: { type: Types.CloudinaryImage },
images: { type: Types.CloudinaryImages },*/
});
Logo.register();
|
/*jshint globalstrict:false, strict:false, maxlen: 400 */
/*global fail, assertEqual, AQL_EXECUTE */
////////////////////////////////////////////////////////////////////////////////
/// @brief test failure scenarios
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var jsunity = require("jsunity");
var arangodb = require("@arangodb");
var db = arangodb.db;
var internal = require("internal");
const {ERROR_QUERY_COLLECTION_LOCK_FAILED} = internal.errors;
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////
function ahuacatlFailureSuite () {
'use strict';
const cn = "UnitTestsAhuacatlFailures";
const en = "UnitTestsAhuacatlEdgeFailures";
let assertFailingQuery = function (query, error) {
if (error === undefined) {
error = internal.errors.ERROR_DEBUG;
}
try {
AQL_EXECUTE(query);
fail();
} catch (err) {
assertEqual(error.code, err.errorNum, query);
}
};
return {
setUpAll: function () {
internal.debugClearFailAt();
db._drop(cn);
db._create(cn, { numberOfShards: 3 });
db._drop(en);
db._createEdgeCollection(en);
},
setUp: function () {
internal.debugClearFailAt();
},
tearDownAll: function () {
internal.debugClearFailAt();
db._drop(cn);
db._drop(en);
},
tearDown: function () {
internal.debugClearFailAt();
},
testQueryRegistryInsert1: function () {
internal.debugSetFailAt("QueryRegistryInsertException1");
// we need a diamond-query to trigger an insertion into the q-registry
assertFailingQuery(
"FOR doc1 IN " +
cn +
" FOR doc2 IN " +
cn +
" FILTER doc1._key != doc2._key RETURN 1",
internal.errors.ERROR_DEBUG
);
},
testQueryRegistryInsert2: function () {
internal.debugSetFailAt("QueryRegistryInsertException2");
// we need a diamond-query to trigger an insertion into the q-registry
assertFailingQuery(
"FOR doc1 IN " +
cn +
" FOR doc2 IN " +
cn +
" FILTER doc1._key != doc2._key RETURN 1",
internal.errors.ERROR_DEBUG
);
},
testShutdownSync: function () {
internal.debugSetFailAt("ExecutionEngine::shutdownSync");
let res = AQL_EXECUTE("FOR doc IN " + cn + " RETURN doc").json;
// no real test expectations here, just that the query works and doesn't fail on shutdown
assertEqual(0, res.length);
},
testShutdownSyncDiamond: function () {
internal.debugSetFailAt("ExecutionEngine::shutdownSync");
let res = AQL_EXECUTE(
"FOR doc1 IN " +
cn +
" FOR doc2 IN " +
en +
" FILTER doc1._key == doc2._key RETURN doc1"
).json;
// no real test expectations here, just that the query works and doesn't fail on shutdown
assertEqual(0, res.length);
},
testShutdownSyncFailInGetSome: function () {
internal.debugSetFailAt("ExecutionEngine::shutdownSync");
internal.debugSetFailAt("RestAqlHandler::getSome");
assertFailingQuery("FOR doc IN " + cn + " RETURN doc");
},
testShutdownSyncDiamondFailInGetSome: function () {
internal.debugSetFailAt("ExecutionEngine::shutdownSync");
internal.debugSetFailAt("RestAqlHandler::getSome");
assertFailingQuery(
"FOR doc1 IN " +
cn +
" FOR doc2 IN " +
en +
" FILTER doc1._key == doc2._key RETURN doc1"
);
},
testNoShardsReturned: function () {
internal.debugSetFailAt("ClusterInfo::failedToGetShardList");
assertFailingQuery(
"FOR doc1 IN " +
cn +
" FOR doc2 IN " +
en +
" FILTER doc1._key == doc2._key RETURN doc1",
ERROR_QUERY_COLLECTION_LOCK_FAILED
);
},
};
}
if (internal.debugCanUseFailAt()) {
jsunity.run(ahuacatlFailureSuite);
}
return jsunity.done();
|
#!/usr/bin/gjs
const Lang = imports.lang;
const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;
const Gdk = imports.gi.Gdk;
const Gio = imports.gi.Gio;
const WebKit = imports.gi.WebKit;
const Soup = imports.gi.Soup;
// This folder should be created on app install. The expected files are
// cookies,txt and rdio-icon.png
const RDIO_USER_DATA = GLib.get_user_data_dir() + '/rdio';
const RDIO_URI = 'https://rdio.com';
const Application = new Lang.Class({
Name: 'Application',
_init: function() {
this.application = new Gtk.Application();
this.application.connect('activate', Lang.bind(this, this._onActivate));
this.application.connect('startup', Lang.bind(this, this._onStartup));
},
_buildUI: function() {
this._createWindow();
this._bindAccelerators();
this._createWebView();
this._createCookies();
this._createStatusIcon();
this._createMenus();
},
_createWindow: function() {
// Application main window
this._window = new Gtk.ApplicationWindow({
application: this.application,
window_position: Gtk.WindowPosition.CENTER,
title: "Rdio"
});
this._window.set_default_size(800, 600);
// Prevent window from be destroyed when clicked on close button
this._window.connect('delete-event',
Lang.bind(this, this._toggleWindowVisibility));
},
_createWebView: function() {
// Scrollable container
let sw = new Gtk.ScrolledWindow({});
this._window.add(sw);
// Web view
this._webView = new WebKit.WebView();
this._webView.load_uri(RDIO_URI);
sw.add(this._webView);
},
_bindAccelerators: function() {
let pauseAction = new Gio.SimpleAction({name: 'pause'});
let nextAction = new Gio.SimpleAction({name: 'next'});
let prevAction = new Gio.SimpleAction({name: 'prev'});
pauseAction.connect('activate', Lang.bind(this, function() {
this._eventDispatcher('.play_pause');
}));
nextAction.connect('activate', Lang.bind(this, function() {
this._eventDispatcher('.next');
}));
prevAction.connect('activate', Lang.bind(this, function() {
this._eventDispatcher('.prev');
}));
this.application.add_action(pauseAction);
this.application.add_action(nextAction);
this.application.add_action(prevAction);
this.application.add_accelerator('<alt>x', 'app.pause', null);
this.application.add_accelerator('<alt>c', 'app.next', null);
this.application.add_accelerator('<alt>z', 'app.prev', null);
},
_eventDispatcher: function(selector) {
let js ="var evt = document.createEvent('MouseEvents');"
js +="evt.initMouseEvent('click', true, false, document, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
js +="document.querySelector('"+selector+"').dispatchEvent(evt);"
this._webView.execute_script(js);
},
_createCookies: function() {
// Cookies persistance
let session = WebKit.get_default_session();
let cookies = new Soup.CookieJarText({
filename: RDIO_USER_DATA + '/cookies.txt'
});
cookies.set_accept_policy(Soup.CookieJarAcceptPolicy.ALWAYS);
cookies.attach(session);
},
_createStatusIcon: function() {
// System tray icon
let tray = new Gtk.StatusIcon();
tray.file = RDIO_USER_DATA + '/rdio-icon.png';
tray.connect('activate', Lang.bind(this, this._toggleWindowVisibility));
this.tray = tray;
},
_createMenus: function() {
let menu = new Gio.Menu();
menu.append('Hide', 'app.hide');
menu.append('Quit', 'app.quit');
menu.append('Pause', 'app.pause');
this.application.set_app_menu(menu);
let hideAction = new Gio.SimpleAction({name: 'hide'});
let quitAction = new Gio.SimpleAction({name: 'quit'});
hideAction.connect('activate',
Lang.bind(this._window, this._window.hide));
quitAction.connect('activate',
Lang.bind(this._window, this._window.destroy));
this.application.add_action(hideAction);
this.application.add_action(quitAction);
},
_toggleWindowVisibility: function() {
if(this._window.is_active) {
this._window.hide();
} else {
this._window.show_all();
this._window.present();
}
return true;
},
_onActivate: function() {
this._window.show_all();
},
_onStartup: function() {
this._buildUI();
},
});
//run the application
let app = new Application();
app.application.run(ARGV);
|
import 'react-native-gesture-handler';
import React from 'react'
import styled from 'styled-components/native'
import { Restaurants } from './Pages/Restaurants'
import { Restaurant } from './Pages/Restaurant'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Container = styled.View`
flex: 1;
background-color: white;
`
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Container>
<Stack.Navigator>
<Stack.Screen name="Trending this Week" component={Restaurants} />
<Stack.Screen name="Best place this week" component={Restaurant} />
</Stack.Navigator>
</Container>
</NavigationContainer>
)
}
export default App
|
const settings = [
{ threshold: "207030ff", up: 1 },
{ threshold: "808077ff" },
{ threshold: "bb2277ff", up: 1, flip: 1 },
]
const boards = document.querySelectorAll("canvas")
Array.from(boards).forEach((canvas, i) => {
const target = canvas.getContext("2d")
const config = settings[i]
const a = config.up ? Math.PI * 0.5 : 0
const y = config.up ? canvas.height : 0
const buffer = canvas.cloneNode().getContext("2d")
buffer.rotate(a)
const master = document.createElement("img")
const worker = new Worker("worker.js")
master.addEventListener("load", () => {
buffer.drawImage(master, 0, -y)
const source = buffer.getImageData(0, 0, canvas.height, canvas.width)
worker.postMessage({ config, source })
})
worker.addEventListener("message", ({ data }) => {
buffer.putImageData(data.result, 0, 0)
target.save()
if (config.up) {
target.translate(0, y)
target.rotate(-a)
}
target.drawImage(buffer.canvas, 0, 0)
target.restore()
})
master.setAttribute("src", canvas.dataset.src)
})
|
import React, { useEffect } from "react";
import Message from "./Message";
import AcceptMessage from "./AcceptMessage";
import * as query from "api/queries";
export const MessagesContainer = ({ room, sender, fetchMore }) => {
const messagesEndRef = React.createRef();
useEffect(() => {
const scrollToBottom = () => {
messagesEndRef.current.scrollIntoView({ behavior: "instant" });
};
if (room.messages.length) {
scrollToBottom();
}
}, [room.messages]);
const handleScroll = ({ currentTarget }, onLoadMore) => {
if (!currentTarget.scrollTop) {
onLoadMore();
}
};
return (
<div
className={"messages"}
onScroll={(e) =>
handleScroll(e, () => {
fetchMore({
variables: {
id: room.id,
first: 5,
skip: room.messages.length,
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
return {
room: {
...prev.room,
messages: [
...prev.room.messages,
...fetchMoreResult.room.messages,
],
},
};
},
});
})
}
>
{room.waitingForApprove ? (
<AcceptMessage
sender={sender}
post={room.post}
receiverPost={room.receiverPost}
/>
) : room.messages.length ? (
<>
{room.messages.map((message) => (
<Message {...message} key={message.id} />
))}
</>
) : (
<p>No messages</p>
)}
<div ref={messagesEndRef}></div>
</div>
);
};
|
//header with button that "click" starts 5 second countdown
//and starts generating a math.random amount of circles between
//1 and 8
//container for the circles
//if buttons.forEach buttons.style.color === "green"
// && ${timer} === 0; display you win else if timer === 0 you lose
//function to set the button color change so it can be stopped
let body = document.querySelector("body");
body.style.height = "100vh";
body.style.width = "100vw";
body.style.margin = "0";
body.style.padding = "0";
body.style.fontFamily = "Luminari";
body.style.letterSpacing = "10px";
let main = document.getElementById("main");
main.style.display = "flex";
main.style.justifyContent = "center";
main.style.alignItems = "center";
// main.style.height = "100%";
// main.style.width = "100%";
let header = document.createElement("header");
header.style.background = "grey";
header.style.height = "100px";
header.style.width = "100%";
header.innerText = "";
header.style.fontSize = "40px";
header.style.color = "red";
header.style.display = "flex";
header.style.justifyContent = "center";
header.style.alignContent = "center";
header.style.alignItems = "center";
// header.innerText = "hello";
header.style.margin = "0";
body.append(header);
let startButton = document.createElement("button");
startButton.style.height = "60px";
startButton.style.width = "150px";
startButton.style.background = "yellow"
startButton.innerText = "S T A R T";
startButton.style.fontSize = "25px";
startButton.style.color = "grey";
header.append(startButton);
let bodySpacing = document.createElement("div");
bodySpacing.style.display = "flex";
bodySpacing.style.justifyContent = "center";
bodySpacing.style.alignItems = "center";
bodySpacing.style.height = "90vh";
// bodySpacing.style.background = "blue";
body.append(bodySpacing);
let gameArea = document.createElement("div");
gameArea.style.display = "flex";
gameArea.style.justifyContent = "center";
gameArea.style.alignItems = "center";
gameArea.style.height = "500px";
gameArea.style.width = "700px";
gameArea.style.background = "lightgrey";
gameArea.style.position = "relative";
bodySpacing.append(gameArea);
let results = document.createElement("p");
results.style.background = "blue";
results.style.height = "200px";
results.style.width = "300px";
results.style.borderRadius = "10px";
results.style.display = "none";
results.style.zIndex = "1";
results.style.alignItems = "center";
results.style.justifyContent = "center";
results.style.color = "gold";
results.style.fontSize = "40px";
gameArea.append(results);
let buttonAmount = Math.floor(Math.random() * 7) + 1;
let clicked = false;
let timeLeft = 5;
let hasWon = false;
startButton.addEventListener("click", () => {
startButton.style.display = "none";
header.innerText = `YOU HAVE ${timeLeft} s REMAINING`;
// header.innerText = `Y O U H A V E ${countDownTime}S R E M A I N I N G`;
for (i = 0; i < buttonAmount; i++) {
let buttons = document.createElement("button");
buttons.classList.add("game-button");
buttons.innerText = i +1;
buttons.style.position = "absolute";
buttons.style.height = "50px";
buttons.style.width = "50px";
buttons.style.border = "none";
buttons.style.borderRadius = "90px";
buttons.style.backgroundColor = "red";
buttons.style.border = "1px solid white";
buttons.style.outline = "none"
buttons.style.color = "white";
buttons.style.fontSize = "30px";
buttons.style.left = `${Math.random() * 650}px`;
buttons.style.top = `${Math.random() * 450}px`
// buttons.addEventListener("click", function (event) {
// buttons.style.backgroundColor = "green";
// });
buttons.addEventListener("click", greenBackground);
gameArea.append(buttons);
}
const gameTimer = setTimeout(function () {
document.querySelectorAll("button").forEach((a) => {
if (!hasWon) {
// results.style.backgroundColor = "white";
// results.innerText = "W I N \n W I N \n W I N";
// results.style.display = "flex";
// clearTimeout(gameTimer);
// buttons.removeEventListener("click", startButton);
// } else {
results.style.backgroundColor = "red";
results.innerText = "L O S E \n L O S E \n L O S E";
results.style.display = "flex";
buttons.removeEventListener("click", greenBackground, true);
}
});
}, 5000);
// var timeLeft = 5;
var countDownTimer = setInterval(function() {
if (hasWon) {
clearInterval(countDownTimer);
} else {
timeLeft -= 1;
header.innerText = `YOU HAVE ${timeLeft} s REMAINING`;
if (timeLeft == 0) {
header.innerText = `TIME IS UP`;
clearInterval(countDownTimer);
buttons.removeEventListener("click", startButton);
}
}
}, 1000);
});
// header.innerText = `Y O U H A V E ${timeLeft} s R E M A I N I N G`;
function greenBackground(event) {
event.target.style.backgroundColor = "green";
// this.style.display = "none";
let allGreen = Array.from(document.querySelectorAll(".game-button")).every(
(b, index, array) => {
console.log(array);
if (b.style.backgroundColor === "green") {
return true;
}
}
)
if (allGreen) {
hasWon = true;
results.style.backgroundColor = "white";
results.innerText = "W I N \n W I N \n W I N";
results.style.display = "flex";
header.innerText = "V I C T O R Y";
}
};
|
import path from 'path';
import * as packageJson from '../package.json';
const config = {
entry: './app/index.js',
module: {
rules: [
{
exclude: /node_modules/,
test: /\.js?$/,
use: {
loader: 'babel-loader',
},
},
],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, '..', 'dist'),
},
plugins: [],
resolve: {
extensions: [
'.js',
],
modules: [
'.',
'app',
'node_modules',
],
},
};
export default config;
|
import React from 'react';
import lottie from 'lottie-web';
export default function useLottieAnimation(animationData, elementRef) {
const ref = React.useRef(null);
React.useEffect(() => {
return () => lottie.destroy();
}, []);
if (ref.current === null && elementRef.current !== null) {
ref.current = lottie.loadAnimation({
container: elementRef.current,
renderer: 'svg',
loop: false,
autoplay: false,
animationData,
});
}
const stopAnimation = React.useCallback(() => {
if (ref.current !== null) lottie.stop();
}, [elementRef]);
return [ref.current, stopAnimation];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.