text
stringlengths
7
3.69M
const monthNames = [ { full: 'January', abb: 'Jan' }, { full: 'February', abb: 'Feb' }, { full: 'March', abb: 'Mar' }, { full: 'April', abb: 'Apr' }, { full: 'May', abb: 'May' }, { full: 'June', abb: 'Jun' }, { full: 'July', abb: 'Jul' }, { full: 'August', abb: 'Aug' }, { full: 'September', abb: 'Sep' }, { full: 'October', abb: 'Oct' }, { full: 'November', abb: 'Nov' }, { full: 'December', abb: 'Dec' } ]; export const parseDate = date => { let datetime = new Date(date); let parsedDate = {}; parsedDate.month = datetime.getMonth(); parsedDate.fullMonthName = monthNames[parsedDate.month].full; parsedDate.abbMonthName = monthNames[parsedDate.month].abb; parsedDate.day = datetime.getDate(); parsedDate.year = datetime.getFullYear(); parsedDate.hour = datetime.getHours(); parsedDate.ampm = 'AM'; if (parsedDate.hour > 12) { parsedDate.hour -= 12; parsedDate.ampm = 'PM'; } parsedDate.mins = datetime.getMinutes(); parsedDate.secs = datetime.getSeconds(); return parsedDate; }; export const timeDisplay = time => { let seconds = Math.floor((time / 1000) % 60), minutes = Math.floor((time / (1000 * 60)) % 60), hours = Math.floor(time / (1000 * 60 * 60)); minutes = minutes < 10 ? '0' + minutes : minutes; seconds = seconds < 10 ? '0' + seconds : seconds; return hours + ':' + minutes + ':' + seconds; }; export const getAbbMonthName = month => { return monthNames[month].abb; };
import React from 'react' import { List } from 'antd-mobile'; import './applyGuide.css' const Item = List.Item; class ApplyGuide extends React.Component{ render(){ return ( <div className='applyGuide'> <div className="applyGuide-title">——报读指南——</div> <List renderHeader={() => '一、报读方法'} className="my-list"> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E7%BA%B8%E9%B9%A4.png" wrap="true" onClick={() => {}} multipleLine="true" > 报名办法: 免试入学,即日起直接到我校报名,或微信、QQ、电话报名、汇款报名、网上报名。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E7%BA%B8%E9%A3%8E%E8%BD%A6.png" wrap="true" multipleLine="true" onClick={() => {}} > 报名条件: 凡是应(往)届初中、高中毕业生或同等学历者,均可报读。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E7%BA%B8%E9%A3%8E%E8%BD%A6.png" onClick={() => {}} wrap="true" multipleLine="true" > ▼ 点击报名链接~在线报名 </Item> </List> <List renderHeader={() => '二、国家推出资助政策 促进技工教育发展'} className="my-list"> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E5%AD%A6%E8%B4%B9.png" wrap="true" onClick={() => {}} multipleLine="true" > 1、免学费: 凡报读我校的农村(含县镇)学生和城市家庭经济困难的学生均可申请免学费就读 (具体参照"粤财教〔2013〕54号文件"实行) ; </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E5%AD%A6%E8%B4%B9.png" wrap="true" multipleLine="true" onClick={() => {}} > 2、国家助学金: 根据省教育厅规定,符合条件的农村(含县镇)学生和城市家庭经济困难的学生均可申请国家助学金2000元/人/年,连续资助二年,共4000元。 </Item> </List> <List renderHeader={() => '三、报到时间'} className="my-list"> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E6%97%A5%E6%9C%9F.png" wrap="true" onClick={() => {}} multipleLine="true" > 2019年9月7日回校报到,9月9日上课。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E6%97%A5%E6%9C%9F.png" wrap="true" multipleLine="true" onClick={() => {}} > 新生接待站: 2019年9月7日新生回校报到注册时,我校在茂名东火车站、河东交委汽车总站和河西汽车总站均设有新生接待站接送新生回校报到注册。 </Item> </List> <List renderHeader={() => '四、报到手续'} className="my-list"> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E6%B5%81%E7%A8%8B%E5%AE%A1%E6%89%B9.png" wrap="true" onClick={() => {}} multipleLine="true" > 1、凭入学录取通知书或者缴费单据到班主任处报到注册。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E6%B5%81%E7%A8%8B%E5%AE%A1%E6%89%B9.png" wrap="true" multipleLine="true" onClick={() => {}} > 2、自备一寸免冠正面彩色相片8张,身份证及户口簿复印件(复印格式见背后)一式五份,高中(中专、中技)毕业证书(报读高技的学生需提供),入学报到时一并交给班主任。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E6%B5%81%E7%A8%8B%E5%AE%A1%E6%89%B9.png" wrap="true" multipleLine="true" onClick={() => {}} > 3、是党(团)员的学生要提交党(团)员组织关系证明。 </Item> </List> <List renderHeader={() => '五、交通指南'} className="my-list"> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E5%9C%B0%E5%9D%80.png" wrap="true" onClick={() => {}} multipleLine="true" > 官渡校区(校本部)地址: 茂名市光华北路638号(即广东石油化工学院官渡校区东侧),乘坐出租车或7路、11路、210路公交车即可直达学校门口。 </Item> <Item thumb="https://mmyjschool.oss-cn-guangzhou.aliyuncs.com/school/%E5%9C%B0%E5%9D%80.png" wrap="true" multipleLine="true" onClick={() => {}} > 厂前校区地址: 茂名市红旗北路126号,乘坐出租车或3路、6路、18路、303路公交车即可直达学校门口。 </Item> </List> </div> ) } } export default ApplyGuide
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var TimerSchema = new Schema({ countdown: {type:Date, required:true}, updatedAt: {type:Date, required:true}, for :{type:String ,required:true}, }); const Timer = mongoose.model("Timer", TimerSchema); module.exports = { Timer: Timer };
import React from "react" import Slider from "react-slick"; import { dummy } from "../../../assets/common/Utils/DummyAboutUs2"; import ReviewsCard from './components/ReviewsCard/ReviewsCard' import 'react-magic-slider-dots/dist/magic-dots.css'; const Reviews = () => { const settings = { className: "center", infinite: true, dots: true, slidesToShow: 1, slidesToScroll: 1, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 1, slidesToScroll: 1, infinite: true, dots: true, }, }, { breakpoint: 761, settings: { slidesToShow: 1, slidesToScroll: 1, initialSlide: 1, infinite: true, }, }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1, initialSlide: 1, infinite: true, }, }, ], } return ( <div className="reviews"> <div className="container"> <div className="reviews__content"> <span className="primary-title">Cómo nuestos clientes cambiaron su negocio </span> <Slider {...settings}> {dummy.reviews.map(i => ( <ReviewsCard social={i.social} proffesion={i.proffession} name={i.name} img={i.image} description={i.description} /> ))} </Slider> </div> </div> </div> ) } export default Reviews
import "./App.css"; import { BrowserRouter as Router, Link } from "react-router-dom"; import "antd/dist/antd.css"; import { Layout, Menu, Button, Row, Col } from "antd"; import React, { Suspense } from "react"; import Routes from "./routes/Routes"; const { Header, Footer, Content, Sider } = Layout; export default function App() { return ( <Router> <Layout className="layout"> <Suspense fallback={<div>Loading...</div>}> <Header> <Row justify="space-between"> <Col span={22}> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={["1"]} > <Menu.Item key="1"> <Link to="/">Home</Link> </Menu.Item> <Menu.Item key="2"> <Link to="/about">About</Link> </Menu.Item> <Menu.Item key="3"> <Link to="/users">Users</Link> </Menu.Item> <Menu.Item key="4"> <Link to="/login">Login</Link> </Menu.Item> <Menu.Item key="5"> <Link to="/register">Register</Link> </Menu.Item> </Menu> </Col> <Col span={2}> <Button type="primary">Logout</Button> </Col> </Row> </Header> <Layout> <Sider theme="light"> <Menu> <Menu.Item> <Link to="/games/all">Games All</Link> </Menu.Item> <Menu.Item> <Link to="/games/favourite">Games Favourite</Link> </Menu.Item> </Menu> </Sider> <Content> <Routes /> </Content> </Layout> <Footer style={{ textAlign: "center" }}> Simple React app by DiFly ©2020 </Footer> </Suspense> </Layout> </Router> ); }
const mongoose = require('mongoose') // 1.连接数据库 mongoose.connect('mongodb://localhost/students', { useNewUrlParser: true, useUnifiedTopology: true }, err => { if (err) return console.log('Connection Error:' + err) console.log('Connection success!') }) // 2.设计文档结构 const userSchema = new mongoose.Schema({ userName: { type: String, required: true, }, age: { type: Number, required: true, }, alias: String, }) // 3.将文档结构发布为模型 // 第一个参数:传入一个大写的字符串表示你的数据库名称,MongoDB会自动转成小写的复数形式 // 例如: User --> users // 第二个参数:架构 Schema // 返回值:模型构造函数 const User = mongoose.model('User', userSchema) // 4.使用模型构造函数,对集合中的数据进行操作 // 4.1 增 const gdz = new User({ userName: '张三', age: 18, alias: '耿德洲' }) // gdz.save((err, result) => { // if (err) return console.log('保存失败') // console.log(result) // }) // 4.2 查 User.find((err, res) => { if (err) return console.log('查询失败') console.log(res) }) // 4.2.2 条件查询 // User.find({userName: '张三'},(err,data) => { // if(err) return console.log('查询出错') // console.log(data) // }) // User.findOne({userName:'张三'},(err,data) => { // if(err) return console.log('查询出错') // console.log(data) // }) User.deleteMany((err, data) => { if (err) return console.log('删除出错') console.log(data) }) // User.updateOne({ userName: '张三' }, { alias: '张狗蛋' }, (err, data) => { // if (err) return console.log('更新失败') // console.log(data) // })
angular.module('main') .factory('Contents', function () { var Contents = [ { "title": "Frozen", "description": "Fearless optimist Anna teams up with Kristoff in an epic journey, encountering Everest-like conditions, and a hilarious snowman named Olaf in a race to find Anna's sister Elsa, whose icy powers have trapped the kingdom in eternal winter.", "url": "http://www.imdb.com/title/tt2294629/", "date": "2013-11-27", "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Animation" } ] } }, { "title": "Rio 2", "description": "It's a jungle out there for Blu, Jewel and their three kids after they're hurtled Rio de Janeiro to the wilds of the Amazon. As Blu tries to fit in, he goes beak-to-beak with the vengefu", "url": "http://www.imdb.com/title/tt2357291/?ref_=hm_otw_tt", "date": "2014-04-11", "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Animation" } ] } }, { "title": "Avatar", "description": "A paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.", "url": "/BrokerDealerCenter/Portal/RenderContent.aspx?ContentId=29733592", "date": "2009-12-18" , "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Action", "subcategoryList": { "subcategoryName": "Adventure" } } ] } }, { "title": "The Shawshank Redemption", "description": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", "url": "http://www.imdb.com/title/tt0111161/", "date": "1994-03-05" , "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Crime", "subcategoryList": { "subcategoryName": "Drama" } } ] } }, { "title": "The Wolf of Wall Street", "description": "Based on the true story of Jordan Belfort, from his rise to a wealthy stock-broker living the high life to his fall involving crime, corruption and the federal government.", "url": "http://www.imdb.com/title/tt0993846/?ref_=nv_sr_1", "date": "2013-12-25" , "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Biograhpy", "subcategoryList": { "subcategoryName": "Comedy" } } ] } }, { "title": "The Grand Budapest Hotel", "description": "The adventures of Gustave H, a legendary concierge at a famous European hotel between the wars, and Zero Moustafa, the lobby boy who becomes his most trusted friend.", "url": "http://www.imdb.com/title/tt2278388/", "date": "2014-03-28" , "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Comedy" } ] } }, { "title": "X-Men: Days of Future Past", "description": "The X-Men send Wolverine to the past in a desperate effort to change history and prevent an event that results in doom for both humans and mutants.", "url": "http://www.imdb.com/title/tt1877832/", "date": "2014-05-23" , "data" : { "contentType" : "movie", "categoryList" : [ { "categoryName": "Adventure" } ] } } ] return Contents; });
const Consultations = require("../models/consultations"); module.exports = (app) => { app.get("/atendimentos", (req, res) => { Consultations.list(res); }); app.get("/atendimentos/:id", (req, res) => { const id = parseInt(req.params.id); Consultations.findId(id, res); }); app.post("/atendimentos", (req, res) => { const consutation = req.body; Consultations.adding(consutation, res); }); app.patch("/atendimentos/:id", (req, res) => { const id = parseInt(req.params.id); const values = req.body; Consultations.change(id, values, res); }); app.delete("/atendimentos/:id", (req, res) => { const id = parseInt(req.params.id); Consultations.delete(id, res); }); };
const Methods = require("./methods") const { resolve } = require("path") const defaultId = { default: Date.now(), required: true } /** * Create a new Schema * * @name Schema * @function * @param {String} model * @param {Object} schema * @param {String} path * @returns {Methods} */ function Schema(model, schema = { _id: defaultId }, path) { if (!model) throw new Error("The Schema requires a name, see the documentation.") if (!schema._id) schema._id = defaultId if (![Number, String].includes(schema._id.type)) schema._id.type = Number if (!schema._id.required || !schema._id.default) Object.assign(schema._id, defaultId) const databasePath = resolve(`${path}/${model}.json`) return { ...Methods(schema, databasePath), } } module.exports = Schema
let codeEditor = CodeMirror(document.querySelector('#code-text-area'), { value: '', mode: 'javascript', theme: 'eclipse', tabSize: 2, lineNumbers: true, extraKeys: {'Tab-Space': 'autocomplete'} }); const getCode = () => { return codeEditor.getValue() }; const setCode = (val) => { codeEditor.getDoc().setValue(val); } export {getCode, setCode};
function play(){ clearErrors(); let round = 1; let input = document.getElementById("input").value; validateInput(input); playGame(input, round); return false; } function clearErrors() { for (let i = 0; i < document.forms["luckySevens"].elements.length; i++) { if (document.forms["luckySevens"].elements[i] .parentElement.className.indexOf("has-") != -1) { document.forms["luckySevens"].elements[i] .parentElement.className = "form-group form-inline"; } } } // function reset(){ // // resets luckySevens.html, hiding results from previous trials and initializing variables // document.getElementById("results").style.display = "none"; // document.getElementById("input").value = ""; // clearErrors(); // } function validateInput(input) { if(input < 0) { alert("The starting bet must be a positive number, with a value of at least 0."); document.forms["luckySevens"]["input"].parent543Element.className = "form-group form-inline has-error"; document.getElementById("res") document.forms["luckySevens"]["input"].focus; return false; } if(input == "" || isNaN(input)) { alert("The value of the starting bet cannot be empty."); document.forms["luckySevens"]["input"].parentElement.className = "form-group form-inline has-error"; document.forms["luckySevens"]["input"].focus; return false; } if(input.charAt(input.length - 3) != ".") { if (!(input.includes("."))) { return false; } else{ alert("The starting bet must be a valid monetary amount") document.forms["luckySevens"]["input"].parentElement.className = "form-group form-inline has-error"; document.forms["luckySevens"]["input"].focus; return false; } } } function playGame(gameMoney, round) { let maxValue = 0; let maxRound = 0; let oldGameMoney = gameMoney; if (oldGameMoney.includes(".") == false) { oldGameMoney = oldGameMoney + '.00'; } while (gameMoney > 0 && round < 10000) { // let oldGameMoney = gameMoney; let die1 = Number(Math.floor(6*Math.random())) + Number(1); let die2 = Number(Math.floor(6*Math.random())) + Number(1); if (Number(die1) + Number(die2) == 7) { gameMoney = Number(gameMoney) + Number(4); } else { gameMoney = Number(gameMoney) + Number(-1); } if (gameMoney >= maxValue) { maxValue = gameMoney; maxRound = Number(round) + Number(1); } round += 1; } document.getElementById("results").style.display = "block"; document.getElementById("startingBet").innerText = '$' + oldGameMoney; document.getElementById("totalRolls").innerText = round; document.getElementById("maxAmount").innerText = '$' + maxValue + '.00'; document.getElementById("maxCount").innerText = maxRound; return false; } // function playRound(gameMoney) { // let die1 = Number(Math.floor(6*Math.random())) + Number(1); // let die2 = Number(Math.floor(6*Math.random())) + Number(1); // if (Number(die1) + Number(die2) == 7) { // gameMoney = Number(gameMoney) + Number(4); // } else { // gameMoney = Number(gameMoney) + Number(-1); // } // return gameMoney; // }
const { Set } = require('./Set') let set = new Set(); set.add(1); console.log(set.values()); console.log(set.has(1)); console.log(set.size()); set.add(2); console.log(set.values()); console.log(set.has(2)); console.log(set.size()); set.delete(1); console.log(set.values()); set.delete(2); console.log(set.values());
import AuthorPage from './AuthorDetails'; export default AuthorPage;
const express=require("express"); module.exports=function(){ const server=express.Router(); server.use("/",function(request,response){ //需要获取session的哪一个部分 const key=request.query.content; //对session进行深拷贝 const cloneSession=Object.assign({},request.session) //返回结果 response.send(cloneSession[key]) }) return server }
//==================== // ページ上部 //==================== function writeTop(){ var html = ""; html += '<div class="container">'; html += '<!--▼header▼-->'; html += '<header class="slide inner">'; html += '<ul id="navToggle" class="burger slide"><li></li><li></li><li></li></ul><!--メニューボタン-->'; html += '<div class="logoAria">'; html += '<a href="/" class="logo"><img src="/img/logo.png" alt="KEMコーポレーション"></a>'; html += '<p class="top">ケーイーエム株式会社は、BG製品の代理店です</p>'; html += '</div>'; html += '<div class="inqAria">'; html += '<a href="/inquiry/" class="btn_inq"><img src="/img/topInq.png" alt="お問い合わせはこちらから"></a>'; html += '</div>'; html += '</header>'; html += '<!--▲header▲-->'; html += '<!--▼menu▼-->'; html += '<nav class="slide inner">'; html += '<ul>'; html += '<li><a href="/" class="active">HOME</a></li>'; html += '<li><a href="/lineups/">製品一覧</a></li>'; html += '<li><a href="/shops/">販売店・整備工場一覧</a></li>'; html += '<li><a href="/aboutbg/">BGとは</a></li>'; html += '<li><a href="/company/">会社概要</a></li>'; html += '<li><a href="/inquiry/">お問い合わせ</a></li>'; html += '<li><a href="/privacy/">プライバシーポリシー</a></li>'; html += '<li><a href="/sitemap.html">サイトマップ</a></li>'; html += '</ul>'; html += '</nav>'; html += '<!--▲menu▲-->'; html += '<!--▼slide▼-->'; html += '<div class="content slide">'; html += '<!--▼body▼-->'; html += '<div class="body clearfix">'; html += '<!--▼scroll▼-->'; html += '<div class="scroll inner">'; html += '<!--▼contents▼-->'; html += '<div class="contents">'; html += '<!--▼introduction▼-->'; html += '<div class="introduction">'; html += '<ol id="breadCrumb" class="clearfix">'; html += '<li>If you turn on javascript, this area is drawn to the breadcrumb(navigation).</li>'; html += '</ol>'; html += '<h1><script type="text/javascript">writeTitle();</script></h1>'; html += '</div>'; html += '<!--▲introduction▲-->'; document.write(html); } //==================== // 新ページ上部 //==================== function writeTopnew1(){ var html = ""; html += '<div class="container">'; html += '<!--▼header▼-->'; html += '<header class="slide inner">'; html += '<ul id="navToggle" class="burger slide"><li></li><li></li><li></li></ul><!--メニューボタン-->'; html += '<div class="logoAria">'; html += '<a href="/" class="logo"><img src="/img/logo.png" alt="KEMコーポレーション"></a>'; html += '<p class="top">ケーイーエム株式会社は、BG製品の代理店です</p>'; html += '</div>'; html += '<div class="inqAria">'; html += '<a href="/inquiry/" class="btn_inq"><img src="/img/topInq.png" alt="お問い合わせはこちらから"></a>'; html += '</div>'; html += '</header>'; html += '<!--▲header▲-->'; html += '<!--▼menu▼-->'; html += '<nav class="slide inner">'; html += '<ul>'; html += '<li><a href="/" class="active">HOME</a></li>'; html += '<li><a href="/lineup/">製品一覧</a></li>'; html += '<li><a href="/shops/">販売店・整備工場一覧</a></li>'; html += '<li><a href="/aboutbg/">BGとは</a></li>'; html += '<li><a href="/company/">会社概要</a></li>'; html += '<li><a href="/inquiry/">お問い合わせ</a></li>'; html += '<li><a href="/privacy/">プライバシーポリシー</a></li>'; html += '<li><a href="/sitemap.html">サイトマップ</a></li>'; html += '</ul>'; html += '</nav>'; html += '<!--▲menu▲-->'; html += '<!--▼slide▼-->'; html += '<div class="content slide">'; html += '<!--▼body▼-->'; html += '<div class="body clearfix">'; html += '<!--▼scroll▼-->'; html += '<div class="scroll inner">'; document.write(html); } //==================== // ページ下部 //==================== function writeBottom(){ var html = ""; html += '</div>'; html += '<!--▲contents▲-->'; html += '<!--▼side▲-->'; html += '<script type="text/javascript">writeSide();</script>'; html += '<!--▲side▲-->'; html += '</div>'; html += '<!--▲scroll▲-->'; html += '</div>'; html += '<!--▲body▲-->'; html += '<!--▼footer▼-->'; html += '<script type="text/javascript">writeFooter();</script>'; html += '<!--▲footer▲-->'; html += '</div>'; html += '<!--▲slide▲-->'; html += '</div>'; document.write(html); } //==================== // header //==================== function writeHeader(){ var html = ""; html += '<header class="slide inner">'; html += '<ul id="navToggle" class="burger slide"><li></li><li></li><li></li></ul><!--メニューボタン-->'; html += '<div class="logoAria">'; html += '<a href="/" class="logo"><img src="/img/logo.png" alt="KEMコーポレーション"></a>'; html += '<p class="top">ケーイーエム株式会社は、BG製品の代理店です</p>'; html += '</div>'; html += '<div class="inqAria">'; html += '<a href="/inquiry/" class="btn_inq"><img src="/img/topInq.png" alt="お問い合わせはこちらから"></a>'; html += '</div>'; html += '</header>'; document.write(html); } //==================== // menu //==================== function writeMenu(){ var html = ""; html += '<nav class="slide inner">'; html += '<ul>'; html += '<li><a href="/" class="active">HOME</a></li>'; html += '<li><a href="/lineup/">製品一覧</a></li>'; html += '<li><a href="/shops/">販売店・整備工場一覧</a></li>'; html += '<li><a href="/aboutbg/">BGとは</a></li>'; html += '<li><a href="/company/">会社概要</a></li>'; html += '<li><a href="/inquiry/">お問い合わせ</a></li>'; html += '<li><a href="/privacy/">プライバシーポリシー</a></li>'; html += '<li><a href="/sitemap.html">サイトマップ</a></li>'; html += '</ul>'; html += '</nav>'; document.write(html); } //==================== // title //==================== function writeTitle(){ document.write(document.title); } //==================== // introduction //==================== function writeIntroduction(){ var html = ""; html += '<div class="introduction">'; html += '<ol id="breadCrumb" class="clearfix">'; html += '<li>If you turn on javascript, this area is drawn to the breadcrumb(navigation).</li>'; html += '</ol>'; html += '<h1><script type="text/javascript">writeTitle();</script></h1>'; html += '</div>'; document.write(html); } //==================== // side //==================== function writeSide(){ var html = ""; html += '<div class="side">'; html += '<a href="/lineup/fuel-d/bg23232.html" class="bun_232"><img src="/img/top/bun_232.png" alt="排ガスを正常な状態に!"></a>'; html += '<a href="/lineup/fuel-g/bg208.html" class="bun_208"><img src="/img/top/bun_208.png" alt="燃料系統の不純物を除去"></a>'; html += '<a href="/digital-book/deasel-care/index_local.html" class="bun_db" target="_blank"><img src="/img/top/bun_db_deaselcare.png" alt="デジタルカタログを見る"></a>'; html += '<a href="https://www.youtube.com/watch?v=XSxcouFaq-8&feature=em-share_video_user" class="kigu" target="_blank"><img src="/img/top/bun_mv_deaelcare.png" alt="器具を使ったディーゼルケアの動画を見る"></a>'; html += '</div>'; document.write(html); } //==================== // footer //==================== function writeFooter(){ var html = ""; html += '<footer class="slide inner">'; html += '<div class="link"><a href="/privacy/">プライバシーポリシー</a> | <a href="/sitemap.html" class="last">サイトマップ</a></div>'; html += '<small>©2016 KEM CORPORATION</small>'; html += '</footer>'; document.write(html); }
import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import Form from 'react-bootstrap/Form'; import FloatingLabel from 'react-bootstrap/FloatingLabel'; import Button from 'react-bootstrap/Button'; import axios from 'axios'; import '../UI/Discover.css'; class CityNameForm extends React.Component { submitHandler = event => { event.preventDefault(); let CN = event.target.CityName.value; this.props.setCityName(CN); this.setState({ name: CN, }); // console.log(this.state.name); //=============================== getting lat , lon from LocationIQ API====================================// axios .get(`${process.env.REACT_APP_URL}/Location?cityName=${CN}`) .then(result => { this.props.getCityName(CN, result.data.lat, result.data.lon); this.props.getAllAPIDataHandler(); }) .catch(err => { console.log(err); }); event.target.reset(); }; render() { return ( <> <section className='bg-discover'> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', }} className='form-discover' > <Form onSubmit={this.submitHandler}> <FloatingLabel controlId='floatingInput' label='Type City Name' className='mb-2' style={{ width: '40rem' }} > <Form.Control type='text' name='CityName' placeholder='City Name' /> </FloatingLabel> <Button className='btn-discover' type='submit' style={{ height: '3rem' }} > Explore ! </Button> </Form> </div> </section> </> ); } } export default CityNameForm;
// @flow import * as React from 'react'; import { getClassNamePrefix } from './prefix'; type Props = { classPrefix: string, componentClass?: React.ElementType }; export default (props: Props): any => { const { classPrefix, ...rest } = props; return WrappedComponent => { class DefaultPropsComponent extends WrappedComponent { // for IE9 & IE10 support static contextTypes = WrappedComponent.contextTypes; static childContextTypes = WrappedComponent.childContextTypes; static getDerivedStateFromProps = WrappedComponent.getDerivedStateFromProps; static defaultProps = { ...WrappedComponent.defaultProps, classPrefix: classPrefix ? `${getClassNamePrefix()}${classPrefix}` : undefined, ...rest }; render() { return super.render(); } } return DefaultPropsComponent; }; };
/** * @file ttf2woff.js * @author mengke01 * @date * @description * ttf2woff 转换 */ define( function(require) { var ajaxFile = require('common/ajaxFile'); var ttf2svg = require('ttf/ttf2svg'); var svg2base64 = require('ttf/svg2base64'); var TTFReader = require('ttf/ttfreader'); var TTF = require('ttf/ttf'); // 设置字体 function setFont(base64str) { var str = '' + '@font-face {' + 'font-family:\'truetype\';' + 'src:url(' + base64str + ') format(\'svg\');' + '}'; document.getElementById('font-face').innerHTML = str; } // 查看ttf glyf function showTTFGlyf(ttfData) { ttf = new TTF(ttfData); var codes = ttf.codes(); var str = ''; // 获取unicode字符 codes.forEach(function(item) { str += '<li data-code="'+ item +'">' + '<span class="i-font">'+ String.fromCharCode(item) +'</span>' + (item > 255 ? '\\u' + Number(item).toString(16) : item) +'</li>'; }); $('#font-list').html(str); } function write() { ajaxFile({ type: 'binary', url: '../font/fonteditor.ttf', onSuccess: function(buffer) { var svgBuffer = ttf2svg(buffer, { metadata: 'fonteditor V0.1' }); var base64str = svg2base64(svgBuffer); setFont(base64str); var saveBtn = $('.saveas'); saveBtn.attr('href', base64str); saveBtn.attr('download', 'save.svg'); var ttfReader = new TTFReader(); var ttfData = ttfReader.read(buffer); showTTFGlyf(ttfData); }, onError: function() { console.error('error read file'); } }); } var entry = { /** * 初始化 */ init: function () { write(); } }; entry.init(); return entry; } );
import low from 'lowdb'; import FileSync from 'lowdb/adapters/FileSync'; // accès au fichier json contenant les données fresco const frescoes = low(new FileSync('database/frescoes.json')); frescoes .defaults({ frescoes: [], }) .write(); const Fresco = frescoes.get('frescoes'); export { Fresco };
const browser = require('./utils/browser.js'); const scroll = require('./utils/scroll.js'); const time = require('./utils/time.js'); const touchscreen = require('./utils/touchscreen.js'); // const visits = require('./utils/visits.js');
/*globals Element:true, NodeList:true*/ $ = (function(document, ua, $) { var element = Element.prototype, nodeList = NodeList.prototype, forEach = 'forEach', trigger = 'trigger', each = [][forEach], dummy = document.createElement('div'), // Firefox requires a valid tag specialEvents = {}; specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'; nodeList[forEach] = each; element.on = function(event, fn) { this.addEventListener(event, fn, false); return this; }; nodeList.on = function(event, fn) { each.call(this, function(el) { el.on(event, fn); }); return this; }; element.trigger = function(type, data) { var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true; event.initEvent(type, true, true); event.data = data || {}; event.eventName = type; event.target = this; this.dispatchEvent(event); return this; }; nodeList.trigger = function(event) { each.call(this, function(el) { el[trigger](event); }); return this; }; $ = function(s) { //console.log('$ for ',s); var r = document.querySelectorAll(s || '☺'), length = r.length; return length == 1 ? r[0] : !length ? [] : r; }; $all = function(s) { var r = document.querySelectorAll(s || '☺'), length = r.length; return !length ? [] : r; } $.on = element.on.bind(dummy); $.trigger = element[trigger].bind(dummy); $.ajax = function(args) { var xhr = new XMLHttpRequest(), type = args.type, url = args.url, success = args.success, opts = {}, error = args.error, fd; //if (typeof opts === 'function') { //callback = opts; //opts = null; //} xhr.open(type, url); if (type === 'POST' && opts) { xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //fd = new FormData(); //for (var key in opts) { //fd.append(key, JSON.stringify(opts[key])); //} } xhr.onload = function() { success(JSON.parse(xhr.response)); }; xhr.onerror = xhr.onabort = xhr.ontimeout = function(e) { error(e); }; //xhr.send(opts ? fd : null); xhr.send(args.data ? args.data : null); }; function detect(ua) { var browser = this.browser = {}, chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), firefox = ua.match(/Firefox\/([\d.]+)/); if (chrome) { browser.chrome = true; browser.version = chrome[1]; } if (firefox) { browser.firefox = true; browser.version = firefox[1]; } } detect.call($, ua); return $; })(document, navigator.userAgent);
////////////////connect to database let mongo = require("mongoose"); mongo.connect("mongodb://localhost/test"); //name of the database --- use test //listen to events const db = mongo.connection; db.on("error", function (e) { console.log(e); }); db.once("open", function () { console.log("connection established"); }); db.once("close", ()=>{ console.log("connection ended") }); //create schema object let Schema = mongo.Schema; let test_schema = new Schema({ name: String, age: Number, sex:{ type:String, default:"male" }, chat: String }); //create model in the specified collection(same as mongos document) let test_model = mongo.model("test", test_schema); //test is the name of the collection in the current database, automatically convert to plural in the system /////////////////////insert document(mongos data) test_model.create({ name: "whoever", age:30, chat: "i dont know lol" }, (err, data)=>{ //if insertion failed, an error returns if(err){ console.log(err); throw err; } else{ console.log("insertion completed", data); } }); //another way is to create a new document object, perform operations on it, and then use save() to submit changes const kim = new test_model({ name: "kim", age:30, chat: "i dont know lol" }); kim.save().then(console.log, console.error); //////////////////////////CURD test_model.create([ {name: "jason", age:20, chat: "happy date"}, {name: "sam", age:34, chat: "to good at goodbye"}, {name: "kelly", age:10, chat: "i am not afraid"}, {name: "smith", age:40, chat: "i am not the only one"} ], (err)=>{ if(!err){ console.log("insertion completed"); } else{ throw err; } }); ///////find //test_model.find({name:"kelly"}) test_model.find({},{name:1, _id:0}, {skip:2, limit:5}, (err, docs)=>{ //the first param is {}, means no filter, search all // the second param represents columns to be displayed, can be written as "name _id", to remove id, add"-id" //the third argument sets the rows to be displayed if(!err){ console.log(docs); } else{ console.log(err); } }); //list all the names ///////update //test_model.update(conditions, doc, options, callback) test_model.update({name: "kim"}, {$set: {age: 54}}, {multi: true}, err=>{ }); ///////delete / remove
import React from 'react'; import { Component } from 'react'; import houseIcon from './found-apt.png'; import PhoneInput from 'react-phone-number-input/basic-input' export default class DetailsForm extends Component { state = { email: "", password1: "", password2: "", phone_number: '', user_logging_in: false, // errors login_error: "", email_error: "", password1_error: "", agent_referral_error: "", password2_error: "", phone_error: "", } componentDidUpdate = (prevProps) => { if(this.props.errors !== prevProps.errors) { this.handleSubmitErrors(this.props.errors); } } handleSubmitErrors = (errors) => { /** * Handles errors returned from the backend * @type {boolean} */ let email_error = ""; let password1_error = ""; let agent_referral_error = ""; let password2_error = ""; let login_error = ""; if (errors.user_form_errors) { // Tests if there was a login error if (errors.user_form_errors.sign_in_failure) { login_error = errors.user_form_errors.sign_in_failure } // Email Errors if (errors.user_form_errors.email) { email_error = errors.user_form_errors.email[0] } // Password errors if (errors.user_form_errors.password1) { password1_error = errors.user_form_errors.password[0]; } else if (errors.user_form_errors.password) { password1_error = errors.user_form_errors.password[0]; } if (!this.state.user_logging_in) { // Agent Referral errors if (errors.user_form_errors.agent_referral) { agent_referral_error = errors.user_form_errors.agent_referral[0]; } // Password errors if (errors.user_form_errors.password2) { password2_error = errors.user_form_errors.password2[0]; } } } this.setState({ email_error, password1_error, agent_referral_error, password2_error, login_error, }) }; handleValidation = () => { if (this.state.user_logging_in) { return this.validateEmail() && this.validatePassword(); } else { return this.validateEmail() && this.validatePhone() && this.validatePassword() && this.validatePasswordMatch(); } }; validateEmail = () => { const re = /\S+@\S+\.\S+/; let email_error = ""; const email = document.querySelector('input[type=email]').value; if (!re.test(email)) { email_error = "You must enter in a valid email"; } this.setState({ email_error }) return re.test(email); } validatePhone = () => { const re = /^(\([0-9]{3}\)\s*|[0-9]{3}\-)[0-9]{3}-[0-9]{4}$/; let phone_error = ""; const phone = document.querySelector('input[type=tel]').value; if (!re.test(phone)) { phone_error = "Enter a valid phone number. ex. (555) 555-5555"; } this.setState({ phone_error }) return re.test(phone); } validatePassword = () => { if (this.state.user_logging_in) { return this.validatePasswordLogin() } else { return this.validatePasswordUserCreation() } } validatePasswordLogin() { const password = document.querySelector('input[name=password1]').value; let password1_error = ""; let valid = true; if (password.length <= 0) { password1_error = "Please enter your password"; valid = false; } this.setState({ password1_error }); return valid; } validatePasswordUserCreation() { const password = document.querySelector('input[name=password1]').value; let password1_error = ""; let valid = true; const numberMatch = /[0-9]/; if (password.length < 8) { password1_error = "Password must be at least 8 characters."; valid = false; } else if (!numberMatch.test(password)) { password1_error = "The password must contain at least 1 number"; valid = false; } this.setState({ password1_error }) return valid; } validatePasswordMatch = () => { const password = document.querySelector('input[name=password1]').value; const confirmPassword = document.querySelector('input[name=password2]').value; let password2_error = ""; let valid = true; if (password !== confirmPassword) { password2_error = "Passwords must match"; valid = false; } this.setState({ password2_error }); return valid; } handleInputChange = (e, type) => { const { name, value } = e.target; if(type === 'number') { this.setState({ [name]: parseInt(value) }); } else { this.setState({ [name]: value }); } } setUserLoggingIn = () => { this.setState({ user_logging_in: true, email: "", email_error: "", password1: "", password2: "", }) } setUserCreation = () => { this.setState({ user_logging_in: false, email_error: "", email: "", password1: "", password2: "", }) } handleSubmit = (e) => { /** * Does a validation check before attempting to send form to backend * If the page is already loading, i.e the button is clicked then the button is * disabled to prevent pressing multiple times */ if (!this.props.loading) { if (!this.props.is_authenticated) { if (!this.handleValidation()) { return false; } } this.props.onSubmit(e, this.state) } } handleUpdatePhoneNumber = (phone_number) => { /** * Updates the phone_number in the state */ this.setState({ phone_number }) } render() { if (!this.props.is_authenticated) { if (this.state.user_logging_in) { return ( <LoginUser login_error={this.state.login_error} email_error={this.state.email_error} password1_error={this.state.password1_error} errors={this.state.user_form_errors} onSubmit={this.props.onSubmit} onUserCreation={this.setUserCreation} validateEmail={this.validateEmail} validatePassword={this.validatePassword} handleInputChange={this.handleInputChange} handlePrevStep={this.props.handlePrevStep} handleSubmit={this.handleSubmit} loading={this.props.loading} /> ); } else { return ( <NewUser email_error={this.state.email_error} password1_error={this.state.password1_error} agent_referral_error={this.state.agent_referral_error} password2_error={this.state.password2_error} phone_error={this.state.phone_error} onSubmit={this.props.onSubmit} onUserLoggingIn={this.setUserLoggingIn} validateEmail={this.validateEmail} validatePhone={this.validatePhone} handleInputChange={this.handleInputChange} validatePassword={this.validatePassword} validatePasswordMatch={this.validatePasswordMatch} handlePrevStep={this.props.handlePrevStep} handleSubmit={this.handleSubmit} loading={this.props.loading} phone_number={this.state.phone_number} onUpdatePhoneNumber={this.handleUpdatePhoneNumber} /> ); } } else { return ( <CurrentUser onSubmit={this.props.onSubmit} handlePrevStep={this.props.handlePrevStep} handleSubmit={this.handleSubmit} loading={this.props.loading} /> ); } } } const LoginUser = (props) => ( <> <div className="survey-question"> <h2>Login to see <span>your results</span>! <small>(or click <a className="login-toggle" onClick={props.onUserCreation}>here</a> to sign up)</small></h2> <p className="col-md-12 survey-error-message"> {props.login_error ? props.login_error : null} </p> <span className="col-md-12 survey-error-message"> {props.email_error ? props.email_error : null} </span> <input className="col-md-12 survey-input" type="email" name="email" placeholder="Email address" maxLength={30} onBlur={(e) => {props.validateEmail(e) && props.handleInputChange(e, 'string')} } required/> <span className="col-md-12 survey-error-message"> {props.password1_error ? props.password1_error : null} </span> <input className="col-md-12 survey-input" type="password" name="password1" placeholder="Password" required onChange={props.validatePassword} onBlur={(e) => {props.validatePassword && props.handleInputChange(e, 'string')} } /> </div> <div className="row survey-btn-wrapper"> <div className="col-sm-6 col-xs-12"> <button className="col-sm-12 survey-btn survey-btn_back" style={{marginTop: '30px'}} onClick={(e) => {props.handlePrevStep(e)}}> Back </button> </div> <div className="col-sm-6 col-xs-12"> <button className="col-sm-12 survey-btn" onClick={(e) => { props.handleSubmit(e); }}> {props.loading ? 'Loading' : 'View'} </button> </div> </div> </> ) const NewUser = (props) => ( <> <div className="survey-question"> <h2>Finish signing up to see <span>your results</span>! <small>(or click <a className="login-toggle" onClick={props.onUserLoggingIn}>here</a> to login)</small></h2> <span className="col-md-12 survey-error-message"> {props.email_error ? props.email_error : null} </span> <input className="col-md-12 survey-input" type="email" name="email" placeholder="Email address" maxLength={30} onBlur={(e) => {props.validateEmail(e) && props.handleInputChange(e, 'string')} } required/> <span className="col-md-12 survey-error-message"> {props.phone_error ? props.phone_error : null} </span> <PhoneInput country="US" className="col-md-12 survey-input" placeholder="Enter phone number" value={props.phone_number } onChange={ phone => props.onUpdatePhoneNumber(phone) } /> <span className="col-md-12 survey-error-message"> {props.agent_referral_error ? props.agent_referral_error : null} </span> <input className="col-md-12 survey-input" type="text" name="agent_referral" placeholder="Agent Referral - Optional" onBlur={(e) => {props.handleInputChange(e, 'string')} } /> <span className="col-md-12 survey-error-message"> {props.password1_error ? props.password1_error : null} </span> <input className="col-md-12 survey-input" type="password" name="password1" placeholder="Password" required onChange={props.validatePassword} onBlur={(e) => {props.validatePassword && props.handleInputChange(e, 'string')} } /> <span className="col-md-12 survey-error-message"> {props.password2_error ? props.password2_error : null} </span> <input className="col-md-12 survey-input" type="password" name="password2" placeholder="Confirm Your Password" required onChange={props.validatePasswordMatch} onBlur={(e) => {props.validatePasswordMatch && props.handleInputChange(e, 'string')} } /> </div> <div className="row survey-btn-wrapper"> <div className="col-sm-6 col-xs-12"> <button className="col-sm-12 survey-btn survey-btn_back" style={{marginTop: '30px'}} onClick={(e) => {props.handlePrevStep(e)}}> Back </button> </div> <div className="col-sm-6 col-xs-12"> <button className="col-sm-12 survey-btn" onClick={(e) => { props.handleSubmit(e); }}> {props.loading ? 'Loading' : 'View'} </button> </div> </div> </> ); const CurrentUser = (props) => ( <div className="form-details-box"> <h2><span>Awesome!</span> Check your best places out now.</h2> <img src={houseIcon} alt="Icon of a house"/> <div className="row survey-btn-wrapper"> <div className="col-xs-6"> <button className="col-sm-12 survey-btn survey-btn_back" style={{marginTop: '30px'}} onClick={(e) => { props.handlePrevStep(e)}}> Back </button> </div> <div className="col-xs-6"> <button className="col-sm-12 survey-btn" onClick={(e) => { props.handleSubmit(e); }}> {props.loading ? 'Loading' : 'View'} </button> </div> </div> </div> )
import * as actionTypes from '../constants/actionTypes'; export default function(state = {}, action) { const { signedAttributes } = action; switch (action.type) { case actionTypes.UPDATE_SIGNED_ATTRIBUTES: return { ...signedAttributes }; case actionTypes.CLEAR_SIGNED_ATTRIBUTES: return {}; default: return state; } }
import { FaTimes } from "react-icons/fa"; import "../styles/css/Task.css"; const Task = ({ task, onDelete, onToggle }) => { const { id, text, date, reminder } = task; return ( <div className={`task ${reminder ? "reminder" : ""}`} onDoubleClick={() => onToggle(id)} > <h3> {text}{" "} <FaTimes style={{ color: "red", cursor: "pointer" }} onClick={() => onDelete(task.id)} /> </h3> <p>{date}</p> </div> ); }; export default Task;
import { date, lng, lat, coords, locationName, location, locationShortName, days } from '../state'; export const useDate = date.hook(); export const useLng = lng.hook(); export const useLat = lat.hook(); export const useCoords = coords.hook(); export const useLocationName = locationName.hook(); export const useLocation = location.hook(); export const useLocationShortName = locationShortName.hook(); export const useDays = days.hook();
var searchData= [ ['testnetflix_2ec_2b_2b',['TestNetflix.c++',['../TestNetflix_8c_09_09.html',1,'']]] ];
import React, { Component } from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import { connect } from 'react-redux' import { SideTab, Tab, Nav } from '../common' import LessonList from './LessonList' import Content from './Content' import LessonActions from '../../redux/lessonStore' const Wrappper = styled.div` display: flex; flex: 1; background-color: #272727; overflow: hidden; ` const Icon = styled.img` width: 26px; height: 26px; ` const Container = styled.div` display: flex; flex: 1; flex-direction: column; width: 100%; padding: 0px 9px; ` class Lesson extends Component { componentDidMount() { const { dispatch, currentLesson, lessons } = this.props dispatch(LessonActions.getLessonGroup()) dispatch(LessonActions.getLesson()) dispatch(LessonActions.getLessonLearning()) if (currentLesson === undefined) { dispatch(LessonActions.learnLesson(lessons[0].id)) } } render() { return ( <Wrappper> <SideTab> <Tab onClick={e => { e.preventDefault() this.props.dispatch(LessonActions.toggleLessonList()) }} > <Icon src={require('../../assets/images/book.png')} /> </Tab> <Tab> <Icon src={require('../../assets/images/trophy.png')} /> </Tab> </SideTab> <Container> <LessonList /> <Nav title="Lesson" /> <Content /> </Container> </Wrappper> ) } } Lesson.propTypes = { dispatch: PropTypes.func, lessons: PropTypes.array, currentLesson: PropTypes.number, } const mapStateToProps = state => ({ lessons: state.lessonStore.lessons, currentLesson: state.lessonStore.currentLesson, }) export default connect(mapStateToProps)(Lesson)
const express = require('express'); const path = require('path'); const app = express(); const server = require('http').Server(app); const io = require('socket.io')(server); const PORT = 8080; const dataStore = { tickets: [ { id: 1, subject: 'Passwort vergessen', status: 'registered' }, { id: 2, subject: 'Internet gelöscht - bin am Ende angekommen', status: 'registered' }, { id: 3, subject: 'Geht nicht', status: 'registered' } ] }; app.use(express.static(path.join(__dirname, 'public'))); io.on('connection', (socket) => { console.log('Neue Connection eingetroffen'); // anfragen aller Tickets - als Liste socket.on('getTicketList', (filter_data) => { console.log('Anfrage nach allen Tickets'); socket.emit('getTicketList_resp', dataStore.tickets); }); socket.on('setTicketStatus', (ticket_data) => { console.log('Ticket Data Changed ', ticket_data); io.emit('TicketStatusChanged', ticket_data); }); socket.on('disconnect', () => { console.log('Disconnected'); }); }); server.listen(PORT, () => { console.log('Listen on Port ' + PORT); });
// Your code goes here let userName = prompt('Enter user login', ''); let currentTime = new Date().getHours(); if (!userName) { alert('Canceled.'); } else if (userName.length < 4) { alert('I don\'t know any users having name length less than 4 symbols'); } else if (userName !== 'User') { alert("I don't know you"); } else { let pass = prompt('Password', ''); if (!pass) { alert('Canceled.'); } else if (pass !== 'SuperUser') { alert('Wrong password'); } else { if (currentTime < 20) { alert('Good day!') } else { alert('Good evening!'); } } }
'use strict'; let mongoose = require('mongoose'); let schema = new mongoose.Schema({ key: String, email: String }); module.exports = mongoose.model('Key', schema);
export const mockCard = { id: 1, class: "Brute", name: "Sweeping Blow", initiative: 64, top_action: "Attack 2 ● Attack Pattern: 3 connected adjacent hexes, enhanceable to 4", bottom_action: "Move 3 Push 1 ● ^(Target all adjacent enemies)", image_url: "./images/cards/Brute3.png", card_level: 1, created_at: "2018-06-01T22:34:26.644Z", updated_at: "2018-06-01T22:34:26.644Z" }; export const mockCards = [ { id: 1, class: "Brute", name: "Sweeping Blow", initiative: 64, top_action: "Attack 2 ● Attack Pattern: 3 connected adjacent hexes, enhanceable to 4", bottom_action: "Move 3 Push 1 ● ^(Target all adjacent enemies)", image_url: "./images/cards/Brute3.png", card_level: 1, created_at: "2018-06-01T22:34:26.644Z", updated_at: "2018-06-01T22:34:26.644Z" }, { class: "Brute", name: "Trample", initiative: 72, top_action: "Attack 3 ● ^(Pierce 2 ●)", bottom_action: "Move 4 ● ^Jump Attack 2 ● ● ^(Target all enemies moved through) 2 XP, LOSS", image_url: './images/cards/Brute1.png', card_level: 1 } ]; export const mockSelectedCards = [ { class: "Brute", name: "Shield Bash", initiative: 15, top_action: "Attack 4 ● ● ^Stun 2 XP, Loss", bottom_action: "Shield 1 ● ● Self Round Bonus", image_url: './images/cards/Brute8.png', card_level: 1 }, { class: "Brute", name: "Grab and Go", initiative: 87, top_action: "Loot 1", bottom_action: "Move 4 ●", image_url: './images/cards/Brute6.png', card_level: 1 } ]; export const mockAvailableCards = [ { class: "Brute", name: "Sweeping Blow", initiative: 64, top_action: "Attack 2 ● Attack Pattern: 3 connected adjacent hexes, enhanceable to 4", bottom_action: "Move 3 Push 1 ● ^(Target all adjacent enemies)", image_url: './images/cards/Brute3.png', card_level: 1 }, { class: "Brute", name: "Trample", initiative: 72, top_action: "Attack 3 ● ^(Pierce 2 ●)", bottom_action: "Move 4 ● ^Jump Attack 2 ● ● ^(Target all enemies moved through) 2 XP, LOSS", image_url: './images/cards/Brute1.png', card_level: 1 }, { class: "Brute", name: "Provoking Roar ", initiative: 10, top_action: "Attack 2 ● ^Disarm ", bottom_action: "Any enemy who targets one of your adjacent allies with an attack this round targets you with that attack instead, regardless of the attack's range. Round Bonus", image_url: './images/cards/Brute4.png', card_level: 1 }, { class: "Brute", name: "Eye for an Eye", initiative: 18, top_action: "Retaliate 2 ● ^Self ^(Gain 1 XP each time you retaliate this round.) Round Bonus ", bottom_action: "Heal 2 ● ● ^(Range 1) Generate Earth", image_url: './images/cards/Brute2.png', card_level: 1 }, { class: "Brute", name: "Warding Strength ", initiative: 32, top_action: "Attack 3 ● ^(Push 2 ●) ", bottom_action: "On the next six sources of damage from attacks targeting you, gain Shield 1. 6 Charges, gain 1 XP on 2nd, 4th, and 6th charge. LOSS", image_url: './images/cards/Brute7.png', card_level: 1 }, { class: "Brute", name: "Overwhelming Assault", initiative: 61, top_action: "Attack 6 ● ● 2 XP, LOSS", bottom_action: "Move 3 Push 2 ● ^(Target one adjacent enemy)", image_url: './images/cards/Brute5.png', card_level: 1 }, { class: "Brute", name: "Spare Dagger", initiative: 27, top_action: "Attack 3 ● ^(Range 3) 1 XP", bottom_action: "Attack 2", image_url: './images/cards/Brute10.png', card_level: 1 }, { class: "Brute", name: "Leaping Cleave", initiative: 54, top_action: "Attack 3 ● Attack Pattern: 3 consecutive adjacent hexes 1XP ", bottom_action: "Move 3 ● ^Jump Generate Air", image_url: './images/cards/Brute9.png', card_level: 1 }, { class: "Brute", name: "Skewer", initiative: 35, top_action: "Attack 3 ● Use Air: +1 Attack, Pierce 1 Attack Pattern: Two hexes in a line from your position. Enhanceable to add a 3rd hex. 1 XP", bottom_action: "Move 6 ● ● 1 XP, LOSS", image_url: './images/cards/Brute11.png', card_level: 0 }, { class: "Brute", name: "Wall of Doom", initiative: 20, top_action: "Retaliate 2 ● ^Self Shield 2 ● ^Self 2 XP, Round Bonus, LOSS", bottom_action: "Add +1 Attack to all your attacks this round. Round Bonus", image_url: './images/cards/Brute13.png', card_level: 0 }, { class: "Brute", name: "Balanced Measure", initiative: 77, top_action: "Attack X ^(where X is the number of hexes you have moved so far this turn) 1XP", bottom_action: "Move X ^(where X is the amount of damage you have inflicted so far this turn.)", image_url: './images/cards/Brute12.png', card_level: 0 }, { class: "Brute", name: "Juggernaut", initiative: 34, top_action: "Move 2 ● Attack 2 ●", bottom_action: "On the next three sources of damage to you, suffer no damage instead. 3 Charges, 1 XP on each charge LOSS", image_url: './images/cards/Brute3.png', card_level: 2 }, { class: "Brute", name: "Fatal Advance", initiative: 40, top_action: "Kill one adjacent normal enemy 2 XP, LOSS ", bottom_action: "Move 4 ●", image_url: './images/cards/Brute14.png', card_level: 2 }, { class: "Brute", name: "Hook and Chain", initiative: 42, top_action: "Attack 3 ● ● ^(Range 3) ^(Pull 2)", bottom_action: "Move 4 ^(If the movement was in a straight line, perform) Attack X ^(where X is the number of hexes you moved with this action).", image_url: './images/cards/Brute16.png', card_level: 3 }, { class: "Brute", name: "Brute Force", initiative: 51, top_action: "Attack 2 ● ^Muddle Attack Pattern: 3 consecutive adjacent hexes. Enhanceable to add a 4th and 5th hex. 1 XP ", bottom_action: "Move 2 Shield 1 ● ^Self Round Bonus", image_url: './images/cards/Brute17.png', card_level: 3 }, { class: "Brute", name: "Unstoppable Charge", initiative: 86, top_action: "Attack 5 ● 1 XP", bottom_action: "Move 4 ● Stun ^(Target all adjacent enemies) LOSS", image_url: './images/cards/Brute18.png', card_level: 4 }, { class: "Brute", name: "Devastating Hack", initiative: 27, top_action: "Attack 8 ● ● 3 XP, LOSS", bottom_action: "Loot 1", image_url: './images/cards/Brute19.png', card_level: 4 }, { class: "Brute", name: "Skirmishing Maneuver", initiative: 29, top_action: "Attack 2 Move 2 ● Attack 2", bottom_action: "Attack 3 ● ^(Range 3) 1 XP", image_url: './images/cards/Brute21.png', card_level: 5 }, { class: "Brute", name: "Whirlwind", initiative: 28, top_action: "Attack 4 ● ^(Target all adjacent enemies. Gain 1 XP for each enemy targeted). LOSS", bottom_action: "Move 4 ● Push 3 ● ^(Target one adjacent enemy)", image_url: './images/cards/Brute20.png', card_level: 5 }, { class: "Brute", name: "Immovable Phalanx", initiative: 17, top_action: "Attack 4 ● Shield 1 ● ^(Self) Round Bonus", bottom_action: "You may treat all Move abilities as Attack abilities of equal value. Round Bonus LOSS", image_url: './images/cards/Brute23.png', card_level: 6 }, { class: "Brute", name: "Quietus", initiative: 57, top_action: "Kill one adjacent normal enemy with STUN 1XP", bottom_action: "Move 3 ● Add +1 Attack to all your attacks this round. Round Bonus", image_url: './images/cards/Brute22.png', card_level: 6 }, { class: "Brute", name: "Crippling Offensive", initiative: 33, top_action: "Attack 6 ● ● ^Wound ^Stun 3 XP, LOSS", bottom_action: "Move 3 ● Immobilize and Push 1 ^(Target one adjacent enemy)", image_url: './images/cards/Brute25.png', card_level: 7 }, { class: "Brute", name: "Defensive Tactics", initiative: 26, top_action: "Attack 2 ● ^(Range 3) ^(Target 2 ●) ^Immobilize 1XP", bottom_action: "Retaliate 1 ^Self Shield 1 ^Self 2 XP, Round Bonus LOSS", image_url: './images/cards/Brute24.png', card_level: 7 }, { class: "Brute", name: "Frenzied Onslaught", initiative: 41, top_action: "Move 2 Attack 2 ● Move 2 Attack 2 ●", bottom_action: "Add +3 Attack to all your attacks targeting enemies with Disarm, Immobilize, or Stun this round. 1XP, Round Bonus", image_url: './images/cards/Brute26.png', card_level: 8 }, { class: "Brute", name: "Selfish Retribution", initiative: 12, top_action: "Move 1 ● Loot 2 LOSS", bottom_action: "Move 3 ● Retaliate 2 ● ^Self 1XP, Round Bonus", image_url: './images/cards/Brute27.png', card_level: 8 }, { class: "Brute", name: "Face Your End", initiative: 67, top_action: "Attack 2 ● ^(Range 4) ^(Target 3 ●) ^(Pull 3) 1XP", bottom_action: "Kill one adjacent normal or elite enemy 2XP LOSS", image_url: './images/cards/Brute29.png', card_level: 9 }, { class: "Brute", name: "King of the Hill", initiative: 39, top_action: "Attack 6 ● ● ^(Target all adjacent enemies) ^(Push 1) ^(Gain 1XP for each enemy targeted) LOSS", bottom_action: "Heal 5 ● ^Self", image_url: './images/cards/Brute28.png', card_level: 9 } ]; export const cardToDelete = { class: "Brute", name: "Trample", initiative: 72, top_action: "Attack 3 ● ^(Pierce 2 ●)", bottom_action: "Move 4 ● ^Jump Attack 2 ● ● ^(Target all enemies moved through) 2 XP, LOSS", image_url: './images/cards/Brute1.png', card_level: 1 }; export const mockDeck = [ { class: "Brute", name: "Sweeping Blow", initiative: 64, top_action: "Attack 2 ● Attack Pattern: 3 connected adjacent hexes, enhanceable to 4", bottom_action: "Move 3 Push 1 ● ^(Target all adjacent enemies)", image_url: './images/cards/Brute3.png', card_level: 1 }, { class: "Brute", name: "Trample", initiative: 72, top_action: "Attack 3 ● ^(Pierce 2 ●)", bottom_action: "Move 4 ● ^Jump Attack 2 ● ● ^(Target all enemies moved through) 2 XP, LOSS", image_url: './images/cards/Brute1.png', card_level: 1 }, { class: "Brute", name: "Provoking Roar ", initiative: 10, top_action: "Attack 2 ● ^Disarm ", bottom_action: "Any enemy who targets one of your adjacent allies with an attack this round targets you with that attack instead, regardless of the attack's range. Round Bonus", image_url: './images/cards/Brute4.png', card_level: 1 }, { class: "Brute", name: "Shield Bash", initiative: 15, top_action: "Attack 4 ● ● ^Stun 2 XP, Loss", bottom_action: "Shield 1 ● ● Self Round Bonus", image_url: './images/cards/Brute8.png', card_level: 1 }, { class: "Brute", name: "Grab and Go", initiative: 87, top_action: "Loot 1", bottom_action: "Move 4 ●", image_url: './images/cards/Brute6.png', card_level: 1 }, { class: "Brute", name: "Eye for an Eye", initiative: 18, top_action: "Retaliate 2 ● ^Self ^(Gain 1 XP each time you retaliate this round.) Round Bonus ", bottom_action: "Heal 2 ● ● ^(Range 1) Generate Earth", image_url: './images/cards/Brute2.png', card_level: 1 }, { class: "Brute", name: "Warding Strength ", initiative: 32, top_action: "Attack 3 ● ^(Push 2 ●) ", bottom_action: "On the next six sources of damage from attacks targeting you, gain Shield 1. 6 Charges, gain 1 XP on 2nd, 4th, and 6th charge. LOSS", image_url: './images/cards/Brute7.png', card_level: 1 }, { class: "Brute", name: "Overwhelming Assault", initiative: 61, top_action: "Attack 6 ● ● 2 XP, LOSS", bottom_action: "Move 3 Push 2 ● ^(Target one adjacent enemy)", image_url: './images/cards/Brute5.png', card_level: 1 }, { class: "Brute", name: "Spare Dagger", initiative: 27, top_action: "Attack 3 ● ^(Range 3) 1 XP", bottom_action: "Attack 2", image_url: './images/cards/Brute10.png', card_level: 1 }, { class: "Brute", name: "Leaping Cleave", initiative: 54, top_action: "Attack 3 ● Attack Pattern: 3 consecutive adjacent hexes 1XP ", bottom_action: "Move 3 ● ^Jump Generate Air", image_url: './images/cards/Brute9.png', card_level: 1 }, { class: "Brute", name: "Skewer", initiative: 35, top_action: "Attack 3 ● Use Air: +1 Attack, Pierce 1 Attack Pattern: Two hexes in a line from your position. Enhanceable to add a 3rd hex. 1 XP", bottom_action: "Move 6 ● ● 1 XP, LOSS", image_url: './images/cards/Brute11.png', card_level: 0 } ]; export const mockMultiDecks = [ {deckId: 1, deckName: 'Hello', class: 'Brute', cards: [1, 2, 3, 4, 5, 6, 7, 8]}, {deckId: 12, deckName: 'Friend', class: 'Cragheart', cards: [10, 2, 3, 12, 5, 6, 7, 8]} ]; export const allBruteCards = [ { class: "Brute", name: "Sweeping Blow", initiative: 64, top_action: "Attack 2 ● Attack Pattern: 3 connected adjacent hexes, enhanceable to 4", bottom_action: "Move 3 Push 1 ● ^(Target all adjacent enemies)", image_url: './images/cards/Brute3.png', card_level: 1 }, { class: "Brute", name: "Trample", initiative: 72, top_action: "Attack 3 ● ^(Pierce 2 ●)", bottom_action: "Move 4 ● ^Jump Attack 2 ● ● ^(Target all enemies moved through) 2 XP, LOSS", image_url: './images/cards/Brute1.png', card_level: 1 }, { class: "Brute", name: "Provoking Roar ", initiative: 10, top_action: "Attack 2 ● ^Disarm ", bottom_action: "Any enemy who targets one of your adjacent allies with an attack this round targets you with that attack instead, regardless of the attack's range. Round Bonus", image_url: './images/cards/Brute4.png', card_level: 1 }, { class: "Brute", name: "Shield Bash", initiative: 15, top_action: "Attack 4 ● ● ^Stun 2 XP, Loss", bottom_action: "Shield 1 ● ● Self Round Bonus", image_url: './images/cards/Brute8.png', card_level: 1 }, { class: "Brute", name: "Grab and Go", initiative: 87, top_action: "Loot 1", bottom_action: "Move 4 ●", image_url: './images/cards/Brute6.png', card_level: 1 }, { class: "Brute", name: "Eye for an Eye", initiative: 18, top_action: "Retaliate 2 ● ^Self ^(Gain 1 XP each time you retaliate this round.) Round Bonus ", bottom_action: "Heal 2 ● ● ^(Range 1) Generate Earth", image_url: './images/cards/Brute2.png', card_level: 1 }, { class: "Brute", name: "Warding Strength ", initiative: 32, top_action: "Attack 3 ● ^(Push 2 ●) ", bottom_action: "On the next six sources of damage from attacks targeting you, gain Shield 1. 6 Charges, gain 1 XP on 2nd, 4th, and 6th charge. LOSS", image_url: './images/cards/Brute7.png', card_level: 1 }, { class: "Brute", name: "Overwhelming Assault", initiative: 61, top_action: "Attack 6 ● ● 2 XP, LOSS", bottom_action: "Move 3 Push 2 ● ^(Target one adjacent enemy)", image_url: './images/cards/Brute5.png', card_level: 1 }, { class: "Brute", name: "Spare Dagger", initiative: 27, top_action: "Attack 3 ● ^(Range 3) 1 XP", bottom_action: "Attack 2", image_url: './images/cards/Brute10.png', card_level: 1 }, { class: "Brute", name: "Leaping Cleave", initiative: 54, top_action: "Attack 3 ● Attack Pattern: 3 consecutive adjacent hexes 1XP ", bottom_action: "Move 3 ● ^Jump Generate Air", image_url: './images/cards/Brute9.png', card_level: 1 }, { class: "Brute", name: "Skewer", initiative: 35, top_action: "Attack 3 ● Use Air: +1 Attack, Pierce 1 Attack Pattern: Two hexes in a line from your position. Enhanceable to add a 3rd hex. 1 XP", bottom_action: "Move 6 ● ● 1 XP, LOSS", image_url: './images/cards/Brute11.png', card_level: 0 }, { class: "Brute", name: "Wall of Doom", initiative: 20, top_action: "Retaliate 2 ● ^Self Shield 2 ● ^Self 2 XP, Round Bonus, LOSS", bottom_action: "Add +1 Attack to all your attacks this round. Round Bonus", image_url: './images/cards/Brute13.png', card_level: 0 }, { class: "Brute", name: "Balanced Measure", initiative: 77, top_action: "Attack X ^(where X is the number of hexes you have moved so far this turn) 1XP", bottom_action: "Move X ^(where X is the amount of damage you have inflicted so far this turn.)", image_url: './images/cards/Brute12.png', card_level: 0 }, { class: "Brute", name: "Juggernaut", initiative: 34, top_action: "Move 2 ● Attack 2 ●", bottom_action: "On the next three sources of damage to you, suffer no damage instead. 3 Charges, 1 XP on each charge LOSS", image_url: './images/cards/Brute3.png', card_level: 2 }, { class: "Brute", name: "Fatal Advance", initiative: 40, top_action: "Kill one adjacent normal enemy 2 XP, LOSS ", bottom_action: "Move 4 ●", image_url: './images/cards/Brute14.png', card_level: 2 }, { class: "Brute", name: "Hook and Chain", initiative: 42, top_action: "Attack 3 ● ● ^(Range 3) ^(Pull 2)", bottom_action: "Move 4 ^(If the movement was in a straight line, perform) Attack X ^(where X is the number of hexes you moved with this action).", image_url: './images/cards/Brute16.png', card_level: 3 }, { class: "Brute", name: "Brute Force", initiative: 51, top_action: "Attack 2 ● ^Muddle Attack Pattern: 3 consecutive adjacent hexes. Enhanceable to add a 4th and 5th hex. 1 XP ", bottom_action: "Move 2 Shield 1 ● ^Self Round Bonus", image_url: './images/cards/Brute17.png', card_level: 3 }, { class: "Brute", name: "Unstoppable Charge", initiative: 86, top_action: "Attack 5 ● 1 XP", bottom_action: "Move 4 ● Stun ^(Target all adjacent enemies) LOSS", image_url: './images/cards/Brute18.png', card_level: 4 }, { class: "Brute", name: "Devastating Hack", initiative: 27, top_action: "Attack 8 ● ● 3 XP, LOSS", bottom_action: "Loot 1", image_url: './images/cards/Brute19.png', card_level: 4 }, { class: "Brute", name: "Skirmishing Maneuver", initiative: 29, top_action: "Attack 2 Move 2 ● Attack 2", bottom_action: "Attack 3 ● ^(Range 3) 1 XP", image_url: './images/cards/Brute21.png', card_level: 5 }, { class: "Brute", name: "Whirlwind", initiative: 28, top_action: "Attack 4 ● ^(Target all adjacent enemies. Gain 1 XP for each enemy targeted). LOSS", bottom_action: "Move 4 ● Push 3 ● ^(Target one adjacent enemy)", image_url: './images/cards/Brute20.png', card_level: 5 }, { class: "Brute", name: "Immovable Phalanx", initiative: 17, top_action: "Attack 4 ● Shield 1 ● ^(Self) Round Bonus", bottom_action: "You may treat all Move abilities as Attack abilities of equal value. Round Bonus LOSS", image_url: './images/cards/Brute23.png', card_level: 6 }, { class: "Brute", name: "Quietus", initiative: 57, top_action: "Kill one adjacent normal enemy with STUN 1XP", bottom_action: "Move 3 ● Add +1 Attack to all your attacks this round. Round Bonus", image_url: './images/cards/Brute22.png', card_level: 6 }, { class: "Brute", name: "Crippling Offensive", initiative: 33, top_action: "Attack 6 ● ● ^Wound ^Stun 3 XP, LOSS", bottom_action: "Move 3 ● Immobilize and Push 1 ^(Target one adjacent enemy)", image_url: './images/cards/Brute25.png', card_level: 7 }, { class: "Brute", name: "Defensive Tactics", initiative: 26, top_action: "Attack 2 ● ^(Range 3) ^(Target 2 ●) ^Immobilize 1XP", bottom_action: "Retaliate 1 ^Self Shield 1 ^Self 2 XP, Round Bonus LOSS", image_url: './images/cards/Brute24.png', card_level: 7 }, { class: "Brute", name: "Frenzied Onslaught", initiative: 41, top_action: "Move 2 Attack 2 ● Move 2 Attack 2 ●", bottom_action: "Add +3 Attack to all your attacks targeting enemies with Disarm, Immobilize, or Stun this round. 1XP, Round Bonus", image_url: './images/cards/Brute26.png', card_level: 8 }, { class: "Brute", name: "Selfish Retribution", initiative: 12, top_action: "Move 1 ● Loot 2 LOSS", bottom_action: "Move 3 ● Retaliate 2 ● ^Self 1XP, Round Bonus", image_url: './images/cards/Brute27.png', card_level: 8 }, { class: "Brute", name: "Face Your End", initiative: 67, top_action: "Attack 2 ● ^(Range 4) ^(Target 3 ●) ^(Pull 3) 1XP", bottom_action: "Kill one adjacent normal or elite enemy 2XP LOSS", image_url: './images/cards/Brute29.png', card_level: 9 }, { class: "Brute", name: "King of the Hill", initiative: 39, top_action: "Attack 6 ● ● ^(Target all adjacent enemies) ^(Push 1) ^(Gain 1XP for each enemy targeted) LOSS", bottom_action: "Heal 5 ● ^Self", image_url: './images/cards/Brute28.png', card_level: 9 } ];
(function () { 'use strict'; angular .module('taximk') .controller('Main', Main); function Main(version) { var vm = this; vm.version = version; } })();
Ext.define('JSONExtJS.view.base.Controller', { extend: 'Ext.app.ViewController', toggleWidget: function (type) { view = this.getView(); var activeWidget = view.child(type); if (!activeWidget) { activeWidget = this.createAndAddWidget(type, view); } view.setActiveItem(activeWidget) }, createAndAddWidget: function (type, view) { var createdWidget = Ext.widget(type); view.add(createdWidget); return createdWidget; } });
$(document).ready(() => { var commonWords = [ "the", "of", "and", "a", "to", "in", "is", "you", "that", "it", "he", "was", "for", "on", "are", "as", "with", "his", "they", "I", "at", "be", "this", "have", "from", "or", "one", "had", "by", "word", "but", "not", "what", "all", "were", "we", "when", "your", "can", "said", "there", "use", "an", "each", "which", "she", "do", "how", "their", "if", "will", "up", "other", "about", "out", "many", "then", "them", "these", "so", "some", "her", "would", "make", "like", "him", "into", "time", "has", "look", "two", "more", "write", "go", "see", "number", "no", "way", "could", "people", "my", "than", "first", "water", "been", "call", "who", "oil", "its", "now", "find", "long", "down", "day", "did", "get", "come", "made", "may", "part" ]; let filteredWord = commonWords.filter(word => { return word.length >= 3; }); let randomWord = filteredWord[ Math.floor(Math.random() * filteredWord.length) ].toUpperCase(); console.log(randomWord); var randomWordArray = randomWord.split(""); for (var i = 0; i < randomWord.length; i++) { $("#container").append('<div class="letter ' + i + '"></div></div>'); $("#container") .find(":nth-child(" + (i + 1) + ")") .text(randomWordArray[i]); $(".letter").css("color", "black"); $(".letter").css("border-radius", "25px"); } //This is the lives left to the player let remaining = 7; $("#livesRemaining").html(remaining); var wrongGuesses = 1; $("button").on("click", function() { $(this).addClass("used"); $(this).prop("disabled", "true"); var matchFound = false; // Check if clicked letter is in secret word var userGuess = $(this).text(); for (var i = 0; i < randomWord.length; i++) { if (userGuess === randomWord.charAt(i)) { $("#container") .find(":nth-child(" + (i + 1) + ")") .css("color", "white") .addClass("winner"); matchFound = true; } } //Check for winner var goodGuesses = []; $(".letter").each(function(index) { if ($(this).hasClass("winner")) { goodGuesses.push(index); if (goodGuesses.length === randomWordArray.length) { $("#container").hide(); $("button").prop("disabled", "true"); $(".category").text("Great job you guessed the secret word!"); $(".category").append( "<br><button enabled class='play-again'>Play again?</button>" ); } } }); // If no match, increase count and add appropriate image if (matchFound === false) { $("#hangman").attr("src", "hangman/" + wrongGuesses + ".png"); wrongGuesses++; remaining--; $("#livesRemaining").html(remaining); } // If wrong guesses gets to 7 exit the game if (remaining === 0) { $("#container").hide(); $("button").prop("disabled", "true"); $(".category").text( "Sorry your Dead! The secret word was " + randomWord + "!" ); $(".category").append( "<br><button enabled class='play-again'>Play again?</button>" ); } // Play again button $(".play-again").on("click", function() { location.reload(); }); }); });
var tabs = document.getElementById('tab-control').getElementsByTagName('a'); var pages = document.getElementById('tab-body').getElementsByTagName('div'); // --------------------------- // ▼B:タブの切り替え処理 // --------------------------- function changeTab() { // ▼B-1. href属性値から対象のid名を抜き出す var targetid = this.href.substring(this.href.indexOf('#')+1,this.href.length); // ▼B-2. 指定のタブページだけを表示する for(var i=0; i<pages.length; i++) { if( pages[i].id != targetid ) { pages[i].style.display = "none"; } else { pages[i].style.display = "block"; } } // ▼B-3. クリックされたタブを前面に表示する for(var i=0; i<tabs.length; i++) { tabs[i].style.zIndex = "2"; } this.style.zIndex = "10"; // ▼B-4. ページ遷移しないようにfalseを返す return false; } // --------------------------- // ▼C:すべてのタブに対して、クリック時にchangeTab関数が実行されるよう指定する // --------------------------- for(var i=0; i<tabs.length; i++) { tabs[i].onclick = changeTab; } // --------------------------- // ▼D:最初は先頭のタブを選択しておく // --------------------------- tabs[0].onclick();
export default class FileManagementService { constructor(axios) { this.axios = axios; } getFileAndFolder(userId, folderId, page, limit) { return this.axios.get(`/api/file/folder?userId=${userId}&folderId=${folderId}&page=${page}&limit=${limit}`); } getTotalFileAndFolder(userId, folderId) { return this.axios.get(`/api/file/total-folder?userId=${userId}&folderId=${folderId}`); } getInforMagic(id) { return this.axios.get(`/api/file/magic-link/${id}`); } getFileByName(userId, folderId, keyword, magicLinkId = '', page, limit) { return this.axios.get(`/api/file/search/${userId}?folderId=${folderId}&search=${keyword}&magicLinkId=${magicLinkId}&page=${page}&limit=${limit}`); } getCountFileByName(userId, folderId, keyword, magicLinkId = '') { return this.axios.get(`/api/file/total-search/${userId}?folderId=${folderId}&search=${keyword}&magicLinkId=${magicLinkId}`); } getFileAndFolderDeleted(userId, folderId, page, limit) { return this.axios.get(`/api/file/folder-deleted?userId=${userId}&folderId=${folderId}&page=${page}&limit=${limit}`); } getTotalFileAndFolderDeleted(userId, folderId) { return this.axios.get(`/api/file/total-deleted?userId=${userId}&folderId=${folderId}`); } restoreFileAndFolder(id) { return this.axios.put(`/api/file/undelete/${id}`); } createFolderInRoot(data) { return this.axios.post(`/api/file/root`, data); } createFolder(data) { return this.axios.post(`/api/file/folder`, data); } createMagicLink(data) { return this.axios.post(`/api/file/magic-link`, data); } archiveFolder(id) { return this.axios.delete(`/api/file/${id}`); } uploadFile(userId, folderId, data, onUploadProgress) { return this.axios.post(`/api/file/upload?userId=${userId}&folderId=${folderId}`, data, { timeout: 300000, onUploadProgress, }); } rename(fileOrFolderId, isFolder, newName) { if (isFolder) { return this.renameFolder(fileOrFolderId, newName); } return this.renameFile(fileOrFolderId, newName); } renameFile(fileId, newName) { return this.axios.put(`/api/file/update-name-file/${fileId}`, { name: newName, isFolder: false }); } renameFolder(folderId, newName) { return this.axios.put(`/api/file/update-name-folder/${folderId}`, { name: newName, isFolder: true }); } listMagicLinks(folderId) { return this.axios.get(`/api/file/get-magic-link-by-folder/${folderId}`); } }
const modelRequest = require('../models/request.js'); function handleAddRequest(request, response) { var requestInfo = request.body; modelRequest.addRequest(requestInfo, function(error, result) { if (error) return response.status(error.code).json(error); request.session.student = result.newRequestId; response.json(result); }); } function handleEditRequest(request, response) { var updatedInfo = request.body; console.log("Editing Request for", updatedInfo.fname + " " + updatedInfo.lname); modelRequest.editRequest(updatedInfo, function(error, result) { if (error) return response.status(error.code).json(error); response.json(result); }); } function handleCurrentRequests(request, response) { console.log("Getting all current Requests!"); modelRequest.currentRequests(function(error, result) { if (error) return response.status(error.code).json(error); response.json(result); }); } function handleRemoveRequest(request, response) { var id = request.params.id; console.log("Delete Request with id:", id); modelRequest.removeRequest(id, function(error, result) { if (error) return response.status(error.code).json(error); if (request.session.student) request.session = null; response.json(result); }); } function handleCleanUp(request, response) { if (!request.session.student) return response.status(400).json({ status: "Failure", failInfo: "No student session to remove." }); request.session = null; // destroy the cookie session response.json({ status: "Success", info: "Session removed" }); } module.exports = { handleAddRequest: handleAddRequest, handleEditRequest: handleEditRequest, handleCurrentRequests: handleCurrentRequests, handleRemoveRequest: handleRemoveRequest, handleCleanUp: handleCleanUp };
/** * This is only setup & fixes (no initialize) for TinyMCE. * TinyMCE is initialized in WK_Nette_Ajax.js - because TinyMCE must be re-initialize after components redrawing. * Author: Jiří Zapletal * Company: Wakers (http://www.wakers.cz) * Contact: zapletal@wakers.cz * Copyright 2017 */ $(function () { // Prevent Bootstrap dialog from blocking focusin $(document).on('focusin', function(e) { if ($(e.target).closest('.mce-window').length !== 0) { e.stopImmediatePropagation(); } }); $(document).on('focusin', '.tiny_mce', function () { var id = $(this).attr('id'); tinymce.get(id).focus() }); // funkce pro inicializaci tinymce editoru $.tinymce_init = function (selector, configuration) { var config = $.extend( { selector: selector, setup: function (editor) { editor.on('keyup change blur', function () { editor.save(); //var $form = $(editor.getElement()).parents('form'); var textarea = document.getElementById(editor.id); Nette.validateControl(textarea); }); } }, configuration); $.nette.ext('tinymce_' + selector, { load: function () { tinymce.remove(); tinymce.init(config); } }); }; $.tinymce_init('.tiny_mce', { skin: false, language: false, mode: 'textareas', paste_as_text: true, entity_encoding: 'named', height: 300, relative_urls : false, remove_script_host : true, menubar: false, nonbreaking_force_tab: true, allow_unsafe_link_target: true, block_formats: 'Heading 2=h2;Heading 3=h3;Paragraph=p;', content_style: '*{font-family:Ubuntu,sans-serif} table{width:100%} p,td,th,li{color:#666} table,td{border: 1px solid #ccc}}', plugins: [ ['nonbreaking textcolor link lists code table paste'] ], toolbar: [ 'formatselect | nonbreaking bold italic underline subscript superscript forecolor | link table | bullist numlist | alignjustify aligncenter alignleft alignright | code' ], //valid_elements: 'table,thead,tbody,tr,td,th,strong,em,sub,sup,br,p[style=text-align],span[style=color],ul,ol,li,a[href|target|title]', invalid_styles: { 'table': 'width height border-collapse', 'tr': 'width height', 'th': 'width height', 'td': 'width height' } //valid_elements: 'table,thead,tbody,tr,td,th,strong,p[style=text-align],h1,h2,h3,br,span[style=color|text-decoration],em,sub,sup,a[href|target|title],ul,li,ol', }); });
import Todo from "../Schemas/Todo"; const getTodos = async () => { try { const todos = await Todo.find({}).exec(); let todosToSend = []; for (var todoItem of todos) { todosToSend.unshift({ id: todoItem._id, description: todoItem.description, completed: todoItem.completed, }); } return { success: true, todosToSend }; } catch (error) { return { success: false, error }; } }; const getTodoById = async (id) => { try { const isIdValid = validateId(id); if (!isIdValid) throw new Error("BAD_REQUEST:INVALID_ID"); const requestedItem = await Todo.findById(id); if (!requestedItem) throw new Error("BAD_REQUEST:INVALID_ID"); return { success: true, requestedItem: { id: requestedItem._id, description: requestedItem.description, completed: requestedItem.completed, }, }; } catch (error) { return { success: false, error }; } }; const createTodo = async (description) => { try { if (typeof description === "number") description = description.toString(); if (typeof description !== "string" || description.length === 0) throw new Error("BAD_REQUEST"); let newTodo = await Todo({ description }).save(); return { success: true, newTodo: { description: newTodo.description, id: newTodo._id, completed: newTodo.completed, }, }; } catch (error) { return { success: false, error, }; } }; const deleteTodoById = async (id) => { try { const isIdValid = validateId(id); if (!isIdValid) throw new Error("BAD_REQUEST:INVALID_ID"); const requestedItem = await Todo.findById(id); if (!requestedItem) throw new Error("BAD_REQUEST:INVALID_ID"); await requestedItem.delete(); return { success: true, deletedItem: { id: requestedItem._id, description: requestedItem.description, completed: requestedItem.completed, }, }; } catch (error) { return { success: false, error }; } }; const toggleTodoCompleted = async (shouldBeChecked, id) => { try { const isIdValid = validateId(id); if (!isIdValid) throw new Error("BAD_REQUEST:INVALID_ID"); const requestedItem = await Todo.findById(id); if (!requestedItem) throw new Error("BAD_REQUEST:INVALID_ID"); await requestedItem.update({ $set: { completed: shouldBeChecked } }); return { success: true, updatedItem: { id: requestedItem._id, description: requestedItem.description, completed: shouldBeChecked, }, }; } catch (error) { return { success: false, error }; } }; const updateTodoDescriptionByID = async (id, description) => { try { if (typeof description === "number") description = description.toString(); if (typeof description !== "string" || description.length === 0) throw new Error("BAD_REQUEST"); const isIdValid = validateId(id); if (!isIdValid) throw new Error("BAD_REQUEST:INVALID_ID"); const requestedItem = await Todo.findById(id); if (!requestedItem) throw new Error("BAD_REQUEST:INVALID_ID"); await requestedItem.update({ $set: { description } }); return { success: true, updatedItem: { id: requestedItem._id, description, completed: requestedItem.completed, }, }; } catch (error) { return { success: false, error }; } }; const validateId = (id) => id.match(/^[0-9a-fA-F]{24}$/); module.exports = { getTodos, getTodoById, createTodo, deleteTodoById, toggleTodoCompleted, updateTodoDescriptionByID, };
const fileSplitter = (file, fragmentSize) =>{ if (file === undefined){ return [] } if (fragmentSize === undefined){ fragmentSize = 3 } if (fragmentSize <= 0){ //validasi if someone just want to prank return [] } var fragmentSize = fragmentSize * 1024 * 1024; var fileSize = file.size; var totalFragments = Math.ceil(fileSize/fragmentSize,fragmentSize); var fragmentTracker = 0; var fragments = [] while (fragmentTracker < totalFragments) { var offset = fragmentTracker*fragmentSize; fragments.push({ sequenceNumber : fragmentTracker, sequenceFile : file.slice(offset,offset+fragmentSize) }) fragmentTracker++; } return fragments } module.exports.fileSplitter = fileSplitter
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { $api } from 'services/api'; // TODO Create category slice and move all related staff there export const fetchDetails = createAsyncThunk( 'productDetails/fetchDetails', async (slug, { rejectWithValue, dispatch }) => { try { const { data } = await $api.get(`/product/${slug}`); console.log(data); return data; } catch (e) { return rejectWithValue(e.response.data); } } ); export const productDetailsSlice = createSlice({ name: 'productDetails', initialState: { data: null, isLoading: true, error: false, }, extraReducers: (builder) => { builder.addCase(fetchDetails.pending, (state) => { state.isLoading = true; }); builder.addCase(fetchDetails.fulfilled, (state, action) => { state.data = action.payload; state.isLoading = false; }); builder.addCase(fetchDetails.rejected, (state, action) => { state.error = true; state.data = {}; state.isLoading = false; }); }, }); export default productDetailsSlice.reducer;
function tempFunc() { debugger; location.href='http://google.com'; }
(function () { 'use strict'; angular .module('myapp.alarm-history') .controller('AlarmController', AlarmController); AlarmController.$inject = [ "$scope", "c8yBase", "c8yAlarms", "c8ySettings" ]; function AlarmController($scope, c8yBase, c8yAlarms, c8ySettings) { var self = this; var alarmList = []; var currentPage = 1; self.start = moment().subtract(1, "month").toDate(); self.end = moment().toDate(); $scope.searchAlarm = function () { if (self.start || self.end || self.end > self.start) { alarmList = []; currentPage = 1; self.addAlarm(); } } self.addAlarm = function () { c8yAlarms.list( _.assign(c8yBase.timeOrderFilter(), { source: $scope.child.config.device.id, dateFrom: moment(self.start.toISOString()).format(c8yBase.dateFullFormat), dateTo: moment(self.end.toISOString()).format(c8yBase.dateFullFormat), pageSize: 5, currentPage: currentPage }) ).then(function (res) { console.log(res); if (res.length) { res.forEach(function (alarm) { alarmList.push(alarm); }); currentPage++; self.alarms = alarmList; } }); } self.addAlarm(); } }());
import React from 'react'; import { Row, Col, Container, Carousel } from 'react-bootstrap'; function Home() { return ( <Container fluid> <Carousel > <Carousel.Item interval={1000}> <img style={{ width: "100vw", height: "85vh", background: "#000000" }} /> <Carousel.Caption> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={1000}> <img style={{ width: "100vw", height: "85vh", background: "#000000" }} /> <Carousel.Caption> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={1000}> <img style={{ width: "100vw", height: "85vh", background: "#000000" }} /> <Carousel.Caption> </Carousel.Caption> </Carousel.Item> </Carousel> </Container> ); } export default Home;
class Job { constructor (employerUrlSlug, description, jobType, salary) { this.employer = employerUrlSlug this.description = description this.jobType = jobType this.salary = salary this.postedAt = new Date() this.accepted = false this.givenTo = null this.applicants = [] } } module.exports = Job
var React = require('react'); var NavBtn = require('./NavBtn'); var EasingOutElastic = require('../utilities/EasingOutElastic'); var NavPanel= React.createClass({ getInitialState: function(){ return { sliderInitialLocation: 300, sliderEndLocation:0 }; }, componentDidMount: function(){ var navSlider = React.findDOMNode(this.refs.navContainer); navSlider.scrollLeft = 300; this.startScrollAnimation(navSlider); }, createNavItem: function(iconData, index){ return <NavBtn key={ iconData+index } iconType={ iconData.iconType } textType={ iconData.iconText } iconColor={ iconData.itemColor } /> }, startScrollAnimation: function(navSlider){ // duration: (250 - 150) * 20ms = 2 seconds var countdown = 250; var timer = setTimeout(function loop(){ if(countdown<=150) { clearTimeout(timer); } if(countdown>150) { var newVal = EasingOutElastic(countdown, {to:150, from:250}) // dampen easing effect navSlider.scrollLeft = Math.floor(300 - (newVal * 200)); countdown--; setTimeout(loop, 20); } }, 500); }, render: function(){ return ( <div className="nav-container" ref="navContainer"> <div className="nav-panel"> { this.props.iconData.map(this.createNavItem) } </div> </div> ); } }); module.exports = NavPanel;
$(document).ready(function() { var divs = document.getElementsByClassName('alert'); for(var i=0; i<divs.length; i++) { divs[i].addEventListener("click", highlightThis); /* divs[i].addEventListener("click", highlightThis, true); divs[i].addEventListener("click", highlightThis, false);*/ } function highlightThis(event) { //event.stopPropagation(); var backgroundColor = this.style.backgroundColor; this.style.backgroundColor='yellow'; alert(this.className); this.style.backgroundColor=backgroundColor; } $(window).on('hashchange', function(e){ var url = window.location.href; doHighlight(url); }); function doHighlight(url) { if (url.indexOf("settings") > -1) { $("#menu-settings").addClass("active"); $("#menu-tasks").removeClass("active"); $("#menu-users").removeClass("active"); } else if (url.indexOf("users") > -1) { $("#menu-users").addClass("active"); $("#menu-tasks").removeClass("active"); $("#menu-settings").removeClass("active"); } else if (url.indexOf("tasks") > -1) { $("#menu-tasks").addClass("active"); $("#menu-settings").removeClass("active"); $("#menu-users").removeClass("active"); } } var url = window.location.href; doHighlight(url); });
import { takeLatest, call, put } from "redux-saga/effects"; import { loginActions } from "./sessionActionConstants"; import sessionRequest from "./sessionApi"; export default function* sessionSaga() { yield takeLatest(loginActions.LOGIN_REQUEST_START, createSessionRequest); } function* createSessionRequest(loginData) { try { const result = yield call(sessionRequest(loginData)); yield put({type: loginActions.LOGIN_REQUEST_COMPLETE, payload: {isAuthenticated: true }}); } catch(e) { yield put({type: loginActions.LOGIN_REQUEST_FAIL, payload: {isAuthenticated: false }}); } }
'use strict'; describe('splash creation, listing', function () { var $scope, element, deferred, compile, q, location, $location, boxFactory, networkFactory, codeFactory, splashFactory, splashFormFactory, $httpBackend, routeParams, locationFactory; beforeEach(module('myApp', function($provide) { networkFactory = { get: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }; locationFactory = { get: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, update: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }; codeFactory = { generate_password: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }; splashFormFactory = { update: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }; splashFactory = { store: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, create_store: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, update_store: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, destroy_store: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, duplicate: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, destroy: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, create: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, get: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, query: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, update: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }; $provide.value("SplashFormPage", splashFormFactory); $provide.value("SplashPage", splashFactory); $provide.value("Code", codeFactory); $provide.value("Location", locationFactory); $provide.value("Network", networkFactory); })); beforeEach(module('components/layouts/submit.html')); beforeEach(module('components/splash_pages/_designer.html')); beforeEach(module('components/splash_pages/design-sidebar.html')); beforeEach(module('components/splash_pages/_index.html')); beforeEach(module('components/splash_pages/_form.html')); beforeEach(module('components/splash_pages/splash_show.html')); beforeEach(module('components/splash_pages/access-password.html')); beforeEach(module('components/splash_pages/store.html')); beforeEach(module('components/splash_pages/view-store.html')); beforeEach(module('components/splash_pages/add-products.html')); describe('splash_pages creation, listing', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams, $injector) { $httpBackend = $injector.get('$httpBackend'); $httpBackend.whenGET('template/tooltip/tooltip-popup.html').respond(""); $scope = $rootScope; routeParams = $routeParams; routeParams.new = "88888"; routeParams.location_id = 123 $scope.box = {}; q = $q; $scope.location = { slug: 456, id: 123 } $scope.loading = true; element = angular.element('<list-splash></list-splash>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should list all the splash pages for a location", function() { expect(element.isolateScope().loading).toBe(true) spyOn(splashFactory, 'get').andCallThrough() var splash = { splash_pages: [ { network_id: '123'} ] } expect(element.isolateScope().location.slug).toBe(123) deferred.resolve(splash); $scope.$apply() expect(element.isolateScope().splash_pages).toBe(splash.splash_pages) expect(element.isolateScope().loading).toBe(undefined) expect(element.isolateScope().cloned_id).toBe("88888") }); it("should mark a splash with the new attribute after cloning it", function() { spyOn(splashFactory, 'get').andCallThrough(); expect(element.isolateScope().loading).toBe(true) var splash = { splash_pages: [{ unique_id: '88888'}]}; deferred.resolve(splash); $scope.$apply(); expect(element.isolateScope().loading).toBe(undefined); expect(element.isolateScope().splash_pages[0].unique_id).toBe(splash.splash_pages[0].unique_id); }); }); describe('splash_pages show', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; $scope.box = {}; routeParams = $routeParams; routeParams.id = "slugit"; q = $q; $scope.location = { slug: 456, id: 123 }; element = angular.element('<location-splash-pages-show slug="{{location.slug}}"></location-splash_pages-show>'); $compile(element)($rootScope); element.scope().$apply(); })); it("should display the splash page with all scopes set", function() { element.isolateScope().loading = true; spyOn(splashFactory, 'query').andCallThrough(); var access = {'Off': 'none', 'Timed Access': 'timed', 'Periodic': "periodic", 'Data': "data" }; var period = { 'Daily' : 'daily', 'Weekly': 'weekly', 'Monthly': 'monthly' }; var nts = { 'Off' : 0, 'MailChimp': 1, 'CampaignMonitor': 2, 'SendGrid': 4, 'Internal only': 3 }; var splash = { splash_page: { available_start: '0000', available_end: '13:54', splash_page_name: 'lobby'}, access_types: [{ name: "password"}], networks: [{name: "123123"}]}; expect(element.isolateScope().splash_loading).toBe(true); deferred.resolve(splash); $scope.$apply(); expect(element.isolateScope().loading).toBe(undefined); expect(element.isolateScope().splash).toBe(splash.splash_page); expect(element.isolateScope().access_types).toBe(splash.access_types); expect(element.isolateScope().networks).toBe(splash.networks); // expect(element.isolateScope().splash.userdays.length).toBe(7) expect(JSON.stringify(element.isolateScope().access_restrict)).toBe(JSON.stringify(access)); expect(JSON.stringify(element.isolateScope().period)).toBe(JSON.stringify(period)); expect(JSON.stringify(element.isolateScope().newsletter_types)).toBe(JSON.stringify(nts)); }); it("should loop through the networks and add a checkbox next to them", function() { element.isolateScope().loading = true; spyOn(splashFactory, 'query').andCallThrough(); var splash = { splash_page: { available_start: '0000', available_end: '13:54', splash_page_name: 'lobby', networks: ['abc']}, access_types: [{ name: "password"}], networks: [{id: "abc"}, {id: 'xyz'}]}; deferred.resolve(splash); $scope.$apply(); expect(element.isolateScope().networks).toBe(splash.networks); element.isolateScope().populateNetworks(); // expect(element.isolateScope().populating).toBe(true); expect(element.isolateScope().networks[0].active).toBe(true); }); it("should test the human access types name filter", function() { spyOn(splashFactory, 'query').andCallThrough() var splash = { splash_page: { available_start: '0000', available_end: '13:54', splash_page_name: 'lobby'}, access_types: [{ id: 1, name: "password"}, {id: 22, name: 'simon'}], networks: [{name: "123123"}]} deferred.resolve(splash); $scope.$apply() expect(element.isolateScope().access_types).toBe(splash.access_types) expect(element.isolateScope().access_name(1)).toBe('password'); expect(element.isolateScope().access_name(22)).toBe('simon'); }); it("should not get the splash pages for a location", function() { spyOn(splashFactory, 'query').andCallThrough() var splash = { network_id: '123'} expect(element.isolateScope().splash_loading).toBe(true) deferred.reject({data: {errors: { base: [123]}}}); $scope.$apply() expect(element.isolateScope().splash_loading).toBe(undefined) expect(element.isolateScope().splash.errors[0]).toBe(123) }); it("should update the location when tagged logins is clicked", function() { element.isolateScope().myForm.$pristine = false; element.isolateScope().myForm.$dirty = true; element.isolateScope().splash = { tagged_logins: true }; spyOn(locationFactory, 'update').andCallThrough(); element.isolateScope().updateLocation(); expect(element.isolateScope().tagged.updating).toBe(true); deferred.resolve(); $scope.$apply() expect(locationFactory.update).toHaveBeenCalled(); expect(element.isolateScope().myForm.$pristine).toBe(true) expect(element.isolateScope().myForm.$dirty).toBe(false) expect(element.isolateScope().tagged.updating).toBe(undefined); expect(element.isolateScope().tagged.updated).toBe(true); }); it("should NOT update the location when tagged logins is clicked", function() { spyOn(locationFactory, 'update').andCallThrough(); element.isolateScope().splash = { tagged_logins: true }; element.isolateScope().updateLocation(); expect(element.isolateScope().tagged.updating).toBe(true); deferred.reject(); $scope.$apply(); expect(locationFactory.update).toHaveBeenCalled(); expect(element.isolateScope().tagged.updating).toBe(undefined); expect(element.isolateScope().tagged.errors).toBe(true); }); it("should update the splash page", function() { element.isolateScope().available_start = new Date(); element.isolateScope().available_end = new Date(); element.isolateScope().splash = { available_start: '0000', available_end: '13:54', splash_page_name: 'lobby'}; spyOn(splashFactory, 'update').andCallThrough(); var form = { $setPristine: function() { } }; element.isolateScope().update(form); expect(element.isolateScope().splash.state).toBe('updating'); deferred.resolve(); $scope.$apply(); expect(splashFactory.update).toHaveBeenCalled(); expect(element.isolateScope().splash.state).toBe('updated'); expect(element.isolateScope().notifications).toBe('Splash Updated Successfully.'); }); it("should uncheck the require email if newsletter is off", function() { element.isolateScope().splash = {newsletter_active: false, email_required: true}; element.isolateScope().updateRequireEmail(); expect(element.isolateScope().splash.email_required).toBe(false); }); it("should not update the splash page", function() { element.isolateScope().available_start = new Date() element.isolateScope().available_end = new Date() element.isolateScope().splash = { available_start: '0000', available_end: '13:54', splash_page_name: 'lobby'} spyOn(splashFactory, 'update').andCallThrough() element.isolateScope().update(); expect(element.isolateScope().splash.state).toBe('updating'); deferred.reject({data: {errors: { base: [123]}}}); $scope.$apply() expect(splashFactory.update).toHaveBeenCalled(); expect(element.isolateScope().splash.state).toBe('failed'); expect(element.isolateScope().myForm.errors).toBe(true); }); }); describe('splash_pages password change days', function () { var routeParams = {}; beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; routeParams = $routeParams; routeParams.id = "slugit"; q = $q; $scope.location = { slug: 456, id: 123 }; $scope.splash = {}; $scope.splash.passwd_change_day = ["1","2","3"]; $scope.splash.userdays = []; element = angular.element('<day-selector days="splash.passwd_change_day" array="splash.userdays"></day-selector>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should loop through and create an checkboxes for days", function() { expect(JSON.stringify($scope.splash.userdays)).toBe(JSON.stringify([0,1,1,1,0,0,0])) }); it("should update the user days passwd change array", function() { expect(JSON.stringify($scope.splash.passwd_change_day)).toBe(JSON.stringify([ '1', '2', '3' ])) element.find("#day_0").click() expect(JSON.stringify($scope.splash.passwd_change_day)).toBe(JSON.stringify([ '1', '2', '3', '0' ])) element.find("#day_1").click() expect(JSON.stringify($scope.splash.passwd_change_day)).toBe(JSON.stringify([ '2', '3', '0' ])) }) }); describe('splash_pages attr', function () { var routeParams = {}; beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; $scope.box = {}; routeParams = $routeParams; routeParams.id = "slugit"; q = $q; $scope.location = { slug: 456, id: 123 } $scope.splash = {}; element = angular.element('<remove-image attribute=\'splash.location_image_name\' temp=\'splash.location_image_name_temp\'></remove-image>'); $compile(element)($rootScope) element.scope().$apply(); })) it("it should remove and undo the location image", function() { // expect(element.html()).toBe('<p class="remove-image"><small><a ng-show="attribute" class="remove-image ng-hide" ng-click="removeImage()">Remove Image</a></small></p><p class="remove-image"><small><a ng-show="temp" class="undo-remove ng-hide" ng-click="undoRemoveImage()">Undo</a></small></p>') expect(element.find('.remove-image').hasClass('ng-hide')).toBe(true); expect(element.find('.undo-remove').hasClass('ng-hide')).toBe(true); // Now with an image // $scope.splash.location_image_name = 123 $scope.$apply(); expect(element.find('.remove-image').hasClass('ng-hide')).toBe(false); expect(element.find('.undo-remove').hasClass('ng-hide')).toBe(true); // Click to remove // element.find('.remove-image').click(); expect($scope.splash.location_image_name).toBe('') expect($scope.splash.location_image_name_temp).toBe(123) expect(element.find('.remove-image').hasClass('ng-hide')).toBe(true); expect(element.find('.undo-remove').hasClass('ng-hide')).toBe(false); // Undo // element.find('.undo-remove').click(); expect($scope.splash.location_image_name).toBe(123) expect($scope.splash.location_image_name_temp).toBe(undefined) expect(element.find('.remove-image').hasClass('ng-hide')).toBe(false); expect(element.find('.undo-remove').hasClass('ng-hide')).toBe(true); }); }); describe('splash_pages desingers', function () { var routeParams = {}; beforeEach(inject(function($compile, $rootScope, $q, $routeParams, $injector) { $httpBackend = $injector.get('$httpBackend'); $httpBackend.whenGET('template/tooltip/tooltip-popup.html').respond(""); $httpBackend.when('PATCH', 'http://mywifi.dev:8080/api/v1/locations/undefined/splash_pages/undefined') .respond(200, {}); $scope = $rootScope; routeParams = $routeParams; routeParams.id = "slugit"; q = $q; $scope.location = { slug: 456, id: 123 }; $scope.splash = {}; element = angular.element('<splash-designer></splash-designer>'); $compile(element)($rootScope); element.scope().$apply(); })) it("it should get the location and splash page", function() { spyOn(locationFactory, 'get').andCallThrough() expect(element.isolateScope().loading).toBe(true) var location = { location_name: 'simon' } deferred.resolve(location); $scope.$apply() expect(element.isolateScope().location).toBe(location) var splash = { splash_page: { logo: 'simon', header_image_name: null, logo_file_name: null } } deferred.resolve(splash); $scope.$apply() expect(element.isolateScope().splash).toBe(splash.splash_page) expect(element.isolateScope().loading).toBe(undefined) expect(element.isolateScope().uploadLogo).toBe(true); }); it("it should set the image to a blank PNG", function() { element.isolateScope().splash = {}; element.isolateScope().nologo = true; element.isolateScope().setTrans(); expect(element.isolateScope().splash.header_image_name).toBe('https://d3e9l1phmgx8f2.cloudfront.net/images/login_screens/transparent.png'); }); it("it should save and continue", function() { spyOn(splashFormFactory, 'update').andCallThrough() element.isolateScope().splash = {}; element.isolateScope().uploadLogo = true; element.isolateScope().saveAndContinue(); expect(element.isolateScope().splash.updating).toBe(true); deferred.resolve({password: 123}); $scope.$apply() // expect(element.isolateScope().uploadLogo).toBe(undefined); }); it("it should have an image and then design the rest", function() { }); }); describe('splash_pages access types panels', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; q = $q; $scope.splash = {} $scope.splash.password = "simon" element = angular.element('<div access-types ver=\'{{access_name(1)}}\'></div>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should add a page to the erm, page", function() { $scope.$apply() expect(element.html() === undefined).toBe(false) // stupid test // }); }); describe('splash_pages password generation', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; q = $q; $scope.splash = {} $scope.myForm = {}; $scope.splash.password = "simon" $scope.generating = undefined; element = angular.element('<splash-generate-passy attribute="splash.password" loading=\'generating\'></splash-generate-passy>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should call CT and generate a new passy", function() { $scope.myForm.$pristine = true; spyOn(codeFactory, 'generate_password').andCallThrough() expect(element.html() == undefined).toBe(false); element.find('a').click() expect($scope.generating).toBe(true) deferred.resolve({password: 123}); $scope.$apply() expect(codeFactory.generate_password).toHaveBeenCalled(); expect($scope.splash.password).toBe(123) expect($scope.generating).toBe(undefined) // expect($scope.myForm.$pristine).toBe(false); }); it("should not call CT and generate a new passy", function() { spyOn(codeFactory, 'generate_password').andCallThrough() element.find('a').click() expect($scope.generating).toBe(true) deferred.reject(); $scope.$apply() expect(codeFactory.generate_password).toHaveBeenCalled(); expect($scope.splash.password).toBe('simon') expect($scope.generating).toBe(undefined) }); }); describe('splash_pages new', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams, _$location_, _$routeParams_) { $location = _$location_; $routeParams = _$routeParams_ $routeParams.location_id = 123 $scope = $rootScope; q = $q; $scope.location = {slug: 123} element = angular.element('<splash-new><splash-new>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should get a list of networks", function() { $scope.loading = true; spyOn(networkFactory, 'get').andCallThrough() expect(element.html() == undefined).toBe(false); var network = { id: 123 } var splash = { access_types: [{name: 'password', id: 888} ]} deferred.resolve([network]); $scope.$apply() expect(element.isolateScope().networks[0]).toBe(network); expect(element.isolateScope().splash.network_id).toBe(123) deferred.resolve(splash); $scope.$apply() expect(element.isolateScope().access_types).toBe(splash.access_types) expect(element.isolateScope().splash.primary_access_id).toBe(888) expect(element.isolateScope().loading).toBe(undefined) expect(element.isolateScope().splash == undefined).toBe(false) }); it("should create the fuck out of the splash", function() { $scope.loading = true; spyOn(networkFactory, 'get').andCallThrough() spyOn(splashFactory, 'create').andCallThrough() element.isolateScope().create() expect(element.isolateScope().splash.creating).toBe(true); var splash = { id: 123} deferred.resolve(splash); $scope.$apply() // expect(element.isolateScope().splash.id).toBe(123) expect(element.isolateScope().notifications).toBe('Splash Created Successfully.') expect($location.path()).toBe('/locations/123/splash_pages/123') }); it("should not create the fuck out of the splash", function() { element.isolateScope().loading = true; spyOn(networkFactory, 'get').andCallThrough() spyOn(splashFactory, 'create').andCallThrough() element.isolateScope().create() deferred.reject({data: {errors: { base: [123]}}}); $scope.$apply() expect(element.isolateScope().splash.errors[0]).toBe(123) expect(element.isolateScope().splash.creating).toBe(undefined); }); }); describe('splash_pages delete!', function () { var routeParams = {}; beforeEach(inject(function($compile, $rootScope, $q, $routeParams, _$location_) { $location = _$location_; $scope = $rootScope; $scope.box = {}; routeParams = $routeParams; routeParams.id = "slugit"; q = $q; $scope.splash = {unique_id: 123123} $scope.myForm = {}; $scope.location = { slug: 456, id: 123 } element = angular.element('<splash-delete slug="{{location.slug}}"></splash-delete>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should go abouts deleting the splash pages", function() { spyOn(splashFactory, 'destroy').andCallThrough() expect(element.find('#delete-splash').hasClass('ng-hide')).toBe(true); element.find('#delete-splash-confirm').click(); $scope.$apply(); expect(element.isolateScope().splash.deleting).toBe(true) expect(element.find('#delete-splash').hasClass('ng-hide')).toBe(false); expect(element.find('#delete-button').hasClass('ng-hide')).toBe(true); element.isolateScope().confirmation = 'danger' $scope.$apply(); expect(element.find('#delete-button').hasClass('ng-hide')).toBe(false); element.find('#delete-button').click() deferred.resolve(); $scope.$apply(); expect($location.path()).toBe('/locations/456/splash_pages') expect(element.isolateScope().notifications).toBe('Splash Deleted Successfully.') }); }); describe('splash_pages duplication', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams, _$location_) { $scope = $rootScope; $location = _$location_ q = $q; $scope.splash = {unique_id: 567} $scope.location = {} $scope.location.slug = 12312783 element = angular.element('<splash-duplicate unique_id=\'splash.unique_id\' slug=\'{{ location.slug }}\'></splash-duplicate>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should copy a splash page to NO location, same.", function() { spyOn(splashFactory, 'duplicate').andCallThrough() expect(element.find('#duplicate').hasClass('ng-hide')).toBe(true); element.isolateScope().duplicate = true; $scope.$apply() expect(element.find('#duplicate').hasClass('ng-hide')).toBe(false); var cont = element.find('input[name*="copy_to"]').controller('ngModel'); cont.$setViewValue(123); $scope.$apply() expect(element.isolateScope().copy_to).toBe(123) element.isolateScope().duplicateSplash(); $scope.$apply() expect(element.isolateScope().duplicating).toBe(true) deferred.resolve({unique_id: 777}); $scope.$apply() expect(element.isolateScope().duplicating).toBe(undefined) expect($location.path()).toBe('/locations/12312783/splash_pages') expect($location.search().new).toBe('777') }); it("should not copy a splash page.", function() { spyOn(splashFactory, 'duplicate').andCallThrough() expect(element.find('#duplicate').hasClass('ng-hide')).toBe(true); element.isolateScope().duplicateSplash(); deferred.reject({data: {errors: { base: [123]}}}); $scope.$apply() expect(splashFactory.duplicate).toHaveBeenCalled(); expect(element.isolateScope().duplicating).toBe(undefined) expect(element.isolateScope().errors[0]).toBe(123) }); }); describe('splash_pages store create', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams) { $scope = $rootScope; routeParams = $routeParams; routeParams.new = "88888"; $scope.box = {}; q = $q; $scope.location = { slug: 456, id: 123 } // $scope.store = {} element = angular.element('<splash-store store="store"><create-store store="store"></create-store></splash-store>'); $compile(element)($rootScope) element.scope().$apply(); })) }) describe('splash_pages store get', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams, $injector) { $httpBackend = $injector.get('$httpBackend'); $httpBackend.whenGET('components/splash_pages/view-store.html').respond(""); $scope = $rootScope; routeParams = $routeParams; routeParams.new = "88888"; $scope.box = {}; q = $q; $scope.location = { slug: 456, id: 123 } $scope.store = {}; element = angular.element('<splash-store store="store"></splash-store>'); $compile(element)($rootScope) element.scope().$apply(); })) it("should list a splash pages products", function() { var store = { store: { id: 123 }} var product = { duration: 60, type: 'multiuse', distance: 'minutes', download_speed: '2048', upload_speed: '1024', dummy: true, value: 300 }; spyOn(splashFactory, 'store').andCallThrough() deferred.resolve(store); $scope.$digest() expect($scope.store).toBe(store.store) expect(element.isolateScope().products[0].value).toBe(product.value) }); it("should add another row to the products and then save!", function() { spyOn(window, 'confirm').andReturn(true); var store = { store: { id: 123 }} var product = { duration: 60, session_timeout: 60, type: 'multiuse', distance: 'minutes', download_speed: '2048', upload_speed: '1024', dummy: true, value: 300 }; spyOn(splashFactory, 'store').andCallThrough() deferred.resolve(store); $scope.$digest() expect($scope.store).toBe(store.store) expect(element.isolateScope().products.length).toBe(1) element.isolateScope().addProduct() $scope.$digest() expect(element.isolateScope().template).toBe(true) expect(element.isolateScope().adding).toBe(true) expect(element.isolateScope().product.value).toBe(product.value) expect(element.isolateScope().product.type).toBe("multiuse") expect(element.isolateScope().product.duration).toBe(60) expect(element.isolateScope().product.session_timeout).toBe(60) element.isolateScope().saveProduct() $scope.$digest() expect(element.isolateScope().products.length).toBe(2) expect(element.isolateScope().updating).toBe(true) // Submits to CT // deferred.resolve(store); $scope.$digest() expect(element.isolateScope().updating).toBe(undefined) expect(element.isolateScope().product).toBe(undefined) }); it("should remove a row from the products", function() { spyOn(window, 'confirm').andReturn(true); var store = { store: { id: 123 }} var product = { duration: 60, type: 'multiuse', distance: 'minutes', download_speed: '2048', upload_speed: '1024', dummy: true, value: 300 }; spyOn(splashFactory, 'store').andCallThrough() deferred.resolve(store); $scope.$digest() expect($scope.store).toBe(store.store) expect(element.isolateScope().products.length).toBe(1) element.isolateScope().addProduct() $scope.$apply() // expect($location.hash()).toBe('new') expect(element.isolateScope().adding).toBe(true) expect(element.isolateScope().product.value).toBe(product.value) element.isolateScope().saveProduct() $scope.$digest() expect(element.isolateScope().products.length).toBe(2) expect(element.isolateScope().updating).toBe(true) element.isolateScope().removeProduct(0) $scope.$digest() expect(element.isolateScope().products[0]._destroy).toBe(1) expect(element.isolateScope().changed).toBe(true); }); it("should update the store accordingly", function() { spyOn(window, 'confirm').andReturn(true); spyOn(splashFactory, 'update_store').andCallThrough() element.isolateScope().update() $scope.$digest() expect(element.isolateScope().updating).toBe(true) deferred.resolve(); $scope.$digest() expect(element.isolateScope().updating).toBe(undefined) }); it("should NOT update the store accordingly", function() { spyOn(splashFactory, 'update_store').andCallThrough() element.isolateScope().update() $scope.$digest() expect(element.isolateScope().updating).toBe(true) deferred.reject(123); $scope.$digest() expect(element.isolateScope().updating).toBe(undefined) expect(element.isolateScope().store.errors).toBe(123) }); it("should create a new store", function() { spyOn(window, 'confirm').andReturn(true); spyOn(splashFactory, 'create_store').andCallThrough() var store = { store: { id: 123, created_at: 123 }} deferred.resolve(); $scope.$digest() element.find('#create-store').click() $scope.$digest() expect(element.isolateScope().creating).toBe(true) deferred.resolve(store); $scope.$digest() expect(element.isolateScope().creating).toBe(undefined) expect($scope.store).toBe(store) }); it("should NOT create a new store", function() { spyOn(splashFactory, 'create_store').andCallThrough() var store = { store: { id: 123 }} deferred.resolve(); $scope.$digest() element.find('#create-store').click() $scope.$digest() expect(element.isolateScope().creating).toBe(true) deferred.reject(123); $scope.$digest() expect(element.isolateScope().creating).toBe(undefined) expect($scope.store.errors).toBe(123) }); it("should set the store as active and update CT", function() { spyOn(window, 'confirm').andReturn(true); spyOn(splashFactory, 'update_store').andCallThrough() var store = { store: { id: 123, active: false }} $scope.store = store.store element.isolateScope().updateLiveStatus(); $scope.$apply(); expect(element.isolateScope().updating).toBe(true) deferred.resolve(); $scope.$digest() expect(element.isolateScope().updating).toBe(undefined) }) it("should start editing and add hash to path", function() { spyOn(window, 'confirm').andReturn(true); element.isolateScope().updateLiveStatus(); $scope.$apply(); }) }); describe('displays the days active on index page', function () { beforeEach(inject(function($compile, $rootScope, $q, $routeParams, $injector) { compile = $compile; $scope = $rootScope; q = $q; $scope.location = { slug: 456, id: 123 } element = angular.element('<splash-days-active start="{{splash.available_start}}" end="{{ splash.available_end }}" days="splash.available_days"></splash-days-active>'); })) it("should show Monday all day ", function() { $scope.splash = { available_days: [1], available_start: '00:00', available_end: '00:00' } compile(element)($scope) element.scope().$apply(); expect(element.isolateScope().days).toBe('Monday') expect(element.isolateScope().when).toBe('all day ') }); it("should show Monday and Tuesday all day ", function() { $scope.splash = { available_days: [1, 2], available_start: '00:00', available_end: '00:00' } compile(element)($scope) element.scope().$apply(); expect(element.isolateScope().days).toBe('Monday and Tuesday') expect(element.isolateScope().when).toBe('all day ') }); it("should show Monday Tuesday Wed all day ", function() { $scope.splash = { available_days: [1, 2, 3], available_start: '00:00', available_end: '00:00' } compile(element)($scope) element.scope().$apply(); expect(element.isolateScope().days).toBe('Monday, Tuesday, Wednesday') expect(element.isolateScope().when).toBe('all day ') }); it("should show no days ", function() { $scope.splash = { available_days: [], available_start: '00:00', available_end: '00:00' } compile(element)($scope) element.scope().$apply(); expect(element.isolateScope().days).toBe('No days selected') expect(element.isolateScope().when).toBe(undefined) }); }); })
angular.module( 'matchGameApp' ) .controller( 'PlayCtrl', function( $scope, $route, Game ){ angular.extend( $scope, Game ); $scope.gameOver = false; $scope.pairsLeft = 52/2; $scope.firstCard = ""; $scope.secondCard = ""; $scope.matches = {}; $scope.foundMatch = false; $scope.message = 'Pick a card!'; $scope.play = function( card ) { if( !card.flipped ) { Game.flipCard( card ); } if( $scope.foundMatch === true) { $scope.foundMatch = false; $scope.firstCard.hidden = true; $scope.secondCard.hidden = true; } if( !$scope.firstCard || $scope.secondCard ){ Game.flipCard($scope.firstCard); Game.flipCard($scope.secondCard); $scope.firstCard = $scope.secondCard = undefined; } if( $scope.firstCard ) { $scope.secondCard = card; if( $scope.firstCard.value === $scope.secondCard.value) { //remove and put to the side $scope.foundMatch = true; $scope.message = "You found a match!"; $scope.pairsLeft -= 1; }else{ $scope.message = "Try again..."; } }else{ $scope.firstCard = card; $scope.message = "Pick another card..."; } if( $scope.pairsLeft === 0 ) { $scope.firstCard.hidden = true; $scope.secondCard.hidden = true; $scope.gameOver = true; $scope.message = "Congratulations, you win!"; } }; $scope.deck = Game.shuffleDeck( Game.makeDeck() ); }) .factory( 'Game', function() { var counter = 0; function Card( suit, value ) { this.suit = suit; this.value = value; this.image = suit + "_" + value; this.flipped = false; this.hidden = false; } flipCard = function( card ) { card.flipped = !card.flipped; return card; }; makeDeck = function() { var deck = []; var suits = [ 'hearts', 'clubs', 'spades', 'diamonds' ]; var values = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ]; suits.forEach(function( suit ) { values.forEach(function( value ) { var newCard = new Card( suit, value ); deck.push(newCard); }); }); return deck; }; shuffleDeck = function( deck ) { for( var i=0; i<deck.length; i++ ) { var temp = deck[i]; var randIndex = Math.floor( Math.random() * ( deck.length - i )) + i; deck[i] = deck[randIndex]; deck[randIndex] = temp; } return deck; }; return { flipCard: flipCard, makeDeck: makeDeck, shuffleDeck: shuffleDeck } });
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, TouchableHighlight } from 'react-native'; export default class CommentsList extends Component { constructor(props) { super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 }), } } getDataSource(comments: Array<any>): ListView.DataSource { if(!comments) return; return this.state.dataSource.cloneWithRows(comments); } componentDidMount() { this.setState({dataSource: this.getDataSource(this.props.comments)}); } componentWillReceiveProps(props) { this.setState({dataSource: this.getDataSource(props.comments)}); } renderRow = (data) => { return( <View style={styles.comment}> <Text style={{fontSize: 16, color: '#494D4F'}}>{data.comment}</Text> </View> ); } render() { return( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} enableEmptySections={true} /> ) } } const styles = { comment: { minHeight: 100, maxHeight: 400, padding: 16, backgroundColor: 'white', borderColor: '#ECF0F1', borderWidth: 1, paddingTop: 10, paddingBottom: 10 } };
const log = require('./../lib/logger')(module) const express = require('express') const router = express.Router() const User = require('./../lib/mongoose').User router.get('/', (req, res, next) => { return User.find((err, users) => { if (err) return next(err) return res.send(users) }) }) router.post('/', (req, res, next) => { let user = new User(req.body) user.save(err => { if (err) return next(err) return res.send({ status: 'ok', content: user }) }) }) router.get('/me', (req, res, next) => { res.send({ 'status': 'ok', content: req.user }) }) router.get('/:id', (req, res, next) => { return User.findById(req.params.id, (err, user) => { if (err) next(err) if (!user) return next() return res.send({ status: 'ок', content: user }) }) }) router.put('/:id', (req, res, next) => { return User.findById(req.params.id, (err, user) => { if (err) return next(err) if (!user) return next() // do nothing return res.send({ status: 'warning', message: 'this command do not realized' }) }) }) router.delete('/:id', (req, res, next) => { return User.findById(req.params.id, (err, user) => { if (err) return next(err) if (!user) return next() return user.remove(err => { if (err) next(err) log.info('user removed') return res.send({ status: 'ок' }) }) }) }) module.exports = router
import FormValidator from '../components/FormValidator.js'; import Section from '../components/Section.js'; import { profileName, formTitle, profileButtonEdit, editButtonEditEmpty, newCardForn, popupEditAvatarIcon, avatarPhoto, data, avatarSelector, formValidEditProfile, CARD_OBJECT_SELECTOR, VIEW_CARD_IMAGE, POPUP_IMAGE_SELECTOR, POPUP_DESCRIPTION_SELECTOR, ARRAY_ELEMENT_PROFILE, POPUP_EDIT_PROFILE, POPUP_ADD_CARD_ELEMENT, ENVIROMENT_TOKEN, IDENTIFICATION_GROUP, POPUP_DELETE_SELECTOR, POPUP_PHOTO_EDIT_PROFILE} from '../utils/constants.js'; import PopupWithImage from '../components/PopupWithImage.js'; import { createCard } from '../utils/utils.js'; import UserInfo from '../components/UserInfo.js'; import PopupWithForm from '../components/PopupWithForm.js'; import Api from '../components/Api.js' import '../pages/index.css'; import PopupWithConfirm from '../components/PopupWithConfirm.js'; //Создание оьъекта с информацией о пользователе export const userInfo = new UserInfo(ARRAY_ELEMENT_PROFILE, avatarSelector); //Создание объекта страницы и заполнение данными const cardListSection = new Section({ renderer: (item) => { const card = createCard(item, popapImageView, popupPhotoDelete); const cardElement = card.generateCard(); cardListSection.addItem(cardElement); //вызов функции генерации } }, CARD_OBJECT_SELECTOR); export const api = new Api({ baseUrl: IDENTIFICATION_GROUP, headers: { authorization: ENVIROMENT_TOKEN, 'Content-Type': 'application/json' } }); Promise.all([api.getUserInfo(), api.getInitialCards()]) .then(([resultUserInfo, resultGetInitialCard]) =>{ userInfo.setUserInfo(resultUserInfo.name, resultUserInfo.about, resultUserInfo.avatar, resultUserInfo._id) cardListSection.renderItems(resultGetInitialCard); }) .catch((err) =>{ console.log(err); }) const popupPhotoDelete = new PopupWithConfirm({ handleConfirm: (cardId, card) => { const buttonText = popupEditProfilePhoto.submitButton.textContent; popupPhotoDelete.submitButton.textContent = "Удаление..."; api.deleteCard(cardId) .then((result) => { card.remove(); popupPhotoDelete.close(); }) .catch((err) => { console.log(err); }) .finally(() => { popupPhotoDelete.submitButton.textContent = buttonText; }); } }, POPUP_DELETE_SELECTOR); //Создание объекта для увеличения карточек const popapImageView = new PopupWithImage(VIEW_CARD_IMAGE, POPUP_IMAGE_SELECTOR, POPUP_DESCRIPTION_SELECTOR); const formEditValidator = new FormValidator(formValidEditProfile, data) formEditValidator.enableValidation() const formAddValidator = new FormValidator(newCardForn, data) formAddValidator.enableValidation() const formEditIconProfile = new FormValidator(popupEditAvatarIcon, data) formEditIconProfile.enableValidation() //Создание объекта для добавления карточки const popupImageAdd = new PopupWithForm({ validatorForm : formAddValidator, handleFormSubmit: (formData) => { const buttonText = popupEditProfilePhoto.submitButton.textContent; popupImageAdd.submitButton.textContent = "Сохранение..." api.postCardApi(formData) .then((result) =>{ const card = createCard(result, popapImageView, popupPhotoDelete); const cardElement = card.generateCard(); cardListSection.addItem(cardElement); /// Вызов функции добавления popupImageAdd.close(); }) .catch((err) =>{ console.log('Какая то ошибка'+ err) }) .finally(() =>{ popupImageAdd.submitButton.textContent = buttonText; }) } }, POPUP_ADD_CARD_ELEMENT) // создание объекта редактирования фото профиля const popupEditProfilePhoto = new PopupWithForm({ validatorForm: formEditIconProfile, handleFormSubmit: (formData) => { const buttonText = popupEditProfilePhoto.submitButton.textContent; popupEditProfilePhoto.submitButton.textContent = "Сохранение..." api.sendUserPhoto(formData.link) .then((result) => { userInfo.setUserInfo(result.name, result.about, result.avatar, result.id) popupEditProfilePhoto.close() }) .catch((err) => { console.log(err); }) .finally(() => { popupProfileEdit.submitButton.textContent = buttonText; }); } }, POPUP_PHOTO_EDIT_PROFILE); // создание объекта редактирования профиля const popupProfileEdit = new PopupWithForm({ validatorForm : formEditValidator, handleFormSubmit: (formData) =>{ const buttonText = popupProfileEdit.submitButton.textContent; popupProfileEdit.submitButton.textContent = "Сохранение..." api.getUserEdit(formData.name, formData.description) .then((result) =>{ userInfo.setUserInfo(result.name, result.about, result.avatar, result.id) popupProfileEdit.close(); }) .catch((err) =>{ console.log('Опять накосячил'+ err) }) .finally(() =>{ popupProfileEdit.submitButton.textContent = buttonText; }) } },POPUP_EDIT_PROFILE); profileButtonEdit.addEventListener('click', () =>{ popupProfileEdit.open(); const information = userInfo.getUserInfo(); profileName.value = information.name; formTitle.value = information.description; }); editButtonEditEmpty.addEventListener('click', () => { popupImageAdd.open() }); avatarPhoto.addEventListener('click', () => { popupEditProfilePhoto.open() }); popapImageView.setEventListeners(); popupProfileEdit.setEventListeners(); popupImageAdd.setEventListeners(); popupEditProfilePhoto.setEventListeners(); popupPhotoDelete.setEventListeners();
import React from 'react'; import PropTypes from 'prop-types'; import * as Styled from './styles'; function ButtonDefault({ children, loading, ...options }) { return ( <Styled.Button {...options}> {loading ? <i className="fas fa-circle-notch fa-spin" /> : children} </Styled.Button> ); } ButtonDefault.propTypes = { children: PropTypes.any, loading: PropTypes.bool, }; ButtonDefault.defaultProps = { children: null, loading: false, }; export default ButtonDefault;
const find = require('./find'); const sanitizeQuery = require('./utils/sanitizeQuery'); /** * A wrapper around `find()` that make it easy to implement a basic HTTP API using Express. So your * user can call "/list?limit=1&fields=_id,name" and the querystring parameters will be passed * to this method on the Express request object. * * @param {ExpressRequest} req An express request object with the following on the querystring: * -limit: If a numeric string, passed to `find()` as the limit. If limit also passed in params * then this value cannot exceed it. * -next: If a non-empty string, passed to `find()` as the next cursor. * -previous: If a non-empty string, passed to `find()` as the previous cursor. * -fields: If a non-empty string, used to limit fields that are returned. Multiple fields * can be specified as a comma-delimited list. If field name used is not in params.fields, * it will be ignored. * @param {MongoCollection} collection A collection object returned from the MongoDB library's * or the mongoist package's `db.collection(<collectionName>)` method. * @param {Object} params See documentation for `find()`, plus these options: * -overrideFields: an object containing fields that should override fields from the querystring, e.g. * {_id: 0} or {internalField: 1}. We only support field exclusion for _id, as we expect whitelists * for fields from both params.fields and params.overrideFields. */ module.exports = async function findWithReq(req, collection, params) { params = sanitizeQuery(req.query, params); return find(collection, params); };
$(document).ready(function () { $("form").submit(function(e) { e.preventDefault(); var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; var searchWord = document.getElementById("query").value; var flickrOptions = { tags: searchWord, format: "json" }; function displayPhotos(data) { var photoHTML = '<ul style="list-style-type: none;">'; $.each( data.items, function (i, photo) { photoHTML += '<li class="awesomePhoto">'; photoHTML += '<a href="' + photo.link + '" class="image">'; photoHTML += '<img src="' + photo.media.m + '"></a></li>'; }); photoHTML += '</ul>'; $('#photos').html(photoHTML); var container = $('#photos').isotope({ itemSelector: '.awesomePhoto', layoutMode: 'fitRows' }); container.imagesLoaded ( function() { $("#photos").isotope("reloadItems"); container.isotope({ layoutMode:'fitRows', itemSelector: '.awesomePhoto'}); }); }; $.getJSON(flickrAPI, flickrOptions, displayPhotos); }); });
'use strict'; /** * @ngdoc overview * @name snaprOrgngApp * @description * # snaprOrgngApp * * Main module of the application. */ angular .module('snaprOrgngApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'hc.marked' ]) .config(function (markedProvider) { markedProvider.setOptions({ gfm: true, tables: true }); /* markedProvider.setRenderer({ link: function(href, title, text) { return "<a href='" + href + "'" + (title ? " title='" + title + "'" : '') + " target='_blank'>" + text + "</a>"; } }); */ }) .config(function ($routeProvider, $windowProvider) { var $window = $windowProvider.$get(); $routeProvider .when('/:locale/main', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .when('/:locale/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl', controllerAs: 'about' }) .when('/:locale/contact', { templateUrl: 'views/contact.html', controller: 'ContactCtrl', controllerAs: 'contact' }) .when('/:locale/roadmap', { templateUrl: 'views/roadmap.html', controller: 'RoadmapCtrl', controllerAs: 'roadmap' }) .when('/:locale/mission', { templateUrl: 'views/mission.html', controller: 'MissionCtrl', controllerAs: 'mission' }) .otherwise({ redirectTo: '/' + ($window.navigator.language || $window.navigator.userLanguage || 'en-GB') + '/main' }); });
export const GetContents = (hourlist,id ) => { return { type: 'GetContents', content:hourlist[id], show:true } };
var table = module.exports = require('azure-mobile-apps').table(); table.read(function (context) { //Si no hay login solo vemos lo publico if (!context.user) { var query = { sql: "select * FROM Notices n where n.ispublic = 'true' order by createdat desc" }; return context.data.execute(query); } else { query = { sql: "select * FROM Notices n where n.ispublic = 'true' or authorid = '"+ context.user.id +"' order by createdat desc" }; return context.data.execute(query); } });
init(); var histviztab; var current_screenshot; var metatags = new Object(); var webtags = new HARDWEBTAGS(); function init() { console.log("HistViz init()"); chrome.browserAction.onClicked.addListener(startHistViz); chrome.extension.onRequest.addListener(function (request, sender, sendResponse) { metatags[request.url] = request.tags; console.log("Received tags from page:"+request); }); } function startHistViz(tab) { // extract keywords from the current page histviztab = null; current_screenshot = null; chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT}, function(tabs) { var srctab = tabs[0]; var title = srctab.title; console.log("Current Window is URL="+srctab.url+", Title="+title); var domain = srctab.url.split("/")[2]; chrome.tabs.captureVisibleTab(function(dataurl) { current_screenshot = dataurl; chrome.tabs.create({url:chrome.extension.getURL("graph_test.html"), index:srctab.index+1}, function(tab) { histviztab = tab; var tags = webtags.lookup(domain); if (metatags.hasOwnProperty(srctab.url)) { tags = tags.concat(metatags[srctab.url]); } console.log("Created viz @"+srctab.url); console.log(tags); chrome.tabs.sendRequest(histviztab.id, {receiver:'rootScreenshot', screenshot:current_screenshot }); chrome.tabs.sendRequest(histviztab.id, { receiver:'initialKeywords', root: true, domain: domain, title: title, url: srctab.url, tags: tags, screenshot: current_screenshot}); }); }); }); } //DEPRECATED function searchDeliciousUrl(domain, title, url) { function parseDomForTags(dom) { var tagStr = ""; var taglinks = $("a[rel='tag']",dom); //console.log(taglinks) if (taglinks.length>0) { tagStr = taglinks[0].text; } for (var i=1; i<taglinks.length; i++) { var taglink = taglinks[i].text; if (taglink != "") { tagStr = tagStr + " " + taglink; } } var regex = /[^a-z0-9 ]/gi; title = title.replace(regex, ""); var titleArr = title.split(" "); console.log(titleArr); for (var i=0;i<titleArr.length;i++) { if (titleArr[i] != "") { tagStr = titleArr[i] + " " + tagStr; } } console.log(tagStr); chrome.tabs.sendRequest(histviztab.id, {receiver:'initialKeywords', root: true, domain: domain, title: title, url: url, tags: tagStr, screenshot: current_screenshot}); } var deliciousUrl = "http://delicious.com/url/"+domain; console.log("Retrieving tags from "+deliciousUrl) $.get(deliciousUrl, {}, parseDomForTags); }
import { FetchService } from '../../services'; export async function userLogin(fnId, username, password) { const url = `/x?fnid=${fnId}&u=${username}&p=${password}`; return FetchService.get(url); } export async function getUser(username) { const url = `/user?id=${username}`; return FetchService.get(url); }
var width; var height; var map; var textures; var scrollPosition = Vector2.zero; function Start () { textures = new Texture[8]; textures[0] = Resources.Load("coast") as Texture; textures[1] = Resources.Load("desert") as Texture; textures[2] = Resources.Load("forest") as Texture; textures[3] = Resources.Load("grass") as Texture; textures[4] = Resources.Load("mountain") as Texture; textures[5] = Resources.Load("ocean") as Texture; textures[6] = Resources.Load("river") as Texture; Debug.Log("Whoo"); width = GetComponent("MapGenerator").map_width; height = GetComponent("MapGenerator").map_height; map = new Array(width); for (var i = 0; i < width; i++){ map[i] = new Array(height); } var biome; for (var x = 0; x < width; x++){ for (var y = 0; y < height; y++){ map[x][y] = GetComponent("MapGenerator").TileBiome(x,y); //Debug.Log(x + ", " + y + ": " + map[x][y]); } } } function OnGUI(){ scrollPosition = GUI.BeginScrollView(new Rect(0,0,Screen.width,Screen.height),scrollPosition,new Rect(0,0,4*width,4*height)); for (var x = 0; x < width; x++){ for (var y = 0; y < height; y++){ GUI.DrawTexture(new Rect(4*x,4*y,4,4), textures[map[x][y]]); } } GUI.EndScrollView(); //GUI.DrawTexture(new Rect(0,0,16,16), textures[0]); } function Update () { if (Input.GetKeyDown(KeyCode.Return)){ width = GetComponent("MapGenerator").map_width; height = GetComponent("MapGenerator").map_height; for (var x = 0; x < width; x++){ for (var y = 0; y < height; y++){ map[x][y] = GetComponent("MapGenerator").TileBiome(x,y); //Debug.Log(x + ", " + y + ": " + map[x][y]); } } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SignAccessPlanController = exports.SetAccessPlanImageController = exports.RemoveAccessPlanController = exports.FindAccessPlanController = exports.AddAccessPlanController = void 0; const httpHelpers_1 = require("../../helpers/httpHelpers"); const Controller_1 = require("../../protocols/Controller"); class AddAccessPlanController extends Controller_1.Controller { constructor(addPlan, buildPlan) { super([ { param: "name" }, { param: "description", type: 'text' }, { param: "value", type: 'number' }, { param: "discount", type: 'number' }, { param: "cycle", type: 'number' }, { param: "access_key", type: 'number' }, ]); this.addPlan = addPlan; this.buildPlan = buildPlan; } async handler(req) { const plan = await this.addPlan.execute(req.body, req.params.id); var result = await this.buildPlan.execute(plan); return httpHelpers_1.OK(result); } } exports.AddAccessPlanController = AddAccessPlanController; class FindAccessPlanController extends Controller_1.Controller { constructor(findPlan, buildPlan) { super(); this.findPlan = findPlan; this.buildPlan = buildPlan; } async handler(req) { var plans = await this.findPlan.execute(req.params.id); var result = await this.buildPlan.execute(plans); return httpHelpers_1.OK(result); } } exports.FindAccessPlanController = FindAccessPlanController; class RemoveAccessPlanController extends Controller_1.Controller { constructor(removePlan) { super(); this.removePlan = removePlan; } async handler(req) { await this.removePlan.execute(req.params.id); return httpHelpers_1.OK(); } } exports.RemoveAccessPlanController = RemoveAccessPlanController; class SetAccessPlanImageController extends Controller_1.Controller { constructor(setImage, buildPlan) { super(); this.setImage = setImage; this.buildPlan = buildPlan; } async handler(req) { const updated = await this.setImage.execute(req.body.buffer, req.body.originalname, req.params.id); var result = await this.buildPlan.execute(updated); return httpHelpers_1.OK(result); } } exports.SetAccessPlanImageController = SetAccessPlanImageController; class SignAccessPlanController extends Controller_1.Controller { constructor(assignPlan) { super(); this.assignPlan = assignPlan; } async handler(req) { const order = await this.assignPlan.execute(req.body.user_id, req.params.id); return httpHelpers_1.OK(order); } } exports.SignAccessPlanController = SignAccessPlanController;
import {Actions} from "../../utils/consts"; const removeClocks = (clocks, index) => [...clocks.slice(0, index), ...clocks.slice(index + 1)]; const addClock = (clocks, timezone) => [...clocks, timezone]; const updateClock = (clocks, item) => [...clocks.slice(0, item.index), {timezone: item.timezone}, ...clocks.slice(item.index + 1)]; const reducer = (state, action) => { switch (action.type) { case Actions.ADD_CLOCK: return { ...state, clocks: addClock(state.clocks, action.payload) }; case Actions.UPDATE_CLOCK: return { ...state, clocks: updateClock(state.clocks, action.payload) }; case Actions.DELETE_CLOCK: return { ...state, clocks: removeClocks(state.clocks, action.payload) }; default: return state; } }; export default reducer;
import fetchData from "./fetch"; const apiKey = "79cd9ba3c0c6f51e69332a75e765e856"; export default function fetchCityById(id, setData) { fetchData( `https://api.openweathermap.org/data/2.5/weather?id=${id}&appid=${apiKey}&units=metric` ).then((city) => { if (city) { setData(city); } else { setData(null); } }); }
function Controller() { function joinGroup(_pkOrgGroups) { var dataTemp = { url: L("ws_groupjoin"), type: "GET", format: "JSON", data: { atoken: APP.getToken({ openLogin: false }), pkOrgGroups: _pkOrgGroups } }; APP.http.request(dataTemp, function(_result) { if (1 == _result._result) if (0 == _result._data.errorcode) { APP.optionbar.changeView(5); alert("You have joined a new group."); } else alert(_result._data.message); else alert("Internet connection error, please try again."); }); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "MyNeighborhoods/GroupList"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; $.__views.GroupList = Ti.UI.createView({ id: "GroupList" }); $.__views.GroupList && $.addTopLevelView($.__views.GroupList); $.__views.tempRow = Ti.UI.createTableViewRow({ height: 45, id: "tempRow" }); var __alloyId164 = []; __alloyId164.push($.__views.tempRow); $.__views.table = Ti.UI.createTableView({ data: __alloyId164, id: "table" }); $.__views.GroupList.add($.__views.table); exports.destroy = function() {}; _.extend($, $.__views); var APP = require("/core"); var args = arguments[0] || {}; args.toolBar.setTitle("Search List"); $.tempRow.height = $.tempRow.height + APP.fixSizeIos7(); for (var i = 0; args.params.data.length > i; i++) if (true == args.params.data[i].iscategory) $.table.appendRow({ title: args.params.data[i].name, color: "#136C8B", hasChild: true, leftImage: "/images/folder.png", data: args.params.data[i].data, iscategory: args.params.data[i].iscategory }); else { var row = Ti.UI.createTableViewRow({ hasChild: false, pkOrgGroups: args.params.data[i].pkOrgGroups, height: 35 }); row.add(Ti.UI.createLabel({ text: args.params.data[i].name, color: "#136C8B", left: 35, height: 35, width: Ti.UI.SIZE })); if (args.params.data[i].oglogo.length > 6 && 14 != i) { var img = Ti.UI.createImageView({ width: 25, hight: 25, image: args.params.data[i].oglogo.replace(/ /g, "%20"), left: 5 }); row.add(img); } $.table.appendRow(row); } $.table.addEventListener("click", function(_evt) { var selfRow; var selfRow = _evt.row; if (true == selfRow.iscategory) APP.openWindow({ controller: "MyNeighborhoods/GroupList", controllerParams: { data: selfRow.data, callback: function() {} } }); else { var notificationDialog = Ti.UI.createAlertDialog({ title: "Join Group", message: "Are you sure you want to join this Group?", buttonNames: [ "YES", "NO" ] }); notificationDialog.addEventListener("click", function(e) { 0 === e.index && joinGroup(selfRow.pkOrgGroups); }); notificationDialog.show(); } }); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
import withRobots from '../index' const robots = { userAgent: 'googlebot', allowPaths: ['foo', 'bar'], disallowPaths: ['fizz', 'buzz'], filename: 'overridden.txt' } describe('withRobots', () => { it('should return exportPathMap', () => { const nextConfig = withRobots() expect(typeof nextConfig.exportPathMap).toEqual('function') }) it('should set default options', () => { const nextConfig = withRobots() expect(nextConfig.robots.userAgent).toEqual('*') expect(nextConfig.robots.filename).toEqual('robots.txt') }) it('should override default options', () => { const nextConfig = withRobots({ robots: { ...robots, sitemap: { hostname: 'https://test.com/', filename: 'sitemap.xml' } } }) expect(nextConfig.robots.userAgent).toEqual('googlebot') expect(nextConfig.robots.filename).toEqual('overridden.txt') expect(nextConfig.robots.sitemap).toEqual({ hostname: 'https://test.com/', filename: 'sitemap.xml' }) }) it('should inherit settings from @newhighsco/next-plugin-sitemap', () => { const nextConfig = withRobots({ robots, sitemap: { hostname: 'https://inherit.com/', filename: 'inherit.xml' } }) expect(nextConfig.robots.sitemap).toEqual({ hostname: 'https://inherit.com/', filename: 'inherit.xml' }) }) })
/** * 所有js文件共享 */ //将图片转为base64 function convertImgToBase64(url, callback, outputFormat) { var canvas = document.createElement('canvas'),   ctx = canvas.getContext('2d'),   img = new Image; img.onload = function() {   canvas.height = img.height;   canvas.width = img.width;   ctx.drawImage(img, 0, 0);   var dataURL = canvas.toDataURL(outputFormat || 'image/jpeg');   callback.call(this, dataURL); canvas = null; }; img.src = url; } //将日期y.m.d转为日期y年m月d日 function dateArrToDate(date) { var dateArr = date.split("."); var y = dateArr[0]; var m = dateArr[1]; var d = dateArr[2]; return y + "年" + m + "月" + d + "日"; }
const router = require("express").Router(); const verify = require("./verifyToken"); const checkAccess = require("./checkAccess"); const MongoClient = require("mongodb").MongoClient; const nodemailer = require("nodemailer"); const dotenv = require("dotenv"); const Service = require("../model/Service"); const Lead = require("../model/Lead"); const leadStatus = require("../model/leadStatus"); const adminMangerAccess = require("./adminMangerAccess"); dotenv.config(); router.use(verify); const sendMail = async (subject, description) => { let transporter = nodemailer.createTransport({ service: "gmail", auth: { user: process.env.gmailUserName, pass: process.env.gmailPassword, }, }); console.log("Inside sendMail"); let mailOptions = { from: process.env.gmailUserName, to: process.env.admin, subject: subject, text: description, }; transporter.sendMail(mailOptions, (err, data) => { if (err) { console.log({ message: "Error Occurs", linkSent: false }); } else { console.log({ message: "Link Sent", linkSent: true }); } }); }; router.get("/dashboard", async (req, res) => {}); router.put("/provideAccess", adminMangerAccess, async (req, res) => {}); router.post("/createService", checkAccess, async (req, res) => { const service = new Service({ subject: req.body.subject, description: req.body.subject, status: req.body.status, }); try { const savedService = await service.save(); sendMail( "New Service Request", `A new service request is created with following details:${savedService}` ); res.send(savedService); } catch (err) { console.log(err); res.status(404).send(err); } }); router.put("/updateService", checkAccess, async (req, res) => { MongoClient.connect(process.env.DB_CONNECTION, function (err, db) { if (err) throw err; let dbo = db.db("akshay"); let ObjectId = require("mongodb").ObjectId; let id = req.body.id; let o_id = new ObjectId(id); const filter = { _id: o_id }; const update = { $set: { status: req.body.status } }; dbo .collection("services") .updateOne(filter, update, function (err, response) { if (err) { res.send(404).send(err); throw err; } console.log("Service Status Updated"); res.send("Service Status Updated"); }); }); }); router.get("/services", async (req, res) => { let response = await Service.find({}); res.send(response); }); router.post("/createLead", checkAccess, async (req, res) => { const lead = new Lead({ name: req.body.name, contact: req.body.contact, status: req.body.status, }); try { const savedLead = await lead.save(); sendMail( "New Lead Request", `A new lead request is created with following details:${savedLead}` ); res.send(savedLead); } catch (err) { console.log(err); res.status(404).send(err); } }); router.put("/updateLead", checkAccess, (req, res) => { MongoClient.connect(process.env.DB_CONNECTION, function (err, db) { if (err) throw err; let dbo = db.db("akshay"); let ObjectId = require("mongodb").ObjectId; let id = req.body.id; let o_id = new ObjectId(id); const filter = { _id: o_id }; const update = { $set: { status: req.body.status } }; dbo.collection("leads").updateOne(filter, update, function (err, response) { if (err) { res.send(404).send(err); throw err; } console.log("Lead Status Updated"); res.send("Lead Status Updated"); }); }); }); router.get("/leads", async (res, req) => { let response = await Lead.find({}); res.send(response); }); router.put("/updateLead/contact", checkAccess, (req, res) => {}); module.exports = router;
export const DATA_LOADING= 'DATA_LOADING'; export const GET_WEATHER_DATA= 'GET_WEATHER_DATA'; export const ADD_CITY= 'ADD_CITY';
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); var Cache = require('local-cache'); var pkg = require('./package.json'); var pkg_mps = require('./routes/pkg_mps.json'); //初始化cms-api var api = require('local-cms-api'); api.config(pkg.api,pkg.cache); app.locals.pkg_json = pkg; app.locals.pkg_mps = pkg_mps; app.locals.cacheMin = 4; //加头部广告 app.locals.logoAd = null; app.use(function(req, res, next){ //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('logoAd',function(err,logoAd){ if(err) { } if(logoAd){ try{ logoAd = JSON.parse(logoAd); } catch (e) {} } app.locals.logoAd = logoAd; next(); }); }); app.use(function(req, res, next){ if(app.locals.logoAd){ next(); }else{ request(pkg.use_urls.www_url+'/logoAd',function(error,response,body){ if(!error && response.statusCode === 200) { var info = JSON.parse(body); app.locals.logoAd = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'logoAd', value : body, left : 60*app.locals.cacheMin },function(err){ if(err){ console.log(err); } }); } next(); }); } }); //头部第二行数据 app.locals.header_www = null; app.use(function(req, res, next){ //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('header_www',function(err,header_www){ if(err) { } if(header_www){ try{ header_www = JSON.parse(header_www); } catch (e) {} }else{ } app.locals.header_www = header_www; next(); }); }); app.use(function(req, res, next){ if(app.locals.header_www){ next(); }else{ request(pkg.use_urls.www_url+'/modules/getmodulehtml?module_id=cshop-com_self_defined&positionId=200030&pageFileName=header',function(error,response,data2){ if(!error && response.statusCode === 200) { var data2_str = data2; if(data2.substr(0,13)=='jsonpCallback'){ data2_str =data2.substring(14,data2.lastIndexOf(")")); } var info = JSON.parse(data2_str); app.locals.header_www = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'header_www', value : data2_str, left : 60*app.locals.cacheMin },function(err){ if(err){ console.log(err); } }); } next(); }); } }); app.locals.js_ad_lady_mx_top_banner = null; app.use(function(req, res, next){ var data2 = null; //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('js_ad_lady_mx_top_banner',function(err,js_ad_lady_mx_top_banner){ if(err) { } if(js_ad_lady_mx_top_banner){ try{ js_ad_lady_mx_top_banner = JSON.parse(js_ad_lady_mx_top_banner); } catch (e) {} }else{ } app.locals.js_ad_lady_mx_top_banner = js_ad_lady_mx_top_banner; next(); }); }); app.use(function(req, res, next){ if(app.locals.js_ad_lady_mx_top_banner){ next(); }else{ request(pkg.use_urls.www_url+'/singleAd?identifier=lady_mx_top_banner',function(error,response,data2){ if(!error && response.statusCode === 200) { var data2_str = data2; if(data2.substr(0,13)=='jsonpCallback'){ data2_str =data2.substring(14,data2.lastIndexOf(")")); } var info = JSON.parse(data2_str); app.locals.js_ad_lady_mx_top_banner = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'js_ad_lady_mx_top_banner', value : data2_str, left : 60*app.locals.cacheMin },function(err){ if(err){ console.log(err); } }); } next(); }); } }); app.locals.js_ad_lady_detail_right_bnr = null; app.use(function(req, res, next){ var data2 = null; //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('js_ad_lady_detail_right_bnr',function(err,js_ad_lady_detail_right_bnr){ if(err) { } if(js_ad_lady_detail_right_bnr){ try{ js_ad_lady_detail_right_bnr = JSON.parse(js_ad_lady_detail_right_bnr); } catch (e) {} }else{ } app.locals.js_ad_lady_detail_right_bnr = js_ad_lady_detail_right_bnr; next(); }); }); app.use(function(req, res, next){ if(app.locals.js_ad_lady_detail_right_bnr){ next(); }else{ request(pkg.use_urls.www_url+'/singleAd?identifier=lady_detail_right_bnr',function(error,response,data2){ if(!error && response.statusCode === 200) { var data2_str = data2; if(data2.substr(0,13)=='jsonpCallback'){ data2_str =data2.substring(14,data2.lastIndexOf(")")); } var info = JSON.parse(data2_str); app.locals.js_ad_lady_detail_right_bnr = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'js_ad_lady_detail_right_bnr', value : data2_str, left : 60*app.locals.cacheMin },function(err){ if(err){ console.log(err); } }); } next(); }); } }); app.locals.js_ad_lady_detail_middle_bnr = null; app.use(function(req, res, next){ var data2 = null; //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('js_ad_lady_detail_middle_bnr',function(err,js_ad_lady_detail_middle_bnr){ if(err) { } if(js_ad_lady_detail_middle_bnr){ try{ js_ad_lady_detail_middle_bnr = JSON.parse(js_ad_lady_detail_middle_bnr); } catch (e) {} }else{ } app.locals.js_ad_lady_detail_middle_bnr = js_ad_lady_detail_middle_bnr; next(); }); }); app.use(function(req, res, next){ if(app.locals.js_ad_lady_detail_middle_bnr){ next(); }else{ request(pkg.use_urls.www_url+'/singleAd?identifier=lady_detail_middle_bnr',function(error,response,data2){ if(!error && response.statusCode === 200) { var data2_str = data2; if(data2.substr(0,13)=='jsonpCallback'){ data2_str =data2.substring(14,data2.lastIndexOf(")")); } var info = JSON.parse(data2_str); app.locals.js_ad_lady_detail_middle_bnr = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'js_ad_lady_detail_middle_bnr', value : data2_str, left : 60*app.locals.cacheMin },function(err){ if(err){ console.log(err); } }); } next(); }); } }); // ads api data app.locals.api_ads_lady_top_banner = null; app.use(function(req, res, next){ //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('api_ads_lady_top_banner',function(err,result){ if(result){ result = JSON.parse(result); } app.locals.api_ads_lady_top_banner = result; next(); }); }); app.use(function(req, res, next){ if(app.locals.api_ads_lady_top_banner){ next(); }else{ request(pkg.use_urls.api_ads_url+'/r.do?adp=23',function(error,response,body){ if(!error && response.statusCode === 200) { var info = JSON.parse(body); app.locals.api_ads_lady_top_banner = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'api_ads_lady_top_banner', value : body, left : 60*app.locals.cacheMin },function(err){ }); } next(); }); } }); app.locals.api_ads_lady_article_right = null; app.use(function(req, res, next){ //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('api_ads_lady_article_right',function(err,result){ if(result){ result = JSON.parse(result); } app.locals.api_ads_lady_article_right = result; next(); }); }); app.use(function(req, res, next){ if(app.locals.api_ads_lady_article_right){ next(); }else{ request(pkg.use_urls.api_ads_url+'/r.do?adp=22',function(error,response,body){ if(!error && response.statusCode === 200) { var info = JSON.parse(body); app.locals.api_ads_lady_article_right = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'api_ads_lady_article_right', value : body, left : 60*app.locals.cacheMin },function(err){ }); } next(); }); } }); app.locals.api_ads_lady_article_middle = null; app.use(function(req, res, next){ //判断缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.get('api_ads_lady_article_middle',function(err,result){ if(result){ result = JSON.parse(result); } app.locals.api_ads_lady_article_middle = result; next(); }); }); app.use(function(req, res, next){ if(app.locals.api_ads_lady_article_middle){ next(); }else{ request(pkg.use_urls.api_ads_url+'/r.do?adp=24',function(error,response,body){ if(!error && response.statusCode === 200) { var info = JSON.parse(body); app.locals.api_ads_lady_article_middle = info; //存缓存 var cache = new Cache(pkg.cache.host,pkg.cache.port,'lady'); cache.set({ key : 'api_ads_lady_article_middle', value : body, left : 60*app.locals.cacheMin },function(err){ }); } next(); }); } }); //设置模板引擎为handlebars var hbs = require('express-hbs'); //注册一个比较判断 hbs.registerHelper("compareEq",function(v1,v2,options){ if(v1==v2){ //满足添加继续执行 return options.fn(this); }else{ //不满足条件执行{{else}}部分 return options.inverse(this); } }); hbs.registerHelper('writeJs', function(src_url,ver,str_from,str_to) { var out = ""; if(src_url){ if(str_from){ out += str_from } out = out + '<script type="text/javascript" src="' + src_url + '?v=' + ver + '"></script>'; if(str_to){ out += str_to } } return out + ""; }); //注册end app.engine('html',hbs.express3({ partialsDir : __dirname + "/views/partials", defaultLayout : __dirname + "/views/layouts/default", layoutsDir : __dirname + "/views/layouts", extname:".html" })); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.set('x-powered-by',false); //设置资源路径 var resourceBaseUrl = ''; var env =app.get('env'); if(env === 'prod') { app.locals.IS_PROD = true; resourceBaseUrl = pkg.use_urls.staticcdn_url + "/proj/" + pkg.name; } app.locals.RESOURCE_BASE_URL = resourceBaseUrl; app.locals.ASSETS_MAP= require('./public/build/map.json'); //获取并设置版本号 var Cache = require('local-cache'); var cache = new Cache(pkg.cache.host,pkg.cache.port); cache.nget('_pre_version',function(err,data){ if(err) { throw err; } if(data) { var y = new Date().getFullYear(); app.locals.VERSION = y + "" + data; }else { app.locals.VERSION = new Date().getTime(); } }); app.use(favicon()); app.use(favicon(path.join(__dirname,'/public/build/images/favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, '/public/build'))); //设置debug调试( b5m.com?debug=true )为调试状态 app.use(function(req,res,next){ app.locals.IS_DEBUG = req.query.debug; next(); }); //routes var routes = require('./routes/entry'); var util = require('util'); if(routes) { for(var k in routes){ app.use(k,routes[k]); } }else { app.use(function(req,res,next){ res.send('<h1>hello world</h1>'); next(); }); } /// 捕获404错误并转到错误处理 app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// 错误处理 // 开发和stage环境错误处理 // 会输出stacktraces if (app.get('env') === 'development' || app.get('env') === 'stage') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // 生产环境错误处理 // 不会输出stacktraces app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); //注册handles的helper require('./lib/hbs-helper'); module.exports = app;
function ThreeDimContext(context) { this.transformation = null; this.context = context; this.strokeStyle = "rgb(0, 0, 0)"; this.fillStyle = "rgb(0, 0, 0)"; this.lineWidth = 1; } ThreeDimContext.prototype.beginPath = function() { this.context.beginPath(); } ThreeDimContext.prototype.closePath = function() { this.context.closePath(); } ThreeDimContext.prototype.setTransformation = function(transformation) { this.transformation = transformation; } ThreeDimContext.prototype.goToOrigin = function() { this.moveTo(0, 0, 0); } ThreeDimContext.prototype.lineTo = function(x, y, z) { let point = [x, y, z]; let transformedPoint = m4.transformPoint(this.transformation, point); this.context.lineTo(transformedPoint[0], transformedPoint[1]); } ThreeDimContext.prototype.moveTo = function(x, y, z) { let point = [x, y, z]; let transformedPoint = m4.transformPoint(this.transformation, point); this.context.moveTo(transformedPoint[0], transformedPoint[1]); } ThreeDimContext.prototype.fillRect = function(x, y, z, width, height) { this.context.fillStyle = this.fillStyle; //bottom left point this.context.beginPath(); this.moveTo(x, y, z); // bottom right point this.lineTo(x + width, y, z); // top right point this.lineTo(x + width, y + height, z); // top left path this.lineTo(x, y + height, z); this.context.closePath(); this.context.fill(); } ThreeDimContext.prototype.Rect = function(x, y, z, width, height) { this.context.strokeStyle = this.strokeStyle; // bottom left point this.context.beginPath(); this.moveTo(x, y, z); // bottom right point this.lineTo(x + width, y, z); // top right point this.lineTo(x + width, y + height, z); // top left path this.lineTo(x, y + height, z); this.context.closePath(); this.context.stroke(); } ThreeDimContext.prototype.stroke = function() { this.context.lineWidth = this.lineWidth; this.context.strokeStyle = this.strokeStyle; this.context.stroke(); } ThreeDimContext.prototype.clearRect = function(x, y, height, width) { this.context.clearRect(x, y, height, width); }
var ntk = require('../lib'); var width = 300; var height = 300; var angle = 0; var model = require('./teapot.json'); function makeList(gl, callback) { gl.GenLists(1, function(err, list) { listId = list; gl.NewList(list, gl.COMPILE); gl.Begin(gl.TRIANGLES); for (var i=0; i < model.indices.length; i+=3) { for (var t=i; t < i+3; t++) { tr = model.indices[t]; var x = model.vertexNormals[tr*3 + 0]; var y = model.vertexNormals[tr*3 + 1]; var z = model.vertexNormals[tr*3 + 2]; gl.Normal3f(x, y, z); var x = model.vertexPositions[tr*3 + 0]; var y = model.vertexPositions[tr*3 + 1]; var z = model.vertexPositions[tr*3 + 2]; gl.Vertex3f(x, y, z); } } gl.End(); gl.EndList(); callback(list); }); } var scale = 0.1; var rotx = 0; var roty = 0; var lightangle = 0; function draw(gl, list) { { var pos = [5.0, Math.sin(lightangle)*100, Math.cos(lightangle)*100.0, 0.0] var red = [ 0.8, 0.1, 0.0, 1.0 ]; var green = [ 0.0, 0.8, 0.2, 1.0 ]; var blue = [ 0.2, 0.2, 1.0, 1.0 ]; gl.Lightfv(gl.LIGHT0, gl.POSITION, pos); gl.Enable(gl.CULL_FACE); gl.Enable(gl.LIGHTING); gl.Enable(gl.LIGHT0); gl.Enable(gl.DEPTH_TEST); gl.Enable(gl.NORMALIZE); gl.ShadeModel(gl.SMOOTH); gl.Enable(gl.BLEND); gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.Viewport(0, 0, width, height); gl.MatrixMode(gl.PROJECTION); gl.LoadIdentity(); if (width < height) gl.Frustum(-1.0, 1.0, -height/width, height/width, -35.0, 20); else gl.Frustum(-width/height, width/height, -1, 1, -35.0, 20); gl.MatrixMode(gl.MODELVIEW); gl.LoadIdentity(); gl.ClearColor(0.3,0.3,0.3,0.0); gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.Scalef(scale, scale, scale); gl.Color3f(1, 0, 0); gl.Rotatef(rotx, 0, 1, 0); gl.Rotatef(-roty, 1, 0, 0); gl.CallList(list) gl.SwapBuffers();} } ntk.createClient(function(err, app) { var wnd = app.createWindow({title: "Close me!", x: 100, y: 100, width: 300, height: 300}); wnd.map(); var gl = wnd.getContext('opengl'); gl.Enable(gl.POINT_SMOOTH); makeList(gl, function(list) { draw(gl, list); setInterval(function() { lightangle += 0.1; draw(gl, list); }, 50); wnd.on('resize', function(ev) { width = ev.width; height = ev.height; draw(gl, list); }).on('mousemove', function(ev) { rotx = ev.x; roty = ev.y; draw(gl, list); }).on('mousedown', function(ev) { if (ev.keycode == 4) scale *= 0.9; else scale /= 0.9; draw(gl, list); }); }); });
const net = require('net'); const ip = require('ip'); const Version = 0x05; const ErrVersion = new Error('invalid socks version'); const MethodNotRequired = 0x00; const MethodUsernamePassword = 0x02; const ReplySucceed = 0x00; const ReplyGeneralFailure = 0x01; const ReplyConnectionNotAllowed = 0x02; const ReplyNetworkUnreachable = 0x03; const ReplyHostUnreachable = 0x04; const ReplyConnectionRefused = 0x05; const ReplyTTLExpired = 0x06; const ReplyCommandNotSupported = 0x07; const ReplyAddressNotSupported = 0x08; const CmdConnect = 0x01; // const CmdBind = 0x02; // const CmdUDP = 0x03; const AddrTypeIPv4 = 0x01; const AddrTypeDN = 0x03; const AddrTypeIPv6 = 0x04; const AuthSuccess = 0x00; const AuthFailure = 0xff; /** * @param {socks5.reply} code * @return {string} */ const replyString = function(code) { switch (code) { case ReplySucceed: return 'succeeded'; case ReplyGeneralFailure: return 'general SOCKS server failure'; case ReplyConnectionNotAllowed: return 'connection not allowed by ruleset'; case ReplyNetworkUnreachable: return 'network unreachable'; case ReplyHostUnreachable: return 'host unreachable'; case ReplyConnectionRefused: return 'connection refused'; case ReplyTTLExpired: return 'TTL expired'; case ReplyCommandNotSupported: return 'command not supported'; case ReplyAddressNotSupported: return 'address type not supported'; default: return `unknown code= ${code}`; } }; /* +----+----------+----------+ |VER | NMETHODS | METHODS | +----+----------+----------+ | 1 | 1 | 1 to 255 | +----+----------+----------+ */ /** * @param {bool} auth * @return {Buffer} */ const createMethodMessage = function(auth) { if (auth) { return Buffer.from([Version, 2, MethodUsernamePassword, MethodNotRequired]); } return Buffer.from([Version, 1, MethodNotRequired]); }; /** * @param {string} chunk * @return {socks5.Method[] | undefined} */ const parseMethodMessage = function(chunk) { if (chunk.length < 2 || chunk.length < chunk[1] + 2) { return; } if (chunk[0] != Version) { throw ErrVersion; } const methods = []; for (let i = 0; i < chunk[1]; i++) { methods.push(chunk[i+2]); } return methods; }; /* +----+--------+ |VER | METHOD | +----+--------+ | 1 | 1 | +----+--------+ */ /** * @param {Method} method * @return {Buffer} */ const createMethodSelection = function(method) { return Buffer.from([Version, method]); }; /** * @param {Buffer} chunk * @return {socks5.Method | undefined} */ const parseMethodSelection = function(chunk) { if (chunk.length < 2) { return; } if (chunk[0] != Version) { throw ErrVersion; } return chunk[1]; }; /* +----+-----+-------+------+----------+----------+ |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | +----+-----+-------+------+----------+----------+ | 1 | 1 | X'00' | 1 | Variable | 2 | +----+-----+-------+------+----------+----------+ */ /** * @param {string} host * @param {number} port * @return {Buffer} */ const createRequest = function(host, port) { const ipType = net.isIP(host); const addrLen = ipType === 0 ? host.length : (ipType === 4 ? 4 : 16); const buf = Buffer.alloc(6 + addrLen + (ipType === 0 ? 1 : 0)); buf[0] = Version; buf[1] = CmdConnect; buf[2] = 0x00; switch (ipType) { case 4: buf[3] = AddrTypeIPv4; ip.toBuffer(host).copy(buf, 4); buf.writeUInt16BE(port, 8); break; case 6: buf[3] = AddrTypeIPv6; ip.toBuffer(host).copy(buf, 4); buf.writeUInt16BE(port, 20); break; default: buf[3] = AddrTypeDN; buf[4] = host.length; buf.write(host, 5); buf.writeUInt16BE(port, 5 + host.length); } return buf; }; /** * @param {Buffer} chunk * @return {object | undefined} addr * @return {number} addr.cmd * @return {string} addr.host * @return {number} addr.port */ const parseRequest = function(chunk) { if (chunk.length < 5) { return; } if (chunk[0] != Version) { throw ErrVersion; } const cmd = chunk[1]; switch (chunk[3]) { case AddrTypeIPv4: if (chunk.length < 10) { return; } return { cmd: cmd, host: ip.toString(chunk.slice(4, 8)), port: chunk.readUInt16BE(8), }; case AddrTypeIPv6: if (chunk.length < 22) { return; } return { cmd: cmd, host: ip.toString(chunk.slice(4, 20)), port: chunk.readUInt16BE(20), }; case AddrTypeDN: if (chunk.length < chunk[4] + 7) { return; } return { cmd: cmd, host: chunk.slice(5, 5 + chunk[4]).toString(), port: chunk.readUInt16BE(5 + chunk[4]), }; } throw new Error('invalid request'); }; /* +----+-----+-------+------+----------+----------+ |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | +----+-----+-------+------+----------+----------+ | 1 | 1 | X'00' | 1 | Variable | 2 | +----+-----+-------+------+----------+----------+ */ /** * @param {bool} isSuccessful * @param {string=} host * @param {number=} port * @return {Buffer} */ const createReply = function(isSuccessful, host, port) { if (!isSuccessful) { const buf = Buffer.alloc(10); buf[0] = Version; buf[1] = ReplyConnectionNotAllowed; buf[2] = AddrTypeIPv4; return buf; } const ipType = net.isIP(host); const addrLen = ipType === 0 ? host.length : (ipType === 4 ? 4 : 16); const buf = Buffer.alloc(6 + addrLen + (ipType === 0 ? 1 : 0)); buf[0] = Version; buf[1] = ReplySucceed; buf[2] = 0x00; switch (ipType) { case 4: buf[3] = AddrTypeIPv4; ip.toBuffer(host).copy(buf, 4); buf.writeUInt16BE(port, 8); break; case 6: buf[3] = AddrTypeIPv6; ip.toBuffer(host).copy(buf, 4); buf.writeUInt16BE(port, 20); break; default: buf[3] = AddrTypeDN; buf[4] = host.length; buf.write(host, 5); buf.writeUInt16BE(port, 5 + host.length); } return buf; }; /** * @param {Buffer} chunk * @return {object | undefined} reply * @return {number} reply.reply * @return {string | undefined} reply.host * @return {number | undefined} reply.port */ const parseReply = function(chunk) { if (chunk.length < 5) { return; } if (chunk[0] != Version) { throw ErrVersion; } const reply = chunk[1]; if (reply != ReplySucceed) { return {reply: reply}; } switch (chunk[3]) { case AddrTypeIPv4: if (chunk.length < 10) { return; } return { reply: reply, host: ip.toString(chunk.slice(4, 8)), port: chunk.readUInt16BE(8), }; case AddrTypeIPv6: if (chunk.length < 22) { return; } return { reply: reply, host: ip.toString(chunk.slice(4, 20)), port: chunk.readUInt16BE(20), }; case AddrTypeDN: if (chunk.length < chunk[4] + 7) { return; } return { reply: reply, host: (chunk.slice(5, 5 + chunk[4])).toString(), port: chunk.readUInt16BE(5 + chunk[4]), }; } return {reply: reply}; }; /* +----+------+----------+------+----------+ |VER | ULEN | UNAME | PLEN | PASSWD | +----+------+----------+------+----------+ | 1 | 1 | 1 to 255 | 1 | 1 to 255 | +----+------+----------+------+----------+ */ /** * @param {string} username * @param {string} password * @return {Buffer} */ const createAuthMessage = function(username, password) { if (!(username) || !(password)) { throw new Error('invalid username or password'); } const buf = Buffer.alloc(3 + username.length + password.length); buf[0] = Version; buf[1] = username.length; buf.write(username, 2); const i = 2 + username.length; buf[i] = password.length; buf.write(password, i+1); return buf; }; /** * @param {Buffer} chunk * @return {object | undefined} auth * @return {string} auth.username * @return {string} auth.password */ const parseAuthMessage = function(chunk) { if (chunk.length < 2) { return; } if (chunk[0] != Version) { return ErrVersion; } if (chunk.length < 2 + chunk[1]) { return; } const i = 2 + chunk[1]; const username = chunk.toString('utf8', 2, i); if (chunk.length < chunk[i] + i + 1) { return; } const password = chunk.toString('utf8', i+1); return {username: username, password: password}; }; /* +----+--------+ |VER | STATUS | +----+--------+ | 1 | 1 | +----+--------+ */ /** * @param {bool} isSuccessful * @return {Buffer} */ const createAuthReply = function(isSuccessful) { if (isSuccessful) { return Buffer.from([Version, AuthSuccess]); } return Buffer.from([Version, AuthFailure]); }; /** * @param {Buffer} chunk * @return {bool | undefined} */ const parseAuthReply = function(chunk) { if (chunk.length < 2) { return; } if (chunk[0] != Version) { return ErrVersion; } return chunk[1] === AuthSuccess; }; module.exports = { MethodNotRequired, MethodUsernamePassword, CmdConnect, ReplySucceed, replyString, createMethodMessage, parseMethodMessage, createMethodSelection, parseMethodSelection, createRequest, parseRequest, createReply, parseReply, createAuthMessage, parseAuthMessage, createAuthReply, parseAuthReply, };
'use strict'; module.exports = { p1: { power: '3.3v' }, p2: { power: '5v' }, p3: { gpio: 2 }, p4: { power: '5v' }, p5: { gpio: 3 }, p6: { power: 'ground' }, p7: { gpio: 4 }, p8: { gpio: 14, uart: { type: 'tx', index: 0 } }, p9: { power: 'ground' }, p10: { gpio: 15, uart: { type: 'rx', index: 0 } }, p11: { gpio: 17, pwm: 0 }, p12: { gpio: 18, pwm: 1 }, p13: { gpio: 27, pwm: 2 }, p14: { power: 'ground' }, p15: { gpio: 22, pwm: 3 }, p16: { gpio: 23, pwm: 4 }, p17: { power: '3.3v' }, p18: { gpio: 24, pwm: 5 }, p19: { gpio: 10 }, p20: { power: 'ground' }, p21: { gpio: 9 }, p22: { gpio: 25, pwm: 6 }, p23: { gpio: 11 }, p24: { gpio: 8 }, p25: { power: 'ground' }, p26: { gpio: 7 }, p29: { gpio: 5 }, p30: { power: 'ground' }, p31: { gpio: 6 }, p32: { gpio: 12 }, p33: { gpio: 13 }, p34: { power: 'ground' }, p35: { gpio: 19 }, p36: { gpio: 16 }, p37: { gpio: 26 }, p38: { gpio: 20 }, p39: { power: 'ground' }, p40: { gpio: 21 } };
var Marionette = require('backbone.marionette'); var Backbone = require('backbone'); var FormView = require('./form'); var ListView = require('./list'); var TwitModel = require('../models/twit'); var Layout = Marionette.View.extend({ el: '#app-hook', template: require('../templates/layout.html'), regions: { form: '.form', list: '.list' }, events: { 'click #btn-filter': 'filter' }, ui: { search: '#id_search' }, filter: function() { var tag = (this.getUI('search').val().trim() || '').replace("#", ""); if (tag) { this.listView.setFilter(function (child, index, collection) { return child.get('tag') == tag; }); } else { this.listView.removeFilter(); } this.listView.render(); }, onShow: function() { var formView = new FormView({model: this.model}); var listView = new ListView({collection: this.collection}); this.listView = listView; this.showChildView('form', formView); this.showChildView('list', listView); }, onChildviewAddTwit: function(child) { var txt = child.ui.text.val()||""; var _model = this.listView.createModel(txt); this.model.set(_model, { validate: true }); if (!this.model.validationError) { this.listView.addTwit(_model); } } }); module.exports = Layout;
var assert = require('assert'); var router = require('../../lib/router'); describe("Router", function () { it("Can create", function () { var r = router(); assert.ok(r); }); describe("Resolve", function (){ it("nothing", function() { var r = router(); var res = r.resolve("/"); assert.ok(res); assert.ok(res.node); assert.strictEqual(res.node.fullPath(),""); }); it("simple child", function() { var r = router().path("child") var res = r.resolve("/child"); assert.ok(res); assert.ok(res.node); assert.strictEqual(res.node.fullPath(),"/child"); }); it("chained childs", function() { var r = router().path("child").path("other").path("lol"); var res = r.resolve("/child/other/lol"); assert.ok(res); assert.ok(res.node); assert.strictEqual(res.node.fullPath(),"/child/other/lol"); }); it("chained childs but can stop before leaf", function() { var r = router().path("child").path("other").path("lol"); var res = r.resolve("/child/other"); assert.ok(res); assert.ok(res.node); assert.strictEqual(res.node.fullPath(),"/child/other"); }); it("Resolve failed", function () { var r = router().path("child").path("other").path("lol"); var res = r.resolve("/child/other2"); assert.strictEqual(res, null); }); }); describe("Resolve regexp", function() { it("Resolve regexp", function () { var r = router().path("child") .path(":id").parent() .path("lol"); var res = r.resolve("/child/truc"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/:id"); }); it("Resolve regexp until leaf", function () { var r = router().path("child") .path(":id") .path("lol"); var res = r.resolve("/child/truc/lol"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/:id/lol"); }); }); describe("Order is serious business", function() { it("First regexp", function () { var r = router() .path("child") .path(":id").parent() .path("lol"); var res = r.resolve("/child/lol"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/:id"); }); it("First string", function () { var r = router().path("child") .path("lol").parent() .path(":id"); var res = r.resolve("/child/lol"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/lol"); }); it("Can go to second soluion", function () { var r = router().path("child") .path(":id") .path("truc").parent() .parent() .path("lol").path("machin"); var res = r.resolve("/child/lol/machin"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/lol/machin"); }); }); describe("PathParams",function () { it("Empty is no regexp",function(){ var r = router().path("child").path("lol"); var res = r.resolve("/child/lol"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/lol"); assert.deepEqual(res.pathParams, {}); }); it("setted regexp", function () { var r = router().path("child").path(":id"); var res = r.resolve("/child/lol"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/:id"); assert.deepEqual(res.pathParams, {id:"lol"}); }); it("setted regexp two time", function () { var r = router().path("child").path(":id").path("ok").path(":truc"); var res = r.resolve("/child/lol/ok/mdr"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/:id/ok/:truc"); assert.deepEqual(res.pathParams, {id:"lol", truc:"mdr"}); }); it("Can go to second soluion without pathParams pollution", function () { var r = router() .path("child") .path(":id") .path("truc") .parent() .parent() .path("lol") .path("machin"); var res = r.resolve("/child/lol/machin"); assert.ok(res); assert.strictEqual(res.node.fullPath(), "/child/lol/machin"); assert.deepEqual(res.pathParams, {}); }); }); });
import React, { useState } from 'react' import { InputGroup, Button, FormControl, Spinner, Row, Col, Container, Form } from 'react-bootstrap' import { connect, useStore } from 'react-redux' import { addShift } from '../../actions/index' const AddShiftWindow = props => { const handleOnChange = (event) => { if (event.target.name === 'start date') { props.inputHandler({ ...props.input, start: event.target.value }) } else { //end props.inputHandler({ ...props.input, end: event.target.value }) } } const handleAddShift = async() => { if (props.input.start === '' || props.input.end === '') { alert('Add start & end datetime') } else { await props.setIsLoading(true) await props.addShift(props.user, props.input.start, props.input.end) await props.displayDialogHandler(false) await props.setIsLoading(false) } } return ( <> <Container style={{ width: '100%' }}> <Row style={RowStyle}> <Col>Start Date {'&'} Hour:</Col> </Row> <Row style={RowStyle}> <Col> <InputGroup className="mb-3"> <Form.Control type='datetime-local' value={props.input.start} name="start date" onChange={handleOnChange} required /> </InputGroup> </Col> </Row> <Row style={RowStyle}> <Col>End Date {'&'} Hour:</Col> </Row> <Row style={RowStyle}> <Col> <InputGroup className="mb-3"> <Form.Control type='datetime-local' name="end date" onChange={handleOnChange} required /> </InputGroup> </Col> </Row> <Row> <Col> <Button variant="outline-secondary" id="button-addon2" onClick={handleAddShift} type="submit"> Add shift </Button> </Col> </Row> </Container> </> ) } const mapStateToProps = (state) => ({ user: state.User }) const mapDispatchToProps = { addShift } const RowStyle = { marginBottom: 5 } export default connect(mapStateToProps, mapDispatchToProps)(AddShiftWindow)
const PATH = require("path"); const FS = require("fs"); const { createRequire } = require("module"); const npxPath = () => { const path = "node_modules/npm/node_modules/libnpx/"; const binPath = PATH.dirname(process.execPath); const getPath = (p) => PATH.join(binPath, ...p); let libnpx = getPath(["../lib", path]); if (!FS.existsSync(libnpx)) { libnpx = getPath([path]); } if (!FS.existsSync(libnpx)) { libnpx = getPath(["../lib", "node_modules/npm/lib/cli.js"]); } return { libnpx, npmCli: getPath(["npm"]) }; }; const { libnpx, npmCli } = npxPath(); const npx8 = (cmd) => { const npmcli = require(libnpx); process.argv[1] = libnpx; process.argv.splice(2, 0, "exec"); for (let i = 0, j = cmd.length; i < j; i++) { process.argv[i + 3] = cmd[i]; } npmcli(process); }; const npx = libnpx.substr(-6) === "cli.js" ? npx8 : createRequire(libnpx)("libnpx"); const pkgPrefix = "generator-"; const isOrgReg = /^@[^/]+\//; const addOrgGenReg = /^@([^/]+)\/(generator-)?/; const addGenReg = new RegExp(`^(${pkgPrefix})?`); const getPkgName = (generator) => isOrgReg.test(generator) ? generator.replace(addOrgGenReg, "@$1/" + pkgPrefix) : generator.replace(addGenReg, pkgPrefix); const getNpxCmd = (argv) => { const generatorName = argv[2]; const otherArgv = argv.slice(3); const [generatorPkg] = (generatorName || "").split(":"); if (!generatorPkg) { return false; } let cmd = [ "--package", "yo", "--package", getPkgName(generatorPkg), "--call", `yo ${generatorName} ${otherArgv.join(" ")}`, ]; if (npx.parseArgs != null) { cmd = npx.parseArgs(cmd, npmCli); } return cmd; }; const init = async () => { const argv = process.argv; const cmdOptions = getNpxCmd(argv); if (cmdOptions) { await npx(cmdOptions); } else { console.error("Generator not found.", argv); process.exit(1); } }; module.exports = { init, getNpxCmd, getPkgName, npxPath, };
import React from 'react' import loginImg from '../../../login.svg' export default function Form(props) { return ( <> <div className='form-header'>{props.header}</div> <main className='content'> <div className='content-image'> <img className='content-image-element' src={loginImg} alt='login-image' /> </div> <form className='content-form'> <div className='content-form-group'> <label htmlFor='username'>Usuário: </label> <input type='text' name='username' placeholder='Digite seu usuário' autoFocus /> </div> <div className='content-form-group'> <label htmlFor='password'>Senha: </label> <input type='password' name='password' placeholder='Senha' /> </div> {props.children} <div className='content-footer'> <button type='button' className='btn'>{props.btnTitle}</button> </div> </form> </main> </> ) }
// @file config.js var path = require('path'), out = path.resolve('./out'), src = path.resolve('./src'); var autoprefixer = require('autoprefixer'); // append CSS Auto Browser Prefix Loader var webpack = require('webpack'); // append CSS Auto Browser Prefix Loader var ExtractTextPlugin = require('extract-text-webpack-plugin'); // extract text var HtmlWebpackPlugin = require('html-webpack-plugin'); // html var UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin(); var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')), __PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false')) }); module.exports = { profile: 'test', out: out, webpack: { entry: { main: path.resolve(src + '/app/statics/main.js'), map: path.resolve(src + '/app/statics/sitemap.js') }, output: { path: out, publicPath: out, filename: '[name].js' }, resolve: { extensions: [ '', '.js', '.jsx', '.scss' ] }, module: { loaders: [ { test: /lodash/, loader: 'exports?_' }, { test: /\.html$/, loader: "file", query: { "name" :"[name].[ext]" } }, { test: /\.temp$/, loader: "raw" }, { test: /\.scss$/, loader: 'style?insertAt=top!css!sass' }, { test: /(\.js)|(\.jsx)$/, exclude: /node_modules/, loader: "babel-loader", query: { presets: ['es2015', 'react'] } } ], noParse: /\.min\.js/ }, postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], plugins: [ definePlugin //,new webpack.optimize.CommonsChunkPlugin({ // name: 'commons', // filename: "commons.js" //}) //,new HtmlWebpackPlugin({ // files: { // title: 'Rouka WIKI', // filename: 'index.html', // js: ["main.js"], // inject: 'body' // } //}) //,new ExtractTextPlugin(out + '/[name].css', { // allChunks: true //}) ] } };
module.exports = function(sequelize, DataType) { const Item = sequelize.define('Item', { name : { type : DataType.STRING, allowNull : false }, description : { type : DataType.STRING, allowNull : false }, imageUrl : { type : DataType.STRING, allowNull : true }, manufacturer : { type : DataType.STRING, allowNull : true }, model : { type : DataType.STRING, allowNull : true }, price : { type : DataType.STRING, allowNull : true }, dimensions : { type : DataType.STRING, allowNull : true }, notes : { type : DataType.TEXT, allowNull : true }, deletedAt : { type : DataType.DATE, allowNull : true } }, // add columns for dimension { tableName : 'items' }); Item.associate = function(models){ Item.belongsTo(models.ItemStatus, { foreignKey : "is_sold", as : 'Status' }); Item.belongsTo(models.User, { foreignKey : "user_id", as : 'User' }); Item.belongsTo(models.Condition, { foreignKey : "condition_id", as : 'Condition' }); Item.belongsTo(models.Category, { foreignKey : "category_id", as : 'Category' }); }; return Item; };
(function () { "use strict"; angular.module("addCep").controller("AddCepController", AddCepController); AddCepController.$inject = [ "$scope", "c8yCepModule" ]; function AddCepController($scope, c8yCepModule) { var datapoints = []; $scope.child.config.datapoints.forEach(function (datapoint) { if (datapoint.__active == true) { datapoints.push(datapoint); }; }) $scope.thresholdDown = 10; $scope.thresholdTop = 100; $scope.setRules = function () { if ($scope.thresholdDown != undefined && $scope.thresholdTop != undefined && $scope.alarm_text != undefined) { var deviceInfo = { fragment: datapoints[0].fragment, series: datapoints[0].series, id: datapoints[0].__target.id, name: datapoints[0].__target.name, thresholdTop: $scope.thresholdTop, thresholdDown: $scope.thresholdDown, alarm_text: $scope.alarm_text }; var my_rule = { body: "module c8y_" + deviceInfo.name + "_Alarm_" + deviceInfo.fragment + "_" + deviceInfo.series + ";\ninsert into CreateAlarm\nselect\ne.measurement.time as time,\ne.measurement.source.value as source,\n\"c8y_" + deviceInfo.name + "_Alarm_" + deviceInfo.fragment + "_" + deviceInfo.series + "\" as type,\n\"" + deviceInfo.alarm_text + "\" as text,\n\"ACTIVE\" as status,\n\"CRITICAL\" as severity\nfrom MeasurementCreated e\nwhere (getNumber(e, \"" + deviceInfo.fragment + "." + deviceInfo.series + ".value\") > " + deviceInfo.thresholdTop + "\nor getNumber(e,\"" + deviceInfo.fragment + "." + deviceInfo.series + ".value\") < " + deviceInfo.thresholdDown + ")\nand e.measurement.source.value=\"" + deviceInfo.id + "\";" }; return new Promise(function (resolve, reject) { c8yCepModule.deploy(my_rule); resolve(); }) } else { alert("Your input is invalid!"); } } function getRuleID(name) { return new Promise(function (resolve, reject) { c8yCepModule.list().then(function (rules) { rules.forEach(function (element) { if (element.name == name) { resolve(element); } }); }); }); } $scope.removeRules = function (name) { var deviceInfo = { fragment: datapoints[0].fragment, series: datapoints[0].series, id: datapoints[0].__target.id, name: datapoints[0].__target.name }; var name = "c8y_" + deviceInfo.name + "_Alarm_" + deviceInfo.fragment + "_" + deviceInfo.series; return new Promise(function (resolve, reject) { getRuleID(name).then(function (rule) { c8yCepModule.remove(rule.id); }); resolve(); }); } } })();
import React, { Component } from "react"; import { Modal, Alert, Button } from "react-bootstrap"; import { Link } from "react-router-dom"; import { base } from "config/base"; import FirestoreServices from 'services/FirestoreServices' import Loading from "commons/Loading"; import { ProgressBar } from "react-bootstrap"; import ProfProfileForm from "components/ProfProfileForm"; import FaCheckCircleO from 'react-icons/lib/fa/check-circle-o' import FaTimesCircleO from 'react-icons/lib/fa/times-circle-o' class ProfProfileUpdater extends Component { constructor(props) { super(props); this.profId = this.props.match.params.id; this.state = { profile: {}, loading: true, errorHandling: { showError: false, errorMsg: "error" }, uploadProgress: { show: false, percentage: 0 }, submitStatus: { showSubmitModal: false, submitSuccessful: false, errorMsg: '' } }; this.handleSubmit = this.handleSubmit.bind(this); this.formPercentageViewer = this.formPercentageViewer.bind(this) this.formSuccessHandler = this.formSuccessHandler.bind(this) } componentWillMount() { const { state: { currentUser } } = this.props; FirestoreServices.getProfessionalUserBusinessId(currentUser.uid, (businessId) => { if (businessId === '') { this.setState({ errorHandling: { showError: true, errorMsg: { message: 'خطأ داخلي: لم يتم العثور على الشركة ' } } }); } else { this.bussRef = base.bindDoc(`${FirestoreServices.BUSINESSES_PATH}/${businessId}`, { context: this, state: "profile", then(data) { this.setState({ loading: false }); }, onFailure(error) { this.setState({ errorHandling: { showError: true, errorMsg: error } }); } }) }//else }, (error) => { this.setState({ errorHandling: { showError: true, errorMsg: error } }); }); } componentWillUnmount() { this.bussRef && base.removeBinding(this.bussRef); } formPercentageViewer(percentage) { this.setState( { uploadProgress: { show: percentage < 100, percentage: percentage } } ) } formSuccessHandler() { //hide waiting alert then show submission success msg let uploadProgress = { show: false, percentage: 100 } //show success popup let submitStatus = { showSubmitModal: true, submitSuccessful: true, errorMsg: '' } let newState = { ...this.state, uploadProgress, submitStatus } this.setState(newState) } handleSubmit( profileData, formErrorHandler ) { if (!this.state.profile) { formErrorHandler('خطأ داخلي: لم يتم العثور على البروفايل في قاعدة البيانات') return } const self = this; profileData.id = this.state.profile.id; FirestoreServices.updateProfProfile(this.props.state.currentUser.uid, profileData, formErrorHandler, this.formSuccessHandler, this.formPercentageViewer) const { state: { admin: adminFlag, currentUser: user }, setCurrentUser } = self.props; setCurrentUser(user, adminFlag) } render() { if (this.state.loading && !this.state.errorHandling.showError) return <Loading />; if (this.state.errorHandling.showError) return ( <div> <Modal show={true} style={{ top: 300 }}> <Modal.Header>حدث خطأ غير معروف</Modal.Header> <Modal.Body> <Alert bsStyle="danger"> {this.state.errorHandling.errorMsg.message} </Alert> <Link to="/"> <Button style={{ margin: 'auto', display: 'block' }}>العودة للصفحة الرئيسية</Button> </Link> </Modal.Body> </Modal> </div> ); if (!this.state.loading && !this.state.showError) return ( <div className="loginreg" > <ProfProfileForm profile={this.state.profile} onSubmit={this.handleSubmit.bind(this)} /> {/* This modal is shown after product addition/form submission is finshed. Its content depends if the form submission was successful or failed. if successful it will ask if user wants to add another new product or go to main page. If failed it will show error message and ask user to go to home pgae */} <Modal show={this.state.submitStatus.showSubmitModal} style={{ top: 300 }} > <Modal.Header > {this.state.submitStatus.submitSuccessful ? <Modal.Title id="contained-modal-title"><FaCheckCircleO style={{ color: 'green', width: '30px', height: '30px' }} /> تم تحديث البروفايل بنجاح</Modal.Title> : <Modal.Title id="contained-modal-title"><FaTimesCircleO style={{ color: 'red', width: '30px', height: '30px' }} /> حدث خطأ في تحديث البروفايل</Modal.Title> } </Modal.Header> <Modal.Body> {this.state.submitStatus.submitSuccessful ? null : <Alert bsStyle='danger' > {this.state.submitStatus.errorMsg} </Alert> } <Link to="/"> <Button style={{ margin: 'auto', display: 'block' }}>العودة للصفحة الرئيسية</Button> </Link> </Modal.Body> </Modal> {/* This modal is for showing image upload progress bar to show progress of uploading/adding product to DB */} <Modal show={this.state.uploadProgress.show} style={{ top: 300 }}> <Modal.Header > <Modal.Title id="contained-modal-title2"> جاري تحديث البروفايل</Modal.Title> <ProgressBar now={this.state.uploadProgress.percentage} label={`${this.state.uploadProgress.percentage}%`} /> </Modal.Header> </Modal> </div> ); } } export default ProfProfileUpdater;
import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; const StyledButton = styled.button` width: 30px; height: 30px; background-color: transparent; border: none; position: relative; cursor: pointer; &:focus { outline: none; } &::before, &::after { content: ''; position: absolute; width: 12px; height: 1px; background-color: ${({ isDarkTheme }) => (isDarkTheme ? '#fff' : '#2d2d2d')}; top: ${({ isOpen }) => (isOpen ? '25%' : '50%')}; transition: all 0.5s ease; } &::before { left: -6px; transform-origin: bottom right; transform: translate(-50%, -50%) ${({ isOpen }) => (isOpen ? 'rotate(-43deg)' : 'rotate(43deg)')}; } &::after { left: 6px; transform-origin: bottom left; transform: translate(-50%, -50%) ${({ isOpen }) => (isOpen ? 'rotate(43deg)' : 'rotate(-43deg)')}; } `; const SlideIcon = ({ isOpen, isDarkTheme }) => { return <StyledButton isOpen={isOpen} isDarkTheme={isDarkTheme} />; }; SlideIcon.propTypes = { isOpen: PropTypes.bool.isRequired, isDarkTheme: PropTypes.bool }; SlideIcon.defaultProps = { isDarkTheme: true }; export default SlideIcon;
/* Anagrams are words that have the same number of same letters, but in different order. For instance: nap - pan ear - are - era cheaters - hectares - teachers Write a function aclean(arr) that returns an array cleaned from anagrams. For instance: let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; alert( aclean(arr) ); // "nap,teachers,ear" or "PAN,cheaters,era" From every anagram group should remain only one word, no matter which one. */ function aClean(arr){ let map = new Map(); for(let word of arr){ let sorted = word.toLowerCase().split('').sort().join(''); map.set(sorted,word); } return Array.from(map.values()); } let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; console.log(aClean(arr));
import React from 'react'; import veruFamily from '../img/verufamily.jpg'; import veruPC from '../img/veruPC.jpg'; export const Veru = () => { return ( <> <p> Jmenuji se Verča, jsem z Českých Budějovic. Doma mám dvě nezbedné děti Adélku, 5 let a Honzíka, 8 let. V předchozích letech jsem vystřídala několik zaměstnání, spíše administrativních. Ráda bych do budoucna změnu, a mít možnost určit si přesně čas, kdy se mohu věnovat práci a kdy dětem. </p> <img className="veru__pc" src={veruPC} alt="Verca" /> <p> Do digitální akademie jsem se přihlásila ze zvědavosti, a s vidinou rozšíření vědomostí a obzorů a mít příležitost do budoucnaucházet se o novou práci. Za svoji parťačku jsem si vybrala Slávku a po společném setkání a povídáním o nás, jsme se rozhodly pro Appku HYPOŠKU. </p> <p> Po absolvování Ekonomické fakulty Jihočeské Univerzity jsem pracovala v E.ONu na pozici Account Managera. Soukormě jsem si k tomu založila e-shop se svatebními doplňky a pomáhala s koordinací svateb. K tvorbě e-shopu jsem musela využít pomoci kamaráda a pak si správu webu dělala sama. Tady vznikla prvně myšlenka, že by bylo moc fajn toto umět a udělat si vlastní kreativní web. Pak přišla mateřská a skloubit dvě ratolesti, koordinaci svateb a správu eshopu už nebylo možné zvládat. Eshop a koordinace šly do ústraní. Po mateřské při návratu zpět do pracovního procesu jsem byla po roce působení v korporátu vyčerpaná a bez kreativity, stala se z práce rutina. Každý den to samé. I díky COVID době jsem se začala více zajímat, kde by bylo moožné se dál vzdělávat a rozvíjet se a našla jsem na Facebooku upoutávku na Digitální akademii. Začala jsem ji sledovat a postupně i nabídku kurzů, co nabízí. Jsem ráda, že jsem se na Digitální akademii WEB přihlásila, podaří se mi ji úspěšně absolvovat a v budoucnu využít získané znalosti. </p> <img className="verca__deti" src={veruFamily} alt="Verča s dětmi" /> <p> Digitální akademie WEB je opravdu intenzivní 3 měsíční kurz, neustále se učíme nové věci, procvičujeme znalosti, je to náročné i díky tomu, že je offline a doma vám k tomu běhají děti. Věřím však, že náš projekt bude skvělý a využijeme k tomu veškeré získané znalosti. </p> <p> A co na závěr - snad už jen mé záliby, ke kterým utíkám, když vyšetřím chvilku času. Ráda sportuji, jezdím na kole, bruslích, poslední dobou "čistím hlavu" běháním, ráda maluji, tvořím, přečtu si ráda pěknou knihu a nejraději posedím s přáteli u dobrého vínka. </p> </> ); };
path = require("path") var bd = require(path.join(__dirname, "../lib/conf")); //fonction pour créer un Groupe //TODO pas de "nomGrp" dans la table function addGroupe(nomTuteurEntreprise,prenomTuteurEntreprise,nomEntreprise,TuteurEnseignant,nomGrp) { return new Promise((resolve, reject) => { bd.query('INSERT INTO Groupe (nomTuteurEntreprise,prenomTuteurEntreprise,nomEntreprise,TuteurEnseignant,nomGrp) VALUES (?,?,?,?,?)', [nomTuteurEntreprise,prenomTuteurEntreprise,nomEntreprise,TuteurEnseignant,nomGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function addComposer(nomEtu, idGroupe) { return new Promise((resolve, reject) => { bd.query('INSERT INTO Composer (etudiant,groupe) VALUES (?,?)', [nomEtu, idGroupe], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } //donne les Groupes de l'élève function getGroupeEleve(IdEleve) { return new Promise((resolve, reject) => { bd.query('SELECT * FROM Groupe WHERE id IN (SELECT Groupe FROM Composer WHERE etudiant=?) ', [IdEleve], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function checkEtu(num) { //fonction qui vérifie qu'un numéro pour créer un Groupe est bien celui d'un étudiant return new Promise((resolve, reject) => { bd.query('SELECT COUNT(0) FROM Etudiant WHERE num=? ', [num], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modNomGroupe(numGrp, nom) { return new Promise((resolve, reject) => { bd.query('UPDATE Groupe SET nomGrp = ? WHERE id=?', [nom, numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modNomTuteur(numGrp, nom) { return new Promise((resolve, reject) => { bd.query('UPDATE Groupe SET NomTuteurEntreprise = ? WHERE id=?', [nom,numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modPrenomTuteur(numGrp, nom) { return new Promise((resolve, reject) => { bd.query('UPDATE Groupe SET prenomTuteurEntreprise = ? WHERE id=?', [nom,numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modEntrepriseTut(numGrp, nom) { return new Promise((resolve, reject) => { bd.query('UPDATE Groupe SET nomEntreprise = ? WHERE id=?', [nom,numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modProf(numGrp, num) { return new Promise((resolve, reject) => { bd.query('UPDATE Groupe SET TuteurEnseignant = ? WHERE id=? ', [num,numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function modnumEleve(numGrp, num) { return new Promise((resolve, reject) => { bd.query('INSERT INTO Composer (etudiant,groupe) VALUES (?,?)', [num,numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function DeleteGrpc(numGrp) { return new Promise((resolve, reject) => { parseInt(numGrp) bd.query('DELETE FROM Composer WHERE groupe = ?', [numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function DeleteGrp(numGrp) { return new Promise((resolve, reject) => { parseInt(numGrp) bd.query('DELETE FROM Groupe WHERE id = ?', [numGrp], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function DeleteGrpLast() { return new Promise((resolve, reject) => { bd.query('DELETE FROM Groupe WHERE id = (SELECT MAX(id) FROM Groupe)', function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function getGroupe(id) { return new Promise((resolve, reject) => { bd.query('SELECT * FROM Groupe WHERE id=?', [id], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } function getEleve(idGroupe) { return new Promise((resolve, reject) => { bd.query('SELECT etudiant FROM Composer WHERE groupe=?', [idGroupe], function(err, result){ if (err){ reject(err); } resolve(result); } ); }); } module.exports = {getGroupe,DeleteGrpLast,DeleteGrp,addGroupe,getGroupeEleve,checkEtu,DeleteGrpc,modnumEleve,modProf,modEntrepriseTut,modPrenomTuteur,modNomTuteur,modNomGroupe,addComposer,getEleve};
import React, {Component} from 'react'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; // Component with filters export default class Filters extends Component { constructor(props){ super(props); this.state = { dropdownOpen: false, } } toggleDropdown = () =>{ this.setState({ dropdownOpen: !this.state.dropdownOpen, }) } render() { const changeFilter = this.props.changeFilter; const typeData = this.props.typeData; let filter = this.props.filter; let header = ''; if(filter === 'popular') header = "Популярные"; else if (filter === 'top_rated') header = "С наивысшым рейтингом"; else header = "Сейчас в прокате"; return ( <div> <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggleDropdown}> <DropdownToggle caret> {header} </DropdownToggle> <DropdownMenu> <DropdownItem onClick={() => changeFilter(typeData, 'popular')} active={filter === 'popular'}>Популярные</DropdownItem> <DropdownItem onClick={() => changeFilter(typeData, 'top_rated')} active={filter === 'top_rated'}>С наивысшим рейтингом</DropdownItem> <DropdownItem onClick={() => changeFilter(typeData, typeData === 'movie' ? 'now_playing' : 'on_the_air')} active={filter === 'now_playing' || filter === 'on_the_air'}>Сейчас в прокате</DropdownItem> </DropdownMenu> </Dropdown> </div> ) } }
const url = 'https://jsonplaceholder.typicode.com/posts'; fetch(url) .then(response => resonse.json()) .then(json => console.log(json))
/** * Layout component that queries for data * with Gatsby's StaticQuery component * * See: https://www.gatsbyjs.org/docs/static-query/ */ import React from "react" import PropTypes from "prop-types" import { StaticQuery, graphql, Link } from "gatsby" import {Helmet} from "react-helmet"; import Header from "./header" import {GlobalStyle, theme} from "./common" import styled, {ThemeProvider} from 'styled-components'; class ExternalScript { constructor({name, url, onload, onupdate}) { this.name = name; this.url = url; this.onload = onload; if (onupdate === undefined) { this.onupdate = onload; } else { this.onupdate = onupdate; } } } let mathjax_es = new ExternalScript({ name: 'mathjax', url: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML', onload: ({ref}) => { if (ref === undefined) { window.MathJax.Hub.Queue([ "Typeset", window.MathJax.Hub, ]); } else { console.log(ref.current); window.MathJax.Hub.Queue([ "Typeset", window.MathJax.Hub, ref.current ]); } }, }); let jquery_es = new ExternalScript({ name: 'jquery', url: 'https://code.jquery.com/jquery-3.4.1.min.js', onload: () => { window.jQuery("code").addClass("prettyprint"); }, }); let highlight_js_es = new ExternalScript({ name: 'highlight-js', url: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/highlight.min.js', onload: () => { window.document.querySelectorAll("pre code").forEach((block) => { window.hljs.highlightBlock(block); }); }, }); const external_scripts = [ jquery_es, mathjax_es, highlight_js_es, ]; class PageContained_ extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); this.external_scripts = props.external_scripts; this.external_scripts.forEach(s => { s.onload && (s.onload = s.onload.bind(this)); s.onupdate && (s.onupdate = s.onupdate.bind(this)); }); } componentDidMount() { this.load_external_scripts(); } load_external_scripts() { this.external_scripts.forEach(s => { let script = window.document.createElement("script"); script.type = "text/javascript"; script.src = s.url; script.onload = s.onload; window.document.getElementsByTagName("head")[0].appendChild(script); }); } componentDidUpdate() { this.external_scripts.forEach(s => s.onupdate && s.onupdate({ref: this.myRef})); } render() { return <div ref={this.myRef} id="global_layout" className={this.props.className}>{this.props.children}</div>; } } const PageContained = styled(PageContained_)` margin: 0 auto; // max-width: ${props => props.theme.maxWidth}px; padding: 0 1.0875rem 1.45rem; display: flex; flex-direction: row; justify-content: center; align-items: flex-start; #content-container { display: flex; flex-direction: column; flex-grow: 0; flex-shrink: 0; align-items: stretch; flex-basis: ${props => props.theme.mainWidth}; } `; class Sidebar_ extends React.Component { render() { return ( <div id="sidebar" className={this.props.className}> {/*<Image/> logo */} <div id="sidebar-nav"> <Link to="/"> Home </Link> <Link to="/about-site">About This Site</Link> <Link to="/about-me">About Me </Link> </div> <div id="sidebar-links"> <div>Useful Links</div> <a href={"www.google.com"}>Example Link</a> </div> <div id="sidebar-message"> <p>Support the Free Software Movement!</p> </div> </div> ) } } const Sidebar = styled(Sidebar_)` flex: 0 0 ${props => props.theme.sidebarWidth}; margin: 0 4ch 0 1ch; display: flex; flex-direction: column; font-size: 14px; border-top: 1px solid gray; border-bottom: 1px solid gray; margin-top: 3em; #sidebar-nav { display:flex; flex-direction: column; padding: 1em 0 1em 0; border-bottom: 1px dotted gray; } #sidebar-links { display:flex; flex-direction: column; padding: 1em 0 1em 0; border-bottom: 1px dotted gray; } #sidebar-message { padding: 1em 0 1em 0; } `; const Footer = styled.footer` text-align: center; margin: 10em 0 0 0; `; const Layout = ({ children }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title description } } } `} render={data => ( <ThemeProvider theme={theme}> <> <Helmet> {/*<link rel="stylesheet" type="text/css" href="https://rsms.me/inter/inter.css"/>*/} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.8/styles/default.min.css"/> <script type="text/x-mathjax-config"> {`MathJax.Hub.Config({extensions: ["jsMath2jax.js"],});`} </script> </Helmet> <GlobalStyle/> <PageContained external_scripts={external_scripts}> <Sidebar/> <div id={`content-container`}> <Header siteMetaData={data.site.siteMetadata}/> {children} <Footer> © {new Date().getFullYear()}, Built with {` `} <a href="https://www.gatsbyjs.org">Gatsby</a> </Footer> </div> </PageContained> </> </ThemeProvider> )} /> ); Layout.propTypes = { children: PropTypes.node.isRequired, }; export default Layout;
// Copyright 2014 Joshua Bell. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function(global) { 'use strict'; // // Utilities // /** * @param {number} a The number to test. * @param {number} min The minimum value in the range, inclusive. * @param {number} max The maximum value in the range, inclusive. * @return {boolean} True if a >= min and a <= max. */ function inRange(a, min, max) { return min <= a && a <= max; } /** * @param {*} o * @return {Object} */ function toDictionary(o) { if (o === undefined) return {}; if (o === Object(o)) return o; throw new TypeError('Could not convert argument to dictionary'); } /** * @param {string} string Input string of UTF-16 code units. * @return {!Array.<number>} Code points. */ function stringToCodePoints(string) { // http://heycam.github.io/webidl/#dfn-obtain-unicode // 1. Let S be the DOMString value. var s = String(string); // 2. Let n be the length of S. var n = s.length; // 3. Initialize i to 0. var i = 0; // 4. Initialize U to be an empty sequence of Unicode characters. var u = []; // 5. While i < n: while (i < n) { // 1. Let c be the code unit in S at index i. var c = s.charCodeAt(i); // 2. Depending on the value of c: // c < 0xD800 or c > 0xDFFF if (c < 0xD800 || c > 0xDFFF) { // Append to U the Unicode character with code point c. u.push(c); } // 0xDC00 ≤ c ≤ 0xDFFF else if (0xDC00 <= c && c <= 0xDFFF) { // Append to U a U+FFFD REPLACEMENT CHARACTER. u.push(0xFFFD); } // 0xD800 ≤ c ≤ 0xDBFF else if (0xD800 <= c && c <= 0xDBFF) { // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT // CHARACTER. if (i === n - 1) { u.push(0xFFFD); } // 2. Otherwise, i < n−1: else { // 1. Let d be the code unit in S at index i+1. var d = string.charCodeAt(i + 1); // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then: if (0xDC00 <= d && d <= 0xDFFF) { // 1. Let a be c & 0x3FF. var a = c & 0x3FF; // 2. Let b be d & 0x3FF. var b = d & 0x3FF; // 3. Append to U the Unicode character with code point // 2^16+2^10*a+b. u.push(0x10000 + (a << 10) + b); // 4. Set i to i+1. i += 1; } // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a // U+FFFD REPLACEMENT CHARACTER. else { u.push(0xFFFD); } } } // 3. Set i to i+1. i += 1; } // 6. Return U. return u; } /** * @param {!Array.<number>} code_points Array of code points. * @return {string} string String of UTF-16 code units. */ function codePointsToString(code_points) { var s = ''; for (var i = 0; i < code_points.length; ++i) { var cp = code_points[i]; if (cp <= 0xFFFF) { s += String.fromCharCode(cp); } else { cp -= 0x10000; s += String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00); } } return s; } // // Implementation of Encoding specification // http://dvcs.w3.org/hg/encoding/raw-file/tip/Overview.html // // // 3. Terminology // /** * End-of-stream is a special token that signifies no more tokens * are in the stream. * @const */ var end_of_stream = -1; /** * A stream represents an ordered sequence of tokens. * * @constructor * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the * stream. */ function Stream(tokens) { /** @type {!Array.<number>} */ this.tokens = [].slice.call(tokens); } Stream.prototype = { /** * @return {boolean} True if end-of-stream has been hit. */ endOfStream: function() { return !this.tokens.length; }, /** * When a token is read from a stream, the first token in the * stream must be returned and subsequently removed, and * end-of-stream must be returned otherwise. * * @return {number} Get the next token from the stream, or * end_of_stream. */ read: function() { if (!this.tokens.length) return end_of_stream; return this.tokens.shift(); }, /** * When one or more tokens are prepended to a stream, those tokens * must be inserted, in given order, before the first token in the * stream. * * @param {(number|!Array.<number>)} token The token(s) to prepend to the stream. */ prepend: function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.<number>}*/(token); while (tokens.length) this.tokens.unshift(tokens.pop()); } else { this.tokens.unshift(token); } }, /** * When one or more tokens are pushed to a stream, those tokens * must be inserted, in given order, after the last token in the * stream. * * @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream. */ push: function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.<number>}*/(token); while (tokens.length) this.tokens.push(tokens.shift()); } else { this.tokens.push(token); } } }; // // 4. Encodings // // 4.1 Encoders and decoders /** @const */ var finished = -1; /** * @param {boolean} fatal If true, decoding errors raise an exception. * @param {number=} opt_code_point Override the standard fallback code point. * @return {number} The code point to insert on a decoding error. */ function decoderError(fatal, opt_code_point) { if (fatal) throw new TypeError('Decoder error'); return opt_code_point || 0xFFFD; } /** @interface */ function Decoder() {} Decoder.prototype = { /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point, or |finished|. */ handler: function(/*stream, bite*/) {} }; /** @interface */ function Encoder() {} Encoder.prototype = { /** * @param {Stream} stream The stream of code points being encoded. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit, or |finished|. */ handler: function(/*stream, code_point*/) {} }; // 4.2 Names and labels // TODO: Define @typedef for Encoding: {name:string,labels:Array.<string>} // https://github.com/google/closure-compiler/issues/247 /** * @param {string} label The encoding label. * @return {?{name:string,labels:Array.<string>}} */ function getEncoding(label) { // 1. Remove any leading and trailing ASCII whitespace from label. label = String(label).trim().toLowerCase(); // 2. If label is an ASCII case-insensitive match for any of the // labels listed in the table below, return the corresponding // encoding, and failure otherwise. if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) { return label_to_encoding[label]; } return null; } // Label to encoding registry. /** @type {Object.<string,{name:string,labels:Array.<string>}>} */ var label_to_encoding = { 'utf-8': { name: 'utf-8' } , 'utf8': { name: 'utf-8' } }; // Registry of of encoder/decoder factories, by encoding name. /** @type {Object.<string, function({fatal:boolean}): Encoder>} */ var encoders = {}; /** @type {Object.<string, function({fatal:boolean}): Decoder>} */ var decoders = {}; // // 7. API // /** @const */ var DEFAULT_ENCODING = 'utf-8'; // 7.1 Interface TextDecoder /** * @constructor * @param {string=} encoding The label of the encoding; * defaults to 'utf-8'. * @param {Object=} options */ function TextDecoder(encoding, options) { if (!(this instanceof TextDecoder)) { return new TextDecoder(encoding, options); } encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING; options = toDictionary(options); /** @private */ this._encoding = getEncoding(encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw new RangeError('Unknown encoding: ' + encoding); /** @private @type {boolean} */ this._streaming = false; /** @private @type {boolean} */ this._BOMseen = false; /** @private @type {?Decoder} */ this._decoder = null; /** @private @type {boolean} */ this._fatal = Boolean(options['fatal']); /** @private @type {boolean} */ this._ignoreBOM = Boolean(options['ignoreBOM']); if (Object.defineProperty) { Object.defineProperty(this, 'encoding', {value: this._encoding.name}); Object.defineProperty(this, 'fatal', {value: this._fatal}); Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM}); } else { this.encoding = this._encoding.name; this.fatal = this._fatal; this.ignoreBOM = this._ignoreBOM; } return this; } TextDecoder.prototype = { /** * @param {ArrayBufferView=} input The buffer of bytes to decode. * @param {Object=} options * @return {string} The decoded string. */ decode: function decode(input, options) { var bytes; if (typeof input === 'object' && input instanceof ArrayBuffer) { bytes = new Uint8Array(input); } else if (typeof input === 'object' && 'buffer' in input && input.buffer instanceof ArrayBuffer) { bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength); } else { bytes = new Uint8Array(0); } options = toDictionary(options); if (!this._streaming) { this._decoder = decoders[this._encoding.name]({fatal: this._fatal}); this._BOMseen = false; } this._streaming = Boolean(options['stream']); var input_stream = new Stream(bytes); var code_points = []; /** @type {?(number|!Array.<number>)} */ var result; while (!input_stream.endOfStream()) { result = this._decoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (result === null) continue; if (Array.isArray(result)) code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result)); else code_points.push(result); } if (!this._streaming) { do { result = this._decoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (result === null) continue; if (Array.isArray(result)) code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result)); else code_points.push(result); } while (!input_stream.endOfStream()); this._decoder = null; } if (code_points.length) { // If encoding is one of utf-8, utf-16be, and utf-16le, and // ignore BOM flag and BOM seen flag are unset, run these // subsubsteps: if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 && !this._ignoreBOM && !this._BOMseen) { // If token is U+FEFF, set BOM seen flag. if (code_points[0] === 0xFEFF) { this._BOMseen = true; code_points.shift(); } else { // Otherwise, if token is not end-of-stream, set BOM seen // flag and append token to output. this._BOMseen = true; } } } return codePointsToString(code_points); } }; // 7.2 Interface TextEncoder /** * @constructor * @param {string=} encoding The label of the encoding; * defaults to 'utf-8'. * @param {Object=} options */ function TextEncoder(encoding, options) { if (!(this instanceof TextEncoder)) return new TextEncoder(encoding, options); encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING; options = toDictionary(options); /** @private */ this._encoding = getEncoding(encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw new RangeError('Unknown encoding: ' + encoding); var allowLegacyEncoding = Boolean(options['NONSTANDARD_allowLegacyEncoding']); var isLegacyEncoding = (this._encoding.name !== 'utf-8' && this._encoding.name !== 'utf-16le' && this._encoding.name !== 'utf-16be'); if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding)) throw new RangeError('Unknown encoding: ' + encoding); /** @private @type {boolean} */ this._streaming = false; /** @private @type {?Encoder} */ this._encoder = null; /** @private @type {{fatal: boolean}} */ this._options = {fatal: Boolean(options['fatal'])}; if (Object.defineProperty) Object.defineProperty(this, 'encoding', {value: this._encoding.name}); else this.encoding = this._encoding.name; return this; } TextEncoder.prototype = { /** * @param {string=} opt_string The string to encode. * @param {Object=} options * @return {Uint8Array} Encoded bytes, as a Uint8Array. */ encode: function encode(opt_string, options) { opt_string = opt_string ? String(opt_string) : ''; options = toDictionary(options); // NOTE: This option is nonstandard. None of the encodings // permitted for encoding (i.e. UTF-8, UTF-16) are stateful, // so streaming is not necessary. if (!this._streaming) this._encoder = encoders[this._encoding.name](this._options); this._streaming = Boolean(options['stream']); var bytes = []; var input_stream = new Stream(stringToCodePoints(opt_string)); /** @type {?(number|!Array.<number>)} */ var result; while (!input_stream.endOfStream()) { result = this._encoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (Array.isArray(result)) bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result)); else bytes.push(result); } if (!this._streaming) { while (true) { result = this._encoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (Array.isArray(result)) bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result)); else bytes.push(result); } this._encoder = null; } return new Uint8Array(bytes); } }; // // 8. The encoding // // 8.1 utf-8 /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function UTF8Decoder(options) { var fatal = options.fatal; // utf-8's decoder's has an associated utf-8 code point, utf-8 // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8 // lower boundary (initially 0x80), and a utf-8 upper boundary // (initially 0xBF). var /** @type {number} */ utf8_code_point = 0, /** @type {number} */ utf8_bytes_seen = 0, /** @type {number} */ utf8_bytes_needed = 0, /** @type {number} */ utf8_lower_boundary = 0x80, /** @type {number} */ utf8_upper_boundary = 0xBF; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and utf-8 bytes needed is not 0, // set utf-8 bytes needed to 0 and return error. if (bite === end_of_stream && utf8_bytes_needed !== 0) { utf8_bytes_needed = 0; return decoderError(fatal); } // 2. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 3. If utf-8 bytes needed is 0, based on byte: if (utf8_bytes_needed === 0) { // 0x00 to 0x7F if (inRange(bite, 0x00, 0x7F)) { // Return a code point whose value is byte. return bite; } // 0xC2 to 0xDF if (inRange(bite, 0xC2, 0xDF)) { // Set utf-8 bytes needed to 1 and utf-8 code point to byte // − 0xC0. utf8_bytes_needed = 1; utf8_code_point = bite - 0xC0; } // 0xE0 to 0xEF else if (inRange(bite, 0xE0, 0xEF)) { // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0. if (bite === 0xE0) utf8_lower_boundary = 0xA0; // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F. if (bite === 0xED) utf8_upper_boundary = 0x9F; // 3. Set utf-8 bytes needed to 2 and utf-8 code point to // byte − 0xE0. utf8_bytes_needed = 2; utf8_code_point = bite - 0xE0; } // 0xF0 to 0xF4 else if (inRange(bite, 0xF0, 0xF4)) { // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90. if (bite === 0xF0) utf8_lower_boundary = 0x90; // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F. if (bite === 0xF4) utf8_upper_boundary = 0x8F; // 3. Set utf-8 bytes needed to 3 and utf-8 code point to // byte − 0xF0. utf8_bytes_needed = 3; utf8_code_point = bite - 0xF0; } // Otherwise else { // Return error. return decoderError(fatal); } // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code // point to utf-8 code point << (6 × utf-8 bytes needed) and // return continue. utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed); return null; } // 4. If byte is not in the range utf-8 lower boundary to utf-8 // upper boundary, run these substeps: if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) { // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8 // bytes seen to 0, set utf-8 lower boundary to 0x80, and set // utf-8 upper boundary to 0xBF. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; utf8_lower_boundary = 0x80; utf8_upper_boundary = 0xBF; // 2. Prepend byte to stream. stream.prepend(bite); // 3. Return error. return decoderError(fatal); } // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary // to 0xBF. utf8_lower_boundary = 0x80; utf8_upper_boundary = 0xBF; // 6. Increase utf-8 bytes seen by one and set utf-8 code point // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes // needed − utf-8 bytes seen)). utf8_bytes_seen += 1; utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen)); // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed, // continue. if (utf8_bytes_seen !== utf8_bytes_needed) return null; // 8. Let code point be utf-8 code point. var code_point = utf8_code_point; // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes // seen to 0. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; // 10. Return a code point whose value is code point. return code_point; }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function UTF8Encoder(/*options*/) { //var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007f)) return code_point; // 3. Set count and offset based on the range code point is in: var count, offset; // U+0080 to U+07FF: 1 and 0xC0 if (inRange(code_point, 0x0080, 0x07FF)) { count = 1; offset = 0xC0; } // U+0800 to U+FFFF: 2 and 0xE0 else if (inRange(code_point, 0x0800, 0xFFFF)) { count = 2; offset = 0xE0; } // U+10000 to U+10FFFF: 3 and 0xF0 else if (inRange(code_point, 0x10000, 0x10FFFF)) { count = 3; offset = 0xF0; } // 4.Let bytes be a byte sequence whose first byte is (code // point >> (6 × count)) + offset. var bytes = [(code_point >> (6 * count)) + offset]; // 5. Run these substeps while count is greater than 0: while (count > 0) { // 1. Set temp to code point >> (6 × (count − 1)). var temp = code_point >> (6 * (count - 1)); // 2. Append to bytes 0x80 | (temp & 0x3F). bytes.push(0x80 | (temp & 0x3F)); // 3. Decrease count by one. count -= 1; } // 6. Return bytes bytes, in order. return bytes; }; } /** @param {{fatal: boolean}} options */ encoders['utf-8'] = function(options) { return new UTF8Encoder(options); }; /** @param {{fatal: boolean}} options */ decoders['utf-8'] = function(options) { return new UTF8Decoder(options); }; if (!('TextEncoder' in global)) global['TextEncoder'] = TextEncoder; if (!('TextDecoder' in global)) global['TextDecoder'] = TextDecoder; }(window));
import React, { Component, PropTypes } from 'react'; import { Router, Route, IndexRoute, browserHistory, Link } from 'react-router'; import { connect } from 'react-redux'; import action from '../../Action/Index'; import { Tool, merged } from '../../Container/Tool'; import { DataLoad, DataNull, Header, TipMsgSignin, GetData } from '../common/index'; import { output,IsNull,checktkexplain} from '../common/verifications'; import './WeChat.less'; function chatMainInit(){//聊天内容滚动 let headHeight = document.querySelector('.chatHead').offsetHeight; let footHeight = document.querySelector('.chatFoot-box').offsetHeight; let bodyHeight = document.documentElement.clientHeight || document.body.clientHeight; let chatMainDom = document.querySelector('.chatMain-box'); let chatAreaHeight = document.getElementById('chatMainArea').offsetHeight; let heightDistance = 0; let heightScroll = 0; heightDistance = bodyHeight - headHeight - footHeight; chatMainDom.style.height = heightDistance +"px"; heightScroll = chatAreaHeight - heightDistance; chatMainDom.scrollTop = heightScroll; } /** * 聊天头部 * * @export * @class ChatHead * @extends {Component} */ export class ChatHead extends Component { render() { return ( <div className = "chatHead-box"> <div className = "chatHead"> <a href="#"> <i className = "iconfont icon-phone"></i> <span>一键呼叫,专家免费回拨电话,省心,省力!</span> </a> </div> <div className = "wx-people-center"> <a href="#"> <i className = "iconfont icon-people-center"></i> </a> </div> <div className = "chatHead-place"></div> </div> ); } } /** * 聊天头部 * * @export * @class ChatMain * @extends {Component} */ export class ChatMain extends Component { constructor(props) { super(props); this.state = { isLeave: false, isLogin: false, }; } chatMainClick(e){ document.querySelector('.upload-content').style.display="none"; document.querySelector('.face-content').style.display="none"; setTimeout(chatMainInit,200); } chatPicToBig(e){ let bigImgSrc = e.target.src; let bigDom=document.createElement("img"); bigDom.setAttribute("src", bigImgSrc ); document.querySelector('.pic-pop-box').style.display="block"; document.querySelector('.pic-pop-main').innerHTML=""; document.querySelector('.pic-pop-main').appendChild(bigDom); } popBoxHide(e){ document.querySelector('.pic-pop-box').style.display="none"; } componentDidMount(e){ let commentsList=document.querySelector('.comments-list'); let commentsSpan=commentsList.getElementsByTagName('span'); let commentsResult=document.querySelector('.comments-result'); for(let i=0;i<commentsSpan.length;i++){ commentsSpan[i].onclick=()=>{ console.log(i); let chooseNr=commentsSpan[i].innerHTML; document.querySelector('.win-box-publish').style.display="block"; commentsResult.innerHTML=chooseNr; } } this.setState({ isLogin:true, }) } comtSure(e){ let commentFwVlue=document.getElementById('comment-fw').value; if(commentFwVlue){ alert("提交中..."); document.querySelector('.win-box-publish').style.display="none"; }else{ document.querySelector('.tkexplain').style.display="block"; document.querySelector('.tkexplain').innerHTML="输入框内容不能为空!"; } } comtBack(e){ document.querySelector('.win-box-publish').style.display="none"; } Checktkexplain(e){ checktkexplain('comment-fw'); } LoginClose(e){ document.querySelector('.win-box-login').style.display="none"; } LoginSure(e){ browserHistory.push(`/login/login`); } render() { let isLogin = this.state.isLogin; if(isLogin==true){ document.querySelector('.win-box-login').style.display="none"; } else{ console.log(222); } return ( <div className = "chatMain-box" onClick = {this.chatMainClick.bind(this)}> <div className = "chatMain-area" id ="chatMainArea"> <p className = "history-dialogue">没有历史记录</p> <p className = "chat-time"><span>2017-02-16 18:49:05</span></p> <div className = "chat-item-news"> <div className="news-content-system"> <div className="content-system"> <p>请您点击开始呼叫药师吧。</p> 【<a className="call_pharmacist">点击呼叫药师</a>】,药师会免费打电话联系您 </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-my"> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> <div className="send-head-pic sender_head_my"> <img src="/src/Pic/user_log_default.png" /> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-service"> <div className="send-head-pic sender_head_service"> <img src="/src/Pic/service.png" /> </div> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-my"> <div className="content-chat-area"> <div className="content-chat-main" data-type="4"> <img src="/src/Pic/ad02.jpg" onClick = {this.chatPicToBig.bind(this)} /> </div> </div> <div className="send-head-pic sender_head_my"> <img src="/src/Pic/user_log_default.png" /> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-my"> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> <div className="send-head-pic sender_head_my"> <img src="/src/Pic/user_log_default.png" /> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-service"> <div className="send-head-pic sender_head_service"> <img src="/src/Pic/service.png" /> </div> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-service"> <div className="send-head-pic sender_head_service"> <img src="/src/Pic/service.png" /> </div> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-my"> <div className="content-chat-area"> <div className="content-chat-main" data-type="4"> <img src="/src/Pic/ad02.jpg" onClick = {this.chatPicToBig.bind(this)} /> </div> </div> <div className="send-head-pic sender_head_my"> <img src="/src/Pic/user_log_default.png" /> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-service"> <div className="send-head-pic sender_head_service"> <img src="/src/Pic/service.png" /> </div> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> 您的情况我基本都了解了. </div> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content-system"> <div className="content-system bg-white"> <p className="goods-name">感冒灵胶囊感冒灵胶囊感冒灵胶囊感冒灵胶囊感冒灵胶囊</p> <div className="pricenu"> <label>¥11.80</label> <i>×4</i> </div> <p className="look-but"> <Link to={`/single/product?goods_id=1`}>点击查看</Link> </p> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content-system"> <div className="content-system bg-white"> <p className="goods-name">感冒灵胶囊感冒灵胶囊感冒灵胶囊感冒灵胶囊感冒灵胶囊</p> <div className="pricenu"> <label>¥11.80</label> <i>×4</i> </div> <p className="look-but"> <Link to={`/single/product?goods_id=1`}>点击查看</Link> </p> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content-system"> <div className="content-system bg-white"> <p className="total-price">小计:<i>25.4</i>元,优惠<i>5</i>元,共<i>20.4</i>元</p> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content news-content-service"> <div className="send-head-pic sender_head_service"> <img src="/src/Pic/service.png" /> </div> <div className="content-chat-area"> <div className="content-chat-main" data-type="1"> <p className="transfer">我们支持在线转账,您可以<br/>【<Link to={`/ `}>点击转账</Link>】<i>20.4</i>元</p> </div> </div> </div> </div> <div className = "chat-item-news"> <div className="news-content-system"> <div className="content-system bg-white"> <div className="win-box-choose-cent"> <p className="comments-cont">感谢您对我们的支持,为了更好地为您服务,请为本次服务打分</p> <p className="comments-list"> <span>非常满意</span> <span>一般</span> <span>不满意</span> </p> </div> </div> </div> </div> <div className = "pic-pop-box"> <div className = "pic-pop-main" onClick = {this.popBoxHide.bind(this)}> </div> </div> <div className="win-box-common win-box-publish"> <div className="win-mask"></div> <div className="win-box-common-cent win-box-publish-cent"> <p className="comments-ti"><label>您本次的评论为:</label><i className="comments-result">非常满意</i></p> <div className="comments-tex"> <textarea className="comments-nr" id="comment-fw" placeholder="您可以在此输入评论内容" onBlur={this.Checktkexplain.bind(this)}/> </div> <div className="from-remarks"> <p className="tkexplain"></p> </div> <p className="comments-but"> <span className="comments-but-sure" onClick={this.comtSure.bind(this)}>确定</span> <span className="comments-but-back" onClick={this.comtBack.bind(this)}>返回</span> </p> </div> </div> <div className="win-box-common win-box-login"> <div className="win-mask"></div> <div className="win-box-common-cent win-box-login-cent"> <p className="login-remind">为了保证给您最好的服务体验,请您登录后再进行聊天咨询哟~</p> <p className="login-choose"> <span onClick={this.LoginClose}>取消</span> <span onClick={this.LoginSure}>确定</span> </p> </div> </div> </div> </div> ); } } /** * 聊天底部输入框 * * @export * @class ChatFoot * @extends {Component} */ export class ChatFoot extends Component { constructor(props) { super(props); this.state = { imgbm : ["/::)", "/::~", "/::B", "/::|", "/:8-)", "/::<", "/::$", "/::X", "/::Z", "/::’(", "/::-|", "/::@", "/::P", "/::D", "/::O", "/::(", "/::+", "/:–b", "/::Q", "/::T", "/:,@P", "/:,@-D", "/::d", "/:,@o", "/::g", "/:|-)", "/::!", "/::L", "/::>", "/::,@", "/:,@f", "/::-S", "/:?", "/:,@x", "/:,@@", "/::8", "/:,@!", "/:!!!", "/:xx", "/:bye", "/:wipe", "/:dig", "/:handclap", "/:@-(", "/:B-)", "/:<@", "/:@>", "/::-O", "/:>-|", "/:P-(", "/::’|", "/:X-)", "/::*", "/:@x", "/:8*", "/:pd", "/:<W>", "/:eat", "/:miao", "/:ill", "/:friend", "/:money", "/:pig", "/:v5", "/:good", "/:ok", "/:thanks", "/:shackhand", "/:ye", "/:break"], img_intro : ["[微笑]", "[撇嘴]", "[色]", "[发呆]", "[得意]", "[流泪]", "[害羞]", "[闭嘴]", "[睡]", "[大哭]", "[尴尬]", "[发怒]", "[调皮]", "[呲牙]", "[惊讶]", "[难过]", "[酷]", "[汗]", "[抓狂]", "[吐]", "[偷笑]", "[快乐]", "[白眼]", "[傲慢]", "[饿]", "[困]", "[惊恐]", "[汗]", "[憨笑]", "[悠闲]", "[努力]", "[咒骂]", "[疑问]", "[嘘]", "[晕]", "[疯了]", "[哀]", "[骷髅]", "[敲打]", "[再见]", "[汗]", "[擦汗]", "[鼓掌]", "[糗大了]", "[坏笑]", "[左哼哼]", "[右哼哼]", "[哈欠]", "[鄙视]", "[委屈]", "[快哭了]", "[阴险]", "[亲亲]", "[爱心]", "[思考]", "[笑哭]", "[好吃]", "[喵]", "[生病]", "[互粉]", "[要钱]", "[猪头]", "[给力]", "[威武]", "[棒]", "[没问题]", "[抱拳]", "[握手]", "[欧耶]", "[心碎]"], icon_face : [] }; } chatAddFace(e){ document.querySelector('.upload-content').style.display="none"; document.querySelector('.face-content').style.display="block"; setTimeout(chatMainInit,200); } chatAddPic(e){ document.querySelector('.face-content').style.display="none"; document.querySelector('.upload-content').style.display="block"; setTimeout(chatMainInit,200); } writeFace(e){//表情输入 let faceImgSrc = e.target.src; let node=document.createElement("img"); node.setAttribute("src", faceImgSrc ); document.querySelector('.input-msg').appendChild(node); } chatSendInfo(e){ let addHtml = `<div class = "chat-item-news"> <div class="news-content news-content-my"> <div class="content-chat-area"> <div class="content-chat-main" data-type="1"> 司法斯蒂芬<img src="/src/Pic/facePic/wx_1.png" /> <img src="/src/Pic/facePic/wx_2.png" /> 是否是司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬司法斯蒂芬 <img src="/src/Pic/facePic/wx_3.png" /> </div> </div> <div class="send-head-pic sender_head_my"> <img src="/src/Pic/user_log_default.png" /> </div> </div> </div>` document.querySelector('.input-msg').innerHTML = ""; document.querySelector('.upload-content').style.display="none"; document.querySelector('.face-content').style.display="none"; document.querySelector('.chatMain-area').innerHTML += addHtml; document.querySelector('.input-msg').focus(); } chatInputFocus(e){ setTimeout(chatMainInit,200); } componentDidMount(){ } render() { const This = this; let arr1 = This.state.imgbm; let newArry = []; for(let i=1;i<=arr1.length;i++){ newArry.push( <img onClick={this.writeFace} key={i} src={`/src/Pic/facePic/wx_${i}.png`} /> ) } return ( <div className = "chatFoot-box"> <div className = "chatFoot-top"> <div className = "chatFoot-top-left"> <i className = "iconfont icon-add-face" onClick ={this.chatAddFace.bind(this)}></i> <i className = "iconfont icon-add-pic" onClick ={this.chatAddPic.bind(this)}></i> </div> <div className = "chatFoot-top-middle"> <div className="input-msg" contentEditable="true" onFocus = {this.chatInputFocus.bind(this)} ></div> </div> <div className = "chatFoot-top-right"> <input className = "input-send" type="button" value="发送" id ="input-send" onClick ={this.chatSendInfo.bind(this)} /> </div> </div> <div className = "chatFoot-bottom"> <div className = "face-content"> {newArry} </div> <div className = "upload-content"> <span className = "img-upload"> <i className = "iconfont icon-add-img"></i> </span> <img src={`/src/Pic/menu01.jpg`} /> <img src={`/src/Pic/menu01.jpg`} /> <img src={`/src/Pic/menu01.jpg`} /> <img src={`/src/Pic/menu01.jpg`} /> <img src={`/src/Pic/menu01.jpg`} /> </div> </div> </div> ); } } /** * 底部导航菜单 * * @export * @class Footer * @extends {Component} */ class FooterInit extends Component { constructor(props) { super(props); this.state = { messageCount: 0 }; this.getMessageCount = () => { var accesstoken = this.props.User ? this.props.User.accesstoken : ''; if (accesstoken) { Tool.get('/api/v1/message/count', { accesstoken }, (res) => { this.setState({ messageCount: res.data }); }); } } } render() { var myUrl = this.props.User && this.props.User.loginname ? '/user/' + this.props.User.loginname : '/signin'; var arr = []; arr[this.props.index] = 'on'; return ( <footer className="common-footer"> <div className="zhanwei"></div> <ul className="menu" data-flex="box:mean"> <li className={arr[0]}> <Link to="/"> <i className="iconfont icon-home"></i>首页 </Link> </li> <li className={arr[1]}> <Link to="/topic/create"> <i className="iconfont icon-category"></i>分类 </Link> </li> <li className={arr[2]}> <Link to={myUrl}> <i className="iconfont icon-cart"></i>购物车 </Link> </li> <li className={arr[3]}> <Link to="/my/wechat"> <i className="iconfont icon-user"></i>个人中心 </Link> </li> </ul> </footer> ); } componentDidMount() { this.getMessageCount(); } shouldComponentUpdate(np, ns) { return this.props.index !== np.index || this.state.messageCount !== ns.messageCount; //防止组件不必要的更新 } componentDidUpdate() { this.getMessageCount(); } } FooterInit.defaultProps = { index: 0 }; var Footer = connect((state) => { return { User: state.User }; }, action('User'))(FooterInit); export { Footer } /** * 模块入口 * * @class Main * @extends {Component} */ class Main extends Component { constructor(props) { super(props); } JudgeState(e){ if(document.querySelector('.chatHead')){//判断是否是聊天页面 chatMainInit(); } } componentDidMount(e){ this.JudgeState(); } render() { console.log(this.props.state); return ( <div> <ChatHead /> <ChatMain /> <ChatFoot /> </div> ); } componentDidMount(){ setTimeout(this.chatMainInit,100); } chatMainInit(){//聊天内容滚动 let headHeight = document.querySelector('.chatHead').offsetHeight; let footHeight = document.querySelector('.chatFoot-box').offsetHeight; let bodyHeight = document.documentElement.clientHeight || document.body.clientHeight; let chatMainDom = document.querySelector('.chatMain-box'); let chatAreaHeight = document.getElementById('chatMainArea').offsetHeight; let heightDistance = 0; let heightScroll = 0; heightDistance = bodyHeight - headHeight - footHeight; chatMainDom.style.height = heightDistance +"px"; heightScroll = chatAreaHeight - heightDistance; chatMainDom.scrollTop = heightScroll; } } Main.contextTypes = { router: React.PropTypes.object.isRequired } //export default connect((state) => { return { User: state.User } }, action('Product'))(Main); //连接redux export default GetData({ id: 'WeChat', //应用关联使用的redux component: Main, //接收数据的组件入口 url: '/product/getProductList?site_id=100166&access_token=123456789098765432123456789124566', //服务器请求的地址 success: (state) => {console.log(state); return state; }, //请求成功后执行的方法 error: (state) => { return state } //请求失败后执行的方法 });
import React from 'react' import ExpandMoreIcon from '@material-ui/icons/ExpandMore' import Typography from '@material-ui/core/Typography' import Accordion from '@material-ui/core/Accordion' import AccordionSummary from '@material-ui/core/AccordionSummary' import AccordionDetails from '@material-ui/core/AccordionDetails' import { Episodes } from './Episodes/Episodes' import { makeStyles } from '@material-ui/core/styles' const useStyles = makeStyles((theme) => ({ root: { borderRadius: '10px', background: '#369457', position: 'unset', color: 'white', width: '80%', }, heading: { fontSize: theme.typography.pxToRem(20), fontWeight: theme.typography.fontWeightRegular, }, details: { backgroundColor: 'white', color: 'black', padding: '2%', }, dark: { marginTop: '10%', backgroundColor: 'white', padding: '20px 50px', borderRadius: '5rem', margin: '5% 5% 0% 5%', }, })) export const CardSeason = (props) => { const { season } = props const classes = useStyles() return ( <div style={{ margin: '3% 0% 0% 18%' }}> {season && ( <Accordion className={classes.root}> <AccordionSummary expandIcon={ <ExpandMoreIcon style={{ color: 'white' }} /> } aria-controls="panel1a-content" id="panel1a-header" > <Typography className={classes.heading}> Season {season} </Typography> </AccordionSummary> <AccordionDetails className={classes.details}> <Episodes {...props} season={season} /> </AccordionDetails> </Accordion> )} </div> ) } export const SeasonPresenter = (props) => { return <CardSeason {...props} /> }
export const GET_FOLLOWERS = "GET_FOLLOWERS"; export const GET_FOLLOWINGS = "GET_FOLLOWINGS"; export const TOGGLE_FOLLOW = "TOGGLE_FOLLOW";
if (window.console) { console.log("Welcome to your Play application's JavaScript!"); } $(document).ready(function () { $(".menu-icon").on("click", function () { $("nav ul").toggleClass("showing"); }); }); // Scrolling Effect $(window).on("scroll", function () { if ($(window).scrollTop()) { $('nav').addClass('black'); } else { $('nav').removeClass('black'); } }); function openNav() { document.getElementById("mySidenav").style.width = "250px"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; }
/*################################################# For: SSW 322 By: Bruno, Hayden, Madeline, Miriam, and Scott #################################################*/ const accountSid = require('../../private').ACCOUNT_SID; const authToken = require('../../private').AUTH_TOKEN; const client = require('twilio')(accountSid, authToken); function codeGen(min, max) { return Math.floor( Math.random() * (max - min) + min ) } var sendText = (number, code, callback) => { client.messages.create({ body: "Use " + code + " as your verification code for Atticus!", from: '+14243469443', to: number }) .then((message, error) => callback(code) ).catch( error => { callback(error) }) }; module.exports = async function (req, res) { if(!req.params.phoneNumber) { return res.status(400).send('Missing phoneNumber') } sendText(req.params.phoneNumber, codeGen(100000, 999999), function(code) { res.json({ code: code }); }); }
var text = "Hello" console.log(text)
function initMap() { var uluru = {lat: 49.98146 , lng: 6.4390300000000025 }; var map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center: uluru }); var marker = new google.maps.Marker({ position: uluru, map: map }); } function myFunction1() { var x = document.getElementById("myDIV"); var y = document.getElementById("myDIV2"); var z = document.getElementById("myDIV3"); x.style.display = "block"; y.style.display = "none"; z.style.display = "none"; } function myFunction2() { var x = document.getElementById("myDIV"); var y = document.getElementById("myDIV2"); var z = document.getElementById("myDIV3"); y.style.display = "block"; x.style.display = "none"; z.style.display = "none"; } function myFunction3() { var x = document.getElementById("myDIV"); var y = document.getElementById("myDIV2"); var z = document.getElementById("myDIV3"); z.style.display = "block"; x.style.display = "none"; y.style.display = "none"; } $(function(){ $('.navbar').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('.navbar').data('size') == 'big') { $('.navbar').data('size','small'); $('.navbar').stop().animate({ height:'50px' },600); } } else { if($('.navbar').data('size') == 'small') { $('.navbar').data('size','big'); $('.navbar').stop().animate({ height:'100px' },600); } } }); $(function(){ $('.navbar-brand').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('.navbar-brand').data('size') == 'big') { $('.navbar-brand').data('size','small'); $('.navbar-brand').stop().animate({ width:'70px' },600); } } else { if($('.navbar-brand').data('size') == 'small') { $('.navbar-brand').data('size','big'); $('.navbar-brand').stop().animate({ width:'200px' },600); } } }); $(function(){ $('.nav').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('.nav').data('size') == 'big') { $('.nav').data('size','small'); $('.nav').stop().animate({ height:'50px' },600); } } else { if($('.nav').data('size') == 'small') { $('.nav').data('size','big'); $('.nav').stop().animate({ height:'100px' },600); } } }); $(function(){ $('.navbar-sites').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('.navbar-sites').data('size') == 'big') { $('.navbar-sites').data('size','small'); $('.navbar-sites').stop().animate({ height:'50px' },600); } } else { if($('.navbar-sites').data('size') == 'small') { $('.navbar-sites').data('size','big'); $('.navbar-sites').stop().animate({ height:'100px' },600); } } }); $ (document).ready(function(){ // Add smooth scrolling to all links in navbar + footer link $(".navbar a, footer a[href='#Startseite']").on('click', function(event) { // Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault(); // Store hash var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll // The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 900, function(){ // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if }); $(window).scroll(function() { $(".slideanim").each(function(){ var pos = $(this).offset().top; var winTop = $(window).scrollTop(); if (pos < winTop + 600) { $(this).addClass("slide"); } }); }); })