text
stringlengths 7
3.69M
|
|---|
import FbGroupShareModel from "./models/FbGroupShareModel";
import i18n from '../i18n';
var FB_GROUP_SHARE_MODEL = null;
const DASHBOARD_TIME_REFRESH_DATA = 10 * 60000;
const TABLE_SHOW_TYPES = [
{ value: 0, text: i18n.t('dashboard.table.show-in-grid') },
{ value: 1, text: i18n.t('dashboard.table.show-in-stack') },
];
function initFaceBookGroupShare() {
FB_GROUP_SHARE_MODEL = new FbGroupShareModel();
}
function getFacebookGroupShareModel() {
if (FB_GROUP_SHARE_MODEL == null) initFaceBookGroupShare();
return FB_GROUP_SHARE_MODEL;
}
function formatNewsType(type) {
switch (type) {
case "TIENPHONG":
return "Tiền Phong";
case "VNEXPRESS":
return "VnExpress";
case "TUOITRE":
return "Tuổi trẻ";
case "SUCKHOEDOISONG":
return "Sức khoẻ & Đời sống";
case "SOHA":
return "Soha News";
case "CHANNEL_NEWS_ASIA":
return "Channel News Asia";
case "TELEGRAPH":
return "Telegraph";
case "STRAITSTIMES":
return "The Straitstimes";
case "RFI":
return "RFI";
default:
return type;
}
}
function adjustFontSizeToParent(domToAdjust, percent = 0.95) {
if (domToAdjust != null) {
const domParent = domToAdjust.parentNode;
const currentFontSize = window.getComputedStyle(domParent).getPropertyValue('font-size');
let targetFontSize = parseInt(currentFontSize);
while (domToAdjust.offsetWidth > (domParent.offsetWidth * percent)) {
targetFontSize -= 1;
domParent.style.fontSize = `${targetFontSize}px`;
}
}
}
function get24hNewCaseRateVariant(dayNewCaseRate) {
dayNewCaseRate = parseFloat(dayNewCaseRate);
if (dayNewCaseRate >= 25) return 'new-case-high';
if (dayNewCaseRate >= 15 && dayNewCaseRate < 25) return 'new-case-medium';
if (dayNewCaseRate >= 5 && dayNewCaseRate < 15) return 'new-case-low';
if (dayNewCaseRate > 0 && dayNewCaseRate < 5) return 'new-case-vlow';
return 'new-case-none';
}
function get24hNewDeathRateVariant(dayNewDeathRate) {
dayNewDeathRate = parseFloat(dayNewDeathRate);
if (dayNewDeathRate >= 25) return 'new-dead-high';
if (dayNewDeathRate >= 15 && dayNewDeathRate < 25) return 'new-dead-medium';
if (dayNewDeathRate >= 5 && dayNewDeathRate < 15) return 'new-dead-low';
if (dayNewDeathRate > 0 && dayNewDeathRate < 5) return 'new-dead-vlow';
return 'new-dead-none';
}
function getDeathRateVariant(dayDeathRate) {
dayDeathRate = parseFloat(dayDeathRate);
if (dayDeathRate >= 20) return 'dead-rate-high';
if (dayDeathRate >= 10 && dayDeathRate < 20) return 'dead-rate-medium';
if (dayDeathRate >= 3 && dayDeathRate < 10) return 'dead-rate-low';
if (dayDeathRate > 0 && dayDeathRate < 3) return 'dead-rate-vlow';
return 'dead-rate-none';
}
function customizeBStickyCols(targetTable) {
const stickyCols = targetTable.getElementsByClassName('b-table-sticky-column');
for (let col of stickyCols) {
const allStickyColsInSameParent = col.parentElement.getElementsByClassName('b-table-sticky-column');
for (let index = 1; index < allStickyColsInSameParent.length; ++index) {
const currentCol = allStickyColsInSameParent[index];
let targetOffsetLeft = 0;
for (let beforeIndex = 0; beforeIndex < index; ++beforeIndex) {
const beforeCol = allStickyColsInSameParent[beforeIndex];
const beforeColRect = beforeCol.getBoundingClientRect();
let colWidth = 0;
if (beforeColRect.width) {
// `width` is available for IE9+
colWidth = beforeColRect.width;
} else {
// Calculate width for IE8 and below
colWidth = beforeColRect.right - beforeColRect.left;
}
targetOffsetLeft += colWidth;
}
currentCol.style.left = targetOffsetLeft + "px"
}
}
}
function observeBTableOnAddData(targetTable, onAdded, onRemoved) {
const observer = new MutationObserver((mutationsList) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
const addedNode = mutation.addedNodes[0];
if (addedNode != null && addedNode.nodeName !== "#comment") onAdded(addedNode);
const removedNode = mutation.removedNodes[0];
if (removedNode != null && removedNode.nodeName !== "#comment") onRemoved(removedNode)
}
}
});
observer.observe(targetTable, {childList: true, subtree: true});
return observer;
}
export default {
FB_GROUP_SHARE_MODEL,
DASHBOARD_TIME_REFRESH_DATA,
TABLE_SHOW_TYPES,
initFaceBookGroupShare,
getFacebookGroupShareModel,
formatNewsType,
adjustFontSizeToParent,
get24hNewCaseRateVariant,
get24hNewDeathRateVariant,
getDeathRateVariant,
customizeBStickyCols,
observeBTableOnAddData
}
|
import tw from 'tailwind-styled-components'
/** Div which contains Logo svg */
export const HeaderUserIconLiner = tw.div`
mx-3
flex-shrink-0
`
|
class Zim {
constructor(name, age) {
this.age = age;
this.name = name;
}
static
printName(obj) {
console.log(obj.name);
}
}
var zimc1 = new Zim("Zim", 21)
Zim.printName(zimc1)
function zim(name, age){
this.name = name;
this.age = age;
}
zim.prototype.printName = function() {
console.log(this.name);
}
var zim1 = new zim("Zim", 21)
zim1.printName()
|
$(document).ready(function(){
console.log("ready");
var launchtimer = setInterval(incrementTimer, 1000);
const {ipcRenderer} = require('electron')
ipcRenderer.on('daemons-windows-get-all-response', (event, arg) => {
console.log(arg) // prints "pong"
})
ipcRenderer.send('daemons-windows-get-all', {"app": "Daemon Initializer"})
});
var secElapsed = 0;
function incrementTimer(){
secElapsed++;
$("#countdown").text(secElapsed+"s elapsed");
if(secElapsed > 60){
$("#humor").text("Okay, more than a moment...");
}
}
|
/**
* @file components/ConfirmDialog.js
* @author leeight
*/
import {defineComponent} from 'san';
import Dialog from './Dialog';
export default defineComponent({
template: `<template>
<ui-dialog open="{=open=}" s-ref="dialog" skin="confirm" width="{{width}}" on-close="onCloseDialog" on-confirm="onConfirmDialog">
<span slot="head">{{title}}</span>
<div class="ui-dialog-icon ui-dialog-icon-confirm"></div>
<div class="ui-dialog-text">{{message | raw}}</div>
</ui-dialog>
</template>`,
components: {
'ui-dialog': Dialog
},
initData() {
return {
open: true,
width: 500,
title: '请确认'
};
},
onCloseDialog() {
this.fire('close');
this.data.set('open', false);
},
onConfirmDialog() {
this.fire('confirm');
this.data.set('open', false);
}
});
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './Issue.css';
class Issue extends Component {
constructor(props) {
super(props);
this.state = {
issueNumber: undefined,
assignedTo: undefined,
escrow: undefined,
value: undefined,
addIssueValue: undefined,
claimIssueEscrow: undefined,
isMessageVisible: false,
message: undefined,
messageUrl: undefined,
};
// This binding is necessary to make `this` work in the callback
this.handleIssueNumberChange = this.handleIssueNumberChange.bind(this);
this.handleAddIssueValueChange = this.handleAddIssueValueChange.bind(this);
this.handleClaimIssueEscrowChange = this.handleClaimIssueEscrowChange.bind(this);
this.addIssueClicked = this.addIssueClicked.bind(this);
this.claimIssueClicked = this.claimIssueClicked.bind(this);
this.closeIssueClicked = this.closeIssueClicked.bind(this);
this.getIssueDetails = this.getIssueDetails.bind(this);
}
handleIssueNumberChange(event) {
this.setState({
issueNumber: event.target.value
}, function() {
this.getIssueDetails();
});
}
handleAddIssueValueChange(event) {
this.setState({
addIssueValue: event.target.value
});
}
handleClaimIssueEscrowChange(event) {
this.setState({
claimIssueEscrow: event.target.value
});
}
addIssueClicked(event) {
var issueNumber = this.state.issueNumber;
window.web3.eth.getAccounts(function(err, accounts) {
console.log(issueNumber);
console.log(accounts[0]);
window.miniToken.addIssue(issueNumber, { from: accounts[0], value: parseInt(this.state.addIssueValue), gas: 110000, gasPrice: 4000000000 })
.then(function (txHash) {
console.log('Transaction sent')
console.dir(txHash)
this.setState({
message: 'Submitted transaction.',
messageUrl: 'https://etherscan.io/tx/' + txHash,
isMessageVisible: true
});
}.bind(this))
.catch(console.error)
}.bind(this));
}
claimIssueClicked(event) {
var issueNumber = this.state.issueNumber;
window.web3.eth.getAccounts(function(err, accounts) {
console.log(issueNumber);
console.log(accounts[0]);
window.miniToken.claimIssue(issueNumber, { from: accounts[0], value: parseInt(this.state.claimIssueEscrow), gas: 110000, gasPrice: 4000000000 })
.then(function (txHash) {
console.log('Transaction sent')
console.dir(txHash)
this.setState({
message: 'Submitted transaction.',
messageUrl: 'https://etherscan.io/tx/' + txHash,
isMessageVisible: true
});
}.bind(this))
.catch(console.error)
}.bind(this));
}
closeIssueClicked(event) {
var reason = event.target.value;
var issueNumber = this.state.issueNumber;
window.web3.eth.getAccounts(function(err, accounts) {
console.log(issueNumber);
console.log(accounts[0]);
window.miniToken.completeIssue(issueNumber, parseInt(reason), { from: accounts[0], gas: 110000, gasPrice: 4000000000 })
.then(function (txHash) {
console.log('Transaction sent')
console.dir(txHash)
this.setState({
message: 'Submitted transaction.',
messageUrl: 'https://etherscan.io/tx/' + txHash,
isMessageVisible: true
});
}.bind(this))
.catch(console.error)
}.bind(this));
}
getIssueDetails() {
if (this.state.issueNumber !== undefined) {
var result = window.miniToken.getIssue(this.state.issueNumber).then(function (result) {
if (typeof window.web3 !== 'undefined') {
this.setState({
assignedTo: result['assignedTo'],
escrow: (result['escrow'] || 0).toNumber(),
value: (result['value'] || 0).toNumber(),
});
}
}.bind(this));
}
}
render() {
return ( <div>
<div className='issue-row'>
Issue Number <input placeholder="Try issue #17" type = "text" name = "issueNumber" value = {this.state.issueNumber} onChange = {this.handleIssueNumberChange.bind(this)} />
<br />
<span className='issue-description'>
This is a work item/issue number for a software project. A positive integer. Try using issue number 17. It's the test issue.
</span>
</div>
<div className='issue-row'>
<button onClick={this.addIssueClicked}>Add Issue</button> Value <input placeholder="100000000000000" type = "text" name = "addIssueValue" value = {this.state.addIssueValue} onChange = {this.handleAddIssueValueChange.bind(this)} />
<br />
<span className='issue-description'>
Adds a new issue. When the issue is added, the Value (in wei) is taken from your account and reserved for issue.
<br />
Note: The value is in wei (10^18 wei == 1 eth). So try using 100000000000000, which is 0.0001 ether.
</span>
</div>
<div className='issue-row'>
<button onClick={this.claimIssueClicked}>Claim Issue</button> Escrow <input placeholder="2000000" type = "text" name = "claimIssueEscrow" value = {this.state.claimIssueEscrow} onChange = {this.handleClaimIssueEscrowChange.bind(this)} />
<br />
<span className='issue-description'>
Claims an issue. In order to work on an issue, you need to claim it. When you claim an issue 20% of the value of the issue is taken from your account and reserved for the issue in escrow. If you fix the issue, the value + your escrow is deposited to your account (100% + 20% = 120%). If you do not fix the issue, your escrow is forfeited (-20%).
<br />
Note: The value must equal the escrow value of the issue. i.e. copy the escrow amount in from the issue details.
</span>
</div>
<div className='issue-row'>
<button onClick={this.closeIssueClicked} value='0'>Close Fixed</button > <button onClick={this.closeIssueClicked} value='1'>Close Not Fixed</button >
<br />
<span className='issue-description'>
Close an issue. An issue can either be closed as fixed or not fixed. If the issue is fixed, the value of the issue + the escrow is deposited in the owner's account. If the issue is not fixed, the owner's escrow is forfeited and the issue value remains (so someone else can claim the issue and provide a fix).
</span>
</div>
<div className='issue-row'>
Issue Number {this.state.issueNumber}
<br />
Owner {this.state.assignedTo}
<br />
Escrow {this.state.escrow}
<br />
Value {this.state.value}
</div>
<div className='issue-row'>
<button onClick={this.getIssueDetails}>Refesh</button>
</div>
{ this.state.isMessageVisible &&
<div className='issue-row-message'>
<span>{this.state.message}</span>
<br />
<a target='_blank' href={this.state.messageUrl}>{this.state.messageUrl}</a>
</div>
}
</div>
);
}
}
export default Issue;
|
import { DEBIT_ATTACHMENT_TYPE } from "../../../configs/attachmentType.config";
const { DEBIT_NOTE, RECEIPT, OTHERS } = DEBIT_ATTACHMENT_TYPE;
export const MODEL_ATTACHMENT = [
{
attachments: [
{
name: "Debit Note",
type: DEBIT_NOTE
}
]
},
{
attachments: [
{
name: "Receipt",
type: RECEIPT
},
{
name: "Others",
type: OTHERS
}
]
}
];
|
function capitalWord(string) {
return string[0].toUpperCase() + string.slice(1).toLowerCase();
}
function lowerCamelString(string) {
let arrOfStr = string.split(" ");
let newString = "";
arrOfStr.forEach((element) => {
newString += capitalWord(element);
});
newString = newString[0].toLowerCase() + newString.slice(1);
return newString;
}
module.exports = lowerCamelString;
|
const { server: electronConnectServer } = require('electron-connect');
const TARGET = {
main: 'electron-main',
renderer: 'electron-renderer'
};
const AVAILABLE_TARGETS = [TARGET.main, TARGET.renderer];
function createElectronReloadWebpackPlugin(options = {}) {
let server = null;
function restartOrReloadServer(targetType, server) {
if (targetType === TARGET.main) {
server.restart();
} else {
server.reload();
}
}
function applyCompiler(userTargetType) {
return {
apply(compiler) {
const configTarget = AVAILABLE_TARGETS.find(target => target === compiler.options.target);
const targetType = userTargetType || configTarget || TARGET.main;
compiler.hooks.done.tap('ElectronReloadWebpackPlugin', () => {
if (!server) {
server = electronConnectServer.create(options);
server.start();
} else {
restartOrReloadServer(targetType, server);
}
});
}
};
}
return target => {
if (target && !AVAILABLE_TARGETS.includes(target)) {
console.log(
`\nElectronReloadWebpackPlugin: Specified target should be one of "${AVAILABLE_TARGETS.join(
' | '
)}". You passed "${target}"`
);
console.log(`ElectronReloadWebpackPlugin: Using default target "${TARGET.main}"`);
return applyCompiler(TARGET.main);
} else {
return applyCompiler(target);
}
};
}
module.exports = createElectronReloadWebpackPlugin;
|
module.exports = {
user: 'b28cd0a337cf8a',
pass: '68141ba0d93995',
host: 'smtp.mailtrap.io',
port: 2525
}
|
import React from "react";
import { graphql } from "gatsby";
import "./styles.scss";
import Layout from "../../../components/Layout";
const Post = props => {
const post = props.data.markdownRemark;
const {
title,
description,
date,
location,
locationEmoji,
} = post.frontmatter;
return (
<Layout>
<div className="post">
<h1>{title}</h1>
<time>{`${date} | ${location} ${locationEmoji}`} </time>
<p>{description}</p>
<div
className="content"
dangerouslySetInnerHTML={{ __html: post.html }}
/>
</div>
</Layout>
);
};
export default Post;
export const query = graphql`
query($slug: String) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
date(formatString: "MMMM Do YYYY")
description
location
locationEmoji
}
}
}
`;
|
require('babel-register');
require('babel-polyfill');
var HDWalletProvider = require("truffle-hdwallet-provider");
var infura_apikey = "55094ac1f57f4ffaa2be7fc764a14d15";
var mnemonic = "traffic bracket depth radar labor double knock ritual ozone ball crisp dune";
var testRpcMnemonic = "civil silk monster coffee access vast peasant village under pretty trade resource"
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545,
// from: "0xb359705e8d34ed0a8ee0f28e733ebc5e6490c515",
from: "0x5964E97B04bfbA5dFD62Bf0E1fED5e54D9B7C54e",
network_id : "*"
},
prod: {
host: "52.66.155.129",
port: 8545,
from: "0x5964E97B04bfbA5dFD62Bf0E1fED5e54D9B7C54e",
network_id : "3257"
},
ropsten: {
provider: function() {
return new HDWalletProvider(mnemonic, "https://ropsten.infura.io/"+infura_apikey);
},
network_id: '3',
gas:4612388,
}
}
};
|
import React, { Component } from "react";
import "./PlantDetails.css";
import userDB from '../Database/UserDB';
import Chart from './Chart.js';
class PlantDetails extends Component {
constructor(props){
super(props);
this.intervalID = null;
this._isMounted = false;
this.state = {
chartData:{},
chartDataSun:{},
user: this.props.currentUser.getUser(),
tableSun: [],
tableHum: [],
days : previousWeekdays(),
dates: previousDates(),
humidity: ["", "", "", "", ""],
sun: ["", "", "", "", ""],
loadingStatus: "Refresh",
}
}
//add this as an observer for the user-state
componentDidMount() {
this._isMounted = true;
this.props.currentUser.addObserver(this);
}
//remove this as an observer
componentWillUnmount() {
clearTimeout(this.intervalID);
this._isMounted = false;
this.props.currentUser.removeObserver(this);
}
//called from the observed class
update() {
this.setState({
user: this.props.currentUser.getUser()
});
}
componentDidUpdate(){
clearTimeout(this.intervalID);
if(this._isMounted && this.state.user){
this.intervalID = setTimeout(() => {
this.refreshChartsAndTable(5);
}, 300000);//1 min
}
}
refreshChartsAndTable(index){
clearTimeout(this.intervalID);
if(this._isMounted && this.state.user){
this.intervalID = setTimeout(() => {
userDB.getHardwareIDFromDB(this.state.user.uid);
let humidData = userDB.getHumidityHistory();
let sunData = userDB.getSunHoursHistory();
this.setState({
chartData:{
labels: humidData,
datasets:[{
label:'Humidity',
data:humidData,
backgroundColor:[
'rgba(75, 119, 190, 1)',
]
}]
},
chartDataSun:{
labels: ["five days ago", "four days ago", "three days ago", "two days ago", "yesterday", "today"],
datasets:[{
label:'Light exposure',
data:sunData,
backgroundColor:[
'rgba(245, 215, 110, 1)',
]
}]
},
tableSun: sunData,
tableHum: humidData,
sun: this.arrayFunc(sunData),
humidity: this.arrayFunc(humidData),
loadingStatus: "loading...",
});
//Brute force buffer
if(index > 0){
this.refreshChartsAndTable(index-1);
}
}, 1000);
}
if(index === 0){
this.setState({
loadingStatus: "Refresh",
})
}
}
//Checks that the array is not empty and calls calc Average() to calc the average of each fifth of the array's elements
arrayFunc (arr) {
if(!(arr == null || arr.length === 0)) {
let returnArr = [];
for(let i = 0; i < 5; i++) {
returnArr[i] = this.calcAverage(arr, i)
}
return returnArr;
}
}
//Calculates average of a specific fifth of an array determined by the index received
calcAverage (arr, index) {
let fifthOfLength = (Math.floor(arr.length/5))
let arrLength1;
let accumulator = 0;
if(!(index === 0)) {
arrLength1 = index * fifthOfLength;
fifthOfLength *= (index+1)
} else {
arrLength1 = 0;
}
for(let i = arrLength1; i < fifthOfLength; i++) {
accumulator += arr[i];
}
return Math.floor(accumulator/fifthOfLength);
}
render() {
let thisPage = null;
if (this.state.user) {
let itemsDays = [];
let itemsHum = [];
let itemsSun = [];
for(let i = 0; i < 5; i++)
{
itemsDays.push(<td key={i}>
{this.state.days[i]}
<br/>
{this.state.dates[i]}
</td>)
if(!(this.state.sun == null || this.state.sun.length == 0 || this.state.humidity == null || this.state.humidity.length == 0)) {
itemsHum.push(<td key={i}>{this.state.humidity[i]}</td>)
itemsSun.push(<td key={i}>{this.state.sun[i]}</td>)
}
}
thisPage = (
<div className="PlantDetailsContainer">
<button onClick={()=>{this.refreshChartsAndTable(5)}}>{this.state.loadingStatus}</button>
<Chart className="humidChart" title="Humidity level" chartData={this.state.chartData} legendPosition="bottom"/>
<Chart title="Light exposure" chartData={this.state.chartDataSun} legendPosition="bottom"/>
<div className="Rectangle2">
<h1>Details for the last five days</h1>
<div className="Table2">
<table className = 'BestTable1'>
<tbody>
<tr className="Column2">
<td>Plant Details</td>
{itemsDays}
</tr>
<tr className="Row2">
<td>Average Humidity</td>
{itemsHum}
</tr>
<tr className="Row2">
<td>Average Sunlight</td>
{itemsSun}
</tr>
</tbody>
</table>
</div>
</div>
</div>
);
}
return thisPage;
}
}
//Determines todays and the past four weekdays
function previousWeekdays() {
let d = new Date();
let dayNumber = d.getDay();
let weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let arr = [];
for(let i = 0; i < 5; i++) {
if((dayNumber - i) < 0) { dayNumber += 7 } //reset to acces elemens in beginning of array. out of bound otherwise
arr[4-i] = weekday[dayNumber - i];
}
return arr;
}
//Determines todays and the past four dates
function previousDates() {
let arr = [];
for(let i = 0; i < 5; i++)
{
let someDate = new Date();
someDate.setDate(someDate.getDate() - i);
let dd = someDate.getDate();
let mm = someDate.getMonth() + 1;
let y = someDate.getFullYear();
if(mm < 10) { mm = "0"+mm }
if(dd < 10) { dd = "0"+dd }
let someFormattedDate = y+"-"+mm+"-"+dd
arr[4-i] = someFormattedDate;
}
return arr;
}
export default PlantDetails;
|
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import SignUpInForm from "./components/SignUpInForm";
import Footer from "./components/Footer";
import React, { Component } from 'react';
import 'whatwg-fetch';
const App = () =>(
<Router>
<div>
<Switch>
<Route exact path ="/" component={SignUpInForm} />
</Switch>
<br/>
<br/>
<br/>
<br/>
<Footer />
</div>
</Router>
);
export default App;
|
(function () {
"use strict";
function GameConsole(gameArea, gameSpeed, maxGameSpeed, speedX) {
this.gameArea = gameArea;
this.gameSpeed = gameSpeed;
this.maxGameSpeed = maxGameSpeed;
this.speedX = speedX;
this.level = 1; // game level starts at 0
this.score = 0;
this.currentGameSpeed = gameSpeed;
}
GameConsole.prototype.start = function () {
this.gameArea.initCanvas();
this.gameArea.initComponent();
this.gameArea.drawComponent();
this.gameArea.drawNextComponent();
this.gameArea.updateLevel(this.level);
this.gameArea.updateScoreBoard(this.score);
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
};
GameConsole.prototype.turnleft = function () {
this.gameArea.changeCompHorizontalSpeed(-this.speedX);
if (this.currentGameSpeed === this.getGameSpeedSlow()) return;
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.getGameSpeedSlow());
}
};
GameConsole.prototype.turnRight = function () {
this.gameArea.changeCompHorizontalSpeed(this.speedX)
if (this.currentGameSpeed === this.getGameSpeedSlow()) return;
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.getGameSpeedSlow());
}
};
GameConsole.prototype.accelerate = function () {
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.maxGameSpeed);
}
};
GameConsole.prototype.reverYSpeed = function () {
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
}
};
GameConsole.prototype.reverXSpeed = function () {
this.gameArea.reverseCompHorizontalSpeed();
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
}
};
GameConsole.prototype.transformComponent = function () {
this.gameArea.transformComponent();
};
GameConsole.prototype.toggleStatus = function () {
if (this.interval) {
this.cancelLoop();
} else {
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
}
};
GameConsole.prototype.getGameSpeed= function () {
this.currentGameSpeed = Math.max(this.gameSpeed - this.level * 100, this.maxGameSpeed);
return this.currentGameSpeed;
};
GameConsole.prototype.getGameSpeedSlow= function () {
this.currentGameSpeed = Math.max(this.gameSpeed - this.level * 50, this.maxGameSpeed);
return this.currentGameSpeed;
};
GameConsole.prototype.cancelLoop = function () {
clearInterval(this.interval);
this.interval = null;
};
GameConsole.prototype.updateGameSpeed = function () {
if (this.interval) {
this.cancelLoop();
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
}
};
GameConsole.prototype.updateLevel = function () {
this.level = Math.floor(this.score / 100) + 1;
};
GameConsole.prototype.update = async function () {
if (this.gameArea.isComponentDone()) {
this.gameArea.updateMatrix();
let tetrix = this.gameArea.tetris();
if (tetrix) {
this.cancelLoop(); // wait
await this.gameArea.showTetrixEffects(600); // wait for effects to finish
this.score += this.gameArea.updateTetris();
this.updateLevel();
this.gameArea.clearCanvas();
this.gameArea.redrawMatrix();
this.updateGameSpeed();
this.gameArea.updateLevel(this.level);
this.gameArea.updateScoreBoard(this.score);
this.interval = setInterval(this.update.bind(this), this.getGameSpeed());
}
// check game status
const gameOver = this.gameArea.isGameOver();
// game over
if (gameOver) {
this.cancelLoop();
return;
}
this.gameArea.initComponent();
this.gameArea.drawComponent();
this.gameArea.drawNextComponent();
return;
}
this.gameArea.eraseComponent();
this.gameArea.updateComponent()
this.gameArea.drawComponent();
};
window.GameConsole = GameConsole || {};
})();
|
// @flow
// Imports
// ==========================================================================
import chai, { expect } from 'chai';
import _ from '//src/nodash';
import t from 'tcomb';
import type { $Refinement } from 'tcomb';
import * as nrser from '//src/';
// Types
// ==========================================================================
declare function it(title: string, block: () => void): void;
function isErrorClass(obj: *): boolean {
return obj === Error || obj.prototype instanceof Error;
}
type ErrorClass = any & $Refinement<typeof isErrorClass>;
function hasEvenLength(array: Array<*>): boolean {
return array.length % 2 === 0;
}
type Pairable<V> = Array<V> & $Refinement<typeof hasEvenLength>;
// Private
// ==========================================================================
class Throws {
errorClass: ErrorClass;
pattern: ?RegExp;
constructor(errorClass: ErrorClass = Error, pattern?: RegExp) {
this.errorClass = errorClass;
this.pattern = pattern;
}
throwArgs() {
const args = [this.errorClass];
if (this.pattern) {
args.push(this.pattern);
}
return args;
}
}
// Exports
// ==========================================================================
// export * from './Describer';
/**
* OO structure for expectations.
*/
export class Expect<T> {
instanceOf: T;
props: Object;
size: number;
lengthOf: number;
constructor({
instanceOf,
props,
size,
lengthOf,
// members,
}: {
instanceOf: T,
props: Object,
size: number,
lengthOf: number,
}) {
this.instanceOf = instanceOf;
this.props = props;
this.size = size;
this.lengthOf = lengthOf;
// this.members = members;
}
test(actual: *): void {
if (this.instanceOf) {
expect(actual).to.be.instanceOf(this.instanceOf);
}
if (this.props) {
_.each(this.props, (value, name) => {
expect(actual).to.have.property(name);
if (value instanceof Expect) {
value.test(actual[name]);
} else {
expect(actual[name]).to.eql(value);
}
});
}
if (this.size) {
expect(_.size(actual)).to.equal(this.size);
}
if (this.lengthOf) {
expect(actual).to.have.lengthOf(this.lengthOf);
}
// TODO figure this out...
// if (this.members) {
// _.each(this.members, (value) => {
// if (value instanceof Expect) {
// expect(actual).to.have.any.member.that.satisfy()
// }
// });
// }
}
}
export function itMaps({
func,
map,
funcName = func.name ? func.name.replace('bound ', '') : 'f',
testMethod = 'eql',
tester = ({actual, expected, testMethod}) => {
if (expected instanceof Expect) {
expected.test(actual);
} else {
expect(actual).to[testMethod](expected);
}
},
formatArgs = (args: Array<*>, funcName: string): string => (
`${ funcName }(${ _.map(args, (a) => JSON.stringify(a)).join(", ") })`
),
formatExpected = (expected: *): string => {
const json = JSON.stringify(expected);
if (typeof json === 'string') {
return json;
}
return '???';
},
formatter = (args: Array<*>, expected: *, funcName: string): string => {
if (expected instanceof Throws) {
return nrser.squish`
${ formatArgs(args, funcName) }
throws
${ expected.errorClass.name }
`;
} else {
return nrser.squish`
maps
${ formatArgs(args, funcName) }
to ${ formatExpected(expected) }
`;
}
},
}: {
func: Function,
funcName?: string,
// the map is function that accepts two arguments:
map: (
// 1. a wrapper that converts it's arguments to an array to be fed into
// the test function
f: (...args: Array<*>) => Array<*>,
// 2. a function that creates a {Throws} to indicate the call should
// throw an error of a certain type with an optional pattern for the
// message
throws: (errorClass: ErrorClass, pattern?: RegExp) => Throws,
// and returns a array of even length that represents actual, expected pairs
) => Pairable<*>,
// the function the performs the assertions, the default implementation of
// which checks that the actual is deeply equal to the expected.
tester?: (pair: {actual: *, expected: *}) => void,
// a function to format the calling args for display
formatArgs?: (args: Array<*>, funcName: string) => string,
// a function to format the expected value
formatExpected?: (expected: *) => string,
// a function to format it all that calls the others by default
formatter?: (args: Array<*>, expected: *, funcName: string) => string,
}): void {
const mapping: Pairable<*> = map(
(...args) => args,
(errorClass, pattern) => new Throws(errorClass, pattern)
);
for (let i = 0; i < mapping.length; i += 2) {
const args = mapping[i];
const expected = mapping[i + 1];
it(formatter(args, expected, funcName), () => {
if (expected instanceof Throws) {
chai.expect(
() => func(...args)
).to.throw(expected.errorClass, expected.pattern);
} else {
tester({actual: func(...args), expected, testMethod});
}
})
}
}
|
import "./App.css";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import axios from "axios";
import Comments from "./Comments";
import Pagination from "./Pagination";
import Pagination2 from "./Pagination2";
import Button from "./button";
function App() {
//all the comments
const [comments, setComments] = useState([]);
const [loading, setLoading] = useState([false]);
const [currentPage, setCurrentPage] = useState(1);
const [commentsPerPage, setCommentsPerPage] = useState(15);
//including the empty dependency list makes useEffect behave like ComponentDidMount
useEffect(() => {
//api call to jsonplaceholder, need async/await
const getComments = async () => {
//loading data
setLoading(true);
const res = await axios.get(
"https://jsonplaceholder.typicode.com/comments"
);
setComments(res.data);
//done loading
setLoading(false);
};
getComments();
}, []);
//get the comments for the current page
const lastCommentIndex = currentPage * commentsPerPage;
const firstCommentIndex = lastCommentIndex - commentsPerPage;
const currentComments = comments.slice(firstCommentIndex, lastCommentIndex);
function paginate(pageObject) {
setCurrentPage(pageObject.selected + 1);
}
function paginate2(number) {
if (number > 0 && number <= Math.ceil(comments.length / commentsPerPage))
setCurrentPage(number);
}
return (
<Router>
<div className="App">
<h1>Comments</h1>
<Comments comments={currentComments} loading={loading} />
{/*<Button label="Cool Button" />*/}
<Switch>
<Route path="/react-paginate">
<Pagination
commentsPerPage={commentsPerPage}
totalComments={comments.length}
paginate={paginate}
currentPage={currentPage}
/>
</Route>
<Route path="/">
<Pagination2
commentsPerPage={commentsPerPage}
totalComments={comments.length}
paginate={paginate2}
currentPage={currentPage}
/>
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
|
import React from 'react'
import {Text,SafeAreaView} from 'react-native'
import CalculadoraCoder from './Components/Calculadora'
export default () => {
return (
<CalculadoraCoder/>
)
}
|
import {
rhythm,
scale,
colors,
fonts,
transitions
} from '../../../lib/traits'
export default {
root: {
fontFamily: fonts.display,
background: colors.maroon
},
wrapper: {
padding: rhythm(1),
maxWidth: '80rem',
margin: '0 auto',
textAlign: 'left'
},
title: {
fontSize: scale(4.5),
color: colors.light,
paddingTop: rhythm(1),
paddingBottom: rhythm(1)
},
events: {
display: 'block',
overflow: 'auto',
marginLeft: rhythm(-1),
marginRight: rhythm(-1),
lineHeight: 1.5
},
eventTileWrapper: {
display: 'inline-block',
float: 'left',
paddingLeft: rhythm(1),
paddingRight: rhythm(1),
marginBottom: rhythm(1),
width: '100% !important',
'@media screen and (min-width:60em)': {
width: '50% !important'
}
},
eventTile: {
background: colors.light,
padding: rhythm(1),
height: '28rem',
position: 'relative',
'@media screen and (min-width:60em)': {
height: '22rem'
}
},
eventTitle: {
fontSize: scale(3),
fontWeight: 'bold',
color: colors.orange,
verticalAlign: 'top'
},
eventDate: {
fontSize: scale(2),
color: colors.green
},
details: {
fontSize: scale(1),
color: colors.dark,
paddingBottom: rhythm(0.5)
},
buttonWrapper: {
position: 'absolute',
bottom: '2rem',
verticalAlign: 'bottom',
display: 'flex',
justifyContent: 'space-between',
flexDirection: 'row',
textAlign: 'center'
},
maroon: {
backgroundColor: colors.maroon,
flexGrow: '1',
display: 'inline-block',
lineHeight: 1,
marginTop: '0',
color: colors.light,
padding: `${rhythm(0.5, 'em')} ${rhythm(0.75, 'em')}`,
transition: `box-shadow ${transitions.easeOut}`,
':hover': {
boxShadow: `inset 0 0 0 ${rhythm(10)} rgba(0,0,0,0.2)`
}
},
orange: {
backgroundColor: colors.orange,
flexGrow: '1',
display: 'inline-block',
lineHeight: 1,
color: colors.light,
marginLeft: rhythm(1),
marginTop: '0 !important',
padding: `${rhythm(0.5, 'em')} ${rhythm(0.75, 'em')}`,
transition: `box-shadow ${transitions.easeOut}`,
':hover': {
boxShadow: `inset 0 0 0 ${rhythm(10)} rgba(0,0,0,0.2)`
}
}
}
|
'use strict'
const axios = require('axios')
const crypto = require('crypto')
const JPush = require('jpush-sdk')
module.exports = class Push {
constructor(config) {
this.config = config
this.client = JPush.buildClient(config.key, config.secret)
this.auth = new Buffer(config.key + ':' + config.secret).toString('base64')
this.http = axios.create({
baseURL: 'https://api.jpush.cn/v3/',
headers: {
Authorization: 'Basic ' + this.auth
}
})
}
async send(to, content, extra, options = {}) {
const {
platform = 'all'
} = options
const ret = this.client.push()
.setPlatform(platform)
.setAudience(to)
.setNotification(content)
.setMessage(content, null, 'text', extra)
.send((err, res) => {
if (err) {
// return console.log(err.message);
}
const PushModel = use('App/Models/Push')
PushModel.create({
platform,
to,
msg_id: res.msg_id,
content,
extra,
data: res,
success: true
})
log(res);
})
}
}
|
import React from 'react';
import PropTypes from "prop-types";
import {useSelector} from "react-redux";
import {gameSelectors} from "core/game";
export const Resource = ({resource}) => {
const value = useSelector((state) => gameSelectors.getResourceValue(state, resource));
const max = useSelector((state) => gameSelectors.getResourceMax(state, resource));
const perSec = useSelector((state) => gameSelectors.getResourcePerSecond(state, resource));
return (
<div>
<span>{value} / {max} ({perSec} /sec)</span>
<span>({resource})</span>
</div>
);
};
Resource.propTypes = {
resource: PropTypes.string.isRequired,
};
|
/*EXPECTED
hello
*/
class _Main {
static function hello () : void {
log "hello";
}
static function say () : void {
return _Main.hello();
}
static function main(args : string[]) : void {
_Main.say();
}
}
|
/**
* @properties={typeid:24,uuid:"5967688D-69EE-4A3A-80CA-F69FE64626E6"}
*/
function gotoEdit()
{
_super.gotoEdit();
controller.focusField(elements.fld_codice.getName(), true)
}
/**
* @param {JSFoundSet<db:/ma_anagrafiche/ditte_turni>} _foundset
* @param {String} [_program]
*
* @return {Number}
*
* @properties={typeid:24,uuid:"908F2C1B-D0E8-4791-A743-2C0529B0FEB2"}
*/
function dc_save_validate(_foundset, _program)
{
try
{
return (_super.dc_save_validate(_foundset,'AG_Req_Turno') !== -1 && globals.validaDittaTurno(_foundset.getSelectedRecord())) ? 0 : -1
}
catch(ex)
{
globals.ma_utl_showErrorDialog(ex.message);
return -1
}
}
|
export default {
// login
login: '/login', // 登陆 post
register: '/register', // 注册 post
resetLoginPassword: '/resetLoginPassword', // 忘记密码
getCodeForMobile: '/baseVerify/sendCodeForMobile', // 获取短信验证码 post
getVerifiCode: '/baseVerify/getVerifyCode', // 获取验证码 get
getLoginInfo: 'getLoginInfo', // 获取登陆信息
loginOut: 'loginOut', // 获取登出信息
getNewsList: '/news/getNewsList', // pc 首页新闻资讯展示
getHotList: '/news/getNewList', // 热点资讯展示 半年内最热5条
getCourseRecommended: '/courseInfo/getCourseRecommended', //首页4条推荐课
getInformationList: '/news/getAllNewsList', // 新闻资讯列表
getByNewsId: '/news/getByNewsId', // 根据id获取新闻详情
getSchoolList: '/school/getSchoolList', // 院校课程首页
getSchoolTakeList: '/school/getSchoolTakeList', // 院校课程首页
getByCourseId: '/courseInfo/getByCourseId', // 院校课程首页
getCourseCatalog: '/courseInfo/courseCatalog', // 获取课程目录
getAddCourseChapter: '/courseChapter/addCourseChapter', // 添加课程章节
getDeleteCourseChapter: '/courseChapter/deleteCourseChapter', // 删除章节
getDeleteCourseChaperVideo: '/courseChapterVideo/deleteCourseChapterVideo', // 删除小节
getAddCourseChaperVideo: '/courseChapterVideo/addCourseChapterVideo', // 添加视频
getUploadVideo: '/courseChapterVideo/uploadVideo', // 上传章节视频
getAddInspectionStandard: '/inspectionStandard/addInspectionStandard', // 添加课程考核
getUpdatePassword: '/account/updatePassword', // 修改用户密码
getUpdateUserName: '/account/updateUserName', // 更新用户名称
getVerifyCodeForMobile: '/baseVerify/verifyCodeForMobile', // 验证修改手机号验证旧手机
getUpdateMobile: '/account/updateMobile', // 更新手机号
getUploadUserPhoto: '/account/uploadUserPhoto', // 上传用户头像
getUpdateSex: '/account/updateSex', // 更新用户性别
getIdentityAuth: '/identityAuth', // 学生认证
getFindUserRoleInfo: '/user/findUserRoleInfo', // 认证成功用户信息
getFindBulletinPage: '/findBulletinPage', // 获取系统公告
getByInspectionStandardId: '/inspectionStandard/getByInspectionStandardId', // 获取考核详情
getCourseStudyProgress: '/courseStudyProgress/getCourseStudyProgress', // 查看用户中心我的学习进度
getAddStudyInfo: '/courseStudy/addStudyInfo', // 添加视频进度
getStudyInfo: '/courseStudy/getStudyInfo', // 根据用户id,课程id,视频id获取视频进度信息
getAddCourse: '/courseInfo/addCourse', // 添加课程
getFindCourseThreeList: '/courseType/findCourseThreeList', // 获取全部课程分类
getByAllTeacher: '/teacher/getByTeacher', // 获取所有学校所有老师
getAddCourseTeacher: '/courseTeacher/addCourseTeacher', // 添加课程关联老师
getAllCourseTeacherList: '/courseTeacher/getAllCourseTeacherList', // 根据课程id查询所有关联老师
getUpdateCourseTeacherDeleteFlag:
'/courseTeacher/updateCourseTeacherDeleteFlag', // 删除关联的课程老师
getUpdateMasterFlag: '/courseTeacher/updateMasterFlag', // 选择课程老师管理者
getAllCourseQuestionsList: '/courseQuestions/getAllCourseQuestionsList', // 根据课程id查询课程全部提问
getAddCourseQuestions: '/courseQuestions/addCourseQuestions', // 添加课程视频提问
getAllCourseQuestionsAnswers:
'/courseQuestionsAnswers/getAllCourseQuestionsList', // 根据问答id查询全部回复
getAddCourseQuestionsAnswers:
'/courseQuestionsAnswers/addCourseQuestionsAnswers', // 添加提问回复
getByMeCourseList: '/courseInfo/getByMeCourseList', // 教师用户中心我的课程
getCourseId: '/courseInfo/getCourseId', // 课程详情供修改课程使用
getUpdateCourse: '/courseInfo/updateCourse', // 保存修改课程信息
getDeleteCourse: '/courseInfo/deleteCourse', // 删除课程
// 根据isSign 获取 video auth
getVideoAuth: '/video/getVideoAuth',
// 二期功能
getQrImage: '/baseVerify/getQrImage', // 获取二维码
getFindOne: '/courseType/findOne', // 获取课程一级分类列表
getAllCourseRecommendedList: '/courseInfo/getAllCourseRecommendedList', //推荐课程列表
getAllCourseDataList: '/courseData/getAllCourseDataList', // 根据学校id获取全部资料
getAllCourseChapterList: '/courseChapter/getAllCourseChapterList', // 获取全部课程章节
getCourseDownList: '/courseInfo/courseDownList', // 课程下拉
getCourseChapterDownList: '/courseChapter/courseChapterDownList', // 章节下拉
getUpdateInspectionStandard: '/inspectionStandard/updateInspectionStandard', // 修改课程考核
getUpdateCourseChapter: '/courseChapter/updateCourseChapter', // 修改课程章节信息
getByCourseChapterId: '/courseChapter/getByCourseChapterId', // 根据id获取章节
getByCourseChapterVideoId: '/courseChapterVideo/getByCourseChapterVideoId', // 根据id获取子章节视频详情
getUpdateCourseChapterVideo: '/courseChapterVideo/updateCourseChapterVideo', // 修改视频
getAddCourseData: '/courseData/addCourseData', // 添加课程资料
getDeleteCourseData: '/courseData/deleteCourseData', //删除课程资料
getUpdateCourseData: '/courseData/updateCourseData', //修改课程资料
getDataStatistics: '/courseStudyProgress/dataStatistics', // 获取教师中心运行分析饼图数据
getAllStudyProgressList: '/courseStudyProgress/getAllStudyProgressList', // 获取教师中心成运行分析成绩列表
getScoreCount: '/courseScore/getScoreCount', // 获取教师中心成绩管理柱状图数据
getCourseScoreSum: '/courseScore/getCourseScoreSum', // 获取教师中心成绩管理最高分以及最低分
getAllCourseScoreList: '/courseScore/getAllCourseScoreList', // 获取教师中心成绩管理成绩列表
// 题库
getFindExamSubjectChoicesList:
'/examSubjectChoices/findExamSubjectChoicesList', // 选择题列表
getByExamSubjectChoicesId: '/examSubjectChoices/getByExamSubjectChoicesId', // 选择题详情
getDeleteExamSubjectChoices: '/examSubjectChoices/deleteExamSubjectChoices', // 删除选择题
getUpdateExamSubjectChoices: '/examSubjectChoices/updateExamSubjectChoices', // 修改选择题
getAddExamSubjectChoices: '/examSubjectChoices/addExamSubjectChoices', // 添加选择题
getByExamSubjectChoicesReleased:
'/examSubjectChoicesCopy/getByExamSubjectChoicesId', // 已发布课程的详情
getUpdateExamSubjectChoicesCopy:
'/examSubjectChoicesCopy/updateExamSubjectChoices', // 已发布课程的修改
getDeleteExamSubjectOptionCopy:
'/examSubjectOptionCopy/deleteExamSubjectOption', // 删除关联题目选项
getAddExamSubjectOptionCopy: '/examSubjectOptionCopy/addExamSubjectOption', // 添加关联题目选项
getDeleteExamSubjectOption: '/examSubjectOption/deleteExamSubjectOption', // 删除题目选项
getAddExamSubjectOption: '/examSubjectOption/addExamSubjectOption', // 添加题目选项
// 单元测试
getFindExamExaminationList: '/examination/findExamExaminationList', // 单元测试列表
getAddExamination: '/examination/addExamination', // 新建课程
getAllExaminationSubject: '/examinationSubject/getAllExaminationSubject', // 根据考试信息id 查询管理考试题目列表
getDeleteExaminationSubject: '/examinationSubject/deleteExaminationSubject', // 删除考试关联题目
getAddExaminationSubject: '/examinationSubject/addExaminationSubject', // 添加考试关联题目
getExaminationTwoList: '/examination/ExaminationTwoList', // 考试所有试卷
getByExaminationId: '/examination/getByExaminationId', // 考试信息详情
getAddExaminationRecord: '/examinationRecord/addExaminationRecord', // 添加考试记录
getSubjectExam: '/examAnswer/subjectExam', // 提交考试试卷
getUpdateExamination: '/examination/updateExamination', // 修改课程信息
getDeleteExamination: '/examination/deleteExamination', // 删除课程信息
getUpdateReleaseStatus: '/examination/updateReleaseStatus', // 取消发布
getAddExaminationPaper: '/examinationPaper/addExaminationPaper', // 添加历史试卷
// 消息通知
getAllSystemMsgList: '/messageInfo/getAllSystemMsgList',
getAllCourseMsgList: '/messageInfo/getAllCourseMsgList', // 课程公告
getCourseMsgList: '/messageInfo/getCourseMsgList', // 学习中心课程公告
getAddMessageInfo: '/messageInfo/addMessageInfo', // 添加学习中心课程公告
getByRecordId: '/examinationRecord/getByRecordId', // 试卷侧边栏的回显
getFindRecordList: '/examinationRecord/findRecordList', // 考试记录列表
// 支付页面
getOrderList: '/order/orderList', // 账户订单列表
getSelectByCourseId: '/courseInfo/selectByCourseId', // 订单课程详情展示
getOrderSuccess: '/order/orderSuccess', // 账户订单列表
getToOrderPay: '/order/toOrderPay', // 订单支付
getContinuePay: '/order/continuePay', // 继续订单支付
getDeleteOrder: '/order/deleteOrder', // 删除订单
getFindStudentOrderExist: '/courseStudyProgress/findStudentOrderExist', // 查看用户是否已购买此课程
// 首页轮播图
getAllAdvertisingList: '/adverting/getAllAdvertisingList', // 首页轮播图
getUploadRecognitionPhoto: '/user/uploadRecognitionPhoto', // 更新存储人脸识别头像
// 教师中心,学生管理
getFindStudentList: '/courseStudyProgress/findStudentList', // 教师中心学员管理列表
getDeleteTeacher: '/courseStudyProgress/deleteTeacher', // 教师中心学员管理退课
getSchoolTeacherList: '/school/getSchoolTeacherList', //教师中心引进课程列表
getAllCourseScoreListOne: '/courseScore/getAllCourseScoreListOne', //教师中心成绩管理引进课程成绩列表
getCourseScoreSumYinJin: '/courseScore/getCourseScoreSum', //教师中心成绩管理引进课程平均,最低,最高分统计,签名为课程id
getScoreCountOneYinJin: '/courseScore/getScoreCountOne', //教师中心成绩管理引进课程成绩柱状图,签名为课程id
getAllStudyProgressListOneYinJin:
'/courseStudyProgress/getAllStudyProgressListOne', //教师中心运行分析引进课程运行分析学习进度列表展示
getdataStatisticsOneYinJin: '/courseStudyProgress/dataStatisticsOne', //教师中心运行分析引进课程运行分析汇总统计
getFindRecordListOneYinJin: '/examinationRecord/findRecordListOne', //教师中心单元测试引进课程考试记录列表
getExaminationTwoListOneYinJin: '/examination/ExaminationTwoListOne', //教师中心单元测试引进课程考试试卷
}
|
import React from "react";
import { Link } from "react-router-dom";
import { makeStyles, Typography, Grid, Container } from "@material-ui/core";
const SectionOne = () => {
return (
<Grid container className="intro-text">
<Grid item xs={12} sm={12} md={12} lg={12}>
<Text />
</Grid>
</Grid>
);
};
export default SectionOne;
const useStyles = makeStyles({
style: {
color: "black",
padding: "1.5em",
fontSize: "1.4rem",
lineHeight: "2em",
},
});
const Text = () => {
const classes = useStyles();
return (
<Container>
<Typography paragraph component="p" className={classes.style}>
ברוכים הבאים לעולם הקסום שלי. כאן תוכלו למצוא לוכדי חלומות הנעשים בעבודת
יד עם המון אהבה.
<Link to="/shop"> בחנות </Link>
ישנו מגוון רחב של דגמי לוכדי חלומות. החל מסטים של לוכדי חלומות על ענף,
ועד ללוכדי חלומות קטנים לרכב או למחזיק מפתחות. הדגמים שלי יהפכו כל פינה
בבית לקסומה במיוחד שאף אחד לא יוכל לפספס. בנוסף, ישנה אפשרות לעצב ביחד
איתי את הדגם המושלם כך שיתאים בדיוק לפינה שלך בבית. אני אשמח לעזור לך
לבחור את בד הלוכד, דגם המפית, נוצות, ועוד מגוון עשיר של אפשרויות
לבחירתך.
</Typography>
</Container>
);
};
|
/* jshint node: true */
'use strict';
var path = require('path');
var fs = require('fs');
var Funnel = require('broccoli-funnel');
var unwatchedTree = require('broccoli-unwatched-tree');
var mergeTrees = require('broccoli-merge-trees');
var replace = require('broccoli-string-replace');
var stew = require('broccoli-stew');
module.exports = {
name: 'ember-reveal-js',
included: function(app/*, parentAddon*/) {
this._super.included(app);
if (app.import) {
this.importNpmDependencies(app);
}
},
importNpmDependencies: function(app/*, parentAddon*/) {
app.import('vendor/reveal.js/js/reveal.js');
app.import('vendor/reveal.js/lib/js/classList.js');
app.import('vendor/reveal.js/plugin/markdown/marked.js');
app.import('vendor/reveal.js/plugin/markdown/markdown.js');
app.import('vendor/reveal.js/plugin/highlight/highlight.js');
},
treeForVendor: function() {
return new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/',
destDir: '/reveal.js',
files: [
'js/reveal.js',
'lib/js/classList.js',
'plugin/markdown/marked.js',
'plugin/markdown/markdown.js',
'plugin/highlight/highlight.js'
]
});
},
treeForStyles: function(tree) {
tree = this._super.treeForStyles.apply(this, [tree]);
var addonThemesDir = 'app/styles/ember-reveal-js/css/theme/source';
var addonThemeFiles = fs.readdirSync(addonThemesDir);
var addonThemes = Array.prototype.map.call(addonThemeFiles, function(addonTheme) {
return addonTheme.split('.')[0];
});
addonThemes.push('ember');
var addonThemesScss = Array.prototype.map.call(addonThemes, function(addonTheme) {
return '$themeName: \'' + addonTheme + '\';\n' +
'@import \'css/theme/source/' + addonTheme + '\';\n\n';
}).join('');
addonThemesScss = '\n/* BEGIN ember-reveal-js-addon-themes */\n' + addonThemesScss;
addonThemesScss += '/* END ember-reveal-js-addon-themes */\n';
var stylesTree = replace(tree, {
files: [
'app/styles/ember-reveal-js/ember-reveal-js-themes.scss'
],
pattern: {
match: /\/\*__ember-reveal-js-addon-themes__\*\//g,
replacement: addonThemesScss
}
});
var revealCssTree = new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/css',
destDir: '/app/styles/ember-reveal-js/css',
include: [
'reveal.scss',
'theme/**/*.scss'
]
});
var replaceCssTree = replace(revealCssTree, {
files: [
'app/styles/ember-reveal-js/css/theme/template/theme.scss',
'app/styles/ember-reveal-js/css/theme/source/*.scss'
],
patterns: [
{
match: /\.reveal/g,
replacement: '.#{$themeName}.reveal'
},
{
match: /body \{/g,
replacement: '.#{$themeName}.reveal {'
},
{
match: /\.\.\/\.\.\/lib\/font/g,
replacement: 'ember-reveal-js/lib/font'
}
]
});
replaceCssTree = replace(replaceCssTree, {
files: [
'app/styles/ember-reveal-js/css/reveal.scss'
],
patterns: [
{
match: /html, body,/g,
replacement: 'html.reveal, body.reveal,'
}
]
});
var revealPrintCssTree = new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/css/print',
destDir: '/app/styles/ember-reveal-js/css/print'
});
revealPrintCssTree = stew.rename(revealPrintCssTree, '.css', '.scss');
var fontCssTree = new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/lib/font',
destDir: '/app/styles/ember-reveal-js/lib/font',
files: [
'league-gothic/league-gothic.css',
'source-sans-pro/source-sans-pro.css'
]
});
var highlightJsTree = new Funnel(unwatchedTree(path.dirname(require.resolve('highlight.js/package.json'))), {
srcDir: '/styles',
destDir: '/app/styles/ember-reveal-js/highlight.js'
});
highlightJsTree = stew.rename(highlightJsTree, '.css', '.scss');
return mergeTrees([
stylesTree,
replaceCssTree,
fontCssTree,
revealPrintCssTree,
highlightJsTree
], {
overwrite: true
}
);
},
treeForPublic: function() {
var assetsPath = path.join(__dirname, 'public');
var assetsTree = new Funnel(this.treeGenerator(assetsPath), {
srcDir: '/',
destDir: '/assets/ember-reveal-js'
});
var fontTree = new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/lib/font',
destDir: '/assets/ember-reveal-js/lib/font'
});
var pluginTree = new Funnel(unwatchedTree(path.dirname(require.resolve('reveal.js/package.json'))), {
srcDir: '/plugin',
destDir: '/assets/ember-reveal-js/plugin'
});
var classListTree = new Funnel(unwatchedTree(path.dirname(require.resolve('highlight.js/package.json'))), {
srcDir: '/lib/js',
destDir: '/assets/ember-reveal-js/lib/js'
});
return mergeTrees([
fontTree,
pluginTree,
classListTree,
assetsTree
]);
},
isDevelopingAddon: function() {
return true;
}
};
|
import React, { Children, Component } from 'react'
import cn from 'classnames'
class Row extends Component {
static defaultProps = {
style: {},
}
shouldComponentUpdate(nextProps) {
return nextProps.style.paddingRight !== this.props.style.paddingRight
|| nextProps.rowData !== this.props.rowData
}
getColumnWidth(width) {
if (typeof width === 'string') {
return width
}
return `${width}px`
}
getFlexStyleForColumn(column) {
const flexValue = `${column.props.flexGrow} ${column.props.flexShrink} ${this.getColumnWidth(column.props.width)}`
const style = {
flex: flexValue,
msFlex: flexValue,
WebkitFlex: flexValue,
}
if (column.props.maxWidth) {
style.maxWidth = column.props.maxWidth
}
if (column.props.minWidth) {
style.minWidth = column.props.minWidth
}
return style
}
renderColumn(column, columnIndex, rowData, rowIndex) {
const {
cellClassName,
cellDataGetter,
columnData,
dataKey,
cellRenderer,
...options,
} = column.props
const cellData = cellDataGetter(dataKey, rowData, columnData, columnIndex, rowIndex)
const renderedCell = cellRenderer(cellData, dataKey, rowData, rowIndex, columnData, columnIndex, options)
const style = this.getFlexStyleForColumn(column)
return (
<div
key={`Row${rowIndex}-Col${columnIndex}`}
className={cn('FlexTable__rowColumn', cellClassName)}
style={style}
>
{renderedCell}
</div>
)
}
renderColumns(columns, rowData, rowIndex) {
return Children.toArray(columns).map(
(column, columnIndex) => this.renderColumn(
column,
columnIndex,
rowData,
rowIndex
)
)
}
render() {
const { columns, rowData, rowIndex, ...props } = this.props
return (
<div {...props}>
{this.renderColumns(columns, rowData, rowIndex)}
</div>
)
}
}
export default Row
|
import { useState } from "react";
import "../css/NavBar.css";
import { Link } from "react-router-dom";
import { HamburgerSlider as Hamburger } from "../../node_modules/react-animated-burgers";
const NavBar = () => {
const [open, setOpen] = useState(false);
function toggle() {
setOpen(!open);
}
function close() {
setTimeout(() => {
setOpen(false);
}, 200);
}
function buttons(active) {
if (active) {
return (
<>
<Link to="/" onClick={() => close()}>
Home
</Link>
<Link to="/activities" onClick={() => close()}>
Give Your Time
</Link>
<Link to="/rewards" onClick={() => close()}>
Get Rewards
</Link>
<Link to="/myaccount" onClick={() => close()}>
My Account
</Link>
</>
);
}
}
return (
<div className="nav-container">
<div className="nav-bar" id="myNavBar">
<Hamburger isActive={open} toggleButton={toggle} barColor="white" />
{buttons(open)}
</div>
</div>
);
};
export default NavBar;
|
const express = require('express');
const PORT = process.env.PORT || 3001;
const jobRouter = require('./routes/jobRouter')
const userRouter = require('./routes/userRouter')
const recruiterRouter = require('./routes/recruiterRouter')
const cors = require('cors')
const bodyParser = require('body-parser');
const logger = require('morgan');
const app = express();
app.use(cors())
app.use(logger('dev'));
app.use(bodyParser.json());
// routes
app.use('/recruiters', recruiterRouter);
// app.use('/recruiters', recruiterRouter);
// app.use('/recruiters/:recruiterId/jobs', jobRouter);
app.use('/jobs', jobRouter);
app.use('/auth', userRouter);
// error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(err.message);
});
app.listen(PORT, () => {
console.log(`wingRecruiter is transmitting from port: ${PORT}`);
});
|
import { Axes } from '@nivo/axes';
import { ResponsiveLine } from '@nivo/line';
import { computeXYScalesForSeries } from '@nivo/scales';
import PropTypes from 'prop-types';
import React from 'react';
import { hashMemo } from '@/utils/hashData';
import injectStyles from '@/utils/injectStyles';
import { COLORS, NIVO_CHART_THEME } from '@/utils/styleConstants';
import LineChartWithBarTooltip from './elements/LineChartWithBarTooltip';
import styles from './styles';
/* eslint-disable react/prop-types */
const LactateAxis = ({ data, innerWidth, innerHeight }) => {
const { xScale, yScale } = computeXYScalesForSeries(
[data[0]],
{ type: 'point' },
{
type: 'linear',
min: 0,
max: data[0].y2Max
},
innerWidth,
innerHeight
);
return (
<Axes
key="custom_axis_lactate"
xScale={xScale}
yScale={yScale}
width={innerWidth}
height={innerHeight}
right={{
legend: data[0].legend2,
legendOffset: 43,
legendPosition: 'middle',
orient: 'left',
tickSize: 5
}}
/>
);
};
/* eslint-disable react/prop-types */
const BarLayer = ({ data, xScale }) => (
<svg style={{ font: '13px sans-serif', color: 'white' }} xmlns="http://www.w3.org/2000/svg">
{data[0].barData.map(value => {
const yBottom = 205; // отступ до нижней оси
const YHeightMax = 100; // максимальная высота столбика
const valueMax = data[0].y2Max / 2; // значение максимального столбца
const height = (YHeightMax * value.value) / valueMax;
const realY = yBottom - height;
const Answer = [];
Answer.push(
<rect
key={`${value.x}bar`}
x={xScale(value.x) - 50}
y={realY}
width={100}
height={height}
fill={COLORS.CHARTS.HISTOGRAM.BLUE}
/>
);
Answer.push(
<text
key={`${value.x}bar text`}
x={xScale(value.x) - (value.value > 99 ? 15 : 9)}
y={realY + height / 2}
>
{' '}
{value.value}{' '}
</text>
);
return Answer;
})}
</svg>
);
const LineChartWithBar = ({ className, data, legend, units, chartColor }) => (
<div className={className}>
{ data.length && <ResponsiveLine
data={data}
margin={{ top: 20, right: 50, bottom: 50, left: 50 }}
// xFormat="time:%d.%m.%Y"
xScale={{
type: 'point',
min: 'auto',
max: 'auto'
// format: '%Y-%m-%dT%H:%M:%S',
// precision: 'minute'
}}
yFormat={value => (units ? `${value} ${units}` : value)}
yScale={{
type: 'linear',
stacked: true,
min: data[0].yMin,
max: data[0].yMax
}}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 5, // размер палка
tickPadding: 12, // отступ
tickValues: 4,
legend: 'Нагрузка, кг',
legendOffset: 40,
legendPosition: 'middle'
}}
axisLeft={{
legend: `${legend}, ${units}`,
legendOffset: -43,
legendPosition: 'middle',
orient: 'left',
tickPadding: 8,
tickRotation: 0,
tickSize: 0,
tickValues: 8
}}
layers={[
BarLayer,
'markers',
'axes',
LactateAxis,
'areas',
'crosshair',
'lines',
'points',
'slices',
'mesh',
'legends'
]}
colors={[chartColor]}
pointSize={8}
pointColor="white"
pointBorderWidth={2}
pointBorderColor={{ from: 'serieColor' }}
pointLabelYOffset={-12}
useMesh
enableSlices={false}
theme={NIVO_CHART_THEME}
animate={false}
tooltip={LineChartWithBarTooltip}
/>}
</div>
);
LineChartWithBar.propTypes = {
className: PropTypes.string.isRequired,
// Used by StyledComponent
height: PropTypes.string, // eslint-disable-line react/no-unused-prop-types
data: PropTypes.array,
legend: PropTypes.string.isRequired,
units: PropTypes.string,
chartColor: PropTypes.string
};
LineChartWithBar.defaultProps = {
data: [],
height: '300px',
units: '',
chartColor: COLORS.CHARTS.PRIMARY
};
LineChartWithBar.displayName = 'LineChartWithBarComponent';
LineChartWithBar.whyDidYouRender = true;
export default injectStyles(hashMemo(LineChartWithBar), styles);
|
import {Component} from '../../Component.js';
/**
* Create an ECharts based LineChart component.
*
*/
export class LineChart extends Component {
/**
*
* Create a new instance of a ECharts LineChart component.
*
* @param {Object} opts - The configuration of the Component.
* @param {string|jquerySelection} [opts.parent] - A string or jquery
* selection indicating the DOM node which this component is to be
* attached.
* @param {string} [opts.id] - The id of this component. Defaults to
* dex-chart-echarts-linechart.
* @param {string} [opts.class] - The class of this component. Used
* when alternate CSS styling is to be employed. Default value is
* dex-chart-echarts-linechart.
* @param {Object} [opts.dimension] - The x, y, and color dimensions for
* this chart.
* @param {Object} [opts.dimension.color] - The color dimension for this
* chart.
* @param {string} [opts.dimension.color.type] - The color type. "category"
* by default.
* @param {number} [opts.dimension.color.index] - The column index in the
* csv data to use for coloring.
* @param {Object} [opts.dimension.x] - The x dimension of this chart.
* @param {string} [opts.dimension.x.type] - The type of X dimension. "value" is
* the default.
* @param {number} [opts.dimension.x.index] - The column index in the csv data
* to use for the X dimension.
* @param {Object} [opts.dimension.y] - The y dimension of this chart.
* @param {string} [opts.dimension.y.type] - The type of Y dimension. "value" is
* the default.
* @param {number} [opts.dimension.y.index] - The column index in the csv data
* to use for the Y dimension.
*
* @return {LineChart} Returns a new LineChart instance.
*
*/
constructor(opts) {
var base = {
"parent": undefined,
"id": "dex-chart-echarts-linechart",
"class": "dex-chart-echarts-linechart",
"dimension": {
color: {type: "category", index: 0},
x: {type: "value", index: 1},
y: {type: "value", index: 2}
},
"palette": "ECharts",
"dimensions": {"series": 0, "x": 1, "y": 2},
"options": {
"xAxis.nameLocation": "middle",
"yAxis.nameLocation": "middle",
"yAxis.nameTextStyle": {"color": "red", "fontSize": 24},
"xAxis.nameTextStyle": {"color": "red", "fontSize": 24}
}
};
super(new dex.Configuration(base).overlay(opts));
if (csv.header && csv.header.length >= 3) {
this.set("options.title.text",
csv.header[this.get("dimension.x.index")] + " vs " +
csv.header[this.get("dimension.y.index")] + " by " +
csv.header[this.get("dimension.color.index")])
}
this.initialize()
}
/**
*
* Return the gui definition after having overlaid the supplied
* configuration options.
*
* @param {Object} opts - The supplied configuration options.
*
* @returns {Object} Returns the gui definition after having overlaid
* the supplied configuration options.
*
*/
getGuiDefinition(opts = {}) {
var base = super.getGuiDefinition();
var defaults = {
"type": "group",
"name": "EChart Line Chart Settings",
"contents": [
{
"type": "group",
"name": "General Options",
"contents": [
dex.config.gui.echartsTitle({}, "options.title"),
dex.config.gui.echartsGrid({}, "options.grid"),
dex.config.gui.echartsTooltip({}, "options.tooltip"),
dex.config.gui.echartsSymbol({}, "series"),
dex.config.gui.columnDimensions({},
"dimensions",
this.get("csv"),
this.get("dimensions")),
{
"name": "Color Scheme",
"description": "The color scheme.",
"target": "palette",
"type": "choice",
"choices": dex.color.colormaps({shortlist: true}),
"initialValue": "ECharts"
},
{
"name": "Display Legend",
"description": "Determines whether or not to draw the legend or not.",
"type": "boolean",
"target": "options.legend.show",
"initialValue": true
},
{
"name": "Background Color",
"description": "The color of the background.",
"target": "options.backgroundColor",
"type": "color",
"initialValue": "#000000"
},
{
"name": "Series Type",
"description": "The series type",
"type": "choice",
"target": "series.type",
"choices": ["line", "scatter", "effectScatter", "bar"]
},
{
"name": "Stack Series",
"description": "Stack the series or not.",
"type": "boolean",
"target": "series.stack",
"initialValue": false
},
{
"name": "Clip Overflow",
"description": "Clip overflow.",
"type": "boolean",
"target": "series.clipOverflow",
"initialValue": true
},
{
"name": "Connect Nulls",
"description": "Connect nulls.",
"type": "boolean",
"target": "series.connectNulls",
"initialValue": false
},
{
"name": "Step",
"description": "Stack the series or not.",
"type": "boolean",
"target": "series.step",
"initialValue": false
}
]
},
dex.config.gui.echartsLabelGroup({}, "series.label"),
{
"type": "group",
"name": "Axis",
"contents": [
dex.config.gui.echartsAxis({name: "X Axis"}, "options.xAxis"),
dex.config.gui.echartsDataZoom({name: "X Axis Data Zoom"}, "xAxisDataZoom"),
dex.config.gui.echartsAxis({name: "Y Axis"}, "options.yAxis"),
dex.config.gui.echartsDataZoom({name: "Y Axis Data Zoom"}, "yAxisDataZoom"),
]
}
]
};
var guiDef = dex.object.expandAndOverlay(opts, defaults, base);
//dex.config.gui.sync(this, guiDef);
return guiDef;
};
/**
*
* Initialize the LineChart. If the chart is attached to the DOM
* document, then the chart will initialize echarts and update it.
*
* @returns {LineChart} The LineChart is returned to the caller.
*
*/
initialize() {
// If we are attached to a dom element
if ($.contains(document, this.$root[0])) {
this.internalChart = echarts.init(this.$root[0]);
this.update();
}
return this;
}
/**
*
* Resize the chart.
*
* @returns {LineChart} The LineChart is returned.
*
*/
resize() {
this.internalChart.resize();
return this;
}
/**
*
* Add click events.
*
* @returns {LineChart} The LineChart is returned.
*
*/
enableClickEvent() {
dex.addClickEvent(this);
return this;
}
/**
*
* A click event.
*
* @returns {LineChart} The LineChart is returned.
*
*/
click() {
return this;
}
/**
*
* Update the chart.
*
* @returns {LineChart} The LineChart is returned.
*
*/
update() {
super.update();
let options = this.calculateOptions();
//dex.log("New Options", options)
//notMerge = true preserves the transition
// Otherwise, this.internalChart.clear()
this.internalChart.setOption(options, true)
this.internalChart.resize();
return this;
}
/**
*
* Used internally to calculate the various charting options
* based upon the user settings.
*
* @returns {Object} The calculated options are returned.
*/
calculateOptions() {
let config = this.config.config;
let csv = config.csv;
//dex.log("OVERLAYING-OPTIONS", config.options)
let options = dex.object.expandAndOverlay(config.options, {
color: dex.color.palette[config.palette],
legend: {show: true, type: "scroll"},
title: {text: ""},
dataZoom: [
{
orient: "horizontal",
show: true,
realtime: true,
start: 0,
end: 100,
xAxisIndex: 0
},
{
orient: "vertical",
show: true,
realtime: true,
start: 0,
end: 100,
yAxisIndex: 0
},
],
xAxis: {
type: config.dimension.x.type,
name: csv.header[config.dimension.x.index]
},
yAxis: {
type: config.dimension.y.type,
name: csv.header[config.dimension.y.index]
},
tooltip: {
trigger: 'axis'
},
series: []
});
var types = csv.guessTypes()
//dex.log("TYPES", types);
if (types[config.dimension.x.index] == "string") {
options.xAxis.type = "category"
}
if (types[config.dimension.y.index] == "string") {
options.yAxis.type = "category"
}
// Figure out if we can lay this chart out by groups.
var groups = csv.group([config.dimension.color.index]);
var xs = groups.map(function (group, gi) {
return group.csv.column(config.dimension.x.index)
});
var EQUAL_GROUPS = true;
for (var i = 1; i < xs.length; i++) {
if (!dex.array.equal(xs[i - 1], xs[i - 1])) {
EQUAL_GROUPS = false;
break;
}
}
if (EQUAL_GROUPS) {
//options.tooltip.trigger = "axis"
// Lay out a single x axis series with y data arrays.
options.xAxis.data = xs[0];
groups.forEach(function (group) {
var series = dex.object.expandAndOverlay(config.series, {
"name": group.key,
"type": 'line',
"data": group.csv.column(config.dimension.y.index)
})
options.series.push(series);
})
} else {
//options.tooltip.trigger = "item";
_.uniq(csv.column(config.dimension.color.index)).forEach(function (name) {
let series = csv.selectRows(function (row) {
return row[config.dimension.color.index] === name
}).include([config.dimension.x.index, config.dimension.y.index]);
options.series.push(
dex.object.expandAndOverlay(config.series, {name: name, type: 'line', data: series.data}));
});
}
//dex.log("OPTIONS", options);
//dex.log(JSON.stringify(options));
return options;
}
}
|
const brand_name = document.getElementById("brand-name");
const login_link = document.getElementById("login-link");
const register_link = document.getElementById("register-link");
brand_name.addEventListener("mouseover", () => {
brand_name.id = "brand-name-hover-active";
});
brand_name.addEventListener("mouseout", () => {
brand_name.id = "brand-name";
});
login_link.addEventListener("mouseover", () => {
login_link.id = "login-link-hover";
});
login_link.addEventListener("mouseout", () => {
login_link.id = "login-link";
});
register_link.addEventListener("mouseover", () => {
register_link.id = "register-link-hover";
});
register_link.addEventListener("mouseout", () => {
register_link.id = "register-link";
});
login_link.addEventListener("click", () => {
login_link.id = "login-link-click";
});
register_link.addEventListener("click", () => {
register_link.id = "register-link-click";
});
|
//var V = {};
var Model = function ( Character, meshs, txt ) {
THREE.Group.call( this );
this.visible = false;
this.isFirstFrame = true;
this.isFirstPlay = false;
this.is3dNoz = false;
this.character = Character;
this.isLockHip = true;
this.isSkeleton = false;
this.rShadow = false;
// sphere, tube, skin
this.bodyType = 'sphere';
this.txt = txt;
this.mats = [];
this.currentPlay = '';
//this.decal = new THREE.Vector3();
//this.position = new THREE.Vector3();
this.baseMat = new THREE.MeshBasicMaterial();
this.baseMatS = new THREE.MeshBasicMaterial({color:0x00ff00, skinning:true });
this.tSize = 1.4;
this.torad = 0.0174532925199432957;
this.hipPos = new THREE.Vector3();
// 1 - BONES
if( this.character === 'Amina' ) this.mesh = meshs.skin_a.clone();
else this.mesh = meshs.skin.clone();
//this.add( this.mesh );
this.mesh.material = this.baseMatS;
this.bones = this.mesh.skeleton.bones;
var i, name, bone, lng = this.bones.length;
this.mtx = new THREE.Matrix4();
// this.matrixWorldInv = new THREE.Matrix4().getInverse( this.mesh.matrixWorld );
this.matrixWorldInv = new THREE.Matrix4().getInverse( this.matrixWorld );
this.poseMatrix = [];
this.b = {};
for( i=0; i<lng; i++){
bone = this.bones[i];
name = bone.name;
//console.log(name)
this.b[ name ] = bone;
this.poseMatrix[i] = bone.matrixWorld.clone();
if( name === 'hip' ) this.hipPos.setFromMatrixPosition( this.poseMatrix[i] );
}
this.mesh.userData.posY = this.hipPos.y;
//this.mesh.setTimeScale( 0.25 );
//this.position.y = this.hipPos.y;
// 2 - ROOT
//this.root = new THREE.Group();
// 3 - BODY
this.dressMesh = null;
switch( this.bodyType ){
case 'sphere':
this.bodygeo = new THREE.SphereBufferGeometry( 23.5, 24, 18 );
this.bodygeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,0,1), 90*this.torad));
this.bodygeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(1,0,0), -90*this.torad));
this.bodygeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,1,0), -14*this.torad));
this.bodygeo.applyMatrix( new THREE.Matrix4().makeTranslation(-2,0,0));
if( this.character === 'Amina' ) this.bodygeo.applyMatrix( new THREE.Matrix4().makeScale(1,0.9,0.9));
this.rondoMesh = new THREE.Mesh( this.bodygeo, this.baseMat );
if( this.character === 'Amina' ){
var dress = new THREE.CylinderBufferGeometry(14,22, 24,24,1 )
dress.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,0,1), 90*this.torad));
dress.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(1,0,0), -90*this.torad));
dress.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,1,0), -14*this.torad));
//dress.applyMatrix( new THREE.Matrix4().makeTranslation(12,0,0));
this.dressMesh = new THREE.Mesh( dress, this.baseMat );
this.dressMesh.position.set( 10, 0,4);
this.rondoMesh.add(this.dressMesh);
}
this.attach( this.rondoMesh, this.b.chest );
break;
case 'tube':
this.tubeSize = 23;
this.bodygeo = new THREE.Tubular( { start:[0,0,0], end:[0,40,0], numSegment:4 }, 30, this.tubeSize, 20 ,false, 'sphere' );
this.rondoMesh = new THREE.Mesh( this.bodygeo, this.baseMat );
this.cax = new THREE.Matrix4().makeTranslation(4,0,0);
this.cbx = new THREE.Matrix4().makeTranslation(-8,0, 0);
this.ccx = new THREE.Matrix4().makeTranslation(-10,0,0);
this.cdx = new THREE.Matrix4().makeTranslation(-25,0,0);
break;
case 'skin':
this.rondoMesh = this.mesh;
break;
}
this.rondoMesh.castShadow = true;
this.rondoMesh.receiveShadow = this.rShadow;
// 3 - HEAD
var headGeo = new THREE.SphereBufferGeometry( 14.5, 20, 15 );
var hearGeo = new THREE.SphereBufferGeometry( 1.6, 12, 9 );
headGeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,0,1), 90*this.torad));
headGeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(1,0,0), -90*this.torad));
headGeo.applyMatrix( new THREE.Matrix4().makeTranslation(-14.5,0,0));
this.headMesh = new THREE.Mesh(headGeo, this.baseMat );
this.hearL = new THREE.Mesh(hearGeo, this.baseMat );
this.hearR = new THREE.Mesh(hearGeo, this.baseMat );
this.hearL.position.set(-14.5, 14.9, 0)
this.hearR.position.set(-14.5, -14.9, 0)
this.attach( this.headMesh, this.b.head );
this.headMesh.castShadow = true;
this.headMesh.receiveShadow = this.rShadow;
if(this.is3dNoz){
this.headNoz = meshs.noz.clone();
this.headNoz.position.set(-14.5,0, 0)
this.headMesh.add( this.headNoz );
}
// 4 - EXTRA
this.headExtra = null;
this.headHair = null;
if( this.character === 'Theo' ){
this.headExtra = meshs.extra_man.clone();
this.headMesh.add( this.headExtra );
} else {
//if(this.bodyType==='skin'){
if(this.character === 'Cynthia') this.headHair = meshs.extra_hair_c.clone();
if(this.character === 'Amina') this.headHair = meshs.extra_hair_a.clone();
if(this.character === 'Eleanor') this.headHair = meshs.extra_hair_c.clone();
this.headHair.skeleton = this.mesh.skeleton;
this.add( this.headHair );
/*}else{
this.headExtra = meshs.extra_wom.clone();
this.headMesh.add( this.headExtra );
}*/
}
// 5 - FOOT
var foot = meshs.foot;
if( this.character === 'Amina' ){ foot = meshs.foot_w; this.tSize = 1; }
this.footR = foot.clone();
this.footL = foot.clone();
this.attach( this.footR, this.b.rFoot );
this.attach( this.footL, this.b.lFoot );
this.footR.castShadow = true;
this.footR.receiveShadow = this.rShadow;
this.footL.castShadow = true;
this.footL.receiveShadow = this.rShadow;
// 6 - HAND
var hand = new THREE.SphereBufferGeometry( 2.5, 12, 9 );
hand.translate( -1.5,0,0 );
this.handL = new THREE.Mesh( hand, this.baseMat );
this.handR = new THREE.Mesh( hand, this.baseMat );
this.attach( this.handL, this.b.lHand );
this.attach( this.handR, this.b.rHand );
this.handL.castShadow = true;
this.handL.receiveShadow = this.rShadow;
this.handR.castShadow = true;
this.handR.receiveShadow = this.rShadow;
// 7 - LEG
this.legL = new THREE.Tubular( { start:[0,0,0], end:[0,-40,0], numSegment:3 }, 12, this.tSize );
this.legmeshL = new THREE.Mesh( this.legL, this.baseMat );
this.legR = new THREE.Tubular( { start:[0,0,0], end:[0,-40,0], numSegment:3 }, 12, this.tSize );
this.legmeshR = new THREE.Mesh( this.legR, this.baseMat );
this.ggg = new THREE.Matrix4().makeTranslation(0,0,-2);
this.fff = new THREE.Matrix4()
if( this.character === 'Amina' ) this.fff.makeTranslation(2,0,-3);
// 8 - ARM
this.arm = new THREE.Tubular( { start:[0,40,0], end:[0,0,0], numSegment:8 }, 20, this.tSize );
this.armmesh = new THREE.Mesh( this.arm, this.baseMat );
this.armmesh.castShadow = true;
this.armmesh.receiveShadow = this.rShadow;
var py = 2
if( this.character === 'Amina' )py = 5;
this.dda = new THREE.Matrix4().makeTranslation(-2,py,0);
this.ddd = new THREE.Matrix4().makeTranslation(-2,-py,0);
this.ddxr = new THREE.Matrix4().makeTranslation(-3,1,0);
this.ddxl = new THREE.Matrix4().makeTranslation(-3,-1,0);
this.legmeshL.castShadow = true;
this.legmeshL.receiveShadow = this.rShadow;
this.legmeshR.castShadow = true;
this.legmeshR.receiveShadow = this.rShadow;
// 9 - ADD
this.headMesh.add( this.hearL );
this.headMesh.add( this.hearR )
this.addEyebow();
this.addEyes();
if( this.character !== 'Theo' ) this.addEarring();
this.add( this.footR );
this.add( this.footL );
this.add( this.handR );
this.add( this.handL );
this.add( this.armmesh );
this.add( this.legmeshL );
this.add( this.legmeshR );
this.add( this.headMesh );
this.add( this.mesh );
if( this.bodyType!=='skin' ){
this.mesh.visible = false;
this.add( this.rondoMesh );
}
this.setMaterial(3);
//this.matrixWorld = this.mesh.matrixWorld;
//this.matrixAutoUpdate = false;
//this.matrixWorldNeedsUpdate = false;
//this.position = this.mesh.position;
}
Model.prototype = Object.assign( Object.create( THREE.Group.prototype ), {
constructor: Model,
//constructor: THREE.Group,
//isGroup: true,
setSize: function ( s ) {
if(this.character === 'Amina') s-=0.002;
this.mesh.scale.set(s,s,s);
if(this.headHair)this.headHair.scale.set(s,s,s);
this.arm.radius = this.tSize*s;
this.legR.radius = this.tSize*s;
this.legL.radius = this.tSize*s;
if( this.bodyType === 'tube') this.bodygeo.radius = this.tubeSize*s;
},
setPosition: function ( x, y, z ) {
this.mesh.position.set(x,y,z);
},
setRotation: function ( x, y, z ) {
this.mesh.rotation.set(x,y,z);
},
/*getDecal: function () {
return this.decal.y;
},
setDecal: function ( v ) {
this.decal.y = v;
this.mesh.position.copy( this.position ).add( this.decal );
},*/
attach: function ( m, b ) {
m.matrix = b.matrixWorld;
m.matrixAutoUpdate = false;
},
addEarring: function () {
var earringGeo;
if(this.character === 'Cynthia') earringGeo = new THREE.SphereBufferGeometry( 0.8, 12, 9 );
else earringGeo = new THREE.TorusBufferGeometry( 2, 0.2, 6, 20 );
earringGeo.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(1,0,0), -90*this.torad));
this.earringL = new THREE.Mesh( earringGeo, this.baseMat );
this.earringR = new THREE.Mesh( earringGeo, this.baseMat );
this.earringL.position.set(-14.5+2, 14.9, -1)
this.earringR.position.set(-14.5+2, -14.9,-1)
this.headMesh.add( this.earringL );
this.headMesh.add( this.earringR );
},
addEyebow: function () {
var w = 2.5;
var h = 0.6;
var r = 0.75;
var g = new THREE.CapsuleBufferGeometry( r, w );
g.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,1,0), -90*this.torad));
this.bowL = new THREE.Mesh( g, this.baseMat );
this.bowR = new THREE.Mesh( g, this.baseMat );
this.bowL.rotation.x = 26*this.torad;
this.bowR.rotation.x = -26*this.torad;
this.bowL.rotation.y = 12*this.torad;
this.bowR.rotation.y = 12*this.torad;
this.bowL.position.set( -19, 5.7,-12.3 );
this.bowR.position.set( -19,-5.7,-12.3 );
this.headMesh.add( this.bowL );
this.headMesh.add( this.bowR );
},
addEyes : function () {
var eye = new THREE.SphereBufferGeometry( 0.75, 8, 6 );
var er = new THREE.Mesh( eye, this.baseMat );
var el = new THREE.Mesh( eye, this.baseMat );
er.position.set( -14.5,5.7,-13.4 );
el.position.set( -14.5,-5.7,-13.4 );
if( this.character !== 'Theo' ){
var c = new THREE.CylinderBufferGeometry(0.14, 0.14, 1), mr, ml;
c.applyMatrix( new THREE.Matrix4().makeRotationAxis( new THREE.Vector3(0,0,1), 90*this.torad));
c.applyMatrix( new THREE.Matrix4().makeTranslation( -1.2, 0, 0 ));
for(var i=0; i<3; i++){
mr = new THREE.Mesh( c, this.baseMat );
ml = new THREE.Mesh( c, this.baseMat );
mr.rotation.z = -(i * 30) * this.torad;
ml.rotation.z = (i * 30) * this.torad;
er.add( mr );
el.add( ml );
}
}
this.headMesh.add( er );
this.headMesh.add( el );
this.eyeR = er;
this.eyeL = el;
},
addSkeleton: function ( b ) {
if( b ){
this.isSkeleton = true;
this.helper = new THREE.SkeletonHelper( this.b.hip );
this.helper.skeleton = this.mesh.skeleton;
this.add( this.helper );
} else {
if(this.isSkeleton){
this.remove( this.helper );
this.isSkeleton = false;
}
}
},
lockHip: function ( b ) {
this.isLockHip = b;
},
setTimescale: function ( v ) {
this.mesh.setTimeScale( v );
},
reset:function(){
this.mesh.stopAll();
var i, name, bone, lng = this.bones.length;
for( i=0; i<lng; i++){
bone = this.bones[i];
bone.matrixWorld.copy( this.poseMatrix[i] );
}
},
dispose: function (){
},
/*addToScene: function ( Scene ){
Scene.add( this.mesh );
Scene.add( this.root );
//if( !this.isSkin ) this.bodygeo.addDebug( Scene );
this.isFull = true;
},
removeFromScene: function( Scene ){
Scene.remove( this.mesh );
Scene.remove( this.root );
//if( this.type !== 'man') Scene.remove( this.plus );
this.isFull = false;
},*/
stop: function (){
this.mesh.stopAll();
},
play: function ( name, crossfade, offset, weight ){
if( name !== this.currentPlay ){
this.currentPlay = name;
this.mesh.play( this.currentPlay, crossfade, offset, weight );
this.isFirstPlay = true;
}
},
getTime: function () {
return this.mesh.currentAnimationAction ? this.mesh.currentAnimationAction.time : false;
},
setWirframe: function ( b ) {
i = this.mats.length;
while(i--) this.mats[i].wireframe = b;
},
setMaterial: function( n, m, r, e ){
var i;
if(!n){
i = this.mats.length;
while(i--){
if( m !== undefined ) this.mats[i].metalness = m;
if( r !== undefined ) this.mats[i].roughness = r;
if( e !== undefined ) this.mats[i].emissiveIntensity = e;
}
return;
}
var mtype = 'MeshBasicMaterial'
this.colors = {
// [ 0 m_skin , 1 m_hair, 2 skin , 3 hair , 4 extra, 5 foot , 6 arm , 7 leg , 8 earring, 9 noz ]
'Theo' : [ 'corps_t', 'head_t', 0xb1774f, 0x613207, 0x111111, 0x050505, 0x000044, 0x000044, 0xeeee00, 0xa36d47 ],
'Amina' : [ 'corps_a', 'head_a', 0x9d6743, 0x0a0704, 0x0a0704, 0x050505, 0x9d6743, 0x9d6743, 0xeeee00, 0x895a39 ],
'Cynthia' :[ 'corps_c', 'head_c', 0x895837, 0x3a160a, 0x3a160a, 0x0f0f0f, 0x1c1c1c, 0x1c1c1c, 0xeeeeee, 0x70472b ],
'Eleanor' :[ 'corps_e', 'head_e', 0x895837, 0x824683, 0x3a160a, 0x0f0f0f, 0xb8cdae, 0x1c1c1c, 0xeeee00, 0xa36d47 ],
}
var cc = this.colors[ this.character ];
if( this.bodyType === 'skin' ) this.txt[cc[0]].flipY = false;
i = this.mats.length;
while(i--){
this.mats[i].dispose();
}
if( n===1 ) mtype = 'MeshLambertMaterial';
if( n===2 ) mtype = 'MeshToonMaterial';
if( n===3 ) mtype = 'MeshStandardMaterial';
this.mats[0] = new THREE[mtype]({ color: cc[4] });// extra
this.mats[1] = new THREE[mtype]({ color: cc[5] });// foot
this.mats[2] = new THREE[mtype]({ color: cc[6] });// arm
this.mats[3] = new THREE[mtype]({ color: cc[2] });// skin
this.mats[4] = new THREE[mtype]({ color:0xffffff, map: this.txt[cc[1]] });// head
this.mats[5] = new THREE[mtype]({ color:0xffffff, map: this.txt[cc[0]] });// body
this.mats[6] = new THREE[mtype]({ color: cc[7] });// arm
this.mats[7] = new THREE[mtype]({ color: 0x020202 });// eye
this.mats[8] = new THREE[mtype]({ color: cc[3] });// bow
this.mats[9] = new THREE[mtype]({ color: cc[8] });// earring
this.mats[10] = new THREE[mtype]({ color: cc[3] });// hair
this.mats[11] = new THREE[mtype]({ color: cc[9] });// hair
if( n===1 || n===3 ){
i = this.mats.length;
while(i--){
if( i === 4 )this.mats[i].emissiveMap = this.txt[cc[1]];
else if( i === 5 )this.mats[i].emissiveMap = this.txt[cc[0]];
this.mats[i].emissive = this.mats[i].color;
this.mats[i].emissiveIntensity = 0.5;
if(n===3){
this.mats[i].metalness = m !== undefined ? m : 0.25;
this.mats[i].roughness = r !== undefined ? r : 0.5;
this.mats[i].envMap = this.txt.env //view.envmap; //
}
}
}
i = this.mats.length;
while(i--) this.mats[i].shadowSide = false;
if( this.character !== 'Theo' ) this.mats[10].skinning = true;
if( this.bodyType === 'skin' ){
this.mats[5].skinning = true;
}
this.headMesh.material = this.mats[4];
this.hearL.material = this.mats[3];
this.hearR.material = this.mats[3];
this.footR.material = this.mats[1];
this.footL.material = this.mats[1];
this.handL.material = this.mats[3];
this.handR.material = this.mats[3];
if( this.headExtra ) this.headExtra.material = this.mats[0];
if( this.headHair ) this.headHair.material = this.mats[10];
this.armmesh.material = this.mats[2];
this.legmeshL.material = this.mats[6];
this.legmeshR.material = this.mats[6];
this.rondoMesh.material = this.mats[5];
this.bowL.material = this.mats[8];
this.bowR.material = this.mats[8];
this.eyeR.material = this.mats[7];
this.eyeL.material = this.mats[7];
if( this.is3dNoz ) this.headNoz.material = this.mats[11];
if( this.dressMesh ) this.dressMesh.material = this.mats[7];
i = this.eyeR.children.length;
while (i--){
this.eyeR.children[i].material = this.mats[7];
this.eyeL.children[i].material = this.mats[7];
}
if( this.character !== 'Theo' ){
this.earringL.material = this.mats[9];
this.earringR.material = this.mats[9];
}
},
getHipPos: function () {
return this.b.hip.getWorldPosition();
},
//----------------------------------------------------------
updateMatrix: function () {
this.mesh.position.copy(this.position);
this.mesh.quaternion.copy(this.quaternion);
//this.matrix.compose( this.position, this.quaternion, this.scale );
//this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ){
/*if( this.isLockHip ){
this.b.hip.position.x = 0;
this.b.hip.position.z = 0;
}*/
//
if( this.dressMesh ){
this.dressMesh.rotation.y = -this.b.abdomen.rotation.y;//this.b.hip.rotation.y
//this.dressMesh.quaternion.copy(this.b.hip.quaternion)
}
if( this.bodyType === 'tube' ){
this.bodygeo.rotations[0].setFromRotationMatrix( this.b.hip.matrixWorld.clone().multiply( this.cax ) );
this.bodygeo.rotations[1].setFromRotationMatrix( this.b.abdomen.matrixWorld.clone().multiply( this.cbx ) );
this.bodygeo.rotations[2].setFromRotationMatrix( this.b.chest.matrixWorld.clone().multiply( this.ccx ) );
this.bodygeo.rotations[3].setFromRotationMatrix( this.b.chest.matrixWorld.clone().multiply( this.cdx ) );
this.bodygeo.positions[0].setFromMatrixPosition( this.b.hip.matrixWorld.clone().multiply( this.cax ) );
this.bodygeo.positions[1].setFromMatrixPosition( this.b.abdomen.matrixWorld.clone().multiply( this.cbx ) );
this.bodygeo.positions[2].setFromMatrixPosition( this.b.chest.matrixWorld.clone().multiply( this.ccx ) );
this.bodygeo.positions[3].setFromMatrixPosition( this.b.chest.matrixWorld.clone().multiply( this.cdx ) );
this.bodygeo.updatePath( false );
}
this.legL.positions[0].setFromMatrixPosition( this.b.lThigh.matrixWorld );
this.legL.positions[1].setFromMatrixPosition( this.b.lShin.matrixWorld.clone().multiply( this.ggg ) );
this.legL.positions[2].setFromMatrixPosition( this.b.lFoot.matrixWorld.clone().multiply( this.fff ) );
this.legL.updatePath();
this.legR.positions[0].setFromMatrixPosition( this.b.rThigh.matrixWorld );
this.legR.positions[1].setFromMatrixPosition( this.b.rShin.matrixWorld.clone().multiply( this.ggg ) );
this.legR.positions[2].setFromMatrixPosition( this.b.rFoot.matrixWorld.clone().multiply( this.fff ) );
this.legR.updatePath();
this.arm.positions[0].setFromMatrixPosition( this.b.lHand.matrixWorld );
this.arm.positions[1].setFromMatrixPosition( this.b.lForeArm.matrixWorld.clone().multiply(this.ddxl) );
this.arm.positions[2].setFromMatrixPosition( this.b.lShldr.matrixWorld.clone().multiply(this.dda) );
this.arm.positions[3].setFromMatrixPosition( this.b.lCollar.matrixWorld );
this.arm.positions[4].setFromMatrixPosition( this.b.rCollar.matrixWorld );
this.arm.positions[5].setFromMatrixPosition( this.b.rShldr.matrixWorld.clone().multiply(this.ddd) );
this.arm.positions[6].setFromMatrixPosition( this.b.rForeArm.matrixWorld.clone().multiply(this.ddxr) );
this.arm.positions[7].setFromMatrixPosition( this.b.rHand.matrixWorld );
this.arm.updatePath();
THREE.Group.prototype.updateMatrixWorld.call( this, force );
if( !this.isFirstFrame && !this.visible ) this.visible = true;
if( this.isFirstPlay && !this.visible ) this.isFirstFrame = false;
}
});
|
import routerx from 'express-promise-router';
import phoneRouter from '../apps/phone/url';
const router = routerx();
router.use('/phone', phoneRouter);
export default router;
|
$( ".flag" ).click(function() {
$("#content-flag").attr("style", "display:block!important");
});
function selectedPrefix(obj){
var prefix = $(obj).data('prefix-flag');
var pais = $(obj).data('pais');
var host = "http://"+window.location.host;
$("#content-flag").attr("style", "display:none!important");
document.getElementById("phone").value = prefix;
$(".flag img").attr("src", host+"/img/flags/"+pais+".png");
//document.getElementById("flag").src = host+"/img/flags/"+pais+".png";
}
|
import './App.css';
import { Box, Button, Card, CssBaseline, Input, List } from '@material-ui/core';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { AppContext } from './context/AppContext';
import Messages from './components/Messages';
import io from "socket.io-client";
const App = () => {
const [messages, setMessages] = useContext(AppContext);
const [message, setMessage] = useState('');
const socket = useRef(null);
useEffect(() => {
socket.current = io.connect('http://localhost:3001');
return () => {
socket.disconnect();
}
}, []);
useEffect(() => {
socket.current.on('message', (message) => {
setMessages([...messages, message]);
});
}, [messages, setMessages]);
const sendMessage = (e) => {
e.preventDefault();
if (message !== '') {
socket.current.emit('message', message);
setMessage('');
}
}
const handleInput = (e) => {
setMessage(e.target.value);
}
const handleEnterKey = (e) => {
if (e.key === 'Enter') {
sendMessage(e);
}
}
return (
<React.Fragment>
<CssBaseline />
<Box className="App"
color="primary">
<Card className="cardMessages">
<List>
<Messages messages={messages} />
</List>
</Card>
<Card className="cardInput">
<Input className="input"
placeholder="Enter a message"
value={message}
onChange={handleInput}
onKeyPress={handleEnterKey}
/>
<Button className="button"
variant="contained"
color="primary"
onClick={sendMessage}
>Send</Button>
</Card>
</Box>
</React.Fragment>
);
};
export default App;
|
let commonConfig = require('./webpack.common.js');
let webpack = require('webpack');
let webpackMerge = require('webpack-merge');
let helpers = require('../helpers');
let config = webpackMerge(commonConfig,
{
plugins: [
new webpack.optimize.UglifyJsPlugin({
parallel:true,
mangle:false,
sourceMap: true,
compress: {
warnings: false
}
}),
]
});
module.exports = config;
|
import config from './config'
import { stopSubmit } from 'redux-form'
import { createActions } from '../common/actions'
const prefix = 'AUTH/'
const actions = [
'LOG_IN',
'SET_USER',
'LOG_OUT'
]
export const Actions = createActions(prefix, actions)
export const ActionCreators = {
loginUser: (username, password, redirect) => ({ type: Actions.LOG_IN, username, password, redirect }),
setUser: (user) => ({ type: Actions.SET_USER, user }),
logoutUser: () => ({ type: Actions.LOG_OUT }),
clearLoginError: () => stopSubmit(config.entityName, null)
}
|
import styled from 'styled-components';
export const FiltersConatiner = styled.div`
display: flex;
flex-direction: row;
width: 485px;
justify-content: space-between;
`;
|
import React from "react";
import { Route } from 'react-router-dom';
//import MuseumDetailPage from "./pages/MuseumDetailPage.js";
//import { Route, Switch } from "react-router-dom";
import MuseumListContainer from "./component/MuseumList/MuseumListContainer";
import MuseumDetailContainer from "./component/MuseumDetail/MuseumDetailContainer";
import RoomDetailContainer from "./component/RoomDetail/RoomDetailContainer";
import './style/common.scss';
const App = () => {
return (
<div>
<Route path="/" component={MuseumListContainer} exact={true} />
<Route path="/museum-detail/:museumIDparam" component={MuseumDetailContainer}/>
<Route path="/room-detail/:roomIDparam" component={RoomDetailContainer}/>
</div>
);
};
export default App;
|
import cartItem from './cart-item.component.jsx';
export default cartItem;
|
import { useEffect, useState } from "react";
import { useFavorites } from "../../contexts/FavoriteContext";
import "./styles.css";
export const FeaturedMovie = ({ item }) => {
const { favorites, setFavorites } = useFavorites();
const [inList, setInList] = useState(false);
let releaseDate = new Date(item.first_air_date);
let genres = [];
for (let i in item.genres) {
genres.push(item.genres[i].name);
}
const handleAddFavorite = (data) => {
let aux = favorites;
if (isAlreadyInMemo(data)) {
const filtered = aux.filter((item) => {
return data.id !== item.id;
});
setFavorites(filtered);
setInList(false);
alert("Removido com sucesso!");
} else {
aux.push(data);
setFavorites(aux);
setInList(true);
alert("Adicionado com sucesso!");
}
localStorage.setItem("favorites", JSON.stringify(favorites));
};
const isAlreadyInMemo = (data) => {
const reference = JSON.parse(localStorage.getItem("favorites"));
if (!reference) {
return false;
} else {
return auxIsAlreadyInMemo(data, reference);
}
};
const auxIsAlreadyInMemo = (data, list) => {
list = list.filter((item) => {
return data.id === item.id;
});
return list.length > 0;
};
useEffect(() => {
const loadSave = () => {
console.log("renderizei.");
isAlreadyInMemo(item) ? setInList(true) : setInList(false);
};
loadSave();
}, [setInList]);
return (
<section
className="featured"
style={{
backgroundSize: "cover",
backgroundPosition: "center",
backgroundImage: `url(https://image.tmdb.org/t/p/original${item.backdrop_path})`,
}}
>
<div className="featured--vertical">
<div className="featured--horizontal">
<div className="featured--name">{item.original_name}</div>
<div className="featured--info">
<div className="featured--point">{item.vote_average} pontos</div>
<div className="featured--year">{releaseDate.getFullYear()}</div>
<div className="featured--seasons">
{item.number_of_seasons} temporada
{item.number_of_seasons !== 1 ? "s" : ""}
</div>
<div className="featured--description">{item.overview}</div>
<div className="featured--buttons">
<a href={`/watch/${item.id}`}>
{" "}
<span>►</span> Assistir
</a>
<a
href={`list/add/${item.id}`}
onClick={(event) => {
event.preventDefault();
handleAddFavorite(item);
}}
>
{!inList && (
<span id="featured--add-button">+ Minha Lista</span>
)}
{inList && (
<span id="featured--add-button">- Remover da lista</span>
)}
</a>
</div>
<div className="featured--genres">
<strong>Gêneros: </strong>
{genres.join(", ")}
</div>
</div>
</div>
</div>
</section>
);
};
|
import React from "react";
import isEqual from "lodash/isEqual";
import ImagePlaceholder from "../../bezopComponents/Images/ImagePlaceholder";
import { getJsonString } from "../../helpers/logic";
import Validator from "../../helpers/validator";
import { Grid, withStyles, Paper } from "../../../node_modules/@material-ui/core";
import GridItem from "../../components/Grid/GridItem";
import Card from "../../components/Card/Card";
import CardHeader from "../../components/Card/CardHeader";
import CardBody from "../../components/Card/CardBody";
import CustomInput from "../../components/CustomInput/CustomInput";
import Button from "../../components/CustomButtons/Button";
const ProductsStyle = {
cardCategoryWhite: {
"&,& a,& a:hover,& a:focus": {
color: "white",
margin: "0",
fontSize: "14px",
marginTop: "0",
marginBottom: "0",
},
"& a,& a:hover,& a:focus": {
color: "#FFFFFF",
},
},
cardTitleWhite: {
color: "#FFFFFF",
marginTop: "0px",
minHeight: "auto",
fontWeight: "300",
fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
marginBottom: "3px",
textDecoration: "none",
"& small": {
color: "#777",
fontSize: "65%",
fontWeight: "400",
lineHeight: "1",
},
},
spacer: {
marginTop: "10px",
marginBottom: "10px",
},
innerSpacer: {
padding: "15px",
},
buttonPosition: {
display: "flex",
alignItems: "center",
justifyContent: "center",
},
propertyPosition: {
display: "flex",
alignItems: "center",
},
};
class GeneralSettings extends React.Component {
constructor(props) {
super(props);
const vendorProfile = getJsonString(localStorage["bezop-login:vendor"], "profile");
this.state = {
vendor: vendorProfile,
generalSetting: {
email: Validator.propertyExist(vendorProfile, "email") ? vendorProfile.email : "",
googleAnalytics: {
trackingId: Validator.propertyExist(vendorProfile, "googleAnalytics", "trackingId") ? vendorProfile.googleAnalytics.trackingId : "",
},
},
};
}
componentWillReceiveProps(newProps) {
const { vendorProfile } = this.props;
if (Validator.propertyExist(newProps, "vendorProfile", "getImageUpdate")
&& !isEqual(newProps.vendorProfile.getImageUpdate, vendorProfile.getImageUpdate)) {
if (typeof newProps.vendorProfile.getImageUpdate === "string") {
return false;
}
this.setState({
vendor: newProps.vendorProfile.getImageUpdate,
});
const updatedAdminProfile = { ...JSON.parse(localStorage["bezop-login:vendor"]), ...{ profile: newProps.vendorProfile.getImageUpdate } };
localStorage.setItem("bezop-login:vendor", JSON.stringify(updatedAdminProfile));
}
if (Validator.propertyExist(newProps, "vendorProfile", "updateProfile")
&& !isEqual(newProps.vendorProfile.updateProfile, vendorProfile.updateProfile)) {
if (typeof newProps.vendorProfile.updateProfile === "string") {
return false;
}
const updatedVendorProfile = { ...JSON.parse(localStorage["bezop-login:vendor"]), ...{ profile: newProps.vendorProfile.updateProfile } };
localStorage.setItem("bezop-login:vendor", JSON.stringify(updatedVendorProfile));
}
return false;
}
handleChange = (e) => {
this.setGeneralSettings(e.target.name, e.target.value);
}
setGeneralSettings = (name, value) => {
const { generalSetting } = this.state;
const newGeneralSettings = JSON.parse(JSON.stringify(generalSetting));
const names = name.split("|");
switch (names.length) {
case 1:
newGeneralSettings[names[0]] = value;
break;
case 2:
newGeneralSettings[names[1]][names[0]] = value;
break;
case 3:
newGeneralSettings[names[2]][names[1]][names[0]] = value;
break;
default:
break;
}
this.setState({
generalSetting: newGeneralSettings,
});
}
onSubmitGeneralSettings = () => {
const { updatedVendorProfile } = this.props;
const { generalSetting } = this.state;
if (updatedVendorProfile) {
updatedVendorProfile(generalSetting);
}
}
render() {
const { vendor, generalSetting } = this.state;
const { postImage, classes } = this.props;
return (
<Grid container>
<GridItem xs={12} sm={12} md={12}>
<Card>
<CardHeader color="primary">
<h4 className={classes.cardTitleWhite}>
General Settings
</h4>
</CardHeader>
<CardBody>
<Paper className={classes.innerSpacer}>
{
vendor
? (
<ImagePlaceholder
srcImage={vendor.frontend.logo}
postImage={postImage}
eachData={vendor}
collection="vendor"
label="logo|frontend"
fileInput="logoFrontend"
height={200}
width={200}
aspect
imageCenter
/>
) : null
}
</Paper>
<Paper className={`${classes.spacer} ${classes.innerSpacer}`}>
<Grid container>
<GridItem xs={12} sm={12} md={5} className={classes.propertyPosition}>
<h4>
Google Analytics Tracking ID
</h4>
</GridItem>
<GridItem xs={12} sm={12} md={5}>
<CustomInput
labelText="Google Analytics Tracking ID"
id="trackingID"
formControlProps={{
fullWidth: true,
}}
inputProps={{
value: generalSetting.googleAnalytics.trackingId,
name: "trackingId|googleAnalytics",
onChange: this.handleChange,
}}
/>
</GridItem>
<GridItem xs={12} sm={12} md={2} className={classes.buttonPosition}>
<Button
color="primary"
style={{ marginTop: "20px" }}
onClick={this.onSubmitGeneralSettings}
>
Update
</Button>
</GridItem>
</Grid>
</Paper>
</CardBody>
</Card>
</GridItem>
</Grid>
);
}
}
export default withStyles(ProductsStyle)(GeneralSettings);
|
var frontexpress = (function () {
'use strict';
/**
* HTTP method list
* @private
*/
var HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
// not supported yet
// HEAD', 'CONNECT', 'OPTIONS', 'TRACE';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* Middleware object.
* @public
*/
var Middleware = function () {
/**
* Middleware initialization
*
* @param {String} middleware name
*/
function Middleware() {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
classCallCheck(this, Middleware);
this.name = name;
}
/**
* Invoked by the app before an ajax request is sent or
* during the DOM loading (document.readyState === 'loading').
* See Application#_callMiddlewareEntered documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
createClass(Middleware, [{
key: 'entered',
value: function entered(request) {}
/**
* Invoked by the app before a new ajax request is sent or before the DOM is unloaded.
* See Application#_callMiddlewareExited documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
}, {
key: 'exited',
value: function exited(request) {}
/**
* Invoked by the app after an ajax request has responded or on DOM ready
* (document.readyState === 'interactive').
* See Application#_callMiddlewareUpdated documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
}, {
key: 'updated',
value: function updated(request, response) {}
/**
* Invoked by the app when an ajax request has failed.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
}, {
key: 'failed',
value: function failed(request, response) {}
/**
* Allow the hand over to the next middleware object or function.
*
* Override this method and return `false` to break execution of
* middleware chain.
*
* @return {Boolean} `true` by default
*
* @public
*/
}, {
key: 'next',
value: function next() {
return true;
}
}]);
return Middleware;
}();
/**
* Module dependencies.
* @private
*/
/**
* Route object.
* @private
*/
var Route = function () {
/**
* Initialize the route.
*
* @private
*/
function Route(router, uriPart, method, middleware) {
classCallCheck(this, Route);
this.router = router;
this.uriPart = uriPart;
this.method = method;
this.middleware = middleware;
this.visited = false;
}
/**
* Return route's uri.
*
* @private
*/
createClass(Route, [{
key: 'uri',
get: function get$$1() {
if (!this.uriPart && !this.method) {
return undefined;
}
if (this.uriPart instanceof RegExp) {
return this.uriPart;
}
if (this.router.baseUri instanceof RegExp) {
return this.router.baseUri;
}
if (this.router.baseUri) {
var baseUri = this.router.baseUri.trim();
if (this.uriPart) {
return (baseUri + this.uriPart.trim()).replace(/\/{2,}/, '/');
}
return baseUri;
}
return this.uriPart;
}
}]);
return Route;
}();
/**
* Router object.
* @public
*/
var error_middleware_message = 'method takes at least a middleware';
var Router = function () {
/**
* Initialize the router.
*
* @private
*/
function Router(uri) {
classCallCheck(this, Router);
this._baseUri = uri;
this._routes = [];
}
/**
* Do some checks and set _baseUri.
*
* @private
*/
createClass(Router, [{
key: '_add',
/**
* Add a route to the router.
*
* @private
*/
value: function _add(route) {
this._routes.push(route);
return this;
}
/**
* Gather routes from routers filtered by _uri_ and HTTP _method_.
*
* @private
*/
}, {
key: 'routes',
value: function routes(application, request) {
request.params = request.params || {};
var isRouteMatch = application.get('route matcher');
return this._routes.filter(function (route) {
return isRouteMatch(request, route);
});
}
/**
* Gather visited routes from routers.
*
* @private
*/
}, {
key: 'visited',
value: function visited() {
return this._routes.filter(function (route) {
return route.visited;
});
}
/**
* Use the given middleware function or object on this router.
*
* // middleware function
* router.use((req, res, next) => {console.log('Hello')});
*
* // middleware object
* router.use(new Middleware());
*
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'use',
value: function use(middleware) {
if (!(middleware instanceof Middleware) && typeof middleware !== 'function') {
throw new TypeError(error_middleware_message);
}
this._add(new Route(this, undefined, undefined, middleware));
return this;
}
/**
* Use the given middleware function or object on this router for
* all HTTP methods.
*
* // middleware function
* router.all((req, res, next) => {console.log('Hello')});
*
* // middleware object
* router.all(new Middleware());
*
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'all',
value: function all() {
var _this = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _toParameters = toParameters(args),
middleware = _toParameters.middleware;
if (!middleware) {
throw new TypeError(error_middleware_message);
}
HTTP_METHODS.forEach(function (method) {
_this[method.toLowerCase()].apply(_this, args);
});
return this;
}
}, {
key: 'baseUri',
set: function set$$1(uri) {
if (!uri) {
return;
}
if (!this._baseUri) {
this._baseUri = uri;
return;
}
if (_typeof(this._baseUri) !== (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
throw new TypeError('router cannot mix regexp and uri');
}
}
/**
* Return router's _baseUri.
*
* @private
*/
,
get: function get$$1() {
return this._baseUri;
}
}]);
return Router;
}();
HTTP_METHODS.forEach(function (method) {
/**
* Use the given middleware function or object, with optional _uri_ on
* HTTP methods: get, post, put, delete...
* Default _uri_ is "/".
*
* // middleware function will be applied on path "/"
* router.get((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/" and
* router.get(new Middleware());
*
* // middleware function will be applied on path "/user"
* router.post('/user', (req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/user" and
* router.post('/user', new Middleware());
*
* @param {String} uri
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
* @public
*/
var methodName = method.toLowerCase();
Router.prototype[methodName] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _toParameters2 = toParameters(args),
baseUri = _toParameters2.baseUri,
middleware = _toParameters2.middleware;
if (!middleware) {
throw new TypeError(error_middleware_message);
}
if (baseUri && this._baseUri && this._baseUri instanceof RegExp) {
throw new TypeError('router cannot mix uri/regexp');
}
this._add(new Route(this, baseUri, method, middleware));
return this;
};
});
function routeMatcher(request, route) {
// check if http method are equals
if (route.method && route.method !== request.method) {
return false;
}
// route and uri not defined always match
if (!route.uri || !request.uri) {
return true;
}
//remove query string and anchor from uri to test
var match = /^(.*)\?.*#.*|(.*)(?=\?|#)|(.*[^\?#])$/.exec(request.uri);
var baseUriToCheck = match[1] || match[2] || match[3];
// if route is a regexp path
if (route.uri instanceof RegExp) {
return baseUriToCheck.match(route.uri) !== null;
}
// if route is parameterized path
if (route.uri.indexOf(':') !== -1) {
var decodeParmeterValue = function decodeParmeterValue(v) {
return !isNaN(parseFloat(v)) && isFinite(v) ? Number.isInteger(v) ? Number.parseInt(v, 10) : Number.parseFloat(v) : v;
};
// figure out key names
var keys = [];
var keysRE = /:([^\/\?]+)\??/g;
var keysMatch = keysRE.exec(route.uri);
while (keysMatch != null) {
keys.push(keysMatch[1]);
keysMatch = keysRE.exec(route.uri);
}
// change parameterized path to regexp
var regExpUri = route.uri
// :parameter?
.replace(/\/:[^\/]+\?/g, '(?:\/([^\/]+))?')
// :parameter
.replace(/:[^\/]+/g, '([^\/]+)')
// escape all /
.replace('/', '\\/');
// checks if uri match
var routeMatch = baseUriToCheck.match(new RegExp('^' + regExpUri + '$'));
if (!routeMatch) {
return false;
}
// update params in request with keys
request.params = Object.assign(request.params, keys.reduce(function (acc, key, index) {
var value = routeMatch[index + 1];
if (value) {
value = value.indexOf(',') !== -1 ? value.split(',').map(function (v) {
return decodeParmeterValue(v);
}) : value = decodeParmeterValue(value);
}
acc[key] = value;
return acc;
}, {}));
return true;
}
// if route is a simple path
return route.uri === baseUriToCheck;
}
/**
* Module dependencies.
* @private
*/
var Requester = function () {
function Requester() {
classCallCheck(this, Requester);
}
createClass(Requester, [{
key: 'fetch',
/**
* Make an ajax request.
*
* @param {Object} request
* @param {Function} success callback
* @param {Function} failure callback
* @private
*/
value: function fetch(request, resolve, reject) {
var method = request.method,
uri = request.uri,
_request$headers = request.headers,
headers = _request$headers === undefined ? [] : _request$headers,
data = request.data;
var fail = function fail(_ref) {
var status = _ref.status,
statusText = _ref.statusText,
errorThrown = _ref.errorThrown;
reject(request, {
status: status,
statusText: statusText,
errorThrown: errorThrown,
errors: 'HTTP ' + status + ' ' + (statusText ? statusText : '')
});
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
//XMLHttpRequest.DONE
if (xmlhttp.status === 200) {
resolve(request, {
status: 200,
statusText: 'OK',
responseText: xmlhttp.responseText
});
} else {
fail({
status: xmlhttp.status,
statusText: xmlhttp.statusText
});
}
}
};
try {
xmlhttp.open(method, uri, true);
Object.keys(headers).forEach(function (header) {
return xmlhttp.setRequestHeader(header, headers[header]);
});
xmlhttp.send(data);
} catch (errorThrown) {
fail({ errorThrown: errorThrown });
}
}
}]);
return Requester;
}();
var httpGetTransformer = {
uri: function uri(_ref2) {
var _uri = _ref2.uri,
headers = _ref2.headers,
data = _ref2.data;
if (!data) {
return _uri;
}
var uriWithoutAnchor = _uri,
anchor = '';
var match = /^(.*)(#.*)$/.exec(_uri);
if (match) {
var _$exec = /^(.*)(#.*)$/.exec(_uri);
var _$exec2 = slicedToArray(_$exec, 3);
uriWithoutAnchor = _$exec2[1];
anchor = _$exec2[2];
}
return '' + uriWithoutAnchor + (uriWithoutAnchor.indexOf('?') === -1 ? '?' : '&') + encodeURIObject(data) + anchor;
}
};
var encodeURIObject = function encodeURIObject(obj) {
var branch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var results = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (obj instanceof Object) {
Object.keys(obj).forEach(function (key) {
var newBranch = new (Function.prototype.bind.apply(Array, [null].concat(toConsumableArray(branch))))();
newBranch.push(key);
encodeURIObject(obj[key], newBranch, results);
});
return results.join('&');
}
if (branch.length > 0) {
results.push('' + encodeURIComponent(branch[0]) + branch.slice(1).map(function (el) {
return encodeURIComponent('[' + el + ']');
}).join('') + '=' + encodeURIComponent(obj));
} else if (typeof obj === 'string') {
return obj.split('').map(function (c, idx) {
return idx + '=' + encodeURIComponent(c);
}).join('&');
} else {
return '';
}
};
var httpPostPatchTransformer = {
data: function data(_ref3) {
var _data = _ref3.data;
if (!_data) {
return _data;
}
return encodeURIObject(_data);
},
headers: function headers(_ref4) {
var uri = _ref4.uri,
_headers = _ref4.headers,
data = _ref4.data;
var updatedHeaders = _headers || {};
if (!updatedHeaders['Content-Type']) {
updatedHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
return updatedHeaders;
}
};
/**
* Module dependencies.
* @private
*/
function errorIfNotFunction(toTest, message) {
if (typeof toTest !== 'function') {
throw new TypeError(message);
}
}
function errorIfNotHttpTransformer(toTest) {
if (!toTest || !toTest.uri && !toTest.headers && !toTest.data) {
throw new TypeError('setting http transformer one of functions: uri, headers, data is missing');
}
}
/**
* Settings object.
* @private
*/
var Settings = function () {
/**
* Initialize the settings.
*
* - setup default configuration
*
* @private
*/
function Settings() {
classCallCheck(this, Settings);
// default settings
this.settings = {
'http requester': new Requester(),
'http GET transformer': httpGetTransformer,
'http POST transformer': httpPostPatchTransformer,
'http PATCH transformer': httpPostPatchTransformer,
'route matcher': routeMatcher
};
this.rules = {
'http requester': function httpRequester(requester) {
errorIfNotFunction(requester.fetch, 'setting http requester has no fetch function');
},
'http GET transformer': function httpGETTransformer(transformer) {
errorIfNotHttpTransformer(transformer);
},
'http POST transformer': function httpPOSTTransformer(transformer) {
errorIfNotHttpTransformer(transformer);
},
'http PATCH transformer': function httpPATCHTransformer(transformer) {
errorIfNotHttpTransformer(transformer);
},
'route matcher': function routeMatcher$$1(_routeMatcher) {
errorIfNotFunction(_routeMatcher, 'setting route matcher is not a function');
}
};
}
/**
* Assign `setting` to `val`
*
* @param {String} setting
* @param {*} [val]
* @private
*/
createClass(Settings, [{
key: 'set',
value: function set$$1(name, value) {
var checkRules = this.rules[name];
if (checkRules) {
checkRules(value);
}
this.settings[name] = value;
}
/**
* Return `setting`'s value.
*
* @param {String} setting
* @private
*/
}, {
key: 'get',
value: function get$$1(name) {
return this.settings[name];
}
}]);
return Settings;
}();
/**
* Module dependencies.
* @private
*/
var DEFAULT = { callback: function callback() {} };
/**
* Application class.
*/
var Application = function () {
/**
* Initialize the application.
*
* - setup default configuration
*
* @private
*/
function Application() {
classCallCheck(this, Application);
this.routers = [];
this.settings = new Settings();
this.plugins = [];
}
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.set('foo');
* // => "bar"
*
* @param {String} setting
* @param {*} [val]
* @return {app} for chaining
* @public
*/
createClass(Application, [{
key: 'set',
value: function set$$1() {
var _settings;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// get behaviour
if (args.length === 1) {
return this.settings.get([args]);
}
// set behaviour
(_settings = this.settings).set.apply(_settings, args);
return this;
}
/**
* Listen for DOM initialization and history state changes.
*
* The callback function is called once the DOM has
* the `document.readyState` equals to 'interactive'.
*
* app.listen(()=> {
* console.log('App is listening requests');
* console.log('DOM is ready!');
* });
*
*
* @param {Function} callback
* @public
*/
}, {
key: 'listen',
value: function listen() {
var _this = this;
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT.callback;
var request = { method: 'GET', uri: window.location.pathname + window.location.search };
var response = { status: 200, statusText: 'OK' };
var currentRoutes = this._routes(request);
this._callMiddlewareMethod('entered', currentRoutes, request);
// manage history
window.onpopstate = function (event) {
if (event.state) {
var _event$state = event.state,
_request = _event$state.request,
_response = _event$state.response;
['exited', 'entered', 'updated'].forEach(function (middlewareMethod) {
return _this._callMiddlewareMethod(middlewareMethod, _this._routes(_request), _request, _response);
});
}
};
// manage page loading/refreshing
window.onbeforeunload = function () {
_this._callMiddlewareMethod('exited');
};
var whenPageIsInteractiveFn = function whenPageIsInteractiveFn() {
_this.plugins.forEach(function (pluginObject) {
return pluginObject.plugin(_this);
});
_this._callMiddlewareMethod('updated', currentRoutes, request, response);
callback(request, response);
};
document.onreadystatechange = function () {
// DOM ready state
if (document.readyState === 'interactive') {
whenPageIsInteractiveFn();
}
};
if (['interactive', 'complete'].indexOf(document.readyState) !== -1) {
whenPageIsInteractiveFn();
}
}
/**
* Returns a new `Router` instance for the _uri_.
* See the Router api docs for details.
*
* app.route('/');
* // => new Router instance
*
* @param {String} uri
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'route',
value: function route(uri) {
var router = new Router(uri);
this.routers.push(router);
return router;
}
/**
* Use the given middleware function or object, with optional _uri_.
* Default _uri_ is "/".
* Or use the given plugin
*
* // middleware function will be applied on path "/"
* app.use((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/"
* app.use(new Middleware());
*
* // use a plugin
* app.use({
* name: 'My plugin name',
* plugin(application) {
* // here plugin implementation
* }
* });
*
* @param {String} uri
* @param {Middleware|Function|plugin} middleware object, middleware function, plugin
* @return {app} for chaining
*
* @public
*/
}, {
key: 'use',
value: function use() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _toParameters = toParameters(args),
baseUri = _toParameters.baseUri,
router = _toParameters.router,
middleware = _toParameters.middleware,
plugin = _toParameters.plugin;
if (plugin) {
this.plugins.push(plugin);
} else {
if (router) {
router.baseUri = baseUri;
} else if (middleware) {
router = new Router(baseUri);
HTTP_METHODS.forEach(function (method) {
router[method.toLowerCase()](middleware);
});
} else {
throw new TypeError('method takes at least a middleware or a router');
}
this.routers.push(router);
}
return this;
}
/**
* Gather routes from all routers filtered by _uri_ and HTTP _method_.
* See Router#routes() documentation for details.
*
* @private
*/
}, {
key: '_routes',
value: function _routes(request) {
var _this2 = this;
return this.routers.reduce(function (acc, router) {
acc.push.apply(acc, toConsumableArray(router.routes(_this2, request)));
return acc;
}, []);
}
/**
* Call `Middleware` method or middleware function on _currentRoutes_.
*
* @private
*/
}, {
key: '_callMiddlewareMethod',
value: function _callMiddlewareMethod(meth, currentRoutes, request, response) {
if (meth === 'exited') {
// currentRoutes, request, response params not needed
this.routers.forEach(function (router) {
router.visited().forEach(function (route) {
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
});
});
return;
}
currentRoutes.some(function (route) {
if (meth === 'updated') {
route.visited = request;
}
if (route.middleware[meth]) {
route.middleware[meth](request, response);
if (route.middleware.next && !route.middleware.next()) {
return true;
}
} else if (meth !== 'entered') {
// calls middleware method
var breakMiddlewareLoop = true;
var next = function next() {
breakMiddlewareLoop = false;
};
route.middleware(request, response, next);
if (breakMiddlewareLoop) {
return true;
}
}
return false;
});
}
/**
* Make an ajax request. Manage History#pushState if history object set.
*
* @private
*/
}, {
key: '_fetch',
value: function _fetch(req) {
var _this3 = this;
var resolve = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT.callback;
var reject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT.callback;
var method = req.method,
uri = req.uri,
headers = req.headers,
data = req.data,
history = req.history;
var httpMethodTransformer = this.get('http ' + method + ' transformer');
if (httpMethodTransformer) {
var _uriFn = httpMethodTransformer.uri,
_headersFn = httpMethodTransformer.headers,
_dataFn = httpMethodTransformer.data;
Object.keys(httpMethodTransformer).forEach(function (k) {
var fn = httpMethodTransformer[k];
req[k] = fn ? fn({ uri: uri, headers: headers, data: data }) : req[k];
});
}
// calls middleware exited method
this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri
var currentRoutes = this._routes(req);
// calls middleware entered method
this._callMiddlewareMethod('entered', currentRoutes, req);
// invokes http request
this.settings.get('http requester').fetch(req, function (request, response) {
if (history) {
window.history.pushState({ request: request, response: response }, history.title, history.uri);
}
_this3._callMiddlewareMethod('updated', currentRoutes, request, response);
resolve(request, response);
}, function (request, response) {
_this3._callMiddlewareMethod('failed', currentRoutes, request, response);
reject(request, response);
});
}
}]);
return Application;
}();
HTTP_METHODS.reduce(function (reqProto, method) {
/**
* Use the given middleware function or object, with optional _uri_ on
* HTTP methods: get, post, put, delete...
* Default _uri_ is "/".
*
* // middleware function will be applied on path "/"
* app.get((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/" and
* app.get(new Middleware());
*
* // get a setting value
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* @param {String} uri or setting
* @param {Middleware|Function} middleware object or function
* @return {app} for chaining
* @public
*/
var middlewareMethodName = method.toLowerCase();
reqProto[middlewareMethodName] = function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var _toParameters2 = toParameters(args),
baseUri = _toParameters2.baseUri,
middleware = _toParameters2.middleware,
which = _toParameters2.which;
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
if (!middleware) {
throw new TypeError('method takes a middleware ' + (middlewareMethodName === 'get' ? 'or a string' : ''));
}
var router = new Router();
router[middlewareMethodName](baseUri, middleware);
this.routers.push(router);
return this;
};
/**
* Ajax request (get, post, put, delete...).
*
* // HTTP GET method
* httpGet('/route1');
*
* // HTTP GET method
* httpGet({uri: '/route1', data: {'p1': 'val1'});
* // uri invoked => /route1?p1=val1
*
* // HTTP GET method with browser history management
* httpGet({uri: '/api/users', history: {state: {foo: "bar"}, title: 'users page', uri: '/view/users'});
*
* Samples above can be applied on other HTTP methods.
*
* @param {String|Object} uri or object containing uri, http headers, data, history
* @param {Function} success callback
* @param {Function} failure callback
* @public
*/
var httpMethodName = 'http' + method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
reqProto[httpMethodName] = function (request) {
var resolve = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT.callback;
var reject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT.callback;
var uri = request.uri,
headers = request.headers,
data = request.data,
history = request.history;
if (!uri) {
uri = request;
}
return this._fetch({
uri: uri,
method: method,
headers: headers,
data: data,
history: history
}, resolve, reject);
};
return reqProto;
}, Application.prototype);
function toParameters(args) {
var _args, _args2, _args3, _args4;
var baseUri = void 0,
middleware = void 0,
router = void 0,
plugin = void 0,
which = void 0;
args.length === 1 ? (_args = args, _args2 = slicedToArray(_args, 1), which = _args2[0], _args) : (_args3 = args, _args4 = slicedToArray(_args3, 2), baseUri = _args4[0], which = _args4[1], _args3);
if (which instanceof Router) {
router = which;
} else if (which instanceof Middleware || typeof which === 'function') {
middleware = which;
} else if (which && which.plugin && typeof which.plugin === 'function') {
plugin = which;
}
return { baseUri: baseUri, middleware: middleware, router: router, plugin: plugin, which: which };
}
/**
* Module dependencies.
*/
/**
* Create a frontexpress application.
*
* @return {Function}
* @api public
*/
var frontexpress = function frontexpress() {
return new Application();
};
/**
* Expose Router, Middleware constructors.
*/
frontexpress.Router = function (baseUri) {
return new Router(baseUri);
};
frontexpress.Middleware = Middleware;
return frontexpress;
}());
|
import React from "react";
import "./VidCall.css";
import VideoChat from "./components/InfoBar/Room/VideoChat";
const App = () => {
return (
<VideoChat />
);
};
export default App;
|
// getSelector.js (c) 2011, Lim Chee Aun. Licensed under the MIT license.
module.exports = (function(d){
if (!d.querySelector) return function(){};
// https://github.com/mathiasbynens/mothereffingcssescapes
function cssEscape(str) {
var firstChar = str.charAt(0),
result = '';
if (/^-+$/.test(str)){
return '\\-' + str.slice(1);
}
if (/\d/.test(firstChar)){
result = '\\3' + firstChar + ' ';
str = str.slice(1);
}
result += str.split('').map(function(chr){
if (/[\t\n\v\f]/.test(chr)){
return '\\' + chr.charCodeAt().toString(16) + ' ';
}
return (/[ !"#$%&'()*+,./:;<=>?@\[\\\]^_`{|}~]/.test(chr) ? '\\' : '') + chr;
}).join('');
return result;
}
function qsm(str, el){ // querySelector match
return d.querySelector(str) === el;
};
return function(el){
if (!el) return;
if (d !== el.ownerDocument) d = el.ownerDocument;
var originalEl = el,
selector = '';
do {
var tagName = el.tagName;
if (!tagName || /html|body|head/i.test(tagName)) return '';
tagName = tagName.toLowerCase();
var id = el.id,
className = el.className.trim(),
classList = el.classList || className.split(/\s+/);
// Select the ID, which is supposed to be unique.
// If there are multiple elements with the same ID, only first will be selected.
if (id){
id = cssEscape(id);
var s = '#' + id + selector;
if (qsm(s, originalEl)) return s;
s = tagName + "[id='" + id + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// If there's no ID or has multiple elements with same ID, select the className.
// Some authors use "unique" classes, like IDs, so use it.
// If one element contains multiple classes, choose the least popular class name.
var uniqueClass;
if (className){
var uniqueClassCount = Infinity;
for (var i=0, l=classList.length; i<l; i++){
var c = classList[i],
count = d.getElementsByClassName(c).length;
if (count < uniqueClassCount){
uniqueClassCount = count;
uniqueClass = cssEscape(c);
}
}
var s = tagName + '.' + uniqueClass + selector;
if (qsm(s, originalEl)) return s;
// If className can't work and the element has an ID, try combine both.
// Eg: div[id*='id'].class
if (id){
s = tagName + "[id='" + id + "']." + uniqueClass + selector;
if (qsm(s, originalEl)) return s;
}
}
// If ID and className fails, try get something "unique" from the element
switch (tagName){
case 'a':
var href = el.getAttribute('href'),
s;
// URL hash
var hash = el.hash;
if (hash){
s = tagName + "[href='" + hash + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// URL filename
var pathname = el.pathname || '',
filename = (pathname.match(/\/([^\/]+\.[^\/\.]+)$/i) || [, ''])[1];
if (filename){
s = tagName + "[href*='" + filename + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// URL hostname
var hostname = el.hostname;
if (hostname){
s = tagName + "[href*='" + hostname + "']" + selector;
if (qsm(s, originalEl)) return s;
}
// "short" URL pathname, ignore the longer ones (50 chars max)
if (pathname && pathname.length <= 50){
s = tagName + "[href*='" + pathname + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'img':
var src = el.getAttribute('src'),
pathname = (function(src){
var a = d.createElement('a');
a.href = src;
var pathname = a.pathname;
a = null;
return pathname;
})(src),
filename = (pathname.match(/\/([^\/]+\.[^\/\.]+)$/i) || [, ''])[1];
if (filename){
var s = tagName + "[src*='" + filename + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'input':
case 'button':
case 'select':
case 'textarea':
var name = el.getAttribute('name');
if (name){
var s = tagName + "[name='" + name + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
case 'label':
var _for = el.getAttribute('for');
if (_for){
var s = tagName + "[for='" + _for + "']" + selector;
if (qsm(s, originalEl)) return s;
}
break;
}
// Select the nth-child if all above fails.
var siblings = el.parentNode.children,
siblingsLength = siblings.length,
index = 0,
theOnlyType = true;
for (var i=0, l=siblings.length; i<l; i++){
var sibling = siblings[i];
if (sibling === el){
index = i+1;
} else if (sibling.tagName.toLowerCase() == tagName){
theOnlyType = false;
}
}
// See if the there are siblings and if there's not only one "type" (tagName) that's the same as selected element.
// Eg: <a><b><c> = only one type; <a><b><b><c><b> = three types
// Also, intelligently use first-child or last-child.
if (siblingsLength>1 && !theOnlyType){
var pseudoChild;
if (index == 1){
pseudoChild = ':first-child';
} else if (index == siblingsLength){
pseudoChild = ':last-child';
} else {
pseudoChild = ':nth-child(' + index + ')';
}
selector = tagName + pseudoChild + selector;
if (qsm(selector, originalEl)) return selector;
} else { // Last step, clean up before traversing to the parent level
if (id){
selector = tagName + "[id='" + id + "']" + selector;
} else if (uniqueClass){
selector = tagName + '.' + uniqueClass + selector;
} else {
selector = tagName + selector;
if (qsm(selector, originalEl)) return selector;
}
}
} while((el = el.parentNode) && (selector = '>' + selector));
return selector;
};
})(window.document);
|
import React, { Component } from 'react';
import {
ListView,
RefreshControl,
View,
Text,
StyleSheet,
Image,
TouchableHighlight,
BackAndroid,
Platform } from 'react-native';
import QueryString from 'query-string';
export default class HeadlineListScene extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id});
this.state = {
dataSource: ds.cloneWithRows(['']),
headlineList: [],
refreshing: false,
queryParams: {
category: 161,
limit: 20,
headline_id: 0
}
};
}
componentWillMount() {
this.getHeaderline();
}
componentDidMount() {
if (Platform.OS === 'android') {
BackAndroid.addEventListener('hardwareBackPress', () => {
if (this.props.navigator.getCurrentRoutes().length > 1) {
this.props.navigator.pop();
return true;
}
return false;
});
}
}
render() {
return (
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.customizedRenderRow.bind(this)}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={() => {
const params = this.state.queryParams;
params.headline_id = 0;
this.setState({
refreshing: true,
queryParams: params,
headlineList: []
});
this.getHeaderline();
}}
/>
}
onEndReached={() => {
// Get last row data
const dataSource = this.state.dataSource;
const lastRowIndex = dataSource.getRowCount() - 1;
const lastSectionIndex = dataSource.getRowAndSectionCount() - dataSource.getRowCount() - 1;
const lastRowData = dataSource.getRowData(lastSectionIndex, lastRowIndex);
// Set headline id
const params = this.state.queryParams;
params.headline_id = lastRowData.id;
this.setState({
queryParams: params
});
this.getHeaderline();
}}
onEndReachedThreshold={50}
/>
</View>
);
}
customizedRenderRow(rowData) {
return (
<TouchableHighlight onPress={() => this.showHeadlineDetail(rowData)}>
<View style={styles.container}>
<Image style={styles.image} source={{uri: rowData.preview}}>
<View style={styles.alphaContainer}>
<Text style={styles.text}>{rowData.title}</Text>
</View>
</Image>
</View>
</TouchableHighlight>
);
}
getHeaderline() {
fetch('http://web.meishuquan.net/rest/headline/get-headline-list?'
+ QueryString.stringify(this.state.queryParams))
.then((response) => response.json())
.then((responseJson) => {
const headlineList = this.state.headlineList.concat(responseJson.data);
this.setState({
headlineList: headlineList,
dataSource: this.state.dataSource.cloneWithRows(headlineList),
refreshing: false
});
})
.catch((error) => {
console.error(error);
});
}
showHeadlineDetail(rowData) {
this.props.navigator.push({
name: 'HeadlineDetailScene',
object: rowData
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
alphaContainer: {
backgroundColor: 'rgba(0,0,0,0.5)'
},
text: {
textAlign: 'auto',
fontSize: 20,
color: 'white',
marginHorizontal: 10,
marginVertical: 5
},
image: {
justifyContent: 'flex-end',
height: 250
}
});
|
//Function to display different messages based on the selection the user makes whether it's a Convio donation share or not.
function show_mssg(q){
if(q=="y"){
document.getElementById('mssg1').style.visibility = 'visible';
document.getElementById('mssg1b').style.visibility = 'visible';
document.getElementById('mssg2').style.visibility = 'hidden';
document.getElementById('mssg2b').style.visibility = 'hidden';
}else{
document.getElementById('mssg1').style.visibility = 'hidden';
document.getElementById('mssg1b').style.visibility = 'hidden';
document.getElementById('mssg2').style.visibility = 'visible';
document.getElementById('mssg2b').style.visibility = 'visible';
}
}
|
import React, { useState } from 'react';
import Axios from 'axios';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import Place from './Place';
import { setUser, setCompany } from '../../mightyDucks/authReducer';
import { findCompany } from '../../ShawnsTests/utils';
function RegisterForm(props) {
const [firstname, setFirstName] = useState('')
const [lastname, setLastName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [place, setPlace] = useState('')
const [company, setCompany] = useState('')
const [state, setState] = useState('')
const [city, setCity] = useState('')
const [searchResults, setSearchResults] = useState([])
const register = () => {
const { formatted_address, name, place_id } = place
Axios.post('/auth/register-company', {
company: { company_name: name, address: formatted_address, google_places_id: place_id }
})
.then(company => {
Axios.post('/auth/register-user', {
user: { firstname, lastname, isadmin: true, email, password }
})
.then(user => {
props.setCompany(company.data)
props.setUser(user.data)
props.history.push('/')
}).catch(console.log)
}).catch(console.log)
}
return (
<div className="registerLandingComp">
<h2>Register</h2>
<div className='registerBox1'>
<div className="user">
<div className="user-inputs">
<div className="user-input">
<label htmlFor="firstname">First Name:</label>
<input value={firstname} id='firstname' type="text" onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="user-input">
<label htmlFor="lastname">Last Name:</label>
<input value={lastname} id="lastname" type="text" onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="user-input">
<label htmlFor="email">Email:</label>
<input value={email} id="email" type="email" onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="user-input">
<label htmlFor="password">Password:</label>
<input value={password} id="password" type="password" onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="company-inputs">
<div className="company-input">
<label htmlFor="company">Company:</label>
<input value={company} id="company" type="text" onChange={(e) => setCompany(e.target.value)} />
</div>
<div className="company-input">
<label htmlFor="city">City:</label>
<input value={city} id="city" type="text" onChange={(e) => setCity(e.target.value)} />
</div>
<div className="company-input">
<label htmlFor="state">State:</label>
<input value={state} id="state" type="text" onChange={(e) => setState(e.target.value)} />
</div>
<button className="find-co-btn" onClick={async () => {
setSearchResults(await findCompany(company, city, state))
}}>Find Company
</button>
<p>please select your company below, before clicking on the register button</p>
</div>
</div>
<button className="register-co-btn" onClick={register}>Register</button>
<div className='companyMappedDisplayed'>
{searchResults.map(place => (
<div key={place.id} onClick={() => setPlace(place)}>
<div className='companyBoxDisplayed'>
<Place place={place} />
</div>
<hr />
</div>
))}
</div>
</div>
</div>
)
}
const mapDispatchToProps = {
setCompany,
setUser
}
export default connect(null, mapDispatchToProps)(withRouter(RegisterForm))
|
var Promise = require('promise')
var urlGenerateResponse = require('./url')
function generateResponse(processed, res, request) {
return new Promise((fulfill, reject) => {
if (processed.pastebinId !== undefined) {
processed.responseUrl = 'https://pastebin.com/raw/'+processed.pastebinId
urlGenerateResponse(processed, res, request)
.then(fulfill)
.catch(reject)
}
else {
reject('no pastebinId')
}
})
}
module.exports = generateResponse
|
import {take, put,call,fork} from 'redux-saga/effects'
import * as API from "../api"
import * as actions from '../actions';
import Message from '@/components/Message'
//获取列表
export function* userFetchList () {
while(true){
let postAction = yield take(actions.USER_FETCH_LIST);
yield put(actions.userLodaing(true));
let posts = yield call(API.fetchListApi,postAction.result);
yield put(actions.userFentchList(posts));
yield put(actions.userLodaing(false));
}
}
//查看角色权限
export function* userViewRole () {
while(true){
let postAction = yield take(actions.USER_VIEW_ROLE);
yield put(actions.userModalLodaing(true));
let [roles, trees] = yield [
call(API.fetchViewRoleApi,postAction.result),
call(API.fetchViewRoleTreeApi,postAction.result)
]
yield put(actions.userViewRole({roles:{...roles},trees:{...trees}}));
postAction.callBack();
yield put(actions.userModalLodaing(false));
}
}
//重置密码
export function* userResetPassWord () {
while(true){
let postAction = yield take(actions.USER_RESET_PASSWORD);
let posts = yield call(API.resetPassWordApi,postAction.result);
yield put(actions.userResetPassword(posts));
if(posts.httpCode === 200){
Message.success("重置密码成功")
}else{
Message.error("重置密码失败")
}
postAction.callBack();
}
}
//冻结用户
export function* userFrozeUser () {
while(true){
let postAction = yield take(actions.USER_FROZE_USER);
let posts = yield call(API.frozeUserApi,postAction.result);
yield put(actions.userFrozeUser(posts));
postAction.callBack();
if(posts.httpCode === 200){
Message.success("操作成功")
}else{
Message.error("操作失败")
}
}
}
//解冻用户
export function* userUnfrozeUser () {
while(true){
let postAction = yield take(actions.USER_UNFROZE_USER);
let posts = yield call(API.unfrozeUserApi,postAction.result);
yield put(actions.userUnfrozeUser(posts));
postAction.callBack();
if(posts.httpCode === 200){
Message.success("操作成功")
}else{
Message.error("操作失败")
}
}
}
//删除用户
export function* userDeleteUser () {
while(true){
let postAction = yield take(actions.USER_DELETE_USER);
let posts = yield call(API.deleteUserApi,postAction.result);
yield put(actions.userDeleteUser(posts));
postAction.callBack();
if(posts.httpCode === 200){
Message.success("删除成功")
}else{
Message.error("删除失败")
}
}
}
//请求角色列表
export function* userFetchRoleList () {
while(true){
let postAction = yield take(actions.USER_ROLE_LIST);
let callback = postAction.callback
let posts = yield call(API.fentchRoleListApi,postAction.result);
yield put(actions.userFentchRoleList(posts));
if(callback) callback && callback()
}
}
//根据选中角色请求树
export function* userAddUserTree () {
while(true){
let postAction = yield take(actions.USER_ADD_USER_TREE);
yield put(actions.userLodaing(true));
let posts = yield call(API.fentchAddUserTreeApi,postAction.result);
yield put(actions.userAddUserTree(posts));
postAction.callBack()
yield put(actions.userLodaing(false));
}
}
//清空树
export function* userDelUserTree () {
while(true){
yield take(actions.USER_DEL_USER_TREE);
yield put(actions.userDelUserTree({}));
}
}
//保存用户
export function* userSaveUser () {
while(true){
let postAction = yield take(actions.USER_SAVE_USER);
yield put(actions.userLodaing(true));
//判断是新增还是编辑,传入参数中id有值则为编辑
let id='';
if(postAction.result.id){
id=postAction.result.id;
yield call(API.saveUserUpdateApi,{...postAction.result.form,id:id});
}else {
//第一步获注册用户获取Id
let posts = yield call(API.saveUserApi,postAction.result.form);
if(posts.httpCode!==424){
id=posts.data.id;
}else{
yield put(actions.userLodaing(false));
postAction.message(posts.msg);
}
}
if(id){
if(postAction.result.roles.length>0){
//第二步更新用户对应的角色
let arr=[],tree=[],dataTree=[];
postAction.result.roles.forEach((item)=>{
arr.push({
"enable": 1,
"roleId":item,
"userId": id
})
})
//第三步更新树
postAction.result.trees.forEach((item)=>{
item.forEach((it)=>{
//判断刨除数据权限的节点
if(it.checked){
if(it.trueName){
//判断为数据节点新增的节点
dataTree.push({
"enable": 1,
"menuId": it.truePid,
"paramId":it.paramId,
"paramKey": it.paramKey,
"paramValue": it.trueName,
"userId": id
})
}else{
if(it.truePid){
//判断为操作权限的节点
tree.push({
"enable": 1,
"menuId": it.truePid,
"permission": it.code,
"userId": id
})
}else{
if(it.flag!=='fakeParent'){
tree.push({
"enable": 1,
"menuId": it.id,
"permission": "",
"userId": id
})
}
}
}
}
else{
if(it.trueName){
//判断为数据节点删除的节点
dataTree.push({
"enable": 1,
"menuId": it.truePid,
"userId": id
})
}
}
})
})
yield call(API.saveUserRoleApi,{list:arr});
yield call(API.saveUserPermissionApi,{list:tree});
let dataTrees=yield call(API.saveUserDataPermissionApi,{list:dataTree});
yield put(actions.userSaveUser(dataTrees));
if(dataTrees.httpCode === 200){
Message.success("保存成功")
}else{
Message.error("保存失败")
}
}else{
let result = postAction.result;
yield call(API.saveUserRoleApi,{list:{enable:1,userId:result.id}});
yield call(API.saveUserPermissionApi,{list:{userId:result.id,enable:1}});
let dataTrees=yield call(API.saveUserDataPermissionApi,{list:{userId:result.id,enable:1}});
yield put(actions.userSaveUser(dataTrees));
if(dataTrees.httpCode === 200){
Message.success("保存成功")
}else{
Message.error("保存失败")
}
}
yield put(actions.userLodaing(false));
postAction.callBack();
}
}
}
//新增角色查看权限树
export function* userReadRoleTree () {
while(true){
let postAction = yield take(actions.USER_READ_ROLE_TREE);
yield put(actions.userModalLodaing(true));
let posts = yield call(API.fentchReadRoleTreeApi,postAction.result);
yield put(actions.userReadRoleTree(posts));
yield put(actions.userModalLodaing(false));
}
}
//新增角色保存角色
export function* userAddRole () {
while(true){
//第一步获注册角色获取Id
let postAction = yield take(actions.USER_ADD_ROLE);
yield put(actions.userModalLodaing(true));
let posts = yield call(API.saveRoleApi,postAction.result.form);
let id='';
if(posts.httpCode!==400){
id=posts.data.id;
}else{
yield put(actions.userModalLodaing(false));
postAction.message(posts.msg);
}
if(id){
//第二步更新树
let tree=[],dataTree=[];
postAction.result.trees.forEach((item)=>{
item.forEach((it)=>{
if(it.checked){
if(it.trueName){
//判断为数据节点新增的节点
dataTree.push({
"enable": 1,
"menuId": it.truePid,
"paramKey": it.paramKey,
"paramId":it.paramId,
"paramValue": it.trueName,
"roleId": id
})
}else{
if(it.truePid){
tree.push({
"enable": 1,
"menuId": it.truePid,
"permission": it.code,
"roleId": id
})
}else{
if(it.flag!=='fakeParent'){
tree.push({
"enable": 1,
"menuId": it.id,
"permission": "",
"roleId": id
})
}
}
}
}
})
})
let addResult=yield call(API.saveRolePermissionApi,{list:tree})
//第三步数据权限
yield call(API.saveUserDataPermissionApi,{list:dataTree});
yield put(actions.userAddRole(addResult))
postAction.callBack();
let roles=yield call(API.fentchRoleListApi,{});
yield put(actions.userFentchRoleList(roles));
yield put(actions.userModalLodaing(false));
if(addResult.httpCode === 200){
Message.success("保存成功")
}else{
Message.error("保存失败")
}
}
}
}
//保存编辑Id
export function* userSaveEditId () {
while(true){
let id=yield take(actions.USER_SAVE_EDIT_ID);
yield put(actions.userSaveEditId(id));
}
}
//编辑角色-获取用户信息
export function* editGetUser () {
while(true){
let postAction = yield take(actions.USER_EDIT_GET_CURRENT_USER);
yield put(actions.userLodaing(true));
let posts = yield call(API.editGetCurrentUserApi,postAction.result);
yield put(actions.userEditGetCurrentUser({
'userName':posts.data.userName,
'account':posts.data.account,
'password':posts.data.password,
'email':posts.data.email,
'phone':posts.data.phone,
'remark':posts.data.remark
}))
}
}
//清空表单
export function* userDelCurrentUser () {
while(true){
yield take(actions.USER_DEL_CURRENT_USER);
yield put(actions.userDelCurrentUser({
'userName':'',
'account':'',
'password':'',
'email':'',
'phone':'',
'remark':''
}));
}
}
//编辑角色-获取用户角色
export function* editGetRole () {
while(true){
let postAction = yield take(actions.USER_EDIT_GET_ROLE);
yield put(actions.userLodaing(true));
let posts = yield call(API.editGetRoleApi,postAction.result);
let roles=[];
posts.data.forEach((item)=>{
roles.push(item.roleId)
})
yield put(actions.userEditGetRole(roles));
yield put(actions.userLodaing(true));
let arr=[]
roles.forEach((item)=>{
arr.push({
'roleId':item
})
})
let allTree=yield call(API.fentchAddUserTreeApi,{list:arr});
let checkTree=yield call(API.fetchViewRoleTreeApi,postAction.result);
yield put(actions.userEditGetTree({allTree:allTree,checkTree:checkTree}));
postAction.callBack()
yield put(actions.userLodaing(false));
}
}
//保存table条件
export function* editTableCondition () {
while(true){
let postAction=yield take(actions.USER_SAVE_TABLE_CONDITION);
yield put(actions.userSaveTableCondition(postAction.result));
}
}
export default function* (){
yield fork(userFetchList)
yield fork(userViewRole)
yield fork(userResetPassWord)
yield fork(userFrozeUser)
yield fork(userUnfrozeUser)
yield fork(userDeleteUser)
yield fork(userFetchRoleList)
yield fork(userAddUserTree)
yield fork(userDelUserTree)
yield fork(userSaveUser)
yield fork(userReadRoleTree)
yield fork(userAddRole)
yield fork(userSaveEditId)
yield fork(editGetUser)
yield fork(editGetRole)
yield fork(userDelCurrentUser)
yield fork(editTableCondition)
}
|
import { TWEET_DELETE } from './actionType'
import axios from 'axios'
export const deleteTweets = id => ({ type: TWEET_DELETE, id })
export const deleteTweetsAsync = id => {
return dispatch => {
axios
.delete(
'https://reactnetwork-fdc20.firebaseio.com/tweets/' + id + '.json'
)
.then(res => {
return {
tweets: Object.keys(this.state.tweets)
.filter(key => key !== id)
.reduce(
(result, next) => ({
...result,
[next]: this.state.tweets[next]
}),
{}
)
}
})
.catch(err => console.log(err))
}
}
|
import React from "react";
import HomeBaner from '../reutilizable/Baner';
import FooterPage from '../reutilizable/FooterPage';
import CardsPage from '../reutilizable/CardsPage';
import BlogPage from '../reutilizable/BlogPage';
import {
Container
} from "mdbreact";
class Inicio extends React.Component {
render() {
return (
<div>
<HomeBaner />
<Container>
<hr className="my-5 mx-5 bg-info" />
<CardsPage />
<hr className="my-5 mx-5 bg-info" />
<BlogPage />
</Container>
<FooterPage />
</div>
);
}
}
export default Inicio;
|
document.addEventListener("DOMContentLoaded", () => {
const monsterCollection = document.getElementById("monster-container")
const pageBack = document.getElementById('back');
const pageForward = document.getElementById('forward')
const createMonsterFrom = document.getElementById("add-monster-form")
fetch('http://localhost:3000/monsters/?_limit=50&_page=1')
.then((response)=>{return response.json()})
.then((monsterJsonObj)=>{
monsterCollection.innerHTML = monsterJsonObj.map((monsterObj)=>{
let monster = new Monster(monsterObj)
return monster.render();
}).join("")
})
let counter = 1;
pageForward.addEventListener('click', (event)=>{
monsterCollection.innerHTML = null;
counter +=1;
fetch(`http://localhost:3000/monsters/?_limit=50&_page=${counter}`)
.then((response)=>{return response.json()})
.then((monsterJsonObj)=> {
monsterCollection.innerHTML = monsterJsonObj.map((monsterObj)=>{
let monster = new Monster(monsterObj)
return monster.render();
}).join("")
})
})
pageBack.addEventListener('click', (event)=>{
monsterCollection.innerHTML = null;
counter -=1;
fetch(`http://localhost:3000/monsters/?_limit=50&_page=${counter}`)
.then((response)=>{return response.json()})
.then((monsterJsonObj)=> {
monsterCollection.innerHTML = monsterJsonObj.map((monsterObj)=>{
let monster = new Monster(monsterObj)
return monster.render();
}).join("")
})
})
createMonsterFrom.addEventListener('submit', (event)=>{
const monsterName = document.getElementById("new-monster-name").value
const monsterAge = document.getElementById("new-monster-age").value
const monsterDescription = document.getElementById("new-monster-description").value
fetch('http://localhost:3000/monsters', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: monsterName,
age: monsterAge,
description: monsterDescription
})
})
.then(response=> response.json())
.then(jsonMonster =>{
const newMonster = new Monster(jsonMonster)
monsterCollection.innerHTML += newMonster.render()
console.log(newMonster)
})
event.target.reset();
})
}) //end DOM Content Loaded
|
import {
validUsername,
isExternal
} from "../utils/validate.js";
var SvgIcon = function() {
Vue.component('svg-icon', {
name: 'SvgIcon',
template: '<div><div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" /><svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners"><use :xlink:href="iconName" /></svg></div>',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
})
}
export default SvgIcon
|
'use strict';
var fs = require('fs');
var assert = require('assert');
var co = require('co');
/*---------- callback ----------*/
fs.readFile('file1.txt', (err, data) => {
if (err) throw err;
// console.log('callback--', data.toString());
});
/*---------- Promise ----------*/
function readFilePromise(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf-8', (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
// readFilePromise('file1.txt').then((data) => { console.log('Promise--', data) });
/*---------- generator ----------*/
function* readFile() {
var path = 'file1.txt';
var result = yield readFilePromise(path);
// console.log('generator--', result);
}
var g = readFile();
var data = g.next();
data.value.then((data) => {
g.next(data);
});
/*---------- thunkify源码 ----------*/
/*---------- https://github.com/tj/node-thunkify/blob/master/index.js ----------*/
function thunkify(fn) {
return function() {
var args = new Array(arguments.length);
var ctx = this;
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return function(done) {
var called; //预检机制,确保done只调用一次
args.push(function() {
if (called) return;
called = true;
done.apply(null, arguments);
});
try {
fn.apply(ctx, args);
} catch (err) {
done(err);
}
}
}
}
/*---------- thunkify and generator ----------*/
var readFileThunk = thunkify(fs.readFile);
var gen1 = function*() {
var r1 = yield readFileThunk('file1.txt', 'utf-8');
console.log(r1);
var r2 = yield readFileThunk('file2.txt', 'utf-8');
console.log(r2);
}
var g1 = gen1();
var r1 = g1.next();
//generator执行器
function run(fn) {
var gen = fn();
function next(err, data) {
var result = gen.next(data);
if (result.done) return;
result.value(next);
}
next();
}
// run(gen1);
/*---------- co模块 ----------*/
var gen2 = function*() {
var r1 = yield readFilePromise('file1.txt', 'utf-8');
var r2 = yield readFilePromise('file2.txt', 'utf-8');
console.log(r1);
console.log(r2);
return 1;
};
co(gen2).then(function(res) {
console.log(res);
})
|
/**
* Created by lusiwei on 2016/9/23.
*/
'use strict';
import { SET_USER } from '../actions/user'
export function user(state = {}, action) {
switch (action.type) {
case SET_USER:
return Object.assign({}, action.user);
default:
return state;
}
}
|
import React from "react";
import PropTypes from "prop-types";
import { Image, StyleSheet, View, TextInput, Button, Text } from "react-native";
import { connect } from "react-redux";
import Colors from "../constants/Colors";
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
flexDirection: "column",
alignItems: "center",
},
image: {
marginTop: 100,
},
input: {
height: 40,
width: 200,
marginTop: 20,
},
button: {
width: 200,
paddingTop: 50,
},
message: {
paddingTop: 20,
fontSize: 12,
color: Colors.primary,
},
});
class LoginScreen extends React.Component {
static navigationOptions = {
header: null,
};
componentDidMount() {
this.props.setMessage("");
}
render() {
return (
<View style={styles.container}>
<Image
source={require("../assets/images/icon.png")}
style={styles.image}
/>
<TextInput
style={styles.input}
placeholder="email"
value={this.props.email}
onChangeText={this.props.setEmail}
/>
<TextInput
style={styles.input}
placeholder="password"
value={this.props.password}
onChangeText={this.props.setPassword}
/>
<View style={styles.button}>
<Button
color={Colors.primary}
title="Login"
onPress={this.props.login}
/>
</View>
<View>
<Text style={styles.message}>{this.props.message}</Text>
</View>
</View>
);
}
}
LoginScreen.propTypes = {
email: PropTypes.string.isRequired,
password: PropTypes.string.isRequired,
login: PropTypes.func.isRequired,
setPassword: PropTypes.func.isRequired,
setEmail: PropTypes.func.isRequired,
message: PropTypes.string.isRequired,
setMessage: PropTypes.func.isRequired,
};
const mapState = ({ loginModel }) => ({
email: loginModel.email,
password: loginModel.password,
message: loginModel.message,
});
const mapDispatch = ({ loginModel }) => ({
setEmail: loginModel.setEmail,
setPassword: loginModel.setPassword,
login: loginModel.login,
setMessage: loginModel.setMessage,
});
const LoginScreenWithProps = connect(
mapState,
mapDispatch,
)(LoginScreen);
export default LoginScreenWithProps;
|
import styled from 'styled-components'
export const RangeInputs = styled.div`
display: flex;
justify-content: space-between;
> div {
align-items: flex-end;
}
input {
outline: none;
border: 0;
font-weight: bold;
font-size: 24px;
line-height: 24px;
max-width: 75px;
}
span {
font-weight: 600;
font-size: 12px;
line-height: 14px;
letter-spacing: 0.02em;
margin-left: 5px;
}
`
|
'use strict';
define([], function () {
function config($routeProvider) {
$routeProvider.when('/PatientReg', {
templateUrl: 'Patient_Registration/_patientRegistration.html',
controller: 'PatientRegiCtrl'
})
.when('/PaymentRecvForm', {
templateUrl: 'Payment/_paymentRecieveForm.html',
controller: 'PaymentCtrl'
})
.when('/BillEntry', {
templateUrl: 'Bill/_billEntryForm.html',
controller: 'BillCtrl'
})
.when('/SignUp', {
templateUrl: 'User_Registration/_signUp.html',
controller: 'UserRegistrationCtrl'
})
.when('/Login', {
templateUrl: 'Login/_login.html',
controller: 'LoginCtrl'
})
.when('/SignOut', {
templateUrl: 'Login/_signOut.html',
controller:'SignOutCtrl'
});
}
config.$inject = ['$routeProvider'];
return config;
});
|
const { compareSync } = require('bcrypt');
const express = require('express');
var methodOverride = require('method-override')
const router = express.Router();
const db = require("../models");
const strava = require('strava-v3');
const axios = require('axios');
//middleware
router.use(methodOverride('_method'))
// pass the id back to the edit.ejs
router.get('/:activity_id', function(req,res) {
res.render('edit', { activityIdPizza: req.params.activity_id })
})
router.put('/:activity_id', function(req, res) {
console.log("should be current token~~~~~~~~~~~~~~~~~~~~~")
console.log(req.user.access_token)
console.log("~~~~~~~~~~~~~~~~~~~~~")
// next steps
// remove hard coded ID
//
console.log('these are the params', req.params)
let activityUrl = `https://www.strava.com/api/v3/activities/${req.params.activity_id}?access_token=ba68f018f4f5b44e69ab96352d4eda047b58383c`
axios.put(activityUrl,
{
headers: {
"Authorization": `Bearer ${req.user.access_token}`
},
name: req.body.name
}).then(function(apiResponse) {
res.redirect('/activities')
})
});
module.exports = router;
|
'use strict';
const reader = require('../lib/reader.js');
require('jest');
let paths = [`${__dirname}/../data/one.txt`, `${__dirname}/../data/two.txt`, `${__dirname}/../data/three.txt`];
describe('Read Files Module', function() {
describe('with incorrect file path', function() {
it('should return an error', function(done) {
reader(`${__dirname}/../data/onez.txt`, function(err) {
expect(err).toBeTruthy();
expect(typeof err).toBe('object');
done();
});
});
});
describe('with correct file path', function() {
it('should return error when no data is passed through', function(done) {
reader(paths[0], function(err) {
expect(err).toBe(null);
done();
});
});
it('should accept two arguments', function(done) {
expect(arguments.length === 2);
done();
});
it('should return first 8 bytes of text from one.txt', function(done) {
reader(paths[0], function(err, data) {
expect(err).toBe(null);
expect(typeof paths[0]).toEqual('string');
expect(typeof data.buffer).toEqual('object');
expect(data.toString()).toEqual('One file');
console.log('one.txt:', data);
done();
});
});
});
describe('with correct file path round 2', function() {
it('should return error when no data is passed through', function(done) {
reader(paths[1], function(err) {
expect(err).toBe(null);
done();
});
});
it('should return first 8 bytes of text from two.txt', function(done) {
reader(paths[1], function(err, data) {
expect(err).toBe(null);
expect(typeof paths[1]).toEqual('string');
expect(typeof data.buffer).toEqual('object');
expect(data.toString()).toEqual('File num');
console.log('two.txt:', data);
done();
});
});
});
describe('with correct file path round 3', function() {
it('should return error when no data is passed through', function(done) {
reader(paths[2], function(err) {
expect(err).toBe(null);
done();
});
});
it('should return first 8 bytes of text from two.txt', function(done) {
reader(paths[2], function(err, data) {
expect(err).toBe(null);
expect(typeof paths[2]).toEqual('string');
expect(typeof data.buffer).toEqual('object');
expect(data.toString()).toEqual('The thir');
console.log('three.txt:', data);
done();
});
});
});
});
|
// ============================================================================== //
// ============================================================================== //
// SETUP ======================================================================== //
// ============================================================================== //
var width = document.querySelector("#fig-strategies").clientWidth,
ratio = .75,
height = 300, //ratio * width,
m = [0, 0, 40, 120],
w = width - m[1] - m[3],
h = height - m[0] - m[2];
var svg = d3.select("#fig-strategies");
svg.attr("height", height);
function redraw() {
d3.selectAll(".alt-view").remove();
draw();
}
d3.select(window)
.on("resize", function() {
width = document.querySelector("#fig-strategies").clientWidth;
// height = 600, // ratio * width;
w = width - m[1] - m[3];
h = height - m[0] - m[2];
svg.attr("height", height);
redraw();
});
var xScale, yScale;
// ============================================================================== //
// ============================================================================== //
// DRAW ========================================================================= //
// ============================================================================== //
var stages = ["TRIGGER", "1", "1b", "2", "3", "4"],
transitions = [];
for (let s1 of stages) {
for (let s2 of stages) {
if (s1 != s2) {
transitions.push({from: s1, to: s2, id: `${s1}-${s2}`});
}
}
}
transitions = [
{
group: "A",
direction: 'tighten',
arrows: [
{from: "1", to: "4", id: "1-4", idx: 0},
{from: "1b", to: "4", id: "1b-4", idx: 1},
{from: "2", to: "4", id: "2-4", idx: 2},
{from: "3", to: "4", id: "3-4", idx: 3},
],
width: 4,
condition: '7-day average > 7.5'
},
{
group: "B",
direction: 'tighten',
arrows: [
{from: "1", to: "3", id: "1-3", idx: 0},
{from: "1b", to: "3", id: "1b-3", idx: 1},
{from: "2", to: "3", id: "2-3", idx: 2},
],
width: 3,
condition: '7-day average > 1.5'
},
{
group: "C",
direction: 'tighten',
arrows: [
{from: "1", to: "2", id: "1-2", idx: 0},
{from: "1b", to: "2", id: "1b-2", idx: 1},
],
width: 2,
condition: '2+ cases in last 14 days'
},
{
group: "D",
direction: 'tighten',
arrows: [
{from: "1", to: "1b", id: "1-1b", idx: 0}
],
width: 1,
condition: 'Any new case'
},
{
group: "E",
direction: 'relax',
arrows: [
{from: "4", to: "3", id: "4-3", idx: 0},
],
width: 1,
condition: '7-day average < 5'
},
{
group: "F",
direction: 'relax',
arrows: [
{from: "3", to: "2", id: "3-2", idx: 0},
],
width: 1,
condition: '7-day average < 1'
},
{
group: "G",
direction: 'relax',
arrows: [
{from: "2", to: "1b", id: "2-1b", idx: 0},
],
width: 1,
condition: 'No cases in 7 days'
},
{
group: "H",
direction: 'relax',
arrows: [
{from: "1b", to: "1", id: "1b-1", idx: 0},
],
width: 1,
condition: 'No cases in 28 days'
},
]
let As = [];
for (let t of transitions) {
t.arrows.forEach(function(d) {
d.group = t.group;
d.width = t.width;
})
As = As.concat(t.arrows);
As.push({id: `spacer-${t.group}`});
}
As.pop();
var stageCols = {
"1": "#ebf0e9",
"1b": "#d6e1d2",
"2": "#c2d2bc",
"3": "#adc3a5",
"4": "#99b48f",
"TRIGGER": "transparent"
}
// defs = svg.append('defs');
// grad = defs.append('linearGradient')
// .attr('id', '1-4')
// .attr('x1', 0)
// .attr('x2', .1)
// .attr('y1', 0.1)
// .attr('y2', .9);
// grad.append('stop').attr('offset', '0%').attr('stop-color', stageCols["1"]);
// grad.append('stop').attr('offset', '100%').attr('stop-color', stageCols["4"]);
function draw() {
yScale = d3.scaleBand()
.domain(stages)
.range([m[0], h+m[0]]);
xScaleGroup = d3.scaleBand()
.domain(transitions.map(d => d.group))
.range([m[3], width - yScale.bandwidth()/2 - m[1]])
.paddingInner(.1)
.paddingOuter(.1)
let aScales = {},
bw;
aScales[4] = d3.scaleBand()
.domain([0,1,2,3])
.range([0, xScaleGroup.bandwidth()])
.paddingInner(0)
.paddingOuter(0)
for (let k = 3; k > 0; k--) {
aScales[k] = d3.scaleBand()
.domain([...Array(k).keys()])
.range([0, xScaleGroup.bandwidth()])
.paddingInner(0)
.paddingOuter((4-k)/2)
}
let brB = yScale.range()[1] + 10,
brT = yScale.range()[1] + m[2]/2;
bracketL = svg.append("path")
.attr("class", "alt-view")
.attr("d", `M ${xScaleGroup("A")} ${brB} L ${xScaleGroup("A")} ${brT} L ${xScaleGroup("D") + xScaleGroup.bandwidth()} ${brT} L ${xScaleGroup("D") + xScaleGroup.bandwidth()} ${brB}`)
.attr("stroke", "#33691e")
.attr("fill", "transparent");
bracketR = svg.append("path")
.attr("class", "alt-view")
.attr("d", `M ${xScaleGroup("E")} ${brB} L ${xScaleGroup("E")} ${brT} L ${xScaleGroup("H") + xScaleGroup.bandwidth()} ${brT} L ${xScaleGroup("H") + xScaleGroup.bandwidth()} ${brB}`)
.attr("stroke", "#33691e")
.attr("fill", "transparent");
bracketTextL = svg.append("text")
.attr("class","alt-view")
.attr("x", xScaleGroup("C"))
.attr("y", yScale.range()[1] + m[2]/2)
.text("TIGHTENING")
.attr("alignment-baseline", "middle")
.attr("text-anchor", "middle")
.attr("fill", "#fff")
.attr("stroke", "#fff")
.attr("stroke-width", 10);
bracketTextL = svg.append("text")
.attr("class","alt-view")
.attr("x", xScaleGroup("C"))
.attr("y", yScale.range()[1] + m[2]/2)
.text("TIGHTENING")
.attr("alignment-baseline", "middle")
.attr("text-anchor", "middle")
.attr("fill", "#33691e");
bracketTextR = svg.append("text")
.attr("class","alt-view")
.attr("x", xScaleGroup("G"))
.attr("y", yScale.range()[1] + m[2]/2)
.text("EASING")
.attr("alignment-baseline", "middle")
.attr("text-anchor", "middle")
.attr("fill", "#fff")
.attr("stroke", "#fff")
.attr("stroke-width", 10);
bracketTextR = svg.append("text")
.attr("class","alt-view")
.attr("x", xScaleGroup("G"))
.attr("y", yScale.range()[1] + m[2]/2)
.text("EASING")
.attr("alignment-baseline", "middle")
.attr("text-anchor", "middle")
.attr("fill", "#33691e");
let ybw = yScale.bandwidth();
rows = svg.append("g")
.attr("class","rows alt-view")
.selectAll("path");
rows
.data(stages.filter(d => d != "TRIGGER"))
.enter()
.append("path")
.attr("class", d => `alt-view row row-${d}`)
.attr("d", d => {
let y = yScale(d);
return `M ${0} ${y} L ${width - ybw/4} ${y} L ${width} ${y + ybw/2} L ${width - ybw/4} ${y + ybw} L ${0} ${y + ybw} L ${ybw/4} ${y + ybw/2} Z`;
})
.attr("fill", d => stageCols[d])
.attr("opacity", d => {
return (d == "1") ? 1 : 0.2;
});
partialRows = svg.append("g")
.attr("class","partial-rows alt-view")
.selectAll("path");
partialRows
.data(transitions)
.enter()
.append("path")
.attr("class", d => {
let classes = ['alt-view', 'partial-row'];
for (let a of d.arrows) {
classes.push(`partial-row-${a.from}`);
}
return classes.join(' ');
})
.attr("d", d => {
let y = yScale(d.arrows[0].to);
let x = xScaleGroup(d.group) + aScales[1](0) + aScales[4].bandwidth()*.15 + aScales[4].bandwidth()*1 - 2;
return `M ${x} ${y} ` +
`L ${width - ybw/4} ${y} ` +
`L ${width} ${y + ybw/2} ` +
`L ${width - ybw/4} ${y + ybw} ` +
`L ${x} ${y + ybw} ` +
`Z`;
})
.attr("fill", d => stageCols[d.arrows[0].to])
.attr("opacity", d => {
return (d.arrows[0].from == "1") ? 1 : 1;
});
rowText = svg.append("g")
.attr("class","rowText alt-view")
.selectAll("text");
rowText
.data(stages)
.enter()
.append("text")
.attr("class","alt-view")
.attr("x", 25)
.attr("y", d => yScale(d) + yScale.bandwidth() / 2)
.text(d => (d == 'TRIGGER' ? "⤉⤈ TRIGGER" : `Stage ${d}`))
.attr("alignment-baseline", "central")
.attr("fill", "#33691e");
// circs = svg.append("g")
// .attr("class","circs alt-view")
// .selectAll("circle");
// circs
// .data(stages)
// .enter()
// .append("circle")
// .attr("class","alt-view")
// .attr("cx", d => xScale(d) + xScale.bandwidth()/2)
// .attr("cy", d => yScale(d) + yScale.bandwidth()/2)
// .attr("r", 5)
// .attr("fill", "#000000");
let aw = aScales[4].bandwidth()*1;
arrows = svg.append("g")
.attr("class", "arrows alt-view")
.selectAll("path");
arrows
.data(As.filter(d => d.hasOwnProperty("from")))
.enter()
.append("path")
.attr("class", d => `alt-view arrow arrow-from-${d.from}`)
.attr("d", d => {
let isTightening = stages.indexOf(d.from) < stages.indexOf(d.to);
let left = xScaleGroup(d.group) + aScales[1](0) + aScales[4].bandwidth()*.15,
middle = left + aw/2,
right = left + aw,
start = (isTightening ? yScale(d.from) : yScale(d.from)),
end = (isTightening ? yScale(d.to) : yScale(d.to) + ybw),
point = (isTightening ? yScale(d.to) + aw/2 : yScale(d.to) + ybw - aw/2);
if (isTightening) {
return `M ${right - 1*ybw} ${start} ` +
`L ${right - ybw} ${start} ` +
`Q ${right} ${start}, ${right} ${start + ybw} ` +
`L ${right} ${end} ` +
// `L ${right} ${end - ybw} ` +
// `Q ${right} ${end}, ${right + ybw} ${end} ` +
`L ${right + ybw} ${end + ybw} ` +
`L ${right} ${end + ybw} ` +
`Q ${right - ybw} ${end + ybw}, ${right-ybw} ${end} ` +
`L ${right - ybw} ${start + ybw} ` +
// `L ${right - ybw} ${start + 2*ybw} ` +
// `Q ${right - ybw} ${start + ybw}, ${right-2*ybw} ${start + ybw} ` +
`Z `;
} else {
return `M ${right - ybw} ${start} ` +
`Q ${right - ybw} ${start - ybw}, ${right} ${start - ybw} ` +
`L ${right} ${start} ` +
`Q ${right} ${end + ybw}, ${right - ybw} ${end + ybw} ` +
`Z`;
// return `M ${left} ${start} L ${right} ${start} L ${right} ${end} L ${middle} ${point} L ${left} ${end} Z`;
}
})
// .attr("stroke", d => stageCols[d.from])
.attr("fill", d => `url(#${d.from}-${d.to})`)
.attr("opacity", d => {
return (d.from == "1") ? 1 : 0;
});
// .attr("fill", d => stageCols[d.from]);
// .attr("fill", "#ffffff");
directions = svg.append("g")
.attr("class", "directions alt-view")
.selectAll("path");
directions
.data(As.filter(d => d.hasOwnProperty("from")))
.enter()
.append("path")
.attr("class", d => `alt-view direction direction-from-${d.from}`)
.attr("d", d => {
let isTightening = stages.indexOf(d.from) < stages.indexOf(d.to);
let y = 4,
z = ybw + 15,
a = 2*y,
o = 10 + (ybw/2) - (y/2)
r = 4*y,
ra = (r + y) * (1 - (1/Math.sqrt(2))) + 2, // TODO - use an SVG arc then remove the +2 kluge
v = 10,
s = (isTightening ? 1 : -1);
let x0 = xScaleGroup(d.group) + aScales[1](0) + aScales[4].bandwidth()*.15 + aw - ybw - 10,
y0 = yScale(d.from) + yScale.bandwidth()/2,
pth = `M ${x0} ${y0} `;
pth = pth +
`L ${x0} ${y0 - s*(y/2)} ` +
`L ${x0 + z} ${y0 - s*(y/2)} ` +
`L ${x0 + z} ${y0 - s*(y/2) - s*y} ` +
`L ${x0 + z + a} ${y0} ` +
`L ${x0 + z} ${y0 + s*(y/2) + s*y} ` +
`L ${x0 + z} ${y0 + s*(y/2)} ` +
`L ${x0 + o + y - ra} ${y0 - s*(y/2) + s*y} ` + // v1
`Q ${x0 + o + y} ${y0 - s*(y/2) + s*y}, ${x0 + o + y} ${y0 - s*(y/2) + s*y + s*r} ` + // v2
`L ${x0 + o + y} ${y0 - s*(y/2) + s*y + s*r + s*v} ` + // v3
`L ${x0 + o + 2*y} ${y0 - s*(y/2) + s*y + s*r + s*v} ` + // v4
`L ${x0 + o + (y/2)} ${y0 - s*(y/2) + s*y + s*r + s*v + s*a} ` + // v5
`L ${x0 + o - y} ${y0 - s*(y/2) + s*y + s*r + s*v} ` + // v6
`L ${x0 + o} ${y0 - s*(y/2) + s*y + s*r + s*v} ` + // v7
`L ${x0 + o} ${y0 - s*(y/2) + s*y + s*r} ` + // v8
`Q ${x0 + o} ${y0 - s*(y/2) + s*y}, ${x0 + o - r} ${y0 - s*(y/2) + s*y} ` + // v9
`L ${x0} ${y0 -s*(y/2) + s*y} ` +
`Z`;
console.log(pth);
return pth;
})
.attr("stroke", "#000000")
.attr("fill", "#ffffff")
.attr("opacity", d => {
return (d.from == "1") ? 1 : 0;
});
hoverRows = svg.append("g")
.attr("class","hover-rows alt-view")
.selectAll("path");
hoverRows
.data(stages.filter(d => d != "TRIGGER"))
.enter()
.append("path")
.attr("class","alt-view hover-row")
.attr("d", d => {
let y = yScale(d);
return `M ${0} ${y} L ${width - ybw/4} ${y} L ${width} ${y + ybw/2} L ${width - ybw/4} ${y + ybw} L ${0} ${y + ybw} L ${ybw/4} ${y + ybw/2} Z`;
})
.attr("opacity", 0)
.on("mouseover", function(d) {
d3.selectAll(`.row`).attr('opacity', 0.2);
d3.select(`.row-${d}`).attr('opacity', 1);
d3.selectAll(`.partial-row`).attr('opacity', 0);
d3.selectAll(`.partial-row-${d}`).attr('opacity', 1);
d3.selectAll(`.arrow`).attr('opacity', 0);
d3.selectAll(`.arrow-from-${d}`).attr('opacity', 1);
d3.selectAll(`.direction`).attr('opacity', 0);
d3.selectAll(`.direction-from-${d}`).attr('opacity', 1);
});
let gbw = xScaleGroup.bandwidth();
conditions = svg.append("g")
.attr("class","conditions alt-view")
.selectAll("text");
conditions
.data(transitions)
.enter()
.append("text")
.attr("class","alt-view")
.attr("x", d => xScaleGroup(d.group) + gbw/2)
.attr("y", yScale("TRIGGER") + yScale.bandwidth()/2)
.text(d => d.condition)
.attr("alignment-baseline", "central")
.attr("text-anchor", "middle");
}
draw();
// digitsNumCoreTitle = svg.append("text")
// .text("n")
// .attr("x", m[3])
// .attr("y", m[0] + height - 60)
// .attr("class", "annotation alt-view")
// .attr("text-anchor","end")
// .attr("opacity", Number(page.params.numbers));
// digitsAvgCoreTitle = svg.append("text")
// .text("AVG")
// .attr("x", m[3])
// .attr("y", m[0] + height - 40 + 20*Number(page.params.comparisonSet != "none"))
// .attr("class", "annotation alt-view")
// .attr("text-anchor","end")
// .attr("opacity", Number(page.params.numbers & page.params.averages));
// digitsNumCompTitle = svg.append("text")
// .text("n")
// .attr("x", m[3])
// .attr("y", m[0] + height - 40)
// .attr("class", "annotation alt-view")
// .attr("text-anchor","end")
// .attr("fill", "hsla(0, 100%, 50%, 1)")
// .attr("opacity", Number(page.params.numbers & page.params.comparisonSet != "none"));
// digitsAvgCompTitle = svg.append("text")
// .text("AVG")
// .attr("x", m[3])
// .attr("y", m[0] + height)
// .attr("class", "annotation alt-view")
// .attr("text-anchor","end")
// .attr("fill", "hsla(0, 100%, 50%, 1)")
// .attr("opacity", Number(page.params.numbers & page.params.averages & page.params.comparisonSet != "none"));
// svg.append("g")
// .attr("class", "xAxis alt-view")
// .attr("transform", "translate(0," + (h + m[0]) + ")")
// .call(xAxis);
// svg.append("g")
// .attr("class", "yAxis alt-view")
// .attr("transform", "translate(" + Math.round(m[3]) + ",0)")
// .call(yAxis)
// .selectAll(".tick text")
// .call(util.wrap, 60)
// .attr("transform", "translate(-10,0)");
// dataCore = coagulateCore(page.dataCore, H);
// dataComp = coagulateComp(page.rawComp, H);
// // ########################################################################## //
// // ########################################################################## //
// // ########################################################################## //
// page.update = function() {
// update[page.params.graphType]();
// }
// // ########################################################################## //
// // ########################################################################## //
// // ########################################################################## //
// console.log(svg)
|
//constant File
|
alert("fast")
|
var http = require('http');
var url = require('url');
var cheerio = require('cheerio');
var couchtunerHost = 'couchtuner.ch';
var crypto = require('crypto');
http.createServer(function (req, res) {
function loadPage(options, callback) {
var request = http.request(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
callback(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();
}
function loadVideos(pageUrl) {
var parsedUrl = url.parse(pageUrl);
console.log(parsedUrl);
loadPage({
host: couchtunerHost,
path: parsedUrl.path
}, function(data) {
var $ = cheerio.load(data);
var anotherUrl = $('#content .post .entry strong a').attr('href');
console.log(anotherUrl);
var parsedUrl = url.parse(anotherUrl);
loadPage({
host: parsedUrl.host,
path: parsedUrl.path
}, function(data) {
var $ = cheerio.load(data);
var urls = $('.postTabs_divs iframe').map(function() {
return $(this).attr('src')
}).get();
console.log(urls);
urls.forEach(function(pageUrl) {
if (pageUrl.match(/thevideo/)) {
var parsedUrl = url.parse(pageUrl);
loadPage({
host: parsedUrl.host,
path: parsedUrl.path
}, function(data) {
var videoUrl = data.match(/http.*\.mp4.*'/).pop().replace(/'/g, '');
res.write('["'+ videoUrl + '"]');
res.end();
});
}
});
})
});
}
function loadReleases() {
loadPage({
host: couchtunerHost,
path: '/'
}, function(data) {
var $ = cheerio.load(data);
var links = $('#content .post .tvbox > a');
res.write(JSON.stringify(links.map(function(index, node) {
var parts = $(this).html().replace(/<span.*<\/span>/gi, '').split('<br>');
var style = $('span', this).attr('style');
var imageUrl = '';
if (style) {
imageUrl = '//' + couchtunerHost + style.match(/\(.*\)/gi)[0].replace('(', '').replace(')', '');
}
return {
id: $(this).attr('href'),//crypto.createHash('md5').update($(this).attr('href')).digest('hex'),
title: parts[0].trim(),
subtitle: parts[1].trim(),
imageUrl: imageUrl,
episodeUrl: $(this).attr('href')
};
}).get()));
res.end();
});
}
var parsedUrl = url.parse(req.url);
var pathname = parsedUrl.pathname;
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
switch (pathname) {
case '/releases':
if (parsedUrl.query) {
loadVideos(parsedUrl.query.split('=').pop());
} else {
loadReleases();
}
break;
case '/shows':
res.write('shows');
res.end();
break;
}
}).listen(8081, process.env.IP);
|
const actions = {
selectTool(context, id) {
context.commit('selectTool', id)
}
}
export default actions
|
import React, { useState, useEffect } from "react";
import CardBack from "../components/CardBack";
import CardFront from "../components/CardFront";
import HandDisplay from "../components/HandDisplay";
const Game = ({ dbUrl, userPlayer}, props) => {
// console.log('userPlayer number', userPlayer)
const [gameId, setGameId] = useState(null)
const [globalGameState, setGlobalGameState] = useState({});
const [userHand, setUserHand] = useState([]);
const [userSelections, setUserSelections] = useState([])
// TODO eliminate frontend HAND data for all but 0
const [hand1, setHand1] = useState([]);
const [hand2, setHand2] = useState([]);
const [hand3, setHand3] = useState([]);
const [passCardsCount, setPassCardsCount] = useState(0);
const [passCards, setPassCards] = useState([])
const [passReady, setPassReady] = useState(false)
const [playReady, setPlayReady] = useState(false)
const [playerState0, setPlayerState0] = useState([]);
const [playerState1, setPlayerState1] = useState([]);
const [playerState2, setPlayerState2] = useState([]);
const [playerState3, setPlayerState3] = useState([]);
const [gamePhase, setGamePhase] = useState('deal')
// Event Handler Functions
//////////////////////////////////////////////////////////
// Spread Game State
// Unpacks game state data into local state varibles
//////////////////////////////////////////////////////////
const spreadGameState = (gameStateData) => {
console.log('spreading to useState', gameStateData)
const { players, ...rest } = gameStateData;
setGlobalGameState(rest);
setUserHand([...players[userPlayer].hand]);
setHand1([...players[1].hand]);
setHand2([...players[2].hand]);
setHand3([...players[3].hand]);
setPlayerState0({ ...players[0] });
setPlayerState1({ ...players[1] });
setPlayerState2({ ...players[2] });
setPlayerState3({ ...players[3] });
}
const getGameState = async (id) => {
// console.log("fetching gameState", id);
const resp = await fetch(`${dbUrl}/gameState/getState/${id}`)
const data = await resp.json()
// console.log("fetched gameStateData", data);
return data.data
};
// GAME LOOPS //
const gameLoop = async () => {
console.log('enter gameLoop')
let currentGameState = await startNewGame()
setGameId(currentGameState._id)
console.log('new game data', currentGameState._id, currentGameState)
let maxScore = 0;
let winScore = currentGameState.winScore
while(maxScore < winScore){
console.log('start new hand, current maxScore:', maxScore)
currentGameState = await handLoop(currentGameState._id)
maxScore = currentGameState.maxScore
}
}
const handLoop = async (id) =>{
// alert('start hand loop', gamePhase)
// One pass loop per hand
// local state, set phase to 'pass'. Pass phase set in backend by 'deal' function
setGamePhase('pass')
// Init selections array
const blankSelections = new Array(13)
blankSelections.fill(false)
console.log('blank',blankSelections)
setUserSelections([...blankSelections])
let gameState = await passLoop(id);
setUserSelections([...gameState.players[userPlayer].hand].fill(false))
spreadGameState(gameState)
// Set all cards in hand to unselected, and set new passed to selected
// Enter Trick taking phase
setGamePhase('tricks')
let trickCount = 1;
while ( trickCount <= 13 ){
await loopDelay(3000)
console.log(` trick ${trickCount} begin`)
trickCount = await trickLoop(id, trickCount)
}
return await getGameState(id)
}
//////////////////////////////
// passLoop
// handles waiting for passable cards to be selected
// loops infinitely waiting for all palyers to make selections
// (including user)
// passing of cards is handled by the backend. Each submission of selected
// cards by human or computer triggers a check for all-selected, and subsequent pass
///////////////////////////////
const passLoop = async (id) => {
// Update local state
let gameState = await getGameState(id)
spreadGameState(gameState)
// calculate pass alignment for display
// same calculation happens in backend when pass is executed
const passIndex = gameState.turn % 4;
if(passIndex === 3) return
else if(passIndex === 0){
// alert('pass left')
}else if(passIndex === 1){
alert('pass right')
}else{
alert('pass across')
}
let ready = passesReady(gameState)
let counter = 0;
// TODO remove counter-limit for production
while(!ready && counter < 100){
await loopDelay(500)
// poll DB game state, looking for all players ready
console.log('passloop update localstate')
gameState = await getGameState(id)
ready = passesReady(gameState) || gameState.phase !== 'pass'
// console.log(counter)
counter ++
}
// alert("pass loop complete")
return gameState
}
/////////////////////////////////////
// Trick Loop function
// after cards have been passed
// if user's turn
// loop with long delay (or escape loop cycles)
// when user selects a card and clicks Play button, escape from loop
// else
// poll server gameState with delay
// show current player turn status
const trickLoop = async (id, trickCount) => {
console.log('start trick loop for trick', trickCount, 'game',id)
let waiting = true
let inProgress = true
while(inProgress){
let gameState = await getGameState(id)
console.log(' trick loop',gameState.players[userPlayer].hand)
if(gameState.activePlayer === userPlayer){
// alert('your turn')
console.log("user's turn (pre)")
await loopDelay(3000)
console.log("user's turn (post)")
}else{
while(waiting){
// console.log("other's turn")
await loopDelay(3000)
gameState = await getGameState(id)
console.log(' trickLoop other player', gameState.players[1].hand)
spreadGameState(gameState)
}
}
}
return trickCount += 1;
}
// Gameplay Functions
const handleSelectCard = (card) => {
const selArr = [...userSelections]
const i = userHand.indexOf(card)
if(gamePhase === 'pass'){
selArr[i] = selArr[i] ? false : true
setUserSelections([...selArr])
// max selected = 3, extras replace
if(passCards.includes(card)){
// alert('gamephase = pass ' + card + ' passready', passReady)
if(passReady) setPassReady(false)
passCards.splice(passCards.indexOf(card), 1)
setPassCards([...passCards])
}else{
if(passCards.length === 3){
setPassCards([passCards[1], passCards[2], card ])
}else{
if(passCards.length === 2) setPassReady(true)
setPassCards([...passCards, card])
}
}
}else if(gamePhase === 'tricks'){
// max selected = 1, extras replace
if(passCards.length === 0){
console.log('first selection')
selArr[i] = true
setPlayReady(true)
setPassCards([card])
setUserSelections([...selArr])
}else{
if(passCards[0] === card){
console.log('selected second. remove first')
selArr[i] = false
setUserSelections([...selArr])
setPassCards([])
}else{
console.log('deselecting')
const j = userHand.indexOf(passCards[0])
selArr[i] = true
selArr[j] = false
setUserSelections([...selArr])
setPassCards([card])
}
}
}
}
const handlePass = async () => {
let gameState = await getGameState(gameId)
console.log('passcards, gamestate', passCards, gameState)
passCards.forEach((card)=>{
const i = gameState.players[0].hand.indexOf(card)
gameState.players[0].hand.splice(i,1)
})
gameState.players[0].passes = [...passCards]
console.log('put game state', gameId)
gameState = await putGameStatePassCards(gameState, gameId)
console.log('post-pass game state', gameState)
spreadGameState(gameState)
setPassCards([])
}
const handlePlay = async () => {
alert('play '+ passCards[0])
}
// UTILITY FUNCTIONS
// TODO transition this functionality into a function in backend that checks each time a set of passes are submitted
const passesReady = (gameState) => {
let readyCount = 0
gameState.players.forEach((player)=>{
if(player.passes.length === 3) readyCount++
})
// Return true if all players have selected cards to pass
return readyCount === 4
}
const loopDelay = (ms) => {
return new Promise(resolve=>{
setTimeout(()=>{ resolve('')}, ms)
})
}
///////////////////////////////////////////////////////
// Start New Game -
// Calls Seed function
// Calls Deal function
// Spreads new game state to local state variables
///////////////////////////////////////////////////////
const startNewGame = async () => {
console.log(" starting new Game")
let resp = await fetch(`${dbUrl}/gameState/seed`)
let data = await resp.json()
const id = data.data._id
resp = await fetch(`${dbUrl}/gameState/deal/${id}`)
data = await resp.json()
const newGameData = data.data
spreadGameState(newGameData)
console.log(' newly dealt game data', newGameData)
return newGameData
}
//////////////////////////////////////////////////////////
// Put Game State
// collects local game state and PUTs to db gameState
// - called after each turn or any other alteration
// of game state to be communicated to other players
//////////////////////////////////////////////////////////
const putGameState = async (gameState, id) => {
console.log("putting gameState");
const resp = await fetch(`${dbUrl}/gameState/putState/${id}`,{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(gameState)
})
console.log('PUT gameState response', resp)
};
const putGameStatePassCards = async (gameState, id) => {
console.log("putting gameState");
const resp = await fetch(`${dbUrl}/gameState/passCards/${id}`,{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(gameState)
})
const data = await resp.json()
console.log('passCard new gameState', data.data)
return data.data
};
// JSX Arrays
const userHandDisplay = userHand.map((card, i) => {
return (
<div key={i} className={`card-container ${userSelections[i] ? 'selected' : 'unselected'}`}>
<CardFront
cardValue={card}
handleSelectCard={handleSelectCard}
/>
</div>
)
});
const handDisplay1 = hand1.map((card, i) => {
return <CardBack key={i} />;
});
const handDisplay2 = hand2.map((card, i) => {
return <CardBack key={i} />;
});
const handDisplay3 = hand3.map((card, i) => {
return <CardBack key={i} />;
});
useEffect( () => {
gameLoop()
}, []);
return (
<main className="game-main">
<section className="play-area"></section>
<aside className="north info-area"></aside>
<aside className="east info-area"></aside>
<aside className="south info-area">
<button className={passReady ? 'shown' : 'hidden'} onClick={handlePass}>Pass</button>
<button className={playReady ? 'shown' : 'hidden'} onClick={handlePlay}>Play Card</button>
</aside>
<aside className="west info-area"></aside>
<section className="north hand-area">
<HandDisplay>{handDisplay2}</HandDisplay>
</section>
<section className="east hand-area">
<HandDisplay>{handDisplay3}</HandDisplay>
</section>
<section className="south hand-area">
<HandDisplay>{userHandDisplay}</HandDisplay>
</section>
<section className="west hand-area">
<HandDisplay>{handDisplay1}</HandDisplay>
</section>
<aside className="game-sidebar">Side</aside>
</main>
);
};
export default Game;
|
const express=require("express");
const app=express()
const bodyParser=require("body-parser")
const excel = require('excel4node');
const fs = require('fs');
const path = require('path');
let dirPath = __dirname;
dirPath = dirPath.replace(/\\/gm, "/") + "/";
const port=9000;
let workbook = new excel.Workbook();
app.use(bodyParser.urlencoded());
app.get("/excelFile",(req,res)=>{
try{
let worksheet = workbook.addWorksheet('Sheet 1');
let style = workbook.createStyle({
font: {
color: '#FF0800',
size: 12
},
numberFormat: '#,##0.00; (#,##0.00); -'
});
// Set value of cell A1 to 10 as a number
worksheet.cell(1,1).number(10).style(style);
// Set value of cell B1 to 20 as a number
worksheet.cell(1,2).number(20).style(style);
// Set value of cell C1 to a formula
worksheet.cell(1,3).formula('A1 + B1').style(style);
workbook.write('Excel.xlsx');
return res.download(dirPath+'/Excel.xlsx');
}
catch(ex){
res.status(500).json("internal server error",ex)
}
});
app.listen(port,()=>{
console.log(`port listen on http://localhost:${port}`);
});
|
import React from "react";
import TablaEvaluaciones from '../components/Tablas/TablaEvaluaciones'
import FormEvaluaciones from '../components/Forms/FormEvaluaciones'
import { Row, Col, Modal, ModalHeader, ModalBody, Button } from "reactstrap";// reactstrap components
import API from "../components/server/api";
import NotificationAlert from 'react-notification-alert';
import paginate from 'paginate-array';
export default class Evaluaciones extends React.Component {
//Metodo Constructor
constructor(props) {
super(props);
this.state = {
tipos: [], //arreglo para los tipos
idtipo: '',
tipo: '',
descripcion: '',
editar: false,
modal: false,
visible: true,
tipoerror: '',
size: 4,
page: 1,
currPage: null,
totalpag: null
}
this.ontipoChange = this.ontipoChange.bind(this);
this.ondescripcionChange = this.ondescripcionChange.bind(this);
this.refresh = this.refresh.bind(this);
this.cargar = this.cargar.bind(this);
this.clear = this.clear.bind(this);
this.toggle = this.toggle.bind(this);
this.notify = this.notify.bind(this);
this.siguiente = this.siguiente.bind(this);
this.anterior = this.anterior.bind(this);
this.primerapag = this.primerapag.bind(this);
this.ultimapag = this.ultimapag.bind(this);
this.numero = this.numero.bind(this);
}
//para cargar la informacion en el modal de editar
cargar(user) {
this.setState({
idtipo: user.idtipo,
tipo: user.tipo,
descripcion: user.descripcion,
editar: true
});
this.toggle();
}
//Metodo para las Alertas
notify(place, color, message, icon) {
var options = {};
options = {
place: place,
message: message,
type: color,
icon: icon,
autoDismiss: 5
};
this.refs.notify.notificationAlert(options);
}
//Metodo para obtener los datos de la api
componentDidMount() {
API.get(`tipo`)
.then(res => {
const tipos = res.data;
const { page, size } = this.state;
const currPage = paginate(tipos, page, size);
this.setState({ ...this.state, tipos, currPage});
this.setState({
totalpag: this.state.currPage.totalPages
})
})
}
//metodo para abrir el modal
toggle() {
this.setState(prevState => ({
modal: !prevState.modal
}));
if(this.state.modal===false){
this.clear()
}
}
//para recargar los datos
refresh(datos) {
this.componentDidMount();
}
//cuando haya cambios en tipo
// ontipoChange(tipo) {
// this.setState({ tipo: tipo });
// }
ontipoChange(tipo) {
this.setState({ tipo: tipo }, () => {
this.validartipo();
});
};
validartipo = () => {
const { tipo } = this.state;
this.setState({
tipoerror:
tipo.length > 3 ? null : `<div className='invalid-feedback'>El tipo de evaluación debe tener más de 3 caracteres.</div>`
});
}
//cuando haya cambios en descripcion
ondescripcionChange(descripcion) {
this.setState({ descripcion: descripcion });
}
//metodo para limpiar los campos y el editar
clear() {
this.setState({
idtipo: '',
tipo: '',
descripcion: '',
editar: false,
});
}
anterior() {
const { page, size, tipos } = this.state;
if (page > 1) {
const newPage = page - 1;
const newCurrPage = paginate(tipos, newPage, size);
this.setState({ ...this.state, page: newPage, currPage: newCurrPage });
}
}
siguiente() {
const { currPage, page, size, tipos } = this.state;
if (page < currPage.totalPages) {
const newPage = page + 1;
const newCurrPage = paginate(tipos, newPage, size);
this.setState({ ...this.state, page: newPage, currPage: newCurrPage });
}
}
primerapag() {
const { size, tipos } = this.state;
const newPage = 1;
const newCurrPage = paginate(tipos, newPage, size);
this.setState({ page: newPage, currPage: newCurrPage });
}
ultimapag() {
const { size, tipos,currPage } = this.state;
const newPage = currPage.totalPages;
const newCurrPage = paginate(tipos, newPage, size);
this.setState({ page: newPage, currPage: newCurrPage });
}
numero(numero) {
const { size, tipos } = this.state;
const newPage = numero;
const newCurrPage = paginate(tipos, newPage, size);
this.setState({ page: newPage, currPage: newCurrPage });
}
//metodo para renderizar la vista
render() {
return (
<div className="content">
<Row>
<Col sm="12" md="12" lg="12">
<NotificationAlert ref="notify" />
<Button className="text-center" color="danger" onClick={this.toggle}>{this.props.buttonLabel} Agregar un Tipo de Evaluación</Button>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader align="center" toggle={this.toggle} className="text-center">{!this.state.editar ? "Agregar Nuevo Tipo" : "Editar Tipo"}</ModalHeader>
<ModalBody >
<FormEvaluaciones validartipo={this.validartipo} ontipoChange={this.ontipoChange} ondescripcionChange={this.ondescripcionChange} tipo={this.state.tipo} descripcion={this.state.descripcion} refresh={this.refresh} idtipo={this.state.idtipo} editar={this.state.editar} clear={this.clear} cargar={this.cargar} toggle={this.toggle} notify={this.notify} />
</ModalBody>
</Modal>
<div className="table-resposive">
<TablaEvaluaciones tipos={this.state.tipos} page={this.state.page} currPage={this.state.currPage} numero={this.numero} totalpag={this.state.totalpag} refresh={this.refresh} cargar={this.cargar} notify={this.notify} siguiente={this.siguiente} anterior={this.anterior} primerapag={this.primerapag} ultimapag={this.ultimapag} responsive />
</div>
</Col>
</Row>
</div>
);
}
}
|
function listarPaises() {
$.post("archivos/phps/listarPaises.php").done(function(data) {
$.each(data, function(key, propiedad) {
$("#paisEmpresa").append("<option value='" + propiedad.idPais + "'>" + propiedad.pais + "</option>");
});
});
}
function listarDepartamentos(idPais) {
$("#departamentoEmpresa").html("<option value='x' selected disabled>Seleccione</option>");
$.post("archivos/phps/listarDepartamentos.php", {
info: idPais
}).done(function(data) {
$.each(data, function(key, propiedad) {
$("#departamentoEmpresa").append("<option value='" + propiedad.idDepartamento + "'>" + propiedad.departamento + "</option>");
});
});
}
function listarCiudades(idDepartamento) {
$("#ciudadEmpresa").html("<option value='x' selected disabled>Seleccione</option>");
$.post("archivos/phps/listarCiudades.php", {
info: idDepartamento
}).done(function(data) {
$.each(data, function(key, propiedad) {
$("#ciudadEmpresa").append("<option value='" + propiedad.idCiudad + "'>" + propiedad.ciudad + "</option>");
});
});
}
|
const electron = require('electron').remote;
var express = require('express')
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs-extra');
const cors = require('cors')
// const userDataPath = electron.getPath('userData');
// // We'll use the `configName` property to set the file name and path.join to bring it all together as a string
// let filePath = path.join(userDataPath, opts.configName + '.json');
app.use(cors())
app.use(express.static(path.join(__dirname, './')))
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//add images?
app.get('/data', function(req, res) {
let filePath = path.join(__dirname, '/../../../../Library/Application\ Support/Sherpa-UI/user-preferences.json');
console.log(filePath)
res.sendFile(filePath)
})
app.listen(8080, function() {
console.log('listening on 8080');
});
|
class CentralMessage {
constructor(st) {
augment(this, st)
}
adjust() {}
draw() {
const tx = this.__
const w = tx.tw - lab.mode.sidePanel.w
const h = tx.th
const len = this.label.length
tx
.back(lib.cidx('baseHi'))
.face(lib.cidx('alert'))
.at(ceil(w/2 - len/2), floor(h/2))
.mode(1).set({
period: .5,
})
.print(this.label)
}
}
|
var numero = 1
switch (numero) {
case 1:
console.log("soy un 1");
break; //se usa el break para detener la validacion y que no pase a los otros casos
case 2:
console.log("soy un 2");
break;
case 100:
console.log("si soy un 100");
break;
default: // para finalizar y no validar nada
console.log("no soy nada")
}
|
function mostrar()
{
var repeticion;
var numero;
repeticion = prompt ("ingrese cantidad de veces");
repeticion = parseInt(repeticion);
while (isNaN(repeticion) || repeticion < 1){
repeticion = prompt ("ingrese unicamente numeros");
repeticion = parseInt(repeticion);
}
for (numero = 1; numero <= repeticion; numero++){
alert ("hola Utn fraa");
}
}//FIN DE LA FUNCIÓN
|
import React, { Component } from "react";
import "./ImageCSS.css";
export default class Image extends Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props.src);
return (
<div className="col-md-6">
<div className="description">{this.props.description}</div>
<img
src={this.props.src}
alt=""
max-width="400"
height="270"
className="thumbnail img"
/>
</div>
);
}
}
|
export const List = (state, action) => {
if (typeof state === "undefined") {
return {
tableList: []
};
}
switch (action.type) {
case "tableList":
console.log(state, '&&&&&&');
return Object.assign({}, state, {
tableList: action.payload
});
case "os":
return '24';
default:
return state;
}
}
|
import React, { Component } from "react";
import Panel from "./Panel";
import Api from "../api/Api";
export default class MainProducts extends Component {
constructor() {
super();
this.state = {newProducts: [], featuredProducts: []};
}
componentWillMount() {
fetch(`http://${Api.getBaseUrl()}/public/product?order=create_date®istersPerPage=6`).then(response => response.json())
.then(json => this.setState({newProducts: json.products}))
.then(() => console.log(this.state))
.catch(err => console.error(err));
}
render() {
return (
<div className="span9">
<h4>Novidades na loja </h4>
<ul className="thumbnails">
{this.state.newProducts.map(product => (
<Panel href="/" img={product.photos[0] ? `http://${Api.getBaseUrl()}${product.photos[0].url}` : "https://scontent.fcgh8-1.fna.fbcdn.net/v/t1.0-9/14600914_1429503647079262_7782924176407537284_n.jpg?_nc_cat=0&_nc_eui2=v1%3AAeEgqc4Fymvc1CP0EpiQ2I2Ndo62GJuMnN5Rrx9FfXjlRngVXwd-QJ_PvdyQFedeXyXSVrYDuOdc_Lau9t-wWSqDkrHIUtGWQG4KLVrcNNFIig&oh=100a838edcdecb2262d03dc94f7b9686&oe=5B6BBC49"} name={product.name} price={product.price} key={product._id}/>
))}
</ul>
</div>
)
}
}
|
import fetch from '@/utils/fetch'
/**
* login 校验用户和密码是否正确
* @param { String } username 用户名称
* @param { String } password 用户密码
* @return {[type]} [description]
*/
export function login(username, password) {
return fetch({
url: '/user/login',
method: 'post',
data: {
username,
password
}
})
}
/**
* getInfo 获取用户新
* @param { Object } token 用户唯一token
* @return {[type]} [description]
*/
export function getInfo(token) {
return fetch({
url: '/user/info',
method: 'get',
params: { token }
})
}
/**
* logout 退出登录
* @return {[type]} [description]
*/
export function logout() {
return fetch({
url: '/user/logout',
method: 'post'
})
}
|
import React from "react";
import "./artist.css";
const Fourth = () => {
return (
<div className="container">
<div className="card">
<img
class="card-img-top img-fluid"
src="https://www.lamontagne.fr/photoSRC/Gw--/guillaume-dottin-magicien_4584013.jpeg"
alt=""
/>
<div className="title">
<h2>Guillaume Dottin</h2>
<h3>Great Illusions</h3>
<p className="overview">
It is in a dreamlike and mysterious universe that Guillaume Dottin
will make you travel.
<br />
His great illusions are unique creations for the circus
Pinder.
<br />
A surprising number that will take your breath away….
<br />
Besides, you will be able to hold your breath as much as our
illusionist in his aquarium ...
</p>
</div>
</div>
</div>
);
}
export default Fourth;
|
(function () {
"use strict";
describe("AddDevicePairingModalService", function () {
var service, $modal;
beforeEach(inject(function(_$injector_) {
service = _$injector_.get("AddDevicePairingModalService");
$modal = _$injector_.get("$modal");
}));
describe("isPairableDevice", function () {
it("should return true if the device is a set top box or smart card", function () {
expect(service.isPairableDevice({ deviceType: "STB_DVB_SC" })).toBe(true);
expect(service.isPairableDevice({ deviceType: "STB_DVB_STB" })).toBe(true);
});
it("should return false if the device is not a set top box or smart card", function () {
expect(service.isPairableDevice({ deviceType: "STB_DVB_NSC1" })).toBe(false);
expect(service.isPairableDevice({ deviceType: "STB_DVB_NSC2" })).toBe(false);
});
});
describe("isNotPairableDevice", function () {
it("should return false if the device is a set top box or smart card", function () {
expect(service.isNotPairableDevice({ deviceType: "STB_DVB_SC" })).toBe(false);
expect(service.isNotPairableDevice({ deviceType: "STB_DVB_STB" })).toBe(false);
});
it("should return true if the device is not a set top box or smart card", function () {
expect(service.isNotPairableDevice({ deviceType: "STB_DVB_NSC1" })).toBe(true);
expect(service.isNotPairableDevice({ deviceType: "STB_DVB_NSC2" })).toBe(true);
});
});
describe("openAddDevicePairingModal", function () {
beforeEach(function () {
spyOn($modal, "open").and.callThrough();
});
it("should do nothing if the provided device is not pairable", function () {
service.openAddDevicePairingModal({ smsDeviceId: "1", deviceType: "STB_DVB_NSC1" });
expect($modal.open).not.toHaveBeenCalled();
});
it("should call the $modal.open method with the expected parameters", function () {
service.openAddDevicePairingModal({ smsDeviceId: "1", deviceType: "STB_DVB_SC" });
expect($modal.open).toHaveBeenCalledWith({
templateUrl: "app/networks/devices/add_device_pairing_modal.html",
controller: "AddDevicePairingModalCtrl as vm",
size: "md",
resolve: {
device: jasmine.any(Function),
devices: jasmine.any(Function)
}
});
});
});
});
}());
|
import {
REQUEST_LOADING,
REQUEST_SUCCESS,
REQUEST_FAILED,
GET_REQUESTS_LOADING,
GET_REQUESTS_SUCCESS,
GET_REQUESTS_FAILED,
} from '../constants/request.js';
export const request = (mediaId, mediaType) => ({
mediaId,
mediaType,
type: REQUEST_LOADING,
});
export const requestSuccess = () => ({
type: REQUEST_SUCCESS,
});
export const requestFailed = error => ({
type: REQUEST_FAILED,
error,
});
export const getRequests = () => ({
type: GET_REQUESTS_LOADING,
});
export const getRequestsSuccess = requests => ({
requests,
type: GET_REQUESTS_SUCCESS,
});
export const getRequestsFailed = error => ({
type: GET_REQUESTS_FAILED,
error,
});
|
const mongoose = require('mongoose');
const sharedFun = require('../services/sharedFun');
const Bluebird = require("bluebird");
const _ = require('lodash');
const async = require('async');
// const sharp = require('../controller/sharp');
/*---------- Imgs Schema------------*/
const MySchema = mongoose.Schema({
fileData:{type:String},
},{timestamps: true});
/*----- statics --- */
MySchema.statics = {
add:(Data,cb)=>{
if(Data){
// sharp.resize({width:200},new Buffer(Data.split(",")[1], 'base64'),(err,img)=>{
// let d=Data.split(",")[0]+','+Buffer.from(img).toString('base64');
let newItem = new Files({fileData:Data});newItem.save(cb);
// });
}
else{cb(null,false);}
},
Add_Multiple:(item,names,oldImg,cb)=>{
Files.DocDelete({_id:oldImg},(err,doc)=>{
if(err){return cb(err)}
if(_.isEmpty(names)){return cb();}
async.eachOfSeries(names,(v,i,cback)=>{let IsArr=_.isArray(item[v]);
let ItemFiles = IsArr?item[v]:[item[v]];
async.eachOfSeries(ItemFiles,(filedata,i2,cback2)=>{
if(!(v in item) || ((v in item) && !filedata) || (filedata && filedata.length <= 24)){return cback2();}
Files.add(filedata,(err,doc)=>{
if(err){return cback2(err);}
if(IsArr){item[v][i2]=_.get(doc,'_id',null);}
else{item[v]=_.get(doc,'_id',null);}
cback2();
});
},cback);
},cb);
});
}
,Render:(req,res)=>{
Files.findOne({_id:req.params.id})
.exec((err,doc)=>{if(!doc){return;}
sharedFun.Render(req.query,doc.fileData,res);});
},Download:(req,res)=>{
Files.findOne({_id:req.params.id})
.exec((err,doc)=>{if(!doc){return;}
sharedFun.Download(doc.fileData,doc._id,res);});
},DocDelete:(q,cb)=>{
Files.find(q)
.then((modules) => Bluebird.each(modules, (module) => module.remove()))
.then((doc)=>cb(null,doc.length))
.catch(cb)
}
,list:(options,cb)=>{
var criteria = options.criteria || {};
Files.find(criteria)
.select(options.select)
.sort({'createdAt': -1})
.limit(options.perPage).skip(options.perPage * options.page)
.exec(cb);
}
}
/*==============( post remove )========================*/
MySchema.post('remove',(doc)=>{
console.log('====== file removed ==========')
});
/*======================================*/
const Files = module.exports = mongoose.model("file",MySchema);
|
import { ActionsTypes } from '../actions';
const initialState = {
isFetchingAverage: false,
isFetchingUsersCalifications: false,
average: '',
califications: [],
};
export default function reputation(state = initialState, action = {}) {
switch (action.type) {
case ActionsTypes.AVERAGE_CALIFICATION_REQUEST:
return {
...state,
isFetchingAverage: true,
};
case ActionsTypes.AVERAGE_CALIFICATION_RESPONSE:
return {
...state,
isFetchingAverage: false,
average: action.response
};
case ActionsTypes.USERS_CALIFICATIONS_REQUEST:
return {
...state,
isFetchingUsersCalifications: true,
};
case ActionsTypes.USERS_CALIFICATIONS_RESPONSE:
return {
...state,
isFetchingUsersCalifications: false,
califications: action.response
};
default:
return state;
}
}
|
before('protect from forgery', function () {
protectFromForgery('bb8221367e3490cd21e362b1400df121e8a47957');
});
|
slide[MODULEID].buildThumbList = function()
{
for (var i=0;i<this.umg_titles.length ;i++ )
{
var item = "";
if (this.umg_mouseoverbehavior == "moveto")
{
item = "<a href='javascript:void(0);' onmouseover='slide[MODULEID].navigateTo("+i+")' class='umg_page' id='page[MODULEID]_"+i+"'>"+jQuery(this.umg_titles[i]).html()+"</" + "a>";
}
else if (this.umg_mouseoverbehavior == "scroll")
{
item = "<a href='javascript:slide[MODULEID].navigateTo("+i+")' onmouseover='slide[MODULEID].hoverTo("+i+")' class='umg_page' id='page[MODULEID]_"+i+"'>"+jQuery(this.umg_titles[i]).html()+"</" + "a>";
}
else //default, do nothing
{
item = "<a href='javascript:slide[MODULEID].navigateTo("+i+")' class='umg_page' id='page[MODULEID]_"+i+"'>"+jQuery(this.umg_titles[i]).html()+"</" + "a>";
}
this.umg_thumbs.append(item);
}
}
slide[MODULEID].previousHover = -1;
slide[MODULEID].hoverTo = function(index)
{
this.ensureVisibility(index, this.previousHover, 2000, false);
slide[MODULEID].previousHover = index;
}
slide[MODULEID].onMoveTo = function(index)
{
if (this.umg_index >= 0)
{
var previousThumb = jQuery(this.umg_thumbs.find("#page[MODULEID]_" + this.umg_index));
previousThumb.removeClass("active");
previousThumb.css("background-position", "0px -120px");
}
var currentThumb = jQuery(this.umg_thumbs.find("#page[MODULEID]_" + index));
currentThumb.addClass("active");
this.ensureVisibility(index, this.umg_index, "fast", true);
}
slide[MODULEID].ensureVisibility = function(index, compareToIndex, speed, ensureTitleBg)
{
if(this.umg_thumbs.width() <= this.umg_container.width())
{
slide[MODULEID].ensureTitleBgPosition(index);
return;
}
var currentThumb = jQuery(this.umg_thumbs.find("#page[MODULEID]_" + index));
if (index > compareToIndex)
{
//scroll right
var xOffset = currentThumb.position().left+currentThumb.width()+this.umg_thumbs.position().left;
if (xOffset > this.umg_container.width() * .67)
{
var scrollTo = (currentThumb.width() / 2 + currentThumb.position().left)*-1 + this.umg_container.width() * .5;
if (scrollTo + this.umg_thumbs.width() < this.umg_container.width())
{
scrollTo = this.umg_container.width() - this.umg_thumbs.width();
}
if (ensureTitleBg)
{
this.umg_thumbs.animate({"left":scrollTo},"fast", function(){
slide[MODULEID].ensureTitleBgPositionEx(index, index);
});
}
else
{
slide[MODULEID].umg_thumbs.animate({"left":scrollTo},"fast");
}
return;
}
}
else
{
//to left
var xOffset = currentThumb.position().left+this.umg_thumbs.position().left;
if (xOffset < this.umg_container.width() * .33)
{
var scrollTo = (currentThumb.width() / 2 + currentThumb.position().left)*-1 + this.umg_container.width() * .5;
if (scrollTo > 0)
{
scrollTo = 0;
}
if(scrollTo+this.umg_thumbs.width() < this.umg_container.width())
{
scrollTo = this.umg_container.width() - this.umg_thumbs.width();
}
if (ensureTitleBg)
{
this.umg_thumbs.animate({"left":scrollTo},"fast", function(){
slide[MODULEID].ensureTitleBgPositionEx(index, index);
});
}
else
{
slide[MODULEID].umg_thumbs.animate({"left":scrollTo},"fast");
}
return;
}
}
if (ensureTitleBg)
{
this.ensureTitleBgPosition(index);
}
}
slide[MODULEID].ensureTitleBgPositionEx = function(index, finishIndex)
{
if (finishIndex >= 0)
{
if (finishIndex != this.umg_index)
{
return;
}
}
var currentThumb = jQuery(this.umg_thumbs.find("#page[MODULEID]_" + index));
var currentThumbWidth = currentThumb.width() + currentThumb.css("padding-left").replace("px", "") * 1 + currentThumb.css("padding-right").replace("px", "") * 1;
var xOffset;
var yRatio = (currentThumb.position().left + currentThumbWidth / 2 + this.umg_thumbs.position().left) / this.umg_container.width();
var yOffset;
if (yRatio < 1/3)
{
xOffset = currentThumbWidth-500-10;
yOffset = 0;
}
else if (yRatio < 2/3)
{
xOffset = currentThumbWidth/2-500+15;
yOffset = -180;
}
else
{
yOffset = -240;
xOffset = -500+40;
}
currentThumb.css("background-position", xOffset+"px "+yOffset+"px");
}
slide[MODULEID].ensureTitleBgPosition = function(index)
{
slide[MODULEID].ensureTitleBgPositionEx(index, -1);
}
|
/*$Rev: 1947 $ Revision number must be in the first line of the file in exactly this format*/
/*
Copyright (C) 2009 Innectus Corporation
All rights reserved
This code is proprietary property of Innectus Corporation. Unauthorized
use, distribution or reproduction is prohibited.
$HeadURL: http://info.innectus.com.cn/innectus/trunk/loom/App/app/public/jscript_dev/widgets/floatingbuttons.js $
$Id: floatingbuttons.js 1947 2010-06-04 19:15:09Z tesanto $
*/
(function(){
function FloatingButtons(){
}
FloatingButtons.prototype.init = function(options){
this._skin = options.skin||'standard';
this._tooltip = document.createElement('div');
document.body.appendChild(this._tooltip);
this._tooltip.appendChild(document.createElement('div'));
this._tooltip.firstChild.className = "isw_floatingButtonTip";
this._tooltip.style.position = 'absolute';
this._hideTip();
this._main = document.createElement('div');
this.attachParent(options.parent||document.body);
this._main.className = "isw-"+this._skin;
this._main.innerHTML = "<table class='isw_floatingButton'><tbody><tr></tr></tbody></table>";
this._rows = this._main.firstChild.firstChild;
if (options.buttons) {
for (var i = 0; i < options.buttons.length; i++) {
this.addButton(options.buttons[i]);
}
}
this.hide();
};
/**
*
* @param {Object} buttonInfo
* @param buttonInfo.onImage
* @param buttonInfo.offImage
* @param buttonInfo.tip
* @param buttonInfo.onClick
*/
FloatingButtons.prototype.addButton = function(buttonInfo){
var that = this;
var cell = document.createElement('td');
cell.className = "isw_floatingButton";
var button = document.createElement('img');
button.className = "isw_floatingButton";
button.src = buttonInfo.offImage;
cell.appendChild(button);
this._rows.appendChild(cell);
button.onmouseover = function(e){
that._showTip(this,buttonInfo.tip);
this.src = buttonInfo.onImage;
}
button.onmouseout = function(e){
this.src = buttonInfo.offImage;
that._hideTip();
}
button.onclick = function(e){
buttonInfo.onClick();
return INNECTUS.Event.Mouse.cancelBubble(e);
}
button = null;
cell = null;
};
FloatingButtons.prototype.attachParent = function(parent){
parent = INNECTUS.element(parent);
if(this._main.parentNode != parent){
parent.appendChild(this._main);
}
};
FloatingButtons.prototype.detachParent = function(){
this.attachParent(document.body);
this.hide();
};
FloatingButtons.prototype.show = function(){
if (this._main) {
//update position
var height = this._main.parentNode.offsetHeight;
var width = this._main.parentNode.offsetWidth;
this._main.style.display = 'block';
this._main.style.marginTop = (-height) + 'px';
this._main.style.marginLeft = (width-this._main.firstChild.offsetWidth) + 'px';
}
};
FloatingButtons.prototype.hide = function(){
if (this._main) {
this._main.style.display = 'none';
}
};
FloatingButtons.prototype._showTip = function(button, tip){
this.show();
var bb = INNECTUS.Graphics.getBoundingBox(button, true);
this._tooltip.style.display = 'block';
this._tooltip.firstChild.innerHTML = tip;
this._tooltip.style.top = (bb.bottom+4) + "px";
this._tooltip.style.left = bb.left + "px";
button = null;
};
FloatingButtons.prototype._hideTip = function(){
this._tooltip.style.display = 'none';
};
INNECTUS.register("FloatingButtons", FloatingButtons);
////////////////////////////////////
/////////////////////////////////////
////////////////////////////////////
/////////////////////////
//TODO: Remove this widget and just use the other one. right now only the reaction edtior
//is using the old one since the new one requires a little more setup to get working.
function FloatingButtonsOld(){
this.setClassStyle("floatingButtons")
this._spacing = 4;
this._parent = null;
this._visible = false;
this._toolTip = document.createElement("div");
this._toolTip.className = this._hideClass;
this._buttons = [];
}
/**
* parent
* spacing
* className
*/
FloatingButtonsOld.prototype.init = function(options){
if(options.spacing)
this._spacing = options.spacing;
if(options.className)
this.setClassStyle(options.className);
if(options.parent)
this.setParent(options.parent);
};
FloatingButtonsOld.prototype.setParent = function(parent){
this._parent = INNECTUS.element(parent);
this.updatePosition();
};
FloatingButtonsOld.prototype.show = function() {
if(!this._visible) {
this._visible = true
this.updatePosition();
}
};
FloatingButtonsOld.prototype.hide = function() {
if(this._visible) {
this._visible = false;
for(var i = 0; i < this._buttons.length; i++){
INNECTUS.Graphics.addClass(this._buttons[i], this._hideClass);
}
}
};
FloatingButtonsOld.prototype.addButton = function(tooltip, onImage, offImage, onClick) {
var that = this; //callback handle
var button = document.createElement("div");
button.className = this._className;
var img = document.createElement("img");
img.className = this._className;
img.src = offImage;
button.appendChild(img);
this._buttons.push(button);
button.onclick = function(e) {
onClick();
e = e||window.event;
e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
};
button.onmouseover = function() {
that._showToolTip(this, tooltip);
img.src = onImage;
};
button.onmouseout = function() {
that._hideToolTip();
img.src = offImage;
};
button.onmousedown = function() {
//INNECTUS.Graphics.addClass(that._toolTip, that._toolTipSelectClass);
};
button.onmouseup = function() {
//INNECTUS.Graphics.removeClass(that._toolTip, that._toolTipSelectClass);
};
};
FloatingButtonsOld.prototype.updatePosition = function(){
if(this._visible && this._parent){
var bb = INNECTUS.Graphics.getBoundingBox(this._parent);
var offset = bb.right;
for(var i =0; i < this._buttons.length; i++){
var button = this._buttons[i];
INNECTUS.Graphics.removeClass(button, this._hideClass);
if(button.parentNode != this._parent)
this._parent.appendChild(button);
offset -= (this._spacing + button.offsetWidth);
button.style.top = (this._spacing + bb.top)+"px";
button.style.left = offset + "px";
button._toolTipLeft = offset;
button._toolTipBottom = (2*this._spacing) + button.offsetHeight + bb.top;
}
if(this._toolTip.parentNode != this._parent)
this._parent.appendChild(this._toolTip);
}
};
FloatingButtonsOld.prototype.setClassStyle = function(className) {
this._className = className;
this._hideClass = this._className + "Hide";
this._toolTipClass = this._className + "ToolTip";
this._toolTipSelectClass = this._className + "Select";
};
FloatingButtonsOld.prototype._showToolTip = function(button, text) {
if(this._toolTip.className == this._hideClass) {
this._toolTip.className = this._toolTipClass;
this._toolTip.innerHTML = text;
this._toolTip.style.top = button._toolTipBottom + "px";
this._toolTip.style.left = button._toolTipLeft + "px";
}
};
FloatingButtonsOld.prototype._hideToolTip = function() {
this._toolTip.className = this._hideClass;
};
INNECTUS.register("FloatingButtonsOld", FloatingButtonsOld);
}());
|
import Joi from 'joi';
import pool from '../database/dbConnection';
import { queryUsersByEmail } from '../database/queries';
import { newUserSchema, loginSchema } from '../utilities.js/inputSchema';
export default class UserValidation {
static handleSignup(request, response, next) {
const { error } = Joi.validate(request.body, newUserSchema, { abortEarly: false });
if (error !== null) {
response.status(400)
.json({
status: 400,
error: error.details.map(d => d.context),
});
return false;
}
pool.query(queryUsersByEmail, [request.body.email])
.then((data) => {
if (data.rowCount !== 0) {
return response.status(409)
.json({
status: 409,
error: 'Email already exist, please use another email or login.',
});
}
next();
});
}
static handleLogin(request, response, next) {
const { error } = Joi.validate(request.body, loginSchema, { abortEarly: false });
if (error !== null) {
response.status(400)
.json({
status: 400,
error: error.details.map(d => d.context),
});
return false;
}
const isEmail = [request.body.email];
pool.query(queryUsersByEmail, isEmail)
.then((data) => {
if (data.rowCount === 0) {
response.status(400)
.json({
status: 400,
error: 'Sorry, the credentials you provided is incorrect. try again',
});
}
return next();
});
}
}
|
/**
* Created by Manideep.
*/
$(document).ready(function(){
$('#submitbutton').click(function(){
var searchTerm = $('#searchbar').val();
var wikiurl = "https://en.wikipedia.org/w/api.php?action=opensearch&search="+ searchTerm +"&format=json&callback=?";
$.ajax({
type: "GET",
url: wikiurl,
async:false,
dataType:"json",
success: function(data){
/* heading:console.log(data[1][0]);
desc: console.log(data[2][0]);
link: console.log(data[3][0]);*/
$('#output').html(' ');
for(var i=0;i<data[1].length;i++){
$('#output').prepend('<div id="search-item"><h1><a target="_blank" href="'+data[3][i]+'">'+data[1][i] +'</a></h1><p>'+data[2][i]+'</p></div>');
}
$('#searchbar').val('');
},
error: function(errorMessage){
alert("Error");
}
});
});
$('#searchbar').keypress(function(e){
if(e.which == 13){
$('#submitbutton').click();
}
});
});
|
/*
* PB_JIT -- Q1-controller.js
*
* Author: @pablo
*
* Purpose: controller for Q1 page
*
* Version: 1.0.0
*
*/
var Q1Ctrl = function($scope,$timeout,$state,s_Main,d_orders){
order_data = (d_orders.d_orders)[2016110401];
// map
$scope.map_mode_v = true;
$scope.map_mode_r = 'Map';
// leaflet map
single_customer_map('osm_q1',order_data,s_Main);
$scope.centerx = order_data.user_data.coords.split(',')[0];
$scope.centery = order_data.user_data.coords.split(',')[1];
$scope.zoom = 15;
$scope.type = 'MapTypeId.SATELLITE';
// map mode
$scope.map_mode = function(mode){
if(mode=='map'){
$scope.map_mode_v = true;
} else {
$scope.map_mode_v = false;
}
}
function show_data(order_data_array){
// set
$scope.order_data = order_data;
// times
$scope.preferred_delivery_time = timestamp_to_hm(order_data.preferred_delivery_time);
$scope.stimated_delivery_time = 0000; //++++ timestamp_to_hm(order_data.altlp.stimated_delivery_time);
$scope.delay_delivery_time = 1111; ///+++ timestamp_to_hm(order_data.altlp.stimated_delivery_time-order_data.delivery.preferred_delivery_time-3600);
// items
$scope.items = order_data.items;
console.log(order_data.items[0]);
}
// init
$timeout(function(){
show_data(22);
});
};
Q1Ctrl.$inject =['$scope','$timeout','$state','s_Main','d_orders'];
angular
.module('PB_jit')
.controller('Q1Ctrl', Q1Ctrl)
|
const { entity, field } = require('@herbsjs/gotu')
const Repository = require('../src/repository')
const assert = require('assert')
describe('Repository', () => {
const givenAnRepositoryClass = (options) => {
return class ItemRepositoryBase extends Repository {
constructor() {
super(options)
}
}
}
describe('Entity field to Collection field converter', () => {
const givenAnEntity = () => {
return entity('A entity', {
id: field(Number),
field1: field(Boolean),
fieldName: field(Boolean)
})
}
})
})
|
class Scissors {
}
|
let capture = document.querySelector("#capture");
capture.onclick = element => {
chrome.tabs.captureVisibleTab(
null,
{ format: "jpeg", quality: 100 },
dataUrl => {
let a = document.createElement("a");
a.href = dataUrl;
a.download = `capture_${formatDate(new Date(), "yyyyMMddHHmmss")}.jpg`;
a.click();
}
);
};
const formatDate = (date, format) => {
format = format.replace(/yyyy/g, date.getFullYear());
format = format.replace(/MM/g, ("0" + (date.getMonth() + 1)).slice(-2));
format = format.replace(/dd/g, ("0" + date.getDate()).slice(-2));
format = format.replace(/HH/g, ("0" + date.getHours()).slice(-2));
format = format.replace(/mm/g, ("0" + date.getMinutes()).slice(-2));
format = format.replace(/ss/g, ("0" + date.getSeconds()).slice(-2));
format = format.replace(/SSS/g, ("00" + date.getMilliseconds()).slice(-3));
return format;
};
|
/* eslint-disable func-style,no-return-await */
const qiniu = require('qiniu');
module.exports = class extends think.Service {
/**
* 七牛上传
* @param filePath 要上传文件的本地路径
* @param key 上传到七牛后保存的文件名
* @returns {*}
*/
async upload(filePath, key, option, istoken = false) {
// this.cacheKey = this.tablePrefix + 'options';
// if (think.isEmpty(option)) {
// option = await think.cache('options').upload.option
// }
// console.log(JSON.stringify(option))
// let $option = await think.cache(this.cacheKey);
// let $upload = $option.upload;
// qiniu.conf.ACCESS_KEY = option['ak'];
// qiniu.conf.SECRET_KEY = option['sk'];
const bucket = option.bucket;
const mac = new qiniu.auth.digest.Mac(option.ak, option.sk);
const options = {
scope: bucket + ':' + key
}
const putPolicy = new qiniu.rs.PutPolicy(options);
// 用于前端直传直接返回 token
if (istoken && filePath === null) {
const putPolicy = new qiniu.rs.PutPolicy({scope: bucket});
// console.log(putPolicy.uploadToken(mac));
return putPolicy.uploadToken(mac);
}
const uploadToken = putPolicy.uploadToken(mac);
const config = new qiniu.conf.Config();
// config.zone = qiniu.zone.Zone_z0;
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();
// file
function uploadFile(uploadToken, key, filePath, putExtra) {
const deferred = think.defer();
formUploader.putFile(uploadToken, key, filePath, putExtra, function (respErr, respBody, respInfo) {
if (respErr) {
throw respErr;
}
if (respInfo.statusCode === 200) {
console.log(respBody);
deferred.resolve(respBody);
} else {
console.log(respInfo.statusCode);
console.log(respBody);
deferred.resolve(false);
}
});
return deferred.promise;
}
return await uploadFile(uploadToken, key, filePath, putExtra);
}
// 删除资源
async remove(key, option) {
if (think.isEmpty(option)) {
option = await think.cache('options').upload
}
const mac = new qiniu.auth.digest.Mac(option.ak, option.sk);
const config = new qiniu.conf.Config();
// config.useHttpsDomain = true;
config.zone = qiniu.zone.Zone_z0;
const bucketManager = new qiniu.rs.BucketManager(mac, config);
const bucket = option.bucket;
const delfile = (bucket, key) => {
const deferred = think.defer();
bucketManager.delete(bucket, key, function (err, respBody, respInfo) {
if (err) {
console.log(err);
// throw err;
deferred.resolve(false);
} else {
console.log(respInfo.statusCode);
console.log(respBody);
deferred.resolve(true);
}
});
return deferred.promise;
}
return await delfile(bucket, key);
}
// 获取文件信息
async stat(key, option) {
if (think.isEmpty(option)) {
option = await think.cache('options').upload
}
// let setup = think.config("setup");
qiniu.conf.ACCESS_KEY = option.ak;
qiniu.conf.SECRET_KEY = option.sk;
const bucket = option.bucket
function stat() {
const deferred = think.defer();
// 构建bucketmanager对象
const client = new qiniu.rs.Client();
// 获取文件信息
client.stat(bucket, key, function (err, ret) {
if (!err) {
console.log(ret.hash, ret.fsize, ret.putTime, ret.mimeType);
deferred.resolve(ret);
} else {
console.log(err);
deferred.resolve(err);
}
});
return deferred.promise;
}
return await stat();
}
// 音视频转码
async pfop(option) {
if (think.isEmpty(option)) {
option = await think.cache('options').upload
}
// let $option = await think.cache("$option");
// let $upload = JSON.parse($option.upload);
qiniu.conf.ACCESS_KEY = option.ak;
qiniu.conf.SECRET_KEY = option.sk;
const bucket = option.bucket;
// 要转码的文件所在的空间和文件名
const key = 'create-project.mp4';
// 转码所使用的队列名称。
const pipeline = 'abc';
// 要进行转码的转码操作。
let fops = "avthumb/mp4/s/640x360/vb/1.25m"
// 可以对转码后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当前空间
const saveas_key = qiniu.util.urlsafeBase64Encode(saved_bucket + ':' + saved_key);
fops = fops + '|saveas/' + saveas_key;
// console.log(saveas_key);
const opts = {
pipeline: pipleline
};
const PFOP = qiniu.fop.pfop(bucket, key, fops, opts, function (err, ret) {
if (!err) {
console.log(ret);
// 上传成功, 处理返回值
// console.log('curl ' + 'http://api.qiniu.com/status/get/prefop?id=' + ret.persistentId);
} else {
// 上传失败, 处理返回代码
// console.log(err);
}
});
}
async download(key, option) {
if (think.isEmpty(option)) {
option = await think.cache('options').upload
}
const mac = new qiniu.auth.digest.Mac(option.ak, option.sk);
const config = new qiniu.conf.Config();
const bucketManager = new qiniu.rs.BucketManager(mac, config);
// TODO: 待处理 https 访问配置,空间访问域名
const http_ = think.config("http_") == 1 ? "http" : "https";
const publicBucketDomain = `${http_}://${option.domain}`;
// 公开空间访问链接
const publicDownloadUrl = bucketManager.publicDownloadUrl(publicBucketDomain, key);
console.log(publicDownloadUrl);
return publicDownloadUrl;
}
}
|
export { classname } from './classname'
export { path } from './object_path'
export { t } from './i18n'
|
module.exports = function(sequelize, DataTypes) {
var Categorie = sequelize.define(
"Categorie",
{
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [45]
}
},
color: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [45]
}
}
},
{
freezeTableName: true
}
);
Categorie.associate = function(models) {
Categorie.hasMany(models.Event, {
onDelete: "restrict",
onUpdate: "restrict"
});
};
return Categorie;
};
|
import React from 'react'
import { Button, Card } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import WeatherIconSmall from '../components/WeatherIconSmall'
import { locationAutocompleteSearch } from '../actions/acuuWeatherApiActions'
const FavoriteCard = ({ city, icon, temp, text }) => {
const dispatch = useDispatch()
const themeReducer = useSelector(({ themeReducer }) => themeReducer)
const degreesReducer = useSelector(({ degreesReducer }) => degreesReducer)
let history = useHistory()
const handleShowMore = () => {
dispatch(locationAutocompleteSearch(city))
history.push('/')
}
return (
<Card
className='mx-auto text-center shadow'
style={{ border: 'none', borderRadius: '20px' }}
bg={themeReducer.theme ? 'light' : 'dark'}
text={themeReducer.theme ? 'dark' : 'light'}
>
<Card.Header>
<h4>{city}</h4>
</Card.Header>
<Card.Body>
<WeatherIconSmall number={icon} />
<br />
<small>{text}</small>
<p>
{degreesReducer.degrees
? parseInt(temp)
: parseInt((temp * 9) / 5 + 32)}{' '}
{degreesReducer.degrees ? '°C' : '°F'}
</p>
</Card.Body>
<Button
variant={themeReducer.theme ? 'light' : 'dark'}
onClick={handleShowMore}
>
Show More
</Button>
</Card>
)
}
export default FavoriteCard
|
import { TabbedPage, TabbedPageTab as Tab, TitleHeader, DescriptionHeader } from "layout";
import { FormattedMessage as T } from "react-intl";
import { default as SignTab } from "./SignMessage";
import { default as ValidateAddressTab } from "./ValidateAddress";
import { default as VerifyMessageTab } from "./VerifyMessage";
const PageHeader = () =>
<TitleHeader
iconClassName="security"
title={<T id="security.title" m="Security Center" />}
/>;
const TabHeader = () =>
<DescriptionHeader
description={<T id="security.description" m="Various tools that help in different aspects of crypto currency security will be located here." />}
/>;
export default () => (
<TabbedPage header={<PageHeader />} >
<Tab path="/security/sign" component={SignTab} header={TabHeader} link={<T id="security.tab.sign" m="Sign Message"/>}/>
<Tab path="/security/verify" component={VerifyMessageTab} header={TabHeader} link={<T id="security.tab.verify" m="Verify Message"/>}/>
<Tab path="/security/validate" component={ValidateAddressTab} header={TabHeader} link={<T id="security.tab.validate" m="Validate Address"/>}/>
</TabbedPage>
);
|
const Player = require('../models/player');
module.exports = {
createNewPlayer: (req, res) => {
const params = req.body.player;
const newPlayer = Player({...params});
newPlayer.save((err) => {
if (err) return console.error(`Error saving: ${err}`);
console.log('Successfully created');
res.send({successfully: true});
});
},
getPlayers: async (req, res) => {
const filter = {};
const players = await Player.find(filter);
res.send({players});
},
}
|
const express = require('express');
//import functions from db.js to utilize
const db = require('../data/db.js');
const router = express.Router();
router.get('/', (req, res) => {
db.find()
.then(posts => res.status(200).json(posts))
.catch(error => {
console.log(error);
res.status(500).json({ error: "The posts information could not be retrieved." })
});
})
//get specific post utilize findById
router.get('/:id', (req, res) => {
//destructure id out of req.params
const { id } = req.params;
db.findById(id)
.then(posts => {
//console log for error checking
//1st element of empty array is undefined for 404
const post = posts[0];
console.log(post);
if (post) {
res.status(200).json(post);
}
else {
res.status(404).json({ error: "The post with the specified id does not exist." })
}
});
});
//
router.post('/', (req, res) => {
//destructure title and contents from the body
const { title, contents } = req.body
//If there is not title or contents we'll throw a 400 error
if (!title || !contents) {
//Return causes this to end and escape function
return res.status(400).json({ error: "Please provide title and contents for the post." });
}
//utilize db.insert to posts contents and title
db.insert({ title, contents })
//destructure id so we can return post to user using this id
.then(({ id }) => {
db.findById(id)
//return the array of that post
.then(([post]) => {
//Return status of 201 created and the created post
res.status(201).json(post);
})
})
.catch(error => {
console.log(error)
res.status(500).json({ error: "There was an error while saving the post to the database." })
})
})
//Build delete endpoint utilizing db.remove
router.delete('/:id', (req, res) => {
const { id } = req.params;
db.findById(id)
.then(post => {
if (post[0]) {
res.status(200).json({ post })
db.remove(id)
.catch(error => res.status(500).json({ error: "The post could not be removed." }))
}
else {
res.status(404).json({ message: "the post with the specified ID does not exist." })
}
})
});
router.put('/:id', (req, res) => {
const { id } = req.params;
//destructure title and contents from the body
const { title, contents } = req.body
//If there is not title or contents we'll throw a 400 error
if (!title && !contents) {
//Return causes this to end and escape function
return res.status(400).json({ error: "Please provide title and contents for the post." });
}
//utilize db.update to update contents and title, we need the object to pass in for the update of title, contents and the id to update the contents of "function update(id, post)"
db.update(id, { title, contents })
//destructure id so we can return post to user using this id
.then(updates => {
if (updates) {
db.findById(id)
//return the array of that post
.then(([post]) => {
//Return status of 201 created and the created post
res.status(200).json(post);
})
} else {
res.status(404).json({ error: "The post with the specified ID does not exist." })
}
})
.catch(error => {
console.log(error)
res.status(500).json({ error: "The post information could not be modified." })
})
})
router.post("/:id/comments", (req, res) => {
const { post_id } = req.params;
// Check if the value for text is a truthy value
if (!req.body.text) {
res.status(400).json({ error: "Please provide text for the comment." })
}
// Locate the post by the id value
db.findById(post_id)
.then(post => {
console.log(post)
// If post.id is a truthy value
if (post) {
db.insertComment(req.body)
.then(commentsId => {
db.findCommentById(commentsId.id)
.then(addedComment => {
res.status(201).json({ data: addedComment });
})
})//throw an error 500 if there is an error
.catch(error => {
res.status(500).json({ error: "There was an error while saving the comment to the database." })
})
//if unable to locate that post id
} else {
res.status(404).json({ error: "The post for the specified ID does not exist." })
}
})
})
// .then(([post]) => {
// console.log(post);
// if (post.length > 0) {
// db.insertComment(post_id)
// .then(commentsId => {
// db.findCommentById(post_id)
// .then(addedComment => {
// res.status(201).json({ data: addedComment });
// })
// })
// .catch(error => {
// console.log(error);
// res.status(500).json({ error: "There was an error while saving the comment to the database." })
// })
// } else {
// res.status(404).json({ error: "The post for the specified ID does not exist." })
// }
// })
router.get('/:post_id/comments', (req, res) => {
const { post_id } = req.params;
db.findById(post_id)
.then(([post]) => {
if (post) {
db.findPostComments(post_id).then(comments => {
if (!comments.length) {
return res.status(404).json({ message: "There are no comments!" })
}
return res.status(200).json(comments);
}
)
} else {
res.status(404).json({ error: "The post with the specified ID does not exist." });
}
})
.catch(error => {
console.log(error);
res.status(500).json({ error: "The comments information could not be retrieved." });
});
});
module.exports = router;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.