text
stringlengths 7
3.69M
|
|---|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import DefaultButton from '../../../ui/buttons/DefaultButton'
export default class CardActions extends Component {
render() {
let {handleSave, handleDelete, handlePDF} = this.props
return (
<div className="CardActions row">
<center>
<DefaultButton
label="Guardar"
floatStyle="center"
onTouchTap={event => handleSave(event)}
/>
<DefaultButton
label="Eliminar"
floatStyle="center"
onTouchTap={event => handleDelete(event)}
/>
<DefaultButton
label="PDF"
floatStyle="center"
onTouchTap={event => handlePDF(event)}
/>
</center>
</div>
);
}
}
CardActions.displayName = 'CardActions'
CardActions.propTypes = {
handleSave: PropTypes.func,
handleDelete: PropTypes.func,
handlePDF: PropTypes.func
};
|
import './borderRadius'
import './borderWidth'
import './colors'
import './fontFamily'
import './fontSize'
import './fontWeight'
import './lineHeight'
import './opacity'
import './shadow'
import './spacing'
|
import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import { remove } from '../../../actions/post'
import Like from './Like'
import ProfileImage from '../ProfileImage'
class Post extends React.Component {
componentDidMount() {
this.refs.body.innerHTML = this.props.post.body
}
onDelete = () => this.props.remove(this.props.post._id)
render() {
const { post, auth, TYPE } = this.props
return (
<div className="card mb-4">
<div className="card-header">
<div className="d-flex justify-content-between align-items-center">
<div className="d-flex justify-content-between align-items-center">
<div className="mr-2">
<Link to={'/user/' + post.user._id}>
<ProfileImage user={post.user} width="50" />
</Link>
</div>
<div className="ml-2">
<div className="h5 m-0">{post.user.name}</div>
<div className="h7 text-muted">
<i className="fa fa-clock-o"></i> {new Date(post.createdDate).toDateString()}
</div>
</div>
</div>
{auth.isAuthenticated && auth.user.name === post.user.name && (
<div className="dropdown">
<button className="btn btn-link dropdown-toggle" type="button" id="drop" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
<div className="dropdown-menu dropdown-menu-right" aria-labelledby="drop">
<a className="dropdown-item" role="button" onClick={this.onDelete}>Remove</a>
</div>
</div>
)}
</div>
</div>
<div className="card-body" ref="body"></div>
<div className="card-footer">
<Like postId={post._id} likes={post.likes} TYPE={TYPE} />
<Link to={'/post/' + post._id} className="card-link">
<i className="fa fa-arrow-right"></i>
</Link>
</div>
</div>
)
}
}
Post.propTypes = {
remove: PropTypes.func.isRequired,
post: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
TYPE: PropTypes.string.isRequired
}
const mapStateToProps = (state) => ({ auth: state.auth })
export default connect(mapStateToProps, { remove })(Post)
|
import React from "react";
import { render, screen } from "@testing-library/react";
import { Feature } from "../../components";
describe("<Feature />", () => {
it("renders the <Feature /> with populated data", () => {
const { container } = render(
<Feature>
<Feature.Title>Unlimited movies, TV shows, and more.</Feature.Title>
<Feature.SubTitle>Watch anywhere. Cancel anytime.</Feature.SubTitle>
</Feature>
);
expect(
screen.getByText("Unlimited movies, TV shows, and more.")
).toBeTruthy();
expect(screen.getByText("Watch anywhere. Cancel anytime.")).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
it("renders the <Feature /> with title", () => {
const { container } = render(
<Feature>
<Feature.Title>Unlimited movies, TV shows, and more.</Feature.Title>
</Feature>
);
expect(
screen.getByText("Unlimited movies, TV shows, and more.")
).toBeTruthy();
expect(screen.queryByText("Watch anywhere. Cancel anytime.")).toBeFalsy();
expect(container.firstChild).toMatchSnapshot();
});
it("renders the <Feature /> with subtitle", () => {
const { container } = render(
<Feature>
<Feature.SubTitle>Watch anywhere. Cancel anytime.</Feature.SubTitle>
</Feature>
);
expect(
screen.queryByText("Unlimited movies, TV shows, and more.")
).toBeFalsy();
expect(screen.getByText("Watch anywhere. Cancel anytime.")).toBeTruthy();
expect(container.firstChild).toMatchSnapshot();
});
});
|
var midas = midas || {};
midas.sizequota = midas.sizequota || {};
midas.sizequota.folder = midas.sizequota.folder || {};
midas.sizequota.constant = { MIDAS_USE_DEFAULT_QUOTA : "0", MIDAS_USE_SPECIFIC_QUOTA : "1" };
midas.sizequota.folder.validateConfig = function(formData, jqForm, options)
{
}
midas.sizequota.folder.successConfig = function(responseText, statusText, xhr, form)
{
try
{
jsonResponse = jQuery.parseJSON(responseText);
}
catch(e)
{
alert("An error occured. Please check the logs.");
return false;
}
if(jsonResponse==null)
{
createNotice('Error',4000);
return;
}
if(jsonResponse[0])
{
location.reload();
}
else
{
createNotice(jsonResponse[1],4000);
}
}
midas.sizequota.folder.radioButtonChanged = function()
{
var selected = $('input[name="usedefault"]:checked');
if(selected.val() == midas.sizequota.constant.MIDAS_USE_DEFAULT_QUOTA)
{
$('input#quota').attr('disabled', 'disabled');
}
else
{
$('input#quota').removeAttr('disabled');
}
}
$(document).ready(function() {
$('#configForm').ajaxForm({
beforeSubmit: midas.sizequota.folder.validateConfig,
success: midas.sizequota.folder.successConfig
});
$('input[name="usedefault"]').change(midas.sizequota.folder.radioButtonChanged);
midas.sizequota.folder.radioButtonChanged();
var content = $('#quotaValue').html();
if(content != '' && content != 0)
{
var quota = parseInt($('#quotaValue').html());
var used = parseInt($('#usedSpaceValue').html());
if(used <= quota)
{
var free = quota - used;
var hUsed = $('#hUsedSpaceValue').html();
var hFree = $('#hFreeSpaceValue').html();
var data = [['Used space (' + hUsed + ')' , used], ['Free space (' + hFree + ')', free]];
$('#quotaChart').show();
$.jqplot('quotaChart', [data], {
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
}
},
legend: {
show: true,
location: 'e'
}
});
}
}
});
|
import axios from './axios.js'
import qs from 'qs'
const API_ROOT = process.env.VUE_APP_API_ROOT
const API_PREFIX = '/api'
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded'
// get 请求
export const get = (url, params) => {
console.log(qs.stringify(params))
return axios({
method: 'get',
url: `${API_ROOT}${API_PREFIX}${url}`,
params,
headers: {}
})
}
// post请求
export const post = (url, params) => {
return axios({
method: 'post',
url: `${API_ROOT}${API_PREFIX}${url}`,
data: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: [
data => {
return qs.stringify(data)
}
]
})
}
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Box from '@material-ui/core/Box';
const useStyles = makeStyles((theme) => ({
root: {
minWidth: 275,
marginTop: theme.spacing(2),
marginBottom: theme.spacing(3),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
}));
//export default function SimpleCard(props) {
const CardContext = (props) => {
const classes = useStyles();
const { mediaLogo, headerContext, footerContext, FormContext } = props;
let { source } = props;
if (source === undefined) {
source = 'default';
}
//////// dynamic component ///////
const media = {
signin: mediaLogo,
default: '',
};
const MediaComp = media[source || false];
const header = {
signin: headerContext,
default: '',
};
const HeaderComp = header[source || false];
const footer = {
signin: footerContext,
default: '',
};
const FooterComp = footer[source || false];
//////// end of dynamic component ///////
return (
<Card className={classes.root}>
<CardContent>
{console.log('cardcontext', props)}
{mediaLogo && <MediaComp />}
{headerContext && <HeaderComp />}
<form noValidate>
<FormContext />
</form>
{footerContext && (
<Box mt={8}>
<FooterComp />
</Box>
)}
</CardContent>
</Card>
);
};
export default CardContext;
CardContext.defaultProps = {
MediaComp: '',
HeaderComp: '',
FooterComp: '',
FormContext: 'CardContext Custom error: FORM CONTEXT props in every page',
};
CardContext.propTypes = {
source: PropTypes.string,
footerContext: PropTypes.func,
mediaLogo: PropTypes.func,
headerContext: PropTypes.func,
formContext: PropTypes.func.isRequired,
};
|
import React from 'react';
import Common from './Common';
import studying from '../images/studying.jpeg';
const Integration = () => {
return (
<div>
<Common name='Very good friends with' imgsrc={studying} visit='/contact' btname="Our friends"/>
</div>
)
}
export default Integration
|
_.zip = function(){
var arg = Base.makeArray(arguments);
var re = [];
var baseLen = arg[0].length;
var loopLen = arg.length;
for(var i= 0;i<baseLen;i++){
re[i] = [];
for(var j=0;j<loopLen;j++){
re[i].push(arg[j][i]);
}
}
return re;
}
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify';
import ApiService from './services/api.service'
import {TokenService} from './services/storage.service'
import JsonExcel from 'vue-json-excel'
import VueGoogleCharts from 'vue-google-charts'
import vueHeadful from 'vue-headful'
import Carousel3d from 'vue-carousel-3d'
Vue.config.productionTip = false
Vue.config.silent = true
Vue.use(VueGoogleCharts)
// Set the base URL of the API
ApiService.init(process.env.VUE_APP_ROOT_API)
// If token exists set header
if (TokenService.getToken()) {
ApiService.setHeader()
}
Vue.component('downloadExcel', JsonExcel)
Vue.component('vue-headful', vueHeadful)
Vue.use(Carousel3d);
Vue.use(require('vue-moment'))
new Vue({
router,
store,
vuetify,
render: function (h) { return h(App) }
}).$mount('#app')
|
let Livro, script, txt, listaGarimpada, versiculosTexto, textoFinal
if (localStorage.getItem("listaVersiculos") == null || !localStorage.listaVersiculos) {
localStorage.setItem("listaVersiculos", "[]")
}
let listaVersiculos = JSON.parse(localStorage.getItem("listaVersiculos"))
function mudaNomes() {
txt = document.getElementById("areaTexto").value
// https://medium.com/better-programming/working-with-regular-expressions-regex-in-javascript-6c7dd951574a
// https://stackoverflow.com/questions/34510746/difference-between-1-and-in-regular-expressions
// let listaNomesLivros = ["Gênesis", "Êxodo", "Levítico", "Números", "Deuteronômio", "Josué", "Juízes", "Rute", "Samuel", "Reis", "Crônicas", "Esdras", "Neemias", "Ester", "Jó", "Salmos", "Provérbios", "Eclesiastes", "Cantares", "Isaías", "Jeremias", "Lamentações", "Ezequiel", "Daniel", "Oséias", "Joel", "Amós", "Obadias", "Jonas", "Miquéias", "Naum", "Habacuque", "Sofonias", "Ageu", "Zacarias", "Malaquias", "Mateus", "Marcos", "Lucas", "João", "Atos", "Romanos", "Coríntios", "Gálatas", "Efésios", "Filipenses", "Colossenses", "Tessalonicenses", "Timóteo", "Tito", "Filemon" "Hebreus", "Tiago", "Pedro", "João", "Judas", "Apocalipse"]
// let listaAbreviacoes = ["Gn", "Ex", "Lv", "Nm", "Dt", "Js", "Jz", "Rt", "Sm", "Rs", "Cr", "Ed", "Ne", "Et", "Jó", "Sl", "Pv", "Ec", "Ct", "Is", "Jr", "Lm", "Ez", "Dn", "Os", "Jl", "Am", "Ob", "Jn", "Mq", "Na", "Hc", "Sf", "Ag", "Zc", "Ml", "Mt", "Mc", "Lc", "Jo", "At", "Rm", "Co", "Gl", "Ef", "Fp", "Cl", "Ts", "Tm", "Tt", "Fm", "Hb", "Tg", "Pe", "Jo", "Jd", "Ap"]
// Se não escapa com \b o JS vai substituir toda palavra tb que tenha as tais letras dentro.
// p.ex: "leva" por Lva - se não colocar \blev\b ...
// n? - onde n é opcional. Seria o mesmo que [n], porém salmo[s] não funciona. ??
// [óo] - ou o ou ó.
// Texto antes de ser manipulado:
console.log("Garimpando texto: ", txt)
// teste - iico2:1 ico 1:10 1 ts 2:1 1 cor3:2 > erro: 1o. Sm 4:4 1°. Sm 2:2
txt = txt.replace(/\b(1|2|3)[o°aª]\.?/gi, "$1")
.replace(/(\d)([a-z])/gi, "$1 $2")
.replace(/([a-z])(\d)/gi, "$1 $2")
.replace(/\bii\ ?/gi, "2\ ")
.replace(/\bi\ /gi, "1\ ")
.replace(/ */g, "\ ")
.replace(/\ ?:\ ?/gi, ":")
.replace(/g[eê]nesis|\bg[eê]n\b|\bgn\b/gi, "Gn")
.replace(/[eê]xodo|[eê]xo\b|[eê]x\b/gi, "Ex")
.replace(/levítico|levitico|\bLev\b|\blv\b/gi, "Lv")
.replace(/n[úu]meros|\bn[úu]m\b|\bnm\b/gi, "Nm")
.replace(/deuteron[ôo]nomio|\bdeut\b|\bdt\b/gi, "Dt")
.replace(/josu[ée]|\bJos\b|\bjs\b/gi, "Js")
.replace(/ju[íi]zes|\bjz\b/gi, "Jz")
.replace(/rute|\brut\b|\brt\b/gi, "Rt")
.replace(/samuel|\bsam\b|\bsm\b/gi, "Sm")
.replace(/\breis|\brs\b/gi, "Rs")
.replace(/cr[ôo]nicas|cr[ôo]n\b|\bcr\b/gi, "Cr")
.replace(/esdras|esd\b|\bed\b/gi, "Ed")
.replace(/neemias|neem\b|\bne\b/gi, "Ne")
.replace(/ester|est\b|\bet\b/gi, "Et")
.replace(/\bjó\b/gi, "Jó")
.replace(/salmos?|\bsl\b/gi, "Sl")
.replace(/prov[ée]rbio[s]|prov\b|\bpv\b/gi, "Pv")
.replace(/ecl[ei]siastes|ecl\b|\bec\b/gi, "Ec")
.replace(/cantares|cant\b|c[âa]ntico[s]|\bct\b/gi, "Ct")
.replace(/isa[íi]as|isa|\bis\b/gi, "Is")
.replace(/jerem[íi]as|jer|\bjr\b/gi, "Jr")
.replace(/lamenta[cç][õo]es|lamen\b|lam\b|\blm\b/gi, "Lm")
.replace(/ezequiel|ezeq\b|eze\b|\bez\b/gi, "Ez")
.replace(/daniel|dan\b|\bdn\b/gi, "Dn")
.replace(/os[ée]ias|ose\b|\bos\b/gi, "Os")
.replace(/joel|\bjl\b/gi, "Jl")
.replace(/am[óo]s|\bam\b/gi, "Am")
.replace(/obad[ií]as|obd[ií]as|obad?\b|\bob\b/gi, "Ob")
.replace(/jonas|jon\b|\bjn\b/gi, "Jn")
.replace(/miqu[ée]ias|miq\b|\bmq\b/gi, "Mq")
.replace(/naum|\bna\b/gi, "Na")
.replace(/habacuque|habacuc|hab\b|\bhc\b/gi, "Hc")
.replace(/sofon[íi]as|sof\b|\bsf\b/gi, "Sf")
.replace(/ageo|\bag\b/gi, "Ag")
.replace(/zacar[ií]as|zaca?\b|\bzc\b/gi, "Zc")
.replace(/malaqu[íi]as|mal\b|malaq\b|\bml\b/gi, "Ml")
.replace(/mateus|mat\b|\bmt\b/gi, "Mt")
.replace(/marcos|\bmc\b/gi, "Mc")
.replace(/lucas|\blc\b/gi, "Lc")
.replace(/jo[aã]o|\bjo\b/gi, "Jo")
.replace(/atos|\bat\b/gi, "At")
.replace(/romanos|rom\b|\brm\b/gi, "Rm")
.replace(/cor[ií]ntios|cor\b|\bco\b/gi, "Co")
.replace(/g[áa]latas|g[áa]l\b|\bgl\b/gi, "Gl")
.replace(/ef[ée]sios|efe\b|\bef\b/gi, "Ef")
.replace(/filipen[sc]es|fil\b|filip\b|\bfl\b|\bfp\b/gi, "Fp")
.replace(/colossenses|colo[cs]en[cs]es|col\b|colos\b|col\b|\bcl\b/gi, "Cl")
.replace(/tessalonicenses|tes?saloni[cs]s?en[cs]s?es|tess?a?\b|\bts\b/gi, "Ts")
.replace(/tim[óo]t[ei]o|tim\b|tim[óo]t\b\btm\b/gi, "Tm")
.replace(/tito|tit\b|\btt\b/gi, "Tt")
.replace(/filemon|\bfm\b|\bflm\b/gi, "Fm")
.replace(/[h]ebre[uo]s|\bheb[r]\b|\bhb\b/gi, "Hb")
.replace(/tiago|\btg\b/gi, "Tg")
.replace(/pedro|ped?r?\b|\bpe\b/gi, "Pe")
.replace(/judas|jud\b|\bjd\b/gi, "Jd")
.replace(/apocalipse|apo[c]\b|apocali?p?\b|\bap\b/gi, "Ap")
.replace(/(1|2|3) (sm|rs|cr|co|ts|tm|pe|jo)/gi, "$1$2")
.replace(/([\d]Gn|Ex|Lv|Nm|Dt|Js|Jz|Rt|Sm|Rs|Cr|Ed|Ne|Et|Jó|Sl|Pv|Ec|Ct|Is|Jr|Lm|Ez|Dn|Os|Jl|Am|Ob|Jn|Mq|Na|Hc|Sf|Ag|Zc|Ml|Mt|Mc|Lc|Jo|At|Rm|Co|Gl|Ef|Fp|Cl|Ts|Tm|Tt|Fm|Hb|Tg|Pe|Jd|Ap)\./gi, "$1\ ")
.replace(/(\d)\.(\d)/gi, "$1:$2")
.replace(/\ ?-\ ?|\ ?_\ ?/g, "-")
// .replace(/ */g, "\ ")
garimpa()
// teste - iico2:1 i co1:10 1 ts 2:1 1 cor3:2 > erro: 1o. Sm 4:4 1°. Sm 2:2
//.replace(/(\bii ?|\b2[o°0a]\.? ?)(sm|rs|cr|co|ts|tm|pe|jo)/gi, "2$2")
//.replace(/(\bi ?|\b1[o°0a]\.? ?)(sm|rs|cr|co|ts|tm|pe|jo)/gi, "1$2")
//.replace(/(\bi ?|\b1o\.? ?|\b1°\.? ?\b1a\.? ?|\b1æ\.? ?)(sm|rs|cr|co|ts|tm|pe|jo)/gi, "1$2")
}
function garimpa() {
let padrao = new RegExp("[1-3]?(Gn|Ex|Lv|Nm|Dt|Js|Jz|Rt|Sm|Rs|Cr|Ed|Ne|Et|Jó|Sl|Pv|Ec|Ct|Is|Jr|Lm|Ez|Dn|Os|Jl|Am|Ob|Jn|Mq|Na|Hc|Sf|Ag|Zc|Ml|Mt|Mc|Lc|Jo|At|Rm|Co|Gl|Ef|Fp|Cl|Ts|Tm|Tt|Fm|Hb|Tg|Pe|Jd|Ap) [0-9]+:?[0-9]*-?[0-9]*", "gi")
//let padrao = new RegExp("[1-3]?(Gn|Ex|Lv|Nm|Dt|Js|Jz|Rt|Sm|Rs|Cr|Ed|Ne|Et|Jó|Sl|Pv|Ec|Ct|Is|Jr|Lm|Ez|Dn|Os|Jl|Am|Ob|Jn|Mq|Na|Hc|Sf|Ag|Zc|Ml|Mt|Mc|Lc|Jo|At|Rm|Co|Gl|Ef|Fp|Cl|Ts|Tm|Tt|Fm|Hb|Tg|Pe|Jd|Ap) [0-9]+:?[0-9]*", "gi")
listaGarimpada = txt.match(padrao)
versiculosTexto = listaGarimpada.toString().replace(/,/g, "\n")
document.getElementById("areaTexto").value = versiculosTexto
// para salvar em localStorage:
versiculosTexto = versiculosTexto.split("\n")
// listaGarimpadaUniq = new Set(listaGarimpada) // erro pq não retorna em array.
// para tirar os repetidos (uniq):
listaGarimpada = Array.from(new Set(listaGarimpada))
console.log(listaGarimpada)
mostraVs()
}
function mostraVs() {
textoFinal = "" // sem esta linha sairia 1a/e. "undefined" no resultado final.
// a variável abaixo servirá quando se faça map na listaGarimpada.
let nroVersiculosExtras
// se no item há um hífen cap:vers a-b (devem ser mostrados os (b-a) versiculos seguintes de b)
// a array: "versiculos" pertence a acf.js!:
listaGarimpada.map(cadaVs => {
// A cada passagem da lista, verifica se a passagem tenha um intervalo de versículos, i.é: Sl 23:1-4 ...
if (cadaVs.match("-")) {
// se sim:
// pega a parte Sl 23: <1-4>
let parteVersiculos = cadaVs.split(":")[1]
// o versiculo final seria no exemplo = 4.
let versFinal = parteVersiculos.split("-")[1]
// o vers. inicial seria no exemplo = 1.
let versInicial = parteVersiculos.split("-")[0]
// abaixo seria o resultado de 3 (3 a mais).
nroVersiculosExtras = Number(versFinal) - Number(versInicial)
// acima: ALÉM do versInicial tem mais nroVersiculosExtras. (Ex.: 15-17 = 15, 16, 17)
}else{
// Caso não haja tracinho na passagem de listaGarimpada (indicando que é só 1 versículo):
nroVersiculosExtras = 0
}
// retira tudo o que pode existir depois de hífem (incluindo o hífem). Caso contr. não acharia em acf.js a passagem.
cadaVs = cadaVs.replace(/-.*/, "")
// percorre "versiculos" (variável do arq acf.js que contém toda a Bíblia em array)
bibliaACF.map((a, b) => {
// encontrando o versículo pedido pelo usuário dentro de acf.js...
if (a[0] === cadaVs) {
// executará a repetição (se houver) de nro de Vers. Extras:
// caso não o nroVersiculosExtras for 0, somente imprimirá o único vers. pedido pelo usuário:
for(rep=0; rep <= nroVersiculosExtras; rep++){
// b+rep = representa o index (b de map) do vs encontrado em acf.js + nro de iterações (rep) dos próx. versículos solicitados (ex: 15-17):
textoFinal += `<br><strong>${bibliaACF[b+rep][0]}:</strong> "${bibliaACF[b+rep][1]}"<br>`
}
}
})
})
document.getElementById("resultado").innerHTML = textoFinal
document.querySelectorAll(".oculta").forEach(a => a.style.display = "block")
}
function salvaLista() {
let data = new Date()
let dia = data.toDateString().split(" ")[2]
let mes = data.getMonth() + 1
if (mes < 10) {
mes = "0" + mes.toString()
}
let ano = data.toDateString().split(" ")[3]
let hoje = `${ano}${mes}${dia}`
let hora = data.toTimeString().split(" ")[0]
let nomeLista = document.querySelector("#nomeLista").value
let listaObj = {}
listaObj.data = hoje
listaObj.hora = hora
listaObj.nomeLista = nomeLista
listaObj.versiculos = versiculosTexto
listaVersiculos.push(listaObj)
localStorage.listaVersiculos = JSON.stringify(listaVersiculos)
}
function limpaInput() {
this.placeholder = ""
}
document.getElementById("bt").addEventListener("click", mudaNomes)
document.getElementById("btSalva").addEventListener("click", salvaLista)
document.getElementById("nomeLista").addEventListener("focus", limpaInput)
// let listaLivros = ["Gn", "Ex", "Lv", "Nm", "Dt", "Js", "Jz", "Rt", "1Sm", "2Sm", "1Rs", "2Rs", "1Cr", "2Cr", "Ed", "Ne", "Et", "Jó", "Sl", "Pv", "Ec", "Ct", "Is", "Jr", "Lm", "Ez", "Dn", "Os", "Jl", "Am", "Ob", "Jn", "Mq", "Na", "Hc", "Sf", "Ag", "Zc", "Ml", "Mt", "Mc", "Lc", "Jo", "At", "Rm", "1Co", "2Co", "Gl", "Ef", "Fp", "Cl", "1Ts", "2Ts", "1Tm", "2Tm", "Tt", "Fm", "Hb", "Tg", "1Pe", "2Pe", "1Jo", "2Jo", "3Jo", "Jd", "Ap"]
// =========================================================
|
import request from 'axios'
import Vue from 'vue'
import elementUI from 'element-ui'
Vue.use(elementUI)
request.defaults.baseURL = 'http://nework-web.rdc.waibaodashi.com'
request.interceptors.request.use((req)=> {
return req
},(error)=>{
})
request.interceptors.response.use((res)=> {
return res
},(error)=>{
console.log(error,'dsdsds')
})
export default request
|
var fs = require("fs");
fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) {
if (line !== "") {
simpleSorting(line);
}
});
function simpleSorting(line) {
console.log(line.trim().split(" ").sort(function(a, b) { return parseFloat(a) - parseFloat(b) }).join(" "));
}
|
import {
BufferGeometry,
BufferAttribute,
Uint16BufferAttribute,
MeshBasicMaterial,
TextureLoader,
Mesh,
DoubleSide,
} from 'three'
import { get } from 'lodash'
import memoize from 'utils/memoize'
import { createSelector } from 'reselect'
import { getAssetUrl } from 'service/gamedb'
import { selectors as gamestateSelectors } from 'morpheus/gamestate'
import { selectors as castSelectors } from 'morpheus/casts'
import { disposeObject, disposeScene } from 'utils/three'
import { isPano, forMorpheusType, and, or, not } from '../matchers'
const SCALE_FACTOR = 1.0
const HOTSPOT_X_OFFSET = Math.PI / 3
const HOTSPOT_X_COORD_FACTOR = Math.PI / -1800
const SIZE = 0.99 * SCALE_FACTOR
const HOTSPOT_Y_COORD_FACTOR = 0.0022 * SCALE_FACTOR
const SCALE_WIDTH_FACTOR = 1.2
const SCALE_HEIGHT_FACTOR = 0.95
function cylinderMap(y, x) {
return {
x: SIZE * Math.sin(x - Math.PI / 2),
y: -y,
z: SIZE * Math.cos(x - Math.PI / 2),
}
}
function createControlledPositions(controlledCastsData) {
const {
controlledLocation: { x, y },
width,
height,
} = controlledCastsData
let top = y - 250
let bottom = y + (height * SCALE_HEIGHT_FACTOR - 250)
let left = x
let right = x + width * SCALE_WIDTH_FACTOR
top *= HOTSPOT_Y_COORD_FACTOR
bottom *= HOTSPOT_Y_COORD_FACTOR
right = HOTSPOT_X_COORD_FACTOR * right + HOTSPOT_X_OFFSET
left = HOTSPOT_X_COORD_FACTOR * left + HOTSPOT_X_OFFSET
const bottomLeft = cylinderMap(bottom, left)
const bottomRight = cylinderMap(bottom, right)
const topRight = cylinderMap(top, right)
const topLeft = cylinderMap(top, left)
const positions = new BufferAttribute(new Float32Array(12), 3)
positions.setXYZ(0, bottomLeft.x, bottomLeft.y, bottomLeft.z)
positions.setXYZ(1, bottomRight.x, bottomRight.y, bottomRight.z)
positions.setXYZ(2, topRight.x, topRight.y, topRight.z)
positions.setXYZ(3, topLeft.x, topLeft.y, topLeft.z)
return positions
}
function createUvs({ cast, gamestates }) {
const { controlledMovieCallbacks } = cast
const gameStateId = get(controlledMovieCallbacks, '[0].gameState', null)
const gs = gamestates.byId(gameStateId)
const { maxValue } = gs
const value = Math.round(gs.value, 0)
const minX = value / (maxValue + 1)
const maxX = (value + 1) / (maxValue + 1)
const uvs = new BufferAttribute(new Float32Array(8), 2)
uvs.setXY(0, minX, 0.0)
uvs.setXY(1, maxX, 0.0)
uvs.setXY(2, maxX, 1.0)
uvs.setXY(3, minX, 1.0)
return uvs
}
function createIndex() {
return new Uint16BufferAttribute([0, 1, 2, 0, 2, 3], 1)
}
function createGeometry(positions, uvs, index) {
const geometry = new BufferGeometry()
geometry.setIndex(index)
geometry.addAttribute('position', positions)
geometry.addAttribute('uv', uvs)
return geometry
}
function createMaterial(asset) {
const loader = new TextureLoader()
loader.crossOrigin = 'anonymous'
let material
return new Promise((resolve, reject) => {
material = new MeshBasicMaterial({
side: DoubleSide,
map: loader.load(asset, resolve, undefined, reject),
})
}).then(() => material)
}
function createObject3D({ geometry, material }) {
const mesh = new Mesh(geometry, material)
return mesh
}
const selectors = memoize(scene => {
const selectSceneCache = castSelectors.forScene(scene).cache
const allCasts = () => get(scene, 'casts', [])
const selectSelfInStore = createSelector(
selectSceneCache,
cache => get(cache, 'controlledMovie'),
)
const selectControlledCasts = createSelector(
selectSelfInStore,
controlledMovie => get(controlledMovie, 'controlledCasts', []),
)
const selectControlledCastsData = createSelector(
allCasts,
forMorpheusType('ControlledMovieCast'),
)
const selectIsPano = createSelector(
() => scene,
isPano,
)
const selectIsLoaded = createSelector(
selectSelfInStore,
controlledMovie => get(controlledMovie, 'isLoaded'),
)
const selectIsLoading = createSelector(
selectSelfInStore,
controlledMovie => get(controlledMovie, 'isLoading'),
)
return {
self: selectSelfInStore,
isLoaded: selectIsLoaded,
isLoading: selectIsLoading,
isPano: selectIsPano,
controlledCasts: selectControlledCasts,
controlledCastsData: selectControlledCastsData,
}
})
export const delegate = memoize(scene => {
function applies() {
return (
isPano(scene) && scene.casts.find(forMorpheusType('ControlledMovieCast'))
)
}
function doLoad({ setState, isLoaded, isLoading }) {
return () => {
const controlledCastsData = scene.casts.filter(
forMorpheusType('ControlledMovieCast'),
)
if (isLoaded) {
return Promise.resolve({})
}
if (isLoading) {
return isLoading
}
const promise = Promise.all(
controlledCastsData.map(curr =>
createMaterial(getAssetUrl(curr.fileName, 'png')).then(material => ({
material,
positions: createControlledPositions(curr),
data: curr,
})),
),
).then(controlledCasts => ({
controlledCasts,
isLoaded: true,
isLoading: false,
}))
setState({
isLoading: promise,
})
return promise
}
}
function doEnter({
controlledCasts,
modules: {
pano: { object3D: panoObject3D },
},
}) {
return (dispatch, getState) =>
Promise.all(
controlledCasts.map(({ data, material, positions }) => {
const uvs = createUvs({
cast: data,
gamestates: gamestateSelectors.forState(getState()),
})
const geometry = createGeometry(positions, uvs, createIndex())
const object3D = createObject3D({ geometry, material })
panoObject3D.add(object3D)
return { data, material, positions, object3D }
}),
).then(c => ({
controlledCasts: c,
}))
}
function doUnload({ controlledCasts }) {
return () => {
return Promise.resolve({
isLoaded: false,
isLoading: null,
controlledCasts: [],
})
}
}
function update({ controlledCasts }) {
return (dispatch, getState) => {
const gamestates = gamestateSelectors.forState(getState())
controlledCasts.forEach(({ object3D, data: cast }) => {
const uv = createUvs({ cast, gamestates })
object3D.geometry.attributes.uv = uv
})
return Promise.resolve()
}
}
return {
applies,
doLoad,
doPreload: doLoad,
doPreunload: doUnload,
doEnter,
doUnload,
update,
}
})
|
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
const Router = EmberRouter.extend({
location: config.locationType
});
Router.map(function() {
this.route('add-airplane');
this.route('airplanes');
this.route('airport');
this.route('airport-info');
this.route('ann-arbor');
this.route('brighton');
this.route('canton');
this.route('dropdown');
this.route('edit-airplane',{path: 'edit-airplane/:id'});
this.route('edit-player',{path: 'edit-player/:id'});
this.route('export-airplanes');
this.route('import');
this.route('import-airplanes');
this.route('import-all');
this.route('index',{'path': '/'});
this.route('jackson');
this.route('login');
this.route('michairplanes');
this.route('navaids');
this.route('new');
this.route('oaklandsw');
this.route('oakland');
this.route('players');
this.route('troy');
this.route('willow');
});
export default Router;
|
//表单错误提示信息
function alertMsg(val){
var html = '<div id="msg" class=" tc mt_10 pt_10" style="center;color:red"></div>';
$("body").append(html);
$("#msg").empty().html(val);
setTimeout(function(){
$("#msg").remove();
},2000)
}
function AlertInfo(mesg){
alert(mesg)
}
|
// Error names
module.exports = {
PARAMS_REQUIRED: 'PARAMS_REQUIRED',
USER_DOES_NOT_EXISTS: 'USER_DOES_NOT_EXISTS',
KIND_NOT_ALLOWED: 'KIND_NOT_ALLOWED',
DATABASE_ERROR: 'DATABASE_ERROR',
};
|
(function() {
// The width and height of the captured photo. We will set the
// width to the value defined here, but the height will be
// calculated based on the aspect ratio of the input stream.
var width = 320; // We will scale the photo width to this
var height = 0; // This will be computed based on the input stream
// |streaming| indicates whether or not we're currently streaming
// video from the camera. Obviously, we start at false.
var streaming = false;
// The various HTML elements we need to configure or control. These
// will be set by the startup() function.
var video = null;
var canvas = null;
var photo = null;
var startbutton = null;
var stk = 'none';
function startup() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
photo = document.getElementById('photo');
startbutton = document.getElementById('startbutton');
var camera_is_enabled = 0;
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
//Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
//video.src = window.URL.createObjectURL(stream);
if ("srcObject" in video) {
video.srcObject = stream;
}
else {
video.src = window.URL.createObjectURL(stream);
}
video.play();
camera_is_enabled = 1;
})/*
.catch(function () {
camera_is_enabled = 0;
studioMessage.innerHTML = "Camera not detected !";
studioMessageBox.style.display = "block";
}); */
}
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
// Firefox currently has a bug where the height can't be read from
// the video, so we will make assumptions if this happens.
if (isNaN(height)) {
height = width / (4/3);
}
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
startbutton.addEventListener('click', function(ev){
var radios = document.getElementsByName('stickers');
for (var i = 0, length = radios.length; i < length; i++)
{
if (radios[i].checked)
{
stk = radios[i].value;
break;
}
}
if (stk != 'none')
{
document.getElementById('startbutton').disabled = false;
takepicture();
ev.preventDefault();
}else {
alert("Choose a sticker");
document.getElementById('startbutton').disabled = true;
location.reload();
}
}, false);
// clearphoto();
}
// Fill the photo with an indication that none has been
// captured.
// function clearphoto() {
// var context = canvas.getContext('2d');
// context.fillStyle = "#AAA";
// context.fillRect(0, 0, canvas.width, canvas.height);
// var data = canvas.toDataURL('image/png');
// photo.setAttribute('src', data);
// var xhr = new XMLHttpRequest();
// xhr.open('POST', 'http://localhost/camagru/camera/save_pic');
// xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// xhr.onreadystatechange = function() {
// if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// console.log(this.responseText);
// }
// }
// alert(stk);
// xhr.send('img=' + encodeURIComponent(data) + '&stk=' + stk);
// }
// Capture a photo by fetching the current contents of the video
// and drawing it into a canvas, then converting that to a PNG
// format data URL. By drawing it on an offscreen canvas and then
// drawing that to the screen, we can change its size and/or apply
// other changes before drawing it.
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/camagru/camera/take_pic');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log(this.responseText);
}
}
xhr.send('img=' + encodeURIComponent(data) + '&stk=' + stk + '&from=video');
} else {
// clearphoto();
}
}
// Set up our event listener to run the startup process
// once loading is complete.
window.addEventListener('load', startup, false);
})();
var width = 320;
var height = 0;
height = width / (4/3);
function uploadimg(){
if(window.File && window.FileReader && window.FileList && window.Blob)
{
var file = document.querySelector('input[type=file]').files[0];
if(file.size > 0)
{
var reader = new FileReader();
reader.readAsDataURL(file);
var stk = 'none';
reader.onloadend = function (e) {
var img = new Image();
img.src = e.target.result;
img.onload = function(ev){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
}
var radios = document.getElementsByName('stickers');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
stk = radios[i].value;
break;
}
}
var data = this.result;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/camagru/camera/take_pic');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// console.log(this.responseText);
}
}
xhr.send('img=' + encodeURIComponent(data) + '&stk=' + stk + '&from=upload');
}
}
}
};
|
module.exports = {
makeArticleFrom : function (article) {
const {url, board_id, title, thumbnail, author, host} = article
return {
url: url,
thumbnail: thumbnail || null,
title: title || "Generic title",
author: author || "Generic author",
host: title || "Generic host",
board_id: board_id
}
}
}
|
$(document).ready(initializeApp);
function initializeApp(){
createBoard();
applyHandlers();
}
function applyHandlers(){
$('.square').on('click', selectPiece);
//turn off click handler on right pieces
$('.square.light').off();
$('.startGame').on('click', function(){
if(hasClicked === true){
return;
} else{
repopulateChecker();
hasClicked = true;
}
});
$('.resetButton').on('click', function(){
hasClicked = false ;
resetGame();
});
}
var hasClicked = false;
var gameStarted = false;
var selectedChecker = null;
var jumpRight = false;
var jumpLeft = false;
var possibleJumpRow = null;
var possibleJumpLeft = null;
var possibleJumpRight = null;
var player1Score = 0;
var player2Score = 0;
var currentRow = null;
var currentColumn = null;
var possibleRow = null;
var possibleColumn = null;
var currentPlayer = 0;
var gameBoard = [
[0,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[2,0,2,0,2,0,2,0],
[0,2,0,2,0,2,0,2],
[2,0,2,0,2,0,2,0],
];
if (player1Score === 12) {
$('h1').text('Player 1 Wins');
} else if (player2Score === 12) {
$('h1').text('Player 2 Wins');
}
function switchPlayer () {
// if current player is true, make current player a false value, change the text in the header to message
if(currentPlayer) {
currentPlayer = 1 - currentPlayer;
$("h1").text("Player 2 Turn");
} else {
currentPlayer = 1 - currentPlayer;
$("h1").text("Player 1 Turn");
}
}
function createBoard(){
//assign the alternateColor a false value
var alternateColor = 0;
//loop the number of rows needed, dynamically create a div with the class of row
for ( var i = 0; i < gameBoard.length; i++) {
var row = $('<div>').addClass('row');
//loop the number of game squares needed per row,
for( var j = 0; j < gameBoard.length; j++) {
// if alternateColor is a truthy value, create a div with the class of square and dark with a row attribute equal to the first loop index
if(alternateColor) {
var square = $('<div>').addClass('square dark').attr('row' , i).attr("col", j) ;
// switch alternateColor to falsey value
alternateColor = 1 - alternateColor;
// append the square to the current row
row.append(square);
} else {
// if falsey, create a div with the class of square and light with a row attribute equal to the first loop index
var square = $('<div>').addClass('square light').attr('row' , i).attr("col", j) ;
alternateColor = 1 - alternateColor;
row.append(square);
}
}
//target the class of gameArea to append the row
$('#gameArea').append(row);
// alternate the value of alternateColor to make the next row start with opposite color div
alternateColor = 1 - alternateColor;
}
}
function repopulateChecker(){
// loop through the gameBoard array
for(var i = 0; i < gameBoard.length; i++){
//loop though easch number in the inner array
for(var j =0; j < gameBoard.length; j++){
// if the gameBoard value at the outerloop index and innerloop index is a 1 the append a checker with the class of player1
if(gameBoard[i][j]=== 1){
var checker = $('<div>').addClass('checker player1');
//jQuery target the div with the row attribute of the outer loop index and col attribute of inner loop index and append the checker
$(`div[row = ${i}][col= ${j}]`).append(checker);
} else if(gameBoard[i][j]=== 2){
// if the gameBoard value at the outerloop index and innerloop index is a 2 the append a checker with the class of player2
var checker = $('<div>').addClass('checker player2');
$(`div[row = ${i}][col= ${j}]`).append(checker);
}
}
}
switchPlayer();
}
function resetGame() {
// set the gameBoard to the original status
gameBoard = [
[0,1,0,1,0,1,0,1],
[1,0,1,0,1,0,1,0],
[0,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[2,0,2,0,2,0,2,0],
[0,2,0,2,0,2,0,2],
[2,0,2,0,2,0,2,0],
];
// remove all the children div's (checkers) from the divs with the class of square
$('.square').empty();
// clear any existing highlights before checkers are repopulated
removeHighlights();
// reloop through array an assign checkers to original position
repopulateChecker();
}
function selectPiece(){
// has a div has not been clicked
if(!selectedChecker){
var currentChecker = this;
//get the numeric value of the div's row attribute that was clicked
currentRow = parseInt($(currentChecker).attr('row'));
//get the numeric value of the div's col attribute that was clicked
currentColumn = parseInt($(currentChecker).attr('col'));
//check who the current player is
// current player is Player 1 who controls the white checkers
if (currentPlayer) {
// current player is Player 1 who controls the white checkers
possibleRow = currentRow + 1;
possibleMoveLeft = currentColumn - 1;
possibleMoveRight = currentColumn + 1;
possibleJumpRow = currentRow + 2;
possibleJumpLeft = currentColumn - 2;
possibleJumpRight = currentColumn + 2;
//if the possible move is off the table to the left or right is undefined
if(gameBoard[possibleRow][possibleMoveLeft] === undefined){
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
} else if( gameBoard[possibleRow][possibleMoveRight] === undefined){
$(`div[row= ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
//if this piece is adjacent to 2 enemies
if( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 2 ) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
jumpRight = true;
jumpLeft = true;
}
// if the possible move left is empty and right is off the board
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleMoveRight] > 7) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
// if the possible move left is an opponent and right is of the table
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleMoveRight] > 7) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if the possible move left is off the table and right is open
if ( gameBoard[possibleMoveLeft] < 0 && gameBoard[possibleRow][possibleMoveRight] === 0) {
$(`div[row = ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
}
//if the possible move left is occupied by a friendly piece and the right is an enemy piece
if ( gameBoard[possibleRow][possibleMoveLeft] === 1 && gameBoard[possibleRow][possibleMoveRight] === 2) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
jumpRight = true;
}
// if the move right is an friendy and move left is a enemy
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if the move right is an enemy and move left is a friendly
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if the move left is open and the move right is a friendly pice
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
// if the move left is a friendly piece and the move right is open
if ( gameBoard[possibleRow][possibleMoveLeft] === 1 && gameBoard[possibleRow][possibleMoveRight] === 0){
$(`div[row = ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
}
// if there is an enemy piece in an adjacent square
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 2) {
// highlight the square of the div to the left and the div 2 rows down and 2 columns to the right
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
//raise a flag that a jump to the right occurred
jumpRight = true;
}
// if the gameBoard array numeric value of the div on the right is 0 (empty) and the value of the div on the left is 2 (opponents piece)
if ( gameBoard[possibleRow][possibleMoveRight] === 0 && gameBoard[possibleRow][possibleMoveLeft] === 2) {
// highlight the square of the div to the right and the div 2 rows down and 2 columns to the left
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
//raise a flag that a jump to the left occurred
jumpLeft = true;
}
//if both available moves are do not contain an opponents piece then add the class of highlight to both divs
else if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 0 ) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
}
} else {
// check the possible movements of the pieces from player 2's perspective (red checkers)
possibleRow = currentRow - 1;
possibleMoveLeft = currentColumn -1;
possibleMoveRight = currentColumn + 1;
possibleJumpRow = currentRow - 2;
possibleJumpLeft = currentColumn - 2;
possibleJumpRight = currentColumn + 2;
//if the possible move is off the table to the left or right is undefined
if(gameBoard[possibleRow][possibleMoveLeft] === undefined){
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
} else if( gameBoard[possibleRow][possibleMoveRight] === undefined){
$(`div[row= ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
// if the possible move left is empty and right is off the board
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleMoveRight] > 7) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
// if the possible move left is an opponent and right is of the table
if ( gameBoard[possibleRow][possibleMoveLeft] === 1 && gameBoard[possibleMoveRight] > 7) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if the possible move left is off the table and right is open
if ( gameBoard[possibleMoveLeft] < 0 && gameBoard[possibleRow][possibleMoveRight] === 0) {
$(`div[row = ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
jumpRight = true;
}
//if the piece is adjacent to two enemies
if( gameBoard[possibleRow][possibleMoveLeft] === 1 && gameBoard[possibleRow][possibleMoveRight] === 1 ) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
jumpRight = true;
jumpLeft = true;
}
//if the possible move left is occupied by a friendly piece and the right is an enemy piece
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
jumpRight = true;
}
// if the move right is an enemy and move left is a friendly
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if the move left is open and the move right is a friendly peice
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 2) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
}
// if the move left is a friendly piece and the move right is open
if ( gameBoard[possibleRow][possibleMoveLeft] === 2 && gameBoard[possibleRow][possibleMoveRight] === 0){
$(`div[row = ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
}
// if the move right is an friendy and move left is a enemy
if ( gameBoard[possibleRow][possibleMoveLeft] === 1 && gameBoard[possibleRow][possibleMoveRight] === 2) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
// if move left is empty and move right is an enemy
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).addClass("highLight");
jumpRight = true;
}
// highlight the square of the div to the right and the div 2 rows down and 2 columns to the left
if ( gameBoard[possibleRow][possibleMoveRight] === 0 && gameBoard[possibleRow][possibleMoveLeft] === 1) {
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).addClass("highLight");
jumpLeft = true;
}
//if the move right is open and the move left is open
if ( gameBoard[possibleRow][possibleMoveLeft] === 0 && gameBoard[possibleRow][possibleMoveRight] === 0 ) {
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).addClass("highLight");
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).addClass("highLight");
}
}
selectedChecker = gameBoard[currentRow][currentColumn];
} else {
//if the next square clicked has the class of highlight
if($(this).hasClass('highLight')){
//reset the checker so another checker may be selected
selectedChecker = null;
//jQuery target the div with the row and col value equal to the current checkers possible moves and remove the class highLight
removeHighlights();
//find the numeric value of row attribute the highlighted div clicked
var moveToRow = parseInt($(this).attr('row'));
//find the numeric value of col attribute the highlighted div clicked
var moveToColumn = parseInt($(this).attr('col'));
//check which player is doing the action to determine which color checker to change the array value to repopulate the correct color
if(currentPlayer) {
gameBoard[moveToRow][moveToColumn] = 1;
} else {
gameBoard[moveToRow][moveToColumn] = 2;
}
//if a jump occured remove what the possible move would have been
if(currentPlayer) {
if (jumpLeft) {
gameBoard[possibleRow][possibleMoveLeft]= 0;
}
if(jumpRight) {
gameBoard[possibleRow][possibleMoveRight]= 0;
}
player1Score++;
} else {
if (jumpLeft) {
gameBoard[possibleRow][possibleMoveLeft]= 0;
}
if(jumpRight) {
gameBoard[possibleRow][possibleMoveRight]= 0;
}
player2Score++;
}
//remove the checker that is currently selected
gameBoard[currentRow][currentColumn]= 0;
//remove all children divs from the divs with the class of square
$('.square').empty();
jumpRight = false;
jumpLeft = false;
//reloop through the array and create cheakers at the new array values
repopulateChecker();
} else {
//if the div clicked does not have the class of highLight, remove the highLight class and reset the original checker clicked, then exit function
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).removeClass("highLight");
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).removeClass("highLight");
selectedChecker =null;
return;
}
}
}
function removeHighlights(){
$(`div[row = ${possibleRow}][col = ${possibleMoveLeft}]`).removeClass("highLight");
$(`div[row= ${possibleRow}][col = ${possibleMoveRight}]`).removeClass("highLight");
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpLeft}]`).removeClass("highLight");
$(`div[row = ${possibleJumpRow}][col = ${possibleJumpRight}]`).removeClass("highLight");
}
|
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const { mongoose } = require("./database");
// Settings
app.set("port", process.env.PORT || 3000);
// Middlewares
app.use(cors({ origin: "http://localhost:4200" }));
app.use(morgan("dev"));
app.use(express.json());
// Routes
app.use("/api/login", require("./routes/login.routes"));
app.use("/api/users", require("./routes/users.routes"));
app.use("/api/internships", require("./routes/internships.routes"));
app.use("/api/ui", require("./routes/usersinternships.routes"));
app.post("/login2", function(request, response) {
if (
request.body.nombre == usuario.nombre ||
request.body.clave == usuario.clave
) {
// var token = jwt.sign(
// {
// usuario: "cecilio"
// },
// jwtClave
// );
let token = jwt.sign({username: "cecilio"},
jwtClave, { expiresIn: '24h' } // expires in 24 hours
);
response.send(token);
} else {
response.status(401).end("Usuario Incorrecto");
}
});
app.listen(3000, () => {
console.log("Server on port ", app.get("port"));
});
|
import React, { Component, PropTypes } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
class Index extends Component {
addTeam() {
Meteor.call( 'addTeam', count, ( error ) => {
if (error) {
console.log( error );
}
});
}
render() {
return (
<div>
<p>index page</p>
<button className="btn btn-primary" onClick={this.addTeam}>Test</button>
</div>
);
}
}
/*
*/
Index.propTypes = {
};
export default createContainer(() => {
return {
}
}, Index);
|
let result = ~5;
console.log(result);
|
import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Master from './src/master.js'
import Picture from './src/Picture.js'
const Routes = () => (
<Router>
<Scene key = "root">
<Scene
key="Master"
component={Master}
title="Master"
initial={true} />
<Scene
key="Picture"
component={Picture}
title="Picture" />
</Scene>
</Router>
)
export default Routes
|
/*
Requires nginx.
Create a block in nginx main server (/etc/nginx/sites-available/default) like below:
server {
...
# ouinode
location /ouinode {
proxy_pass http://127.0.0.1:1338;
}
location /ouinode_static {
alias /home/ceefour/git/optimizedui-sandbox/nodejs/static;
autoindex on;
}
}
With concurrency 128 and categories is delayed 1000ms:
Requests per second: 117.65 [#/sec] (mean)
Time per request: 1088.014 [ms] (mean)
Time per request: 8.500 [ms] (mean, across all concurrent requests)
With concurrency 256 and categories is delayed 1000ms:
Requests per second: 212.57 [#/sec] (mean)
Time per request: 1204.327 [ms] (mean)
Time per request: 4.704 [ms] (mean, across all concurrent requests)
So even under many concurrent load, RPS is good.
Problemm is, time per request is bad.
*/
var _ = require('./lib/underscore.js');
var http = require('http');
var fs = require('fs');
var categoryRepo = require('./category.js');
function fetchCategories(success) {
console.log('Fetching categories, simulating load by waiting 1000ms...');
setTimeout(function() {
success(categoryRepo.categories);
}, 1000);
}
function fetchContent(success) {
console.log('Fetching content...');
process.nextTick(function() {
var content = '<h1>Latest Fashion</h1><p>You will like this very much!</p>';
success(content);
});
}
var homePageTemplate = fs.readFileSync('templates/layout.html.tpl', 'UTF-8');
function checkHomePage(homePage) {
if (homePage.headerView != undefined && homePage.contentView != undefined && homePage.sidebarView != undefined) {
console.log('Page has all elements, rendering response');
//homePage.response.end(homePage.headerView + homePage.contentView);
fs.readFile('templates/layout6.html.tpl', 'UTF-8', function(err, data) {
if (err) throw err;
var output = _.template(data, {
baseUri: '/ouinode/',
staticUri: '/ouinode_static/',
jsUri: '/ouinode_static/js/',
skinUri: '/ouinode_static/skin/',
mediaUri: '/ouinode_static/media/',
pageTitle: 'Buy best fashion',
headerView: homePage.headerView,
sidebarView: homePage.sidebarView,
contentView: homePage.contentView,
});
homePage.response.end(output);
});
} else {
console.log('Checking page but page is not complete');
}
}
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var homePage = {response: res};
homePage.headerView = ' <ul class="nav">\
<li><p class="navbar-text"><span id="notification-count">0</span> </p></li>\
<li class="active"><h:link outcome="pretty:home" value="Home" /></li>\
<li><a href="#about">About</a></li>\
<li><a href="#contact">Contact</a></li>\
</ul>';
fetchCategories(function(categories) {
console.log('Categories:', categories);
output = _.template('<ul> \
<% _.each(categories, function(category) { %> \
<li><%- category %></li> \
<% }) %> \
</ul>', {categories: categories});
homePage.sidebarView = output;
checkHomePage(homePage);
});
fetchContent(function(content) {
console.log('Content:', content);
var output = _.template('<div id="content"><%= content %></div>', {content: content});
homePage.contentView = output;
checkHomePage(homePage);
});
console.log('Request handler done! Response will be sent later.');
}).listen(1338, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1338/');
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
define(["../globals", "underscore"], function(Globals, _) {
/**
* This module helps external agents that interact with content documents from
* the level of the iframe browsing context:
*
* - By providing a means of identifying the content through metadata
* that's brought down from the package document level.
*
* - By providing a direct link (bringing down the shareable URL) that could be used
* to load the content in the proper context with the reader app instead of the actual
* content document asset path.
*
* - By responding to an event when the external agent wants to bring a
* specific range of content into view.
*
* @param {Views.ReaderView} reader The Reader instance
* @constructor
*/
var ExternalAgentSupport = function(reader) {
var contentDocumentStates = {};
var contentDocuments = {};
Globals.on(Globals.Events.PLUGINS_LOADED, function() {
// Disable the AMD environment since it's not needed anymore at this point.
// This is done because external agents with their own module systems (Browserify)
// might load third-party scripts that are in the format of
// UMD (Universal Module Definition),
// and will mistakenly try to use Readium's AMD shim, almond.js, or require.js
if (window.define && window.define.amd) {
delete window.define.amd;
}
});
function appendMetaTag(_document, property, content) {
var tag = _document.createElement('meta');
tag.setAttribute('name', property);
tag.setAttribute('content', content);
_document.head.appendChild(tag);
}
function injectDublinCoreResourceIdentifiers(contentDocument, spineItem) {
var renditionIdentifier = reader.metadata().identifier; // the package unique identifier
var spineItemIdentifier = spineItem.idref; // use the spine item id as an identifier too
if (renditionIdentifier && spineItemIdentifier) {
appendMetaTag(contentDocument, 'dc.relation.ispartof', renditionIdentifier);
appendMetaTag(contentDocument, 'dc.identifier', spineItemIdentifier);
}
}
function determineCanonicalLinkHref(contentWindow) {
// Only grab the href if there's no potential cross-domain violation
// and the reader application URL has a CFI value in a 'goto' query param.
var isSameDomain = Object.keys(contentWindow).indexOf('document') !== -1;
if (isSameDomain && contentWindow.location.search.match(/goto=.*cfi/i)) {
return contentWindow.location.href.split("#")[0];
}
}
function getContentDocumentCanonicalLink(contentDocument) {
var contentDocWindow = contentDocument.defaultView;
if (contentDocWindow && (contentDocWindow.parent|| contentDocWindow.top)) {
var parentWindowCanonicalHref = determineCanonicalLinkHref(contentDocWindow.parent);
var topWindowCanonicalHref = determineCanonicalLinkHref(contentDocWindow.top);
return topWindowCanonicalHref || parentWindowCanonicalHref;
}
}
function injectAppUrlAsCanonicalLink(contentDocument, spineItem) {
if (contentDocument.defaultView && contentDocument.defaultView.parent) {
var canonicalLinkHref = getContentDocumentCanonicalLink(contentDocument);
if (canonicalLinkHref) {
var link = contentDocument.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('href', canonicalLinkHref);
contentDocument.head.appendChild(link);
contentDocumentStates[spineItem.idref].canonicalLinkElement = link;
}
}
}
var bringIntoViewDebounced = _.debounce(function (range) {
var target = reader.getRangeCfiFromDomRange(range);
var contentDocumentState = contentDocumentStates[target.idref];
if (contentDocumentState && contentDocumentState.isUpdated) {
reader.openSpineItemElementCfi(target.idref, target.contentCFI);
} else {
contentDocumentState.pendingNavRequest = {
idref: target.idref,
contentCFI: target.contentCFI
};
}
}, 100);
function bindBringIntoViewEvent(contentDocument) {
// 'scrolltorange' is a non-standard event that is emitted on the content frame
// by some external tools like Hypothes.is
contentDocument.addEventListener('scrolltorange', function (event) {
event.preventDefault();
var range = event.detail;
bringIntoViewDebounced(range);
});
}
function bindSelectionPopupWorkaround(contentDocument) {
// A hack to make the Hypothes.is 'adder' context menu popup work when the content doc body is positioned.
// When the content doc has columns and a body with position set to 'relative'
// the adder won't be positioned properly.
//
// The workaround is to clear the position property when a selection is active.
// Then restore the position property to 'relative' when the selection clears.
contentDocument.addEventListener('selectionchange', function () {
var selection = contentDocument.getSelection();
if (selection && selection.isCollapsed) {
contentDocument.body.style.position = 'relative';
} else {
contentDocument.body.style.position = '';
}
});
}
/***
*
* @param {Document} contentDocument Document instance with DOM tree
* @param {Models.SpineItem} spineItem The associated spine item object
*/
this.bindToContentDocument = function(contentDocument, spineItem) {
contentDocuments[spineItem.idref] = contentDocument;
contentDocumentStates[spineItem.idref] = {};
injectDublinCoreResourceIdentifiers(contentDocument, spineItem);
injectAppUrlAsCanonicalLink(contentDocument, spineItem);
bindBringIntoViewEvent(contentDocument);
if (spineItem.isReflowable()) {
bindSelectionPopupWorkaround(contentDocument);
}
};
/***
*
* @param {Models.SpineItem} spineItem The associated spine item object
*/
this.updateContentDocument = function (spineItem) {
var contentDocument = contentDocuments[spineItem.idref];
var state = contentDocumentStates[spineItem.idref];
if (contentDocument && state) {
if (state.canonicalLinkElement) {
var canonicalLinkHref = getContentDocumentCanonicalLink(contentDocument);
if (canonicalLinkHref) {
state.canonicalLinkElement.setAttribute('href', canonicalLinkHref);
}
}
state.isUpdated = true;
var pendingNavRequest = state.pendingNavRequest;
if (pendingNavRequest) {
reader.openSpineItemElementCfi(pendingNavRequest.idref, pendingNavRequest.contentCFI);
state.pendingNavRequest = null;
}
}
};
};
return ExternalAgentSupport;
});
|
import React, { useContext, useState } from "react";
import {
Text,
View,
TouchableOpacity,
TextInput,
TouchableWithoutFeedback,
Keyboard,
} from "react-native";
import { FontAwesome as Icon } from "@expo/vector-icons";
import styles from "../../styles/signInStyles";
import { UserContext } from "../../functions/providers/UserContext";
import { ColorContext } from "../../functions/providers/ColorContext";
export default function Name(props) {
const { navigation } = props;
const { color } = useContext(ColorContext);
const { newUser, setNewUser } = useContext(UserContext);
const [name, setName] = useState("");
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<View style={{ ...styles.container, backgroundColor: color.primary}}>
<Text style={{ ...styles.headerText, color: color.primaryText}}>What's your name?</Text>
<Text style={{ ...styles.subHeaderText, color: color.primaryText}}>
This is what we'll call you inside the app and it won’t be shared with
anyone.
</Text>
<TextInput
placeholder="Johnny Appleseed"
placeholderTextColor={color.inactive}
style={{ fontSize: 20, padding: 20, paddingBottom: 15, paddingTop: 15, borderWidth: 1, borderRadius: 20, borderColor: color.primaryText }}
onChangeText={setName}
/>
<TouchableOpacity
style={[
{ ...styles.button, backgroundColor: color.highlight},
name.length > 2 ? {} : { backgroundColor: color.inactive },
]}
onPress={() => {
if (name.length > 2) {
setNewUser({ ...newUser, name });
navigation.navigate("Number");
}
}}
>
<Icon
name="chevron-right"
color={color.primary}
size={28}
style={{ marginLeft: 3, marginTop: 2 }}
/>
</TouchableOpacity>
{/* <TouchableOpacity
//onPress={() => navigation.goBack()}
style={{ ...styles.signIn, backgroundColor: color.primary, marginLeft: 2, marginTop: 2}}
>
<Text style={{
fontSize: 20,
color: color.inactive
}}>
Sign In Here!
</Text>
</TouchableOpacity> */}
</View>
</TouchableWithoutFeedback>
);
}
|
var net=require('net');
var tcpServer=net.createServer(function(socket){
socket.write("hello\n");
setTimeout(function(){
socket.end("world \n");
},2000);
});
tcpServer.listen(8000);
|
import Controller from "@ember/controller";
import { inject as service } from "@ember/service";
import { getOwner } from "@ember/application";
export default Controller.extend({
router: service(),
actions: {
routeToPageDown() {
const currentRoute = getOwner(this).lookup("controller:application")
.currentPath;
switch (currentRoute) {
case "index":
this.get("router").transitionTo("skills");
break;
case "skills":
this.get("router").transitionTo("portfolio");
break;
case "portfolio":
this.get("router").transitionTo("education");
break;
case "education":
this.get("router").transitionTo("index");
break;
}
},
routeToPageUp() {
const currentRoute = getOwner(this).lookup("controller:application")
.currentPath;
switch (currentRoute) {
case "index":
this.get("router").transitionTo("education");
break;
case "skills":
this.get("router").transitionTo("index");
break;
case "portfolio":
this.get("router").transitionTo("skills");
break;
case "education":
this.get("router").transitionTo("portfolio");
break;
}
}
}
});
|
(function(window) {
var HOSTNAME = window.location.hostname;
var RUNTIME_ID = chrome.runtime.id;
var _$body;
document.addEventListener('DOMContentLoaded',init);
function init() {
_$body = document.getElementById('body');
setScheduleBackground();
}
/* =======================================================================
Set Schedule Background
========================================================================== */
function setScheduleBackground() {
if (!_$body) return;
function setBackgroundColor() {
var $targetList = _$body.querySelectorAll('p,a');
for (var i = 0; i < $targetList.length; i++) {
var $target = $targetList[i];
var $spanList = $target.querySelectorAll('span');
if ($spanList.length <= 0) continue;
var $span = $spanList[0];
var className = $span.getAttribute('class');
if (className && -1 < className.indexOf('event_')) {
var color = document.defaultView.getComputedStyle($span,null).backgroundColor;
var rgb = color.substring(4, color.length - 1).replace(/ /g, '').split(',');
var $parents = getParents($target,'.group_week_calendar_item');
if ($parents.length <= 0) $parents = getParents($target,'.personalMonth_calendar_item');
if (0 < $parents.length) {
$parents[0].style.backgroundColor = 'rgba(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ',.2)';
$parents[0].style.padding = '5px';
}
}
}
}
_$body.addEventListener('DOMSubtreeModified',setBackgroundColor,false);
_$body.addEventListener('propertychange',setBackgroundColor,false);
setBackgroundColor();
}
var getParents = function (elem, selector) {
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
var parents = [];
for ( ; elem && elem !== document; elem = elem.parentNode ) {
if (selector) {
if (elem.matches(selector)) {
parents.push(elem);
}
continue;
}
parents.push(elem);
}
return parents;
};
})(window);
|
// models/customer.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var accounting = mongoose.createConnection('mongodb://localhost/accounting');
var random = require('mongoose-simple-random');
var CustomerSchema = new Schema({
firstName : String,
lastName : String,
loyaltyNum : Number
});
CustomerSchema.plugin(random);
module.exports = accounting.model('Customer', CustomerSchema);
|
import React from 'react';
import './CSSFiles/TableMapper.css';
export default function TableMapper(props) {
const { standings } = props;
let mapper = standings.map((standing,i)=>{
console.log(standing.position)
console.log(standing.team.crestUrl)
return <tr key={i}><p>{standing.position}</p>{" "}<img src={standing.team.crestUrl}/></tr>
})
return (
<div>
{mapper}
</div>
)
}
|
// Get all products to be
// displayed in the products page
window.onload = getProducts();
function getProducts() {
let token = localStorage.getItem('token');
let allProducts = document.getElementById('products')
fetch('http://localhost:5000/api/v2/products', {
mode: 'cors',
headers: {
'x-access-token': token
}
})
.then((res) => res.json())
.then((data) => {
if (data.message == 'Token is invalid') {
alert('You must login to access this page');
window.location.replace('index.html')
}
if (data.message == 'No available products') {
// alert('No available products at the moment');
// window.location.replace('index.html')
}
let result = '';
data.products?.forEach(product => {
result += `
<div onclick="displayModal('${product.product_id}')" class="single-product" id="getsingleproduct">
<div>
<a href="#" title=""><img src=${product.image_url} alt="Product1"></a>
</div>
<form>
<label href="" title="" id="description">${product.title}</label>
</form>
<div class="product-footer">
<a href="" title="">Ksh<span class="first" id="price">${product.price}</span></a>
<span class="last"><a href="#" title="">Buy <i class="fa fa-plus"></i></a></span>
</div>
</div>
`;
allProducts.innerHTML = result;
});
localStorage.setItem('products', JSON.stringify(data.products));
})
.catch((error) => console.log(error))
}
function findProduct() {
let input, sort, maindiv, singlediv, divdata, i;
input = document.getElementById("searchInput");
sort = input.value.toUpperCase();
maindiv = document.getElementById("products");
singlediv = maindiv.getElementsByTagName("div");
for (i = 0; i < singlediv.length; i++) {
divdata = singlediv[i].getElementsByTagName("label")[0];
if (divdata) {
if (divdata.innerHTML.toUpperCase().indexOf(sort) > -1) {
singlediv[i].style.display = "";
} else {
singlediv[i].style.display = "none";
}
}
}
}
|
/*
Finite Automaton module.
An extension to the JFLAP library.
*/
var FiniteAutomaton = function(jsav, options) {
Automaton.apply(this, arguments);
this.configurations = $("<ul>"); // configurations jQuery object used to setup view at a step
this.configViews = []; // configurations view for a step
this.step = 0; // current step the user is at, used for changing configuration display
}
JSAV.ext.ds.FA = function (options) {
var opts = $.extend(true, {visible: true, autoresize: true}, options);
return new FiniteAutomaton(this, opts);
};
JSAV.utils.extend(FiniteAutomaton, JSAV._types.ds.Graph);
FiniteAutomaton.prototype = Object.create(Automaton.prototype, {});
var faproto = FiniteAutomaton.prototype;
faproto.loadFAFromJFLAPFile = function (url) {
var parser,
xmlDoc,
text,
jsav = this.jsav;
$.ajax( {
url: url,
async: false, // we need it now, so not asynchronous request
success: function(data) {
text = data;
}
});
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
if (!xmlDoc.getElementsByTagName("type")[0]) {
// This file is not a file that can be parsed.
window.alert('File does not contain an automaton.');
return;
}
if (xmlDoc.getElementsByTagName("type")[0].childNodes[0].nodeValue !== 'fa') {
// This file was created by a different automaton editor.
window.alert('File does not contain a finite automaton.');
return;
}
else {
var maxYvalue = 0;
var nodeMap = {}; // map node IDs to nodes
var xmlStates = xmlDoc.getElementsByTagName("state");
//xmlStates = sortBy(xmlStates, function(x) { return x.id; })
var xmlTrans = xmlDoc.getElementsByTagName("transition");
// Iterate over the nodes and initialize them.
for (var i = 0; i < xmlStates.length; i++) {
var x = Number(xmlStates[i].getElementsByTagName("x")[0].childNodes[0].nodeValue);
var y = Number(xmlStates[i].getElementsByTagName("y")[0].childNodes[0].nodeValue);
maxYvalue = (y>maxYvalue)? x:maxYvalue;
var newNode = this.addNode({left: x, top: y, value: xmlStates[i].attributes[1].nodeValue});
// Add the various details, including initial/final states and state labels.
var isInitial = xmlStates[i].getElementsByTagName("initial")[0];
var isFinal = xmlStates[i].getElementsByTagName("final")[0];
var isLabel = xmlStates[i].getElementsByTagName("label")[0];
if (isInitial) {
this.makeInitial(newNode);
}
if (isFinal) {
newNode.addClass('final');
}
if (isLabel) {
label_val = '<p class = "label_css">' + isLabel.childNodes[0].nodeValue + '</p>';
newNode.stateLabel(label_val);
}
nodeMap[xmlStates[i].id] = newNode;
newNode.stateLabelPositionUpdate();
}
// Iterate over the edges and initialize them.
for (var i = 0; i < xmlTrans.length; i++) {
var from = xmlTrans[i].getElementsByTagName("from")[0].childNodes[0].nodeValue;
var to = xmlTrans[i].getElementsByTagName("to")[0].childNodes[0].nodeValue;
var read = xmlTrans[i].getElementsByTagName("read")[0].childNodes[0];
// Empty string always needs to be checked for.
if (!read) {
read = emptystring;
}
else {
read = read.nodeValue;
}
var edge = this.addEdge(nodeMap[from], nodeMap[to], {weight: read});
edge.layout();
}
var currentFAHeight = this.element.height();
this.element.height(Math.max(currentFAHeight, maxYvalue));
jsav.displayInit();
}
/*if (auto === 'auto'){
layoutGraph();
}*/
};
/*
NFA to DFA conversion
Note: g.transitionFunction takes a single node and returns an array of node values
Requires underscore.js
*/
var convertToDFA = function(jsav, graph, opts, visualizable = false) {
var left = 10;
var g;
if(!visualizable)
g = jsav.ds.FA($.extend({layout: 'automatic'}, opts)),
alphabet = Object.keys(graph.alphabet),
startState = graph.initial,
newStates = [];
else{
var options = $.extend(true, {layout: 'automatic'}, opts);
g = jsav.ds.FA(options),
alphabet = Object.keys(graph.alphabet),
startState = graph.initial,
newStates = [];
}
// Get the first converted state
if(visualizable)
jsav.umsg("The first step is to find the lambda closure for the NFA start state. From the NFA's start state, find every other state that can be reached by a lambda transition.");
var first = lambdaClosure([startState.value()], graph).sort().join();
if(visualizable){
var listOfFirstNodes = first.split(',');
var highlightedNodes = [];
for(var i = 0; i< listOfFirstNodes.length; i++ ){
var node = graph.getNodeWithValue(listOfFirstNodes[i])
node.highlight();
highlightedNodes.push(node);
}
}
newStates.push(first);
if(visualizable){
jsav.step();
jsav.umsg("The resulting list of states becomes the name of the DFA's start state.");
}
var temp = newStates.slice(0);
first = g.addNode({value: first});
g.makeInitial(first);
g.layout();
if(visualizable){
left += 50;
for(var state in highlightedNodes){
highlightedNodes[state].unhighlight();
}
jsav.step();
jsav.umsg("Nest step is to identify the transitions out of the DFA start state. For each letter in the alphabet, consider all states reachable in the NFA from any state in the start state on that letter. This becomes the name of the target state on that transition.");
}
// Repeatedly get next states and apply lambda closure
while (temp.length > 0) {
var val = temp.pop(),
valArr = val.split(',');
var prev = g.getNodeWithValue(val);
for (var i = 0; i < alphabet.length; i++) {
var letter = alphabet[i];
var next = [];
for (var j = 0; j < valArr.length; j++) {
next = _.union(next, lambdaClosure(graph.transitionFunction(graph.getNodeWithValue(valArr[j]), letter), graph));
}
var nodeName = next.sort().join();
var node;
if (nodeName) {
if (!_.contains(newStates, nodeName)) {
temp.push(nodeName);
newStates.push(nodeName);
node = g.addNode({value: nodeName});
if(visualizable){
if(left + 50 < opts.width)
left+=50;
g.layout();
}
} else {
node = g.getNodeWithValue(nodeName);
}
var edge = g.addEdge(prev, node, {weight: letter});
}
}
if(visualizable){
if(temp.length > 0)
{
jsav.step();
jsav.umsg("Repeat the process for each new node we find");
}
}
}
// add the final markers
if(visualizable)
jsav.umsg("Determine the final states");
addFinals(g, graph);
g.layout();
if(visualizable){
jsav.step();
jsav.umsg("The final (optional) step is to rename the states.")
}
/*var nodes = g.nodes();
for (var next = nodes.next(); next; next = nodes.next()) {
next.stateLabel(next.value());
next.stateLabelPositionUpdate();
}*/
g.updateNodes();
g.layout();
return g;
};
// Function to add final markers to the resulting DFA
var addFinals = function(g1, g2) {
var nodes = g1.nodes();
for (var next = nodes.next(); next; next = nodes.next()) {
var values = next.value().split(',');
for (var i = 0; i < values.length; i++) {
if (g2.getNodeWithValue(values[i]).hasClass('final')) {
next.addClass('final');
break;
}
}
}
};
/*
Function to apply lambda closure.
Takes in an array of values (state names), returns an array of values
Only used in NFA to DFA conversion.
There's a different lambda closure function used for nondeterministic traversal in certain tests.
*/
var lambdaClosure = function(input, graph) {
var arr = [];
for (var i = 0; i < input.length; i++) {
arr.push(input[i]);
var next = graph.transitionFunction(graph.getNodeWithValue(input[i]), lambda);
arr = _.union(arr, next);
}
var temp = arr.slice(0);
while (temp.length > 0) {
var val = temp.pop(),
next = graph.transitionFunction(graph.getNodeWithValue(val), lambda);
next = _.difference(next, arr);
arr = _.union(arr, next);
temp = _.union(temp, next);
}
return arr;
};
// helper depth-first search to find connected component
var dfs = function (visited, node, options) {
var successors = node.neighbors();
for (var next = successors.next(); next; next = successors.next()) {
if (!_.contains(visited, next)) {
visited.push(next);
dfs(visited, next);
}
}
};
// function to toggle the intitial state of a node
// appears as a button in the right click menu
var toggleInitial = function(g, node) {
$("#rmenu").hide();
node.unhighlight();
if (node.equals(g.initial)) {
g.removeInitial(node);
}
else {
if (g.initial) {
alert("There can only be one intial state!");
} else {
g.makeInitial(node);
}
}
};
// function to toggle the final state of a node
// appears as a button in the right click menu
var toggleFinal = function(g, node) {
if (node.hasClass("final")) {
node.removeClass("final");
}
else {
node.addClass("final");
}
$("#rmenu").hide();
node.unhighlight();
};
// function to change the customized label of a node
// an option in right click menu
var changeLabel = function(node) {
$("#rmenu").hide();
var nodeLabel = prompt("How do you want to label it?");
if (!nodeLabel || nodeLabel == "null") {
nodeLabel = "";
}
node.stateLabel(nodeLabel);
node.stateLabelPositionUpdate();
node.unhighlight();
}
// function to clear the customized label
// an option in the right click menu
var clearLabel = function(node) {
$("#rmenu").hide();
node.unhighlight();
node.stateLabel("");
}
// Function to switch which empty string is being used (lambda or epsilon) if a loaded graph uses the opposite representation to what the editor is currently using.
var checkEmptyString = function(w) {
var wArray = w.split("<br>");
// It is necessary to check every transition on the edge.
for (var i = 0; i < wArray.length; i++) {
if ((wArray[i] == lambda || wArray[i] == epsilon) && wArray[i] != emptystring) {
emptyString();
}
}
return wArray.join("<br>");
};
// Function to add final markers to the resulting DFA
var addFinals = function(g1, g2) {
var nodes = g1.nodes();
for (var next = nodes.next(); next; next = nodes.next()) {
var values = next.value().split(',');
for (var i = 0; i < values.length; i++) {
if (g2.getNodeWithValue(values[i]).hasClass('final')) {
next.addClass('final');
break;
}
}
}
};
var visualizeConvertToDFA = function(jsav, graph, opts) {
// jsav.label("Converted:");
var left = 10;
var options = $.extend(true, {layout: 'automatic'}, opts);
var g = jsav.ds.FA(options),
alphabet = Object.keys(graph.alphabet),
startState = graph.initial,
newStates = [];
// Get the first converted state
jsav.umsg("The first step is to find the lambda closure for the NFA start state.");
var first = lambdaClosure([startState.value()], graph).sort().join();
var listOfFirstNodes = first.split(',');
var highlightedNodes = [];
for(var i = 0; i< listOfFirstNodes.length; i++ ){
var node = graph.getNodeWithValue(listOfFirstNodes[i])
node.highlight();
highlightedNodes.push(node);
}
newStates.push(first);
jsav.step();
jsav.umsg("The result we got is the start state for the DFA.");
var temp = newStates.slice(0);
first = g.addNode({value: first});
left += 50;
g.makeInitial(first);
g.layout();
for(var state in highlightedNodes){
highlightedNodes[state].unhighlight();
}
jsav.step();
jsav.umsg("Nest step is to identify the transitons for the DFA start state.");
// Repeatedly get next states and apply lambda closure
while (temp.length > 0) {
var val = temp.pop(),
valArr = val.split(',');
var prev = g.getNodeWithValue(val);
for (var i = 0; i < alphabet.length; i++) {
var letter = alphabet[i];
var next = [];
for (var j = 0; j < valArr.length; j++) {
next = _.union(next, lambdaClosure(graph.transitionFunction(graph.getNodeWithValue(valArr[j]), letter), graph));
}
var nodeName = next.sort().join();
var node;
if (nodeName) {
if (!_.contains(newStates, nodeName)) {
temp.push(nodeName);
newStates.push(nodeName);
node = g.addNode({value: nodeName});
if(left + 50 < opts.width)
left+=50;
g.layout();
} else {
node = g.getNodeWithValue(nodeName);
}
var edge = g.addEdge(prev, node, {weight: letter});
}
}
if(temp.length > 0)
{
jsav.step();
jsav.umsg("repeat the same process for each new node we find");
}
}
// add the final markers
jsav.umsg("Determine the final states");
addFinals(g, graph);
g.layout();
jsav.step();
jsav.umsg("Final step is to rename the states names.")
var nodes = g.nodes();
for (var next = nodes.next(); next; next = nodes.next()) {
next.stateLabel(next.value());
next.stateLabelPositionUpdate();
}
g.updateNodes();
return g;
};
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
|
import { Strategy as TwitterStrategy } from 'passport-twitter';
export default function ({ passport, login }) {
// https://github.com/jaredhanson/passport-twitter
passport.use(new TwitterStrategy({
consumerKey: process.env.TWITTER_KEY,
consumerSecret: process.env.TWITTER_SECRET,
callbackURL: '/login/twitter/return',
includeEmail: true,
includeStatus: false,
passReqToCallback: true,
}, async (req, token, tokenSecret, profile, done) => {
try {
if (profile.emails && profile.emails.length) profile.emails[0].verified = true;
const user = await login(req, 'twitter', profile, { token, tokenSecret });
done(null, user);
} catch (err) {
done(err);
}
}));
}
|
import { storiesOf } from '@storybook/vue';
import OfferBanner from './OfferBanner';
import { action } from '@storybook/addon-actions';
storiesOf('Design System|Atoms/OfferBanner', module)
.add('default', () => {
return {
components: { OfferBanner },
template: `<OfferBanner text="schnapp dir pur: nur heute die 100 g packung für 2,99 euro kaufen!" />`,
data: () => ({ }),
};
})
.add('different color', () => {
return {
components: { OfferBanner },
template: `<OfferBanner backgroundColor="red" color="black" text="schnapp dir pur: nur heute die 100 g packung für 2,99 euro kaufen!" />`,
data: () => ({ }),
};
})
.add('no text', () => {
return {
components: { OfferBanner },
template: `<OfferBanner />`,
data: () => ({ }),
};
});
|
$(document).ready(function(){
/*广告图效果*/
var current = 0;
var bannerLength = $(".banner-ul li").width();
var num = $(".banner-ul").children().length;
$(".banner-ul").css("width",bannerLength*num);
/*前驱按钮*/
$("#left").click(function(){
if(current!=0){
$(".banner-ul").animate({marginLeft:-bannerLength*(--current)});
}else{
$(".banner-ul").animate({marginLeft:-bannerLength*(num-1)});
current = num-1;
}
});
/*后驱按钮*/
$("#right").click(clicknext =function(){
if(current!=(num-1)){
$(".banner-ul").animate({marginLeft:-bannerLength*(++current)});
}else{
$(".banner-ul").animate({marginLeft:-bannerLength*0});
current = 0;
}
});
/*滚动播放*/
setInterval("clicknext()",5000);
/*产品轮播效果*/
var current1 = 0;
var productLength = $(".group").width();
var childNum = $(".group ul").children().length%4;
var group = parseInt($(".group ul").children().length/4);
var productNum = childNum==0?group:group+1;
$(".group ul").css("width",productLength*productNum);
/*
$(".group ul li").each(function(index, element) {
if(index%4==0){
$(this).addClass("first");
}
});*/
var productNum = $(".group ul").children().length/2;
var iMarginLeft = parseInt($('.group ul').css('margin-left'));
var iSpeed = 1;
var timer = null;
var aa = function (){
if(iMarginLeft == -productNum*219){
iMarginLeft = 0;
}else if(iMarginLeft == 0 && iSpeed<0){
iMarginLeft = -productNum*219;
}
iMarginLeft -= iSpeed;
$('.group ul').css("margin-left", iMarginLeft);
}
timer = setInterval(aa,10);
$(".group ul li").mouseover(function(){clearInterval(timer)});
$(".group ul li").mouseout(function(){clearInterval(timer);timer = setInterval(aa,10);});
/*前驱按钮*/
$("#left2").click(function(){
/*if(current1!=0){
$(".group ul").animate({marginLeft:-productLength*(--current1)});
}else{
$(".group ul").animate({marginLeft:-productLength*(productNum-1)});
current1 = productNum-1;
}*/
if(iSpeed<0){
iSpeed = -iSpeed;
}
});
/*后驱按钮*/
$("#right2").click(clicknext1 =function(){
/*if(current1!=(productNum-1)){
$(".group ul").animate({marginLeft:-productLength*(++current1)});
}else{
$(".group ul").animate({marginLeft:-productLength*0});
current1 = 0;
}*/
if(iSpeed>0){
iSpeed = -iSpeed;
}
});
/*滚动播放*/
/* setInterval(function(){
},5000);*/
});
|
import logo from './logo.png'
import React, { Component } from 'react';
import { Layout, Menu, Dropdown, Avatar, Badge } from 'antd';
import './frame.less';
import { adminRoutes } from '../../routes';
import { withRouter } from 'react-router-dom';
import { DownOutlined } from '@ant-design/icons';
const { Header, Content, Sider } = Layout;
// 通过装饰器模式,让组件的props具有router的history属性
@withRouter
class Frame extends Component {
onClickHandler = ({ key }) => {
this.props.history.push(key)
}
onMenuDropDownClick = ({ key }) => {
console.log(key)
this.props.history.push(key)
}
render() {
const menu = (
<Menu onClick={this.onMenuDropDownClick}>
<Menu.Item key='/admin/notifications'>
<Badge dot>
通知中心
</Badge>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">
个人设置
</a>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="http://www.tmall.com/">
退出
</a>
</Menu.Item>
</Menu>
);
return (
<Layout style={{ minHeight: '100%' }}>
<Header className="header zisuye-header">
<div className="logo zisuye-logo">
<img src={logo} alt='LOGO' />
</div>
<div>
<Dropdown overlay={menu}>
<a className="ant-dropdown-link" onClick={e => e.preventDefault()} style={{ display: 'flex', alignItems: 'center' }}>
<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
<span>欢迎您,紫苏叶</span>
<Badge count={10} offset={[-10, -10]}>
<DownOutlined />
</Badge>
</a>
</Dropdown>
</div>
</Header>
<Layout>
<Sider width={200} className="site-layout-background">
<Menu
mode="inline"
selectedKeys={[this.props.location.pathname]}
// defaultOpenKeys={['sub1']}
onClick={this.onClickHandler}
style={{ height: '100%', borderRight: 0 }}
>
{
adminRoutes.filter(item => item.nav === true).map(route => {
return <Menu.Item key={route.pathname}>
{/* <Icon type='dashboard' /> */}
{route.title}
</Menu.Item>
})
}
</Menu>
</Sider>
<Layout style={{ padding: '0 0' }}>
{/* <Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>List</Breadcrumb.Item>
<Breadcrumb.Item>App</Breadcrumb.Item>
</Breadcrumb> */}
<Content
className="site-layout-background"
style={{
padding: 24,
margin: 0,
minHeight: 280,
}}
>
{this.props.children}
</Content>
</Layout>
</Layout>
</Layout>
);
}
}
export default Frame;
|
const {Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = require('../db');
const Role=require('./User_Role.js')
class Task extends Model {}
Task.init({
id_task: {
type:Sequelize.INTEGER,
primaryKey: true
},
id_product: Sequelize.INTEGER,
name:DataTypes.STRING,
finish: DataTypes.BOOLEAN
}, {
sequelize,
modelName: "tasks",
timestamps: false
});
Task.belongsToMany(Role, { through: "RoleTasks" });
Role.belongsToMany(Task, { through: "RoleTasks" });
module.exports = Task;
|
import CustomerServicePage from "./customer-service-page";
export default CustomerServicePage;
|
import system from '../../utils/systemInfo'
// pages/index/index.js
Page({
/**
* 页面的初始数据
*/
data: {
// 状态
state:{
// input与textarea切换,0为input,1为textarea
changeInput:0,
// 工具是否显示,0为不显示,1为显示
toolBox:0
},
// 文字内容
chat:[
{content:'我企鹅委屈打算的气味啊撒我企鹅委屈打算的气味啊撒打算的胃打算的胃',mine:false,width:265}
],
// scroll位置
scroll:0,
// 聊天框高度
chatContentHeight:0,
// input行数
chatLine: 1,
// input 内容和最后宽度
textareValue: "",
inputFocus:false,
textareFocus:false,
// 测试宽度的隐藏chat_box
chatWidth: 265,
chatValue: ' ',
chatHeight: 'auto'
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
// 初始化默认值
this._focusNone = true
// 获取空格的宽度
this._getNbsp()
// 获取聊天框的高度
this._getScrollHeight()
// 1rpx高度
this._getRPX()
},
// 获取1rpx的高度
_getRPX(){
// 正常input框的高度
this.setData({
chatHeight:'1rpx'
})
var query = wx.createSelectorQuery();
query.select('#chatWidth').boundingClientRect()
query.exec((res) => {
this._RPX = res[0].height
})
},
_changeChatHeight(){
const input = this.data.state.changeInput
if(input===0){
this.setData({
chatContentHeight:100*this._RPX
})
}else{
this.setData({
chatContentHeight:(100+((chatLine-1)*60))*this._RPX
})
}
},
// 工具栏弹出时聊天框高度
_changeChatMinHeight(){
this.setData({
chatContentHeight:this._chatToolHeight
})
},
// 键盘弹出时聊天框高度
_changeSetChatHeight(height){
this.setData({
chatContentHeight:this._chatHeight - height
})
},
// 获取聊天框的高度
_getScrollHeight(){
// 正常input框的高度
this.setData({
chatHeight:'100rpx'
})
var query = wx.createSelectorQuery();
query.select('#chatWidth').boundingClientRect()
query.exec((res) => {
this._chatHeight = system.windowHeight - res[0].height
})
// 工具栏的高度
this.setData({
chatHeight:'320rpx'
})
var query = wx.createSelectorQuery();
query.select('#chatWidth').boundingClientRect()
query.exec((res) => {
this._chatToolHeight = this._chatHeight - res[0].height
this._changeChatHeight()
})
},
// 获取空格的宽度
_getNbsp(){
var query = wx.createSelectorQuery();
query.select('#chatWidth').boundingClientRect()
query.exec((res) => {
this._nbsp = res[0].width
})
this._arrStr = 0
this._chatStr = []
},
// chat行数改变跟着改变
bindleChangeChatLine: function (e) {
this.setData({
chatLine: e.detail.lineCount
})
if(this._focusInput){
const chatLine = e.detail.lineCount>4?4:e.detail.lineCount
const textareaHeight = (chatLine-1)*(this._RPX*60)
this._changeSetChatHeight(this._keyboardHeight+textareaHeight)
}
},
// 获取焦点,点击输入框,键盘与输入框的高度
bindleFocusTextarea: function (e) {
if (e.detail.height) {
const chatLine = this.data.chatLine>4?4:this.data.chatLine
const textareaHeight = (chatLine-1)*(this._RPX*60)
this._changeSetChatHeight(e.detail.height+textareaHeight)
this._scrollMoveDown()
this._setState('toolBox',0)
this._keyboardHeight = e.detail.height
}
},
bindleFocusInput:function(e){
if (e.detail.height) {
this._changeSetChatHeight(e.detail.height)
this._scrollMoveDown()
this._setState('toolBox',0)
this._focusInput = false
}
},
// 宽度计算最佳宽度
_getChatWidth (arr) {
let total = 0
let max = 265
let line = 0
for(let i=0;i<arr.length;i++){
total+=arr[i]
if(total>max){
line++
max = total - arr[i]
total = 0
}
}
this.setData({
chat:this.data.chat.concat(
{content:this.data.textareValue,width:max+line,mine:true}
),
textareValue:''
})
},
// 获取单字的宽度
_forCheckOneString (arr) {
if(arr[this._arrStr]){
this.setData({
chatValue:arr[this._arrStr]
})
}
var query = wx.createSelectorQuery()
query.select('#chatWidth').boundingClientRect()
query.exec((res) => {
if(arr.length-1 < this._arrStr){
this._getChatWidth(this._chatStr)
this._arrStr = 0
this._chatStr = []
}else{
if(res[0].width===0&&this.data.chatValue===" "){
this._chatStr.push(this._nbsp)
}else{
this._chatStr.push(res[0].width)
}
this._arrStr++
this._forCheckOneString(arr)
}
})
},
// 失去焦点,底部距离恢复
bindleBlurInput: function () {
this._focusInput = true
if(this._focusNone){
this._changeChatHeight()
}else{
this._focusNone = true
}
},
bindleBlurTextarea:function(){
if(this._focusNone){
this._changeChatHeight()
}else{
this._focusNone = true
}
},
// 提交输入
bindleConfirm: function (e) {
if(e.detail.value){
const value = e.detail.value
const arr = value.split('')
this._forCheckOneString(arr)
this._focusNone = false
this.setData({
textareValue: e.detail.value,
})
const changeInput = this.data.state.changeInput
if(changeInput===1){
this.setData({
textareFocus: true
})
}else{
this.setData({
inputFocus: true
})
}
}
},
// 根据输入修改值
bindleInput:function(e){
if(e.detail.value){
const value = e.detail.value
this.setData({
textareValue: value
})
}
},
// 修改多行还是单行
bindleText:function(){
const changeInput = this.data.state.changeInput
if(changeInput===1){
this._setState('changeInput',0)
}else{
this._setState('changeInput',1)
}
},
// 修改状态的方法
_setState:function(name,total){
let section = "state."+name
let param = {}
param[section] = total
this.setData(param)
},
// 弹出工具箱
bindleChangeToolBox:function(){
const toolBox = this.data.state.toolBox
if(toolBox===1){
this._setState('toolBox',0)
this._changeChatHeight()
}else{
this._focusNone = false
this._changeChatMinHeight()
this._setState('toolBox',1)
}
},
// 关闭工具箱
bindleCloseToolBox:function(){
this._setState('toolBox',0)
this._changeChatHeight()
},
// 自动下滑到底部
_scrollMoveDown:function(){
this.setData({
scroll:100000
})
},
})
|
//加验证的callback 丑陋
/*
function fetchX(fn){
setTimeout(()=>fn(10),2000);
}
function fetchY(fn){
setTimeout(()=>fn(20),1000);
}
function add(getX,getY,cb){
var x,y;
getX(function(xVal){
x = xVal;
if(y != undefined){
cb(x + y);
}
});
getY(function(yVal){
y =yVal;
if(x != undefined){
cb(x + y);
}
})
};
add(fetchX,fetchY,function(sum){
console.log(sum);
});
*/
//promise
/*
const fetchX = ()=>new Promise((resolve,reject)=>setTimeout(()=>resolve(10)),2000);
const fetchY = ()=>new Promise((resolve,reject)=>setTimeout(()=>resolve(20)),1000);
const add = (xPromise,yPromise)=>{
return Promise.all([xPromise,yPromise])
.then(values=>values[0]+values[1],err=>console.log(err));
};
add(fetchX(),fetchY()).then(sum=>console.log(sum));
*/
//---------------------------------------------------//
//使用回调的话,通知就是任务调用的回调
//foo完成后,通知它的回调(推)
foo(x){
//sometime
return listener;
}
var evt = foo(42);
evt.on('completion',function(){
//next
});
evt.on('error',function(){
});
//使用Promise的话,侦听来自foo(...)的事件,然后在得到通知的时候,根据情况继续(拉)
var evt = foo(42);
//让 bar 和 baz侦听foo的完成
bar(evt);
vaz(evt);
//其实evt就是promise的一个模拟
function foo(x){
//...
return new Promise(function(resolve,reject){
//最终调用resolve或者reject
})
}
var p = foo(42);
bar(p);
baz(p);
//p.then(bar,oopsBar);
//p.then(baz,oopsBaz);
|
import Logo from './banners/sorrento_by_the_sea_logo.jpg'
import './App.css';
import {Switch,Route} from 'react-router-dom'
import {Home} from './components/Home'
import {Apartments} from './components/Apartments'
import {Pricing} from './components/Pricing'
import {Bookings} from './components/Bookings'
import {LocalArea} from './components/LocalArea'
import {Contact} from './components/Contact'
import {NotFound} from './components/NotFound'
import Social1 from './banners/facebook_small.png'
import Social2 from './banners/instagram_small.png'
import Social3 from './banners/twitter_small.png'
import Social4 from './banners/youtube-variation_small.png'
import {Header} from './components/Header'
const NavItems = [
{"name" : "Home" , "link" : "/"},
{"name" : "Apartments" , "link" : "/Apartments"},
{"name" : "Pricing" , "link" : "/pricing"},
{"name" : "Bookings" , "link" : "/book"},
{"name" : "Local Area" , "link" : "/LocalArea"},
{"name" : "Contact" , "link" : "/contact"}
]
function App() {
return (
<div className="website">
<Header logo={Logo} nav = {NavItems}/>
<header className="header"></header>
<main className="content"></main>
<Switch>
<Route exact path= "/">
<Home />
</Route>
<Route path= "/Apartments">
<Apartments />
</Route>
<Route path= "/pricing">
<Pricing />
</Route>
<Route path= "/book">
<Bookings />
</Route>
<Route path= "/LocalArea">
<LocalArea />
</Route>
<Route path= "/contact">
<Contact />
</Route>
<Route path="/*">
<NotFound />
</Route>
</Switch>
<footer className="footer"> <p class="copyright"> © Sorrento 2021</p>
<nav class="social-nav">
<a href="www.facebook.com/sorrentovictoria">
<img src= { Social1 } width="30" height="30"
alt="Sorrento Apartments on Facebook" /></a>
<a href="www.instagram.com/sorrentovictoria">
<img src= { Social2 } width="30" height="30"
alt="Sorrento Apartments on Instagram" /></a>
<a href="www.twitter.com/sorrentovictoria">
<img src= { Social3 } width="30" height="30"
alt="Sorrento Apartments on Youtube" /></a>
<a href="www.youtube.com/sorrentovictoria">
<img src= { Social4 } width="30" height="30"
alt="Sorrento Apartments on Youtube" /></a>
</nav>
</footer>
</div>
)
}
export default App;
|
'use strict';
var _ = require('lodash');
var validate = require('../../app/dividend-calculator/validator');
describe('Dividend validator', () => {
it('should validate that race result is mandatory', (done) => {
validate((err) => {
expect(err.message).to.equal('RaceResult is mandatory');
done();
});
});
});
|
function stringToHslColor(str, saturation = 50, lightness = 75) {
let hash = 0;
for (let i = 0; i < str.length; i += 1) {
const x = hash << 5; // eslint-disable-line no-bitwise
hash = str.charCodeAt(i) + (x - hash);
}
const h = hash % 360;
return `hsl(${h}, ${saturation}%, ${lightness}%)`;
}
export default stringToHslColor;
|
import { SET_MONITORINFO} from '../constants/ActionTypes'
const initState= {
monitorId : ''
}
export default function monitorInfo(state = initState, action) {
switch (action.type) {
case SET_MONITORINFO:
return {
monitorId: action.data
}
default:
return state
}
}
|
import React from "react";
import styled from "styled-components";
import { ModalHeader, ModalBody, Form } from "reactstrap";
import { Modal, FormGroup, FormBox } from "../common";
import { isEmpty } from "validator";
import Rating from '@material-ui/lab/Rating';
import { useSelector } from "react-redux";
const StyledModal = styled(Modal)`
.rating-block {
display: flex;
align-item: center;
margin: 10px 44px;
}
.form-box {
max-width: 450px !important;
margin: auto !important;
}
&& {
max-width: 580px;
width: 100%;
margin: 0 auto;
padding: 15px;
.modal-header {
background: rgba(20, 30, 98, 0.03);
position: relative;
border-bottom: 2px solid rgba(3, 9, 48, 0.15);
height: 185px;
.modal-title {
display: flex;
padding: 20px 15px;
}
&__text {
position: absolute;
text-align: center;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
p {
font-size: 21px;
color: #08135a;
font-weight: 400;
margin-bottom: 0;
}
}
.close {
opacity: 1;
span {
color: #6254e8;
font-size: 45px;
font-weight: 400;
}
}
}
.modal-body {
text-align: center;
padding: 30px 15px;
form {
h3 {
color: #6254e8;
font-size: 16px;
max-width: 400px;
margin: 0 auto;
line-height: 30px;
margin-bottom: 24px;
}
.textarea {
border-radius: 4px;
font-size: 14px;
height: 150px;
max-width: 430px;
margin: 0 auto;
color: #08135a
resize: none;
&:placeholder {
color: #6b7cb7;
}
}
button {
background: #fd7e14;
border-radius: 40px;
height: 40px;
max-width: 160px;
width: 50%;
border: none;
font-size: 12px;
transition: 0.3s ease;
color: #fff;
margin-top: 10px;
&:hover {
transform: translateY(-3px);
box-shadow: 0 4px 8px 0 #d69777;
}
&[disabled] {
pointer-events: none;
background: #908e8e;
}
}
}
}
@media only screen and (max-width: 480px) {
.modal-header {
height: 160px;
}
.modal-body {
padding: 20px 15px;
}
.modal-header__text {
left: 56%;
p {
font-size: 18px;
}
}
}
@media only screen and (max-width: 350px) {
.modal-body form h3 {
font-size: 13px;
}
}
}
`;
const ModalComment = ({ isOpen, handleToggle, onSubmit, loading }) => {
const [error, setError] = React.useState({});
const [comment, setComment] = React.useState("");
const [rating, setRating] = React.useState(5);
const teacherStore = useSelector(store => store.parent.teachers);
const TEACHER_OPTIONS = teacherStore.data.map(item => {
return {
value: item.id,
label: `${item.first_name} ${item.last_name}`
}
})
const [selectTeacher, setSelectTeacher] = React.useState({
value: undefined,
label: "Select teacher"
})
const handleSubmitForm = (event) => {
event.preventDefault();
const errorState = validate();
if (Object.keys(errorState).length > 0) {
return setError(errorState);
}
const formData = {
comment: comment,
teacher_profile_id: selectTeacher.value,
rating,
};
if (onSubmit) {
onSubmit(formData);
}
};
const validate = () => {
const errorState = {};
// check validate
if (isEmpty(comment)) {
errorState.comment = "Please fill out this field ";
}
if (selectTeacher.value === undefined) {
errorState.teacher = "Please select a teacher";
}
return errorState;
};
const handleChange = (event) => {
setComment(event.target.value);
};
const handleFocus = (event) => {
setError({
...error,
[event.target.name]: "",
});
};
const handleSelect = (value) => {
setSelectTeacher(value)
}
const handleFocusTeacher = () => {
setError({
...error,
teacher: ""
})
}
return (
<StyledModal
isOpen={isOpen}
toggle={handleToggle}
wrapClassName="wrap-modalDashboard"
id="modal-assistance"
centered
>
<ModalHeader toggle={handleToggle}>
<div className="modal-header__text">
<p>Leave a review for your teacher</p>
</div>
</ModalHeader>
<ModalBody>
<Form onSubmit={handleSubmitForm}>
<h3>
This review will be displayed in your teacher's profile
</h3>
<FormBox
propsInput={{
name: "teacher",
onChange: handleSelect,
onFocus: handleFocusTeacher,
value: selectTeacher,
options: TEACHER_OPTIONS,
}}
variant="SingleSelectLabel"
label="Select Teacher"
error={error.teacher}
/>
<div className="rating-block">
<label>Rate your teacher from 1-5 star: </label>
<Rating
name="simple-controlled"
value={rating}
onChange={(event, newValue) => {
setRating(newValue);
}}
/>
</div>
<FormGroup
propsInput={{
type: "textarea",
name: "comment",
placeholder: "Please share your thought about your teacher",
className: "textarea",
onChange: handleChange,
onFocus: handleFocus,
value: comment,
}}
error={error.comment}
/>
<button className="fw-500" disabled={loading}>
Send
</button>
</Form>
</ModalBody>
</StyledModal>
);
};
export default ModalComment;
|
import axios from "axios";
import {
GET_SEARCH_MOVIES,
MOVIES_LOADING,
SET_DETAILS_MOVIE,
GET_MY_MOVIES,
GET_ERRORS,
CLEAR_MY_MOVIES,
ADD_MOVIE,
REMOVE_MOVIE,
CLEAR_SEARCH_RESULTS
} from "./types";
import { getCurrentProfile } from "../actions/profileActions";
// GEt My movies
export const getMyMovies = () => dispatch => {
axios
.get("api/profile/movies/all")
.then(res => {
console.log(res.data.movies);
dispatch({
type: GET_MY_MOVIES,
payload: res.data.movies
});
})
.catch(err => console.log(err));
};
// Clear My movies
export const clearMyMovies = () => {
return {
type: CLEAR_MY_MOVIES
};
};
// Search movie
export const onSearchSubmit = title => dispatch => {
axios
.get(
`https://api.themoviedb.org/3/search/movie?api_key=cbf8a5918204c1c55f4c7ce039c99036&language=en-US&query=${title}&page=1&include_adult=false`
)
.then(res => {
console.log(res);
dispatch({
type: GET_SEARCH_MOVIES,
payload: res.data.results
});
})
.catch(err => console.log(err));
};
// Set Detatil movie
export const setDetailsMovie = movie => {
return {
type: SET_DETAILS_MOVIE,
payload: movie.movie
};
};
// Add movie to collection
export const addMovieToCollection = movie => dispatch => {
console.log(movie);
axios
.post("api/profile/movies", movie)
.then(res => {
dispatch({
type: ADD_MOVIE,
payload: movie
});
dispatch(getMyMovies());
dispatch(getCurrentProfile());
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
// Remove movie from collection
export const removeMovieFromCollection = movie_id => dispatch => {
axios
.delete(`api/profile/movies/${movie_id}`)
.then(res => {
dispatch({
type: REMOVE_MOVIE,
payload: movie_id
});
dispatch(getMyMovies());
dispatch(getCurrentProfile());
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
// Profile loading
export const setMoviesLoading = () => {
return {
type: MOVIES_LOADING
};
};
// Clear search results
export const clearSearchResults = () => {
return {
type: CLEAR_SEARCH_RESULTS
};
};
|
import React from "react";
import styled, { keyframes } from "styled-components";
import { MAIN_IMG } from "../../Assets";
const MainContainer = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: transparent;
`;
const ImgContainer = styled.div`
position: fixed;
height: 100%;
width: 100%;
background-image: url(${(props) => props.url});
background-attachment: fixed;
background-size: cover;
background-repeat: no-repeat;
opacity: 0.5;
z-index: -1;
`;
const typing = (isLast) => keyframes`
0% {
border-right: 0.15em solid orange;
width: 0;
}
0.01% {
opacity: 1;
}
99.99%{
border-right: 0.15em solid orange;
}
100%{
border-right: ${isLast ? "0.15em solid orange" : 0};
width: 100%;
opacity: 1;
}
`;
const blinkcaret = keyframes`
from, to { border-color: transparent; }
50% { border-color: orange; }
`;
const TypeWriterWrapper = styled.div``;
const TypeWriter = styled.h1`
position: relative;
color: white;
font-size: 3.5vw;
font-weight: 600;
margin: 0 auto;
overflow: hidden; /* Ensures the content is not revealed until the animation */
white-space: pre; /* Keeps the content on a single line */
letter-spacing: 0.3vw;
animation: ${typing(false)} 3s steps(30, end) forwards,
${blinkcaret} 0.75s step-end infinite;
@media only screen and (min-width: 1600px) {
font-size: 56px;
letter-spacing: 4.8px;
}
`;
const TypeWriter2 = styled(TypeWriter)`
margin-top: 2vw;
opacity: 0;
animation: ${typing(true)} 1.5s steps(15, end) forwards,
${blinkcaret} 0.75s step-end infinite;
animation-delay: 3.1s;
`;
export default () => {
return (
<>
<ImgContainer url={MAIN_IMG} />
<MainContainer>
<TypeWriterWrapper>
<TypeWriter>안녕하세요. 언제나 발전하기 위해 노력하는</TypeWriter>
</TypeWriterWrapper>
<TypeWriterWrapper>
<TypeWriter2>개발자 이혁원입니다.</TypeWriter2>
</TypeWriterWrapper>
</MainContainer>
</>
);
};
|
var ColoringSimulation = require("./ColoringSimulation");
var networks = require("./networks.json");
var _ = require("underscore");
var toCSV = require("array-to-csv");
var fs = require("fs");
// var networksIdx = _.range(networks.length);
var networksIdx = [0, 4, 5, 7, 8, 9, 10, 11, 12];
// var networksIdx = [7];
var fullResults = [];
for (var n in networksIdx) {
var i = networksIdx[n];
var simulation = new ColoringSimulation({
networkName: i
});
// simulation.simultaneous = 1/10;
simulation.printLittle = true;
// simulation.printSome = true;
// simulation.printMore = true;
simulation.runs = 10000;
simulation.strict = true;
simulation.movesAllowed = 20000;
simulation.machineType = "mwu";
simulation.network = networks[i];
simulation.run();
fullResults.push(simulation.equilibriumResults);
fs.writeFileSync("results/equilibriumResults-mwu.csv", toCSV(fullResults));
console.log("finished one!!", i);
console.log(fullResults);
// simulation.saveFile();
}
|
import React from "react";
import { CommentBox } from "../components/Comment";
export const CommentViews = () => {
return (
<React.Fragment>
<CommentBox />
</React.Fragment>
);
};
|
import React, { useState } from 'react';
import DataTable, { createTheme } from 'react-data-table-component';
import Button from '../shared/Button';
import {convertArrayOfObjectsToCSV} from './helpers';
import {headerColumns} from './constants';
createTheme('solarized', {
text: {
primary: '#268bd2',
secondary: '#2aa198',
},
background: {
default: '#002b36',
},
context: {
background: '#cb4b16',
text: '#FFFFFF',
},
divider: {
default: '#073642',
},
action: {
button: 'rgba(0,0,0,.54)',
hover: 'rgba(0,0,0,.08)',
disabled: 'rgba(0,0,0,.12)',
},
});
// Blatant "inspiration" from https://codepen.io/Jacqueline34/pen/pyVoWr
const downloadCSV = (array) => {
const link = document.createElement('a');
let csv = convertArrayOfObjectsToCSV(array);
if (csv == null) return;
const filename = 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = `data:text/csv;charset=utf-8,${csv}`;
}
const downloadData = encodeURI(csv);
link.setAttribute('href', downloadData);
link.setAttribute('download', filename);
link.click();
}
const Export = ({ onExport }) => (
<Button onClick={e => onExport(e.target.value)}>Export</Button>
);
const MoneyTable = ({ data }) => {
const actionsMemo = React.useMemo(() => <Export onExport={() => downloadCSV(data)} />, []);
return (<DataTable
title="Ass hole this your spending "
columns={headerColumns}
data={data}
selectableRows // add for checkbox selection
theme="solarized"
actions={actionsMemo}
/>);
};
export default MoneyTable;
|
import './src';
// import React, { Component } from 'react';
// import {AppRegistry} from 'react-native';
// import App from './react_native_element/Presentation/App.js';
// const YoutubePlayer = () => <App />;
// AppRegistry.registerComponent('YoutubePlayer', () => YoutubePlayer);
|
module.exports = function apiServer (getApi) {
apiCall.getApi = getApi;
apiCall.delimiter = '/';
return apiCall;
function apiCall (path, args) {
return new Promise(function (win, fail) {
try {
var api = apiCall.getApi();
} catch (e) {
fail("api: error getting api: " + e.message)
}
try {
var split = (isFunction(apiCall.delimiter)
? apiCall.delimiter(path)
: path.split(apiCall.delimiter))
} catch (e) {
fail("api: error parsing path " + path + ": " + e.message)
}
resolve(api, split);
function resolve (branch, steps) {
if (steps.length < 1) {
fail("api: no path specified")
return;
}
if (steps.length > 1) {
descend(branch, steps)
return;
}
var method = branch[steps[0]];
if (method === undefined) {
fail("api: " + path + " not found")
}
if (!isFunction(method)) {
fail("api: " + path + " not a function but " + typeof method)
}
win(method.apply(branch, args));
}
function descend (branch, steps) {
if (!exists(branch, steps[0])) {
fail("api: " + path + " is not in the api" +
" (starting from '" + steps[0] + "')")
return;
}
var next = branch[steps[0]];
if (!isFunction(next)) {
resolve(next, steps.slice(1))
} else {
next = next();
if (!isPromise(next)) {
resolve(next, steps.slice(1))
} else {
next.then(function (val) {
resolve(val, steps.slice(1))
})
}
}
}
})
}
}
function exists (branch, name) {
return Object.keys(branch).indexOf(name) > -1
}
function isFunction (x) {
return typeof x === "function"
}
function isObject(x) {
return x === Object(x)
}
function isPromise(x) {
return isObject(x) && isFunction(x.then)
}
|
$(function () {
var myChart1 = echarts.init(document.getElementById('chartOne'));
var myChart2 = echarts.init(document.getElementById('chartTwo'));
var option1 = {
title: {
text: '安全天数',
left: "center"
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataZoom: {
yAxisIndex: 'none'
},
dataView: {
readOnly: false
},
magicType: {
type: ['line', 'bar']
},
restore: {},
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
name: "月份"
},
yAxis: {
type: 'value',
name: "天"
},
series: [{
name: '安全天数/月',
type: 'line',
data: [30, 28, 30, 30, 31, 30, 31, 30, 30, 31, 30, 31],
markPoint: {
data: [{
type: 'max',
name: '最大值'
},
{
type: 'min',
name: '最小值'
}
]
},
markLine: {
data: [{
type: 'average',
name: '平均值'
}]
}
}]
};
var option2 = {
title: {
text: '最近一周混凝土运输量',
left: "centers"
},
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [{
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
axisTick: {
alignWithLabel: true
}
}],
yAxis: [{
name:"吨"
}],
series: [{
name: '运输量/吨',
type: 'bar',
barWidth: '60%',
data: [86, 75,94, 78, 82, 79, 92]
}]
};
myChart1.setOption(option1);
myChart2.setOption(option2);
});
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Link, Route, Switch } from 'react-router-dom'
import Home from './pages/home/Home';
import Exercise from './pages/exercise/Exercise';
import Workout from './pages/workout/Workout';
import History from './pages/history/History';
import NotFound from './pages/notfound/NotFound';
class App extends Component {
render() {
return (
<div className="App">
<div className="container-fluid">
<nav className="navbar navbar-inverse">
<div className="container-fluid">
<div className="navbar-header">
<div className="navbar-brand">
<Link to="/">Django Fitness</Link>
</div>
</div>
<ul className="nav navbar-nav">
<li><Link to="/exercise">Exercise</Link></li>
<li><Link to="/workout">Workouts</Link></li>
<li><Link to="/history">History</Link></li>
</ul>
</div>
</nav>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/exercise" component={Exercise}/>
<Route path="/workout" component={Workout}/>
<Route path="/history" component={History}/>
<Route path="*" component={NotFound}/>
</Switch>
</div>
</div>
);
}
}
export default App;
|
window.sessionStorage.setItem( "qunit-test-Reorder-Second", 1 );
window.sessionStorage.setItem( "qunit-test-Reorder-Third", 1 );
var lastTest = "";
QUnit.module( "Reorder" );
QUnit.test( "First", function( assert ) {
assert.strictEqual( lastTest, "Third" );
lastTest = "First";
} );
QUnit.test( "Second", function( assert ) {
assert.strictEqual( lastTest, "" );
lastTest = "Second";
// For some reason PhantomJS mutates config.reorder
QUnit.config.reorder = true;
// This test is "high priority" so it should execute before test "First"
// even though it is added to the queue late
// eslint-disable-next-line qunit/no-nested-tests
QUnit.test( "Third", function( assert ) {
assert.strictEqual( lastTest, "Second" );
lastTest = "Third";
} );
} );
|
////////////////////////////////////////////////////////////////////////////////
//the 3 functions below are needed to use Erichs generic framework for dynamic
//programing problems.
////////////////////////////////////////////////////////////////////////////////
//function to compute the value of a specific nCk call.
//comatible with Erichs fill table function
var computeCell = function(data, n, k)
{
var table = [];
var row = [];
//i is number of items
for(var i = 0; i <= n; i++)
{
row = [];
//j is num items to pick
for(var j = 0; j <= i; j++)
{
if(i == j || j == 0)
row[j] = 1;
else
row[j] = table[i-1][j-1] + table[i-1][j];
}
table[i] = row;
}
// for(var i = 0; i < table.length; i++)
// {
// var str;
// str = "";
// for(var j = 0; j < table[i].length; j++)
// {
// str = str + table[i][j] + ", ";
// }
// console.log(str);
// }
return table[n][k];
}
//builds a list of cells to highlight as dependancies for Erichs
//fill table function
var computeHighlight = function(data, n, k)
{
if(n == k || k == 0)
return [[n, k]];
return([[n-1,k],[n-1,k-1]]);
}
//returns true if the parameters are a base case.
//built for erichs fill table function
var isBase = function(data, n, k)
{
return (n == k || k == 0);
}
////////////////////////////////////////////////////////////////////////////////
//The two functions below create a Jsav call tree for Erichs fill table function
////////////////////////////////////////////////////////////////////////////////
//build a jsav tree for a nCk call
var buildTree = function(tree, n, k, animate)
{
tree.root("" + (n) + "," + k);
if(animate != false)
{
tree.layout();
jsav.step();
}
buildNode(tree.root(), n, k, animate);
return;
}
//recursive helper for buildTree
var buildNode = function(node, n, k, animate)
{
if(n == k || k == 0)
{
return;
}
else
{
node.addChild("" + (n-1) + "," + (k-1));
node.addChild("" + (n-1) + "," + (k));
buildNode(node.child(0), n-1, k-1);
buildNode(node.child(1), n-1, k);
}
return;
}
//////////////////////////////////////////////////////////////////////
//below is the code to setup jsav and get the animation off the ground
//////////////////////////////////////////////////////////////////////
var jsav = new JSAV("av");
var callTree = jsav.ds.tree({visible: false, centered:false});
var dynTable = [];
//set up the dynamic table with the base cases and blank other spaces
dynTable[0] = jsav.ds.array([1, "", "", "", ""],{centered:false, left:"500px", top:0});
dynTable[1] = jsav.ds.array([1, 1, "", "", ""],{centered:false, left:"500px", top:40});
dynTable[2] = jsav.ds.array([1, "", 1, "", ""],{centered:false, left:"500px", top:80});
dynTable[3] = jsav.ds.array([1, "", "", 1, ""],{centered:false, left:"500px", top:120});
dynTable[4] = jsav.ds.array([1, "", "", "", 1],{centered:false, left:"500px", top:160})
//labels for the arrays
jsav.label("N", {left:(parseInt(dynTable[0].css("left")) - 40), top:(parseInt(dynTable[0].css("top")) + 10)});
jsav.label("K", {top:(parseInt(dynTable[0].css("top")) - 40), left:(parseInt(dynTable[0].css("left")) + 17 )});
//N labels
for(var i = 0; i <= 4; i++)
{
jsav.label(i, {top:(parseInt(dynTable[0].css("top")) + 42 * i + 10), left:(parseInt(dynTable[0].css("left")) - 20)});
}
//K labels
for(var i = 0; i <= 4; i++)
{
jsav.label(i, {top:(parseInt(dynTable[0].css("top")) - 20), left:(parseInt(dynTable[0].css("left")) + 17 + 41*i)});
}
//build the tree
buildTree(callTree, 4, 2, false);
callTree.layout();
callTree.css({top:"-50px", left:"0px"});
callTree.show();
//build an animation using Erichs framework.
fillTable(jsav, callTree, callTree.root(), dynTable, {}, isBase, computeHighlight, computeCell, 0);
jsav.recorded();
|
/*
ES6会强制开启严格模式 use strict
let 为块级作用域
let 变量不能重复定义
暂存性死区(通常用来描述let和const的不提升效果)
let 声明的变量一定要在声明后使用,否则报错 */
/* function test() {
for (let i = 1; i < 3; i++) { //let 为块级作用域
console.log(i);
}
console.log(i); //Uncaught ReferenceError: i is not defined
let a = 1
let a = 5 //let 变量不能重复定义
// var 的情况 //let不会提升
console.log(foo); // 输出undefined
var foo = 2;
let a = 2
// let a = 3
// // let 的情况
console.log(bar); // 报错ReferenceError
let bar = 2;
if (true) {
// TDZ开始 (暂时性死区)
tmp = 'abc'; // ReferenceError
console.log(tmp); // ReferenceError
let tmp; // TDZ结束
console.log(tmp); // undefined
tmp = 123;
console.log(tmp); // 123
}
}
test() */
/* const 为常量,不能再次赋值,且初次定义就必须赋值
注意:const声明不允许修改绑定,但是允许修改值
*/
/* function test1() {
const PI = 456
PI = 45 // 报错
console.log(PI);
}
test1()
const a = {name:"科比"}
a.name = "詹姆斯"
console.log(a); // 詹姆斯
*/
/* var condition = true
if(condition){
console.log('fuck');
console.log(typeof value) // 引用错误 ReferenceError: value is not defined
let value = "blue"
} */
/* var Array = "hello"
console.log(window.Array)
var nice = 'hehe'
console.log(window.nice) */
/*************解构赋值*******************/
//数组
{
console.log('数组解构');
let a, b, res
[a, b] = [1, 5]
console.log(a, b); // 1 5
}
{
let a, b, rest;
[a, b, ...rest] = [1, 2, 3, 4, 5, 6];
console.log(a, b, rest); //1 2 Array [ 3, 4, 5, 6 ]
}
//对象
{
let a, b;
({ a, b } = { a: 6, b: 2 })
console.log(a, b); // 6 2
}
//应用:
// 1.变量交换
{
let a = 8
let b = 2;
[a, b] = [b, a]
console.log(a, b); //2 8
}
{
let a = 8;
let b = 18;
({ a, b } = { a: b, b: a })
console.log(a, b); //18 8
}
// 2.接收函数返回值
{
function f() {
return [1, 2];
}
let a, b;
[a, b] = f();
console.log(a, b); // 1 2
}
// 3.返回多个值时,可以选择性接收自己想要的某几个变量
{
function f() {
return [1, 2, 3, 4, 5];
}
let a, b, c;
[a, , , b] = f();
console.log(a, b); //1 4
}
// 4.不知道函数返回数组的长度,只想取出前几个元素,其余用数组表示
{
function f() {
return [1, 2, 3, 4, 5];
}
let a, b, c;
[a, ...b] = f();
console.log(a, b); //1 [2,3,4,5]
}
// 对象解构赋值
{
let a = { p: 3, q: true };
let { p, q } = a;
console.log(p, q); // 3 true
}
{
let { a = 10, b = 5 } = { a: 3 };
console.log(a, b); //3 5
}
{
let metaData = {
title: 'abc',
test: [{
title: 'test',
desc: 'description'
}]
}
let { title: esTitle, test: [{ title: cnTitle }] } = metaData;
console.log(esTitle, cnTitle); //'abc' test
}
//实际上,对象的解构赋值是下面形式的简写
{ let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" }; }
/* 也就是说,对象的解构赋值的内部机制,是先找到同名属性,
然后再赋给对应的变量。真正被赋值的是后者,而不是前者。 */
/* {
let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined
//foo是匹配的模式,baz才是变量。
//真正被赋值的是变量baz,而不是模式foo。
} */
|
import React, { useState } from 'react';
import './style.css';
import Rotas from '../Rotas/'
import {Link} from 'react-router-dom';
export default function NumeroAleatorio() {
const [numeroaleatorio, setNumero] = useState(0);
function gerar(){
const novo = Math.floor(Math.random() * (100 - 1) + 1);
setNumero(novo);
}
return(
<div className="card-numeroaleatorio">
<div>
<p>
<h3>Número aleatório:</h3>
<h1>{numeroaleatorio}</h1>
</p>
<p>
Click no botão para gerar um numero aleatório
</p>
<button onClick={gerar}>
Gerar número
</button>
</div>
<div>
<button><Link to="/front-end">Front-end</Link></button>
<button> <Link to="/back-end">Back-end</Link></button>
</div>
</div>
);
}
|
import { useState } from 'react';
import { validate } from '../helpers';
import { useToasts } from 'react-toast-notifications';
export default function Input({
inputs,
submitButton,
cb,
validateForm = true,
}) {
const [validateSelf, setValidateSelf] = useState(false);
const [inputTypes, setInputTypes] = useState(inputs);
const { addToast } = useToasts();
const handleSubmit = async (e) => {
e.preventDefault();
let keys = Object.keys(inputTypes);
const values = Object.values(inputTypes);
const shouldSubmit = keys.some((key, i) => {
return !validate(values[i], keys[i]);
});
if (shouldSubmit && validateForm) {
addToast('Please ensure the form is completely and correctly filled', {
appearance: 'warning',
autoDismiss: true,
});
setValidateSelf(true);
return;
}
submitButton.current.classList.add('spinner1');
let response;
try {
response = await cb(inputTypes);
} catch (error) {
addToast(error.message, {
appearance: 'error',
autoDismiss: true,
});
submitButton.current.classList.remove('spinner1');
return;
}
return { msg: 'success', response };
};
const handleChange = (event, error) => {
const { name, value, type, checked } = event.target;
setInputTypes({
...inputTypes,
[name]: type === 'checkbox' ? (checked ? checked : false) : value,
});
};
return [handleSubmit, handleChange, inputTypes, validateSelf];
}
|
const db = require('../data/dbConfig.js');
const { genericModel: {
genFindAll,
genFindBy,
genAdd,
genFindById,
genUpdate,
genRemove
} } = require("../globalServices")
const dbname = 'articles';
module.exports = {
add,
findBy,
findById,
remove,
update
};
async function findBy(filter) {
return await genFindBy(filter, dbname)
}
async function add(user, genDF) {
return await genAdd(user, dbname, genDF);
}
async function findById(id) {
return await genFindById(id, dbname)
}
async function update(info) {
return await genUpdate({...info, dbname})
}
async function remove(board_id) {
return await genRemove(board_id,dbname);
}
|
import React from 'react';
import './Footer.css';
import { Link } from 'react-router-dom';
const Footer = () => {
return (
<div className="footer">
<nav className="nav">
<Link to="/">Home</Link> | <Link to="/dashboard">Dashboard</Link> | <a href = "https://quizzical-mestorf-7a04b8.netlify.com/index.html">About Us</a>
</nav>
<h5 className="copyright">Copyright Med Cabinet</h5>
</div>
)
}
export default Footer;
|
const saturdayFun = function saturdayFun(fun = "roller-skate") {
return `This Saturday, I want to ${fun}!`
}
const mondayWork = function mondayWork(todo = "go to the office") {
return `This Monday, I will ${todo}.`
}
// LAB:
// Implement a function called wrapAdjective.
// It should return a function
// This "inner" function should:
// take a single parameter that should default to "special". Name it however you wish.
// return a String of the form "You are ..." where ... should be the adjective this function received wrapped in visual flair
// It should take as parameter a String that will be used to create visual flair
// You may call the parameter whatever you like, but its default value should be "*"
// Call example: let encouragingPromptFunction = wrapAdjective("!!!")
// Thus a total call should be: wrapAdjective("%")("a dedicated programmer") //=> "You are %a dedicated programmer%!"
// describe("defines wrapAdjective function according to the specification", function() {
// it("function exists", function() {
// expect(wrapAdjective).to.exist
// })
//I don't understand below specs. '*' and '||'
// it("when initialized with '*' creates a function that, when called, wraps an adjective in a highlight", function() {
// let result = wrapAdjective()
// let emphatic = result("a hard worker")
// expect(emphatic).to.equal("You are *a hard worker*!")
// });
// it("when initialized with '||' creates a function that, when called, wraps an adjective in a highlight", function() {
// let result = wrapAdjective("||")
// let emphatic = result("a dedicated programmer")
// expect(emphatic).to.equal("You are ||a dedicated programmer||!")
// });
const wrapAdjective = function wrapAdjective() {
return function inner(adjective = "special") {
if (adjective = "*") {
return `You are *${adjective}*!` };
if (adjective = "||") {
return `You are ||${adjective}||!`};
return inner
}
}
const Calculator = function(number, number1)
{add(number + number1),
subtract(number - number1),
multiply(number * number1),
devide (number / number1)}
// const actionApplyer =
// function actionApplyer(integer, arrayOfTransforms[]) {
// let integer = number
// let arrayOfTransforms = [
// function(integer){ return integer * 2 },
// function(integer){ return integer + 1000},
// function(integer){ return integer % 7 }];
// if (arrayOfTransforms.length === 0)
// return (0)
// }
// return number
// }
|
import React from 'react';
import { PolarisTestProvider } from '@shopify/polaris';
import en from '@shopify/polaris/locales/en.json';
import { createMount } from '@shopify/react-testing';
import fetch from 'unfetch';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { AppProvider } from '@shopify/polaris';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const link = createHttpLink({
uri: 'https://rails-tutorial.myshopify.io/graphql',
fetch: fetch
})
const client = new ApolloClient({
link: link,
cache: new InMemoryCache()
})
export const mountWithApolloProvider = createMount({
context(options) {
return options;
},
render(element, context) {
return (
<ApolloProvider client={client}>
<PolarisTestProvider i18n={en} {...context}>
{element}
</PolarisTestProvider>
</ApolloProvider>
);
},
});
|
const jwt = require('jsonwebtoken');
const fs = require('fs');
const Employer = require("../models/employers.model");
const crypto = require("../libs/data-encryption");
let secretKeys = require("../config/secret.key");
function updateEmployer(conditions, employer, options, res) {
Employer.updateOne(conditions, employer, options, (err, result) => {
console.log(result.n);
if (err || !result.n) {
return res.status(500).send({
error: "Server Error."
});
}
res.status(200).send({
"success": "Updated successfully."
});
});
}
module.exports = {
register: async (req, res, next) => {
if (Object.keys(req.body).length > 5) {
res.status(400).send({
error: "Invalid data format."
});
}
let password = req.body.password || "";
req.checkBody("username", "Username is required.").notEmpty();
req.checkBody("username", "Username must be at 4 characters long.").isLength({
min: 4
});
req.checkBody("name", "Name is required.").notEmpty();
req.checkBody("name", "Name must be at 4 characters long.").isLength({
min: 4
});
req.checkBody("email", "Email is required.").notEmpty();
req.checkBody("email", "Enter valid email.").isEmail();
req.checkBody("password", "Password is required.").notEmpty();
req.checkBody("password", "Password must be 6 character long.").isLength({
min: 6
});
req.checkBody("confirmPassword", "Please retype password.").notEmpty();
req
.checkBody("confirmPassword", "Please confirm password.")
.equals(password);
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let employer = await Employer.findOne({
username: req.body.username
}, "username");
if (employer) {
return res.status(400).send({
error: "Username is already used."
});
}
let email = crypto.encrypt(
req.body.email.toLowerCase(),
secretKeys.employerEmailKey,
secretKeys.employerEmailIV
);
employer = await Employer.findOne({
email: email
}, "email");
if (employer) {
return res.status(400).send({
error: "Email is used."
});
}
let newEmployer = new Employer({
username: req.body.username,
name: req.body.name,
email: email,
password: crypto.encrypt(password, secretKeys.employerPasswordKey)
});
newEmployer.save(newEmployer, (err, employer) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
}
res.status(201).send({
success: "Registration successful."
});
});
},
login: async (req, res, next) => {
if (Object.keys(req.body).length !== 2) {
return res.status(401).send({
error: ['Invalid Data Format']
});
}
req.checkBody('email', 'Not a valid email.').isEmail();
req.checkBody('password', 'Password can not be empty.').notEmpty();
if (req.validationErrors()) {
return res.status(401).send({
error: req.validationErrors()
});
}
let email = crypto.encrypt(req.body.email.toLowerCase(), secretKeys.employerEmailKey, secretKeys.employerEmailIV);
let employer = await Employer.findOne({
email: email
}, "name email password");
if (!employer || req.body.password != crypto.decrypt(employer.password, secretKeys.employerPasswordKey)) {
return res.status(401).send({
error: ['Incorrect email or password.']
});
}
jwt.sign({
id: employer._id,
name: employer.name
}, secretKeys.jwt, {
algorithm: 'HS256',
expiresIn: '30d'
}, (err, token) => {
if (err) {
res.status(500).send({
error: 'Server Error.'
});
} else {
res.status(200).json({
success: "Login Successful.",
token: token
});
}
});
},
logout: (req, res, next) => {
res.status(200).send({
success: 'You are successfully logged out.'
});
},
getAllEmployer: (req, res, next) => {
Employer.find({}, (err, result) => {
if (err) {
res.status(500).send({
error: "Server Error"
});
} else {
res.status(200).send(result);
}
});
},
getProfile: async (req, res, next) => {
Employer.findById(res.locals.id, {
username: 0,
password: 0
}, (err, employer) => {
if (err || !employer) {
return res.status(500).send({
error: "Server Error."
});
}
employer.email = crypto.decrypt(employer.email, secretKeys.employerEmailKey);
employer.imagePath = employer.imagePath ? req.protocol + "://" + "localhost:3000" + '/' + employer.imagePath : "";
res.status(200).send(employer);
});
},
getProfileByUserName: async (req, res, next) => {
Employer.findOne({
username: req.params.username
}, 'name email imagePath rating jobs', (err, employer) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
}
if (!employer) {
return res.status(404).send({
error: "No employer found."
});
}
employer.email = crypto.decrypt(employer.email, secretKeys.employerEmailKey);
res.status(200).send(employer);
});
},
updateProfile: async (req, res, next) => {
if (Object.keys(req.body).length > 3) {
return res.status(400).send({
error: "Invalid Format."
});
}
req.checkBody("name", "Name must be at 4 characters long.").notEmpty().isLength({
min: 4
});
req.checkBody("email", "Enter valid email.").notEmpty().isEmail();
req.checkBody('phone', 'Phone is required.').notEmpty();
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let employer = await Employer.findOne({
_id: res.locals.id
}, {
password: 0
});
let email = crypto.encrypt(req.body.email, secretKeys.employerEmailKey, secretKeys.employerEmailIV);
if (email != employer.email) {
let checkEmail = await Employer.findOne({
email: email
});
if (checkEmail) {
res.status(422).send({
error: "Email is already used."
});
}
}
if (req.body.phone != employer.phone) {
let checkPhone = await Employer.findOne({
phone: req.body.phone
});
if (checkPhone) {
res.status(422).send({
error: "Phone is already used."
});
}
}
newEmployer = {
name: req.body.name,
phone: req.body.phone,
email: crypto.encrypt(req.body.email.toLowerCase(), secretKeys.employerEmailKey, secretKeys.employerEmailIV)
}
updateEmployer({
_id: res.locals.id
}, newEmployer, {
new: true
}, res);
},
updateProfileImage: async (req, res, next) => {
if (!req.file) {
return res.status(400).send({
error: "No file is selected."
});
}
let employer = await Employer.findOne({
_id: res.locals.id
}, 'imagePath');
if (employer.imagePath) {
fs.unlinkSync(employer.imagePath);
}
let imagePath = 'public/uploads/' + req.file.filename || employer.imagePath;
updateEmployer({
_id: res.locals.id
}, {
imagePath: imagePath
}, {
new: true
}, res);
},
updatePassword: async (req, res, next) => {
let employer = await Employer.findOne({
_id: res.locals.id
}, 'password');
req.checkBody("newPassword", "Password must be 6 character long.").notEmpty().isLength({
min: 6
});
let password = req.body.newPassword;
req
.checkBody("confirmPassword", "Please confirm password.").notEmpty()
.equals(password);
let errors = req.validationErrors();
if (errors) {
return res.status(422).send(errors);
}
let oldPassword = crypto.decrypt(employer.password, secretKeys.employerPasswordKey);
if (req.body.oldPassword != oldPassword) {
return res.status(400).send({
error: "Incorrect Password"
});
}
updateEmployer({
_id: res.locals.id
}, {
password: crypto.encrypt(req.body.newPassword, secretKeys.employerPasswordKey)
}, {
new: true
}, res);
},
updateCompany: async (req, res, next) => {
if (Object.keys(req.body).length > 7) {
return res.status(422).send({
error: "Invalid data format."
});
}
let employer = await Employer.findOne({
_id: res.locals.id
}, 'company');
let company = {
companyName: req.body.companyName || employer.company.companyName || "",
location: req.body.location || employer.company.location || "",
companyType: req.body.companyType || employer.company.companyType || "",
industryType: req.body.industryType || employer.company.industryType || "",
maxEmployee: req.body.maxEmployee || employer.company.maxEmployee || 0,
minEmployee: req.body.minEmployee || employer.company.minEmployee || 0,
website: req.body.website || employer.company.website || "",
}
updateEmployer({
_id: res.locals.id
}, {
company: company
}, {
new: true
}, res);
},
deleteAccount: (req, res, next) => {
Employer.deleteOne({
_id: res.locals.id
}, (err) => {
if (err) {
return res.status(500).send({
error: "Server Error."
});
} else {
res.status(200).send({
success: "Account deleted."
});
}
})
}
};
|
if (typeof HMS == 'undefined' || !HMS) {
var HMS = {};
}
HMS.namespace = function () {
var a = arguments,
o = null,
i, j, d;
for (i = 0; i < a.length; i = i + 1) {
d = ('' + a[i]).split('.');
o = HMS;
for (j = (d[0] == 'HMS') ? 1 : 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
}
return o;
}
HMS.namespace('ReceiptEdit');
HMS.ReceiptEdit = function () {
var Global = {
UrlAction: {
Delete: '/Receipt/Delete',
Gets: '/Receipt/Gets',
Save: '/Receipt/Save',
Find: '/Khachhang/Get',
},
Data: {
Id: 0,
table: null,
selectedObj: { Id: 0 },
trans: [],
ReceiptXe: [],
_DKId: 0,
_SXId: 0,
_TNId: 0,
_TNganId: 0,
_KTCuoiId: 0,
_works: [],
_dichvus: [],
_phutungs: [],
_dsPhuTungs: []
}
}
this.GetGlobal = function () {
return Global;
}
this.Delete = function (Id) {
swal({
title: "Bạn có chắc muốn xóa?",
text: "Chú ý tất cả dữ liệu liên quan đến khách hàng này cũng sẽ bị mất theo.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Xóa",
closeOnConfirm: true
}, function () {
Delete(Id);
});
}
this.Init = function () {
RegisterEvent();
if (Global.Data._works.length > 0) {
$.each(Global.Data._works, (i, item) => {
$('#works').append('<option value="' + item.Code + '"></option>')
$('#works-name').append('<option value="' + item.Name + '"></option>')
});
}
if (Global.Data._phutungs.length > 0) {
$.each(Global.Data._phutungs, (i, item) => {
$('#phutungs').append('<option value="' + item.Code + '"></option>')
$('#phutungs-name').append('<option value="' + item.Name + '"></option>')
});
}
if (Global.Data._dichvus.length == 0)
AddNew();
if (Global.Data._dsPhuTungs.length == 0)
AddNewPT();
TinhTong();
var $demoMaskedInput = $('.masked-input');
$demoMaskedInput.find('.date').inputmask('dd/mm/yyyy', { placeholder: '__/__/____' });
$('#dangky').val(Global.Data._DKId);
$('#suaxe').val(Global.Data._SXId);
$('#tiepnhan').val(Global.Data._TNId);
$('#thungan').val(Global.Data._TNganId);
$('#ktcuoi').val(Global.Data._KTCuoiId);
RefreshControls();
//Textarea auto growth
autosize($('textarea.auto-growth'));
}
var RegisterEvent = function () {
$('#btSave').click(function () {
// $('#frmReceipt').append('<input type="hidden" name ="TaoKH" id="TaoKH" value="1" />');
if (Global.Data._dichvus.length > 0) {
var index = 0;
$.each(Global.Data._dichvus, (i, item) => {
if (item.DVId != null && item.DVId > 0) {
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].DVId" value="' + item.DVId + '" />');
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].DVCode" value="' + item.DVCode + '" />');
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].DVName" value="' + item.DVName + '" />');
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].GiaBan" value="' + item.GiaBan + '" />');
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].CKhau" value="' + item.CKhau + '" />');
$('#frmReceipt').append('<input type="hidden" name ="DichVus[' + index + '].GiaCK" value="' + item.GiaCK + '" />');
index++;
}
})
}
if (Global.Data._dsPhuTungs.length > 0) {
var index = 0;
$.each(Global.Data._dsPhuTungs, (i, item) => {
if (item.PTId != null && item.PTId > 0) {
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].PTId" value="' + item.PTId + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].PTCode" value="' + item.PTCode + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].PTName" value="' + item.PTName + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].SoLuong" value="' + item.SoLuong + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].GiaBan" value="' + item.GiaBan + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].CKhau" value="' + item.CKhau + '" />');
$('#frmReceipt').append('<input type="hidden" name ="PhuTungs[' + index + '].GiaCK" value="' + item.GiaCK + '" />');
index++;
}
})
}
$('#frmReceipt').append("<input type='hidden' name ='jsonDichVus' value='" + JSON.stringify(Global.Data._dichvus) + "' />");
$('#frmReceipt').append("<input type='hidden' name ='jsonPhuTungs' value=\'" + JSON.stringify(Global.Data._dsPhuTungs) + "' />");
$('#frmReceipt').submit();
// Save();
});
$('#btClose').click(() => { window.location.href = '/Receipt/Close?id=' + $('#Id').val(); });
$('#btAdd').click(function () {
$('#frmReceipt').append('<input type="hidden" name ="TaoKH" id="TaoKH" value="1" />');
$('#frmReceipt').submit();
});
$("#Receipt-type").on("changed.bs.select",
function (e, clickedIndex, newValue, oldValue) {
var inter = setInterval(function () {
clearInterval(inter);
RefreshControls();
}, 500);
});
$('.btn-find').click(() => { window.location.href = ('/Receipt/Create?ma=' + $('#code').val()); });
}
_tr = () => { return '<tr></tr>' }
_td = () => { return '<td></td>' }
_input = (value, list, name, index, className) => { return '<input class="' + className + '" type="text" value="' + value + '" list="' + list + '" name="' + name + '" id="dv_' + index + '" />' }
_delete = () => { return '<i class="fa fa-trash col-red fa-lg pointer" ></i>' }
DrawTable = () => {
if (Global.Data._dichvus.length > 0) {
var tb = $('.tb-dichvu tbody');
tb.empty();
$.each(Global.Data._dichvus, (i, item) => {
var tr = $(_tr());
var td = $(_td());
var code = $(_input(item.DVCode, 'works', '', ('code_' + i), 'i-code pointer'));
code.change(() => { findCode(i, $(code).val()); });
code.focus(() => { $(code).select(); })
td.append(code);
tr.append(td);
td = $(_td());
var name = $(_input(item.DVName, 'works-name', '', ('name_' + i), 'i-name pointer'));
name.change(() => { findName(i, $(name).val()); })
name.focus(() => { $(name).select(); })
td.append(name);
tr.append(td);
td = $(_td());
td.text(item.GiaBan);
tr.append(td);
td = $(_td());
var ck = $(_input(item.CKhau, '', '', ('ck_' + i), 'i-number pointer'));
ck.change(() => { Global.Data._dichvus[i].CKhau = $(ck).val(); TinhTong(); })
td.append(ck);
tr.append(td);
td = $(_td());
td.text(item.GiaCK);
td.addClass('col-red bold');
tr.append(td);
td = $(_td());
var btndelete = $(_delete());
btndelete.click(() => { Global.Data._dichvus.splice(i, 1); TinhTong(); })
td.append(btndelete);
tr.append(td);
tb.append(tr);
});
}
}
findName = (index, value) => {
var obj = Global.Data._works.filter(x => x.Name == value)[0];
if (obj) {
Global.Data._dichvus[index].DVId = obj.Id;
Global.Data._dichvus[index].DVName = value;
Global.Data._dichvus[index].DVCode = obj.Code;
Global.Data._dichvus[index].GiaBan = obj._double1;
}
TinhTong();
}
findCode = (index, value) => {
var obj = Global.Data._works.filter(x => x.Code == value)[0];
if (obj) {
Global.Data._dichvus[index].DVId = obj.Id;
Global.Data._dichvus[index].DVCode = value;
Global.Data._dichvus[index].DVName = obj.Name;
Global.Data._dichvus[index].GiaBan = obj._double1;
}
TinhTong();
}
AddNew = () => { Global.Data._dichvus.push({ DVId: null, DVCode: '', DVName: '', GiaBan: 0, CKhau: 0, GiaCK: 0 }); }
DrawTablePhuTung = () => {
if (Global.Data._dsPhuTungs.length > 0) {
var tb = $('.tb-phutung tbody');
tb.empty();
$.each(Global.Data._dsPhuTungs, (i, item) => {
var tr = $(_tr());
var td = $(_td());
var code = $(_input(item.PTCode, 'phutungs', '', ('pt_code_' + i), 'i-code pointer'));
code.change(() => { findCode_PT(i, $(code).val()); });
code.focus(() => { $(code).select(); })
td.append(code);
tr.append(td);
td = $(_td());
var name = $(_input(item.PTName, 'phutungs-name', '', ('pt_name_' + i), 'i-name pointer'));
name.change(() => { findName_PT(i, $(name).val()); })
name.focus(() => { $(name).select(); })
td.append(name);
tr.append(td);
td = $(_td());
var sl = $(_input(item.SoLuong, '', '', ('pt_sl_' + i), 'i-number pointer'));
sl.change(() => {
var num = parseInt($(sl).val());
if (num <= 0)
num = 1;
Global.Data._dsPhuTungs[i].SoLuong = num;
TinhTong();
});
td.append(sl);
tr.append(td);
td = $(_td());
td.text(item.GiaBan);
tr.append(td);
td = $(_td());
var ck = $(_input(item.CKhau, '', '', ('pt_ck_' + i), 'i-number pointer'));
ck.change(() => { Global.Data._dsPhuTungs[i].CKhau = $(ck).val(); TinhTong(); })
td.append(ck);
tr.append(td);
td = $(_td());
td.text(item.GiaCK);
td.addClass('col-red bold');
tr.append(td);
td = $(_td());
var btndelete = $(_delete());
btndelete.click(() => { Global.Data._dsPhuTungs.splice(i, 1); TinhTong(); })
td.append(btndelete);
tr.append(td);
tb.append(tr);
});
}
}
AddNewPT = () => { Global.Data._dsPhuTungs.push({ PTId: null, PTCode: '', PTName: '', SoLuong: 1, GiaBan: 0, CKhau: 0, GiaCK: 0 }); }
findCode_PT = (index, value) => {
var obj = Global.Data._phutungs.filter(x => x.Code == value)[0];
if (obj) {
if (obj.Data > 0) {
Global.Data._dsPhuTungs[index].PTId = obj.Id;
Global.Data._dsPhuTungs[index].PTCode = value;
Global.Data._dsPhuTungs[index].PTName = obj.Name;
Global.Data._dsPhuTungs[index].GiaBan = obj._double1;
}
else
swal("Lỗi nhập liệu", "Số lượng tồn kho đã hết. Vui lòng nhập thêm phụ tùng.", "error");
}
TinhTong();
}
findName_PT = (index, value) => {
var obj = Global.Data._phutungs.filter(x => x.Name == value)[0];
if (obj) {
if (obj.Data > 0) {
Global.Data._dsPhuTungs[index].PTId = obj.Id;
Global.Data._dsPhuTungs[index].PTCode = obj.Code;
Global.Data._dsPhuTungs[index].PTName = value;
Global.Data._dsPhuTungs[index].GiaBan = obj._double1;
}
else
swal("Lỗi nhập liệu", "Số lượng tồn kho đã hết. Vui lòng nhập thêm phụ tùng.", "error");
}
TinhTong();
}
TinhTong = () => {
var total = 0;
var totalPT = 0;
$.each(Global.Data._dichvus, (i, item) => {
var gia = item.GiaBan;
var ck = item.CKhau;
item.GiaCK = gia - ((gia * ck) / 100);
total += item.GiaCK;
});
$.each(Global.Data._dsPhuTungs, (i, item) => {
var gia = item.GiaBan;
var ck = item.CKhau;
item.GiaCK = (gia - ((gia * ck) / 100)) * item.SoLuong;
totalPT += item.GiaCK;
});
$('#total_dv').html(total);
$('#total_pt').html(totalPT);
$('#total').html(total + totalPT);
if (Global.Data._dichvus[Global.Data._dichvus.length - 1].DVId)
AddNew();
if (Global.Data._dsPhuTungs[Global.Data._dsPhuTungs.length - 1].PTId)
AddNewPT();
DrawTable();
DrawTablePhuTung();
// console.log(Global.Data._dichvus);
}
function Delete(Id) {
$.ajax({
url: Global.UrlAction.Delete,
type: 'POST',
data: JSON.stringify({ 'Id': Id }),
contentType: 'application/json charset=utf-8',
// beforeSend: function () { $('.progress').removeClass('hide'); },
success: function (response) {
// $('.progress').addClass('hide');
if (response.success) {
Gets();
}
else
swal("Lỗi", response.responseText, "error");
}
});
}
function Gets() {
$.ajax({
url: Global.UrlAction.Gets,
type: 'POST',
data: null,
contentType: 'application/json charset=utf-8',
beforeSend: function () { $('.progress').removeClass('hide'); },
success: function (objs) {
$('.progress').addClass('hide');
if (Global.Data.table != null) {
Global.Data.table.destroy();
$('#kh-table').empty();
Global.Data.table = null;
Global.Data.ReceiptXe.length = 0;
}
Global.Data.ReceiptXe = objs;
InitTable(objs);
}
});
}
function InitTable(Objs) {
Global.Data.table = $('#kh-table').DataTable({
responsive: true,
"data": Objs,
"dom": '<"top"<"col-sm-3 m-b-0 p-l-0"l><"col-sm-9 m-b-0"f><"clear">>rt<"bottom"<"col-sm-6 p-l-0"i><"col-sm-6 m-b-0"p><"clear">><"clear">',
"oLanguage": {
"sSearch": "Bộ lọc",
"sLengthMenu": "Hiển thị _MENU_ dòng mỗi trang",
"sInfo": "Hiển thị từ _START_ - _END_ trong _TOTAL_ dòng",
'paginate': {
'previous': '<span class="prev-icon"></span>',
'next': '<span class="next-icon"></span>'
}
},
"columns": [
{ "orderable": true, "data": "Ma", "title": "Mã khách hàng", 'width': '100px' },
{ "data": "Ten", "title": "tên khách hàng", 'width': '150px' },
{ "data": "NSinh", "title": "ngày sinh", 'width': '50px', render: (data, type, full, meta) => { return (data != null ? ddMMyyyy(data) : '') } },
{ "data": "GTinh", "title": "giới tính", 'width': '30px', render: (data, type, full, meta) => { return (data ? '<i class="fa fa-male col-blue fa-2x"></i>' : '<i class="fa fa-female col-pink fa-2x"></i>') } },
{ "data": "DThoai", "title": "điện thoại", 'width': '70px' },
{ "data": "DChi", "title": "địa chỉ", 'width': '300px' },
{ "data": "Note", "title": "Ghi chú", 'width': 'calc(100% - 700px)', className: 'tb-Receipt-note' },
{
'className': 'table-edit-delete-col',
"orderable": false,
"render": function (data, type, full, meta) {
return `<i class='fa fa-edit col-blue fa-lg pointer' onClick="Edit(${full.Id})"></i> <i class='fa fa-trash col-red fa-lg pointer' onClick="Delete(${full.Id})"></i>`;
}
}]
});
$('#kh-table_wrapper #kh-table_filter').append($('<label><i class="fa fa-file-excel-o fa-lg col-red pointer" title="xuất excel" aria-hidden="true"></i></label>'));
}
function Save() {
if (IsValid()) {
var transObj = {
Id: Global.Data.selectedObj.Id,
Ma: $('#code').val(),
Ten: $('#name').val(),
NSinh: moment($('#ngaysinh').val(), ''),
GTinh: $('#gioitinh').val() == '0' ? false : true,
DThoai: $('#phone').val(),
DChi: $('#address').val(),
TPho: $('#tinh-thanhpho').val(),
Huyen: $('#quan-huyen').val(),
Phuong: $('#phuong').val(),
JobId: $('#jobid').val(),
Note: $('#note').val()
}
$.ajax({
url: Global.UrlAction.Save,
type: 'POST',
data: JSON.stringify(transObj),
contentType: 'application/json charset=utf-8',
// beforeSend: function () { $('.progress').removeClass('hide'); },
success: function (response) {
// $('.progress').addClass('hide');
if (response.IsSuccess) {
Gets();
$('#btCancel').click();
}
//window.location.href = '/Receipt/Index';
else
swal("Lỗi nhập liệu", response.sms);
}
});
}
}
function IsValid() {
$('.err-name,.err-code').empty();
var error = 0;
if ($('#code').val() == '') {
$('.err-code').append('<span class="err-msg">Trường không được để trống.</span>');
error++;
}
if ($('#name').val() == '') {
$('.err-name').append('<span class="err-msg">Trường không được để trống.</span>');
error++;
}
return error > 0 ? false : true;
}
findKH = () => {
if ($('#code').val() != '') {
$.ajax({
url: Global.UrlAction.Find,
type: 'POST',
data: JSON.stringify({ 'data': $('#code').val() }),
contentType: 'application/json charset=utf-8',
// beforeSend: function () { $('.progress').removeClass('hide'); },
success: function (obj) {
if (obj)
Bind(obj);
else
swal("Thông báo", "Không tìn thấy khách hàng trong hệ thống.!");
}
});
}
}
function Bind(obj) {
$('#tinh-thanhpho').val(obj.TPho);
Global.Data.HuyenValue = obj.Huyen;
$('#ngaysinh').val(moment(obj.NSinh).format('DD/MM/YYYY'));
$('#name').val(obj.Ten);
$('#gioitinh').val(obj.GTinh ? '1' : '0');
$('#phone').val(obj.DThoai);
$('#address').val(obj.DChi);
$('#phuong').val(obj.Phuong);
$('#note').val(obj.Note);
$('#jobid').val(obj.JobId);
$('#code').val(obj.Ma);
$('#tinh-thanhpho').change();
RefreshControls();
//Textarea auto growth
autosize($('textarea.auto-growth'));
}
SavePhieu = () => {
if (IsValid()) {
var transObj = {
SoPhieu: $('#sophieu').val(),
MaKH: $('#code').val(),
ModelId: $('#model').val(),
Ngay: moment($('#ngaytao').val(), ''),
SoKhung: $('#sokhung').val(),
SoMay: $('#somay').val(),
BienSo: $('#bienso').val(),
Km: parseInt($('#km').val()),
yeucau: parseFloat($('#giaban').val()),
nhanxet: parseFloat($('#chietkhau').val()),
trangthai: parseFloat($('#chietkhau').val()),
Note: $('#note').val()
}
$.ajax({
url: Global.UrlAction.SavePhieu,
type: 'POST',
data: JSON.stringify(transObj),
contentType: 'application/json charset=utf-8',
// beforeSend: function () { $('.progress').removeClass('hide'); },
success: function (response) {
// $('.progress').addClass('hide');
if (response.IsSuccess) {
Gets();
$('#btCancel').click();
}
//window.location.href = '/BanHang/Index';
else
swal("Lỗi nhập liệu", response.sms);
}
});
}
}
}
|
const axios = require('axios')
const Dev = require('../model/Dev')
module.exports = {
async store(req, res) {
const { username } = req.body
try {
const response = await axios.get(`https://api.github.com/users/${username}`)
const { name, bio, avatar_url: avatar} = response.data
await Dev.create({
name,
user: username,
bio,
avatar
})
} catch (error) {
return res.status(500).send(err);
}
return res.json(response.data)
}
}
|
//精度10m
var correct_pts = {};
correct_pts['hh'] = [
//20130729最新参考点
{ j: 106.287494, w: 30.345093, utm_x: 0, utm_y: 0, x: 106.287390, y: 30.344014 },
{ j: 106.287336, w: 30.347885, utm_x: 0, utm_y: 0, x: 106.290126, y: 30.346180 },
{ j: 106.283367, w: 30.344955, utm_x: 0, utm_y: 0, x: 106.283527, y: 30.346501 },
{ j: 106.289577, w: 30.340953, utm_x: 0, utm_y: 0, x: 106.285087, y: 30.339693 },
{ j: 106.291069, w: 30.345771, utm_x: 0, utm_y: 0, x: 106.291313, y: 30.342315 },
{ j: 106.282960, w: 30.341329, utm_x: 0, utm_y: 0, x: 106.279508, y: 30.344104 },
{ j: 106.286098, w: 30.337433, utm_x: 0, utm_y: 0, x: 106.278363, y: 30.339294 },
{ j: 106.297964, w: 30.348508, utm_x: 0, utm_y: 0, x: 106.300306, y: 30.340049 },
{ j: 106.295850, w: 30.342086, utm_x: 0, utm_y: 0, x: 106.291856, y: 30.336641 },
{ j: 106.277658, w: 30.345055, utm_x: 0, utm_y: 0, x: 106.278526, y: 30.350127 },
{ j: 106.283192, w: 30.334256, utm_x: 0, utm_y: 0, x: 106.272545, y: 30.338774 },
{ j: 106.292784, w: 30.350689, utm_x: 0, utm_y: 0, x: 106.297851, y: 30.344866 },
{ j: 106.291348, w: 30.353957, utm_x: 0, utm_y: 0, x: 106.299880, y: 30.348153 },
{ j: 106.287014, w: 30.355851, utm_x: 0, utm_y: 0, x: 106.297937, y: 30.352211 },
{ j: 106.286323, w: 30.351691, utm_x: 0, utm_y: 0, x: 106.293061, y: 30.349618 },
//20131024最新参考点
{ j: 106.267141, w: 30.341900, utm_x: 0, utm_y: 0, x: 106.265862, y: 30.354336 },
{ j: 106.274153, w: 30.344097, utm_x: 0, utm_y: 0, x: 106.274373, y: 30.351610 },
{ j: 106.269808, w: 30.337980, utm_x: 0, utm_y: 0, x: 106.264248, y: 30.349813 },
{ j: 106.276458, w: 30.336522, utm_x: 0, utm_y: 0, x: 106.268749, y: 30.344628 },
{ j: 106.276873, w: 30.343291, utm_x: 0, utm_y: 0, x: 106.276009, y: 30.349323 },
{ j: 106.281986, w: 30.349299, utm_x: 0, utm_y: 0, x: 106.286713, y: 30.350539 },
{ j: 106.284344, w: 30.353276, utm_x: 0, utm_y: 0, x: 106.292885, y: 30.352011 },
{ j: 106.285371, w: 30.363450, utm_x: 0, utm_y: 0, x: 106.304096, y: 30.358813 },
{ j: 106.289469, w: 30.361729, utm_x: 0, utm_y: 0, x: 106.306047, y: 30.355024 },
{ j: 106.291001, w: 30.355080, utm_x: 0, utm_y: 0, x: 106.300695, y: 30.349199 }
//{ j: , w: , utm_x: 0, utm_y: 0, x: , y: },
// { j: , w: , utm_x: 0, utm_y: 0, x: , y: },
];
var num = {};
num['hh'] = { num: Math.sin(Math.PI / 4), num2: Math.sin(Math.PI / 4) };
//得到需要转换坐标的类型
function getTypeP(type) {
if (type == "jw")
return { strX: 'j', strY: 'w', initValue: 180, minPreX: 0.00005, minPreY: 0.00005 };
if (type == "utm")
return { strX: 'utm_x', strY: 'utm_y', initValue: 1294723000, minPreX: 500, minPreY: 500 };
if (type == "xy")
return { strX: 'x', strY: 'y', initValue: 1000000000, minPreX: 500, minPreY: 500 };
}
//输入一个点,得到这个点最近却比较合理的两对点。
function getPx_Py(city, x, y, typeP) {
var pointsIndex = getFourNearIndex(city, x, y, typeP);
return get2PairPointsX_Y(city, pointsIndex, typeP);
}
//得到输入所有点中,比较合理的两对点。
//一对在X轴上,一对在Y轴上。
function get2PairPointsX_Y(city, pointsIndex, typeP) {
var pointsX = {};
var pointsY = {};
var haveX = false;
var haveY = false;
var oldInstanceX = 0;
var oldInstanceY = 0;
for (var i = 0; i < pointsIndex.length; i++) {
for (var j = i + 1; j < pointsIndex.length; j++) {
var tempInstanceX_Y = getInstanceCommon2P(city, pointsIndex[i], pointsIndex[j], typeP);
if (tempInstanceX_Y.Ix > oldInstanceX && !haveX) {
oldInstanceX = tempInstanceX_Y.Ix;
pointsX.index0 = pointsIndex[i];
pointsX.index1 = pointsIndex[j];
}
if (tempInstanceX_Y.Ix > typeP.minPreX && !haveX) {
haveX = true;
}
if (tempInstanceX_Y.Iy > oldInstanceY && !haveY) {
oldInstanceY = tempInstanceX_Y.Iy;
pointsY.index0 = pointsIndex[i];
pointsY.index1 = pointsIndex[j];
}
if (tempInstanceX_Y.Iy > typeP.minPreY && !haveY) {
haveY = true;
}
if (haveY && haveX) {
return { px: pointsX, py: pointsY };
}
}
}
return { px: pointsX, py: pointsY };
}
//得到两个点在指定坐标上的距离,兼容了25DMap的点。
function getInstanceCommon2P(city, index0, index1, typeP) {
if (typeP.strX == "x" && typeP.strY == "y") {
return getInstance2P_XY(city, index0, index1);
}
else {
return getInstance2P(city, index0, index1, typeP);
}
}
//得到25DMap两个点在X轴和Y轴上的距离。
function getInstance2P_XY(city, index0, index1) {
var px_1 = fromMap(city, correct_pts[city][index0].x, correct_pts[city][index0].y);
var px_2 = fromMap(city, correct_pts[city][index1].x, correct_pts[city][index1].y);
var instanceX = Math.abs(px_1.x - px_2.x);
var instanceY = Math.abs(px_1.y - px_2.y);
return { Ix: instanceX, Iy: instanceY };
}
//得到两个点在指定坐标上的距离。
function getInstance2P(city, index0, index1, typeP) {
var instanceX = Math.abs(correct_pts[city][index0][typeP.strX] - correct_pts[city][index1][typeP.strX]);
var instanceY = Math.abs(correct_pts[city][index0][typeP.strY] - correct_pts[city][index1][typeP.strY]);
return { Ix: instanceX, Iy: instanceY };
}
//得到指定点最近的四个点
function getFourNearIndex(city, x, y, typeP) {
var p1 = 0;
var p2 = 0;
var p3 = 0;
var p4 = 0;
var minDis = typeP.initValue, secMinDis = typeP.initValue, thrMinDis = typeP.initValue, fouMinDis = typeP.initValue;
for (var i = 0; i < correct_pts[city].length; i++) {
var dis = getDis(correct_pts[city][i][typeP.strX], correct_pts[city][i][typeP.strY], x, y);
if (dis < minDis) {
fouMinDis = thrMinDis;
thrMinDis = secMinDis;
secMinDis = minDis;
minDis = dis;
p4 = p3;
p3 = p2;
p2 = p1;
p1 = i;
}
else if (dis > minDis && dis < secMinDis) {
fouMinDis = thrMinDis;
thrMinDis = secMinDis;
sedMinDis = dis;
p4 = p3;
p3 = p2;
p2 = i;
}
else if (dis > secMinDis && dis < thrMinDis) {
fouMinDis = thrMinDis;
thrMinDis = dis;
p4 = p3;
p3 = i;
}
else if (dis > thrMinDis && dis < fouMinDis) {
fouMinDis = dis;
p4 = i;
}
}
return new Array(p1, p2, p3, p4);
}
//计算坐标之间的距离。
function getDis(x, y, x1, y1) {
return Math.abs(x - x1) + Math.abs(y - y1);
}
//从标准平面坐标得到地图坐标
function toMap(city, x, y) {
var x2 = (x - y) * num[city].num;
var y2 = (x + y) * num[city].num * num[city].num2;
return { x: x2, y: y2 };
}
//从地图坐标得到标准平面坐标
function fromMap(city, x, y) {
y = y / num[city].num2;
var x2 = (x + y) / (num[city].num * 2);
var y2 = (y - x) / (num[city].num * 2);
return { x: x2, y: y2 };
}
//得到小范围地图精度
function getDgPix_mm(city, index0, index1) {
var px_1 = fromMap(city, correct_pts[city][index0].x, correct_pts[city][index0].y);
var px_2 = fromMap(city, correct_pts[city][index1].x, correct_pts[city][index1].y);
var x_1 = px_1.x, y_1 = px_1.y;
var x_2 = px_2.x, y_2 = px_2.y;
var dj1 = correct_pts[city][index0].utm_x, dw1 = correct_pts[city][index0].utm_y;
var dj2 = correct_pts[city][index1].utm_x, dw2 = correct_pts[city][index1].utm_y;
var a = Math.abs((dj2 - dj1) * 100000 / (x_2 - x_1));
var b = Math.abs((dw2 - dw1) * 100000 / (y_2 - y_1));
//a,b每十万像素对应的经纬度
return { j: a, w: b, x: 100000 / a, y: 100000 / b };
}
//得到小范围地图精度
function getDgPix_mm_25DMap(city, indexX0, indexX1, indexY0, indexY1, typeP) {
var px_1 = fromMap(city, correct_pts[city][indexX0].x, correct_pts[city][indexX0].y);
var px_2 = fromMap(city, correct_pts[city][indexX1].x, correct_pts[city][indexX1].y);
var py_1 = fromMap(city, correct_pts[city][indexY0].x, correct_pts[city][indexY0].y);
var py_2 = fromMap(city, correct_pts[city][indexY1].x, correct_pts[city][indexY1].y);
var x_1 = px_1.x, x_2 = px_2.x;
var y_1 = py_1.y, y_2 = py_2.y;
var dj1 = correct_pts[city][indexX0][typeP.strX], dj2 = correct_pts[city][indexX1][typeP.strX];
var dw1 = correct_pts[city][indexY0][typeP.strY], dw2 = correct_pts[city][indexY1][typeP.strY];
var a = Math.abs((dj2 - dj1) * 100000 / (x_2 - x_1));
var b = Math.abs((dw2 - dw1) * 100000 / (y_2 - y_1));
//a,b每十万像素对应的经纬度
return { j: a, w: b, x: 100000 / a, y: 100000 / b };
}
//从经纬度得到地图像素值,如需将地图坐标转换成经纬则反过来算即可
//小范围内地图满足线性关系
function getPx_mm(city, utm_x, utm_y, px, py, typeP) {
var px_src = correct_pts[city][px.index0];
var gp_src = correct_pts[city][px.index0];
var dgPix = getDgPix_mm_25DMap(city, px.index0, px.index1, py.index0, py.index1, typeP);
var px_1 = fromMap(city, px_src.x, px_src.y);
var dj1 = gp_src[typeP.strX], dw1 = gp_src[typeP.strY];
var dj = utm_x, dw = utm_y;
var x_1 = px_1.x;
var y_1 = px_1.y;
var dj_s = dj - dj1, dw_s = dw - dw1;
var x = dj_s * dgPix.x + x_1;
var y = -dw_s * dgPix.y + y_1;
var r = toMap(city, x, y);
return r;
}
function getJw_mm(city, x, y, px1, py1, typeP) {
var mappx_src = correct_pts[city][px1.index0];
var gp_src = correct_pts[city][px1.index0];
var dgPix = getDgPix_mm_25DMap(city, px1.index0, px1.index1, py1.index0, py1.index1, typeP);
var px = fromMap(city, x, y);
var px_src = fromMap(city, mappx_src.x, mappx_src.y);
//var dj1=gp_src.utm_x,dw1=gp_src.utm_y;
var dj1 = gp_src[typeP.strX], dw1 = gp_src[typeP.strY];
var x_1 = px_src.x;
var y_1 = px_src.y;
var px_s = px.x - x_1, py_s = y_1 - px.y;
var gp_j = px_s / dgPix.x + dj1;
var gp_w = py_s / dgPix.y + dw1;
return { lng: gp_j, lat: gp_w };
}
//接口函数
function get25DMap_pts(city, pts) {
if (!pts.px || !pts.py) {
var typeP = getTypeP("utm");
var twoIndexs = getPx_Py(city, pts.x, pts.y, typeP);
pts.px = twoIndexs.px;
pts.py = twoIndexs.py;
}
return get25DMap_index(city, pts.utm_x, pts.utm_y, pts.px, pts.py);
}
//接口函数
function getMapJw_pts(city, pts) {
if (!pts.px || !pts.py) {
var typeP = getTypeP("xy");
var twoIndexs = getPx_Py(city, pts.x, pts.y, typeP);
pts.px = twoIndexs.px;
pts.py = twoIndexs.py;
}
return getMapJw_index(city, pts.x, pts.y, pts.px, pts.py);
}
function get25DMap_index(city, utm_x, utm_y, px0, py0, typeP) {
var xy = getPx_mm(city, utm_x, utm_y, px0, py0, typeP);
return { x: xy.x, y: xy.y, px: px0, py: py0 };
}
function getMapJw_index(city, x, y, px0, py0, typeP) {
var lnglat = getJw_mm(city, x, y, px0, py0, typeP);
return { lng: lnglat.lng, lat: lnglat.lat, px: px0, py: py0 };
}
function getMapJw_Array(city, pts) {
var typeP = getTypeP("xy");
var twoIndexs = getPx_Py(city, pts[0].x, pts[0].y, typeP);
//墨卡托坐标坐标的转换
var typeP1 = getTypeP("utm");
var lnglat = new Array;
for (var i = 0; i < pts.length; i++) {
var tmp = getJw_mm(city, pts[i].x, pts[i].y, twoIndexs.px, twoIndexs.py, typeP1);
lnglat[i] = { lng: tmp.lng, lat: tmp.lat, px: twoIndexs.px, py: twoIndexs.py };
}
return lnglat;
}
function get25DMap_Array(city, pts) {
var typeP = getTypeP("utm");
var twoIndexs = getPx_Py(city, pts[0].utm_x, pts[0].utm_y, typeP);
var xy = new Array;
for (var i = 0; i < pts.length; i++) {
var tmp = getPx_mm(city, pts[i].utm_x, pts[i].utm_y, twoIndexs.px, twoIndexs.py, typeP);
xy[i] = { lng: tmp.x, lat: tmp.y, px: twoIndexs.px, py: twoIndexs.py };
}
return xy;
}
//25D坐标得到经纬度
function getMapJw(city, x, y) {
y = -y;
var typeP = getTypeP("xy");
var twoIndexs = getPx_Py(city, x, y, typeP);
var typeP1 = getTypeP("jw");
return getMapJw_index(city, x, y, twoIndexs.px, twoIndexs.py, typeP1);
}
//经纬度得到25D坐标
function get25DMap(city, j, w) {
var typeP = getTypeP("jw");
var twoIndexs = getPx_Py(city, j, w, typeP);
var pt = get25DMap_index(city, j, w, twoIndexs.px, twoIndexs.py, typeP);
pt.y = -pt.y;
return pt;
}
//UTM坐标得到25D坐标
function get25DMap_mm(city, utm_x, utm_y) {
var typeP = getTypeP("utm");
var twoIndexs = getPx_Py(city, utm_x, utm_y, typeP);
return get25DMap_index(city, utm_x, utm_y, twoIndexs.px, twoIndexs.py, typeP);
}
//25D坐标得到UTM坐标
function getMapJw_mm(city, x, y) {
var typeP = getTypeP("xy");
var twoIndexs = getPx_Py(city, x, y, typeP);
var typeP1 = getTypeP("utm");
return getMapJw_index(city, x, y, twoIndexs.px, twoIndexs.py, typeP1);
}
function parsePoints() {
for (var item in correct_pts) {
var arr = correct_pts[item];
for (var i = 0; i < arr.length; i++) {
arr[i].y = -arr[i].y;
}
}
}
parsePoints();
|
appCliente.controller("clienteController", function($scope, $http) {
$scope.nome = "";
$scope.clientes = [];
$scope.cliente = {};
$scope.carregarClientes = function() {
$http({method:'GET', url:'/clientes'}).then(
function(response){
$scope.clientes = response.data;
},
function(response){
console.log(response.data);
console.log(response.status);
}
);
}
$scope.salvarCliente = function () {
$http({method:'POST', url:'/clientes', data: $scope.cliente}).then(
function(response){
$scope.carregarClientes();
$scope.cancelar();
},
function(response){
console.log(response.data);
console.log(response.status);
}
);
}
$scope.removerCliente = function (cliente) {
$http({method:'DELETE', url:'/clientes/'+ cliente.id}).then(
function(response){
pos = $scope.clientes.indexOf(cliente);
$scope.clientes.splice(pos, 1);
},
function(response){
console.log(response.data);
console.log(response.status);
}
);
}
$scope.alterarCliente = function (cliente) {
$scope.cliente = angular.copy(cliente);
}
$scope.cancelar = function () {
$scope.cliente = {};
}
$scope.carregarClientes();
});
|
import React, { useState, useEffect } from 'react';
import { Col, Row, Button, Container, Image } from 'react-bootstrap';
import { useParams, useHistory } from 'react-router-dom';
import { incrementCartItem, getUsersCart } from '../../lib/cart';
import axios from '../../lib/axios';
import LoadingSpinner from '../../components/LoadingSpinner';
/**
* List of items in a category that can be added to cart- quantity can be increased/decreased
*/
export default function Category({ session }) {
const [items, setItems] = useState([]);
const [itemsLoading, setItemsLoading] = useState(true);
let categoryName;
const { id } = useParams();
const history = useHistory();
/**
* makes GET request to /categories endpoint. Uses route category id parameter to request specific category items
* @returns array of items objects
*/
const getItems = async () => {
const response = await axios.get(`/categories/${id}?getNested=true`);
categoryName = response.data.name;
return response.data.Items;
};
/**
* checks is a user session is present
* sets isLoading state component to true while users cart information request completes.
* adds property to cart
*/
const refreshItems = async () => {
setItemsLoading(true);
let tempCart = [];
if (session.loggedIn) {
tempCart = await getUsersCart(session.userId);
}
const tempItems = await getItems();
const quantifiedItems = addQuantityProperty(tempItems, tempCart);
setItems(quantifiedItems);
setItemsLoading(false);
};
/**
*
* adds property to item object for simpler retrieval and manipulation of quantity
* value is zero or set to quantity for item in cart for user session
*/
const addQuantityProperty = (tempItems, tempCart) => {
console.log(tempItems, tempCart);
let initialisedItems = tempItems.map((item) => {
return { ...item, quantityInCart: 0 };
});
console.log(initialisedItems);
initialisedItems.forEach((item) => {
const index = tempCart.findIndex((cartItem) => item.id === cartItem.id);
if (index > -1) {
item.quantityInCart = tempCart[index].CartItem.quantity;
}
});
return initialisedItems;
};
// used useEffect to make request to items API from /items
useEffect(async () => {
await refreshItems();
}, []);
/**
* Attempts to change item quantity in user's cart.
* Will redirect to login if there is no session logged in.
* We would lke to update the quantity seen by the user, when they request the change
*/
const handleChangeItemQuantity = async (itemId, quantity) => {
if (!session.loggedIn) {
history.push('/login');
return;
}
const newQuantityResponse = await incrementCartItem(session.userId, itemId, quantity);
updateItemQuantity(itemId, newQuantityResponse.data);
};
/**
* Updates quantity of for displaying on client
* @param {number} itemId
* @param {number} quantity
*/
const updateItemQuantity = (itemId, quantity) => {
const newItems = items.map((item) => {
if (item.id === itemId) {
item.quantityInCart = quantity;
return item;
}
return item;
});
setItems(newItems);
console.log('updated quantity:', items);
};
if (itemsLoading) {
return <LoadingSpinner />;
} else {
return (
<Container className="my-4">
<h2 className="display-3 my-2">{categoryName}</h2>
{/* map over the items data pass it into item card */}
{items.map((item) => {
return (
<>
<ItemRow
key={item.id}
item={item}
incrementItem={() => handleChangeItemQuantity(item.id, 1)}
decrementItem={() => handleChangeItemQuantity(item.id, -1)}
></ItemRow>
<hr></hr>
</>
);
})}
</Container>
);
}
}
function ItemRow({ incrementItem, decrementItem, item }) {
return (
<Row>
<Col className="m-auto" xs="3">
<Image style={{ maxWidth: '6rem', maxHeight: '30rem' }} src={item.imageLink} />
</Col>
{/* name and desc */}
<Col className="m-auto">
<Row className="m-auto" style={{ textAlign: 'center' }}>
<h3>{item.name}</h3>
</Row>
<Row style={{ textAlign: 'center' }}>
<hr />
<p style={{ textOverflow: 'ellipsis', maxLines: '5' }}>{item.description}</p>
</Row>
</Col>
<Col className="m-auto" xs="1" lg="2">
<Row className="my-0">
<Col>
<Button disabled={!item.quantityInCart} onClick={() => decrementItem(item.id)} variant="danger">
-
</Button>
</Col>
<Col>
<h2>{item.quantityInCart}</h2>
</Col>
<Col>
<Button onClick={() => incrementItem(item.id)} variant="primary">
+
</Button>
</Col>
</Row>
</Col>
</Row>
);
}
|
//creating DOM elements
//1. create tag element
var a = document.createElement('a');
//2. modify properties
a.href = "https://google.com";
a.textContent = "GOOGLE";
//3. add to document
document.body.appendChild(a); //bottom of body section
/*
//second example: add a <li>
const listItem = document.createElement("li");
listItem.textContent = 'Pirates of the Carribbean';
const list = document.querySelector('ul');
const listItem2 = list.children[1];
list.insertBefore(listItem, listItem2);
*/
// obtain a reference to where we'll add it
var list = document.getElementById("my-favorite-movies");
// CREATE
var newMovie = document.createElement("li");
// MODIFY
newMovie.textContent = "Pirates of Silicon Valley";
// ATTACH
list.appendChild(newMovie);
|
const jwt = require("jsonwebtoken");
const responseFactory = require('../libs/response-factory').init();
module.exports.init = function (logger) {
logger.info("Initializing Auth Layer.")
let handle = {
authenticateUser: (req, res, next) => {
const token = req.header("x-auth-token");
if (!token) {
return responseFactory.unauthorized(req, res, "Access denied. No user token provided.", logger)
}
try {
const decoded = jwt.verify(token, process.env.JWT_PRIVATE_KEY);
req.user = decoded;
return next();
} catch (ex) {
return responseFactory.unauthorized(req, res, "Access denied. Invalid user token.", logger)
}
},
authenticateApiConsumer: (req, res, next) => {
const token = req.header("x-auth-token-api");
if (!token) {
return responseFactory.unauthorized(req, res, "Access denied. No API token provided.", logger)
} else if (token !== process.env.API_TOKEN) {
return responseFactory.unauthorized(req, res, "Access denied. Invalid API token.", logger)
}
next();
}
}
return handle;
}
|
module.exports = function (RED) {
class CombineDeltaNode {
constructor(config) {
RED.nodes.createNode(this, config);
this.topic = config.topic;
this.status({fill: 'grey', shape: 'ring'});
this.on('input', msg => {
if (msg.topic === config.topicA) {
const val = parseFloat(msg.payload);
if (isNaN(val)) {
delete this.valA;
} else {
this.valA = val;
}
this.calc();
} else if (msg.topic === config.topicB) {
const val = parseFloat(msg.payload);
if (isNaN(val)) {
delete this.valB;
} else {
this.valB = val;
}
this.calc();
}
});
}
calc() {
if (typeof this.valA !== 'undefined' && typeof this.valB !== 'undefined') {
const delta = this.valA - this.valB;
this.send({topic: this.topic, payload: delta});
this.status({fill: 'blue', shape: 'dot', text: 'Δ ' + delta.toFixed(3)});
} else {
this.status({fill: 'grey', shape: 'ring'});
}
}
}
RED.nodes.registerType('combine-delta', CombineDeltaNode);
};
|
var router = require('koa-router')()
var multer = require('koa-multer')
var fs = require('fs')
var qn = require('qn')
module.exports = function (app, cfg) {
var debug = cfg.debug
var upload = multer(cfg.multer)
if (!cfg.path) {
cfg.path = '/fileupload'
}
if (!cfg.fileKey) {
cfg.fileKey = 'myfile'
}
if (!cfg.callback) {
cfg.callback = function (ctx) {
return ctx.request.files
}
}
function log (str) {
if (debug === true) {
console.log(str)
}
}
app.use(router.routes()).use(router.allowedMethods())
router.post(cfg.path, upload.array(cfg.fileKey), function (ctx, next) {
log(ctx.request)
if (cfg.qn) {
var client = qn.create(cfg.qn)
var filepath = ctx.req.files[0]['path']
var p = __dirname.split('node_modules')[0]
var fp = fs.createReadStream(p + '/' + filepath)
return new Promise((resolve, reject) => {
client.upload(fp, function (err, result) {
log(err)
log(result)
if (err) {
return reject(err)
}
var f = ctx.req.files[0]
for (var k in result) {
var v = result[k]
f[k] = v
}
var arr = []
arr.push(f)
log(f)
ctx.body = arr
resolve()
})
})
} else {
ctx.body = ctx.req
}
})
}
|
import React, { Component } from 'react'
// import { testMixins } from './mixins'
import './test.css'
class Test extends Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
num: 0
}
this.tick = () => {
this.setState({
date: new Date()
})
}
this.change = (event) => {
this.setState({
num: event.target.value
})
this.props.setNum(event.target.value)
}
}
componentWillMount() {
this.setState({
num: this.props.num
})
}
componentDidMount() {
this.timerID = setInterval(this.tick, 1000)
}
componentWillUnmount() {
console.log('componentWillUnmount')
clearInterval(this.timerID)
}
render() {
return (
<div>
<h2>It is {this.state.date.toLocaleTimeString()}</h2>
<p>这是test组件</p>
<input type="text" value= { this.state.num } onChange= { this.change } />
<br />
{this.props.left}
<br />
<p>{this.props.children}</p>
<br />
<button onClick={this.props.cancle}>点我关闭</button>
</div>
);
}
}
export default Test;
|
import logo from './logo.svg';
import './App.css';
import { Provider, useSelector } from "react-redux";
import { configureStore } from "./store/index"
import RadioButtons from './components/RadioButtons';
import DailyCard from './components/DailyCard';
import DailyCards from './components/DailyCards';
import BarCharts from './components/BarCharts';
import { createTheme, ThemeProvider } from '@material-ui/core';
import Dashboard from './components/Dashboard';
const store = configureStore();
const theme = {
palette: {
primary: { main: "#ff4800" },
secondary: { main: '#ff4800' },
},
};
const muiTheme = createTheme(theme);
function App() {
return <Provider store={store}>
<ThemeProvider theme={muiTheme}>
<Dashboard/>
</ThemeProvider>
</Provider>;
}
export default App;
|
import React, {useState} from 'react';
import LoadingAnimation from '../../animations/Loading.js'
import { Modal } from '../../utils/dialog/Modal.js';
import { sendMessage, websocket } from '../../utils/websocket/RemoteWebsocket.js';
import { ACTION } from '../definitions/commDefinition.js';
import { useHistory } from 'react-router-dom';
import { printLog } from '../../utils/logger/Logger.js'
// css
import '../../css/ManageDevice.css';
/**
* @brief Change Device Password
* @note default id : root, pw : root
*/
function ChangeDevicePW () {
/**
* @brief Animation
*/
const [loadingStatus, setLoadingStatus] = useState(false);
const bRenderLoading = loadingStatus;
/**
* @brief Dialog (Modal)
*/
const history = useHistory();
const [modalOpen, setModalOpen] = useState(false);
const [modalStatus, setModalStatus] = useState({
status: false,
body: ''
});
const openModal = () => {
setModalOpen(true);
}
const closeModal = () => {
setModalOpen(false);
if(true === modalStatus[0])
{
history.push('/main');
}
else
{
setInputs('','','');
}
}
const cancelModal = () => {
setModalOpen(false);
setInputs('','','');
}
/**
* @brief Websocket onmessage override
*/
websocket.onmessage = (event) => {
const response = JSON.parse(event.data);
printLog(event.data);
if(ACTION.MANAGE_DEVICE === response.action)
{
setLoadingStatus(false);
if(true === response.result) {
setModalStatus([true, "비밀번호가 성공적으로 변경되었습니다."]);
openModal();
}
else{
setModalStatus([false, "비밀번호를 다시 입력해주세요"]);
openModal();
}
}
}
/**
* @brief Old & new device password state
*/
const [inputs, setInputs] = useState({
originPw: '',
newPw: '',
confirmPw: '',
})
const { originPw, newPw, confirmPw } = inputs;
const onValueChange = (element) => {
const { value, name } = element.target;
setInputs({
...inputs,
[name]: value
})
}
/**
* @brief Verify and change device password
*/
const changeDevicePassword = () =>{
setLoadingStatus(true);
setTimeout(() => {
if('' === originPw || '' === newPw || '' === confirmPw) {
setLoadingStatus(false);
setModalStatus([false, "비밀번호를 입력해주세요"]);
openModal();
}
else if(newPw !== confirmPw) {
setLoadingStatus(false);
setModalStatus([false,"변경하고자하는 비밀번호가 서로 일치하지 않습니다."]);
openModal();
}
else {
let requestChangePw = JSON.stringify({
action: ACTION.MANAGE_DEVICE,
manageDevice: {
oldPassword: originPw,
newPassword: newPw
}
});
sendMessage(requestChangePw);
}
}, 500);
}
return (
<div className="rootWrap">
<LoadingAnimation bIsRender={bRenderLoading}></LoadingAnimation>
<Modal open={modalOpen} onCancel={cancelModal} onConfirm={closeModal} header="비밀번호 변경" confirm="확인">
{modalStatus[1]}
</Modal>
<div className="logoWrap">
<div className="logoImg"></div>
</div>
<div className="pwInputWrap">
<p>사이니지 컨트롤 접속 비밀번호 변경</p>
<div className="pwInpWrap">
<div className="pwInpImgWrap">
<div className="pwInpImg"></div>
</div>
<div className="pwInp">
<input type="password" name="originPw"
value={originPw || ''}
onChange={onValueChange}
placeholder="현재 비밀번호"/>
<input type="password" name="newPw"
value={newPw || ''}
onChange={onValueChange}
placeholder="새 비밀번호"/>
<input type="password" name="confirmPw"
value={confirmPw || ''}
onChange={onValueChange}
placeholder="비밀번호 확인"/>
</div>
</div>
<button onClick={changeDevicePassword}>변경</button>
</div>
</div>
);
}
export default ChangeDevicePW;
|
import React from 'react'
import renderer from 'react-test-renderer'
import 'jest-styled-components'
import CardBackground from './CardBackground'
describe('CardBackground', () => {
const component = renderer.create(<CardBackground>Press Me</CardBackground>)
it('renders corrctly', () => {
expect(component.toJSON()).toMatchSnapshot()
})
})
|
'use strict';
var _ = require('lodash');
module.exports = _.extend(exports, {
internal_system_error: {type: 'internal_system_error', message: 'internal system error', zh_message: '系统内部错误'},
invalid_email: {type: 'invalid_email', message: 'invalid email', zh_message: '邮箱格式不正确'},
invalid_account: {type: 'invalid_account', message: 'the account is invalid', zh_message: '无效账户'},
invalid_password: {type: 'invalid_password', message: 'the password\'s format is incorrect', zh_message: '无效密码'},
account_group_not_exist: {type: 'account_group_not_exist', message: 'the account group is not exist', zh_message: '用户组不存在'},
account_group_deleted: {type: 'account_group_deleted', message: 'the account group is deleted', zh_message: '用户组已删除'},
account_not_match: {type: 'account_not_match', message: 'the account is not match', zh_message: '账户不匹配'},
password_wrong: {type: 'password_wrong', message: 'the account password is wrong', zh_message: '密码错误'},
account_not_exist: {type: 'account_not_exist', message: 'the account is not exist', zh_message: '账户不存在'},
account_existed: {type: 'account_existed', message: 'the account has been existed', zh_message: '账户已存在'},
account_deleted: {type: 'account_deleted', message: 'the account has been deleted', zh_message: '账户已删除'},
invalid_access_token: {type: 'invalid_access_token', message: 'the access token invalid', zh_message: '无效访问凭据'},
param_null_error: {type: 'param_null_error', message: 'the param is null', zh_message: '参数为空'},
database_save_error: {type: 'database_save_error', message: 'the database save error', zh_message: '数据库保存出错'},
account_group_name_null: {type: 'account_group_name_null', message: 'the account group name is null!'},
firm_user_id_null: {type: 'firm_user_id_null', message: 'the account id is null', zh_message: '用户firm_id为空'},
invalid_old_password: {type: 'invalid_old_password', message: 'the account old password is invalid', zh_message: '无效旧密码'},
invalid_new_password: {type: 'invalid_new_password', message: 'the account new password is invalid', zh_message: '无效新密码'},
database_query_error: {type: 'database_query_error', message: 'the database query error', zh_message: '数据库查询出错'},
not_super_admin: {type: 'not_super_admin', message: 'you are not super admin', zh_message: '你不是管理员'},
user_not_exist: {type: 'user_not_exist', message: 'User is not exist', zh_message: '该用户不存在'},
invitation_code_not_exist: {type: 'invitation_code_not_exist', message: 'The invitation code is not exist', zh_message: '该邀请码不存在'},
invitation_code_exist: {type: 'invitation_code_exist', message: 'You have fill the invitation code', zh_message: '邀请码已填写'},
not_invite_each_other: {type: 'not_invite_each_other', message: 'You are not invited each other', zh_message: '不能相互邀请'},
not_invited_by_freshman: {type: 'not_invited_by_freshman', message: 'You can not invited by a freshman', zh_message: '填入的邀请码用户为新手'},
invalid_user_id: {type: 'invalid_user_id', message: 'The user_id is invalid', zh_message: '无效的用户id'},
params_parse_error: {type: 'params_parse_error', message: 'The params parse error', zh_message: '参数解析错误'}
});
|
'use strict';
// ---------------------------------------------------------------------
// Dependencies
// ---------------------------------------------------------------------
var gulp = require('gulp');
var tasks = require('cibulka-gulp-tasks').task;
var config = require('cibulka-gulp-tasks').config({
base: __dirname + '/'
});
// ---------------------------------------------------------------------
// Tasks
// ---------------------------------------------------------------------
gulp.task('sass', function() {
var options = {};
options.useRuby = true;
tasks('sass', options, config);
});
gulp.task('headers', function() {
tasks('headers', {}, config);
});
gulp.task('images', function() {
var options = {};
options.useResize = true;
options.imageres = require(config.theme).img;
options.useSvg2png = true;
tasks('images', options, config);
});
gulp.task('sprites', function() {
var options = {};
options.removeFill = true;
tasks('sprites', options, config);
});
gulp.task('jsonSass', function() {
tasks('sass-json', {}, config);
});
gulp.task('scripts', function() {
tasks('scripts', {
jsHint: ['main.js']
}, config);
});
// ---------------------------------------------------------------------
// Tasks bundles
// ---------------------------------------------------------------------
gulp.task('build', function() {
process.chdir(__dirname);
// Sass
gulp.start('sass', ['jsonSass']);
// Headers
gulp.start('headers');
// Images
gulp.start('images');
gulp.start('sprites');
// Scripts
gulp.start('scripts');
});
gulp.task('default', function() {
process.chdir(__dirname);
gulp.start('build');
gulp.watch(config.src.sass + '/*.scss', ['sass']);
gulp.watch(config.pkg, ['headers']);
gulp.watch(config.src.js + '/*.js', ['scripts']);
});
|
require(['config'],function(){
require(['jquery','swipeslider'],function($,a){
// ===========轮播图=====================
var $x_main = $('#x_main');
$x_main.find('#banner').swipeslider();
// $x_main.find('#banner').css({'margin-top':'-50%'})
$x_main.find('.sw-next-prev').css({'display':'none'})
// ==========回到顶部===========
// var $go_back = $('.go_back');
// $x_main.scroll( function() {
// var scrollValue = $x_main.scrollTop();
// scrollValue > 100 ? $go_back.fadeIn() : $go_back.fadeOut();
// } );
// $go_back.click(function(){
// $x_main.animate({scrollTop:0}, 500);
// });
//==============点击二维码出现遮罩层============
// var $x_header = $('#x_header');
// // 遮罩层
// var $div = $('<div/>')
// $div.css({
// 'display':'none',
// 'width':$(document.body).width(),
// 'height':$(document.body).height(),
// 'background-color':'rgba(0,0,0,.7)',
// 'position':'absolute',
// 'left':'0',
// 'top':'0',
// 'z-index':'7'
// })
// $x_header.find('.left').on('click',function(){
// $x_main.find('.code').css({
// 'display':'block'
// })
// $div.css({'display':'block'}).appendTo('#daishu').on('click',function(){
// $x_main.find('.code').css({'display':'none'})
// $(this).css({'display':'none'})
// })
// })
});
});
|
import * as lfo from 'waves-lfo/client';
import * as controllers from 'basic-controllers';
const valueController = new controllers.Text({
label: 'frame.data[0]',
default: '',
readonly: true,
container: '#controllers'
});
// Markers
const eventIn = new lfo.source.EventIn({
frameType: 'scalar',
frameRate: 1,
});
const markerDisplay = new lfo.sink.MarkerDisplay({
canvas: '#marker',
duration: 5,
});
const bridge = new lfo.sink.Bridge({
processFrame: (frame) => valueController.value = frame.data[0],
});
eventIn.connect(markerDisplay);
eventIn.connect(bridge);
eventIn.start();
let time = 0;
const period = 1;
(function generateData() {
eventIn.process(time, Math.random());
time += period;
setTimeout(generateData, period * 1000);
}());
new controllers.Slider({
label: 'threshold',
min: 0,
max: 1,
step: 0.001,
default: 0,
size: 'default',
container: '#controllers',
callback: (value) => markerDisplay.params.set('threshold', value),
});
new controllers.Slider({
label: 'duration',
min: 1,
max: 20,
step: 0.1,
default: 1,
size: 'default',
container: '#controllers',
callback: (value) => markerDisplay.params.set('duration', value),
});
new controllers.Slider({
label: 'width',
min: 300,
max: 400,
step: 1,
default: 300,
size: 'default',
container: '#controllers',
callback: (value) => markerDisplay.params.set('width', value),
});
new controllers.Slider({
label: 'height',
min: 150,
max: 200,
step: 1,
default: 150,
size: 'default',
container: '#controllers',
callback: (value) => markerDisplay.params.set('height', value),
});
|
'use strict';
require('dotenv').config();
const joi = require('@hapi/joi');
const portSchema = joi
.number()
.port()
.required();
const PORT = joi.attempt(process.env.REST_PORT, portSchema);
module.exports = {
PORT
};
|
import { reqserver } from '../../../api/index';
import * as actionType from './constants.js';
export const getServerLeftRightData = () => {
return (dispatch) => {
reqserver().then((res) => {
if (res.data.success) {
dispatch(changeServerLeftRightData(res.data.data))
} else {
console.log("失败", res);
}
}).catch((e) => {
console.log("服务页面数据请求错误!");
})
}
};
export const changeServerLeftRightData = (data) => {
return {
type: actionType.CHANGE_SERVER_DATA,
data: data
}
}
|
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { Col, Row, Container } from "../components/Grid";
import Jumbotron from "../components/Jumbotron/Jumbotron";
import API from "../utils/API";
import Navbar1 from "../components/Navbar1/Navbar1";
function CompletedProjects(props) {
const [projectForm, setProjectForm] = useState({})
const {id} = useParams()
useEffect(() => {
API.getProjectForm(id)
.then(res => setProjectForm(res.data))
.catch(err => console.log(err));
}, [id])
return (
<Container fluid>
<Navbar1/>
<Row>
<Col size="md-12">
<Jumbotron>
<h1>Great Job,
{projectForm.username}! Your Hard Work Will Pay Off!
</h1>
</Jumbotron>
</Col>
</Row>
<Row>
<Col size="md-12">
<Jumbotron>
<h1>
{projectForm.projectname} is a tough project.
</h1>
</Jumbotron>
</Col>
</Row>
<Jumbotron>
<Row>
<Col size="md-12">
<p>
<Link to="/profile"><h2>← Back to My Profile</h2></Link>
</p>
</Col>
</Row>
</Jumbotron>
<Row>
<Col size="md-2">
</Col>
</Row>
</Container>
);
}
export default CompletedProjects;
|
const source = './src';
const destination = './dist';
const deploy = {
host: "",
user: "",
pass: ""
}
module.exports = {
css_source: source + '/sass/*.sass',
css_dest: destination + '/css/',
js_source: source + '/js/',
js_main: 'main.js',
js_dest: destination + '/js/',
images_source: source + '/assets/images/**/*',
images_dest: destination + '/assets/images/',
fonts_source: source + '/assets/fonts/**/*',
fonts_dest: destination + '/assets/fonts/',
pug_source: source + '/pug/*.pug',
pug_dest: destination + '/',
css_watch: source + '/sass/**/*.sass',
js_watch: source + '/js/**/*.js',
images_watch: source + '/assets/images/**/*.*',
icons_watch: source + '/assets/icons/**/*.*',
fonts_watch: source + '/assets/fonts/**/*.*',
pug_watch: source + '/**/*.pug',
destination: destination,
deploy: deploy
}
|
import React from "react";
import styled, { css } from "styled-components";
export const Root = styled.main`
display: flex;
flex-direction: column;
justify-content: center;
height: 80vh;
width: 70vw;
`;
const CSSReset = css`
padding: 0;
margin: 0;
outline: 0;
`;
const Title = styled.h1`
${CSSReset}
position: relative;
text-align: left;
font-size: 10rem;
padding: 0;
span {
position: relative;
z-index: 2;
}
&:after {
content: "";
background-color: #4699ff;
display: inline-block;
width: 65%;
height: 75%;
position: absolute;
bottom: 0;
left: 0;
z-index: 1;
transform: translateX(-10px);
}
`;
const Subtitle = styled.h2`
${CSSReset}
text-align: left;
`;
const Cover = () => {
return (
<Root>
<Title>
<span>React.js com TypeScript</span>
</Title>
<Subtitle>
<span>O que pode dar errado?</span>
</Subtitle>
</Root>
);
};
export default Cover;
|
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs');
const expect = chai.expect;
const assert = chai.assert;
const DriverToMdConverter = require('../index');
const converter = new DriverToMdConverter();
describe('convert()', () => {
const outputPath = './test/drivers/output.md';
before(async () => {
sinon.spy(converter, '_getDriver');
sinon.spy(converter, '_makeBaseInfo');
sinon.spy(converter, '_makeCommandsInfo');
sinon.spy(converter, '_makeDataInfo');
await converter.convert('./test/drivers/nexpaq.module.hat.driver.json', outputPath);
})
it('Calls getDriver() method', () => {
expect(converter._getDriver.callCount).to.be.equal(1);
});
it('Calls makeBaseInfo() method', () => {
expect(converter._makeBaseInfo.callCount).to.be.equal(1);
});
it('Calls makeCommandsInfo() method', () => {
expect(converter._makeCommandsInfo.callCount).to.be.equal(1);
});
it('Calls makeDataInfo() method', () => {
expect(converter._makeDataInfo.callCount).to.be.equal(1);
});
it('Saves result to output file', async () => {
fs.unlinkSync(outputPath);
await converter.convert('./test/drivers/nexpaq.module.hat.driver.json', outputPath);
let exception = null;
try {
fs.accessSync(outputPath);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal(null);
});
after(() => {
converter._getDriver.restore();
converter._makeBaseInfo.restore();
converter._makeCommandsInfo.restore();
converter._makeDataInfo.restore();
});
});
describe('getDriver()', () => {
it('Incorrect path should trigger not found exception', async () => {
let exception;
try {
await converter._getDriver('./driver.json');
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('File ./driver.json not found');
});
it('Unreadable json should trigger bad format exception', async () => {
let exception;
try {
await converter._getDriver('./test/drivers/bad_json_driver.json');
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: can\'t parse');
});
it('Missing type or version should trigger bad format exception', async () => {
let exception;
try {
await converter._getDriver('./test/drivers/empty_object_driver.json');
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: no type or version');
});
it('Correct path should return driver object', async () => {
const driver = await converter._getDriver('./test/drivers/moduware.module.led.driver.json');
assert.isObject(driver);
});
});
describe('makeBaseInfo()', () => {
const driversListLink = "https://moduware.github.io/developer-documentation/module-drivers/";
let driver;
let baseInfo;
before(async () => {
driver = await converter._getDriver('./test/drivers/moduware.module.led.driver.json');
baseInfo = converter._makeBaseInfo(driver);
});
it('Info contains type and version of driver', () => {
expect(baseInfo).to.contain(driver.type);
expect(baseInfo).to.contain(driver.version);
});
it('Contains link to drivers list', () => {
expect(baseInfo).to.contain(driversListLink);
});
});
describe('Driver Commands', () => {
describe('makeCommandsInfo()', () => {
let driver;
let commandsInfo;
before(async () => {
driver = await converter._getDriver('./test/drivers/moduware.module.led.driver.json');
commandsInfo = converter._makeCommandsInfo(driver);
});
it('Driver without commands return empty string', async () => {
const noCommandsDriver = await converter._getDriver('./test/drivers/no_commands_no_data_driver.json');
const commandsInfo = converter._makeCommandsInfo(noCommandsDriver);
expect(commandsInfo).to.be.equal('');
});
it('Outputs title or name for every command', () => {
for(let command of driver.commands) {
expect(commandsInfo).to.contain(command.title || command.name);
}
});
it('Outputs correct example for command without arguments', () => {
const correctCommandWithoutArgumentsExample = "Moduware.v0.API.Module.SendCommand(Moduware.Arguments.uuid, 'TurnOffLeds', []);";
expect(commandsInfo).to.contain(correctCommandWithoutArgumentsExample);
});
it('Outputs correct example for command with arguments', () => {
const correctCommandWithArgumentsExample = "Moduware.v0.API.Module.SendCommand(Moduware.Arguments.uuid, 'SetRGB', [<Red>, <Green>, <Blue>]);";
expect(commandsInfo).to.contain(correctCommandWithArgumentsExample);
});
it('Outputs table with command info', () => {
const commandInfoTable = `Name | Description | Validation
-------------- | -------------- | --------------
Red | - | (**value** >= 0) and (**value** <= 255)
Green | - | (**value** >= 0) and (**value** <= 255)
Blue | - | (**value** >= 0) and (**value** <= 255)`;
expect(commandsInfo).to.contain(commandInfoTable);
});
it('Outputs command description', () => {
for(let command of driver.commands) {
if(typeof command.description != 'undefined') {
expect(commandsInfo).to.contain(command.command);
}
}
});
it('Missing command name should trigger bad format exception', async () => {
const missingCommandNameDriver = await converter._getDriver('./test/drivers/missing_command_name_driver.json')
let exception;
try {
converter._makeCommandsInfo(missingCommandNameDriver);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: command missing name');
});
it('Missing message type should trigger bad format exception', async () => {
const missingMessageTypeDriver = await converter._getDriver('./test/drivers/missing_message_type_driver.json')
let exception;
try {
converter._makeCommandsInfo(missingMessageTypeDriver);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: command missing message type');
});
it('Calls makeCommandsArgumentsInfo() for every command', () => {
sinon.spy(converter, '_makeCommandsArgumentsInfo');
converter._makeCommandsInfo(driver);
expect(converter._makeCommandsArgumentsInfo.callCount).to.be.equal(driver.commands.length);
converter._makeCommandsArgumentsInfo.restore();
});
});
describe('renderArgumentsForExample()', () => {
let driver;
before(async () => {
driver = await converter._getDriver('./test/drivers/moduware.module.led.driver.json');
});
it('Command without arguments will return empty string', () => {
const commandWithoutArguments = driver.commands[1];
const commandArgumentsExample = converter._renderArgumentsForExample(commandWithoutArguments);
expect(commandArgumentsExample).to.be.equal('');
});
it('Outputs correct example arguments string', () => {
const commandWithArguments = driver.commands[0];
const correctArgumentsExample = `<Red>, <Green>, <Blue>`;
const commandArgumentsExample = converter._renderArgumentsForExample(commandWithArguments);
expect(commandArgumentsExample).to.be.equal(correctArgumentsExample);
});
it('Missing argument name should trigger bad format exception', async () => {
const driverWithMissingArgumentName = await converter._getDriver('./test/drivers/missing_argument_name_driver.json');
const command = driverWithMissingArgumentName.commands[0];
let exception;
try {
converter._renderArgumentsForExample(command);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal(`Bad file format: argument of command '${command.name}' missing name`);
});
});
describe('makeCommandsArgumentsInfo()', () => {
let driver;
before(async () => {
driver = await converter._getDriver('./test/drivers/moduware.module.led.driver.json');
});
it('Command without arguments will return empty string', () => {
const commandWithoutArguments = driver.commands[1];
const commandWithoutArgumentsInfo = converter._makeCommandsArgumentsInfo(commandWithoutArguments);
expect(commandWithoutArgumentsInfo).to.be.equal('');
});
it('Outputs name and description for every argument', () => {
const commandWithArguments = driver.commands[3];
const argumentsInfo = converter._makeCommandsArgumentsInfo(commandWithArguments);
for(let argument of commandWithArguments.arguments) {
expect(argumentsInfo).to.contain(argument.name);
if(typeof argument.description != 'undefined') {
expect(argumentsInfo).to.contain(argument.description);
}
}
});
it('Calls formatArgumentValidation() for every argument that has validation', () => {
sinon.spy(converter, '_formatArgumentValidation');
let argumentsWithValidation = 0;
for(let command of driver.commands) {
if(typeof command.arguments != 'undefined') {
for(let argument of command.arguments) {
if(typeof argument.validation != 'undefined') argumentsWithValidation++;
}
}
converter._makeCommandsArgumentsInfo(command);
}
expect(converter._formatArgumentValidation.callCount).to.be.equal(argumentsWithValidation);
converter._formatArgumentValidation.restore();
});
it('Outputs none if there are no validation and - if there are no description', async () => {
const driverWithArgumentWithoutDescriptionAndValidation = await converter._getDriver('./test/drivers/nexpaq.module.hat.driver.json');
const command = driverWithArgumentWithoutDescriptionAndValidation.commands[2];
const argumentsInfo = converter._makeCommandsArgumentsInfo(command);
expect(argumentsInfo).to.contain(' none');
expect(argumentsInfo).to.contain(' - ');
});
});
describe('formatArgumentValidation()', () => {
it('Convert argument validation to human readable format', () => {
const validationString = '({0} >= 0) and ({0} <= 5)';
const correctFormattedValidationString = '(**value** >= 0) and (**value** <= 5)';
const formattedValidationString = converter._formatArgumentValidation(validationString);
expect(formattedValidationString).to.be.equal(correctFormattedValidationString);
});
});
});
describe('Driver Data', () => {
describe('makeDataInfo()', () => {
let driver;
let dataInfo;
before(async () => {
driver = await converter._getDriver('./test/drivers/nexpaq.module.hat.driver.json');
dataInfo = converter._makeDataInfo(driver);
});
it('Driver without data return empty string', async () => {
const driverWithoutData = await converter._getDriver('./test/drivers/no_commands_no_data_driver.json');
const dataInfo = converter._makeDataInfo(driverWithoutData);
expect(dataInfo).to.be.equal('');
});
it('Output title and name for every data field', () => {
for(let dataField of driver.data) {
expect(dataInfo).to.contain(dataField.title);
expect(dataInfo).to.contain(dataField.name);
}
});
it('Missing data field name should trigger bad format exception', async () => {
const driverWithMissingDataName = await converter._getDriver('./test/drivers/missing_datafield_name_driver.json');
let exception;
try {
converter._makeDataInfo(driverWithMissingDataName);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: data field missing name');
});
it('Missing data field source should trigger bad format exception', async () => {
const driverWithMissingDataSource = await converter._getDriver('./test/drivers/missing_datafield_source_driver.json');
let exception;
try {
converter._makeDataInfo(driverWithMissingDataSource);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal('Bad file format: data field missing source');
});
it('Contains if statement in JS example', () => {
const jsIfStatementExampleCode = `console.log(event.variables.ambient_temperature);`;
expect(dataInfo).to.contain(jsIfStatementExampleCode);
});
it('Contains table with info field info', () => {
const dataInfoTable = `Data Name | Message Type
-------------- | --------------
SensorStateChangeResponse | 2701`;
expect(dataInfo).to.contain(dataInfoTable);
});
it('Contains info field description', () => {
for(let dataField of driver.data) {
if(typeof dataField.description == 'undefined') {
expect(dataInfo).to.contain(dataField.description);
}
}
});
it('Calls makeDataVariablesInfo() for every data field', () => {
sinon.spy(converter, '_makeDataVariablesInfo');
converter._makeDataInfo(driver);
expect(converter._makeDataVariablesInfo.callCount).to.be.equal(driver.data.length);
converter._makeDataVariablesInfo.restore();
});
});
describe('makeDataVariablesInfo()', () => {
let driver;
before(async () => {
driver = await converter._getDriver('./test/drivers/nexpaq.module.hat.driver.json');
});
it('Data field without variables will return empty string', async () => {
const driver = await converter._getDriver('./test/drivers/datadield_without_variables_driver.json');
const dataVariablesInfo = converter._makeDataVariablesInfo(driver.data[0]);
expect(dataVariablesInfo).to.be.equal('');
});
it('Calls makeDataVariablesExample()', () => {
sinon.spy(converter, '_makeDataVariablesExample');
converter._makeDataVariablesInfo(driver.data[0]);
expect(converter._makeDataVariablesExample.callCount).to.be.equal(1);
});
it('Outputs name, title and description for every variable', () => {
const dataField = driver.data[2];
const dataVariablesInfo = converter._makeDataVariablesInfo(dataField);
for(let variable of dataField.variables) {
expect(dataVariablesInfo).to.contain(variable.name);
if(typeof variable.title != 'undefined') {
expect(dataVariablesInfo).to.contain(variable.title);
}
if(typeof variable.description != 'undefined') {
expect(dataVariablesInfo).to.contain(variable.description);
}
}
});
it('Missing variable name should trigger bad format exception', async () => {
const driver = await converter._getDriver('./test/drivers/variable_without_name_driver.json');
const dataField = driver.data[0];
let exception;
try {
converter._makeDataVariablesInfo(dataField);
} catch(e) {
exception = e;
}
expect(exception).to.be.equal(`Bad file format: variable of ${dataField.name} missing name`);
});
it('Outputs - instead of title and description if they are not specified', async () => {
const driver = await converter._getDriver('./test/drivers/variable_without_title_and_description_driver.json');
const dataField = driver.data[0];
const dataVariablesInfo = converter._makeDataVariablesInfo(dataField);
expect(dataVariablesInfo).to.contain(' - ');
expect(dataVariablesInfo).to.contain(' -');
});
it('Outputs * if variable has no states', () => {
const dataField = driver.data[2];
const dataVariablesInfo = converter._makeDataVariablesInfo(dataField);
expect(dataVariablesInfo).to.contain('| *');
});
it('Outputs all possible states if they are specified for a variable', () => {
const dataField = driver.data[1];
const dataVariablesInfo = converter._makeDataVariablesInfo(dataField);
const states = Object.values(dataField.variables[0].state);
for(let state of states) {
expect(dataVariablesInfo).to.contain(state);
}
})
});
describe('makeDataVariablesExample()', () => {
let driver;
before(async () => {
driver = await converter._getDriver('./test/drivers/nexpaq.module.hat.driver.json');
});
it('Data field without variables will return empty string', async () => {
const driver = await converter._getDriver('./test/drivers/datadield_without_variables_driver.json');
const dataField = driver.data[0];
const dataVariablesExample = converter._makeDataVariablesExample(dataField);
expect(dataVariablesExample).to.be.equal('');
});
it('Output console.log for all variables without states', () => {
const dataField = driver.data[2];
const dataVariablesExample = converter._makeDataVariablesExample(dataField);
for(let variable of dataField.variables) {
if(typeof variable.state == 'undefined') {
expect(dataVariablesExample).to.contain(`console.log(event.variables.${variable.name});`);
}
}
});
it('Output switch for all variables with states', () => {
const dataField = driver.data[1];
const dataVariablesExample = converter._makeDataVariablesExample(dataField);
expect(dataVariablesExample).to.contain(`switch(event.variables.${dataField.variables[0].name}) {`);
});
it('Outputs state cases for every variable with states', () => {
const dataField = driver.data[1];
const dataVariablesExample = converter._makeDataVariablesExample(dataField);
const stateCases = Object.values(dataField.variables[0].state).map(state => `case '${state}':`);
for(let stateCase of stateCases) {
expect(dataVariablesExample).to.contain(stateCase);
}
});
});
});
|
require('./config/config');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose');
var {Hotel} = require('./models/hotel');
var {User} = require('./models/user');
var app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.post('/hotels', (req, res) => {
const {name, stars, price, detail} = req.body;
var hotel = new Hotel({
name, stars, price, detail
});
hotel.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.get('/hotels', (req, res) => {
Hotel.find().then((list) => {
var hotels = list.reduce(
(acum, item) => {
const {_id, name, price, stars, detail} = item;
const image = detail.images[0]
const hotel = {_id, name, price, stars, image}
return [...acum, hotel ];
},[]);
res.send({hotels});
}, (e) => {
res.status(400).send(e);
});
});
app.get('/hotels/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Hotel.findById(id).then((hotel) => {
if (!hotel) {
return res.status(404).send();
}
res.send({hotel});
}).catch((e) => {
res.status(400).send();
});
});
app.delete('/hotels/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Hotel.findByIdAndRemove(id).then((hotel) => {
if (!hotel) {
return res.status(404).send();
}
res.send({hotel});
}).catch((e) => {
res.status(400).send();
});
});
app.patch('/hotels/:id', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['text', 'completed']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
if (_.isBoolean(body.completed) && body.completed) {
body.completedAt = new Date().getTime();
} else {
body.completed = false;
body.completedAt = null;
}
Hotel.findByIdAndUpdate(id, {$set: body}, {new: true}).then((hotel) => {
if (!hotel) {
return res.status(404).send();
}
res.send({hotel});
}).catch((e) => {
res.status(400).send();
})
});
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
|
import React, { Component } from 'react';
import Countdown from "./components/Countdown.jsx";
import logo from "./images/loadingPage.png";
import "./styling/loadingpage.css";
class LoadingPage extends Component {
render() {
return (
<div className="loadingPage">
<h2 className="titleLoadingPage"> Jenny & Stephen Wedding </h2>
<h3 className="loadingText"> l o a d i n g . . . </h3>
<img className="logoLoading" src={logo} alt="JS logo" />
<Countdown />
</div>
)
}
}
export default LoadingPage;
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueCookies from 'vue-cookies'
import qs from 'qs'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue
.use(VueAxios,axios)
.use(qs)
.use(VueCookies)
// this.$cookies.config('7d','/')
Vue.config.productionTip = false
//配置请求头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
import 'lib-flexible/flexible'
import {
Button,
Divider,
Collapse,
CollapseItem,
Popup,
NavBar,
Toast,
Dialog,
DropdownMenu,
DropdownItem,
Popover,
Loading
} from 'vant';
Vue
.use(Button)
.use(Divider)
.use(Collapse)
.use(CollapseItem)
.use(NavBar)
.use(Popup)
.use(Toast)
.use(Dialog)
.use(DropdownMenu)
.use(DropdownItem)
.use(Popover)
.use(Loading)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
router.beforeEach((to,from,next)=>{
next()
})
|
module.exports = function(Handcraft) {
Handcraft.beforeRemote('create', function(context, user, next) {
context.args.data.customerId = context.req.accessToken.userId;
next();
});
};
|
const {Op} = require("sequelize");
var express = require('express');
var router = express.Router();
const models = require("../../../../models");
const errors = require("../../../errors");
const ResponseTemplate = require("../../../ResponseTemplate");
const SequelizeUtil = require("../../../../util/SequelizeUtil");
const SimpleValidators = require("../../../../util/SimpleValidators");
const TypeChecker = require("../../../../util/TypeChecker");
const {asyncFunctionWrapper} = require("../../util");
router.get('', asyncFunctionWrapper(getAllSecretaries));
router.post('', asyncFunctionWrapper(addSecretary));
router.use('/:userId', (req, res, next) => {
req.secretaryInfo = {
userId: req.params.userId,
};
next();
})
router.get('/:userId', asyncFunctionWrapper(getSecretary));
router.put('/:userId', asyncFunctionWrapper(updateSecretary));
router.delete('/:userId', asyncFunctionWrapper(removeSecretary));
async function getAllSecretaries(req, res, next) {
let secretaries = await models.Admin.findSecretaries(req.principal.userId);
const response = ResponseTemplate.create()
.withData({
secretaries: secretaries,
})
.toJson();
res.json(response);
}
async function getSecretary(req, res, next) {
const secretaryUserId = req.params.userId;
const admin = await models.Admin.findOne(
{
where: {
userId: req.principal.userId
},
include: ['workPlaces']
}
);
if (admin == null) {
next(new errors.AdminNotFound());
return;
}
const secretary = await models.Secretary.findOne({
where: {
userId: secretaryUserId,
},
include: ['workPlaces'],
});
const sharesWorkPlace = secretary.workPlaces
.some(secretaryWorkPlace => admin.workPlaces.some(adminWorkPlace => adminWorkPlace.placeId == secretaryWorkPlace.placeId));
if (!sharesWorkPlace) {
next(new errors.SecretaryNotFound());
return;
}
const response = ResponseTemplate.create()
.withData({
secretary: secretary,
})
.toJson();
res.json(response);
}
async function addSecretary(req, res, next) {
const secretaryInfo = req.body.secretary;
if (!TypeChecker.isObject(secretaryInfo)) {
next(new errors.IncompleteRequest("Secretary info was not provided."));
return;
}
else if (!SimpleValidators.isNonEmptyString(secretaryInfo.nationalId)) {
next(new errors.IncompleteRequest("Field {nationalId} was not provided."));
return;
}
const secretary = await models.Secretary.findOne(
{
where: {
nationalId: secretaryInfo.nationalId
},
}
);
if (secretary != null) {
next(new errors.AlreadyExistsException("A secretary with this national id already exists"));
return;
}
const admin = await models.Admin.findOne(
{
where: {
userId: req.principal.userId
},
include: ['workPlaces']
}
);
if (admin == null) {
next(new errors.AdminNotFound());
return;
}
else if (admin.workPlaces.length == 0) {
next(new errors.IllegalOperation('You need to have a workplace before being able to add secretaries.'));
return;
}
const placeId = SimpleValidators.hasValue(req.query.placeId) ? req.query.placeId : admin.workPlaces[0].id;
const adminHasThePlace = admin.workPlaces.some(workPlace => Number(workPlace.id) == Number(placeId));
if (!adminHasThePlace) {
next(new errors.NotFound("You do not work at the place with the specified id"));
return;
}
delete secretaryInfo.id;
delete secretaryInfo.userId;
delete secretaryInfo.userInfo;
await models.Secretary.sequelize.transaction(async (tr) => {
let createdUserInfo = await models.User.createSecretary(secretaryInfo.nationalId, tr);
secretaryInfo.userId = createdUserInfo.userId;
let createdSecretary = await models.Secretary.create(secretaryInfo, {transaction: tr});
createdSecretary = createdSecretary.get({plain: true});
let createdPlace = await models.UserPlace.createPlace(createdSecretary.userId, placeId, tr);
createdSecretary.userInfo = createdUserInfo;
const response = ResponseTemplate.create()
.withData({
secretary: createdSecretary,
place: createdPlace,
});
res.json(response);
return;
})
}
async function updateSecretary(req, res, next) {
const secretaryInfo = req.body.secretary;
const secretaryUserId = req.secretaryInfo.userId;
if (!TypeChecker.isObject(secretaryInfo)) {
next(new errors.IncompleteRequest("Secretary info was not provided."));
return;
}
else if (!SimpleValidators.isNonEmptyString(secretaryInfo.nationalId)) {
next(new errors.IncompleteRequest("Field {nationalId} was not provided."));
return;
}
else if (!SimpleValidators.isNonEmptyString(secretaryUserId)) {
next(new errors.IncompleteRequest("Field {userId} was not provided."));
return;
}
const secretary = await models.Secretary.findOne(
{
where: {
userId: secretaryUserId,
},
}
);
if (!secretary) {
next(new errors.SecretaryNotFound("No secretary was found with the provided userId"));
return;
}
delete secretaryInfo.userInfo;
secretaryInfo.userId = secretary.userId;
secretaryInfo.id = secretary.id;
await models.Secretary.update(
secretaryInfo,
{
where: {
userId: secretary.userId,
},
returning: true,
}
);
let savedSecretary = await secretary.reload({include: ['workPlaces']});
const response = ResponseTemplate.create()
.withData({
secretary: savedSecretary,
});
res.json(response);
return;
}
async function removeSecretary(req, res, next) {
next(new errors.IllegalOperation("Not implemented"));
return;
const secretaryUserId = req.secretaryInfo.userId;
await models.Secretary.sequelize.transaction(async (tr) => {
const response = ResponseTemplate.create()
.withMessage("Secretary was removed from system.")
.toJson();
res.json(response);
});
}
models.Admin.findSecretaries = async function (adminUserId) {
if (!SimpleValidators.isNumber(adminUserId))
throw new Error("Admin user id must be a number");
const workPlaces = await models.UserPlace.findAll(
{
where: {
userId: adminUserId,
}
},
);
if (!workPlaces || !workPlaces.length) return [];
const sharedUserPlaces = await models.UserPlace.findAll(
{
where: {
placeId: {
[Op.in]: workPlaces.map(workPlace => workPlace.placeId),
[Op.ne]: adminUserId,
},
}
}
)
const distinctSharedUserPlaces = sharedUserPlaces.filter((tag, index, array) => array.findIndex(t => t.userId == tag.userId) == index);
if (!distinctSharedUserPlaces || !distinctSharedUserPlaces.length)
return [];
const secretaries = await models.Secretary.findAll(
{
where: {
userId: {
[Op.in]: distinctSharedUserPlaces.map(userPlace => userPlace.userId)
}
},
include: ['workPlaces']
}
);
return secretaries || [];
}
module.exports = router;
|
export default class Vector2 {
static Unit() {
return new Vector2(1, 1)
}
static Zero() {
return new Vector2(0, 0)
}
static Left() {
return new Vector2(-1, 0)
}
static Right() {
return new Vector2(1, 0)
}
static Up() {
return new Vector2(0, -1)
}
static Down() {
return new Vector2(0, 1)
}
static FromArray(arr) {
return new Vector2(arr[0], arr[1])
}
static FromObject(obj) {
return new Vector2(obj.x, obj.y)
}
static Random(scale = 1) {
return new Vector2(Math.random() * scale, Math.random() * scale)
}
static Clone(vector) {
return new Vector2(vector.x, vector.y)
}
static Add(v1, v2) {
return new Vector2(v1.x + v2.x, v1.y + v2.y)
}
static Sub(v1, v2) {
return new Vector2(v1.x - v2.x, v1.y - v2.y)
}
/**
* Calculate the distance between two vectors.
*
* @param v1
* @param v2
* @returns {number}
*/
static Distance(v1, v2) {
return Math.abs(Vector2.Sub(v1, v2).mag())
}
static Mult(v1, v2) {
return new Vector2(v1.x * v2.x, v1.y * v2.y)
}
static Div(v1, v2) {
return new Vector2(v1.x / v2.x, v1.y / v2.y)
}
static DivScalar(v, n) {
if (n === 0) {
console.warn("Vector2.DivScalar: division by zero")
return Vector2.Zero()
}
return new Vector2(v.x / n, v.y / n)
}
static Scale(v, s) {
return new Vector2(v.x * s, v.y * s)
}
/**
* @param v1
* @param v2
* @returns {number}
*/
static Dot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y
}
/**
* @param vecA
* @param vecB
* @returns {number}
*/
static AngleBetween(vecA, vecB) {
return Math.acos(vecA.dot(vecB) / (vecA.mag() * vecB.mag()))
}
constructor(x = 0, y = 0) {
this.x = x
this.y = y
}
clone() {
return new Vector2(this.x, this.y)
}
add(vector) {
this.x += vector.x
this.y += vector.y
return this
}
sub(vector) {
this.x -= vector.x
this.y -= vector.y
return this
}
scale(n) {
this.x *= n
this.y *= n
return this
}
dot(vector) {
return this.x * vector.x + this.y * vector.y
}
mult(vector) {
this.x *= vector.x
this.y *= vector.y
return this
}
div(vector) {
this.x /= vector.x
this.y /= vector.y
return this
}
divScalar(n) {
this.x /= n
this.y /= n
return this
}
normalize() {
const mag = this.mag()
const revMag = mag !== 0 ? 1 / mag : 1
this.x *= revMag
this.y *= revMag
return this
}
mag() {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
magSquare() {
return this.x * this.x + this.y * this.y
}
setMag(length) {
this.normalize()
this.scale(length)
return this
}
limit(limit) {
const mag = this.mag()
if (mag > limit) {
this.setMag(limit)
}
return this
}
toString() {
return `{ x: ${this.x}, y: ${this.y} }`
}
parseToInt() {
this.x = parseInt(this.x)
this.y = parseInt(this.y)
return this
}
toArray() {
return [this.x, this.y]
}
toObject() {
return { x: this.x, y: this.y }
}
equals(other) {
return this.x === other.x && this.y === other.y
}
angle() {
return Math.atan2(this.y, this.x)
}
rotateBy(angle) {
this.setAngle(this.angle() + angle)
return this
}
setAngle(angle) {
const r = this.mag()
this.x = r * Math.cos(angle)
this.y = r * Math.sin(angle)
return this
}
setTo(v) {
this.x = v.x
this.y = v.y
}
}
|
import React from "react"
import {
FacebookShareButton,
TwitterShareButton,
LineShareButton,
HatenaShareButton,
FacebookIcon,
TwitterIcon,
LineIcon,
HatenaIcon,
} from "react-share"
const Share = props => {
const articleTitle = props.title
const articleUrl = props.url
// const articleDescription = props.description // 現時点では未使用
const iconSize = 40
return (
<div className="share">
<p className="share__title">SHARE!</p>
<div className="social-links">
<div className="social-links__icon">
<TwitterShareButton url={articleUrl} title={articleTitle}>
<TwitterIcon round size={iconSize} />
</TwitterShareButton>
</div>
<div className="social-links__icon">
<FacebookShareButton url={articleUrl}>
<FacebookIcon round size={iconSize} />
</FacebookShareButton>
</div>
<div className="social-links__icon">
<LineShareButton url={articleUrl} title={articleTitle}>
<LineIcon round size={iconSize} />
</LineShareButton>
</div>
<div className="social-links__icon">
<HatenaShareButton url={articleUrl} title={articleTitle}>
<HatenaIcon round size={iconSize} />
</HatenaShareButton>
</div>
</div>
</div>
)
}
export default Share
|
define(function(require){
var React = require('react');
var ReactDom = require('react-dom');
var mat = require('materialize');
var Router = require('react-router').Router;
var Header = require('jsx!app/components/header');
var Footer = require('jsx!app/components/footer');
var Page = React.createClass({
getInitialState: function(){
var location = window.location.href.split('/');
var locationEnd = location[location.length - 1];
return {
title: "",
content: "",
loaded: false,
loc: locationEnd,
posts: [
{
post_title: "",
post_content: ""
},
{
post_title: "",
post_content: ""
},
{
post_title: "",
post_content: ""
},
{
post_title: "",
post_content: ""
}
],
}
},
componentWillMount: function(){
console.log(this.props);
},
componentDidMount: function(){
},
sortByKey: function(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
},
render: function(){
var location = window.location.href.split('/');
var locationEnd = location[location.length - 1];
if(!this.state.loaded){
for(var i = 0; i < this.props.posts.length; ++i){
var title = locationEnd.replace("%20", " ");
if(this.props.posts[i].post_title == title){
this.setState({
title: this.props.posts[i].post_title,
content: this.props.posts[i].post_content,
loaded: true
});
}
}
}
if(this.state.loaded){
console.log(this.state.title);
return (
<div id="wrapper">
<Header postData={this.state.posts} routeHandler={this.handleRoute}/>
<div className="container" key={locationEnd}>
<div className="row">
<div className="col s12 m6">
<div className="card blue-grey darken-1">
<div className="card-content white-text">
<span className="card-title">{this.state.title}</span>
<p>{this.state.content}</p>
</div>
<div className="card-action">
<a href="#">This is a link</a>
<a href="#">This is a link</a>
</div>
</div>
</div>
</div>
</div>
<Footer />
</div>
)
} else {
return (<div>loading...</div>);
}
}
});
return Page;
});
|
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
//class Square extends React.Component {
//parent component passes stated down to children by using props; keeps child components in sync with each other and parent
//add a constructor to initialize the state
// constructor(props) {
// super(props); //need to call a super when defining constructor of subclass; all react component classes have constructor that start with super(props)call
// this.state = {
// //this.state is private to a React component that it's defined in
// value: null,
// };
// }
//No longer need constructor because square no longer keeps track of the game
//render(i) {
//function components are a simpler way to write components that only contain render method and don't have their own state
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
// constructor(props) {
// super(props);
// this.state = {
// squares: Array(9).fill(null),
// xIsNext: true, //x is set as first move by default now (a boolean)
// };
// }
renderSquare(i) {
return (
//need parenthesis so JS doesn't insert ; and break code
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
//using two loops to make squares
const boardSize = 3;
let squares = [];
//outer loop runs one time
for (let i = 0; i < boardSize; i++) {
//inner loop runs three times
let row = [];
for (let j = 0; j < boardSize; j++) {
//adds a square each time (three squares to the row)
row.push(this.renderSquare(i * boardSize + j)); //the equation sets index number for square(0,1,2,3,4,5,6,7,8,9)
}
squares.push(
<div key={i} className="board-row">
{row}
</div>
);
}
return <div>{squares}</div>;
// const winner = calculateWinner(this.state.squares);
// let status;
// if (winner) {
// status = "Winner: " + winner;
// } else {
// status = "Next player: " + (this.state.xIsNext ? "X" : "O");
// }
// return (
// <div>
// <div className="board-row">
// {this.renderSquare(0)}
// {this.renderSquare(1)}
// {this.renderSquare(2)}
// </div>
// <div className="board-row">
// {this.renderSquare(3)}
// {this.renderSquare(4)}
// {this.renderSquare(5)}
// </div>
// <div className="board-row">
// {this.renderSquare(6)}
// {this.renderSquare(7)}
// {this.renderSquare(8)}
// </div>
// </div>
}
}
class Game extends React.Component {
//initialize state for the game component within it's constructor
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
},
],
stepNumber: 0,
xIsNext: true,
};
}
//Define handleClick
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice(); //.slice used to create a copy of squares array to modify
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([
{
squares: squares,
recentLocation: i,
},
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: step % 2 === 0,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const recentLocation = step.recentLocation;
const col = 1 + (recentLocation % 3);
const row = 1 + Math.floor(recentLocation / 3);
const desc = move
? "This was move #" + move + " taken at Col: " + col + ", Row: " + row
: "Go to game start";
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>
{/* If move is current step, return the move in bold into desc */}
{move === this.state.stepNumber ? <b>{desc}</b> : desc}
</button>
</li>
);
});
let status;
if (winner) {
status = "Winner: " + winner;
} else {
status = "Next player: " + (this.state.xIsNext ? "X" : "O");
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(<Game />, document.getElementById("root"));
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
serviceWorker.unregister();
|
import { useState, useEffect } from 'react'
import { getCharacterByName } from '../../services/characters/characterServices'
const useGetCharactersByName = (name) => {
const [data, setData] = useState([])
useEffect(() => {
getCharacterByName(name).then((resp) => {
setData(resp.data[0])
})
}, [name])
return data
}
export default useGetCharactersByName
|
$(function (){
$('.page-header').each(function (){
var $window = $(window),
$header = $(this),
headerOffsetTop = $header.offset().top;
$window.on('scroll',function(){
if($window.scrollTop()>headerOffsetTop) {
$header.addClass('sticky');
}
else {
$header.removeClass('sticky');
}
});
$window.trigger('scroll');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.