text
stringlengths
7
3.69M
import React, { Component } from 'react'; import {Link} from 'react-router-dom' import Chat from './Chat' import Groom from './Groom' import $ from 'jquery' class Vedioplay extends Component { constructor(props){ super(props) this.state={ "id":this.props.match.params.id, "res":[], "flag":1 } console.log(this.props.match.params.id) } componentDidMount(){ $.ajax({ type:"get", url:"https://room.api.m.panda.tv/index.php?callback=jQuery112409635895076665502_1523186948555&method=room.shareapi&roomid="+this.state.id, async:true, dataType:'jsonp', success:function(data){ console.log(data); var arr = []; arr.push(data.data); this.setState({ "res":arr }) console.log(this.state.res); }.bind(this) }); } excolor(x){ var tem = !x; this.setState({ "flag":tem }); } render() { return ( <div> <div className="playhead"> <div className="logo"><img src={"https://i.h2.pdim.gs/c1ce37e223711ac773cf78cd9410556a.png"} alt=""/></div> <Link className="return" to="/">返回</Link> </div> { this.state.res.map((val,ind) => ( <div className="play" key={ind}> <video src={val.videoinfo.address} controls width="100%" height="auto" poster={val.roominfo.pictures.img}></video> <div className="detail"> <p>{val.roominfo.name}</p> <p>{val.hostinfo.name}</p> <p>人气:{val.roominfo.person_num}</p> </div> <div className="detail2"> <div className="detailLeft"> <p>{val.hostinfo.name}</p> <p>{val.roominfo.name}</p> </div> <div className="detailRight"> <p>房间号:{this.state.id}</p> <p>人气:{val.roominfo.person_num}</p> </div> </div> </div> )) } <div className="chatList"> <div className={ this.state.flag ? "active" : "" } onClick={this.excolor.bind(this,0)}>聊天</div> <div className={ this.state.flag ? "" : "active" } onClick={this.excolor.bind(this,1)}>精彩推荐</div> </div> {this.state.flag ? <Chat/> : <Groom/>} </div> ); } } export default Vedioplay;
function test(){ alert("Welcome to Paris !"); } //Tableau des ventes à Paris// // fonction qui génère le tableau_de_données de données function tableau_de_données(){ return {"code_insee_commune":[], "commune":[], "numero_voie": [], "voie": [], "date_mutation":[], "nombre_pieces_principales": [], "valeur_fonciere":[]} } // FONCTION FETCH function fetch_par_département(tableau_de_données, plus_petit_num_commune, plus_grand_num_commune){ for (num_commune=plus_petit_num_commune; num_commune<=plus_grand_num_commune; num_commune++){ fetch('https://api.cquest.org/dvf?code_commune='+num_commune+'&nature_mutation=Vente&type_local=Maison', { method: 'GET', headers: {}, mode: 'cors', cache: 'default'}).then( function(response){ response.json().then( function(data){ num=data.resultats[0]['code_commune'] commune=data.resultats[0]["commune"] code_html="<tr class='commune' code_com='"+num+"'><td>"+num+"</td><td>"+commune+"</td></tr>" $(".ligne").append(code_html) $(".commune").click(function(){ num_commune=parseInt($(this).attr('code_com')) $(this).append(camembert(ventes_démo_par_commune[num_commune]["commune"][0], ventes_démo_par_commune[num_commune]["part_moins_20ans"][0], ventes_démo_par_commune[num_commune]["part_20_60ans"][0], ventes_démo_par_commune[num_commune]["part_plus_60ans"][0])) $('.moyenne').html("<h2>Prix moyen d'une maison : "+Math.round(moyenne(ventes_démo_par_commune[num_commune]["valeur_fonciere"]))+" </h2>") }) if (data.resultats.length>0){//si on a accès à des ventes de la commune dans l'url for (i=0; i<data.resultats.length;i++) { tableau_de_données["code_insee_commune"].push(data.resultats[i]["code_commune"]); tableau_de_données["commune"].push(data.resultats[i]["commune"]); tableau_de_données["date_mutation"].push(data.resultats[i]["date_mutation"]); tableau_de_données["nombre_pieces_principales"].push(data.resultats[i]["nombre_pieces_principales"]); tableau_de_données["numero_voie"].push(data.resultats[i]["numero_voie"]); tableau_de_données["voie"].push(data.resultats[i]["voie"]); tableau_de_données["valeur_fonciere"].push(data.resultats[i]["valeur_fonciere"]); } select_distinct(noms_communes_distinct, vente_paris["commune"]) select_distinct(codes_communes_distinct, vente_paris["code_insee_commune"]) } } ) } ); } }; function fetch_vente_par_commune(tableau_commune, num_commune){ fetch('https://api.cquest.org/dvf?code_commune='+num_commune+'&nature_mutation=Vente&type_local=Maison', { method: 'GET', headers: {}, mode: 'cors', cache: 'default'}).then( function(response){ response.json().then( function(data){ if (data.resultats.length>0){//si on a accès à des ventes de la commune dans l'url for (i=0; i<data.resultats.length;i++) { tableau_commune["code_insee_commune"].push(data.resultats[i]["code_commune"]); tableau_commune["commune"].push(data.resultats[i]["commune"]); tableau_commune["date_mutation"].push(data.resultats[i]["date_mutation"]); tableau_commune["nombre_pieces_principales"].push(data.resultats[i]["nombre_pieces_principales"]); tableau_commune["numero_voie"].push(data.resultats[i]["numero_voie"]); tableau_commune["voie"].push(data.resultats[i]["voie"]); tableau_commune["valeur_fonciere"].push(data.resultats[i]["valeur_fonciere"]); } infos_sup=tableau_commune_paris() fetch_infos_commune_distincte(tableau_commune,infos_sup);//il appelle le 2e fetch } } ) } ); }; //Tableau des infos sur la démographie à Paris// //fonction initialisation function tableau_commune_paris(){ return {"code_insee_commune":[], "population_actuelle":[], "evolution_pop":[], "densité":[], "part_moins_20ans":[], "part_20_60ans":[], "part_plus_60ans":[], "pourcentage_etranger":[], "evolution_etranger":[] }; } function fetch_infos_commune_paris(tableau){ //fetch fetch('https://opendata.arcgis.com/datasets/fa5ab237190945f58eb210b0ffad40ee_4.geojson', { method: 'GET', headers: {}, mode: 'cors', cache: 'default'}).then( function(response){ response.json().then( function(data){ for (i=0; i<data.features.length; i++){ //info général tableau["code_insee_commune"].push(data.features[i].properties["c_cainsee"]); tableau["population_actuelle"].push(data.features[i].properties["nb_pop"]); tableau["evolution_pop"].push(data.features[i].properties["pct_evo_pop_n5"]); tableau["densité"].push(data.features[i].properties["nb_densite"]); //pop en fonction de l'age tableau["part_moins_20ans"].push(data.features[i].properties["pct_age_019"]); tableau["part_20_60ans"].push( 100 - data.features[i].properties["pct_age_019"] - data.features[i].properties["pct_age_60p"]); tableau["part_plus_60ans"].push(data.features[i].properties["pct_age_60p"]); //les etrangers tableau["pourcentage_etranger"].push(data.features[i].properties["pct_etranger"]); tableau["evolution_etranger"].push(data.features[i].properties["pct_evo_etranger"]); } } ) } ); }; function fetch_infos_commune_distincte(tableau_commune,infos_sup){ //fetch fetch('https://opendata.arcgis.com/datasets/fa5ab237190945f58eb210b0ffad40ee_4.geojson', { method: 'GET', headers: {}, mode: 'cors', cache: 'default'}).then( function(response){ response.json().then( function(data){ for (i=0; i<data.features.length; i++){ //info général infos_sup["code_insee_commune"].push(data.features[i].properties["c_cainsee"]); infos_sup["population_actuelle"].push(data.features[i].properties["nb_pop"]); infos_sup["evolution_pop"].push(data.features[i].properties["pct_evo_pop_n5"]); infos_sup["densité"].push(data.features[i].properties["nb_densite"]); //pop en fonction de l'age infos_sup["part_moins_20ans"].push(data.features[i].properties["pct_age_019"]); infos_sup["part_20_60ans"].push( 100 - data.features[i].properties["pct_age_019"] - data.features[i].properties["pct_age_60p"]); infos_sup["part_plus_60ans"].push(data.features[i].properties["pct_age_60p"]); //les etrangers infos_sup["pourcentage_etranger"].push(data.features[i].properties["pct_etranger"]); infos_sup["evolution_etranger"].push(data.features[i].properties["pct_evo_etranger"]); } jointure(tableau_commune,infos_sup, "code_insee_commune", "code_insee_commune") } ) } ); }; //Enrichissement de la table des vente à Paris par la table contenant la démographie à Paris// function jointure(dico_cible, dico_pour_ajout, var_jointure_dico_cible, var_jointure_dico_pour_ajout){ /*Entré: deux dico json l'un de base et l'autre pour enrichir le 1er, et leurs clés de jointure Opération: enrichi le 1er dico_cible avec les info du dico pour ajour Sortie: rien*/ //les clés à ajouter au dico cible clés_dico_pour_ajout=Object.keys(dico_pour_ajout); //ajout des clés de dico_ajout à dico_cible for (i=0; i<clés_dico_pour_ajout.length;i++ ){ if (dico_cible[clés_dico_pour_ajout[i]]==undefined && clés_dico_pour_ajout[i]!=var_jointure_dico_pour_ajout){//car les var jointure peuvent avoir nom différente// dico_cible[clés_dico_pour_ajout[i]]=[]; } } // Remplir les info si on trouve mm clé sinon on insère vide. parseInt() sur les index car l'un est en chiffre et l'autre en caractere for (pos_dico_cible=0; pos_dico_cible<dico_cible[var_jointure_dico_cible].length; pos_dico_cible++){ index1=parseInt(dico_cible[var_jointure_dico_cible][pos_dico_cible]); for (pos_dico_ajout=0; pos_dico_ajout<dico_pour_ajout[var_jointure_dico_pour_ajout].length; pos_dico_ajout++){ index2=parseInt(dico_pour_ajout[var_jointure_dico_pour_ajout][pos_dico_ajout]); if (index1==index2){//s'il trouve le bon index il push les info correspondant au mm niveau de dico_cible for (z=0; z<clés_dico_pour_ajout.length; z++){ if (clés_dico_pour_ajout[z]!=var_jointure_dico_pour_ajout){ dico_cible[clés_dico_pour_ajout[z]][pos_dico_cible]=dico_pour_ajout[clés_dico_pour_ajout[z]][pos_dico_ajout]; }//les place vide représentent les jointures qui n'ont pas de correspondance// } } } } } function select_distinct(tableau_distinct, tableau_de_base){ for (i=0; i<tableau_de_base.length;i++){ trouvé=false; for (j=0; j<tableau_distinct.length;j++){ if (tableau_de_base[i] == tableau_distinct[j]){ trouvé=true; } } if (trouvé==false){ tableau_distinct.push(tableau_de_base[i]) } } } //Code pour générer les infos vente et démo sur paris sans jointure // infos sur les ventes dans tout paris// vente_paris=tableau_de_données() fetch_par_département(vente_paris, 75101, 75156) //infos pour la demo dans tout paris// infos_communes_paris=tableau_commune_paris(); fetch_infos_commune_paris(infos_communes_paris); //par commune les infos sur les ventes et la démographie// ventes_démo_par_commune={} for (i=75101; i<=75156; i++){ tableau_par_commune=tableau_de_données() fetch_vente_par_commune(tableau_par_commune, i) ventes_démo_par_commune[String(i)]=tableau_par_commune; } // Select distinct pour faciliter les affichage et diagrammes// //noms et codes communes distinctes codes_communes_distinct=[] noms_communes_distinct=[] //ils vont être rempli automatiquement après le fetch dans tout paris // DIagramme// function camembert(nom_commune, part_moins_20ans, part_20_60ans, part_plus_60ans){ Chart.defaults.global.title.display = true; Chart.defaults.global.title.text = "La répartition de la population en fonction de l'âge"; Chart.defaults.global.title.fontSize = 18; var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'pie', // The data for our dataset data: { datasets: [{ data : [ part_moins_20ans, part_20_60ans, part_plus_60ans, ], backgroundColor : [ 'rgba(255, 205, 86, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(201, 203, 207, 0.2))', ], label: "La répartition de la population en fonction de l'âge de "+nom_commune }], labels: [ '0 à 20 ans', '20 à 60 ans', 'plus de 60 ans' ] }, // Configuration options go here options: { legend: { display: true, position: 'right' }, } }); } function moyenne(liste){ s=0; n=0; for (i=0; i<liste.length; i++){ if (liste[i]!=undefined){ s+=liste[i] n+=1 } } return s/n } function barre(nom_commune, liste_nb_chambre, liste_prix){ liste_nb_chambre_distinct=select_distinct(liste_nb_chambre);//type maisons liste_prix_moyen=[] for (i=0; i<liste_nb_chambre_distinct.length; i++){ liste=[] for (j=0; j<liste_nb_chambre.length; j++){ if(liste_nb_chambre[j]==liste_nb_chambre_distinct[i]){ liste.push(liste_prix[j]) } } liste_prix_moyen.push(moyenne(liste)) } var ctx = document.getElementById("myChart2").getContext("2d"); var data = { labels : liste_nb_chambre_distinct, datasets : [ { label : "Valeur Foncière par nombre de pièce", data : liste_prix_moyen, backgroundColor : [ 'rgba(255, 205, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(153, 102, 255, 0.2)' ], borderColor: [ 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', 'rgb(153, 102, 255)', 'rgb(201, 203, 207)' ], borderWidth : 1 } ] }; var options = { title : { display : true, position : "top", text : "BarGraph" } }; var chart = new Chart( ctx, { type :"horizontalBar", data : data, options : options }); }
import dayjs from "dayjs" export const createCalendar = () => { // 今月の最初の日を取得 const firstDay = dayjs().startOf("month") // 必ず1日? // 最初の日の曜日のindex取得 const firstDayIndex = firstDay.day() // day()は曜日のindex return Array(35) .fill(0) .map((_, i) => { const diffFromFirstDay = i - firstDayIndex const day = firstDay.add(diffFromFirstDay, "day") console.log(day) return day } ) } // 当日か export const isSameDay = (d1, d2) => { const format = "YYYYMMDD" return d1.format(format) === d2.format(format) } // 同月か export const isSameMonth = (m1, m2) => { const format = "YYYYMM" return m1.format(format) === m2.format(format) } // 日付を受け取る export const isFirstDay = day => day.date() === 1
/** * Date:01/04/2021 * Author: Muhammad Minhaj * Title: Application Content Reducers * Description: All Content Of Data Fetch To Server With API * * */ import types from '../types'; const { HANDLE_LOADING, HANDLE_LOADING_CONTENT, UPDATE_CONTENT_PATH, TOPICS_DATA_FETCH_SUCCESS, TOPICS_DATA_FETCH_FAILED, CONTENT_DATA_FETCH_SUCCESS, CONTNET_DATA_FETCH_FAILED, HANDLE_TOP_LOADING_PROGRESS, HANDLE_CLICK_CLEAR_MESSAGE, } = types.content; const initalState = { isLoading: false, isLoadingContent: false, topics: [], currentTopic: null, currentChapter: null, currentContent: null, content: null, topLoadingProgress: null, msg: null, }; const reducer = (state = initalState, action) => { switch (action.type) { case HANDLE_LOADING: state = { ...state, isLoading: !state.isLoading, }; return state; case HANDLE_LOADING_CONTENT: state = { ...state, isLoadingContent: !state.isLoadingContent, }; return state; case UPDATE_CONTENT_PATH: state = { ...state, currentTopic: action.payload.currentTopic, currentChapter: action.payload.currentChapter, currentContent: action.payload.currentContent, }; return state; case HANDLE_CLICK_CLEAR_MESSAGE: state = { ...state, msg: null, }; return state; case TOPICS_DATA_FETCH_SUCCESS: state = { ...state, isLoading: false, topics: [...action.payload], }; return state; case TOPICS_DATA_FETCH_FAILED: state = { ...state, isLoading: false, msg: action.payload, }; return state; case CONTENT_DATA_FETCH_SUCCESS: state = { ...state, isLoadingContent: false, content: action.payload, }; return state; case CONTNET_DATA_FETCH_FAILED: state = { ...state, msg: action.payload, isLoadingContent: false, }; return state; case HANDLE_TOP_LOADING_PROGRESS: state = { ...state, topLoadingProgress: !state.topLoadingProgress, }; return state; default: return state; } }; export default reducer;
var stuff = [10,34,56,67,93,120,137,168,259,280,311,342,413,514]; var random_value = stuff[ Math.floor( Math.random() * stuff.length ) ]; console.log("the computer picked" + random_value); for(var i = 0; i <stuff.length ; i++){ if (stuff[i] === random_value){ console.log("We have a match with " + stuff[i]); } }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const User = require('./user'); const blogSchema = new Schema({ title: { type: String, default:'BlogTitle', required: true}, description: { type: String, default:'BlogDescription', required: true}, user: { type:Schema.Types.ObjectId, ref:'User'} }); module.exports = mongoose.model('Blog', blogSchema, 'blogs');
/* # 695. Max Area of Island (https://leetcode.com/problems/max-area-of-island/description/) You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0. Example 1: Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] Output: 6 Explanation: The answer is not 11, because the island must be connected 4-directionally. Example 2: Input: grid = [[0,0,0,0,0,0,0,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 grid[i][j] is either 0 or 1. */ /** * @param {number[][]} grid * @return {number} */ var siblings = function* (y, x) { if (y > 0) { yield [y-1, x]; } if (x > 0) { yield [y, x-1]; } } var getTopMostGroup = (graph, a) => { let parent; while (graph[a][0] !== a) { parent = graph[a][0]; a = parent; } return graph[a]; }; var vertexUnion = (graph, a, b) => { let groupA = getTopMostGroup(graph, a); let groupB = getTopMostGroup(graph, b); let tmp; if (groupA[0] === groupB[0]) { return groupA[1]; } if (groupA[0] > groupB[0]) { tmp = groupA; groupA = groupB; groupB = tmp; } groupB[0] = groupA[0]; groupA[1] += groupB[1]; return groupA[1]; }; var maxAreaOfIsland = function(grid) { const M = grid.length; const N = grid[0].length; let cellId; let sCellId; let maxArea = 0; let area; const graph = {}; // graph[cellId] = [groupID, area]; for (let y = 0; y < M; y++) { for (let x = 0; x < N; x++) { cellId = x + y * N; if (grid[y][x] !== 1) continue; if (graph[cellId] === undefined) { graph[cellId] = [cellId, 1]; } for ([sY, sX] of siblings(y, x)) { if (grid[sY][sX] !== 1) continue; sCellId = sX + sY * N; area = vertexUnion(graph, sCellId, cellId) maxArea = Math.max(maxArea, area); } } } if (maxArea === 0 && Object.keys(graph).length > 0) { return 1; } return maxArea; }; let input; input = [ [0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0] ]; assert(6, maxAreaOfIsland(input), "Area should be 6"); input = [[1]]; assert(1, maxAreaOfIsland(input), "Area should be 1"); input = [[0]]; assert(0, maxAreaOfIsland(input), "Area should be 0"); input = [[0, 0, 0, 0], [0, 0, 0, 0]]; assert(0, maxAreaOfIsland(input), "Area should be 0"); function assert(expected, actual, message) { if (expected === actual) { console.log(` + OK. ${message}. '${expected} === ${actual}'.`); } else { console.error(`x FAILED! ${message}. Expected '${expected}' but got '${actual}' :o(`); } }
import { requestLogin, receiveLogin, loginError } from './actions'; const loginUser = (creds) => { const config = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=${creds.username}&password=${creds.password}`, }; return (dispatch) => { dispatch(requestLogin(creds)); return fetch('http://localhost:3000/user/find', config) .then((response) => { response.json().then(user => ({ user, response })) .then(({ user, res }) => { if (!res.ok) { dispatch(loginError(user.message)); return Promise.reject(user); } localStorage.setItem('id_token', user.id_token); localStorage.setItem('id_token', user.access_token); dispatch(receiveLogin(user)); }).catch(err => console.log(err)); }); }; }; export default loginUser;
import React, { useState, useEffect } from "react"; import Link from "next/link"; import axios from "axios"; import { useDispatch } from "react-redux"; import { Button, Checkbox, Form, Input } from "antd"; import { MailOutlined } from "@ant-design/icons"; import styled from "styled-components"; import { LeftOutlined, CheckOutlined } from "@ant-design/icons"; import { TOGGLE_REGISTER, TOGGLE_LOGIN } from "../../actions/types"; import baseUrl from "../../utils/baseUrl"; const InputWrapper = styled.div` margin-bottom: 1rem; `; const A = styled.a` color: ${({ theme }) => theme.secondaryBlue}; `; const ForgotPasswordForm = ({ setForgotPasswordVisible }) => { const dispatch = useDispatch(); const [email, setEmail] = useState(""); const [disabled, setDisabled] = useState(true); const [loading, setLoading] = useState(false); const [isSent, setSent] = useState(null); //disable login button if fields are empty useEffect(() => { const emailVaidate = /\S+@\S+\.\S+/; if (emailVaidate.test(email)) { setDisabled(false); } else { setDisabled(true); } }, [email]); //handle submit const handleSubmit = async () => { setLoading(true); //set headers for request const config = { headers: { "Content-Type": "application/json", }, }; //stringify the form items const data = { userEmail: email }; const body = JSON.stringify(data); //update post to DB try { setSent(null); const url = `${baseUrl}/api/verification/send/forgotPassword`; const res = await axios.post(url, body, config); if (res) { setSent(true); } else { setSent(false); } } catch (err) { setSent(false); } finally { setLoading(false); } }; return ( <div> <p style={{ marginBottom: "1em", textAlign: "center" }}> Forgot your password? No problem! Enter your email in the input below to send a recovery link to your registered email address. </p> <InputWrapper> <Input placeholder='Email' prefix={<MailOutlined style={{ color: "rgba(0,0,0,.25)" }} />} size='large' name='email' value={email} onChange={(e) => setEmail(e.target.value)} type='email' /> </InputWrapper> <Button type='primary' htmlType='submit' loading={loading} size='large' style={{ width: "100%" }} disabled={disabled} onClick={handleSubmit} > {isSent ? ( <> <CheckOutlined /> Sent </> ) : ( "Send Recovery Link" )} </Button> <Button type='link' onClick={() => setForgotPasswordVisible(false)} style={{ marginTop: "1em" }} > <LeftOutlined /> Click here to return to Login </Button> </div> ); }; export default ForgotPasswordForm;
import React, { Component } from 'react'; import styles from './Drawing.module.css'; import drawingList from '../../../../assets/images/drawing'; import Modal from '../../../UI/Modal/Modal'; import LoadElement from '../../../UI/LoadElement/LoadElement'; class Drawing extends Component { constructor() { super(); this.state = { show: false, imgNum: 0, loading: true, width: '23%', }; this.imgLength = drawingList.length - 2; } increaseNumber = () => { this.setState((prevState) => ({ imgNum: (prevState.imgNum + 1) % this.imgLength, })); }; decreaseNumber = () => { if (this.state.imgNum === 0) { return; } this.setState((prevState) => ({ imgNum: prevState.imgNum - 1, })); }; modalClosed = () => { this.setState({ show: false }); }; modalOpen = (e) => { this.setState({ imgNum: Number(e.target.id), show: true, }); if (window.innerWidth <= 1024) { this.setState({ width: '38%', }); } else if (window.innerWidth > 1024 && window.innerWidth <= 1366) { this.setState({ width: '27%', }); } else if (window.innerWidth > 1366) { this.setState({ width: '30%', }); } }; renderLoader() { if (!this.state.loading) { return null; } return <LoadElement />; } handleImageLoaded = () => { this.setState({ loading: false }); }; render() { const { imgNum, show, width, hoverStates } = this.state; return ( <> <div className={styles.Header}> <h1>Drawing</h1> <div> <span>사용 프로그램</span> <span>illustrator, clipstudio</span> </div> </div> <div className={styles.Gallery}> <div className={styles.Row}> {/* {this.renderLoader()} */} <div className={styles.Col}> <div className={styles.EachImg}> <img id={0} onClick={this.modalOpen} src={drawingList[0].smallSrc} alt={drawingList[0].alt} /> <h2 id={0} onClick={this.modalOpen}> Dionysos </h2> </div> <div className={styles.EachImg}> <img id={2} onClick={this.modalOpen} onLoad={this.handleImageLoaded} src={drawingList[2].smallSrc} alt={drawingList[2].alt} /> <h2 id={2} onClick={this.modalOpen}> Tinker-Bell </h2> </div> <div className={styles.EachImg}> <img id={4} onClick={this.modalOpen} src={drawingList[4].smallSrc} alt={drawingList[4].alt} /> <h2 id={4} onClick={this.modalOpen}> Venus </h2> </div> </div> <div className={styles.Col}> <div className={styles.EachImg}> <img id={1} onClick={this.modalOpen} src={drawingList[7].smallSrc} alt={drawingList[7].alt} /> <h2 id={1} onClick={this.modalOpen}> Narcissus </h2> </div> <div className={styles.EachImg}> <img id={3} onClick={this.modalOpen} src={drawingList[6].smallSrc} alt={drawingList[6].alt} /> <h2 id={3} onClick={this.modalOpen}> Romeo&Juliet </h2> </div> <div className={styles.EachImg}> <img id={5} onClick={this.modalOpen} src={drawingList[5].smallSrc} alt={drawingList[5].alt} /> <h2 id={5} onClick={this.modalOpen}> Rapunzel </h2> </div> </div> </div> {show && ( <Modal show={show} modalClosed={this.modalClosed} nextArrow={this.increaseNumber} prevArrow={this.decreaseNumber} imgLength={this.imgLength} imgNum={imgNum + 1} index="Drawing" name={drawingList[imgNum].name} isMany={true} > <div className={styles.ImgContainer}> {this.renderLoader()} <img onLoad={this.handleImageLoaded} className={styles.ImgInModal} style={{ width: imgNum === 3 ? width : '', }} src={drawingList[imgNum].src} alt={drawingList[imgNum].alt} /> </div> </Modal> )} </div> </> ); } } export default Drawing;
function setup() { createCanvas(500, 500); background(100); console.log(numberOfStudents); let numberOfStudents = 8; } function draw() { }
/** * Created with PhpStorm. * User: kimh * Date: 16/12/13 * Time: 3:39 PM */ define([],function(){ var Background = function(game, pitchSize){ this._pitchSize = pitchSize; this._game = game; this._bmp = null; this._bg = null; this._clouds = null; this._scoreBg = null; this.redraw(); } Background.prototype.redraw = function() { log(this + '::redraw()'); // Background // if(!this._bmp){ this._bmp = this._game.add.bitmapData( this._game.world.width,this._game.world.height ); } this._bmp.clear(); this._bmp.fillStyle('#70B5E8'); this._bmp.fillRect( 0,0, this._game.world.width,this._game.world.height-this._pitchSize ); this._bmp.fillStyle('#4A87B3'); this._bmp.fillRect( 0,this._game.world.height-this._pitchSize-103, this._game.world.width,103 ); this._bmp.fillStyle('#769A56'); this._bmp.fillRect( 0,this._game.world.height-this._pitchSize, this._game.world.width,this._pitchSize ); if(!this._bg) { this._bg = this._game.add.sprite(0,0); this._bmp.add(this._bg); } // Clouds // if(!this._clouds) { this._clouds = this._game.add.group(); this._clouds.create(38,0,'sprite').frameName = 'cloud'; this._clouds.create(446,186,'sprite').frameName = 'cloud'; } if(!this._scoreBg) { this._scoreBg = this._game.add.sprite(636,-82,'sprite'); this._scoreBg.frameName = 'cloud'; } // find cloud group height // var h = 0; this._clouds.forEach(function(item){ h = Math.max(h,item.y + item.height); },this); this._clouds.y = ((this._game.world.height-this._pitchSize-103)-h)*.5; } Background.prototype.toString = function() { return 'Background'; } return Background; });
migration.up = function(migrator) { try{ migrator.createTable({ columns: { "Codigo": "integer PRIMARY KEY", "Nome": "varchar", "Cpf": "varchar", "DataNasc": "datetime", "Email": "varchar", "Endereco": "varchar", "Numero": "varchar", "Referencia": "varchar", "Bairro": "varchar", "Cep": "varchar", "Cidade": "varchar", "UF": "varchar", "Login": "varchar", "UsuarioUAU": "varchar" } }); } catch(e){ Ti.API.info("tabela não criada"); } }; migration.down = function(migrator) { Ti.API.info("Fim do migrator"); };
require('dotenv').config(); export const IS_PRODUCTION = process.env.REACT_APP_PRODUCTION; export const appId = process.env.REACT_APP_APP_ID; export const apiUrl = process.env.REACT_APP_API_MASTER; export const apiUrlWithdraw = process.env.REACT_APP_API_WITHDRAW; export const apiUrlEsports = process.env.REACT_APP_API_ESPORTS; export const websocketUrlEsports = process.env.REACT_APP_WEBSOCKET_ESPORTS; export const websocketUrlEsportsListener = process.env.REACT_APP_WEBSOCKET_ESPORTS_LISTENER;
/*EXPECTED Hi */ class K { delete function constructor() {} static function doit() : void { log "Hi"; } } class _Main { static function main(args : string[]) : void { K.doit(); } }
import yaml from 'js-yaml'; import ini from 'ini'; import _ from 'lodash'; const fixValue = (value) => { if (typeof value === 'boolean') return value; if (_.isNaN(Number(value))) return value; return Number(value); }; const fixIniValues = object => _.toPairs(object).reduce((acc, [key, value]) => ({ ...acc, [key]: _.isObject(value) ? fixIniValues(value) : fixValue(value), }), {}); const parseIni = string => fixIniValues(ini.parse(string)); const parsers = { json: JSON.parse, yml: yaml.safeLoad, ini: parseIni, }; const parse = (format, data) => parsers[format](data); export default parse;
export default function () { return (Math.random()<0.5); }
import React, { useEffect, useState } from 'react'; import LoadingOverlay from 'react-loading-overlay'; //Redux import { connect } from 'react-redux'; import { actFetchVehiclesRequest, actFetchVehicleDetailRequest, actDeleteVehicleDetai, } from './../../store/actions/index'; //Component import CustomTable from './../../component/Table/Table'; import CustomPagination from './../../component/Pagination/Pagination'; import CustomModal from './../../component/Modal/Modal' import { InputGroup, FormControl, Button, Alert } from 'react-bootstrap'; const { Append, Text } = InputGroup; const HomeCtn = (props) => { const { count, deleteDetailVehicle, fetchVehicles, fetchDetailVehicle, next, previous, vehicleDetail, vehicles, isError, isErrorSever } = props; const [state, setState] = useState({ numberPage: 0, searchString: "", isShowModal: false, isError: false, loading: false, isShowTable: true }); useEffect(() => { fetchVehicles(); },[]); useEffect(() => { if ( props ) { setState( prevState => ({ ...prevState, numberPage: next !== null ? next - 1 : previous + 1, maxPage: Math.ceil(count / 10), isShowTable: vehicles && vehicles.length > 0 ? true : false, })); } }, [props]); useEffect(() => { if(isError) { setState( prevState => ({ ...prevState, isShowModal: false, isError: true })); } },[isError]); const _handleChangeState = ( key, value ) => { setState( prevState => ({ ...prevState, [key]: value, })); }; const _handleModal = url => { _handleChangeState('isShowModal', true); fetchDetailVehicle(url); }; const _handleChangePage = page => { fetchVehicles(page); }; const _handleSearch = () => { if ( state.searchString === "" ) return; fetchVehicles(state.searchString); _handleChangeState('searchString', ""); }; const _handleClose = async () => { await deleteDetailVehicle(); _handleChangeState("isShowModal", false); } return( <LoadingOverlay active={props.loading} spinner text='Loading your content...' > <div className="container-fluid"> <h1 style={{textAlign:'center'}}> LIST VEHICLES </h1> <div className="groupInput"> <InputGroup className="mb-3 w-30" onKeyDown={ (e) => { if (e.key === "Enter") { _handleSearch(e) } } } > <FormControl placeholder="Search..." aria-label="value" aria-describedby="basic-addon2" onChange = { (e) => _handleChangeState("searchString", e.target.value) } value = { state.searchString } /> <Append> <Text id="basic-addon2"> <Button onClick={() => _handleSearch()}> <i className="fas fa-search"></i> </Button> </Text> </Append> </InputGroup> </div> { state.isShowTable === true ? <> <CustomTable vehicles = { vehicles } numberPage = { state.numberPage - 1 } handleModal = { _handleModal } /> <CustomPagination count = { count } next = { next } previous = { previous } numberPage = { state.numberPage} handleChangePage = { _handleChangePage } maxPage = { state.maxPage } /> </> : isErrorSever === true ? <Alert variant="danger" style={{textAlign:'center'}}>We have a issues. Please try again!</Alert> : <Alert variant="warning" style={{textAlign:'center'}}>Not found data. Please try again!</Alert> } <CustomModal vehicleDetail = { vehicleDetail } handleClose = { _handleClose} isShow = { state.isShowModal } isError = { state.isError } /> </div> </LoadingOverlay> ); }; const mapStateToProps = state => { const { vehicles } = state; return { count: vehicles.count, vehicles: vehicles.vehicles, next: vehicles.next, previous: vehicles.previous, loading: vehicles.loading, vehicleDetail: vehicles.vehicleDetail, isError: vehicles.error, isErrorSever: vehicles.errorSever } } const mapDispatchToProps = (dispatch, props) => { return { fetchVehicles : (numberPage) => { dispatch(actFetchVehiclesRequest(numberPage)); }, fetchDetailVehicle : (url) => { dispatch(actFetchVehicleDetailRequest(url)); }, deleteDetailVehicle : () => { dispatch(actDeleteVehicleDetai()); } } } export default connect(mapStateToProps, mapDispatchToProps) (HomeCtn);
export const listSortCheckBox = [ { name: "maPhim", label: "Mã Phim", isChecked: "false", }, { name: "tenPhim", label: "Tên Phim", isChecked: "true", }, // { // name: "biDanh", // label: "Bí Danh", // isChecked: "false", // }, { name: "moTa", label: "Mô tả", isChecked: "false", }, // { // name: "hinhAnh", // label: "Hình Ảnh", // isChecked: "false", // }, // { // name: "trailer", // label: "Trailer", // isChecked: "false", // }, // { // label: "Đánh giá", // isChecked: false, // }, ];
const React = require('react') const Header = require('./components/Header') const MetaData = require('./components/MetaData') const Layout = ({ namePage, children }) => { return ( <html> <MetaData namePage={namePage} /> <body> <Header /> <div className='content'> {children} </div> <script src='/dist/bundle.js' /> </body> </html> ) } module.exports = Layout
const topmost = require("tns-core-modules/ui/frame").topmost; const keys = require("./keys"); const observableModule = require("tns-core-modules/data/observable"); const ObservableArray = require("tns-core-modules/data/observable-array").ObservableArray; const http = require("http"); const dialogs = require("tns-core-modules/ui/dialogs"); const viewModel = observableModule.fromObject({ groups: new ObservableArray([]), isLoading: false }); /* *********************************************************** * This is the master list code behind in the master-detail structure. * This code behind gets the data, passes it to the master view and displays it in a list. * It also handles the navigation to the details page for each item. *************************************************************/ /* *********************************************************** * Use the "onNavigatingTo" handler to initialize the page binding context. * Call any view model data initialization load here. *************************************************************/ function onNavigatingTo(args) { /* *********************************************************** * The "onNavigatingTo" event handler lets you detect if the user navigated with a back button. * Skipping the re-initialization on back navigation means the user will see the * page in the same data state that he left it in before navigating. *************************************************************/ if (args.isBackNavigation) { return; } const page = args.object; page.bindingContext = viewModel; load(); } function load() { viewModel.set("isLoading", true); viewModel.set("groups", new ObservableArray([])); console.log("KEYS"); console.log(keys.loadKey()); http.request({ url: "https://lammediafunctions.azurewebsites.net/api/newsearchmain", method: "GET", headers:{ "content-type":"application/json", "X-ZUMO-AUTH": keys.loadKey() } }).then((response) => { viewModel.set("isLoading", false); const arr1 = response.content.toJSON(); for (let index = 0; index < arr1.length; index++) { arr1[index].imageSrc = "https://lamfamily.blob.core.windows.net/thumbs160/" + arr1[index].id; } viewModel.set("groups", new ObservableArray(arr1)); }, (error) => { console.log("error"); viewModel.set("isLoading", false); }); } /* *********************************************************** * Use the "itemTap" event handler of the <RadListView> to navigate to the * item details page. Retrieve a reference for the data item and pass it * to the item details page, so that it can identify which data item to display. * Learn more about navigating and passing context in this documentation article: * https://docs.nativescript.org/core-concepts/navigation#navigate-and-pass-context *************************************************************/ function onGroupTap(args) { topmost().navigate({ moduleName: "media/group-page/group-page", context: args.view.bindingContext, animated: true, transition: { name: "slide", duration: 200, curve: "ease" } }); } function onEnterKey() { // Add proper facebook authentication somewhere in the future dialogs.prompt("Your key", "authkeyfromfacebook").then(function (r) { console.log("Dialog result: " + r.result + ", text: " + r.text); keys.saveKey(r.text); load(); }); } exports.onNavigatingTo = onNavigatingTo; exports.onGroupTap = onGroupTap; exports.onEnterKey = onEnterKey;
import prettyInput from './prettyInput.vue' export default { name: 'pretty-radio', input_type: 'radio', mixins: [prettyInput] }
function toDo() { var a = 12; // console.log(arguments.push(12), 'arguments') arguments[arguments.length] = 12; console.log(arguments, 'arguments'); return 'hello'; } // console.log(a, 'a'); var z; console.log(toDo(1, 2, 3, 4)) // --------- // function foo() { // return function() { // console.log('123'); // } // } // var callback = foo(); // console.log(callback(), 'callback'); /* Object 1. diff: link, primitive type 2. Object 3. add, read, update, delete --keys 4. nested object 4. loop 5. Object.entries(), keys(), values() 6. clone */ // ------------- primitive type ---------- var mass = []; function foo(arr) { //arr = mass if (!arr) { return; } arr.push(12); console.log(arr, 'arr'); } // foo(mass); // console.log(mass, 'mass'); var a = 12; function foo2(value) { // value = a; value = 13; } foo2(a); // console.log(a, 'a'); /// -------- // var link1 = []; // var link2 = link1; // link2[link2.length] = 12; // console.log(link2, 'link2'); // console.log(link1, 'link1'); // ----- primitive -------- var a1 = 12; var a2 = a1; // console.log(a1, 'a1 before mutation'); // console.log(a2, 'a2 before mutation'); a2 = 14; // console.log(a1, 'a1 after mutation'); // console.log(a2, 'a2 after mutation'); // -------------- var team = [ ['valera', 'ternavsky', 26], ['valera', 'ternavsky', 36] ] // var valera = team[0]; // valera.reverse(); // console.log(valera, 'valera'); // var name = valera[0]; // var lastName = valera[1]; // var age = valera[2]; // console.log(name, 'name'); // console.log(lastName, 'lastName'); // console.log(age, 'age'); // var human = { name: 'Valera', lastName: 'Ternavsky', age: 22, age: 26 }; // --- read -- console.log(human, 'human'); var name = human.name; console.log(name, 'name'); console.log(human.age, 'age'); var key = 'lastName'; console.log(human[key], 'age'); console.log(human.key) // --- write ---- human.children = [1]; // create human['children'] = [2]; // update console.log(human, 'human'); console.log(human.children[0] ,'human.children') human.sister = { name: 'kate' }; console.log(human.sister.na, 'human'); // [2].push(3); // ------ delete --- delete human.children; console.log(human, 'human'); // -------- loop ------ console.log(human.age, 'age'); // for(var key in human) { // // console.log(typeof key, 'key') // var value = human[key]; // console.log(key, value, 'value'); // } console.log(human, 'human'); var human2 = human; function cloneObject(obj) { // obj = human var newObj = {}; console.log(obj, 'obj'); for(var key in obj) { console.log(key, 'key'); newObj[key] = obj[key]; } console.log(newObj, 'newObj'); console.log(newObj == obj) } cloneObject(human);
const prisma = require("../app.js").prisma; async function createUser(user) { await prisma.user.create({ data: { name: user.name, email: user.email, phone: user.phone, role: user.role } }) } async function showUsers(req,res) { prisma.user.findMany().then(data =>{ res.send(data) }) } async function updateUser(usr) { const user = await prisma.user.update({ where: { id: parseInt(usr.id,10) }, data: { name: usr.name, email: usr.email, phone: usr.phone, role: usr.role }, }) } module.exports.createUser = createUser; module.exports.showUsers = showUsers; module.exports.updateUser = updateUser;
function verificar(){ var numero = document.getElementById('finicio') var numerotwo = document.getElementById('ffim') var res = document.getElementById('res') n = Number(numero.value) n2 = Number(numerotwo.value) if (numero.value.length == 0 ) { window.alert('[ERROR] Verifique seus dados..') } else { res.innerHTML = '' for(c = 1; c <=n2; c++) { Resultado = n * c res.innerHTML += `${n} x ${c} = ${Resultado} <br>` } } }
const { uploadImage, getImageRelativePath } = require('../_helpers') const db = require('../models') const sequelize = require('sequelize') const Op = sequelize.Op const Restaurant = db.Restaurant const Category = db.Category const Comment = db.Comment const Meal = db.Meal const Order = db.Order const User = db.User const moment = require('moment-timezone'); const _ = require('underscore') const customQuery = process.env.heroku ? require('../config/query/heroku') : require('../config/query/general') let ownerController = { getRestaurant: async (req, res) => { try { let restaurant = await Restaurant.findAll({ where: { UserId: req.user.id }, include: [{ model: Category, attributes: ['id', 'name'] }], attributes: { exclude: ['createdAt', 'updatedAt'] } }) const categories = await Category.findAll({ attributes: ['id', 'name'] }) if (restaurant.length === 0) { return res.status(200).json({ status: 'success', categories, message: 'You have not restaurant yet.' }) } return res.status(200).json({ status: 'success', restaurant, categories, message: 'Successfully get the restaurant information.' }) } catch (error) { return res.status(500).json({ status: 'error', message: error }) } }, postRestaurant: async (req, res) => { try { let { lat, lng } = req.body if (!lat || !lng) return res.status(400).json({ status: 'error', message: 'need lat and lng' }) let restaurant = await Restaurant.findAll({ where: { UserId: req.user.id } }) if (restaurant.length > 0) return res.status(400).json({ status: 'error', message: 'You already have a restaurant.' }); const point = sequelize.fn('ST_GeomFromText', `POINT(${lng} ${lat})`) const { file } = req if (!file) return res.status(400).json({ status: 'error', message: 'You need to pick a picture' }) const fileName = `restaurant-${req.body.name}`; const folder = '/Nextmeal/Restaurant'; const { url } = await uploadImage(file.buffer, fileName, folder); await Restaurant.create({ ...req.body, image: getImageRelativePath(url), lat: lat, lng: lng, geometry: point, UserId: req.user.id }) return res.status(200).json({ status: 'success', message: 'Successfully create the restaurant information with image.' }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, putRestaurant: async (req, res) => { try { const { lat, lng } = req.body if (!lat || !lng) return res.status(400).json({ status: 'error', message: 'can not find address' }) let restaurant = await Restaurant.findOne({ where: { UserId: req.user.id } }) if (!restaurant) { return res.status(400).json({ status: 'error', message: 'The restaurant does not exist.' }) } const point = sequelize.fn('ST_GeomFromText', `POINT(${lng} ${lat})`) const { file } = req let image = restaurant.image; if (file) { const fileName = `restaurant-${req.body.name}`; const folder = '/Nextmeal/Restaurant'; const { url } = await uploadImage(file.buffer, fileName, folder); image = getImageRelativePath(url); } await restaurant.update({ name: req.body.name, description: req.body.description, image, tel: req.body.tel, address: req.body.address, CategoryId: req.body.CategoryId, opening_hour: req.body.opening_hour, closing_hour: req.body.closing_hour, lat: lat, lng: lng, geometry: point, }) return res.status(200).json({ status: 'success', message: 'Successfully update restaurant information with image.' }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, getDishes: async (req, res) => { try { let restaurant = await Restaurant.findAll({ where: { UserId: req.user.id }, include: [{ model: Meal, where: { isDeleted: false } }], attributes: ['id', 'UserId'] }) if (restaurant.length === 0 || restaurant[0].dataValues.Meals.length === 0) { return res.status(200).json({ status: 'success', meals: [], message: 'You haven\'t setting restaurant or meal yet.' }) } if (restaurant[0].dataValues.UserId !== req.user.id) { return res.status(400).json({ status: 'error', message: 'You are not allow do this action.' }) } let meals = restaurant.map(rest => rest.dataValues.Meals) meals = meals[0].map(meal => meal.dataValues) return res.status(200).json({ status: 'success', meals, message: 'Successfully get the dish information.' }) } catch (error) { return res.status(500).json({ status: 'error', message: error }) } }, postDish: async (req, res) => { try { let restaurant = await Restaurant.findOne({ where: { UserId: req.user.id }, include: [Meal], attributes: ['id'] }) if (restaurant === null) { res.status(422).json({ status: 'error', message: 'You haven\'t setting restaurant yet.' }) } const { file } = req if (!file) return res.status(400).json({ status: 'error', message: 'You need to pick a picture' }) const fileName = `dish-${req.body.name}`; const folder = '/Nextmeal/Food'; const { url } = await uploadImage(file.buffer, fileName, folder); if (restaurant.Meals.length === 0) { await Meal.create({ ...req.body, image: getImageRelativePath(url), RestaurantId: restaurant.id, nextServing: true }) } else { await Meal.create({ ...req.body, image: getImageRelativePath(url), RestaurantId: restaurant.id, }) } return res.status(200).json({ status: 'success', message: 'Successfully create a meal with image.' }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, getDish: async (req, res) => { try { let meal = await Meal.findOne({ include: [{ model: Restaurant, attributes: ['UserId'] }], where: { id: req.params.dish_id, isDeleted: false } }) if (!meal) { return res.status(400).json({ status: 'error', meal, message: 'meal does not exist' }) } if (meal.Restaurant.UserId !== req.user.id) { return res.status(401).json({ status: 'error', message: 'You are not allow do this action.' }) } return res.status(200).json({ status: 'success', meal, message: 'Successfully get the dish information.' }) } catch (error) { return res.status(500).json({ status: 'error', message: error }) } }, putDish: async (req, res) => { try { let meal = await Meal.findOne({ include: [{ model: Restaurant, attributes: ['UserId'] }], where: { id: req.params.dish_id, isDeleted: false } }) if (!meal) { return res.status(422).json({ status: 'error', message: 'meal is not exist.' }) } if (meal.Restaurant.UserId !== req.user.id) return res.status(422).json({ status: 'error', message: 'You are not allow this action.' }) const { file } = req if (file) { const fileName = `dish-${req.body.name}`; const folder = '/Nextmeal/Food'; const { url } = await uploadImage(file.buffer, fileName, folder); await meal.update({ ...req.body, image: getImageRelativePath(url), }) return res.status(200).json({ status: 'success', message: 'Successfully update a meal with image.' }) } else { await meal.update(req.body) res.status(200).json({ status: 'success', message: 'Successfully update a meal.' }) } } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, deleteDish: async (req, res) => { try { let meal = await Meal.findOne({ where: { id: req.params.dish_id, isDeleted: false } }) if (!meal) return res.status(422).json({ status: 'error', message: 'meal is not exist.' }) await meal.update({ isDeleted: true }) res.status(200).json({ status: 'success', message: 'meal was successfully destroyed.' }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, getMenu: async (req, res) => { try { const restaurant = await Restaurant.findOne({ where: { UserId: req.user.id }, attributes: ['id'], include: [{ model: Meal, attributes: ['id', 'name'], where: { isDeleted: false } }] }) if (!restaurant) return res.status(200).json({ status: 'success', meals: [], options: [], message: 'you do not have your restaurant info filled or a meal yet' }) let whereQuery = {} let message = '' if (req.query.ran !== 'thisWeek' && req.query.ran !== 'nextWeek') { return res.status(400).json({ status: 'error', message: 'must query for this week or next week' }) } if (req.query.ran === 'thisWeek') { whereQuery = { RestaurantId: restaurant.id, isServing: true, isDeleted: false } message = 'the meals for this week' } if (req.query.ran === 'nextWeek') { whereQuery = { RestaurantId: restaurant.id, nextServing: true, isDeleted: false } message = 'the meals for next week' } let meals = await Meal.findAll({ where: whereQuery }) return res.status(200).json({ status: 'success', meals, options: (req.query.ran === 'nextWeek') ? restaurant.Meals : undefined, message: message }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } }, putMenu: async (req, res) => { try { if (Number(req.body.quantity) < 1) { return res.status(400).json({ status: 'error', message: 'the menu\'s quantity not allow 0 or negative for next week' }) } const today = moment().day() // 修改 nextServing 為真,而且可以更改數量 if (today >= 6) { return res.status(400).json({ status: 'error', message: 'Today can not edit next week\'s menu.' }) } let meal = await Meal.findOne({ where: { id: req.body.id, isDeleted: false }, include: [{ model: Restaurant, where: { UserId: req.user.id } }] }) //要修改的 meal if (!meal) return res.status(400).json({ status: 'error', message: 'meal does not exist' }) if (req.user.id !== meal.Restaurant.UserId) return res.status(400).json({ status: 'error', message: 'You are not allow do this action.' }) let originNextWeeK = await Meal.findOne({ where: { nextServing: true, isDeleted: false }, include: [{ model: Restaurant, where: { UserId: req.user.id } }] }) // 如果有先更新成 false if (originNextWeeK) { originNextWeeK = await originNextWeeK.update({ nextServing: false }) } meal = await Meal.findOne({ where: { id: req.body.id } }) meal = await meal.update({ nextServing_quantity: req.body.quantity || meal.quantity, nextServing: true }) return res.status(200).json({ status: 'success', meal, message: 'Successfully setting menu for next week' }) } catch (error) { console.log(error); return res.status(500).json({ status: 'error', message: error }) } }, getOrders: async (req, res) => { try { //算出今天開始、結束日期 const start = moment().startOf('day').utc().format() const end = moment().endOf('day').utc().format() const restaurant = await Restaurant.findOne({ where: { UserId: req.user.id } }) // 處理餐廳資料尚未創建的情況 if (!restaurant) { return res.status(200).json({ status: 'success', orders: {}, message: 'You haven\'t provided your restaurant info yet.' }) } if (req.user.id !== restaurant.UserId) return res.status(400).json({ status: 'error', message: 'you are not allow do this action' }) let orders = await Order.findAll({ where: { order_status: { [Op.like]: '今日' }, require_date: { // 大於開始日 [Op.gte]: start, // 小於結束日 [Op.lte]: end } }, include: [ { model: Meal, as: 'meals', where: { RestaurantId: restaurant.id }, attributes: ['id', 'name', 'image'] }, { model: User, attributes: ['id', 'name', 'email'] } ], attributes: [ 'id', 'require_date', 'order_status', customQuery.char.time, ], order: [['require_date', 'ASC']], }) // 11/1 加入處理order不存在時的情況 by Danny if (orders.length === 0) { return res.status(200).json({ status: 'success', orders: {}, message: 'Can not find any orders' }) } orders = orders.map(order => ({ ...order.dataValues, meals: order.dataValues.meals[0] })) orders = _.mapObject(_.groupBy(orders, 'time')) return res.status(200).json({ status: 'success', orders, message: 'Successfully get Orders' }) } catch (error) { return res.status(500).json({ status: 'error', message: error }) } }, dashborad: async (req, res) => { try { // 取得一個月前的時間做為區間起點 const pass_one_month = moment().subtract(1, 'months').utc().format() // 取得該owner的餐廳資料 const restaurant = await Restaurant.findOne({ where: { UserId: req.user.id } }) // query過去一個月內每日的訂單 let orders = await Order.findAll({ include: [ { model: Meal, as: 'meals', where: { RestaurantId: restaurant.id }, attributes: [] } ], where: { require_date: { [Op.gte]: pass_one_month } }, attributes: [ customQuery.char.date_for_dashboard, ] }) // 手動加總不同日期的訂單量 let results = orders.reduce((obj, item) => { if (item.dataValues.date in obj) { obj[item.dataValues.date] += 1 } else { obj[item.dataValues.date] = 1 } return obj }, {}) // 複寫orders的結果達到與group by相同的輸出 orders = [] for (i in results) { orders.push({ date: i, count: results[i] }) } // find all dates a month from now var dateArray = []; var currentDate = moment(pass_one_month).utc().format(); var stopDate = moment().utc().format(); while (currentDate <= stopDate) { dateArray.push(moment(currentDate).format('MM/DD')) currentDate = moment(currentDate).add(1, 'days').utc().format() }; // check if there's missing dates const currentDates = orders.map(item => item.date) const missing_fields_order_mod = dateArray.filter(v => currentDates.indexOf(v) === -1) // create the an end result object for later sorting const order_result = orders.map(item => ({ date: item.date, count: item.count })) // if missing fields exist,fill in with value 0 missing_fields_order_mod.map(async item => { await order_result.push({ "date": item, count: 0 }) }) // sort the result order_result.sort((a, b) => { return new Date(a["date"]) - new Date(b["date"]) }) let users = await User.findAll({ include: [{ model: Order, where: { require_date: { [Op.gte]: pass_one_month, } }, include: [{ model: Meal, as: 'meals', where: { RestaurantId: restaurant.id }, attributes: ['id', 'name', 'description', 'image'] }] }], order: [['dob', 'DESC']] }) // calculate user age and count by group let user_result = { "<20歲": 0, "20~30歲": 0, "30~40歲": 0, "40~50歲": 0, "50~60歲": 0, ">60歲": 0 } users = users.map(item => ( { age: moment().utc().diff(item.dob, 'years') } )).map(item => { if (item.age < 20) user_result["<20歲"]++ if (item.age >= 20 && item.age < 30) user_result["20~30歲"]++ if (item.age >= 30 && item.age < 40) user_result["30~40歲"]++ if (item.age >= 40 && item.age < 50) user_result["40~50歲"]++ if (item.age >= 50 && item.age < 60) user_result["50~60歲"]++ if (item.age > 60) user_result[">60歲"]++ }) let comments = await Comment.findAll({ where: { RestaurantId: restaurant.id }, attributes: ['rating', [sequelize.literal(`COUNT(*)`), 'count']], group: ['rating'] }) // check if the rating has missing field const original_ratings = comments.map(item => item.dataValues.rating) const missing_fields = [1, 2, 3, 4, 5].filter(v => original_ratings.indexOf(v) === -1) // create the an end result object for later sorting const rating_result = comments.map(item => ({ rating: item.dataValues.rating, count: item.dataValues.count })) // if missing fields exist,fill in with value 0 missing_fields.map(async item => { await rating_result.push({ rating: item, count: 0 }) }) // sort the result const sorted = rating_result.sort((a, b) => { return b.rating - a.rating }) // adjust rating data format for front-end const ratings = { labels: ['5星', '4星', '3星', '2星', '1星'], data: sorted.map(item => Number(item.count)), tableName: '滿意度', average: sorted.every(item => Number(item.count) === 0) ? 0 : Number.parseFloat(sorted.reduce((total, current) => total + Number(current.rating) * Number(current.count), 0) / sorted.reduce((total, current) => total + Number(current.count), 0)).toFixed(1) } // adjust comment data format for front-end comments = await Comment.findAll({ where: { RestaurantId: restaurant.id }, attributes: ['user_text', 'rating', customQuery.literal.name, 'createdAt'], order: [['createdAt', 'DESC'], ['rating', 'DESC']], }) // adjust user data format for front-end users = { labels: Object.keys(user_result), data: Object.values(user_result), tableName: '客群', total: Object.values(user_result).reduce((total, current) => total + Number(current), 0) } // adjust order data format for front-end orders = { labels: dateArray, data: order_result.map(item => Number(item.count)), tableName: '訂單', total: Object.values(order_result).reduce((total, current) => total + Number(current.count), 0) } return res.status(200).json({ status: 'success', orders, comments, ratings, users, message: 'Successfully get owner dashboard' }) } catch (error) { res.status(500).json({ status: 'error', message: error }) } } } module.exports = ownerController
import { EventHandler } from '../../core/event-handler.js'; import { platform } from '../../core/platform.js'; import { XrTrackedImage } from './xr-tracked-image.js'; /** * Image Tracking provides the ability to track real world images by provided image samples and * their estimated sizes. * * @augments EventHandler * @category XR */ class XrImageTracking extends EventHandler { /** * @type {import('./xr-manager.js').XrManager} * @private */ _manager; /** * @type {boolean} * @private */ _supported = platform.browser && !!window.XRImageTrackingResult; /** * @type {boolean} * @private */ _available = false; /** * @type {XrTrackedImage[]} * @private */ _images = []; /** * Image Tracking provides the ability to track real world images by provided image samples and * their estimate sizes. * * @param {import('./xr-manager.js').XrManager} manager - WebXR Manager. * @hideconstructor */ constructor(manager) { super(); this._manager = manager; if (this._supported) { this._manager.on('start', this._onSessionStart, this); this._manager.on('end', this._onSessionEnd, this); } } /** * Fired when the XR session is started, but image tracking failed to process the provided * images. * * @event XrImageTracking#error * @param {Error} error - Error object related to a failure of image tracking. */ /** * Add an image for image tracking. A width can also be provided to help the underlying system * estimate the appropriate transformation. Modifying the tracked images list is only possible * before an AR session is started. * * @param {HTMLCanvasElement|HTMLImageElement|SVGImageElement|HTMLVideoElement|Blob|ImageData|ImageBitmap} image - Image * that is matching real world image as close as possible. Resolution of images should be at * least 300x300. High resolution does NOT improve tracking performance. Color of image is * irrelevant, so grayscale images can be used. Images with too many geometric features or * repeating patterns will reduce tracking stability. * @param {number} width - Width (in meters) of image in the real world. Providing this value * as close to the real value will improve tracking quality. * @returns {XrTrackedImage|null} Tracked image object that will contain tracking information. * Returns null if image tracking is not supported or if the XR manager is not active. * @example * // image with width of 20cm (0.2m) * app.xr.imageTracking.add(bookCoverImg, 0.2); */ add(image, width) { if (!this._supported || this._manager.active) return null; const trackedImage = new XrTrackedImage(image, width); this._images.push(trackedImage); return trackedImage; } /** * Remove an image from image tracking. * * @param {XrTrackedImage} trackedImage - Tracked image to be removed. Modifying the tracked * images list is only possible before an AR session is started. */ remove(trackedImage) { if (this._manager.active) return; const ind = this._images.indexOf(trackedImage); if (ind !== -1) { trackedImage.destroy(); this._images.splice(ind, 1); } } /** @private */ _onSessionStart() { this._manager.session.getTrackedImageScores().then((images) => { this._available = true; for (let i = 0; i < images.length; i++) { this._images[i]._trackable = images[i] === 'trackable'; } }).catch((err) => { this._available = false; this.fire('error', err); }); } /** @private */ _onSessionEnd() { this._available = false; for (let i = 0; i < this._images.length; i++) { const image = this._images[i]; image._pose = null; image._measuredWidth = 0; if (image._tracking) { image._tracking = false; image.fire('untracked'); } } } /** * @param {Function} callback - Function to call when all images have been prepared as image * bitmaps. * @ignore */ prepareImages(callback) { if (this._images.length) { Promise.all(this._images.map(function (trackedImage) { return trackedImage.prepare(); })).then(function (bitmaps) { callback(null, bitmaps); }).catch(function (err) { callback(err, null); }); } else { callback(null, null); } } /** * @param {*} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame) { if (!this._available) return; const results = frame.getImageTrackingResults(); const index = { }; for (let i = 0; i < results.length; i++) { index[results[i].index] = results[i]; const trackedImage = this._images[results[i].index]; trackedImage._emulated = results[i].trackingState === 'emulated'; trackedImage._measuredWidth = results[i].measuredWidthInMeters; trackedImage._pose = frame.getPose(results[i].imageSpace, this._manager._referenceSpace); } for (let i = 0; i < this._images.length; i++) { if (this._images[i]._tracking && !index[i]) { this._images[i]._tracking = false; this._images[i].fire('untracked'); } else if (!this._images[i]._tracking && index[i]) { this._images[i]._tracking = true; this._images[i].fire('tracked'); } } } /** * True if Image Tracking is supported. * * @type {boolean} */ get supported() { return this._supported; } /** * True if Image Tracking is available. This property will be false if no images were provided * for the AR session or there was an error processing the provided images. * * @type {boolean} */ get available() { return this._available; } /** * List of {@link XrTrackedImage} that contain tracking information. * * @type {XrTrackedImage[]} */ get images() { return this._images; } } export { XrImageTracking };
import { useEffect, useState } from "react"; import packageJson from "../../package.json"; const CacheBusting = ({ isEnable = true }) => { const [cacheStatus, setCacheStatus] = useState({ loading: true, isLatestVersion: false, }); let version = packageJson.version; const [metaVersion, setMetaVersion] = useState(""); useEffect(() => { checkCatchStatus(); }, []); const checkCatchStatus = async () => { try { console.log("executed"); const currentVersion = packageJson.version; const response = await fetch("/meta.json"); const { version: metaVersion } = await response.json(); const shouldForceReload = checkVersion(metaVersion, currentVersion); console.log(shouldForceReload); if (shouldForceReload) { alert(""); console.log( `We are having the new version ${metaVersion} Should need to force reload` ); setCacheStatus({ loading: false, isLatestVersion: false, }); } else { console.log("You are with the latest version. No need to reload"); setCacheStatus({ loading: false, isLatestVersion: true, }); } } catch (error) { console.error(error.message); } }; const refreshCacheAndReload = async () => { try { if (caches) { const cacheNames = await caches.keys(); await Promise.all(cacheNames.map((name) => caches.delete(name))); console.log("The cache has been cleared"); //alert("not equal"); console.log("not-equal"); window.location.reload(); } } catch (error) { console.error(error.message); } }; if (!cacheStatus.loading && !cacheStatus.isLatestVersion) { refreshCacheAndReload(); return null; } const checkVersion = (metaVersion, currentVersion) => { if (!currentVersion) { return false; } const metaVersions = metaVersion.split(/\./g); const currentVersions = currentVersion.split(/\./g); while (metaVersions.length || currentVersions.length) { const a = Number(metaVersions.shift()); const b = Number(currentVersions.shift()); console.log("a ", a); console.log("b ", b); if (a === b) { continue; } return a > b || isNaN(b); } return false; }; return ( <div> {!cacheStatus.loading && cacheStatus.isLatestVersion ? ( <h2>CacheBusting v-{`${version}`}</h2> ) : null} </div> ); }; export default CacheBusting;
import React from 'react'; import postImg from '../assets/logo.svg'; import './Post.css'; function Post({ message, likesCount }) { return ( <div className="post"> <img className="post__img" src={postImg} alt="post" /> {message} <div> <span className="post__like">like</span> {likesCount} </div> </div> ); } export default Post;
import React, { Component } from "react"; import "./UpdateOrder.css"; import { faCheckCircle } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import Header from "../../Components/Header/Header"; import SideNav from "../../Components/SideNav/SideNav"; import axios from "axios"; import { getOrderURLbyID, updateOrderURL } from "../../Services/endpoints"; import Swal from "sweetalert2"; export default class UpdateOrder extends Component { constructor(props) { super(props); this.state = { orderId: "", description: "", quantity: "", itemId: "", unitPrice: 0, totalPrice: 0, date: "", customerName: "", customerPhoneNo: "", status: "", orders: [], }; } async componentDidMount() { let id = localStorage.getItem("updateId"); await axios.get(getOrderURLbyID + id).then((result) => { this.setState({ orderId: result.data.orderId, description: result.data.description, itemId: result.data.itemId, quantity: result.data.quantity, unitPrice: result.data.unitPrice, totalPrice: result.data.totalPrice, date: result.data.date, customerName: result.data.customerName, customerPhoneNo: result.data.customerPhoneNo, status: result.data.status, }); }); } handleSubmit = (e) => { e.preventDefault(); let id = localStorage.getItem("updateId"); const data = { orderId: id, description: this.state.description, itemId: this.state.itemId, quantity: this.state.quantity, unitPrice: this.state.unitPrice, totalPrice: this.state.quantity*this.state.unitPrice, date: this.state.date, customerName: this.state.customerName, customerPhoneNo: this.state.customerPhoneNo, status: this.state.status, }; console.log("Data to send", data); axios.put(updateOrderURL, data).then(() => { Swal.fire({ icon: "success", title: "Update Successful!!!", }).then(() => { window.location = "/orderList"; }); }); }; handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }); }; render() { return ( <div> <SideNav /> <div className="content-layer"> <Header topic="Order Management" /> <div className="CreateOrder"> <div className="Order-Create-Heading-Container"> <h3 className="Add-Order-Heading">Update Order</h3> </div> <div className="Order-Create-Body-Container"> <form onSubmit={this.handleSubmit}> <div className="mb-3 row"> <label className="col-sm-3 col-form-label">Order Id. :</label> <div className="col-sm-9 "> <input style={{ backgroundColor: "#345454" }} className="form-control " type="text" id="orderId" name="orderId" placeholder="Order Id" readOnly="true" required value={this.state.orderId} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label"> Description : </label> <div className="col-sm-9"> <textarea className="form-control" type="text" id="description" name="description" placeholder="Order Description" required value={this.state.description} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label">Item No. :</label> <div className="col-sm-9"> <input className="form-control" type="text" id="itemId" name="itemId" placeholder="Item No." required value={this.state.itemId} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label"> Unit Price : </label> <div className="col-sm-9"> <input className="form-control" type="Number" id="unitPrice" name="unitPrice" placeholder="Unit Price" required value={this.state.unitPrice} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label">Quantity :</label> <div className="col-sm-9"> <input className="form-control" type="Number" id="quantity" name="quantity" placeholder="Quantity" required value={this.state.quantity} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label"> Total Price : </label> <div className="col-sm-9"> <input className="form-control" style={{ backgroundColor: "#345454" }} type="Number" id="totalPrice" name="totalPrice" placeholder="Total Price" required readOnly="true" value={this.state.quantity*this.state.unitPrice} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label">Order Date:</label> <div className="ui fluid col-sm-9"> <input className="form-control" type="date" id="date" name="date" placeholder="Order Date" required value={this.state.date} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label"> Customer Name : </label> <div className="col-sm-9"> <input className="form-control" type="text" id="customerName" name="customerName" placeholder="Customer Name" required value={this.state.customerName} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label"> Customer Phone No: </label> <div className="col-sm-9"> <input className="form-control" type="text" id="customerPhoneNo" name="customerPhoneNo" placeholder="Customer Phone Number" required value={this.state.customerPhoneNo} onChange={this.handleChange} /> </div> </div> <div className="mb-3 row"> <label className="col-sm-3 col-form-label">Status :</label> <div className="ui fluid col-sm-9"> <select className="form-control" name="status" value={this.state.status} onChange={this.handleChange} > <option value="Pending">Pending</option> <option value="Shipped">Shipped</option> <option value="Delivered">Delivered</option> <option value="Cancelled">Cancelled</option> </select> </div> </div> <div className="OrderRow"> <button type="submit" className="Order-Button-Update"> <FontAwesomeIcon icon={faCheckCircle} /> Update Order </button> </div> </form> </div> </div> </div> </div> ); } }
import React, { Component } from "react"; class Popular extends Component { render() { return ( <section className="popular-places"> <div className="container"> <div className="section-title"> <h3>Most Popular</h3> <h2>Places</h2> </div> <div className="row"> <div className="col-md-12"> </div> <div className="col-lg-4 col-md-6"> <a href="properties-right-sidebar.html" className="img-box hover-effect"> <img src={require('../../../images/popular-places/1.jpg')} className="img-responsive" alt="" /> <div className="listing-badges"> <span className="featured">Featured</span> </div> <div className="img-box-content visible"> <h4>New York City </h4> <span>203 Properties</span> </div> </a> </div> <div className="col-lg-8 col-md-6"> <a href="properties-right-sidebar.html" className="img-box hover-effect"> <img src={require('../../../images/popular-places/2.jpg')} className="img-responsive" alt="" /> <div className="img-box-content visible"> <h4>Los Angeles</h4> <span>307 Properties</span> </div> </a> </div> <div className="col-lg-8 col-md-6"> <a href="properties-right-sidebar.html" className="img-box hover-effect no-mb"> <img src={require('../../../images/popular-places/3.jpg')} className="img-responsive" alt="" /> <div className="img-box-content visible"> <h4>San Francisco </h4> <span>409 Properties</span> </div> </a> </div> <div className="col-lg-4 col-md-6"> <a href="properties-right-sidebar.html" className="img-box hover-effect no-mb x3"> <img src={require('../../../images/popular-places/4.jpg')} className="img-responsive" alt="" /> <div className="listing-badges"> <span className="featured">Featured</span> </div> <div className="img-box-content visible"> <h4>Miami</h4> <span>507 Properties</span> </div> </a> </div> </div> </div> </section> ); } } export default Popular;
// import Home from './page/home'; import Login from './page/login'; import Profile from './page/profile' import Register from './page/register'; function App() { return ( <Register/> ); } export default App;
// @flow strict import * as React from 'react'; import { HeaderButton } from '@kiwicom/mobile-navigation'; import { TextIcon } from '@kiwicom/mobile-shared'; import type { TooltipsTranslationType } from '@kiwicom/mobile-localization'; type Props = {| +onPress: () => void, +icon: React.Element<typeof TextIcon>, +text: TooltipsTranslationType, +testID?: string, |}; export default function MapHeaderButton(props: Props) { return ( <HeaderButton.Right onPress={props.onPress} testID={props.testID}> {props.icon} </HeaderButton.Right> ); }
/*================================================*\ * Author : Attaphon Wongbuatong * Created Date : 08/02/2016 01:14 * Module : Class * Description : Backoffice Javascript * Involve People : zeroline * Last Updated : 08/02/2016 01:14 \*================================================*/ /*================================================*\ :: FUNCTION :: \*================================================*/ me.ViewHeader=function(){ me.ViewSetHeader([ {display:'ธนาคาร', name:'bank_code',type:'cbo'}, {display:'ชื่อบัญชี', name:'name'}, {display:'เลขที่บัญชี', name:'acc_no'}, {display:'จำนวนเงิน', name:'balance',width:'200',align:'center',style:'danger'}, {display:'Action', name:'action',width:'200',align:'center', sort:false, search:false} ]); }; me.OpenRecord=function(code){ $('#ref_code').val(code); $('#amount').val(''); $('#type_record').val(''); var myData={ code : code }; $.ajax({ url:me.url+'?mode=OpenRecord&mod='+me.mod+'&'+new Date().getTime(), type:'GET', dataType:'json', data:myData, success:function(data){ $('#lyDetailLoad').text(''); me.LoadAppendData(data); $('#modalRecord').modal('show'); } }); }; me.LoadDataSave=function(){ var code = $('#ref_code').val(); var myData={ code : code }; $.ajax({ url:me.url+'?mode=OpenRecord&mod='+me.mod+'&'+new Date().getTime(), type:'GET', dataType:'json', data:myData, success:function(data){ $('#lyDetailLoad').text(''); me.LoadAppendData(data); } }); }; me.LoadAppendData=function(data){ var html = ''; html += '<tr id=bus_{time}" class="recorddata" rel="{code}">'; html += ' <td class="center">{no}</td>'; html += ' <td class="center">{date_create}</td>'; html += ' <td class="left">{type_record}</td>'; html += ' <td class="center danger">{bring_forward}</td>'; html += ' <td class="center">{amount}</td>'; html += ' <td class="center success" >{total}</td>'; html += ' <td class="center">{comment}</td>'; html += ' <td class="center">{user_create}</td>'; html += '</tr>'; var temp = ''; var cnt = data.length; $.each(data, function(i, attr){ temp = html; temp = temp.split('{code}').join(data.code); temp = temp.split('{no}').join(cnt-i); temp = temp.split('{date_create}').join(attr.date_create); temp = temp.split('{type_record}').join(attr.type_record); temp = temp.split('{bring_forward}').join(ft.NumberDisplay(attr.bring_forward,0)); temp = temp.split('{amount}').join(ft.NumberDisplay(attr.amount,0)); temp = temp.split('{total}').join(ft.NumberDisplay(attr.total,0)); temp = temp.split('{comment}').join(attr.comment); temp = temp.split('{user_create}').join(attr.user_create); $('#lyDetailLoad').append(temp); }); }; // me.LoadAppendData=function(data){ // var html = ''; // html += '<tr id=bus_{time}" class="recorddata" rel="{code}">'; // html += ' <td class="center">{no}</td>'; // html += ' <td class="center">{date_create}</td>'; // html += ' <td class="left">{type_record}</td>'; // html += ' <td class="center">{bring_forward}</td>'; // html += ' <td class="center">{amount}</td>'; // html += ' <td class="center">{total}</td>'; // html += ' <td class="center">{user_create}</td>'; // html += '</tr>'; // var time = new Date().getTime(); // html = html.split('{code}').join(data.code); // html = html.split('{no}').join($('.recorddata').length+1); // html = html.split('{date_create}').join(data.date_create); // html = html.split('{type_record}').join(data.type_record); // html = html.split('{bring_forward}').join(ft.NumberDisplay(data.bring_forward,0)); // html = html.split('{amount}').join(ft.NumberDisplay(data.amount,0)); // html = html.split('{total}').join(ft.NumberDisplay(data.total,0)); // html = html.split('{user_create}').join(data.user_create); // $('#lyDetailLoad').append(html); // }; me.SaveRecord=function(){ if($('#amount').val() == ""){ alert('กรุณาใส่ จำนวนเงิน'); $('#amount').focus() return false; } if($('#type_record').val() == ""){ alert('กรุณาเลือก ประเภทรายการ'); $('#type_record').focus() return false; } var myData = { data : ft.LoadForm('mydatab') }; $.ajax({ url:me.url+'?mode=SaveRecord&mod='+me.mod, type:'POST', dataType:'json', cache:false, data:myData, success:function(data){ alert('บันทึกข้อมูลสำเร็จ'); $('#amount').val(''); $('#type_record').val(''); me.LoadDataSave(); } }); }; me.LoadCbo=function(){ $.getJSON(me.url+'?mode=LoadCbo&mod='+me.mod+'&'+new Date().getTime(), {}, function(data){ $.each(data.bank, function(i, result) { $('<option>').attr('value', result.code).text(result.name).appendTo('#bank_code'); $('<option>').attr('value', result.code).text(result.name).appendTo('#search_bank_code'); }); }); }; /*================================================*\ :: DEFAULT :: \*================================================*/ $(document).ready(function(){ me.SetUrl(); me.ViewHeader(); me.LoadCbo(); me.SetSort('name', 'asc'); $('#amount').bind('keypress', function (event) { var regex = new RegExp("^[0-9]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } }); me.View(); });
import React from "react"; import { BiComment } from "react-icons/bi"; import "./NormalPostV.css"; import { Link, useLocation, } from "react-router-dom"; import { url } from "../../../baseHost"; export const NormalPostV = (props) => { // console.log(props.post) return ( <div style={props.style} className="Normal_postV_cont"> <div className="Normal_postV_cont_image"style={{ backgroundImage: `url("${url}/${props.post.image}")` }} ></div> <div className="Normal_postV_text_cont"> <h2>{props.post.Title}</h2> <div className="Normal_postV_cont_date"> <div>{props.post.Date}</div> <div> <BiComment /> 200 </div> </div> <p> {props.post.Article.replace(/<\/?[^>]+(>|$)/g, "").split('').filter((e,i)=>i<50).join('')} ... </p> <Link to={`/article/${props.post._id}`} className="Normal_postV_morebtn">More ...</Link> </div> </div> ); };
const {BaseModel} = require('../base.model') class Educations extends BaseModel{ static get tableName(){ return 'support.educations' } static get idColumn(){ return 'id_education' } static get relationMappings(){ return{ guru:{ relation: BaseModel.HasManyRelation, modelClass: BaseModel.modelPaths + '/guru/guru.model', join:{ from: 'support.educations.id_education', to: 'guru.guru.education_id' } }, } } } module.exports = Educations
export const GET_EMPLOYEES = 'app/Employees/GET_EMPLOYEES'; export const GET_ALL_EMPLOYEES = 'app/Employees/GET_ALL_EMPLOYEES'; export const GET_DEPARTMENT = 'app/UserCard/GET_DEPARTMENT'; export const GET_ALL_DEPARTMENT = 'app/UserCard/GET_ALL_DEPARTMENT'; export const DELETE_EMPLOYEES = 'app/Employees/DELETE_EMPLOYEES'; export const GET_CONST_EMPLOYEES = 'app/Employees/GET_CONST_EMPLOYEES'; export const GET_CONST_ALL_EMPLOYEES = 'app/Employees/GET_CONST_ALL_EMPLOYEES';
function goCart(){ $.ajax({ url: "/shop/list", type: "POST", success: function(result) { var bill = JSON.parse(result); if(bill.goodsCount == 0){ var pbill = "<p>购物车是空的<p>"; $("#bill").append(pbill); $("#bill").addClass("cartisnull"); }else{ var pnamet = "<p>商品名<p>"; var pvaluet = "<p>商品价格<p>"; $("#dis-goods-name").append(pnamet); $("#dis-goods-price").append(pvaluet); $.each(bill.allGoods, function(name,value) { var pname = "<p>" + name + "<p>"; var pvalue = "<p>" + value + "<p>"; $("#dis-goods-name").append(pname); $("#dis-goods-price").append(pvalue); }); var pgoodsCount = "<p>总数:" + bill.goodsCount + "<p>"; var ptotalPrice = "<p>总计:" + bill.totalPrice + "<p>"; $("#dis-goods-name").append(pgoodsCount); $("#dis-goods-price").append(ptotalPrice); } } }); } function addCart(){ var goods = $("#goods-name").val(); var price = $("#goods-price").val(); $.ajax({ url: "/shop/add", type: "POST", data: { goods:goods, price:price }, success: function(result) { if(result == "ok"){ $("#goods-name").val(""); $("#goods-price").val(""); }else{ alert("添加购物车失败"); } } }); }
// As funções call e apply nos deixam invocar métodos como se estivéssemos no contexto de um outro objeto: var myself = { firstName: 'Matheus', lastName: 'Lima' }; function showFullName() { console.log(this.firstName + " " + this.lastName); } showFullName.call(myself); // Matheus Lima showFullName.apply(myself); // Matheus Lima // Enquanto apply aceita um array, call requer parâmetros divididos por vírgulas: var myself2 = { age: 26 }; function isOlderThan() { for (var i = 0; i < arguments.length; i++) { console.log(this.age < arguments[i]); } } isOlderThan.call(myself2, 30, 40, 15); // true true false isOlderThan.apply(myself2, [30, 40, 15]); // true true false //Qual a importância? // A importância desses dois métodos e o porquê deles serem tão usados (principalmente em libs) é bem simples: apply e call nos permitem pegar métodos emprestados reduzindo assim a quantidade total de código gerada e seguindo o DRY.
'use strict'; angular.module('blipApp') .controller('UserLocationsCTRL', ['$http', '$scope', '$location', 'ResultPageState', '$rootScope', function($http, $scope, $location, ResultPageState, $rootScope) { //Close mobile-navigation menu on page load $rootScope.toggleNavClass = $rootScope.animateOut; $scope.currentPath = $location.path(); $scope.userLocations = ""; $scope.filterUserLocations = []; $scope.showLoadingAnimation = true; var user = { ID: parseInt($rootScope.userIdCookie), }; $scope.getUserLocations = function() { $http.post('http://localhost/blip/app/phpCore/get_user_locations.php', user) .then(function(response) { $scope.userLocations = response.data; $scope.filterUserLocations = $scope.userLocations; $scope.showLoadingAnimation = false; localStorage.cacheUserLocs = JSON.stringify($scope.filterUserLocations); }); }; //Called from front-end to set filtered results and set active class on button $scope.setFilterSetClass = function(filter, index) { getFilter(filter); setQuickFilterClass(index); }; //Called to return filtered content //If search result matches the filter button it gets pushed into 'filterUserLocations' array //else 'filterUserLocations' equals the content that was origionaly returned from the server var getFilter = function(filter) { if (filter !== "All") { $scope.filterUserLocations = []; angular.forEach($scope.userLocations, function(value) { if (value.CategoryName === filter) { $scope.filterUserLocations.push(value); } }); } else { $scope.filterUserLocations = $scope.userLocations; } }; //Sets active class on selected filter button $scope.activeFilter = 0; var setQuickFilterClass = function(type) { $scope.activeFilter = type; }; //Set class for individual search results based off location type //typeHeadClass -- controls the serarch result header //setIconClass -- controls the icon that is displayed on the header //return class controls the styles for the hover action on each result $scope.typeHeadClass = " "; $scope.setIconClass = " "; $scope.setResultClass = function(classIn) { switch (classIn) { case 'Bar': { $scope.typeHeadClass = "result-header-bar"; $scope.setIconClass = "fa fa-glass fa-lg"; return ""; } case 'Restaurant': { $scope.typeHeadClass = "result-header-restaurant"; $scope.setIconClass = 'fa fa-cutlery fa-lg'; return ""; } case 'Supermarket': { $scope.typeHeadClass = "result-header-shop"; $scope.setIconClass = 'fa fa-shopping-cart fa-lg'; return ""; } case 'Other': { $scope.typeHeadClass = "result-header-other"; $scope.setIconClass = "fa fa-ellipsis-h fa-lg"; return ""; } default: { return ""; } } }; $scope.confirmDeleteLocation = function(index) { $scope.nameToDelete = $scope.filterUserLocations[index].LocationName; $scope.indexToDelete = index; $("#myModal").modal('show'); }; $scope.cancelDeleteLocation = function () { $("#myModal").modal('hide'); } $scope.deleteLocation = function() { $http.post('http://localhost/blip/app/phpCore/delete_location.php', $scope.filterUserLocations[$scope.indexToDelete]) .then(function(response) { console.log("Success"); }); $("#myModal").modal('hide'); $scope.filterUserLocations.splice($scope.indexToDelete, 1); }; $scope.editLocation = function(index) { ResultPageState.SetPageState($scope.filterUserLocations[index]); ResultPageState.SetEditState(true); $location.path('LocationView'); }; $scope.storeFocusedResult = function(index) { ResultPageState.SetPageState($scope.filterUserLocations[index]); ResultPageState.SetEditState(false); $location.path('LocationView'); }; }]);
"use strict"; var Graphics = /** @class */ (function () { function Graphics(g, bounds) { this.g = g; this.bounds = bounds; this.offsetX = 0; this.offsetY = 0; } Graphics.prototype.drawImage = function (img, sx, sy, sw, sh, dx, dy, dw, dh) { var ax = dx - this.offsetX + this.bounds.width / 2 - dw / 2; var ay = dy - this.offsetY + this.bounds.height / 2 - dh; if (ax + dw < 0 || ax - dw / 2 > this.bounds.width || ay + dh < 0 || ay >= this.bounds.height) return; this.g.drawImage(img, sx, sy, sw, sh, Math.round(ax), Math.round(ay), dw, dh); }; Graphics.prototype.clearRect = function (x, y, w, h) { this.g.clearRect(x, y, w, h); }; Graphics.prototype.translate = function (x, y) { this.offsetX = x; this.offsetY = y; }; return Graphics; }());
import React from "react"; import device from "../../images/image-block/device.jpg"; import probirka from "../../images/image-block/probirka.jpg"; const About = () => { return ( <div className="s-second-screen"> <div className="container"> <div className="section-title">О&nbsp;компании</div> <div className="image-block"> <div className="text-border"> <div className="image-block__text"> <div className="image-block__title">мы занимаемся Производством лекарственных препаратов и медицинских изделий</div> <p className="image-block__content">«ТК Фарм Актобе» является одной из крупнейших фармацевтических компаний не только в Актюбинской области, но и по всему Казахстану. Компания производит выпуск противокашлевых сиропов: солодки, солодки с термопсисом и пертуссин, а также экстракта корня солодки и глицирризиновой кислоты высокой степени очистки для использования в косметологии и фармацевтике.</p> </div> </div> <div className="image-block__photo"> <div className="photo-border photo-border--right"></div> <img src={device}></img> </div> </div> <div className="image-block"> <div className="image-block__photo"> <div className="photo-border photo-border--left"></div> <img src={probirka}></img> </div> <div className="text-border"> <div className="image-block__text"> <div className="image-block__title">мы занимаемся Производством лекарственных препаратов и медицинских изделий</div> <p className="image-block__content">«ТК Фарм Актобе» является одной из крупнейших фармацевтических компаний не только в Актюбинской области, но и по всему Казахстану. Компания производит выпуск противокашлевых сиропов: солодки, солодки с термопсисом и пертуссин, а также экстракта корня солодки и глицирризиновой кислоты высокой степени очистки для использования в косметологии и фармацевтике.</p> </div> </div> </div> </div> </div> ); } export default About;
$( document ).ready() { //var redditApi = "http://www.reddit.com/r/jokes/hot.json?limit=50"; //fetchReddit( redditApi ); $( "#funny" ).click(function() { var redditApi = "http://www.reddit.com/r/jokes/hot.json?limit=50"; fetchReddit( redditApi ); }); $( "#unfunny" ).click(function() { var redditApi = "http://www.reddit.com/r/antijokes/hot.json?limit=50"; fetchReddit( redditApi ); }); } function fetchReddit( redditApi ) { //redditApi = "http://www.reddit.com/r/jokes/hot.json?limit=50"; $.getJSON(redditApi, function( json ){ var jokes = json.data.children; var jokesDiv = document.getElementById('jokes'); $.each( jokes, function( key, value) { title = jokes[key]['data']['title']; text = jokes[key]['data']['selftext']; score = jokes[key]['data']['score']; $('#jokes > tbody:last').append('<tr><td>' + score + '</td><td><b>' + title + '</b> ' + text +'</td></tr>'); }); }); }
import { useEffect, useState } from 'react'; import './App.css'; import Cards from './Components/Cards/Cards'; import Header from './Components/Header/Header'; import Preview from './Components/Preview/Preview'; function App() { // hooks const [players, setPlayers] = useState([]); const [selectedPlayers, setSelectedPlayers] = useState([]); // fetch data useEffect(() => { fetch("https://api.npoint.io/2fa013978b09d3cc5e85") .then(response => response.json()) .then(data => setPlayers(data)) }, []); // buttonClickManagement let newSelected = selectedPlayers; const addClickedPlayer = (player) =>{ hideCard(); if(selectedPlayers.indexOf(player) === -1){ newSelected = [...selectedPlayers, player]; } setSelectedPlayers(newSelected); }; const hideCard = () =>{ const preview = document.getElementsByClassName("preview"); const list = document.getElementsByClassName("list") if(list.innerHTML !== ""){ preview[0].classList.remove("none"); } } // return return ( <div className="App"> <Header></Header> <p className="slogan">/---Make Your Dream Team ! ---/</p> <Preview selectedPlayers={selectedPlayers} ></Preview> <div className="main"> { players.map(player => <Cards player={player} addClickedPlayer={addClickedPlayer}></Cards>) } </div> </div> ); } export default App;
import React, {Component} from 'react'; import { connect } from 'react-redux'; import {injectIntl, intlShape} from 'react-intl'; import { Activity } from '../../containers/Activity'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { withFirebase } from 'firekit-provider'; import { withRouter } from 'react-router-dom'; import ReactList from 'react-list'; import Avatar from 'material-ui/Avatar'; import FloatingActionButton from 'material-ui/FloatingActionButton'; import FontIcon from 'material-ui/FontIcon'; import PropTypes from 'prop-types'; import { setPersistentValue } from '../../store/persistentValues/actions'; import { ChatMessages } from '../../containers/ChatMessages'; import Scrollbar from '../../components/Scrollbar/Scrollbar'; import { filterSelectors } from 'material-ui-filter' class Chats extends Component { componentDidMount(){ const { watchList, path } =this.props; watchList(path); } handleItemClick = (val, key) => { const { usePreview, history, setPersistentValue, firebaseApp, auth } = this.props; if(val.unread>0){ firebaseApp.database().ref(`user_chats/${auth.uid}/${key}/unread`).remove(); } if(usePreview){ setPersistentValue('current_chat_uid', key); }else{ history.push(`/chats/edit/${key}`); } } renderItem = (i, k) => { const { list, intl, currentChatUid, usePreview, muiTheme } = this.props; const key=list[i].key; const val=list[i].val; const isPreviewed=usePreview && currentChatUid===key; return <div key={i}> <ListItem leftAvatar={ <Avatar alt="person" src={val.photoURL} icon={<FontIcon className="material-icons">person</FontIcon>} /> } style={isPreviewed?{backgroundColor: muiTheme.toolbar.separatorColor}:undefined} onClick={()=>{this.handleItemClick(val, key)}} key={key} id={key} rightIcon={ <div style={{width: 'auto',fontSize: 11,color: muiTheme.listItem.secondaryTextColor }}> <div style={{width: 'auto',color: val.unread>0?muiTheme.palette.primary1Color:undefined}} > {val.lastCreated?intl.formatTime(new Date(val.lastCreated), 'hh:mm'):undefined} </div> {val.unread>0 && <div style={{textAlign: 'right'}}> <Avatar size={20} backgroundColor={muiTheme.palette.primary1Color} color={muiTheme.palette.primaryTextColor} alt="unread"> <div style={{color: muiTheme.listItem.secondaryTextColor}} > {val.unread} </div> </Avatar> </div> } </div> } primaryText={val.unread>0?<div><b>{val.displayName}</b></div>:val.displayName} secondaryText={val.unread>0?<div><b>{val.lastMessage}</b></div>:val.lastMessage} /> <Divider inset={true}/> </div>; } render(){ const { intl, list, history, currentChatUid, usePreview, auth } = this.props; const isDisplayingMessages=usePreview && currentChatUid; return ( <Activity isLoading={list===undefined} title={intl.formatMessage({id: 'chats'})}> <div style={{ height: '100%', width: '100%', alignItems: 'strech', display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-start', flexDirection: 'row' }}> <Scrollbar style={{ maxWidth: usePreview?300:undefined}}> <List style={{padding:0, height: '100%', width:'100%', maxWidth: usePreview?300:undefined}} > <ReactList style={{maxWidth: 300}} itemRenderer={this.renderItem} length={list?list.length:0} type='simple' /> </List> </Scrollbar> <div style={{position: 'absolute', width: usePreview?300:'100%', bottom:5}}> <FloatingActionButton onClick={()=>{history.push(`/chats/create`)}} style={{position: 'absolute', right: 20, bottom: 10, zIndex: 99}} secondary={true}> <FontIcon className="material-icons" >chat</FontIcon> </FloatingActionButton> </div> <div style={{marginLeft: 0, flexGrow: 1}}> {isDisplayingMessages && <ChatMessages path={`user_chat_messages/${auth.uid}/${currentChatUid}`} /> } </div> <div style={{ float:"left", clear: "both" }} /> </div> </Activity> ); } } Chats.propTypes = { list: PropTypes.array.isRequired, history: PropTypes.object, intl: intlShape, }; const mapStateToProps = (state, ownPops) => { const { lists, auth, browser, persistentValues } = state; const path=`user_chats/${auth.uid}`; const usePreview=browser.greaterThan.small; const currentChatUid=persistentValues['current_chat_uid']?persistentValues['current_chat_uid']:undefined; const list=lists[path]?lists[path].sort(filterSelectors.dynamicSort('lastCreated', false, fieldValue => fieldValue.val)):[]; return { auth, path, usePreview, currentChatUid, list, }; }; export default connect( mapStateToProps, { setPersistentValue } )(injectIntl(withFirebase(withRouter(muiThemeable()(Chats)))));
import { readFile, writeFile } from './fs.js' export async function replaceInReadme (startMarker, endMarker, replacement) { let readme = await readFile('./README.md', 'utf8') const startIndex = readme.indexOf(startMarker) const endIndex = readme.indexOf(endMarker) + endMarker.length readme = readme.substring(0, startIndex) + startMarker + '\n\n' + replacement + '\n\n' + endMarker + readme.substring(endIndex) await writeFile('./README.md', readme, 'utf8') }
"use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var symbioteSymbols = require('symbiote-symbol'); var nanoid = require('nanoid'); module.exports = { createSymbiote: createSymbiote /** * @param {{}} initialState * @param {{}} actionsConfig * @param {defaultOptions | string} namespaceOptions * @returns {{ actions: {}, reducer: Function }} */ }; function createSymbiote(initialState, actionsConfig) { var namespaceOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : nanoid(); var builder = new SymbioteBuilder({ state: initialState, options: createOptions(namespaceOptions) }); return builder.createSymbioteFor(actionsConfig); } /** * @param {defaultOptions | string} options * @return {defaultOptions} */ function createOptions(options) { if (typeof options === 'string') { return Object.assign({}, defaultOptions, { namespace: options }); } return Object.assign({}, defaultOptions, options); } var defaultOptions = { /** @type {string} */ namespace: undefined, /** @type {Function} */ defaultReducer: undefined, /** @type {string} */ separator: '/' }; var SymbioteBuilder = /*#__PURE__*/ function () { function SymbioteBuilder(_ref) { var state = _ref.state, options = _ref.options; _classCallCheck(this, SymbioteBuilder); this.initialReducerState = state; this.options = options; this.actions = {}; this.reducers = {}; this.namespacePath = options.namespace ? [options.namespace] : []; } _createClass(SymbioteBuilder, [{ key: "createSymbioteFor", value: function createSymbioteFor(actions) { var actionCreators = this.createActionsForScopeOfHandlers(actions, this.namespacePath); return { actions: actionCreators, reducer: this.createReducer(), types: extractTypesForActionCreators({}, actionCreators) }; } }, { key: "createActionsForScopeOfHandlers", value: function createActionsForScopeOfHandlers(reducersMap, parentPath) { var _this = this; var actionsMap = {}; Object.keys(reducersMap).forEach(function (key) { var currentPath = createPathFor(parentPath, key); var currentHandlerOrScope = reducersMap[key]; var currentType = _this.createTypeFromPath(currentPath); if (isHandler(currentHandlerOrScope)) { var currentHandler = currentHandlerOrScope; actionsMap[key] = makeActionCreatorFor(currentType, currentHandler); _this.saveHandlerAsReducerFor(currentType, currentHandler); } else if (isScope(currentHandlerOrScope)) { actionsMap[key] = _this.createActionsForScopeOfHandlers(currentHandlerOrScope, currentPath); } else { throw new TypeError('createSymbiote supports only function handlers and object scopes in actions config'); } }); return actionsMap; } }, { key: "createTypeFromPath", value: function createTypeFromPath(path) { return path.join(this.options.separator); } }, { key: "saveHandlerAsReducerFor", value: function saveHandlerAsReducerFor(type, handler) { this.reducers[type] = handler; } }, { key: "createReducer", value: function createReducer() { var _this2 = this; return function () { var previousState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this2.initialReducerState; var action = arguments.length > 1 ? arguments[1] : undefined; if (!action) throw new TypeError('Action should be passed'); var reducer = _this2.findReducerFor(action.type); if (reducer) { return reducer(previousState, action); } return previousState; }; } }, { key: "findReducerFor", value: function findReducerFor(type) { var expectedReducer = this.reducers[type]; if (expectedReducer) { return function (state, _ref2) { var _ref2$symbiotePayloa = _ref2['symbiote-payload'], payload = _ref2$symbiotePayloa === void 0 ? [] : _ref2$symbiotePayloa; return expectedReducer.apply(void 0, [state].concat(_toConsumableArray(payload))); }; } return this.options.defaultReducer; } }]); return SymbioteBuilder; }(); function createPathFor(path) { for (var _len = arguments.length, chunks = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { chunks[_key - 1] = arguments[_key]; } return path.concat.apply(path, chunks); } function isHandler(handler) { return typeof handler === 'function'; } function isScope(scope) { return !Array.isArray(scope) && scope !== null && _typeof(scope) === 'object'; } var createDefaultActionCreator = function createDefaultActionCreator(type) { return function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return { type: type, payload: args[0], 'symbiote-payload': args }; }; }; function makeActionCreatorFor(type, handler) { var createActionCreator = handler[symbioteSymbols.getActionCreator] || createDefaultActionCreator; var actionCreator = createActionCreator(type); actionCreator.toString = function () { return type; }; return actionCreator; } function extractTypesForActionCreators(types, actionCreators) { Object.keys(actionCreators).forEach(function (x) { if (_typeof(actionCreators[x]) === 'object') { if (typeof types[x] === 'undefined') { types[x] = {}; } extractTypesForActionCreators(types[x], actionCreators[x]); } else { types[x] = actionCreators[x].toString(); } }); return types; }
if(typeof(JS_LIB_LOADED)=='boolean') { var JS_APPROUTINES_FILE = "appRoutines.js"; var JS_APPROUTINES_LOADED = true; /****************** Common Application Routines *********************/ /**************************** QUIT **********************************/ function jslibQuit() { try { var windowManager = C.classes['@mozilla.org/appshell/window-mediator;1'] .getService(C.interfaces.nsIWindowMediator); var enumerator = windowManager.getEnumerator(null); // we are only closing dom windows for now // var appShell = C.classes['@mozilla.org/appshell/appShellService;1'].getService(); // appShell = appShell.QueryInterface(C.interfaces.nsIAppShellService); while (enumerator.hasMoreElements()) { var domWindow = enumerator.getNext(); if (("tryToClose" in domWindow) && !domWindow.tryToClose()) return false; domWindow.close(); } // we are only closing dom windows for now // appShell.quit(C.interfaces.nsIAppShellService.eAttemptQuit); } catch (e) { jslibPrint(e); } return true; } /**************************** QUIT **********************************/ jslibDebug('*** load: '+JS_APPROUTINES_FILE+' OK'); } // END BLOCK JS_LIB_LOADED CHECK // If jslib base library is not loaded, dump this error. else { dump("JS_BASE library not loaded:\n" + " \tTo load use: chrome://jslib/content/jslib.js\n" + " \tThen: include('chrome://jslib/content/xul/appRoutines.js');\n\n"); }; // END FileSystem Class
import React from 'react'; import './index.css'; const About = () => ( <main id="about"> 我是容器内部组件 </main> ); export default About;
document.getElementById("loadbutton").addEventListener("click", ajaxcall); function ajaxcall(){ var ajax = new XMLHttpRequest(); ajax.open("GET", "https://assets.breatheco.de/json/project_list.php", true); ajax.addEventListener("load", ajaxArrives); ajax.send(); } function ajaxArrives(event){ var cardContent ='<div class="card" style="width: 20rem;">' + '<img class="card-img-top" src="%img%" alt="Card image cap">' + '<div class="card-body">'+ '<h4 class="card-title">%title%</h4>'+ '<p class="card-text">%desc%</p>'+ '</div>'+ '</div>'; var jsonObj = JSON.parse(event.target.response); var text =""; var wholeContent = ""; for (var i = 0 ; i <jsonObj.length; i++) { text = cardContent.replace("%img%", jsonObj[i].thumb); text = text.replace("%title%", jsonObj[i].name); text = text.replace("%desc%", jsonObj[i].description); wholeContent += text; // text = "<li>" + jsonObj[i].name + "</li>"; // document.getElementById("getList").innerHTML += text; // text = "<li>" + jsonObj[i].thumb + "</li>"; // document.getElementById("getList").innerHTML += text; // text = "<li>" + jsonObj[i].description + "</li>"; // document.getElementById("getList").innerHTML += text; // text = "<li>" + jsonObj[i].images + "</li>"; // document.getElementById("getList").innerHTML += text; } var myJSON =""; var localStorage =""; document.getElementById("wholeContent").innerHTML=wholeContent; }
import React from 'react'; import { Platform, } from 'react-native'; import { TabNavigator, StackNavigator, DrawerNavigator } from 'react-navigation'; import { Icon } from 'react-native-elements'; import FeedUsers from '../containers/FeedUsersContainer'; import Settings from '../containers/SettingsContainer'; import TakePhoto from '../containers/TakePhotoContainer'; import UserDetail from '../containers/UserDetailContainer'; import Home from '../containers/HomeContainer'; import LaborDetail from '../components/LaborDetail'; import CameraRollPicker from '../containers/CameraRollPickerContainer'; import SendInfo from '../containers/SendInformationContainer'; import LaborNews from '../components/LaborDetailWebView'; import CameraPicker from '../containers/CameraContainer'; import LoginStatus from '../containers/LoginStatusContainer'; import Login from '../containers/LoginContainer'; import Register from '../containers/RegisterContainer'; import SelectUser from '../containers/SelectUserContainer'; import VerificateCode from '../containers/VerificateCodeContainer'; import { configData } from '../branding/index'; import I18n from '../i18n/index' export const FeedStack = StackNavigator({ Feed: { screen: FeedUsers, navigationOptions: { title: I18n.t('LABOR'), headerBackTitle: null, }, }, Details: { screen: UserDetail, navigationOptions: ({navigation, screenProps}) => ({ cardStack: { gesturesEnabled: true, }, // title: `${navigation.state.params.name.first.toUpperCase()} ${navigation.state.params.name.last.toUpperCase()}`, title: configData.App.appTitle, }), }, }, { //mode: 'modal', //headerMode: 'none', }); export const SelectUserStack = StackNavigator({ SelectUser: { screen: SelectUser, navigationOptions: { title: '', headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, header: null, }, } }, { mode: 'modal', //headerMode: 'none', }); export const IndexStack = StackNavigator({ SelectUser: { screen: SelectUser, navigationOptions: { title: '', headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, header: null, }, }, LoginStatus: { screen: LoginStatus, navigationOptions: { title: '', headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, header: null, }, }, Login: { screen: Login, navigationOptions: { title: I18n.t('LOGIN'), headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, }, }, Register: { screen: Register, navigationOptions: { title: I18n.t('REGISTR'), headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, }, }, VerificateCode: { screen: VerificateCode, navigationOptions: { title: I18n.t('VERIFICATION'), headerBackTitle: null, headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', }, }, }, }, { mode: 'card', //headerMode: 'none', }); export const Root = StackNavigator({ Index: { screen: IndexStack, }, // SelectUser: { // screen: SelectUserStack, // }, Home: { screen: Home, navigationOptions: { title: configData.App.appTitle, headerBackTitle: null, }, }, LaborDetail: { screen: LaborDetail, navigationOptions: { title: I18n.t('LABOR'), headerTintColor:'#fafff4', headerStyle:{ backgroundColor:'#22356B', } }, }, TakePhoto: { screen: TakePhoto, navigationOptions: { title: I18n.t('SUBMIT_FOTO'), }, }, SendInfo: { screen: SendInfo, navigationOptions: { title: I18n.t('SUBMIT_FOTO'), }, }, CameraRoll: { screen: CameraRollPicker, navigationOptions: { title: I18n.t('TAKE_PHOTO'), }, }, Camera: { screen: CameraPicker, navigationOptions: { title: I18n.t('TAKE_PHOTO'), }, }, Settings: { screen: Settings, navigationOptions: { title: I18n.t('SETTINGS'), }, }, LaborNews: { screen: LaborNews, navigationOptions: { title: 'News', }, }, Feed: { screen: FeedStack, }, // Feed: { // screen: FeedUsers, // navigationOptions: { // title: I18n.t('LABOR'), // headerBackTitle: null, // }, // }, // Details: { // screen: UserDetail, // navigationOptions: ({navigation, screenProps}) => ({ // cardStack: { // gesturesEnabled: true, // }, // title: `${navigation.state.params.name.first.toUpperCase()} ${navigation.state.params.name.last.toUpperCase()}` // }), // }, }, { initialRouteName: 'Index', headerMode: 'none', mode: Platform.OS === 'ios' ? 'modal' : 'card', });
/* create filter banks */ function filtered(data){ // init let resp_data = []; let tmp_sum; let filter_width = parseInt( data.length / N_FILTERS ); for( let i = 0; i < N_FILTERS; i++ ){ tmp_sum = 0; /* sum energies over each filter */ for( let j = i * filter_width; j < ( i+1 ) * filter_width; j++ ){ tmp_sum += data[j]; } resp_data.push( parseInt( tmp_sum/( 1+filter_width ) ) ); } return resp_data; } /* Get access to microphone and print status */ function get_mic_input(){ let flags = {audio:true, video:false}; navigator.getUserMedia ( flags, function( stream ){ let source = audio_ctx.createMediaStreamSource( stream ); source.connect ( audio_analyser ) ; }, function( error ){ console.log( 'Error Getting Microphone Access!\n'+error ); }); } /* Get sum of amplitudes of all frequencies in audio_buffer */ function get_amp_sum(){ var sum = 0; for(i=0;i<audio_buffer.length;i++){ sum += audio_buffer[i]; } return sum; } /* clamping is used as tweak to make the model compatible to faster beats as the audio analyser node uses the actual freqs similar to an acceleration to values it provides */ function clamped_fft(data){ let modf_fft = []; for(let i=0;i<data.length;i++){ if(data[i] - prev_fft[i]< -5){ modf_fft[i] = 0; }else{ modf_fft[i] = data[i]; } } prev_fft = data; return modf_fft; }
import React from "react"; import "../../Styles/Product.css"; import {Link, useHistory} from 'react-router-dom'; import {addToCart} from "../../redux"; import {connect} from "react-redux"; function Product({ item, addToCart }) { const history= useHistory(); const handleAddButton=()=>{ addToCart(item); } const handleImage= ()=>{ history.push({ pathname: "/productDetails", state: { item: item } }) } return ( <div className="product"> {/*<div className="product__info">*/} {/* <p>{item.name}</p>*/} {/* <p className="product__price">*/} {/* <small>$</small>*/} {/* <strong>{item.price}</strong>*/} {/* </p>*/} {/*</div>*/} {/* <Link to={{*/} {/* pathname:"/productDetails",*/} {/* state: {*/} {/* item: item*/} {/* }*/} {/* }}>*/} <img className="image" src={item.img} alt="" onClick={handleImage}/> {/*</Link>*/} <div className="product__info"> <p className="product__name">{item.name}</p> <p className="product__price"> <small>$</small> <strong>{item.price}</strong> </p> <button style={{cursor: 'pointer'}} onClick={handleAddButton}>Add to Cart</button> </div> {/*<button>Add to Basket</button>*/} </div> ); } const mapDispatchToProps = dispatch => { return { addToCart: (item) => dispatch(addToCart(item)) } } export default connect(null, mapDispatchToProps)(Product);
function CheckAll(form) {for (var i=0;i<form.elements.length;i++) {var e = form.elements[i];if (e.name != 'chkall' & !e.disabled) e.checked = form.chkall.checked;}} function chkid(){ var nid=""; $("input[name='id[]']:checked").each(function(i){ if(i==0){ nid=$(this).attr("value"); }else{ nid=nid+","+$(this).attr("value"); //nid=nid+",'"+$(this).attr("value")+"'"; } }); return nid; } $(document).ready(function(){ $(".dela").bind("click",function(){if(confirm("确认删除该内容?")){return true;}else{return false;}}); }); function chkfromlist(){ if(chkid()!=""){ if($("#op").attr("value").indexOf("del")>-1){ $.msgbox({ height:120, width:350, animation:0, content:{type:'confirm', content: '确认批量删除数据?'}, onClose:function(v){ if(v) $("#f2").submit(); } }); return false; } return true; }else{ $.msgbox({width:500,height:120,title:'出错',content:{type:'alert', content:'请勾选要批量操作的记录'}}); return false; } /* if(chkid()!=""){ if($("#op").attr("value").indexOf("del")>-1){ return confirm("确认删除数据?"); } return true; }else{ alert("请勾选要批量操作的记录"); return false; } */ }
(function () { "use strict"; describe("DomainsCtrl", function () { var ctrl, DomainMgmtService, MessagesService, EntitlementsService, ResultsHandlerService, $modal, AlertsService, queryResult, domains, ConfirmModalService; beforeEach(inject(function (_$injector_) { DomainMgmtService = _$injector_.get("DomainMgmtService"); AlertsService = _$injector_.get("AlertsService"); EntitlementsService = _$injector_.get("EntitlementsService"); MessagesService = _$injector_.get("MessagesService"); ResultsHandlerService = _$injector_.get("ResultsHandlerService"); ConfirmModalService = _$injector_.get("ConfirmModalService"); $modal = _$injector_.get("$modal"); domains = [ { smsDomainId: "1", selected: true, maxDevices: "100", }, { smsDomainId: "2", selected: undefined, maxDevices: "22", }, { smsDomainId: "3", selected: true, maxDevices: "33", }, ]; queryResult = null; })); describe("initialize", function () { beforeEach(function () { ctrl = initializeCtrl(); }); it("should initialize ctrl.source with the expected properties", function () { expect(ctrl.source).toEqual({ handler: DomainMgmtService.getDomains, callback: ctrl.setDomains, }); expect(ctrl.source.handler).toEqual(jasmine.any(Function)); expect(ctrl.source.callback).toEqual(jasmine.any(Function)); }); it("should initialize ctrl.columns with the expected values", function () { expect(ctrl.columns).toEqual([{ label: "Domain ID", field: "smsDomainId", }, { label: "Max Devices", field: "maxDevices", }, { label: "Address", field: "domainAddress", }, { label: "Start Time", field: "timePeriodRule.startTime", filter: jasmine.any(Function), }, { label: "End Time", field: "timePeriodRule.endTime", filter: jasmine.any(Function), }]); }); it("should initialize ctrl.bulkActions with the expected values", function () { expect(ctrl.bulkActions).toEqual([{ label: "Edit Domains", handler: ctrl.openEditDomainModal, }, { label: "Remove Domains", handler: ctrl.confirmRemoveDomains, }]); expect(ctrl.bulkActions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.bulkActions[1].handler).toEqual(jasmine.any(Function)); }); it("should initialize ctrl.itemActions with the expected values", function () { expect(ctrl.itemActions).toEqual([{ label: "Messaging", actions: [{ label: "Send Domain Message", handler: ctrl.openSendMessageModal, }, { label: "Preload Domain Message", handler: ctrl.openPreloadMessageModal, }, { label: "Remove Preloaded Domain Message", handler: ctrl.openRemovePreloadMessageModal, }, { label: "Delete Domain Message", handler: ctrl.openDeleteMessageModal, }, { label: "Send Diagnostic Domain Message", handler: ctrl.openDiagnoseMessageModal, isDisabled: ctrl.disableDiagnostic, }, { label: "Generate Domain Command", handler: ctrl.openSendCommandModal, }], }, { label: "Entitlements", actions: [{ label: "View Entitlements", handler: ctrl.openDomainEntitlementListModal, }, { label: "Add Entitlements", handler: ctrl.openAddEntitlementsModal, }, { label: "Remove All Entitlements", handler: ctrl.promptToRemoveDomainEntitlements, }], }, { label: "Devices", actions: [{ label: "View Devices", handler: ctrl.openDomainDeviceListModal, }, { label: "Add Devices", handler: ctrl.openAddDevicesModal, }] }, { actions: [{ label: "Edit Domain", handler: ctrl.openEditDomainModal, }, { label: "Remove Domain", handler: ctrl.confirmRemoveDomains, }] }]); expect(ctrl.itemActions[0].actions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[0].actions[1].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[0].actions[2].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[0].actions[3].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[0].actions[4].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[1].actions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[1].actions[1].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[1].actions[2].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[2].actions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[2].actions[1].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[3].actions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.itemActions[3].actions[1].handler).toEqual(jasmine.any(Function)); }); it("should initialize ctrl.otherActions with the expected values", function () { expect(ctrl.otherActions).toEqual([{ label: "Add Domain", handler: ctrl.openAddDomainModal, }, { label: "Message All Devices", handler: ctrl.openSendMessageModal, icon: "md-mail" }]); expect(ctrl.otherActions[0].handler).toEqual(jasmine.any(Function)); expect(ctrl.otherActions[1].handler).toEqual(jasmine.any(Function)); }); }); describe("setDomains", function () { var results; beforeEach(function () { results = { domains: [{id: "1"}, {id: "2"}] }; ctrl = initializeCtrl(); }); it("should call ResultsHandlerService.toArray with the given results", function () { spyOn(ResultsHandlerService, "toArray").and.callThrough(); ctrl.setDomains(results); expect(ResultsHandlerService.toArray).toHaveBeenCalledWith(results.domains); }); it("should set ctrl.content to the return value of ResultsHandlerService.toArray", function () { var res = ResultsHandlerService.toArray(results.domains); ctrl.setDomains(results); expect(ctrl.domains).toEqual(res); }); }); describe("removeDomains", function () { var result, targets, singleError, singleSuccess; beforeEach(function () { result = null; targets = [domains[0]]; singleSuccess = { resultCode: "0", resultText: "Success", resultId: "1" }; singleError = { resultCode: "5", resultText: "Doh", resultId: "1" }; spyOn(AlertsService, "addSuccess"); spyOn(AlertsService, "addErrors"); spyOn(DomainMgmtService, "removeDomains").and.returnValue({ then: function (cb) { cb({ result: result || singleSuccess }); } }); }); describe("confirmRemoveDomains", function() { it("should open the confirm modal", function() { spyOn(ConfirmModalService, "openModal").and.callThrough(); ctrl = initializeCtrl(); ctrl.confirmRemoveDomains(); expect(ConfirmModalService.openModal).toHaveBeenCalled(); }); }); it("should call DomainMgmtService.removeDomains with the given Domains", function () { targets = [domains[0], domains[2]]; ctrl = initializeCtrl(); ctrl.removeDomains(targets); expect(DomainMgmtService.removeDomains).toHaveBeenCalledWith(targets); }); it("should support a single success result", function () { ctrl = initializeCtrl(); ctrl.removeDomains(targets); expect(AlertsService.addSuccess).toHaveBeenCalledWith("Successfully removed Domains: 1"); }); it("should support multiple success results", function () { targets = [domains[0], domains[2]]; result = [singleSuccess, { resultCode: "0", resultText: "Success", resultId: "3" }]; ctrl = initializeCtrl(); ctrl.removeDomains(targets); expect(AlertsService.addSuccess).toHaveBeenCalledWith("Successfully removed Domains: 1, 3"); }); it("should remove any Domains that were successfully deleted", function () { ctrl = initializeCtrl(); ctrl.setDomains({ domains: domains }); ctrl.removeDomains(targets); expect(ctrl.domains).toEqual([{ smsDomainId: "2", selected: undefined, maxDevices: 22, domainAddress: null }, { smsDomainId: "3", selected: true, maxDevices: 33, domainAddress: null }]); }); it("should not remove any Domains if no Domains were successfully deleted", function () { result = singleError; ctrl = initializeCtrl(); ctrl.setDomains({ domains: domains }); var original = _.cloneDeep(ctrl.domains); ctrl.removeDomains(targets); expect(ctrl.domains).toEqual(original); }); }); describe("opening modals", function() { beforeEach(function() { var modalResult = { then: function(callback){ callback(); } }; spyOn($modal, "open").and.returnValue({result: modalResult}); ctrl = initializeCtrl(); }); it("should open the add domain modal", function() { ctrl.openAddDomainModal(); expect($modal.open).toHaveBeenCalled(); }); it("should open the domain entitlements modal", function() { ctrl.openDomainEntitlementListModal(); expect($modal.open).toHaveBeenCalled(); }); it("should open the device list modal", function() { ctrl.openDomainDeviceListModal(); expect($modal.open).toHaveBeenCalled(); }); }); describe("openSendMessageModal", function () { it("should invoke the MessagesService.openSendMessageModal method with the expected domain", function () { var domain = { smsDomainId: "7" }; spyOn(MessagesService, "openSendMessageModal"); ctrl = initializeCtrl(); ctrl.openSendMessageModal(domain); expect(MessagesService.openSendMessageModal).toHaveBeenCalledWith({ domain: domain }); }); }); describe("openPreloadMessageModal", function () { var domain; beforeEach(function () { domain = { smsDomainId: "7" }; spyOn(MessagesService, "openPreloadMessageModal"); ctrl = initializeCtrl(); }); it("should invoke the MessagesService.openPreloadMessageModal method with the expected domain and false", function () { ctrl.openPreloadMessageModal(domain); expect(MessagesService.openPreloadMessageModal).toHaveBeenCalledWith({ domain: domain }, false); }); }); describe("openRemovePreloadMessageModal", function () { it("should invoke MessagesService.openPreloadMessageModal with the domain and true", function () { var domain = { smsDomainId: "7" }; spyOn(MessagesService, "openPreloadMessageModal"); ctrl = initializeCtrl(); ctrl.openRemovePreloadMessageModal(domain); expect(MessagesService.openPreloadMessageModal).toHaveBeenCalledWith({ domain: domain }, true); }); }); describe("openDeleteMessageModal", function () { it("should invoke MessagesService.openDeleteMessageModal with the domain", function () { var domain = { smsDomainId: "8" }; spyOn(MessagesService, "openDeleteMessageModal"); ctrl = initializeCtrl(); ctrl.openDeleteMessageModal(domain); expect(MessagesService.openDeleteMessageModal).toHaveBeenCalledWith({ domain: domain }); }); }); describe("promptToRemoveDomainEntitlements", function(){ var domain = { smsDeviceId: "000111" }; it("should call $modal.open with the expected configuration", function () { spyOn($modal, "open"); ctrl = initializeCtrl(); ctrl.promptToRemoveDomainEntitlements(domain); expect($modal.open).toHaveBeenCalledWith({ templateUrl: "app/domains/domain_remove_entitlements_prompt.html", controller: "DomainRemoveEntitlementsPromptCtrl as vm", size: "md", resolve: { domain: jasmine.any(Function) } }); }); }); describe("openSendCommandModal", function () { it("should invoke MessagesService.openSendCommandModal with the domain", function () { var domain = { smsDomainId: "8" }; spyOn(MessagesService, "openSendCommandModal"); ctrl = initializeCtrl(); ctrl.openSendCommandModal(domain); expect(MessagesService.openSendCommandModal).toHaveBeenCalledWith({ domain: domain }); }); }); describe("openDiagnoseMessageModal", function () { var domain = { smsDomainId: "000111" }; it("should call MessagesService.openDiagnoseMessageModal with the given domain", function () { spyOn(MessagesService, "openDiagnoseMessageModal"); ctrl = initializeCtrl(); ctrl.openDiagnoseMessageModal(domain); expect(MessagesService.openDiagnoseMessageModal).toHaveBeenCalledWith({ domain: domain }); }); }); describe("disableDiagnostic", function() { it("should return 'true'", function() { ctrl = initializeCtrl(); expect(ctrl.disableDiagnostic()).toBe(true); }); }); describe("openAddEntitlementsModal", function () { it("should call $modal.open with the expected configuration", function () { spyOn($modal, "open"); ctrl = initializeCtrl(); ctrl.openAddEntitlementsModal({}); expect($modal.open).toHaveBeenCalledWith({ templateUrl: "app/networks/devices/add_entitlement_modal.html", controller: "AddEntitlementModalCtrl as vm", size: "lg", resolve: { chosenEntity: jasmine.any(Function) } }); }); }); ////////// function initializeCtrl() { return $controller("DomainsCtrl"); } }); }());
$(document).ready(function () { $(window).scroll(function() { var verticalScroll = $(this).scrollTop(); console.log(verticalScroll); if(verticalScroll >= 2140) { $('#find-me').addClass('animated slideInLeft'); $('#find-me').removeClass('hide_me'); } }); });
/** * Created by 86wh2 on 2017/7/8. */ import Vue from 'vue' import VueRoute from 'vue-router' import 'babel-polyfill' //解决ie浏览器无内置promise对象 import MyRoutes from './routers' import store from './../store/index' import NProgress from 'nprogress' import 'nprogress/nprogress.css' import components from './routesLazy'; Vue.use(VueRoute); let router = new VueRoute({ // mode: 'history', routes: MyRoutes, scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return {x: 0, y: 0} } } }); // let addRouter= // if(addRouter){ // router.addRoutes(transRouter(addRouter)); // router.options.routes=Object.assign({},transRouter(addRouter)); // console.log(router) // } router.beforeEach((to, from, next) => { NProgress.done().start();//模拟页面加载的滚动条 if (to.path === '/login') { sessionStorage.removeItem('Token'); sessionStorage.removeItem('menu_router'); } let token = JSON.parse(sessionStorage.getItem('Token')); if (!token && to.path !== '/login') { next({path: '/login'}) } else { next() } }) //路由完成之后的操作 router.afterEach(route => { NProgress.done() }) export default router;
let yargs = require('yargs'); let appDetails = require('./appDetails'); yargs.scriptName('gnote'); // check and show if no command passed let showAppDetails = !['add', 'list', 'remove', 'update', 'auth'].includes(yargs.argv._[0]); if(showAppDetails) appDetails(); yargs.command({ command: 'add', describe: 'Add new Note', builder: { title: { describe: 'Note Title', type: 'string', demandOption: true }, body: { describe: 'Note Body', type: 'string', demandOption: true } }, handler: require('./addNote') }); yargs.command({ command: 'list', describe: 'Show All Note', builder: { title: { describe: 'Note Title', type: 'string' } }, handler: require('./allNote') }); yargs.command({ command: 'update', describe: 'update Note', builder: { title: { describe: 'Note Title', type: 'string', demandOption: true }, body: { describe: 'Note Body', type: 'string', demandOption: true }, }, handler: require('./updateNote') }); yargs.command({ command: 'delete', describe: 'Delete Note', builder: { title: { describe: 'Note Title', type: 'string', demandOption: true } }, handler: require('./deleteNote') }); // commnad for author info yargs.command({ command: "auth", describe: "Show details about the author", handler: appDetails }) yargs.demandCommand().parse();
/** @format */ module.exports = function parseLyric(lyric) { let arrLyric = lyric.split("\n"); let res = []; arrLyric.forEach((lyr) => { const reg = lyr.match(/\[(\d*):(.*)\](.*)/); //console.log(reg); if (reg) res.push({ time: parseInt(reg[1]) * 60000 + parseFloat(reg[2]) * 1000, txt: reg[3], }); }); return res; };
var x; x = 100; var y = 100; var name1 = 'Jim', name2 = 'Tom'; var fruit1, fruit2; var a = null; console.log(a); //null var b; console.log(b); //undefined var score = 100; console.log(typeof score); //number型態 score = 'Jim'; console.log(typeof score); // string型態
var Util = require('../../utils/md5.js'); Page({ data: { amount: 0 }, onLoad: function () { var that = this; wx.getSystemInfo({ success: function (res) { } }); this.setData({ balance: getApp().globalData.balance }) }, goReset: function(e) { var url = '../reset/reset'; wx.redirectTo({ url: url }) }, goRegister: function (e) { var url = '../register/register'; wx.redirectTo({ url: url }) }, onLogin: function (e) { var that = this; var params = {}; params["cellphone"] = e.detail.value.cellphone; params["password"] = Util.hexMD5( e.detail.value.password) ; wx.request({ url: getApp().config.host + "/login", data: params, method: "POST", header: { "Content-Type": "application/x-www-form-urlencoded", }, success: function (res) { if (res.data.code != 0) { wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) return } wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) wx.setStorageSync('user', res.data.data);//存储openid getApp().globalData.userInfo = res.data.data wx.navigateBack({ }) } }) }, });
const { readSvg } = require("./svg") const config = { dir: { input: "utils", includes: "shortcodes/__fixtures__" } } describe("readSvg()", () => { it("Reads the contents of the SVG from within an svg directory", () => { expect(readSvg("test", config)).toEqual("Hello World\n") }) })
import {combineReducers} from 'redux' import {fetchReducer} from './fetchReducer' import {counterReducer} from './counterReducer' export const rootReducer = combineReducers({ fetchQuiz: fetchReducer, counterQuiz: counterReducer, // iterateQuiz: iteratedReducer })
const mongoose = require('mongoose'); const express = require("express"); const router = express.Router(); const auth = require("./auth.js"); const users = require("./users.js"); const User = users.model; const storySchema = new mongoose.Schema({ user: { type: mongoose.Schema.ObjectId, ref: 'User' }, title: String, content: String, created: { type: Date, default: Date.now }, }); const Story = mongoose.model('Story', storySchema); // upload story router.post("/", auth.verifyToken, User.verify, async (req, res) => { const story = new Story({ user: req.user, title: req.body.title, content: req.body.content, }); console.log("req\n" + req) try { await story.save(); return res.sendStatus(200); } catch (error) { console.log(error); return res.sendStatus(500); } }); // get my story router.get("/", auth.verifyToken, User.verify, async (req, res) => { // return story try { let stories = await Story.find({ user: req.user }).sort({ created: -1 }); return res.send(stories); } catch (error) { console.log(error); return res.sendStatus(500); } }); // get all story router.get("/all", async (req, res) => { try { let stories = await Story.find().sort({ created: -1 }).populate('user'); return res.send(stories); } catch (error) { console.log(error); return res.sendStatus(500); } }); // get single story router.get("/:storyId", async (req, res) => { console.log("trying to get story") // return story try { let stories = await Story.find({ _id: req.params.storyId }).populate('user'); return res.send(stories); } catch (error) { console.log(error); return res.sendStatus(500); } }); module.exports = { model: Story, routes: router, }
'use strict'; const releases = require('./src/github/releases'); const colors = require('colors'); function main() { var requests = [ releases.latest('docker', 'docker'), releases.latest('docker', 'machine'), releases.latest('docker', 'compose'), releases.latest('docker', 'swarm') ]; Promise.all(requests).then((releases) => { console.log('Latest Versions'.bold.underline.green); console.log('Docker Engine:', releases[0]); console.log('Docker Machine:', releases[1]); console.log('Docker Compose:', releases[2]); console.log('Docker Swarm:', releases[3]); }); } main();
import React from 'react'; import { View, StyleSheet, TextInput, Image, TouchableOpacity, Platform } from 'react-native'; const InputWithIcon = ({ placeholder,rightIcon }) => { const { main, rightBtnIconStyle, rightIconStyle, inputBox, inputBoxOuter } = styles; return ( <View style={ main }> <View style = { inputBoxOuter }> <TextInput style={ inputBox } placeholder={ placeholder } placeholderTextColor = "#aaaaaa" /> <TouchableOpacity style = { rightBtnIconStyle } > <Image style = { rightIconStyle } resizeMode="contain" source={rightIcon} /> </TouchableOpacity> </View> </View> ) } const styles = StyleSheet.create({ main: { paddingHorizontal: 20, paddingVertical: 6, }, inputBox: { height:Platform.OS === 'ios' ? 34 : "auto", width: '100%', borderRadius: 5, backgroundColor: '#fff', alignSelf: 'center', color:'#000000', }, inputBoxOuter: { width: '100%', height: 36, borderRadius: 5, backgroundColor: '#fff', borderStyle: "solid", borderWidth: 1, borderColor: 'rgb(234, 234, 234)', alignSelf: 'center', paddingHorizontal: 17, color:'#000000', position: 'relative', }, rightBtnIconStyle: { position: 'absolute', width: 30, right: 0, top:0, bottom: 0, alignItems: 'center', justifyContent: 'center', }, }); export default InputWithIcon
QUnit.test( "Unicode", function( assert ) { assert.ok(/𝌆/.test('foo𝌆bar')); assert.ok(/𝌆/u.test('foo𝌆bar')); assert.notOk(/foo.bar/.test('foo𝌆bar')); assert.ok(/foo.bar/u.test('foo𝌆bar')); }); QUnit.test( "Sticky", function( assert ) { var re1=/foo/, str = '++foo++'; assert.equal(re1.lastIndex, 0); assert.ok(re1.test(str)); assert.equal(re1.lastIndex, 0); re1.lastIndex=2; assert.ok(re1.test(str)); assert.equal(re1.lastIndex, 2); var re1=/foo/y, str = '++foo++'; assert.equal(re1.lastIndex, 0); assert.notOk(re1.test(str)); assert.equal(re1.lastIndex, 0); re1.lastIndex=2; assert.ok(re1.test(str)); assert.equal(re1.lastIndex,5); assert.notOk(re1.test(str)); assert.equal(re1.lastIndex,0); }); QUnit.test( "Sticky: exampl 2", function( assert ) { var re=/f../y, str = 'foo far fad'; assert.deepEqual(str.match(re), ["foo"]); re.lastIndex = 4; assert.deepEqual(str.match(re), ["far"]); re.lastIndex = 8; assert.deepEqual(str.match(re), ["fad"]); }); QUnit.test( "Sticky: exampl 3", function( assert ) { var re=/\d+\.\s(.*?)(?:\s|$)/y, str = '1. foo 2. far 3. fad'; assert.deepEqual(str.match(re), ["1. foo ","foo"]); assert.equal(re.lastIndex, 7); assert.deepEqual(str.match(re), ["2. far ","far"]); assert.equal(re.lastIndex, 14); assert.deepEqual(str.match(re), ["3. fad","fad"]); }); QUnit.test( "Flags", function( assert ) { // Old var re=/foo/gi; var flags = re.toString().match(/\/([gim]*)$/)[1]; assert.equal(flags, "gi"); // New assert.equal(re.flags, "gi"); });
#!/usr/bin/env node //TODO implement using yargs
import React, { Component } from 'react'; import { AddStockForm } from '../../components/AddStockForm/AddStockForm'; import { StocksTable } from '../../components/StocksTable/StocksTable'; import { SummaryStocks } from '../../components/SummaryStocks/SummaryStocks'; import { TransferedBrokerForm } from '../../components/TransferedBrokerForm/TransferedBrokerForm'; import { GlobalStore } from '../../services/GlobalStore'; export class Home extends Component { constructor(props) { super(props); this.state = { keycloak: GlobalStore.lookAt('keycloak') } } componentDidMount() { GlobalStore.subscribe('keycloak', keycloak => { this.setState({ keycloak }); }) } render() { return ( <div> <TransferedBrokerForm></TransferedBrokerForm> <AddStockForm></AddStockForm> <SummaryStocks></SummaryStocks> <StocksTable></StocksTable> </div> ); } }
var expect = require('expect'); var {generateMessage, generateLocationMessage} = require('./message') describe('generateMessage', () => { it('should generate message object', () => { var from = 'test'; var text = 'test'; var message = generateMessage(from,text); expect(message.text).toBe(from); expect(message.from).toBe(text); }); it('should generate location object', () => { var from = 'location'; var latitude = '-14.6962419'; var longitude = '-48.248675999999996'; var locationObject = generateLocationMessage(from, latitude, longitude); expect(locationObject.url).toBe('https://www.google.com/maps?q=-14.6962419,-48.248675999999996') }); });
const http = require('http'); const port = 8080; const requiredRoles = process.env.REQUIRED_ROLES || 'ADMIN,DEVELOPER' const AUTH_HEADERFIELD = 'X-MWAY-BAAS-ROLES'.toLowerCase();; const INTERNAL_SERVICE_NAME = 'com.example.helloBaaS'; const PERMISSION_UUID = process.env['BAAS_PERMISSION_UUID']; const parsedRequiredRoles = requiredRoles.split(',').filter(r => !!r); console.log('Server will require the following roles:', parsedRequiredRoles.join(', ')) registerService(); const HANDLERS = { '/restricted': (request, response) => { /* Header is stringified object like: { id: string, username: string, type: string, ('system' or 'ldap') roles:[ { service: string, roles: string[] }, ], */ let authenticated = false; if (request.headers[AUTH_HEADERFIELD]) { const parsedHeader = JSON.parse(request.headers[AUTH_HEADERFIELD]); const serviceRoleObject = parsedHeader.roles.find((element) => { return element.service === PERMISSION_UUID; }); if (serviceRoleObject) { authenticated = serviceRoleObject.roles.some( role => parsedRequiredRoles.some( requiredRole => role === requiredRole ) ); } } if (authenticated) { return response.end(JSON.stringify({ message: 'Hello, you are authenticated', role: request.headers[AUTH_HEADERFIELD], })); } response.statusCode = 401; response.statusMessage = 'Unauthorized'; response.end(JSON.stringify({ message: response.statusMessage, code: response.statusCode })); }, '/print-headers': (request, response) => { response.end(JSON.stringify(request.headers)) }, '/print-env': (request, response) => { response.end(JSON.stringify(process.env)) } }; const server = http.createServer((request, response) => { const handler = HANDLERS[request.url]; if (handler) { return handler(request, response); } response.statusCode = 404; response.statusMessage = 'Not Found'; response.end(JSON.stringify({ message: response.statusMessage, code: response.statusCode })); }) server.listen(port, (err) => { if (err) { console.log('Something bad happened', err); process.exitCode = 1; } console.log(`Server is listening on ${port}`); }); function registerService() { console.log('registering service', Object.keys(process.env).join(', ')) const options = { host: process.env.BAAS_SERVER_NAME || 'localhost', path: '/register', port: process.env.BAAS_SERVER_PORT || 8081, method: 'POST', }; const payload = { permissionUuid: PERMISSION_UUID, availableRoles: parsedRequiredRoles, port, }; const req = http.request(options, (res) => { if (res.statusCode !== 200) { console.log('Couldn\'t connect to BaaS-Application'); console.log({ payload }); return; } let data; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('registering done') // const responseData = JSON.parse(data); // TODO: get the uuid and save it, no use case yet }); }); req.on('error', (err) => { const reqError = err; console.log('Error while trying to reach BaaS-Application:'); if (reqError.code === 'ENOTFOUND') { console.log('Couldn\'t reach Application at ' + options.host + options.path + ':' + options.port); } else { console.log(err); } // process.exit(); // if active will stop service after unsuccessful registration }); req.write(JSON.stringify(payload)); req.end(); }
import React,{Component} from 'react'; import {Link} from 'react-router-dom'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {Toast} from "antd-mobile"; import 'antd-mobile/lib/toast/style/css.js'; //获取样式 import {login,signUp} from "../functional/common"; import {Login,SignUp} from "../../action/action"; class Sign extends Component{ constructor(props) { super(props); this.state = { isSignUp: false }; this.emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/; } componentWillMount() { document.body.style.background = '#fff'; } email() { } pwd() { // console.log('pwd',this.refs.pwd.value) } //登录 signin() { let email = this.refs.email.value; let pwd = this.refs.pwd.value; if(email && pwd ) { if(this.emailReg.test(email)) { let fetch = login(email, pwd); //dispatch action 进入reducer处理登录事件 this.props.Login(fetch).then(() => { //resolve之后返回 if(this.props.user) { Toast.info('Login successfully!', 2); localStorage.setItem('email', email); window.location.href = '/'; //登录后强制刷新返回主页 } }); }else{ Toast.info('Please enter a valid email!', 1.5); } }else{ Toast.info('Please enter your information.', 1.5); } } //注册 register() { let email = this.refs.email.value; let pwd = this.refs.pwd.value; if(email && pwd) { if(this.emailReg.test(email)) { let fetch = signUp(email, pwd); console.log(fetch) this.props.SignUp(fetch).then(() => { if(this.props.user) { Toast.info('Register successfully!', 2); localStorage.setItem('email', email); window.location.href = '/'; //注册成功后强制刷新返回主页 } }); }else{ Toast.info('Please enter a valid email!', 1.5); } }else{ Toast.info('Please enter your information.', 1.5); } } render() { let token = localStorage.getItem('token'); // let token = null; return( <div className="sign"> <p className="rounded">M</p> <div className="commit-area"> <input type="text" placeholder="Email" ref={"email"} onChange={this.email.bind(this)} /> <input type="password" placeholder="Password" ref={"pwd"} maxLength="16" onChange={this.pwd.bind(this)} /> <div className="commit-btn" onClick={this.signin.bind(this)} >Sign in</div> <div className={token ? 'commit-btn none' : 'commit-btn'} onClick={this.register.bind(this)} >New Account</div> <p className={token ? 'service none' : 'service'}> <Link to="/term"> <span>Terms of Service</span> </Link> <span> & </span> <Link to="/privacy"> <span>Privacy Policy</span> </Link> </p> </div> </div> ) } } const mapStateToProps = (state,props) => { return state; }; const mapDispatchToProps = (dispatch, ownProps) => { return bindActionCreators({ Login,SignUp },dispatch); }; export default connect(mapStateToProps, mapDispatchToProps)(Sign);
const apiURL = "http://api.openweathermap.org/data/2.5/weather?q="; const apiKey = "&appid=b11149c6eb203b39d0dd88f337b6bb1d"; let appId = 'b11149c6eb203b39d0dd88f337b6bb1d'; let units = 'metric'; let searchMethod; var resultApi; var listDate; var weatherContainer = document.getElementById("image_of_tab1"); var dailyWeather = weatherContainer.getElementsByClassName("weather"); var main; var date; var dateTXT; var temp; var humidity; var icon; var feature = []; function getSearchMethod(searchTerm) { if (searchTerm.length === 5 && Number.parseInt(searchTerm) + '' === searchTerm) { searchMethod = 'zip'; } else { searchMethod = 'q'; } } function searchWeather(searchTerm) { getSearchMethod(searchTerm); fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${searchTerm}${apiKey}`).then(result => { console.log(`https://api.openweathermap.org/data/2.5/forecast?q=${searchTerm}${apiKey}`) resultApi = result; return result.json(); }).then(result => { init(result); }); } function init(resultFromServer) { var listDate = resultFromServer.list; for (var i = 3; i < 42; i += 8) { date = listDate[i]; dateTXT = date.dt_txt; // console.log("Today's date:", dateTXT); main = date.main; temp = Math.round(main.temp - 273); //console.log("Temperature: ", temp); humidity = main.humidity; icon = listDate[1].weather[0].icon; description = listDate[1].weather[0].description; //console.log(`Humidity: ${humidity}%`) var obj = { 'dt_txt': dateTXT, 'temp': temp, 'humidity': humidity, "icon": icon, "description": description, 'img': `http://openweathermap.org/img/wn/${icon}@2x.png` }; feature.push(obj) } for (var i = 0; i < 5; i++) { var dailyDate = dailyWeather[i].getElementsByClassName("date"); var dailyTemp = dailyWeather[i].getElementsByClassName("temp"); var dailyHumidity = dailyWeather[i].getElementsByClassName("humidity"); var dailyDes = dailyWeather[i].getElementsByClassName('description'); var dailyImg = dailyWeather[i].getElementsByClassName('icon_img'); var dailyFeature = feature[i]; } } document.getElementById('searchBtn').addEventListener('click', () => { let searchTerm = document.getElementById('searchInput').value; if (searchTerm) { searchWeather(searchTerm); console.log(feature); } });
// @flow import { lazy } from "react"; import { USER_ROLES } from "constants/user"; import authRoutes from "modules/auth/routes"; export default [ { path: "/", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/dashboard/home")), }, { path: "/product/create", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/inventory/addNewProduct") ), }, { path: "/product/products", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/inventory/viewProducts") ), }, { path: "/product/update/:productCode", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/inventory/updateProducts") ), }, { path: "/product/margin", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/inventory/setProductMargin") ), }, { path: "/return/create", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/stockReturn/createStockReturn") ), }, { path: "/return/update/:returnId", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/stockReturn/updateStockReturn") ), }, { path: "/returns", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/stockReturn/viewStockReturns") ), }, { path: "/orders/create", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/orders/addNewOrder")), }, { path: "/orders/update/:orderId", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/orders/updateOrder")), }, { path: "/orders", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/stockManagement/orders/viewOrders")), }, { path: "/admin/users", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/users/viewUsers")), }, { path: "/admin/users/update/:userId", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/users/updateUser")), }, { path: "/admin/employee/create", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/employee/addEmployee") ), }, { path: "/admin/employees/update/:employeeId", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/employee/updateEmployee") ), }, { path: "/admin/employees", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/employee/viewEmployees") ), }, { path: "/admin/leaves/add", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/leaves/addLeaves")), }, { path: "/admin/leaves", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/leaves/viewLeaves")), }, { path: "/admin/supplier/create", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/suppliers/addSupplier") ), }, { path: "/admin/supplier/update/:supplierCode", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/suppliers/updateSupplier") ), }, { path: "/admin/suppliers", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/suppliers/viewSuppliers") ), }, { path: "/admin/salary", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/adminManagement/salary/salaryPayment") ), }, { path: "/cashier", exact: true, auth: true, roles: [USER_ROLES.ADMIN], component: lazy(() => import("modules/cashierManagement/cashier")), }, ...authRoutes, ];
import React from 'react'; import { useQuery } from '@apollo/client'; import { GET_ROBOT_MAP_CONFIG } from './requests'; import Map from '../Map'; const MapPage = () => { const { data, loading, error } = useQuery(GET_ROBOT_MAP_CONFIG); if (loading || error) return null; const { config } = data; return config && <Map config={config} />; }; export default MapPage;
import Link from 'next/link' export default function Home() { return ( <div className = "card"> <h1>Rota de API</h1> <Link href="https://api-router-lvwfbi6si-soares97.vercel.app/api/informaticos"> <a>Endpoint para conjuntos de Informáticos</a> </Link> <style jsx> {` a{ padding: 0 10px; text-decoration:none; color: rgb(0,0,0); background-color:#dddddd; padding: 5px; --margin: 2px; } .card { width: 20%; margin: 20px auto; text-align: center; padding: 1.5rem; font-size: 16pt; text-decoration: none; border: 2px solid #eaeaea; border-radius: 10px; } `} </style> </div> ) }
// ********** DOM Icinden Oge Secimi ********** // https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById // https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector // let h2 = document.getElementsByTagName('h2') // let title = document.getElementById('title') // title.innerHTML = "Degisen Bilgi" // console.log(title.innerHTML) // let link = document.querySelector("#kodluyoruzLink") // link.innerHTML += " degisti" // link.style.color = "red" // link.classList.add('btn') let title = document.getElementById("title") title.innerHTML = "Degişen Bilgi"; console.log(title.innerHTML) // let link = document.querySelector("ul#list>li>a") // link.innerHTML += "değişti" let link = document.querySelector("#kodluyoruzLink") link.innerHTML += " değişti" link.style.color = "red" link.style.backgroundColor = "green"
TrelloClone.Views.CardCreate = Backbone.View.extend({ tagName: 'form', className: 'create-form', template: JST['cards/create'], events: { "click button.create-card" : "createCard" }, initialize: function(options) { this.board = options.board; this.list = options.list; }, createCard: function (event) { event.preventDefault(); var that = this; var attrs = this.$el.serializeJSON(); attrs['card']['list_id'] = this.list.id; this.model.set(attrs); this.model.save({ }, { success: function () { that.collection.add(this.model); Backbone.history.navigate("boards/"); Backbone.history.navigate("boards/" + that.board.id, {trigger: true}); } }); }, render: function () { var content = this.template({ card: this.model, cards: this.collection }); this.$el.html(content); return this; }, });
import JQuery from 'jquery' import './polyfill' function id(it) { return it; } function qsel(selector) { return Array.from(JQuery(selector).get()); } function attribute(element, name) { return element.getAttribute(name) || ''; } function property(element, name) { return element[name] || ''; } function getOgUrl() { let found = document.querySelector('meta[property="og:url"][content]') return found && head(found.getAttribute('content')) } function getCanonicalUrl() { let found = document.querySelector('link[rel="canonical"][href]') return found && head(found.getAttribute('href')) } function head(s) { if (typeof s === 'string') return s.split('\n')[0] else return s } function main() { const actions = { attribute: message => qsel(message.query).map(it => attribute(it, message.attribute)).filter(id), ping: message => 'pong', property: message => qsel(message.query).map(it => property(it, message.property)).filter(id), selected: message => [window.getSelection().toString()], selector: message => qsel(message.query).map(it => it.textContent).filter(id), 'og-url': message => [getOgUrl() || document.location.href], 'canonical-url': message => [getCanonicalUrl() || document.location.href], 'x-url': message => [getCanonicalUrl() || getOgUrl() || document.location.href], }; browser.runtime.onMessage.addListener((message, sender, callback) => callback(actions[message.command](message))) } main();
module.exports = { host: "localhost", title: "The Exocortex", description: "I keep it full of notes for reference and sharing. Most are related to web development but could honestly be about anything - nonfiction, fiction, general life skills and topics, and whatever else I want remember without relying on my unreliable brain.", head: [ [ "link", { rel: "apple-touch-icon", sizes: "180x180", href: "/assets/favicons/apple-touch-icon.png", }, ], [ "link", { rel: "icon", type: "image/png", sizes: "32x32", href: "/assets/favicons/favicon-32x32.png", }, ], [ "link", { rel: "icon", type: "image/png", sizes: "16x16", href: "/assets/favicons/favicon-16x16.png", }, ], ["link", { rel: "manifest", href: "/assets/favicons/site.webmanifest" }], [ "link", { rel: "mask-icon", href: "/assets/favicons/safari-pinned-tab.svg", color: "#3a0839", }, ], ["link", { rel: "shortcut icon", href: "/assets/favicons/favicon.ico" }], ["meta", { name: "msapplication-TileColor", content: "#3a0839" }], [ "meta", { name: "msapplication-config", content: "/assets/favicons/browserconfig.xml", }, ], ["meta", { name: "theme-color", content: "#ffffff" }], ], themeConfig: { nav: [{ text: "Portfolio", link: "https://shahidshaikh.com" }], sidebar: [ // "/", { title: "Javascript ES6", children: [ "/notes/javascript/letAndVar", "/notes/javascript/datatypes", "/notes/javascript/ternary", "/notes/javascript/eventbubbling", "/notes/javascript/delegation", "/notes/javascript/methodsOrFunctions", "/notes/javascript/callback", "/notes/javascript/promises", "/notes/javascript/async", "/notes/javascript/hoisting", "/notes/javascript/closures", "/notes/javascript/spreadrest", "/notes/javascript/this", "/notes/javascript/oops", "/notes/javascript/classes", "/notes/javascript/getpost", "/notes/javascript/localstorage", ], }, { title: "Cascading Style Sheets", children: [ "/notes/css/boxmodal", "/notes/css/position", "/notes/css/aligncenter", "/notes/css/specificity", "/notes/css/units", "/notes/css/keyframes", "/notes/css/hardwareA", ], }, { title: "Github", children: [ "/notes/github/main", ], }, { title: "Bookmarks", children: [ "/notes/bookmarks/css", "/notes/bookmarks/javascript", "/notes/bookmarks/assets", ], }, ], logo: "/assets/images/logo.png", }, };
describe('Buttons - options - buttons.className', function() { let params; dt.libs({ js: ['jquery', 'datatables', 'buttons'], css: ['datatables', 'buttons'] }); describe('Functional tests', function() { dt.html('basic'); it('Check class on single button', function() { $('#example').DataTable({ dom: 'Bfrtip', buttons: [ { text: 'first', className: 'class1' }, { text: 'second', className: 'class2' }, { text: 'third', className: 'class1' } ] }); expect($('button.class2').text()).toBe('second'); }); it('Check class on multiple buttons', function() { expect($('button.class1').text()).toBe('firstthird'); }); }); });
var express = require('express'); var router = express.Router(); var booksController = require('../controllers/booksController'); // GET /index router.get('/', booksController.index); // GET /books/new router.get('/new', booksController.new); // GET /books/12345 router.get( '/:id', booksController.show ); // GET /books/12345/edit router.get('/:id/edit', booksController.edit); // POST create router.post('/', booksController.create); // POST /books/12345 router.post('/:id', booksController.update); // POST books/12345/delete router.post('/:id/delete', booksController.delete); module.exports = router;
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; var _excluded = ["className", "getTextAndFormatDate", "index", "item", "itemContentTemplate", "onDelete", "onHide", "showDeleteButton", "singleAppointment"]; import { createVNode, createComponentVNode, normalizeProps } from "inferno"; import { BaseInfernoComponent } from "@devextreme/vdom"; import noop from "../../../utils/noop"; import { Marker } from "./marker"; import { Button } from "../../button"; import { TooltipItemContent } from "./item_content"; import getCurrentAppointment from "./utils/get_current_appointment"; import { defaultGetTextAndFormatDate } from "./utils/default_functions"; export var viewFunction = viewModel => { var ItemContentTemplate = viewModel.props.itemContentTemplate; return viewModel.props.itemContentTemplate ? ItemContentTemplate({ model: { appointmentData: viewModel.props.item.data, targetedAppointmentData: viewModel.currentAppointment }, index: viewModel.props.index }) : normalizeProps(createVNode(1, "div", "dx-tooltip-appointment-item ".concat(viewModel.props.className), [createComponentVNode(2, Marker), createComponentVNode(2, TooltipItemContent, { "text": viewModel.formattedContent.text, "formattedDate": viewModel.formattedContent.formatDate }), viewModel.props.showDeleteButton && createVNode(1, "div", "dx-tooltip-appointment-item-delete-button-container", createComponentVNode(2, Button, { "className": "dx-tooltip-appointment-item-delete-button", "icon": "trash", "stylingMode": "text", "onClick": viewModel.onDeleteButtonClick }), 2)], 0, _extends({}, viewModel.restAttributes))); }; export var TooltipItemLayoutProps = { className: "", item: { data: {} }, index: 0, showDeleteButton: true, onDelete: noop, onHide: noop, getTextAndFormatDate: defaultGetTextAndFormatDate, singleAppointment: {} }; var getTemplate = TemplateProp => TemplateProp && (TemplateProp.defaultProps ? props => normalizeProps(createComponentVNode(2, TemplateProp, _extends({}, props))) : TemplateProp); export class TooltipItemLayout extends BaseInfernoComponent { constructor(props) { super(props); this.state = {}; } get currentAppointment() { var { item } = this.props; return getCurrentAppointment(item); } get onDeleteButtonClick() { var { item, onDelete, onHide, singleAppointment } = this.props; return e => { onHide(); e.event.stopPropagation(); onDelete(item.data, singleAppointment); }; } get formattedContent() { var { getTextAndFormatDate, item } = this.props; var { data } = item; return getTextAndFormatDate(data, this.currentAppointment); } get restAttributes() { var _this$props = this.props, restProps = _objectWithoutPropertiesLoose(_this$props, _excluded); return restProps; } render() { var props = this.props; return viewFunction({ props: _extends({}, props, { itemContentTemplate: getTemplate(props.itemContentTemplate) }), currentAppointment: this.currentAppointment, onDeleteButtonClick: this.onDeleteButtonClick, formattedContent: this.formattedContent, restAttributes: this.restAttributes }); } } TooltipItemLayout.defaultProps = _extends({}, TooltipItemLayoutProps);
import { Button, f7ready, Page, Navbar, Swiper, SwiperSlide, Toolbar, } from "framework7-react"; import React, { useEffect, useState } from "react"; import { Pagination } from "swiper"; import sanitizeHtml from "../js/utils/sanitizeHtml"; const IntroPage = (props) => { const [slides, setSlides] = useState([]); let images = [ "couple", "segment", "chilling", "choose", "chatting", "confirmed", "agreement", "grades", "brainstorming", "hiring", "love", "messages1", "development", "team", "together", "space", "mobile", "website", "easter", "romantic", "tasting", "drone", "coding", "mindfulness", "artificial", "celebration", "virtual", "doggy", "static", "healthy", "data", "sleep", "force", "makeup", "bicycle", "podcast", "fishing", "credit", "workout", "pilates", "group", "mouth", "school", ]; useEffect(() => { f7ready(async (f7) => { setSlides( _.zip(_.sampleSize(images, 3), [ "<script>console.log('a')</script>\n인썸니아의 <br/> \n 교육용 골격입니다.", "ㅎㅎ ", "파이팅입니다.", ]) ); }); }, []); return ( <Page> <Navbar className="hidden"></Navbar> <Toolbar bottom className="p-0" inner={false}> <div className="w-full flex"> <Button className="w-full rounded-none" large href="/users/sign_in"> 로그인 </Button> <Button className="w-full rounded-none" large href="/users/sign_up" fill > 회원가입 </Button> </div> </Toolbar> <Swiper className="h-full" spaceBetween={30} slidesPerView={1} centeredSlides={true} pagination={{ clickable: true }} observer > {slides.map((item, i) => ( <SwiperSlide key={i}> <div className="flex justify-center p-0 "> <img src={`https://insomenia.com/svgs/${item[0]}`} alt="" /> </div> {sanitizeHtml(item[1], { className: "text-lg text-center pt-4" })} </SwiperSlide> ))} </Swiper> </Page> ); }; export default IntroPage;
import React, { Component } from 'react'; import { classroomService } from '../../services' import ClassroomItem from './ClassroomItem' import { Link } from 'react-router-dom'; import { withAuthConsumer } from '../../contexts/AuthStore'; class ClassroomList extends Component { state = { classrooms: [] } componentDidMount() { classroomService.list() .then(classrooms => this.setState({ classrooms: classrooms})) } handleDeleteClassroom = (id) => { this.setState({classrooms: this.state.classrooms.filter(classroom => classroom.id !== id)}) } render () { const { isTutor } = this.props; const classrooms = this.state .classrooms .map(classroom => (<ClassroomItem key={classroom.id} {...classroom} tutorOptions={isTutor()} onClickDeleteClassroom ={this.handleDeleteClassroom} />)); return ( <div className="row justify-content-center mt-5"> <div className = "box mx-auto col-sm-8"> <h2>Listado de Clases</h2> <div className="col-xs-12 "> <ul className="list-group mt-5"> {classrooms} </ul> </div> <div className="mt-3"> <Link className="btn btn-sm btn-primary" to={`/classrooms/create`}>Crear Clase</Link> </div> <a className="float-right"><i className='fa fa-reply fa-2x mt-3 text-danger' onClick={() => this.props.history.go(-1)}></i></a> </div> </div> ) } } export default withAuthConsumer(ClassroomList)
(function () { "use strict"; var app = angular.module("PeopleManagement", ["common.services", "ngRoute", "ngAnimate", "ui.bootstrap"]).config(config).run(run); function config($routeProvider) { $routeProvider .when("/", { templateUrl: "AngularApp/client/clientListView.html", controller: "clientListController", controllerAs: 'vm', }) .when("/client/:id", { templateUrl: "AngularApp/client/clientView.html", controller: "clientController", controllerAs: 'vm', }) .when("/login", { templateUrl: "AngularApp/account/loginView.html", controller: "loginController", controllerAs: 'vm', }) .when("/admin", { templateUrl: "AngularApp/admin/adminViewList.html", controller: "adminListController", controllerAs: 'vm', }) .when("/admin/create", { templateUrl: "AngularApp/admin/adminCreateView.html", controller: "adminCreateController", controllerAs: 'vm', }) .when("/admin/edit/:id", { templateUrl: "AngularApp/admin/adminEditView.html", controller: "adminEditController", controllerAs: 'vm', }) .otherwise({ redirectTo: "/" }); } app.config(function ($httpProvider) { $httpProvider.interceptors.push('authInterceptorService'); });; function run(localStorageService, $rootScope, currentUser) { $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) { if (localStorageService.get('authData')) { currentUser.setProfile(localStorageService.get('authData').username, localStorageService.get('authData').token); } }); } })();
var questions = [ new Question("The sum of any two odd integers is odd?",["True","False","I don't know","It's possible"],"False"), new Question("n Roman Numerals, what does XL equate to?",["90","15","40","5"],"40"), new Question("What is the symbol for imaginary numbers?",["e","i","t","m"],"i") ]; var quiz = new Quiz(questions); quiz.fill();
(function() { var slice = [].slice, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; define(['oraculum', 'oraculum/libs', 'oraculum/mixins/evented'], function(oraculum) { 'use strict'; var _; _ = oraculum.get('underscore'); oraculum.defineMixin('URLAppend.ModelMixin', { mixinitialize: function() { var url; url = this.url; return this.url = (function(_this) { return function() { var parentUrl, thisUrl; parentUrl = _.result(_this.parent, 'url'); thisUrl = _.isFunction(url) ? url.apply(_this, arguments) : url; return "" + parentUrl + thisUrl; }; })(this); } }); return oraculum.defineMixin('Submodel.ModelMixin', { mixconfig: function(mixinOptions, attrs, arg) { var submodels; submodels = (arg != null ? arg : {}).submodels; return mixinOptions.submodels = _.extend({}, mixinOptions.submodels, submodels); }, mixinitialize: function() { var attributes, set; attributes = _.clone(this.attributes); _.each(this.attributes, (function(_this) { return function(submodel, attr) { if (!_this.mixinOptions.submodels[attr]) { return; } if (!_.isFunction(submodel != null ? submodel.on : void 0)) { return; } return _this.configureSubmodelAttribute(submodel, attr); }; })(this)); _.each(this.mixinOptions.submodels, (function(_this) { return function(submodel, attr) { if (!submodel["default"]) { return; } submodel = _this.createSubmodelFor(attr); return _this.set(attr, submodel, { silent: true }); }; })(this)); set = this.set; this.set = (function(_this) { return function(attrs, val, options) { if (attrs == null) { return; } if (_.isObject(attrs)) { options = val; } if (!_.isObject(attrs)) { attrs = _.object([attrs], [val]); } if (!(options != null ? options.unset : void 0)) { attrs = _this.parseSubmodelAttributes(attrs, options); } return set.call(_this, attrs, options); }; })(this); this.on('dispose', (function(_this) { return function(model) { if (model !== _this) { return; } return _.each(_this.attributes, function(value, attr) { var spec; spec = _this.mixinOptions.submodels[attr]; if (spec && spec.keep) { return; } return value != null ? typeof value.dispose === "function" ? value.dispose() : void 0 : void 0; }); }; })(this)); return this.set(attributes, { silent: true }); }, createSubmodelFor: function(attr) { var Model, ctorArgs, ref, submodel; Model = this.mixinOptions.submodels[attr].model; ctorArgs = this.mixinOptions.submodels[attr].ctorArgs; if (_.isFunction(ctorArgs)) { ctorArgs = ctorArgs.call(this); } ctorArgs || (ctorArgs = []); submodel = _.isString(Model) ? (ref = this.__factory()).get.apply(ref, [Model].concat(slice.call(ctorArgs))) : (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(Model, ctorArgs, function(){}); return this.configureSubmodelAttribute(submodel, attr); }, configureSubmodelAttribute: function(submodel, attr) { submodel.parent = this; this.stopListening(submodel); this.listenTo(submodel, 'all', (function(_this) { return function() { var args, eventName; eventName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; return _this.trigger.apply(_this, [attr + ":" + eventName].concat(slice.call(args))); }; })(this)); this.listenTo(submodel, 'dispose', (function(_this) { return function(target) { if (target !== submodel) { return; } return _this.stopListening(submodel); }; })(this)); this.listenTo(this, "change:" + attr, (function(_this) { return function(model, value, options) { if (Boolean(value)) { return; } if (!Boolean(options != null ? options.unset : void 0)) { return; } if (_this.mixinOptions.submodels[attr].keep) { return; } if (!options.keep) { return typeof submodel.dispose === "function" ? submodel.dispose() : void 0; } }; })(this)); return submodel; }, parseSubmodelAttributes: function(attrs, options) { attrs = _.clone(attrs); _.each(attrs, (function(_this) { return function(value, attr) { var isCollection, isModel, isModelOrCollection, spec, submodel, tags; if (!(spec = _this.mixinOptions.submodels[attr])) { return; } tags = value != null ? typeof value.__tags === "function" ? value.__tags() : void 0 : void 0; isModel = (tags != null) && indexOf.call(tags, 'Model') >= 0; isCollection = (tags != null) && indexOf.call(tags, 'Collection') >= 0; isModelOrCollection = isModel || isCollection; if (isModelOrCollection) { return _this.configureSubmodelAttribute(value, attr); } submodel = _this.get(attr); if (_.isFunction(submodel != null ? submodel.set : void 0)) { submodel.set(value, _.extend({}, spec.setOptions, options)); return delete attrs[attr]; } else { submodel = _this.createSubmodelFor(attr); submodel.set(value, _.extend({}, spec.setOptions, options)); return attrs[attr] = submodel; } }; })(this)); return attrs; } }, { mixins: ['Evented.Mixin'] }); }); }).call(this);
define([ 'client/views/graph/component', 'extensions/mixins/pivot' ], function (Component, Pivot) { var LABELS_OFF = 'no labels'; var Tooltip = Component.extend({ classed: 'tooltip', constrainToBounds: true, horizontal: 'right', vertical: 'bottom', textHeight: 11, xOffset: -7, yOffset: -7, x: function (index) { var xPos = this.graph.getXPos(index); return this.scales.x(xPos); }, y: function (index, attr) { var yPos = this.graph.getYPos(index, attr); return this.scales.y(yPos); }, textWidth: function (selection) { return selection.node().getBBox().width; }, getValue: function (model, index, attr) { attr = attr || this.graph.valueAttr; return model.get(attr); }, formatValue: function (value) { if (value === null) { return '(no data)'; } var format = _.extend({ type: 'number', magnitude: true, pad: true }, this.graph.formatOptions); if (this.graph.isOneHundredPercent()) { format.type = 'percent'; } return this.format(value, format); }, onChangeSelected: function (model, index, options) { options = options || {}; var selection = this.componentWrapper.selectAll('text'); if (model === null) { selection.data([]).exit().remove(); return; } var value = this.getValue(model, index, options.valueAttr); if (value === LABELS_OFF) { selection.data([]).exit().remove(); return; } value = this.formatValue(value); selection = selection.data([value, value]); selection.exit().remove(); selection.enter().append('text').attr('class', function (d, index) { return index === 0 ? 'tooltip-stroke' : 'tooltip-text'; }).attr('dy', this.textHeight); selection.text(value); var basePos = { x: this.x(index), y: this.y(index, options.valueAttr) }; var pos = this.applyPivot(basePos, { horizontal: this.horizontal, vertical: this.vertical, xOffset: this.xOffset, yOffset: this.yOffset, constrainToBounds: this.constrainToBounds, width: this.textWidth(selection), height: this.textHeight }, { width: this.graph.innerWidth, height: this.graph.innerHeight }); selection.attr('transform', 'translate(' + pos.x + ', ' + pos.y + ')'); this.moveToFront(); } }); _.extend(Tooltip.prototype, Pivot); return Tooltip; });
var check_all = document.getElementsByClassName('check_all'); //全选 var showStyle = getTagName('img',$('right_img'));//显示风格按钮1 var list_style = document.getElementsByClassName('list_sort'); //列表样式切换 var aBoxs = getClassName('right_main_box');//单个文件夹1 var lis = getClassName('lis_style');//单个文件夹列表样式1 var checkBox = getClassName('checkBox');//全选1 var grid = document.getElementsByClassName('grid'); //块样式 var list = document.getElementsByClassName('list'); //列表样式 var nav_list = document.getElementById('nav_list'); var old_style = {elem:aBoxs[0],index:0}; //默认样式 var all_check = false; //全选状态 var pid = 0;//当前位置hash值 var arr_pid = [];//当前位置hash对应数据 var Id = 0; var data = [{ //文件数据列表 fid : 1, file_name : 111, pid : 0 }, { fid : 2, file_name : 'CSS课程', pid : 0 }, { fid : 3, file_name : 'HTML课程', pid : 0 }, { fid : 4, file_name : 'JS课程', pid : 0 }] //创建DOM结构,录入相应数据 function newDOM(obj,num,arr,insert){ pid = location.hash.split('=')[1]; //获取当前所在位置; pid = pid?parseInt(pid):0; //当前位置不存在 默认首页; arr_pid = arr.filter(function(a){ return a.pid == pid;}); //取出当前位置下文件列表 if(!insert){ //插入数据 不执行清除 obj.innerHTML = ''; //构建数据前执行数据清除 } if(num){ for(var i=0;i<arr_pid.length;i++){ var li = document.createElement('li'); var input = document.createElement('input'); var a = document.createElement('a'); input.type = 'checkbox'; input.onclick = function(){ checked_fun(old_style.index); //处理选中状态 } a.href = 'javascript:;'; a.innerText = arr_pid[i].file_name; li.appendChild(input); li.appendChild(a); li.onmousedown = function(ev){ //右击事件 if(ev.button == 2){ tips_fun(this,obj); } } li.fid = arr_pid[i].fid; //记录元素编号 用于重命名 li.pid = arr_pid[i].pid; li.ondblclick = function(ev){ ev.cancelBubble = true; //阻止冒泡 双击时单击会被触发两次 location.hash = 'pid='+this.fid; //记录打开文件路径 } if(!insert){ //列表展现 数据插入尾部 obj.appendChild(li); }else{ //新增 数据插入头部 return obj.insertBefore(li,obj.firstElementChild); } } }else{ for(var i=0;i<arr_pid.length;i++){ var dl = document.createElement('dl'); var dt = document.createElement('dt'); var img = document.createElement('img'); img.src = 'img/images/6_9.png'; var span = document.createElement('span'); var dd = document.createElement('dd'); var a = document.createElement('a'); a.href = 'javascript:;'; a.innerText = arr_pid[i].file_name; dd.appendChild(a); dt.appendChild(img); dt.appendChild(span); dt.onmouseenter = function(){ //鼠标移入 this.className = 'active'; } dt.onmouseleave = function(){ //鼠标移出 if(this.lastElementChild.className != 'active'){ _removeClass(this,'active'); _removeClass(this.lastElementChild,'active'); } } dt.onclick = function(){ //鼠标点击 if(this.lastElementChild.className == 'active'){ _removeClass(this.lastElementChild,'active'); }else{ this.lastElementChild.className = 'active'; this.className = 'active'; } checked_fun(old_style.index); //处理选中状态 } dl.appendChild(dt); dl.appendChild(dd); dl.onmousedown = function(ev){ //右击事件 if(ev.button == 2){ tips_fun(this,obj); } } dl.fid = arr_pid[i].fid; dl.pid = arr_pid[i].pid; //记录文件父级 dl.ondblclick = function(){ location.hash = 'pid='+this.fid; //记录打开文件路径 } if(!insert){ //列表展现 数据插入尾部 obj.appendChild(dl); }else{ //新建 数据插入头部 return obj.insertBefore(dl,obj.firstElementChild); } } } } newDOM(old_style.elem,old_style.index,data); //构建初始数据 //==============================数据操作(增、删、改)======================================== function data_edit(obj,num,arr){ //修改数据 新数据 修改方式(新增0 删除1 修改2) 原数据 if(num==2){ for(var i=0;i<arr.length;i++){ if(arr[i].fid == obj.fid){ arr[i].file_name = obj.file_name; //替换找到位置 } } }else if(num==1){ //删除 for(var i=0;i<arr.length;i++){ if(arr[i].fid == obj.fid){ arr.splice(i,1); //删除找到位置 i--; } } }else{ arr.push(obj[0]); //新增数据 } } //==============================新建文件夹======================================== $('right_btn_btn1').onclick = function(){ //增加文件夹 Id = Id?Id:data.length; //Id号设置 Id++; var new_data = [{ //新建数据 fid : Id, file_name : '新建文件夹', pid : pid }]; var obj = newDOM(old_style.elem,old_style.index,new_data,1); //列表显示添加数据 data_edit(new_data,0,data); //添加数据记录 checked_fun(old_style.index); //处理选中状态 // rename_fun(obj); } //==============================列表样式切换======================================== showStyle[0].onclick = function(){ //列表样式切换 if(!old_style.index){ //判断列表展现样式 showStyle[0].src = 'img/images/6.png'; showStyle[1].src = 'img/images/8.png'; old_style.elem = lis[0]; old_style.index = 1; showStyle[1].onclick = function(){ showStyle[0].src = 'img/images/7.png'; showStyle[1].src = 'img/images/9.png'; old_style.elem = aBoxs[0]; old_style.index = 0; } newDOM(old_style.elem,old_style.index,data); //样式改变重构数据 checked_fun(old_style.index,1); //处理选中状态 } //==============================右键列表层======================================== function tips_fun(obj,parObj){ //右键列表 obj.oncontextmenu = function(ev){ //阻止默认鼠标事件 ev = ev || event; ev.preventDefault(); }; var tips = getClassName('tips'); //获取右键列表 var tips_lis = tips[0].getElementsByTagName('li'); //获取右键列表 tips[0].oncontextmenu = function(ev){ //阻止默认鼠标事件 ev = ev || event; ev.preventDefault(); }; tips[0].style.display = 'block'; tips[0].style.left = obj.offsetLeft+60+'px'; tips[0].style.top = obj.offsetTop+'px'; for(var i=0;i<tips_lis.length;i++){ tips_lis[i].index = i; tips_lis[i].onclick = function(){ if(this.index==1){ //重命名 rename_fun(obj); }else if(this.index==2){ //删除元素 parObj.removeChild(obj); data_edit(obj,1,data); //删除数据列表中对应数据 checked_fun(old_style.index); //处理选中状态 }else{ //打开文件夹 location.hash = 'pid='+obj.fid; //记录打开文件路径 // newDOM(parObj,0,data); //展开子级文件列表 } tips[0].style.display = 'none'; } } tips[0].onmouseleave = function(){ //鼠标移出 关闭右键列表 this.style.display = 'none'; } for(var i=0;i<tips_lis.length;i++){ tips_lis[i].onmouseenter = function(){ //右键列表 鼠标经过状态 for(var j=0;j<tips_lis.length;j++){ _removeClass(tips_lis[j],'active'); } this.className = 'active'; } } } //==============================文件重命名层======================================== function rename_fun(obj){ //重命名 var rename = document.getElementsByClassName('rename'); var inputs = rename[0].getElementsByTagName('input'); inputs[0].value = ''; rename[0].style.display = 'none'; if(!old_style.index){ //判断列表展现样式 rename[0].style.left = obj.offsetLeft+'px'; rename[0].style.top = obj.offsetTop+obj.offsetHeight-20+'px'; }else{ rename[0].style.left = obj.offsetLeft+48+'px'; rename[0].style.top = obj.offsetTop+5+'px'; } rename[0].style.display = 'block'; //打开重命名层 inputs[0].focus(); inputs[1].onclick = function(){ //确认按钮 if(inputs[0].value == ''){ alert('请输入文件名!'); inputs[0].focus(); }else{ if(!old_style.index){ obj.lastElementChild.lastElementChild.innerText = inputs[0].value; //替换名称 }else{ obj.lastElementChild.innerText = inputs[0].value; //替换名称 } obj.file_name = inputs[0].value; rename[0].style.display = 'none'; data_edit(obj,2,data); //修改数据列表对应名称 } } inputs[2].onclick = function(){ //取消按钮 inputs[0].value = ''; rename[0].style.display = 'none'; } document.onmousedown = function(ev){ //重命名打开时检测鼠标按下事件 ev = ev || event; if(ev.target != inputs[0] && ev.target != inputs[1]){ //不是输入框 也不是确认按钮 inputs[2].onclick(); //关闭重命名层 document.onmousedown = null; //清空鼠标按下事件 } } } //==============================选择处理======================================== var check_ed = []; //记录选中状态 checkBox.ed = false; checkBox[0].onclick = function(){ if(this.checked){ checkBox.ed = true; checked_fun(old_style.index,1); //全选 }else{ check_ed = []; //清除记录状态 checkBox.ed = false; //清除全选 checked_fun(old_style.index,1); //全不选 } } function checked_fun(index,style,check){ //选择处理(当前样式,切换) if(style){ //切换列表 还原已选中状态 if(index){ //还原对应样式 var lis = lis[0].children; for(var i=0;i<lis.length;i++){ //循环列表 if(check_ed[lis[i].fid] || checkBox.ed){ //记录为真的勾选 lis[i].firstElementChild.checked = true; }else{ lis[i].firstElementChild.checked = false; } } }else{ var dts = aBoxs[0].children; for(var i=0;i<dts.length;i++){ //循环列表 if(check_ed[dts[i].fid] || checkBox.ed){ //记录为真的添加选中状态 dts[i].firstElementChild.className = 'active'; dts[i].firstElementChild.lastElementChild.className = 'active'; }else{ dts[i].firstElementChild.className = ''; dts[i].firstElementChild.lastElementChild.className = ''; } } } return false; //切换样式 还原选中状态 返回函数 } if(index){ var lis = lis[0].children; for(var i=0;i<lis.length;i++){ if(lis[i].firstElementChild.checked){ //已选中对象 加入记录 check_ed[lis[i].fid] = true; }else{ check_ed[lis[i].fid] = false; } } }else{ var dts = aBoxs[0].children; for(var i=0;i<dts.length;i++){ //已选中对象 加入记录 if(dts[i].firstElementChild.lastElementChild.className == 'active'){ check_ed[dts[i].fid] = true; }else{ check_ed[dts[i].fid] = false; } } } if(check_ed.every(function(a){ return a;})){ checkBox[0].checked = true; }else{ checkBox.ed = false; //清除全选键记录 checkBox[0].checked = false; //清除全选 } } //==============================当前所在位置处理======================================== var title_left = getClassName('right_title_line')[0]; var dis_arr = []; function dis_list(p_id){ //循环查找父级 if(p_id){ data.some(function(a){ if(a.fid == p_id){ //存储每一级 dis_arr.push('<a href="#pid='+a.fid+'">'+a.file_name+'</a>'); dis_list(a.pid); } }); }else{ if(dis_arr.length){ //处理每一级 全部文件 返回上级 dis_arr.push('<a href="#pid=0">全部文件</a>'); dis_arr = dis_arr.reverse(); var dis_last = dis_arr[dis_arr.length-2].split('">')[0]+'">返回上一级</a>'; title_left.innerHTML = dis_last +' | '+ dis_arr.join(' > ') + ' > '; }else{ title_left.innerText = '全部文件'; } } } //==============================页面跳转(hash改变)======================================== window.onhashchange = function(){ //hash值改变时 刷新列表 data_list(old_style.elem,old_style.index,data); //展开子级文件列表 dis_arr = []; //清空历史位置数据 dis_list(pid); //当前所在位置 数据重组 } }
import React from 'react'; import '../styles/flashcard.css'; import ActionBarComp from './ActionBarComp'; class FlashcardChartComp extends React.Component { constructor() { super(); this.state = { headerText: 'Chart', }; } render() { const { headerText } = this.state; return ( <div className="FlashcardChartComp"> <ActionBarComp showAdd={false} showBack={false} headerText={headerText} /> <p>FlashcardChartComp coming soon</p> </div> ); } } export default FlashcardChartComp;
class Offer extends React.Component { constructor(props) { super(props); } handleClose = () => { this.props.handleClose(); }; handleClick = () => { this.props.handleClick(this.props.offer.id); }; render(){ const { offer, handleClose, singleOffer } = this.props; const expirationDate = new Date(offer.expiration).toLocaleString(); return( <div className={`offer ${singleOffer ? 'single' : ''}`} onClick={this.handleClick}> {singleOffer && <a className="back" onClick={this.handleClose}>Back</a> } <div className="title">{offer.name}</div> <div className="imgContainer"> <img src={offer.image_url} alt=""/> </div> <div>{offer.description}</div> { singleOffer && <div> <div>{offer.terms}</div> <div>Expires: {expirationDate}</div> </div> } </div> ) } } Offer.proptypes = { handleClick: PropTypes.func }; Offer.defaultProps = { handleClick: () => {}, };
import React, { Component ,Fragment} from 'react' import SideBar from '../components/SideBar' import './Layout.css' import ArticalForm from '../components/ArticalForm' import {articleCreate, showArea,deleteArticle ,articleUpdate} from '../redux/actions/index' import {connect} from 'react-redux' import ArticleTitle from '../components/ArticleTitle' import Area from '../components/Area'; import $ from 'jquery' import {reset} from 'redux-form' class Layout extends Component { constructor(props) { super(props) this.onCreateArticle = this.onCreateArticle.bind(this); } onCreateArticle(values){ if(!this.props.tempArticle.id ){ this.props.onCreateArticle(values) } else { this.props.onUpdateArticle( values) } $('#articleForm').modal('hide'); this.props.onResetForm() } render() { return ( <React.Fragment> <ArticalForm onSubmitArticle = {this.onCreateArticle} /> <div className="continer-fluid"> <div className="row"> <div className="col-2 sibebar " style={{paddingRight:'0'}} > <SideBar /> </div> <div className="col-3 title " style={{paddingLeft:'0'}}> {this.props.articleTitle.map(titles=> <ArticleTitle id={titles.id} title={titles.title} showArea={()=>this.props.onShowArea(titles.id)} clicked={() => this.props.onRemovedArticle(titles.id)} EditArticle={()=>this.props.onEditArticle(titles.id)} clickStar={()=>this.props.onClickStar(titles.id)} /> )} </div> <div className="col-7"> <Area /> </div> </div> </div> </React.Fragment> ) } } const mapStateToProps=state=>{ return{ articleTitle:state.artr.articles, editing:state.artr.editing, tempArticle:state.artr.article } } const mapDispatchToProps=dispatch=>{ return{ onShowArea:id=>dispatch(showArea(id)), onCreateArticle:values=>((dispatch(articleCreate({article:values}))),$('#articleForm').modal('hide')), onRemovedArticle: id => dispatch(deleteArticle(id)), onEditArticle:articleId=>((dispatch({type: 'ARTICLE_LOAD', payload:{articleId}})),$('#articleForm').modal('show')), onUpdateArticle:values=>dispatch(articleUpdate(values)), onClickStar:articleId=>dispatch({type:'ARTICLE_FAVOURITE',payload:{articleId}}), onResetForm:()=>dispatch(reset("articleForm")) } } export default connect(mapStateToProps,mapDispatchToProps)(Layout);
import { Component } from 'kapla' import lottie from 'lottie-web' // Bodymovin JSON files import feature0 from './lottie-animation/feature-0.json' import feature1 from './lottie-animation/feature-1.json' import feature2 from './lottie-animation/feature-2.json' import feature3 from './lottie-animation/feature-3.json' import feature4 from './lottie-animation/feature-4.json' const bodymovins = [ { data: feature0, step: 158, }, { data: feature1, step: 140, }, { data: feature2, step: 100, }, { data: feature3, step: 140, }, { data: feature4, step: 110, }, ] export default class extends Component { load() { const featureOrder = this.data.get('order') this.bodymovin = bodymovins[featureOrder] if (!this.bodymovin) { return } this.animation = lottie.loadAnimation({ container: this.$refs.bodymovin, renderer: 'svg', loop: false, autoplay: false, animationData: this.bodymovin.data, }) this.animation.setSpeed(1.5) } animateOut() { if (!this.animation) { return Promise.resolve() } return new Promise(resolve => { this.animation.playSegments( [this.bodymovin.step, this.animation.animationData.op], true ) setTimeout(() => { resolve() }, 1500) }) } animateIn() { if (!this.animation) { return Promise.resolve() } return new Promise(resolve => { this.animation.playSegments([0, this.bodymovin.step], true) setTimeout(() => { resolve() }, 1000) }) } }
import {ADD_NEW_DECK, ADD_CARD_TO_DECK, GET_ALL_DECKS, GET_SINGLE_DECK} from "../components/action/types"; export default function deckReducer(state = {}, action) { switch (action.type) { case GET_ALL_DECKS: { return {...state, ...action.decks}; } case ADD_NEW_DECK: { return {...action.decks}; } default: { return state; } } }
//see all endpoints in one file import axios from 'axios' const auth = { register: params => axios.post('http://localhost:3000/auth/register', params), login: params => axios.post('http://localhost:3000/auth/login',params), // etc. } const skills ={ get: () => axios.get('http://localhost:3000/skills/all', { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), match: async(params) => await axios.post('http://localhost:3000/skills/match', params), add: params => axios.post('http://localhost:3000/skills/add', params, { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), remove: params => axios.post('http://localhost:3000/skills/remove', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), suggested: () => axios.post('http://localhost:3000/skills/suggested', { "limit": 5 },{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const profile={ get: () => axios.get('http://localhost:3000/user/profile', { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), update: params => axios.post('http://localhost:3000/user/profile', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), updateSocial: params => axios.post('http://localhost:3000/social/profile', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), uploadImage: params => axios.post('http://localhost:3000/social/profile/image', params, { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), updateLocations: params => axios.post('http://localhost:3000/social/profile/locations', params, { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), getPublic: params => axios.post('http://localhost:3000/profile', params, { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const work ={ get: () => axios.get('http://localhost:3000/work/all', { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), add: params => axios.post('http://localhost:3000/work/add', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), remove: params => axios.post('http://localhost:3000/work/remove', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), update: params => axios.post('http://localhost:3000/work/update', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), matchCategory: params =>axios.post('http://localhost:3000/work/match_category', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), getPublic:params =>axios.post('http://localhost:3000/work/get', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const bookmarks = { get: () => axios.get('http://localhost:3000/jobs/bookmarks/all', { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), add: params => axios.post('http://localhost:3000/jobs/bookmarks/add', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), remove: params => axios.post('http://localhost:3000/jobs/bookmarks/remove', params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const searchJobsAcct = { get: (queryString) => axios.get(`http://localhost:3000/jobs/search?${queryString}`, { headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), click: params => axios.post('http://localhost:3000/jobs/click',params,{ headers: {'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const searchJobs = { get: (queryString) => axios.get(`http://localhost:3000/jobs/search?${queryString}`) } const articles = { get: () => axios.get('http://localhost:3000/article') } const events = { get: () => axios.get('http://localhost:3000/event/all') } const dailyDigest = { get: () => axios.get('http://localhost:3000/daily', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), getFromUrl: params => axios.get('http://localhost:3000/daily', { headers:{ 'Authorization': 'Token '+ params} }), getPublic: () => axios.get('http://localhost:3000/daily') } const invitations = { getPending: () => axios.get('http://localhost:3000/meetup/invite/pending', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), getCurrent: () => axios.get('http://localhost:3000/meetup/invite/all', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), acceptInvitation: params => axios.post('http://localhost:3000/meetup/invite/accept', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), rejectInvitation: params => axios.post('http://localhost:3000/meetup/invite/reject', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const meetups = { getTeleLink: params => axios.post('http://localhost:3000/telegram/user', params), changeDate: params => axios.post('http://localhost:3000/meetup/update', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), completeMeetup: params => axios.post('http://localhost:3000/meetup/complete', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), cancelMeetup: params => axios.post('http://localhost:3000/meetup/cancel', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), search: params => axios.post('http://localhost:3000/meetup/search', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), invite: params => axios.post('http://localhost:3000/meetup/invite/send', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), by_location: ()=> axios.get('http://localhost:3000/meetup/by_location', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), by_stage: ()=> axios.get('http://localhost:3000/meetup/by_stage', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const recommendations = { request: (params) => axios.post('http://localhost:3000/recommendation/request', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), retrieveAll: ()=>axios.get('http://localhost:3000/recommendation/all', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), retrieveAllRequest:()=>axios.get('http://localhost:3000/recommendation/request/all', { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), submitRecommendation:(params)=>axios.post('http://localhost:3000/recommendation/submit', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), reject:(params)=>axios.post('http://localhost:3000/recommendation/request/reject', params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), processRecord: (params) => axios.post("http://localhost:3000/meetup/invite/process", params,{ headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), getPublic: (params) => axios.post("http://localhost:3000/recommendation/get", params,{ headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } const alerts = { retrieve: (params) => axios.post("http://localhost:3000/alert/all", params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), seen: (params) => axios.post("http://localhost:3000/alert/seen", params, { headers:{ 'Authorization': 'Token '+ window.localStorage.getItem('authToken')} }), } export default { auth, skills, profile, work, bookmarks, searchJobsAcct, searchJobs, articles, dailyDigest, events, invitations, meetups, recommendations, alerts, }
const utils1 = require("../../modules/IMPmodules/util") const util = new utils1() const mushroom = require("../../entity/objects/food/mushroom.js") const redmushroom = require("../../entity/objects/food/redmushroom.js") const watermelon = require("../../entity/objects/food/watermelon.js") const watermelonslice = require("../../entity/objects/food/watermelonslice.js") const waterberry = require("../../entity/objects/food/waterberry.js") const berry = require("../../entity/objects/food/berry.js") function foodspawn(entities, objectid, aobjids) { if (entities[objectid].isloaded) { if (entities[objectid].spawnedtime + 5000 < Date.now()) { switch (entities[objectid].type) { case 1: if (entities[objectid].mushroomamount < entities[objectid].maxmushroomamount) { let random = util.randomNumber(0, 100) entities[objectid].addedmushroom(); let objids = aobjids.giveid(true); let newpos = { x: util.randomNumber(entities[objectid].x - entities[objectid].width / 2, entities[objectid].x + entities[objectid].width / 2 ) , y: util.randomNumber(entities[objectid].y - entities[objectid].height / 2, entities[objectid].y + entities[objectid].height / 2) } if (util.isnumbcorrectbetween(0, 15, random)) { entities[objids] = new redmushroom(objids, entities[objectid].id, newpos.x, newpos.y) } else { entities[objids] = new mushroom(objids, entities[objectid].id, newpos.x, newpos.y) } } break; case 4: if (entities[objectid].foodamount < 12) { let objids = aobjids.giveid(true); let newpos = util.rotate(entities[objectid].x, entities[objectid].y, entities[objectid].x + entities[objectid].radius, entities[objectid].y, util.randomNumber(0, 360)) entities[objectid].addedfood(); entities[objids] = new waterberry(objids, entities[objectid].id, newpos.x, newpos.y) } break case 27: if (entities[objectid].foodamount < 10) { let objids = aobjids.giveid(true); let newpos = util.rotate(entities[objectid].x, entities[objectid].y, entities[objectid].x + entities[objectid].radius, entities[objectid].y, util.randomNumber(0, 360)) entities[objectid].addedfood(); entities[objids] = new berry(objids, entities[objectid].id, newpos.x, newpos.y) } break case 44: if (entities[objectid].foodamount < 2) { let which = (Math.floor(Math.random() * 2)) entities[objectid].addedfood() if (which == 1) { let objids = aobjids.giveid(true); let newpos = util.rotate(entities[objectid].x, entities[objectid].y, entities[objectid].x + util.randomNumber(entities[objectid].radius / 2, entities[objectid].radius), entities[objectid].y, util.randomNumber(0, 360)) entities[objids] = new watermelon(objids, entities[objectid].id, newpos.x, newpos.y) } else { let objids = aobjids.giveid(true); let newpos = util.rotate(entities[objectid].x, entities[objectid].y, entities[objectid].x + util.randomNumber(entities[objectid].radius / 2, entities[objectid].radius), entities[objectid].y, util.randomNumber(0, 360)) entities[objids] = new watermelonslice(objids, entities[objectid].id, newpos.x, newpos.y) } } break } } } } foodspawn.prototype = {} module.exports = foodspawn
$(document).ready(function () { // console.clear(); //$("p").click(function () { // $(this).hide(); //}); $('#processBtn').click(function(event) { event.preventDefault(); var bbArray = []; if($('#startNumber').val() !== "" && $('#endNumber').val() !== "" && $('#bishNumber').val()!=="" && $('#boshNumber').val()!=="") { for (let i = $('#startNumber').val(); i <= $('#endNumber').val(); i++) { bbArray.push(i); } bbArray.forEach(myFunction); }else if ($('#endNumber').val() < $('#startNumber').val()) { alert('End number must be greater than start number!!!') } else { alert('All fields are required!') } }); function myFunction(bbNumber) { var msg = bbNumber; if (bbNumber % $('#bishNumber').val() == 0) { msg = "Bish"; } if (bbNumber % $('#boshNumber').val() == 0) { msg = "Bosh"; } if (bbNumber % $('#bishNumber').val() == 0 && bbNumber % $('#boshNumber').val() == 0) { msg = "Bish-Bosh"; } console.log(msg); } });
// 1 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 // 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 // 例如:给定 nums = [2, 7, 11, 15], target = 9 // 因为 nums[0] + nums[1] = 2 + 7 = 9 // 所以返回 [0, 1] //1. 第一种解法 // 思路很简单,就是两次遍历 function getIndex (nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] === target) { return [i, j] } } } } getIndex([1,2,3,4], 6) //2. 第二种解法,利用新的数据结构Map function twoSum (nums, target) { const len = nums.length if (len < 2) { return [] } if (len === 2) { if (nums[0] + nums[1] === target) return [0, 1] return [] } const newNums = new Map() for (let i = 0; i < len; i++) { newNums.set(nums[i], i) } for (let i = 0; i < len; i++) { const right = target - nums[i] if (newNums.has(right)) { const targetIndex = newNums.get(right) if (targetIndex > i) { return [i, targetIndex] } } } return [] }
var sql=require('./db'); const UniqueId=function(uniqueId) { this.UniqueIdType=uniqueId.UniqueIdType; this.UniqueIdNumber=uniqueId.UniqueIdNumber; this.Patientid=uniqueId.Patientid; }; UniqueId.getAllUniqueId=function(result) { sql.query('Select * from UniqueIdTypes', function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { console.log('UniqueId : ', res); result(null, res.recordset); } }); }; UniqueId.getUniqueIdById = function(UniqueId, result) { // eslint-disable-next-line quotes sql.query("Select * from UniqueIdTypes where UniqueTypeId ='"+UniqueId+"'", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { result(null, res.recordset); } }); }; UniqueId.createUniqueId = function(newUniqueId, result) { // eslint-disable-next-line quotes sql.query("Insert into UniqueIdTypes(UniqueIdType,UniqueIdNumber,Patientid) values('"+newUniqueId.UniqueIdType+"','"+newUniqueId.UniqueIdNumber+"',,'"+newUniqueId.Patientid+"')", function(err, res) { if (err) { console.log('error: ', err); result(err, null); } else { console.log(res.Id); result(null, res.Id); } }); }; UniqueId.updateById = function(id, uniqueId, result) { // eslint-disable-next-line quotes sql.query("Update UniqueIdTypes Set UniqueIdType='"+uniqueId.UniqueIdType+"',UniqueIdNumber='"+uniqueId.UniqueIdNumber+"',Patientid='"+uniqueId.Patientid+"'where UniqueId='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { result(null, res.recordset); } }); }; UniqueId.remove = function(id, result) { // eslint-disable-next-line quotes sql.query("DELETE FROM UniqueIdTypes WHERE UniqueId ='"+id+"'", function(err, res) { if (err) { console.log('error: ', err); result(null, err); } else { res.send(`Record deleted with id: ${id}`); result(null, res); } }); }; module.exports= UniqueId;