text stringlengths 7 3.69M |
|---|
module.exports = {
// TODO Fix these tests once it's clear how to login during UI tests.
/*
'The "Import story" page has a button labelled "Import story"': browser => {
browser.page.storyImportPage().navigate()
browser.expect.element('#app').to.be.visible.after(5000)
browser
.expect.element('button[type="submit"]')
.to.be.visible.after(500)
.and.to.have.text.that.equals('Import story');
browser.end()
},
'The "Import story" page has an autofocussed text input box': browser => {
browser.page.storyImportPage().navigate()
browser.expect.element('#app').to.be.visible.after(5000)
browser
.expect.element('input[type="text"]')
.to.be.visible.after(500)
.and.have.attribute('autofocus');
browser.end()
}
*/
}
|
function $sliver(el) {
return document.getElementById(el);
}
function InitSearch() {
try
{
var sb = $sliver("tbSearch");
sb.onfocus = function() {
if (sb.value.toLowerCase() == "search...") sb.value = "";
}
sb.onblur = function() {
if (sb.value == "") sb.value = "Search...";
}
sb.onkeypress = Search;
}
catch(err)
{
}
}
function SearchClick() {
location.href = "http://www.drexel.edu/search.aspx?q=" + escape(document.getElementById("tbSearch").value);
}
function Search(e) {
var d = "http://www.drexel.edu/search.aspx?q=";
var keyCode;
var source;
if (!e) var e = window.event;
keyCode = e.keyCode ? e.keyCode : e.charCode;
source = e.srcElement ? e.srcElement : e.target;
if (keyCode == 13) {
location.href = d + escape(source.value);
return false;
}
}
function InitHovers() {
window.setTimeout("SetHovers()", 500);
}
function SetHovers() {
var img_a = document.getElementsByTagName("img");
if (!img_a) return;
for (var x=0;x<img_a.length;x++) {
var i = img_a[x];
if (i.src.indexOf("blank.gif") == -1 && $j(i).hasClass("hover")) { //i.className.indexOf("hover") != -1) {
i.onmouseover = function() {
var arr = this.src.split(".");
arr[arr.length-2] += "-over";
this.src = arr.join(".");
}
i.onmouseout = function() {
this.src = this.src.replace("-over.", ".");
}
}
}
}
var _LoadEventFunctions = Array();
function AddLoadEvent(func) {
_LoadEventFunctions[_LoadEventFunctions.length] = func;
}
function LoadEvents() {
for (var x=0;x<_LoadEventFunctions.length;x++) {
var func = _LoadEventFunctions[x];
func();
}
}
AddLoadEvent(InitSearch);
AddLoadEvent(InitHovers);
window.onload = LoadEvents; |
'use strict';
angular.module('biofuels.core.resource.service', [
'ngResource'
])
.factory(
'resourceService',
function ($resource) {
var url = 'http://biofuels-csis471.rhcloud.com';
var userAuth = $resource(url + '/api/v1/user/auth', {}, {
'save': {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
});
var userRegister = $resource(url + '/api/v1/user/create', {}, {
'save': {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
});
var customerList = $resource(url + '/api/v1/customer/list', {}, {
'get': {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
});
var customerCreate = $resource(url + '/api/v1/customer/create', {}, {
'save': {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
});
var vialList = $resource(url + '/api/v1/vial/list', {}, {
'get': {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
});
var vialCreate = $resource(url + '/api/v1/vial/create', {}, {
'save': {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
});
return {
userAuth: userAuth,
userRegister: userRegister,
customerList: customerList,
customerCreate: customerCreate,
vialList: vialList,
vialCreate: vialCreate
};
}
);
|
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);
Vue.config.productionTip = false
import Home from './components/Home';
import Test from './components/Test';
import Admin from './components/Admin';
const routes = [
{
name: 'home',
path: '/',
component: Home
},
{
name: 'test',
path: '/test',
component: Test
},
{
name: 'admin',
path: '/admin',
component: Admin
}
];
const router = new VueRouter({mode: 'history', routes: routes});
new Vue(Vue.util.extend({ router }, App)).$mount('#app'); |
import React from 'react';
import CardContent from './CardContent';
import PropTypes from 'prop-types';
import './styles/ServicesCard.css';
const ServicesCard = ({ delay, iconCSS, cardColor, title, content }) => {
return (
<div className="col-md-6" data-aos="fade-up" data-aos-delay={delay}>
<div className={`serviceCard ${cardColor}`}>
<CardContent content={content} iconCSS={iconCSS} title={title} />
</div>
</div>
);
};
ServicesCard.propTypes = {
delay: PropTypes.number,
cardColor: PropTypes.oneOf(['white', 'black']),
iconCSS: PropTypes.string,
title: PropTypes.string,
content: PropTypes.string,
};
export default ServicesCard;
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { Global } from '@emotion/react'
ReactDOM.render(
<>
<Global
styles={{
'*': { boxSizing: 'border-box' },
body: {
color: 'rgb(255, 255, 255, 0.9)',
fontFamily: '"Courier New", Courier, monospace',
fontSize: '1.5rem',
padding: 0,
margin: 0,
},
p: {
margin: 0,
},
input: {
color: 'rgb(255, 255, 255, 0.9)',
backgroundColor: 'transparent',
border: '1px solid rgba(255, 255, 255, 0.23)',
borderRadius: 4,
fontFamily: '"Courier New", Courier, monospace',
fontSize: '1.2rem',
height: 48,
padding: '0 16px',
'&:hover': {
border: '1px solid rgba(255, 255, 255, 0.9)',
},
},
}}
/>
<App />
</>,
document.getElementById('root')
)
|
function findAmicableNumbers(upToN) {
return new Array(upToN)
.fill()
.map((_, ind) => ind)
.map(findSumOfDivisors)
.filter((div, ind, divisors) => divisors[div] === ind && divisors[div] !== div);
function findSumOfDivisors(n) {
if(n <= 1) return 0;
let divSum = 1;
const cutoff = Math.sqrt(n);
for(let testDiv = 2; testDiv < cutoff; testDiv++) {
if(n % testDiv === 0) divSum += (testDiv + n / testDiv)
}
if(n % cutoff === 0) divSum += cutoff;
return divSum;
}
}
console.log(findAmicableNumbers(10000).reduce((acc, el) => acc + el, 0)); |
// [Sergio D. Jubera]
// Represents an abstract, general AI machine state. Every type of automaton or
// robot should implement its own subclass of this one, with its specific
// behaviour.
AiAutomatonClass = Class.extend({
_entity: null, // pointer to entity, to gather and update position & velocity coordinates
route: null, // route to follow in idle state, if any (e.g.: enemies walking around)
_currentState: 'idle', // current state of the automaton
init: function(ent) {
this._entity = ent;
this.route = new AiRouteClass();
},
update: function() {
switch (this._currentState) {
case 'idle':
var destination = this.route.nextPoint();
if (destination !== null) {
if (distance(this._entity.pos, destination) > 5) {
this.lookAt(destination);
this.moveTo(destination);
}
else
this.route.moveToNext();
}
else
this._currentState = 'stop';
break;
case 'stop':
default:
break;
}
},
// Moves towards the specified point.
moveTo: function(point) {
var move_dir = new Vec2(point.x - this._entity.pos.x, point.y - this._entity.pos.y);
this.move(move_dir);
},
// Move in specified direction.
move: function(move_dir) {
if (this._entity.inputInfo === null)
this._entity.inputInfo = new InputInfoClass();
var inputInfo = this._entity.inputInfo;
if (move_dir.LengthSquared())
{
move_dir.Normalize();
move_dir.Multiply(this._entity.speed);
inputInfo.walking = true;
inputInfo.move_dir = move_dir;
}
else
inputInfo.walking = false;
},
// Look at specified point (quantized).
lookAt: function(point) {
var look_dir = new Vec2(point.x - this._entity.pos.x, point.y - this._entity.pos.y);
if (this._entity.inputInfo === null)
this._entity.inputInfo = new InputInfoClass();
this._entity.inputInfo.faceAngle0to3 = quantizeAngle(look_dir, 4);
},
// Do attack.
attack: function() {
if (this._entity.inputInfo === null)
this._entity.inputInfo = new InputInfoClass();
this._entity.inputInfo.fire0 = true;
},
stop: function() {
if (this._entity.inputInfo === null)
this._entity.inputInfo = new InputInfoClass();
var inputInfo = this._entity.inputInfo;
inputInfo.move_dir = new Vec2(0, 0);
inputInfo.walking = false;
this._currentState = 'stop';
}
});
|
const allProductsReducers=function allProductsreduce(state=null,action){
var allProducts= [
{
name: 'Lenovo',
price: '940',
stock: '530',
description: 'Elctronics',
category: 'Electronics',
imageUrl: 'lenovo.jpg',
id: 1
},
{
name :'Hp',
price: '940',
stock: '600',
description: 'NIce',
category: 'Electronics',
imageUrl: 'hp.jpg',
id: 2
},
{
name :'Accer',
price: '940',
stock: '600',
description: 'NIce',
category: 'Electronics',
imageUrl: 'hp.jpg',
id: 3
},
{
name :'Dell',
price: '940',
stock: '600',
description: 'NIce',
category: 'Electronics',
imageUrl: 'hp.jpg',
id: 4
}
]
switch(action.type){
case 'Delete_Product':
return state.filter(prod=>action.payload!== prod.id);
case 'Add_Product':
var length=state.length
return [
...state,
{
id:++length,
name:action.payload.name,
price:action.payload.price,
category:action.payload.category,
imageUrl:action.payload.imageUrl,
stock:action.payload.stock,
description:action.payload.description,
}
]
case 'search_product':
allProducts=allProducts.filter((prod)=>{
return prod.name.toLocaleLowerCase().includes(action.payload.toLocaleLowerCase());
})
return allProducts;
case 'Update_Product':
// console.log("reducer")
for (var i in state){
if(parseInt(action.payload.id)===state[i].id){
// console.log("reducerIf")
state[i].name=action.payload.name
state[i].price=action.payload.price
state[i].description=action.payload.description
state[i].stock=action.payload.stock
state[i].category=action.payload.category
state[i].imageUrl=action.payload.imageUrl
}
}
return state;
case 'sort_product':
if(action.payload!==''){
if(action.payload==='name'){
allProducts.sort((a,b)=>{
if(a.name.toLocaleLowerCase()<b.name.toLocaleLowerCase()){return -1}
if(a.name.toLocaleLowerCase()>b.name.toLocaleLowerCase()){return 1}
return 0
})
return allProducts
}
if(action.payload==='price'){
allProducts.sort((a,b)=>{
if(parseInt(a.price)<parseInt(b.price)){return -1}
if(parseInt(a.price)>parseInt(b.price)){return 1}
return 0
})
return allProducts;
}
if(action.payload==='stock'){
allProducts.sort((a,b)=>{
if(parseInt(a.stock)<parseInt(b.stock)){return -1}
if(parseInt(a.stock)>parseInt(b.stock)){return 1}
return 0
})
return allProducts;
}
}else{
return allProducts;
}
break;
case 'category_product':
return allProducts.filter(prod=>prod.category===action.payload)
default:
break;
}
return allProducts;
}
export default allProductsReducers; |
import React from "react"
import { Route, Switch } from "react-router-dom"
import Header from "./components/header/Header"
import Landing from "./components/page/Landing"
import NotFound from "./components/NotFound"
import Footer from "./components/footer/Footer"
import "./App.scss"
function App() {
return (
<div className="app">
<Header />
<Switch>
<Route exact path="/" render={(props) => <Landing {...props} />} />
<Route component={NotFound} />
</Switch>
<Footer />
</div>
)
}
export default App
|
import React from "react";
import { connect } from "react-redux";
import { createUseStyles } from "react-jss";
const useStyles = createUseStyles({
container: {
display: "flex",
justifyContent: "center",
position: "absolute",
top: "20px",
width: "100vw",
height: "50px",
zIndex: "1000",
},
contentCard: {
minWidth: "250px",
backgroundColor: "#FFF",
borderRadius: "10px",
padding: "15px",
boxShadow: "0 3px 14px rgba(0,0,0,0.4)",
opacity: "0.8",
display: "flex",
justifyContent: "center",
alignItems: "center",
},
});
const ActivityDisplay = (props) => {
const classes = useStyles();
return (
<div className={classes.container}>
<div className={classes.contentCard}>
<h2>{props.text}</h2>
</div>
</div>
);
};
const mapStateToProps = (state) => ({});
const mapDispatchToProps = (dispatch) => ({});
export default connect(mapStateToProps, mapDispatchToProps)(ActivityDisplay);
|
function fixTheMeerkat(arr) {
let temp = arr[arr.length - 1];
arr[arr.length - 1] = arr[0];
arr[0] = temp;
return arr;
} |
import React from 'react';
import Top from './top.jsx'
import Pro from '../assets/pro.jpg'
import {Link } from 'react-router-dom'
// import Port from './portfolio'
import {AiFillDribbbleCircle , AiFillBehanceSquare ,AiFillGithub, AiOutlineTwitter} from 'react-icons/ai'
const Home=()=>{
return (
<div>
<Top home="HOME" portfolio="PORTFOLIO" contact="CONTACT" />
{/* intro page */}
<section className="flow">
<div className="intro" >
<div className="img">
<center>
<img src={Pro} alt="" className="prof"/>
</center>
</div>
{/* the bio aspect */}
<div className="bio">
<div className="content">
<h4 >Ejeh Obiabo Immanuel</h4>
<center> <span className="empty"></span></center>
<div className="author">
<p style={{textAlign:'center'}}>A UI/UX Designer | Web Developer | App Developer .</p><p> I simplify the web and applicatio for you all i see in the world is designed and programmed. </p>
</div>
</div>
<center>
<div className="detailed">
<ul className='entail'>
<li><AiOutlineTwitter id="twitter" onClick={()=>window.location='https://twitter.com/yhoungdev'}/></li>
<li ><AiFillDribbbleCircle id="dribbble" onClick={()=>window.location='https://dribbble.com/obiabo'} /></li>
<li><AiFillBehanceSquare id="behance" onClick={()=>window.location='https://behance.com/yhoungdev'} /></li>
<li ><AiFillGithub id="github" onClick={()=>window.location='https://github.com/yhoungdev'}/></li>
</ul>
</div>
</center>
<center>
<div className="but">
<Link to='./Port'>
<button className="btn">EXPLORE</button>
</Link>
</div>
</center>
</div>
</div>
</section>
</div>
)
}
export default Home
|
rand = function(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
};
var MosaicBackgroundWidget = (function(){
var container = document.getElementById('widgetContainer');
var containerWidth, containerHeight;
var textWarning = document.getElementById('textWarning');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var color, arrColor;
var showBackgroundPattern = true;
var listImgSrc = [];
var listImages = [];
var movingObjects = [];
var grids = [];
var imageWidth = 200;
var magnet = 2000;
var mouse = { x: 1, y: 0 };
var isRunning = false;
var isStop = false;
var sessionId = 0;
//=====================================================================
// Steps to animate: preload images => pre-process images => run & loop
//=====================================================================
function getImages(imageSetting, isOriginal){
var images = [];
if(imageSetting && imageSetting.length > 0)
for(var i=0;i<imageSetting.length;i++){
var imgArr = imageSetting[i].images
if(isOriginal)
images.push(imgArr[0].url); // get original image
else
images.push(imgArr[imgArr.length-1].url); //get smallest image
}
return images;
}
function preloadImages(currentSesssionId) {
var loaded = 0;
for(var i=0;i<listImgSrc.length;i++) {
var image = new Image();
image.onload = function() {
if(++loaded >= listImgSrc.length) {
if(currentSesssionId == sessionId){
preprocessImages();
}
}
}
image.src = listImgSrc[i];
listImages.push(image);
}
}
function preprocessImages() {
for(var i=0;i<listImages.length;i++) {
listImages[i].oriWidth = listImages[i].width;
listImages[i].oriHeight = listImages[i].height;
listImages[i].width = imageWidth;
listImages[i].height = listImages[i].width * listImages[i].oriHeight/listImages[i].oriWidth;
}
run();
}
function run() {
var averageHeight = 0;
for(var i=0;i<listImages.length;i++) {
averageHeight += listImages[i].height;
}
averageHeight = averageHeight/listImages.length;
var numberRandomPhoto = (Math.ceil(containerWidth / imageWidth)) * (Math.ceil(containerHeight / averageHeight));
if (showBackgroundPattern) {
createGrid();
}
populateCanvas(numberRandomPhoto * 4);
canvas.className += ' ready';
render();
addListeners();
};
function addListeners() {
container.addEventListener('mousemove', updateMouse);
container.addEventListener('touchmove', updateMouse);
};
function updateMouse(e) {
mouse.x = e.touches ? e.touches[0].clientX : e.clientX;
mouse.y = e.touches ? e.touches[0].clientY : e.clientY;
};
function createGrid() {
var numberCols = Math.ceil(containerWidth / imageWidth);
var numberFullCols = 0;
var x,y;
var indexImage = 0;
var previousRowGridItem = null;
while(true) {
indexImage = rand(0, listImages.length-1);
if(grids.length >= numberCols) {
previousRowGridItem = grids[grids.length - numberCols];
}
x = imageWidth * (grids.length % numberCols);
y = previousRowGridItem != null ? (previousRowGridItem.y + previousRowGridItem.image.height) : 0;
grids.push(new GridItem(x,y, listImages[indexImage]));
// Check grid be full
if(x == 0) // the first item in a row
numberFullCols = 0;
if(y + listImages[indexImage].height >= containerHeight) { // full the height of the container
numberFullCols++;
}
if(numberFullCols >= numberCols) {
break;
}
}
for (var i=0; i < grids.length; i++) {
grids[i].draw();
}
};
function populateCanvas(nb) {
var i = 0;
var indexImage = 0;
while (i <= nb) {
indexImage = rand(0, listImages.length-1);
var p = new Photo(listImages[indexImage]);
movingObjects.push(p);
i++;
}
};
function GridItem(x, y, image) {
if (x == null) {
x = 0;
}
if (y == null) {
y = 0;
}
this.x = x;
this.y = y;
this.image = image;
this.draw = function() {
// ctx.save();
//ctx.drawImage(image, 0, 0, image.oriWidth, image.oriHeight, x, y, image.width, image.height);
// ctx.globalCompositeOperation = "multiply";
// ctx.fillStyle = color;
// ctx.fillRect(x, y, image.width, image.height);
//ctx.restore();
// blend mode - multiply - fix for IE
if(!this.canvasTemp){
this.canvasTemp = document.createElement("canvas");
this.canvasTemp.width = image.width;
this.canvasTemp.height = image.height;
var ctxTemp = this.canvasTemp.getContext('2d');
ctxTemp.drawImage(image, 0, 0, image.oriWidth, image.oriHeight, 0, 0, image.width, image.height);
var imageData = ctxTemp.getImageData(0, 0, image.width, image.height);
for(var i=0; i < imageData.data.length ; i+=4) {
imageData.data[i] = arrColor[0] * imageData.data[i] / 255;
imageData.data[i+1] = arrColor[1] * imageData.data[i+1] / 255;
imageData.data[i+2] = arrColor[2] * imageData.data[i+2] / 255;
}
ctxTemp.putImageData(imageData, 0, 0);
}
ctx.drawImage(this.canvasTemp, x, y);
};
};
function Photo(image) {
var seed = Math.random() * (2.5 - 0.7) + 0.7;
var w = image.width / seed;
var h = image.height / seed;
var x = containerWidth * Math.random();
var y = containerHeight * Math.random();
var finalX = x;
var finalY = y;
var r = Math.random() * (180 - (-180)) + (-180);
var forceX = 0;
var forceY = 0;
var TO_RADIANS = Math.PI / 180;
this.image = image;
this.update = function() {
var distance, dx, dy, powerX, powerY, x0, x1, y0, y1;
x0 = x;
y0 = y;
x1 = mouse.x;
y1 = mouse.y;
dx = x1 - x0;
dy = y1 - y0;
distance = Math.sqrt((dx * dx) + (dy * dy));
powerX = x0 - (dx / distance) * magnet / distance;
powerY = y0 - (dy / distance) * magnet / distance;
forceX = (forceX + (finalX - x0) / 2) / 2.1;
forceY = (forceY + (finalY - y0) / 2) / 2.2;
x = powerX + forceX;
y = powerY + forceY;
};
this.draw = function() {
rotateAndPaintImage(ctx, this, r * TO_RADIANS, x, y, w / 2, h / 2, w, h);
};
};
function rotateAndPaintImage(context, photo, angle, positionX, positionY, axisX, axisY, widthX, widthY) {
if(!photo.canvasTemp) {
var canvasTemp = document.createElement('canvas');
var canvasTemp2 = document.createElement('canvas');
canvasTemp.width = widthX;
canvasTemp.height = widthY;
canvasTemp2.width = widthX;
canvasTemp2.height = widthY;
var ctxTemp = canvasTemp.getContext('2d');
var ctxTemp2 = canvasTemp2.getContext('2d');
ctxTemp2.drawImage(photo.image, 0, 0, photo.image.oriWidth, photo.image.oriHeight, 0, 0, widthX, widthY);
// ctxTemp2.globalCompositeOperation = "multiply";
// ctxTemp2.fillStyle = color;
// ctxTemp2.fillRect(0, 0, widthX, widthY);
// blend mode - multiply - fix for IE
var imageData = ctxTemp2.getImageData(0, 0, widthX, widthY);
for(var i=0; i < imageData.data.length ; i+=4) {
imageData.data[i] = arrColor[0] * imageData.data[i] / 255;
imageData.data[i+1] = arrColor[1] * imageData.data[i+1] / 255;
imageData.data[i+2] = arrColor[2] * imageData.data[i+2] / 255;
}
ctxTemp2.putImageData(imageData, 0, 0);
ctxTemp.drawImage(canvasTemp2, 0, 0);
ctxTemp.globalCompositeOperation = "destination-in";
ctxTemp.drawImage(photo.image, 0, 0, photo.image.oriWidth, photo.image.oriHeight, 0, 0, widthX, widthY);
photo.canvasTemp = canvasTemp;
}
// context.save();
// context.translate(positionX, positionY);
// context.rotate(angle);
// context.drawImage(photo.image, 0, 0, photo.image.oriWidth, photo.image.oriHeight, -axisX, -axisY, widthX, widthY);
// context.globalCompositeOperation = "multiply";
// context.fillStyle = color;
// context.fillRect(-axisX, -axisY, widthX, widthY);
// context.restore();
context.save();
context.translate(positionX, positionY);
context.rotate(angle);
context.drawImage(photo.canvasTemp, -axisX, -axisY, widthX, widthY);
context.restore();
};
function render() {
if(isStop){
isRunning = false;
grids = [];
listImages = [];
movingObjects = [];
return;
}
isRunning = true;
var x = 0, y = 0;
ctx.clearRect(0, 0, containerWidth, containerHeight);
for(var i=0; i<grids.length; i++) {
grids[i].draw();
}
for(var i=0; i<movingObjects.length; i++) {
movingObjects[i].update();
movingObjects[i].draw();
}
requestAnimationFrame(render);
};
/*==============================================*/
/*===== Start point of animation =====*/
/*==============================================*/
function reloadGlobalVariables() {
containerWidth = parseInt(window.getComputedStyle(container).getPropertyValue('width'));
containerHeight = parseInt(window.getComputedStyle(container).getPropertyValue('height'));
canvas.width = containerWidth;
canvas.height = containerHeight;
}
function stopCurrentAnimation(callback) {
isStop = true;
if(isRunning) {
var timeout = setTimeout(function(){
clearTimeout(timeout);
stopCurrentAnimation(callback);
}, 200);
} else {
isStop = false;
if(callback)
callback();
}
}
function startAnimation(currentSesssionId) {
stopCurrentAnimation(function(){
if(!listImgSrc || listImgSrc.length == 0){
if(typeof BannerFlow != "undefined" && BannerFlow.editorMode)
textWarning.style.display = "block";
return;
}
textWarning.style.display = "none";
container.setAttribute('style','background-color:' + color);
preloadImages(currentSesssionId);
});
}
/*==============================================*/
/*===== Default settings from Banner Flow =====*/
/*==============================================*/
function loadSettings() {
listImgSrc = [];
if(typeof BannerFlow !== "undefined") {
imageWidth = BannerFlow.settings.imageWidth > 10 ? BannerFlow.settings.imageWidth : 100;
color = BannerFlow.settings.backgroundColor;
showBackgroundPattern = BannerFlow.settings.showBackgroundPattern;
arrColor = color.substring("rgba(".length);
arrColor = arrColor.substring(0, color.length-1);
arrColor = arrColor.split(",");
for(var i=0;i<arrColor.length;i++) {
arrColor[i] = parseInt(arrColor[i]);
}
// for(var i=1;i<=3;i++){
// var image = BannerFlow.settings['image'+i];
// if(image && image.length > 0) {
// listImgSrc.push(image);
// }
// }
listImgSrc = getImages(BannerFlow.settings.image, true);
} else {
imageWidth = 200;
listImgSrc.push("./image1.jpg");
listImgSrc.push("./image2.jpg");
listImgSrc.push("./image3.jpg");
listImgSrc.push("./rose.png");
color = "rgba(174, 219, 15, 1)";
arrColor = color.substring("rgba(".length);
arrColor = arrColor.substring(0, color.length-1);
arrColor = arrColor.split(",");
for(var i=0;i<arrColor.length;i++) {
arrColor[i] = parseInt(arrColor[i]);
}
}
}
/*====================================================*/
var timeoutStart;
function init() {
if(timeoutStart) {
clearTimeout(timeoutStart);
timeoutStart = setTimeout(function() {
loadSettings();
reloadGlobalVariables();
startAnimation(++sessionId);
}, 500);
} else {
timeoutStart = setTimeout(function(){
loadSettings();
reloadGlobalVariables();
startAnimation(++sessionId);
}, 0);
}
}
var isStartAnimation = false;
function onStart() {
if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode && isStartAnimation) {
return;
}
isStartAnimation = true;
init();
}
function onResized(){
if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) {
return;
}
init();
}
function onSettingChanged(){
if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) {
return;
}
init();
}
return {
start: onStart,
onResized: onResized,
onSettingChanged: onSettingChanged
};
})();
if(typeof BannerFlow == "undefined"){
MosaicBackgroundWidget.start();
} else {
BannerFlow.addEventListener(BannerFlow.START_ANIMATION, function () {
MosaicBackgroundWidget.start();
});
BannerFlow.addEventListener(BannerFlow.RESIZE, function () {
MosaicBackgroundWidget.onResized();
});
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function () {
MosaicBackgroundWidget.onSettingChanged();
});
}
|
exports.CalTodayStock = function StockAnalysizer( data, callback){
//client data
var jsonobj = JSON.parse(data);
var stockToday="";
var returnArray=new Array();
//load server data//-------------------------------------------------//
var fs = require('fs');
var file = __dirname + '/today.json';
fs.readFile(file, 'utf8', function (err, datajson) {
if (err) {
console.log('Error: ' + err);
return;
}
stockToday = JSON.parse(datajson);
//console.log(stockToday);
//console.log(stockToday.stock[0].item1[0]);
//-------------------------------------------------------------------//
//load server data//
//好像要一起做 不然會錯誤 見鬼
//-------------------------------------------------------------------//
//選擇滿足item1的stocks 讀取滿足item1的json
//console.log(stockToday.stock[0]);
console.log("\nitem1 count data--------------------------------");
console.log("item1 count :" +stockToday.stock[0].item1.length );
console.log("item1 count :" +stockToday.stock[0].item2.length);
console.log("item1 count :" +stockToday.stock[0].item3.length);
console.log("item1 count :" +stockToday.stock[0].item4.length);
console.log("item1 count :" +stockToday.stock[0].item5.length);
console.log("item1 count :" +stockToday.stock[0].item6.length);
console.log("item1 count :" +stockToday.stock[0].item7.length);
console.log("item1 count data--------------------------------\n");
var countItem = 0;
var stockarr = new Array();
if ( jsonobj.item1 === true)
{
//console.log(stockToday.stock[0].item1[].length);
for( var i = 0;i <stockToday.stock[0].item1.length; ++i)
{
stockarr.push(stockToday.stock[0].item1[i]);
}
countItem++;
}
if ( jsonobj.item2 === true)
{
for( var i = 0;i <stockToday.stock[0].item2.length; ++i)
{
stockarr.push(stockToday.stock[0].item2[i]);
}
countItem++;
//////
}
if ( jsonobj.item3 === true)
{
// for( var i = 0;i <stockToday.stock[0].item3.length; ++i)
// {
// stockarr.push(stockToday.stock[0].item3[i]);
// }
// countItem++;
var item;
var iIndex = 0;
iIndex = jsonobj.Combo_Week_AVG;
console.log("Combo_Week_AVG Index:"+ iIndex);
switch ( iIndex)
{
case "13": item=stockToday.stock[0].item3; break;
case "20": item=stockToday.stock[0].item4; break;
case "50": item=stockToday.stock[0].item5; break;
default: item=stockToday.stock[0].item4; break;
}
console.log("count index: " +iIndex +" .Count:"+item.length);
for( var i = 0;i <item.length; ++i)
{
stockarr.push(item[i]);
}
//console.log(stockarr);
countItem++;
}
if ( jsonobj.item4 === true)
{
var item;
var iIndex = 0;
iIndex = jsonobj.Combo_Day_AVG;
console.log( "Combo_Day_AVG Index:"+ iIndex);
switch ( iIndex)
{
case "18": item=stockToday.stock[0].item6; break;
case "50": item=stockToday.stock[0].item7; break;
default: item=stockToday.stock[0].item6; break;
}
console.log("count index: " +iIndex +" .Count:"+item.length);
for( var i = 0;i <item.length; ++i)
{
stockarr.push(item[i]);
}
countItem++;
}
if ( jsonobj.AdvancedItem1 === true)
{
if ( typeof(stockToday.stock[0].item8) != "undefined" )
{
for( var i = 0;i <stockToday.stock[0].item8.length; ++i)
{
stockarr.push(stockToday.stock[0].item8[i]);
}
countItem++;
}
}
if ( jsonobj.AdvancedItem2 === true)
{
if ( typeof(stockToday.stock[0].item9) != "undefined" )
{
for( var i = 0;i <stockToday.stock[0].item9.length; ++i)
{
stockarr.push(stockToday.stock[0].item9[i]);
}
countItem++;
}
}
if ( jsonobj.AdvancedItem3 === true)
{
if ( typeof(stockToday.stock[0].item10) != "undefined" )
{
for( var i = 0;i <stockToday.stock[0].item10.length; ++i)
{
stockarr.push(stockToday.stock[0].item10[i]);
}
countItem++;
}
}
//sort the array
stockarr.sort();
console.log("stock choose count:"+countItem+"\n" );
//console.log(stockarr );
var count = 0;
var temp = "";
var Islast = false;
do{
if( stockarr.length == 0) break;
if( stockarr.length == 1 ){
if ( 1 == countItem ){
temp = stockarr.shift();
returnArray.push(temp);
Islast = true;
//console.log(returnArray );
}else{
temp = stockarr.shift();
}
}
else{
count = 0;
temp = stockarr.shift();
count++;
do{
if ( temp == stockarr[0] ){
temp = stockarr.shift();
count++;
}else{
break;
}
}while( stockarr.length != 0 || stockarr[0] == temp );
}
//console.log("----------------------" );
if ( count == countItem && !Islast){
//console.log( "tmp:"+temp );
returnArray.push(temp);
}
}while( stockarr.length != 0 );
(callback && typeof(callback)==="function") && callback( returnArray );
});
}
|
'use strict';
const SSL = require('../lib/SSL.js');
const expect = require('expect');
describe('testing SSL', () => {
it('SSL should exist',()=>{
let ssl = new SSL();
expect(ssl).toExist();
expect(ssl.length).toEqual(0);
})
it('adding 3 nodes', () => {
let ssl = new SSL();
ssl.add(10);
ssl.add(20);
ssl.add(30);
expect(ssl.length).toEqual(3);
expect(ssl.head.value).toEqual(10);
expect(ssl.tail.value).toEqual(30);
})
it('adding 3 nodes removing middle', () => {
let ssl = new SSL();
ssl.add(10);
ssl.add(20);
ssl.add(30);
ssl.remove(20)
expect(ssl.length).toEqual(2);
expect(ssl.head.value).toEqual(10);
expect(ssl.tail.value).toEqual(30);
})
it('reverse linked list', () => {
let ssl = new SSL();
ssl.add(10);
ssl.add(20);
ssl.add(30);
ssl.reverse();
expect(ssl.head.value).toEqual(30);
expect(ssl.tail.value).toEqual(10);
})
}); |
import flux from 'flux-react';
const actions = flux.createActions([
'toggleTextFieldStatus',
'startLoading',
'endLoading',
'selectMenuItem',
'hoverMenuItem',
'dehoverMenuItem',
'toggleCompatibility',
'addChip',
'notify',
'showBackButton',
'hideBackButton'
]);
export default actions;
|
import './styles/main.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import SonHarfApp from './app';
const sonHarfApp = new SonHarfApp({
nameAreaSelector: '.nameArea',
startMicButtonSelector: 'startMicButton',
startGameButtonSelector: '#startGameButton',
reloadGameButtonSelector: '.reloadGameButton',
timerSelector: '#timerP',
liveScoreSelector: '#liveScore',
difficultyAreaSelector: '.difficultyArea',
introductionSelector: '#introduction',
languageInputSelector: '#languageInput',
languageAreaSelector: '.languageArea',
playerNameInputSelector: 'playerNameInput'
});
sonHarfApp.init();
|
import React, { Component } from 'react';
import {Input, Alert, Table, Spinner, Button, Navbar, NavbarBrand, Nav, NavItem, NavLink, Container, Row, Col,} from 'reactstrap';
export class Search extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
query: "",
rescode: "",
response: []
};
}
componentDidMount() {
// Execute initial search function.
this.fetchSearch();
}
handleSearchChange = (value) => {
// If the user edits the search textbox, update the state with the new contents.
this.setState({query: value.target.value});
}
runSearch = () => {
// If the user clicks search, update the loading state to true to enable the loading animation.
this.setState({loading: true})
// Run the search function and forcefully reload the UI to display new results.
this.fetchSearch();
this.forceUpdate();
}
static renderSearchTable(shows, rescode) {
if (rescode !== "429") {
if (shows.length === 0) {
// If error 429 isn't returned but no results, return an alert asking the user to enter a query.
return (
<Alert color="warning">No Results. Please enter a search query or try another one.</Alert>
)
} else {
// If valid results, return table with rows created using the Map function of the show array.
return (
<Table>
<thead>
<tr>
<th>Cover</th>
<th>Title</th>
<th>Description</th>
<th>Select</th>
</tr>
</thead>
<tbody>
{shows.map(show =>
<tr>
<td><img src={show.image_url} alt="Cover Art" /></td>
<td>{show.title}</td>
<td>{show.synopsis}</td>
<td><a href={"show?ID=" + show.mal_id}><Button color="primary">Select</Button></a></td>
</tr>
)}
</tbody>
</Table>
)
}
} else {
// If 429 error code returned, notify user about being ratelimited.
return (
<Alert color="danger">You have been ratelimited by Jikan, please wait a few seconds before trying again.</Alert>
)
}
}
render() {
let contents = this.state.loading
? <Spinner color="primary" />
: Search.renderSearchTable(this.state.response, this.state.rescode); // If loading is true, display animation. Otherwise, show result table.
// Return first elements of page, including Navbar, search box and submit button.
return(
<div>
<Navbar color="dark" dark expand="md">
<NavbarBrand href="/">AniMuse</NavbarBrand>
<Nav className="mr-auto" navbar>
<NavItem>
<NavLink href="/">Search</NavLink>
</NavItem>
</Nav>
</Navbar>
<Container fluid>
<Row>
<Col xs="5"></Col>
<Col xs="5"><h1>Search</h1></Col>
</Row>
<Row>
<Col xs="10"><Input type="text" placeholder="Search for a show" id="Searchup1" name="Search" value={this.state.query} onChange={this.handleSearchChange} /></Col>
<Col xs="2"><Button color="primary" onClick={this.runSearch}>Search</Button></Col>
<br />
<br />
</Row>
<Row>
<Col xs="auto">{contents}</Col>
</Row>
</Container>
</div>
)
}
async fetchSearch() {
// Query API endpoint with current value from the query state and update state.
const response = await fetch(window.location.origin.split(':')[0] + ":" + window.location.origin.split(':')[1] + ":" + process.env.REACT_APP_SRVPORT + '/search?title=' + this.state.query);
const data = await response.json();
this.setState({response: data.search, rescode: data.response,loading: false});
}
}
export default Search; |
$(document).ready(function() {
$('form[action="?m=settings&p=themes"] tr:nth-child(5)').hide();
$('form[action="?m=settings&p=themes"]').after('<br><h2>Extra Options</h2><table class="center more-option"><tbody></tbody></table>');
$('.more-option tbody').append('<tr><td align="right"><label><a href="#"><i class="fa fa-eye" id="fp" aria-hidden="true"><span class="preview-f"><img src="" /></span></i></a> Favicon:</label></td><td align="left"><input id="favicon" name="favicon" type="text" size="50"></td><td><div class="image-tip" original-title="The Favicon Icon URL."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option tbody').append('<tr><td align="right"><label><a href="#"><i class="fa fa-eye" id="lbp" aria-hidden="true"><span class="preview-lb"><img src="" /></span></i></a> Login Background Image:</label></td><td align="left"><input id="loginbg" name="loginbg" type="text" size="50"></td><td><div class="image-tip" original-title="The Login Page\'s Background Image URL."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option tbody').append('<tr><td align="right"><label>Background Blur Effect:</label></td><td align="left"><select id="bgblur" name="bgblur"><option value="1">Enable</option><option value="0">Disable</option></select></td><td><div class="image-tip" title="Enables/Disable Blur Effect of Login/Register Background."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option tbody').append('<tr><td align="right"><label><a href="#"><i class="fa fa-eye" id="lp" aria-hidden="true"><span class="preview-l"><img src="" /></span></i></a> Logo:</label></td><td align="left"><input id="logo" name="logo" type="text" size="50"></td><td><div class="image-tip" original-title="The Logo image URL."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option tbody').append('<tr><td align="right"><label>Loading Bar:</label></td><td align="left"><select id="pace" name="pace"><option value="default">Default</option><option value="big-counter">Big Counter</option><option value="bounce">Bounce</option><<option value="center-circle">Center Circle</option><option value="center-radar">Center Radar</option><option value="center-simple">Center Simple</option><option value="corner-indicator">Corner Indicator</option><option value="center-rotate">Center Rotate</option><option value="material">Material</option></select></td><td><div class="image-tip" title="Change style of Loading Bar."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option tbody').append('<tr><td align="right"><label>Responsive Mode:</label></td><td align="left"><select id="responsive" name="responsive"><option value="1">Enable</option><option value="0">Disable</option></select><span class="beta">Beta - unstable</span></td><td><div class="image-tip" title="Enables/Disable Responsiveness for the whole theme."><img src="themes/Obsidian/images/icon_help_small.png"></div></td></tr>');
$('.more-option').after('<p class="center update_options"><img id="op_load" style="display: none;" src="images/loading.gif" /><button id="update_options">Update Options</button></p>');
$.ajax({
type: "GET",
url: "themes/Obsidian/config/config.xml",
dataType: "xml",
success: function (xml) {
// Parse the xml file and get data
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
var favicon = $(xml).find('favicon').text();
var loginbg = $(xml).find('loginbg').text();
var bgblur = $(xml).find('bgblur').text();
var logo = $(xml).find('logo').text();
var pace = $(xml).find('pace').text();
var responsive = $(xml).find('responsive').text();
$('#favicon').attr('value', favicon);
$('#loginbg').attr('value', loginbg);
if(bgblur == 1) {
$('#bgblur option[value="1"]').attr('selected', 'selected');
} else if(bgblur == 0) {
$('#bgblur option[value="0"]').attr('selected', 'selected');
}
$('#logo').attr('value', logo);
$('#pace option[value="' + pace + '"]').attr('selected', 'selected');
if(responsive == 1) {
$('#responsive option[value="1"]').attr('selected', 'selected');
} else if(responsive == 0) {
$('#responsive option[value="0"]').attr('selected', 'selected');
}
}
});
$('#update_options').click(function(){
$('#update_options').hide();
$('#op_load').show();
var favicon = $('#favicon').val();
var loginbg = $('#loginbg').val();
var bgblur = $('#bgblur').val();
var logo = $('#logo').val();
var pace = $('#pace').val();
var responsive = $('#responsive').val();
$.ajax({
url: 'themes/Obsidian/config/config.php',
type: 'POST',
data: {
favicon:favicon,
loginbg:loginbg,
bgblur:bgblur,
logo:logo,
pace:pace,
responsive:responsive
},
success: function(data) {
$('#op_load').hide();
$('#update_options').show();
alert('Updated Options successfully');
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
$('#op_load').hide();
$('#update_options').show();
alert("Failed to Update Options");
}
});
e.preventDefault();
});
$('#fp').hover(function(){
$('.preview-f img').attr('src', $('#favicon').val() + '?' + Math.random() );
});
$('#lbp').hover(function(){
$('.preview-lb img').attr('src', $('#loginbg').val() + '?' + Math.random() );
});
$('#lp').hover(function(){
$('.preview-l img').attr('src', $('#logo').val() + '?' + Math.random() );
});
}); |
import FileParser from '../loadDatabase/fileParser.js'
import PersonModel from '../models/personsModel.js'
import DateHelper from '../helper/dateHelper.js'
import Jimp from 'jimp'
import ImageHelper from '../helper/imageHelper.js'
import StrHelper from '../helper/strHelper.js'
export default class FileParserPersons extends FileParser {
constructor(log, filepath) {
super()
this.log = log
this.name = 'ВОВ. Герои'
this.pageUrls = ['surname', 'name']
this.model = PersonModel
this.filepath = filepath
// this.maxRow = 2
}
async getJsonFromRow(row) {
let json = {errorArr: [], warningArr: [], lineSource: 0}
try {
json.surname = row.Surname
json.name = row.Name
json.middlename = row.MiddleName
json.dateBirth = DateHelper.ignoreAlterDate(row.DateBirth)
json.dateBirthStr = row.DateBirth
json.dateDeath = DateHelper.ignoreAlterDate(row.DateDeath)
json.dateDeathStr = row.DateDeath
json.dateAchievement = DateHelper.ignoreAlterDate(row.DateAchievement)
json.dateAchievementStr = row.DateAchievement
json.deathYearStr = DateHelper.betweenYearTwoDates(
row.DateBirth, row.DateDeath)
json.achievementYearStr = DateHelper.betweenYearTwoDates(
row.DateBirth, row.DateAchievement)
json.description = row.Description
json.fullDescription = row.FullDescription
json.srcUrl = row.Source
const pageUrl = this.getPageUrl(json)
try {
let photoUrl = row.PhotoUrl
if (photoUrl) {
photoUrl = photoUrl.replaceAll('\\', '/')
if (photoUrl[0] == '/') {
const filename = StrHelper.getLastAfterDelim(photoUrl, '/')
photoUrl = `public/img/person/${filename}`
} else {
const middleUrl = `public/img/person-middle/${pageUrl}.png`
const res = await ImageHelper.loadImageToFile(photoUrl, middleUrl)
if (res.error) {
throw Error(`Не удалось обработать фото ${row.PhotoUrl}`) //: ${res.error}`)
}
photoUrl = middleUrl
}
const destFullUrl = `public/img/person-full/${pageUrl}.png`
let photo = await Jimp.read(photoUrl)
await photo.getBufferAsync(Jimp.MIME_PNG)
let writeResult = await photo.writeAsync(destFullUrl)
const destShortUrl = `public/img/person-short/${pageUrl}.png`
photo.resize(600, Jimp.AUTO).quality(100)
writeResult = await photo.writeAsync(destShortUrl)
json.photoFullUrl = `/img/person-full/${pageUrl}.png`
json.photoShortUrl = `/img/person-short/${pageUrl}.png`
}
} catch (err) {
console.error(err)
json.warningArr.push('' + err)
}
json.linkUrls = row.Link.split(' http')
json.linkUrls = json.linkUrls.filter(item => (item && item.length != 0))
json.linkUrls = json.linkUrls.map((item, idx) => (idx == 0 ? item : 'http' + item))
json.placeAchievement = row.PlaceAchievement
json.placeAchievementCoords = await this.getCoords(row.PlaceAchievement)
if (!json.placeAchievementCoords)
json.errorArr.push(`Не удалось найти координату достижения ${row.PlaceAchievement}`)
json.placeBirth = row.PlaceBirth
json.placeBirthCoords = await this.getCoords(row.PlaceBirth)
if (!json.placeBirthCoords)
json.errorArr.push(`Не удалось найти координату рождения ${row.PlaceBirth}`)
json.placeDeath = row.PlaceDeath
json.placeDeathCoords = await this.getCoords(row.PlaceDeath)
if (!json.placeDeathCoords)
json.errorArr.push(`Не удалось найти координату рождения ${row.PlaceDeath}`)
json.activity = row.FieldActivity
} catch(err) {
console.log(err)
json.errorArr.push('' + err)
}
return json
}
}
|
requirejs.config({
baseUrl: 'scripts'
});
define([
'constants',
'levels/levelController',
'interface/bottomPanel'
], function(constants, levelController, bottomPanel) {
var level = null;
var bootState = {
preload: function () {
game.load.image('logoGamin', 'img/logoGamin.png');
},
create: function() {
var gameContainer = document.querySelector('#game-container');
gameContainer.style.backgroundImage = "url('img/interface/gameFrame.png')";
game.state.start('preloadState');
}
};
var preloadState = {
preload: function () {
this.loadingText = game.add.text(10, 10, 'Загрузка...', {fill: 'white'});
game.load.image('title', 'img/title.png');
game.load.spritesheet('newGameButton', 'img/interface/newGameButton_spritesheet.png', 190, 49, 2, 0, 10);
game.load.bitmapFont('basis', 'fonts/basis.png', 'fonts/basis.xml');
game.load.bitmapFont('basisBlack', 'fonts/basisBlack.png', 'fonts/basisBlack.xml');
// load screens ("curtains")
game.load.image('loadScreen_romantism_1_left', 'img/load_screens/romantism_1_left.jpg');
game.load.image('loadScreen_romantism_1_right', 'img/load_screens/romantism_1_right.jpg');
game.load.image('loadScreen_romantism_2_left', 'img/load_screens/romantism_2_left.jpg');
game.load.image('loadScreen_romantism_2_right', 'img/load_screens/romantism_2_right.jpg');
game.load.image('loadScreen_romantism_3_left', 'img/load_screens/romantism_3_left.jpg');
game.load.image('loadScreen_romantism_3_right', 'img/load_screens/romantism_3_right.jpg');
game.load.image('loadScreen_romantism_4_left', 'img/load_screens/romantism_4_left.jpg');
game.load.image('loadScreen_romantism_4_right', 'img/load_screens/romantism_4_right.jpg');
game.load.image('loadScreen_renaissance_1_left', 'img/load_screens/renaissance_1_left.jpg');
game.load.image('loadScreen_renaissance_1_right', 'img/load_screens/renaissance_1_right.jpg');
game.load.image('loadScreen_renaissance_2_left', 'img/load_screens/renaissance_1_left.jpg');
game.load.image('loadScreen_renaissance_2_right', 'img/load_screens/renaissance_1_right.jpg');
game.load.image('loadScreen_renaissance_3_left', 'img/load_screens/renaissance_1_left.jpg');
game.load.image('loadScreen_renaissance_3_right', 'img/load_screens/renaissance_1_right.jpg');
game.load.image('loadScreen_suprematism_1_left', 'img/load_screens/suprematism_1_left.jpg');
game.load.image('loadScreen_suprematism_1_right', 'img/load_screens/suprematism_1_right.jpg');
game.load.image('loadScreen_suprematism_2_left', 'img/load_screens/suprematism_2_left.jpg');
game.load.image('loadScreen_suprematism_2_right', 'img/load_screens/suprematism_2_right.jpg');
game.load.image('loadScreen_suprematism_3_left', 'img/load_screens/suprematism_3_left.jpg');
game.load.image('loadScreen_suprematism_3_right', 'img/load_screens/suprematism_3_right.jpg');
game.load.image('loadScreen_ancient_1_right', 'img/load_screens/ancient_1_right.jpg');
game.load.image('loadScreen_ancient_1_left', 'img/load_screens/ancient_1_left.jpg');
game.load.image('loadScreen_ancient_2_right', 'img/load_screens/ancient_2_right.jpg');
game.load.image('loadScreen_ancient_2_left', 'img/load_screens/ancient_2_left.jpg');
game.load.image('loadScreen_ancient_3_right', 'img/load_screens/ancient_3_right.jpg');
game.load.image('loadScreen_ancient_3_left', 'img/load_screens/ancient_3_left.jpg');
game.load.image('loadScreen_final_1_left', 'img/load_screens/final_left.jpg');
game.load.image('loadScreen_final_1_right', 'img/load_screens/final_right.jpg');
// intro
game.load.spritesheet('hero_spritesheet', 'img/backgrounds/hero_spritesheet.png', 172, 292, 5, 0, 10);
game.load.spritesheet('intro_spritesheet', 'img/backgrounds/intro_spritesheet.png', 980, 600, 2, 0, 0);
// backgrounds
game.load.image('bg_intro', 'img/backgrounds/intro.png');
game.load.image('bg_final', 'img/backgrounds/final.png');
game.load.image('bg_romantism', 'img/backgrounds/romantism.jpg');
game.load.image('bg_renaissance', 'img/backgrounds/renaissance.jpg');
game.load.image('bg_suprematism', 'img/backgrounds/suprematism.jpg');
game.load.image('bg_ancient', 'img/backgrounds/ancient.jpg');
// interface
game.load.image('dialogBubble', 'img/interface/dialog-bubble.png');
game.load.image('bottomPanel', 'img/interface/bottomPanel.png');
game.load.image('heroFace', 'img/interface/heroFace.png');
game.load.spritesheet('button', 'img/interface/button_spritesheet.png', 190, 49, 2, 0, 10);
// suprematism
game.load.physics("suprematism_physics", "img/suprematism/suprematism_physics.json");
game.load.image("suprematism_bullet", "img/suprematism/bullet.png");
game.load.image("suprematism_obstacle_1", "img/suprematism/obstacle_1.png");
game.load.image("suprematism_obstacle_2", "img/suprematism/obstacle_2.png");
game.load.image("suprematism_instruction", "img/suprematism/instruction.png");
game.load.spritesheet('suprematism_boss', 'img/suprematism/boss.png', 121, 142, 2, 0, 8);
game.load.atlasJSONHash('suprematism_boss_starting', 'img/suprematism/boss_starting.png', 'img/suprematism/boss_starting.json');
game.load.spritesheet('suprematism_player', 'img/suprematism/suprematism_player.png', 42, 23, 2, 0, 10);
//romantism
game.load.image('fatmanFace', 'img/romantism/fatmanFace.png');
game.load.image('thinmanFace', 'img/romantism/thinmanFace.png');
game.load.image('womanFace', 'img/romantism/womanFace.png');
game.load.image('charFrame', 'img/romantism/faceFrame.png');
game.load.image('charDialog', 'img/romantism/dialog.png');
game.load.image('dialogLeft', 'img/romantism/dialogLeft.png');
game.load.image('dialogRight', 'img/romantism/dialogRight.png');
game.load.image('dialogCenter', 'img/romantism/dialogCenter.png');
// reneissance
game.load.image('renaissancePainting_1_1', 'img/renaissance/1_1.jpg');
game.load.image('renaissancePainting_1_2', 'img/renaissance/1_2.jpg');
game.load.image('renaissancePainting_2_1', 'img/renaissance/2_1.jpg');
game.load.image('renaissancePainting_2_2', 'img/renaissance/2_2.jpg');
game.load.image('renaissancePainting_3_1', 'img/renaissance/3_1.jpg');
game.load.image('renaissancePainting_3_2', 'img/renaissance/3_2.jpg');
game.load.image('renaissancePainting_4_1', 'img/renaissance/4_1.jpg');
game.load.image('renaissancePainting_4_2', 'img/renaissance/4_2.jpg');
game.load.image('renaissancePainting_5_1', 'img/renaissance/5_1.jpg');
game.load.image('renaissancePainting_5_2', 'img/renaissance/5_2.jpg');
game.load.image('renaissancePainting_6_1', 'img/renaissance/6_1.jpg');
game.load.image('renaissancePainting_6_2', 'img/renaissance/6_2.jpg');
// ancient
game.load.spritesheet('man', 'img/ancient/man.png', 42, 46, 4, 0, 10);
game.load.image('man_dead', 'img/ancient/man_dead.png');
game.load.image('spear', 'img/ancient/spear.png');
game.load.image('meat', 'img/ancient/meat.png');
game.load.spritesheet('wolf', 'img/ancient/wolf.png', 70, 41, 3, 0, 0);
game.load.image('mammoth', 'img/ancient/mammoth.png');
game.load.image('corral', 'img/ancient/corral.png');
// final
game.load.image('dialogLeftFinal', 'img/final/dialogLeft.png');
game.load.image('dialogRightFinal', 'img/final/dialogRight.png');
game.load.image('dialogCenterFinal', 'img/final/dialogCenter.png');
game.load.spritesheet('customers', 'img/final/customers.png', 386, 296, 2, 0, 0);
game.load.image('pic_contemporary', 'img/final/pic_contemporary.png');
game.load.image('pic_renaissanse', 'img/final/pic_renaissanse.png');
game.load.image('pic_romantism', 'img/final/pic_romantism.png');
game.load.image('pic_suprematism', 'img/final/pic_suprematism.png');
game.load.image('pic_ancient', 'img/final/pic_ancient.png');
game.load.image("ancient_instruction", "img/ancient/instruction.png");
// sounds
game.load.audio('intro', 'music/cute.wav');
game.load.audio('final', 'music/final.wav');
game.load.audio('suprematism', 'music/suprematism.wav');
game.load.audio('romantism', 'music/romantism.wav');
game.load.audio('renaissance', 'music/renaissance.wav');
game.load.audio('ancient', 'music/ancient.wav');
game.load.audio('curtains', 'music/sliding.wav');
game.load.audio('curtainsClunk', 'music/clunk.wav');
game.load.audio('buttonClick', 'music/click.wav');
game.load.audio('typing', 'music/typeClickShort.wav');
game.load.audio('shot1', 'music/shot1.wav');
game.load.audio('shot2', 'music/shot2.wav');
game.load.audio('shot3', 'music/shot3.wav');
game.load.audio('playerDamaged', 'music/bossDamaged.wav');
game.load.audio('bossDamaged', 'music/playerDamaged.wav');
game.load.audio('death', 'music/death.wav');
game.load.audio('popUp', 'music/popUp2.wav');
game.load.audio('popDown', 'music/popDown.wav');
game.load.audio('throw', 'music/throw.wav');
game.load.audio('manDeath', 'music/manDeath.wav');
game.load.audio('wolfDeath', 'music/wolfDeath.wav');
game.load.audio('growl', 'music/growl.wav');
game.load.audio('elephant', 'music/elephant.wav');
game.load.audio('howl', 'music/howl.wav');
game.load.audio('bark', 'music/bark.wav');
game.load.audio('wolfEat', 'music/wolfEat.wav');
},
create: function() {
this.loadingText.kill();
game.add.text(0, 0, 'text sample', {font: '40px basis0', fill: 'transparent'});
exitKey = game.input.keyboard.addKey(constants.KEY_ESC);
exitKey.onDown.add(function() {
var exit = confirm("Покинуть игру? (если вы играете в веб-версию, то просто закройте вкладку)");
if (exit) {
window.close();
}
});
this.logoGamin = this.add.sprite(game.world.centerX, game.world.centerY, 'logoGamin');
this.logoGamin.anchor.setTo(0.5);
this.logoGamin.alpha = 0;
var logoGaminTween = game.add.tween(this.logoGamin);
logoGaminTween.to({alpha: 1}, constants.GAME_START_DELAY, null, true);
var startNextState = function() {
var logoGaminTween = game.add.tween(this.logoGamin);
logoGaminTween.to({alpha: 0}, constants.GAME_START_DELAY, null, true);
game.time.events.add(constants.GAME_START_DELAY * 2, function(){
if (this.gameStartTimer) game.time.events.remove(this.gameStartTimer);
game.state.start('mainMenuState');
}, this);
}.bind(this);
this.gameStartTimer = game.time.events.add(constants.GAME_START_DELAY * 5, function(){
startNextState();
}, this);
},
update: function() {
}
};
var mainMenuState = {
create: function() {
exitKey = game.input.keyboard.addKey(constants.KEY_ESC);
exitKey.onDown.add(function() {
var exit = confirm("Покинуть игру? (если вы играете в веб-версию, то просто закройте вкладку)");
if (exit) {
window.close();
}
});
game.add.sprite(0, 0, 'bg_intro');
this.title = game.add.sprite(game.world.centerX, 18, 'title');
this.title.anchor.setTo(0.5, 0);
this.newGameButton = game.add.button(265, 520, 'newGameButton', this.newGame, this, 0, 0, 1, 0);
},
newGame: function() {
game.sound.play('buttonClick', 1);
this.newGameButton.kill();
var titleTween = game.add.tween(this.title);
titleTween.to({alpha: 0}, constants.GAME_START_DELAY, null, true);
game.time.events.add(constants.GAME_START_DELAY, function(){
game.state.start('mainState');
}, this);
}
};
var mainState = {
preload: function () {
},
create: function () {
exitKey = game.input.keyboard.addKey(constants.KEY_ESC);
exitKey.onDown.add(function() {
var exit = confirm("Покинуть игру? (если вы играете в веб-версию, то просто закройте вкладку)");
if (exit) {
window.close();
}
});
window.grayFilter = game.add.filter('Gray');
window.backgroundLayer = game.add.group();
window.gameObjectsLayer = game.add.group();
window.interfaceLayer = game.add.group();
window.curtainsLayer = game.add.group();
game.physics.startSystem(Phaser.Physics.ARCADE);
levelController.init();
},
update: function () {
levelController.update();
bottomPanel.update();
}
};
var gameContainer = document.querySelector('#game-container');
window.game = new Phaser.Game(constants.GAME_WITDH, constants.GAME_HEIGHT, Phaser.AUTO, gameContainer);
game.state.add('bootState', bootState);
game.state.add('preloadState', preloadState);
game.state.add('mainMenuState', mainMenuState);
game.state.add('mainState', mainState);
game.state.start('bootState');
}); |
import React from 'react';
import PhotoPage from '../features/photo/PhotoPage';
import { portfolioLink, portfolioPaginationSize } from './portfolio';
export const paginate = {
data: 'portfolio',
size: 1,
};
export const portfolioPhotoLink = function (photo) {
return `/portfolio/${photo.slug}/index.html`;
};
export const permalink = function (data) {
const photo = data.pagination.items[0];
return portfolioPhotoLink(photo);
};
let page = 0;
export default function PortfolioPhoto({ pagination, route }) {
const photo = pagination.items[0];
if (photo.index % portfolioPaginationSize === 1) {
page++;
}
let backTo = `${portfolioLink(page)}`;
return (
<PhotoPage
photo={photo}
pagination={pagination}
backTo={backTo}
backToText="Torna al portfolio"
route={route}
/>
);
}
|
function ProjectListCtrl($scope, $rootScope, $http, $localStorage, $modal, $stateParams, SweetAlert, timeAgo, nowTime, userPhotoService, Commons, Constants) {
$scope.TimeFrequency = Constants.TimeFrequency;
$scope.loading = true;
$scope.IsShowIncomeExpenseSummary = false;
$scope.totalAmount = 0;
$scope.totalIncome = 0;
$scope.totalExpense = 0;
$scope.Project = {
Id: $stateParams.id,
Title: '',
Currency: null
};
$scope.NoneCategoryFilter = {
Id: null,
CategoryTitle: 'All'
};
$scope.NoneAccountFilter = {
Id: null,
AccountTitle: 'All'
};
$scope.FilterPrevious = {
Id: 10,
Name: 'Previous',
Text: 'Previous',
Title: 'Previous',
FilterTypeId: 6,
SelectedDate: new Date(),
Order: 10
};
$scope.FilterNext = {
Id: 11,
Name: 'Next',
Text: 'Next',
Title: 'Next',
FilterTypeId: 7,
SelectedDate: new Date(),
Order: 11
};
$scope.TransactionFilters = [
{
Id: 1,
Name: 'Today',
Text: 'Today',
Title: 'Today',
FilterTypeId: 1,
SelectedDate: new Date(),
Order: 1
},
{
Id: 2,
Name: '',
Text: '',
Title: '',
FilterTypeId: 0,
SelectedDate: new Date(),
Order: 2
},
{
Id: 3,
Name: 'This Week',
Text: 'This Week',
Title: 'This Week',
FilterTypeId: 2,
SelectedDate: new Date(),
Order: 3
},
{
Id: 4,
Name: 'This Month',
Text: 'This Month',
Title: 'This Month',
FilterTypeId: 3,
SelectedDate: new Date(),
Order: 4
},
{
Id: 5,
Name: 'This Year',
Text: 'This Year',
Title: 'This Year',
FilterTypeId: 4,
SelectedDate: new Date(),
Order: 5
}
,
{
Id: 6,
Name: '',
Text: '',
Title: '',
FilterTypeId: 0,
SelectedDate: new Date(),
Order: 6
},
$scope.FilterPrevious
,
$scope.FilterNext];
$scope.TransactionFilter = {
ProjectId: $stateParams.id,
FilterType: $scope.TransactionFilters[0], // default by this week
FilterTypeId: 0,
Category: $scope.NoneCategoryFilter,
Account: $scope.NoneAccountFilter,
IsUpcoming: false,
IsUnclearOnly: false,
};
$scope.Categories = [];
$scope.Accounts = [];
$scope.SelectedTransaction = null;
$scope.PrimaryAccount = null;
$scope.Transactions = [];
$scope.Members = null;
$scope.AuditLogs = [];
$scope.CommentText = '';
$scope.UserComments = [];
$rootScope.$on(Constants.Events.ProjectHeaderUpdated, function (event, data) {
$scope.Project.Currency = data.Project.Currency;
$rootScope.CurrencyRoot = data.Project.Currency;
});
$scope.ShowIncomeExpenseSummary = function()
{
$scope.IsShowIncomeExpenseSummary = !$scope.IsShowIncomeExpenseSummary;
}
$scope.getProjectFilter = function (projectId) {
var transactionFilter = {
ProjectId: projectId
};
$http.post(Constants.WebApi.Project.GetProjectFilter, transactionFilter).then(function (response) {
// this callback will be called asynchronously
// when the response is available
var projectFilter = response.data;
var date = new Date();
if (projectFilter.FromDate != null)
{
date = new Date(projectFilter.FromDate);
projectFilter.FromDate = date;
}
$scope.updateFilterNextPrevious(projectFilter.FilterTypeId, date);
$scope.updateProjectFilter(projectFilter);
$scope.searchTransactions($scope.TransactionFilter);
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.searchTransactions($scope.TransactionFilter);
});
}
$scope.updateProjectFilter = function (filter) {
var filterType = $scope.TransactionFilters[0];
if (filter.FilterTypeId != null && filter.FilterTypeId > 0) {
filterType = $scope.getFilterType(filter.FilterTypeId);
}
$scope.TransactionFilter.FilterType = filterType;
$scope.TransactionFilter.FilterTypeId = filterType.FilterTypeId;
$scope.TransactionFilter.FromDate = filter.FromDate;
if (filter.Category != null) {
$scope.TransactionFilter.Category =
{
Id: filter.Category.Id,
CategoryTitle: null
};
var selectedCategory = $scope.getCategory(filter.Category.Id);
if (selectedCategory != null)
$scope.TransactionFilter.Category = selectedCategory;
}
if (filter.Account != null) {
$scope.TransactionFilter.Account =
{
Id: filter.Account.Id,
CategoryTitle: null
};
var selectedAccount = $scope.getAccount(filter.Account.Id);
if (selectedAccount != null)
$scope.TransactionFilter.Account = selectedAccount;
}
}
$scope.getAccount = function(accountId)
{
var matchedAccount = null;
if(accountId != null)
{
for (var i = 0; i < $scope.Accounts.length; i++) {
var account = $scope.Accounts[i];
if (account.Id == accountId) {
matchedAccount = account;
break;
}
}
}
return matchedAccount;
}
$scope.getCategory = function (categoryId) {
var matchedCategory = null;
if (categoryId != null) {
for (var i = 0; i < $scope.Categories.length; i++) {
var category = $scope.Categories[i];
if (category.Id == categoryId) {
matchedCategory = category;
break;
}
}
}
return matchedCategory;
}
$scope.saveProjectFilter = function (transactionFilter) {
$http.post(Constants.WebApi.Project.SaveProjectFilter, transactionFilter).then(function (response) {
// this callback will be called asynchronously
// when the response is available
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
$scope.searchTransactions = function (transactionFilter) {
transactionFilter.FilterTypeId = transactionFilter.FilterType.FilterTypeId;
$http.post(Constants.WebApi.Project.SearchTransactions, transactionFilter).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Transactions = response.data;
$scope.totalAmount = $scope.calcTotalAmount();
$scope.saveProjectFilter(transactionFilter);
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load Transaction Failed!",
type: "warning"
});
});
}
$scope.calcTotalAmount = function () {
$scope.totalIncome = 0;
$scope.totalExpense = 0;
for (count = 0; count < $scope.Transactions.length; count++) {
var amount = Number($scope.Transactions[count].Amount);
if ($scope.Transactions[count].IsIncome) {
$scope.totalIncome += amount;
}
else {
$scope.totalExpense += amount;
}
}
var total = $scope.totalIncome - $scope.totalExpense;
return total;
};
$scope.loadCategories = function () {
$http.get(Constants.WebApi.Project.GetAvailableCategories, { params: { projectId: $scope.Project.Id } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Categories = response.data;
if ($scope.TransactionFilter.Category.Id != null) {
var selectedCategory = $scope.getCategory($scope.TransactionFilter.Category.Id);
if (selectedCategory != null)
$scope.TransactionFilter.Category = selectedCategory;
}
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load Category Failed!",
type: "warning"
});
});
}
$scope.loadAccounts = function () {
$http.get(Constants.WebApi.Project.GetAccounts, { params: { projectId: $scope.Project.Id } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Accounts = response.data.Accounts;
$scope.PrimaryAccount = $scope.getPrimaryAccount($scope.Accounts);
if ($scope.TransactionFilter.Account.Id != null) {
var selectedAccount = $scope.getAccount($scope.TransactionFilter.Account.Id);
if (selectedAccount != null)
$scope.TransactionFilter.Account = selectedAccount;
}
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load Project Account Failed!",
type: "warning"
});
});
}
$scope.onload = function ()
{
$scope.loading = true;
$scope.loadCategories();
$scope.loadAccounts();
$scope.getProjectFilter($scope.Project.Id);
$rootScope.$broadcast(Constants.Events.ProjectChanged, $scope.Project.Id);
$scope.loading = false;
$scope.loadProjectMembers($scope.Project.Id);
}
$scope.createNewTransaction = function () {
var newTrans = {
ProjectId: $scope.Project.Id,
AccountId: null,
Account: $scope.PrimaryAccount,
CategoryId: null,
Category: null,
TransactionTitle: '',
Amount: 0,
TransactionDate: new Date(),
IsIncome: true,
RecurringTransaction: null,
RecurringTransactionId: null,
IsClear: true,
IsDeleted: false,
ClientId: null,
Client: null
}
return newTrans;
}
$scope.getPrimaryAccount = function (accounts)
{
if(accounts != null)
{
for(var i = 0; i < accounts.length; i ++)
{
var account = accounts[i];
if (account.IsPrimary) {
return account;
}
}
/*angular.forEach(accounts, function(value, key) {
if (value.IsPrimary) {
return value;
}
});*/
}
return null;
}
$scope.loadProjectMembers = function (projectId)
{
$http.get(Constants.WebApi.Project.GetProjectMembers, { params: { projectId: projectId } }).then(function (response) {
$scope.Members = response.data;
}, function (response) {
alert('Failed');
});
}
$scope.addNewExpense = function () {
var newTrans = this.createNewTransaction();
newTrans.IsIncome = false;
$scope.Transactions.push(newTrans);
}
$scope.addNewIncome = function () {
var newTrans = this.createNewTransaction();
newTrans.IsIncome = true;
$scope.Transactions.push(newTrans);
}
$scope.transfer = function () {
var modalInstance = $modal.open({
templateUrl: 'views/proj/transfer.html',
controller: ProjectTransferMoneyCtrl,
resolve: {
ProjectId: function () {
return $scope.Project.Id;
}
}
});
modalInstance.result.then(function () {
//on ok button press
$scope.searchTransactions($scope.TransactionFilter);
}, function () {
//on cancel button press
});
}
$scope.removeCategory = function(trans)
{
trans.Category = null;
$scope.partialSave();
}
$scope.removeTransactionDate = function(trans)
{
trans.TransactionDate = null;
$scope.partialSave();
}
$scope.selectTransaction = function (TransDto) {
$scope.SelectedTransaction = TransDto;
$scope.getCurrentTransactionId();
}
$scope.saveTrans = function () {
$scope.loading = true;
$http.post(Constants.WebApi.Project.SaveTransactions, $scope.Transactions).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Transactions = response.data;
$scope.loading = false;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Load Recent Project Failed!",
type: "warning"
});
});
}
$scope.saveTransaction = function (transaction)
{
if (transaction != null) {
$http.post(Constants.WebApi.Project.SaveTransaction, transaction).then(function (response) {
// this callback will be called asynchronously
// when the response is available
transaction.Id = response.data.Id;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Save Failed!",
type: "warning"
});
});
}
}
$scope.partialSave = function ()
{
$scope.saveTransaction($scope.SelectedTransaction);
}
$scope.confirmDeleteTransaction = function (deletingTransaction) {
SweetAlert.swal({ title: "Delete this transaction?", text: "You will not be able to recover this!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: true },
function (isConfirm) {
if (isConfirm) {
$scope.deleteTransaction(deletingTransaction);
}
});
}
$scope.deleteTransaction = function (deletingTransaction)
{
$http.post(Constants.WebApi.Project.DeleteTransaction, deletingTransaction).then(function (response) {
var index = $scope.Transactions.indexOf(deletingTransaction);
$scope.Transactions.splice(index, 1);
$scope.SelectedTransaction = null;
}, function (response) {
SweetAlert.swal({
title: "Error!",
text: "Save Failed!",
type: "warning"
});
});
}
$scope.setRecurringTransaction = function(transaction, timeId)
{
if (transaction.RecurringTransaction == null) {
if ($scope.TimeFrequency.Never != timeId) {
// create new
transaction.RecurringTransaction = {
Id: transaction.RecurringTransactionId,
ProjectId: transaction.ProjectId,
TimeFrequencyId: timeId
}
$scope.saveRecurringTransaction(transaction, transaction.RecurringTransaction);
}
}
else {
if (transaction.RecurringTransaction.TimeFrequencyId != timeId) {
if ($scope.TimeFrequency.Never == timeId) {
$scope.removeRecurringTransaction(transaction, transaction.RecurringTransaction);
//transaction.RecurringTransaction = null;
}
else {
transaction.RecurringTransaction.TimeFrequencyId = timeId;
$scope.saveRecurringTransaction(transaction, transaction.RecurringTransaction);
}
}
}
}
$scope.saveRecurringTransaction = function (transaction, recurringTransaction)
{
recurringTransaction.TransactionDate = transaction.TransactionDate;
var recurringTransactionSubmitDto =
{
TransactionId: transaction.Id,
RecurringTransaction: recurringTransaction
};
$http.post(Constants.WebApi.Project.SaveRecurringTransaction, recurringTransactionSubmitDto).then(function (response) {
transaction.RecurringTransaction = response.data;
}, function (response) {
SweetAlert.swal({
title: "Error!",
text: "Save Recurring Transaction Failed!",
type: "warning"
});
});
}
$scope.removeRecurringTransaction = function (transaction, recurringTransaction) {
var recurringTransactionSubmitDto =
{
TransactionId: transaction.Id,
RecurringTransaction: recurringTransaction
};
$http.post(Constants.WebApi.Project.RemoveRecurringTransaction, recurringTransactionSubmitDto).then(function (response) {
transaction.RecurringTransaction = null;
transaction.RecurringTransactionId = null;
}, function (response) {
SweetAlert.swal({
title: "Error!",
text: "Save Recurring Transaction Failed!",
type: "warning"
});
});
}
$scope.getCurrentTransactionId = function()
{
var transactionId = null;
if (!(angular.isUndefined($scope.SelectedTransaction) || $scope.SelectedTransaction === null)) {
if (!(angular.isUndefined($scope.SelectedTransaction.Id) || $scope.SelectedTransaction.Id === null)) {
transactionId = $scope.SelectedTransaction.Id;
}
}
$localStorage.transactionId = transactionId;
$localStorage.selectedTransaction = $scope.SelectedTransaction;
return transactionId;
}
$scope.loadAuditLogs = function(transId)
{
if (!(angular.isUndefined(transId) || transId === null)) {
$http.get(Constants.WebApi.AuditLog.GetTransactionAuditLogs, { params: { TransactionId: transId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.AuditLogs = response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load project activity failed!",
type: "warning"
});
});
}
}
$scope.loadUserComments = function (transId) {
if (!(angular.isUndefined(transId) || transId === null)) {
$http.get(Constants.WebApi.UserComment.GetTransactionUserComments, { params: { TransactionId: transId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.UserComments = response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load Recent Project Failed!",
type: "warning"
});
});
}
}
$scope.addComment = function()
{
var transactionId = this.getCurrentTransactionId();
if(transactionId != null)
{
var comment = {
ObjectId: transactionId,
CommentText: $scope.CommentText
}
$http.post(Constants.WebApi.UserComment.CreateTransactionUserComment, comment).then(function (response) {
// this callback will be called asynchronously
// when the response is available
var savedComment = response.data;
savedComment.User = {
Id: savedComment.UserId,
Photo: null
};
$scope.UserComments.push(savedComment);
$scope.CommentText = '';
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Load Recent Project Failed!",
type: "warning"
});
});
}
}
$scope.changeAccount = function(account)
{
if ($scope.SelectedTransaction != null) {
$scope.SelectedTransaction.Account = account;
$scope.partialSave();
}
}
$scope.changeCategory = function (category) {
if ($scope.SelectedTransaction != null) {
$scope.SelectedTransaction.Category = category;
$scope.partialSave();
}
}
$scope.assignMember = function (member) {
if ($scope.SelectedTransaction != null) {
if (member != null) {
$scope.SelectedTransaction.Client = member.Client;
}
else {
$scope.SelectedTransaction.Client.User.Photo = null;
$scope.SelectedTransaction.Client = null;
}
$scope.partialSave();
}
}
$scope.setClear = function(transaction)
{
transaction.IsClear = !transaction.IsClear;
}
$scope.openProjectSetting = function (projId) {
var modalInstance = $modal.open({
templateUrl: 'views/modals/ProjectSetting.html',
controller: ProjectSettingCtrl,
resolve: {
ProjectId: function () {
return projId;
}
}
});
modalInstance.result.then(function () {
//on ok button press
$scope.loadProjectHeader();
$rootScope.$broadcast('projectListChanged', { ProjectId: $scope.Project.Id });
}, function () {
//on cancel button press
});
}
$scope.$watch('SelectedTransaction', function (newVal, oldVal) {
if (newVal != null && newVal.Id != null) {
var transId = newVal.Id;
$scope.loadAuditLogs(transId);
$scope.loadUserComments(transId);
var client = newVal.Client;
if (client == null || client.User == null || client.User.Photo == null) {
if (client == null || client.User == null)
{
newVal.Client = {
User: {
Id: null,
Photo: null
}
};
}
newVal.Client.User.Photo = '//:0';
}
console.debug('SelectedTransaction changed');
}
}, false);
$scope.$watch(function ($scope) {
return $scope.Transactions.
map(function (obj) {
return obj.Amount
});
}, function (newVal) {
$scope.totalAmount = $scope.calcTotalAmount();
console.debug('Changed amount: {0}', newVal);
}, true);
$scope.$watch('Members', function (newVal, oldVal) {
if (newVal != null) {
for (var i = 0; i < newVal.length; i++)
{
var client = newVal[i].Client;
if (client.User.Id != null && (client.User.Photo == null || client.User.Photo.length < 8)) {
var photoResult = userPhotoService.getUserPhoto(client.User);
photoResult.then(function (data) {
}, function (error) { });
}
}
}
}, true);
$scope.$watch('Transactions', function (newVal, oldVal) {
if (newVal != null) {
for (var i = 0; i < newVal.length; i++) {
var client = newVal[i].Client;
if (client != null && client.User != null && client.User.Id != null && (client.User.Photo == null || client.User.Photo.length < 8)) {
var photoResult = userPhotoService.getUserPhoto(client.User);
photoResult.then(function (data) {
}, function (error) { });
}
}
}
}, true);
$scope.$watch('UserComments', function (newVal, oldVal) {
if (newVal != null) {
for (var i = 0; i < newVal.length; i++) {
var user = newVal[i].User;
if (user != null && user.Id != null && (user.Photo == null || user.Photo.length < 8)) {
var photoResult = userPhotoService.getUserPhoto(user);
photoResult.then(function (data) {
}, function (error) { });
}
}
}
}, true);
$scope.getFilterType = function(FilterTypeId)
{
var filterType = $scope.TransactionFilters[0];
for (var i = 0; i < $scope.TransactionFilters.length; i++) {
var filter = $scope.TransactionFilters[i];
if (filter.FilterTypeId == FilterTypeId) {
filterType = filter;
break;
}
}
return filterType;
}
$scope.filter = function(filter)
{
//var filter = $scope.getFilterType(FilterTypeId);
$scope.TransactionFilter.FilterType = filter;
$scope.TransactionFilter.FilterTypeId = filter.FilterTypeId;
$scope.TransactionFilter.FromDate = filter.SelectedDate;
$scope.searchTransactions($scope.TransactionFilter);
$scope.updateFilterNextPrevious(filter.FilterTypeId, filter.SelectedDate);
}
$scope.filterUpcoming = function(isUpcoming)
{
$scope.TransactionFilter.IsUpcoming = isUpcoming;
}
$scope.filterAccount = function (account) {
$scope.TransactionFilter.Account = account;
$scope.searchTransactions($scope.TransactionFilter);
}
$scope.filterCategory = function (category) {
$scope.TransactionFilter.Category = category;
$scope.searchTransactions($scope.TransactionFilter);
}
$scope.updateFilterNextPrevious = function(filterType, date)
{
//console.debug('Filter:', filterType, ', date:', date);
switch (filterType) {
case 1: //Today
{
$scope.FilterPrevious.Text = 'Yesterday';
$scope.FilterPrevious.Title = 'Yesterday';
$scope.FilterPrevious.FilterTypeId = 5;
$scope.FilterPrevious.SelectedDate.setDate(date.getDate() - 1);
$scope.FilterNext.Text = 'Tomorrow';
$scope.FilterNext.Title = 'Tomorrow';
$scope.FilterNext.FilterTypeId = 5;
$scope.FilterNext.SelectedDate.setDate(date.getDate() + 1);
}
break;
case 2: //This Week
{
$scope.FilterPrevious.Text = 'Last Week';
$scope.FilterPrevious.Title = 'Last Week';
$scope.FilterPrevious.FilterTypeId = 6;
var lastMonday = Commons.GetPreviousMonday(date);
$scope.FilterPrevious.SelectedDate = lastMonday;
$scope.FilterNext.Text = 'Next Week';
$scope.FilterNext.Title = 'Next Week';
$scope.FilterNext.FilterTypeId = 6;
var nextMonday = Commons.GetNextMonday(date);
$scope.FilterNext.SelectedDate = nextMonday;
}
break;
case 3: //This Month
{
$scope.FilterPrevious.Text = 'Last Month';
$scope.FilterPrevious.Title = 'Last Month';
$scope.FilterPrevious.FilterTypeId = 7;
var preMonth = Commons.GetPreviousMonth(date);
$scope.FilterPrevious.SelectedDate = preMonth;
$scope.FilterNext.Text = 'Next Month';
$scope.FilterNext.Title = 'Next Month';
$scope.FilterNext.FilterTypeId = 7;
var nextMonth = Commons.GetNextMonth(date);
$scope.FilterNext.SelectedDate = nextMonth;
}
break;
case 4: //This Year
{
$scope.FilterPrevious.Text = 'Last Year';
$scope.FilterPrevious.Title = 'Last Year';
$scope.FilterPrevious.FilterTypeId = 8;
var preYear = Commons.GetPreviousYear(date);
$scope.FilterPrevious.SelectedDate = preYear;
$scope.FilterNext.Text = 'Next Year';
$scope.FilterNext.Title = 'Next Year';
$scope.FilterNext.FilterTypeId = 8;
var nextYear = Commons.GetNextYear(date);
$scope.FilterNext.SelectedDate = nextYear;
}
break;
case 5: //Date
{
$scope.FilterPrevious.Title = $scope.FilterPrevious.Text;
$scope.FilterPrevious.SelectedDate.setDate(date.getDate() - 1);
$scope.FilterPrevious.Text = Commons.DateToString($scope.FilterPrevious.SelectedDate);
$scope.FilterNext.Title = $scope.FilterNext.Text;
$scope.FilterNext.SelectedDate.setDate(date.getDate() + 1);
$scope.FilterNext.Text = Commons.DateToString($scope.FilterNext.SelectedDate);
}
break;
case 6: //Week
{
$scope.FilterPrevious.Title = $scope.FilterPrevious.Text;
var lastMonday = Commons.GetPreviousMonday(date);
$scope.FilterPrevious.SelectedDate = lastMonday;
$scope.FilterPrevious.Text = 'Week from ' + Commons.DateToString($scope.FilterPrevious.SelectedDate);
$scope.FilterNext.Title = $scope.FilterNext.Text;
var nextMonday = Commons.GetNextMonday(date);
$scope.FilterNext.SelectedDate = nextMonday;
$scope.FilterNext.Text = 'Week from ' + Commons.DateToString($scope.FilterNext.SelectedDate);
}
break;
case 7: //Month
{
$scope.FilterPrevious.Title = $scope.FilterPrevious.Text;
var preMonth = Commons.GetPreviousMonth(date);
$scope.FilterPrevious.SelectedDate = preMonth;
$scope.FilterPrevious.Text = Commons.DateToMonthString($scope.FilterPrevious.SelectedDate);
$scope.FilterNext.Title = $scope.FilterNext.Text;
var nextMonth = Commons.GetNextMonth(date);
$scope.FilterNext.SelectedDate = nextMonth;
$scope.FilterNext.Text = Commons.DateToMonthString($scope.FilterNext.SelectedDate);
}
break;
case 8: //Year
{
$scope.FilterPrevious.Title = $scope.FilterPrevious.Text;
var preYear = Commons.GetPreviousYear(date);
$scope.FilterPrevious.SelectedDate = preYear;
$scope.FilterPrevious.Text = Commons.DateToYearString($scope.FilterPrevious.SelectedDate);
$scope.FilterNext.Title = $scope.FilterNext.Text;
var nextYear = Commons.GetNextYear(date);
$scope.FilterNext.SelectedDate = nextYear;
$scope.FilterNext.Text = Commons.DateToYearString($scope.FilterNext.SelectedDate);
}
break;
};
}
}; |
import React from 'react';
import web3 from '../utils/web3';
import Container from './Container';
const Header = ({ host, bankroll, fomoBalance }) => {
const renderBankrollText = () => {
if (bankroll === '0') {
return (
<p>No bankroll is available at the moment. Please wait until host deposit some bankroll to start the game.</p>
);
}
if (fomoBalance === '0') {
return <p>The current available bankroll for players to win is {web3.utils.fromWei(bankroll, 'gwei')} Gwei!</p>;
} else {
const actualAvailableBankroll = +bankroll - +fomoBalance;
return (
<p>
Given Fomo pool balance of {web3.utils.fromWei(String(fomoBalance), 'gwei')} Gwei, The current available
bankroll for players to win is {web3.utils.fromWei(String(actualAvailableBankroll), 'gwei')} Gwei
</p>
);
}
};
return (
<Container>
<h2>Rock Paper Scissors Game</h2>
<p>This contract is hosted by {host}.</p>
{renderBankrollText()}
</Container>
);
};
export default Header;
|
class Game {
scale = data.game.scale;
cuePower = 0.04;
numBalls = data.ball.objectBallsInitialPos.length;
numSolidBalls = data.ball.numSolidBalls;
numStripedBalls = data.ball.numStripedBalls;
eightBallIndex = data.ball.eightBallindex;
table;
cueBall;
objectBalls;
constructor() {
this.table = new Table();
this.cueBall = new CueBall(data.cueBall.initialPos[0], data.cueBall.initialPos[1]);
this.objectBalls = this.createObjectBalls();
this.startEventHandlers();
}
get balls() {
return [this.cueBall].concat(this.objectBalls);
}
createObjectBalls() {
let ballTypeChoices = [];
for (let i = 0; i < this.numSolidBalls; i++) {
ballTypeChoices.push("SOLID");
}
for (let i = 0; i < this.numStripedBalls; i++) {
ballTypeChoices.push("STRIPED");
}
let balls = [];
data.ball.objectBallsInitialPos.forEach((pos, i) => {
let ball;
if (i === data.ball.eightBallIndex) {
ball = new EightBall(pos[0], pos[1]);
} else {
let randIndex = Math.floor(Math.random() * ballTypeChoices.length);
let ballType = ballTypeChoices.splice(randIndex, 1)[0];
if (ballType === "SOLID") ball = new SolidBall(pos[0], pos[1]);
if (ballType === "STRIPED") ball = new StripedBall(pos[0], pos[1]);
}
balls.push(ball);
});
return balls;
}
areBallsStationary() {
return this.balls.filter(ball => ball.velocity.magnitude > 0) === 0;
}
update() {
this.balls.forEach(ball =>
ball.update(this.table.walls, this.balls, this.table.holes));
this.balls.forEach(ball => ball.move());
this.objectBalls = this.objectBalls.filter(ball => !ball.potted);
if (this.cueBall.potted) {
this.cueBall.reset();
}
}
draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.table.draw(this.scale);
this.balls.forEach(ball => ball.draw(this.scale));
}
startEventHandlers() {
canvas.addEventListener("click", (e) => {
let cursorPos = new Vector(e.offsetX/this.scale, e.offsetY/this.scale);
this.cueBall.shoot(
Vector.scale(
Vector.subtract(cursorPos, this.cueBall.pos),
this.cuePower
)
);
});
}
}
|
/*
Al presionar el botón pedir números hasta que el USUARIO QUIERA
e informar la suma acumulada y el promedio.
*/
function mostrar()
{
let vNum = 0;
let vSuma = 0;
let vCont = 0;
let vProm;
do {
vSuma = vNum + vSuma;
vCont++;
vNum = parseInt(prompt("Ingresar Numero"));
}
while (!(isNaN(vNum))) ;
document.getElementById("txtIdSuma").value = vSuma ;
vProm= vSuma/(vCont-1);
document.getElementById ("txtIdPromedio").value = vProm;
}//FIN DE LA FUNCIÓN |
// ------------------------------------------------------------------------------------------------------------------
// Class: Blueprint
//
// ------------------------------------------------------------------------------------------------------------------
var _ = require('underscore'),
Blueprint,
dottie = require('dottie');
Blueprint = function Blueprint (elementTree, templateGear, loggerGear) {
this.elements = elementTree;
this.templateComponent = templateGear;
this._logger = loggerGear;
};
// -------------------------------------------------------------------
// Method: findGearByPath
// Purpose: Find an element from a '.' delimited path of element ids.
// Args:
// path: A '.' delimited path of element ids.
// -------------------------------------------------------------------
Blueprint.prototype.findGearByPath = function findGearByPath (path) {
return dottie.get(this.elements, path);
};
// ---------------------------------------------------------------------------------------------
// Method: findAllGears
// Purpose: Return all elements (in order specified by _seq) as per the supplied config.
// Args:
// config:
// rootPath Find all elements from here (defaults to the blueprint-root)
// gear Restrict elements to a single gear (string) or a set (array of strings)
// Defaults to no restriction
//
// ---------------------------------------------------------------------------------------------
Blueprint.prototype.findAllGears = function findAllGears (config) {
var root,
gearRestriction,
idx,
element,
elements = [];
if (config) {
// Derive or default root
// ----------------------
if (_.has(config, 'root')) {
root = dottie.get(this.elements, config.root);
}
else {
root = this.elements;
}
// Derive or default gear restriction
// -----------------------------------
if (_.has(config, 'gearName')) {
if (_.isString(config.gearName)) {
gearRestriction = [config.gearName];
}
else {
gearRestriction = config.gearName;
}
}
else {
gearRestriction = [];
}
}
else {
root = this.elements;
gearRestriction = [];
}
// Go add elements
// ---------------
if (root) {
for (var key in root._index) {
if (root._index.hasOwnProperty(key)) {
idx = root._index[key];
element = root[idx.id];
if (gearRestriction.length === 0) {
// No restriction, so OK to add element
elements.push(element);
}
else {
// Restricted in some way - add element if in restriction list
if (gearRestriction.indexOf(element._gearName) != -1) {
elements.push(element);
}
}
}
}
}
return elements;
};
// -----------------------------------------------------------------
// Method: renderTemplate
// Purpose: Renders a template defined for this blueprint.
// -----------------------------------------------------------------
// templateName, context, options, callback
Blueprint.prototype.renderTemplate = function renderBlueprintTemplate (templateName, context, options, callback) {
this.templateComponent.render(templateName, context, options, callback);
};
// -----------------------------------------------------------------------------------------
// Method: _debug
// Purpose: To output blueprint-debug content.
// -----------------------------------------------------------------------------------------
Blueprint.prototype._debug = function _debug() {
var _this = this,
element;
function debug(text) {
_this._logger.debug(text);
}
function debugElements(elements, depth) {
var atLeastOne = false;
for (var key in elements) {
if (elements.hasOwnProperty(key)) {
element = elements[key];
if (_.has(element, '_id') && key[0]!='_' && key[0]!='@' && _.isObject(element) && !_.isArray(element) && _.isFunction(element.debug)) {
element.debug(depth);
atLeastOne = true;
debugElements(element, depth+1);
}
}
}
if (atLeastOne || depth ===0) {
debug('');
}
}
debug('');
debug(' BLUEPRINT DEBUG');
debug(' ---------------');
debugElements(this.elements, 0);
debug('');
};
module.exports = Blueprint; |
import jwt from "jsonwebtoken";
import nodemailer from 'nodemailer';
const generateAccessToken = async (data) => {
return jwt.sign(data, process.env.TOKEN_SECRET, { expiresIn: "1800s" });
};
const sendEmail = async ({otp, email}) => {
const smtpSetting = {
host: process.env.smtp_host,
port: process.env.smtp_port,
secure: false, // true for 465, false for other ports
auth: {
user: process.env.smtp_user, // generated ethereal user
pass: process.env.smtp_pass, // generated ethereal password
},
}
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport(smtpSetting);
const mailOptions = {
from: 'romesh.30@gmail.com', //from,
to: email, // to
subject: "test aws ses", // subject,
html: `hello world ${otp}`,//html,
headers: {
priority: 'hight'
}
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log("Email not sent :: ", error);
// res.send('failed');
} else {
console.log('Email sent: ', info.response);
// res.send('success');
}
});
};
export { generateAccessToken, sendEmail };
|
var def_txt = "What's on your mind?";
jQuery(document).ready(function(){
set_def_text();
jQuery('.expand_comment').click(function() {
event.preventDefault();
jQuery('#id_'+this.id).toggle();
});
jQuery('#link_tab').click(function() {
jQuery('#main_comment_share').hide();
jQuery('#main_link_share').show();
});
jQuery('#main_comment_tab').click(function() {
jQuery('#main_comment_share').show();
jQuery('#main_link_share').hide();
});
jQuery('#main_share_btn').click(function() {
comment = jQuery('#main_comment').val();
if(comment != def_txt) {
jQuery('#main_box_loader').show();
jQuery.ajax({
data: 'comment='+comment+'&form=main_comment_req',
url: "/stream/new_share",
type: "POST",
success: function(results) { jQuery('#comment_history').prepend(results); set_def_text('a');},
complete: function(results) { jQuery('#main_box_loader').hide(); }
});
}
});
jQuery('.comment_reply_button').click(function() {
comment = jQuery('#input_'+this.id).val();
wrapper = '#wrapper_id_'+this.id;
boxLoader = '#box_loader_'+this.id;
if(comment != def_txt) {
jQuery(boxLoader).show();
jQuery.ajax({
data: { reply_comment: comment, form: "reply_comment_req", stream_id: this.id},
url: "/stream/reply_share",
type: "POST",
success: function(results) { jQuery(wrapper).prepend(results); set_def_text('a');},
complete: function(results) { jQuery(boxLoader).hide(); }
});
}
});
jQuery('#main_comment').focus(function() {set_def_text('r');});
jQuery('#main_comment').blur(function() {set_def_text();});
/*
jQuery('#link_share_btn').click(function() {
comment = jQuery('#main_link').val();
if(comment != def_txt) {
jQuery('#main_box_loader').show();
jQuery.ajax({
data: 'url='+comment+'&form=main_comment_req',
url: "/stream/get_link",
type: "POST",
success: function(results) { jQuery('#comment_history').prepend(results); set_def_text('a');},
complete: function(results) { jQuery('#main_box_loader').hide(); }
});
}
});
*/
// delete event
jQuery('#link_share_btn').livequery("click", function(){
if(!isValidURL(jQuery('#main_link').val()))
{
alert('Please enter a valid url.');
return false;
}
else
{
jQuery('#link_box_loader').show();
comment = jQuery('#main_link').val();
jQuery.ajax({
data: 'url='+comment+'&form=main_comment_req',
url: "/stream/get_link",
type: "POST",
success: function(results) {
if(results.match(/^--VID--/)) {
res = results.replace(/^--VID--/,'');
jQuery('#comment_history').prepend(res);
}
else {
if(results != '') {
jQuery('#hold_post').html('');
jQuery('#hold_post').prepend(results);
jQuery('#hold_post').show();
jQuery('.images img').hide();
jQuery('#load').hide();
jQuery('img#1').fadeIn();
jQuery('#cur_image').val(1);
}
}
},
complete: function(results) { jQuery('#link_box_loader').hide(); }
});
}
});
// next image
jQuery('#next_prev_img').livequery("click", function(){
var firstimage = jQuery('#cur_image').val();
jQuery('#cur_image').val(1);
jQuery('img#'+firstimage).hide();
if(firstimage <= jQuery('#total_images').val())
{
firstimage = parseInt(firstimage)+parseInt(1);
jQuery('#cur_image').val(firstimage);
jQuery('img#'+firstimage).show();
}
});
// prev image
jQuery('#prev_prev_img').livequery("click", function(){
var firstimage = jQuery('#cur_image').val();
jQuery('img#'+firstimage).hide();
if(firstimage>0)
{
firstimage = parseInt(firstimage)-parseInt(1);
jQuery('#cur_image').val(firstimage);
jQuery('img#'+firstimage).show();
}
});
// watermark input fields
jQuery(function(jQuery){
jQuery("#main_link").Watermark("http://");
});
jQuery(function(jQuery){
jQuery("#main_link").Watermark("watermark","#369");
});
function UseData() {
jQuery.Watermark.HideAll();
jQuery.Watermark.ShowAll();
}
});
function set_def_text(flag) {
if(flag && flag == 'r')
jQuery('#main_comment').val('');
else if(flag && flag == 'a')
jQuery('#main_comment').val(def_txt);
else if(jQuery('#main_comment').val() == '')
jQuery('#main_comment').val(def_txt);
}
function isValidURL(url){
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
} |
import object3D from './object3D';
class points extends object3D {
getIntro() {
return 'Creates a [THREE.Points](http://threejs.org/docs/#Reference/Objects/Points)';
}
getDescription() {
return 'This object can contain [[Materials]] and [[Geometries]].';
}
}
module.exports = points;
|
import React from "react";
import { navigateTo } from "gatsby-link";
function encode(data) {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}
export default class Contact extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
const form = e.target;
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": form.getAttribute("name"),
...this.state
})
})
.then(() => navigateTo(form.getAttribute("action")))
.catch(error => alert(error));
};
render() {
return (
<div className="box">
<form
name="ccu-contact"
method="post"
action="/thanks/"
data-netlify="true"
data-netlify-honeypot="bot-field"
onSubmit={this.handleSubmit}
>
{/* The `form-name` hidden field is required to support form submissions without JavaScript */}
<input type="hidden" name="form-name" value="contact" />
<p hidden>
<label>
Don’t fill this out:{" "}
<input name="bot-field" onChange={this.handleChange} />
</label>
</p>
<div className="field">
<div className="control">
<label>
Your full name<br />
<input className="input is-large" type="text" name="name" onChange={this.handleChange} />
</label>
</div>
</div>
<div className="field">
<div className="control">
<label>
Your email<br />
<input className="input is-large" type="email" name="email" onChange={this.handleChange} />
</label>
</div>
</div>
<div className="field">
<div className="control">
<label>
Your phone<br />
<input className="input is-large" type="tel" name="phone" onChange={this.handleChange} />
</label>
</div>
</div>
<div className="field">
<div className="control">
<label>
What kind of services are you seeking?<br />
<textarea className="textarea is-large" name="message" onChange={this.handleChange} />
</label>
</div>
</div>
<div className="field">
<div className="control">
<button className="button is-primary is-medium" type="submit">Request more information</button>
</div>
</div>
</form>
</div>
);
}
}
|
import React from 'react';
import {connect} from 'react-redux';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import NavigationBar from './nav';
import Footer from './footer';
import SearchPage from './searchPage';
import GameView from './gameView';
import Dashboard from './dashboard';
import LoginPage from './loginPage';
import SignUpPage from './signUpPage';
import {refreshAuthToken} from '../actions/auth';
import './styles/app.css';
import './styles/response-grid.css';
export class App extends React.Component{
componentWillReceiveProps(nextProps) {
if (nextProps.loggedIn && !this.props.loggedIn) {
// refreshes the auth token periodically
this.startPeriodicRefresh();
} else if (!nextProps.loggedIn && this.props.loggedIn) {
// stop refreshing on log out
this.stopPeriodicRefresh();
}
}
componentWillUnmount() {
this.stopPeriodicRefresh();
}
startPeriodicRefresh() {
this.refreshInterval = setInterval(
() => this.props.dispatch(refreshAuthToken()),
60 * 60 * 1000 // One hour
);
}
stopPeriodicRefresh() {
if (!this.refreshInterval) {
return;
}
clearInterval(this.refreshInterval);
}
render() {
return (
<Router>
<div className="app">
<NavigationBar />
<Route exact path="/" component={SearchPage} />
<Route exact path="/gameview/:id" component={GameView} />
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/signup" component={SignUpPage} />
<Footer />
</div>
</Router>
);
}
}
const mapStateToProps = state => ({
hasAuthToken: state.auth.authToken !== null,
loggedIn: state.auth.currentUser !== null
});
export default connect(mapStateToProps)(App); |
import React from 'react';
import { Button, Form, Grid, Header, Message, Segment, Loader } from 'semantic-ui-react'
const LoginForm = (props) =>{
const {onSubmit, status, errorMessage} = props;
return(
<Grid textAlign='center' style={{ height: '100vh' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 450 }}>
<Header as='h2' color='teal' textAlign='center'>
Log-in to your account
</Header>
{
status==='error' &&
<Message error>
{errorMessage}
</Message>
}
<Form size='large' onSubmit={onSubmit}>
<Segment stacked>
<Form.Input
id={'login__login'}
fluid
icon='user'
autoComplete='username email'
iconPosition='left'
placeholder='E-mail address or username' />
<Form.Input
id={'login__password'}
fluid
autoComplete='current-password'
icon='lock'
iconPosition='left'
placeholder='Password'
type='password'
/>
<Button type='submit' color='teal' size='large'>
Login
{
status==='loading' &&
<Loader as='i' active inline size='tiny'/>
}
</Button>
</Segment>
</Form>
<Message>
New to us? <a href='/register'>Sign Up</a>
</Message>
</Grid.Column>
</Grid>
)
}
export default LoginForm; |
var G_SCROLL_EVENT_DATA = {};
function eventInit(obj, eventDatas) {
var event, id;
id = obj.attr('id');
$.each(eventDatas, function (eidx, eventData) {
obj.data('eventCnt-' + eventData.eventId, 0);
switch (eventData.type) {
case 'click':
event = 'click';
break;
case 'custom':
event = eventData.customevent;
break;
case 'scroll':
if (!G_SCROLL_EVENT_DATA[id]) G_SCROLL_EVENT_DATA[id] = [];
G_SCROLL_EVENT_DATA[id].push(eventData);
return;
default:
return;
}
eventData.sourceObject = id;
switch (eventData.actiontype) {
case 'style':
$(obj).on(event, null, eventData, eventStyleHandler);
break;
case 'scroll':
$(obj).on(event, null, eventData, eventScrollToHandler);
break;
case 'link':
$(obj).on(event, null, eventData, eventLinkHandler);
break;
case 'play':
$(obj).on(event, null, eventData, eventPlayHandler);
break;
case 'fireevent':
$(obj).on(event, null, eventData, eventFireEventHandler);
break;
case 'script':
$(obj).on(event, null, eventData, eventScriptHandler);
break;
default:
return;
}
});
$.each(G_SCROLL_EVENT_DATA, function (id, data) {
var selector = '#'+id;
if ($(selector).prop("tagName").toLowerCase() == 'body') selector = window;
$(selector).on('scroll', null, [id, data], function (e) {
var beforeScrollPos = parseInt($(this).data('BEFORE_SCROLL_POS'));
var nowScrollPos;
var objid = e.data[0];
var obj = $('#'+objid);
if (isNaN(beforeScrollPos)) beforeScrollPos = 0;
if (G_CONF.orientation == 'landscape') {
nowScrollPos = $(this).scrollLeft();
} else {
nowScrollPos = $(this).scrollTop();
}
$(this).data('BEFORE_SCROLL_POS', nowScrollPos);
$.each(e.data[1], function (idx, eventData) {
if (beforeScrollPos < eventData.eventpos_real && nowScrollPos > eventData.eventpos_real) {
eventData.sourceObject = objid;
switch (eventData.actiontype) {
case 'style': eventStyleHandler({ data: eventData }); break;
case 'scroll': eventScrollToHandler({ data: eventData }); break;
case 'link': eventLinkHandler({ data: eventData }); break;
case 'play': eventPlayHandler({ data: eventData }); break;
case 'fireevent': eventFireEventHandler({ data: eventData }); break;
case 'script': eventScriptHandler({ data: eventData }); break;
default: return;
}
}
});
});
});
eventComputeScrollPos();
}
function eventComputeScrollPos() {
var refSize;
if (G_CONF.orientation == 'landscape') {
refSize = $('body').prop("scrollWidth");
} else {
refSize = $('body').prop("scrollHeight");
}
$.each(G_SCROLL_EVENT_DATA, function (id, data) {
$.each(data, function (idx, eventData) {
if (!eventData.eventpos) eventData.eventpos_real = refSize;
if (eventData.eventpos[1] == '%') {
eventData.eventpos_real = Math.round(refSize * (parseFloat(eventData.eventpos[0]) / 100));
} else {
eventData.eventpos_real = eventData.eventpos[0];
}
});
});
}
function eventStyleHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var tarObjTrans = $(tarObj).data('transition');
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
//return;
} else {
var defaultStyle = $(tarObj).data('default-style');
var nowStyle = $(tarObj).data('style');
var newStyle = {};
var toggle = false;
var defAnimCnt = 0;
var newAnimCnt = 0;
var animCnt = 0;
$.each(eventData.datas, function (idx, css) {
var value;
if (css.value.length > 1) {
if (css.value[0] == 'auto' ||
css.value[0] == 'transparent' ||
css.value[0] == 'initial' ||
css.value[0] == 'inherit'
) {
value = css.value[0];
} else {
value = css.value[0] + css.value[1];
}
} else {
value = css.value[0];
}
newStyle[css.css] = value;
});
if (typeof tarObjTrans == 'object') {
$.each(newStyle, function (key, value) {
for (var j = 0; j < tarObjTrans.length; j++) {
if ((tarObjTrans[j].property == key) || (tarObjTrans[j].property == 'all')) {
if (value != defaultStyle[key]) defAnimCnt++;
if (value != nowStyle[key]) newAnimCnt++;
}
}
});
}
if (eventData.eventRepeat == 'toggle' && (eventCnt % 2) == 1) {
toggle = true;
animCnt = defAnimCnt;
} else {
animCnt = newAnimCnt;
}
if (animCnt > 0 && eventData.endEvent) {
$(tarObj).on(EVT_TRANSITIONEND, null,
{
sourceObject: $(srcObj).attr('id'),
endEvent: eventData.endEvent,
animCnt: animCnt,
animEnd: 0
}, function (e) {
e.data.animEnd++;
if (e.data.animEnd == e.data.animCnt) {
$(tarObj).off(EVT_TRANSITIONEND);
$('#'+e.data.sourceObject).trigger(e.data.endEvent);
}
e.preventDefault();
e.stopPropagation();
});
}
if (toggle) {
$.each(newStyle, function (key, value) {
objectSetStyle(tarObj, key, defaultStyle[key]);
});
} else {
$.each(newStyle, function (key, value) {
objectSetStyle(tarObj, key, value);
});
}
if (animCnt == 0) $(srcObj).trigger(eventData.endEvent);
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
}
e.preventDefault();
e.stopPropagation();
}
function eventScrollToHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
} else {
var scrollPos;
if (eventData.eventRepeat == 'toggle' && (eventCnt % 2) == 1) {
scrollPos = $(srcObj).data('oldScrollPos');
} else {
if (G_CONF.orientation == 'landscape') {
$(srcObj).data('oldScrollPos', $(window).scrollLeft());
} else {
$(srcObj).data('oldScrollPos', $(window).scrollTop());
}
if (eventData.position[1] == '%') {
var refSize, fV;
if (G_CONF.orientation == 'landscape') {
refSize = $(window).height();
} else {
refSize = $(window).width();
}
fV = parseFloat(eventData.position[0]);
scrollPos = Math.round(refSize * (fV / 100));
} else {
scrollPos = eventData.position[0];
}
}
if (scrollPos != $(srcObj).data('oldScrollPos')) {
var _fireNextEvent;
if (eventData.endEvent) {
_fireNextEvent = function (e) {
$(srcObj).trigger(eventData.endEvent);
if (e) {
e.preventDefault();
e.stopPropagation();
}
};
} else {
_fireNextEvent = function (e) {
if (e) {
e.preventDefault();
e.stopPropagation();
}
};
}
if (G_CONF.orientation == 'landscape') {
$('html, body').animate({ scrollLeft: scrollPos }, 500, 'swing', _fireNextEvent);
} else {
$('html, body').animate({ scrollTop: scrollPos }, 500, 'swing', _fireNextEvent);
}
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
} else {
_fireNextEvent();
}
}
e.preventDefault();
e.stopPropagation();
}
function eventLinkHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
} else {
window.open(eventData.url);
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
}
e.preventDefault();
e.stopPropagation();
}
function eventPlayHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
} else {
tarObj.trigger(eventData.action+'media');
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
}
e.preventDefault();
e.stopPropagation();
}
function eventFireEventHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
} else {
tarObj.trigger(eventData.event);
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
}
e.preventDefault();
e.stopPropagation();
}
function eventScriptHandler(e) {
var eventData = e.data;
var eventId = eventData.eventId;
var srcObj = $(e.target);
var tarObj = $('#'+eventData.targetObject);
var eventCnt = parseInt($(srcObj).data('eventCnt-'+eventId));
if (eventData.eventRepeat == 'no-repeat' && eventCnt > 0) {
} else {
var func = window['userfunc_'+eventData.script];
if (func) func(srcObj);
$(srcObj).data('eventCnt-' + eventId, ++eventCnt);
}
e.preventDefault();
e.stopPropagation();
}
|
let info ={
personagem:"Margarida",
origem: "Pato Donald",
nota:"Namorada do personagem principal nos quadrinhos do Pato Donald",
recorrente:"Sim"
};
console.log(info)
|
import Configs from '../configs';
const PATH_TG_TONDEV = 'https://t.me/TON_DEV';
const PATH_TG_TONLABS = 'https://t.me/tonlabs';
const PATH_TONDEV = 'https://ton.dev';
const PATH_TONSPACE = 'https://ton.space';
const PATH_TONSURF = 'https://ton.surf';
const PATH_GRAMSCAN = 'https://gramscan.io';
const PATH_TWITTER_TONLABS = 'https://twitter.com/tonlabs';
const PATH_GITHAB_TONLABS = 'https://github.com/tonlabs/';
const PATH_YOUTUBE = 'https://www.youtube.com/watch?v=NrbvU5j-9Yw';
const FREETON_JURY_ADDRESS = Configs.isContestsTest() ? '0:5fcc2bedb0854de24af59069c2b19f94c1f401fb861838f8be8f0aafc039a343' : '0:582b1d3427aa9ace29eb2748ccedf7ae291852d5458dc7931da000af18996ac5';// '0:46402089c4c830633fa87a814786b047b7b69244d1aff7c9b02c1d1e5005312e';
const WIKI_JURY_ADDRESS = '0:3c2795cedbc89270f46653812cf02d0ce52068fd498ca450d49cd8b1ddc7f6ac';
const KOREA_JURY_ADDRESS = '0:923054b68abfd02396697318d5a5b871b092199aff4c845b0457924c26caa737';
const DEFI_JURY_ADDRESS = '0:595c8aa8919687951ecc5f783d87a22ae4e78df744c3c9ccea8f3f54d5b30e51';
const AMBASSADOR_JURY_ADDRESS = '0:e50db524fc6f095d76cfd252ea2e831e7a14e9e518848103ff5d11f89078d923';
const SMM_JURY_ADDRESS = '0:aaaaec8853e687857898a94728a44293c59f02ae3afe95ad117f95de932dd1dc';
const DGO_JURY_ADDRESS = '0:159142dd37c0e6b6c5a243c7cdd7a9675e9ddebb0153e7469b9c300a577adcd3';
const ESPORTS_JURY_ADDRESS = '0:7e1cd60316d9578b3567d75f39d0efc6b0c533a829f22853b4ea27c0e1dd17a8';
const DEVEX_JURY_ADDRESS = '0:5ac0c98e728dd15ab54dda84f48b90ed1d205a3e6317aaf407eccf4fc46cfef2';
const SUPPORT_JURY_ADDRESS = '0:6634c7290e059649a5c539123ef1a1da3ab5d59a3d0b9b5e1bb3cab2a7575f4e';
const WD_JURY_ADDRESS = '0:ac83ade89453722bc0df26fa816ac2639310a9b8563b3011a3e24e2fa9978e27';
const GOV_FREETON = 'freeton';
const GOV_WIKI = 'wiki';
const GOV_KOREA = 'korea';
const GOV_DEFI = 'defi';
const GOV_AMBASSADOR = 'ambassador';
const GOV_SMM = 'smm';
const GOV_DGO = 'dgo';
const GOV_ESPORTS = 'esports';
const GOV_DEVEX = 'devex';
const GOV_SUPPORT = 'support';
const GOV_WD = 'wd';
const JURY_ADDRESS = {
[GOV_FREETON]: FREETON_JURY_ADDRESS,
[GOV_WIKI]: WIKI_JURY_ADDRESS,
[GOV_KOREA]: KOREA_JURY_ADDRESS,
[GOV_DEFI]: DEFI_JURY_ADDRESS,
[GOV_AMBASSADOR]: AMBASSADOR_JURY_ADDRESS,
[GOV_SMM]: SMM_JURY_ADDRESS,
[GOV_DGO]: DGO_JURY_ADDRESS,
[GOV_ESPORTS]: ESPORTS_JURY_ADDRESS,
[GOV_DEVEX]: DEVEX_JURY_ADDRESS,
[GOV_SUPPORT]: SUPPORT_JURY_ADDRESS,
[GOV_WD]: WD_JURY_ADDRESS,
};
export default class Constant {
static governanceFreeton() {
return GOV_FREETON;
}
static governanceWiki() {
return GOV_WIKI;
}
static governanceKorea() {
return GOV_KOREA;
}
static governanceDefi() {
return GOV_DEFI;
}
static governanceAmbassador() {
return GOV_AMBASSADOR;
}
static governanceSmm() {
return GOV_SMM;
}
static governanceDgo() {
return GOV_DGO;
}
static governanceEsports() {
return GOV_ESPORTS;
}
static governanceDevex() {
return GOV_DEVEX;
}
static governanceSupport() {
return GOV_SUPPORT;
}
static governanceWd() {
return GOV_WD;
}
static submissionsVotingDuration() {
const days = 14;
return days * 24 * 60 * 60 * 1000;
}
static juryWalletAddress(governance) {
return JURY_ADDRESS[governance];
}
static pathYoutubeTranslation() {
return PATH_YOUTUBE;
}
static pathTonDev() {
return PATH_TONDEV;
}
static pathTonSpace() {
return PATH_TONSPACE;
}
static pathTonSurf() {
return PATH_TONSURF;
}
static pathGramScan() {
return PATH_GRAMSCAN;
}
static pathTgTonDev() {
return PATH_TG_TONDEV;
}
static pathTgTonLabs() {
return PATH_TG_TONLABS;
}
static pathTwiterTonLabs() {
return PATH_TWITTER_TONLABS;
}
static pathGithubTonLabs() {
return PATH_GITHAB_TONLABS;
}
}
|
import request from 'superagent'
export const getTracks = (query, callback) => {
request
.get("http://api.soundcloud.com/tracks")
.query({
q: query || 'bad blood',
client_id: "MHsPaGAB9flti3yZ6a7bMdgq1GM9n7EL"
})
.end((err, res) => {
callback(err, res.body)
})
}
|
import React from 'react'
export default function Mainsection() {
return (
<div>
<section className="special-area bg-white section_padding_100" id="about">
<div className="container">
<div className="row">
<div className="col-12">
{/* Section Heading Area */}
<div className="section-heading text-center">
<h2>Why PayNow</h2>
<div className="line-shape" />
</div>
</div>
</div>
<div className="row">
{/* Single Special Area */}
<div className="col-12 col-md-4">
<div className="single-special text-center wow fadeInUp" data-wow-delay="0.2s">
<div className="single-icon">
<i className="ti-mobile" aria-hidden="true" />
</div>
<h4>Easy to use</h4>
<p>We have a user-friendly payment and integration method which is easy to use</p>
</div>
</div>
{/* Single Special Area */}
<div className="col-12 col-md-4">
<div className="single-special text-center wow fadeInUp" data-wow-delay="0.4s">
<div className="single-icon">
<i className="ti-ruler-pencil" aria-hidden="true" />
</div>
<h4>Powerful Design</h4>
<p>Our design was engineered with users in mind.</p>
</div>
</div>
{/* Single Special Area */}
<div className="col-12 col-md-4">
<div className="single-special text-center wow fadeInUp" data-wow-delay="0.6s">
<div className="single-icon">
<i className="ti-settings" aria-hidden="true" />
</div>
<h4>Customizability</h4>
<p>Highly customizable interface to suit any user need be it enterprise or normal user. </p>
</div>
</div>
</div>
</div>
{/* Special Description Area */}
<div className="special_description_area mt-150">
<div className="container">
<div className="row">
<div className="col-lg-6">
<div className="special_description_img">
<img src="img/bg-img/special.png" alt />
</div>
</div>
<div className="col-lg-6 col-xl-5 ml-xl-auto">
<div className="special_description_content">
<h2>Get App</h2>
<p>You can get our app on the following platform.</p>
<div className="app-download-area">
<div className="app-download-btn wow fadeInUp" data-wow-delay="0.2s">
{/* Google Store Btn */}
<a href="#">
<i className="fa fa-android" />
<p className="mb-0"><span>available on</span> Google Store</p>
</a>
</div>
<div className="app-download-btn wow fadeInDown" data-wow-delay="0.4s">
{/* Apple Store Btn */}
<a href="#">
<i className="fa fa-apple" />
<p className="mb-0"><span>available on</span> Apple Store</p>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
|
const sh = require("./shifts");
console.log("START");
const getDayValue = (shiftName) => {
switch (shiftName) {
case sh.DAY_SHIFT:
return 1;
case sh.NIGHT_SHIFT:
return 1;
case sh.START_NIGHT_SHIFT:
return 0.5;
case sh.END_NIGHT_SHIFT:
return 0.5;
case sh.DAY_OFF:
return 0;
}
console.error("unknown day:", shiftName);
};
sh.shift.A.forEach((day, index) => {
let sum = (getDayValue(sh.shift.A[index])
+ getDayValue(sh.shift.B[index])
+ getDayValue(sh.shift.C[index])
+ getDayValue(sh.shift.D[index]));
console.log(`sum for day: ${index + 1} = ${sum}`);
});
console.log("STOP");
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setRent } from '../ducks/propertyReducer';
import { Link } from 'react-router-dom';
class Wiz5 extends Component {
constructor() {
super();
this.state = {
desiredRent: ''
}
this.handleClick = this.handleClick.bind(this);
}
handleInput(field, input) {
let tempField = {};
tempField[field] = input;
this.setState(tempField);
}
handleClick() {
this.props.setRent(this.state.desiredRent);
}
render() {
console.log(this.props);
return(
<div>
<p>Recommended Rent {this.props.recommendedRent}</p>
<p>Desired Rent</p>
<input placeholder={this.props.desiredRent} onChange={(e) => this.handleInput('desiredRent', e.target.value)}/>
<Link to='/wizard/2'><button>Previous Step</button></Link>
<Link to='/dashboard'><button onClick={this.handleClick}>Complete</button></Link>
</div>
)
}
}
function mapStateToProps(state) {
return {
recommendedRent: state.recommendedRent,
desiredRent: state.desiredRent
}
}
export default connect(mapStateToProps, { setRent })(Wiz5); |
class CommandBase {
constructor(names) {
this.names = names;
}
run(message, args) {
throw new Error("This method is abstract");
}
}
module.exports = CommandBase;
|
var mn = mn || {};
mn.components = mn.components || {};
mn.components.MnRootCertificate =
(function (Rx) {
"use strict";
mn.core.extend(MnRootCertificate, mn.core.MnEventableComponent);
MnRootCertificate.annotations = [
new ng.core.Component({
templateUrl: "app-new/mn-root-certificate.html",
changeDetection: ng.core.ChangeDetectionStrategy.OnPush
})
];
MnRootCertificate.parameters = [
mn.services.MnSecurity,
mn.services.MnForm
];
return MnRootCertificate;
function MnRootCertificate(mnSecurityService, mnFormService) {
mn.core.MnEventableComponent.call(this);
this.cert = mnSecurityService.stream.getCertificate;
this.form = mnFormService.create(this)
.setFormGroup({pem: ""})
.setSource(this.cert.pipe(Rx.operators.pluck("cert")));
}
})(window.rxjs);
|
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin')
const config = require('../config.json');
/**
* 通过webpack.DllPlugin 打包第三方资源库 节约打包时间
*/
// 生产环境ts要打包到dist 本地直接ts-node启动
const isProd = process.env.NODE_ENV == 'production';
// 第三方包单独打包成文件
const vendors = [
'animejs',
'axios',
'classnames',
'mobx',
'mobx-react',
'react',
'react-dom',
'react-hook-form',
'react-router-dom',
'react-transition-group',
'react-zmage', // 图片查看器
];
module.exports = {
output: {
path: path.resolve(__dirname, isProd ? '../dist/' : '../', config.staticPath),
filename: '[name].[hash:8].js',
library: '[name]',
},
entry: {
'vendors': vendors,
},
plugins: [
new webpack.DllPlugin({
context: path.resolve(__dirname, '../'),
path: path.join(__dirname, '../manifest.json'),
name: '[name]'
}),
new AssetsPlugin({
filename: 'vendors-config.json'
}),
new CleanWebpackPlugin(),
],
}; |
import React, { Fragment, useEffect, useContext, useState } from "react";
import { Form, Button } from "react-bootstrap";
import TransactionContext from "../../../context/transactions/transactionContext";
import DisputeContext from "../../../context/disputes/disputeContext";
const DisputeForm = () => {
const transactionContext = useContext(TransactionContext);
const { loadTransactions, transactions, loading } = transactionContext;
console.log(transactions);
const disputeContext = useContext(DisputeContext);
const { addDispute } = disputeContext;
const [dispute, setDispute] = useState({
decision: "",
disputeStatus: "Open",
transactionId: "",
});
const onChange = (e) =>
setDispute({ ...dispute, [e.target.name]: e.target.value });
useEffect(() => {
loadTransactions();
//eslint-disable-next-line
}, []);
const { decision, disputeStatus, transactionId } = dispute;
const onSubmit = (e) => {
e.preventDefault();
addDispute({
decision,
disputeStatus,
transactionId,
});
};
return (
<Fragment>
<Form onSubmit={onSubmit}>
<Form.Group controlId="formBasicDecision">
<Form.Label>Decision</Form.Label>
<Form.Control
type="text"
placeholder="Decision"
onChange={onChange}
value={decision}
name="decision"
/>
</Form.Group>
<Form.Group controlId="formBasicTransaction">
<Form.Label>Transaction</Form.Label>
<Form.Control
name="transactionId"
value={transactionId}
as="select"
onChange={onChange}
>
{transactions !== null && !loading
? transactions.map((transaction) => (
<option key={transaction._id} value={transaction._id}>
{transaction.firstName}
</option>
))
: null}
</Form.Control>
</Form.Group>
<Form.Group controlId="formBasicDispute">
<Form.Label>Status</Form.Label>
<Form.Control
as="select"
name="disputeStatus"
value={disputeStatus}
onChange={onChange}
>
<option value="Open">Open</option>
</Form.Control>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Fragment>
);
};
export default DisputeForm;
|
/* eslint-disable eqeqeq */
import React from 'react'
import { StyleSheet } from 'quantum'
import { range, isStartInterval, isEndInterval, canRenderPosition } from './utils'
import Page from './Page'
const styles = StyleSheet.create({
self: {},
})
const Pages = ({ count = 0, pageSize = 10, offset = 0, onChange }) => {
const currentPage = +offset / +pageSize
return (
<span className={styles()}>
{range(count, pageSize).map((n, i) => {
if (isStartInterval(n, currentPage)) {
return <span key={i}>...</span>
}
if (canRenderPosition(n, count, pageSize, currentPage)) {
return (
<Page
key={i}
current={n == currentPage}
onClick={() => onChange && onChange(pageSize * n, pageSize)}
>
{n + 1}
</Page>
)
}
if (isEndInterval(n, currentPage, count, pageSize)) {
return <span key={i}>...</span>
}
return null
})}
</span>
)
}
export default Pages
|
'use strict';
angular.module('blipApp')
.controller('VisitedLocationsCtrl', ['$http',
'$scope',
'$rootScope',
'$location',
function($http, $scope, $rootScope, $location) {
//Close mobile-navigation menu on page load
$rootScope.toggleNavClass = $rootScope.animateOut;
$scope.currentPath = $location.path();
$scope.visitedLocations = "";
$scope.filterVisitedLocations = [];
$scope.showLoadingAnimation = true;
var user = {
ID: parseInt($rootScope.userIdCookie),
};
$scope.getVisitedLocations = function() {
if(localStorage.getItem("cacheVisit") === null) {
$http.post('http://localhost/blip/app/phpCore/get_visited_locations.php', user)
.then(function(response)
{
$scope.visitedLocations = response.data;
$scope.filterVisitedLocations = $scope.visitedLocations;
localStorage.cacheVisit = JSON.stringify($scope.filterVisitedLocations);
});
}
else{ $scope.filterVisitedLocations = JSON.parse(localStorage.cacheVisit)}
$scope.showLoadingAnimation = false;
$(".visited-locations").removeClass("hide");
};
$scope.editReview = function(location, user, index) {
$("#myModal").modal('show');
$scope.commentTitle = $scope.filterVisitedLocations[index].CommentTitle;
$scope.commentText = $scope.filterVisitedLocations[index].CommentText;
$scope.index = index;
};
$scope.cancelEdit = function() {
$("#myModal").modal('hide');
};
$scope.updateReview = function(rate, title, text) {
$scope.review = {
locID: $scope.filterVisitedLocations[$scope.index].LocationID,
userID: $rootScope.userIdCookie,
title: title,
text: text,
rating: rate
};
var update = $http.post('http://localhost/blip/app/phpCore/update_review.php', $scope.review)
.success(function(data, status, headers, config) {
console.log(status + ' - ' + 'Success');
})
.error(function(data, status, headers, config) {
console.log(status + ' - ' + 'Error');
});
$("#myModal").modal('hide');
$scope.filterVisitedLocations[$scope.index].CommentTitle = $scope.review.title;
$scope.filterVisitedLocations[$scope.index].CommentText = $scope.review.text;
$scope.filterVisitedLocations[$scope.index].ThumbsUp = $scope.review.rating;
localStorage.cacheVisit = JSON.stringify($scope.filterVisitedLocations)
};
$scope.setFilterSetClass = function(filter, index) {
getFilter(filter);
setQuickFilterClass(index);
};
//Called to return filtered content
//If search result matches the filter button it gets pushed into 'filterVisitedLocations' array
//else 'filterVisitedLocations' equals the content that was origionaly returned from the server
var getFilter = function(filter) {
if (filter !== "All") {
$scope.filterVisitedLocations = [];
angular.forEach($scope.visitedLocations, function(value) {
if (value.CategoryName === filter) {
$scope.filterVisitedLocations.push(value);
}
});
} else {
$scope.filterVisitedLocations = $scope.visitedLocations;
}
};
//Sets active class on selected filter button
$scope.activeFilter = 0;
var setQuickFilterClass = function(type) {
$scope.activeFilter = type;
};
$scope.typeHeadClass = " ";
$scope.setIconClass = " ";
$scope.setResultClass = function(classIn) {
switch (classIn) {
case 'Bar':
{
$scope.typeHeadClass = "result-header-bar";
$scope.setIconClass = "fa fa-glass fa-lg";
return "";
}
case 'Restaurant':
{
$scope.typeHeadClass = "result-header-restaurant";
$scope.setIconClass = 'fa fa-cutlery fa-lg';
return "";
}
case 'Supermarket':
{
$scope.typeHeadClass = "result-header-shop";
$scope.setIconClass = 'fa fa-shopping-cart fa-lg';
return "";
}
case 'Other':
{
$scope.typeHeadClass = "result-header-other";
$scope.setIconClass = "fa fa-ellipsis-h fa-lg";
return "";
}
default:
{
return "";
}
}
};
$scope.init = getFilter('All');
}])
.directive('profileMap', ['$rootScope', function($rootScope) {
return {
restrict: 'E',
replace: true,
scope: true,
link:function(scope, element, attributes){
$(document).ready(function() {
var map = new AmCharts.AmMap();
map.pathToImages = "bower_components/ammap3/images/";
var userVisitedCountries = [];
var areas = [];
if($rootScope.userVisitedCookie != undefined) {
userVisitedCountries = $rootScope.userVisitedCookie.split("-");
}
for(var i=0;i<userVisitedCountries.length; i++) {
var country = {
id: userVisitedCountries[i],
}
areas.push(country);
}
var dataProvider = {
map: "worldHigh",
areas: areas,
};
map.dataProvider = dataProvider;
map.areasSettings = {
color: "#16a085",
rollOverOutlineColor: "#16a085",
};
map.smallMap = {
enabled: false
};
map.zoomControl = {
zoomControlEnabled: false,
homeButtonEnabled: false
};
map.dragMap = false;
var mapDiv = document.getElementById("visitedCountriesMap");
map.write(mapDiv);
});
}
}
}]); |
Swap the maximum and minimum elements of an array
question
Write a function changeMaxAndMin that takes the arr array as an argument and returns an array in which the maximum and minimum elements are swapped. If the array has several maximum or several minimum elements, swap the first of them. In all tests, the array contains at least two elements.
Use loops in your solution. The use of the Math.min () and Math.max () methods is not permitted.
function changeMaxAndMin (arr) {
let indMin = 0;
let indMax = 0;
let min = arr [0];
let max = arr [0];
let temp;
for (let i = 1; i <arr.length; i ++) {
if (arr [i] <min) {
min = arr [i];
indMin = i;
}
if (arr [i]> max) {
max = arr [i];
indMax = i;
}
}
arr [indMin] = max;
arr [indMax] = min;
return arr;
}
|
import axios from './index'
const getLostList=(data)=>{
return axios.request({
url:'/lost/list',
method:'post',
data
})
}
const delLostInfo=(data)=>{
return axios.request({
url:'/lost/delete',
method:'post',
data
})
}
const addLostInfo=(data)=>{
return axios.request({
url:'/lost/insert',
method:'post',
data
})
}
const recevied=(data)=>{
return axios.request({
url:'/lost/updateStatus',
method:'post',
data
})
}
const getNoticeInfo=(data)=>{
return axios.request({
url:'/Announcement/list',
method:'post',
data
})
}
const addNoticeInfo=(data)=>{
return axios.request({
url:'/Announcement/insert',
method:'post',
data
})
}
const editNoticeInfo=(data)=>{
return axios.request({
url:'/Announcement/update',
method:'post',
data
})
}
const delNoticeInfo=(data)=>{
return axios.request({
url:'/Announcement/delete',
method:'post',
data
})
}
const Release=(data)=>{
return axios.request({
url:'/Announcement/update',
method:'post',
data
})
}
export {
getLostList,
delLostInfo,
addLostInfo,
recevied,
getNoticeInfo,
addNoticeInfo,
editNoticeInfo,
delNoticeInfo,
Release
} |
import router from '../../../zhimali/zhimahua_vue/src/router'
import {
getCookie
} from '../../../zhimali/zhimahua_vue/src/utils/cookie'
import store from '../../../zhimali/zhimahua_vue/src/store'
// 不重定向 定义白名单
const whiteList = [null, 'index', 'code', 'auth', 'order', 'login','registered', 'mine', 'forgetPwd']
let ua = navigator.userAgent.toLowerCase() //navigator.userAgent转小写
if (ua.indexOf('micromessenger') >= 0) { //通过userAgent是否包含MicroMessenger来判断是否在微信内置浏览器打开网页
router.beforeEach(async (to, from, next) => { //路由钩子函数 router.beforeEach/在跳转之前执行 router.afterEach/在跳转之前执行
if (to.name == 'registered') {
next()
return
}
if (!store.state.openId && to.name !== 'code' && to.name !== 'auth') {
// 如果刷新页面获取页面和参数直接进入页面
store.commit('addPage', {
name: to.name,
query: to.query
})
// this.$store.commit('toShowLoginDialog', true); 同步操作
// this.$store.dispatch('toShowLoginDialog',false) 含有异步操作
/** 微信网页授权 *********************/
// 生成换取微信code连接,并跳转,用户授权后, 有一个接收code的页面
router.push({
name: 'code'
})
} else {
if (getCookie('token')) {
if (!to.name) { //没有目的
next({
name: 'index'
})
} else {
next()
}
} else {
if (whiteList.indexOf(to.name) !== -1) { //如果在白名单里 继续执行
next()
} else {
next({
name: 'login'
}) //如果不在白名单 跳转登录
}
}
}
})
} else { //如果不是微信浏览器
router.beforeEach(async (to, from, next) => {
// to and from are both route objects. must call `next`.
if (getCookie('token')) {
if (!to.name) {
next({
name: 'index'
})
} else {
next()
}
} else {
if (whiteList.indexOf(to.name) !== -1) {
next()
} else {
next({
name: 'login'
})
}
}
})
} |
$(document).ready(function(){
$(".new_toggle").click(function(){
var id = $(this).data("id")
if ($(this).hasClass( "active" )) {//close
$("#"+id).slideToggle(300)
setTimeout(function () {
$(".new_toggle").removeClass('active').html('<i class="fa fa-plus "></i>')
}, 300);
} else {//open
$("#"+id).delay(200).slideToggle(300)
$(this).addClass("active").html('<p>New Offer</p><i class="fa fa-times fa-lg"></i>')
}
});
$(".day_toggle, .close").click(function(){
var id = $(this).data("id")
$("#"+id).fadeToggle(300)
});
$("#month0").css("display","block")
$(".change_month").click(function(){
var id = $(this).data("id")
if (id >= 0 && id+1<=6 ) {
$(".month").css("display","none")
$("#month"+id).show()
}
});
});
|
import React from "react";
import $ from 'jquery';
import {connect} from "react-redux";
import {Body, Header, Screen} from "../common/Common";
import {fetchShoppingItems} from "../../actions/shoppingActions";
import {addToCart, deleteItem, updateQty} from "../../actions/cartActions";
class CartPage extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
}
render() {
return (
<Screen>
<Header>
<a
style={{
position: "absolute",
left: "10px",
cursor: "pointer"
}}
onClick={() => {
this.props.history.push('/shopping');
}}
>
<i className="fa fa-lg fa-arrow-circle-left"/>
</a>
{/*Cart*/}
</Header>
<Body>
<div style={{
paddingTop: "15px",
height: "50px",
fontSize: "16px",
fontWeight: "bolder",
}}>
YOUR CART ({this.props.num_of_items})
</div>
<div style={{
width: "100%",
height: "250px"
}}>{this.props.cart_items.map((c, index) => {
return (<CartItem
key={index}
c={c}
onChange={(value) => {
this.props.updateQty(c.id, value);
}}
onDelete={()=> {
this.props.deleteItem(c.id);
}}
/>)
})}</div>
<div style={{
height: "50px",
}}>
SubTotal: ${this.props.total}
</div>
<div
style={{
display: "flex",
flexDirection: "column",
height: "60px"
}}
>
<button
className="button button1"
onClick={() => {
if (this.props.num_of_items === 0) {
$.notify('Cart is empty!', {
offset: {y: 45, x: 0},
placement: {from: 'top'}
}
);
}
else {
this.props.history.push('/checkout');
}
}}
>CHECKOUT
</button>
</div>
</Body>
</Screen>
)
}
}
function CartItem(props) {
return (
<div style={{
height: "80px",
// backgroundColor: "red",
display: "flex",
justifyContent: "space-between",
marginBottom: "5px",
}}>
<div
style={{
flex: "2",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
{/*{props.c.title}*/}
<img
style={{
display: "block",
maxWidth: "50px",
maxHeight: "70px",
width: "auto",
height: "auto",
}}
src={props.c.img_path}
alt=""
/>
</div>
<div
style={{
flex: "1",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<input
style={{
width: "50px",
}}
value={props.c.quantity}
onChange={(e)=> {
props.onChange(e.target.value);
}}
type="text"
/>
</div>
<div
style={{
flex: "1",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
${props.c.cost}
</div>
<div
style={{
flex: "1",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<a
style={{
cursor: "pointer"
}}
onClick={() => {
props.onDelete();
// this.props.history.push('/shopping');
}}
>
<i className="fa fa-lg fa-window-close"/>
</a>
</div>
</div>);
}
const mapStateToProps = function(state) {
return {
total: state.cart.total,
cart_items: state.cart.cart_items,
num_of_items: state.cart.num_of_items,
}
};
const mapDispatchToProps = dispatch => ({
deleteItem: (id) => dispatch(deleteItem(id)),
updateQty: (id, value) => dispatch(updateQty(id, value))
});
export default connect(mapStateToProps, mapDispatchToProps)(CartPage); |
var mongoose = require('mongoose');
var articleSchema = new mongoose.Schema({
/*关联category项*/
category: { //关联category表信息(category)
type:String,
required:true
},
/*文章主题项*/
title: String, //文章标题
subTitle: String, //副标题
author: { //文章作者
type: String,
default: "佚名"
},
updateTime: { //文章发表时间
type: Date,
default: Date.now
},
content: String, //文章内容
hot:{ //是否为推荐文章
type: Boolean,
default: false
},
/*seo项*/
keywords: Array, //关键字
description: String //描述(也会做文章导读用)
});
var articles = mongoose.model('articles', articleSchema);
module.exports = articles; |
//Components
import DashboardButton from "./components/DashboardButton";
import AppBarUserMenu from "./components/AppBarUserMenu";
//Pages
import UserManagementPage from './pages/UserManagementPage'
import RoleManagementPage from './pages/RoleManagementPage'
import GroupManagementPage from './pages/GroupManagementPage'
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import ActivationPage from './pages/ActivationPage'
import RecoveryPage from './pages/RecoveryPage'
import ProfilePage from './pages/ProfilePage'
import DashboardPage from './pages/DashboardPage'
//Resources
import i18nMessages from './i18n/messages'
import UserModuleStore from './store/UserModule'
//Providers
import authProvider from "./providers/AuthProvider";
import userProvider from "./providers/UserProvider";
import roleProvider from "./providers/RoleProvider";
import groupProvider from "./providers/GroupProvider";
import profileProvider from "./providers/ProfileProvider";
import recoveryProvider from "./providers/RecoveryProvider";
import sessionProvider from "./providers/SessionProvider";
//Routes
import routes from "./routes";
import ClientError from './errors/ClientError'
const setGraphQlClientToProviders = (graphQlClient) => {
authProvider.setGqlc(graphQlClient)
userProvider.setGqlc(graphQlClient)
roleProvider.setGqlc(graphQlClient)
groupProvider.setGqlc(graphQlClient)
profileProvider.setGqlc(graphQlClient)
recoveryProvider.setGqlc(graphQlClient)
sessionProvider.setGqlc(graphQlClient)
}
export {
//ClientError
ClientError,
//Components
DashboardButton,
AppBarUserMenu,
//Pages
UserManagementPage,
RoleManagementPage,
GroupManagementPage,
LoginPage,
RegisterPage,
ActivationPage,
RecoveryPage,
ProfilePage,
DashboardPage,
//Resources
i18nMessages,
UserModuleStore,
routes,
//Provider
authProvider,
userProvider,
roleProvider,
groupProvider,
profileProvider,
recoveryProvider,
sessionProvider,
//Initialice gqlc
setGraphQlClientToProviders
}
|
import React from 'react'
const Pending = props => (
<svg id="prefix__Layer_1" data-name="Layer 1" viewBox="0 0 48 48" {...props}>
<defs>
<style>{'.prefix__cls-3{fill:#ffb400}'}</style>
</defs>
<title>{'pending'}</title>
<g id="prefix__Time-Icon">
<circle
cx={24}
cy={24}
r={22}
stroke="#fff"
strokeWidth={4}
fill="none"
/>
<circle id="prefix__path-1" cx={24} cy={24} r={20} fill="#fff7e5" />
</g>
<g id="prefix__Time-Icon-2" data-name="Time-Icon">
<g id="prefix__Shape">
<path
className="prefix__cls-3"
d="M23.94 11.64a11.83 11.83 0 1 0 11.84 11.83 11.82 11.82 0 0 0-11.84-11.83zm0 21.29a9.46 9.46 0 1 1 9.46-9.46 9.46 9.46 0 0 1-9.4 9.46z"
/>
<path fill="none" d="M9.77 9.28h28.38v28.38H9.77V9.28z" />
<path
className="prefix__cls-3"
d="M24.55 17.56h-1.78v7.09l6.21 3.73.89-1.46-5.32-3.16v-6.2z"
/>
</g>
</g>
</svg>
)
export default Pending
|
import React from 'react'
import {Button} from 'antd'
const Switch=()=>{
return(<div>
<Button>red</Button>
<Button>green</Button>
</div>)
}
export default class ContComponent extends React.Component{
render(){
return(<div><p>Redux内容组件</p>
<Switch/>
</div>)
}
} |
import React, { useContext, useState } from "react";
const UserContext = React.createContext();
export const useUser = () => {
return useContext(UserContext);
};
export const UserProvider = ({ children }) => {
//get all the contacts for a spcific userId
// async function fetchContacts(userId) {
// try {
// const option = {
// method: "GET",
// credentials: "include",
// headers: {
// "Content-Type": "application/json",
// Accept: "application/json",
// Origin: "http://localhost:3000",
// "Access-Control-Allow-Credentials": true,
// "Access-Control-Allow-Headers":
// "Origin, X-Requested-With, Content-Type, Accept,Access-Control-Allow-Credentials",
// },
// };
// const res = await fetch(
// `http://localhost:3000/allContacts/?userId=${userId}`,
// option
// );
// const fetchAllContacts = await res.json();
// if (fetchAllContacts.success) {
// allContacts = fetchAllContacts.data;
// renderContacts(allContacts);
// } else {
// alert(fetchAllContacts.message);
// }
// } catch (err) {
// console.log(err);
// }
// }
const value = {
val: 10,
};
return (
<>
<UserContext.Provider value={value}>{children}</UserContext.Provider>
</>
);
};
|
const form = document.querySelector("#bookingDeletion");
async function handleDeletionRequest() {
const bookingID = document.querySelector('#bookingIDInput').value;
const data = {bookingID};
let options = {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
let response = await fetch('removeBooking',options);
let json = await response.json();
}
window.addEventListener('load', () =>{
form.addEventListener('submit',async () =>{
await handleDeletionRequest();
})
}) |
/*
w-шерлок
t- властолин
с-робинзон
s-бойцов кл
h- молчание ягнят
f- мастер маргарита
*/
const quiz = [
{
"q": "which of these genres do you like ?",
"a" : {
"w": "detectives",
"t": "fantasy",
"c" : "Adventures",
"s" : "instructive",
"h" : "horrors",
"f" : "classic."
}
},
{
"q": "It is important for you that the book first",
"a" : {
"w": "О",
"t": "У ",
"c" : "П ",
"s" : "В ",
"h" : "н ",
"f": "д ",
}
},
{
"q": "What do you look for when choosing a book?",
"a" : {
"w": "mysteriousness",
"t": "by description",
"c" : "???",
"s" : "meaning",
"h" : "on cover style ",
"f": "by price",
}
},
{
"q": "what time would you like to be",
"a" : {
"w": "19 century",
"t": "in the Middle Ages",
"c" : "BC",
"s" : "future",
"h" : "currently",
"f": "20 century",
}
},
{
"q": "which country would you like to live in",
"a" : {
"w": "Great Britain",
"t": "new Zealand",
"c" : "kazakstan",
"s" : "USA",
"h" : "France",
"f": "Russia",
}
},
{
"q": "how long have you read the last book",
"a" : {
"w": "3month",
"t": "6month",
"c" : "1year",
"s" : "2month",
"h" : "8month",
"f": "1month",
}
},
];
|
import React from 'react'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import { mount } from 'enzyme'
import reducers from './src/reducers'
function mountComponentWithRedux(ComponentClass, state = {}, props = {}) {
const componentInstance = mount(
// produces app by going through full React lifecycle
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>,
)
return componentInstance
}
export { mountComponentWithRedux }
|
import React, {Component} from 'react'
import {AsideNav} from '../../components/AsideNav/AsideNav'
import {Header} from '../../components/Header/Header'
import {Track} from '../../components/Track/Track'
import firebase from 'firebase';
import { store } from "../../store";
export class Favorites extends React.Component {
componentWillUnmount(){
clearTimeout(this.timeout1);
}
constructor(props){
super(props);
this.state = {
favorites: []
};
let currentUser = {uid: store.getState().auth.uid};
let favorites = [];
if(currentUser){
const refFavorites = firebase.database().ref(`users/${currentUser.uid}/favorites`);
refFavorites.once("value", function (snapshot) {
snapshot.forEach(function (data) {
firebase.database().ref(`podcasts/${data.key}`).once("value", function (podcast) {
if(podcast.val()){
let profileImage = '';
let podcastURL = '';
let favorited = false;
if(currentUser){
firebase.database().ref(`users/${currentUser.uid}/favorites/${podcast.val().id}`).once('value', function (fav) {
if(fav.val()){
favorited = true;
}
})
}
if(podcast.val().rss){
firebase.database().ref(`users/${podcast.val().podcastArtist}/profileImage`).once("value", function (image) {
if(image.val().profileImage){
profileImage = image.val().profileImage;
}
});
podcastURL = podcast.val().podcastURL;
}
else{
const storageRef = firebase.storage().ref(`/users/${podcast.val().podcastArtist}/image-profile-uploaded`);
storageRef.getDownloadURL()
.then(function(url) {
profileImage = url;
}).catch(function(error) {
//
});
firebase.storage().ref(`/users/${podcast.val().podcastArtist}/${podcast.val().id}`).getDownloadURL().catch(() => {console.log("file not found")})
.then(function(url){
podcastURL = url;
});
}
let username = '';
firebase.database().ref(`users/${podcast.val().podcastArtist}/username`).once("value", function (name) {
if(name.val().username){
username = name.val().username
}
});
setTimeout(() => {
let ep = {podcastTitle: podcast.val().podcastTitle, podcastArtist: podcast.val().podcastArtist, id: podcast.val().id, username: username, profileImage: profileImage, podcastURL: podcastURL, favorited: favorited};
favorites.push(ep);
}, 1000);
}
})
})
});
}
this.timeout1 = setTimeout(() => {this.setState({favorites: favorites.reverse(), })}, 2000);
}
render() {
return (
<div>
<Header props={this.props}/>
<div className="tcontent">
<AsideNav/>
<div className="tsscrollwrap">
<div className="tsscrollcontent">
<div className="container">
<div className="trow-header">
<div className={"tsHeaderTitles"}>
<h2>{store.getState().auth.loggedIn ? 'Favorites' : 'Log in to see your favorites!'}</h2>
</div>
</div>
<div className="row">
{this.state.favorites.map((_, i) => (
<div key={i} className="col-xs-4 col-sm-4 col-md-3 col-lg-2">
<Track menukey={i} podcast={_}/>
</div>
))}
</div>
</div>
</div>
</div>
</div>
</div>
)
}
} |
//供應商查詢表單Action
function vendorSelected(data) {
}
/* $("#PopSuppliesSearchResult").hide();
$("#suppliesConfirm").on('click', function () {
SupplierNumber = $("#inpSuppliesID_SearchBox").val();
SuppliesName = $("#inpSuppliesName_SearchBox").val();
SuppliesIdNumber = $("#inpSuppliesNumber_SearchBox").val();
if (SupplierNumber.length == 0 && SuppliesName.length == 0 && SuppliesIdNumber.length == 0) {
alert("請至少輸入一個查詢條件")
return false;
}
else {
$("#PopSuppliesSearchResult").hide();
$.ajax({
type: 'POST',
url: '/PR/SuppliesListGet',
data: {
SupplierNumber: SupplierNumber, SName: SuppliesName, SuppliesIdNumber: SuppliesIdNumber
},
async: false,
success: function (data) {
$("#divPopSuppliesSearchbody ul").find("li[CopyTarget=N]").remove();
$.each(data, function (index, obj) {
NewRow = $("#divPopSuppliesSearchbody ul").find("li[CopyTarget=Y]").clone()
NewRow.attr("CopyTarget", "N")
NewRow.find("div").eq(0).text(obj.SupplierNumber)
NewRow.find("div").eq(1).text(obj.SuppliesName)
NewRow.find("div").eq(2).text(obj.RatingDate)
NewRow.find("div").eq(3).text(obj.CommitmentDate)
NewRow.show()
$("#divPopSuppliesSearchbody ul").append(NewRow);
})
if ($("#divPopSuppliesSearchbody ul").find("li[CopyTarget=N]").length==0) {
$("#spanPopSuppliesNomatch").show()
$("#divPopSuppliesSearchList").hide()
}
else {
$("#spanPopSuppliesNomatch").hide()
$("#divPopSuppliesSearchList").show()
}
$("#PopSuppliesSearchResult").show()
}
, error: function (xhr) {
alert('Ajax request 發生錯誤' + xhr);
// $(e.target).attr('disabled', false);
}
});
}
$("#PopSuppliesSearchResult").show();
})
$("#suppliesCancel").on('click', function () {
$("#inpSuppliesID_SearchBox").val("");
$("#inpSuppliesName_SearchBox").val("");
$("#inpSuppliesNumber_SearchBox").val("");
$("#PopSuppliesSearchResult").hide();
})*/
//供應商查詢表單Action
//pop品名跳窗 Action
{
$(function () {
$("#popPOitemList").find("a[alt=btnSearch]").on("click", function () {
if ($("#popPOitemList").remodal().state == "opened") {
$("#popPOitemList").remodal().close()
}
$.blockUI({ message: "搜尋中" });
let keyWord = $("#inp_POitemListSearchBox").val().trim();
let VendorName = $("#inp_VendorNameSearchBox").val().trim();
$("#popPOitemList").find("#div_POitemListSearchedbody").find("li").not("[alt=template]").remove();
$.ajax({
type: 'POST',
url: '/PR/POitemListGet',
data: {
SName: keyWord,
VendorName: VendorName
},
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
row = $("#popPOitemList").find("#div_POitemListSearchedbody").find("li[alt=template]").eq(0).clone()
$(row).attr("alt", "")
if (obj.QuoteAmount - obj.usedTwdQuoteAmount - obj.UnitTwdPrice >= 0) {//可用餘額減產品單價大於0才顯示
$(row).find("input:radio").data("obj", obj);
}
else {
$(row).attr("title", "協議採購項已超出剩餘合約金額")
$(row).find("input:radio").addClass("input-disable").prop("disabled", true)
}
$(row).find("div").eq(1).text(obj.VendorName)
$(row).find("div").eq(2).text(obj.CategoryName)
$(row).find("div").eq(3).text(obj.ItemDescription)
$(row).find("div").eq(4).text(obj.UomName)
$(row).find("div").eq(5).text(fun_accountingformatNumberdelzero(obj.UnitPrice))
$(row).find("div").eq(6).text(obj.BpaNum)
$(row).find("div").eq(7).text(obj.strContractStartDate + " ~ " + obj.strContractEndDate)
$(row).find("div").eq(8).text(obj.PurchaseEmpName + "(" + obj.PurchaseEmpNum + ")")
$(row).show()
$("#popPOitemList").find("#div_POitemListSearchedbody ul").append(row)
})
}
if ($("#popPOitemList").find("#div_POitemListSearchedbody").find("li").not("[alt=template]").length == 0) {
$("#popPOitemList").find("#div_POitemListSearchedbody ul").append("<li> <label class=\"w100 label-box\"><div class=\"table-box w100\">查無資料</div></label></li>")
$("#popPOitemList").find("[alt=btnZone]").hide();
}
else {
$("#popPOitemList").find("[alt=btnZone]").show();
}
$("#popPOitemList").find("#div_POitemListSearchedList").show();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)
}
}).always(function () {
setTimeout(function () {
$.unblockUI();
$("#popPOitemList").remodal().open()//避免ajax太快回覆,會導致remodal未關閉就開啟
}, 500)
});
})
$("#popPOitemList").find("a[data-remodal-action=confirm]").on("click", function () {
$("#popPOitemList").find("input:radio").each(function () {
if ($(this).prop("checked")) {
obj = $(this).data("obj")
return false
}
})
if (obj) {
target = $("#popPOitemList").data("target")
popPOitem_inputData(obj, target)
$(target).find("[Errmsg=Y]").remove();
}
else {
alert("請選擇一樣品項")
return false;
}
})
})
function popPOitem_inputData(obj, target) {
$(target).data("obj", obj)
$(target).find("[name=DeliveryPrompt]").val("")
$(target).data("DeliveryList", null)//更換商品時清空送貨層
$(target).find("[name=Quantity]").html("<span> <b class=\"Classification undone-text\">0</b></span>")//數量歸零
$(target).find("[tag]").each(function () {
tag = $(this).attr("tag")
if (obj[tag]) {
if ($(this).is("[value]")) {
$(this).val(obj[tag])
}
else {
if ($(this).is("[Amount]")) {
$(this).text(fun_accountingformatNumberdelzero(obj[tag]))
}
else {
$(this).text(obj[tag])
}
}
}
else {
$(this).text("")
}
})
$.when(th_PurchaseEmpListSet).always(
function () {
$(target).find("select[name=PurchaseEmpNum]").eq(0).val(obj.PurchaseEmpNum).prop("disabled", false).selectpicker('setStyle', 'input-disable', 'remove').selectpicker("refresh")
GetFirstPurchaseEmpNum()
})
}
function popPOitemList_reset() {
$("#inp_POitemListSearchBox").val("")
$("#popPOitemList").find("#div_POitemListSearchedList").hide();
$("#popPOitemList").find("#div_POitemListSearchedbody").find("li").not("[template]").remove();
$("#popPOitemList").find("[alt=btnZone]").hide();
}
}
//pop品名跳窗 Action
//送貨單位明細 Action
{
$(function () {
$("#popPROneTimeDetail").on("reset", function (evet, ReadOnly) {
$.when(thrOneTimeDetail_ChargeDept, thrOneTimeDetail_RcvDept).done(function () {
$("#popPROneTimeDetail").find("tbody[dataloading]").remove();
$("#popPROneTimeDetail").find("[alt=add]").show();
$("#popPROneTimeDetail").find("[alt=add]").off("click")
$("#popPROneTimeDetail").find("[alt=add]").on("click", function () {
fun_addDeliveryRow(null, UomCode)
})
$("#popPROneTimeDetail").find("#OnceDevyConfirm").off("click")
$("#popPROneTimeDetail").find("#OnceDevyConfirm").on("click", function () {
$("#popPROneTimeDetail").trigger("Confirm")
})
$("#popPROneTimeDetail").find("tbody").not("[dataloading]").not("[template]").remove();
target = $("#popPROneTimeDetail").data("target")
UomCode = $(target).find("[name=UomCode]").val()
if (ReadOnly == 1) {
$("#popPROneTimeDetail").find("#OnceDevyConfirm").hide()
$("#popPROneTimeDetail").find("[alt=add]").hide()
$("#popPROneTimeDetail").find("a[alt=cancel]").text("確認")
if (target.data("DeliveryList") && target.data("DeliveryList").length > 0) {
$.each($.map(target.data("DeliveryList"), function (o) { if (!o.IsDelete) { return o } }), function (index, info) {
fun_addDeliveryReadonlyRow(info)
})
}
}
else {
$("#popPROneTimeDetail").find("#OnceDevyConfirm").show()
$("#popPROneTimeDetail").find("[alt=add]").show()
$("#popPROneTimeDetail").find("a[alt=cancel]").text("取消")
if (target.data("DeliveryList") && target.data("DeliveryList").length > 0) {
DeliveryList = target.data("DeliveryList")
$.each(DeliveryList, function (index, info) {
fun_addDeliveryRow(info, UomCode)
})
}
else {
fun_addDeliveryRow(null, UomCode)
}
}
}).fail(function () {
alert("FIIS資料異常")
})
})
$("#popPROneTimeDetail").on("Confirm", function () {
$("#popPROneTimeDetail").find("[Errmsg=Y]").remove();
target = $("#popPROneTimeDetail").data("target")
let rtn = true;
if (target) {
let UomCode = $(target).find("[name=UomCode]").val()
totalQuantity = 0;
DeliveryList = [];
PRDetailID = $(this).find("[name=PRDeliveryID]").val()
$("#popPROneTimeDetail").find("tbody").not("[dataloading]").not("[template]").each(function () {
PurReqDelivery =
{
ChargeDeptName: $(this).find("[name=ChargeDept]").find("option:selected").text(),
RcvDeptName: $(this).find("[name=RcvDept]").find("option:selected").text(),
PRDeliveryID: $(this).find("[name=PRDeliveryID]").val(),
PRDetailID: PRDetailID,
Quantity: accounting.unformat($(this).find("[name=DevQuantity]").val()),
Amount: accounting.unformat($(this).find("[name=DevAmount]").text()),
TranferStatus: 0,
ChargeDept: $(this).find("[name=ChargeDept]").val(),
RcvDept: $(this).find("[name=RcvDept]").val(),
IsDelete: ($(this).find("[name=IsDelete]").val() == "1")
}
DeliveryList.push(PurReqDelivery)
if (!PurReqDelivery.IsDelete) {
if (!fun_basicVerify(this)) {
rtn = false
}
totalQuantity += PurReqDelivery.Quantity
}
})
if (rtn && UomCode == "AMT") {
if ($.map(DeliveryList, function (o) { return o.Quantity }).reduce(function (a, b) {
return a + b
}) != 1) {
rtn = false;
alert("數量總合不等於1")
}
}
if (rtn) {
let UnitTwdPrice = accounting.unformat((target).find("[tag=UnitTwdPrice]").text())
$(target).data("DeliveryList", DeliveryList)
$(target).find("[name=Quantity]").text(fun_accountingformatNumberdelzero(totalQuantity))
$(target).find("[name=totalTwdAmount]").text(fun_accountingformatNumberdelzero(accounting.toFixed(totalQuantity * UnitTwdPrice, 4)))
$("#popPROneTimeDetail").remodal().close()
}
}
})
thrOneTimeDetail_ChargeDept = $.ajax({
url: "/PR/GetDepartmentList/", //存取Json的網址
type: "POST",
cache: false,
data: { PRnum: $("hidPRNum").val() },
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("#popPROneTimeDetail").find("select[name=ChargeDept]").append($("<option></option>").attr("data-subtext", obj.DeptCode).attr("value", obj.DeptCode).text(obj.DeptName))
})
$("#popPROneTimeDetail").find("select[name=ChargeDept]").selectpicker('refresh');
}
else {
$("#popPROneTimeDetail").find("tbody[dataloading]").find("span").text("取得掛帳單位失敗")
}
},
error: function (err) {
$("#popPROneTimeDetail").find("tbody[dataloading]").find("span").text("取得掛帳單位失敗")
}
})
thrOneTimeDetail_RcvDept = $.ajax({
url: "/PR/GetHrDepartment/", //存取Json的網址
type: "POST",
cache: false,
data: { PRnum: $("hidPRNum").val() },
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("#popPROneTimeDetail").find("select[name=RcvDept]").append($("<option></option>").attr("data-subtext", obj.DeptCode).attr("value", obj.DeptCode).text(obj.DeptName))
})
$("#popPROneTimeDetail").find("select[name=RcvDept]").selectpicker('refresh');
}
else {
$("#popPROneTimeDetail").find("tbody[dataloading]").find("span").text("取得收貨單位失敗")
}
},
error: function (err) {
$("#popPROneTimeDetail").find("tbody[dataloading]").find("span").text("取得收貨單位失敗")
}
})
})
function fun_addDeliveryRow(info, UomCode) {
obj = $("#popPROneTimeDetail tbody[template]").eq(0).clone()
$(obj).removeAttr("template");
$(obj).find("[alt=template]").attr("alt", "Index")
$(obj).find('.selectpicker').data('selectpicker', null);
$(obj).find('.bootstrap-select').find("button:first").remove();
$(obj).find(".selectpicker").selectpicker("render")
if (UomCode == "AMT") {
$(obj).find("[name=DevQuantity]").attr("Accuracy", "2").attr("MaxValue", 1)
}
else {
$(obj).find("[name=DevQuantity]").attr("MaxValue", "999999999").removeAttr("Accuracy")
}
$(obj).find("input[Amount]").on("focus", function () {
fun_onfocusAction(this);
})
$(obj).find("input[Amount]").on("blur", function () {
target = $("#popPROneTimeDetail").data("target")
inpValue = $(this).val()
if (fun_onblurAction(this) && $(target).data("obj")) {
$(this).closest("tbody").find("[name=DevAmount]").html(fun_accountingformatNumberdelzero(accounting.toFixed(inpValue * $(target).data("obj").UnitTwdPrice, 4)))
}
else {
$(this).closest("tbody").find("[name=DevAmount]").html("<b class=\"ItemName undone-text\">系統自動帶入</b>")
}
})
$(obj).find("[alt=remove]").on("click", function () {
fun_DelDeliveryRow($(this).closest("tbody"));
})
$(obj).mouseenter(function () {
$(this).find("[alt=remove]").show();
})
$(obj).mouseleave(function () {
$(this).find("[alt=remove]").hide();
})
$(obj).show()
if (info) {
target = $("#popPROneTimeDetail").data("target")
$(obj).find("select[name=ChargeDept]").val(info.ChargeDept).selectpicker("refresh")
$(obj).find("select[name=RcvDept]").val(info.RcvDept).selectpicker("refresh")
$(obj).find("input[name=DevQuantity]").val(info.Quantity)
if (fun_onblurAction($(obj).find("input[name=DevQuantity]")) && $(target).data("obj")) {
$(obj).find("div[name=DevAmount]").html(fun_accountingformatNumberdelzero(info.Amount))
}
$(obj).find("input[name=PRDeliveryID]").val(info.PRDeliveryID)
$(obj).find("input[name=IsDelete]").val(info.IsDelete)
if (info.IsDelete) {
fun_DelDeliveryRow(obj)
}
else {
fun_basicVerify(obj)
}
}
$("#popPROneTimeDetail").find("table").append(obj)
fun_resetCellIndex($("#popPROneTimeDetail"), "Index", 1)
}
function fun_addDeliveryReadonlyRow(info) {
obj = $("#popPROneTimeDetail tbody[template]").eq(0).clone()
$(obj).removeAttr("template");
$(obj).find("[alt=template]").attr("alt", "Index")
$(obj).find("td").eq(1).html("").text(info.ChargeDeptName)
$(obj).find("td").eq(2).html("").text(info.RcvDeptName)
$(obj).find("td").eq(3).html("").text(fun_accountingformatNumberdelzero(info.Quantity))
$(obj).find("td").eq(4).html("").text(fun_accountingformatNumberdelzero(info.Amount))
$(obj).show()
$("#popPROneTimeDetail").find("table").append(obj)
fun_resetCellIndex($("#popPROneTimeDetail"), "Index", 3)
}
function fun_DelDeliveryRow(target) {
if ($(target).find("input[name=PRDeliveryID]").val() != "") {
$(target).find("input[name=IsDelete]").val(1)
$(target).hide();
$(target).find("[alt=Index]").attr("alt", "deleted")
}
else {
$(target).remove()
}
fun_resetCellIndex($("#popPROneTimeDetail"), "Index", 1)
}
}
//送貨單位明細 Action
//新增報價單 Action
{
$(function () {
$("#popQuote").on("reset", function () {
$.when(thrCurrencyCode).done(function () {
$("#popQuote").find("input").val("");
$("#popQuote").find("select").val("").selectpicker('refresh');
$("#popQuote").find("[Errmsg=Y]").remove();
$("#popQuote").find("select[name=VendorSiteId] option").remove()
$("#popQuote").find("td[name=subTotal]").text("")
$("#popQuote").find("select[name=CurrencyCode]").val("TWD").selectpicker('refresh')
$("#popQuote").find("input[name=CurrencyName]").val($("#popQuote").find("select[name=CurrencyCode]").find("option[value=TWD]").text())
$("#popQuote").find("input[name=ForeignPrice]").attr("accuracy", $("#popQuote").find("select[name=CurrencyCode]").find("option[value=TWD]").attr("extendedPrecision"))
PRDList = $("#popQuote").data("PRDList")
VID = $("#popQuote").data("VID")
if (!VID) { alert("請選擇供應商"); return false }
if (!PRDList) { alert("請選擇報價商品"); return false }
StakeHolder = { flag: false }
$.ajax({
url: "/PR/SuppliesListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { SupplierNumber: VID },
async: false,
success: function (data) {
if (data) {
$("#popQuote").find("[name=supplierName]").text(data.supplierName)
$.each(data.supplierSite, function (index, obj) {
$("#popQuote").find("select[name=VendorSiteId]").append($("<option></option>").attr("value", obj.supplierSiteID).text(obj.supplierSiteCode))
})
$("#popQuote").find("select[name=VendorSiteId]").selectpicker('refresh');
$("#popQuote").find("input[name=VendorNum]").val(VID)
$("#popQuote").find("input[name=VendorSiteName]").val(data.supplierName)
StakeHolder = fun_StakeHolder(data.vatRegistrationNumber, data.supplierName)
}
},
error: function (err) {
alert("FIIS 供應商資料異常")
}
})
$.each(PRDList, function (index, obj) {
TrObj = $("#tabQOItemList").find("tr[Datarow]").eq(0).clone();
if (index == 0) {
$("#tabQOItemList").find("tr[Datarow]").remove();
}
$(TrObj).find("td[tag]").each(function () {
tag = $(this).attr("tag")
if (obj[tag]) {
if ($(this).is("[Amount]")) {
$(this).text(fun_accountingformatNumberdelzero(obj[tag]))
}
else {
$(this).text(obj[tag])
}
}
})
$(TrObj).find("[name=PRDetailId]").val(obj.PRDetailID)
$(TrObj).find("input[name=ForeignPrice]").on("focus", function () {
fun_onfocusAction(this);
})
$(TrObj).find("input[name=ForeignPrice]").on("blur", function () {
if (fun_onblurAction(this)) {
ForeignPrice = accounting.unformat($(this).val())
Quantity = accounting.unformat($(this).closest("tr").find("[tag=Quantity]").text())
subTotal = accounting.toFixed(Quantity * ForeignPrice, 4);
$(this).closest("tr").find("[name=subTotal]").text(fun_accountingformatNumberdelzero(subTotal))
TotalAmount = 0
$("#tabQOItemList").find("tr[Datarow]").each(function () {
subTotal = accounting.unformat($(this).closest("tr").find("[name=subTotal]").text())
if (subTotal == 0) {
TotalAmount = 0;
return false
}
else {
TotalAmount += accounting.unformat(subTotal)
}
})
if (TotalAmount <= 0) {
$("#QuoteDetail").find("[name=TotalAmount]").val("")
}
else {
$("#QuoteDetail").find("[name=TotalAmount]").val(fun_accountingformatNumberdelzero(TotalAmount))
}
}
else {
$(this).closest("tr").find("[name=subTotal]").text("")
$("#QuoteDetail").find("[name=TotalAmount]").val("")
}
})
$("#tabQOItemList").append(TrObj)
})
fun_resetCellIndex($("#tabQOItemList"), "Index", 1)
if (StakeHolder.flag) {
if (String(StakeHolder.IsInvolvedParties).toLocaleLowerCase() == "false") {
$("#popQuote").find("[name=divStakeHolderDescription]").hide();
$("#popQuote").find("[name=StakeHolderDescription]").removeAttr("necessary")
$("#popQuote").find("[name=strStakeHolder]").text("否")
$("#popQuote").find("input[name=StakeHolder]").val(false);
}
else {
$("#popQuote").find("[name=divStakeHolderDescription]").show();
$("#popQuote").find("[name=StakeHolderDescription]").attr("necessary", "")
$("#popQuote").find("[name=strStakeHolder]").text("是")
$("#popQuote").find("input[name=StakeHolder]").val(true);
}
}
else {
alert("檢核是否為利害關係人時發生錯誤")
return false
}
$("#QuotefileSection").empty("")
let objitem = Q_FileUploadReset(false)
$("#QuotefileSection").append($(objitem))
window.location.href = "#modal-QO"
})
})
$("#popQuote").find("a[Confirm]").on("click", function () {
if (fun_basicVerify($("#popQuote"))) {
Quoteinfo = {
// PurchaseEmpNum: $("#FillInEmpNum").val(),
// PurchaseEmpName: $("#FillInName").val(),
QuoteEmpNum: $("#FillInEmpNum").val(),
QuoteEmpName: $("#FillInName").val(),
VendorNum: $("#popQuote").find("input[name=VendorNum]").val(),
VendorSiteId: $("#popQuote").find("select[name=VendorSiteId]").val(),
ContactPerson: $("#popQuote").find("input[name=ContactPerson]").val(),
ContactEmail: $("#popQuote").find("input[name=ContactEmail]").val(),
StakeHolder: $("#popQuote").find("input[name=StakeHolder]").val(),
StakeHolderDescription: $("#popQuote").find("input[name=StakeHolderDescription]").val(),
CurrencyCode: $("#popQuote").find("select[name=CurrencyCode]").val(),
VendorSiteName: $("#popQuote").find("input[name=VendorSiteName]").val(),
InvoiceAddress: $("#popQuote").find("input[name=InvoiceAddress]").val(),
CurrencyName: $("#popQuote").find("input[name=CurrencyName]").val(),
supplierName: $("#popQuote").find("div[name=supplierName]").text(),
QuoDetailList: []
}
$("#tabQOItemList").find("tr[Datarow]").each(function () {
Quoteinfo.QuoDetailList.push({
PRDetailId: $(this).find("[name=PRDetailId]").val(), ForeignPrice: accounting.unformat($(this).find("[name=ForeignPrice]").val())
, Quantity: accounting.unformat($(this).find("[tag=Quantity]").text())
})
})
$.ajax({
url: "/PR/QuoteDbAdd/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { QuoObj: Quoteinfo },
async: false,
success: function (data) {
if (!data || data.FormGuid == "" || data.FormGuid == null) {
if (!(data.FormNum == "" || data.FormNum == null)) {
alert(data.FormNum)//拿來存錯誤訊息
}
else {
alert("合格供應商檢查失敗!!")
}
return false
}
else {
QsaveFileInfo(data.FormGuid);
$("#popQuote").remodal().close()
}
},
error: function (err) {
alert("報價單存檔失敗!!")
return false
}
})
}
else {
return false
}
})
$("#popQuote").find("select[name=CurrencyCode]").on("change", function () {
$("#popQuote").find("input[name=CurrencyName]").val($(this).find("option:selected").text())
/* if ($(this).val() == "TWD") {
$("#popQuote").find("input[name=ForeignPrice]").attr("Accuracy", 0)
}
else {
let extendedPrecision = parseInt($(this).find("option:selected").attr("extendedPrecision"))
extendedPrecision = (extendedPrecision > 4) ? 4 : extendedPrecision //小數點最多四位
$("#popQuote").find("input[name=ForeignPrice]").attr("Accuracy", extendedPrecision)
}*/
let extendedPrecision = parseInt($(this).find("option:selected").attr("extendedPrecision"))
extendedPrecision = (extendedPrecision > 4) ? 4 : extendedPrecision //小數點最多四位
$("#popQuote").find("input[name=ForeignPrice]").attr("Accuracy", extendedPrecision)
fun_onblurAction($("#popQuote").find("input[name=ForeignPrice]").eq(0))
$("#popQuote").find("input[name=ForeignPrice]").eq(0).blur()
})
$("#popQuote").find("select[name=VendorSiteId]").on("change", function () {
$("#popQuote").find("input[name=InvoiceAddress]").val($(this).find("option:selected").text())
})
thrCurrencyCode = $.ajax({
url: "/PR/CurrencyListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("#popQuote").find("select[name=CurrencyCode]").append($("<option></option>").attr("data-subtext", obj.currencyCode).attr("value", obj.currencyCode).text(obj.currencyName).attr("extendedPrecision", obj.extendedPrecision))
})
$("#popQuote").find("select[name=CurrencyCode]").selectpicker('refresh');
}
},
error: function (err) {
}
})
})
//利害關係人檢核
function fun_StakeHolder(uid, name) {
let rtn = { flag: false }
$.ajax({
url: "/PR/CheckIsInvolvedParties/", //存取Json的網址
type: "POST",
data: { uid: uid, name: name },
cache: false,
async: false,
success: function (data) {
rtn = { flag: true, IsInvolvedParties: data }
}
})
return rtn
}
}
//新增報價單 Action
//報價明細 Action
{
$("#QuotationInforemodal").on("reset", function (event, option) {
$.ajax({
url: "/PR/QuoteDetailListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { PRDetailID: option.PRDetailID },
async: false,
success: function (data) {
if (data) {
if ($(data).length == 0) {
alert("查無可用報價")
return
}
$.each(data, function (index, obj) {
TrObj = $("#tab_QuotationInfo").find("tr[Datarow]").eq(0).clone();
if (index == 0) {
$("#tab_QuotationInfo").find("tr[Datarow]").remove();
}
$(TrObj).find("[tag]").each(function () {
$(this).text("")
tag = $(this).attr("tag")
if (obj[tag]) {
if ($(this).is("[Amount]")) {
$(this).text(fun_accountingformatNumberdelzero(obj[tag]))
}
else {
$(this).text(obj[tag])
}
}
})
if (obj.IsEnabled) {
$(TrObj).find("[alt=IsEnabled][value=true]").prop("checked", true)
$(TrObj).find("[alt=IsEnabled][value=false]").prop("checked", false)
}
else {
$(TrObj).find("[alt=IsEnabled][value=true]").prop("checked", false)
$(TrObj).find("[alt=IsEnabled][value=false]").prop("checked", true)
}
if (option.Confirmed) {
$(TrObj).find("[alt=IsEnabled][value=true]").prop("disabled", true).addClass("input-disable")
$(TrObj).find("[alt=IsEnabled][value=false]").prop("disabled", true).addClass("input-disable")
$("#QuoDetConfirm").hide()
}
else {
$(TrObj).find("[alt=IsEnabled][value=true]").prop("disabled", false).removeClass("input-disable")
$(TrObj).find("[alt=IsEnabled][value=false]").prop("disabled", false).removeClass("input-disable")
$("#QuoDetConfirm").show()
}
$(TrObj).find("[alt=IsEnabled]").attr("name", "radion_IsEnabled" + index)
$(TrObj).find("input[name=QDetailID]").val(obj.QDetailID)
$(TrObj).find("a[tag=QuoteNum]").on("click", function () {
$.ajax({
url: "/PR/GetQuoteInfo/" + $(this).text(), //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
async: false,
success: function (data) {
if (data && data.Detail) {
$("#QuoteInfoArea").find("[tag]").each(function () {
$(this).text("")
tag = $(this).attr("tag")
if (data.Detail[tag]) {
if ($(this).is("[Amount]")) {
$(this).text(fun_accountingformatNumberdelzero(data.Detail[tag]))
}
else {
$(this).text(data.Detail[tag])
}
}
})
if (data.Detail.StakeHolder) {
$("#QuoteInfoArea").find("[name=strStakeHolder]").text("是")
}
else {
$("#QuoteInfoArea").find("[name=strStakeHolder]").text("否")
}
TotalAmount = 0
$.each(data.Detail.QuoDetailList, function (index, QD) {
TrObj = $("#tabQOItemReadOnlyList").find("tr[Datarow]").eq(0).clone();
if (index == 0) {
$("#tabQOItemReadOnlyList").find("tr[Datarow]").remove();
}
$(TrObj).find("[tag=ForeignPrice]").text(fun_accountingformatNumberdelzero(QD.ForeignPrice))
$.ajax({
url: "/PR/GetPRDetailByPRDetailId/" + $(this).text(), //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { PRDetailId: QD.PRDetailId },
async: false,
success: function (PRDdata) {
if (PRDdata && PRDdata.Detail) {
subTotal = parseFloat(accounting.toFixed((QD.ForeignPrice * PRDdata.Detail.Quantity), 4))
TotalAmount += subTotal
$(TrObj).find("[tag=CategoryName]").text(PRDdata.Detail.CategoryName)
$(TrObj).find("[tag=ItemDescription]").text(PRDdata.Detail.ItemDescription)
$(TrObj).find("[tag=Quantity]").text(fun_accountingformatNumberdelzero(PRDdata.Detail.Quantity))
$(TrObj).find("[tag=UomName]").text(PRDdata.Detail.UomName)
$(TrObj).find("[name=subTotal]").text(fun_accountingformatNumberdelzero(subTotal))
}
}
})
$("#tabQOItemReadOnlyList tbody").append(TrObj)
})
$("#popQuoteReadonly").find("[name=TotalAmount]").val(fun_accountingformatNumberdelzero(TotalAmount))
fun_resetCellIndex($("#tabQOItemReadOnlyList"), "Index", 1)
//檔案上傳區塊
$("#QuoteReadonlyfileSection").empty().append(Q_FileUploadReset(true))
QgetFileInfo(data.Detail["QID"], $("#QuoteReadonlyfileSection")).then(function () {
$("#QuoteReadonlyfileSection").find("a.deleteFile").remove()
$("#QuoteReadonlyfileSection").html($("#QuoteReadonlyfileSection").html().replace(/downloadFileHandler/g, "QdownloadFileHandler"))
})
//檔案上傳區塊
$("#popQuoteReadonly").remodal().open()
}
else {
alert("報價單載入失敗!!")
}
},
error: function (err) {
alert("報價單載入失敗!!")
}
})
})
$("#tab_QuotationInfo tbody").append(TrObj)
})
window.location.href = "#QuotationInforemodal"
}
else {
alert("取得報價明細失敗")
}
},
error: function (err) {
alert("取得報價明細失敗")
}
})
})
$("#QuoDetConfirm").on("click", function () {
QDlist = []
$("#tab_QuotationInfo tr[Datarow]").each(function () {
QDlist.push({
QDetailID: $(this).find("input[name=QDetailID]").val(),
IsEnabled: $(this).find("[alt=IsEnabled]:checked").val()
})
})
$.ajax({
url: "/PR/QuoteToEnable/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { QDlist: QDlist },
async: false,
success: function (data) {
if (!data) {
alert("更新報價狀態失敗")
}
},
error: function (err) {
alert("更新報價狀態失敗")
}
})
})
}
//報價明細 Action
//報價上傳 Action
{
var Q_existData = []
function Q_FileUploadReset(readonly) {
Q_existData = []
let Qesunfile = {}
let QfileSectionitem = $('#QfileSection').clone();
Qesunfile = $(QfileSectionitem).find("div.QesunfileList")
$(Qesunfile).empty()
var temp = $.extend(true, {}, $(Qesunfile)).attr('id');
html = ""
if (readonly) {
html = fileZoneReadOnlyTemplate(temp, Qesunfile, index);
} else {
html = fileZoneEditTemplate(temp, Qesunfile, index);
}
//避免被主單的JS控制到
html = html.replace(/dndregion/g, "Qdndregion")
html = html.replace(/fileUploadBtn/g, "QfileUploadBtn")
html = html.replace(/chageDescription/g, "QchageDescription")
html = html.replace(/<div class="file-table-area text-center">/, "<div class=\"file-table-area text-center\" style=\"text-align:center\">")
html = html.replace(/<div class="icon-cloud_upload upload-icon-size">/, "<div class=\"icon-cloud_upload upload-icon-size\" style=\"text-align:center\">")
//避免被主單的JS控制到
$(Qesunfile).append(html)
//拖曳上傳功能
$(Qesunfile).find('.Qdndregion').on({
'dragenter':
function (e) {
e.stopPropagation();
e.preventDefault();
$(this).css('border', '2px solid #0B85A1');
},
'dragover':
function (e) {
$(this).css('border', '2px solid #0B85A1');
e.stopPropagation();
e.preventDefault();
},
'drop':
function (e) {
e.preventDefault();
$(this).css('border', '');
var files = e.originalEvent.dataTransfer.files;
if (files.length > 0) {
Q_existData = QuploadFileHandler(files, $(this), Q_existData);
}
}
});
//監聽上傳按鈕是否有選擇檔案
$(Qesunfile).find(".QfileUploadBtn").on('change', function () {
Q_existData = QuploadFileHandler($(this)[0].files, $(this).parents('.box'), Q_existData);
//將檔案放入FormData後初始化input file
$(this).val("");
});
$(Qesunfile).find('.selectAllFile').on('click', function () {
$(this).parents('.box').find('.selectFileDetail').prop('checked', $(this).prop('checked'));
});
//刪除按鈕
$(Qesunfile).find(".deleteFile").off('click');
$(Qesunfile).find(".deleteFile").on('click', '.deleteFile', QdeleteFileHandler);
$(QfileSectionitem).show()
return QfileSectionitem
}
//==============================================================================================
// 檔案上傳 / 檔案下載 / 刪除檔案 / 存檔 / 取得現有檔案
//==============================================================================================
function QuploadFileHandler(files, appendRoot, dataList) {
var data = new FormData();
var uploadCount = 0;
var existFileName = "";
$.each(files, function (index, item) {
uploadCount++;
data.append(index, item);
//若檔案清單已有檔案,則檢查是否有重複上傳的檔
if ($(appendRoot).find('tr.fileDetail').length > 0) {
$.each($(appendRoot).find('tr.fileDetail a.fileName'), function (existIndex, existItem) {
if (item.name == $(existItem).text()) {
delete (data[index]);
existFileName = existFileName + "\n" + item.name + " 已經存在";
uploadCount--;
}
})
}
});
//若無重複上傳,則回傳0筆失敗
if (existFileName == "") {
existFileName = "0筆";
}
var uploadResult;
if (uploadCount > 0) {
$.when(
$.ajax({
headers: { FormType: "QO", UserID: $('#LoginEno').val() },
type: 'POST',
data: data,
async: true,
cache: false,
contentType: false,
processData: false,
url: '/CBP/Upload/',
success: function (data1, param, param1) {
uploadResult = data1;
},
error: function (data1, param, param1) {
alert("檔案上傳失敗")
}
})
).then(
function () {
blockPage('')
if (uploadResult.length > 0) {
alert("成功上傳:" + uploadResult.length + "筆檔案\n" + "失敗:" + existFileName)
dataList = QsetFileData(uploadResult, appendRoot, dataList)
}
}
)
} else {
// alert(existFileName)
}
return dataList
}
function QdeleteFileHandler(e) {
var alertMsg = "";
var root = $(e.target).parents('.box');
var deleteGroup = $(root).find('input[type="checkbox"][class="selectFileDetail"]:checked').parents('tr.fileDetail');
if (deleteGroup.length < 1) {
alert("請勾選要刪除的檔案");
} else {
$.each($(deleteGroup).find('.fileName'), function (index, item) {
alertMsg = alertMsg + $(item).text() + '\n'
})
var noSernoDelete = [];
alertMsg = alertMsg + "即將被刪除,請確認是否刪除"
if (confirm(alertMsg)) {
$(root).find('.selectAllFile').prop('checked', false);
$.each(deleteGroup, function (index, item) {
Q_existData.find(function myfunction(x, index) {
if ($(item).find('input[type="checkbox"]').attr('id').split('_')[1] == 0) {
if (x.file.FileName == $(item).find('a.fileName').text()) {
x.fileStatus = 99;
}
}
if (x.Serno == $(item).find('input[type="checkbox"]').attr('id').split('_')[1] && x.Serno != 0) {
x.fileStatus = 2;
}
})
})
deleteGroup.remove();
if ($(root).find('.fileDetail').length < 1) {
$(root).find('.deleteFile').remove();
$(root).find('.downloadFile').remove();
$(root).find('tbody').append('<tr class="unUpload"><td colspan="5" class="text-center"><div class="file-table-area text-center"><div class="icon-cloud_upload upload-icon-size"></div>\
<b>請將檔案拖曳至此或點【上傳檔案】按鈕</b></div></td></tr>');
}
}
}
}
function QsaveFileInfo(formGuid) {
if (Q_existData.length > 0) {
$.ajax({
async: true,
type: 'POST',
data: JSON.stringify(Q_existData),
contentType: "application/json",
url: '/CBP/SaveFile/' + formGuid,
error: function (data) {
alert(data.responseText)
}
})
}
}
function QgetFileInfo(formGuid, target) {
return $.ajax({
async: true,
type: 'GET',
contentType: "application/json",
url: '/CBP/GetFile/' + formGuid,
success: function (data) {
if (data != undefined && data.length > 0) {
$.each(data, function (index, item) {
item.fileStatus = 0;
})
Q_existData = QsetFileData(data, target, Q_existData)
}
},
error: function (data) {
alert(data.responseText)
}
})
}
function QdownloadFileHandler(specificFile) {
var downLoadData = [];
if (typeof (specificFile) == "undefined") {
return;
} else if (typeof (specificFile) == "object") {
Q_existData.find(function (element) {
if (element.fileStatus != 2 && element.fileStatus != 99) {
downLoadData.push(element)
}
})
//$.each(specificFile, function (index, item) {
// downLoadData.push(_existData.find(function (element) {
// return element.file.FileName == item
// }))
//})
} else {
downLoadData.push(Q_existData.find(function (element) {
return element.file.FileName == specificFile
}))
}
//判斷是否為IE11,因IE11不支援使用FetchAPI
if (rv != undefined && parseFloat(rv[1]) == 11.0) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/CBP/Download', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = xhr.getResponseHeader('x-filename') == null ? "attechment.zip" : xhr.getResponseHeader('x-filename');
var disposition = filename;
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = typeof File === 'function'
? new File([this.response], filename, { type: type })
: new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
xhr.setRequestHeader('content-type', 'application/json');
xhr.send(JSON.stringify(downLoadData));
} else {
var fileName = "default";
fetch('/CBP/Download', {
body: JSON.stringify(downLoadData),
method: 'POST',
mode: 'cors',
headers: {
'content-type': 'application/json'
}
}).then(function (response) {
fileName = decodeURI(response.headers.get('x-fileName')) == "null" ? decodeURI(response.headers.get('content-disposition').split('=')[1]) : decodeURI(response.headers.get('x-fileName'))
return response.blob();
}).then(function (blob) {
saveAs(blob, fileName);
})
}
}
//==============================================================================================
// 處理檔案區的各式樣板功能
//==============================================================================================
function QsetFileData(fileData, appendRoot, dataList) {
var appendTarget = $(appendRoot).find('tbody.fileList');
if (typeof (fileData) != "object" || fileData == null || fileData.length < 1) {
return;
}
//加入刪除及下載鈕
if ($(appendRoot).find('.fileBtnArea').find('.deleteFile').length < 1) {
$(appendRoot).find('.fileBtnArea').append('<a class="btn-02-gray btn-text4 deleteFile"> <div class="glyphicon glyphicon-trash bt-icon-size"></div>刪除檔案</a>');
}
if ($(appendRoot).find('.fileBtnArea').find('.downloadFile').length < 1) {
$(appendRoot).find('.fileBtnArea').append('<a class="btn-02-yellow btn-text4 downloadFile" onclick=\'QdownloadFileHandler([])\'><div class="glyphicon glyphicon-save bt-icon-size"></div>全部下載</a>');
}
$.each(fileData, function (index, item) {
item.fileSeq = dataList.length + 1;
dataList.push(item);
_peopleInfoTemplate = peopleInfoTemplate(item.uploaderID, item.uploaderName, item.uploaderDept)
item.Serno == 0 ? $(appendTarget).append(fileDescriptionOpenTemplate(item).replace(/downloadFileHandler/g, "QdownloadFileHandler").replace(/chageDescription/g, "QchageDescription")) :
item.uploaderID == $('#LoginEno').val() ? $(appendTarget).append(fileDeleteOpenTemplate(item)) : (appendTarget).append(fileDefaultTemplate(item));
});
// $(appendTarget).html($(appendTarget).html().replace(/downloadFileHandler/g, "QdownloadFileHandler"))
// $(appendTarget).html($(appendTarget).html().replace(/chageDescription/g, "QchageDescription"))
$(appendTarget).find('tr.unUpload').remove();
if (urlParam[1].toLocaleLowerCase() == "readonly") {
$('input.selectFileDetail').remove()
}
return dataList
}
function QchageDescription(e) {
var description = $(e).val();
Q_existData.find(function myfunction(x, index) { if ($(e).parents('tr').find('a.fileName').text() == x.file.FileName) { x.fileDescription = description } })
}
}
//報價上傳 Action |
import chai, {expect} from 'chai';
import { _ } from 'nrser';
import { itMaps } from '//lib/testing';
import { Logger } from '//lib/metalogger/Logger';
import { Level, LEVEL_NAME_PAD_LENGTH } from '//lib/metalogger/Level';
import { LevelSpec } from '//lib/metalogger/LevelSpec';
import type { LevelName, LevelRank } from '//lib/metalogger/Level';
describe('metalogger/Logger.js', () => {
describe("Logger", () => {
describe("#getDelta", () => {
it("starts at undefined", () => {
const logger = new Logger();
expect(logger.getDelta(new Date())).to.be.undefined;
});
it("gets the difference in ms", () => {
const logger = new Logger();
logger.lastMessageDate = new Date();
const now = new Date(logger.lastMessageDate.getTime() + 888);
expect(logger.getDelta(now)).to.equal(888);
});
}); // #getDelta
// describe(".formatDelta", () => {
// itMaps({
// func: Logger.formatDelta.bind(Logger),
// map: (f, throws) => [
// f(), '+----ms',
// f(0), '+0000ms',
// f(888), '+0888ms',
// f(9999), '+9999ms',
// f(10000), '+++++ms',
// ]
// });
// }); // .formatDelta
// describe(".formatHeader", () => {
// const level = Level.DEBUG;
// const date = new Date(2016, 9-1, 14, 17, 33, 44, 888);
// const delta = 888;
//
// const message = {
// level,
// refs: false,
// notif: false,
// formattedLevel: Logger.formatLevel(level),
// date: date,
// formattedDate: Logger.formatDate(date, 'YYYY-MM-DD HH:mm:ss.SSS'),
// path: '/imports/api/blah.js:x:y:8',
// delta,
// formattedDelta: Logger.formatDelta(delta),
// content: [],
// };
//
// itMaps({
// func: (format) => Logger.formatHeader(message, format),
//
// map: (f, throws) => [
// f("%date (%delta) %level [%path]"),
// "2016-09-14 17:33:44.888 (+0888ms) DEBUG [/imports/api/blah.js:x:y:8]",
// ]
// });
// }); // .formatDate
describe("#pushSpec", () => {
const logger = new Logger();
const spec = logger.pushSpec({
file: '/a/b/c.js',
level: 'info',
});
expect(spec).to.be.instanceof(LevelSpec);
expect(logger.specs.length).to.eql(1);
expect(logger.specs[0]).to.eql(spec);
const spec2 = logger.pushSpec({
file: "/x/y/z.js",
level: "debug",
});
expect(logger.specs.length).to.eql(2);
expect(logger.specs[0]).to.eql(spec);
expect(logger.specs[1]).to.eql(spec2);
}); // #pushSpec
describe("#shouldLog", () => {
const logger = new Logger();
const spec = logger.pushSpec({
path: '/a/b/c.js:8',
level: 'info',
});
const query = {
path: '/a/b/c.js:8',
content: [],
};
expect(logger.shouldLog(Level.DEBUG, query)).to.be.false;
expect(logger.shouldLog(Level.INFO, query)).to.be.true;
});
}); // Logger
}); // metalogger/Logger.js |
import { subDays } from 'date-fns';
/**
* convert utc string to Date object
* @param {*} str
* @param {*} allDay
*/
function stringToTime(str, allDay) {
if (typeof str === 'string' && allDay) {
const [yr, mo, dt] = str.split(/\D+/, 3).map(Number);
return new Date(yr, mo - 1, dt); // month is 0-based
}
return new Date(str);
}
/**
* Convert UTC strings from backend to Date times
* @param time
* @returns {{start: *|Date, end: *|Date, allDay: boolean}}
*/
function fromUTCStrings(time) {
let { allDay } = time;
if (allDay === undefined) {
const midnight = 'T00:00:00Z';
allDay = time.start.endsWith(midnight) && time.end.endsWith(midnight);
}
const start = stringToTime(time.start, allDay);
let end = stringToTime(time.end, allDay);
if (allDay) {
end = subDays(end, 1);
}
return {
...time,
start,
end: time.end && (end < start ? start : end),
allDay,
};
}
export default fromUTCStrings;
|
define([
'foreground/view/prompt/errorPromptView'
], function (ErrorPromptView) {
'use strict';
describe('ErrorPromptView', function () {
beforeEach(function () {
this.documentFragment = document.createDocumentFragment();
this.view = new ErrorPromptView();
});
afterEach(function () {
this.view.destroy();
});
it('should show', function () {
this.documentFragment.appendChild(this.view.render().el);
this.view.triggerMethod('show');
});
});
}); |
const { generateError, generateAjvError } = require('../utils/generateResponse');
const bcrypt = require('bcrypt');
const db = require('../../db');
const Ajv = require('ajv');
const ajv = new Ajv();
require("ajv-formats")(ajv);
const { verifySchema } = require('../validations');
const verifyValidate = ajv.compile(verifySchema)
const validateToken = (req, res, next) => {
const { authorization } = req.headers;
if (authorization == undefined || authorization !== process.env.LAUNCHER_SECRET)
return generateError(res, 400, {message: 'Invalid Token !'});
next();
}
const validateUser = async (req, res, next) => {
if (req.method === 'POST' && !verifyValidate(req.body))
return generateAjvError(res, ajv, verifyValidate);
const { email, password } = req.body;
const user = await db.User.findOne({attributes: ['uuid', 'password'], where: { email: email }});
if (!user) return generateError(res, StatusCodes.NOT_FOUND, {error: 'user not found'});
const validPass = await bcrypt.compare(password, user.password);
if (!validPass) return generateError(res, StatusCodes.UNAUTHORIZED, 'invalid password');
res.locals.user_uuid = user.uuid;
next();
}
module.exports = {
validateToken,
validateUser
}; |
var addPrinters = function(data){
var printers_names = new Array;
for (i = 0; i < data['data'].length; i++) {
name = data['data'][i]['attributes']['name'];
printers_names.push(name)
}
$.each(printers_names, function(val, text) {
$('#printer_name').append( $('<option></option>').attr('id', text).html(text) )
});
};
var getPrinters = function(){
$.ajax({
url : baseUrl() + 'printers',
type : 'GET',
success: addPrinters,
error: showErrors
})
}; |
/**
* home reducer
* @param {Array} [state=[]] initstate
* @param {Object} action action
* @return {Array} same as the initstate
*/
const home = (state = [], action) => {
switch (action.type) {
case 'ADD_LIST_PENDING':
return []
case 'ADD_LIST_FULFILLED':
return action.payload
case 'ADD_LIST_REJECTED':
return state
default:
return state
}
}
export default home
|
const convict = require('convict');
const config = convict({
http: {
port: {
doc: 'The port to listen on',
default: 3000,
env: 'PORT'
}
},
authentication: {
google: {
"clientId": {
"doc": "The Client ID from Google to use for authentication",
"default": process.env.CLIENT_ID,
"env": process.env.CLIENT_ID
},
"clientSecret": {
"doc": "The Client Secret from Google to use for authentication",
"default": process.env.CLIENT_SECRET,
"env": process.env.CLIENT_SECRET
}
},
token: {
secret: {
doc: 'The signing key for the JWT',
default: process.env.JWT_SECRET,
env: process.env.JWT_SECRET
},
issuer: {
doc: 'The issuer for the JWT',
default: 'live-horror-stream'
},
audience: {
doc: 'The audience for the JWT',
default: 'live-horror-stream'
}
}
}
});
config.validate();
module.exports = config;
|
var express = require('express')
var router = express.Router()
let people = []
const findPerson = id => {
return people.find(person => person.id == id)
}
router
.get('/people', (req, res) => {
res.send({
message: 'Here are all the people currently in our database',
items: people
})
})
.post('/people', (req, res) => {
const resContent = {
error: false,
message: 'Here are all the people currently in our database including the newly created one',
items: people
}
try {
if (req.body.name) {
if (req.body.lastname) {
let maxId = 0
people.forEach(person => {
if (person.id > maxId) maxId = person.id
})
req.body.id = maxId + 1
people.push(req.body)
} else {
resContent.error = true
resContent.message = 'Please provide your last name!'
}
} else {
resContent.error = true
resContent.message = 'Please provide your first name!'
}
} catch (err) {
resContent.error = true
resContent.message = err.message
}
res.send(resContent)
})
.patch('/people/:id', (req, res) => {
const resContent = {
error: false,
message: 'The product is successfully updated',
items: people
}
try {
const person = findPerson(req.params.id)
if (person) {
if (req.body.name) person.name = req.body.name
if (req.body.lastname) person.lastname = req.body.lastname
} else {
resContent.error = true
resContent.message = 'We couldn\'t find a person with the specified id'
}
} catch (err) {
resContent.error = true
resContent.message = err.message
}
res.send(resContent)
})
.delete('/people/:id', (req, res) => {
const resContent = {
error: false,
message: 'The machine is no more',
items: people
}
try {
people = people.filter(person => person.id != req.params.id)
resContent.items = people
} catch (err) {
resContent.error = true
resContent.message = err.message
}
res.send(resContent)
})
module.exports = router
|
import React, { Component } from 'react'
import './style.css'
import ball from '../public/images/soccerball.png'
class Header extends Component {
state = {
user: "",
currentBalance:100,
team:[]
}
render() {
return (
<div className="header-container">
<a href="#home" >
<img src={ball} alt="" />
Fantazy League
</a>
<div class="right-floated">
<a href="Team">(user)-(Current Balance)</a>
<a href="/user/logout">Logout</a>
</div>
</div>
)
}
}
export default Header;
|
var AWS = require('aws-sdk');
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
//list all objects
function aws(domain){
return new Promise((resolve, reject)=> {
s3.listObjects({Bucket: domain}).promise()
.then(data=>resolve(data))
.catch(err=>reject(err, err.stack))
})
}
module.exports = {
aws
} |
import React from "react";
import { Draggable } from "react-beautiful-dnd";
const DashboardItem = ({ draggableId, index, children }) => {
return (
<Draggable draggableId={draggableId} index={index}>
{provided => (
<section
className="box box--width-header px-0"
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
{children}
</section>
)}
</Draggable>
);
};
export default DashboardItem;
|
import React from "react";
import { StyleSheet, css } from "aphrodite";
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import { getFullYear, getFooterCopy } from "../utils/utils";
const styles = StyleSheet.create({
paragraph: {
textAlign: "center",
fontSize: "1.2rem",
},
copyright: {
marginTop: "40px",
},
});
class Footer extends React.Component {
constructor(props) {
super(props);
}
render() {
const { user } = this.props;
return (
<footer className="footer">
<p className={css(styles.copyright)}>
Copyright {getFullYear()} - {getFooterCopy(true)}
</p>
{ user ?
<p className={css(styles.paragraph)}>
<a>Contact us</a>
</p> :
<></>
}
</footer>
);
}
}
Footer.propTypes = {
user: PropTypes.object,
};
Footer.defaultProps = {
user: null,
};
export const mapStateToProps = (state) => {
return {
user: state.get('user')
};
};
export default connect(mapStateToProps, null)(Footer);
|
import React, {Component} from 'react';
import {View, StyleSheet, Image} from 'react-native';
export class MapPlaceHolder extends Component {
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.mapPlaceHolderStyle}>
<Image
style={styles.imgStyle}
source={require('./../assets/map.png')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
mapPlaceHolderStyle: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
position: 'relative'
},
imgStyle: {
width: '100%',
height: '100%'
}
}
); |
import baseState from './base/state.js'
import listState from './list/state.js'
config.$inject = ['$urlRouterProvider','$locationProvider','$stateProvider']
export default function config($urlRouterProvider, $locationProvider, $stateProvider) {
$urlRouterProvider.otherwise('/')
$locationProvider.html5Mode(true)
$stateProvider
.state('base', baseState)
.state('base.list', listState)
}
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
//Define our Model
const userSchema = new Schema({
//makes the email unique, no two user with the same email
googleId: String,
facebookId: String,
displayName: String,
email: { type: String, unique: true, lowercase: true },
password: String,
credits: { type: Number, default: 0 }
});
//Create a model class
mongoose.model('users', userSchema);
|
#!/usr/bin/env node
/**
* This file contains the command line interface application
* for the server.
*/
var program = require('commander');
var fs = require('fs');
var exec = require('child_process').exec;
var csv = require('csvtojson');
var csvWriter = require('csv-write-stream');
program
.version('0.1.0')
/**
* Command to execute jar file
*/
program
.command('exec-jar [inFile] [outDir]')
.description('Run the java program')
.action(function (inFile, outDir) {
var command = '/usr/bin/java -jar maras_10_10_17.jar ' + inFile + ' ' + outDir;
var child = exec(command, {maxBuffer: 1024 * 1000}, (error, stdout, stderr) => {
if (error) {
console.log(error);
}
});
});
program
.command('generate-drugs-rules [inFile] [outFile1] [outFile2')
.description('Generate CSV file with drugnames and drugID and file with drugrules and drugID')
.action(function (inFile, outFile1, outFile2) {
let drugNames = [];
let rules = [];
csv()
.fromFile(inFile)
.on('json',(jsonObj) => {
drugNames.push(jsonObj.Drug1);
drugNames.push(jsonObj.Drug2);
rules.push(jsonObj);
})
.on('done',(error) => {
drugNames = drugNames
.filter((value, index, self) => self.indexOf(value) === index)
.map((value, index) => ({id: index, name: value}));
let writer = csvWriter();
writer.pipe(fs.createWriteStream(outFile1));
drugNames.forEach(drug => {
writer.write(drug);
});
writer.end()
rules.map((rule, index) => {
let temp = rule;
temp.Drug1 = drugNames.filter(obj => obj.name == temp.Drug1)[0];
temp.Drug2 = drugNames.filter(obj => obj.name == temp.Drug2)[0];
return temp;
});
const content = JSON.stringify(rules);
fs.writeFile(outFile2, content, 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
if (error) {
console.log(error);
}
});
});
program.parse(process.argv);
|
import { validate, splitStringByComma } from '../utils'
describe('Utils', () => {
it('Validate email', () => {
const validEmail = 'email@domain.com'
const invalidEmail = 'email'
const validResult = validate(validEmail)
const invalidResult = validate(invalidEmail)
expect(validResult.valid).toBe(true)
expect(validResult.value).toBe(validEmail)
expect(invalidResult.valid).toBe(false)
expect(invalidResult.value).toBe(invalidEmail)
})
it('Split str by comma', () => {
const str = 'email1, email2,email3,,,, email4'
const list = splitStringByComma(str)
expect(list.length).toEqual(4)
})
})
|
const documentStore = require("../helper/documentStoreHolder");
const User_ForAuthentication = require("../indexes/userForAuthentication");
const Room_ForSearch = require("../indexes/roomForSearch");
const Game_ForSearch = require("../indexes/gameForSearch");
exports.CreateIndexes = function () {
const UserForAuthentication = new User_ForAuthentication();
const RoomForSearch = new Room_ForSearch();
const GameForSearch = new Game_ForSearch();
UserForAuthentication.execute(documentStore);
RoomForSearch.execute(documentStore);
GameForSearch.execute(documentStore);
}; |
import React, { useState, useEffect, useRef } from "react";
import {
FormControl,
Row,
Col,
Button,
Form,
Card,
Image,
} from "react-bootstrap";
import NavbarMolecule from "./NavbarMolecule";
import { IoOptionsOutline } from "react-icons/io5";
import MyDate from "../common/MyDate";
export default ({ title, date, image }) => {
return (
<>
<Card className="mt-3 p-3">
<Row>
<Col
xs="4"
className="justify-content-center align-items-center d-flex"
>
<Image
className="mx-auto"
fluid
src={image}
rounded
onError={(e) => {
e.target.onerror = null;
e.target.src = "./image_not_found.svg";
}}
/>
</Col>
<Col>
<div className="my_font_size_md">{title}</div>
<div className="my_font_size_sm">{MyDate(date)}</div>
</Col>
</Row>
</Card>
</>
);
};
|
document.addEventListener('DOMContentLoaded',()=> {
const squares =document.querySelectorAll(".grid div");
let resultText = document.querySelector("#result");
let gameArea=document.querySelector(".game-area");
let resultBox=document.querySelector(".result-box");
let resultBoxMass=document.querySelector(".result-box h1");
let replayBtn =document.querySelector('#replay');
let leftBtn =document.querySelector(".left");
let rightBtn =document.querySelector(".right");
let controlUp =document.querySelector(".control .up");
let controlLeft =document.querySelector(".control .left");
let controlRight =document.querySelector(".control .right");
let controlDown =document.querySelector(".control .down");
let manId=202;
squares[manId].classList.add("man");
let width = 15 ;
let cars=[[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0] ];
let direction =1;
let result =0 ;
let rowsStart=[15,30,45,60,90,105,120,150,165,180];
let rowEnd =rowsStart.map((e)=>e+width-1);
let rowMoveingDirction = [1,1,0,0,1,1,1,0,0,0] ; // 1:right and 0:left
let gameTimer = setInterval (moveCars,400);
showCars();
function showCars () {
for (let row=0;row<rowsStart.length;row++){
for (let rand=0;rand<7;rand++){
cars[row][rand]=Math.floor(Math.random()*(width-1)+rowsStart[row]);
if (rowMoveingDirction[row]===1){
squares[cars[row][rand]].classList.add("car-right");
}else {
squares[cars[row][rand]].classList.add("car-left");
}
}
}
}
function moveCars () {
for (let row=0;row<rowsStart.length;row++){
for(let car=0;car<7;car++){
if (rowMoveingDirction[row]===1){
squares[cars[row][car]].classList.remove("car-right");
}else {
squares[cars[row][car]].classList.remove("car-left");
}
if(rowMoveingDirction[row]===0){ //left
if (cars[row][car]>rowsStart[row]){
cars[row][car] -=1;
}else {
cars[row][car] +=14;
}
}else { // right
if (cars[row][car]<rowEnd[row]){
cars[row][car] +=1;
}else {
cars[row][car] -=14;
}
}
if (rowMoveingDirction[row]===1){
squares[cars[row][car]].classList.add("car-right");
}else {
squares[cars[row][car]].classList.add("car-left");
}
}
}
// lose
if (squares[manId].classList.contains("car-left") || squares[manId].classList.contains("car-right")){
gameArea.classList.add("end");
resultBox.classList.add("end");
squares[manId].classList.add("boom");
resultBoxMass.textContent="you lose!"
}
// win
if (manId<15){
gameArea.classList.add("end");
resultBox.classList.add("end");
resultBoxMass.textContent="you win!"
}
}
document.addEventListener("keydown", function(event) {
squares[manId].classList.remove("man");
if(event.key=="ArrowDown"){
if (manId<(15*14)){
manId +=15;
}
}else if(event.key=="ArrowUp"){
if (manId>14){
manId -=15;
}
}else if(event.key=="ArrowLeft"){
if (manId%15>0){
manId -=1;
}
}else if(event.key=="ArrowRight"){
if (manId%15<14){
manId +=1;
}
}
squares[manId].classList.add("man");
// win
if (manId<15){
gameArea.classList.add("end");
resultBox.classList.add("end");
resultBoxMass.textContent="you win!"
}
});
controlUp.onclick = function() {
squares[manId].classList.remove("man");
if (manId>14){
manId -=15;
}
squares[manId].classList.add("man");
}
controlLeft.onclick = function() {
squares[manId].classList.remove("man");
if (manId%15>0){
manId -=1;
}
squares[manId].classList.add("man");
}
controlRight.onclick = function() {
squares[manId].classList.remove("man");
if (manId%15<14){
manId +=1;
}
squares[manId].classList.add("man");
}
controlDown.onclick = function() {
squares[manId].classList.remove("man");
if (manId<(15*14)){
manId +=15;
}
squares[manId].classList.add("man");
}
replayBtn.addEventListener("click", function() {
window.location = window.location.href;
});
}) |
module.exports = {
projects: [
"./client/",
{
root: "./client/",
package: "./package.json",
globalComponents: ["./src/**/*.vue"],
},
],
};
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {autobind} from 'core-decorators';
import moment from 'moment';
import Datetime from 'react-datetime';
import 'react-datetime/css/react-datetime.css';
import {setField, sendRegistration} from '../actions/index.js';
import Activity from './Activity.jsx';
import Field from './Field.jsx';
class Form extends Component {
@autobind
handleCommentsChange(e) {
this.props.setField('comments', e.target.value);
}
@autobind
handleRegisterClick(e) {
this.props.sendRegistration(this.props.form);
}
@autobind
handleDobChange(date) {
this.props.setField(
'dob',
typeof date.format === 'function' ? date.format('YYYY-MM-DD') : date
);
}
@autobind
handleConsentChange(e) {
this.props.setField('consent', e.target.checked);
}
render() {
const {app, form} = this.props;
const isMobileDevice = /iPhone|iPad|iPod|Android/.test(navigator.userAgent);
return (
<form>
{
!!Object.keys(form.errors).length && form.validated &&
<div className="message error">
Før skjemaet kan sendes inn, må du rette opp i feltene som er
markert med feil.
</div>
}
<fieldset>
<div className="activities">
<h2>Hva vil du gjøre?</h2>
<p>
Som ny kan du velge maks to frivilligaktiviteter, for å{' '}
sikre at vi klarer å gi deg en god start.
</p>
{form.data.activities && Object.keys(form.data.activities).map(id => (
<Activity key={id} type={form.data.activities[id]} />
))}
{
form.errors.activities && (form.validated || form.touched.activities) &&
<div className="validation error">{form.errors.activities}</div>
}
</div>
<h2>Kommentarer</h2>
<div>
<textarea onChange={this.handleCommentsChange}></textarea>
</div>
</fieldset>
<fieldset>
<h2>Litt om deg</h2>
<Field
label="Fornavn"
name="firstName"
value={form.firstName || ''}
required
/>
<Field
label="Etternavn"
name="lastName"
value={form.lastName || ''}
required
/>
<Field
label="Adresse"
name="address"
value={form.address || ''}
required
/>
<Field
label="Postnummer"
name="zipcode"
value={form.zipcode || ''}
required
/>
<Field
label="Sted"
name="city"
value={form.city || ''}
required
/>
<Field
label="Fødselsdato"
type={isMobileDevice ? 'date' : 'text'}
name="dob"
value={form.dob || ''}
input={
isMobileDevice ?
null
:
<Datetime
value={form.dob ? moment(form.dob).format('DD.MM.YYYY') : ''}
dateFormat={'DD.MM.YYYY'}
utc={true}
timeFormat={false}
locale="nb"
onChange={this.handleDobChange}
closeOnSelect={true}
/>
}
/>
<Field
label="Telefon"
type="tel"
name="phone"
value={form.phone || ''}
required
/>
<Field
type="email"
label="Epost"
name="email"
value={form.email || ''}
required
/>
</fieldset>
<fieldset>
<div className="checkbox">
<label>
<input type="checkbox" onChange={this.handleConsentChange} />
Jeg har lest <a href="https://www.dnt.no/personvern/" target="_blank">DNTs personvernerklæring</a>{' '}
og samtykker til at DNT kan lagre mine opplysninger så lenge jeg er{' '}
aktiv som frivillig for DNT.
</label>
</div>
{
form.errors.consent && form.validated &&
<div className="validation error">{form.errors.consent}</div>
}
</fieldset>
{
!!Object.keys(form.errors).length && form.validated &&
<div className="message error">
Før skjemaet kan sendes inn, må du rette opp i feltene som er markert
med feil.
</div>
}
{
(() => {
if (app.isSending) {
return (
<button type="button" disabled>Sender registrering...</button>
);
} else if (app.isSent !== true) {
return (
<button type="button" onClick={this.handleRegisterClick}>
Registrer meg
</button>
);
}
return null;
})()
}
{
app.isSent &&
<div className="message success">
Skjemaet er sendt til DNT Oslo og Omegn for behandling.
</div>
}
{
form.error &&
<div className="message error">
Det skjedde en feil ved innsending av skjemaet.
</div>
}
</form>
);
}
}
const mapStateToProps = state => ({
activities: state.activities,
app: state.app,
form: state.form,
});
const mapDispatchToProps = dispatch => ({
setField: function dispatchSetField(field, value) {
dispatch(setField(field, value));
},
sendRegistration: function dispatchSendRegistration() {
dispatch(sendRegistration());
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Form);
|
export const PREFIX = "@@supplier/";
export const ASYNC_SUPPLIER_INIT = `${PREFIX}ASYNC_SUPPLIER_INIT`;
export const HANDLE_NOTIFICATION = `${PREFIX}HANDLE_NOTIFICATION`;
export const GET_SUPPLIERS_SUCCESS = `${PREFIX}GET_SUPPLIERS_SUCCESS`;
export const GET_SUPPLIER_SUCCESS = `${PREFIX}GET_SUPPLIER_SUCCESS`;
|
// 若要执行文档转换,先执行gulp, 再执行 gulp i
const gulp = require('gulp');
const gulpsync = require('gulp-sync')(gulp);
const del = require('del');
const fs = require('fs');
const markdown = require('gulp-markdown');
const util = require('./util');
const config = require('./config.json');
var DOCUMENT_DEST = config.docDist;
var DOCUMENT_SRC = config.docSrc;
// 清空util文件夹
gulp.task('clean-doc', function () {
del.sync(DOCUMENT_DEST + '/*', {force: true});
});
// 清空除了index.html之外的util文件夹
gulp.task('i', function () {
del.sync([DOCUMENT_DEST + '/*', '!' + DOCUMENT_DEST + 'index.html'], {force: true});
});
// 移动其他文件至目标文件
gulp.task('move-doc', ['clean-doc'], function (cb) {
gulp.src([DOCUMENT_SRC + '**/*', '!' + DOCUMENT_SRC + 'md/**/*'])
.pipe((gulp.dest(DOCUMENT_DEST)))
.on('end', cb);
});
// 将doc的md文件转换为html文件放入目标文件夹
gulp.task('c', ['move-doc'], function (cb) {
gulp.src(DOCUMENT_SRC + 'md/**/*')
.pipe(markdown())
.pipe(gulp.dest(DOCUMENT_DEST + 'md/'))
.on('end', cb);
});
// 将各个页面拼接
gulp.task('p', ['c'], function (cb) {
var catas,
structure,
stream,
htmls,
docList,
htmlRoot;
htmlRoot = DOCUMENT_DEST + 'md/';
catas = fs.readdirSync(htmlRoot);
docList = fs.createWriteStream(DOCUMENT_DEST + 'doc_list.html');
// 构造内容对象
structure = util.scanOption(catas, htmlRoot);
htmls = structure && structure.htmls;
if (htmls.length) {
concatHTML();
}
// html片段拼接
function concatHTML () {
if (!htmls.length) {
docList.end();
util.generate(structure.lists);
return;
}
var currentfile = htmlRoot + htmls.shift();
stream = fs.createReadStream(currentfile);
stream.pipe(docList, {end: false});
stream.on('end', function () {
concatHTML();
});
}
});
// 默认任务
/* gulp.task('default', function () {
gulp.start('p');
}); */
// gulp.task('default', gulpsync.sync(['c', 'p', 'i']));
gulp.task('default', gulpsync.sync(['p', 'i']));
|
import React from 'react';
import { Button, Card } from 'react-bootstrap';
import './ProjectCard.css'
const ProjectCard = (props) => {
return (
<Card className="project-card-view">
<Card.Img variant="top" src={props.imgPath} alt="card-img" />
<Card.Body>
<Card.Title>{props.title}</Card.Title>
<Card.Text style={{ textAlign: "justify" }}>
{props.description}
</Card.Text>
<Button variant="primary" href={props.live} target="_blank">
<i className="cil-external-link"> </i>
{props.isBlog ? "View Blog" : "Live Project"}
</Button>
{" "}
<Button variant="primary" href={props.link} target="_blank">
<i className="cil-external-link"> </i>
{props.isBlog ? "View Blog" : "Code"}
</Button>
</Card.Body>
</Card>
);
};
export default ProjectCard; |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2016, Joyent, Inc.
*/
module.exports = {
ClaimTimeoutError: ClaimTimeoutError,
NoBackendsError: NoBackendsError,
ConnectionTimeoutError: ConnectionTimeoutError,
ConnectionClosedError: ConnectionClosedError,
PoolFailedError: PoolFailedError,
PoolStoppingError: PoolStoppingError,
ClaimHandleMisusedError: ClaimHandleMisusedError
};
const mod_util = require('util');
const mod_assert = require('assert-plus');
function ClaimHandleMisusedError() {
if (Error.captureStackTrace)
Error.captureStackTrace(this, ClaimHandleMisusedError);
this.name = 'ClaimHandleMisusedError';
this.message = 'CueBall claim handle used as if it was a ' +
'socket. Check the order and number of arguments in ' +
'your claim callbacks.';
}
mod_util.inherits(ClaimHandleMisusedError, Error);
function ClaimTimeoutError(pool) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, ClaimTimeoutError);
this.pool = pool;
this.name = 'ClaimTimeoutError';
this.message = 'Timed out while waiting for connection in pool ' +
pool.p_uuid + ' (' + pool.p_domain + ')';
}
mod_util.inherits(ClaimTimeoutError, Error);
function NoBackendsError(pool) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, NoBackendsError);
this.pool = pool;
this.name = 'NoBackendsError';
this.message = 'No backends available in pool ' + pool.p_uuid +
' (' + pool.p_domain + ')';
}
mod_util.inherits(NoBackendsError, Error);
function PoolFailedError(pool) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, PoolFailedError);
this.pool = pool;
this.name = 'PoolFailedError';
this.message = 'Pool ' + pool.p_uuid + ' (' + pool.p_domain + ') ' +
'has failed and cannot take new requests.';
}
mod_util.inherits(PoolFailedError, Error);
function PoolStoppingError(pool) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, PoolStoppingError);
this.pool = pool;
this.name = 'PoolStoppingError';
this.message = 'Pool ' + pool.p_uuid + ' (' + pool.p_domain + ') ' +
'is stopping and cannot take new requests.';
}
mod_util.inherits(PoolStoppingError, Error);
function ConnectionTimeoutError(fsm) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, ConnectionTimeoutError);
this.fsm = fsm;
this.backend = fsm.cf_backend;
this.name = 'ConnectionTimeoutError';
this.message = 'Connection timed out to backend ' +
JSON.stringify(this.backend);
}
mod_util.inherits(ConnectionTimeoutError, Error);
function ConnectionClosedError(fsm) {
if (Error.captureStackTrace)
Error.captureStackTrace(this, ConnectionClosedError);
this.fsm = fsm;
this.backend = fsm.cf_backend;
this.name = 'ConnectionClosedError';
this.message = 'Connection closed unexpectedly to backend ' +
JSON.stringify(this.backend);
}
mod_util.inherits(ConnectionClosedError, Error);
|
const BASE_URL = "http://localhost:4040";
function removeBook(bookId) {
const options = {
method: "DELETE",
};
return fetch(`${BASE_URL}/books/${bookId}`, options);
}
// removeBook(12)
// removeBook(5)
// ======================================
// async/await
// async function removeBook(bookId) {
// const url = `${BASE_URL}/books/${bookId}`;
// const options = {
// method: "DELETE",
// };
// const response = await fetch(url, options);
// return response;
// =====
// === если бек возвращает ответ
// const response = await fetch(url, options);
// const book = await response.json()
// return book;
// ====
// }
|
function solve(worker) {
if (worker.handsShaking === true) {
let modifiedWorker = {
weight: worker.weight,
experience: worker.experience,
bloodAlcoholLevel: worker.bloodAlcoholLevel + worker.weight * worker.experience * 0.1,
handsShaking: false,
}
return modifiedWorker;
}
return worker;
} |
/*
gulp the main.css for production.
Used for further processing of css file.
*/
var gulp = require('gulp');
var cssTask = function() {
return gulp.src('assets/css/main.css') // files to be bundled
.pipe(gulp.dest('production/assets/css')); // directory to be placed in
};
gulp.task('cssTask', cssTask);
module.exports = cssTask;
|
import AdminLogin from '../backstagePages/Login.vue'
import AdminIndex from '../backstagePages/Index.vue'
import AdminScores from '../backstagePages/websiteSetting/AdminScores.vue'/*会员积分*/
import AdminShopInfoSet from '../backstagePages/websiteSetting/AdminShopInfoSetting.vue'/*商城信息设置*/
import AdminShopBannerSetting from '../backstagePages/websiteSetting/AdminShopBannerSetting.vue'/*首页轮播图设置*/
import AdminBannerAdd from '../backstagePages/websiteSetting/AdminBannerAdd.vue'/*新增首页轮播图*/
import AdminBannerEdit from '../backstagePages/websiteSetting/AdminBannerEdit.vue'/*编辑首页轮播图*/
import AdminMemberTypeSetting from '../backstagePages/websiteSetting/AdminMemberTypeSetting.vue'/*会员类型设置*/
import AdminMemberEdit from '../backstagePages/websiteSetting/AdminMemberEdit.vue'/*编辑会员类型*/
import AdminMemberAdd from '../backstagePages/websiteSetting/AdminmemberAdd.vue'/*新增会员信息*/
import AdminGoodsSetting from '../backstagePages/websiteSetting/AdminGoodsSetting.vue'/*商品版块设置*/
import AdminGoodsPlateEdit from '../backstagePages/websiteSetting/AdminGoodsPlatEdit.vue'/*商品板块编辑*/
import AdminGoodsPlateAdd from '../backstagePages/websiteSetting/AdminGoodsPlateAdd.vue'/*商品板块的添加*/
import AdminGoodsTypeSetting from '../backstagePages/websiteSetting/AdminGoodsTypeSetting.vue'/*商品类别设置*/
import AdminGoodsTypeAdd from '../backstagePages/websiteSetting/AdminGoodsTypeAdd.vue'/*商品类别的添加*/
import AdminGoodsTypeEdit from '../backstagePages/websiteSetting/AdminGoodsTypeEdit.vue'
import AdminNews from '../backstagePages/websiteSetting/AdminNews.vue'/*新闻公告*/
import AdminNewsAdd from '../backstagePages/websiteSetting/AdminNewsAdd.vue'/*新增新闻公告*/
/*网站管理*/
import GoodsApproval from '../backstagePages/websiteManagement/GoodsApproval.vue'/*商品审批*/
import MembershipGradeSetting from '../backstagePages/websiteManagement/MembershipGradeSetting.vue'/*会员等级设置*/
import PasswordSetting from '../backstagePages/websiteManagement/PasswordSetting.vue'/*会员密码设置*/
import BackSearchUserInfoList from '../backstagePages/websiteManagement/BackSearchUserInfoList.vue'/*后台查看会员*/
import BackOrderProcess from '../backstagePages/websiteManagement/BackOrderProcess.vue'/*后台处理订单*/
import BackGoodsList from '../backstagePages/websiteManagement/BackGoodsList.vue'/*后台查看商品*/
/*菜单权限*/
import MenuManager from '../backstagePages/menuPermissions/MenuManager.vue'/*菜单定义*/
import PermissionSet from '../backstagePages/menuPermissions/PermissionSet.vue'/*菜单权限设置*/
/*个人中心*/
import AdminPersonInfo from '../backstagePages/personCenter/personInfo.vue'/*个人信息*/
import Test from '../backstagePages/websiteSetting/test2.vue'
const routers = [
{
path:'/admin/login',
component:AdminLogin
},
{
path:'/admin/index',
component:AdminIndex,
redirect: '/admin/index/scores',
children:[
{
path:'test' ,
component:Test
},
/*个人中心*/
{/*个人信息*/
path:'personInfo',
component:AdminPersonInfo
},
{/*会员积分*/
path:'scores',
component:AdminScores
},
{/*网站基本信息设置*/
path:'shopInfo',
component:AdminShopInfoSet
},
{/*首页轮播图设置*/
path:'shopBanner',
component:AdminShopBannerSetting
},
{/*新增首页轮播图*/
path:"shopBannerAdd",
component:AdminBannerAdd
},
{/*编辑首页轮播图*/
path:'shopBannerEdit',
component:AdminBannerEdit
},
{/*会员类型设置*/
path:'userType',
component:AdminMemberTypeSetting
},
{/*编辑会员*/
path:'memberEdit',
component:AdminMemberEdit
},
{/*新增会员*/
path:'memberAdd',
component:AdminMemberAdd
},
{/*商品板块设置*/
path:'goodsPlate',
component:AdminGoodsSetting
},
{/*商品板块编辑*/
path:'goodsPlateEdit',
component:AdminGoodsPlateEdit
},
{/*商品板块的添加*/
path:'goodsPlateAdd',
component:AdminGoodsPlateAdd
},
{/*商品类别设置*/
path:'goodsTypeList',
component:AdminGoodsTypeSetting
},
{/*商品类别的添加*/
path:'goodsTypeAdd',
component:AdminGoodsTypeAdd
},
{/*商品类别的编辑*/
path:'goodsTypeEdit',
component:AdminGoodsTypeEdit
},
{/*新闻公告*/
path:'shopNews',
component:AdminNews
},
{/*新增新闻公告*/
path:'newsAdd',
component:AdminNewsAdd
},
/*网站管理模块*/
{/*商品审批*/
path:'goodsManagerApprove',
component:GoodsApproval
},
{/*会员等级设置*/
path:'userTypeUpgrade',
component:MembershipGradeSetting
},
{/*会员密码设置*/
path:'userResetPass',
component:PasswordSetting
},
{/*后台查看会员*/
path:'backSearchUserInfoList',
component:BackSearchUserInfoList
},
{/*后台处理订单*/
path:'backOrderProcess',
component:BackOrderProcess
},
{/*后台查看商品*/
path:'backGoodsList',
component:BackGoodsList
},
/*菜单权限*/
{/*菜单定义*/
path:'menuManager',
component:MenuManager
},
{/*权限定义*/
path:'permissionSet',
component:PermissionSet
}
]
}
]
export default routers
|
import React from 'react';
import { MyStylesheet } from './styles'
import Construction from './construction'
class Landing {
getslidebyid(id) {
const landing = new Landing()
const slides = landing.getslides.call(this)
let myslide = false;
if (slides) {
// eslint-disable-next-line
slides.map(slide => {
if (slide.id === id) {
myslide = slide;
}
})
}
return myslide;
}
getmainslide() {
const construction = new Construction();
const navigation = construction.getNavigation.call(this)
if (navigation) {
if (navigation.position === 'closed') {
if (this.state.width > 1200) {
return ({ width: '1087px', height: 'auto' })
} else if (this.state.width > 800) {
return ({ width: '762px', height: 'auto' })
} else {
return ({ width: '356px', height: 'auto' })
}
} else if (navigation.position === 'open') {
if (this.state.width > 1200) {
return ({ width: '800px', height: 'auto' })
} else if (this.state.width > 800) {
return ({ width: '600px', height: 'auto' })
} else {
return ({ width: '300px', height: 'auto' })
}
}
}
}
getslides() {
const slides = () => {
return ([
{
title: 'Employees',
id: 'employees',
url: 'http://civilengineer.io/construction/slides/employees.png',
caption: `Keeps track of the Employees that are part of your company `
},
{
title: 'View Employee',
id: 'viewemployee',
url: 'http://civilengineer.io/construction/slides/viewemployee.png',
caption: `Adds benefits to the Employee to determine their labor rate. Adds accounts to benefits. Shows the percent distribution for the labor rate for each account. `
},
{
title: 'Accounts',
id: 'accounts',
url: 'http://civilengineer.io/construction/slides/accounts.png',
caption: `Create accounts for your employee benefits, equipment, and materials `
},
{
title: 'View Account',
id: 'viewaccount',
url: 'http://civilengineer.io/construction/slides/viewaccount.png',
caption: `Shows the balance per account `
},
{
title: 'Equipment',
id: 'equipment',
url: 'http://civilengineer.io/construction/slides/equipment.png',
caption: `Add your company equipment `
},
{
title: 'View Equipment',
id: 'viewequipment',
url: 'http://civilengineer.io/construction/slides/viewequipment.png',
caption: `Enter equipment ownership costs. Special cost formula determines the equipment rate. `
},
{
title: 'Materials',
id: 'materials',
url: 'http://civilengineer.io/construction/slides/materials.png',
caption: `Add your material list for your company. `
},
{
title: 'View Material',
id: 'viewmaterial',
url: 'http://civilengineer.io/construction/slides/viewmaterial.png',
caption: `Update the unit and unit price for each material. Update the account id for each material `
},
{
title: 'Project',
id: 'project',
url: 'http://civilengineer.io/construction/slides/project.png',
caption: `Shows the location and the scope of work. Has links to the other project components. `
},
{
title: 'Schedule',
id: 'Schedule',
url: 'http://civilengineer.io/construction/slides/schedule.png',
caption: `Enter and View project schedule. Assigns schedule to employees, determines cost. `
},
{
title: 'Bid Schedule',
id: 'proposals',
url: 'http://civilengineer.io/construction/slides/bidschedule.png',
caption: `Your Project Bid Schedule Broken Down Per Line Item Per Code Simply Enter your Units to Create your Unit Price `
},
{
title: 'Bid Schedule Line Item',
id: 'bidschedulelineitem',
url: 'http://civilengineer.io/construction/slides/bidschedulelineitem.png',
caption: `View Each Bid Schedule Line Item. Adjust rates and Profit Factor to create the bid amount `
},
{
title: 'Actual',
id: 'actual',
url: 'http://civilengineer.io/construction/slides/actual.png',
caption: `Enter your actual costs for the project. `
},
{
title: 'View Bid',
id: 'bid',
url: 'http://civilengineer.io/construction/slides/bid.png',
caption: `Your actual Construction Bid to Be Send to the PM for Payment. Produces Itemized Construction Invoice using your Actual Costs. `
},
{
title: 'Bid Line Item',
id: 'bidlineitem',
url: 'http://civilengineer.io/construction/slides/bidlineitem.png',
caption: `View Each Line Item in your Bid. Adjust any rates and add your profit to produce the actual bid price. `
}
])
}
return slides();
}
showslide(slide) {
const construction = new Construction();
const styles = MyStylesheet();
const smallslide = () => {
const construction = new Construction();
const navigation = construction.getNavigation.call(this)
if (navigation.position === 'closed') {
if (this.state.width > 1200) {
return ({ width: '362px', height: 'auto' })
} else if (this.state.width > 800) {
return ({ width: '254px', height: 'auto' })
} else {
return ({ width: '178px', height: 'auto' })
}
} else if (navigation.position === 'open') {
if (this.state.width > 1200) {
return ({ width: '240px', height: 'auto' })
} else if (this.state.width > 800) {
return ({ width: '180px', height: 'auto' })
} else {
return ({ width: '120px', height: 'auto' })
}
}
}
const regularFont = construction.getRegularFont.call(this)
return(
<div style={{...styles.generalFlex}} key={slide.id}>
<div style={{...styles.flex1}}>
<div style={{...styles.generalContainer,...styles.showBorder,...smallslide(),...styles.marginAuto}} onClick={()=>{this.setState({activeslideid:slide.id})}}>
<img src={slide.url} alt={slide.title} style={{...smallslide()}} />
</div>
<div style={{...styles.generalContainer,...styles.marginAuto,...styles.alignCenter}} onClick={()=>{this.setState({activeslideid:slide.id})}}>
<span style={{...styles.generalFont,...regularFont}}>{slide.title}</span>
</div>
</div>
</div> )
}
showslides() {
const landing = new Landing()
const slides = landing.getslides.call(this);
const styles = MyStylesheet();
const allslides = [];
if(slides) {
// eslint-disable-next-line
slides.map(slide=> {
allslides.push(landing.showslide.call(this,slide))
})
}
const templatecolumns = () => {
if(this.state.width>800) {
return (styles.triplegrid)
} else {
return (styles.doublegrid)
}
}
return(<div style={{...styles.generalGrid,...templatecolumns(),...styles.bottomMargin15}}>
{allslides}
</div>)
}
showlanding() {
const landing = new Landing()
const construction = new Construction();
const styles = MyStylesheet();
const mainslide = landing.getmainslide.call(this)
const headerFont = construction.getHeaderFont.call(this)
const regularFont = construction.getRegularFont.call(this)
const myslide = () => {
if(this.state.activeslideid) {
return(landing.getslidebyid.call(this,this.state.activeslideid))
} else {
return false;
}
}
const showmainslide = () => {
if(myslide()) {
return(<div style={{...styles.generalContainer,...styles.showBorder,...mainslide,...styles.marginAuto}}>
<img src={myslide().url} alt={myslide().title} style={{...mainslide}} />
</div> )
}
}
const showmaintitle = () => {
if(myslide()) {
return(<span style={{...styles.generalFont,...headerFont}}>{myslide().title}</span>)
}
}
const showmaincaption = () => {
if(myslide()) {
return(<span style={{...styles.generalFont,...regularFont}}>{myslide().caption}</span>)
}
}
return (
<div style={{ ...styles.generalFlex }}>
<div style={{ ...styles.flex1 }}>
<div style={{ ...styles.generalFlex,...styles.bottomMargin15 }}>
<div style={{ ...styles.flex1, ...styles.alignCenter }}>
{showmaintitle()}
</div>
</div>
<div style={{ ...styles.generalFlex,...styles.bottomMargin15 }}>
<div style={{ ...styles.flex1, ...styles.alignCenter }}>
{showmainslide()}
</div>
</div>
<div style={{ ...styles.generalFlex,...styles.bottomMargin15 }}>
<div style={{ ...styles.flex1, ...styles.alignCenter }}>
{showmaincaption()}
</div>
</div>
{landing.showslides.call(this)}
</div>
</div>
)
}
}
export default Landing; |
$(document).ready(function () {
$("#problemList").on('change', function () {
var val = $("#problemList").val();
$.ajax({
url : '/api/get_tasks',
dataType: "json",
data: { val : val },
success : function (data) {
$("#tasks tr").remove();
var html = "<table data-toggle='table' class=' table table-sm table-bordered'>";
html+= "<thead><tr><th scope='col' data-checkbox='true' style='width: 5%'></th>";
html+="<th scope='col'>Task title</th>";
html+="</tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
html+="<tr>";
html+="<td scope='row' align='center'>" + "<span class='align-middle'>" +
"<input type='checkbox' checked value=" + data[i].id +
" style='width: 1.10rem !important;" +
"height: 1.10rem !important;'/>" + "</span></td>";
html+="<td>" + data[i].name + "</td>";
html+="</tr>";
}
html+="</tbody></table>";
$("#tasks").html(html);
$("#gettools").css("visibility", "visible");
},
error : function () {
alert("error get tasks");
}
})
})
});
|
$(function(){
getLocationFun(); // 获取位置信息上传
var pagenum = 1,totalNum = "";
var logininf = localStorage.getItem("logininf");
if(logininf == "" || logininf == null || logininf == "null" || logininf == undefined || logininf == "undefined"){
}else{
logininf = JSON.parse(localStorage.getItem("logininf"));
}
var ua = window.navigator.userAgent.toLowerCase();
/*if(ua.match(/MicroMessenger/i) == 'micromessenger'){
$(".header").show();
}*/
$(".main").scroll(function(){
var scrollNum = document.documentElement.clientWidth / 7.5;
if($(".main .orderList").outerHeight() - $(".main").scrollTop() - $(".main").height() < 10){
if($(".ajax-loder-wrap").length > 0){
return false;
}
if(pagenum < totalNum){
pagenum = parseInt(pagenum) + parseInt(1)
pageInf.pageInfo.pageNum = pagenum;
orderListFun()
}
}
})
$(".header .right").click(function(){
$(".searchLayer").show();
})
$(".header .right .searchBtn").click(function(){
$(".searchLayer").hide();
})
var pageInf = {
"startCreateTime":getQueryTime(14),
"endCreateTime":getCurrentTime2("0"),
"isException":true,
"carDrvContactTel":logininf.mobilePhone,
"pageInfo": {
pageNum: pagenum,
pageSize: 30
}
};
orderListFun();
function orderListFun() {
$.ajax({
url: tmsUrl + '/driver/query/DriverHeadOrderTaskInfoPage',
type: "post",
contentType: 'application/json',
beforeSend:function(){
$(".main").append('<div class="ajax-loder-wrap"><img src="../images/ajax-loader.gif" class="ajax-loader-gif"/><p class="loading-text">加载中...</p></div>');
},
data: JSON.stringify(pageInf),
success: function(data) {
totalNum = data.pageInfo.pages;
$(".ajax-loder-wrap").remove();
var orderData = data.result;
var orderlist = "";
var paymentItem = "";
var classname = "";
tasklistData = data.result;
if(data.result.length == 0){
var timer1 = setTimeout(function(){
$(".orderCon").append('<p class="noContent" style="width: 3rem; height: auto; margin: 0 auto; padding-top: 0.36rem;">'+
'<img src="images/noContent.png" alt="" style="width: 3rem; height: auto; display: block;"/>'+
'</p>');
},600)
}else{
for(var i = 0; i < data.result.length; i++) {
if(data.result[i].exceptionStatus == "1" || data.result[i].exceptionStatus == "2"){
classname = "excpli"
}else{
classname = "";
}
if(data.result[i].actCode == "DIST"){
data.result[i].actCode = "接单"
}
if(data.result[i].actCode == "COFM"){
data.result[i].actCode = "装车"
}
if(data.result[i].actCode == "LONT"){
data.result[i].actCode = "配送"
}
if(data.result[i].actCode == "ACPT"){
data.result[i].actCode = "签收"
}
if(data.result[i].actCode == "EXCP"){
data.result[i].actCode = "异常"
}
//单位换算
//体积
if(data.result[i].volumeUnit == "CM3"){
data.result[i].totalVolume = (data.result[i].totalVolume/parseInt(1000000)).toFixed(2);
}
//重量
if(data.result[i].weightUnit == "TN"){
data.result[i].totalWeight = (data.result[i].totalWeight*parseFloat(0.4535924)).toFixed(2);
}else if(data.result[i].weightUnit == "LB"){
data.result[i].totalWeight = (data.result[i].totalWeight*parseFloat(1000)).toFixed(2);
}
//价值
if(data.result[i].currency == "USD"){
data.result[i].totalAmount = (data.result[i].totalAmount*parseFloat(6.5191)).toFixed(2);
}
// 付款方式
if(orderData[i].payment == "spot"){
paymentItem += '<p class="receiverAddress">收款方式:现付</p>'
}else if(orderData[i].payment == "collect"){
paymentItem += '<p class="receiverAddress">收款方式:到付</p>'
}else if(orderData[i].payment == "voucher"){
paymentItem += '<p class="receiverAddress">收款方式:凭单回复</p>'
}
orderlist += '<li class="'+classname+'" ordernum=' + orderData[i].orderNo + ' orderid=' + orderData[i].omOrderId + ' actCode=' + orderData[i].actCode + ' >'+
'<input type="hidden" class="weightnum" value="'+orderData[i].totalWeight+'" />'+
'<input type="hidden" class="weightunit" value="'+orderData[i].weightUnit+'" />'+
'<input type="hidden" class="volumenum" value="'+orderData[i].totalVolume+'" />'+
'<input type="hidden" class="volumeunit" value="'+orderData[i].volumeUnit+'" />'+
'<input type="hidden" class="amountnum" value="'+orderData[i].totalAmount+'" />'+
'<div class="right">'+
'<p class="ordernum">订单号:'+orderData[i].orderNo+'</p>'+
'<p class="ordernum"style="line-height:0.36rem;height:0.4rem;">原单号:'+orderData[i].customerOriginalNo+'</p>'+
'<p class="ordernum"style="line-height:0.36rem;height:0.4rem;">班次号:'+orderData[i].tfoOrderNo+'</p>'+
'<p class="shipAddress">数量:'+orderData[i].totalQty+ ' 重量:'+orderData[i].totalWeight+'kg 体积:'+orderData[i].totalVolume+'m³ <br/>价值:'+orderData[i].totalAmount+'元</p>'+
'<p class="receiverAddress">客户:'+orderData[i].stoPartyName+' 配送日期:'+timestampToTime1(orderData[i].shpDtmTime)+' </p>'+
'<p class="receiverAddress">收货地址:'+orderData[i].stoAddress+'</p>'+paymentItem+
'</div>'+
'<div class="orderHandle">'+
'<a href="javascript:;" class="truck"></a>'+
'<p class="photo">'+
'<img src="images/top_pic.png" alt="" />'+
'<span class="txt">上传附件图片</span>'+
'</p>'+
'</div>'+
'<p class="round"></p>'+
'</li>'
}
$(".main .orderCon .orderList").append(orderlist);
}
},
error: function(xhr) {
}
})
}
//获取任务数据 结束
//输入搜索条件查询
$(".searchCon .searchbtn").click(function(){
getSearchInf("1");
})
$(".mouthSearch p").click(function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
if($(this).index() == 0){
getSearchInf("0","-2","+1");
}else if($(this).index() == 1){
getSearchInf("0","-5","-2");
}
})
function getSearchInf(isGetTime,startmouthnum,endmouthnum){
$(".main .orderCon .orderList").html("");
$(".noContent").remove();
$(".searchLayer").hide();
console.log($("#startTime").val());
pageNumVal = 1;
totalNum = 1;
var orderNoInp = $(".searchCon ul li .orderNo").val().trim();
var trackingNoInp = $(".searchCon ul li .trackingNo").val().trim();
var actCodeSelect = $(".searchCon ul li .statusSelect").val().trim();
var startCreateTime = $("#startTime").val().trim();
var endCreateTime = $("#endTime").val().trim();
console.log(trackingNoInp);
if(isGetTime == 1){
if(startCreateTime == "" || startCreateTime == "null" || startCreateTime == null){
}else{
pageInf.startCreateTime = startCreateTime
}
if(endCreateTime == "" || endCreateTime == "null" || endCreateTime == null){
}else{
pageInf.endCreateTime = endCreateTime
}
}else{
pageInf.endCreateTime = getCurrentTime(endmouthnum);
pageInf.startCreateTime = getCurrentTime(startmouthnum);
}
console.log(123);
pageInf.carDrvContactTel = logininf.mobilePhone
pageInf.orderNo = orderNoInp
pageInf.trackingNo = trackingNoInp
pageInf.actCode = actCodeSelect
pageInf.pageInfo.pageNum = "1";
orderListFun();
clickbtnTxt = "附件图片"
}
//关闭订单详细弹窗
$(".maskLayer .popup3 .popupCon .infHint .closeorderinf").click(function(){
$(".maskLayer").hide();
$(".maskLayer .popup3").hide();
})
//关闭订单提交弹窗
$(".maskLayer .popup2 .orderCon .closebtn").click(function(){
$(".maskLayer").hide();
$(".maskLayer .popup2").hide();
$(".maskLayer .popup2 .orderDesc .orderTextBox").hide();
})
$(".popup3 .popupCon .popuptitle ul").on("click","li .seeAnnex span",function(){
$(".popup3").hide();
$(".popup6").show();
})
$(".maskLayer .popup6 .popupTitle a").click(function(){
$(".popup6").hide()
$(".maskLayer").hide();
})
var seeOrderDetailId = "";
//点击获取详情
$(".main .orderCon").on("click",".orderList li",function(e){
var orderid = $(this).attr("orderid");
var ordernum = $(this).attr("ordernum");
$(".maskLayer").show();
$(".maskLayer .popup3").show();
$.ajax({
url: omsUrl + '/driver/query/OrderInfoDetail?orderId='+orderid+'&orderNo='+ordernum,
type: "get",
beforeSend:function(){
loadData('show');
},
success: function(data) {
getGoodsList(data.result.orderItemList);
getOrderReceiptImg(data.result.imgList);
getOrderBaseInf(data.result);
orderReceiptImgList = data.result.imgList;
loadData('hide');
}
})
})
function getGoodsList(goodslistData){
var sortList = "";
for(var i = 0; i < goodslistData.length;i++){
sortList += '<ul>'+
'<li>'+goodslistData[i].itemName+'</li>'+
'<li>x'+goodslistData[i].qty+'</li>'+
'<li>'+goodslistData[i].weight+'</li>'+
'</ul>'
}
$(".ordersortList").html(sortList);
}
var imgLiEle = "";
function getOrderReceiptImg(receiptImgList){
imgLiEle = "";
var imgListPic = "";
if(receiptImgList == "" ||receiptImgList == null || receiptImgList == "null"){
imgLiEle = "暂无附件图片";
}else{
for(var i = 0; i < receiptImgList.length;i++){
imgLiEle += '<span><img src="'+ ImgWebsite + receiptImgList[i].extValue+'" alt="" /></span>'
imgListPic += ' <li class="swiper-slide"><img src="'+ ImgWebsite + receiptImgList[i].extValue+'" alt="" /></li>'
}
}
$(".maskLayer .popup5 .imgList").html(imgListPic);
$(".swiper-container .imgList").html(imgListPic);
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
loop: true,
observer:true,
observeParents:true
});
}
function getOrderBaseInf(tasklistData){
if(tasklistData.exceRemarkList == "null" || tasklistData.exceRemarkList == null || tasklistData.exceRemarkList == ""){
var actRemark = ["-","-","-","-"];
}else{
var actRemarkLen = tasklistData.exceRemarkList.length - 1;
console.log(actRemarkLen);
console.log(tasklistData.exceRemarkList[actRemarkLen]);
//var actRemark = tasklistData[i].actRemark
var actRemark = tasklistData.exceRemarkList[actRemarkLen].note.split(",");
}
if(tasklistData.exceptionStatus == "0"){
tasklistData.exceptionStatus = "正常";
}
if(tasklistData.stoAddress == "null" || tasklistData.stoAddress == null){
tasklistData.stoAddress = "-"
}
if(tasklistData.sfrAddress == "null" || tasklistData.sfrAddress == null){
tasklistData.sfrAddress = "-"
}
if(tasklistData.actCode == "DIST"){
tasklistData.actCode = "接单"
}else if(tasklistData.actCode == "COFM"){
tasklistData.actCode = "装车"
}else if(tasklistData.actCode == "LONT"){
tasklistData.actCode = "配送"
}else if(tasklistData.actCode == "ACPT"){
tasklistData.actCode = "签收"
}else if(tasklistData.actCode == "EXCP"){
tasklistData.actCode = "异常"
}
if(tasklistData.payStatus == "0"){
tasklistData.payStatus = "未支付"
}else if(tasklistData.payStatus == "1"){
tasklistData.payStatus = "已支付"
}else if(tasklistData.payStatus == "2"){
tasklistData.payStatus = "部分支付"
}
//异常订单详细页面展示
if(tasklistData.exceptionStatus == "1" || tasklistData.exceptionStatus == "2" || tasklistData.exceptionStatus == "异常"){
tasklistData.exceptionStatus = "异常"
var orderdetail = '<li>'+
'<span class="txt">订单号</span>'+
'<p class="inf">'+tasklistData.orderNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">原单号</span>'+
'<p class="inf">'+tasklistData.customerOriginalNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">班次号</span>'+
'<p class="inf">'+tasklistData.tfoOrderNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">收货地址</span>'+
'<p class="inf">'+tasklistData.stoAddress+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">订单当前状态</span>'+
'<p class="inf">'+tasklistData.actCode+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">订单是否异常</span>'+
'<p class="inf">'+tasklistData.exceptionStatus+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">异常描述</span>'+
'<p class="inf">'+actRemark[0]+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">处理意见</span>'+
'<p class="inf">'+actRemark[1]+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">客户姓名</span>'+
'<p class="inf">'+actRemark[2]+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">客户电话</span>'+
'<p class="inf">'+actRemark[3]+'</p>'+
'</li>'+
'<li>'+
'<span class="txt" style="display:block;float:none;">附件图片</span>'+
'<p class="inf seeAnnex">'+ imgLiEle +'</p>'+
'</li>'
}else{
console.log("imgLiEle" + imgLiEle);
tasklistData.exceptionStatus = "正常";
var orderdetail = '<li>'+
'<span class="txt">订单号</span>'+
'<p class="inf">'+tasklistData.orderNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">原单号</span>'+
'<p class="inf">'+tasklistData.customerOriginalNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">班次号</span>'+
'<p class="inf">'+tasklistData.tfoOrderNo+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">收货地址</span>'+
'<p class="inf">'+tasklistData.stoAddress+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">订单当前状态</span>'+
'<p class="inf">'+tasklistData.actCode+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">订单是否异常</span>'+
'<p class="inf">'+tasklistData.exceptionStatus+'</p>'+
'</li>'+
'<li>'+
'<span class="txt">支付状态</span>'+
'<p class="inf">'+tasklistData.payStatus+'</p>'+
'</li>'+
'<li>'+
'<span class="txt" style="display:block;float:none;">附件图片</span>'+
'<p class="inf seeAnnex">'+ imgLiEle +'</p>'+
'</li>'
}
$(".popuptitle ul").html(orderdetail);
}
function getCurrentTime(mouthParmes){
function p(s) {
return s < 10 ? '0' + s: s;
}
var myDate = new Date();
//获取当前年
var year=myDate.getFullYear();
//获取当前月
var month=myDate.getMonth() + parseInt(mouthParmes);
var month1=myDate.getMonth();
//获取当前日
var date = myDate.getDate();
var date1 = myDate.getDate() - 1;
var h = myDate.getHours(); //获取当前小时数(0-23)
var m = myDate.getMinutes(); //获取当前分钟数(0-59)
var s = myDate.getSeconds();
var todayTime = year+'-'+p(month)+'-'+p(date);
return todayTime;
}
function getCurrentTime2(mouthParmes){
var date1 = new Date();
date1.setMonth(date1.getMonth() - mouthParmes);
var year1 = date1.getFullYear();
var month1 = date1.getMonth() + 1;
var day = date1.getDate();
var sDate;
month1 = (month1 < 10 ? "0" + month1 : month1);
day = (day < 10 ? ('0' + day) : day);
var sDate = (year1.toString() + '-' + month1.toString() + '-' + day.toString());
return sDate;
}
}) |
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var chai = require('chai');
var chaiHTTP = require('chai-http');
var garageController = require('../../garage/garage.controller');
var userController = require('../users.controller');
chai.use(chaiHTTP);
var app = require('../../app').app;
before( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
console.log('Limpiando base de datos...');
_context.next = 3;
return userController.deleteUserDB();
case 3:
_context.next = 5;
return garageController.deleteGarageDB();
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
})));
describe('Suite de pruebas auth', function () {
var testCredential = {
user: 'luis_forerop',
password: 'hola mundo 123'
};
var testFakeCredential = {
user: 'luis_forerop',
password: 'hola mundo 321 no es la clave'
};
var testNoUserExist = {
user: 'Pepe',
password: 'hola mundo 321 no es la clave'
};
it('should return 400 when no data is provided', function (done) {
chai.request(app).post('/auth/login').end(function (err, res) {
chai.assert.equal(res.statusCode, 400);
done();
});
});
it('should return 400 when no user or password is provided', function (done) {
console.log('hacemos la petici�n a login enviando solo usuario');
chai.request(app).post('/auth/login').set('Content-Type', 'application/json').send({
nombre: 'pepe'
}).end(function (err, res) {
chai.assert.equal(res.statusCode, 400);
done();
});
}); // TEST PARA SIGN UP
it('should return 200 when user signup and 401 if user exist', function (done) {
chai.request(app).post('/auth/signUp').set('Content-Type', 'application/json').send(testCredential).end(function (err, res) {
chai.assert.equal(res.statusCode, 200);
console.log('Iniciamos test para user exist');
chai.request(app).post('/auth/signUp').set('Content-Type', 'application/json').send(testCredential).end(function (err, res) {
console.log('este esl body en user exist', res.body);
chai.assert.equal(res.statusCode, 409);
done();
});
});
}); // TESTS PARA LOGIN
// Los test de login van a pasar porque nos registramos con el user y password de prueba
it('should return 401 when password is wrong', function (done) {
chai.request(app).post('/auth/login').set('Content-Type', 'application/json') // Enviamos por header el tipo de contenido que va a recibir
.send(testFakeCredential) // Enviamos la informaci�n del usuario por body
.end(function (err, res) {
console.log('estas son las credenciales falsas', testFakeCredential);
chai.assert.equal(res.statusCode, 401);
done();
});
});
it('should return 401 when user no exist', function (done) {
chai.request(app).post('/auth/login').set('Content-Type', 'application/json') // Enviamos por header el tipo de contenido que va a recibir
.send(testNoUserExist) // Enviamos la informaci�n del usuario por body
.end(function (err, res) {
console.log('Este es el test y las credenciales son:', testNoUserExist);
chai.assert.equal(res.statusCode, 401);
done();
});
});
it('should return 200 and token for succesful login', function (done) {
chai.request(app).post('/auth/login').set('Content-Type', 'application/json') // Enviamos por header el tipo de contenido que va a recibir
.send(testCredential) // Enviamos la informaci�n del usuario por body
.end(function (err, res) {
chai.assert.equal(res.statusCode, 200);
done();
});
});
/* Devolvemos 200 cuando el usuario tiene un token
* Si el token es v�lido, devolvemos un 200
* Para implementarlo correctamente debemos combinar diferentes llamadas
*/
it('should return 200 when jwt is valid', function (done) {
chai.request(app) // Primero corremos un test para loguear un usuario
.post('/auth/login').set('content-type', 'application/json') // Enviamos por header el tipo de contenido que va a recibir
.send(testCredential) // Enviamos la informaci�n del usuario por body
// Tan pronto como terminamos de hacer el login, podemos hacer un request
.end(function (err, res) {
chai.assert.equal(res.statusCode, 200); // Comparamos si el request es 200
// Evaluamos la informaci�n que estamos recibiendo
//console.log('Este es el c�digo ' + res.statusCode);
//console.log('Este es el token ' + res.body.token);
chai.request(app).get('/garage').set('Authorization', "JWT ".concat(res.body.token), 'content-type', 'application/json') // Enviamos el token en el header .set('Authorization', 'JWT token')
.send(res.body).end(function (err, res) {
chai.assert.equal(res.statusCode, 200); // Si el token es v�lido, devolvemos 200
done();
});
});
});
}); |
// test
export const getCount = state => {
return state.count
}
export const getLangs = state => {
return state.langs
} |
import React from 'react';
import './Welcome.css';
export default function Welcome() {
return (
<section className='Welcome'>
<h1 className='Welcome__heading'>Welcome</h1>
<h4 className='Welcome__subheading'>
Search for images and then run them through the TensorFlow.js MobileNet
model to measure its prediction accuracy
</h4>
</section>
);
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import TestPage from './test/TestPage';
ReactDOM.render(
//This is a comment test
<React.StrictMode>
<TestPage />
</React.StrictMode>,
document.getElementById('root')
); |
import React from 'react';
import './Page1.css';
import SpeechBubble from "../components/Speechbubble";
// Intro
function Page1 (props) {
return (
<div name ='page1' className='fullPage flexFixedSize flexContainerRow Page1_container'>
<div className='page1_text'>
<SpeechBubble top={true} text={[
"Did you know you already have a digital identity?",
"Everything from your smartphone usage, to your social",
"media activity, captures data about you...",
"but how is it used?"
]}/>
<div className="heading centered fiftyfive">
What is a digital identity?
</div>
<div className="text centered fiftyfive">
Digital data sources are already used to build your <br/>
digital identity, painting a picture of who you are, <br/>
what you like, and how likely you are to behave in a <br/>
certain way. Some examples include:
</div>
<div className="icons">
<div className="icon">
<svg className="logo" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 265 265" style={{"enable-background":"new 0 0 265 265;"}} xmlSpace="preserve">
<path className="st0" d="M247.2,3.7H17.9c-7.8,0-14.2,6.4-14.2,14.2v229.3c0,7.9,6.4,14.2,14.2,14.2h123.4v-99.8h-33.6v-38.9h33.6V94
c0-33.3,20.3-51.4,50-51.4c14.2,0,26.5,1.1,30,1.5v34.8h-20.6c-16.1,0-19.3,7.7-19.3,18.9v24.8h38.5l-5,38.9h-33.5v99.8H247
c7.9,0,14.2-6.4,14.2-14.2V17.9C261.3,10.1,254.9,3.7,247.2,3.7z"/>
</svg>
your <br/>
facebook <br/>
posts
</div>
<div className={"icon"}>
<svg className="logo" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 44 265 180" xmlSpace="preserve">
<path className="st0" d="M217.5,44.4H47.2c-24.1,0-43.6,19.5-43.6,43.6V179c0,24.1,19.5,43.6,43.6,43.6h170.3
c24.1,0,43.6-19.5,43.6-43.6V87.9C261.1,63.9,241.6,44.4,217.5,44.4z M143.3,153.3l-38.6,19.8V93.9l38.6,19.8l38.6,19.8L143.3,153.3
z"/>
</svg>
your <br/>
youtube <br/>
comments
</div>
<div className="icon">
<svg className="logo" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 265 265" style={{"enable-background":"new 0 0 265 265;"}} xmlSpace="preserve">
<path className="st0" d="M151.3,132.5c0,10.4-8.4,18.8-18.8,18.8c-10.4,0-18.8-8.4-18.8-18.8s8.4-18.8,18.8-18.8
S151.3,122.1,151.3,132.5z"/>
<path className="st0" d="M206.9,132.5c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8s8.4-18.8,18.8-18.8S206.9,122.1,206.9,132.5z"/>
<path className="st0" d="M262.6,132.5c0,10.4-8.4,18.8-18.8,18.8c-10.4,0-18.8-8.4-18.8-18.8s8.4-18.8,18.8-18.8
C254.1,113.6,262.6,122.1,262.6,132.5z"/>
<path className="st0" d="M95.7,132.5c0,10.4-8.4,18.8-18.8,18.8S58,142.9,58,132.5s8.4-18.8,18.8-18.8S95.7,122.1,95.7,132.5z"/>
<path className="st0" d="M151.3,243.8c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8c0-10.4,8.4-18.8,18.8-18.8
S151.3,233.4,151.3,243.8z"/>
<path className="st0" d="M151.3,21.2c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8s8.4-18.8,18.8-18.8S151.3,10.8,151.3,21.2z"/>
<path className="st0" d="M151.3,190.4c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8c0-10.4,8.4-18.8,18.8-18.8S151.3,180,151.3,190.4z
"/>
<path className="st0" d="M206.9,190.4c0,10.4-8.4,18.8-18.8,18.8c-10.4,0-18.8-8.4-18.8-18.8c0-10.4,8.4-18.8,18.8-18.8
C198.5,171.5,206.9,180,206.9,190.4z"/>
<path className="st0" d="M95.7,190.4c0,10.4-8.4,18.8-18.8,18.8S58,200.8,58,190.4c0-10.4,8.4-18.8,18.8-18.8S95.7,180,95.7,190.4z"/>
<path className="st0" d="M151.3,73.8c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8S122.1,55,132.5,55S151.3,63.4,151.3,73.8z"/>
<path className="st0" d="M206.9,73.8c0,10.4-8.4,18.8-18.8,18.8c-10.4,0-18.8-8.4-18.8-18.8S177.7,55,188.1,55
C198.5,55,206.9,63.4,206.9,73.8z"/>
<path className="st0" d="M95.7,73.8c0,10.4-8.4,18.8-18.8,18.8S58,84.2,58,73.8S66.4,55,76.8,55S95.7,63.4,95.7,73.8z"/>
<path className="st0" d="M40.1,132.5c0,10.4-8.4,18.8-18.8,18.8s-18.8-8.4-18.8-18.8s8.4-18.8,18.8-18.8S40.1,122.1,40.1,132.5z"/>
</svg>
your <br/>
fitbit <br/>
steps
</div>
<div className="icon">
<svg className="logo" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 265 265" style={{"enable-background":"new 0 0 265 265;"}} xmlSpace="preserve">
<g>
<g>
<path className="st0" d="M132.5,70C98.1,70,70,98.1,70,132.5s28,62.5,62.5,62.5s62.5-28,62.5-62.5S166.9,70,132.5,70z M132.5,186.1
c-29.6,0-53.6-24.1-53.6-53.6s24.1-53.6,53.6-53.6s53.6,24.1,53.6,53.6S162.1,186.1,132.5,186.1z"/>
<path className="st0" d="M174.4,4.6H90.6c-47.4,0-86,38.6-86,86v83.8c0,47.4,38.6,86,86,86h83.8c47.4,0,86-38.6,86-86V90.6
C260.4,43.2,221.8,4.6,174.4,4.6z M251.5,174.4c0,42.5-34.6,77.2-77.2,77.2H90.6c-42.5,0-77.2-34.6-77.2-77.2V90.6
c0-42.5,34.6-77.2,77.2-77.2h83.8c42.5,0,77.2,34.6,77.2,77.2C251.5,90.6,251.5,174.4,251.5,174.4z"/>
<path className="st0" d="M202.3,42.5c-11.1,0-20.2,9.1-20.2,20.2s9.1,20.2,20.2,20.2s20.2-9.1,20.2-20.2S213.5,42.5,202.3,42.5z
M202.3,74.1c-6.3,0-11.4-5.1-11.4-11.4s5.1-11.4,11.4-11.4c6.3,0,11.4,5.1,11.4,11.4S208.6,74.1,202.3,74.1z"/>
</g>
</g>
</svg>
your <br/>
instagram <br/>
hashtags
</div>
<div className={"icon"}>
<svg version="1.1" className="logo"
id="svg1936" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 265 265"
style={{"enable-background":"new 0 0 265 265;"}} xmlSpace="preserve">
<path id="path8" className="st0" d="M238.3,129.6c-28.7,21.1-70.2,32.4-106,32.4
c-50.2,0-95.3-18.6-129.5-49.4c-2.7-2.4-0.3-5.7,2.9-3.8c36.9,21.5,82.5,34.4,129.6,34.4c31.8,0,66.7-6.6,98.8-20.2
C239,120.8,243,126.1,238.3,129.6"/>
<path id="path10" className="st0" d="M250.2,115.9c-3.7-4.7-24.2-2.2-33.5-1.1
c-2.8,0.3-3.2-2.1-0.7-3.9c16.4-11.5,43.3-8.2,46.4-4.3c3.1,3.9-0.8,30.8-16.2,43.7c-2.4,2-4.6,0.9-3.6-1.7
C246.1,140,253.9,120.6,250.2,115.9"/>
</svg>
your <br/>
amazon <br/>
reviews
</div>
<div className="icon">
<svg version="1.1" className="logo" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 265 265" style={{"enable-background":"new 0 0 265 265;"}} xmlSpace="preserve">
<path className="st0" d="M241.6,3.9H23.4c-10.8,0-19.5,8.7-19.5,19.5v218.2c0,10.8,8.7,19.5,19.5,19.5h218.2c10.8,0,19.5-8.7,19.5-19.5
V23.4C261.1,12.6,252.4,3.9,241.6,3.9z M137.7,210.3c-41.9,2.8-78.5-28.2-82.8-70h54.2V152c0,2.2,1.7,3.9,3.9,3.9h39
c2.2,0,3.9-1.7,3.9-3.9v-39c0-2.2-1.7-3.9-3.9-3.9h-39c-2.2,0-3.9,1.7-3.9,3.9v11.7H54.9c4-39.8,37.5-70.1,77.6-70.1
c42,0,76.5,33.3,77.9,75.3S179.6,207.5,137.7,210.3z"/>
</svg>
your <br/>
uber <br/>
rating
</div>
</div>
<div className="heading centered fiftyfive">
How are organisations <br/>
currently using your data?
</div>
<div className="text centered fiftyfive">
Google collects data about your location, alongside<br/>
others around you, to recognise traffic patterns.<br/><br/>
The NHS collects your health data and shares it with<br/>
other NHS organisations to improve the care and<br/>
treatment of other patients.
</div>
<div className="heading centered fiftyfive">
How is this relevant <br/> to me?
</div>
<div className="text centered">
In the future, we see ownership of data shifting <br/>
away from businesses into the hands of individuals, just <br/>
like you.<br/>
<br/>
With Lens, find out how you could take back control of <br/>
your own data and use it to apply for a job.
</div>
</div>
</div>
);
}
export default Page1;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.