text
stringlengths 7
3.69M
|
|---|
import { connect } from 'react-redux';
import { fetchBlogItem, postComment } from '../actions/index';
// 1. Import Component: Smart
import BlogItemPage from '../components/BlogItemPage';
const mapActionCreators = {
fetchBlogItem,
postComment
};
const mapComments = (embeddedComments) => {
let comments = [];
let commentsMapped = {};
let commentsArr = [];
if (embeddedComments && embeddedComments instanceof Array && embeddedComments.length > 0) {
comments = embeddedComments[0];
}
if (!(comments instanceof Array)) {
comments = [];
}
comments.map(function (comment) {
const id = comment.id;
const parent = comment.parent;
if (parent === 0) {
commentsMapped[id] = comment;
commentsMapped[id].replies = [];
commentsArr.push(commentsMapped[id]);
} else {
commentsMapped[parent].replies.push(comment);
}
});
return {
total: comments.length,
comments: commentsArr
};
};
const mapData = (post) => {
const contentO = post.content || {};
const content = contentO.rendered || '';
let text = contentO.rendered;
let leadText = '';
const contentArr = content.split('<!--more-->');
if (contentArr instanceof Array && contentArr.length > 0) {
leadText = contentArr[0];
text = contentArr[1];
}
const acf = post.acf || {};
const leadTitle = acf.subtitle || '';
const _embedded = post._embedded || {};
const title = post.title || {};
const authors = _embedded.author || [];
const author = authors[0] || {};
const avatar = author.avatar_urls || {};
const avatarUrl = avatar[96] || '';
let imageMedium = '';
try {
imageMedium = post._embedded['wp:featuredmedia'][0].media_details.sizes.medium.source_url;
} catch (err){}
const comments = mapComments(_embedded.replies);
return {
subtitle: contentO.rendered,
leadTitle: leadTitle,
title: title.rendered,
leadText: leadText,
text: text,
image: post.featured_image_url,
content: content,
date: post.date,
slug: post.slug,
tags: post.tags,
id: post.id,
comments: comments,
author: {
avatar: avatarUrl,
name: author.name,
url: author.url,
description: author.description
},
imageMedium: imageMedium
};
};
// 2. Use only part of global state data
const mapStateToProps = (state) => {
return ({
post: mapData(state.post.getPost.post),
isLoading: state.post.getPost.fetching,
isSending: state.post.postComment.sending,
isSent: state.post.postComment.sent,
comment: state.post.postComment.comment,
all: state
});
}
// 3. Make it Smart with connect
export default connect(mapStateToProps, mapActionCreators)(BlogItemPage)
|
import React, { useState, useEffect, useContext } from 'react';
import { Link } from 'react-router-dom';
import Rating from '../utils/Rating';
import ProfileContext from '../../context/profile/profileContext';
import ReviewContext from '../../context/review/reviewContext';
const HeaderRating = () => {
const profileContext = useContext(ProfileContext);
const reviewContext = useContext(ReviewContext);
const { language } = profileContext;
const { reviews, getReviews } = reviewContext;
useEffect(() => {
getReviews();
// eslint-disable-next-line
}, []);
useEffect(() => {
updateGlobalRating();
// eslint-disable-next-line
}, [reviewContext, reviews]);
const [globalRating, setGlobalRating] = useState(0);
const updateGlobalRating = () => {
if(reviews?.length > 0) {
const sum = reviews.reduce((acc, review) => {
return review.rating ? acc + review.rating : acc;
}, 0);
const note = sum / reviews.length <= 5 ? sum / reviews.length : 5;
setGlobalRating(note);
}
}
return (
<div className="main-rating">
<h1>{globalRating.toFixed(1)}</h1>
<Rating rating={globalRating}/>
<Link exact="true" to="/reviews">{language === 'en' ? 'Evaluation' : 'Évaluation'}</Link>
</div>
);
}
export default HeaderRating;
|
import React from "react";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {faTwitter, faFacebook,faLinkedin, faGithub} from "@fortawesome/free-brands-svg-icons";
export default function Home() {
return(
<main id="home">
<h1 className="lg-heading">Roman <span className="text-secondary">Legun</span></h1>
<h2 className="sm-heading">Web developer, Programmer, Designer & Entrepreneur</h2>
<div className="icons">
<a href="#"><FontAwesomeIcon icon={faTwitter} size="lg"/></a>
<a href="#"><FontAwesomeIcon icon={faFacebook} size="lg"/></a>
<a href="#"><FontAwesomeIcon icon={faLinkedin} size="lg"/></a>
<a href="#"><FontAwesomeIcon icon={faGithub} size="lg"/></a>
</div>
</main>
)
}
|
/* global Restaurant */
var Food = {
controller: {
create: function (form) {
var newFood = {
name: form.name.value,
course: form.course.value,
price: form.price.value,
restaurantId: form.restaurantId.value
};
Food.model.create(
newFood,
function success() {
Restaurant.controller.show(form.restaurantId.value);
},
function error(err) {
$('#error-message').html(err.responseJSON.message);
}
);
}
},
model: {
create: function (data, success, error) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/foods',
data: data,
success: success,
error: error
});
}
}
};
|
import React, { useReducer, useEffect } from 'react';
// Routers
import MainRouter from './routes/MainRouter'
// Store
import authenticationReducer from './store/reducers/authenticationReducer';
// Context
import AuthContext from './context/authContext';
const init = () => JSON.parse(localStorage.getItem('user')) || { isLogged: false };
const MainApp = () => {
const [user, dispatch] = useReducer(authenticationReducer, {}, init);
useEffect(() => {
localStorage.setItem('user', JSON.stringify(user));
}, [user])
return (
<div>
<AuthContext.Provider value={{ user, dispatch }}>
<MainRouter />
</AuthContext.Provider>
</div>
);
};
export default MainApp;
|
function reverseTitle(s) {
return s
.toLowerCase()
.split(' ')
.map((x) => x.slice(0, 1) + x.slice(1).toUpperCase())
.join(' ');
}
const result = reverseTitle('Elephants dance about bravely in Thailand');
console.log(result);
// String.prototype.reverseTitle = function() {
// return this.toUpperCase().replace(/\b./g, m => m.toLowerCase());
// };
// const reverseCapitalize = str =>
// str[0].toLowerCase() + str.slice(1).toUpperCase();
// const reverseTitle = str => str.split(' ').map(reverseCapitalize).join(' ');
|
var ko = require('knockout');
var _ = require('lodash');
var cuid = require('cuid');
var md = require('./markdown');
var fs = require('fs');
var path = require('path');
require('./tutor-task-markdown')
var ViewModel = function (params) {
this.task = ko.utils.unwrapObservable(params.task);
this.showModelSolutionPreview = params.showModelSolutionPreview;
this.testResults = params.task.testResults;
this.autoRefresh = params.autoRefresh || ko.observable(true);
this.renderedSolution = ko.computed(function() {
if (this.task.tests) {
return this.task.tests() + "\n\n" + this.task.solution();
} else {
return this.task.solution();
}
}.bind(this));
};
ko.components.register('tutor-task-preview', {
template: fs.readFileSync(path.join(__dirname, 'task_preview.html'), 'utf8'),
viewModel: ViewModel
});
|
const toString = Object.prototype.toString;
export const isFunction = function isFunction(obj) {
return toString.call(obj) === '[object Function]';
};
export const isObj = function isObj(obj) {
return toString.call(obj) === '[object Object]';
};
export const isArray = function(obj) {
return toString.call(obj) === '[object Array]';
};
export const deepCopy = function(p, co) {
const c = co || {};
for (const i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
};
export const getUrlParam = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
const p = window.location.search;
const r = p && p.substr(1);
const m = r.match(reg);
const val = m && m.length > 1 && decodeURI(unescape(m[2])) || '';
const result = val && val.replace('>', '>').replace('<', '>');
return result;
};
export const date = {
parse(date) {
// debugger
let timestamp = Date.parse(date);
if (isNaN(timestamp) == true) {
timestamp = Date.parse(new Date());
}
return timestamp;
},
format(timestamp, type) {
const date = new Date(timestamp);
let dd = date.getDate(); // after 2 day
let mm = date.getMonth() + 1; // January is 0!
const yyyy = date.getFullYear();
let res;
if (type == 'zh') {
res = yyyy + '年' + mm + '月' + dd + '日';
} else {
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
res = yyyy + '-' + mm + '-' + dd;
}
return res;
}
};
export const throttle = (fn, delay, mustRunTime) => {
let timer = null;
let tStart;
return function() {
const content = this;
const arg = arguments;
const tCurr = +new Date();
clearTimeout(timer);
if (!tStart) {
tStart = tCurr;
} else if (tCurr - tStart >= mustRunTime) {
fn.apply(content, arg);
tStart = tCurr;
} else {
timer = setTimeout(() => {
fn.apply(content, arg);
}, delay);
}
};
};
export const getCsrf = () => {
const keyValue = document.cookie.match('(^|;) ?csrfToken=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
};
export const formateDate = (date) => {
if (date.constructor !== Date) return console.log("数据格式不正确");
const result = {};
result.year = date.getFullYear();
result.month = date.getMonth() + 1;
result.date = date.getDate();
result.hour = date.getHours();
result.minutes = date.getMinutes();
result.second = date.getSeconds();
return `${result.year}-${result.month}-${result.date} ${result.hour}:${result.minutes}:${result.second}`;
}
export const IsPC = () => {
const userAgentInfo = navigator.userAgent;
console.log('userAgentInfo',userAgentInfo)
const Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
let flag = true;
for (let v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
}
return flag;
}
|
(function($){
// window.onload = function() {
// setInterval(function() {
// $('body').removeClass('overlay');
// }, 3000);
// setTimeout(function() {
// $(document.body).scrollLeft(0);
// }, 5);
// };
$(window).keydown(function(e) {
var scrollWidth = ($(window).width()/3);
var enterButton = ((e.which == 13) || (e.which === 13))
var arrowDown = (e.which == 40)
var arrowUp = (e.which == 38)
var arrowLeft = (e.which == 37)
var arrowRight = (e.which == 39)
var squareButton = (e.which == 83)
var swipeUp = (e.which == 187)
var swipeDown = (e.which == 189)
if (arrowDown && (!$('body').hasClass('mtc-on')) && (!$('body').hasClass('timeline-on')) && (!$('body').hasClass('drawer-on'))) {
$('body').addClass('top');
}
if (arrowUp && ($('body').hasClass('top'))) {
setTimeout(function () {
$('body').removeClass('top');
}, 5);
}
if (arrowRight && (!$('body').hasClass('top')) && (!$('body').hasClass('mtc-on')) && (!$('body').hasClass('timeline-on')) && (!$('body').hasClass('drawer-on'))) {
$('body').addClass('end');
}
if (arrowLeft && ($('body').hasClass('end')) && (!$('body').hasClass('top')) && (!$('body').hasClass('mtc-on')) && (!$('body').hasClass('timeline-on')) && (!$('body').hasClass('drawer-on'))) {
setTimeout(function () {
$('body').removeClass('end');
}, 5);
}
if (enterButton && (!$('body').hasClass('top')) && (!$('body').hasClass('mtc-on')) && (!$('body').hasClass('timeline-on')) && (!$('body').hasClass('drawer-on'))) {
setTimeout(function () {
$('body').addClass('mtc-on');
}, 5);
}
if (arrowDown && ($('body').hasClass('mtc-on'))) {
setTimeout(function () {
$('body').addClass('timeline-on');
$('body').removeClass('mtc-on');
}, 5);
}
if (enterButton && (!$('body').hasClass('top')) && ($('body').hasClass('mtc-on')) && (!$('body').hasClass('timeline-on')) && (!$('body').hasClass('drawer-on'))) {
$('body').removeClass('mtc-on');
}
if (arrowDown && ($('body').hasClass('timeline-on'))) {
setTimeout(function () {
$('body').addClass('milestones-on');
}, 5);
}
if (arrowUp && ($('body').hasClass('timeline-on')) && (!$('body').hasClass('milestones-on'))) {
setTimeout(function () {
$('body').removeClass('timeline-on');
$('body').addClass('mtc-on');
}, 5);
}
if (arrowUp && ($('body').hasClass('milestones-on'))) {
setTimeout(function () {
$('body').removeClass('milestones-on');
}, 5);
}
if (arrowDown && ($('body').hasClass('milestones-on'))) {
setTimeout(function () {
$('body').addClass('drawer-on stats-on');
$('body').removeClass('timeline-on');
$('body').removeClass('milestones-on');
}, 5);
}
if (arrowUp && ($('body').hasClass('drawer-on stats-on'))) {
setTimeout(function () {
$('body').removeClass('drawer-on stats-on');
$('body').addClass('timeline-on');
$('body').addClass('milestones-on');
}, 5);
}
if (arrowRight && ($('body').hasClass('stats-on'))) {
setTimeout(function () {
$('body').addClass('highlights-on');
}, 5);
$('body').removeClass('stats-on');
}
if (arrowRight && ($('body').hasClass('highlights-on'))) {
setTimeout(function () {
$('body').addClass('boxscore-on');
}, 5);
$('body').removeClass('highlights-on');
}
if (arrowRight && ($('body').hasClass('boxscore-on'))) {
setTimeout(function () {
$('body').addClass('todaysgames-on');
}, 5);
$('body').removeClass('boxscore-on');
}
if (arrowRight && ($('body').hasClass('todaysgames-on'))) {
setTimeout(function () {
$('body').addClass('settings-on');
}, 5);
$('body').removeClass('todaysgames-on');
}
if (arrowLeft && ($('body').hasClass('highlights-on'))) {
setTimeout(function () {
$('body').addClass('stats-on');
}, 5);
$('body').removeClass('highlights-on');
}
if (arrowLeft && ($('body').hasClass('boxscore-on'))) {
setTimeout(function () {
$('body').addClass('highlights-on');
}, 5);
$('body').removeClass('boxscore-on');
}
if (arrowLeft && ($('body').hasClass('todaysgames-on'))) {
setTimeout(function () {
$('body').addClass('boxscore-on');
}, 5);
$('body').removeClass('todaysgames-on');
}
if (arrowLeft && ($('body').hasClass('settings-on'))) {
setTimeout(function () {
$('body').addClass('todaysgames-on');
}, 5);
$('body').removeClass('settings-on');
}
if (arrowDown && ($('body').hasClass('boxscore-on'))) {
setTimeout(function () {
$('body').addClass('boxscore-focused');
}, 5);
}
if (arrowUp && ($('body').hasClass('boxscore-on'))) {
setTimeout(function () {
$('body').removeClass('boxscore-focused');
}, 5);
}
if (squareButton && (!$('body').hasClass('details-focused'))) {
$('body').toggleClass('pitcherbox-on');
}
});
// $(window).on('DOMMouseScroll mousewheel', function (e) {
// var swipeDown=(e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0);
// var swipeUp=(e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0);
// if (swipeUp && ($('body').hasClass('top'))) {
// clearTimeout(timeout);
// timeout = setTimeout(function() {
// $('body').removeClass('top');
// }, 40);
// }
// if (swipeDown && (!$('body').hasClass('overlay')) && (!$('body').hasClass('bottom')) && (!$('body').hasClass('mtc'))) {
// $('body').addClass('top');
// }
// if (swipeUp && (!$('body').hasClass('overlay')) && (!$('body').hasClass('top')) && (!$('body').hasClass('mtc'))) {
// $('body').addClass('bottom');
// $('upnexttile').navigate('destroy');
// }
// if (swipeDown && ($('body').hasClass('bottom')) && (!$('body').hasClass('menu'))) {
// clearTimeout(timeout);
// timeout = setTimeout(function() {
// $('body').removeClass('bottom');
// }, 40);
// }
// if (swipeDown && ($('body').hasClass('menu'))) {
// $('body').removeClass('menu');
// }
// var eo = e.originalEvent;
// if(Math.abs(eo.wheelDeltaY) < 10 && Math.abs(eo.wheelDeltaX) > 2){
// e.preventDefault();
// if(eo.wheelDeltaX < -100){
// // swipe left
// console.log('left');
// }
// if(eo.wheelDeltaX > 100){
// // swipe right
// console.log('right');
// }
// }
// //prevent page fom scrolling
// return false;
// });
})(jQuery);
|
const Log = (...data) => console.log("[DEBUG]", ...data);
const Storage = {
get: key =>
new Promise(resolve => chrome.storage.sync.get([key], resolve)).then(
d => d[key]
),
set: (key, value) => {
let o = {};
o[key] = value;
return new Promise(resolve => chrome.storage.sync.set(o, resolve));
}
};
const ActiveTab = () =>
new Promise(res => {
chrome.tabs.query({ active: true, currentWindow: true }, res);
}).then(r => r[0]);
const getObjectFromArrayByUrl = (array, url) => {
let data;
array.find((el, i) => {
if (el.url == url) data = array[i];
});
return data;
};
function reportLink(link, result, message, link) {
let containerContent = $(".main__container__content");
containerContent.prepend("<a href="+ link + " id='buttonSeeReport'></a>");
containerContent.prepend("<div id='containerText'></div>");
$("#buttonSeeReport")
.addClass("main__container__button main__container__button_" + result)
.text("Смотреть отчет");
$("#containerText")
.addClass("main__container__text main__container__text_" + result)
.text(message);
}
async function dataResult(message, link) {
$("#buttonSeeReport").remove();
$("#containerText").remove();
switch (message) {
case "warning":
reportLink("url", message, "Предупреждение", link);
break;
case "danger":
reportLink("url", message, "Опасность", link);
break;
case "secure":
$(".main__container__content").prepend("<div id='containerText'></div>");
$("#containerText")
.addClass("main__container__text main__container__text_secure")
.text("Страница безопасна");
break;
default:
$(".main__container__content").prepend("<div id='containerText'></div>");
$("#containerText")
.addClass("main__container__text")
.text("Идет загрузка...");
}
}
const onButtonClickMore = () => sendMessage({ type: "onRequestFetch" });
document.addEventListener("DOMContentLoaded", async function() {
Log("Start Application");
// let { url } = await ActiveTab();
// let urls = await Storage.get("urls");
// Log(`[DOMContentLoaded] url: ${url}`);
// if (urls.some((el, i) => el.url == url)) {
// Log(`[DOMContentLoaded] url is exist: ${url}`);
// let { result } = getObjectFromArrayByUrl(urls, url);
// dataResult(result);
// } else {
// Log(`[DOMContentLoaded] url is not exist: ${url}`);
onButtonClickMore();
// }
$("#buttonCheckMore").click(() => sendMessage({ type: "onRequestFetch" }));
});
const sendMessage = data => {
Log("sendMessage", data.type);
chrome.runtime.sendMessage(data);
};
chrome.runtime.onMessage.addListener(function(msg) {
Log("onMessage", msg.type, msg.data);
switch (msg.type) {
case "onResponseSuccess":
dataResult(msg.data.result, msg.data.link);
break;
case "onWaitRequest":
dataResult("waiting");
break;
case "onResponseError":
Log(msg.data);
break;
}
});
|
class Slide extends Directional {
private var firstPoint:Vector3;
private var lastPoint:Vector3;
// Project p onto axis. i.e., we don't care about being to the side of the axis.
function constrain(axis:Transform, p:Vector3):Vector3 {
var vNormalized = axis.right;
var dot = Vector3.Dot(vNormalized, p - firstPoint); // Use Vector3.Project instead?
var proj = dot * vNormalized;
return firstPoint + proj;
}
function startDragging(assembly:Transform, axis:Transform, plane:Transform, cameraRay:Ray, hit:RaycastHit) {
plane.rotation = Quaternion.LookRotation(axis.right, -Camera.main.transform.forward);
plane.position = firstPoint = lastPoint = hit.point;
return plane.GetComponent.<Collider>();
}
function doDragging(assembly:Transform, axis:Transform, plane:Transform, hit:RaycastHit) {
plane.position = constrain(axis, hit.point);
assembly.position = assembly.position + plane.position - lastPoint;
lastPoint = plane.position;
var v = assembly.localPosition;
Application.ExternalCall('updatePosition', v.x, v.y, v.z);
}
}
|
// Repeat a message in SPonGEbOB CaSe
module.exports = {listeners: [
{
type: "regex",
query: /^\.(sb|sponge|spongebob) +(.+)/i,
callback: function(reply, message, api, match){
var str = match[2];
var out = "";
// Try up to 10 times to get random-looking case
for(var i = 0; i < 10; i++){
out = spongebob(str);
if(out !== str && out !== str.toUpperCase() && out !== str.toLowerCase())
break;
}
reply(out);
}
}
]};
function spongebob(str){
var out = "";
for(var i = 0; i < str.length; i++){
if(Math.random() < .5)
out += str[i].toUpperCase();
else
out += str[i].toLowerCase();
}
return out;
}
|
//1. 引入express
const express = require('express');
const { request } = require('http');
//2. 创建应用对象
const app = express();
//3.创建路由归责 request 是对请求报文的封装 response 是对响应报文的封
app.get('/',(request,response) => {
//设置响应
response.send('hello express');
});
//监听端口启动服务
app.listen(8000, ()=>{
console.log("服务已经启动,8000 端口监听中...");
})
app.get('/delay',(request,response) => {
//设置响应头,允许跨域
setTimeout(() => {
response.send('延时响应');
},3000)
});
|
/* Creator : ABDUL BASITH A */
/* Email : ambalavanbasith@gmail.com */
/* github : abdulbasitha */
/* More Info : https://techzia.in */
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Button,
TouchableOpacity,
TextInput,
Image,
SafeAreaView,
Alert,
} from "react-native";
// import cio from 'cheerio-without-node-native';
import firebase, { auth } from "firebase";
import config from '../config/firebase';
import { Drawer } from "react-native-router-flux";
import { readBuilderProgram } from "typescript";
import Login from "./LoginScreen";
import Geolocation from '@react-native-community/geolocation';
import Geocoder from 'react-native-geocoding';
class Home extends Component {
state ={
lat : null,
lng : null,
place:null,
dist:null,
count:0,
htmlcode:null,
places:[],
responseCode:null
}
getData(){
// const $ = require('react-native-cheerio');
Geocoder.init("AIzaSyChiwupcs4om20XFLC7iylVTO5Ef6OTH90",{language : "en"});
Geocoder.from(this.state.lat, this.state.lng).then(
json => {
var addressComponent = json.results[0].address_components[1];
//console.log(addressComponent);
console.log("check",json.results[0].address_components[5])
this.setState({
place:addressComponent.long_name,
dist:json.results[0]
})
this.loadGraphicCards()
}).catch(error => console.warn(error)
);
error=>{
alert(error);
}
}
place_check = ()=>{
if(this.state.responseCode == 404){
if(this.state.count==0){
this.loadGraphicCards(this.state.dist.address_components[3].long_name)
this.setState({count:1})
return
}
else if(this.state.count==1){
this.loadGraphicCards(this.state.dist.address_components[0].long_name)
this.setState({count:2})
return
}
else if(this.state.count==2){
this.loadGraphicCards(this.state.dist.address_components[1].long_name)
this.setState({count:3})
return
}
else if(this.state.count==3){
this.loadGraphicCards(this.state.dist.address_components[4].long_name)
this.setState({count:4})
return
}
else if(this.state.dist.address_components[3].short_name){
this.setState({count:5})
return
}
}
}
loadGraphicCards=(dis = this.state.dist.address_components[2].long_name) => {
var quizUrl = `https://www.holidify.com/places/${dis}/sightseeing-and-things-to-do.html`;
console.log(quizUrl)
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'text/html');
var data = fetch(quizUrl,{
mode: 'no-cors',
method: 'get',
headers: myHeaders
}).then((response)=> {
if(response.status==404){
this.setState({responseCode:404})
this.place_check()
return
}else{
this.setState({responseCode:response.status})
console.log("new res",response.status)
this.setState({dist:dis})
}
response.text()
.then(html=>{
this.setState({
htmlcode:html
})
// console.log(code)
this.extract()
// console.log(html)
})
})
// console.log("code",this.state.responseCode)
// if(this.state.responseCode==404){
// console.log("code",this.state.responseCode)
// }
}
extract =()=>{
// Alert.alert("ok")
// console.log(this.state.htmlcode)
const cheerio = require('react-native-cheerio')
const $ = cheerio.load(this.state.htmlcode)
// console.log($('#attractionList').html())
$('#attractionList').html()
// console.log($('div',$('#attractionList').html()).html())
//console.log($('div',$('#attractionList').html()).html())
//console.log($('.content-card',$('#attractionList'))[0])
data = $('div',$('.content-card',$('#attractionList'))).html()
// console.log($('div',$('.content-card',$('#attractionList'))))
// console.log($(data).html())
// console.log($('h3',dataurl).text()) //place name
// console.log($('img',dataurl).data().original) // image url
// console.log($('.card-text',dataurl).text()) // description
data = []
let limit = $('.content-card',$('#attractionList')).length
// console.log(limit)
for(let i=0;i<limit;i++){
// console.log(i)
let dataurl = $('.content-card',$('#attractionList'))[i]
temp = {}
temp["place_name"] = $('h3',dataurl).text()
temp["image_url"] = $('img',dataurl).data().original
temp["desc"] = $('.card-text',dataurl).text()
temp["view_more"]=$('a',$(dataurl).html())[0].attribs.href
data.push(temp)
//console.log("near:",this.state.dist)
}
//console.log(data)
this.setState({
places:data
})
}
constructor(){
super()
Geolocation.watchPosition(
info =>{
this.setState({
lat:info.coords.latitude,
lng:info.coords.longitude,
})
this.getData()
});
}
render() {
return (
<SafeAreaView style={styles.container}>
{/* <TouchableOpacity onPress={()=>{this.getData()}}>
<Text>Address</Text>
</TouchableOpacity> */}
<View style={styles.SquareShapeView} >
<TouchableOpacity style={{alignSelf: "flex-start", marginleft: 15,marginTop:10}} onPress={this.props.navigation.openDrawer}>
<Image
source={require('./images/drawer.png')}
style={{ width: 36.5, height: 19.13}} />
</TouchableOpacity >
<Image
source={require('./images/user.png')}
style={{ width: 42, height: 42, alignSelf: "flex-end",marginTop:-20}} />
<View>
<Text style={{color:'white'}}>{this.state.place}</Text>
</View>
</View>
<Text style={styles.Text}>Nearby Services</Text>
<View style={{flexDirection: "row"}}>
<TouchableOpacity style={styles.signButton} onPress={()=>this.props.navigation.navigate("Near_Place",{data:this.state.places})} activeOpacity={0.5}>
<Text style={styles.btnTxt}> Places </Text>
</TouchableOpacity>
<TouchableOpacity style={styles.signButton} activeOpacity={0.5}>
<Text style={styles.btnTxt}>Gase Stations</Text>
</TouchableOpacity>
</View>
<TouchableOpacity style={styles.signButton} activeOpacity={0.5}>
<Text style={styles.btnTxt}>Hotels</Text>
</TouchableOpacity>
<View>
<Text style={styles.Text}>Other Sevices</Text>
</View>
<View style={{flexDirection: "row"}}>
<TouchableOpacity style={styles.signButton} activeOpacity={0.5}>
<Text style={styles.btnTxt}> Road Assistance </Text>
</TouchableOpacity>
<TouchableOpacity style={styles.signButton} activeOpacity={0.5}>
<Text style={styles.btnTxt}>Rental</Text>
</TouchableOpacity>
</View>
<View style={{alignItems:"center"}}>
<Text style={styles.texttap}>Tap on any services or search destinations</Text>
<TextInput
placeholderTextColor={'#797C80'}
placeholder={'Search destinations'}
style={styles.emailField}
/>
</View>
<Text style={styles.footerTxt}>WeGo</Text>
</SafeAreaView>
);
}
signout=() =>{
firebase.auth().signOut()
this.props.navigation.navigate('Login')
}
}
export default Home;
const styles = StyleSheet.create({
container: {
flex: 1,
// alignItems: 'center',
//justifyContent: 'center'
},
SquareShapeView: {
marginHorizontal: 0,
height: 100,
paddingHorizontal:10,
backgroundColor: '#0000ff',
borderBottomEndRadius: 20,
borderBottomStartRadius: 20,
},
textProp: {
fontFamily: 'Montserrat-Bold',
fontSize: 38,
color: '#ffffff',
marginTop: 32,
marginBottom: 0,
marginRight: 0,
marginLeft: 37,
alignSelf: 'flex-start',
},
emailField: {
fontFamily: 'Montserrat-Light',
fontSize: 14,
color: '#86898E',
width: 330,
height: 50,
backgroundColor: '#E1E6EC',
borderRadius: 30,
paddingLeft: 22,
marginTop: 10,
marginBottom: 10,
marginLeft: 0,
marginRight: 0,
},
pwdField: {
fontFamily: 'Montserrat-Light',
fontSize: 14,
color: '#BDC7D4',
width: 286,
height: 60,
backgroundColor: '#314256',
borderRadius: 30,
paddingLeft: 22,
marginTop: 36,
marginBottom: 0,
marginLeft: 0,
marginRight: 0,
},
btnTxt: {
fontFamily: 'Montserrat-Bold',
fontSize: 14,
textAlign: 'center',
color: '#000000',
backgroundColor: '#BDC7D4',
padding: 0,
alignContent: 'space-between',
marginHorizontal: 5,
marginBottom: 0.5,
marginTop: 0,
paddingTop: 15,
paddingBottom: 15,
borderRadius: 30,
left: 0,
bottom: 0,
width: 138,
height: 52,
},
signButton: {
// alignSelf: 'center',
marginTop: 10,
marginLeft: 0,
marginRight: 0,
marginBottom: 0,
},
bodyTxt: {
fontFamily: 'Montserrat-Regular',
fontSize: 14,
color: '#ffffff',
marginTop: 58,
marginBottom: 0,
marginRight: 0,
marginLeft: 0,
alignSelf: 'center',
},
signUpTxt: {
fontFamily: 'Montserrat-Bold',
fontSize: 14,
color: '#0176FB',
alignSelf: 'center',
},
footerTxt: {
fontFamily: 'Montserrat-Bold',
fontSize: 20,
alignSelf: 'center',
color: '#314256',
marginTop: 90,
marginBottom: 16,
marginRight: 0,
marginLeft: 0,
},
Text: {
fontFamily: 'Montserrat-Bold',
fontSize: 20,
marginLeft: 10,
marginRight: 0,
color: '#314256',
marginHorizontal: 0,
marginTop: 40,
},
texttap: {
fontFamily: 'Montserrat-Regular',
fontSize: 16,
marginLeft: 0,
marginRight: 0,
color: '#314256',
marginHorizontal: 0,
marginTop: 60,
}
});
|
function toggleMenu() {
let x = document.getElementById("links");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
let m = document.getElementById("bars");
if (m.src.endsWith("images/menu.png")) {
m.src = "images/cross.png";
} else {
m.src = "images/menu.png";
}
}
var isMobile = false;
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
isMobile = true;
document.write("mobile device");
console.log("mobile");
}else{
isMobile = false;
// document.writeln("<div style='position:fixed;width:100%;height:100%;top:0px;left:0px;background-color:black;'><img style='width:50%;margin:0 auto;display:block;' src='menu.png'></div>");
// document.writeln("<style>body{margin:0;}</style><div style='width:100%;height:100%;background-color:black;'><img style='width:60%;margin: auto;display: block;' src='menu.png'></div>");
// document.writeln("<style>body{margin:0;}</style><div style='width:100%;height:100%;background-color:black;'><img style='width:30%;margin-left:auto;margin-right:auto;margin-top:auto;margin-bottom:auto;display:block;' src='color.jpeg'></div>");
document.writeln("<style>body{margin:0;}</style><div style='width:100%;height:100%;background-color:black;'><img style='width:50%;position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);' src='color.jpeg'></div>");
// window.stop();
}
window.onload = function (){
if (!isMobile){
document.getElementById('content2').style.display = 'none';
} else {
document.getElementById('content2').style.display = 'block';
}
// if (document.getElementById('video2') != undefined){
// document.getElementById('video2').addEventListener('ended', videoHandler, false);
// } else {
// document.getElementById('content2').style.display = 'block';
// console.log("No video");
// }
};
function videoHandler(e) {
// What you want to do after the event
document.getElementById('content2').style.display = 'block';
document.getElementById('video2').style.display = 'none';
}
|
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require admin/bootstrap-datepicker
//= require admin/jquery.metisMenu
//= require admin/jquery.slimscroll.min
//= require admin/jquery.flot
//= require admin/jquery.flot.tooltip.min
//= require admin/jquery.flot.spline
//= require admin/jquery.flot.resize
//= require admin/jquery.flot.pie
//= require admin/jquery.peity.min
//= require admin/peity-demo
//= require admin/inspinia
//= require admin/pace.min
//= require admin/jquery-ui.min
//= require admin/jquery.gritter.min
//= require admin/jquery.sparkline.min
//= require admin/sparkline-demo
//= require admin/toastr.min
|
import React from 'react';
import renderer from 'react-test-renderer';
import QuestionArtistScreen from './question-artist-screen';
import withActivePlayer from '../../hocs/with-active-player/with-active-player';
const QuestionArtistScreenWrapped = withActivePlayer(QuestionArtistScreen);
const questionArtist = {
artist: `Пелагея`,
src: `https://upload.wikimedia.org/wikipedia/commons/4/4e/BWV_543-fugue.ogg`,
options: [
{
artist: `Пелагея`,
picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/Quincas_Moreira.jpg`,
},
{
artist: `Меладзе`,
picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/Jesse_Gallagher.jpg`,
},
{
artist: `Шнуров`,
picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/sextile.jpg`,
},
]
};
it(`Render QuestionArtistScreen`, () => {
const tree = renderer
.create(<QuestionArtistScreenWrapped
question={questionArtist}
onAnswer={() => {}}
/>, {
createNodeMock: () => {
return {};
}
})
.toJSON();
expect(tree).toMatchSnapshot();
});
|
const { KindleConverter } = require('./src/kindle-converter');
const fs = require('fs');
const myArgs = process.argv.slice(2);
if (myArgs === undefined || myArgs.length === 0) console.log('using default test html');
const bookFileLocation = myArgs[0] ? myArgs[0]
: './tests/test-kindle.html';
const bookHTML = fs.readFileSync(bookFileLocation, 'utf8');
const converter = new KindleConverter(bookHTML);
// console.log("test chinese note headng",
// converter.parseNoteHeading("标注(黄色) - One: If You Want to Understand the Country, Visit McDonald’s > 第 38 页·位置 313")
// )
// console.log("test short chinese note heading",
// converter.parseNoteHeading("笔记 - 位置 25")
// );
// console.log("test english note heading",
// converter.parseNoteHeading("Highlight (pink) - Page 17 · Location 284")
// );
// console.log("test full english note heading",
// converter.parseNoteHeading("Highlight (yellow) - One: If You Want to Understand the Country, Visit McDonald’s > Page 37 · Location 310")
// );
let bookInfo = converter.getBookInfo();
console.log(bookInfo);
console.log("test note parsing");
let bookNotes = converter.getBookNotes();
fs.writeFileSync(
'./tests/test-results.json',
JSON.stringify({ bookInfo, bookNotes}, null, 2),
'utf8'
);
|
TEXT_GAMEOVER = '游戏结束'
TEXT_OF = '/'
TEXT_SCORE = '得分'
TEXT_BEST_SCORE = '最高分'
TEXT_MULTIPLIER = 'x'
TEXT_ARE_SURE = '确定离开吗?'
TEXT_BALL_OUT = '打飞了'
TEXT_PAUSE = '暂停'
TEXT_CONGRATULATION = ['nb!', '绝了!', '学习了!!!']
TEXT_SAVED = '神扑'
TEXT_HELP = '滑动来射门'
TEXT_SHARE_IMAGE = '200x200.jpg'
TEXT_SHARE_TITLE = '恭喜!'
TEXT_SHARE_MSG1 = 'You collected <strong>'
TEXT_SHARE_MSG2 = ' points</strong>!<br><br>Share your score with your friends!'
TEXT_SHARE_SHARE1 = 'My score is '
TEXT_SHARE_SHARE2 = ' points! Can you do better?'
|
Ext.define('Reahoo.view.CodeEditor', {
extend: 'Ext.panel.Panel',
controller: true,
viewModel: {
sourceCode: null
},
xtype: 'code-editor',
prefix: 'code-editor',
language: 'json',
initComponent: function(){
var me = this;
this.html = Ext.String.format('<div id="{0}{1}" style="width:auto;height:100%;"></div>', me.prefix, me.id);
this.listeners = {
resize: function () {
if (me.editorEl) {
me.editorEl.layout();
}
}
}
this.callParent(arguments);
},
setSourceCode: function(value){
var me = this;
if (me.editorEl) {
me.editorEl.setValue(value);
me.editorEl.getAction('editor.action.formatDocument').run();
}
},
getSourceCode: function(){
var me = this;
if (me.editorEl) {
return me.editorEl.getValue();
}
return null;
},
afterRender: function(){
var me = this;
require(['vs/editor/editor.main'], function () {
if (!me.editorEl) {
me.editorEl = monaco.editor.create(
document.getElementById(me.prefix + me.id),
{
language: me.language,
fontSize: 12,
minimap: {
enabled: false
}
}
);
}
});
this.callParent();
}
});
|
'use strict';
var app = require('angular').module('noteshareApp');
app.directive('ngEnter', require('./enterOnKeyPress'))
app.directive('elemReady', require('./elemReady'))
app.directive('file', require('./File'))
|
/**
* 阉割版的underScore只保留backbone依赖的函数已经 _.each 和 _.template
*
*/
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
var ArrayProto = Array.prototype,
ObjProto = Object.prototype,
FuncProto = Function.prototype,
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create,
hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'),
nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'],
MAX_ARRAY_INDEX = Math.pow(2, 53) - 1,
getLength = property('length'),
Ctor = function () {
};
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function (obj) {
return typeof obj == 'function' || false;
};
}
function property(key) {
return function (obj) {
return obj == null ? void 0 : obj[key];
};
}
function isArrayLike(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
}
function collectNonEnumProps(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
var prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
function baseCreate(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
}
function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
}
function createAssigner(keysFunc, undefinedOnly) {
return function (obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
}
function cb(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
}
function property(key) {
return function (obj) {
return obj == null ? void 0 : obj[key];
};
}
function optimizeCb(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1:
return function (value) {
return func.call(context, value);
};
case 2:
return function (value, other) {
return func.call(context, value, other);
};
case 3:
return function (value, index, collection) {
return func.call(context, value, index, collection);
};
case 4:
return function (accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function () {
return func.apply(context, arguments);
};
}
function flatten(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
}
_.isObject = function (obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
_.each = _.forEach = function (obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
_.has = function (obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
_.keys = function (obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
var idCounter = 0;
_.uniqueId = function (prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
_.isArray = nativeIsArray || function (obj) {
return toString.call(obj) === '[object Array]';
};
_.isEmpty = function (obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
_.size = function (obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
_.bind = function (func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function () {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
_.partial = function (func) {
var boundArgs = slice.call(arguments, 1);
var bound = function () {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
_.once = _.partial(_.before, 2);
_.allKeys = function (obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
_.extend = createAssigner(_.allKeys);
_.extendOwn = _.assign = createAssigner(_.keys);
_.pick = function (object, oiteratee, context) {
var result = {}, obj = object, iteratee, keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function (value, key, obj) {
return key in obj;
};
obj = Object(obj);
}
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
_.result = function (object, property, fallback) {
var value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
_.identity = function (value) {
return value;
};
_.matcher = _.matches = function (attrs) {
attrs = _.extendOwn({}, attrs);
return function (obj) {
return _.isMatch(obj, attrs);
};
};
_.iteratee = function (value, context) {
return cb(value, context, Infinity);
};
_.map = _.collect = function (obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
_.bindAll = function (obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
_.some = _.any = function (obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
_.has = function (obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function (name) {
_['is' + name] = function (obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
_.templateSettings = {
evaluate: /<%([\s\S]+?)%>/g,
interpolate: /<%=([\s\S]+?)%>/g,
escape: /<%-([\s\S]+?)%>/g
};
var noMatch = /(.)^/;
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function (match) {
return '\\' + escapes[match];
};
_.defaults = createAssigner(_.allKeys, true);
_.template = function (text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function (data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
_.isEqual=function(a,b){
return eq(a,b)
};
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
module.exports = _;
|
import React, { Component} from "react";
const Content = () => {
return(<>МОИ ПОЗДРАВЛЕНИЯ ЭТОТ ГРЕБАНЫЙ КОД СРАБОТАЛ</>)
}
export default Content;
|
let nbCities = 17;
let mutationRate = 0.01;
let maxPop = nbCities * nbCities;
let cities = [];
let labelsPlaced = false;
let width = 600;
let height = 400;
/* UI */
let generationslabel;
let fitnesslabel;
let mutationratelabel;
let bestpointslabel;
let shortestpathlabel;
function setup() {
createCanvas(500, 500, WEBGL);
noStroke();
fill(255, 102, 204);
generationslabel = createP();
fitnesslabel = createP();
bestpointslabel = createP();
mutationratelabel = createP();
shortestpathlabel = createP();
generateCities();
population = new Population(cities, maxPop, mutationRate);
}
/* Program loop */
function draw() {
background(255);
genetic();
drawCities();
disp();
if (!labelsPlaced)
drawLabels();
if (population.isFinished())
noLoop();
}
function drawLabels() {
labelsPlaced = true;
var i = 65;
population.bestPoints().forEach((e) => {
let city = cities[e];
let cityChar = createP(String.fromCharCode(i));
cityChar.class("cityLabel");
cityChar.position(city.x + (width/2) + 5, city.y + (height/2) + 20);
i++;
});
}
function drawCities() {
beginShape(LINES);
fill(220);
stroke(70);
population.bestPoints().forEach((e) => {
let city = cities[e];
ellipse(city.x, city.y, 13, 13);
});
endShape();
}
/* Main algorithm */
function genetic() {
population.naturalSelection();
population.newGeneration();
population.fitness();
population.evaluate();
}
function disp() {
strokeWeight(3);
stroke(237, 34, 93);
beginShape(LINES);
let p = population.bestPoints();
for (let i = 0; i < population.bestPoints().length - 1; i++) {
let curr = cities[p[i]];
let next =cities[p[i+1]];
line(curr.x, curr.y, next.x, next.y);
}
endShape();
bestpointslabel.html("Best points: " + population.bestPoints());
fitnesslabel.html("Best fit: " + population.bestFitness);
mutationratelabel.html("Mutation rate: " + population.mutationRate * 100 + "%");
generationslabel.html("Generations: " + population.generations);
shortestpathlabel.html("Shortest path: " + population.getBestPath());
}
/* Initial points generation */
function generateCities() {
var arr = [];
for (let i = 0; i < nbCities; i++) {
let x = floor(random(-width/3, width/3));
let y = floor(random(-height/2, height/2));
arr.push({x: x, y: y});
}
cities = arr;
}
|
; (function ($) {
$.fn.setupScrollToBottomEvent = function (settings) {
//多个jq对象
if (this.length != 1) {
return this.each(function (index, el) { $(el).setupScrollToBottomEvent(settings); });
}
//默认参数
var defaults = {
node:document,
offset: 0,//此选项提供设置
callback:null//此选项提供设置
};
//合并参数
if(this[0]!=window)
settings.node=this[0]
$.extend(this, defaults, settings);
//扩展方法
$.extend(this, {
initialize: function () {
var that=this
this.scroll(function() {
var total_height=that.scrollTop() + that.height()
var real_height=that.getRealHeight.call(that)
if( total_height >= real_height - that.offset){
if(that.callback)
that.callback()
that.trigger('scrollToBottom');
}
});
},
getRealHeight:function(){
if(this.node==document){
return Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
Math.max(document.body.clientHeight, document.documentElement.clientHeight)
)
}else{
return Math.max(
this.node.scrollHeight,
this.node.offsetHeight,
this.node.clientHeight
)
}
}
});
this.initialize();
return this
};
})(jQuery);
|
db.testEnv.remove({});
db.testEnv.insert({"authKey": "change-secret-1", "name": "bare metal (desktop)", "specification": "Intel i5, Ubuntu 14.04" });
db.testEnv.insert({"authKey": "change-secret-2", "name": "digitalocean, 10$, Frankfurt", "specification" : "Ubuntu 14.04, x64"});
db.task.remove({});
db.task.insert({"authKey": "change-secret-1", "packageName": "github.com/bradfitz/slice", "created" : new Date()});
db.task.insert({"authKey": "change-secret-1", "packageName": "github.com/valyala/fasttemplate", "created" : new Date()});
db.task.insert({"authKey": "change-secret-1", "packageName": "github.com/regorov/logwriter", "created" : new Date()});
db.package.remove({});
db.package.insert({"name": "github.com/regorov/logwriter",
"url": "https://github.com/regorov/logwriter",
"repositoryUrl": "https://github.com",
"engine" : "git",
"created" : new Date()});
db.package.insert({"name": "github.com/nfnt/resize",
"url": "https://github.com/nfnt/resize",
"repositoryUrl": "https://github.com",
"engine" : "git",
"created" : new Date(),
"updated" : new Date()
});
db.package.insert({"name": "github.com/valyala/gorpc",
"url": "https://github.com/valyala/gorpc",
"repositoryUrl": "https://github.com",
"engine" : "git",
"created" : new Date(),
"updated" : new Date()});
db.package.insert({"name": "github.com/valyala/fasttemplate",
"url": "https://github.com/valyala/fasttemplate",
"repositoryUrl": "https://github.com",
"engine" : "git",
"created" : new Date(),
"updated" : new Date()});
db.package.insert({"name": "github.com/valyala/fasthttp",
"url": "https://github.com/valyala/fasthttp",
"repositoryUrl": "https://github.com",
"engine" : "git",
"created" : new Date(),
"updated" : new Date()});
|
import "react-native";
import React from "react";
import renderer from "react-test-renderer";
import VideoLabel from "../src/video-label";
export default () => {
it("renders VideoLabel with an explicit title", () => {
const tree = renderer
.create(<VideoLabel title="swimming" color="#008347" />)
.toJSON();
expect(tree).toMatchSnapshot();
});
it("renders VideoLabel without an explicit title", () => {
const tree = renderer.create(<VideoLabel color="#008347" />).toJSON();
expect(tree).toMatchSnapshot();
});
};
|
structinit = {
treeDemo_8: {
"id": 3,
"pId": null,
"name": "父节点 3",
"open": true,
"children": [{
"id": 31,
"pId": 3,
"name": "叶子节点 3-1",
"level": 1,
"tId": "treeDemo_10",
"parentTId": "treeDemo_9",
"open": false,
"isParent": false,
"zAsync": true,
"isFirstNode": true,
"isLastNode": false,
"isAjaxing": false,
"checked": false,
"checkedOld": false,
"nocheck": false,
"chkDisabled": false,
"halfCheck": false,
"check_Child_State": -1,
"check_Focus": false,
"isHover": false,
"editNameFlag": false
},
{
"id": 32,
"pId": 3,
"name": "叶子节点 3-2",
"level": 1,
"tId": "treeDemo_11",
"parentTId": "treeDemo_9",
"open": false,
"isParent": false,
"zAsync": true,
"isFirstNode": false,
"isLastNode": false,
"isAjaxing": false,
"checked": false,
"checkedOld": false,
"nocheck": false,
"chkDisabled": false,
"halfCheck": false,
"check_Child_State": -1,
"check_Focus": false,
"isHover": false,
"editNameFlag": false
},
{
"id": 33,
"pId": 3,
"name": "叶子节点 3-3",
"level": 1,
"tId": "treeDemo_12",
"parentTId": "treeDemo_9",
"open": false,
"isParent": false,
"zAsync": true,
"isFirstNode": false,
"isLastNode": true,
"isAjaxing": false,
"checked": false,
"checkedOld": false,
"nocheck": false,
"chkDisabled": false,
"halfCheck": false,
"check_Child_State": -1,
"check_Focus": false,
"isHover": false,
"editNameFlag": false
}
],
"level": 0,
"tId": "treeDemo_9",
"parentTId": null,
"isParent": true,
"zAsync": true,
"isFirstNode": false,
"isLastNode": true,
"isAjaxing": false,
"checked": false,
"checkedOld": false,
"nocheck": false,
"chkDisabled": false,
"halfCheck": false,
"check_Child_State": 0,
"check_Focus": false,
"isHover": false,
"editNameFlag": false
}
}
|
require("./test-go-ndoh.js");
require('./test-go-ndoh-v2.js');
|
import * as d3 from 'd3'
let margin = { top: 30, left: 30, right: 30, bottom: 30 }
let height = 400 - margin.top - margin.bottom
let width = 1080 - margin.left - margin.right
let svg = d3
.select('#chart-3b')
.append('svg')
.attr('height', height + margin.top + margin.bottom)
.attr('width', width + margin.left + margin.right)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
let pie = d3
.pie()
.value(1 / 12)
.sort(null)
let radius = 100
let radiusScale = d3
.scaleLinear()
.domain([0, 120])
.range([0, radius])
let arc = d3
.arc()
.innerRadius(0)
.outerRadius(d => radiusScale(d.data.high_temp))
let colorScale = d3
.scaleLinear()
.domain([0, 120])
.range(['#a1d99b', '#31a354'])
let xPositionScale = d3.scalePoint().range([0, width])
d3.csv(require('./data/all-temps.csv'))
.then(ready)
.catch(err => console.log('Failed on', err))
function ready(datapoints) {
let nested = d3
.nest()
.key(function(d) {
return d.city
})
.entries(datapoints)
let keys = nested.map(d => d.key)
xPositionScale.domain(keys)
let allTemp = datapoints.map(d => +d.high_temp)
colorScale.domain(d3.extent(allTemp))
radiusScale.domain([0, d3.max(allTemp)])
svg
.selectAll('.chart-3b-graph')
.data(nested)
.enter()
.each(function(d) {
// distribute it across the x axis.
let graphX = xPositionScale(d.key) + 90
let container = d3
.select(this)
.append('g')
.attr('transform', `translate(${graphX},${height / 2})`)
container
.selectAll('.chart-3b-path')
.data(pie(d.values))
.enter()
.append('path')
.attr('class', 'chart-3b-path')
.attr('d', d => arc(d))
.attr('fill', d => colorScale(d.data.high_temp))
container
.append('text')
.text(d.key)
.attr('text-anchor', 'middle')
.attr('font-size', 20)
.attr('dy', 120)
.attr('font-weight', 'bold')
container
.append('circle')
.attr('r', 2.5)
.attr('x', 0)
.attr('y', 0)
})
}
|
// We require/import the HTTP module
var http = require("http");
// =====================================================================
// Then define the ports we want to listen to
var PORTS = [{port:8090, func: handleRequestOne}, {port:7501,func:handleRequestTwo}];
PORTS.forEach(function(el){
makeServer(el.func,el.port);
});
// =====================================================================
// We need two different functions to handle requests, one for each server.
function handleRequestOne(request, response) {
response.end("You're a JavaScript mastermind!");
}
function handleRequestTwo(request, response) {
response.end("You smell.");
}
// =====================================================================
// Create our servers
function makeServer(handler,port) {
var server = http.createServer(handler);
server.listen(port, function() {
// Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", port);
});
}
// =====================================================================
|
import React from 'react';
import "./ButtonEncrypt.css";
const buttonEncrypt = props => {
return(
<button className="encButton" onClick={props.clicked}>Encrypt</button>
);
}
export default buttonEncrypt;
|
var ForagerBee = function(age, color, job, hPot, fly) {
HoneyMakerBee.apply(this, [age || 10, color, job || "find pollen"])
if (fly === undefined) {
this.canFly = true;
} else {
this.canFly = fly;
}
this.treasureChest = [];
};
ForagerBee.prototype.eat = HoneyMakerBee.prototype.eat;
ForagerBee.prototype.forage = function(item) {
this.treasureChest.push(item);
};
|
import knex from '../config/db';
class Notification {
static store(data) {
return knex.insert(data).into('notification');
}
static index() {
return knex.select().into('notification');
}
static indexContent(id) {
return knex.select().into('notification').where('idUser', id);
}
static indexCount(id) {
return knex
.select()
.table('notification')
.where('idUser', id)
.where('reader', true);
}
static updateReadNotification(id) {
return this.indexCount(id).update({ reader: false });
}
}
export default Notification;
|
import Vue from 'vue';
import Loading from '../components/Loading/index.js';
Vue.use(Loading);
|
/* eslint-disable no-undef */
import React from 'react';
import PropTypes from 'prop-types';
import FilterItem from './filter-item';
import PriceConstants from '../../constants/priceConstants';
/**
* Handles filtering of prices
*/
class PriceFilter extends React.Component {
constructor(props) {
super(props);
// necessary for unit testing
this.state = {
filters: '0', // default state
};
this.handleToggle = ::this.handleToggle;
this.handleSelect = ::this.handleSelect;
}
handleToggle(e) {
this.state = {
filters: e.target.value,
};
this.props.setFilter(e.target.value);
}
handleSelect() {
this.setState({
filters: '0',
});
this.props.handleFilterSelect();
}
render() {
return (
<div id="price-filter-container">
<input type="radio" name="filter" id="prc-filter" onChange={this.handleSelect} checked={this.props.isDisplayed} />
<label htmlFor="prc-filter" className="list-title">Price</label>
{
(this.props.isDisplayed) ?
<ul id="price-filter">
<FilterItem filter="option1" text={`${PriceConstants.under15 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
<FilterItem filter="option2" text={`${PriceConstants.under30 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
<FilterItem filter="option3" text={`${PriceConstants.under50 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
<FilterItem filter="option4" text={`${PriceConstants.under100 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
<FilterItem filter="option5" text={`${PriceConstants.under250 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
<FilterItem filter="option6" text={`${PriceConstants.under1000 / PriceConstants.divisor}`} handleToggle={this.handleToggle} type="radio" />
</ul> :
<div />
}
</div>
);
}
}
PriceFilter.propTypes = {
isDisplayed: PropTypes.bool.isRequired,
setFilter: PropTypes.func.isRequired,
handleFilterSelect: PropTypes.func.isRequired,
};
export default PriceFilter;
|
import React from "react";
import styled from "styled-components";
import { string, func, oneOf, bool } from "prop-types";
import { useTransition, animated } from "react-spring";
import Text from "../BaseComponents/Text";
import CustomizedButton from "../BaseComponents/CustomizedButton";
const Container = styled(animated.div)`
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
`;
const Content = styled.div`
width: 330px;
box-sizing: border-box;
background-color: white;
padding: 37px 9px;
border-radius: 0.5em;
display: flex;
flex-direction: column;
align-items: center;
`;
export default function Modal({
hide,
show,
type,
title,
onConfirm,
onCancel
}) {
const transitions = useTransition(show, null, {
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
const contentRef = null;
function handleContainerClick(e) {
if (
e.target !== contentRef.current &&
!contentRef.current.contains(e.target)
) {
hide();
}
}
function handleConfirm(e) {
hide();
if (onConfirm && typeof onConfirm === "function") {
onConfirm();
}
e.stopPropagation();
}
function handleCancel(e) {
hide();
if (onCancel && typeof onCancel === "function") {
onCancel();
}
e.stopPropagation();
}
return transitions.map(
({ item, key, props }) =>
item && (
<Container key={key} style={props} onClick={handleContainerClick}>
<Content ref={contentRef}>
<div style={{ marginTop: "14px", textAlign: "center" }}>
<Text
primary={type === "primary"}
secondary={type === "secondary"}
warning={type === "warning"}
>
{title}
</Text>
</div>
{onConfirm && (
<div style={{ marginTop: "18px", minWidth: "58px" }}>
<CustomizedButton filled onClick={handleConfirm}>
确认
</CustomizedButton>
</div>
)}
{onCancel && (
<div style={{ marginTop: "9px", minWidth: "58px" }}>
<CustomizedButton onClick={handleCancel}>取消</CustomizedButton>
</div>
)}
</Content>
</Container>
)
);
}
Modal.propTypes = {
hide: func.isRequired,
show: bool.isRequired,
title: string.isRequired,
type: oneOf(["primary", "secondary", "warning"]).isRequired,
onConfirm: func,
onCancel: func
};
Modal.defaultProps = {
onConfirm: () => {},
onCancel: () => {}
};
|
import React, { Component, Fragment } from 'react';
import WeatherResult from '../WeatherResult/WeatherResult';
import Loader from '../Loader/Loader';
import './style.css';
import { API_KEY, URI } from '../../config';
class Search extends Component {
state = {
loading: false,
notFound: false,
weatherInfo: [],
};
weatherRef = React.createRef();
getWeather = (e) => {
//Data From text Input
const INPUT_VALUE = this.weatherRef.current.value;
this.setState({ loading: true }, () =>
fetch(`${URI}${INPUT_VALUE}&APPID=${API_KEY}`)
.then((res) => res.json())
.then((weather) => {
if(weather.cod === 200) {
this.setState({
weatherInfo: weather,
notFound: false,
loading: false
});
};
if(weather.cod === "404") {
this.setState({
notFound: true,
loading: false
});
};
//console.log(weather.cod)
})
.catch((error) => {
console.error(error);
}),
);
e.target.reset();
e.preventDefault();
};
render() {
const { weatherInfo, loading, notFound } = this.state;
return (
<Fragment>
<form onSubmit={this.getWeather}>
<input
type="text"
placeholder="Enter City"
ref={this.weatherRef}
autoFocus={true}
/>
</form>
{loading ? <Loader /> : notFound ? <h2>Not found</h2> : <WeatherResult weather={weatherInfo} />}
</Fragment>
);
}
}
export default Search;
|
import "../imports/startup/accounts-config";
import "../imports/ui/bio.html";
import "../imports/ui/projects.html";
import "../imports/ui/blog.html";
import "../imports/ui/blog";
import "../imports/ui/collection.html";
import "../imports/ui/collection";
import { Blogs } from "../imports/api/blogs";
Router.configure({
layoutTemplate: "main",
});
Router.route("/", {
name: "bio",
template: "bio",
});
Router.route("/projects", {
name: "projects",
template: "projects",
});
Router.route("/addBlog", {
name: "addBlog",
template: "addBlog",
});
Router.route("/blog/:_id", {
name: "blogItem",
template: "blog",
data: function() {
var currentBlog = this.params._id;
return Blogs.findOne({ _id: currentBlog });
},
});
Router.route("/collection", {
name: "collection",
template: "collection",
});
|
// General Toggle Function
// Usage:
// <div data-toggle="#toggle1"></div>
// <el id="toggle1" data-group="accordion"></el>
$('[data-toggle]').on('click',function(e){
e.preventDefault();
var target = $($(this).data('toggle'));
if (target.length) {
var group = target.data('group');
if (group) {
var groups = '[data-group="'+group+'"]';
$(groups).not(target)
.removeClass('--open')
.attr('aria-hidden', 'true');
}
if (target.hasClass('--open')){
target.removeClass('--open')
.attr('aria-hidden', 'true');
} else {
target.addClass('--open')
.attr('aria-hidden', 'false');
}
}
});
|
import React from "react"
import searchDB from './searchDB'
import Select from './Select'
import * as S from "./styled"
const Forms = ({ number, setNumber }) => {
const [name, setName] = React.useState('')
const [search, setSearch] = React.useState([])
const [select, setSelect] = React.useState(false)
React.useEffect(() => {
if (name) {
setSearch(() => find(name))
} else {
setSearch(() => find(' '))
}
}, [name])
return (
<S.Wrapper select={select}>
<S.Container>
<S.Text displayMobile="block">Número Atômico:</S.Text>
<S.Input
type='number'
placeholder='0'
size='4rem'
min='1'
max='118'
value={number}
onChange={ev => setNumber(ev.target.value)}
/>
</S.Container>
<S.Container >
<S.Text displayMobile="none" >Nome:</S.Text>
<S.InputText
type='text'
placeholder='Digite o nome ou o simbolo'
size='20rem'
min='1'
max='118'
value={name}
onChange={ev => setName(ev.target.value)}
onClick={() => setSelect(true)}
onBlur={() => setTimeout(() => setSelect(false), 200)}
/>
</S.Container>
<Select search={search} select={select} setNumber={setNumber} />
</S.Wrapper>
)}
const find = (name) => (
searchDB.map((element, index) => {
if ( element.toLocaleLowerCase().indexOf(name.toLocaleLowerCase()) !== -1 ) {
return [element, index]
}
return false
})
)
export default Forms
|
import app from 'firebase/app';
import 'firebase/auth';
const config = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
};
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
this.provider = new app.auth.GoogleAuthProvider();
this.userDetails = null;
}
doSignOut = () => this.auth.signOut();
doGoogleLogin = async (successCallBack, failureCallBack) => {
try {
const { user } = await this.auth.signInWithPopup(this.provider);
console.log(user);
const authUser = {
uid: user.uid,
email: user.email,
emailVerified: user.emailVerified,
providerData: user.providerData,
};
successCallBack && successCallBack(authUser);
} catch (err) {
console.error(err.message);
failureCallBack && failureCallBack();
}
}
onAuthStateChanged(successCallBack, failureCallBack) {
this.auth.onAuthStateChanged(user => {
if (user) {
const authUser = {
uid: user.uid,
name: user.displayName,
email: user.email,
emailVerified: user.emailVerified,
providerData: user.providerData,
photoURL: user.photoURL
};
successCallBack(authUser);
} else {
this.userDetails = null;
failureCallBack();
}
})
}
}
export default new Firebase();
|
import React from 'react';
const CopyP2 = () => {
return (
<div className="paragraph-2">
<h2 className="title">You wouldn’t buy stale bread at a grocery store</h2>
<p className="copy-p2">
So why have we come to treat coffee this way? Coffee is roasted with a
shelf life-- the best flavors are obtained within one month of roasting.
Yet most grocery stores don’t even include a roast date on their
coffees. It’s no wonder we’re taught to drown our coffee with sugar and
cream. Why not replace those calories with a delicious breakfast, and
enjoy your coffee guilt-free?
</p>
</div>
);
};
export default CopyP2;
|
const sharp = require('sharp')
const path = require('path')
const FileType = require('file-type')
const { randomStr } = require('../utils/generic')
const getMimeType = async (path) => {
const { ext, mime:mimeType } = await FileType.fromFile(path)
return { ext, mimeType }
}
const resizeImage = async (input) => {
const dir = path.dirname(input)
const ouput = path.resolve(dir, `./${randomStr(10)}`)
await sharp(input)
.resize(200)
.toFile(ouput)
return ouput
}
module.exports = {
getMimeType,
resizeImage
}
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "1a2e203e50db96e718d176c78be492cc",
"url": "./index.html"
},
{
"revision": "2c2413f9998a7fac350f",
"url": "./static/css/2.d9ad5f5c.chunk.css"
},
{
"revision": "a9f28b778d9ec455049c",
"url": "./static/css/main.1f377e84.chunk.css"
},
{
"revision": "2c2413f9998a7fac350f",
"url": "./static/js/2.203acaef.chunk.js"
},
{
"revision": "5ac48c47bb3912b14c2d8de4f56d5ae8",
"url": "./static/js/2.203acaef.chunk.js.LICENSE.txt"
},
{
"revision": "a9f28b778d9ec455049c",
"url": "./static/js/main.57f4087d.chunk.js"
},
{
"revision": "14a35cfea90c458617df",
"url": "./static/js/runtime-main.0cb4c1b5.js"
},
{
"revision": "cbf442f11dc5cca699ede7bb9da22d38",
"url": "./static/media/curtain.cbf442f1.jpg"
}
]);
|
/*
Gradebook from Names and Scores
I worked on this challenge [by myself, with:]
This challenge took me [#] hours.
You will work with the following two variables. The first, students, holds the names of four students.
The second, scores, holds groups of test scores. The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/
var students = ["Joseph", "Susan", "William", "Elizabeth"]
var scores = [ [80, 70, 70, 100],
[85, 80, 90, 90],
[75, 70, 80, 75],
[100, 90, 95, 85] ]
// __________________________________________
// Write your code below.
//release 1
// var gradebook = {
// //release 2/3
// Joseph: {testScores: scores[0]},
// Susan: {testScores: scores[1]},
// William: {testScores: scores[2]},
// Elizabeth: {testScores: scores[3]},
// };
// //release 4
// gradebook.addScore = function(name, score) {
// gradebook[name]['testScores'].push(score)
// };
// // driver code
// // gradebook.addScore('Elizabeth', 2);
// // console.log(gradebook)
// //release 5/7
// gradebook.getAverage = function(name){
// return average(gradebook[name]['testScores'])
// };
// //release 6
// var average = function(num_array){
// var sum = 0
// for(var i = 0; i < num_array.length; i++){
// sum += num_array[i]
// }
// return (sum/num_array.length)
// };
// __________________________________________
// Refactored Solution
function gradebook(array_of_students, array_of_grades) {
//create function that combines student names and grades into a new container object
this.createGradebook = function() {
var gradebook_array = [];
for (var index in array_of_students) {
var student_name = array_of_students[index];
var student_grades = array_of_grades[index];
var student_record = {};
student_record[student_name] = student_grades;
gradebook_array.push(student_record);
}
return gradebook_array;
}
// Call the createGradebook() function, to create a new gradebook instance object
var current_gradebook = this.createGradebook();
// function to push new scores into a student's record
this.addScore = function(name, score) {
// iterate over each student record
for (var index in current_gradebook) {
// if name fed as method argument matches name in student record
if (current_gradebook[index][name]) {
// push score provided as method argument into student record
current_gradebook[index][name].push(score);
console.log("Updated scores for " + name + ": " + current_gradebook[index][name])
}
}
return current_gradebook;
};
// function to calculate an average score for a student
this.getAverage = function(name) {
// iterate over each student record
for (var index in current_gradebook) {
// if name fed as method argument matches name in student record
if (current_gradebook[index][name]) {
// run the average function on that students record
console.log("Average score for " + name + ": " + average(current_gradebook[index][name]));
return (average(current_gradebook[index][name]) );
}
}
}
function average(num_array){
var sum = 0
for(var i = 0; i < num_array.length; i++){
sum += num_array[i]
}
return (sum/num_array.length)
};
};
//DRIVER CODE
// create a new instance of a gradebook object and call methods on it.
var gradebookOne = new gradebook(students, scores)
gradebookOne.addScore("Susan", 90)
gradebookOne.getAverage("Susan")
// __________________________________________
// Reflect
/*
What did you learn about adding functions to objects?
it can be tricky. in the initial solution we couldn't get them working internally.
so we decided to use the object.newMethod = function() and add them externally. that worked well.
in the refactored solution we created a constructor method and got them working perfectly.
How did you iterate over nested arrays in JavaScript?
by using variable names and appropriate syntax of course. You just have to make sure the
iteration is pointing at the correct layer inside the array. we tested the code in a
browser console first to make sure we were calling on the correct layer before iterating.
Were there any new methods you were able to incorporate? If so, what were they and how did they work?
nothing new. just had to do a lot of research on constructor functions to get the refactored solution
working. the refactored solution is a universal solution and will work with any lists of students and
scores. however, there is an added "nested" layer meaning that the tests are not passing. but, we like
the universal usefulness of the updated code and it passes our driver code tests.
*/
// __________________________________________
// Test Code: Do not alter code below this line.
// function assert(test, message, test_number) {
// if (!test) {
// console.log(test_number + "false");
// throw "ERROR: " + message;
// }
// console.log(test_number + "true");
// return true;
// }
// assert(
// (gradebook instanceof Object),
// "The value of gradebook should be an Object.\n",
// "1. "
// )
// assert(
// (gradebook["Elizabeth"] instanceof Object),
// "gradebook's Elizabeth property should be an object.",
// "2. "
// )
// assert(
// (gradebook.William.testScores === scores[2]),
// "William's testScores should equal the third element in scores.",
// "3. "
// )
// assert(
// (gradebook.addScore instanceof Function),
// "The value of gradebook's addScore property should be a Function.",
// "4. "
// )
// gradebook.addScore("Susan", 80)
// assert(
// (gradebook.Susan.testScores.length === 5
// && gradebook.Susan.testScores[4] === 80),
// "Susan's testScores should have a new score of 80 added to the end.",
// "5. "
// )
// assert(
// (gradebook.getAverage instanceof Function),
// "The value of gradebook's getAverage property should be a Function.",
// "6. "
// )
// assert(
// (average instanceof Function),
// "The value of average should be a Function.\n",
// "7. "
// )
// assert(
// average([1, 2, 3]) === 2,
// "average should return the average of the elements in the array argument.\n",
// "8. "
// )
// assert(
// (gradebook.getAverage("Joseph") === 80),
// "gradebook's getAverage should return 80 if passed 'Joseph'.",
// "9. "
// )
|
// @flow
const choo = require('choo');
const html = require('choo/html');
const plur = require('plur');
type Model = {
counter: number;
}
type Event = 'increment' | 'decrement' | 'incrementAsync' | 'decrementAsync';
const app: ChooApp<Event, Model> = choo();
app.use(counterStore);
app.route('/', mainView);
app.mount('body');
function mainView (state, emit) {
const count = state.counter;
return html`
<body>
<main class="app">
<h1>Async counter</h1>
<p>Clicked ${ count } ${ plur('time', count) }!</p>
<button onclick=${ () => emit('increment') }>Increment</button>
<button onclick=${ () => emit('decrement') }>Decrement</button>
<button onclick=${ () => emit('incrementAsync') }>Increment async</button>
<button onclick=${ () => emit('decrementAsync') }>Decrement async</button>
</main>
</body>
`;
}
function counterStore(state, emitter) {
state.counter = 0;
emitter.on('increment', increment);
emitter.on('decrement', decrement);
emitter.on('decrementAsync', decrementAsync);
emitter.on('incrementAsync', incrementAsync);
function increment() {
state.counter++;
emitter.emit('render');
}
function decrement() {
state.counter--;
emitter.emit('render');
}
function decrementAsync() {
setTimeout(() => emitter.emit('decrement'), 1000);
}
function incrementAsync() {
setTimeout(() => emitter.emit('increment'), 1000);
}
}
|
module.exports = (sequelize, DataTypes) => {
const Episode = sequelize.define('Episode', {
tmdbId: DataTypes.STRING,
genres: {
type: DataTypes.STRING,
get: function() {
return JSON.parse(this.getDataValue('genres'));
},
set: function(val) {
return this.setDataValue('genres', JSON.stringify(val));
}
},
networks: {
type: DataTypes.STRING,
get: function() {
return JSON.parse(this.getDataValue('networks'));
},
set: function(val) {
return this.setDataValue('networks', JSON.stringify(val));
}
},
overview: DataTypes.TEXT,
episode_no: DataTypes.STRING,
season: DataTypes.STRING,
streamLink: DataTypes.TEXT,
episode_run_time: {
type: DataTypes.STRING,
get: function() {
return JSON.parse(this.getDataValue('episode_run_time'));
},
set: function(val) {
return this.setDataValue('episode_run_time', JSON.stringify(val));
}
},
name: DataTypes.STRING,
poster_path: DataTypes.STRING,
original_title: DataTypes.STRING,
})
return Episode
}
|
(function($) {
var width, height, canvas, ctx, points, target, animateHeader = true;
var background;
$(function() {
// initHeader();
// initAnimation();
canvas = document.getElementById("bgcanvas");
background = $($(".color-bg")[0]);
addListeners();
});
var opacityScale = 0.6;
var bgColorPerSection = [
[237, 245, 249],
[242, 248, 255],
[245, 244, 249]
];
var colorPerSection = [
[25, 77, 77],
[68, 73, 136],
[17, 56, 110]
];
var lastColor = colorPerSection[0];
var strokecolor = colorToString.apply(this, lastColor);
var lastBGColor = bgColorPerSection[0];
var colorChange = [];
var bgColorChange = [];
function generateColorChangeArray() {
var sections = $(".fill-screen");
sections.each(function(i, sec) {
var elemRect = sec.getBoundingClientRect();
colorChange.push([elemRect.top].concat(colorPerSection[i]));
bgColorChange.push([elemRect.top].concat(bgColorPerSection[i]));
});
}
generateColorChangeArray();
function clamp(min, max, value) {
return Math.min(Math.max(value, min), max);
}
function linearBezier(start, finish, time) {
return start + time * (finish - start);
}
function colorToString(r, g, b) {
return r + "," + g + "," + b;
}
function changeColor(scrollValue) {
var maximumIndex = colorChange.length;
for (var i = maximumIndex - 1; i >= 0; i--) {
if (scrollValue > colorChange[i][0]) {
if (i == maximumIndex - 1) {
strokecolor = colorToString.apply(this, colorChange[i].slice(1));
background.css("background-color", "rgb(" + colorToString.apply(this, bgColorChange[i].slice(1)) + ")");
} else {
var lowerBound = colorChange[i][0];
var time = (scrollValue - lowerBound) / (colorChange[i + 1][0] - lowerBound);
strokecolor = colorToString(
clamp(0, 255, linearBezier(colorChange[i][1], colorChange[i + 1][1], time)).toFixed(0),
clamp(0, 255, linearBezier(colorChange[i][2], colorChange[i + 1][2], time)).toFixed(0),
clamp(0, 255, linearBezier(colorChange[i][3], colorChange[i + 1][3], time)).toFixed(0));
background.css("background-color", "rgb(" + colorToString(
clamp(0, 255, linearBezier(bgColorChange[i][1], bgColorChange[i + 1][1], time)).toFixed(0),
clamp(0, 255, linearBezier(bgColorChange[i][2], bgColorChange[i + 1][2], time)).toFixed(0),
clamp(0, 255, linearBezier(bgColorChange[i][3], bgColorChange[i + 1][3], time)).toFixed(0)) + ")");
}
return;
}
}
strokecolor = colorToString.apply(this, colorChange[0].slice(1));
background.css("background-color", "rgb(" + colorToString.apply(this, bgColorChange[0].slice(1)) + ")");
}
function getHeight() {
return $(document.body).height() - $("#footer").innerHeight();
}
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {
x: width / 2,
y: height / 2
};
width = $(document.body).width();
height = getHeight();
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
points = [];
for (var x = 0; x < width; x = x + width / 20) {
for (var y = 0; y < height; y = y + height / 20) {
var px = x + Math.random() * width / 20;
var py = y + Math.random() * height / 20;
var p = {
x: px,
originX: px,
y: py,
originY: py
};
points.push(p);
}
}
for (var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for (var j = 0; j < points.length; j++) {
var p2 = points[j];
if (p1 !== p2) {
var placed = false;
for (var k = 0; k < 5; k++) {
if (!placed) {
if (closest[k] === undefined) {
closest[k] = p2;
placed = true;
}
}
}
for (k = 0; k < 5; k++) {
if (!placed) {
if (getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
for (i in points) {
var c = new Circle(points[i],2 + Math.random() * 2,"rgba(255,255,255,0.3)");
points[i].circle = c;
}
}
function addListeners() {
if (!("ontouchstart" in window)) {
window.addEventListener("mousemove", mouseMove);
}
window.addEventListener("scroll", scrollCheck);
window.addEventListener("resize", resize);
}
function mouseMove(e) {
var posx = 0;
var posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
changeColor(document.body.scrollTop);
if (document.body.scrollTop > height)
animateHeader = false;
else
animateHeader = true;
}
function resize() {
width = $(document.body).width();
height = getHeight();
canvas.width = width;
canvas.height = height;
generateColorChangeArray();
initHeader();
initAnimation();
}
function initAnimation() {
animate();
for (var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if (animateHeader) {
ctx.clearRect(0, 0, width, height);
for (var i in points) {
if (Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if (Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if (Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0;
points[i].circle.active = 0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1 + 1 * Math.random(), {
x: p.originX - 50 + Math.random() * 100,
y: p.originY - 50 + Math.random() * 100,
ease: Circ.easeInOut,
onComplete: function() {
shiftPoint(p);
}
});
}
function drawLines(p) {
if (!p.active)
return;
for (var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = "rgba(" + strokecolor + "," + p.active * opacityScale + ")";
ctx.stroke();
}
}
function Circle(pos, rad, color) {
var _this = this;
(function() {
_this.pos = pos || null ;
_this.radius = rad || null ;
_this.color = color || null ;
})();
this.draw = function() {
if (!_this.active)
return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgba(" + strokecolor + "," + _this.active * opacityScale + ")";
ctx.fill();
};
}
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}
})(jQuery);
|
/**
* @license
* Copyright (c) 2020 ForgeRock. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import BootstrapVue from 'bootstrap-vue';
import { createLocalVue, shallowMount } from '@vue/test-utils';
import i18n from '@/i18n';
import WelcomeWidget from '@/components/dashboard/widgets/WelcomeWidget';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
describe('Dashboard.vue', () => {
it('Welcome widget loaded', () => {
const wrapper = shallowMount(WelcomeWidget, {
localVue,
i18n,
propsData: {
userDetails: {
givenName: 'test',
sn: 'test',
},
},
});
expect(wrapper.name()).toBe('WelcomeWidget');
expect(wrapper).toMatchSnapshot();
});
});
|
define('GameOverScreen', [
'createjs'
], function (createjs) {
var container;
var CONTENT_WIDTH = 2100,
CONTENT_HEIGHT = 1050;
var GameOver = function(gameContainer) {
this.gameContainer = gameContainer;
};
GameOver.prototype.registerOnExit = function(callback) {
this.onExit = callback;
};
GameOver.prototype.resize = function () {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
var scale = Math.min(this.canvas.width / CONTENT_WIDTH, this.canvas.height / (100 + CONTENT_HEIGHT));
container.scaleX = scale;
container.scaleY = scale;
container.x = (this.canvas.width - CONTENT_WIDTH * scale) / 2;
this.gameContainer.scaleX = scale;
this.gameContainer.scaleY = scale;
this.gameContainer.x = (this.canvas.width - CONTENT_WIDTH * scale) / 2;
this.stage.update();
};
GameOver.prototype.enter = function (canvas, stage, assets) {
var self = this;
this.stage = stage;
this.canvas = canvas;
this.assets = assets;
container = new createjs.Container();
this.resize();
this.stage.addChild(container);
window.onresize = function () {
self.resize();
};
var bitmap = new createjs.Bitmap(assets['gameover']);
bitmap.alpha = 0.5;
container.addChild(bitmap);
setTimeout(function () {
document.location.reload();
}, 4000);
};
GameOver.prototype.exit = function() {
this.stage.removeAllChildren();
this.onExit();
}
return GameOver;
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Objeto Schema
var UsuarioSchema = new Schema({
nombre: String,
apellido: String,
correo: String,
contrasena: String,
rol: String,
imagen: String,
//telefono: Number,
//fecha: String
});
// Exportar el modelo
module.exports = mongoose.model('Usuario', UsuarioSchema);
|
const router = require('koa-router')()
const { getList,
getDetail,
newBlog,
updateBlog,
deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')
router.prefix('/api/blog')
router.get('/list', async (ctx, next) => {
let author = ctx.query.author || ''
const keyword = ctx.query.keyword || ''
if (ctx.query.isadmin) {
// 管理员界面
console.log('管理员-list');
if (!ctx.session.username) {
console.error('未登录啦');
ctx.body = new ErrorModel('管理员-未登录')
return
}
// 强制查询自己的
author = ctx.session.username
}
const result = await getList(author, keyword)
ctx.body = new SuccessModel(result)
});
router.get('/detail', async (ctx, next) => {
const result = await getDetail(ctx.query.id)
ctx.body = new SuccessModel(result)
});
router.post('/new', loginCheck, async (ctx, next) => {
const body = ctx.request.body
body.author = ctx.session.username
const result = await newBlog(body)
ctx.body = new SuccessModel(result)
})
router.post('/update', loginCheck, async (ctx, next) => {
const uData = await updateBlog(ctx.query.id, ctx.session.username, ctx.request.body)
if (uData) {
ctx.body = new SuccessModel('更新成功')
} else {
ctx.body = new ErrorModel({ message: '更新失败' })
}
})
router.post('/delete', loginCheck, async (ctx, next) => {
const result = await deleteBlog(ctx.query.id, ctx.session.username)
if (result) {
ctx.body = new SuccessModel('删除成功')
} else {
ctx.body = new ErrorModel({ message: '删除失败' })
}
})
module.exports = router
|
const students = [{
name: "Tanya",
course: 3,
subjects: {
math: [4, 4, 3, 4],
algorithms: [3, 3, 3, 4, 4, 4],
data_science: [5, 5, 3, 4],
}
}, {
name: "Victor",
course: 4,
subjects: {
physics: [5, 5, 5, 3],
economics: [2, 3, 3, 3, 3, 5],
geometry: [5, 5, 2, 3, 5]
}
}, {
name: "Anton",
course: 2,
subjects: {
statistics: [4, 5, 5, 5, 5, 3, 4, 3, 4, 5],
english: [5, 3],
cosmology: [5, 5, 5, 5]
}
}];
// Function 1
function getSubjects(student) {
const newSubjectsArray = []
const subjectsOfStudent = Object.keys(student.subjects);
subjectsOfStudent.forEach( subject => {
const upperCaseSubject = subject[0].toUpperCase() + subject.substring(1);
const modifiedSubject = upperCaseSubject.replace();
newSubjectsArray.push(modifiedSubject);
});
return newSubjectsArray;
}
console.log(`Список предметів: ${getSubjects(students[0])}.`)
// Function 2
function getAverageMark(student) {
const marks = Object.values(student.subjects);
const averageMarks = [];
let averageMark = null;
marks.forEach(array => {
let sumForSubject = null;
let averageForSubject = null;
let i = 0;
while (i < array.length) {
sumForSubject += array[i];
i++;
}
averageForSubject = sumForSubject / array.length
averageMarks.push(averageForSubject);
});
let sumForSubjects = null;
averageMarks.forEach(mark => {
sumForSubjects += mark;
});
averageMark = +(sumForSubjects / averageMarks.length).toFixed(2);
return averageMark;
}
console.log(`Середня оцінка: ${getAverageMark(students[2])}.` );
// Function 3
function getStudentInfo(student) {
let studentInfo = {
course: student.course,
name: student.name,
averageMark: getAverageMark(student),
}
return studentInfo;
}
console.log(getStudentInfo(students[1]));
// Function 4
function getStudentsNames(array) {
const names = [];
students.forEach(person => {
let personName = person.name;
names.push(personName);
});
return names.sort();
}
console.log(`Імена учнів у алфавітному порядку: ${getStudentsNames(students)}.`);
// Function 5
function getBestStudent(array) {
const allAverageMarks = [];
array.forEach(student => {
allAverageMarks.push(getAverageMark(student));
});
const maxAverageMark = Math.max(...allAverageMarks);
let bestStudents = [];
array.forEach(student => {
if ( getAverageMark(student) === maxAverageMark) {
bestStudents.push(student.name);
}
});
return bestStudents;
}
console.log(`Кращий студент ${getBestStudent(students)}.`);
// Function 6
function calculateWordLetters(word) {
const arrayFromWord = word.split('');
let wordObject = {};
arrayFromWord.forEach(letter => {
let letterQuantity = 0;
let letterObject = {};
for (let i = 0; i < arrayFromWord.length; i++) {
if (arrayFromWord[i] === letter) {
letterQuantity += 1;
}
}
letterObject[letter] = letterQuantity;
Object.assign(wordObject, letterObject);
})
return wordObject;
}
console.log(calculateWordLetters("test"));
|
define("alinw/select/2.0.6/select-debug", [ "arale/select/0.9.9/select-debug", "arale/overlay/1.1.4/overlay-debug", "$-debug", "arale/position/1.0.1/position-debug", "arale/iframe-shim/1.0.2/iframe-shim-debug", "arale/widget/1.1.1/widget-debug", "arale/base/1.1.1/base-debug", "arale/class/1.1.0/class-debug", "arale/events/1.1.0/events-debug", "arale/templatable/0.9.2/templatable-debug", "gallery/handlebars/1.0.2/handlebars-debug", "gallery/handlebars/1.0.2/runtime-debug" ], function(require, exports, module) {
var araleSelect = require("arale/select/0.9.9/select-debug");
var $ = require("$-debug");
var Select = araleSelect.extend({
attrs: {
triggerTpl: '<div class="kuma-select"><a href="javascript:void(0);"><span data-role="trigger-content"></span><i class="kuma-icon kuma-icon-triangle-down" title="下拉"></i></a></div>',
classPrefix: "kuma-select"
},
/**
* 继承arale 原生select控件的setup方法
*/
setup: function() {
var me = this;
Select.superclass.setup.call(me);
if (!me.get("notInitWidth")) {
me._initSelectWidth();
}
var selectSource = me.get("selectSource");
selectSource && me.on("change", function() {
selectSource.trigger("change");
me.get("trigger").attr("title", me.get("trigger").text());
});
me.get("trigger").attr("title", me.get("trigger").text());
me.element.css({
"min-width": me.element.width(),
width: "auto"
});
me.after("show", function() {
me._setPosition(me.get("align"));
});
},
/**
* 初始化下拉框宽度
*/
_initSelectWidth: function() {
var selectSource = this.get("selectSource");
if (selectSource) {
var selectSourceWidth = this.get("selectSource").outerWidth() || 0;
if (!this.get("width") && selectSourceWidth > 0) {
this.set("width", parseInt(selectSourceWidth, 10));
}
}
this.render();
},
_setTriggerWidth: function() {
var trigger = this.get("trigger");
if (this.get("width")) {
// 减2是为了fix http://gitlab.alibaba-inc.com/alinw/select/issues/4
trigger.css({
width: parseInt(this.get("width"), 10) - 26,
"padding-right": 24,
overflow: "hidden"
});
} else {
var width = this.element.outerWidth();
var pl = parseInt(trigger.css("padding-left"), 10);
var pr = parseInt(trigger.css("padding-right"), 10);
// maybe 'thin|medium|thick' in IE
// just give a 0
var bl = parseInt(trigger.css("border-left-width"), 10) || 0;
var br = parseInt(trigger.css("border-right-width"), 10) || 0;
trigger.css({
width: width - pl - pr - bl - br - 24,
"padding-right": 24,
overflow: "hidden"
});
}
}
});
Select.init = function(selector) {
$(selector).each(function() {
new Select({
trigger: this
});
});
};
module.exports = Select;
});
|
import React, { Fragment } from 'react';
import classes from './SideDrawer.module.scss';
import NavigationItems from '../NavigationItems/NavigationItems';
import Backdrop from '../../UI/Backdrop/Backdrop';
const sideDrawer = ( props ) => {
console.log(`props`, props);
let attachedClasses = [classes.SideDrawer, classes.Close];
// open={this.state.showSideDrawer}
if (props.open) {
attachedClasses = [classes.SideDrawer, classes.Open];
}
return (
<Fragment>
<Backdrop
show={props.open}
clicked={props.closed}/>
<div
className={attachedClasses.join(' ')}
onClick={props.closed}>
<NavigationItems />
</div>
</Fragment>
);
};
export default sideDrawer;
|
var express = require('express');
var router = express.Router();
var logger = require('@ekhanei/logger').getLogger();
var passport = require('passport');
var sdk = require('@ekhanei/sdk');
var utils = require('@ekhanei/utils');
var _ = require('lodash');
// Middleware
var requireLogin = require('../middleware/require-login');
var requireLogout = require('../middleware/require-logout');
// Login interface
// There are two ways to login: via an overlay, used when
// we want to keep the context in which the user find
// themselves (the ad insertion form, for example); and
// in-page, useful for when users try to access an
// authenticated route. This route handler the latter.
router.get('/login-signup', requireLogout, function (req, res, next) {
res.render('auth/login-signup', {
title: req.i18n.__("Login or create an account"),
disableAuthOverlay : true,
showUnverifiedMessage: false
});
});
// Signup interface
// For cases when we want to drive people explicitly to
// signup, and remove the distraction of login.
router.get('/signup', requireLogout, function(req, res, next) {
res.render('auth/signup', {
title: req.i18n.__("Create an account"),
disableAuthOverlay : true,
showUnverifiedMessage: false
});
});
router.get('/logout', requireLogin, function (req, res, next) {
var userID = req.user.id;
req.logout();
req.session.regenerate(function (err) {
if (err) {
logger.error("Unexpected error while logging out user %s, error: %s", userID, JSON.stringify(err));
return next(err);
}
logger.info("Successfully logged out user %s", userID);
// Track this event
req.visitor.event("Login and Signup", "Logout Success").send();
// Flash and redirect
req.flash('info', req.i18n.__("You are now logged out"));
res.redirect('/');
});
});
module.exports = router;
|
function showNotify(msg) {
$id('notify').innerText = msg;
$id('notify').style.display = 'inline-block'
setTimeout(function () {
$id('notify').style.display = 'none'
}, 5000)
}
function $id(id) {
return document.getElementById(id)
}
function $class(className) {
return document.getElementsByClassName(className)
}
function $tag(tag) {
return document.getElementsByTagName(tag)
}
function $isNull(sth) {
if (sth == '' || sth == null || sth == undefined || sth.length == 0) {
return true
} else {
return false
}
}
function $mkEle(ele){
return document.createElement(ele)
}
function scrollToEnd(ele){
ele.children[ele.children.length-1].scrollIntoView(false)
}
function $stringToByte(str) {
var bytes = new Array();
var len, c;
len = str.length;
for(var i = 0; i < len; i++) {
c = str.charCodeAt(i);
if(c >= 0x010000 && c <= 0x10FFFF) {
bytes.push(((c >> 18) & 0x07) | 0xF0);
bytes.push(((c >> 12) & 0x3F) | 0x80);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if(c >= 0x000800 && c <= 0x00FFFF) {
bytes.push(((c >> 12) & 0x0F) | 0xE0);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if(c >= 0x000080 && c <= 0x0007FF) {
bytes.push(((c >> 6) & 0x1F) | 0xC0);
bytes.push((c & 0x3F) | 0x80);
} else {
bytes.push(c & 0xFF);
}
}
return bytes;
}
|
game.resources = [
/* Graphics.
* @example
* {name: "example", type:"image", src: "data/img/example.png"},
*/
{name: "background-tiles", type: "image", src: "data/img/background-tiles.png"},
{name: "meta-tiles", type: "image", src: "data/img/meta-tiles.png"},
{name: "player", type: "image", src: "data/img/orcSpear.png"},
{name: "tower", type: "image", src: "data/img/tower_round.svg.png"},
{name: "creep1", type: "image", src: "data/img/brainmonster.png"},
{name: "devil", type: "image", src: "data/img/devil.jpg"},
/* Atlases
* @example
*/
/* Maps.
* @example
* example01", type: "tmx", src: "data/map/example01.tmx"},{name: "
* {name: "example01", type: "tmx", src: "data/map/example01.json"},
*/
{name: "level1", type: "tmx", src: "data/map/bob.tmx"},
{name: "level2", type: "tmx", src: "data/map/bob2.tmx"},
/* Background music.
* @example
* {name: "example_bgm", type: "audio", src: "data/bgm/"},
*/
{name: "music3", type: "audio", src: "data/bgm/"}
/* Sound effects.
* @example
* {name: "example_sfx", type: "audio", src: "data/sfx/"}
*/
];
|
import Axios from 'axios';
const register = '/api/auth/register';
const login = '/api/auth/login';
const logout = '/api/auth/logout';
export const REGISTER_USER = 'REGISTER_USER';
export const LOGIN_USER = 'LOGIN_USER';
export const LOGOUT_USER = 'LOGOUT_USER';
export const ERROR = 'ERROR';
export const registerUser = (registerCreds) => {
return (dispatch) => {
return Axios.post(register, registerCreds)
.then(response => {
dispatch({
type: REGISTER_USER,
response: response.data
});
})
.catch(err => {
dispatch({
type: ERROR,
error: err
});
});
};
};
export const loginUser = (userCreds) => {
return (dispatch) => {
return Axios.post(login, userCreds)
.then((response) => {
// console.log(response, "RESPONSE DATA");
dispatch({
type: LOGIN_USER,
userDetails: response.data
});
})
.catch((err) => {
dispatch({
type: ERROR,
error: 'invalid user name or password'
});
});
};
};
export const logoutUser = () => {
return (dispatch) => {
// console.log(dispatch, "logout");
return Axios.get(logout)
.then((response) => {
if (response.data.success) {
dispatch({
type: LOGOUT_USER,
success: response.data.success
});
}
})
.catch((err) => {
console.log('Logout Failed. Please try again', err);
return false;
});
};
};
|
const TwingTestMockCompiler = require('../../../../mock/compiler');
const TwingNodeExpressionConstant = require('../../../../../lib/twing/node/expression/constant').TwingNodeExpressionConstant;
const TwingMap = require('../../../../../lib/twing/map').TwingMap;
const TwingNodePrint = require('../../../../../lib/twing/node/print').TwingNodePrint;
const TwingNodeExpressionName = require('../../../../../lib/twing/node/expression/name').TwingNodeExpressionName;
const TwingNode = require('../../../../../lib/twing/node').TwingNode;
const TwingNodeIf = require('../../../../../lib/twing/node/if').TwingNodeIf;
const TwingNodeType = require('../../../../../lib/twing/node').TwingNodeType;
const tap = require('tap');
tap.test('node/if', function (test) {
test.test('constructor', function (test) {
let tNodes = new TwingMap();
tNodes.push(new TwingNodeExpressionConstant(true, 1));
tNodes.push(new TwingNodePrint(new TwingNodeExpressionName('foo', 1), 1));
let t = new TwingNode(tNodes, new TwingMap(), 1);
let else_ = null;
let node = new TwingNodeIf(t, else_, 1);
test.same(node.getNode('tests'), t);
test.false(node.hasNode('else'));
else_ = new TwingNodePrint(new TwingNodeExpressionName('bar', 1), 1);
node = new TwingNodeIf(t, else_, 1);
test.same(node.getNode('else'), else_);
test.same(node.getType(), TwingNodeType.IF);
test.end();
});
test.test('compile', function (test) {
let compiler = new TwingTestMockCompiler();
test.test('without else', function (test) {
let tNodes = new TwingMap();
tNodes.push(new TwingNodeExpressionConstant(true, 1));
tNodes.push(new TwingNodePrint(new TwingNodeExpressionName('foo', 1), 1));
let t = new TwingNode(tNodes, new TwingMap(), 1);
let else_ = null;
let node = new TwingNodeIf(t, else_, 1);
test.same(compiler.compile(node).getSource(), `// line 1
if (true) {
Twing.echo((context.has("foo") ? context.get("foo") : null));
}
`);
test.end();
});
test.test('with multiple tests', function (test) {
let tNodes = new TwingMap();
tNodes.push(new TwingNodeExpressionConstant(true, 1));
tNodes.push(new TwingNodePrint(new TwingNodeExpressionName('foo', 1), 1));
tNodes.push(new TwingNodeExpressionConstant(false, 1));
tNodes.push(new TwingNodePrint(new TwingNodeExpressionName('bar', 1), 1));
let t = new TwingNode(tNodes, new TwingMap(), 1);
let else_ = null;
let node = new TwingNodeIf(t, else_, 1);
test.same(compiler.compile(node).getSource(), `// line 1
if (true) {
Twing.echo((context.has("foo") ? context.get("foo") : null));
}
else if (false) {
Twing.echo((context.has("bar") ? context.get("bar") : null));
}
`);
test.end();
});
test.test('with else', function (test) {
let tNodes = new TwingMap();
tNodes.push(new TwingNodeExpressionConstant(true, 1));
tNodes.push(new TwingNodePrint(new TwingNodeExpressionName('foo', 1), 1));
let t = new TwingNode(tNodes, new TwingMap(), 1);
let else_ = new TwingNodePrint(new TwingNodeExpressionName('bar', 1), 1);
let node = new TwingNodeIf(t, else_, 1);
test.same(compiler.compile(node).getSource(), `// line 1
if (true) {
Twing.echo((context.has("foo") ? context.get("foo") : null));
}
else {
Twing.echo((context.has("bar") ? context.get("bar") : null));
}
`);
test.end();
});
test.end();
});
test.end();
});
|
// Filename: scripts.js
var Modernizr = Modernizr || {};
// General Functions
// ------------------
define([
'cat',
'ev',
'jquery',
'backbone',
'underscore',
'jquery.textfill',
'jquery.transit',
'jquery.chosen'
], function(cat, ev, $, Backbone, _){
/* Detect Device */
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEcat.Options.mobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
/* Ready */
$(function(){
// First Functions
cat.Options.currentPage = $('body').attr('id');
if(isMobile.any()){
cat.Options.mobile = true;
$('html').addClass('mobile');
}
if(cat.Options.mobile && $(window).width() < 768){
cat.Options.phone = true;
$('html').addClass('phone');
}
if(cat.Options.mobile && $(window).width() >= 768){
cat.Options.tablet = true;
$('html').addClass('tablet');
}
cat.Options.pagePos = $(window).scrollTop();
cat.Options.screenSize = $(window).width();
responsive();
// Window Resize
$(window).resize(function(){
cat.Options.screenSize = $(window).width();
responsive();
ev.vent.trigger('resized');
});
// Scrolling
var updatePosition = function(){
cat.Options.pagePos = $(window).scrollTop();
ev.vent.trigger('scroll',cat.Options.pagePos);
};
var scrollBuffer = _.throttle(updatePosition, 16);
$(window).scroll(scrollBuffer);
// Navigation
var routeCheck = function(href,routes) {
if (!href || !routes) return;
// takes a href and does a lookup on a router object
href = href.replace(/\/$/, "");
var segment = href.substr(href.lastIndexOf('/') + 1);
var pattern = new RegExp(segment,'i');
var route = _.find(routes,function(val,key){
if (val === 'atlanta' || val === 'dallas' || val === 'westcoast') return;
return pattern.test(key);
});
return route;
};
$('#header_logo').on('click', function(vent){
vent.preventDefault();
var path = routeCheck(window.location.pathname,cat.router.routes);
if (cat.Options.phone) $('#phone_nav').trigger('click');
if (cat.app.single.currentView) {
cat.app.single.currentView.slideDown();
} else if (window.location.pathname !== '/' && path) {
cat.router.navigate('/', { trigger: true });
} else if (window.location.pathname !== '/' && !path) {
window.location = '/';
} else {
pageScrollTo('#home', 108);
}
});
$('.main_nav_btn a').on('click', function(vent){
vent.preventDefault();
var target = $(vent.currentTarget);
var href = $(vent.currentTarget).attr('href');
// Check to make sure our route actually exist in backbone
var route = routeCheck(href,cat.router.routes);
// Check our current path to see if we're in an existing Backbone
// route or a Standard EE page. In order to trigger a new BB route
// - we need to already "be in" the app
var path = routeCheck(window.location.pathname,cat.router.routes);
if (route && path) {
$('body').scrollTop(0);
$('#header').trigger('click');
if (cat.Options.phone) $('#phone_nav').trigger('click');
cat.router.navigate( href, { trigger: true } );
} else {
window.location = href;
}
});
// Dropdown Subnav
if(cat.Options.mobile){
if(cat.Options.tablet){
$('#tablet_menu').on('click', function(vent){
$('#header').toggleClass('active');
vent.stopPropagation();
});
$('#main_nav ul, #main_nav li a').on('click',function(vent){
vent.stopPropagation();
});
$('#header').on('click', function(){
$(this).toggleClass('active');
});
}
if(cat.Options.phone){
// Responsive Navigation
$('#phone_nav').on('click', function(){
var navHeight = $('#main_nav #navwrap').outerHeight() + 30;
if($('#main_nav').hasClass('active')){
$('#main_nav').removeClass('active');
$('#main_nav').stop().dequeue().transition({
height: 0
}, 300, 'easeInOutQuad');
} else {
$('#main_nav').addClass('active');
$('#main_nav').stop().dequeue().transition({
height: navHeight + 'px'
}, 300, 'easeInOutQuad');
}
});
$('.show-sub-btn').on('click', function( vent ){
vent.preventDefault();
$(this).siblings('ul').toggleClass('active');
$(this).parents('li').siblings().find('ul').removeClass('active');
$(this).parents('li').siblings().find('.show-sub-btn').text('+');
if($(this).text() == '+'){
$(this).text('–');
} else {
$(this).text('+');
}
});
}
} else {
var t;
// var menuHeight = $('#main_nav ul li ul').height() + 120;
$('#header').on('mouseenter', function(){
var self = this;
t = setTimeout(function(){ $(self).addClass('active'); },280);
});
$('#header').on('mouseleave', function(){
clearTimeout(t);
$(this).removeClass('active');
});
$('#main_nav ul, #main_nav li a').on('click',function(vent){
vent.stopPropagation();
});
$('#header').on('click', function(){
$(this).toggleClass('active');
});
}
$('#login_btn a').on('click', function(){
var btnWidth = $(this).outerWidth();
var arrowWidth = $('.nav_arrow').width();
var offset = (arrowWidth / 2) - (btnWidth / 2);
var newArrowPos = $(this).position().left - offset;
if($(this).parent().hasClass('logged_in')){
pageScrollTo('#home', 108);
// bannerScroll('#account');
$(this).parent().siblings().removeClass('active');
$('.nav_arrow').css('display', 'block').stop().dequeue().transition({
x: newArrowPos + 'px'
}, 200, 'easeInOutQuad');
} else {
openLogin();
}
return false;
});
// Bios
$('.team_entry').on('click', function(){
var bioHTML = $('.team_detail', this).html();
var $targetContainer = $(this).closest('.row').find('.bio_container');
if(!$targetContainer.hasClass('active')){
$('.bio_container').each(function(){
$(this).stop().dequeue().transition({
height: 0 + 'px'
}, 300, 'easeInOutQuad', function(){
$(this).removeClass('active');
});
});
$targetContainer.addClass('active');
}
$targetContainer.html(bioHTML);
var bioHeight = $targetContainer.find('.span8').outerHeight();
$targetContainer.stop().dequeue().transition({
height: bioHeight + 'px'
}, 300, 'easeInOutQuad');
});
});
/* Responsive Breakpoints */
function responsive(){
// Desktop Large
if(cat.Options.screenSize >= 1200 && !cat.Options.mobile){
if(cat.Options.screenType != 'desktop-large'){
cat.Options.screenType = 'desktop-large';
$('body').removeClass('desktop-medium desktop-medium-small desktop-small tablet phone').addClass(cat.Options.screenType);
}
// Desktop Medium
} else if(cat.Options.screenSize > 979 && cat.Options.screenSize < 1200 && !cat.Options.mobile){
if(cat.Options.screenType != 'desktop-medium'){
cat.Options.screenType = 'desktop-medium';
$('body').removeClass('desktop-large desktop-medium-small desktop-small tablet phone').addClass(cat.Options.screenType);
}
// Desktop Medium Small
} else if(cat.Options.screenSize >= 768 && cat.Options.screenSize <= 979 && !cat.Options.mobile){
if(cat.Options.screenType != 'desktop-medium-small'){
cat.Options.screenType = 'desktop-medium-small';
$('body').removeClass('desktop-large desktop-medium desktop-small tablet phone').addClass(cat.Options.screenType);
}
// Desktop Small
} else if(cat.Options.screenSize < 768 && !cat.Options.mobile){
if(cat.Options.screenType != 'desktop-small'){
cat.Options.screenType = 'desktop-small';
$('body').removeClass('desktop-large desktop-medium desktop-medium-small tablet phone').addClass(cat.Options.screenType);
}
// Tablet Size
} else if(cat.Options.screenSize >= 768 && cat.Options.screenSize <= 1024 && cat.Options.mobile){
if(cat.Options.screenType != 'tablet'){
cat.Options.screenType = 'tablet';
$('body').removeClass('desktop-large desktop-medium desktop-medium-small desktop-small phone').addClass(cat.Options.screenType);
}
// Phone
} else if (cat.Options.screenSize < 768 && cat.Options.mobile) {
if (cat.Options.screenType != 'phone'){
cat.Options.screenType = 'phone';
$('body').removeClass('desktop-large desktop-medium desktop-medium-small desktop-small tablet').addClass(cat.Options.screenType);
}
}
}
function pageScrollTo(target, offset) {
if (!target) { return; }
var scrollTo = $(target).offset().top - offset;
$('html, body').stop().dequeue().animate({
scrollTop: scrollTo
}, 500);
}
function openLogin(){
// var loginHeight = $('#login_form .container').height();
if($('#login_form').hasClass('active')){
$('#login_form').stop().dequeue().transition({
opacity: 0
}, 200, 'easeOutExpo', function(){
$(this).removeClass('active');
});
if(!cat.Options.phone){
$('#main_nav ul ul').css('display', 'block').stop().dequeue().transition({
opacity: 100
}, 200);
}
} else {
$('#login_form').addClass('active').stop().dequeue().transition({
opacity: 100
}, 200);
if(!cat.Options.phone){
$('#main_nav ul ul').stop().dequeue().transition({
opacity: 0
}, 200, function(){
$('#main_nav ul ul').css('display', 'none');
});
}
}
}
String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
var tag = t.replace("#","%23");
return t.link("http://search.twitter.com/search?q="+tag);
});
};
String.prototype.parseUsername = function() {
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
var username = u.replace("@","");
return u.link("http://twitter.com/"+username);
});
};
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
return url.link(url);
});
};
});
|
var express = require('express'),
app = express(),
path = require('path'),
port = 8000,
bp = require('body-parser'),
session = require('express-session');
app.use(express.static(path.join(__dirname, './client/dist')));
app.use(bp.json());
app.use(session({secret:"key", saveUninitialized: true}));
// require('./server/config/mongoose')
require('./server/config/route')(app)
app.listen(port, function(){
console.log("Listening on Port: " + port)
})
|
'use strict'
/* Global Imports */
import { dbTypeUser } from '../db-api/'
import { Success, Error } from '../util'
import Debug from 'debug'
/* Config Vars */
const debug = new Debug('nodejs-hcPartnersTest-backend:controllers:typeUser')
/* * * * * * * * * * Controlller Functions * * * * * * * * * * * */
const getTypeUsers = async (req, res) => {
try {
debug('getTypeUsers')
const typeUsers = await dbTypeUser.findAll()
if (!typeUsers) return Error({ message: 'TypeUser not found', status: 404 }, res)
Success(res, { data: typeUsers, model: 'typeUsers' })
} catch (error) {
Error(error, res)
}
}
const getTypeUser = async (req, res) => {
try {
const { id } = req.params
debug('getTypeUser')
const typeUser = await dbTypeUser.findById(id)
if (!typeUser) return Error({ message: 'TypeUser not found', status: 404 }, res)
Success(res, { data: typeUser, model: 'typeUser' })
} catch (error) {
Error(error, res)
}
}
const saveTypeUser = async (req, res) => {
try {
debug('saveTypeUser')
const objectTypeUser = req.body
const typeUser = await dbTypeUser.create(objectTypeUser)
Success(res, { data: typeUser, model: 'typeUser' }, 201)
} catch (error) {
Error(error, res)
}
}
const updateTypeUser = async (req, res) => {
try {
const { id } = req.params
const objectTypeUser = req.body
debug('updateTypeUser')
const typeUser = await dbTypeUser.update(id, objectTypeUser)
if (!typeUser) return Error({ message: 'TypeUser not found', status: 404 }, res)
Success(res, { data: typeUser, model: 'typeUser' })
} catch (error) {
Error(error, res)
}
}
const deleteTypeUser = async (req, res) => {
const { id } = req.params
try {
debug('deleteTypeUser')
await dbTypeUser.delete(id)
Success(res)
} catch (error) {
Error(error, res)
}
}
export default {
saveTypeUser,
getTypeUsers,
getTypeUser,
updateTypeUser,
deleteTypeUser
}
|
const socket = io.connect();
// let submit = document.getElementById('form-product');
// let submitChat = document.getElementById('form-Chat');
//Pedimos la data que hay actualmente enviando un socket
socket.emit('Productos');
socket.emit('Mensajes');
// Si emite un mensaje individual
socket.on('mensajes', (data) => {
console.log('RECIBI MENSAJE');
alert(data);
});
// Mensaje para todos los clientes
socket.on('update', (products) => {
products.forEach((product) => {
render(product);
});
});
// // WebSocket que recibe mensajes desde le backend para pintar un nuevo mensaje del chat
socket.on('updateChat', (messages) => {
messages.forEach((message) => {
renderChat(message);
});
});
//Reestructurando las nuevas llamadas de mensajes con normalizr
const formMensaje = document.getElementById('formMensajes');
const mensajesContainer = document.getElementById('mensajesContainer');
let date = new Date();
let now = date.toLocaleString();
formMensaje.addEventListener('submit', (event) => {
event.preventDefault();
if (email.value && mensaje.value) {
let data = {
author: {
email: email.value,
nombre: nombre.value,
apellido: apellido.value,
alias: alias.value,
edad: edad.value,
url: url.value,
},
msg: mensaje.value,
// timestamp: data.value,
};
console.log('EMITIENDO SOCKET');
socket.emit('newMessage', data);
email.value = '';
nombre.value = '';
apellido.value = '';
(alias.value = ''), (edad.value = ''), (url.value = '');
mensaje.value = '';
}
});
socket.on('receiveMessages', (mensajes) => {
console.log(mensajes);
});
socket.on('newMessage', (mensaje) => {
let p = document.createElement('p');
p.innerHTML = `
<span class='mx-2 mensaje__email'>${mensaje.author.email}</span>
<span class='mx-2 mensaje__time'>${mensaje.author.nombre}</span>
<span class='mx-2 mensaje__text'>${mensaje.msg}</span>`;
mensajesContainer.appendChild(p);
});
|
// import * as googleTTS from "google-tts-api"; // ES6 or TypeScript
// import { useEffect } from "react";
// import Player from "./Player";
import fs from "fs";
import tts from "google-translate-tts";
import { useEffect } from "react";
// const googleTTS = require('google-tts-api'); // CommonJS
const TextToSpeech = () => {
// // get audio URL
// const url = googleTTS.getAudioBase64("Hello World", {
// lang: "en",
// slow: false,
// host: "https://translate.google.com",
// });
// console.log("URL", url); // https://translate.google.com/translate_tts?...
// notice that `tts.synthesize` returns a Promise<Buffer>
const saveFile = async () => {
const buffer = await tts.synthesize({
text: "Hello, world!",
voice: "en-US",
slow: false, // optional
});
fs.writeFileSync("hello-world.mp3", buffer);
};
const fun = () => {
const msg = new SpeechSynthesisUtterance("Hello, hope my code is helpful");
window.speechSynthesis.speak(msg);
};
// useEffect(() => {
// var audio = new Audio();
// audio.src =
// "https://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en&total=1&idx=0&textlen=11&client=tw-ob&prev=input&ttsspeed=1";
// audio.play();
// }, []);
// useEffect(() => {
// const audio = new Audio(
// "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
// );
// audio.load();
// playAudio();
// }, []);
// const playAudio = () => {
// const audio = new Audio(
// "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
// );
// const audioPromise = audio.play();
// if (audioPromise !== undefined) {
// audioPromise
// .then((_) => {
// // autoplay started
// })
// .catch((err) => {
// // catch dom exception
// console.info(err);
// });
// }
// };
return (
<div>
<h2>googleTTS</h2>
{/* <p>{url}</p> */}
<div>
{/* <Player
// url={"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"}
url={url}
/> */}
{/* <audio
autoPlay="autoPlay"
href="audio_tag"
loop
src={
"https://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en&total=1&idx=0&textlen=11&client=tw-ob&prev=input&ttsspeed=1"
}
// type="audio/mpeg"
controls
></audio> */}
<button onClick={saveFile}>Click</button>
<button type="button" onClick={fun}>
Listen to me
</button>
</div>
</div>
);
};
export default TextToSpeech;
|
import { recursiveGetFieldName } from 'utils/common';
import { validateRequired, validateEmail } from './validation';
describe('MetaData tab', () => {
describe('recursiveGetFieldName', () => {
it('Should combined recursive keys in string by the input "entity" string to trigger the recursive to stop if any', () => {
const dataResp = {
data: {
introduce: {
en: {
entity: {
show_name: {
fieldName: 'show_name',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD' }
],
fieldType: 'input',
fieldLabel: 'SHOW_NAME',
fieldValue: 'en'
},
show_label: {
fieldName: 'show_label',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD' },
{
rule: 'isEmail',
code: 'FORM_ERROR_REQUIRED_FIELD_EMAIL_INVALID'
}
],
fieldType: 'input',
fieldLabel: 'SHOW_LABEL',
fieldValue: ''
}
}
},
ar: {
entity: {
show_name: {
fieldName: 'show_name',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD' }
],
fieldType: 'input',
fieldLabel: 'SHOW_NAME',
fieldValue: 'ar'
},
show_label: {
fieldName: 'show_label',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD' },
{
rule: 'isEmail',
code: 'FORM_ERROR_REQUIRED_FIELD_EMAIL_INVALID'
}
],
fieldType: 'input',
fieldLabel: 'SHOW_LABEL',
fieldValue: ''
}
}
}
}
}
};
const dataRespExpected = {
'en.entity.show_name': {
fieldName: 'show_name',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD', validator: validateRequired }
],
fieldType: 'input',
fieldLabel: 'SHOW_NAME',
fieldValue: 'en'
},
'en.entity.show_label': {
fieldName: 'show_label',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD', validator: validateRequired },
{ rule: 'isEmail', code: 'FORM_ERROR_REQUIRED_FIELD_EMAIL_INVALID', validator: validateEmail }
],
fieldType: 'input',
fieldLabel: 'SHOW_LABEL',
fieldValue: ''
},
'ar.entity.show_name': {
fieldName: 'show_name',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD', validator: validateRequired }
],
fieldType: 'input',
fieldLabel: 'SHOW_NAME',
fieldValue: 'ar'
},
'ar.entity.show_label': {
fieldName: 'show_label',
validationRules: [
{ rule: 'isRequired', code: 'FORM_ERROR_REQUIRED_FIELD', validator: validateRequired },
{ rule: 'isEmail', code: 'FORM_ERROR_REQUIRED_FIELD_EMAIL_INVALID', validator: validateEmail }
],
fieldType: 'input',
fieldLabel: 'SHOW_LABEL',
fieldValue: ''
},
}
const wrapper = recursiveGetFieldName(dataResp.data.introduce, 'entity');
expect(wrapper).toEqual(dataRespExpected);
});
});
});
|
import Layout from '../components/layout/main'
export default () => (
<Layout>
<div className='content'>
<h2>Starter</h2>
<p>☠️hello world ☠️</p>
</div>
<style jsx global>{`.content-bg{background:black;}`}</style>
<style jsx>{`
.content {
display:grid;
padding: 2rem;
max-width: 1080px;
}
`}</style>
</Layout>
)
|
import { Redirect, BrowserRouter as Router, Route, Switch, withRouter, useLocation, Link} from 'react-router-dom';
import HoritzontalCard from './HorizontalCard'
import React, { useState, useEffect} from 'react';
import { useHistory } from "react-router";
import './Topics.css';
import icon from './icon.png'; // Tell webpack this JS file uses this image
import { FirebaseUtil } from '../Services/FirebaseUtil';
function Topics(props) {
const history = useHistory()
let location = useLocation();
const [allRooms, setAllRooms] = useState([])
useEffect(async() => {
let rooms_ = await FirebaseUtil.getAllRooms()
setAllRooms(rooms_)
}, []);
function onJoinRoom(room){
console.log(room)
history.push("/chat")
}
return (
<div class="page-root">
<div className="header-div">
<h3 className="header-title">ROOMS</h3>
{/*<button className="header-button">create new topic</button>*/}
</div>
<div className="topics-root">
{allRooms.map((room)=>{
return(
<HoritzontalCard
imageSource={icon}
title={room.roomName}
description={"This is a wider card with supporting text below as a natural lead-in to additional content."}
subtext={"Last updated 3 mins ago"}
onClick={()=>onJoinRoom(room)}
/>
)
})}
</div>
</div>
);
}
export default Topics;
|
'use strict';
/**
* @author: Maria Andrea Cruz Blandon
* Controller of the results view. This allow to load the analysis of a list of tweets. It uses RestFulAPI provider to request
* the analysis of a list of tweets. If there is not query and tweets list in the request that load this view the user is
* redirected to home (When the user tries to load the view directly without following the process of search).
* If the response of the request is success then the analysis is load, in the case of percentages these are multiplicated
* by 100, because that is the format used in easy-pie-chart. If the response is rejection then a error message is show.
* The user can return to home using the buttons ('go home' or 'new search')
*/
angular.module('app.sentimentAnalysis').controller('ResultsController', function ($scope, $state, $stateParams, RestFulAPI) {
// Attributes of the controller. Values used to manage the visibility of components or values used in the view
$scope.tweet_list = $stateParams.tweets;
$scope.query = $stateParams.query;
$scope.error_message = null;
$scope.analysis = false;
$scope.type_class = null;
$scope.results = null;
$scope.response = false;
// Redirect if there is no tweet_list
if($scope.tweet_list == null || $scope.query == null){
$state.go('app.home');
}else{
if($scope.query[0] == '@'){
$scope.type_class = "nickname";
}else{
$scope.type_class = "hashtag";
}
var sentiment_query = {tweets: $scope.tweet_list};
RestFulAPI.get_analysis(sentiment_query).then(function(sentiment_data){
$scope.analysis = true;
// Sentiment statistics
$scope.results = sentiment_data[0];
$scope.results.score.positive_percentage = $scope.results.score.positive_percentage * 100;
$scope.results.score.negative_percentage = $scope.results.score.negative_percentage * 100;
$scope.results.score.neutral_percentage = $scope.results.score.neutral_percentage * 100;
// Most negative, most positive
$scope.min_max = sentiment_data[1];
$scope.response = true;
}, function(err){
$scope.error_message = "Something went wrong :(";
$scope.analysis = false;
$scope.response = true;
});
}
// Redirect to home
$scope.change_search = function(){
$state.go('app.home')
}
});
|
const request = require('supertest');
const express = require('express');
const assert = require('assert');
const app = express();
const server = request('http://localhost:1337');
const crypto = require("crypto");
const jwt = require('jsonwebtoken');
const {registration} = require("./../db/models/registration");
let token = "";
const deviceName1ToUse = crypto.randomBytes(20).toString('hex');
console.log("using as first device: "+deviceName1ToUse);
let lastinsertedId;
let apiKey ="";
let regkey = require('./../tools/global').REGISTERKEY;
it('get PSK', done => {
registration.findOne().then(r => {
console.log("fetched PSK: " + r.registerkey);
regkey = r.registerkey
console.log("set PSK: " + regkey);
}).catch(error => console.error(error));
done();
});
it('authenticate correct', done => {
server.post('/api/auth/login')
.send({username: 'muster', password: 'plain'})
.expect(200)
.expect((res) => {
if (!('jwt' in res.body)) throw new Error("missing jwt token");
if (res.body.jwt === "") throw new Error("jwt token cannot be null");
token = res.body.jwt;
})
.end(done);
});
const getBuffer = (data) => {
console.log("BUFFER" + require('./../tools/global').REGISTERKEY);
return crypto
.createHmac("sha256", require('./../tools/global').REGISTERKEY)
.update(Buffer.from(data.toString(), 'hex'))
.digest("hex");
};
const getBufferBad = (data) => {
return crypto
.createHmac("sha256", "asd")
.update(Buffer.from(data.toString(), 'hex'))
.digest("hex");
};
it('register bad', done => {
const data = {
configurationId: null,
name: 'testdevqweicqwe213ees',
description: 'devicey',
approved: false,
approvaltime: new Date(),
apikey: "testapikey"
};
console.log(getBuffer(data));
server.post('/api/ext/register')
.set('authorization', getBufferBad(data))
.send(data)
.expect(res => console.log(JSON.stringify(res.body)))
.expect(401)
.end(done);
});
it('register good', done => {
const data = {
configurationId: null,
name: deviceName1ToUse,
description: 'devicey',
approved: false,
approvaltime: new Date(),
apikey: "testapikey"
};
console.log(getBuffer(data));
server.post('/api/ext/register')
.set('authorization', getBuffer(data))
.send(data)
.expect(res => {
console.log(JSON.stringify(res.body, null, 4));
lastInsertedId = res.body.device.id;
})
.expect(200)
.end(done);
});
it('get all devices, ok, check 1 device with 1 id 1 not approved', done => {
server.get('/api/device')
.set("bearer", token)
.expect(res => {
console.log(JSON.stringify(res.body, null, 4));
//if (!(res.body.device.length === 1)) throw new Error("device with id 3 seems not to be deleted");
})
.expect(200, done);
});
it('await good, not approved', done => {
console.log(getBuffer({}));
server.get('/api/ext/awaitapprove/'+lastInsertedId)
.set('authorization', getBuffer({}))
.expect(res => console.log(JSON.stringify(res.body)))
.expect(202)
.end(done);
});
it('put 1 device update approved, good', done => {
server.put('/api/device/'+lastInsertedId)
.set("bearer", token)
.send({
configurationId: null,
name: deviceName1ToUse,
description: 'deviceAPPROVED',
approved: true,
approvaltime: new Date(),
apikey: null
}).expect((res) => {
console.log("PUT 1 DEVICE UPDATE: " + res.body);
console.log(JSON.stringify(res.body, null, 4));
})
.expect(200)
.end(done);
});
console.log("FETCHED PSK FOR APPROVAL TEST:" + require('./../tools/global').REGISTERKEY);
let jwtTokenE = "";
it('await good, approved', done => {
console.log(getBuffer({}));
server.get('/api/ext/awaitapprove/'+lastInsertedId)
.set('authorization', getBuffer({}))
.expect(res => {
console.log(JSON.stringify(res.body, null, 4));
console.log("using regkey: "+regkey);
let jwtToken = jwt.verify(res.body.jwt, regkey);
apiKey = jwtToken.apikey;
jwtTokenE = res.body.jwt;
console.log("got apikey: "+apiKey);
})
.expect(200)
.end(done);
});
it('await good, already approved 422', done => {
console.log(getBuffer({}));
server.get('/api/ext/awaitapprove/' + lastInsertedId)
.set('authorization', getBuffer({}))
.expect(res => console.log(JSON.stringify(res.body, null, 4)))
.expect(422)
.end(done);
});
for (let i = 0; i < 1; i++) {
it('send status', done => {
server.post('/api/ext/status/')
.send({id: lastInsertedId, bearer: jwtTokenE})
.expect(res => console.log(JSON.stringify(res.body, null, 4)))
.expect(200)
.end(done);
});
it('get status', done => {
server.get('/api/ext/status/'+lastInsertedId)
.set('bearer',token)
.expect(res => console.log(JSON.stringify(res.body, null, 4)))
.expect(200)
.end(done);
});
}
it('get status', done => {
console.log("apikey: " + apiKey);
server.get('/api/ext/status/'+lastInsertedId)
.set('bearer',token)
.expect(res => console.log(JSON.stringify(res.body, null, 4)))
.expect(200)
.end(done);
});
|
module.exports = async () => ({
testMatch: ['**/*.acceptance.{test,spec}.js']
})
|
import React, {useState } from 'react'
//import {UserContext} from '../context/UserContext'
export default () => {
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
const [phoneNumber, setPhoneNumber] = useState('')
const [birthDate, setBirthDate] = useState('')
const [dateExamen, setDateExamen] = useState('')
const [examen, setExamen] = useState('')
const [imageOrdo, setImageOrdo] = useState(null)
const [error, setError] = useState('')
console.log("file", imageOrdo)
// const {user} = useContext(UserContext)
const handleSubmit = async (event) => {
event.preventDefault()
// if(!user){
// setError('Please log in first')
// return
// }
if(!lastName){
setError('Please add a name')
return
}
if(!firstName){
setError('Please add a prénom')
return
}
if(!imageOrdo){
setError('Please add a File')
return
}
const formData = new FormData()
formData.append('data', JSON.stringify({firstName}))
formData.append('data', JSON.stringify({lastName}))
formData.append('data', JSON.stringify({phoneNumber}))
formData.append('data', JSON.stringify({birthDate}))
formData.append('data', JSON.stringify({dateExamen}))
formData.append('data', JSON.stringify({examen}))
formData.append('files.image', imageOrdo)
try{
const response = await fetch(`https://frozen-dawn-43758.herokuapp.com/ordonnances`, {
method: 'POST',
// headers: {
// 'Authorization': `Bearer ${user.jwt}`
// },
body: formData
})
const data = await response.json()
console.log("data", data)
} catch(err){
console.log("Exception ", err)
setError(err)
}
}
return (
<div className="Create">
<h2>Création ordonnance</h2>
{error && <p>{error}</p>}
<form onSubmit={handleSubmit}>
<input
placeholder="prénom"
value={firstName}
onChange={(event) => {
setError('')
setDescription(event.target.value)
}}
/>
<input
placeholder="nom"
value={lastName}
onChange={(event) => {
setError('')
setDescription(event.target.value)
}}
/>
<input
placeholder="Date de naissance"
value={birthDate}
onChange={(event) => {
setError('')
setDescription(event.target.value)
}}
/>
<input
placeholder="examen"
value={examen}
onChange={(event) => {
setError('')
setDescription(event.target.value)
}}
/>
<input
placeholder="date d'examen"
value={dateExamen}
onChange={(event) => {
setError('')
setDescription(event.target.value)
}}
/>
<input
type="file"
placeholder="Add a File"
onChange={(event) => {
setError('')
setFile(event.target.files[0])
}}
/>
<button>Submit</button>
</form>
</div>
)
}
|
import React, {useState} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
// import CardMedia from '@material-ui/core/CardMedia';
// import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Badge from '@material-ui/core/Badge';
import QueryBuilderIcon from '@material-ui/icons/QueryBuilder';
import { withRouter } from 'react-router-dom';
import Divider from '@material-ui/core/Divider';
import WhatshotIcon from '@material-ui/icons/Whatshot';
import {getLocalTime, isBefore }from '../../containers/Utils/TimeUtils';
import classs from './Card.module.css'
// const useStyles = makeStyles({
// card: {
// // maxWidth: 345,
// // marginBottom:2
// },
// media: {
// height: 120,
// },
// });
const useStyles = makeStyles(theme => ({
margin: {
margin: theme.spacing(2),
},
padding: {
padding: theme.spacing(0, 2),
},
}));
function MediaCard(props) {
const classes = useStyles();
let {description, organizer, size, total_participants, game_mode, start, title, id} = props.tournament
const handleClick = () => {props.history.push('/tournament/'+id)}
if(description && description.length > 55){
description = description.substring(0,50) + "..."
}
const badgeData = total_participants + '/' + size;
const tournamentTime = getLocalTime(start);
const [dateColor, setDateColor] = useState('initial');
if(dateColor!=='error' && isBefore(start)) {
setDateColor('error');
}
return (
<Card className={classs.Card} onClick={handleClick} >
<CardActionArea>
{/* <CardMedia
className={classes.media}
image="/static/images/cards/contemplative-reptile.jpg"
title="Contemplative Reptile"
/> */}
<CardContent>
<Badge className={classes.margin} badgeContent={badgeData} color="primary">
<Typography gutterBottom variant="h6" component="h2">
{title}
</Typography>
</Badge>
<Typography variant="body2" color="textSecondary" component="span">
{/* <Typography className={classes.padding}> {description} </Typography> */}
</Typography>
</CardContent>
<Typography className={classs.Strap}>{game_mode.name}</Typography>
</CardActionArea>
<Divider />
<CardActions className={classs.CardAction} >
<Typography className={[classs.Organiser, classs.small].join(' ')}> <WhatshotIcon fontSize='small' /> {organizer} </Typography>
<Typography color={dateColor} className={[classes.padding, classs.Time, classs.small].join(' ')}> <QueryBuilderIcon fontSize='small' /> {tournamentTime} </Typography>
</CardActions>
</Card>
);
}
export default withRouter(MediaCard);
|
'use strict';
app.controller('subscriptionsController', ['$scope', 'User', 'subscriptionsService', function ($scope, User, subscriptionsService) {
$scope.user = User;
$scope.subscriptions = [];
subscriptionsService.get($scope.user.org).then(function(results) {
$scope.subscriptions = results.data;
});
}]);
|
var game = new Phaser.Game(320,480,Phaser.CANVAS,"",{preload:onPreload, create:onCreate, update:onUpdate});
var ball; // the ball! Our hero
var arrow; // rotating arrow
var rotateDirection = 1; // rotate direction: 1-clockwise, 2-counterclockwise
var power = 0; // power to fire the ball
var hudText; // text to display game info
var charging=false; // are we charging the power?
var degToRad=0.0174532925; // degrees-radians conversion
var score = 0; // the score
var coin; // the coin you have to collect
var deadlyArray = []; // an array which will be filled with enemies
var gameOver = false; // flag to know if the game is over
// these settings can be modified to change gameplay
var friction = 0.99; // friction affects ball speed
var ballRadius = 10; // radius of all elements
var rotateSpeed = 3; // arrow rotation speed
var minPower = 50; // minimum power applied to ball
var maxPower = 200; // maximum power applied to ball
// when the game preloads, graphic assets are loaded
function onPreload() {
game.load.image("ball", "assets/ball.png");
game.load.image("deadly", "assets/deadly.png");
game.load.image("coin", "assets/coin.png");
game.load.image("arrow", "assets/arrow.png");
}
// function to be executed when the game is created
function onCreate() {
// center and scale the stage
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
// add the ball and set its anchor point in the center
ball = game.add.sprite(game.world.centerX,game.world.centerY,"ball");
ball.anchor.x = 0.5;
ball.anchor.y = 0.5;
// ball starting speed
ball.xSpeed = 0;
ball.ySpeed = 0;
// the rotating arrow
arrow = game.add.sprite(game.world.centerX,game.world.centerY,"arrow");
arrow.anchor.x = -1;
arrow.anchor.y = 0.5;
// place an enemy
placeDeadly();
// create and place a coin
coin = game.add.sprite(Math.random()*400+40,Math.random()*240+40,"coin");
coin.anchor.x = 0.5;
coin.anchor.y = 0.5;
placeCoin();
// create and place the text showing speed and score
hudText = game.add.text(5,0,"",{
font: "11px Arial",
fill: "#ffffff",
align: "left"
});
// update text content
updateHud();
// listener for input down
game.input.onDown.add(charge, this);
}
// place an enemy
function placeDeadly(){
// first, create the enemy and set its anchor point in the center
var deadly = game.add.sprite(0,0,"deadly");
deadly.anchor.x = 0.5;
deadly.anchor.y = 0.5;
// add the newly created enemy in the enemy array
deadlyArray.push(deadly);
// assign it a random position until such position is legal
do {
var randomX=Math.random()*(game.width-2*ballRadius)+ballRadius;
var randomY=Math.random()*(game.height-2*ballRadius)+ballRadius;
deadlyArray[deadlyArray.length-1].x=randomX;
deadlyArray[deadlyArray.length-1].y=randomY;
} while (illegalDeadly());
}
// determine if an enemy position is illegal
function illegalDeadly(){
// if the distance between the enemy and the ball is less than three times the radius, it's NOT legal
if(getDistance(ball,deadlyArray[deadlyArray.length-1])<(ballRadius*3)*(ballRadius*3)){
return true;
}
// if the distance between the enemy and any other enemy is less than two times the radius, it's NOT legal
for(i=0;i<deadlyArray.length-1;i++){
if(getDistance(deadlyArray[i],deadlyArray[deadlyArray.length-1])<(ballRadius*2)*(ballRadius*2)){
return true
}
}
// otherwise it's legal
return false;
}
// the function to place a coin is similar to the one which places the enemy, but this time we don't need
// to place it in an array because there's only one coin on the stage
function placeCoin(){
// assign the coin a random position until such position is legal
do{
coin.x=Math.random()*(game.width-2*ballRadius)+ballRadius;
coin.y=Math.random()*(game.height-2*ballRadius)+ballRadius;
} while (illegalCoin());
}
// determine if a coin position is illegal
function illegalCoin(){
// if the distance between the coin and any ball is less than 2.5 times the radius, it's NOT legal
if(getDistance(ball,coin)<(ballRadius*2.5)*(ballRadius*2.5)){
return true;
}
// if the distance between the coin and any enemy is less than three times the radius, it's NOT legal
for(i=0;i<deadlyArray.length;i++){
if(getDistance(deadlyArray[i],coin)<(ballRadius*3)*(ballRadius*3)){
return true
}
}
// otherwise it's legal
return false;
}
// function to be executed each time the game is updated
function onUpdate() {
// the game is update only if it's not game over
if(!gameOver){
// when the player is charging the power, this is increased until it reaches the maximum allowed
if(charging){
power++;
power = Math.min(power,maxPower)
// then game text is updated
updateHud();
}
// if the player is not charging, keep rotating the arrow
else{
arrow.angle+=rotateSpeed*rotateDirection;
}
// update ball position according to its speed
ball.x+=ball.xSpeed;
ball.y+=ball.ySpeed;
// handle wall bounce
wallBounce();
// reduce ball speed using friction
ball.xSpeed*=friction;
ball.ySpeed*=friction;
// update arrow position
arrow.x=ball.x;
arrow.y=ball.y;
// if the player picked a coin, then update score and text, change coin position and add an enemy
if(getDistance(ball,coin)<(ballRadius*2)*(ballRadius*2)){
score += 1;
placeDeadly();
placeCoin();
updateHud();
}
// if the player hits an enemy, it's game over
for(i=0;i<deadlyArray.length;i++){
if(getDistance(ball,deadlyArray[i])<(ballRadius*2)*(ballRadius*2)){
gameOver = true;
window.alert("Game Over!分数:" + score + "分,去发ajax吧!");
}
}
}
}
// function to handle bounces. Just check for game boundary collision
function wallBounce(){
if(ball.x<ballRadius){
ball.x=ballRadius;
ball.xSpeed*=-1
}
if(ball.y<ballRadius){
ball.y=ballRadius;
ball.ySpeed*=-1
}
if(ball.x>game.width-ballRadius){
ball.x=game.width-ballRadius;
ball.xSpeed*=-1
}
if(ball.y>game.height-ballRadius){
ball.y=game.height-ballRadius;
ball.ySpeed*=-1
}
}
// simple function to get the distance between two sprites
// does not use sqrt to save CPU
function getDistance(from,to){
var xDist = from.x-to.x
var yDist = from.y-to.y;
return xDist*xDist+yDist*yDist;
}
// when the player is charging, set the power to min power allowed
// and wait the player to release the input to fire the ball
function charge(){
power = minPower;
game.input.onDown.remove(charge, this);
game.input.onUp.add(fire, this);
charging=true;
}
// FIRE!!
// update ball speed according to arrow direction
// invert arrow rotation
// reset power and update game text
// wait for the player to fire again
function fire(){
game.input.onUp.remove(fire, this);
game.input.onDown.add(charge, this);
ball.xSpeed += Math.cos(arrow.angle*degToRad)*power/20;
ball.ySpeed += Math.sin(arrow.angle*degToRad)*power/20;
power = 0;
updateHud();
charging=false;
rotateDirection*=-1;
}
// function to update game text
function updateHud(){
hudText.text = "Power: "+power+" * Score: "+score
}
|
function twoSum(numbers, target) {
let s = 0;
let e = numbers.length - 1;
for (let i = 0; i < numbers.length; i++) {
let req_num = target - numbers[i];
s = i;
while (s <= e) {
let m = Math.floor(s + (e - s) / 2);
if (req_num == target) {
return [++i, ++m];
}
else if(req_num < numbers[m])
e = m-1;
else
s = m + 1;
}
}
return -1;
}
console.log(twoSum([3, 24, 50, 79, 88, 150, 345], 200));
// console.log(twoSum([3,2,4], 6));
// console.log(twoSum([3,2], 6));
// console.log(twoSum([2,5,5,11], 10));
// console.log(twoSum([0,4,3,0], 0));
|
// init the game. loads all required resources and starts the game ui
// firefox et.al. dont always have console available
if (!window.console) window.console = {log:function(){}};
// scripts in one group are loaded serially.
// script groups are loaded in parallel.
new LoadQueue(
[{name: "core",
files: [
'js/tools/vector.js',
'js/game.js',
'js/ui.js',
'js/hud.js'
]},
{name: "actors",
files: [
'js/actor.js',
'js/backpack.js',
'js/actors/model.js',
'js/actors/player.js',
'js/actors/enemy.js',
'js/actors/particle.js',
'js/actors/placeholder.js',
'js/actors/rocket.js'
]},
{name: "map",
files: [
'js/map.js',
'js/maps/maplayout.js',
'js/maps/tile.js',
'js/maps/mapui.js',
'js/maps/cell.js'
]},
{name: "ownables",
files: [
'js/ownable.js',
'js/ownables/weapon.js',
'js/ownables/weapons/gun.js',
'js/ownables/weapons/shotgun.js',
'js/ownables/weapons/rocketlauncher.js',
'js/ownables/ammo.js',
'js/ownables/ammos/gunbullet.js',
'js/ownables/ammos/shotgunbullet.js',
'js/ownables/ammos/dumdum.js'
]},
{name: "data",
files: [
'js/data/tiles.js',
'js/data/models.js',
'js/data/maps.js'
]},
{name: "libs",
files: [
'js/lib/jquery/jquery.mousewheel.min.js',
/* dragndrop: http://interface.eyecon.ro/demos/drag.html */
//'js/lib/jquery/idrag.js',
//'js/lib/jquery/iutil.js',
'js/lib/jquery/draggable.js',
/* A* path finding */
'js/lib/astar/graph.js',
'js/lib/astar/astar.js'
]},
{name: "imagery",
files: [
'img/characters/character.png',
'img/characters/enemy-sentry.png',
'img/characters/enemy.png',
'img/characters/enemy-patrol.png',
'img/characters/selected.png',
'img/hud.jpg',
'img/hudplayer.jpg',
'img/bag.png',
'img/maps/minimap.png',
'img/roundbutton.png',
'img/button.png',
'img/tiles/water.png',
'img/hover_blue.png',
'img/hover_red.png',
// 'img/gun.png',
// 'img/gunbullet.png',
// 'img/shotgun.png',
// 'img/shotgunbullet.png',
'img/characters/smoke.png', // TOFIX: more logical position?
'img/characters/explosion.png',
'img/characters/rocket.png',
'img/backpacks/army.png',
'img/backpacks/hike.png',
'img/backpacks/standard.png',
'img/skull.png'
]}
], {
init: function(count){
$('#count').html(0+" of "+count);
},
loading: function(group,file){
// TOFIX: make this better looking
$('#files').prepend("<div>loading ["+group.name+"]: "+file+"</div>");
},
loaded: function(group,file){
// TOFIX: make this better looking
$('#files').prepend("<div>loaded ["+group.name+"]: "+file+"</div>");
$('#count').html(this.loaded+" of "+this.toLoad);
},
finished: function(){
// TOFIX: make this better looking / smooth transition
$('#files').prepend("<div>Finished loading</div>"); // hmm
// give some time to catch up
setTimeout(function(){
$('#loader').hide();
$('#ui').show();
new UI(new Game, $('#enterprise'));
},1);
}
},
6
);
|
import { DropzoneArea } from "material-ui-dropzone";
import React from "react";
function FileUpload(props) {
const handleUpload = (files) => {
console.log("Files:", files);
if (files.length > 0) {
const data = new FormData();
data.append("file", files[0]);
data.append("filename", files[0].name);
data.append("note_id", props.noteID);
console.log(props.noteID)
fetch("/api/upload", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
body: data,
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
props.handleUploaded();
})
.catch((error) => {
console.log("There was an error: ", error);
});
}
};
return (
<DropzoneArea
acceptedFiles={["video/mp4"]}
dropzoneText={"Please upload recording mp4 file "}
onChange={handleUpload}
filesLimit={1}
maxFileSize={500000000}
/>
);
}
export default FileUpload;
|
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
/*jslint sub: true*/
function SecureObject(thing, key) {
"use strict";
var o = Object.create(null, {
toString: {
value: function () {
return "SecureObject: " + thing + "{ key: " + JSON.stringify(key) + " }";
}
}
});
setLockerSecret(o, "key", key);
setLockerSecret(o, "ref", thing);
$A.lockerService.markOpaque(o);
return Object.seal(o);
}
SecureObject.isDOMElementOrNode = function(el) {
"use strict";
return typeof el === "object" &&
((typeof HTMLElement === "object" && el instanceof HTMLElement) ||
(typeof Node === "object" && el instanceof Node) ||
(typeof el.nodeType === "number" && typeof el.nodeName === "string"));
};
function newWeakMap() {
return typeof WeakMap !== "undefined" ? new WeakMap() : {
/* WeakMap dummy polyfill */
"get": function () {
return undefined;
},
"set": function () {}
};
}
var rawToSecureObjectCaches = {};
SecureObject.addToCache = function(raw, so, key) {
// Keep SecureObject's segregated by key
var psuedoKeySymbol = JSON.stringify(key);
var rawToSecureObjectCache = rawToSecureObjectCaches[psuedoKeySymbol];
if (!rawToSecureObjectCache) {
rawToSecureObjectCache = newWeakMap();
rawToSecureObjectCaches[psuedoKeySymbol] = rawToSecureObjectCache;
}
rawToSecureObjectCache.set(raw, so);
};
SecureObject.getCached = function(raw, key) {
var psuedoKeySymbol = JSON.stringify(key);
var rawToSecureObjectCache = rawToSecureObjectCaches[psuedoKeySymbol];
return rawToSecureObjectCache ? rawToSecureObjectCache.get(raw) : undefined;
};
SecureObject.filterEverything = function (st, raw, options) {
"use strict";
if (!raw) {
// ignoring falsy, nully references.
return raw;
}
var t = typeof raw;
if (t === "object") {
if (raw instanceof File || raw instanceof FileList) {
// Passthru for objects without priviledges.
return raw;
}
}
function filterOpaque(opts, so) {
return opts && opts.filterOpaque === true && $A.lockerService.isOpaque(so);
}
var key = getLockerSecret(st, "key");
var cached = SecureObject.getCached(raw, key);
if (cached) {
return !filterOpaque(options, cached) ? cached : undefined;
}
var swallowed;
var mutated = false;
if (t === "function") {
// wrapping functions to guarantee that they run in system mode but their
// returned value complies with user-mode.
swallowed = function SecureFunction() {
var fnReturnedValue = raw.apply(SecureObject.unfilterEverything(st, this), SecureObject.unfilterEverything(st, SecureObject.ArrayPrototypeSlice.call(arguments)));
return SecureObject.filterEverything(st, fnReturnedValue);
};
mutated = true;
setLockerSecret(swallowed, "ref", raw);
} else if (t === "object") {
if (raw === window) {
return $A.lockerService.getEnv(key);
} else if (raw === document) {
return $A.lockerService.getEnv(key).document;
}
var isNodeList = raw && (raw instanceof NodeList || raw instanceof HTMLCollection);
if (Array.isArray(raw) || isNodeList) {
swallowed = [];
for (var n = 0; n < raw.length; n++) {
var newValue = SecureObject.filterEverything(st, raw[n]);
// TODO: NaN !== NaN
if (!filterOpaque(options, newValue)) {
swallowed.push(newValue);
}
mutated = mutated || (newValue !== raw[n]);
}
setLockerSecret(swallowed, "ref", raw);
// Decorate with .item() to preserve NodeList shape
if (isNodeList) {
Object.defineProperty(swallowed, "item", {
value: function(index) {
return swallowed[index];
}
});
}
} else {
var hasAccess = $A.lockerService.util.hasAccess(st, raw);
$A.assert(key, "A secure object should always have a key.");
if ($A.util.isAction(raw)) {
swallowed = hasAccess ?
SecureAction(raw, key) : SecureObject(raw, key);
mutated = raw !== swallowed;
} else if ($A.util.isComponent(raw)) {
swallowed = hasAccess ?
SecureComponent(raw, key) : SecureComponentRef(raw, key);
mutated = raw !== swallowed;
} else if (SecureObject.isDOMElementOrNode(raw)) {
if (hasAccess || raw === document.body || raw === document.head) {
swallowed = SecureElement(raw, key);
} else if (!options || options.filterOpaque !== true) {
swallowed = SecureObject(raw, key);
} else {
swallowed = options.defaultValue;
}
mutated = true;
} else if (raw instanceof Aura.Event.Event) {
swallowed = SecureAuraEvent(raw, key);
mutated = true;
} else if (raw instanceof Event) {
swallowed = SecureDOMEvent(raw, key);
mutated = true;
} else if ($A.lockerService.util.isKeyed(raw)) {
swallowed = SecureObject(raw, key);
mutated = true;
} else {
swallowed = {};
mutated = true;
setLockerSecret(swallowed, "key", key);
setLockerSecret(swallowed, "ref", raw);
SecureObject.addToCache(raw, swallowed, key);
for (var name in raw) {
if (typeof raw[name] === "function") {
Object.defineProperty(swallowed, name, SecureObject.createFilteredMethod(swallowed, raw, name, {
filterOpaque : true
}));
} else {
Object.defineProperty(swallowed, name, SecureObject.createFilteredProperty(swallowed, raw, name, {
filterOpaque : true
}));
}
}
}
}
}
if (mutated) {
SecureObject.addToCache(raw, swallowed, key);
return swallowed;
} else {
return raw;
}
};
SecureObject.unfilterEverything = function(st, value, visited) {
"use strict";
function memoize(visitedCache, v, unfiltered) {
try {
visitedCache.set(v, unfiltered);
} catch (ignore) { /* ignored */ }
return unfiltered;
}
var t = typeof value;
if (!value || (t !== "object" && t !== "function") || value === window || value === document) {
// ignoring falsy, nully references, non-objects and non-functions, and global window/document
return value;
}
var isArray = Array.isArray(value);
var raw = getLockerSecret(value, "ref");
if (raw) {
// If this is an array make sure that the backing array is updated to match the system mode proxy that might have been manipulated
if (isArray) {
raw.length = 0;
value.forEach(function (v) {
raw.push(SecureObject.unfilterEverything(st, v, visited));
});
}
// returning the raw value stored in the secure reference, which means
// this value was original produced in system-mode
return raw;
}
// Handle cyclic refs and duplicate object refs
if (visited) {
var previous = visited.get(value);
if (previous) {
return previous;
}
} else {
visited = newWeakMap();
}
if (t === "function") {
// wrapping functions to guarantee that they run in user-mode, usually
// callback functions privided by non-privilege code.
return memoize(visited, value, function () {
var filteredArguments = SecureObject.filterEverything(st, SecureObject.ArrayPrototypeSlice.call(arguments));
var fnReturnedValue = value.apply(SecureObject.filterEverything(st, this), filteredArguments);
return SecureObject.unfilterEverything(st, fnReturnedValue, visited);
});
}
var proxy;
if (isArray) {
proxy = memoize(visited, value, []);
value.forEach(function (v) {
proxy.push(SecureObject.unfilterEverything(st, v, visited));
});
return proxy;
} else if (t === "object") {
proxy = memoize(visited, value, {});
for (var prop in value) {
proxy[prop] = SecureObject.unfilterEverything(st, value[prop], visited);
}
return proxy;
}
return value;
};
SecureObject.createFilteredMethod = function(st, raw, methodName, options) {
"use strict";
// Do not expose properties that the raw object does not actually support
if (!(methodName in raw)) {
if (options && options.ignoreNonexisting) {
return undefined;
} else {
throw new $A.auraError("Underlying raw object " + raw + " does not support method: " + methodName);
}
}
return {
enumerable: true,
value : function() {
var args = SecureObject.ArrayPrototypeSlice.call(arguments);
if (options && options.beforeCallback) {
options.beforeCallback.apply(raw, args);
}
var unfilteredArgs = SecureObject.unfilterEverything(st, args);
var fnReturnedValue = raw[methodName].apply(raw, unfilteredArgs);
if (options && options.afterCallback) {
fnReturnedValue = options.afterCallback(fnReturnedValue);
}
return SecureObject.filterEverything(st, fnReturnedValue, options);
}
};
};
SecureObject.createFilteredProperty = function(st, raw, propertyName, options) {
"use strict";
// Do not expose properties that the raw object does not actually support.
if (!(propertyName in raw)) {
if (options && options.ignoreNonexisting) {
return undefined;
} else {
throw new $A.auraError("Underlying raw object " + raw + " does not support property: " + propertyName);
}
}
var descriptor = {
enumerable: true
};
descriptor.get = function() {
var value = raw[propertyName];
// Continue from the current object until we find an acessible object.
if (options && options.skipOpaque === true) {
while (value) {
var hasAccess = $A.lockerService.util.hasAccess(st, value);
if (hasAccess || value === document.body || value === document.head) {
break;
}
value = value[propertyName];
}
}
if (options && options.afterGetCallback) {
// The caller wants to handle the property value
return options.afterGetCallback(value);
} else {
return SecureObject.filterEverything(st, value, options);
}
};
if (!options || options.writable !== false) {
descriptor.set = function(value) {
if (options && options.beforeSetCallback) {
value = options.beforeSetCallback(value);
}
raw[propertyName] = SecureObject.unfilterEverything(st, value);
if (options && options.afterSetCallback) {
options.afterSetCallback();
}
};
}
return descriptor;
};
SecureObject.addIfSupported = function(behavior, st, element, name, options) {
options = options || {};
options.ignoreNonexisting = true;
var prop = behavior(st, element, name, options);
if (prop) {
Object.defineProperty(st, name, prop);
}
};
SecureObject.addPropertyIfSupported = function(st, raw, name, options) {
SecureObject.addIfSupported(SecureObject.createFilteredProperty, st, raw, name, options);
};
SecureObject.addMethodIfSupported = function(st, raw, name, options) {
SecureObject.addIfSupported(SecureObject.createFilteredMethod, st, raw, name, options);
};
SecureObject.FunctionPrototypeBind = Function.prototype.bind;
SecureObject.ArrayPrototypeSlice = Array.prototype.slice;
Aura.Locker.SecureObject = SecureObject;
|
// 1.导入模块
const fs = require("fs")
const path = require("path")
// 2.使用方法 - writeFileSync()
// writeFileSync()-写文件
// 语法
// fs.writeFileSync(file, data[, options])
// 参数
// file:文件路径
// data:要写入文件的内容 (支持中文)
// options:选参
// 返回值:
// undefined
// (1)文件不存在
const res = fs.writeFileSync('./test/写个文件.txt', '你好,文件不存在,创建了一个,并且你写成功啦')
console.log('res',res) // res undefined
// 读文件
const res1 = fs.readFileSync('./test/写个文件.txt','utf-8')
console.log('res1',res1) // res1 你好,文件不存在,创建了一个,并且你写成功啦
// (2)文件存在
fs.writeFileSync('./test/info.md','你好,文件存在,又写了一点吗')
// 读文件
const res2 = fs.readFileSync('./test/info.md','utf-8')
console.log('res2',res2) // res2 你好,文件存在,又写了一点吗
// (3)文件夹不存在
fs.writeFileSync('./不存在的文件夹/写个文件.md','你好,不存在的文件夹也写成功啦')
// 读文件
const res3 = fs.readFileSync('./不存在的文件夹/写个文件.md','utf-8')
// 报错
console.log('res3',res3)
// 综上
// 文件不存在,writeFileSync()会创建文件,并写入内容
// 文件已存在,writeFileSync()会将写入的内容覆盖原来的内容
// 文件路径中有不存在的文件夹,报错
// ==> writeFileSync() 能创建文件,不能创建文件夹
|
/**
* Created by hui.sun on 15/12/10.
*/
/**
* 4pl Grid thead配置
* check:true //使用checkbox 注(选中后对象中增加pl4GridCheckbox.checked:true)
* checkAll:true //使用全选功能
* field:’id’ //字段名(用于绑定)
* name:’序号’ //表头标题名
* link:{
* url:’/aaa/{id}’ //a标签跳转 {id}为参数 (与click只存在一个)
* click:’test’ //点击事件方法 参数test(index(当前索引),item(当前对象))
* }
* input:true //使用input 注(不设置默认普通文本)
* type:text //与input一起使用 注(type:operate为操作项将不绑定field,与按钮配合使用)
* buttons:[{
* text:’收货’, //显示文本
* call:’tackGoods’, //点击事件 参数tackGoods(index(当前索引),item(当前对象))
* type:’link button’ //类型 link:a标签 button:按钮
* state:'checkstorage', //跳转路由 注(只有当后台传回按钮数据op.butType=link 才会跳转)
* style:’’ //设置样式
* }] //启用按钮 与type:operate配合使用 可多个按钮
* style:’width:10px’ //设置样式
*
*/
'use strict';
define(['../../../app'], function(app) {
app.factory('lineManage', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) {
return {
getThead: function() {
return [{
field: 'pl4GridCount',
name: '序号',
type: 'pl4GridCount'
}, {
field: 'lineId',
name: '编号'
}, {
field: 'lineName',
name: '线路名称'
}, {
field: 'deliveryFrequency',
name: '配送频率'
}, {
field: 'lineDescription',
name: '线路路径'
}, {
field: 'tranMode',
name: '运输方式'
}, {
field: 'tranType',
name: '线路类型'
}, {
field: 'remarks',
name: '备注'
}, {
field: 'op',
name: '操作',
type: 'operate',
buttons: [{
text: '修改',
btnType:'btn',
call: 'updateLine',
openModal:'#addLine'
},{text:'|'},{
text: '删除',
btnType:'btn',
call: 'deleteLine'
},{text:'|'},{
text: '查看',
btnType:'btn',
call: 'queryLine',
openModal:'#queryLine'
}]
}]
},
getSearch: function() {
var deferred = $q.defer();
$http.post(HOST + '/wlLine/getDicLists',{})
.success(function(data) {
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
},
getDataTable: function(data,url) {
//将parm转换成json字符串
data.param = $filter('json')(data.param);
var deferred = $q.defer();
$http.post(HOST + (!url?'/wlLine/queryWlLine':url), data)
.success(function(data) {
// console.log(data)
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
}
}
}]);
});
|
import React from "react";
import ReactSwitch from "react-switch";
import "./controls.css";
const Controls = ({ type, onChange, isLucene, toggleIsLucene }) => (
<div>
<form className="controls__form">
<div className="controls__form__input">
<input
type="radio"
value="all"
checked={type === "all"}
onChange={onChange}
/>
Search by all fields
</div>
<div className="controls__form__input">
<input
type="radio"
value="year"
checked={type === "year"}
onChange={onChange}
/>
Search by year and title
</div>
<div className="controls__switch">
<span>LuceneSearch</span>
<ReactSwitch checked={isLucene} onChange={toggleIsLucene} />
</div>
</form>
</div>
);
export default Controls;
|
(function() {
'use strict';
angular
.module('app.admin')
.controller('EditController', EditController);
EditController.$inject = ['logger'];
function EditController(logger) {
var vm = this;
vm.title = 'Edit';
activate();
////////////////
function activate() {
logger.info('Activated Edit View');
}
}
})();
|
import { CREATE_PARTY_SUCCESS, CREATE_PARTY_FAILURE, GET_PARTY_SUCCESS, GET_PARTY_FAILURE } from '../action-types';
const initialState = {};
export const partyReducer = (state = initialState, action) => {
switch (action.type) {
case CREATE_PARTY_SUCCESS:
return {
...state,
party: state.party.concat([action.payload]),
message: action.message,
createPartyError: false
};
case CREATE_PARTY_FAILURE:
return {
...state,
...action.payload,
message: action.message,
createPartyError: true
};
case GET_PARTY_SUCCESS:
return {
...state,
party: action.payload
};
case GET_PARTY_FAILURE:
return {
...state,
...action.payload,
message: action.message
};
default:
return state;
}
};
|
// var timedId = setInterval(function() {
// console.log("Hello World!");
// },2000);
// setTimeout(function() {
// clearInterval(timedId);
// console.log("Welcome");
// }, 10000);
var timedId = setTimeout(function tick(){
console.log("Hello");
timedId = setTimeout(tick(), 2000);
}, 10);
|
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { check, validationResult } = require('express-validator');
const auth = require("../middlewares/auth")
const User = require('../models/User');
router.get("/profile", auth, async (req, res) => {
try {
const profile = await User.findOne({
_id: req.user.id
});
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
})
// @route POST api/users
// @desc Register user
// @access Public
router.post(
'/register',
[
check('username', 'username is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { username, email, password } = req.body;
try {
const Exists = await User.findOne({ email });
if (Exists) {
return res
.status(400)
.json({ errors: [{ msg: 'User already exists' }] });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
email,
password: hashedPassword
});
const user = await newUser.save();
res.json({ user });
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
);
// @route POST api/auth
// @desc Authenticate user & get token
// @access Public
router.post(
'/login',
[
check('email', 'Please include a valid email').isEmail(),
check('password', 'Password is required').exists()
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
return res
.status(400)
.json({ errors: [{ msg: 'Invalid Credentials' }] });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res
.status(400)
.json({ errors: [{ msg: 'Invalid Credentials' }] });
}
const payload =
{
id: user.id
};
jwt.sign(
payload,
process.env.JWTSECRET,
{ expiresIn: '5 days' },
(err, token) => {
if (err) throw err;
res.json({ token, user });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
|
var express = require('express');
var mysql = require('mysql');
var router = express.Router();
var creds = require('../app');
// GET login page.
router.get('/', function(req, res, next) {
req.session.id = "";
req.session.user = 0;
req.session.emp = 0;
// if(req.query.err==302)
// res.render('login', { title: 'Login', error: '302'});
// else
res.render('login', { title: 'Login' });//, error: 'None'});
});
// POST from login page.
router.post('/verify', function(req, res, next) {
// Verify login crendentials from DB.
console.log(creds.creds[0].username);
/*var con = mysql.createConnection({
host: 'localhost',
user: 'devansh',
password: 'kanha0812',
database: 'VEHICLE_RENTAL'
});*/
var con = mysql.createConnection({
host: 'localhost',
user: creds.creds[0].username,
password: creds.creds[0].password,
database: 'VEHICLE_RENTAL'
});
con.connect(function(err) {
if(err) throw err;
console.log('Connected to PROJECT database');
if(req.body.type == 'User') {
var sql = 'SELECT Password FROM User WHERE User_ID = ' + mysql.escape(req.body.username);
con.query(sql, function(err, result) {
if(err) throw err;
if(result=='') {
// res.redirect(302, '/login');
res.render('login', { title: 'Login', value: 1 });
return;
}
var reqPass = String(req.body.password);
var resPass = result[0].Password;
if(resPass === reqPass) {
console.log('True');
//auth = true;
//res.write('Credentials verified... Redirecting to homepage...')
//sleep.sleep(2)
//res.redirect('/homeUser?uid=' + req.body.username)
req.session.user = 1;
req.session.id = req.body.username.toLowerCase();
res.redirect('/homeUser');
}
else {
console.log('False')
//res.write('Credentials invalid... Redirecting to login...')
//sleep.sleep(2)
// res.redirect(302, '/login')
res.render('login', { title: 'Login', value: 1 });
}
});
}
else {
var sql = 'SELECT Password FROM Employee WHERE User_ID = ' + mysql.escape(req.body.username);
con.query(sql, function(err, result) {
if(err) throw err;
if(result=='') {
// res.redirect(302, '/login');
res.render('login', { title: 'Login', value: 1 });
return;
}
var reqPass = String(req.body.password);
var resPass = result[0].Password;
if(resPass === reqPass) {
console.log('True');
//auth = true;
//res.write('Credentials verified... Redirecting to homepage...')
//sleep.sleep(2)
//res.redirect('/homeEmp?uid=' + req.body.username)
req.session.emp = 1;
req.session.id = req.body.username;
res.redirect('/homeEmp');
}
else {
console.log('False')
//res.write('Credentials invalid... Redirecting to login...')
//sleep.sleep(2)
// res.redirect(302, '/login')
res.render('login', { title: 'Login', value: 1 });
}
});
}
//con.end();
});
});
module.exports = router;
|
/**
* Negates the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to negate
* @returns {vec2} out
*/
export default function negate(out, a) {
out[0] = -a[0]
out[1] = -a[1]
return out
}
|
'use strict';
var url = require('url');
var utils = module.exports = {
timeout: 5 * 60,
clock: function () {
return Math.round(Date.now() / 1000);
},
encode: function (str) {
return encodeURIComponent(str)
.replace(/!/g,'%21')
.replace(/'/g,'%27')
.replace(/\(/g,'%28')
.replace(/\)/g,'%29')
.replace(/\*/g,'%2A');
},
decode: function (str) {
return decodeURIComponent(str);
},
mergeParams: function (target, src) {
target = target || {};
Object
.keys(src || {})
.forEach(function (name) {
if (/^oauth_/.test(name) || !target[name]) {
target[name] = src[name];
return;
}
if (!Array.isArray(target[name])) {
target[name] = [target[name]];
}
if (Array.isArray(src[name])) {
Array.prototype.push.apply(target[name], src[name]);
} else {
target[name].push(src[name]);
}
});
return target;
},
constantTimeCompare: function (a, b) {
var length = Math.min(a.length, b.length),
diff = 0;
for (var i = 0; i < length; ++i) {
diff |= a[i] ^ b[i];
}
return diff === 0;
},
buildSignatureData: function (req, params) {
var protocol = req.protocol || req.connection.encrypted && 'https' || 'http',
host = req.headers.host,
hostParts = host.split(':');
if (protocol === 'http' && hostParts[1] === 80 || protocol === 'https' && hostParts[1] === 443) {
host = hostParts[0];
}
var method = req.method.toUpperCase(),
hitUrl = protocol + '://' + host + url.parse(req.url).pathname,
normalizedParams = Object
.keys(params)
.sort()
.map(function (name) {
var values = params[name];
if (!Array.isArray(values)) {
values = [values];
}
return values
.sort()
.map(function (value) {
return name + '=' + utils.encode(value);
})
.join('&');
})
.join('&');
return [method, utils.encode(hitUrl), utils.encode(normalizedParams)].join('&');
},
buildRequestParams: function (req) {
// Default is the urlencoded body
var params = req.body;
// Bring in params from the url query, overriding oauth parameters
var parsedUrl = url.parse(req.url, true);
utils.mergeParams(params, parsedUrl.query);
// Finally, override oauth parameters if they're in the Authorization header
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length >= 2) {
var isOauth = /OAuth/i.test(parts[0]);
if (isOauth) {
var headerParams = /(\w+)="([^"]*)"/g.match(req.headers.authorization) || [],
oauthParams = {};
headerParams.forEach(function (param) {
var parts = /(\w+)="([^"]*)"/.exec(param),
name = utils.decode(parts[0]);
if (/^oauth_/.test(name)) {
var value = utils.decode(parts[1]);
oauthParams[name] = value;
}
});
utils.mergeParams(params, oauthParams);
}
}
}
}
};
|
import React, { Component } from 'react';
import { FormErrors } from './FormErrors';
import uuid from 'uuid';
import '../css/estilos.css';
import '../css/form.css';
import 'bootstrap/dist/css/bootstrap.css';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
id: uuid().substring(0,8),
imagen: '',
grad: '',
nombre: '',
tipo: '',
ingr: '',
chk: '',
precio: '',
formErrors: { imagen: '', grad: '', nombre: '', tipo: '', ingr: '', precio: ''},
imagenValid: false,
gradValid: false,
nombreValid: false,
tipoValid: false,
ingrValid: false,
chkValid: false,
precioValid: false,
formValid: false,
beerStore: JSON.parse(localStorage.getItem("datos")) || []
}
}
handleSubmit = (e) => {
e.preventDefault();
let data = {
id: uuid().substring(0,8),
imagen: this.state.imagen,
graduacion: this.state.grad,
nombre: this.state.nombre,
tipo: this.state.tipo,
ingredientes: this.state.ingr,
check: this.state.chk,
precio: this.state.precio
}
this.state.beerStore.push(data);
localStorage.setItem('datos', JSON.stringify(this.state.beerStore));
this.setState(prevState => {
return prevState = {
...prevState,
imagen: '',
grad: '',
nombre: '',
tipo: '',
ingr: '',
chk: '',
precio: '',
formValid: false
}
})
alert("Se ha creado la entrada correctamente!. Pulse aceptar para continuar.");
}
/* readURL(input) {
document.getElementById("imgSelected").style.display = "block";
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function (e) {
document.getElementById('imgSelected').src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
} */
handleUserInput = (e) => {
e.preventDefault();
const name = e.target.name;
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
this.setState({[name]: value},
() => { this.validateField(name, value) })
}
validateField(fieldName, value){
let fieldValidationErrors = this.state.formErrors;
let {
imagenValid, gradValid, nombreValid, tipoValid, ingrValid, chkValid, precioValid
} = this.state;
switch(fieldName){
case 'imagen':
this.imagen = value;
imagenValid = value.match(/[0-9a-zA-Z]/i);
fieldValidationErrors.imagen = imagenValid ? '' : 'Error al seleccionar archivo!';
break;
case 'grad':
this.grad = value;
gradValid = value.match(/[0-9]/i);
fieldValidationErrors.grad = gradValid ? '' : 'El campo Graduación debe ser numérico!';
break;
case 'nombre':
this.nombre = value;
nombreValid = value.match(/[a-zA-Z]/i);
fieldValidationErrors.nombre = nombreValid ? '' : 'El campo solo puede contener caracteres alfanuméricos';
break;
case 'tipo':
tipoValid = document.getElementById("tipo").selectedIndex;
let tipo2 = document.getElementById("tipo");
this.tipo = tipo2.options[tipo2.selectedIndex].text;
//console.log(this.tipo);
if((tipoValid === null) || (tipoValid === 0)){
tipoValid = false;
}else{
tipoValid = true;
}
//console.log(tipoValid);
fieldValidationErrors.tipo = tipoValid ? '' : 'Debe de seleccionar un tipo';
break;
case 'ingr':
ingrValid = value.match(/[a-zA-Z]/i);
fieldValidationErrors.ingr = ingrValid ? '' : 'El campo solo puede contener caracteres alfanuméricos';
break;
case 'chk':
chkValid = value;
//console.log(chkValid);
if(!chkValid.checked){
chkValid = false;
}else{
chkValid = true;
}
break;
case 'precio':
precioValid = value.match(/[0-9]/i);
fieldValidationErrors.precio = precioValid ? '' : 'El campo precio debe de ser numérico';
break;
default:
break;
}
this.setState(
{formErrors: fieldValidationErrors,
imagenValid: imagenValid,
gradValid: gradValid,
nombreValid: nombreValid,
tipoValid: tipoValid,
ingrValid: ingrValid,
chkValid: chkValid,
precioValid: precioValid}, this.validateForm);
}
validateForm() {
this.setState({formValid: this.state.imagenValid && this.state.gradValid && this.state.nombreValid && this.state.tipoValid &&
this.state.precioValid
});
}
errorClass(error) {
return(error.length === 0 ? '' : 'has-error');
}
render() {
return(
<form className="formBeer" method="POST" encType="multipart/form-data" onSubmit={this.handleSubmit}>
<h2>Introduzca valores para la creación:</h2>
<div className="formBorder">
<div className="panel panel-default">
<FormErrors formErrors={this.state.formErrors}/>
</div>
<div className="form-group" id="img">
<label htmlFor="imagen">Imagen:</label>
<input type="file" className="form-control-file" id="img_in" name="imagen" value={this.state.imagen}
onChange={(event) => this.handleUserInput(event)} required></input>
<img id="imgSelected" src={"/img/"+this.state.imagen.substring(12)} width="100px" height="100px" name="imgSelected"
alt="imagen seleccionada mediante cuadro de diálogo">
</img>
<br/>
</div>
<div className="form-row">
<div className={`form-group col-md-4 ${this.errorClass(this.state.formErrors.nombre)}`} id="nom">
<label htmlFor="nombre">Nombre:</label>
<input type="text" className="form-control" name="nombre" value={this.state.nombre}
onChange={(event) => this.handleUserInput(event)} required></input><br/>
</div>
<div className={`form-group col-md-2 ${this.errorClass(this.state.formErrors.grad)}`} id="grad">
<label htmlFor="grad">Graduación:</label>
<input type="text" className="form-control" size="3" name="grad" value={this.state.grad}
onChange={(event) => this.handleUserInput(event)} required></input><br/>
</div>
</div>
<div className="form-group" id="sel">
<label htmlFor="sele">Selección</label>
<select id="tipo" name="tipo" onChange={(event) => this.handleUserInput(event)} required>
<option value="0">Seleccione Un tipo</option>
<option value="1">Ale</option>
<option value="2">De trigo</option>
<option value="3">IPA</option>
<option value="4">Lager</option>
<option value="5">Lambic</option>
<option value="6" >Pilsen</option>
<option value="7">Porter</option>
<option value="8">Stout</option>
</select><br/>
</div>
<div className={`form-group ${this.errorClass(this.state.formErrors.ingr)}`} id="ingr">
<label htmlFor="ingr">Ingredientes:</label><br/>
<textarea name="ingr" rows="4" cols="80" value={this.state.ingr}
onChange={(event) => this.handleUserInput(event)}></textarea><br/>
</div>
<div className="form-group" id="check">
<label><input type="checkbox" name="chk" id="chk" value="Sin Gluten"
onChange={(event) => this.handleUserInput(event)}></input>Sin gluten</label><br />
</div>
<div className={`form-group ${this.errorClass(this.state.formErrors.precio)}`} id="pre">
<label htmlFor="precio">Precio:</label><br/>
<input type="text" name="precio" value={this.state.precio}
onChange={(event) => this.handleUserInput(event)} required></input><br/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary" disabled={!this.state.formValid} align="center">
Añadir
</button>
</div>
</div>
</form>
)
}
}
export default Form;
|
import mongoose from 'mongoose'
export default (url) => {
return mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
}
|
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var revHash = require('rev-hash');
var imageinfo = require('imageinfo');
var modifyFilename = require('modify-filename');
function transformFilename(file, opts) {
var hash = revHash(file.contents);
var ret_path = "";
file.path = modifyFilename(file.path, function(filename, ext) {
if (opts.showName == true) {
ret_path += filename;
}
if (opts.showSize == true) {
var info = imageinfo(file.contents);
var size = parseInt(file.contents.length / 1024, 10);
ret_path += "_" + info.width + "x" + info.height + "_" + size;
}
if (opts.showHash == true) {
ret_path += "_" + hash;
}
if (ret_path.length === 0) {
ret_path = filename;
}
return ret_path + ext;
});
}
;
var plugin = function(opts) {
opts = opts || {};
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError('gulp-rev', 'Streaming not supported'));
return;
}
transformFilename(file, opts);
cb(null, file);
}, function(cb) {
cb();
});
};
module.exports = plugin;
|
import {
useState,
useRef,
useLayoutEffect,
useEffect,
useContext,
lazy,
Suspense,
} from "react";
import { SiteContext } from "../SiteContext";
import { Modal } from "./Modal";
import { Link, useHistory } from "react-router-dom";
import { ProfileAvatar } from "./Account";
import {
EmailShareButton,
FacebookShareButton,
HatenaShareButton,
InstapaperShareButton,
LineShareButton,
LinkedinShareButton,
LivejournalShareButton,
MailruShareButton,
OKShareButton,
PinterestShareButton,
PocketShareButton,
RedditShareButton,
TelegramShareButton,
TumblrShareButton,
TwitterShareButton,
ViberShareButton,
VKShareButton,
WhatsappShareButton,
WorkplaceShareButton,
EmailIcon,
FacebookIcon,
HatenaIcon,
InstapaperIcon,
LineIcon,
LinkedinIcon,
LivejournalIcon,
MailruIcon,
OKIcon,
PinterestIcon,
PocketIcon,
RedditIcon,
TelegramIcon,
TumblrIcon,
TwitterIcon,
ViberIcon,
VKIcon,
WhatsappIcon,
WorkplaceIcon,
} from "react-share";
const DateRange = lazy(async () => {
await import("react-date-range/dist/styles.css");
await import("react-date-range/dist/theme/default.css");
return import("react-date-range").then((mod) => ({ default: mod.DateRange }));
});
require("./styles/elements.scss");
export const Err_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="158"
height="158"
viewBox="0 0 158 158"
>
<defs>
<linearGradient
id="linear-gradient-red"
x1="-0.298"
y1="-0.669"
x2="1.224"
y2="1.588"
gradientUnits="objectBoundingBox"
>
<stop offset="0" stopColor="#f93389" />
<stop offset="1" stopColor="#e3003e" />
</linearGradient>
</defs>
<rect
id="Rectangle_1104"
data-name="Rectangle 1104"
width="158"
height="158"
rx="79"
fill="url(#linear-gradient-red)"
/>
<g
id="Component_85_8"
data-name="Component 85 – 8"
transform="translate(49.472 49.472)"
>
<path
id="Union_3"
data-name="Union 3"
d="M29.527,34.9,5.368,59.057,0,53.686,24.158,29.527,0,5.368,5.368,0l24.16,24.158L53.686,0l5.371,5.368L34.9,29.527l24.16,24.158-5.371,5.371Z"
fill="#fff"
/>
</g>
</svg>
);
};
export const Succ_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="158"
height="158"
viewBox="0 0 158 158"
>
<defs>
<linearGradient
id="linear-gradient"
x1="-0.298"
y1="-0.669"
x2="1.224"
y2="1.588"
gradientUnits="objectBoundingBox"
>
<stop offset="0" stopColor="#336cf9" />
<stop offset="1" stopColor="#1be6d6" />
</linearGradient>
<clipPath id="clip-path">
<rect width="64" height="64" fill="none" />
</clipPath>
</defs>
<g
id="Group_163"
data-name="Group 163"
transform="translate(-0.426 -0.384)"
>
<g id="Group_103" data-name="Group 103" transform="translate(0 0)">
<rect
id="Rectangle_1104"
data-name="Rectangle 1104"
width="158"
height="158"
rx="79"
transform="translate(0.426 0.384)"
fill="url(#linear-gradient)"
/>
</g>
<g
id="Component_148_2"
data-name="Component 148 – 2"
transform="translate(47.426 58.384)"
clipPath="url(#clip-path)"
>
<rect
id="Rectangle_460"
data-name="Rectangle 460"
width="64"
height="64"
transform="translate(0 0)"
fill="none"
/>
<path
id="Checkbox"
d="M25.35,44.087,0,18.737l5.143-5.143L25.35,33.432,58.782,0l5.143,5.143Z"
transform="translate(0 1.728)"
fill="#fff"
/>
</g>
</g>
</svg>
);
};
export const X_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15.557"
height="15.557"
viewBox="0 0 15.557 15.557"
>
<defs>
<clipPath id="clip-path">
<rect width="15.557" height="15.557" fill="none" />
</clipPath>
</defs>
<g id="Cancel" clipPath="url(#clip-path)">
<path
id="Union_3"
data-name="Union 3"
d="M7.778,9.192,1.414,15.557,0,14.142,6.364,7.778,0,1.414,1.414,0,7.778,6.364,14.142,0l1.415,1.414L9.192,7.778l6.364,6.364-1.415,1.415Z"
fill="#2699fb"
/>
</g>
</svg>
);
};
export const Step_tick = ({ className }) => {
return (
<svg
className={className}
xmlns="http://www.w3.org/2000/svg"
width="65"
height="65"
viewBox="0 0 65 65"
>
<g
id="Ellipse_110"
data-name="Ellipse 110"
fill="#fff"
stroke="#336cf9"
strokeWidth="1"
>
<circle cx="32.5" cy="32.5" r="32.5" stroke="none" />
<circle cx="32.5" cy="32.5" r="32" fill="none" />
</g>
<path
id="Checkbox"
d="M12.267,23.067,0,9.8,2.489,7.112l9.778,10.38L28.444,0l2.489,2.691Z"
transform="translate(17.034 20.967)"
fill="#336cf9"
/>
</svg>
);
};
export const Step_blank = ({ className }) => {
return (
<svg
className={className}
xmlns="http://www.w3.org/2000/svg"
width="65"
height="65"
viewBox="0 0 65 65"
>
<g
id="Ellipse_229"
data-name="Ellipse 229"
fill="#fff"
stroke="#707070"
strokeWidth="1"
>
<circle cx="32.5" cy="32.5" r="32.5" stroke="none" />
<circle cx="32.5" cy="32.5" r="32" fill="none" />
</g>
</svg>
);
};
export const Step_fill = ({ className }) => {
return (
<svg
className={className}
xmlns="http://www.w3.org/2000/svg"
width="65"
height="65"
viewBox="0 0 65 65"
>
<g
id="Ellipse_110"
data-name="Ellipse 110"
fill="#336cf9"
stroke="#336cf9"
strokeWidth="1"
>
<circle cx="32.5" cy="32.5" r="32.5" stroke="none" />
<circle cx="32.5" cy="32.5" r="32" fill="none" />
</g>
<path
id="Checkbox"
d="M12.267,23.067,0,9.8,2.489,7.112l9.778,10.38L28.444,0l2.489,2.691Z"
transform="translate(17.034 20.967)"
fill="#fff"
/>
</svg>
);
};
export const InputDateRange = ({
dateRange: defaultRange,
onChange,
required,
}) => {
const dateFilterRef = useRef();
const [dateRange, setDateRange] = useState(
defaultRange || {
startDate: new Date(),
endDate: new Date(),
}
);
const [datePickerStyle, setDatePickerStyle] = useState({});
const [dateFilter, setDateFilter] = useState(!!defaultRange);
const [open, setOpen] = useState(false);
useLayoutEffect(() => {
const {
height,
y,
width,
x,
bottom,
} = dateFilterRef.current.getBoundingClientRect();
setDatePickerStyle({
position: "fixed",
top: Math.min(height + y + 4, window.innerHeight - 350),
right: Math.min(window.innerWidth - x - width, window.innerWidth - 335),
});
}, [open]);
useEffect(() => {
if (dateFilter) {
onChange?.(dateRange);
} else {
onChange?.(null);
}
}, [dateRange]);
return (
<>
<section
className={`date ${dateFilter ? "open" : ""}`}
ref={dateFilterRef}
onClick={() => setOpen(true)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="30.971"
height="30.971"
viewBox="0 0 30.971 30.971"
>
<path
id="Path_299"
data-name="Path 299"
d="M3.992,2.42H6.775V.968a.968.968,0,1,1,1.936,0V2.42H22.26V.968a.968.968,0,1,1,1.936,0V2.42h2.783a4,4,0,0,1,3.992,3.992V26.978a4,4,0,0,1-3.992,3.992H3.992A4,4,0,0,1,0,26.978V6.412A4,4,0,0,1,3.992,2.42ZM26.978,4.355H24.2v.968a.968.968,0,1,1-1.936,0V4.355H8.71v.968a.968.968,0,1,1-1.936,0V4.355H3.992A2.059,2.059,0,0,0,1.936,6.412v2.3h27.1v-2.3A2.059,2.059,0,0,0,26.978,4.355ZM3.992,29.035H26.978a2.059,2.059,0,0,0,2.057-2.057V10.646H1.936V26.978A2.059,2.059,0,0,0,3.992,29.035Z"
fill="#336cf9"
/>
</svg>
<input
className="dateInput"
type="date"
style={{
width: "100%",
height: "100%",
}}
value={
dateFilter
? moment({
time: dateRange.startDate,
format: "YYYY-MM-DD",
})
: ""
}
required={required}
onChange={() => {}}
/>
{dateFilter && (
<>
<div className="dates">
<p>
From:{" "}
<Moment format="DD MMM, YYYY">{dateRange.startDate}</Moment>
</p>
<p>
To: <Moment format="DD MMM, YYYY">{dateRange.endDate}</Moment>
</p>
</div>
<button
className="clearDateFilter"
onClick={() => {
setDateRange({
startDate: new Date(),
endDate: new Date(),
});
setDateFilter(false);
}}
>
<X_svg />
</button>
</>
)}
</section>
<Modal
open={open}
onBackdropClick={() => setOpen(false)}
backdropClass="datePicker"
className="datePicker"
style={datePickerStyle}
>
<Suspense fallback={<>Loading</>}>
<DateRange
className="dateRange"
ranges={[dateRange]}
onChange={(e) => {
setDateRange(e.range1);
if (e.range1.endDate !== e.range1.startDate) {
setOpen(false);
setDateFilter(true);
}
}}
/>
</Suspense>
</Modal>
</>
);
};
export const Prog_done = () => {
return (
<svg
className="done"
xmlns="http://www.w3.org/2000/svg"
width="214.5"
height="2"
viewBox="0 0 214.5 2"
>
<line
id="Line_22"
data-name="Line 22"
x2="214.5"
transform="translate(0 1)"
fill="none"
stroke="#1be6d6"
strokeWidth="2"
/>
</svg>
);
};
export const Prog_running = () => {
return (
<svg
className="running"
xmlns="http://www.w3.org/2000/svg"
width="200"
height="16.55"
viewBox="0 0 200 16.55"
>
<g
id="Group_203"
data-name="Group 203"
transform="translate(-5063.943 -1197)"
>
<path
id="Path_301"
data-name="Path 301"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5063.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_302"
data-name="Path 302"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5073.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_303"
data-name="Path 303"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5083.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_304"
data-name="Path 304"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5093.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_305"
data-name="Path 305"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5103.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_306"
data-name="Path 306"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5113.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_307"
data-name="Path 307"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5123.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_308"
data-name="Path 308"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5133.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_309"
data-name="Path 309"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5143.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_310"
data-name="Path 310"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5153.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_311"
data-name="Path 311"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5163.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_312"
data-name="Path 312"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5173.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_313"
data-name="Path 313"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5183.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_314"
data-name="Path 314"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5193.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_315"
data-name="Path 315"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5203.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_316"
data-name="Path 316"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5213.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_317"
data-name="Path 317"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5223.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_318"
data-name="Path 318"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5233.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_319"
data-name="Path 319"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5243.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
<path
id="Path_320"
data-name="Path 320"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5253.943 1213.55) rotate(-90)"
fill="#1be6d6"
/>
</g>
</svg>
);
};
export const Prog_runningBack = () => {
return (
<svg
className="runningBack"
xmlns="http://www.w3.org/2000/svg"
width="200"
height="16.55"
viewBox="0 0 200 16.55"
>
<g
id="Group_226"
data-name="Group 226"
transform="translate(5263.943 1213.55) rotate(-180)"
>
<path
id="Path_301"
data-name="Path 301"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5063.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_302"
data-name="Path 302"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5073.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_303"
data-name="Path 303"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5083.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_304"
data-name="Path 304"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5093.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_305"
data-name="Path 305"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5103.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_306"
data-name="Path 306"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5113.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_307"
data-name="Path 307"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5123.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_308"
data-name="Path 308"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5133.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_309"
data-name="Path 309"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5143.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_310"
data-name="Path 310"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5153.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_311"
data-name="Path 311"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5163.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_312"
data-name="Path 312"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5173.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_313"
data-name="Path 313"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5183.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_314"
data-name="Path 314"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5193.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_315"
data-name="Path 315"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5203.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_316"
data-name="Path 316"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5213.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_317"
data-name="Path 317"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5223.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_318"
data-name="Path 318"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5233.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_319"
data-name="Path 319"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5243.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
<path
id="Path_320"
data-name="Path 320"
d="M8.275,10,0,2.3,2.465,0l5.81,5.41L14.085,0,16.55,2.3Z"
transform="translate(5253.943 1213.55) rotate(-90)"
fill="#f6577c"
/>
</g>
</svg>
);
};
export const Plus_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
>
<line
id="Line_29"
data-name="Line 29"
y2="20"
transform="translate(10)"
fill="none"
stroke="#006dff"
strokeWidth="2"
/>
<line
id="Line_30"
data-name="Line 30"
x2="20"
transform="translate(0 10)"
fill="none"
stroke="#006dff"
strokeWidth="2"
/>
</svg>
);
};
export const Minus_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
>
<line
id="Line_30"
data-name="Line 30"
x2="20"
transform="translate(0 10)"
fill="none"
stroke="#006dff"
strokeWidth="2"
/>
</svg>
);
};
export const Arrow_up_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 18 18"
>
<g
id="Symbol_82"
data-name="Symbol 82"
transform="translate(-507 1272) rotate(-90)"
>
<path
id="Path_10"
data-name="Path 10"
d="M9,0,7.364,1.636l6.195,6.195H0v2.338H13.558L7.364,16.364,9,18l9-9Z"
transform="translate(1254 507)"
fill="#336cf9"
/>
</g>
</svg>
);
};
export const Arrow_down_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 18 18"
>
<g id="_1" data-name=" 1" transform="translate(525 -1254) rotate(90)">
<path
id="Path_10"
data-name="Path 10"
d="M9,0,7.364,1.636l6.195,6.195H0v2.338H13.558L7.364,16.364,9,18l9-9Z"
transform="translate(1254 507)"
fill="#ff0080"
/>
</g>
</svg>
);
};
export const Arrow_left_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
>
<path
id="Path_10"
data-name="Path 10"
d="M8,0,6.545,1.455l5.506,5.506H0V9.039H12.052L6.545,14.545,8,16l8-8Z"
transform="translate(16 16) rotate(180)"
fill="#2699fb"
/>
</svg>
);
};
export const Chev_down_svg = ({ className }) => {
return (
<svg
className={className || ""}
xmlns="http://www.w3.org/2000/svg"
width="23.616"
height="13.503"
viewBox="0 0 23.616 13.503"
>
<path
id="Icon_ionic-ios-arrow-down"
data-name="Icon ionic-ios-arrow-down"
d="M18,20.679l8.93-8.937a1.681,1.681,0,0,1,2.384,0,1.7,1.7,0,0,1,0,2.391L19.2,24.258a1.685,1.685,0,0,1-2.327.049L6.68,14.14a1.688,1.688,0,0,1,2.384-2.391Z"
transform="translate(-6.188 -11.246)"
fill="#53aefc"
/>
</svg>
);
};
export const External_link_icon = () => {
return (
<span className="externalLinkIcon" aria-label="(opens a new window)">
<svg
viewBox="0 0 20 20"
className="Polaris-Icon__Svg_375hu"
focusable="false"
aria-hidden="true"
>
<path d="M14 13v1a1 1 0 0 1-1 1H6c-.575 0-1-.484-1-1V7a1 1 0 0 1 1-1h1c1.037 0 1.04 1.5 0 1.5-.178.005-.353 0-.5 0v6h6V13c0-1 1.5-1 1.5 0zm-3.75-7.25A.75.75 0 0 1 11 5h4v4a.75.75 0 0 1-1.5 0V7.56l-3.22 3.22a.75.75 0 1 1-1.06-1.06l3.22-3.22H11a.75.75 0 0 1-.75-.75z"></path>
</svg>
</span>
);
};
export const Tick = () => {
return (
<svg
className="tick"
xmlns="http://www.w3.org/2000/svg"
width="15.1"
height="10.8"
viewBox="0 0 15.1 10.8"
>
<path
id="Path_207"
data-name="Path 207"
d="M6.5,10.8,0,4.3,2.1,2.2,6.5,6.5,13,0l2.1,2.1Z"
fill="#2699fb"
/>
</svg>
);
};
export const Cart_svg = () => {
return (
<svg
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
x="0px"
y="0px"
viewBox="0 0 122.9 107.5"
>
<g>
<path d="M3.9,7.9C1.8,7.9,0,6.1,0,3.9C0,1.8,1.8,0,3.9,0h10.2c0.1,0,0.3,0,0.4,0c3.6,0.1,6.8,0.8,9.5,2.5c3,1.9,5.2,4.8,6.4,9.1 c0,0.1,0,0.2,0.1,0.3l1,4H119c2.2,0,3.9,1.8,3.9,3.9c0,0.4-0.1,0.8-0.2,1.2l-10.2,41.1c-0.4,1.8-2,3-3.8,3v0H44.7 c1.4,5.2,2.8,8,4.7,9.3c2.3,1.5,6.3,1.6,13,1.5h0.1v0h45.2c2.2,0,3.9,1.8,3.9,3.9c0,2.2-1.8,3.9-3.9,3.9H62.5v0 c-8.3,0.1-13.4-0.1-17.5-2.8c-4.2-2.8-6.4-7.6-8.6-16.3l0,0L23,13.9c0-0.1,0-0.1-0.1-0.2c-0.6-2.2-1.6-3.7-3-4.5 c-1.4-0.9-3.3-1.3-5.5-1.3c-0.1,0-0.2,0-0.3,0H3.9L3.9,7.9z M96,88.3c5.3,0,9.6,4.3,9.6,9.6c0,5.3-4.3,9.6-9.6,9.6 c-5.3,0-9.6-4.3-9.6-9.6C86.4,92.6,90.7,88.3,96,88.3L96,88.3z M53.9,88.3c5.3,0,9.6,4.3,9.6,9.6c0,5.3-4.3,9.6-9.6,9.6 c-5.3,0-9.6-4.3-9.6-9.6C44.3,92.6,48.6,88.3,53.9,88.3L53.9,88.3z M33.7,23.7l8.9,33.5h63.1l8.3-33.5H33.7L33.7,23.7z" />
</g>
</svg>
);
};
export const Seller_cart_svg = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
width="512"
height="512"
>
<g id="Outline">
<path d="M488.2,409.63l-15.921,1.592,5.945,59.448L432,436V176h16.76l21.7,217.054,15.921-1.592L463.96,167.2A8,8,0,0,0,456,160H368V96A79.96,79.96,0,0,0,256,22.7,79.96,79.96,0,0,0,144,96v64H56a8,8,0,0,0-7.96,7.2l-5.335,53.347,15.921,1.592L63.24,176H104v75.056L76.422,264.845A8,8,0,0,0,72,272v32H88V276.944l16-8V288h16V268.944l16,8V360H88V320H72v48a8,8,0,0,0,8,8h64a8,8,0,0,0,8-8V272a8,8,0,0,0-4.422-7.155L120,251.056V176h24v18.165a16,16,0,1,0,16,0V176H288v18.165a16,16,0,1,0,16,0V176h79.16l-30.4,304H32.84l23.8-237.957-15.921-1.592L16.04,487.2A8,8,0,0,0,24,496H488a8,8,0,0,0,7.96-8.8ZM208,160H160V96a63.953,63.953,0,0,1,78.054-62.426A79.871,79.871,0,0,0,208,96Zm80,0H224V96a64.023,64.023,0,0,1,32-55.39A64.023,64.023,0,0,1,288,96Zm64,0H304V96a79.871,79.871,0,0,0-30.054-62.426A63.953,63.953,0,0,1,352,96Zm47.24,16H416V436l-46.227,34.67ZM384,480l40-30,40,30Z" />
</g>
</svg>
);
};
export const Img = ({ src: defaultSrc, ...rest }) => {
const [src, setSrc] = useState(defaultSrc);
useEffect(() => {
setSrc(defaultSrc);
}, [defaultSrc]);
return (
<img
alt={rest.alt || ""}
src={src}
onError={() => setSrc("/img_err.png")}
{...rest}
onClick={rest.onClick || function () {}}
/>
);
};
export const Checkbox = ({ defaultValue, value, required, onChange }) => {
const [checked, setChecked] = useState(!!defaultValue);
useEffect(() => {
setChecked(value);
}, [value]);
return (
<section className="checkbox">
<div className="ticks" onClick={() => setChecked(!checked)}>
<input
type="checkbox"
value={checked}
required={required}
onChange={(e) => {
setChecked(!checked);
onChange?.(!checked);
}}
/>
<svg
className="border"
xmlns="http://www.w3.org/2000/svg"
width="30"
height="30"
viewBox="0 0 30 30"
>
<g
id="Rectangle_661"
data-name="Rectangle 661"
fill="none"
stroke="#7fc4fd"
strokeWidth="3"
>
<rect width="30" height="30" rx="4" stroke="none" />
<rect x="1.5" y="1.5" width="27" height="27" rx="2.5" fill="none" />
</g>
</svg>
{checked && <Tick />}
</div>
</section>
);
};
export const Combobox = ({
options,
defaultValue,
onChange,
maxHeight,
required,
disabled,
dataId,
validationMessage,
className,
placeholder,
}) => {
const [value, setValue] = useState(() => {
if (defaultValue > -1 && options[defaultValue]) {
return options[defaultValue].label;
} else if (options.find((item) => item.value === defaultValue)) {
return options.find((item) => item.value === defaultValue).label;
} else if (typeof defaultValue === "object") {
return defaultValue?.label;
} else {
return "";
}
});
const [open, setOpen] = useState(false);
const [data, setData] = useState("");
const [optionsStyle, setOptionsStyle] = useState({});
const input = useRef();
const section = useRef();
useLayoutEffect(() => {
const { width, height, x, y } = section.current.getBoundingClientRect();
const top = window.innerHeight - y;
setOptionsStyle({
position: "absolute",
left: x,
top: Math.max(
Math.min(y + height, window.innerHeight - (37 * options.length + 8)),
8
),
width: width,
height: 37 * options.length,
maxHeight: window.innerHeight - 16,
});
}, [open]);
return (
<section
className={`combobox ${open ? "open" : ""}`}
ref={section}
onClick={() => setOpen(!open)}
>
{placeholder && !value && <label>{placeholder}</label>}
<input
ref={input}
required={required}
value={value}
autoComplete="off"
onFocus={(e) => e.target.blur()}
onChange={() => {}}
/>
<button type="button">
<svg
xmlns="http://www.w3.org/2000/svg"
width="13"
height="8.872"
viewBox="0 0 13 8.872"
>
<defs>
<clipPath id="clip-path">
<rect width="8.872" height="13" fill="none" />
</clipPath>
</defs>
<g
id="Component_47_7"
data-name="Component 47 – 7"
transform="translate(0 8.872) rotate(-90)"
clipPath="url(#clip-path)"
>
<path
id="Path_36"
data-name="Path 36"
d="M6.5,8.872,0,2.036,1.936,0,6.5,4.8,11.064,0,13,2.036Z"
transform="translate(8.872) rotate(90)"
fill="#336cf9"
/>
</g>
</svg>
</button>
<Modal
className="sectionOptions"
open={open}
setOpen={setOpen}
backdropClass="selectionOptionBack"
onBackdropClick={() => setOpen(false)}
style={optionsStyle}
>
<ul
style={{
width: "100%",
maxHeight: open ? maxHeight : 0,
zIndex: 100,
}}
className={"options"}
>
{options.map((option) => (
<li
key={option.label}
onClick={(e) => {
setData(option.value);
setValue(option.label);
onChange && onChange(option);
setOpen(false);
input.current.setCustomValidity("");
}}
className={`option ${option.className || ""} ${
value === option.label ? "selected" : ""
}`}
>
{option.label}
</li>
))}
</ul>
</Modal>
</section>
);
};
export const NumberInput = ({
defaultValue,
min,
max,
required,
onChange,
step,
placeholder,
readOnly,
}) => {
const [value, setValue] = useState(defaultValue || 0);
return (
<section className="number">
<input
type="number"
step={step || "0.01"}
required={required}
value={value}
readOnly={readOnly}
onChange={(e) => {
setValue((+e.target.value).toString());
onChange?.(e);
}}
placeholder={placeholder || "0.00"}
min={min}
max={max}
/>
<div className="ticker">
<button type="button" onClick={() => setValue(+value + 1)}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="13"
height="8.872"
viewBox="0 0 13 8.872"
>
<defs>
<clipPath id="clip-path">
<rect width="8.872" height="13" fill="none" />
</clipPath>
</defs>
<g
id="Component_47_8"
data-name="Component 47 – 8"
transform="translate(13) rotate(90)"
clipPath="url(#clip-path)"
>
<path
id="Path_36"
data-name="Path 36"
d="M6.5,8.872,0,2.036,1.936,0,6.5,4.8,11.064,0,13,2.036Z"
transform="translate(8.872) rotate(90)"
fill="#336cf9"
/>
</g>
</svg>
</button>
<button type="button" onClick={() => setValue(+value - 1)}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="13"
height="8.872"
viewBox="0 0 13 8.872"
>
<defs>
<clipPath id="clip-path">
<rect width="8.872" height="13" fill="none" />
</clipPath>
</defs>
<g
id="Component_47_7"
data-name="Component 47 – 7"
transform="translate(0 8.872) rotate(-90)"
clipPath="url(#clip-path)"
>
<path
id="Path_36"
data-name="Path 36"
d="M6.5,8.872,0,2.036,1.936,0,6.5,4.8,11.064,0,13,2.036Z"
transform="translate(8.872) rotate(90)"
fill="#336cf9"
/>
</g>
</svg>
</button>
</div>
</section>
);
};
export const FileInput = ({
required,
onChange,
prefill,
label,
multiple,
accept,
name,
}) => {
const [files, setFiles] = useState(prefill || []);
useEffect(() => {
onChange?.(files);
}, [files]);
return (
<section className="fileInput">
{files.map((item, fileIndex) => {
const file =
typeof item === "string"
? {
type: "url",
url: item,
}
: {
type: item.type,
name: item.name,
url: URL.createObjectURL(item),
};
const img =
file.type.startsWith("image") ||
file.url.match(/(\.gif|\.png|\.jpg|\.jpeg|\.webp)$/);
return (
<div key={fileIndex} className={`file ${img ? "thumb" : "any"}`}>
<button
className="close"
type="button"
onClick={() =>
setFiles((prev) => prev.filter((item, i) => i !== fileIndex))
}
>
<X_svg />
</button>
<Img
className={img ? "thumb" : ""}
src={img ? file.url : "/file_icon.png"}
/>
{!img && <p className="filename">{item.name}</p>}
</div>
);
})}
{(files.length === 0 || multiple) && (
<div className="uploadBtn">
<Plus_svg />
<input
name={name}
type="file"
multiple={multiple}
required={required}
accept={accept}
onChange={(e) => {
setFiles((prev) => [
...prev,
...[...e.target.files].filter(
(item) => !files.some((file) => file.name === item.name)
),
]);
}}
/>
</div>
)}
</section>
);
};
export const useOnScreen = (options) => {
const ref = useRef();
const [visible, setVisible] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setVisible(entry.isIntersecting);
}, options);
if (ref.current) {
observer.observe(ref.current);
}
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
};
}, [ref, options]);
return [ref, visible];
};
export const Pagination = ({
total,
btns,
perPage,
currentPage,
setCurrentPage,
setPage,
}) => {
const [pages, setPages] = useState([]);
const [links, setLinks] = useState([]);
useEffect(() => {
setPages(
[...Array(Math.ceil(total / perPage)).keys()].map((num) => num + 1)
);
setLinks([...Array(btns).keys()].map((num) => num + 1));
}, [total, perPage]);
if (total <= perPage) {
return <></>;
}
return (
<div className="pagination">
<button
disabled={currentPage <= 1}
onClick={() => setPage((prev) => prev - 1)}
>
{"<"}
</button>
<ul className="pages">
{pages.length <= btns &&
pages.map((item) => (
<li key={item} className={item === +currentPage ? "active" : ""}>
<button onClick={() => setPage(item)}>{item}</button>
</li>
))}
{pages.length > btns &&
links.map((item) => {
const remain = pages.length - btns;
const middle = Math.ceil(btns / 2);
let pivit = 0;
if (currentPage > middle) {
if (currentPage - middle + btns <= pages.length) {
pivit = currentPage - middle;
} else {
pivit = remain;
}
}
const num = item + pivit;
return (
<li key={num} className={num === currentPage ? "active" : ""}>
<button onClick={() => setPage(item)}>{num}</button>
</li>
);
})}
</ul>
<button
disabled={currentPage >= pages.length}
onClick={() => setPage((prev) => prev + 1)}
>
{">"}
</button>
</div>
);
};
export const Header = () => {
const { user, setUser, cart, setCart, userType } = useContext(SiteContext);
const history = useHistory();
const [noti, setNoti] = useState(false);
useEffect(() => {
fetch("/api/authUser")
.then((res) => res.json())
.then((data) => {
if (data.user) {
setUser(data.user);
}
});
}, []);
return (
<header className="genericHeader">
<Link className="logoLink" to="/">
<Img className="logo" src="/logo_land.jpg" alt="Delivery pay logo" />
<Img
className="logo_small"
src="/logo_sqr.jpg"
alt="Delivery pay logo"
/>
</Link>
<div className="links">
<Link to="/" className="home">
Home
</Link>
</div>
<div className="clas">
{user ? (
<ProfileAvatar key="genericHeader" />
) : (
<>
{history.location.pathname === "/u/login" ? (
<Link to="/u/join">Register</Link>
) : (
<Link to="/u/login">Login</Link>
)}
</>
)}
</div>
</header>
);
};
export const Footer = () => {
return (
<footer>
<div className="links">
<Link to="/aboutUs">About us</Link>
<Link to="/privacyPolicy">Privacy Policy</Link>
<Link to="/codeOfConduct">Code of Conduct</Link>
<Link to="/copyrightPolicy">Copyright Policy</Link>
<Link to="/fees&Charges">Fees & Charges</Link>
<Link to="/terms">User Agreement</Link>
<Link to="/howItWorks">How it works</Link>
<Link to="/contactUs">Contact us</Link>
<Link to="/employment-opportunities">Work with us</Link>
<Link to="/refundCancellationPolicy">Refund & Cancellation Policy</Link>
<Link to="/shippingDeliveryPolicy">Shipping & Delivery Policy</Link>
</div>
</footer>
);
};
export const UploadFiles = ({ files, setMsg }) => {
const cdn = process.env.REACT_APP_CDN_HOST;
const formData = new FormData();
const uploaded = [];
for (var _file of files) {
if (typeof _file === "string") {
uploaded.push(_file);
} else {
formData.append("file", _file);
}
}
return fetch(`${cdn}/upload`, {
method: "POST",
body: formData,
})
.then((res) => res.json())
.then((data) => {
if (data.code === "ok") {
return [...uploaded, ...data.files.map((link) => cdn + "/" + link)];
} else {
return null;
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>File upload failed</h4>
</div>
</>
);
}
})
.catch((err) => {
console.log(err);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>File upload failed. Make sure you're online.</h4>
</div>
</>
);
});
};
export const Media = ({ links }) => {
const [mediaPreview, setMediaPreview] = useState(false);
const [media, setMedia] = useState(null);
const [index, setIndex] = useState(0);
const medias =
links?.map((item, i) => {
let thumb = null;
let view = null;
const handleClick = (e) => {
setMediaPreview(true);
setMedia(view);
setIndex(i);
};
if (
item.match(/(\.gif|\.png|\.jpg|\.jpeg|\.webp)$/) ||
item.startsWith("https://image")
) {
thumb = (
<Img
className={index === i ? "active" : ""}
key={i}
src={item}
onClick={handleClick}
/>
);
view = <Img key={i} src={item} />;
} else if (item.match(/(\.mp3|\.ogg|\.amr|\.m4a|\.flac|\.wav|\.aac)$/i)) {
thumb = (
<div
key={i}
className={`audioThumb ${index === i ? "active" : ""}`}
onClick={handleClick}
>
<Img src="/play_btn.png" />
</div>
);
view = <audio key={i} src={item} controls="on" autoPlay="on" />;
} else if (item.match(/(\.mp4|\.mov|\.avi|\.flv|\.wmv|\.webm)$/i)) {
thumb = (
<div key={i} className={`videoThumb ${index === i ? "active" : ""}`}>
<video src={item} onClick={handleClick} />
<Img src="/play_btn.png" />
</div>
);
view = <video key={i} src={item} controls="on" autoPlay="on" />;
} else {
thumb = (
<a key={i} href={i}>
{item}
</a>
);
}
return thumb;
}) || "N/A";
return (
<>
{medias}
<Modal
className="mediaModal"
open={mediaPreview}
backdropClass="disputeMediaViewBack"
>
<button className="close" onClick={() => setMediaPreview(false)}>
<X_svg />
</button>
<div className="view">{media}</div>
<div className="thumbs">{medias}</div>
</Modal>
</>
);
};
export const Actions = ({
icon,
children,
className,
wrapperClassName,
clickable,
onClick,
}) => {
const [open, setOpen] = useState(false);
const [style, setStyle] = useState({});
const buttonRef = useRef();
const wrapperRef = useRef();
useLayoutEffect(() => {
const { height, y, width, x } = buttonRef.current?.getBoundingClientRect();
const bottom = window.innerHeight - (y + height);
const wrapper = wrapperRef.current?.getBoundingClientRect();
setStyle({
position: "fixed",
...(wrapper?.height > bottom
? height > y
? {}
: { bottom: window.innerHeight - y }
: { top: height + y + 4 }),
right: window.innerWidth - x - width,
});
}, [open]);
return (
<div className={`actions ${className || ""}`}>
<button
type="button"
className="btn"
ref={buttonRef}
onClick={(e) => {
e.stopPropagation();
setOpen(true);
onClick?.();
}}
>
{icon || <Img src="/menu_dot.png" />}
</button>
<Modal
className="actions"
backdropClass="actionsBackdrop"
open={open}
style={style}
onBackdropClick={() => setOpen(false)}
>
<ul
ref={wrapperRef}
className={wrapperClassName}
onClick={(e) => {
e.stopPropagation();
!clickable && setOpen(false);
}}
>
{children}
</ul>
</Modal>
</div>
);
};
export const Tabs = ({ basepath, tabs }) => {
const history = useHistory();
return (
<ul className="tabs">
{tabs.map((item, i) => (
<Link
to={basepath + item.path}
key={i}
onClick={() => item.onClick?.()}
>
<li
className={
history.location.pathname.startsWith(basepath + item.path)
? "active"
: ""
}
>
{item.label}
</li>
</Link>
))}
</ul>
);
};
export const User = ({ user }) => {
return (
<div className="profile">
<Img src={user.profileImg || "/profile-user.jpg"} />
<p className="name">
{user.name || user.firstName + " " + user.lastName}
<span className="contact">{user.phone}</span>
</p>
</div>
);
};
export const ShareButtons = ({ url }) => {
return (
<div className="shareBtns">
<EmailShareButton url={url}>
<EmailIcon />
</EmailShareButton>
<FacebookShareButton url={url}>
<FacebookIcon />
</FacebookShareButton>
<HatenaShareButton url={url}>
<HatenaIcon />
</HatenaShareButton>
<InstapaperShareButton url={url}>
<InstapaperIcon />
</InstapaperShareButton>
<LineShareButton url={url}>
<LineIcon />
</LineShareButton>
<LinkedinShareButton url={url}>
<LinkedinIcon />
</LinkedinShareButton>
<LivejournalShareButton url={url}>
<LivejournalIcon />
</LivejournalShareButton>
<MailruShareButton url={url}>
<MailruIcon />
</MailruShareButton>
<OKShareButton url={url}>
<OKIcon />
</OKShareButton>
<PinterestShareButton url={url}>
<PinterestIcon />
</PinterestShareButton>
<PocketShareButton url={url}>
<PocketIcon />
</PocketShareButton>
<RedditShareButton url={url}>
<RedditIcon />
</RedditShareButton>
<TelegramShareButton url={url}>
<TelegramIcon />
</TelegramShareButton>
<TumblrShareButton url={url}>
<TumblrIcon />
</TumblrShareButton>
<TwitterShareButton url={url}>
<TwitterIcon />
</TwitterShareButton>
<ViberShareButton url={url}>
<ViberIcon />
</ViberShareButton>
<VKShareButton url={url}>
<VKIcon />
</VKShareButton>
<WhatsappShareButton url={url}>
<WhatsappIcon />
</WhatsappShareButton>
<WorkplaceShareButton url={url}>
<WorkplaceIcon />
</WorkplaceShareButton>
</div>
);
};
export const moment = ({ time, format }) => {
if (new Date(time).toString() === "Invalid Date") {
return time;
}
const options = {
year: format.includes("YYYY") ? "numeric" : "2-digit",
month: format.includes("MMMM")
? "long"
: format.includes("MMM")
? "short"
: format.includes("MM")
? "2-digit"
: "numeric"
? "long"
: format.includes("ddd")
? "short"
: "narrow",
weekday: format.includes("dddd")
? "long"
: format.includes("ddd")
? "short"
: "narrow",
day: format.includes("DD") ? "2-digit" : "numeric",
hour: format.includes("hh") ? "2-digit" : "numeric",
minute: format.includes("mm") ? "2-digit" : "numeric",
second: format.includes("ss") ? "2-digit" : "numeric",
};
const values = {};
new Intl.DateTimeFormat("en-IN", options)
.formatToParts(new Date(time || new Date()))
.map(({ type, value }) => {
values[type] = value;
});
return format
.replace(/Y+/g, values.year)
.replace(/M+/g, values.month)
.replace(/D+/g, values.day)
.replace(/h+/g, values.hour)
.replace(/m+/g, values.minute)
.replace(/s+/g, values.second)
.replace(/a+/g, values.dayPeriod)
.replace(/d+/g, values.weekday);
};
export const Moment = ({ format, children, ...rest }) => {
return <time {...rest}>{moment({ time: children, format })}</time>;
};
export const calculatePrice = ({ product, gst, discount }) => {
let finalPrice = product.price;
if (discount !== false && product.discount?.amount) {
finalPrice -= calculateDiscount(product);
}
if (gst?.verified) {
finalPrice += finalPrice * ((product.gst || gst.amount) / 100);
}
if (gst === true) {
finalPrice += finalPrice * (product.gst / 100);
}
return finalPrice.fix();
};
export const calculateDiscount = ({ discount, price }) => {
if (discount?.amount) {
if (discount.type === "flat") {
return (+discount.amount).fix();
} else if (discount.type === "percent") {
return ((+price / 100) * discount.amount).fix();
} else {
return 0;
}
} else {
return 0;
}
};
export const SS = {
set: (key, value) => sessionStorage.setItem(key, value),
get: (key) => sessionStorage.getItem(key),
remove: (key) => sessionStorage.removeItem(key),
};
export const LS = {
set: (key, value) => localStorage.setItem(key, value),
get: (key) => localStorage.getItem(key),
remove: (key) =>
key.push
? key.forEach((item) => localStorage.removeItem(item))
: localStorage.removeItem(key),
};
export const addToCart = (prev, product, userType) => {
if (
prev.find((item) =>
userType === "seller"
? item.product._id === product._id && item.buyer === LS.get("buyer")
: item.product._id === product._id
)
) {
return prev.map((item) => {
if (item.product._id === product._id) {
return {
...item,
qty: item.qty + 1,
...(userType === "seller" &&
LS.get("buyer") && { buyer: LS.get("buyer") }),
};
} else {
return item;
}
});
} else {
return [
...prev,
{
product,
qty: 1,
...(userType === "seller" &&
LS.get("buyer") && { buyer: LS.get("buyer") }),
},
];
}
};
export const Tip = ({ className, children }) => {
return (
<Actions
className={`${className || ""} tip`}
wrapperClassName="tipWrapper"
icon={<Img src="/help.png" />}
>
{children}
</Actions>
);
};
|
import React from 'react'
import { BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import Header from './components/Header/header'
import Landing from './components/Landing/landing';
import Footer from './components/Footer/footer';
import Welcome from './components/Welcome/welcome'
import Signin from './components/Signin/signin';
import Signup from './components/Signup/signup';
import ErrorPage from './components/ErrorPage/errorPage';
import './App.css';
function App() {
return (
<Router>
<Header />
<Switch>
<Route path="/" exact component={Landing} />
<Route path="/welcome" component={Welcome} />
<Route path="/signin" component={Signin} />
<Route path="/signup" component={Signup} />
<Route component={ErrorPage} />
</Switch>
<Footer />
</Router>
);
}
export default App;
|
"use strict";
window.$ = window.jQuery = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
//Bootstrap from Bower
require('../../bower_components/bootstrap-sass/assets/javascripts/bootstrap');
|
// this holds the action types
export const ADD_ERROR="ADD_ERROR"
export const REMOVE_ERROR="REMOVE_ERROR"
export const SET_CURRENT_USER="SET_CURRENT_USER"
export const GET_MESSAGES="GET_MESSAGES"
export const ADD_MESSAGE="ADD_MESSAGE"
export const REMOVE_MESSAGE="REMOVE_MESSAGE"
|
$(document).ready(function() {
var animation = true;
$('.mini-background').on('click', function() {
if (animation) {
$('body').css('background-image', 'url('+$(this).data('img')+')');
animation = false;
}
setTimeout(function() {animation = true}, 1000);
});
$('.start, .start-window_list-item').on('click', function() {
$('.start').toggleClass('active');
$('.start-window').toggleClass('active');
});
// $('.window_top-menu-link').on('click', function() {
// $('.window_top-menu-link').removeClass('active');
// $(this).addClass('active');
// $('.checkout-window_part').hide();
// $('.'+$(this).data('window')).show();
// });
$('.window_close').mouseup(function () {
var startToHide = $(this).parent().parent().attr('class').split(' ')[1];
//$('.start-line.'+startToHide).remove();
$(this).parent().parent().hide();
});
$('.open-window').on('click', function() {
openWindow (this);
});
$('.open-paint-window').on('click', function() {
var cooldown = -900;
$.each($('.paint'), function(i, el) {
cooldown += 900;
$(el).addClass('active');
setTimeout(function() {
$(el).show();
}, cooldown);
});
});
function openWindow (obj) {
$('.'+$(obj).data('link')).show();
$('.window').removeClass('active');
$('.window.'+$(obj).data('link')).addClass('active');
if(!$('.window.active .shirt-body .shirt-img-thumbnails').hasClass('slick-initialized')) {
$('.window.active .shirt-body .shirt-img-thumbnails').slick({
lazyLoad: 'ondemand',
infinite: true,
slidesToShow: 4,
slidesToScroll: 1,
prevArrow: '<button type="button" class="slick-prev button">Prev</button>',
nextArrow: '<button type="button" class="slick-next button">Next</button>'
});
}
//$('.start-line').removeClass('active-line');
// if(!$('.start-line').hasClass($(obj).data('link'))) {
// $('.start-lines').append('<div class="start-line '+$(obj).data('link')+' active-line">'+$(obj).text()+'</div>');
// } else {
// $('.start-line.'+$(obj).data('link')).addClass('active-line');
// }
}
$('.button').mousedown(function () {
$('.button').removeClass('current');
$(this).addClass('current');
})
$('.shirt_img-thumbnail').on('click', function() {
$('.window.active .shirt-body .shirt_img').attr('src', $(this).attr('src'));
});
$('.pictures_img').on('click', function() {
openWindow (this);
if(!$('.window.active .main_images').hasClass('slick-initialized')) {
$('.window.active .main_images').slick({
infinite: true,
slidesToScroll: 1,
prevArrow: '<button type="button" class="slick-prev button">Prev</button>',
nextArrow: '<button type="button" class="slick-next button">Next</button>'
});
}
$('.main_images').slick('slickGoTo', $(this).data('photo'), true);
});
var timer = 0;
$('.desktop_icon').on('click', function() {
if(timer == 0) {
timer = 1;
timer = setTimeout(function(){
timer = 0;
}, 600);
} else {
openWindow (this);
timer = 0;
}
});
$('.shipping-part').submit(function(e) {
$('.window_top-menu-link').removeClass('active');
$('.payment-link').addClass('active');
$('.shipping-part').hide();
$('.payment-part').show();
e.preventDefault();
});
$('.place').on('click', function() {
if($('#diffplace').prop("checked")) {
$('.diffplace').show();
$('.diffplace input, .diffplace select').prop('disabled', false);
} else {
$('.diffplace').hide();
$('.diffplace input, .diffplace select').prop('disabled', true);
}
});
$('.payment-part').submit(function(e) {
$('.window_top-menu-link').removeClass('active');
$('.review-link').addClass('active');
$('.payment-part').hide();
$('.review-part').show();
e.preventDefault();
});
$('.mini-background').on('click', function() {
$('.desktop_icon').removeClass('select');
$('.desktop_icon.'+$(this).data('icon')).addClass('select');
});
function checkboxLock (checkbox) {
checkbox.change(function() {
if(this.checked) {
$('.checkout-window_button').removeAttr('disabled');
} else {
$('.checkout-window_button').prop('disabled', true);
}
});
}
checkboxLock ($('#delivery'));
checkboxLock ($('#shippingpolicy'));
$('img').each(function(){
$(this).attr('src', $(this).data('delayedsrc'));
});
});
|
import { AuthSlice } from './AuthSlice'
export const {
logout,
login,
loginSuccess,
loginFailed,
signup,
signupSuccess,
signupFailed
} = AuthSlice.actions
export { initialState as AuthState } from './AuthSlice'
export default AuthSlice.reducer
|
/*
* Generate power easing.
*
* @param {Number} p Easing power.
* @returns {Function} Easing function with the defined power.
*/
const pow = function (p = 2) {
const easeIn = (k => t => t ** k)(p);
const easeOut = (k => t => 1 - Math.abs((t - 1) ** k))(p);
return {
in: easeIn,
out: easeOut,
inout: (t) => {
return (t < .5) ? easeIn(t * 2) / 2 : (easeOut((t * 2) - 1) / 2) + .5;
},
};
};
export default pow;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.