text stringlengths 7 3.69M |
|---|
import styled from "styled-components";
import Dialog from "~/components/atoms/dialog/Dialog";
const StyledPageTagsDialog = styled(Dialog)`
.MuiDialog-paper {
width: 1200px;
max-width: 1200px;
height: 80vh;
}
.MuiGrid-container {
height: 100%;
}
.item-selector {
width: 250px;
overflow-y: scroll;
margin-right: 24px;
height: 100%;
position: relative;
padding-bottom: 75px;
box-sizing: border-box;
.button-wrapper {
position: absolute;
bottom: 0;
left: 0;
right: 0;
text-align: center;
background: #fff;
}
}
.variable-selector {
flex-grow: 1;
position: relative;
width: calc(100% - 250px - 24px);
}
.MuiTableHead-root .MuiTableCell-head {
font-weight: bold;
}
.table-wrapper {
height: 100%;
overflow-y: scroll;
.property {
width: 300px;
max-width: 300px;
}
.type {
width: 50px;
max-width: 50px;
}
}
`;
export {StyledPageTagsDialog};
|
module.exports = {
'f10': 'Telecommunications companies only',
'f11': 'Internet companies only',
'p8': 'Internet companies only',
'p13': 'Internet companies only'
};
|
const mongoose = require('mongoose');
const server = 'localhost:27017'; // Could be replaced with extern ip
const database = 'workoutdb'; // Any database name here
class Database {
constructor() {
this._connect()
}
_connect() {
mongoose.connect(`mongodb://${server}/${database}`)
.then(() => {
console.log('Database connection succeeded')
})
.catch(err => {
console.error('Database connection failed')
})
}
};
const gracefulShutdown = (msg, callback) => {
mongoose.connection.close( () => {
console.log(`Mongoose disconnected through ${msg}`);
callback();
});
};
mongoose.connection.on('connected', () => {
console.log(`Mongoose connected to mongodb://${server}/${database}`);
});
mongoose.connection.on('error', err => {
console.log('Mongoose connection error: ', err);
});
mongoose.connection.on('disconnected', () => {
console.log('Mongoose disconnected');
});
// For nodemon restarts
process.once('SIGUSR2', () => {
gracefulShutdown('nodemon restart', () => {
process.kill(process.pid, 'SIGUSR2');
});
});
// For app termination
process.on('SIGINT', () => {
gracefulShutdown('app termination', () => {
process.exit(0);
});
});
process.on('SIGTERM', () => {
gracefulShutdown('Heroku app shutdown', () => {
process.exit(0);
});
});
module.exports = new Database(); |
'use strict';
const HDDevice = require('./hd4/device');
const fs = require('fs');
module.exports = function( requestOptions, onlyLoad, free ) {
requestOptions;
onlyLoad;
const dbFile = `${ __dirname }/${ free? 'community': '' }database.json`;
let tree = {};
if (fs.existsSync(dbFile)) {
const buffer = fs.readFileSync(dbFile);
tree = JSON.parse( buffer );
} else {
console.log(`${dbFile} not found. Must download.`);
}
const device = new HDDevice(tree);
const CACHE = {};
return function parse(input) {
if (typeof input === 'string') {
input = {'user-agent': input};
}
const inputKey = JSON.stringify(input).toLowerCase();
if (CACHE[inputKey] !== undefined) {
return CACHE[inputKey];
}
const result = device.localDetect(input);
if (!result) {
return undefined;
}
const reply = device.reply;
const hdSpecs = reply.hd_specs;
reply.aliases = hdSpecs.general_aliases;
reply.browser = hdSpecs.general_browser;
reply.browserVersion = hdSpecs.general_browser_version;
reply.model = hdSpecs.general_model;
reply.platform = hdSpecs.general_platform;
reply.platformVersion = hdSpecs.general_platform_version;
reply.type = hdSpecs.general_type;
reply.vendor = hdSpecs.general_vendor;
CACHE[inputKey] = reply;
return reply;
};
};
|
import React, { Component } from 'react';
import '../Assets/css/grayscale.css';
import { Link } from 'react-router-dom';
class Details extends Component {
constructor(){
super();
this.state = {
equipes:[]
};
}
componentDidMount(){
fetch('http://api.football-data.org/v1/competitions/'+this.props.match.params.id+'/teams', {
method: 'GET',
headers: {
'X-Auth-Token': '3b7136ad76ce4b0cacd7e1b02d50870f',
}
})
.then(res => res.json())
.then(res => {
this.setState({
equipes: res.teams
});
})
.catch(error => {
console.log('error dude, desolé');
})
}
render () {
return (
<div>
<header className="ligues">
<div className="intro-body">
<div className="container">
<div className="row">
<div className="col-lg-8 mx-auto">
<h1 className="brand-heading">Ligues Football</h1>
<a href="" className="btn btn-circle js-scroll-trigger">
<i className="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</header>
<h1>Teams Page</h1>
<div className="container">
<div className="row">
{
this.state.equipes.map(p => {
const newTo = {
pathname: "/jouers",
param1: p._links.players.href
};
const ubication ={
pathname: "/Geolocalisation",
param2: p.name
}
if(p.crestUrl != null){
return(
<div className="col-md-3">
<div className="centered">
<img className="ing" src={p.crestUrl} alt="no image disponible"/>
<div className="card-body">
<h5 className="card-title black"> {p.name}</h5>
<Link to= {ubication} className="btn btn-primary">Geolocalisation</Link>
<Link to= {newTo} className="btn btn-primary">Regarder Jouers</Link>
</div>
</div>
</div>
);
}else{
return(
<div className="col-md-3">
<div className="centered">
<img className="ing" src="https://cdn.icon-icons.com/icons2/924/PNG/512/Football_2-61_icon-icons.com_72117.png" alt="Card image cap"/>
<div className="card-body">
<h5 className="card-title black"> {p.name} {p.id} </h5>
<Link to= {newTo} className="btn btn-primary">GO somewhere</Link>
</div>
</div>
</div>
);
}
})
}
</div>
</div>
</div>
);
}
}
export default Details; |
'use strict';
angular.module('apuqaApp.auth', ['apuqaApp.constants', 'apuqaApp.util', 'ngCookies', 'ui.router'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
|
import React from "react";
import Navbar from "../components/FollowNavbar";
import { Jumbotron } from "reactstrap";
import Dog from "../images/dogNose.jpg"
function NoMatch() {
return (
<div>
<Navbar />
<div style={{height: "100%", minHeight: "80vh", display: "block", overflow: "scroll", textAlign: "center"}}>
<Jumbotron style={{backgroundColor: "#026670", color: "#FFF", marginBottom: "0"}}>
<h1 style={{paddingTop: "40px", paddingBottom: "60px"}}>404 Page Not Found</h1>
</Jumbotron>
<img src={Dog} alt="Dog's Face" style={{width: "100%"}}></img>
</div>
</div>
);
}
export default NoMatch; |
import React from 'react';
import { connect } from 'react-redux'
import { handleEditTicket } from '../../redux/modules/dataReducer.js'
import Ticket from './Ticket.js';
let todoTicketsAr = [];
class Todo extends React.Component {
onDragOver = (ev) => {
ev.preventDefault();
}
onDrop = (ev, cat) => {
// finds the location of the ticket in the project array
let ticketNum = ev.dataTransfer.getData('ticketNum')
let projNumber = this.props.projNumber
// sets up our data to edit. only change is the status to match the dropped category
let data = {
title: this.props.data[0].projects[projNumber].tasks[ticketNum].title,
description: this.props.data[0].projects[projNumber].tasks[ticketNum].description,
hours: parseInt(this.props.data[0].projects[projNumber].tasks[ticketNum].hours, 10),
status: cat,
type: this.props.data[0].projects[projNumber].tasks[ticketNum].type,
trimmedType: this.props.data[0].projects[projNumber].tasks[ticketNum].trimmedType,
}
// dispatches to redux store to edit ticket and re-render application
this.props.dispatch(handleEditTicket(data, ticketNum, projNumber))
}
render() {
//on initial render, this.props = undefined or is set to be an empty array, so error checked for these values
if (this.props === undefined || this.props.length === 0) {
//else we pass the todoTickets from props into the Ticket component for rendering
} else {
todoTicketsAr = this.props.tasks.map(function (obj, i) {
return <Ticket key={i} dataset={obj} ></Ticket>
})
}
return (
<div className="droppable" onDragOver={(e) => this.onDragOver(e)} onDrop={(e) => this.onDrop(e, 'To-do')}>
<h2>To do:</h2>
{todoTicketsAr}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
data: state.dataReducer.data,
projNumber: state.changeProjectReducer.projNumber
}
}
export default connect(mapStateToProps)(Todo)
|
'use strict';
angular.module('myApp').
filter('supernumber', function() {
return function(input, count) {
if (input == undefined) return '';
var number=Math.floor(input);
var decimal =(input - number).toFixed(count).toString().substring(2);
var decimalStr=fract(input);
return number+'<sup>'+decimal+'</sup>';
};
});
function fract(n){
return Number(String(n).split('.')[1] || 0);
}
|
function classify() {
var data = {"text": document.getElementById("tweetText").value}
$.post("/classify", data, function(data, status){
var img = document.getElementById('sentimentImg')
if (data.probability <= 0.65) {
img.setAttribute('src', 'static/img/neutral.svg');
}
else if (data.sentiment == 'Positive') {
img.setAttribute('src', 'static/img/happy.svg');
} else {
img.setAttribute('src', 'static/img/sad.svg');
}
document.getElementById('probText').textContent = '(' + data.sentiment + ' with probability: ' + data.probability * 100 + '%)'
}, "json");
}
function imgPreview(fileInput) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imgOrigin').css('background-image', 'url("' + e.target.result + '")');
}
reader.readAsDataURL(fileInput);
}
function Retrieval()
{
$("#result_imgs").html("");
$("#count_results").hide();
var fileUpload = $("#fileInputImg").get(0);
var files = fileUpload.files;
var data = new FormData();
// data.append("function", "loadIMG");
if (files.length == 1) {
for (var i = 0; i < files.length; i++) {
data.append("files", files[i]);
}
$.ajax({
type: "POST",
url: "/upload",
contentType: false,
processData: false,
data: data,
beforeSend: function () {
setLoading(true);
},
success: function (path) {
var ggD_url = "https://drive.google.com/uc?export=view&id=";
console.log(path);
var count_rs = path.length;
imgs_html = "";
for (i = 0; i < path.length; i++) {
imgs_html += "<img class='lazy' width='300' height='150' data-src='" + path[i].id + "' />";
}
$("#count_results").text("Found " + count_rs + " results.");
$("#count_results").show();
$("#result_imgs").css("height","70vh");
$("#result_imgs").css("overflow-y","scroll");
$("#result_imgs").append(imgs_html);
lazyload(this);
setLoading(false);
},
error: function (err) {
console.log(err);
setLoading(false);
}
});
}
}
$("#fileInputImg").on('change', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var data = new FormData();
// data.append("function", "loadIMG");
if (files.length == 1) {
for (var i = 0; i < files.length; i++) {
data.append("files", files[i]);
$('#txtImgName').text(files[i].name);
}
imgPreview(files[0])
}
Retrieval();
});
$("#btnSubmit").on('click', function () {
$("#result_imgs").html("");
var fileUpload = $("#fileInputImg").get(0);
var files = fileUpload.files;
var data = new FormData();
// data.append("function", "loadIMG");
if (files.length == 1) {
for (var i = 0; i < files.length; i++) {
data.append("files", files[i]);
}
$.ajax({
type: "POST",
url: "/upload",
contentType: false,
processData: false,
data: data,
beforeSend: function () {
setLoading(true);
},
success: function (path) {
var ggD_url = "https://drive.google.com/uc?export=view&id=";
console.log(path);
imgs_html = "";
for (i = 0; i < path.length; i++) {
imgs_html += "<img class='lazy' width='300' height='150' data-src='" + path[i].id + "' />";
}
$("#result_imgs").append(imgs_html);
lazyload(this);
setLoading(false);
},
error: function (err) {
console.log(err);
setLoading(false);
}
});
}
});
function setLoading(isLoading) {
if (isLoading) {
$('#preloader').show();
//$("#loader").show();
//$('body').css({ 'opacity': 0.5 });
}
else {
$('#preloader').hide();
//$("#loader").hide();
//$('body').css({ 'opacity': 1 });
}
};
// Prevent default submit behaviour
$("#tweet_form").submit(function(e) {
e.preventDefault();
});
function lazyload(window) {
var ggD_url = "https://drive.google.com/uc?export=view&id=";
var $q = function (q, res) {
if (document.querySelectorAll) {
res = document.querySelectorAll(q);
} else {
var d = document
, a = d.styleSheets[0] || d.createStyleSheet();
a.addRule(q, 'f:b');
for (var l = d.all, b = 0, c = [], f = l.length; b < f; b++)
l[b].currentStyle.f && c.push(l[b]);
a.removeRule(0);
res = c;
}
return res;
}
, addEventListener = function (evt, fn) {
window.addEventListener
? this.addEventListener(evt, fn, false)
: (window.attachEvent)
? this.attachEvent('on' + evt, fn)
: this['on' + evt] = fn;
}
, _has = function (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
;
function loadImage(el, fn) {
var img = new Image()
, src = ggD_url+el.getAttribute('data-src');
img.onload = function () {
if (!!el.parent)
el.parent.replaceChild(img, el)
else
el.src = src;
fn ? fn() : null;
}
img.src = src;
}
function elementInViewport(el) {
var rect = el.getBoundingClientRect()
return (
rect.top >= 0
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight)
)
}
var images = new Array()
, query = $q('img.lazy')
, processScroll = function () {
for (var i = 0; i < images.length; i++) {
if (elementInViewport(images[i])) {
loadImage(images[i], function () {
images.splice(i, i);
});
}
};
}
;
// Array.prototype.slice.call is not callable under our lovely IE8
for (var i = 0; i < query.length; i++) {
images.push(query[i]);
};
processScroll();
//addEventListener('scroll', processScroll);
$("#result_imgs").scroll(processScroll);
};
/*
$(function() {
//Inset Dark
$("#rs").mCustomScrollbar({
theme: "inset-3-dark"
});
});
*/ |
var app = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mysql = require('mysql');
var sql = mysql.createConnection({
host: 'localhost',
post: 12345,
user: 'nodejs',
password: 'nodejs',
database: 'nodejs',
charset : 'utf8mb4'
});
sql.connect();
io.on('connection', function(socket){ //연결 되면 이벤트 설정
console.log('a user connected');
socket.on('disconnect', function(){//연결해제 이벤트
console.log('user disconnected');
});
socket.on('login', function(msg){//로그인 확인 이벤트
sql.query("SELECT * FROM user WHERE user.id = '"+msg.id+"' and user.pw = '"+msg.pw+"';", function (error, results, fields) {
if (error) {
io.emit('onBoolean'+msg.myID,false);
}
else { //결과는 배열인덱스.키값으로 접근 없으면 배열.length가 0
if(results.length != 0){//로그인 정보가 있다면 나머지 정보도 전송
io.emit('msg'+msg.myID,results[0]);
// console.log("로그인 "+JSON.stringify(results[0]));
}
io.emit('onBoolean'+msg.myID,results.length != 0);//결과가 0이면 아이디가 X이므로 false
}
});
});
socket.on('signup',function(msg){//아이디 중복 확인 및 회원가입 이벤트
signup_callback(msg.id,msg.pw,function(val_bool){
io.emit('onBoolean'+msg.myID,val_bool);
});
});
socket.on('msg', function(msg){
io.emit('msg'+msg.myID, msg);
});
socket.on('userInfo',function(msg){
sql.query("SELECT id,name,picture,msg FROM user WHERE id='"+msg.id+"'; ",function(error,results,fields){
io.emit('userInfo'+msg.myID,results[0]);
});
});
socket.on('userUpdate',function(msg){
sql.query("UPDATE user SET name = ?,msg=? WHERE id='"+msg.id+"'; ",[msg.name,msg.msg],function(error,results,fields){if(error) console.log("error"+error);
console.log(msg.name,msg.msg);
});
});
socket.on('addFriend',function(msg){
sql.query("INSERT INTO user_friend(id_me,id_friend,name_friend) VALUES(?,?,?);",[msg.me,msg.friend,msg.name],function(error,results,fields){
});//위는 그냥 친구추가 아래는 상대방도 자동으로 추가시킴 (없다면)
sql.query("SELECT * FROM user_friend WHERE id_me = ? AND id_friend = ?",[msg.friend,msg.me], function(error,results,fields){
if(results[0] == null){
sql.query("INSERT INTO user_friend(id_me,id_friend,name_friend) VALUES(?,?,?);",[msg.friend,msg.me,msg.myname],function(error,results,fields){//로그인할때 첨들어갈때만 초기화됨
sql.query("SELECT * FROM user WHERE id = '"+msg.me+"';",[msg.friend,msg.me,msg.myname],function(error,results,fields){
if(results[0].picture == null)
results[0].picture = "";
io.emit("addFriend"+msg.friend,results[0]);
});
});
}
});
});
socket.on('getFriend',function(msg){
sql.query("SELECT user.id, user_friend.name_friend, user.picture, user.msg FROM user, user_friend WHERE user.id = user_friend.id_friend AND user_friend.id_me = '"+msg.id+"';",function(error,results,fields){
io.emit('getFriend'+msg.myID,results);
});
});
socket.on('updateFriendName',function(msg){
sql.query("UPDATE user_friend SET name_friend = ? WHERE id_me = ?",[msg.name,msg.id],function(error,results,fields){
});
});
socket.on('deleteFriend',function(msg){
sql.query("DELETE FROM user_friend WHERE id_me= ? AND id_friend = ?;",[msg.me,msg.friend],function(error,results,fields){
});
});
socket.on('addChatRoom',function(msg){
sql.query("INSERT INTO chatroom(room_user) VALUES(?);",[msg.users],function(error,results,fields){
sql.query("SELECT room_num FROM chatroom ORDER BY room_num DESC LIMIT 1;",function(error,results,fields){
io.emit("addChatRoom"+msg.myID,results[0].room_num);
});
});
});
socket.on('addChatRecode',function(msg){//채팅 친걸 서버로 보냈을때
sql.query("INSERT INTO chatrecode(room_num,who,date,text,type) VALUES(?,?,?,?,?);",[msg.a,msg.c,msg.d,msg.e,msg.f],function(error,results,fields){//채팅레코드 추가
if(error)console.log("에러 : "+error);
sql.query("SELECT recode_num FROM chatrecode ORDER BY recode_num DESC LIMIT 1;",function(error2,results2,fields2){//추가한 레코드 넘버 확인
var jsonobj = new Object();
jsonobj.num = msg.a;
jsonobj.amount = msg.b;
jsonobj.id = msg.c;
jsonobj.time = msg.d;
jsonobj.type = msg.f;
jsonobj.server = results2[0].recode_num;
userName_callback(msg.isCreate,msg.e,msg.c ,function(result){
jsonobj.text = result;
console.log(result);
for(var i of msg.g.split("/")){
io.emit("sendChatting"+i,jsonobj);
}
});
});
});
});
socket.on('readChat',function(msg){
io.emit("readChat",msg);//msg.roomNum, msg.start;
});
socket.on('initChatRoom',function(msg){
sql.query("SELECT * FROM chatroom",function(error,results,fields){
var jsonArr = new Array();
for(var i in results){
var array = results[i].room_user.split('/');
for(var j in array){
if(array[j] == msg.id){
var jsonobj = new Object();
jsonobj.num = results[i].room_num;
jsonobj.user = results[i].room_user;
jsonArr.push(jsonobj);
break;
}
}
}
io.emit('initChatRoom'+msg.myID,jsonArr);
});
});
socket.on('createRoomID',function(msg){
sql.query("SELECT * FROM chatroom WHERE room_num = '"+msg.num+"';",function(error,results,fields){ io.emit('createRoomID'+msg.myID,results[0]);
});
});
socket.on('updateProfile',function(msg){
sql.query("UPDATE user SET picture = ? WHERE id = ? ;",[msg.img,msg.id],function(error,results,fields){
console.log(msg.img,msg.id);
io.emit('updateProfile',msg);
});
});
});
signup_callback = function(id,pw,callback){
sql.query("SELECT * FROM user WHERE user.id = '"+id+"';", function (error, results, fields) {
if (error) {
callback(false);
} else { //결과는 배열인덱스.키값으로 접근 없으면 배열.length가 0
if(results.length == 0){//하려는 아이디가 없다면 insert
sql.query("insert into user(id,pw) values('"+id+"','"+pw+"');", function (error, results, fields) { });//쿼리문도 콜백형식
callback(true);
}else{
callback(false);
}
}
});
};
userName_callback = function(isCreate,msg,who,callback){
if(isCreate){
sql.query("SELECT name,id FROM user",function (error, results, fields) {
var resultMsg = "제가 ";
var users = msg.split("/");
for(var userID of users){//받은 유저 모두 검사
if(userID == who)
continue;//나면 넘어감
for(var column of results){//유저아이디에 해당하는 닉네임 찾기
if(column.id == userID){
resultMsg += column.name+" 님, ";
break;
}
}
}
resultMsg = resultMsg.substring(0,resultMsg.length -2);
resultMsg += "을 초대하였습니다.";
callback(resultMsg);
});
}else{
callback(msg);
}
};
http.listen(12345, function(){
console.log('listening on *:12345');
});
// mysql 쿼리문, char set utf-8, varchar(n)은 바이트수가 아닌 글자 수,외래키사용 데이터관리주의
// create database nodejs;
// CREATE USER nodejs@'localhost' IDENTIFIED BY 'nodejs'
// grant all privileges on nodejs.* to nodejs@'localhost';
// CREATE TABLE user(
// user_num int AUTO_INCREMENT PRIMARY KEY,
// id varchar(30) NOT NULL,
// pw char(64) NOT NULL,
// name varchar(20) DEFAULT 'visitor',
// picture TEXT ,
// msg varchar (40) DEFAULT ''
// );
// CREATE TABLE chatroom(
// room_num INT AUTO_INCREMENT PRIMARY KEY,
// room_user TEXT
// );
// CREATE TABLE chatrecode(
// recode_num INT AUTO_INCREMENT PRIMARY KEY,
// room_num INT,
// who varchar(30) NOT NULL,
// date char(19) NOT NULL,
// text TEXT NOT NULL,
// type TINYINT NOT NULL,
// FOREIGN KEY (room_num) REFERENCES chatroom(room_num)
// );
// CREATE TABLE user_friend(
// friend_num INT AUTO_INCREMENT PRIMARY KEY,
// id_me varchar(30) NOT NULL,
// id_friend varchar(30) NOT NULL,
// name_friend varchar(20) NOT NULL
// );
//type : 1-문자 , 2-이미지 , 3-파일 |
import React from "react";
// MaterialUI
import { CssBaseline, Grid } from "@material-ui/core";
import MainHeader from "./MainHeader";
import SongList from "./SongList";
import SongDetail from "./SongDetail";
// Action(s)
export default function App() {
return (
<div>
<CssBaseline />
<MainHeader />
<Grid alignItems="center" container spacing={16}>
<Grid item xs={12} md={6}>
<SongList />
</Grid>
<Grid item xs={12} md={6}>
<SongDetail />
</Grid>
</Grid>
</div>
);
}
|
"use strict";
// This object holds all possible playing card suits and values.
const CARDS = {
"values": [
"ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"
],
"suits": [
"clubs", "diamonds", "spades", "hearts"
]
};
// This prefix is used to locate the card image.
// Card image name is following the format:
// {card value}_of_{suit}.
const PATH_PREFIX = 'Playing Cards\\';
const REVERSE_SIDE_PATH = `${PATH_PREFIX}reverse_side.png`;
// States of timer. Indicate whether the timer has to be stopped or started.
const START_TIMER = 'start';
const STOP_TIMER = 'stop';
// Server settings.
const SERVER_LOCAL = 'http://localhost:8000/cgi-bin/prax3.py';
const SERVER_LIVE = 'http://dijkstra.cs.ttu.ee/~alfrol/cgi-bin/prax3.py';
let server = SERVER_LOCAL;
let playerName;
let mode;
let cardsAmount;
let timer;
let score = 0;
let scoreText;
let order = 'asc';
// Indicates how many correct guesses the player has.
let streak = 0;
let timePassed = 1;
/**
* Validate player name.
* The name is needed in order to start a new game.
*/
function validatePlayerName() {
const name = getGameForm()['player-name'].value;
if (!name.trim()) {
getById('play-button').style.visibility = 'hidden';
} else {
playerName = name;
getById('play-button').style.visibility = 'visible';
}
}
/**
* Change field size options according to selected game mode.
*
* Mode defines which cards are treated as pairs and can be:
* 1. Only value
* 2. Both value and suit
*/
function changeBoardSize() {
const boardSizeSelector = getById('board-size');
if (mode === 'same-value') {
boardSizeSelector.removeChild(boardSizeSelector.options[3]);
} else {
const option = createElement('option');
option.value = '52';
option.innerText = '52';
boardSizeSelector.appendChild(option);
}
}
/**
* Start the game by generating the table.
*
* Before starting the game the user must specify
* the preferences (how to count pairs and number
* of cards they want to play with).
*/
function startGame() {
generateGameField();
setTimer(START_TIMER);
document.getElementsByClassName('details')[0].style.display = 'block';
getById('board').style.display = 'block';
getById('player-name').style.pointerEvents = 'none';
score = 0;
streak = 0;
}
/**
* Generate the gamefield where the game will be played on.
*/
function generateGameField() {
mode = getGameForm()["game-mode"].value;
cardsAmount = Number.parseInt(getGameForm()["board-size"].value);
scoreText = getById('score');
scoreText.innerText = '0';
document.getElementsByClassName('details')[0].style.display = 'none';
getById('game-stats-popup').style.display = 'none';
setTimer(STOP_TIMER);
clearBoard();
// Calculate the amount of rows in the board table.
const rowsCount = cardsAmount % 4 === 0 ? 4 : cardsAmount / 13;
for (let i = 0; i < rowsCount; i++) {
const tr = createElement('tr');
getCardBoard().appendChild(tr);
}
const cards = mode === 'same-value' ? cardsForRegularBoard(cardsAmount) : cardsForHarderBoard(cardsAmount);
addCardsToBoard(cards);
}
/**
* Finish current game.
* Add current score to table.
*/
function finishGame() {
clearBoard();
score += timePassed > score ? timePassed % score : score % timePassed;
scoreText.innerText = `${score}`;
showStats();
updateScoreTable();
saveGameData();
setTimer(STOP_TIMER);
document.getElementsByClassName('details')[0].style.display = 'none';
getById('player-name').style.pointerEvents = 'all';
}
/**
* Update the scores, put new score into the table.
*/
function updateScoreTable() {
const rows = getById('stats').rows;
const timeTaken = getById('timer').innerText;
let tr, newTdIndex, tdPlayerName, tdMode, tdScore, tdTime;
let isFreeSpace = false;
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
if (!row.className.includes('logged')) {
tr = row;
[tdPlayerName, tdMode, tdScore, tdTime] = [...row.children].slice(1);
isFreeSpace = true;
break;
}
}
if (isFreeSpace) {
addStatsToTable(tr, tdPlayerName, tdMode, tdScore, tdTime, timeTaken);
} else {
[tr, newTdIndex, tdPlayerName, tdMode, tdScore, tdTime] = [...createTableCells()];
newTdIndex.innerText = Number.parseInt(rows[rows.length - 1].children[0].innerText) + 1;
addStatsToTable(tr, tdPlayerName, tdMode, tdScore, tdTime, timeTaken);
getById('stats').tBodies[0].appendChild(tr);
}
}
/**
* Create new table cells in order to insert new scores into table.
*
* @returns {HTMLElement[]} Return created table cells.
*/
function createTableCells() {
const tr = createElement('tr');
const newTdIndex = createElement('td');
const newTdPlayerName = createElement('td');
const newTdMode = createElement('td');
const newTdScore = createElement('td');
const newTdTime = createElement('td');
tr.appendChild(newTdIndex);
tr.appendChild(newTdPlayerName);
tr.appendChild(newTdMode);
tr.appendChild(newTdScore);
tr.appendChild(newTdTime);
return [tr, newTdIndex, newTdPlayerName, newTdMode, newTdScore, newTdTime];
}
/**
* Add the data to the table row.
*
* @param {HTMLElement} row Is the row where the data should be put.
* @param {HTMLElement} tdPlayerName Is the name of the player.
* @param {HTMLElement} tdMode Is the table data cell to put game mode into.
* @param {HTMLElement} tdScore Is the table data cel to put player score into.
* @param {HTMLElement} tdTime Is the table data cell to put time into.
* @param {string} timeTaken Is actual time taken to finish the game.
*/
function addStatsToTable(row, tdPlayerName, tdMode, tdScore, tdTime, timeTaken) {
const gameMode = `${mode[0].toUpperCase()}${mode.replace(/-/g, ' ').substr(1)}`;
tdPlayerName.innerText = playerName;
tdMode.innerText = `${gameMode} | ${cardsAmount}`;
tdScore.innerText = score;
tdTime.innerText = timeTaken;
row.className = 'logged';
}
/**
* Sort the table by some criteria.
*
* Make GET request to the server with the specified criteria.
* The sorting will take place on the server and sorted data will be returned
* back.
*
* @param criteria Is the criteria by which sorting should be done.
*/
function sortTable(criteria) {
const nameFilterValue = getById('filter-bar').value;
let url;
if (order === 'asc') {
order = 'desc';
} else {
order = 'asc'
}
if (nameFilterValue) {
url = `${server}?action=sort&criteria=${criteria}&order=${order}&name=${nameFilterValue}`;
} else {
url = `${server}?action=sort&criteria=${criteria}&order=${order}`
}
fetch(url, {
headers: {
'Accept': 'application/json'
},
mode: "no-cors"
})
.then(r => r.json())
.then(data => insertNewDataIntoTable(data));
}
/**
* Filter scores by player name.
* Player name is typed into the <input> field and
* the scores are filtered by this input.
*/
function filterByPlayer() {
const nameFilterValue = getById('filter-bar').value;
if (nameFilterValue) {
fetch(`${server}?action=filter&name=${nameFilterValue}`, {
headers: {
'Accept': 'application/json'
},
mode: "no-cors"
})
.then(response => response.json())
.then(data => insertNewDataIntoTable(data));
} else {
loadGameData();
}
}
/**
* Fetch the scores saved to the server and update the table.
*
* @returns {Promise<void>}
*/
function loadGameData() {
fetch(server, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'no-cors'
})
.then(response => response.json())
.then(data => insertNewDataIntoTable(data));
}
/**
* Insert new data obtained from the server into the table.
*
* @param data New data with scores etc.
*/
function insertNewDataIntoTable(data) {
const rows = getById('stats').rows;
for (let i = 1; i < rows.length; i++) {
for (let j = 1; j < rows[i].children.length; j++) {
rows[i].children[j].innerText = '-';
}
rows[i].className = '';
}
for (const d of data.scores) {
playerName = d.name;
mode = d.mode;
cardsAmount = d.cards;
score = d.score;
getById('timer').innerText = d.time;
updateScoreTable();
}
}
/**
* Send data over to the server in order to save it.
*/
function saveGameData() {
const Data = {
name: playerName,
mode: mode,
cards: cardsAmount,
time: getById('timer').innerText,
score: score
};
fetch(server, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(Data),
method: 'POST',
mode: 'no-cors'
});
}
/**
* Clear the field if the player doesn't want to play anymore.
*/
function clearGameField() {
getCardBoard().style.display = 'none';
clearBoard();
setTimer(STOP_TIMER);
scoreText.innerText = '0';
document.getElementsByClassName('details')[0].style.display = 'none';
getById('game-stats-popup').style.display = 'none';
getById('player-name').style.pointerEvents = 'all';
}
/**
* Show statistics about current game.
*/
function showStats() {
const statsPopup = getById('game-stats-popup');
const scoreCurrent = getById('game-stats-score');
const timeCurrent = getById('game-stats-time');
getById('game-stats-popup').style.display = 'none';
scoreCurrent.innerText = score;
timeCurrent.innerText = getById('timer').innerText;
statsPopup.style.display = 'block'
}
/**
* Start or stop a timer.
*
* Timer is used to count the duration of current game.
*
* @param {string} action Defines whether to start or stop the timer.
*/
function setTimer(action) {
const timerText = getById('timer');
if (action === 'stop') {
clearInterval(timer);
timerText.innerText = '00:00:00';
timePassed = 1;
} else if (action === 'start') {
timePassed = 1;
timer = setInterval(() => {
const seconds = timePassed % 60;
const minutes = Math.floor(timePassed / 60);
const hours = Math.floor(timePassed / 3600);
const formatTime = (time) => time < 10 ? `0${time}` : `${time}`;
timerText.innerText = `${formatTime(hours)}:${formatTime(minutes)}:${formatTime(seconds)}`;
timePassed++;
}, 1000);
}
}
/**
* Generate cards for regular board.
*
* Regular board means a pair of cards has only the same value.
*
* @param {number} numOfCards Number of cards to generate.
*/
function cardsForRegularBoard(numOfCards) {
const cards = [];
const values = shuffle(CARDS['values'], numOfCards / 2);
for (const value of values) {
const suits = shuffle(CARDS['suits'], 2);
for (const suit of suits) {
const card = getCard(value.toString(), suit.toString());
cards.push(card);
}
}
return cards;
}
/**
* Generate cards for harder board.
*
* Harder board means a pair of cards has both same suit and value.
*
* @param {number} numOfCards Number of cards to generate.
*/
function cardsForHarderBoard(numOfCards) {
const cards = [];
if (numOfCards === 52) {
for (const value of CARDS['values']) {
for (const suit of CARDS['suits']) {
const card = getCard(value, suit);
cards.push(card);
}
}
} else {
// Add some noise to getting random cards.
const randomNum = getRandomInt(0, numOfCards === 6 ? 0 : 7);
// Number of values needed with the noise.
const numOfValues = (numOfCards - (randomNum % 2 === 0 ? randomNum : randomNum + 1)) / 2;
const values = shuffle(CARDS['values'], numOfValues);
// Difference between full stack cards (13 max) and cards with noise.
const diff = (numOfCards / 2) - numOfValues;
// Number of cards which will occur twice with both black and red suits.
const repeatingCards = shuffle(values, diff);
for (const value of values) {
let suits;
if (repeatingCards.includes(value)) {
suits = CARDS['suits'];
} else {
suits = getRandomInt(1, 4) % 2 === 0 ? ['clubs', 'spades'] : ['hearts', 'diamonds'];
}
suits = shuffle(suits);
for (const suit of suits) {
const card = getCard(value.toString(), suit);
cards.push(card);
}
}
}
return cards;
}
/**
* Add cards to the board.
*
* @param {HTMLElement} board Game board where to add cards.
* @param {string[]} cards Cards to add.
*/
function addCardsToBoard(cards) {
cards = shuffle(cards);
const cardsPerRow = cards.length / getCardBoard().rows.length;
for (const row of getCardBoard().rows) {
for (let i = 0; i < cardsPerRow; i++) {
row.appendChild(cards.pop());
}
}
}
/**
* Create a new card with specified suit and value.
*
* Card must be a HTML <td></td> element with another
* HTML <img> element.
* Ny default the card itself is not shown to the player,
* so the image should be neutral.
*
* @param {string} value Card value.
* @param {string} suit Card suit.
* @returns {HTMLElement}
*/
function getCard(value, suit) {
const td = createElement('td');
const div1 = createElement('div');
const div2 = createElement('div');
const cardBack = createElement('img');
const cardFront = createElement('img');
td.id = `${value}-${suit}`;
td.className = 'card';
div1.className = 'card-face card-back';
div2.className = 'card-face card-front';
div1.onclick = handleCardSelection;
div2.onclick = handleCardSelection;
cardBack.src = REVERSE_SIDE_PATH;
cardBack.alt = `Playing card: ${value} of ${suit}`
cardFront.src = `${PATH_PREFIX}${value}_of_${suit}.png`;
cardFront.alt = `Playing card: ${value} of ${suit}`;
div1.appendChild(cardFront);
div2.appendChild(cardBack);
td.appendChild(div1);
td.appendChild(div2);
return td;
}
/**
* Handle the event when the player clicks some card.
*
* If there are less than 2 cards with face turned to the player, show the clicked card.
* Otherwise decide, whether the two showing cards make up a pair.
* If so, remove the cards from the board.
* If not, hide the cards (turn the reverse sides to the player).
*
* @param {HTMLImageElement} element Caller element that has been clicked by the player.
*/
function handleCardSelection(element) {
const showingCards = document.getElementsByClassName('showing');
if (showingCards.length < 2) {
let card = element.target || element.srcElement;
if (card.nodeType === 3) card = card.parentNode;
showCard(card);
if (showingCards.length === 2) {
const card1 = showingCards[0], card2 = showingCards[1];
const match = isMatch(card1, card2);
if (match) {
streak++;
setTimeout(() => {
removeCards([...showingCards]);
}, 1000);
} else {
streak = 0;
setTimeout(() => {
hideCards([...showingCards]);
}, 1000);
}
}
}
}
/**
* Show the card to the player when clicked.
*
* @param {HTMLImageElement} card Card to be shown.
*/
function showCard(card) {
card.parentElement.parentElement.className = 'card showing';
}
/**
* Remove cards that made up a pair (there was a match).
*
* @param {HTMLImageElement[]} cards Cards to remove.
*/
function removeCards(cards) {
for (const card of cards) {
card.style.visibility = 'hidden';
card.className = 'card';
}
score += streak + getRandomInt(cardsAmount / 2, cardsAmount);
scoreText.innerText = `${score}`;
let boardEmpty = true;
for (const card of document.getElementsByClassName('card')) {
if (card.style.visibility !== 'hidden') {
boardEmpty = false;
break;
}
}
if (boardEmpty) finishGame();
}
/**
* Hide the cards if there was no match.
* By hiding it is meant to show the reverse side of the card to the player.
*
* @param {HTMLImageElement[]} cards Cards to hide.
*/
function hideCards(cards) {
for (const card of cards) {
card.className = 'card';
card.src = REVERSE_SIDE_PATH;
}
score = score - 5 <= 0 ? 0 : score - 5;
scoreText.innerText = score;
}
/**
* Check whether two cards make up a pair.
*
* @param {HTMLElement} card1 First card.
* @param {HTMLElement} card2 Second card.
* @returns {boolean} true if cards make up a pair, false otherwise.
*/
function isMatch(card1, card2) {
const value1 = card1.id.split('-')[0], suit1 = card1.id.split('-')[1];
const value2 = card2.id.split('-')[0], suit2 = card2.id.split('-')[1];
if (mode === 'same-value') {
return value1 === value2;
} else if (mode === 'same-suit-and-value') {
const black = ['clubs', 'spades'], white = ['hearts', 'diamonds'];
return value1 === value2 &&
(black.includes(suit1) && black.includes(suit2) || white.includes(suit1) && white.includes(suit2));
}
return false;
}
/**
* Clear the board after the game.
*/
function clearBoard() {
getById('board').innerHTML = '';
}
/**
* Get an element by ID.
*
* @param {string} id Id of the desired element.
* @returns {HTMLElement} Element.
*/
function getById(id) {
return document.getElementById(id);
}
/**
* Create a new HTML element.
*
* @param {string} element Name of the element.
* @returns {HTMLElement} Created element.
*/
function createElement(element) {
return document.createElement(element);
}
/**
* Shuffle the collection.
*
* Shuffling means switching places of some elements in the collection.
*
* @param {string[]} collection Collection with values to shuffle.
* @param {number} maxItems Maximum number of items in shuffled array.
* @returns {string[]} A shuffled array.
*/
function shuffle(collection, maxItems = collection.length) {
const shuffled = [];
const copy = [...collection];
let i = getRandomInt(0, copy.length - 1);
while (shuffled.length < maxItems && copy.length > 0) {
shuffled.push(copy[i]);
copy.splice(i, 1);
i = getRandomInt(0, copy.length - 1);
}
return shuffled;
}
/**
* Return random integer between min and max.
*
* @param {number} min Minimum value (included).
* @param {number} max Maximum value (included).
* @returns {number}
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Get game form where the player can choose game presets.
*/
function getGameForm() {
return document.forms['presets'];
}
/**
* Get the board where cards are shown.
* @returns {HTMLElement}
*/
function getCardBoard() {
return getById('board');
} |
import { loadProfile, getSkater, scoreBruisePoints, scoreCoolPoints } from '../common/utils.js';
import { bpMessages, cpMessages } from './messages.js';
loadProfile();
const skater = getSkater();
const storyDisplay = document.getElementById('story');
const storyImg = document.getElementById('results-image');
const bpResult = scoreBruisePoints(skater.bp);
const cpResult = scoreCoolPoints(skater.cp);
const bpMessage = bpMessages[bpResult];
const cpMessage = cpMessages[cpResult];
let story = 'Your first couple weeks on your new team as a new ' + skater.position + ' is coming to a close! ' + skater.name + ', ' + bpMessage + '. ' + cpMessage;
storyDisplay.textContent = story;
storyImg.src = '../assets/wheels-of-justice.jpg';
|
var express = require('express')
var tweetBank = require('../tweetBank')
//Integration with Models
var User = require('../models/index.js').User;
var Tweet = require('../models/index.js').Tweet;
module.exports = function(io) {
var router = express.Router()
router.get('/', function(req, res) {
var tweetArray = [];
Tweet.findAll({ include: [ User ] })
.then(function(tweets) {
for (var i = 0; i < tweets.length; i++) {
tweetArray.push(tweets[i].dataValues);
}
console.log(tweetArray);
res.render('index', {
tweets: tweetArray,
showForm: true
})
})
})
router.get('/users/:name', function(req, res) {
var tweetArray = [];
var userName = req.params.name
User.findAll({ include: [ {model: Tweet, required: true}], where: {name: userName}})
.then(function(tweets) {
for (var i = 0; i < tweets[0].Tweets.length; i++) {
tweetArray.push(tweets[0].Tweets[i].dataValues);
}
res.render('index', {
tweets: tweetArray,
formName: userName,
showForm: true
})
})
})
router.get('/users/:name/tweets/:id', function(req, res){
req.params.id = parseInt(req.params.id)
var tweets = tweetBank.find({id: req.params.id})
res.render('index', {
tweets: tweets
})
})
router.post('/submit', function(req, res){
var userName = req.body.name;
var tweetText = req.body.text;
var tableUserId = "";
var tweetArray = [];
//(1) See if userName already exists in Users table
// (1a) IF it does, THEN get the ID of the User and RETURN
// (1b) ELSE CREATE userName in Users table and return User ID
//(2) Create a new tweetText in the Tweet table with a userId from 1a/1b and an auto-incremented ID
User.findOrCreate({ where: {name: userName}, defaults: {} })
.then(function(user) {
tableUserId = user[0].dataValues.id;
// console.log("WROTE TO USER TABLE " + tableUserId);
Tweet.create({UserId: tableUserId, tweet: tweetText});
// console.log("WROTE TO TWEET TABLE, NEW TWEET " + tweetText);
}
)
//OLD CODE!!!
//Select all tweets from database and push them into tweetArray
//TODO
Tweet.findAll({ include: [ User ] })
.then(function(tweets) {
for (var i = 0; i < tweets.length; i++) {
tweetArray.push(tweets[i].dataValues);
var all_tweets = tweetArray;
var last_tweet = all_tweets[all_tweets.length-1];
// last_tweet = last_tweet[last_tweet.length-1];
console.log(last_tweet);
io.sockets.emit('new_tweet', last_tweet)
}
})
// res.redirect(req.body.redirectUrl)
// res.redirect('/')
})
return router
}
|
import Notfound from '../../components/404';
const module = angular.module('app.pages.notfound', [
Notfound.name
]);
export default module.name;
|
var CarContract = artifacts.require("CarContract");
var toKeys=["dWreo9NBaEsmM5yRVkR12VpkdnTWvxeT8NHk2BINbHA="];
contract('CarContract', function(accounts) {
it("Should return Mitsubishi static info", function() {
var instance;
return CarContract.deployed().then(function(_instance) {
instance = _instance;
return instance.getStaticCarInfo.call("12345678901234567");
}).then(function(_carInfo) {
console.log('VIN: ' + _carInfo[0]);
console.log('Car make: ' + _carInfo[1]);
console.log('Car model: ' + _carInfo[2]);
assert.equal(_carInfo[0], "12345678901234567", "Car VIN is wrong");
assert.equal(_carInfo[1], "Mitsubishi", "Car make is wrong");
assert.equal(_carInfo[2], "Galant ES, 2009", "Car model is wrong");
});
});
it("Should return Mitsubishi owner info", function() {
var instance2;
return CarContract.deployed().then(function(_instance) {
instance2 = _instance;
return instance2.getAllIndexes.call("12345678901234567");
}).then(function(_indexes) {
return instance2.getOwner.call("12345678901234567", _indexes[0]);
}).then(function(_ownerInfo) {
console.log('Owner address: ' + _ownerInfo[0]);
console.log('Time bought: ' + _ownerInfo[1]);
console.log('Car Mileage: ' + _ownerInfo[2]);
console.log('Account 0: ' + accounts[0]);
console.log('Account 1: ' + accounts[1]);
console.log('Account 2: ' + accounts[2]);
console.log('Account 3: ' + accounts[3]);
console.log('Account 4: ' + accounts[4]);
assert.equal(_ownerInfo[0], accounts[0], "Car owner is wrong");
});
});
it("Should set then get airbag info", function() {
var instance3;
return CarContract.deployed().then(function(_instance3) {
instance3 = _instance3;
return instance3.changeAirbag("12345678901234567", "AIRBAG6789", 0, "MANUFACTURER", {privateFor: toKeys});
}).then(function() {
console.log(' Airbag part added');
return instance3.getAllIndexes.call("12345678901234567");
}).then(function(_indexes) {
return instance3.getAirbag.call("12345678901234567", _indexes[1]);
}).then(function(_airbagInfo) {
console.log('Airbag part number: ' + _airbagInfo[0]);
console.log('Time installed: ' + _airbagInfo[1]);
console.log('Car Mileage: ' + _airbagInfo[2]);
console.log('Installer: ' + _airbagInfo[3]);
assert.equal(_airbagInfo[0], "AIRBAG6789", "Airbag part number is wrong");
assert.equal(_airbagInfo[2], 0, "Car mileage for airbag installation is wrong");
assert.equal(_airbagInfo[3], "MANUFACTURER", "Airbag installer is wrong");
});
});
it("Should reject part change from anyone who is not the car owner", function() {
return CarContract.deployed().then(function(_instance3) {
instance3 = _instance3;
return instance3.changeAirbag("12345678901234567", "FAKEPART", "110333", "Hank Hammer, Meineke", {from: accounts[3], privateFor: toKeys});
}).then(function(result) {
console.log(' Airbag part added');
}).catch(function(e) {
//console.log(e);
// An error was correctly detected. CarContract should have rejected part change from unauthorized account
return instance3.getAllIndexes.call("12345678901234567");
}).then(function(_indexes) {
return instance3.getAirbag.call("12345678901234567", _indexes[1]);
}).then(function(_airbagInfo) {
console.log('Airbag part number: ' + _airbagInfo[0]);
console.log('Time installed: ' + _airbagInfo[1]);
console.log('Car Mileage: ' + _airbagInfo[2]);
console.log('Installer: ' + _airbagInfo[3]);
// All airbag part info should be unchanged
assert.equal(_airbagInfo[0], "AIRBAG6789", "Airbag part number change by unauthorized account");
assert.equal(_airbagInfo[2], 0, "Car mileage changed by unauthorized account");
assert.equal(_airbagInfo[3], "MANUFACTURER", "Airbag installer changed by unauthorized account");
});
});
it("Add two installations of tires then report tire history", function() {
var instance3;
var i = 0;
return CarContract.deployed().then(function(_instance3) {
instance3 = _instance3;
return instance3.changeTires("12345678901234567", "GOODYEAR3456", 0, "MANUFACTURER", {privateFor: toKeys});
}).then(function() {
console.log(' Tires added');
return instance3.changeTires("12345678901234567", "MICHELIN3456", 55000, "Randy Wrench, AutoFix", {privateFor: toKeys});
}).then(function() {
console.log(' Tires added\n');
return instance3.getAllIndexes.call("12345678901234567");
}).then(function(_indexes) {
console.log('-----Tire history-----');
return instance3.getTires.call("12345678901234567", 0);
}).then(function(_tireInfo) {
console.log(i + ' Tire part number: ' + _tireInfo[0]);
console.log(i + ' Time installed: ' + _tireInfo[1]);
console.log(i + ' Car Mileage: ' + _tireInfo[2]);
console.log(i + ' Installer: ' + _tireInfo[3] + '\n');
i = 1;
return instance3.getTires.call("12345678901234567", i);
}).then(function(_tireInfo) {
console.log(i + ' Tire part number: ' + _tireInfo[0]);
console.log(i + ' Time installed: ' + _tireInfo[1]);
console.log(i + ' Car Mileage: ' + _tireInfo[2]);
console.log(i + ' Installer: ' + _tireInfo[3]);
console.log('----------------------');
assert.equal(_tireInfo[0], "MICHELIN3456", "Tire part number is wrong");
assert.equal(_tireInfo[2], 55000, "Car mileage for tire installation is wrong");
assert.equal(_tireInfo[3], "Randy Wrench, AutoFix", "Tire installer is wrong");
});
});
it("Change ownership, disable previous owner's ability to make transactions", function() {
var instance3;
var numOwners;
var numTires;
var numTires2;
return CarContract.deployed().then(function(_instance3) {
instance3 = _instance3;
return instance3.changeOwner("12345678901234567", accounts[3], "78000", {privateFor: toKeys});
}).then(function() {
console.log('Owner changed to: ' + accounts[3]);
return instance3.getOwner.call("12345678901234567", 1, {from: accounts[3]});
}).then(function(_ownerInfo) {
console.log('Reported owner address: ' + _ownerInfo[0]);
console.log('Reported time bought: ' + _ownerInfo[1]);
console.log('Reported car Mileage: ' + _ownerInfo[2]);
return instance3.getAllIndexes.call("12345678901234567", {from: accounts[3]});
}).then(function(_indexes) {
numOwners = Number(_indexes[0]) + 1;
numTires = Number(_indexes[3]) + 1;
console.log('Number of owners: ' + numOwners);
console.log('Number of tire installations: ' + numTires);
return instance3.changeTires("12345678901234567", "FAKETIRE3456", "80000", "Fake Mechanic, AutoFix", {privateFor: toKeys});
}).then(function() {
return instance3.getAllIndexes.call("12345678901234567", {from: accounts[3]});
}).then(function(_indexes) {
numTires2 = Number(_indexes[3]) + 1;
console.log('Number of tire installations: ' + numTires2); // Would report 3 if latest changeTires() call was allowed
assert.equal(numTires, numTires2, "New tires logged by unauthorized account");
});
});
});
|
const express = require('express')
const router = express.Router()
const bookController = require('../controllers/bookController')
// sans parametre
router.get('/', bookController.getAllBooks)
router.post('/', bookController.createBook)
router.put('/', bookController.updateBook)
// par id
router.get('/:id', bookController.getBookById)
router.delete('/:id', bookController.deleteBookById)
// get by label
router.get('/label/:label', bookController.getBooksByLabel)
module.exports = router
|
uses("panjs.core.http.TrestClient");
defineClass("TgraphDataService", "panjs.events.TeventDispatcher", {
_baseUrl: null,
_className: null,
constructor: function(args){
this._super.constructor.call(this,args);
this._className = args.className;
this._baseUrl = args.baseUrl;
this.restClient = new TrestClient({baseUrl: this._baseUrl, dataType:"json"});
},
createObject: function(data, sucess, failure){
},
linkObject: function(sourceId, destId, data, sucess, failure){
}
});
|
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var Article = new Schema({
title: {type: String},
content: {type: String},
owner: {type: Schema.Types.ObjectId, required: true},
created: {
type: Date,
default: Date.now
},
update: {
type: Date,
default: Date.now
}
});
Article.set("autoIndex", true);
module.exports = mongoose.model('Article', Article); |
import * as PropTypes from 'prop-types';
import * as React from 'react';
const Badge = (props) => (
<div className={
`chi-badge
${props.color ? `-${props.color}` : ''}
${props.size ? `-${props.size}` : ''}
${props.variant ? `-${props.variant}` : ''}
`}>
<span>{props.text}</span>
</div>
);
/* eslint-disable sort-keys */
Badge.propTypes = {
color: PropTypes.oneOf(['primary', 'success', 'warning', 'danger', 'dark', 'muted', 'secondary', 'light']),
size: PropTypes.oneOf(['xs', 'sm', 'md']),
variant: PropTypes.oneOf(['outline', 'flat']),
text: PropTypes.string,
};
/* eslint-enable sort-keys */
Badge.defaultProps = {
size: 'md',
text: 'Badge',
};
export { Badge as default };
|
import { getWindow } from './utils/window';
var window = getWindow();
import injector from './utils/dependency_injector';
var nativeXMLHttpRequest = {
getXhr: function getXhr() {
return new window.XMLHttpRequest();
}
};
export default injector(nativeXMLHttpRequest); |
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import Card from 'grommet/components/Card'
import './CarCard.css'
class CarCard extends Component {
render () {
const url = '/car/' + this.props.car._id
return (
<Card
className='carCard'
contentPad='none'
thumbnail={this.props.car.photos[0]}
heading={this.props.car.manufacturer + ' ' + this.props.car.model}
headingStrong={false}
description={this.props.car.kilometrage * 1000 +
' km, $' + this.props.car.price}
link={<Link to={url}>Link</Link>}
/>
)
}
}
export default CarCard
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.state.command.AddTrackCommand');
goog.require('audioCat.state.Clip');
goog.require('audioCat.state.Section');
goog.require('audioCat.state.Track');
goog.require('audioCat.state.command.Command');
/**
* Adds a new track. The subclass for a lot of other commands that involve
* adding a class.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
* throughout one instance of the application.
* @param {string} trackName The name of the new track.
* @param {!audioCat.audio.AudioChest=} opt_audioChest The chest containing the
* audio for the track. If not provided, creates an empty track.
* @param {number=} opt_beginTime The number of seconds into the audio at which
* to begin the new section. Defaults to 0.
* @constructor
* @extends {audioCat.state.command.Command}
*/
audioCat.state.command.AddTrackCommand =
function(idGenerator, trackName, opt_audioChest, opt_beginTime) {
goog.base(this, idGenerator, true);
/**
* The name of the imported audio.
* @private {string}
*/
this.trackName_ = trackName;
/**
* The audio chest containing the full audio data for the imported audio. Or
* null if no such audio exist, ie an empty track.
* @private {audioCat.audio.AudioChest}
*/
this.audioChest_ = opt_audioChest || null;
/**
* The index of the new track. Null if command not yet performed.
* @private {?number}
*/
this.trackIndex_ = null;
// Create track.
var track = new audioCat.state.Track(idGenerator, trackName);
if (opt_audioChest) {
// Create a section.
var section = new audioCat.state.Section(
idGenerator, opt_audioChest, trackName, opt_beginTime || 0);
// Create a clip.
var clip = new audioCat.state.Clip(
idGenerator, 0, opt_audioChest.getNumberOfSamples());
section.addClip(clip);
track.addSection(section);
}
/**
* The track added due to the audio import.
* @private {!audioCat.state.Track}
*/
this.track_ = track;
};
goog.inherits(
audioCat.state.command.AddTrackCommand, audioCat.state.command.Command);
/** @override */
audioCat.state.command.AddTrackCommand.prototype.perform =
function(project, trackManager) {
// Remember the index at which we inserted this track.
this.trackIndex_ = trackManager.getNumberOfTracks();
trackManager.addTrack(this.track_);
};
/** @override */
audioCat.state.command.AddTrackCommand.prototype.undo =
function(project, trackManager) {
trackManager.removeTrack(/** @type {number} */ (this.trackIndex_));
return;
};
/** @override */
audioCat.state.command.AddTrackCommand.prototype.getSummary =
function(forward) {
return (forward ? 'Added' : 'Removed') + ' track ' + this.track_.getName();
};
/**
* @return {?audioCat.audio.AudioChest} The audio chest if any. Could be null
* if track added was empty.
*/
audioCat.state.command.AddTrackCommand.prototype.getOptionalAudioChest =
function() {
return this.audioChest_;
};
|
import React from 'react';
class Image extends React.Component {
render() {
const { data } = this.props
if (!data) {
return <div></div>
}
return (
<img src={data.url} className="img-fluid"></img>
);
}
}
export default Image
|
class Abilities {
constructor(options) {
this.name = options.name;
this.range = options.range;
// effect being a function thats called on the target piece
this.effect = options.effect;
}
};
|
import { StatusBar } from 'expo-status-bar';
import 'react-native-gesture-handler';
import React, { useEffect, useState } from 'react';
import * as firebase from 'firebase';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './redux/reducers';
import thunk from 'redux-thunk';
import 'firebase/firestore';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { StyleSheet, Text, View } from 'react-native';
import Main from './components/Main';
import Add from './components/main/Add';
import Save from './components/main/Save';
const firebaseConfig = {
apiKey: 'AIzaSyA-PRrLezsGHgHNY8FWQ5FjsFEuYNSWVSg',
authDomain: 'instagram-native-3f222.firebaseapp.com',
projectId: 'instagram-native-3f222',
storageBucket: 'instagram-native-3f222.appspot.com',
messagingSenderId: '552086268871',
appId: '1:552086268871:web:a3ed181c12b4e46dec07e2',
measurementId: 'G-RZ1ZTGMTBX',
};
if (firebase.apps.length === 0) {
firebase.initializeApp(firebaseConfig);
}
const store = createStore(rootReducer, applyMiddleware(thunk));
const Stack = createStackNavigator();
export default function App({ navigation }) {
const [loaded, setLoaded] = useState(null);
const [loggedIn, setLoggedIn] = useState(null);
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (!user) {
setLoggedIn(false);
setLoaded(true);
} else {
setLoaded(true);
setLoggedIn(true);
}
});
}, []);
if (!loaded) {
return (
<View className={styles.loading}>
<Text> Loading </Text>
</View>
);
}
// if (!loggedIn) {
// return (
// <NavigationContainer>
// <Stack.Navigator initialRouteName="Landing">
// <Stack.Screen
// name="Landing"
// component={Landing}
// options={{
// headerShown: false,
// }}
// />
// <Stack.Screen name="Register" component={Register} />
// <Stack.Screen name="Login" component={Login} />
// </Stack.Navigator>
// </NavigationContainer>
// );
// }
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Main">
<Stack.Screen
name="Main"
component={Main}
options={{
headerShown: false,
}}
/>
<Stack.Screen name="Add" component={Add} navigation={navigation} />
<Stack.Screen name="Save" component={Save} navigation={navigation} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
loading: {
flex: 1,
justifyContent: 'center',
},
});
|
import React, { useState } from 'react';
import { useMutation, useQuery } from 'react-apollo';
import { CreateNoteMutation, DeleteNoteMutation, UpdateNoteMutation } from './graphql/mutations';
import NotesQuery from './graphql/queries';
const NotesPage = () => {
// Graphql query
const { loading, data, error } = useQuery(NotesQuery);
// State hooks
const [newNote, setNewNote] = useState('');
const [noteContentBeingUpdated, setNoteContentBeingUpdated] = useState('');
const [noteIdBeingUpdated, setNoteIdBeingUpdated] = useState('');
// Graphql mutations
const [createNoteMutation] = useMutation(CreateNoteMutation);
const [deleteNoteMutation] = useMutation(DeleteNoteMutation);
const [updateNoteMutation] = useMutation(UpdateNoteMutation);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
const { notes } = data;
// Handlers
const handleCreateNote = () => {
if (newNote) {
createNoteMutation({ variables: { content: newNote }, refetchQueries: ['NotesQuery'] }).then(() => {
// eslint-disable-next-line no-console
console.log('Response received from server.');
}).catch(createNoteMutationError => {
// eslint-disable-next-line no-console
console.log(createNoteMutationError);
});
setNewNote('');
}
};
const handleUpdateNote = (_id, content, isBeingUpdated) => () => {
if (isBeingUpdated) {
updateNoteMutation({ variables: { _id, content: noteContentBeingUpdated } }).then(() => {
// eslint-disable-next-line no-console
console.log('Response received from server.');
}).catch(updateNoteMutationError => {
// eslint-disable-next-line no-console
console.log(updateNoteMutationError);
});
setNoteIdBeingUpdated('');
setNoteContentBeingUpdated('');
} else {
setNoteIdBeingUpdated(_id);
setNoteContentBeingUpdated(content);
}
};
const handleNoteBeingUpdated = (e) => setNoteContentBeingUpdated(e.target.value);
const handleDeleteNote = (_id) => () => {
deleteNoteMutation({ variables: { _id }, refetchQueries: ['NotesQuery'] }).then(() => {
// eslint-disable-next-line no-console
console.log('Response received from server.');
}).catch(deleteNoteMutationError => {
// eslint-disable-next-line no-console
console.log(deleteNoteMutationError);
});
};
const handleOnChangeNote = e => setNewNote(e.target.value);
return (
<div>
<header>Notes</header>
<ul>
{notes.map(note => {
const { content, _id } = note;
const isBeingUpdated = noteIdBeingUpdated === _id;
return (
<div key={_id}>
{isBeingUpdated ? (
<li>
<input
value={noteContentBeingUpdated}
onChange={handleNoteBeingUpdated}
/>
</li>
) : (
<li>{content}</li>
)}
<div style={{ display: 'flex' }}>
<button type="button" onClick={handleUpdateNote(_id, content, isBeingUpdated)}>update</button>
<button type="button" onClick={handleDeleteNote(_id)}>delete</button>
</div>
</div>
);
})}
</ul>
<footer>
<input
value={newNote}
onChange={handleOnChangeNote}
placeholder='Add a note here'
/>
<button type="button" onClick={handleCreateNote}>create note</button>
</footer>
</div>
);
};
export default NotesPage;
|
"use strict";
"use warning";
var RangeUnit = function(_positionX, _positionY, _unitInfo, _powerUpCost) {
this.walkImg = [];
this.atkImg = [];
this.exploImg = [];
this.upgradeImg;
this.fastImg = []; //PlayResManager.getMyUnitMap().get("buff_fast");
this.walkImg[0] = [];
this.walkImg[1] = [];
this.atkImg[0] = [];
this.atkImg[1] = [];
this.Missile = [];
for (var i = 0; i < 4; i++) {
this.walkImg[0][i] = PlayResManager.getMyUnitMap().get("my_" + _unitInfo.getRes() + "_r_w_" + i);
this.walkImg[1][i] = PlayResManager.getMyUnitMap().get("my_" + _unitInfo.getRes() + "_l_w_" + i);
this.atkImg[0][i] = PlayResManager.getMyUnitMap().get("my_" + _unitInfo.getRes() + "_r_a_" + i);
this.atkImg[1][i] = PlayResManager.getMyUnitMap().get("my_" + _unitInfo.getRes() + "_l_a_" + i);
}
for (var i = 0; i < 3; i++) {
this.fastImg[i] = PlayResManager.getMyUnitMap().get("speedUp_" + i);
}
for (var i = 0; i < 10; i++) {
this.Missile[i] = new Missile(_unitInfo.getWeaponName());
}
for (var i = 0; i < 5; i++) {
this.exploImg[i] = PlayResManager.getMyUnitMap().get("explo_" + i);
}
this.upgradeImg = PlayResManager.getMyUnitMap().get("upgrade");
this.unitWidth = this.walkImg[0][0].width;
this.unitHeight = this.walkImg[0][0].height;
this.directValue = 0;
this.frameCnt = 0;
this.fastCnt = 170;
this.upgradeAniCnt = 10;
this.powerUpCost = _powerUpCost;
this.powerUpGold = _powerUpCost;
this.initAtkDam = 0;
this.mFrame = 0;
this.exploIdx = 0;
this.ballPosX = 0;
this.ballPosY = 0;
this.myPosX = 0;
this.myPosY = 0;
this.enPosX = 0;
this.enPosY = 0;
this.enWidth = 0;
this.enHeight = 0;
this.oldAtkSpeed = 0;
this.atkIdx = 0;
this.ballIdx = 0;
this.name;
this.constructor(_positionX, _positionY, _unitInfo);
};
RangeUnit.prototype = new Unit();
RangeUnit.prototype.constructor = function(_positionX, _positionY, _unitInfo) {
// Unit.prototype.constructor.call(this, _positionX, _positionY);
this.curState = STATE_IDLE;
this.name = _unitInfo.getName();
// 캐릭터 속성
this.rangeValue = _unitInfo.getAttackRange();
this.splashValue = _unitInfo.getSplashRange();
this.atkDam = _unitInfo.getAttack();
this.critical = _unitInfo.getCritical();
this.attr = _unitInfo.getAttr();
this.type = _unitInfo.getType();
this.atkSpeed = _unitInfo.getAttackSpd();
this.atkInc = _unitInfo.getAttackInc();
this.moveSpeed = _unitInfo.getMoveSpd();
this.isSplash = _unitInfo.getIsSplash();
this.skill = _unitInfo.getSkill();
this.oldAtkSpeed = this.atkSpeed;
this.initAtkDam = this.atkDam;
this.skillCoolTime = _unitInfo.getSkillCoolTime();
this.isSkillCoolTime = false;
this.upgradePoint = 0;
this.hpValue = 2000;
this.hpDefault = this.hpValue;
// 생성 위치에 이미지를 그리기 위해 이미지의 넓이와 높이의 반씩 마이너스 한다
this.posX = _positionX - Math.floor(this.unitWidth / 2);
this.posY = _positionY - this.unitHeight;
this.myPosX = this.posX;
this.myPosY = this.posY;
// 공격 미사일 좌표
this.ballPosX = this.posX + Math.floor(this.unitWidth / 2);
this.ballPosY = this.posY + Math.floor(this.unitHeight / 2);
// 공격 사정거리 좌표
this.rangePosX = this.posX + Math.floor((this.unitWidth / 2)) - this.rangeValue;
this.rangePosY = this.posY + Math.floor((this.unitHeight / 2)) - this.rangeValue;
// 목표물 좌표
this.destiPosX = this.rangePosX + this.rangeValue;
this.destiPosY = this.rangePosY + this.rangeValue;
};
RangeUnit.prototype.unitDataRefresh = function() {
// this.posX = this.posX - (this.unitWidth / 2);
// this.posY = this.posY - (this.unitHeight / 2);
this.ballPosX = this.posX + Math.floor(this.unitWidth / 2);
this.ballPosY = this.posY + Math.floor(this.unitHeight / 2);
// this.rangePosX = this.posX + Math.floor(this.unitWidth / 2) - this.rangeValue;
// this.rangePosY = this.posY + Math.floor(this.unitHeight / 2) - this.rangeValue;
this.destiPosX = this.rangePosX + this.rangeValue;
this.destiPosY = this.rangePosY + this.rangeValue;
this.mFrame = 0;
this.exploIdx = 0;
};
RangeUnit.prototype.update = function() {
this.frameCnt++;
if (!this.isAtk && !this.isDead) {
this.curState = STATE_IDLE;
this.isAtk = false;
this.isHit = false;
this.destiPosX = this.rangePosX + this.rangeValue;
this.destiPosY = this.rangePosY + this.rangeValue;
}
if (this.upgradeAniCnt < 10) {
this.upgradeAniCnt++;
}
if (this.skillCoolTimeCnt < this.skillCoolTime) {
this.skillCoolTimeCnt++;
this.isSkillCoolTime = false;
} else {
this.isSkillCoolTime = true;
}
if (this.fastCnt < 170) {
this.fastCnt++;
} else {
this.atkSpeed = this.oldAtkSpeed;
}
switch (this.curState) {
case STATE_IDLE:
this.isHit = false;
this.isAtk = false;
this.mFrame = 0;
this.exploIdx = 0;
if (Math.abs(this.destiPosX - (this.posX + Math.floor(this.unitWidth / 2))) <= this.moveSpeed && Math.abs(this.destiPosY - (this.posY + Math.floor(this.unitHeight / 2))) <= this.moveSpeed) {
this.posX = this.myPosX;
this.posY = this.myPosY;
} else {
if (this.destiPosX < this.posX + Math.floor(this.unitWidth / 2)) {
this.posX -= this.moveSpeed;
}
if (this.destiPosX > this.posX + Math.floor(this.unitWidth / 2)) {
this.posX += this.moveSpeed;
}
if (this.destiPosY < this.posY + Math.floor(this.unitHeight / 2)) {
this.posY -= this.moveSpeed;
}
if (this.destiPosY > this.posY + Math.floor(this.unitHeight / 2)) {
this.posY += this.moveSpeed;
}
}
for (var i = 0; i < this.Missile.length; i++) {
this.Missile[i].update();
if (this.Missile[i].getIsRunning()) {
this.Missile[i].setIsRunning(this.enWidth, this.enHeight, this.enPosX, this.enPosY);
}
if (this.Missile[i].getExploCnt() == 4) {
this.isHit = true;
}
}
break;
case STATE_ATTACK:
this.atkIdx++;
this.isHit = false;
if (Math.floor(this.atkIdx % this.atkSpeed) == 0) {
for (var i = 0; i < this.Missile.length; i++) {
if (!this.Missile[i].getIsRunning()) {
this.Missile[i].setPosition(this.posX + Math.floor(this.unitWidth / 2), this.posY + Math.floor(this.unitHeight / 2), this.destiPosX, this.destiPosY, this.enWidth, this.enHeight, this.enPosX, this.enPosY, this.atkSpeed);
break;
}
}
}
for (var i = 0; i < this.Missile.length; i++) {
this.Missile[i].update();
if (this.Missile[i].getIsRunning()) {
this.Missile[i].setIsRunning(this.enWidth, this.enHeight, this.enPosX, this.enPosY);
}
if (this.Missile[i].getExploCnt() == 4) {
this.isHit = true;
}
}
case STATE_DEAD:
break;
default:
break;
}
};
RangeUnit.prototype.render = function(g) {
if (this.isDead) return;
// g.setColor(COLOR_BLACK);
// g.fillRect(this.posX, this.posY, this.unitWidth, this.unitHeight);
if (GameEngine.getGameMode() == GAME_READY) {
g.setColor(COLOR_ALPHA);
HDrawMgr.drawCircle(g, this.rangePosX, this.rangePosY, (this.rangeValue * 2), (this.rangeValue * 2), this.rangeValue);
}
switch (this.curState) {
case STATE_IDLE:
g.drawImage(this.walkImg[this.directValue][Math.floor(this.frameCnt / 2 % 4)], this.posX, this.posY);
break;
case STATE_ATTACK:
g.drawImage(this.atkImg[this.directValue][Math.floor(this.Missile[0].getFrameCnt() / this.atkSpeed % 2)], this.posX, this.posY);
for (var i = 0; i < this.Missile.length; i++) {
this.Missile[i].render(g);
}
break;
case STATE_DEAD:
break;
default:
break;
}
if (this.fastCnt < 170) {
g.drawImage(this.fastImg[Math.floor(this.fastCnt / 3 % 3)], this.posX + Math.floor(this.walkImg[0][0].width / 2) - Math.floor(this.fastImg[0].width / 2), this.posY + this.walkImg[0][0].height -Math.floor(this.fastImg[0].height / 2) - 20);
}
if (this.upgradeAniCnt < 10) {
g.drawImage(this.upgradeImg, this.posX + Math.floor(this.unitWidth / 2) - Math.floor(130 / 2), this.posY - this.upgradeAniCnt, 130, 30);
}
};
RangeUnit.prototype.keyAction = function() {
switch (this.curState) {
case STATE_IDLE:
break;
case STATE_ATTACK:
break;
case STATE_DEAD:
break;
default:
break;
}
};
RangeUnit.prototype.getPurposeX = function() {
return this.enPosX;
};
RangeUnit.prototype.getPurposeY = function() {
return this.enPosY;
};
RangeUnit.prototype.getPurposeW = function() {
return this.enWidth;
};
RangeUnit.prototype.getPurposeH = function() {
return this.enHeight;
};
RangeUnit.prototype.getPowerUpGold = function() {
return this.powerUpGold;
};
RangeUnit.prototype.upgrade = function() {
this.upgradePoint++;
this.atkDam = (this.atkDam + Math.floor(this.initAtkDam * 5 / 100));
this.upgradeAniCnt = 0;
this.powerUpGold = this.powerUpGold + this.powerUpCost;
};
RangeUnit.prototype.getUpgradePoint = function() {
return this.upgradePoint;
};
RangeUnit.prototype.setFast = function() {
this.fastCnt = 0;
this.atkSpeed = Math.floor(this.atkSpeed / 2);
// this.atkSpeed = this.atkSpeed / 2;
};
RangeUnit.prototype.unitAttackCheck = function(positionX, positionY, unitWidth, unitHeight) {
// if (!Math.floor(this.frameCnt / this.atkSpeed % this.atkSpeed) == 0) return;
this.enPosX = positionX;
this.enPosY = positionY;
this.enWidth = unitWidth;
this.enHeight = unitHeight;
// 공격 사정거리 // 원거리의 경우 atkDistance와 hiDistance가 같다
this.atkDistance = this.attackRangeDistanceCheck(positionX + Math.floor(unitWidth / 2), this.rangePosX + this.rangeValue, positionY + Math.floor(unitHeight / 2), this.rangePosY + this.rangeValue);
// 실제 공격거리 // 근거리의 경우 atkDistance로 몬스터에게 다가가고 hitDistance로 공격한다
this.hitDistance = this.attackRangeDistanceCheck(positionX + Math.floor(unitWidth / 2), this.posX + Math.floor(this.unitWidth / 2), positionY + Math.floor(unitHeight / 2), this.posY + Math.floor(this.unitHeight / 2));
if (this.atkDistance < this.rangeValue) {
this.isAtk = true;
this.directValue = (this.destiPosX > (this.posX + Math.floor(this.unitWidth / 2)) ? 0 : 1);
this.destiPosX = positionX + Math.floor(unitWidth / 2);
this.destiPosY = positionY + Math.floor(unitHeight / 2);
if (this.hitDistance <= this.rangeValue) {
this.curState = STATE_ATTACK;
} else {
this.isHit = false;
this.curState = STATE_IDLE;
}
return true;
} else {
this.curState = STATE_IDLE
this.isHit = false;
this.isAtk = false;
this.mFrame = 0;
this.exploIdx = 0;
this.destiPosX = this.rangePosX + this.rangeValue;
this.destiPosY = this.rangePosY + this.rangeValue;
this.ballPosX = this.posX + Math.floor(this.unitWidth / 2);
this.ballPosY = this.posY + Math.floor(this.unitHeight / 2);
}
return false;
};
RangeUnit.prototype.stop = function() {
this.walkImg = null;
this.atkImg = null;
this.exploImg = null;
this.upgradeImg = null;
this.fastImg = null;
for (var i = 0; i < this.Missile.length; i++) {
this.Missile[i].flush();
}
this.Missile = null;
}; |
import React, { useEffect, useState } from "react";
import Carousel from '../../components/Carousel';
import MyMenuItem from '../../components/MyMenuItem';
import ListTopic from '../../components/ListTopic';
import { Row, Col, Layout } from 'antd';
import ListProduct from '../../components/ListProduct'
import axios from 'axios';
const { Content, Sider } = Layout;
const HomePage = () => {
const [data, setData] = useState({});
const access_Token = `eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5NGUyZDU3NC1iZGY1LTQxMTctODc4Mi00OGM3NDRmOGQ1M2IiLCJzdWIiOiIyIiwic2NwIjoiYXBpX3VzZXIiLCJhdWQiOm51bGwsImlhdCI6MTYwNjcyNzc1NSwiZXhwIjoxNjA2NzMxMzU1fQ.asvSFQOB0OIeGC326iFFd9-u15IIG_xRwpv7Y2M-q7k`;
const AuthStr = 'Bearer '.concat(access_Token);
useEffect(() => {
axios({
method: 'get',
url: "http://localhost:3000/api/home"
}).then(res => {
setData(res.data);
console.log(res.data);
})
},[])
return(
<>
<Row>
<Col offset={2} span={20}>
<Content style={{ padding: '10px 0px',}}>
<Layout className="site-layout-background" style={{ padding: '0px 0', backgroundColor: "#f0f2f5" }}>
<Sider className="site-layout-background" width={200}>
<MyMenuItem/>
</Sider>
<Content style={{ minHeight: 280 }}>
<Carousel products={data.products_1}/>
</Content>
</Layout>
</Content>
</Col>
</Row>
<ListTopic />
<ListProduct title={'Sản phẩm bán chạy'} products={data.products_1}/>
<ListProduct title={'Sản phẩm được tài trợ'} products={data.products_2}/>
<ListProduct title={'Sản phẩm được gợi ý'} products={data.products_3}/>
</>
)
}
export default HomePage |
/* exported SocoboAuth */
var SocoboAuth = (function() {
/**
* Instance stores a reference to the Singleton
*/
var instance;
/**
* Public API
*
* @returns {Object} {
* {registerUserAndLogin: registerUserAndLogin,
* loginWithProvider: loginWithProvider,
* loginWithEmailaddress: loginWithEmailaddress
* }}
*/
function init() {
/**
* create user on firebase
*
* @param {String} baseURL
* @param {Object} userObj
* @return {Promise}
* @private
*/
var _createUser = function(baseURL, userObj) {
return new Promise(function(resolve, reject) {
var rootRef = new Firebase(baseURL);
rootRef.createUser(userObj, function(err, user) {
if (err) {
reject(err);
}
if (user) {
resolve(user);
}
});
});
};
/**
* get username from auth data
*
* @param {Object} authData
* @return {String}
* @private
*/
var _getUserName = function(authData) {
switch (authData.provider) {
case "password":
return authData.password.email.replace(/@.*/, "");
case "google":
return authData.google.displayName;
case "twitter":
return authData.twitter.displayName;
case "facebook":
return authData.facebook.displayName;
}
};
/**
* get email address from auth data
*
* @param {Object} userObj
* @return {String}
* @private
*/
var _getUserEmailAddress = function(userObj) {
switch (userObj.provider) {
case "password":
return userObj.password.email;
case "google":
return userObj.google.hasOwnProperty("email") ?
userObj.google.email
: userObj.google.cachedUserProfile.link;
case "twitter":
return userObj.twitter.username;
case "facebook":
return userObj.facebook.hasOwnProperty("email") ?
userObj.facebook.email
: userObj.facebook.cachedUserProfile.email;
}
};
/**
* get profile image from auth data
*
* @param {Object} userObj
* @return {String}
* @private
*/
var _getUserProfileImage = function(userObj) {
switch (userObj.provider) {
case "password":
return userObj.password.profileImageURL;
case "google":
return userObj.google.profileImageURL;
case "twitter":
return userObj.twitter.profileImageURL;
case "facebook":
return userObj.facebook.profileImageURL;
}
};
/**
* ToDo: Generate API Keys for
* - Facebook
* auth user with social media provider
*
* @param {String} baseURL
* @param {String} provider
* @param {Boolean} isRegister
* @param {Boolean} isAdmin
* @param {Boolean} hasTermsAccepted
* @return {Promise}
*/
var loginWithProvider = function(baseURL, provider, isRegister, isAdmin, hasTermsAccepted) {
return new Promise(function(resolve, reject) {
var rootRef = new Firebase(baseURL);
rootRef.authWithOAuthPopup(provider, function(err, user) {
if (err) {
reject(err);
}
if (user) {
if (isRegister) {
rootRef.child("users").child(user.uid).child("administration").set({
provider: user.provider,
isAdmin: isAdmin,
hasTermsAccepted: hasTermsAccepted
});
rootRef.child("profiles").child(user.uid).set({
name: _getUserName(user),
email: _getUserEmailAddress(user),
biography: "Please tell us something about you!",
profileImage: _getUserProfileImage(user),
provider: user.provider
});
}
resolve(user);
}
}.bind(this));
});
};
/**
* auth user with Email Address
*
* @param {String} baseURL
* @param {Object} userObj
* @param {Boolean} isRegister
* @param {Boolean} isAdmin
* @param {Boolean} hasTermsAccepted
* @return {Promise}
*/
var loginWithEmailaddress = function(baseURL, userObj, isRegister, isAdmin, hasTermsAccepted) {
return new Promise(function(resolve, reject) {
var rootRef = new Firebase(baseURL);
rootRef.authWithPassword(userObj, function onAuth(err, user) {
if (err) {
reject(err);
}
if (user) {
if (isRegister) {
rootRef.child("users").child(user.uid).child("administration").set({
provider: user.provider,
isAdmin: isAdmin,
hasTermsAccepted: hasTermsAccepted
});
rootRef.child("profiles").child(user.uid).set({
name: _getUserName(user),
email: _getUserEmailAddress(user),
biography: "Please tell us something about you!",
profileImage: _getUserProfileImage(user),
provider: user.provider
});
}
resolve(user);
}
}.bind(this));
});
};
/**
* register user on firebase and log user in
*
* @param {String} baseURL
* @param {String} provider
* @param {Object} userObj
* @param {Boolean} isAdmin
* @param {Boolean} hasTermsAccepted
* @return {Promise}
*/
var registerUserAndLogin = function(baseURL, provider, userObj, isAdmin, hasTermsAccepted) {
if (userObj === null) {
return loginWithProvider(baseURL ,provider, true, isAdmin, hasTermsAccepted);
} else {
return _createUser(baseURL, userObj)
.then(function() {
return loginWithEmailaddress(baseURL ,userObj, true, isAdmin, hasTermsAccepted);
}.bind(this))
.catch(function(err) {
return err;
});
}
};
/**
* Provide public functions
*/
return {
registerUserAndLogin: registerUserAndLogin,
loginWithProvider: loginWithProvider,
loginWithEmailaddress: loginWithEmailaddress
};
}
/**
* Return Singleton Instance
*/
return {
/**
* Get the Singleton instance if one exist or create one if it doesn't
*
* @return {Object}
*/
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
|
Package.describe({
summary: "flot - Attractive JavaScript plotting for jQuery"
});
Package.on_use(function (api) {
api.use('jquery', 'client');
api.add_files([
'lib/js/excanvas.js',
'lib/js/excanvas.min.js',
'lib/js/jquery.flot.js',
'lib/jquery.colorhelpers.js',
'lib/jquery.flot.crosshair.js',
'lib/jquery.flot.fillbetween.js',
'lib/jquery.flot.image.js',
'lib/jquery.flot.navigate.js',
'lib/jquery.flot.pie.js',
'lib/jquery.flot.resize.js',
'lib/jquery.flot.selection.js',
'lib/jquery.flot.stack.js',
'lib/jquery.flot.symbol.js',
'lib/jquery.flot.threshold.js'
], 'client'
);
}); |
function init(){
var url=document.getElementById('url').value;
document.getElementById('img').src=url;
(function() {
var $section = $('section').first();
$section.find('.panzoom').panzoom({
$zoomIn: $section.find(".zoom-in"),
$zoomOut: $section.find(".zoom-out"),
$zoomRange: $section.find(".zoom-range"),
$reset: $section.find(".reset")
});
})();
}
function closeimg(){
history.back();
}
window.onload=init() |
import React, { Component } from 'react';
//import logo from './logo.svg';
class Lesson extends Component {
render() {
return React.createElement('li',{className:'list-group-item'}, '123');
}
}
export default Lesson; |
$(function () {
baseUrl = 'https://arcane-lake-91251.herokuapp.com';
ADD_USER_BUTTON = "images/add_user.png";
function getUser(username) {
return fetch(`${baseUrl}/users/${username}`)
.then(res => res.json());
}
function getStats(username) {
return fetch(`${baseUrl}/stats/${username}`)
.then(res => res.json());
}
function getFollowing(username) {
return fetch(`${baseUrl}/following/${username}`)
.then(res => res.json());
}
function getFollowers(username) {
return fetch(`${baseUrl}/followers/${username}`)
.then(res => res.json());
}
/**
* Initialize the content of the page
*/
function initialize() {
getData('LionelNanchen');
getData('onicoleheig');
getData('wasadigi');
getData('paulnta');
getData('edri');
getData('mraheigvd');
getData('kamkill01011');
getData('onicole');
}
/**
* Add the loading icon
* @param username the name of the user
*/
function addLoading(username){
const row = $("#user-frame-row");
const div = document.createElement("div");
div.setAttribute("class", "col-lg-4 col-sm-6 text-center mb-4 user-frame");
div.setAttribute("id", "user-frame-box-" + username.split(' ').join('-'));
const divLoading = document.createElement("div");
divLoading.setAttribute("class", "loader");
const h3 = document.createElement("h3");
h3.setAttribute("class", "user-frame-name");
h3.textContent = username;
div.appendChild(divLoading);
div.appendChild(h3);
row.append(div);
}
/**
* Delete the loading icon
* @param username the name of the user
*/
function deleteLoading(username){
$("#user-frame-box-" + username + " .loader").remove();
}
/**
* Get user data from the server
* @param username the name of the user
*/
function getData(username){
addLoading(username);
return Promise.all([
getUser(username),
getStats(username),
getFollowing(username),
getFollowers(username),
])
.then(([user, stats, following, followers]) => {
stats.fg = following.length;
stats.fr = followers.length;
user.stats = stats;
createFrame(user);
})
.catch(err => {
console.error('Error ! cannot fetch data', err);
});
}
/**
* Create a frame with the user informations
* @param user the user on which the frame will be created
*/
function createFrame(user) {
const row = $("#user-frame-row");
const div = $("#user-frame-box-" + user.login);
const buttonImg = document.createElement("img");
buttonImg.setAttribute("class", "add-user-button");
buttonImg.src = ADD_USER_BUTTON;
const a = document.createElement("a");
a.setAttribute("class", "user-frame-image");
a.id = user.login.split(' ').join('-') + "-frame";
const avatar = document.createElement("img");
avatar.setAttribute("class", "rounded-circle img-fluid d-block mx-auto frame-avatar");
avatar.src = user.avatar_url;
a.appendChild(avatar);
deleteLoading(user.login);
//append new elements
div.append(buttonImg);
div.prepend(a);
//attach user to the frame
$("#" + a.id).data(a.id, user);
}
/**
* Bold all the biggest values for each row on the comparison table
*/
function boldBiggestVules() {
const rows = $("#sorted-tbody").children();
for (let i = 1; i < rows.length; ++i) {
let max = 0;
let index = 0;
row = rows[i].children;
for (let j = 1; j < row.length; ++j) {
row[j].style.fontWeight = "normal";
if (parseInt(row[j].textContent) > parseInt(max)) {
max = parseInt(row[j].textContent);
index = j;
}
}
row[index].style.fontWeight = "bold";
}
}
//code inspired by https://www.w3schools.com/howto/howto_js_filter_lists.asp
$(document).on("keyup", ".search-bar", function () {
let input, filter, ul, li, a, i;
input = document.getElementById("search-bar");
filter = input.value.toUpperCase();
div = document.getElementById("user-frame-row");
frames = div.getElementsByClassName("user-frame");
for (i = 0; i < frames.length; i++) {
frame = frames[i];
if (frame.innerHTML.toUpperCase().indexOf(filter) > -1) {
frames[i].style.display = "";
} else {
frames[i].style.display = "none";
}
}
});
/**
* Check if the user is already in the list.
* @param String id the id of the list-group-item corresponding to the user.
*/
function isUserInList(id) {
return $("#" + id).length > 0;
}
/**
* Sort the users list
*/
function sortUsersList() {
let i, users, shouldSwitch;
let list = document.getElementById("users-list");
let switching = true;
while (switching) {
switching = false;
users = list.getElementsByClassName("list-group-item");
for (i = 0; i < (users.length - 1); ++i) {
shouldSwitch = false;
if (users[i].textContent.toLowerCase() > users[i + 1].textContent.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
users[i].parentNode.insertBefore(users[i + 1], users[i]);
switching = true;
}
}
}
/**
* Action performed after click on the add-user-button button.
* Add the user in the user list.
*/
$(document).on("click", ".add-user-button", function addUserToList() {
//get user attach to the frame
const frame = this.parentElement.getElementsByClassName("user-frame-image")[0];
const frameId = frame.getAttribute("id");
const user = $("#" + frameId).data(frameId);
//id for the futur user a in the list
const id = user.login.split(' ').join('-') + "-list";
//check if user is already in the list
if (isUserInList(id)) return;
const a = document.createElement("a");
a.setAttribute("href", "#");
a.setAttribute("class", "list-group-item user-list");
a.setAttribute("id", id);
const spanUserName = document.createElement("span");
spanUserName.setAttribute("class", "users-list-name")
spanUserName.textContent = user.login;
const button = document.createElement("button");
button.setAttribute("type", "button");
button.setAttribute("class", "close delete-user");
button.setAttribute("aria-label", "Close");
const span = document.createElement("span");
span.setAttribute("aria-hidden", "true");
span.innerHTML = "×";
a.appendChild(spanUserName)
button.appendChild(span);
a.appendChild(button);
const element = document.getElementById("users-list");
element.appendChild(a);
//attach user to user element in list
$("#" + id).data(id, user);
//sort the list
sortUsersList();
});
/**
* Action performed after click on the compare users button
* Open model with the users comparison.
*/
$(document).on("click", "#compare-user-btn", function() {
//get users
const userslist = $("#users-list").children();
const alert = $("#compare-user-alert");
//need at least 2 users to compare
if (userslist.length < 2) {
alert.html("Need at lest 2 users");
setTimeout(() => alert.html(""), 1500);
return;
}
//no more than 6 users (for readability purpose)
else if (userslist.length > 6) {
alert.html("No more than 6 users");
setTimeout(() => alert.html(""), 1500);
return;
}
//initialize array with all UserList objects
let users = [];
for (let i = 0; i < userslist.length; ++i) {
const id = userslist[i].getAttribute("id")
users.push($("#" + id).data(id));
}
//get table informations
const table = $("#users-comparison-table");
const headRow = $("#head-row");
const rows = $("#sorted-tbody").children();
//clear the table
table.find("th").not("th").remove();
table.find("td").not("th").remove();
//users images
for (let i = 0; i < users.length; i++) {
const td = document.createElement("td");
td.setAttribute("class", "text-center table-row");
const img = document.createElement("img");
img.setAttribute("src", users[i].avatar_url);
img.setAttribute("class", "rounded-circle table-user-image");
td.append(img);
const button = document.createElement("button");
button.setAttribute("type", "button");
button.setAttribute("class", "close modal-delete-user");
button.setAttribute("aria-label", "Close");
const span = document.createElement("span");
span.setAttribute("aria-hidden", "true");
span.innerHTML = "×";
button.appendChild(span);
td.appendChild(button);
headRow.append(td);
}
//users names
for (let i = 0; i < users.length; i++) {
const td = document.createElement("td");
td.class = "text-center table-row";
td.textContent = users[i].login;
rows[0].append(td);
}
//user infos
for (let i = 0; i < users.length; i++) {
//commits
let td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = users[i].stats.c;
rows[1].append(td);
//++
td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = users[i].stats.a;
rows[2].append(td);
//--
td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = users[i].stats.d;
rows[3].append(td);
//ratio
td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = Math.round((users[i].stats.a / users[i].stats.d) * 100) / 100;
rows[4].append(td);
//followers
td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = users[i].stats.fr;
rows[5].append(td);
//following
td = document.createElement("td");
td.setAttribute("class", "table-row");
td.textContent = users[i].stats.fg;
rows[6].append(td);
}
//bold all
boldBiggestVules();
$("#users-comparison-table #sorted-head tr").sortable("refresh");
//code inspired by https://johnny.github.io/jquery-sortable/#
$("#users-comparison-table").sortable({
containerSelector: "#users-comparison-table",
itemPath: '> tbody',
itemSelector: 'tr',
placeholder: '<tr class="placeholder"/>'
});
var oldIndex;
$('#sorted-head tr').sortable({
containerSelector: 'tr',
itemSelector: 'td',
placeholder: '<th class="placeholder"/>',
vertical: false,
onDragStart: function ($item, container, _super) {
oldIndex = $item.index();
$item.appendTo($item.parent());
_super($item, container);
},
onDrop: function ($item, container, _super) {
var field,
newIndex = $item.index();
if(newIndex != oldIndex) {
$item.closest('table').find('tbody tr').each(function (i, row) {
row = $(row);
if(newIndex < oldIndex) {
row.children().eq(newIndex).before(row.children()[oldIndex]);
} else if (newIndex > oldIndex) {
row.children().eq(newIndex).after(row.children()[oldIndex]);
}
});
}
_super($item, container);
}
});
$("#compare-users-modal").modal();
});
/**
* Action performed after click on a user frame or user name in the users list.
* Open model with the user informations.
*/
$(document).on("click", ".user-frame-image, .user-list", function () {
//get user
const id = this.getAttribute("id");
user = $("#" + id).data(id);
//title
$("#user-info-modal-title").text(user.login);
//image
$("#user-modal-image").attr("src", user.avatar_url);
//infos
$("#user-infos-commit").text(user.stats.c);
$("#user-infos-add").text(user.stats.a);
$("#user-infos-del").text(user.stats.d);
$("#user-infos-ratio").text(Math.round((user.stats.a / user.stats.d) * 100) / 100);
$("#user-infos-followers").text(user.stats.fr);
$("#user-infos-following").text(user.stats.fg);
//open modal
$("#user-info-modal").modal();
});
/**
* Action performed after click on a cross in the users list.
* Delete the user from the list.
*/
$(document).on("click", ".delete-user", function (e) {
e.stopPropagation();
this.parentElement.parentElement.removeChild(this.parentElement);
});
/**
* Action performed after click on a cross in a column in the table
* Delete the column selected
*/
$(document).on("click", ".modal-delete-user", function (e) {
e.stopPropagation();
const array = this.parentElement.parentElement.children;
for (let i = 0; i < array.length; ++i) {
if (array[i] == this.parentElement) {
$("#head-row").children()[i].remove();
$("#images-row").children()[i].remove();
$("#commits-row").children()[i].remove();
$("#add-row").children()[i].remove();
$("#del-row").children()[i].remove();
$("#ratio-row").children()[i].remove();
$("#followers-row").children()[i].remove();
$("#following-row").children()[i].remove();
break;
}
}
boldBiggestVules();
});
//Initialization of the web page;
initialize();
});
|
import "antd/lib/upload/style/css";
import Upload from "antd/lib/upload";
export default Upload;
|
class SystemStatus extends ComponentWithPreloader {
constructor(fetch_data_path, cloud_connector, container_selector, title, i18n, icons) {
super(container_selector, title);
this.fetch_data_path = fetch_data_path;
this.cloud_connector = cloud_connector;
this.container_selector = container_selector;
this.i18n = i18n;
this.icons = icons;
}
render() {
var container = document.body.querySelector(this.container_selector);
if(!container) {
return '';
}
this.__render_preloader(container);
this.cloud_connector.get_data(this.fetch_data_path)
.then(data => {
var metrics = '';
for (var [metric_key, metric_value] of Object.entries(data['metrics'])) {
metrics +=
(new SystemMetric(
metric_key,
metric_value,
this.i18n(metric_key),
this.icons(metric_key),
this.i18n(data['units'][metric_key]))
).render();
}
var html = `
<h2>${this.title}</h2>
<div class="row">
${metrics}
</div>
`;
this.__sleep(500).then(
() => {
container.innerHTML = '';
container.insertAdjacentHTML('afterbegin', html);
this.__subscribe_to_stream(this.container_selector)
}
);
return html;
});
}
__subscribe_to_stream(container_selector) {
const event_source = new EventSource(this.cloud_connector.subscribe_to_system_status_sse_url());
event_source.onerror = function(error) {
console.error("EventSource failed: ", error);
};
event_source.addEventListener("system_status", function(e) {
const data = JSON.parse(e.data);
if (data.metric) {
// TODO : this logic is duplicated at system-metric.js
var metric_dom = document.body.querySelector(`${container_selector} [data-metric="${data.metric}"] .value`);
if (data.metric === 'start_time') {
const date = new Date(parseInt(data.value) * 1000);
data.value = date.toISOString();
}
metric_dom.innerHTML = data.value;
}
});
}
} |
import React, { useEffect,useState } from 'react'
import './App.css'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { useQuery } from '@apollo/react-hooks'
import gql from 'graphql-tag'
import List from './List';
import withListLoading from './withListLoading';
export const client = new ApolloClient({
link: new HttpLink({
uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2'
}),
fetchOptions: {
mode: 'no-cors'
},
cache: new InMemoryCache()
})
const DAI_QUERY = gql`
query tokens($tokenAddress: Bytes!) {
tokens(where: { id: $tokenAddress }) {
derivedETH
totalLiquidity
}
}
`
const USDC_QUERY = gql`
query tokens($tokenAddress: Bytes!) {
tokens(where: { id: $tokenAddress }) {
derivedETH
totalLiquidity
}
}
`
const ETH_PRICE_QUERY = gql`
query bundles {
bundles(where: { id: "1" }) {
ethPrice
}
}
`
function App() {
const ListLoading = withListLoading(List);
const [appState, setAppState] = useState({
loading: false,
repos: null,
});
const [curveState, setCurveState] = useState({
susdApy: null,
poolApy: null,
susdVolume: null,
poolVolume: null,
});
useEffect(() => {
setAppState({ loading: true });
const apiUrl = `https://cors-anywhere.herokuapp.com/https://api.vesper.finance/pools?stages=prod`;
fetch(apiUrl)
.then((res) => res.json())
.then((repos) => {
setAppState({ loading: false, repos: repos });
});
}, [setAppState]);
useEffect(() => {
const curveURL = `https://stats.curve.fi/raw-stats/apys.json`;
fetch(curveURL)
.then((response) => response.json())
.then((curveData) => {
setCurveState({
susdApy: curveData.apy.day.susd,
poolApy: curveData.apy.day["3pool"],
susdVolume: curveData.volume.susd,
poolVolume: curveData.volume["3pool"]
});
console.log(curveData)
});
}, [setCurveState]);
const { loading: ethLoading, data: ethPriceData } = useQuery(ETH_PRICE_QUERY)
const { loading: daiLoading, data: daiData } = useQuery(DAI_QUERY, {
variables: {
tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f'
}
})
const { loading: usdcLoading, data: usdcData } = useQuery(USDC_QUERY, {
variables: {
tokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'
}
})
const daiPriceInEth = daiData && daiData.tokens[0].derivedETH
const daiTotalLiquidity = daiData && daiData.tokens[0].totalLiquidity
const ethPriceInUSD = ethPriceData && ethPriceData.bundles[0].ethPrice
//USDC data details:
const usdcPriceInEth = usdcData && usdcData.tokens[0].derivedETH
const usdcTotalLiquidity = usdcData && usdcData.tokens[0].totalLiquidity
return (
<div>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex text-center">
<div className="content mr-auto ml-auto">
<div>
<h2>
Dai price:{' '}
{ethLoading || daiLoading
? 'Loading token data...'
: '$' +
(parseFloat(daiPriceInEth) * parseFloat(ethPriceInUSD)).toFixed(2)}
</h2>
<h2>
Dai total liquidity:{' '}
{daiLoading
? 'Loading token data...'
: parseFloat(daiTotalLiquidity).toFixed(0)}
</h2>
</div>
</div>
</main>
<main role="main" className="col-lg-12 d-flex text-center">
{/* USDC */}
<div className="content mr-auto ml-auto">
<div>
<h2>
USDC price:{' '}
{ethLoading || usdcLoading
? 'Loading token data...'
: '$' +
// parse responses as floats and fix to 2 decimals
(parseFloat(usdcPriceInEth) * parseFloat(ethPriceInUSD)).toFixed(2)}
</h2>
<h2>
USDC total liquidity:{' '}
{usdcLoading
? 'Loading token data...'
: // display the total amount of USDC spread across all pools
parseFloat(usdcTotalLiquidity).toFixed(0)}
</h2>
</div>
</div>
</main>
</div>
</div>
<div className='App'>
<div className='container'>
</div>
<div className='repo-container'>
<ListLoading isLoading={appState.loading} repos={appState.repos} />
</div>
</div>
<div className='App'>
<div className='container'>
</div>
<div className='repo-container'>
<h2>Curve.Fi</h2>
<ul>
<li><b>Base Apy (sUSD):</b> {Number((curveState.susdApy*100).toFixed(2))} |
<b>Volume (sUSD):</b> {curveState.susdVolume}</li>
<li><b>Base Apy (3pool):</b> {Number((curveState.poolApy*100).toFixed(2))}|
<b>Volume (3pool):</b> {curveState.poolVolume}</li>
</ul>
</div>
</div>
</div>
);
}
export default App
|
$(function()
{
var rmbtn_cb = function()
{
if(!confirm('真的要删除吗?'))
return;
var row = $(this).parent().parent();
var id = row.children(':eq(0)').text();
$.get("./admin?action=rmuser&id=" + id, function(res)
{
var json = JSON.parse(res);
if(json.errno == 0)
row.remove();
else
alert("删除失败!" + json.errmsg);
});
};
$(".rmbtn").click(rmbtn_cb);
}); |
$('#alert').click(function() {
alert('Thank you!');
}); |
const chai = require('chai');
const chaiSpies = require('chai-spies');
const reverseString = require('../problems/reverse-string.js')
let expect = chai.expect;
describe('reverseString()', () => {
context("When input is a string", () => {
it('Should reverse the string', () => {
const input = 'fun';
const output = 'nuf';
expect(reverseString(output)).to.equal(input);
});
});
context("when input is not a string", () => {
it("should throw a type error when the input is not a string", () => {
expect(() => reverseString(!String)).to.throw(TypeError)
});
});
});
|
angular.module('AdAcc').controller('EditAccPstgController', function($scope, $routeParams, $location, AccPstgResource ) {
var self = this;
$scope.disabled = false;
$scope.$location = $location;
$scope.get = function() {
var successCallback = function(data){
self.original = data;
$scope.accPstg = new AccPstgResource(self.original);
};
var errorCallback = function() {
$location.path("/AccPstgs");
};
AccPstgResource.get({AccPstgId:$routeParams.AccPstgId}, successCallback, errorCallback);
};
$scope.isClean = function() {
return angular.equals(self.original, $scope.accPstg);
};
$scope.save = function() {
var successCallback = function(){
$scope.get();
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError=true;
};
$scope.accPstg.$update(successCallback, errorCallback);
};
$scope.cancel = function() {
$location.path("/AccPstgs");
};
$scope.remove = function() {
var successCallback = function() {
$location.path("/AccPstgs");
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError=true;
};
$scope.accPstg.$remove(successCallback, errorCallback);
};
$scope.pstgDirList = [
"DEBIT",
"CREDIT"
];
$scope.accTypeList = [
"CAPITAL_ACC",
"ESTATE_ASSETS_ACC",
"GENERAL_ASSETS_ACC",
"THIRD_PARTY_ACC",
"TREASURY_ACC",
"EXPENSE_ACC",
"INCOME_ACC",
"CLOSING_ACC"
];
$scope.opTypeList = [
"CAPITAL_PYMT",
"CAPITAL_WDWL",
"RENTAL_DPST",
"TAX_ON_RENT",
"RENT_PYMT",
"UNMAT_EXPENSE",
"OP_EXPENSE",
"NOOP_EXPENSE",
"MAT_EXPENSE",
"UNREAL_INCOME",
"OP_INCOME",
"NOOP_INCOME",
"REAL_INCOME",
"TREASURY_MVMT",
"VAT_PYMT",
"INCOME_TAX_WH",
"SALARY",
"SALARY_PYMT",
"AUX_TAX_PYMT",
"AMORTISATION",
"RISK_PROVISION",
"WARANTY",
"GRATUITY",
"DONNATION",
"STOCK_CORRECT",
"SALES_COMM",
"PURCHASE_COMM",
"SALES",
"PURCHASE",
"ASSET_VAL_CORRECT",
"OTHER_SALES_EXP",
"OTHER_PURCHASE_EXP",
"OTHER_SALES_INC",
"OTHER_PURCHASE_INC",
"GENERAL_PYMT",
"GENERAL_ENCASHMT"
];
$scope.get();
}); |
// https://github.com/connorgr/d3-cam02 Version 0.1.4. Copyright 2016 Connor Gramazio.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-color')) :
typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) :
(factory((global.d3 = global.d3 || {}),global.d3));
}(this, (function (exports,d3Color) { 'use strict';
var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;
// Implementation based on Billy Bigg's CIECAM02 implementation in C
// (http://scanline.ca/ciecam02/)
// and information on Wikipedia (https://en.wikipedia.org/wiki/CIECAM02)
//
// IMPORTANT NOTE : uses XYZ [0,100] not [0,1]
//
// When transforming colors into CIECAM02 space we use Luo et al.'s uniform
// color space transform; however, we also provide commented out transform
// coefficients for the long-distance and short-distance CIECAM02 transforms,
// should others desire to use these alternative perceptually uniform
// approximation spaces instead.
//
// Another important note is that we provide the full range of CIECAM02 color
// values in the JCh constructor, but the d3 color object stores only lightness
// (J), chroma (C), and hue (h).
//
// used for brighter and darker functions
// Kn is completely arbitrary and was picked originally by Mike Bostock to make
// the Lab brighter and darker functions behave similarly to the RGB equivalents
// in d3-color. We copy and paste the value directly and encourage others to
// add a more systematically chosen value.
var Kn = 18;
// Conversion functions
function rgb2xyz(r, g, b) {
r = r / 255.0;
g = g / 255.0;
b = b / 255.0;
// assume sRGB
r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
// Convert to XYZ in [0,100] rather than [0,1]
return {
x: ( (r * 0.4124) + (g * 0.3576) + (b * 0.1805) ) * 100.0,
y: ( (r * 0.2126) + (g * 0.7152) + (b * 0.0722) ) * 100.0,
z: ( (r * 0.0193) + (g * 0.1192) + (b * 0.9505) ) * 100.0
};
}
function xyz2rgb(x, y, z) {
x = x / 100.0;
y = y / 100.0;
z = z / 100.0;
var preR = x * 3.2404542 + y * -1.5371385 - z * 0.4985314,
preG = x * -0.9692660 + y * 1.8760108 + z * 0.0415560,
preB = x * 0.0556434 + y * -0.2040259 + z * 1.0572252;
function toRGB(c) {
return 255.0 * (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
}
return {r: toRGB(preR), g: toRGB(preG), b: toRGB(preB)};
}
function xyz2cat02(x,y,z) {
var l = ( 0.7328 * x) + (0.4296 * y) - (0.1624 * z),
m = (-0.7036 * x) + (1.6975 * y) + (0.0061 * z),
s = ( 0.0030 * x) + (0.0136 * y) + (0.9834 * z);
return {l: l, m: m, s: s};
}
function cat022xyz(l, m, s) {
var x = ( 1.096124 * l) - (0.278869 * m) + (0.182745 * s),
y = ( 0.454369 * l) + (0.473533 * m) + (0.072098 * s),
z = (-0.009628 * l) - (0.005698 * m) + (1.015326 * s);
return {x: x, y: y, z:z};
}
function cat022hpe(l,m,s) {
var lh = ( 0.7409792 * l) + (0.2180250 * m) + (0.0410058 * s),
mh = ( 0.2853532 * l) + (0.6242014 * m) + (0.0904454 * s),
sh = (-0.0096280 * l) - (0.0056980 * m) + (1.0153260 * s);
return {lh: lh, mh: mh, sh: sh};
}
function hpe2xyz(l, m, s) {
var x = (1.910197 * l) - (1.112124 * m) + (0.201908 * s),
y = (0.370950 * l) + (0.629054 * m) - (0.000008 * s),
z = s;
return {x:x, y:y, z:z};
}
function nonlinearAdaptation(coneResponse, fl) {
var p = Math.pow( (fl * coneResponse) / 100.0, 0.42 );
return ((400.0 * p) / (27.13 + p)) + 0.1;
}
function inverseNonlinearAdaptation(coneResponse, fl) {
return (100.0 / fl) *
Math.pow((27.13 * Math.abs(coneResponse - 0.1)) /
(400.0 - Math.abs(coneResponse - 0.1)),
1.0 / 0.42);
}
// CIECAM02_VC viewing conditions; assumes average viewing conditions
var CIECAM02_VC = (function() {
var vc = {
D65_X: 95.047, // D65 standard referent
D65_Y: 100.0,
D65_Z: 108.883,
// Viewing conditions
// Note about L_A:
// Billy Bigg's implementation just uses a value of 4 cd/m^2, but
// the colorspacious implementation uses greater precision by calculating
// it with (64 / numpy.pi) / 5
// This is based on Moroney (2000), "Usage guidelines for CIECAM97s" where
// sRGB illuminance is 64 lux. Because of its greater precision we use
// Moroney's alternative definition.
la: (64.0 / Math.PI) / 5.0,
yb: 20.0, // 20% gray
// Surround
f: 1.0, // average; dim: 0.9; dark: 0.8
c: 0.69, // average; dim: 0.59; dark: 0.525
nc: 1.0 // average; dim: 0.95; dark: 0.8
};
vc.D65_LMS = xyz2cat02(vc.D65_X, vc.D65_Y, vc.D65_Z),
vc.n = vc.yb / vc.D65_Y;
vc.z = 1.48 + Math.sqrt(vc.n);
var k = 1.0 / ((5.0 * vc.la) + 1.0);
vc.fl = (0.2 * Math.pow(k, 4.0) * (5.0 * vc.la)) +
0.1 * Math.pow(1.0 - Math.pow(k, 4.0), 2.0) *
Math.pow(5.0 * vc.la, 1.0/3.0);
vc.nbb = 0.725 * Math.pow(1.0 / vc.n, 0.2);
vc.ncb = vc.nbb;
vc.d = vc.f * ( 1.0 - (1.0 / 3.6) * Math.exp((-vc.la - 42.0) / 92.0) );
vc.achromaticResponseToWhite = (function() {
var l = vc.D65_LMS.l,
m = vc.D65_LMS.m,
s = vc.D65_LMS.s;
var lc = l * (((vc.D65_Y * vc.d) / l) + (1.0 - vc.d)),
mc = m * (((vc.D65_Y * vc.d) / m) + (1.0 - vc.d)),
sc = s * (((vc.D65_Y * vc.d) / s) + (1.0 - vc.d));
var hpeTransforms = cat022hpe(lc, mc, sc),
lp = hpeTransforms.lh,
mp = hpeTransforms.mh,
sp = hpeTransforms.sh;
var lpa = nonlinearAdaptation(lp, vc.fl),
mpa = nonlinearAdaptation(mp, vc.fl),
spa = nonlinearAdaptation(sp, vc.fl);
return (2.0 * lpa + mpa + 0.05 * spa - 0.305) * vc.nbb;
})();
return vc;
})(); // end CIECAM02_VC
function cat022cam02(l,m,s) {
var theColor = {};
var D65_CAT02 = xyz2cat02(CIECAM02_VC.D65_X,CIECAM02_VC.D65_Y,CIECAM02_VC.D65_Z);
function cTransform(cone, D65_cone) {
var D65_Y = CIECAM02_VC.D65_Y,
VC_d = CIECAM02_VC.d;
return cone * (((D65_Y * VC_d) / D65_cone) + (1.0 - VC_d));
}
var lc = cTransform(l, D65_CAT02.l),
mc = cTransform(m, D65_CAT02.m),
sc = cTransform(s, D65_CAT02.s);
var hpeTransforms = cat022hpe(lc, mc, sc),
lp = hpeTransforms.lh,
mp = hpeTransforms.mh,
sp = hpeTransforms.sh;
var lpa = nonlinearAdaptation(lp, CIECAM02_VC.fl),
mpa = nonlinearAdaptation(mp, CIECAM02_VC.fl),
spa = nonlinearAdaptation(sp, CIECAM02_VC.fl);
var ca = lpa - ((12.0*mpa) / 11.0) + (spa / 11.0),
cb = (1.0/9.0) * (lpa + mpa - 2.0*spa);
theColor.h = (180.0 / Math.PI) * Math.atan2(cb, ca);
if(theColor.h < 0.0) theColor.h += 360.0;
var temp;
if(theColor.h < 20.14) {
temp = ((theColor.h + 122.47)/1.2) + ((20.14 - theColor.h)/0.8);
theColor.H = 300 + (100*((theColor.h + 122.47)/1.2)) / temp;
} else if(theColor.h < 90.0) {
temp = ((theColor.h - 20.14)/0.8) + ((90.00 - theColor.h)/0.7);
theColor.H = (100*((theColor.h - 20.14)/0.8)) / temp;
} else if(theColor.h < 164.25) {
temp = ((theColor.h - 90.00)/0.7) + ((164.25 - theColor.h)/1.0);
theColor.H = 100 + ((100*((theColor.h - 90.00)/0.7)) / temp);
} else if (theColor.h < 237.53) {
temp = ((theColor.h - 164.25)/1.0) + ((237.53 - theColor.h)/1.2);
theColor.H = 200 + ((100*((theColor.h - 164.25)/1.0)) / temp);
} else {
temp = ((theColor.h - 237.53)/1.2) + ((360 - theColor.h + 20.14)/0.8);
theColor.H = 300 + ((100*((theColor.h - 237.53)/1.2)) / temp);
}
var a = ( 2.0*lpa + mpa + 0.05*spa - 0.305 ) * CIECAM02_VC.nbb;
theColor.J = 100.0 * Math.pow(a / CIECAM02_VC.achromaticResponseToWhite,
CIECAM02_VC.c * CIECAM02_VC.z);
var et = 0.25 * (Math.cos((theColor.h * Math.PI) / 180.0 + 2.0) + 3.8),
t = ((50000.0 / 13.0) * CIECAM02_VC.nc * CIECAM02_VC.ncb * et * Math.sqrt(ca*ca + cb*cb)) /
(lpa + mpa + (21.0/20.0)*spa);
theColor.C = Math.pow(t, 0.9) * Math.sqrt(theColor.J / 100.0) *
Math.pow(1.64 - Math.pow(0.29, CIECAM02_VC.n), 0.73);
theColor.Q = (4.0 / CIECAM02_VC.c) * Math.sqrt(theColor.J / 100.0) *
(CIECAM02_VC.achromaticResponseToWhite + 4.0) * Math.pow(CIECAM02_VC.fl, 0.25);
theColor.M = theColor.C * Math.pow(CIECAM02_VC.fl, 0.25);
theColor.s = 100.0 * Math.sqrt(theColor.M / theColor.Q);
return theColor;
}
function Aab2Cat02LMS(A, aa, bb, nbb) {
var x = (A / nbb) + 0.305;
var l = (0.32787 * x) + (0.32145 * aa) + (0.20527 * bb),
m = (0.32787 * x) - (0.63507 * aa) - (0.18603 * bb),
s = (0.32787 * x) - (0.15681 * aa) - (4.49038 * bb);
return {l:l, m:m, s:s};
}
function cam022rgb(J, C, h) {
// NOTE input is small h not big H, the later of which is corrected
var t = Math.pow(C / (Math.sqrt(J / 100.0) *
Math.pow(1.64-Math.pow(0.29, CIECAM02_VC.n), 0.73)),
(1.0 / 0.9)),
et = 1.0 / 4.0 * (Math.cos(((h * Math.PI) / 180.0) + 2.0) + 3.8);
var a = Math.pow( J / 100.0, 1.0 / (CIECAM02_VC.c * CIECAM02_VC.z) ) *
CIECAM02_VC.achromaticResponseToWhite;
var p1 = ((50000.0 / 13.0) * CIECAM02_VC.nc * CIECAM02_VC.ncb) * et / t,
p2 = (a / CIECAM02_VC.nbb) + 0.305,
p3 = 21.0 / 20.0,
p4, p5, ca, cb;
var hr = (h * Math.PI) / 180.0;
if (Math.abs(Math.sin(hr)) >= Math.abs(Math.cos(hr))) {
p4 = p1 / Math.sin(hr);
cb = (p2 * (2.0 + p3) * (460.0 / 1403.0)) /
(p4 + (2.0 + p3) * (220.0 / 1403.0) *
(Math.cos(hr) / Math.sin(hr)) - (27.0 / 1403.0) +
p3 * (6300.0 / 1403.0));
ca = cb * (Math.cos(hr) / Math.sin(hr));
}
else {
p5 = p1 / Math.cos(hr);
ca = (p2 * (2.0 + p3) * (460.0 / 1403.0)) /
(p5 + (2.0 + p3) * (220.0 / 1403.0) -
((27.0 / 1403.0) - p3 * (6300.0 / 1403.0)) *
(Math.sin(hr) / Math.cos(hr)));
cb = ca * (Math.sin(hr) / Math.cos(hr));
}
var lms_a = Aab2Cat02LMS(a, ca, cb, CIECAM02_VC.nbb),
lpa = lms_a.l,
mpa = lms_a.m,
spa = lms_a.s;
var lp = inverseNonlinearAdaptation(lpa, CIECAM02_VC.fl),
mp = inverseNonlinearAdaptation(mpa, CIECAM02_VC.fl),
sp = inverseNonlinearAdaptation(spa, CIECAM02_VC.fl);
var txyz = hpe2xyz(lp, mp, sp),
lms_c = xyz2cat02(txyz.x, txyz.y, txyz.z);
var D65_CAT02 = xyz2cat02(CIECAM02_VC.D65_X, CIECAM02_VC.D65_Y,
CIECAM02_VC.D65_Z);
var l = lms_c.l / ( ((CIECAM02_VC.D65_Y * CIECAM02_VC.d) / D65_CAT02.l) +
(1.0 - CIECAM02_VC.d) ),
m = lms_c.m / ( ((CIECAM02_VC.D65_Y * CIECAM02_VC.d) / D65_CAT02.m) +
(1.0 - CIECAM02_VC.d) ),
s = lms_c.s / ( ((CIECAM02_VC.D65_Y * CIECAM02_VC.d) / D65_CAT02.s) +
(1.0 - CIECAM02_VC.d) );
var xyz = cat022xyz(l, m, s),
rgb = xyz2rgb(xyz.x, xyz.y, xyz.z);
return rgb;
}
function jchConvert(o) {
if (o instanceof JCh) return new JCh(o.J, o.C, o.h, o.opacity);
if (!(o instanceof d3Color.rgb)) o = d3Color.rgb(o);
var xyz = rgb2xyz(o.r, o.g, o.b),
lmsConeResponses = xyz2cat02(xyz.x,xyz.y,xyz.z),
cam02obj = cat022cam02(lmsConeResponses.l,lmsConeResponses.m,
lmsConeResponses.s);
return new JCh(cam02obj.J, cam02obj.C, cam02obj.h, o.opacity);
}
function jch(J, C, h, opacity) {
return arguments.length === 1 ? jchConvert(J) : new JCh(J, C, h,
opacity == null ? 1 : opacity);
}
function JCh(J, C, h, opacity) {
this.J = +J;
this.C = +C;
this.h = +h;
this.opacity = +opacity;
}
var jchPrototype = JCh.prototype = jch.prototype = Object.create(d3Color.color.prototype);
jchPrototype.constructor = JCh;
jchPrototype.brighter = function(k) {
return new JCh(this.J + Kn * (k === null ? 1 : k), this.C, this.h,
this.opacity);
};
jchPrototype.darker = function(k) {
return new JCh(this.J - Kn * (k === null ? 1 : k), this.C, this.h,
this.opacity);
};
jchPrototype.rgb = function () {
var converted = cam022rgb(this.J, this.C, this.h);
return d3Color.rgb(converted.r, converted.g, converted.b, this.opacity);
};
////////////////////////////////////////////////////////////////////////////////
// Updated attempts at perceptually uniform color spaces
// Formulas and constants taken from
// M.R. Luo and C. Li. "CIECAM02 and Its Recent Developments"
var altCam02Coef = {
lcd: {k_l: 0.77, c1: 0.007, c2:0.0053},
scd: {k_l: 1.24, c1: 0.007, c2:0.0363},
ucs: {k_l: 1.00, c1: 0.007, c2:0.0228}
};
function jabConvert(o) {
if(o instanceof Jab) {
return new Jab(o.J, o.a, o.b, o.opacity);
}
if (!(o instanceof d3Color.rgb)) o = d3Color.rgb(o);
var xyz = rgb2xyz(o.r, o.g, o.b),
lmsConeResponses = xyz2cat02(xyz.x,xyz.y,xyz.z),
cam02 = cat022cam02(lmsConeResponses.l, lmsConeResponses.m, lmsConeResponses.s);
var coefs = altCam02Coef.ucs;
var JPrime = ((1.0 + 100.0*coefs.c1) * cam02.J) / (1.0 + coefs.c1 * cam02.J);
JPrime = JPrime / coefs.k_l;
var MPrime = (1.0/coefs.c2) * Math.log(1.0 + coefs.c2*cam02.M); // log=ln
var a = MPrime * Math.cos(deg2rad*cam02.h),
b = MPrime * Math.sin(deg2rad*cam02.h);
return new Jab(JPrime, a, b, o.opacity);
}
// DE color distance function generator for the three CAM02 perceptually uniform
// models: lcd, scd, and ucs
function cam02de(coefs) {
return function(o) {
if (!(o instanceof Jab)) o = jabConvert(o);
var k_l = coefs.k_l,
diffJ = Math.abs(this.J - o.J),
diffA = Math.abs(this.a - o.a),
diffB = Math.abs(this.b - o.b);
var de = Math.sqrt( (diffJ/k_l)*(diffJ/k_l) + diffA*diffA + diffB*diffB );
return de;
};
}
function jab(J, a, b, opacity) {
opacity = opacity == null ? 1 : opacity;
return arguments.length === 1 ? jabConvert(J) :
new Jab(J, a, b, opacity);
}
function Jab(J, a, b, opacity) {
this.J = J;
this.a = a;
this.b = b;
this.opacity = opacity;
}
var jabPrototype = Jab.prototype = jab.prototype = Object.create(d3Color.color.prototype);
jabPrototype.constructor = JCh;
jabPrototype.brighter = function(k) {
return new Jab(this.J + Kn * (k === null ? 1 : k), this.a, this.b,
this.opacity);
};
jabPrototype.darker = function(k) {
return new Jab(this.J - Kn * (k === null ? 1 : k), this.a, this.b,
this.opacity);
};
jabPrototype.rgb = function() {
var coefs = altCam02Coef.ucs;
var J = this.J, a = this.a, b = this.b;
// Get the new M using trigonomic identities
// MPrime = (1.0/coefs.c2) * Math.log(1.0 + coefs.c2*cam02.M); // log=ln
// var a = MPrime * Math.cos(o.h),
// b = MPrime * Math.sin(o.h);
// x*x = (x*cos(y))*(x(cos(y))) + (x*sin(y))*(x(sin(y)))
var newMPrime = Math.sqrt(a*a + b*b),
newM = (Math.exp(newMPrime * coefs.c2) - 1.0) / coefs.c2;
var newh = rad2deg*Math.atan2(b,a);
if(newh < 0) newh = 360.0 + newh;
// M = C * Math.pow(CIECAM02_VC.fl, 0.25);
// C = M / Math.pow(CIECAM02_VC.fl, 0.25);
var newC = newM / Math.pow(CIECAM02_VC.fl, 0.25);
// Last, derive the new Cam02J
// JPrime = ((1.0 + 100.0*coefs.c1) * cam02.J) / (1.0 + coefs.c1 * cam02.J)
// simplified: var cam02J = JPrime / (1.0 + coefs.c1*(100.0 - JPrime));
// if v = (d*x) / (b + a*x), x = (b*(v/d)) / (1 - a(v/d))
var newCam02J = J / (1.0 + coefs.c1*(100.0 - J));
var converted = cam022rgb(newCam02J, newC, newh);
return d3Color.rgb(converted.r, converted.g, converted.b, this.opacity);
};
jabPrototype.de = cam02de(altCam02Coef.ucs);
function interpolateJab(start, end) {
// constant, linear, and colorInterpolate are taken from d3-interpolate
// the colorInterpolate function is `nogamma` in the d3-interpolate's color.js
function constant(x) { return function() { return x; } }
function linear(a, d) { return function(t) { return a + t * d; }; }
function colorInterpolate(a, b) {
var d = b - a;
return d ? linear(a, d) : constant(isNaN(a) ? b : a);
}
start = jabConvert(start);
end = jabConvert(end);
// TODO import color function from d3-interpolate
var J = colorInterpolate(start.J, end.J),
a = colorInterpolate(start.a, end.a),
b = colorInterpolate(start.b, end.b),
opacity = colorInterpolate(start.opacity, end.opacity);
return function(t) {
start.J = J(t);
start.a = a(t);
start.b = b(t);
start.opacity = opacity(t);
return start + "";
};
}
exports.jch = jch;
exports.jab = jab;
exports.interpolateJab = interpolateJab;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
// ==UserScript==
// @name Degenderator
// @namespace http://www.pribluda.de/
// @version 0.1
// @description improve reader experience by removing gendrerstern
// @include *
// @author Konstantin Pribluda
// @grant none
// ==/UserScript==
(function() {
'use strict';
const traverse = function(node) {
if(node){
if(node.nodeType == Node.TEXT_NODE)
{
node.data = node.data.replace(/[*:_]innen/gi,"")
}
else
if(node.nodeType == Node.ELEMENT_NODE)
{ node.childNodes.forEach(traverse)}
}
}
document.body.childNodes.forEach(traverse)
})(); |
import React, { useContext } from 'react';
const ThemeContext = React.createContext()
export default function Parent() {
return (
<ThemeContext.Provider value='dark'>
<Child data="something for grandChild"></Child>
</ThemeContext.Provider>
)
}
function Child() {
return (
<GrandChild ></GrandChild>
)
}
function GrandChild() {
const theme = useContext(ThemeContext);
return (
<div>{theme}</div>
)
} |
easyNutri.controller('mudarPasswordCtrl', ['$scope', '$http', 'WebServiceFactory', 'modalFactory', '$ionicPopup',
'$window', '$rootScope', '$ionicLoading',
function ($scope, $http, WebServiceFactory, modalFactory, $ionicPopup, $window, $rootScope, $ionicLoading) {
$scope.pass = {};
var toast = function (texto, caso) {
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-bottom-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "100",
"timeOut": "3000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
switch (caso) {
case 1:
toastr.success(texto);
break;
case 2:
toastr.error(texto);
break;
case 3:
toastr.info(texto);
break;
}
};
var isValid = function (passwords) {
var mensagem = "";
if (passwords.antiga == undefined || passwords.antiga == "") {
mensagem += "Preencha a password antiga; ";
}
if (passwords.nova == undefined || passwords.nova == "") {
mensagem += "Preencha a password nova; ";
}
if (passwords.nova.indexOf(' ') != -1) {
mensagem += "A password não pode conter espaços; ";
}
if (passwords.PasswordConfirma == undefined || passwords.PasswordConfirma == "") {
mensagem += "Preencha a password para confirmar; ";
}
if (passwords.nova != passwords.PasswordConfirma) {
mensagem += "A password nova e a password de confirmação não são iguais; ";
}
if (mensagem != "") {
toast(mensagem, 2);
return false;
}
return true;
};
var mostrarSpinner = function () {
$ionicLoading.show({
content: '<i class="icon ion-load-a"></i>',
animation: 'fade-in',
showBackdrop: false,
maxWidth: 50,
showDelay: 0
});
};
var esconderSpinner = function () {
$ionicLoading.hide();
};
$scope.hideModal = function () {
$scope.mudarPasswordModal.hide();
};
$scope.mudarPassword = function (passwords) {
if (isValid(passwords)) {
mostrarSpinner();
WebServiceFactory.verificarConexao().success(function () {
var arrayHash = {};
passwords.nova = passwords.nova.trim();
var hashNova = CryptoJS.SHA256(passwords.nova);
hashNova = hashNova.toString(CryptoJS.enc.Hex);
var hashVelha = CryptoJS.SHA256(passwords.antiga);
hashVelha = hashVelha.toString(CryptoJS.enc.Hex);
arrayHash.nova = hashNova;
arrayHash.antiga = hashVelha;
WebServiceFactory.mudarPasswordWeb(arrayHash).success(function () {
var stringDescodificada;
if ($rootScope.guardarCredenciais) {
stringDescodificada = atob($window.localStorage.getItem('credencial'));
} else {
stringDescodificada = atob($rootScope.credencial);
}
var res = stringDescodificada.split(':');
var string = res[0] + ":" + hashNova;
var stringEncoded = btoa(string);
if ($rootScope.guardarCredenciais) {
$window.localStorage.setItem('credencial', stringEncoded);
} else {
$rootScope.credencial = stringEncoded;
}
esconderSpinner();
$scope.hideModal();
toast('Password alterada com sucesso!', 1);
}).error(function (data, status, header) {
esconderSpinner();
toast('Erro a alterar a password', 2);
});
}).error(function () {
esconderSpinner();
toast('Não está ligado à rede', 3);
});
}
};
}]); |
import React from "react";
import {
WithStore,
Slider,
Slide,
DotGroup
} from "pure-react-carousel";
class SliderCrousel extends React.Component {
componentDidMount() {
let interval = this.createInterval();
let carousel = document.getElementById('slider-carousel');
carousel.onmouseover = () => {
clearInterval(interval);
}
carousel.onmouseout = () => {
interval = this.createInterval();
}
console.log(carousel);
}
createInterval() {
return setInterval(() => {
if (this.props.currentSlide < this.props.totalSlides - 1) {
this.props.carouselStore.setStoreState({
currentSlide: this.props.currentSlide + 1
});
} else {
this.props.carouselStore.setStoreState({ currentSlide: 0 });
}
}, 5000);
}
render() {
return (
<div>
<Slider>
<Slide index={0}>
<div className="slide">
I couldnt possibly use my own eyes to look at the stars, thansk
Starnught App...
</div>
</Slide>
<Slide index={1}>
<div className="slide">
I couldnt possibly use my own eyes to look at the stars, thansk
Starnught App...
</div>
</Slide>
<Slide index={2}>
<div className="slide">
I couldnt possibly use my own eyes to look at the stars, thansk
Starnught App...
</div>
</Slide>
</Slider>
<DotGroup />
</div>
);
}
}
export default WithStore(SliderCrousel, state => ({
currentSlide: state.currentSlide,
disableAnimation: state.disableAnimation,
hasMasterSpinner: state.hasMasterSpinner,
imageErrorCount: state.imageErrorCount,
imageSuccessCount: state.imageSuccessCount,
lockOnWindowScroll: state.lockOnWindowScroll,
masterSpinnerThreshold: state.masterSpinnerThreshold,
naturalSlideHeight: state.naturalSlideHeight,
naturalSlideWidth: state.naturalSlideWidth,
orientation: state.orientation,
slideSize: state.slideSize,
slideTraySize: state.slideTraySize,
step: state.step,
totalSlides: state.totalSlides,
touchEnabled: state.touchEnabled,
visibleSlides: state.visibleSlides
}));
|
/**
* Date:01/04/2021
* Author: Muhammad Minhaj
* Title: WEB LAYOUT
* Description: Website layout for each page
* * */
import { Container } from '@material-ui/core';
import Alert from './Alert';
import Footer from './Footer';
import Header from './Header';
function Layout({ children }) {
return (
<>
{/* Header */}
<Header />
{/* Container */}
<main>
<Container>{children}</Container>
</main>
<Alert />
{/* Footer */}
<Footer />
</>
);
}
export default Layout;
|
/* global escapeHTML */
/**
* @namespace
*/
OC.Share = _.extend(OC.Share || {}, {
SHARE_TYPE_USER:0,
SHARE_TYPE_GROUP:1,
SHARE_TYPE_LINK:3,
SHARE_TYPE_GUEST:4,
SHARE_TYPE_REMOTE:6,
STATE_ACCEPTED: 0,
STATE_PENDING: 1,
STATE_REJECTED: 2,
/**
* Regular expression for splitting parts of remote share owners:
* "user@example.com/path/to/owncloud"
* "user@anotherexample.com@example.com/path/to/owncloud
*/
_REMOTE_OWNER_REGEXP: new RegExp("^([^@]*)@(([^@]*)@)?([^/]*)([/](.*)?)?$"),
/**
* @deprecated use OC.Share.currentShares instead
*/
itemShares:[],
/**
* Full list of all share statuses
*/
statuses:{},
/**
* Shares for the currently selected file.
* (for which the dropdown is open)
*
* Key is item type and value is an array or
* shares of the given item type.
*/
currentShares: {},
/**
* Whether the share dropdown is opened.
*/
droppedDown:false,
/**
* Loads ALL share statuses from server, stores them in
* OC.Share.statuses then calls OC.Share.updateIcons() to update the
* files "Share" icon to "Shared" according to their share status and
* share type.
*
* If a callback is specified, the update step is skipped.
*
* @param itemType item type
* @param fileList file list instance, defaults to OCA.Files.App.fileList
* @param callback function to call after the shares were loaded
*/
loadIcons:function(itemType, fileList, callback) {
var path = fileList.dirInfo.path;
if (path === '/') {
path = '';
}
path += '/' + fileList.dirInfo.name;
// Load all share icons
$.get(
OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares',
{
subfiles: 'true',
path: path,
format: 'json'
}, function(result) {
if (result && result.ocs.meta.statuscode === 200) {
OC.Share.statuses = {};
$.each(result.ocs.data, function(it, share) {
if (!(share.item_source in OC.Share.statuses)) {
OC.Share.statuses[share.item_source] = {link: false};
}
if (share.share_type === OC.Share.SHARE_TYPE_LINK) {
OC.Share.statuses[share.item_source] = {link: true};
}
});
if (_.isFunction(callback)) {
callback(OC.Share.statuses);
} else {
OC.Share.updateIcons(itemType, fileList);
}
}
}
);
},
/**
* Updates the files' "Share" icons according to the known
* sharing states stored in OC.Share.statuses.
* (not reloaded from server)
*
* @param itemType item type
* @param fileList file list instance
* defaults to OCA.Files.App.fileList
*/
updateIcons:function(itemType, fileList){
var item;
var $fileList;
var currentDir;
if (!fileList && OCA.Files) {
fileList = OCA.Files.App.fileList;
}
// fileList is usually only defined in the files app
if (fileList) {
$fileList = fileList.$fileList;
currentDir = fileList.getCurrentDirectory();
}
// TODO: iterating over the files might be more efficient
for (item in OC.Share.statuses){
var iconClass = 'icon-shared';
var data = OC.Share.statuses[item];
var hasLink = data.link;
// Links override shared in terms of icon display
if (hasLink) {
iconClass = 'icon-public';
}
if (itemType !== 'file' && itemType !== 'folder') {
$('a.share[data-item="'+item+'"] .icon').removeClass('icon-shared icon-public').addClass(iconClass);
} else {
// TODO: ultimately this part should be moved to files_sharing app
var file = $fileList.find('tr[data-id="'+item+'"]');
var shareFolder = OC.imagePath('core', 'filetypes/folder-shared');
var img;
if (file.length > 0) {
this.markFileAsShared(file, true, hasLink);
} else {
var dir = currentDir;
if (dir.length > 1) {
var last = '';
var path = dir;
// Search for possible parent folders that are shared
while (path != last) {
if (path === data.path && !data.link) {
var actions = $fileList.find('.fileactions .action[data-action="Share"]');
var files = $fileList.find('.filename');
var i;
for (i = 0; i < actions.length; i++) {
// TODO: use this.markFileAsShared()
img = $(actions[i]).find('img');
if (img.attr('src') !== OC.imagePath('core', 'actions/public')) {
img.attr('src', image);
$(actions[i]).addClass('permanent');
$(actions[i]).html('<span> '+t('core', 'Shared')+'</span>').prepend(img);
}
}
for(i = 0; i < files.length; i++) {
if ($(files[i]).closest('tr').data('type') === 'dir') {
$(files[i]).find('.thumbnail').css('background-image', 'url('+shareFolder+')');
}
}
}
last = path;
path = OC.Share.dirname(path);
}
}
}
}
}
},
/**
* Format a remote address
*
* @param {String} remoteAddress full remote share
* @return {String} HTML code to display
*/
_formatRemoteShare: function(remoteAddress) {
var parts = this._REMOTE_OWNER_REGEXP.exec(remoteAddress);
if (!parts) {
// display as is, most likely to be a simple owner name
return escapeHTML(remoteAddress);
}
var userName = parts[1];
var userDomain = parts[3];
var server = parts[4];
var dir = parts[6];
var tooltip = userName;
if (userDomain) {
tooltip += '@' + userDomain;
}
if (server) {
if (!userDomain) {
userDomain = '…';
}
tooltip += '@' + server;
}
var html = '<span class="remoteAddress" title="' + escapeHTML(tooltip) + '">';
html += '<span class="username">' + escapeHTML(userName) + '</span>';
if (userDomain) {
html += '<span class="userDomain">@' + escapeHTML(userDomain) + '</span>';
}
html += '</span>';
return html;
},
/**
* Loop over all recipients in the list and format them using
* all kind of fancy magic.
*
* @param {String[]} recipients array of all the recipients
* @return {String[]} modified list of recipients
*/
_formatShareList: function(recipients) {
var _parent = this;
return $.map(recipients, function(recipient) {
recipient = _parent._formatRemoteShare(recipient);
return recipient;
});
},
/**
* Marks/unmarks a given file as shared by changing its action icon
* and folder icon.
*
* @param $tr file element to mark as shared
* @param hasShares whether shares are available
* @param hasLink whether link share is available
*/
markFileAsShared: function($tr, hasShares, hasLink) {
var action = $tr.find('.fileactions .action[data-action="Share"]');
var type = $tr.data('type');
var icon = action.find('.icon');
var message;
var recipients;
var owner = $tr.attr('data-share-owner');
var shareFolderIcon;
var iconClass = 'icon-shared';
action.removeClass('shared-style');
// update folder icon
if (type === 'dir' && (hasShares || hasLink || owner)) {
if (hasLink) {
shareFolderIcon = OC.MimeType.getIconUrl('dir-public');
}
else {
shareFolderIcon = OC.MimeType.getIconUrl('dir-shared');
}
$tr.find('.filename .thumbnail').css('background-image', 'url(' + shareFolderIcon + ')');
$tr.attr('data-icon', shareFolderIcon);
} else if (type === 'dir') {
var mountType = $tr.attr('data-mounttype');
// FIXME: duplicate of FileList._createRow logic for external folder,
// need to refactor the icon logic into a single code path eventually
if (mountType && mountType.indexOf('external') === 0) {
shareFolderIcon = OC.MimeType.getIconUrl('dir-external');
$tr.attr('data-icon', shareFolderIcon);
} else {
shareFolderIcon = OC.MimeType.getIconUrl('dir');
// back to default
$tr.removeAttr('data-icon');
}
$tr.find('.filename .thumbnail').css('background-image', 'url(' + shareFolderIcon + ')');
}
// update share action text / icon
if (hasShares || owner) {
recipients = $tr.attr('data-share-recipients');
action.addClass('shared-style');
message = t('core', 'Shared');
// even if reshared, only show "Shared by"
if (owner) {
message = this._formatRemoteShare(owner);
}
else if (recipients) {
message = t('core', 'Shared with {recipients}', {recipients: this._formatShareList(recipients.split(", ")).join(", ")}, 0, {escape: false});
}
action.html('<span> ' + message + '</span>').prepend(icon);
if (owner || recipients) {
action.find('.remoteAddress').tipsy({gravity: 's'});
}
}
else {
action.html('<span class="hidden-visually">' + t('core', 'Shared') + '</span>').prepend(icon);
}
if (hasLink) {
iconClass = 'icon-public';
}
icon.removeClass('icon-shared icon-public').addClass(iconClass);
},
/**
*
* @param itemType
* @param itemSource
* @param callback - optional. If a callback is given this method works
* asynchronous and the callback will be provided with data when the request
* is done.
* @returns {OC.Share.Types.ShareInfo}
*/
loadItem:function(itemType, itemSource, callback) {
var data = '';
var checkReshare = true;
var async = !_.isUndefined(callback);
if (typeof OC.Share.statuses[itemSource] === 'undefined') {
// NOTE: Check does not always work and misses some shares, fix later
var checkShares = true;
} else {
var checkShares = true;
}
$.ajax({type: 'GET', url: OC.filePath('core', 'ajax', 'share.php'), data: { fetch: 'getItem', itemType: itemType, itemSource: itemSource, checkReshare: checkReshare, checkShares: checkShares }, async: async, success: function(result) {
if (result && result.status === 'success') {
data = result.data;
} else {
data = false;
}
if(async) {
callback(data);
}
}});
return data;
},
share:function(itemType, itemSource, shareType, shareWith, permissions, itemSourceName, expirationDate, callback, errorCallback) {
// Add a fallback for old share() calls without expirationDate.
// We should remove this in a later version,
// after the Apps have been updated.
if (typeof callback === 'undefined' &&
typeof expirationDate === 'function') {
callback = expirationDate;
expirationDate = '';
console.warn(
"Call to 'OC.Share.share()' with too few arguments. " +
"'expirationDate' was assumed to be 'callback'. " +
"Please revisit the call and fix the list of arguments."
);
}
return $.post(OC.filePath('core', 'ajax', 'share.php'),
{
action: 'share',
itemType: itemType,
itemSource: itemSource,
shareType: shareType,
shareWith: shareWith,
permissions: permissions,
itemSourceName: itemSourceName,
expirationDate: expirationDate
}, function (result) {
if (result && result.status === 'success') {
if (callback) {
callback(result.data);
}
} else {
if (_.isUndefined(errorCallback)) {
var msg = t('core', 'Error');
if (result.data && result.data.message) {
msg = result.data.message;
}
OC.dialogs.alert(msg, t('core', 'Error while sharing'));
} else {
errorCallback(result);
}
}
}
);
},
unshare:function(itemType, itemSource, shareType, shareWith, callback) {
$.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'unshare', itemType: itemType, itemSource: itemSource, shareType: shareType, shareWith: shareWith }, function(result) {
if (result && result.status === 'success') {
if (callback) {
callback();
}
} else {
OC.dialogs.alert(t('core', 'Error while unsharing'), t('core', 'Error'));
}
});
},
showDropDown:function(itemType, itemSource, appendTo, link, possiblePermissions, filename) {
var configModel = new OC.Share.ShareConfigModel();
var attributes = {itemType: itemType, itemSource: itemSource, possiblePermissions: possiblePermissions};
var itemModel = new OC.Share.ShareItemModel(attributes, {configModel: configModel});
var dialogView = new OC.Share.ShareDialogView({
id: 'dropdown',
model: itemModel,
configModel: configModel,
className: 'drop shareDropDown',
attributes: {
'data-item-source-name': filename,
'data-item-type': itemType,
'data-item-source': itemSource
}
});
var $dialog = dialogView.render().$el;
$dialog.appendTo(appendTo);
$dialog.slideDown(OC.menuSpeed, function() {
OC.Share.droppedDown = true;
});
itemModel.fetch();
},
hideDropDown:function(callback) {
OC.Share.currentShares = null;
$('#dropdown').slideUp(OC.menuSpeed, function() {
OC.Share.droppedDown = false;
$('#dropdown').remove();
if (typeof FileActions !== 'undefined') {
$('tr').removeClass('mouseOver');
}
if (callback) {
callback.call();
}
});
},
dirname:function(path) {
return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
}
});
$(document).ready(function() {
if(typeof monthNames != 'undefined'){
// min date should always be the next day
var minDate = new Date();
minDate.setDate(minDate.getDate()+1);
$.datepicker.setDefaults({
monthNames: monthNames,
monthNamesShort: monthNamesShort,
dayNames: dayNames,
dayNamesMin: dayNamesMin,
dayNamesShort: dayNamesShort,
firstDay: firstDay,
minDate : minDate
});
}
$(this).click(function(event) {
var target = $(event.target);
var isMatched = !target.is('.drop, .ui-datepicker-next, .ui-datepicker-prev, .ui-icon')
&& !target.closest('#ui-datepicker-div').length && !target.closest('.ui-autocomplete').length;
if (OC.Share && OC.Share.droppedDown && isMatched && $('#dropdown').has(event.target).length === 0) {
OC.Share.hideDropDown();
}
});
});
|
import React,{Component} from "react";
import "./index.css";
import axios from "axios";
class Navbar extends Component{
constructor(){
super();
this.state={
ddddlist:null
}
}
render(){
return (
<div className="ddddAll">
{
this.props.ddShow?
<span>
<ul className="dddd">
<li>商区</li>
<li>地铁站</li>
</ul>
<div className="ddddleft">
<ul>
{
this.props.ddShow?
<div>
{
this.state.ddddlist.map(item=>
<li>
{item.name}
</li>
)
}
</div>
:null
}
</ul>
</div>
<div className="ddddright">ss</div>
</span>
:null
}
</div>
)
}
componentDidMount(){
axios.get("/ajax/filterCinemas?ci=65").then(res=>{
console.log(res.data.district.subItems)
this.setState({
ddddlist:res.data.district.subItems
})
})
}
}
export default Navbar
|
import React, {Component} from 'react';
import {Link} from "react-router-dom";
import '../Styles/Tabs.css';
import {FaGlobe, FaSortDown} from 'react-icons/fa';
class Footer extends Component {
state = {
langContent: false
}
handleToggle = (e) => {
e.preventDefault();
this.setState({
langContent: !this.state.langContent
});
}
handleBlur = () => {
console.log('blur');
this.setState({
langContent: !this.state.langContent
})
}
render() {
return (
<div className='footer-container'>
<p>Questions? <span>Call 1-800-000</span></p>
<div className="footer-columns">
<ul>
<li><Link to=''>FAQ</Link></li>
<li><Link to=''>Investor Relations</Link></li>
<li><Link to=''>Ways To Watch</Link></li>
<li><Link to=''>Information</Link></li>
</ul>
<ul>
<li><Link to=''>Help Center</Link></li>
<li><Link to=''>Jobs</Link></li>
<li><Link to=''>Terms of Use</Link></li>
<li><Link to=''>Contact Us</Link></li>
</ul>
<ul>
<li><Link to=''>Account</Link></li>
<li><Link to=''>Redeem Gift Cards</Link></li>
<li><Link to=''>Privacy</Link></li>
<li><Link to=''>Speed Test</Link></li>
</ul>
<ul>
<li><Link to=''>Media Center</Link></li>
<li><Link to=''>Buy Gift Cards</Link></li>
<li><Link to=''>Cookie preferences</Link></li>
<li><Link to=''>Legal Notices</Link></li>
</ul>
<div className="lang-btn"
onClick={this.handleToggle}>
<FaGlobe/>
English
<FaSortDown onBlur={this.handleBlur}/>
</div>
</div>
{this.state.langContent && (
<div className="toggle-language">
<ul>
<li>English</li>
</ul>
<ul>
<li>Francais</li>
</ul>
</div>
)}
</div>
);
}
}
export default Footer; |
document.getElementById('submitter').addEventListener('mouseover', function () {
console.log("ENT");
var el = document.getElementById('submitter');
bgHighlight(el);
});
document.getElementById('submitter').addEventListener('mouseout', function () {
console.log("EXT");
var el = document.getElementById('submitter');
bgUNHighlight(el);
});
document.getElementById('pf').addEventListener('mouseover', function () {
console.log("PF ENT");
var el = document.getElementById('pf');
highlight(el);
});
document.getElementById('pf').addEventListener('mouseout', function () {
console.log("PF EXT");
var el = document.getElementById('pf');
unHighlight(el);
});
document.getElementById('portraits').addEventListener('mouseover', function () {
console.log("Por ENT");
var el = document.getElementById('portraits');
highlight(el);
});
document.getElementById('portraits').addEventListener('mouseout', function () {
console.log("Por EXT");
var el = document.getElementById('portraits');
unHighlight(el);
});
document.getElementById('portraits').onclick = function () {
location.href = "portraits.html";
};
document.getElementById('pf').onclick = function () {
location.href = "index.html";
};
function highlight(el) {
el.style.color = 'lightgrey';
}
function unHighlight(el) {
el.style.color = 'rgb(128,128,128)';
}
function bgHighlight(el) {
el.style.backgroundColor = 'orange';
}
function bgUNHighlight(el) {
el.style.backgroundColor = 'black';
} |
import React, { Component } from 'react'
import moment from 'moment'
import { Form, Row, Col, Input, Select, Upload, DatePicker, Button, Icon } from 'antd'
import { WeiXinId, ZhiFuBaoId } from '../wxAndzfb'
import UploadImg from '@/components/UploadImg'
import UploadFile from '@/components/UploadFile'
import { bankList, licenceList, formItemLayout } from '../moadel'
const FormItem = Form.Item;
const Option = Select.Option;
class SloveModal extends Component {
constructor(props) {
super(props)
this.state = {
acctype: 'organization',
passways: [],
endOpen: false,
}
}
handleSubmit = () => {
this.props.form.validateFields((err, values) => {
console.log(values);
this.props.onSubmit(err, values);
});
}
/**
* 开户银行列表
*/
getBank = () => {
return bankList.map((item, index) => {
return <Option key={index} value={item}>{item}</Option>
}
)
}
getLicence = () => {
return licenceList.map((item, index) => {
return <Option key={index} value={item.number}>{item.type}</Option>
}
)
}
handleUpload = (e) => {
console.log(e)
}
/********开始、结束日期关联***********/
disabledStartDate = (startValue) => {
const endValue = this.state.endValue;
if (!startValue || !endValue) {
return false;
}
return startValue.valueOf() > endValue.valueOf();
}
disabledEndDate = (endValue) => {
const startValue = this.state.startValue;
if (!endValue || !startValue) {
return false;
}
return endValue.valueOf() <= startValue.valueOf();
}
onChange = (field, value) => {
this.setState({
[field]: value,
});
}
onStartChange = (value) => {
this.onChange('startValue', value);
}
onEndChange = (value) => {
this.onChange('endValue', value);
}
handleStartOpenChange = (open) => {
if (!open) {
this.setState({ endOpen: true });
}
}
handleEndOpenChange = (open) => {
this.setState({ endOpen: open });
}
/********开始、结束日期关联*********/
// 支付通道选择
handlePaySelectChange = (value) => {
this.props.handlePaySelectChange(value.join(','))
}
// 账户类型选择
handleTypeChange = (value) => {
this.props.handleTypeChange(value)
}
render() {
const { getFieldDecorator } = this.props.form;
const { tabInfos, isUpdate, SelectedPasswayIds, SelectedAcctype } = this.props;
const { endOpen } = this.state;
let SelectedPasswayIdsArray = SelectedPasswayIds ? SelectedPasswayIds.split(',') : []
let passway = this.props.passway.map(item => ({
key: item.id,
value: item.passwayName
}))
return (
<Form onSubmit={this.handleSubmit}>
<h3 className="modal-title">基本信息</h3>
<Row gutter={12}>
<Col span={12}>
<FormItem {...formItemLayout} label={`受理机构名称`}>
{getFieldDecorator(`orgname`, {
rules: [{ required: true, message: '请输入受理机构' }, {
pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{0,16}$/, message: '非法字符'
}],
initialValue: tabInfos.orgname
})(
<Input placeholder={`请输入受理机构`} maxLength="255" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`受理机构简称`}>
{getFieldDecorator(`orgstname`, {
initialValue: tabInfos.orgstname,
rules: [{ pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{0,16}$/, message: '非法字符' }]
})(
<Input placeholder={`受理机构简称`} maxLength="255" />
)}
</FormItem>
</Col>
</Row>
<Row gutter={12}>
<Col span={12}>
<FormItem {...formItemLayout} label={`支付通道`}>
{getFieldDecorator('passwayIds', {
initialValue: tabInfos.passwayIds ? tabInfos.passwayIds.split(',') : undefined
})(
<Select
allowClear
placeholder="请选择"
mode="multiple"
onChange={this.handlePaySelectChange}
getPopupContainer={() => document.querySelector('.vertical-center-modal')}
>
{this.props.passway.map(item => <Option key={item.id}>{item.passwayName}</Option>)}
</Select>
)}
</FormItem>
</Col>
</Row>
{ //微信支付
SelectedPasswayIdsArray.includes(WeiXinId)
? <Row>
<Col span={24}>
<h3 className="modal-title">微信支付</h3>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`FAPP_SECRET`}>
{getFieldDecorator(`appSecret`, {
initialValue: tabInfos.appSecret,
rules: [{
required: true, message: '请输入'
}]
})(
<Input placeholder={`请输入FAPP_SECRET`} />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`APPID`}>
{getFieldDecorator(`appid`, {
initialValue: tabInfos.appid,
rules: [{
required: true, message: '请输入'
}]
})(
<Input placeholder={`请输入应用ID`} />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`服务商商户号`}>
{getFieldDecorator(`facno`, {
initialValue: tabInfos.facno,
rules: [{
required: true, message: '请输入'
}]
})(
<Input placeholder={`请输入服务商商户号`} />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`KEY`}>
{getFieldDecorator(`key`, {
initialValue: tabInfos.key,
rules: [{
required: true, message: '请输入'
}]
})(
<Input placeholder={`请输入KEY`} />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`微信是否启用`}>
{getFieldDecorator(`effective`, {
initialValue: (tabInfos.effective !== undefined) ? String(tabInfos.effective) : '1'
})(
<Select>
<Option value="0">否</Option>
<Option value="1">是</Option>
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="微信证书">
{getFieldDecorator(`cert`)(
<UploadFile
keys={tabInfos.id}
url={tabInfos.certUrl} />
)}
</FormItem>
</Col>
</Row>
: null
}
{
// 支付宝支付
SelectedPasswayIdsArray.includes(ZhiFuBaoId)
? <Row>
<Col span={24}>
<h3 className="modal-title">支付宝支付</h3>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`应用ID`}>
{getFieldDecorator(`appidzfb`, {
initialValue: tabInfos.appidzfb,
rules: [{
required: true, message: '请输入'
}]
})(
<Input type="textarea" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`应用私钥`}>
{getFieldDecorator(`privateKey`, {
initialValue: tabInfos.privateKey,
rules: [{
required: true, message: '请输入'
}]
})(
<Input type="textarea" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`应用公钥`}>
{getFieldDecorator(`publicKey`, {
initialValue: tabInfos.publicKey,
rules: [{
required: true, message: '请输入'
}]
})(
<Input type="textarea" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`阿里公钥`}>
{getFieldDecorator(`alipayPublickey`, {
initialValue: tabInfos.alipayPublickey,
rules: [{
required: true, message: '请输入'
}]
})(
<Input type="textarea" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`支付宝是否启用`}>
{getFieldDecorator(`effectivez`, {
initialValue: (tabInfos.effectivez !== undefined) ? String(tabInfos.effectivez) : '1'
})(
<Select>
<Option value="0">否</Option>
<Option value="1">是</Option>
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="pId">
{getFieldDecorator(`pId`, {
initialValue: tabInfos.pId,
rules: [{
required: true, message: '请输入'
}]
})(
<Input />
)}
</FormItem>
</Col>
</Row>
: null
}
{isUpdate === true ? "" : (
<div>
<h3 className="modal-title">用户信息</h3>
<Row gutter={12}>
<Col span={12}>
<FormItem {...formItemLayout} label={`用户名`}>
{getFieldDecorator(`userName`, {
rules: [
{ required: true, message: '请输入用户名' },
{ pattern: /^[a-zA-Z0-9_-]{1,16}$/, message: '非法字符' },
],
validateFirst: true,
})(
<Input placeholder={`用户名`} autoComplete="off" maxLength="255" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`密码`}>
{getFieldDecorator(`passWord`, {
rules: [{ required: true, whitespace: true, message: '请输入密码' }]
})(
<Input placeholder={`密码`} type="passWord" autoComplete="new-password" maxLength="255" />
)}
</FormItem>
</Col>
</Row>
</div>
)}
<h3 className="modal-title">结算账户信息</h3>
<Row gutter={12}>
<Col span={12}>
<FormItem {...formItemLayout} label={`账户类型`}>
{getFieldDecorator(`acctype`, {
initialValue: (tabInfos.acctype !== undefined) ? String(tabInfos.acctype) : undefined
})(
<Select onChange={this.handleTypeChange}>
<Option value="0">机构</Option>
<Option value="1">个人</Option>
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`开户银行`}>
{getFieldDecorator(`deposite`, {
initialValue: tabInfos.deposite
})(
<Select placeholder="请选择"
showSearch
allowClear
>{this.getBank()}</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`银行卡号`} hasFeedback>
{getFieldDecorator(`bankno`, {
initialValue: tabInfos.bankno,
// rules: [{ pattern: /^([1-9]{1})(\d{14}|\d{18})$/, message: '请输入正确的银行卡号' }]
})(
<Input placeholder={`银行卡号`} />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`开户支行名称`}>
{getFieldDecorator(`branchNmae`, {
initialValue: tabInfos.branchNmae,
rules: [{ pattern: /[\u4e00-\u9fa5]/gm, message: '请输入正确名称' }]
})(
<Input placeholder={`开户支行名称`} maxLength="255" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`开户支行地区`}>
{getFieldDecorator(`branchRegion`, {
initialValue: tabInfos.branchRegion,
rules: [{ pattern: /[\u4e00-\u9fa5]/gm, message: '请输入正确名称' }]
})(
<Input placeholder={`开户支行地区`} maxLength="255" />
)}
</FormItem>
</Col>
{this.state.acctype === '0' ? (
<Col span={12}>
<FormItem {...formItemLayout} label={`企业名称`}>
{getFieldDecorator(`company`, {
initialValue: tabInfos.company
})(
<Input placeholder={`企业名称`} maxLength="255" />
)}
</FormItem>
</Col>)
: ''
}
</Row>
{SelectedAcctype === '1'
? <Row gutter={12}>
<Col span={24}>
<h3 className="modal-title">个人银行账户信息</h3>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`开户人`}>
{getFieldDecorator(`acctholder`, {
initialValue: tabInfos.acctholder,
rules: [{
pattern: /[\u4e00-\u9fa5]/gm, message: '非法字符'
}]
})(
<Input placeholder={`开户人`} maxLength="255" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`持卡人证件类型`}>
{getFieldDecorator(`identitp`, {
initialValue: tabInfos.identitp
})(
<Select placeholder={'==请选择=='}>
{this.getLicence()}
</Select>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`持卡人证件号码`}>
{getFieldDecorator(`identino`, {
initialValue: tabInfos.identino,
rules: [{ pattern: /^[0-9a-zA-Z]{0,30}$/, message: '请输入正确证件号码' }]
})(
<Input placeholder={`持卡人证件号码`} maxLength="30" />
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`持卡人手机号`}>
{getFieldDecorator(`holderphone`, {
initialValue: tabInfos.holderphone,
rules: [{ pattern: /^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$/, message: '请输入正确手机号码' }]
})(
<Input placeholder={`持卡人手机号`} maxLength="11" />
)}
</FormItem>
</Col>
<Col span={24}>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label={`持卡人地址`}>
{getFieldDecorator(`holderaddress`, {
initialValue: tabInfos.holderaddress
})(
<Input placeholder={`持卡人地址`} maxLength="255" />
)}
</FormItem>
</Col>
</Row>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`证件有效期起`}>
{getFieldDecorator(`idendtstart`, {
initialValue: tabInfos.idendtstart && moment(tabInfos.idendtstart),
})(
<DatePicker disabledDate={this.disabledStartDate}
placeholder="开始时间"
onChange={this.onStartChange}
onOpenChange={this.handleStartOpenChange}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`证件有效期止`}>
{getFieldDecorator(`idendtend`, {
initialValue: tabInfos.idendtend && moment(tabInfos.idendtend),
})(
<DatePicker disabledDate={this.disabledEndDate}
placeholder="结束时间"
onChange={this.onEndChange}
open={endOpen}
onOpenChange={this.handleEndOpenChange}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`身份证正面照片`}>
{getFieldDecorator(`front`)(
<UploadImg
keys={tabInfos.id}
url={tabInfos.frontUrl}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label={`身份证反面照片`}>
{getFieldDecorator(`back`)(
<UploadImg
keys={tabInfos.id}
url={tabInfos.backUrl}
/>
)}
</FormItem>
</Col>
</Row>
: null
}
</Form>
)
}
}
SloveModal = Form.create()(SloveModal);
export default SloveModal
|
function shrinkBalls(balls){
for(let i=0; i<balls.length; i++){
let ball = balls[i];
if(Math.random() >=0.5)
ball.shrink();
}//end i-for
}//end shrinkBalls
function accelerateBalls(balls){
for(let i=0; i<balls.length; i++){
let ball = balls[i];
if(ball.dx < 1)
ball.dx += 3;
if(ball.dy < 1)
ball.dy += 3;
const dxGain = getRandomFloat(0, 0.99) * ball.dx;
const dyGain = getRandomFloat(0, 0.99) * ball.dy;
ball.accelerate( dxGain, dyGain );
}//end i-for
}//end accelerateBalls
function decelerateBalls(balls){
for(let i=0; i<balls.length; i++){
let ball = balls[i];
const dxLoss = getRandomFloat(0, 0.99) * ball.dx;
const dyLoss = getRandomFloat(0, 0.99) * ball.dy;
ball.decelerate( dxLoss, dyLoss );
}//end i-for
}//end decelerateBalls
class Ball{
'use strict';
constructor(properties){
this.type = 'ball';
this.ballID = properties.ballID;
this.color = properties.color;
this.xCord = properties.xCord;
this.yCord = properties.yCord;
this.radius = properties.radius;
this.dx = properties.dx;
this.dy = properties.dy;
this.gravity = 0.45;
this.friction = 0.05;
this.kineticLoss = 1/3;
this.kineticGain = 2/3;
//Direction variables;
this.isGoingRight = true; //Ball starts going to the right;
this.isGoingDown = true; //Ball starts going down;
this.isGoingLeft = false;
this.isGoingUp = false;
this.nextX = this.xCord + this.dx;
this.nextY = this.yCord + this.dy;
//Boundary variables;
this.canGoLeft = false;
this.canGoRight = false;
this.canGoDown = false;
this.canGoUp = false;
}
accelerate(dxBoost, dyBoost){
this.dx += dxBoost;
this.dy += dyBoost;
//Apply buffer to stay in speed of light realm;
if(this.dx > this.radius*2 - 0.01)
this.dx = this.radius*2 - 0.01;
if(this.dy > this.radius*2 - 0.01)
this.dy = this.radius*2 - 0.01;
if(this.dx > this.maxSpeed)
this.dx = this.maxSpeed;
if(this.dy > this.maxSpeed)
this.dy = this.maxSpeed;
this.decelerate(0,0); //Hack to check if zero;
//Should we be updating the next coords here?
//this.setNextCoordinates();
}
accelerateBySize(dx=true, dy=true, ratio=50){
const rate = this.radius/ratio;
if(dx && dy)
this.accelerate(rate, rate);
else if(dx)
this.accelerate(rate, 0);
else if(dy)
this.accelerate(0, rate);
//Should we be updating the next coords here?
//this.setNextCoordinates();
}
applyGravity(){
if(this.isGoingDown)
this.accelerate(0, this.gravity);
else if(this.isGoingUp)
this.decelerate(0, this.gravity);
else if (this.canGoDown)
this.accelerate(0, this.gravity);
}
decelerate(dxLoss, dyLoss){
this.dx -= dxLoss;
this.dy -= dyLoss;
if(this.dx <=0)
this.dx = 0;
if(this.dy <=0)
this.dy = 0;
//Should we be updating the next coords here?
//this.setNextCoordinates();
}//end decelerate()
destruct(){
//Destroy Ball
this.radius = 0;
}
distanceTo(x, y){
const xDiff = this.nextX - x;
const yDiff = this.nextY - y;
const distance = Math.sqrt(xDiff**2 + yDiff**2);
return distance;
}
draw(ctx){
ctx.beginPath();
ctx.arc(
this.xCord,
this.yCord,
this.radius,
2*Math.PI, //Start angle in radians
0 //End angle in radians
);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}//end draw()
handleBallCollisions(allBalls){
//Find out if NEXT coordinates overlap anything;
for(let i=0; i<allBalls.length; i++){
if(this.ballID === allBalls[i].ballID)
continue;
let otherBall = allBalls[i];
const minDistance = otherBall.radius + this.radius;
let nextDistance = this.distanceTo(otherBall.nextX, otherBall.nextY);
let willOverlap = nextDistance <= minDistance;
if( !willOverlap ){
continue;
}
//Set the directions that this ball cannot go;
if(this.nextX > otherBall.nextX){
//Current ball is right of otherball
this.canGoLeft = false;
}
else
this.canGoRight = false;
if(this.nextY > otherBall.yCord){
//Current ball is below of otherball
this.canGoUp = false;
}
else
this.canGoDown = false;
//Adjust the next coordinates so that they do not overlap otherBall;
//We can do this by taking the ratio of dx and dy changes and "step back"
// through time until we find a place the balls no longer overlap;
let timeRatio = 50;
let dyRatio = this.dy / timeRatio;
let dxRatio = this.dx / timeRatio;
let cnt = 0;
while(willOverlap){
if(this.isGoingRight)
this.nextX -= dxRatio; //Step back left
else if(this.isGoingLeft)
this.nextX += dxRatio; //Step back right
if(this.isGoingDown)
this.nextY -= dyRatio; //Step back up
else if(this.isGoingUp)
this.nextY += dyRatio; //Step back down
nextDistance = this.distanceTo(otherBall.nextX, otherBall.nextY);
willOverlap = nextDistance < minDistance;
cnt += 1;
if(cnt === timeRatio){
//Problem not solved;
//We need to adjust the ball instead;
this.nextY = this.yCord;
this.nextX = this.xCord;
break;
}
}//end while
if(cnt === timeRatio){
//Overlap problem not solved;
if(this.canGoDown === false){
if(this.canGoRight && this.canGoLeft)
console.log('weird');
if(this.canGoRight && this.dx === 0){
this.accelerateBySize(true, false);
}
else if(this.canGoLeft && this.dx === 0){
this.accelerateBySize(true, false);
}
//else, stuck
return false;
}
}
//Apply Kinetic Transfers & Friction
otherBall.decelerate(this.friction, this.friction);
this.decelerate(otherBall.friction, otherBall.friction);
if(this.kineticLoss > 0 && this.kineticGain > 0){
otherBall.accelerate(this.dx * this.kineticLoss, 0)
otherBall.accelerate(0, this.dy * this.kineticLoss)
this.dy *= this.kineticGain;
this.dx *= this.kineticGain;
}
}//end i-for
return true;
}//End handleBallCollision()
handleClick(){
console.log('accelerating ball' + this.ballID);
this.accelerate(5, 20);
return true;
}
handleMovement(friction){
//Set directions for next movement based off of current collisions;
if(this.dy === 0){
//Ball has no more momentum;
if(this.isGoingUp){
//Ball lost momentum, but is in the air; Ball comes back down;
this.isGoingUp = false;
if(this.canGoDown){
//We have a small bug here where momentum is still happening;
this.isGoingDown = true;
}
else{
this.isGoingDown = false;
}
}
else if(this.isGoingDown){
//Ball has no more momentum to go back up;
this.isGoingUp = false;
this.isGoingDown = false;
}
else{
//Ball is just rolling and losing dx momentum;
this.isGoingUp = false;
this.isGoingDown = false;
this.decelerate(friction, 0);
}
}
else{
//Ball Has Momenutm;
if(this.canGoDown && this.canGoUp){
//Ball can go anywhere and should follow its natural path;
if(this.isGoingDown){
this.isGoingUp = false;
this.isGoingDown = true;
}
else if(this.isGoingUp){
this.isGoingUp = true;
this.isGoingDown = false;
}
else{
this.isGoingUp = false;
this.isGoingDown = true;
}
}
else if(this.canGoUp){
//Ball has momentum and can go up;
//Ball cannot go down;
this.isGoingUp = true;
this.isGoingDown = false;
}
else if(this.canGoDown){
this.isGoingDown = true;
this.isGoingUp = false
}
else{
this.isGoingDown = false;
this.isGoingUp = false;
this.decelerate(friction, 0);
}
}
//END up/down movements;
if(this.dx <=0){
//If Ball has no momentum, it can go in neither direction;
//But if ball is "stuck", we need to give it a boost;
if(this.canGoDown && this.gravity > 0){
if(this.dx === 0){
//this.accelerate(this.gravity*4, 0);
}
if(this.canGoRight){
this.isGoingRight = true;
this.isGoingLeft = false;
}
else if(this.canGoLeft){
this.isGoingRight = false;
this.isGoingLeft = true;
}
}
else{
this.isGoingRight = false;
this.isGoingLeft = false;
}
}
else if(!this.isGoingRight && !this.isGoingLeft){
//Ball had no momentum but just received momentum;
if(this.canGoRight){
this.isGoingRight = true;
this.isGoingLeft = false;
}
else if(this.canGoLeft){
this.isGoingLeft = true;
this.isGoingRight = false;
}
}
else if(this.canGoRight && this.canGoLeft){
//Ball has momentum and can go its natural path;
if(this.isGoingRight){
this.isGoingRight = true;
this.isGoingLeft = false;
}
else{
this.isGoingLeft = true;
this.isGoingRight = false;
}
}
else if(this.canGoRight){
//Ball has momentum but cannot go left;
this.isGoingRight = true;
this.isGoingLeft = false;
}
else if(this.canGoLeft){
//Ball has momentum but cannot go right;
this.isGoingLeft = true;
this.isGoingRight = false;
}
else{
this.isGoingRight = false;
this.isGoingLeft = false;
}
if(this.isGoingUp && this.isGoingDown)
console.log('ERROR: BALL CANNOT GO UP AND DOWN');
if(this.isGoingLeft && this.isGoingRight){
console.log('ERROR: BALL CANNOT GO LEFT AND RIGHT');
}
}//End handleMovement()
handleRectangleInteractions(rectangle, screenWidth, screenHeight){
//Handle rectangle objects
let isOverlapping = rectangle.isOverLappingBall(this);
if( isOverlapping === false)
return;
this.decelerate(rectangle.friction, rectangle.friction);
//There is a collision;
//Set the directions that this ball cannot go;
if(this.nextX > rectangle.xCenter){
//Current ball is right of rectangle
this.canGoLeft = false;
}
else
this.canGoRight = false;
if(this.nextY > rectangle.yCenter){
//Current ball is below of rectangle;
this.canGoUp = false;
}
else{
this.canGoDown = false;
if(this.dy === 0){
//BUG: this never seems to happen
//console.log('cant go back up');
this.canGoUp = false;
}
this.nextY = rectangle.yTop + this.radius;
}
//Set canGo* flags, rewind time on next* coords;
let timeRatio = 50;
let dyRatio = this.dy / timeRatio;
let dxRatio = this.dx / timeRatio;
let cnt = 0;
let isResolved = true;
while(isOverlapping){
if(this.isGoingRight)
this.nextX -= dxRatio; //Step back left
else if(this.isGoingLeft)
this.nextX += dxRatio; //Step back right
if(this.isGoingDown)
this.nextY -= dyRatio; //Step back up
else if(this.isGoingUp)
this.nextY += dyRatio; //Step back down
isOverlapping = rectangle.isOverLappingBall(this);
cnt += 1;
if(cnt === timeRatio){
//Problem not solved;
//We need to adjust the ball instead;
isResolved = false;
break;
}
}//end while
if(isResolved === false){
this.nextY = this.yCord;
this.nextX = this.xCord;
}
}//end handleRectangleInteractions()
handleWallCollisions(maxWidth, maxHeight, friction){
const willOverlapBottom = this.hitBottom(maxHeight);
const willOverlapTop = this.hitTop(0);
const willOverlapRight = this.hitRight(maxWidth);
const willOverlapLeft = this.hitLeft(0);
if(willOverlapTop && willOverlapBottom){
//The screen is now to small for our ball;
//This is now handles with window resize;
}
else if(willOverlapBottom){
this.decelerate(0, friction);
if(this.dy === 0){
this.canGoUp = false;
}
this.canGoDown = false;
this.nextY = maxHeight - this.radius;
}
else if(willOverlapTop){
this.decelerate(0, friction);
this.canGoUp = false;
this.nextY = 0 + this.radius;
}
else{
//No collision
}
if(willOverlapRight && willOverlapLeft){
//The screen is now to small for our ball;
//We will just keep the ball at it's current place and stop all movemnt;
//TODO: Handle this with window resize;
this.nextX = this.xCord;
this.nextY = this.yCord;
this.dy = 0;
this.dx = 0;
console.log('WARNING: SCREEN NOT FITTED;');
}
else if(willOverlapRight){
this.canGoRight = false;
this.nextX = maxWidth - this.radius;
}
else if(willOverlapLeft){
this.canGoLeft = false;
this.nextX = 0 + this.radius;
}
else{
//No collision
}
}//End handleWallCollision
handleWindowResize(maxWidth, maxHeight, otherBalls, rectangles){
if(this.yCord + this.radius > maxHeight){
this.yCord = maxHeight - this.radius;
this.accelerate(4, 10);
this.shrink();
}
if(this.yCord - this.radius <= 0){
this.shrink();
}
if(this.xCord + this.radius > maxWidth || this.xCord - this.radius < 0){
if(this.xCord + this.radius > maxWidth)
this.xCord = maxWidth - this.radius;
else
this.xCord = 0 + this.radius;
this.accelerate(10, 4);
this.shrink();
}
for(let i=0; i<otherBalls.length; i++){
let otherBall = otherBalls[i];
if(otherBall.ballID === this.ballID)
continue;
const isOverLapping = this.isOverLappingBall(otherBall);
if(isOverLapping)
this.shrink();
}//end i-for
for(let i=0; i<rectangles.length; i++){
const rectangle = rectangles[i];
if(rectangle.isOverLappingBall(this)){
//Need to find balls position relative to rectangle;
//nearestX and nearestY are places on our rectangle;
const nearestX = Math.max(
rectangle.xLeft,
Math.min(this.xCord, rectangle.xLeft+rectangle.width),
);
const nearestY = Math.max(
rectangle.yTop,
Math.min(this.xCord, rectangle.yTop+rectangle.height),
);
if(this.yCord + this.radius < nearestY){
//Ball is above rectangle;
//We need to adjust ball up;
this.yCord = nearestY + this.radius;
}
else if(this.yCord - this.radius < nearestY){
//Ball is below rectangle;
//We need to adjust ball down;
this.yCord = nearestY - this.radius;
}
if(this.xCord - this.radius > nearestX){
//Ball is right of rectangle and needs to be adjusted right;
this.xCord = nearestX + this.radius;
}
else if(this.xCord + this.radius < nearestX){
//Ball is left of rectangle and needs to be adjusted left;
this.xCord = nearestX - this.radius;
}
this.accelerate(6,6);
this.shrink();
}
}//end i-for
}//end handleWindowResize()
hitBottom(maxHeight){
const ballMaxBottom = this.nextY + this.radius;
if(ballMaxBottom >= maxHeight)
return true;
return false;
}
hitLeft(minWidth){
const ballMaxLeft = this.nextX - this.radius;
if(ballMaxLeft <= minWidth)
return true;
return false;
}
hitTop(minHeight){
const ballMaxTop = this.nextY - this.radius;
if(ballMaxTop <= minHeight)
return true;
return false;
}
hitRight(maxWidth){
const ballMaxRight = this.nextX + this.radius;
if(ballMaxRight >= maxWidth)
return true;
return false;
}
isOverLappingBall(otherBall){
const doesOverLap = isOverLapping(
this.xCord,
this.yCord,
otherBall.nextX,
otherBall.nextY,
this.radius + otherBall.radius
);
if(doesOverLap === false)
return false;
return true;
}//end isOverLappingBall
label(ctx){
if(this.radius < 30)
return;
ctx.beginPath();
if(!this.isGoingDown && !this.isGoingUp){
if(!this.isGoingRight && !this.isGoingLeft){
ctx.font = "12px Arial";
ctx.fillStyle = "white";
ctx.fillText("Static"+this.ballID, this.xCord - this.radius+1, this.yCord+1);
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText("dx:" + this.dx.toFixed(2), this.xCord - this.radius+10, this.yCord+10);
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText("dy:" + this.dy.toFixed(2), this.xCord - this.radius+10, this.yCord+20);
}
else{
ctx.font = "12px Arial";
ctx.fillStyle = "white";
ctx.fillText("Rolling"+this.ballID, this.xCord - this.radius+1, this.yCord+1);
if(this.isGoingRight){
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText("Right", this.xCord - this.radius+10, this.yCord+10);
}
if(this.isGoingLeft){
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText("Left", this.xCord - this.radius+10, this.yCord+10);
}
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText(this.dx.toFixed(2), this.xCord - this.radius+10, this.yCord+20);
}
}
else{
ctx.font = "10px Arial";
ctx.fillStyle = "white";
ctx.fillText("Bouncing" + this.ballID, this.xCord - this.radius+1, this.yCord+1);
if(this.isGoingDown){
ctx.font = "8px Arial";
ctx.fillStyle = "white";
ctx.fillText("Down: " + this.dy.toFixed(1), this.xCord - this.radius+13, this.yCord+10);
}
else{
ctx.font = "8px Arial";
ctx.fillStyle = "white";
ctx.fillText("Up: " + this.dy.toFixed(1), this.xCord - this.radius+13, this.yCord+10);
}
if(this.isGoingLeft){
ctx.font = "8px Arial";
ctx.fillStyle = "white";
ctx.fillText("Left: " + this.dx.toFixed(1), this.xCord - this.radius+13, this.yCord+22);
}
if(this.isGoingRight){
ctx.font = "8px Arial";
ctx.fillStyle = "white";
ctx.fillText("Right: " + this.dx.toFixed(1), this.xCord - this.radius+13, this.yCord+22);
}
}
ctx.closePath();
}//end label()
move(sWidth, sHeight, wallFriction, rectangles, balls){
//Assume we can go any direction first; Change values on `handle`*;
//Reset canGo* properties for this iteration;
this.resetSurroundings();
//Set coordinates for next movment;
this.setNextCoordinates();
//See if next coordinates create any conflicts and if expected coordinates
// will prevent us from going certain directions;
for(let i=0; i<rectangles.length; i++){
this.handleRectangleInteractions(
rectangles[i],
sWidth,
sHeight
);
}
this.handleWallCollisions(sWidth, sHeight, wallFriction);
this.handleBallCollisions(balls);
//Process final available movements; Update coords appropriately; Apply Gravity;
this.handleMovement(wallFriction);
this.updateCoordinates();
this.applyGravity();
}//end move()
resetSurroundings(){
this.canGoUp = true;
this.canGoDown = true;
this.canGoLeft = true;
this.canGoRight = true;
}
setNextCoordinates(){
//Update balls nextX and nextY according to previous movement;
if(this.isGoingUp)
this.nextY = this.yCord - this.dy;
else if(this.isGoingDown)
this.nextY = this.yCord + this.dy;
if(this.isGoingLeft)
this.nextX = this.xCord - this.dx;
else if(this.isGoingRight)
this.nextX = this.xCord + this.dx;
}//end setNextCoordinates
shrink(){
//Destroy Ball
this.radius *= 0.9;
this.setNextCoordinates();
}
updateCoordinates(){
this.xCord = this.nextX;
this.yCord = this.nextY;
}
}//End Ball Class
|
import tw from 'tailwind-styled-components'
export const StyledAdvancedNavigationItem = tw.li`
block
text-gray-500
text-xs
hover:underline
pr-4
my-0.5
` |
import Box from '@/components/Collocation/Report/box';
import Button from '@/components/Button';
import ArrowDropDownIcon from '@/icons/arrow_drop_down';
import PollutantDropdown from '@/components/Collocation/Report/PollutantDropdown';
import CorrelationChart from '@/components/Collocation/Report/Charts/CorrelationLineChart';
import Spinner from '@/components/Spinner';
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
addActiveSelectedDeviceCollocationReportData,
addActiveSelectedDeviceReport,
} from '@/lib/store/services/collocation/collocationDataSlice';
import { useRouter } from 'next/router';
import CustomLegend from './custom_legend';
import { useGetCollocationResultsQuery } from '@/lib/store/services/collocation';
import { isEmpty } from 'underscore';
const IntraCorrelationChart = ({
intraCorrelationConcentration,
toggleIntraCorrelationConcentrationChange,
collocationResults,
isLoading,
deviceList,
graphColors,
}) => {
const router = useRouter();
const { device, batchId } = router.query;
const dispatch = useDispatch();
const [isOpen, setIsOpen] = useState(false);
const [input, setInput] = useState(null);
const [skipCollocationResults, setSkipCollocationResults] = useState(true);
const activeSelectedDeviceCollocationReportData = useSelector(
(state) => state.collocationData.activeSelectedDeviceCollocationReportData,
);
const activeSelectedDeviceReport = useSelector(
(state) => state.collocationData.activeSelectedDeviceReport,
);
const {
data: collocationResultsData,
isError: isFetchCollocationResultsError,
isSuccess: isFetchCollocationResultsSuccess,
isLoading: isFetchCollocationResultsLoading,
} = useGetCollocationResultsQuery(input, { skip: skipCollocationResults });
const newCollocationResults = collocationResultsData ? collocationResultsData.data : null;
useEffect(() => {
dispatch(addActiveSelectedDeviceCollocationReportData(collocationResults));
}, [activeSelectedDeviceCollocationReportData, collocationResults]);
useEffect(() => {
const getActiveSelectedDeviceReport = () => {
if (!device || !batchId) return;
dispatch(addActiveSelectedDeviceReport({ device, batchId }));
};
getActiveSelectedDeviceReport();
}, [device, batchId]);
const handleSelect = async (newDevice, batchId) => {
dispatch(addActiveSelectedDeviceReport({ device: newDevice, batchId }));
setInput({ device: newDevice, batchId });
setSkipCollocationResults(false);
setIsOpen(false);
};
useEffect(() => {
if (isFetchCollocationResultsSuccess) {
const updatedQuery = {
...input,
};
router.replace({
pathname: `/analytics/collocation/reports/monitor_report/${updatedQuery.device}`,
query: updatedQuery,
});
dispatch(addActiveSelectedDeviceCollocationReportData(newCollocationResults));
}
}, [input, isFetchCollocationResultsSuccess, newCollocationResults]);
return (
<Box
isBigTitle
title='Intra Sensor Correlation'
subtitle='Detailed comparison of data between two sensors that are located within the same device. By comparing data from sensors to create a more accurate and reliable reading.'
>
{isLoading || isFetchCollocationResultsLoading ? (
<div className='h-20' data-testid='correlation-data-loader'>
<Spinner />
</div>
) : (
<div className='flex flex-col justify-start w-full'>
<div className='relative'>
<Button
className='relative w-auto h-10 bg-purple-600 rounded-lg text-base font-semibold text-purple-700 ml-6'
onClick={() => setIsOpen(!isOpen)}
>
<span className='uppercase'>
{activeSelectedDeviceReport && activeSelectedDeviceReport.device}
</span>
<span className='ml-2 text-purple-700'>
<ArrowDropDownIcon fillColor='#584CAB' />
</span>
</Button>
{isOpen && deviceList.length > 1 && (
<ul className='absolute z-30 bg-white mt-1 ml-6 py-1 w-36 rounded border border-gray-200 max-h-60 overflow-y-auto text-sm'>
{deviceList.map((device, index) => (
<>
{activeSelectedDeviceReport.device !== device.device_name && (
<li
key={index}
className='px-4 py-2 hover:bg-gray-200 cursor-pointer text-xs uppercase'
onClick={() => handleSelect(device.device_name, device.batch_id)}
>
{device.device_name}
</li>
)}
</>
))}
</ul>
)}
</div>
<PollutantDropdown
pollutantValue={intraCorrelationConcentration}
handlePollutantChange={toggleIntraCorrelationConcentrationChange}
options={[
{ value: '2.5', label: 'pm2_5' },
{ value: '10', label: 'pm10' },
]}
/>
{!isEmpty(activeSelectedDeviceCollocationReportData) ? (
<CorrelationChart
data={activeSelectedDeviceCollocationReportData}
pmConcentration={intraCorrelationConcentration}
isInterSensorCorrelation
graphColors={graphColors}
/>
) : (
<div className='text-center text-grey-300 text-sm'>No data found</div>
)}
{graphColors && activeSelectedDeviceReport && (
<CustomLegend
devices={[
{
device_name: activeSelectedDeviceReport.device,
},
]}
graphColors={graphColors}
isSingleDevice
/>
)}
</div>
)}
</Box>
);
};
export default IntraCorrelationChart;
|
Bmob.initialize("46f2060ea2c4c94ee2b13a2406259153", "e44bf4e2278676417180492571813b4e");
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function login() {
var userName = $('#account').val();
var password = $('#password').val();
Bmob.User.logIn(userName, password, {
success: function(user) {
window.location.href = './bannar.html'
setCookie('islogin',1,1);
},
error: function(user, error) {
alert('账号或密码错误');
}
});
} |
var path = require('path');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
content: String,
//author: String,
author_id: { type: Schema.Types.ObjectId },
keywords: {type: [String]},
total_view: {type: Number, default: 0},
create_at: {type: Date, default: Date.now},
update_at: {type: Date, default: Date.now}
});
blogSchema.index({author_id: 1, creat_at: -1});
var Blog = mongoose.model('Blog', blogSchema);
|
window.addEventListener('load', function () {
var nme = 0;
var nmi = 0;
AjaxMail.numeroMensajesRecibidosTiempo(10000, function (respuesta) {
if (nme < respuesta.cantidad) {
AjaxMail.recibirMensajesRecibidos(function (respuesta) {
var listaMensajes = respuesta.mensajes;
for (; nme < listaMensajes.length; nme++) {
nuevoMensaje(listaMensajes[nme].sender, listaMensajes[nme].mensaje, "mensajes_mensajesRecibidos");
}
});
document.getElementById("mensajes_numMensajesEntrada").innerHTML = " (" + respuesta.cantidad + ")";
}
});
AjaxMail.recibirMensajesEnviados(function (respuesta) {
var listaMensajes = respuesta.mensajes;
for (var i = 0; i < listaMensajes.length; i++) {
nuevoMensaje(listaMensajes[i].receiver, listaMensajes[i].mensaje, "mensajes_mensajesEnviados");
}
nmi = listaMensajes.length;
document.getElementById("mensajes_numMensajesSalida").innerHTML = " (" + nmi + ")";
});
var form = document.getElementById("mensajes_form");
form.addEventListener("submit", function (ev) {
ev.preventDefault();
var usuario=document.getElementById("mensajes_usuario").value;
var text=document.getElementById("mensajes_text").value;
document.getElementById("mensajes_text").value="";
AjaxMail.enviarMensaje(usuario, text, function (respuesta) {});
nuevoMensaje(usuario, text, "mensajes_mensajesEnviados");
nmi++;
document.getElementById("mensajes_numMensajesSalida").innerHTML = " (" + nmi + ")";
});
});
function nuevoMensaje(usuario, text, articuloId) {
var vis = document.getElementById(articuloId);
var b = document.createElement("b");
b.appendChild(document.createTextNode(usuario));
var p = document.createElement("p");
p.appendChild(document.createTextNode(text));
var hr = document.createElement("hr");
var div = document.createElement("div");
div.className = "mensajes_mensaje";
div.appendChild(hr);
div.appendChild(b);
div.appendChild(p);
vis.insertBefore(div, vis.getElementsByTagName("div")[0]);
} |
import React, {useState, useEffect, useRef} from 'react';
import { useDispatch } from 'react-redux'
import { GetData } from './redux/WeatherActions'
import './App.css'
import Content from './components/Content';
import FavoritePlaces from './components/FavoritePlaces'
function App() {
const [zipCode, setZipCode] = useState('02111');
const dispatch = useDispatch();
const inputEl = useRef(null);
const onSubmit = (event) => {
event.preventDefault();
setZipCode(inputEl.current.value);
//dispatch(GetData(zipCode));
}
useEffect(() => {
dispatch(GetData(zipCode));
}, [zipCode])
return (
<div className="App">
<div className="weather">
<div className="weather__search">
<form onSubmit={onSubmit}>
<input type="text" id="country_code" name="country_code"
className="weather__input" maxLength={5} ref={inputEl}
pattern="[0-9]{5}" title="5 digit zip code" placeholder="02111" />
<button type="submit" className="weather__button" >Show Me The Future</button>
</form>
</div>
{/** Favorite City banner*/}
<FavoritePlaces />
<div className="weather__result">
<Content />
</div>
</div>
</div>
);
}
export default App;
|
import React, { Component } from "react";
import "../Home.css";
class Welcomerecruiter extends Component {
constructor(props) {
super(props);
};
render() {
let username = localStorage.getItem("username");
return (
<div class="flex-container">
<div class="container">
<div class="col-sm-12">
<h4>Welcome, {username}</h4>
<ul>Want to create a new teacher opening?</ul>
<ul>Just fill in the details to make it available.</ul>
<a href="/createjob">click here</a>
</div>
</div>
<div class="container">
<div class="col-xs-15">
<h3>Refer Now</h3>
<ul>Refer the site to peer or a friend</ul>
<ul>Increase the chances of closing the appplication you posted</ul>
<a href="/refernow">Refer Now</a>
</div>
</div>
</div>
);
}
}
export default Welcomerecruiter; |
import React, { useContext } from 'react';
import { ItemContext } from '../contexts/ItemContext';
import useForm from 'react-hook-form';
import styled from 'styled-components';
import { withRouter } from 'react-router-dom';
const Form = styled.form``;
const FormInput = styled.input`
display: inline-block;
padding: 10px ;
box-sizing: border-box;
margin: 5px;
border-right: solid black 1px;
width: 30%;
background: #eee;
color: #333;
&:focus{
outline: none;
border-bottom: 1px solid black;
}
`;
const ConfirmButton = styled.input`
display: inline-block;
border: 0;
background: #eee;
margin: 10px;
padding: 10px 20px;
cursor: pointer;
box-sizing: border-box;
&:focus{
outline: none;
border-bottom: 1px solid black;
}
`;
const CancelButton = styled.button`
display: inline-block;
border: 0;
background: #eee;
margin: 10px;
padding: 10px 20px;
cursor: pointer;
box-sizing: border-box;
&:focus{
outline: none;
border-bottom: 1px solid black;
}
`;
const EditedItem = ({ history }) => {
const { register, handleSubmit, errors } = useForm();
const { setEditMode, saveEditedItem, editedItem } = useContext(ItemContext);
const changeEditMode = () => {
setEditMode(false);
history.push('/');
}
const handleSaveEditedItem = (data) => {
let newItem = {
name: data.itemName,
entity: data.itemEntity,
id: editedItem.id
}
saveEditedItem(newItem);
setEditMode(false);
history.push('/')
}
return (
<Form onSubmit={handleSubmit(handleSaveEditedItem)}>
<FormInput
type="text"
defaultValue={editedItem.name}
ref={register({ required: true, minLength: 2, maxLength: 20 })}
name="itemName"
/>
<FormInput
type="number"
defaultValue={editedItem.entity}
ref={register({ required: true, min: 1, max: 50 })}
name="itemEntity"
/>
<CancelButton type="button" onClick={changeEditMode}>X</CancelButton>
<ConfirmButton type="submit" value="OK" />
{errors.itemName && errors.itemName.type === 'required' && <p>Item's name is required</p>}
{errors.itemName && errors.itemName.type === 'minLength' && <p>Item's name has minimum length of 2</p>}
{errors.itemName && errors.itemName.type === 'maxLength' && <p>Item's name has maximum length of 20</p>}
{errors.itemEntity && errors.itemEntity.type === 'required' && <p>Item's entity is required</p>}
{errors.itemEntity && errors.itemEntity.type === 'min' && <p>Item's entity has minimum value of 1</p>}
{errors.itemEntity && errors.itemEntity.type === 'max' && <p>Item's entity has minimum value of 50</p>}
</Form>
);
};
export default withRouter(EditedItem); |
var assert = require('assert');
var Dinosaur = require('../dinosaur.js');
describe('Dinosaur', function() {
var dino1;
beforeEach('before each', function() {
dino1 = new Dinosaur('Tyrannosaurus',1);
})
it('should have a type', function(){
assert.strictEqual('Tyrannosaurus', dino1.type);
})
it('Should define number of offspring per year', function() {
assert.strictEqual(1, dino1.offspringPerYear);
})
}) |
const mongoose = require('mongoose')
const { Schema } = mongoose
const stateSchema = new Schema({
name: {
type: String,
trim: true,
required: 'El campo `nombre` es requerido',
},
}, {
timestamps: true,
})
module.exports = mongoose.model('State', stateSchema)
|
// import rAF from one place so that the bundle size is a bit smaller
const rAF = requestAnimationFrame
export { rAF as requestAnimationFrame }
|
import React from 'react'
import { View, Text,TouchableOpacity } from 'react-native'
const Button = (props) => {
return (
<TouchableOpacity style={props.style} >
<Text></Text>
</TouchableOpacity>
)
}
export default Button
|
import React, { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown, faChevronUp } from '@fortawesome/free-solid-svg-icons';
/**
* Composant Collapsable :
* Permet d'afficher ou non du contenu en cliquant sur son titre
*
* props :
* - title: Titre
* - defaultOpen (optionnel) : Si le contenu doit être affiché ou non par défaut
* - children : Contenu
*/
function Collapsable({ title, defaultOpen = false, children }) {
const [isOpen, setIsOpen] = useState(defaultOpen);
return (
<>
<div
className="mt-2 collapsable"
onClick={() => setIsOpen(!isOpen)}
>
<h4>{title}</h4>
<FontAwesomeIcon icon={isOpen ? faChevronUp : faChevronDown} />
</div>
{isOpen && children}
</>
);
}
export default Collapsable;
|
const { JSDOM } = require('jsdom');
const formatXml = require('xml-formatter');
const DOCTYPE = '<!DOCTYPE html>'; // TODO want to figure out if this can be incorporated
const BASE_HTML = '<html><head></head><body></body></html>';
const removeElements = (elements) =>
[...new Array(elements.length).keys()]
.map((index) => elements.item(index))
.forEach((element) => element.parentElement.removeChild(element));
class HtmlBuilder {
constructor() {
this.dom = new JSDOM(BASE_HTML);
this.document = this.dom.window.document;
}
setCss(css) {
const styles = this.document.getElementsByTagName('style');
removeElements(styles);
const style = this.createElement({
tagName: 'style',
textContent: css
});
this.document.head.appendChild(style);
}
setTitle(title) {
const titles = this.document.getElementsByTagName('title');
removeElements(titles);
const titleElem = this.createElement({
tagName: 'title',
textContent: title
});
this.document.head.appendChild(titleElem);
}
createElement({ tagName, textContent, className }) {
const elem = this.document.createElement(tagName);
if (textContent) {
elem.textContent = textContent;
}
if (className) {
elem.className = className;
}
return elem;
}
createTextNode(text) {
return this.document.createTextNode(text);
}
appendElement(parentSelector, element) {
this.document.querySelector(parentSelector).appendChild(element);
}
serialize() {
return formatXml(this.dom.serialize()); // TODO drop the formatXml eventually... maybe...
}
}
module.exports = {
HtmlBuilder
}; |
class PointCapOptionSet extends MultipleChoiceOptionSet{
constructor(options, itemListName, keyVerb, isMandatory, pointCap) {
super();
this.pointCap = pointCap;
}
}
export default PointCapOptionSet; |
'use strict';
const chai = require('chai');
const should = chai.should(); // eslint-disable-line
const expect = chai.expect; // eslint-disable-line
const SlackWebhook = require('../../../src/slack/SlackWebhook');
const TEST_NAME = 'Test Slack Webhooks';
if(!process.env.SLACK_INCOMING_WEB_HOOK){
throw new Error('You MUST supply SLACK_INCOMING_WEB_HOOK environment variable to run this integration test.');
}
let slackWebhookClient = new SlackWebhook(process.env.SLACK_INCOMING_WEB_HOOK);
describe(TEST_NAME, () => {
before(() => {
// console.log('-------------------------------------------------------');
// console.log('TESTS RUNNING USING:');
// console.log('-------------------------------------------------------');
});
it('should send basic message',()=>{
return slackWebhookClient.sendMessage('Hey there from integration land!')
.then((result)=>{
expect(result).to.exist;
result.text.should.eql('ok');
});
});
it('should send an attachment message',()=>{
return slackWebhookClient.sendAttachmentMessage(
'@monstermakes/example-web',
'',
{
Version: '3.4.5-fake-release'
},
{
pretext: 'New Terminal Project Released!'
}
)
.then((result)=>{
expect(result).to.exist;
result.text.should.eql('ok');
});
});
}); |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Change zoom factor of the camera.
* Note: only attach to <a-camera> entity.
*/
AFRAME.registerComponent('zoom-utility', {
schema: {
delta: {type: 'float', default: 0.25}, // increasing/decreasing factor
// for each zoom in/out action
min: {type: 'float', default: 1}, // limit for zooming out
max: {type: 'float', default: 2}, // limit for zomming int
zoomFactor: {type: 'float', default: 1} // (new) zoom factor (to be used with range slider)
},
init: function() {
var data = this.data;
var el = this.el;
// Attach event listener for 'zoom in' action
el.addEventListener('in', function(event) {
// Retrieve the current zoom factor of the camera
var curZoom = el.getAttribute('camera').zoom;
// Update new zoom factor for the camera (note: within the upper boundary
if (curZoom + data.delta > data.max) {
el.setAttribute('camera', 'zoom', data.max);
} else {
el.setAttribute('camera', 'zoom', curZoom + data.delta);
}
});
// Attach event listener for 'zoom out' action
el.addEventListener('out', function(event) {
// Retrieve the current zoom factor of the camera
var curZoom = el.getAttribute('camera').zoom;
// Update new zoom factor for the camera (if within the limit)
if (curZoom - data.delta < data.min) {
el.setAttribute('camera', 'zoom', data.min);
} else {
el.setAttribute('camera', 'zoom', curZoom - data.delta);
}
});
},
update: function() {
var data = this.data;
var el = this.el;
// Update the corresponding 'zoom' factor in camera whenever 'zoomFactor' value is changed
el.setAttribute('camera', 'zoom', data.zoomFactor);
}
});
|
function createGlobalTemp(YEARS, YEARMARKINGS, BODY, WIDTH, HEIGHT) {
const RED = [230, 100, 101];
const BLUE = [145, 152, 229];
function findMinMax() {
var min = Number.POSITIVE_INFINITY;
var max = Number.NEGATIVE_INFINITY;
for (var i = 0; i < YEARS.length; i++) {
var level = YEARS[i].globalTemp;
if (level < min) {
min = level;
}
if (level > max) {
max = level;
}
}
return [min, max];
}
var minMax = findMinMax();
function scaleRGB(temperature) {
var redRange = RED[0] - BLUE[0];
var greenRange = RED[1] - BLUE[1];
var blueRange = RED[2] - BLUE[2];
var tempMinMaxPercentage = minMax[1] - minMax[0];
var tempPercent = (temperature - minMax[0]) / tempMinMaxPercentage;
var scaledRed = Math.round((tempPercent * redRange) + BLUE[0]);
var scaledGreen = Math.round((tempPercent * greenRange) + BLUE[1]);
var scaledBlue = Math.round((tempPercent * blueRange) + BLUE[2]);
var scaled = [scaledRed, scaledGreen, scaledBlue];
return scaled;
}
for (var i = 0; i < (YEARS.length - 1); i++) {
var scaledRGB1 = scaleRGB(YEARS[i].globalTemp);
var scaledRGB2 = scaleRGB(YEARS[i + 1].globalTemp);
var leftRGB = "rgb(" + scaledRGB1[0] + "," + scaledRGB1[1] + "," + scaledRGB1[2] + ")";
var rightRGB = "rgb(" + scaledRGB2[0] + "," + scaledRGB2[1] + "," + scaledRGB2[2] + ")";
var box = document.createElement("div");
box.style.height = HEIGHT + "px";
box.style.width = Math.ceil(YEARMARKINGS[i + 1] - YEARMARKINGS[i] + 10) + "px";
box.style.position = "absolute";
box.style.top = "0px";
box.style.left = Math.floor(YEARMARKINGS[i]) + "px";
box.style.zIndex = "-1";
var bgColor = "linear-gradient(to left, " + rightRGB + ", " + leftRGB + ")";
box.style.background = bgColor;
BODY.appendChild(box);
}
} |
//PARA ACESSAR ARQUIVO
//requere o arquivo, por padrão é ".js" - então não precisa botar
// "./" caminho relativo para acessar dentro do arquivo
const moduloA = require('./moduloA')
const moduloB = require('./moduloB')
console.log(moduloA.ola)
console.log(moduloA.ateLogo)
console.log(moduloA.bemVindo)
console.log(moduloA)
console.log(moduloB.bomDia)
console.log(moduloB.boaNoite())
console.log(moduloB) |
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: ['./src/js/index.js','./src/index.html'],
output: {
path: path.resolve(__dirname, './build'),
filename: './js/built.js'
},
module: {
rules: [
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader" // compiles Less to CSS
}]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
limit:8192, //文件大小
publicPath:'../images', //引入图片的路径
outputPath:'./images', //决定图片的输出路径
name:'[hash:5].[ext]' //重命名
}
}
]
},
{
test: /\.js$/, // 涵盖 .js 文件
enforce: "pre", // 预先加载好 jshint loader
exclude: /node_modules/, // 排除掉 node_modules 文件夹下的所有文件
use: [
{
loader: "jshint-loader",
options: {
// 查询 jslint 配置项,请参考 http://www.jshint.com/docs/options/
// 例如
camelcase: true,
//jslint 的错误信息在默认情况下会显示为 warning(警告)类信息
//将 emitErrors 参数设置为 true 可使错误显示为 error(错误)类信息
emitErrors: false,
//jshint 默认情况下不会打断webpack编译
//如果你想在 jshint 出现错误时,立刻停止编译
//请设置 failOnHint 参数为true
failOnHint: false,
esversion: 6
//自定义报告函数
// reporter: function(errors) { }
}
}
]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './build',
hot: true ,//开启热模替换功能
port:3000,
open:true
}
}; |
const box = document.querySelector('.box');
const todoItself = document.querySelector('.todo-itself');
const todoField = document.querySelector('#todoField');
const addBtn = document.querySelector('.add');
const inputed = document.querySelector('.inputed');
const Edit = document.querySelector('#editTodo');
const btn = document.querySelector('#todoSend');
let arr = [];
let num = 0;
let arrays = [];
var array = localStorage.getItem('todo', arr);
let mainarr = [...arrays, ...arr];
console.log(mainarr);
localStorage.setItem('todo', arrays);
document.addEventListener('DOMContentLoaded', () => {
localStorage.setItem('todo', arrays);
console.log(arrays);
addBtn.addEventListener('click', () => {
let text = todoField.value;
mainarr += JSON.stringify(arr.push(text));
console.log(arr);
// console.log(mainarr);
localStorage.setItem('todo', JSON.stringify(arr));
if (text === '') {
alert("Todo can't be Empty");
} else {
num++;
todoField.select();
document.execCommand('cut');
let bodyHtml = '';
bodyHtml += ` <br> <article id="1" class="todo-itself">
<span id="num">${num}</span><p class="inputed">${text}</p>
<div class="buttons">
<span class="button" id="edit">Edit</span>
<span class="button" id="done">Done</span>
<span class="button" id="view">View</span>
</div>
</article><br><br>`;
box.innerHTML += bodyHtml;
const buttons = document.querySelectorAll('.button');
btns = [...buttons];
btns.forEach(item => {
item.addEventListener('click', e => {
let E = e.target;
if (E.id === 'done') {
E.parentElement.parentElement.remove();
let previous = E.parentElement.previousElementSibling.parentElement;
console.log(previous);
num--;
} else if (E.id === 'edit') {
let edit = E.parentElement.previousElementSibling.textContent;
todoField.value = edit;
Edit.style.visibility = 'visible';
function editTodo() {
let newEdit = todoField.value;
if (text === newEdit) {
console.log('same text');
} else {
console.log(arr);
console.log(newEdit);
E.parentElement.previousElementSibling.textContent = newEdit;
setTimeout(() => {
todoField.select();
document.execCommand('cut');
Edit.style.visibility = 'hidden';
}, 1000);
}
}
Edit.addEventListener('click', e => {
editTodo();
});
}
});
});
}
});
}); |
var SessionCache = (function() {
var sessionCacheData = {};
// When session storage is not available or disabled, such as in the case
// of iOS private browsing mode, create a "best possible" session storage
// standin that stores data in javascript space.
//
// See http://m.cg/post/13095478393/detect-private-browsing-mode-in-mobile-safari-on-ios5
try {
sessionStorage.setItem('available-test', '1');
sessionStorage.removeItem('available-test');
// Return an object for stubability
return {
getItem: function(name) {
return sessionStorage.getItem(name);;
},
setItem: function(name, value) {
sessionStorage.setItem(name, value);
},
removeItem: function(name) {
sessionStorage.removeItem(name);
}
};
} catch (err) {
return {
getItem: function(name) {
return sessionCacheData[name];
},
setItem: function(name, value) {
sessionCacheData[name] = value;
},
removeItem: function(name) {
delete sessionCacheData[name];
}
};
}
})();
|
function mostrarTasa(){
var s = $('#result').val().replace(".","");
document.write(s);
} |
/*
*
* codeTableApi.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
* @author vn87351
* @since 2.12.0
*/
'use strict';
(function () {
angular.module('productMaintenanceUiApp').factory('codeTableApi', codeTableApi);
codeTableApi.$inject = ['urlBase', '$resource'];
/**
* Creates a factory to create methods to Code Table API.
*
* Supported method:
* codetableApi: Will return all varietal from database.
*
* @param urlBase The base URL to use to contact the backend.
* @param $resource Angular $resource used to construct the client to the REST service.
* @returns {*} The API factory.
*/
function codeTableApi(urlBase, $resource) {
return $resource(null, null, {
'getAllVarietal': {
method: 'GET',
url: urlBase + '/pm/code-table/getAllVarietal',
isArray: true
},
'getAllVarietalType': {
method: 'GET',
url: urlBase + '/pm/code-table/getAllVarietalType',
isArray: true
},
'getAllWineArea': {
method: 'GET',
url: urlBase + '/pm/code-table/getAllWineArea',
isArray: true
},
'getAllWineMaker': {
method: 'GET',
url: urlBase + '/pm/code-table/getAllWineMaker',
isArray: true
},
'getAllWineRegion': {
method: 'GET',
url: urlBase + '/pm/code-table/getAllWineRegion',
isArray: true
},
'getAllProductStateWarnings': {
method: 'GET',
url: urlBase + '/pm/codeTable/productStateWarning/findAll',
isArray:true
},
'getAllRetailUnitsOfMeasure': {
method: 'GET',
url: urlBase + '/pm/codeTable/retailUnitOfMeasure/findAll',
isArray:true
},
'findAllProductGroupTypes': {
method: 'GET',
url: urlBase + '/pm/codeTable/productGroupType/findAllProductGroupTypes',
isArray: true
},
'addNewVarietal' : {
method: 'POST',
url: urlBase + '/pm/code-table/addNewlVarietal',
isArray: false
},
'updateVarietal' : {
method: 'POST',
url: urlBase + '/pm/code-table/updateVarietal',
isArray: false
},
'deleteVarietal' : {
method: 'POST',
url: urlBase + '/pm/code-table/deleteVarietal',
isArray: false
},
'addNewVarietalType' : {
method: 'POST',
url: urlBase + '/pm/code-table/addNewlVarietalType',
isArray: false
},
'updateVarietalType' : {
method: 'POST',
url: urlBase + '/pm/code-table/updateVarietalType',
isArray: false
},
'deleteVarietalType' : {
method: 'POST',
url: urlBase + '/pm/code-table/deleteVarietalType',
isArray: false
},
'addNewWineRegion' : {
method: 'POST',
url: urlBase + '/pm/code-table/addNewlWineRegion',
isArray: false
},
'updateWineRegion' : {
method: 'POST',
url: urlBase + '/pm/code-table/updateWineRegion',
isArray: false
},
'deleteWineRegion' : {
method: 'POST',
url: urlBase + '/pm/code-table/deleteWineRegion',
isArray: false
},
'addNewWineMaker' : {
method: 'POST',
url: urlBase + '/pm/code-table/addNewlWineMaker',
isArray: false
},
'updateWineMaker' : {
method: 'POST',
url: urlBase + '/pm/code-table/updateWineMaker',
isArray: false
},
'deleteWineMaker' : {
method: 'POST',
url: urlBase + '/pm/code-table/deleteWineMaker',
isArray: false
},
'addNewWineArea' : {
method: 'POST',
url: urlBase + '/pm/code-table/addNewlWineArea',
isArray: false
},
'updateWineArea' : {
method: 'POST',
url: urlBase + '/pm/code-table/updateWineArea',
isArray: false
},
'deleteWineArea' : {
method: 'POST',
url: urlBase + '/pm/code-table/deleteWineArea',
isArray: false
},
'getAllProductCategories': {
method: 'GET',
url: urlBase + '/pm/codeTable/productCategory/allProductCategories',
isArray: true
},
'getAllMarketConsumerEventTypes': {
method: 'GET',
url: urlBase + '/pm/codeTable/productCategory/allMarketConsumerEventTypes',
isArray:true
},
'getAllProductCategoryRoles': {
method: 'GET',
url: urlBase + '/pm/codeTable/productCategory/allProductCategoryRoles',
isArray:true
},
'updateProductCategory': {
method: 'POST',
url: urlBase + '/pm/codeTable/productCategory/updateProductCategory',
isArray:false
},
'addProductCategory': {
method: 'POST',
url: urlBase + '/pm/codeTable/productCategory/addProductCategory',
isArray:false
},
'deleteProductCategory': {
method: 'POST',
url: urlBase + '/pm/codeTable/productCategory/deleteProductCategory',
isArray:false
},
'deleteProductGroupTypes': {
method: 'POST',
url: urlBase + '/pm/codeTable/productGroupType/deleteProductGroupTypes',
},
});
}
})();
|
function DataNode(editor){
this.editor = editor;
this.graph = this.editor.graph;
this.model = this.graph.model;
this.multiplicities = new Array();
this.overlaysMap = new Map();
this.init();
}
DataNode.prototype = new MashupNode();
DataNode.prototype.constructor = DataNode;
DataNode.prototype = new MashupNode();
DataNode.prototype.constructor = DataNode;
DataNode.prototype.overlaysMap = null;
DataNode.prototype.init = function(){
//must correspondign to Multiplicities
// hard code here
var typeKey = ['jsonOperator', 'joinOperator'];
//get as Source Multiplicities
// var validNeighbors = this.multiplicities[0].validNeighbors;
// for(var i in validNeighbors)
// typeKey.push(validNeighbors[i]);
//create overlay
var step = -50;
for(var i = 0; i < typeKey.length; i ++){
var overlay = new mxCellOverlay(new mxImage('images/add.png', 24, 24), 'Add ' + typeKey[i]);
overlay.cursor = 'hand';
overlay.offset = new mxPoint(50, step);
step = step + 24;
overlay.align = mxConstants.ALIGN_CENTER;
// overlay.listner_flag = false;
this.overlaysMap.put(typeKey[i], overlay);
}
}
//supposing all of the outgoing key corresponding to DataNode
DataNode.prototype.createOverlayListener = function(cell, key, overlay, nodeMap){
overlay.addListener(mxEvent.CLICK, mxUtils.bind(this, function(sender, evt){
var model = this.model;
var editor = this.editor;
var graph = this.graph;
var parent = cell.getParent();
var e = evt.getProperty('event');
var x = mxEvent.getClientX(e);
var y = mxEvent.getClientY(e);
var v1Geo = model.getGeometry(cell);
var vertex = editor.templates[key];
var node = nodeMap.get(key);
var style = node.getAttribute("style");
if (vertex != null && style != null) {
vertex = vertex.clone();
vertex.setStyle(style);
}
//var cell = graph.getModel().cloneCell(template);
editor.addVertex(parent, vertex, x, y + 100);
model.beginUpdate();
try
{
var edge = editor.createEdge(cell, vertex);
var edgeValue = model.getValue(edge);
var inParam = OperatorUtils.getOperatorInEdgeParam(key);
//get index = 0 param by default
edgeValue.setAttribute('attribute', inParam[0].key);
if (model.getGeometry(edge) == null) {
var k = new mxGeometry();
k.relative = true;
e.setGeometry(edge, k);
}
graph.addEdge(edge, parent, cell, vertex);
graph.setSelectionCell(vertex);
// redraw the cell overlay
// overlaysHelper.removeOverlay(graph, cell);
// overlaysHelper.addOverlay(graph, cell, overlaysHelper.getOverlay(graph, cell, editor, nodeMap));
graph.removeCellOverlays(cell);
}
finally
{
model.endUpdate();
// overlay.listner_flag = true;
}
}));
}
DataNode.prototype.getMultiplicities = function(multiplicitiesContainer){
// DataNode as Source constrain only connect to JdbcOperator, JsonOperator
var asTarget = new mxMultiplicity(
true, 'dataNode', null, null, null, 'n', ['jsonOperator','jdbcOperator','joinOperator','fusionChartOperator'],
null,
'DataNode must connect to OperatorNode as target');
// DataNode as Target constrain only connect to JdbcOperator, JsonOperator
var asSource = new mxMultiplicity(
false, 'dataNode', null, null, 1, 1, ['jsonOperator','jdbcOperator','joinOperator','fusionChartOperator'],
'DataNode must have only one OperatorNode as source',
'DataNode must connect to OperatorNode as source');
this.multiplicities.push(asTarget);
this.multiplicities.push(asSource);
// DataNode as Target constrain only
multiplicitiesContainer.push(asTarget);
multiplicitiesContainer.push(asSource);
}
DataNode.prototype.getOverLays = function(cell){
//
var asTargetMulti = this.multiplicities[0];
var maxCount = asTargetMulti.max;
var cellOutgoingEdges = this.model.getOutgoingEdges(cell);
var result = new Map();
if(maxCount = 'n' || cellOutgoingEdges.length < maxCount){
// all type target node can show
var clone = mxUtils.clone(this.overlaysMap);
//result.put(key, clone);
return clone;
// return this.overlaysMap;
}
return new Map();
}
DataNode.prototype.save = function(userObject){
mashup.saveDataNode(userObject);
}
|
const express = require('express')
const router = require("express-promise-router")()
const CourseController = require('../controllers/course')
const SiteController = require('../controllers/site')
//get home page
router.get('/', SiteController.getHomePage)
//get the admin sign in page
router.get("/admin/signin", SiteController.getAdminSignInPage)
//get the admin sign up page
router.get("/admin/signup", SiteController.getAdminSignUpPage)
//get the page for course registrant to apply
router.get('/start-job-search', SiteController.getJobs)
//get the lead main course page
router.get('/courses', SiteController.getMainCourseLandingPage)
//get the catalog page
router.get('/classes', SiteController.getMainClassLandingPage)
//get courses for the general site page
router.get('/catalog', SiteController.getCatalog)
//get the questions page
router.get("/questions", SiteController.getQuestionsPage)
//receipt page after waitlisting for a course
router.get('/success', SiteController.getReceiptPage)
//gets page for student to pay registration fee after receiving email // getStudentPayRegistrationForm
router.get('/secure/:code/:course_id/:student_id', SiteController.getStudentPayRegistrationForm )
//receipt page after receipt of payment for course sign up
router.get('/confirm-payment', SiteController.getReceiptPage)
//get the courses landing page
router.get('/course/:name', SiteController.getCoursesLandingPage )
//get lead page for other courses
router.get("/schedules/:name", SiteController.getLeadCourses)
//get lead page for courses
router.get('/register/:course/:course_id', SiteController.getCourseRegistrationForm)
//get lead page for courses
router.get('/train/:course/:course_id', SiteController.getCourseRegistrationForm)
//get regular sign up page
router.get('/signup/:course_id', SiteController.getCourseRegistrationForm)
//get the the videos page
router.get("/videos", SiteController.getVideosPage)
//get the all courses - single day, multiple day, and reservations - in catalog
router.get('/learn/:course', SiteController.getCatalogCourse)
//get the the why post page
router.get("/recruit", SiteController.getJobsMainLandingPage )
//get the hca page
router.get("/page/:course", SiteController.getCourseDetailsPage )
//get the jobs landing page
router.get("/hire", SiteController.getJobsLandingPage )
module.exports = router |
const getCombinations = (items, length) => {
if (length === 1) return items.map((item) => [item]);
return items.flatMap((item) => getCombinations(items, length - 1).map((x) => [item, ...x]));
};
const last = (array) => array[array.length - 1];
const count = (array, item) => array.reduce((a, x) => (x === item ? a + 1 : a), 0);
const count2d = (array2d, item) => array2d.reduce((a, y) => a + count(y, item), 0);
const intersect = (setA, setB) => {
const result = new Set();
setB.forEach((item) => {
if (setA.has(item)) {
result.add(item);
}
});
return result;
};
module.exports = { getCombinations, last, count, count2d, intersect };
|
import React, { useState } from 'react';
const Pagination = ({ itemsPerPage, totalItems, paginate }) => {
const pageNumbers = [];
const [clicked, setClicked] = useState(false);
const [currentNumber, setCurrentNumber] = useState(1);
for (let i = 1; i <= Math.ceil(totalItems / itemsPerPage); i++) {
pageNumbers.push(i);
window.scrollTo(0, 0);
}
return (
<ul className="pagination">
<li className="page-item">
<a
className="page-link"
onClick={() => {
currentNumber >= 2 ? paginate(currentNumber-1) : paginate(1);
}}>
{'<'}
</a>
</li>
{pageNumbers.map((number, key) => (
<li className="page-item" key={key}>
<a
onClick={() => {
setCurrentNumber(number);
setClicked(true);
paginate(number);
}}
className={clicked ? 'page-link page-number' : 'page-link page-number active'}>
{number}
</a>
</li>
))}
<li className="page-item">
<a className="page-link" onClick={() => {
currentNumber >= pageNumbers.length ? paginate(pageNumbers.length) : paginate(currentNumber+1);
}}>
{'>'}
</a>
</li>
</ul>
);
};
export default Pagination;
|
let toasts = 0;
const toast = (type, message) => {
const tl = new TimelineMax();
const toastEl = $(`<div class="toast ${type}">${message}</div>`);
$('body').append(toastEl);
tl.to(toastEl, .25, {
opacity: 1,
y: 0 + (66 * toasts),
ease: Power4.easeOut,
onComplete: function() {
toasts++;
}
});
tl.to(toastEl, .5, {
delay: 2,
y: '-100px',
opacity: 0,
ease: Power4.easeOut,
onComplete: function() {
toastEl.remove();
toasts--;
}
});
}
$('body').on('click', '[data-toast]', function() {
let toastText = $(this).attr('data-toast');
toast('success', toastText);
});
|
// @flow
import * as React from 'react';
import MapView from 'react-native-maps';
import { PositionMarker } from '@kiwicom/mobile-shared';
type Props = {|
+coordinate: ?{|
+latitude: number,
+longitude: number,
|},
+color?: string,
+code: string,
|};
export default function TransportationMapMarker({
coordinate,
color,
code,
}: Props) {
if (coordinate) {
return (
<MapView.Marker coordinate={coordinate}>
<PositionMarker code={code} color={color} />
</MapView.Marker>
);
}
return null;
}
|
const MongoClient = require('mongodb').MongoClient;
const fs = require('fs')
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
var moment = require('moment') //時間
var moment = require('moment-timezone') //時區
var allResults = 0; //所有資料筆數
var limit = 0; //最多limit筆資料
var skip = 0; //跳過前面skip筆資料
var check = 0;//每次搜尋歸0
var first_skip = 0;
var offset = 10;
var start = 0;
var end = 0;
// date = '2018-06-14'
// cateogry = '時尚消費'
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*')
return next()
})
router.get('/sub', async (ctx, next) => {
var { email, subCategory } = ctx.request.query
user = {
'email': email,
'subCategory': subCategory,
}
ctx.body = user
console.log('----------')
// email_list.push(user);
console.log(user)
// writefile
fs.appendFile('./userEmail/emailList.txt', '@user:' + '\n' + '@email:' + user.email + '\n' + '@category:' + user.subCategory + '\n', "UTF8", function (err) {
if (err)
console.log(err);
else
console.log('Append operation complete.');
});
});
router.get('/search', async (ctx, next) => {
console.log("router.get('/search')")
var { term, date, category, limit, skip } = ctx.request.query
if (date == '今天新聞') { var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '昨天新聞') { var first_Date = moment().tz('Asia/Taipei').subtract(1, 'days').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '當週新聞') {
var last_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD');//當天
var week_day = moment().tz('Asia/Taipei').format('d'); //星期幾
var week_day_Mon = moment().tz('Asia/Taipei').subtract(week_day - 1, 'days').format('YYYY-MM-DD');//星期一日期
var first_Date = week_day_Mon
}
if (date == '當月新聞') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-01')
var last_Date = moment().tz('Asia/Taipei').endOf('month').format('YYYY-MM-DD')
}
if (date == '2018') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-01-01')
var last_Date = moment().tz('Asia/Taipei').format('YYYY-12-31')
}
if (date == '2017') {
var first_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-12-31');
}
if (date == '2016') {
var first_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-12-31');
}
if (date == '2015') {
var first_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-12-31');
}
if (date == '2014') {
var first_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-12-31');
}
if (date == '2013') {
var first_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-12-31');
}
if (date == '2012') {
var first_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-12-31');
}
limit = parseInt(limit);
skip = parseInt(skip);
console.log(`${term},${first_Date},${last_Date},${category},${limit},${skip}`)
return new Promise((resolve, reject) => {
MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) {
if (err) throw err;
db.collection('news', function (err, collection) {
collection.find(
{
$text: { $search: term },
$and: [
{ "date": { $gte: first_Date, $lte: last_Date } },
{ "category": category },
],
},
{
score: { $meta: "textScore" }
}
).limit(10).skip(skip).sort({ score: { $meta: "textScore" } })
.toArray(function (err, items) {
if (err) throw err;
console.log("All results " + items.length + " results!");
// 如果limit=30,skip=20 =>第3分頁會出現第第30~60筆,limit=40,skip=30 =>第4分頁會出現第第40~80筆,拿取前一頁除了前10筆以外的資料,e.g.第3頁=拿第2頁扣掉前十筆的資料
console.log(items.length)
// ctx.body = items.splice(0, 10)
ctx.body = items
console.log(ctx.body.length)
resolve()
db.close(); //關閉連線
});
});
});
});
})
// 拿總結果數
router.get('/', async (ctx, next) => {
console.log("router.get(' /')")
// ctx.request.quer= > { term: 'javan', offset: '0' }
var { term, date, category } = ctx.request.query
if (date == '今天新聞') { var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '昨天新聞') { var first_Date = moment().tz('Asia/Taipei').subtract(1, 'days').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '當週新聞') {
var last_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD');//當天
var week_day = moment().tz('Asia/Taipei').format('d'); //星期幾
var week_day_Mon = moment().tz('Asia/Taipei').subtract(week_day - 1, 'days').format('YYYY-MM-DD');//星期一日期
var first_Date = week_day_Mon
}
if (date == '當月新聞') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-01')
var last_Date = moment().tz('Asia/Taipei').endOf('month').format('YYYY-MM-DD')
}
if (date == '2018') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-01-01')
var last_Date = moment().tz('Asia/Taipei').format('YYYY-12-31')
}
if (date == '2017') {
var first_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-12-31');
}
if (date == '2016') {
var first_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-12-31');
}
if (date == '2015') {
var first_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-12-31');
}
if (date == '2014') {
var first_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-12-31');
}
if (date == '2013') {
var first_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-12-31');
}
if (date == '2012') {
var first_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-12-31');
}
console.log(`${term},${date},${category}`)
console.log(`${term},${first_Date},${last_Date},${category}`)
// ctx.body = 'we are at home!';
return new Promise((resolve, reject) => {
MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) {
if (err) throw err;
db.collection('news', function (err, collection) {
collection.find(
{
$text: { $search: term },
$and: [
{ "date": { $gte: first_Date, $lte: last_Date } },
{ "category": category },
],
},
{
score: { $meta: "textScore" }
}
).sort({ score: { $meta: "textScore" } })
.toArray(function (err, items) {
if (err) throw err;
console.log("All results " + items.length + " results!");
// 如果limit=30,skip=20 =>第3分頁會出現第第30~60筆,limit=40,skip=30 =>第4分頁會出現第第40~80筆,拿取前一頁除了前10筆以外的資料,e.g.第3頁=拿第2頁扣掉前十筆的資料
// console.log(items)
// ctx.body = items.splice(0, 10)
ctx.body = items.length
console.log(ctx.body.length)
resolve()
db.close(); //關閉連線
});
});
});
});
})
// 預設是全部新聞
router.get('/all_news', async (ctx, next) => {
console.log("router.get('all_news')")
// ctx.request.quer= > { term: 'javan', offset: '0' }
var { term, date } = ctx.request.query
if (date == '今天新聞') { var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '昨天新聞') { var first_Date = moment().tz('Asia/Taipei').subtract(1, 'days').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '當週新聞') {
var last_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD');//當天
var week_day = moment().tz('Asia/Taipei').format('d'); //星期幾
var week_day_Mon = moment().tz('Asia/Taipei').subtract(week_day - 1, 'days').format('YYYY-MM-DD');//星期一日期
var first_Date = week_day_Mon
}
if (date == '當月新聞') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-01')
var last_Date = moment().tz('Asia/Taipei').endOf('month').format('YYYY-MM-DD')
}
if (date == '2018') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-01-01')
var last_Date = moment().tz('Asia/Taipei').format('YYYY-12-31')
}
if (date == '2017') {
var first_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-12-31');
}
if (date == '2016') {
var first_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-12-31');
}
if (date == '2015') {
var first_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-12-31');
}
if (date == '2014') {
var first_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-12-31');
}
if (date == '2013') {
var first_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-12-31');
}
if (date == '2012') {
var first_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-12-31');
}
console.log(`${term},${date},${first_Date},${last_Date}`)
// ctx.body = 'we are at home!';
return new Promise((resolve, reject) => {
MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) {
if (err) throw err;
db.collection('news', function (err, collection) {
collection.find(
{
$text: { $search: term },
$and: [
{ "date": { $gte: first_Date, $lte: last_Date } },
],
},
{
score: { $meta: "textScore" }
}
).sort({ score: { $meta: "textScore" } })
.toArray(function (err, items) {
if (err) throw err;
console.log("All results " + items.length + " results!");
// 如果limit=30,skip=20 =>第3分頁會出現第第30~60筆,limit=40,skip=30 =>第4分頁會出現第第40~80筆,拿取前一頁除了前10筆以外的資料,e.g.第3頁=拿第2頁扣掉前十筆的資料
console.log(items.length)
// ctx.body = items.splice(0, 10)
ctx.body = items.length
console.log(ctx.body.length)
resolve()
db.close(); //關閉連線
});
});
});
});
})
router.get('/all_news_search', async (ctx, next) => {
console.log("router.get('all_news_search')")
var { term, date, limit, skip } = ctx.request.query
if (date == '今天新聞') { var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '昨天新聞') { var first_Date = moment().tz('Asia/Taipei').subtract(1, 'days').format('YYYY-MM-DD'); var last_Date = first_Date }
if (date == '當週新聞') {
var last_Date = moment().tz('Asia/Taipei').format('YYYY-MM-DD');//當天
var week_day = moment().tz('Asia/Taipei').format('d'); //星期幾
var week_day_Mon = moment().tz('Asia/Taipei').subtract(week_day - 1, 'days').format('YYYY-MM-DD');//星期一日期
var first_Date = week_day_Mon
}
if (date == '當月新聞') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-MM-01')
var last_Date = moment().tz('Asia/Taipei').endOf('month').format('YYYY-MM-DD')
}
if (date == '2018') {
var first_Date = moment().tz('Asia/Taipei').format('YYYY-01-01')
var last_Date = moment().tz('Asia/Taipei').format('YYYY-12-31')
}
if (date == '2017') {
var first_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(1, 'years').format('YYYY-12-31');
}
if (date == '2016') {
var first_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(2, 'years').format('YYYY-12-31');
}
if (date == '2015') {
var first_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(3, 'years').format('YYYY-12-31');
}
if (date == '2014') {
var first_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(4, 'years').format('YYYY-12-31');
}
if (date == '2013') {
var first_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(5, 'years').format('YYYY-12-31');
}
if (date == '2012') {
var first_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-01-01');
var last_Date = moment().tz('Asia/Taipei').subtract(6, 'years').format('YYYY-12-31');
}
limit = parseInt(limit);
skip = parseInt(skip);
console.log(`${term},${date},${first_Date},${last_Date},${limit},${skip}`)
return new Promise((resolve, reject) => {
MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) {
if (err) throw err;
db.collection('news', function (err, collection) {
collection.find(
{
$text: { $search: term },
$and: [
{ "date": { $gte: first_Date, $lte: last_Date } },
],
},
{
score: { $meta: "textScore" }
}
).limit(10).skip(skip).sort({ score: { $meta: "textScore" } })
.toArray(function (err, items) {
if (err) throw err;
console.log("All results " + items.length + " results!");
// 如果limit=30,skip=20 =>第3分頁會出現第第30~60筆,limit=40,skip=30 =>第4分頁會出現第第40~80筆,拿取前一頁除了前10筆以外的資料,e.g.第3頁=拿第2頁扣掉前十筆的資料
console.log(items.length)
// ctx.body = items.splice(0, 10)
ctx.body = items
console.log(ctx.body.length)
resolve()
db.close(); //關閉連線
});
});
});
});
})
const port = process.env.PORT || 3000
app
.use(router.routes())
.listen(port, err => {
if (err) console.error(err)
console.log(`App Listening on Port ${port}`)
}) |
var xhr = require('xhr')
//var currentImage = document.getElementById('carousel-image')
var currentState = 0
var leftButton = document.getElementById('left-control')
var rightButton = document.getElementById('right-control')
var indicators = []
var itemImages = []
console.log('here!')
xhr('/carousel-photos', function (err, resp, body) {
if (err) console.log(err)
else{
setInterval(moveRight, 15000)
var images = JSON.parse(body)
images.forEach(function(imageUri, index) {
var newLi = document.createElement('li')
newLi.setAttribute('class', 'indicator')
document.getElementById('indicator-ol').appendChild(newLi)
indicators.push(newLi)
var newItem = document.createElement('div')
newItem.setAttribute('class', 'item')
var newImage = document.createElement('img')
newImage.setAttribute('src', "img/carousel-images/"+ images[index])
newItem.appendChild(newImage)
document.getElementById('slide-wrapper').appendChild(newItem)
itemImages.push(newItem)
})
indicators[currentState].setAttribute('class', 'indicator active')
itemImages[currentState].setAttribute('class', 'item active')
function moveLeft() {
indicators[currentState].setAttribute('class', 'indicators')
itemImages[currentState].setAttribute('class', 'item')
if (currentState === 0){ currentState = images.length-1 }
else { currentState-- }
indicators[currentState].setAttribute('class', 'indicator active')
itemImages[currentState].setAttribute('class', 'item active')
}
function moveRight() {
indicators[currentState].setAttribute('class', 'indicators')
itemImages[currentState].setAttribute('class', 'item')
if (currentState === images.length-1){ currentState = 0 }
else { currentState++ }
indicators[currentState].setAttribute('class', 'indicator active')
itemImages[currentState].setAttribute('class', 'item active')
}
leftButton.onclick = moveLeft
rightButton.onclick = moveRight
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null
var yDown = null
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX
yDown = evt.touches[0].clientY
}
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return
}
var xUp = evt.touches[0].clientX
var yUp = evt.touches[0].clientY
var xDiff = xDown - xUp
var yDiff = yDown - yUp
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) { moveRight() }
else { moveLeft() }
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
}
}
})
|
import inquirer from 'inquirer';
import multichoice from '../utils/inquirer-multichoice';
import * as questions from '../config/questions';
import { defaultFramework as defaultCssFramework } from '../config/frameworks/css';
export default async function(options) {
if(options.skipPrompts) {
return {
...options,
cssFramework: defaultCssFramework
}
}
let questionQueue = [];
if(!options.cssFramework) {
questionQueue.push(multichoice(questions.css));
}
if(!options.git) {
questionQueue.push(questions.git);
}
const answers = await inquirer.prompt(questionQueue);
return {
...options,
cssFramework: options.cssFramework || answers.cssFramework,
git: options.git || answers.git
}
} |
function (key, values, rereduce) {
var addrs = {};
for (var vn in values) {
addrs[values[vn][0]] = values[vn][1];
}
var returns = [];
for (var addr in addrs) {
returns.push([addr, addrs[addr]]);
}
return returns;
}
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2014-11-04.
*/
'use strict';
/**
* The following exit codes means:
* 2 Wrong configuration
* 3 HTTP/HTTPS port is busy or restricted
* 4 Manually restarted from API (look at `/api/admin/restart`)
*/
// external libs
const Promise = require('bluebird');
// services
const LKE = require('./services');
// locals
const Options = require('./options');
class WorkerSignal extends Error {}
// remove deprecation warnings for some modules (nodejs-depd)
process.env['NO_DEPRECATION'] = 'express-session';
/**
* @returns {Bluebird<void>} resolved when Linkurious is up
*/
function startApp() {
// parse command-line options
const parsedOptions = Options.parse(LKE);
LKE.init(parsedOptions);
// configure bluebird
Promise.config({
// Enable all warnings except forgotten return statements
warnings: {
wForgottenReturn: false
},
// Enable long stack traces
longStackTraces: !!(LKE.isDevMode() || LKE.isTestMode()),
// Note: longStackTraces = true will result in a memory leak due to the use of promise loops in the scheduler service
// Enable cancellation
cancellation: true,
// Enable monitoring
monitoring: true
});
// these should never fail
const Config = LKE.getConfig();
const Errors = LKE.getErrors();
const Log = LKE.getLogger(__filename);
const Utils = LKE.getUtils();
// services created in init phase
let StateMachine, Data, Access;
// init rejects when WorkerSignal if we are a Layout worker
/**@type {function}*/
const init = Promise.method(() => {
// layout cluster init (stop after that if not master)
const Layout = LKE.getLayout();
if (!Layout.isMaster) {
Layout.startWorker();
throw new WorkerSignal();
} else {
// load configuration from file
LKE.getConfig().load();
// setup a default costumer ID if it's not setup already in the configuration
if (Utils.noValue(Config.get('customerId'))) {
Config.set('customerId', Utils.generateUniqueCustomerId());
}
Layout.startCluster();
}
Log.info('Starting Linkurious ' + LKE.getVersionString());
StateMachine = LKE.getStateMachine();
Data = LKE.getData();
Access = LKE.getAccess();
});
return init().then(() => {
return LKE.getFirstRun().check();
}).then(() => {
return LKE.getSqlDb().connect();
}).then(() => {
// register a SIGINT/SIGTERM handler
process.on('SIGINT', onSignal);
process.on('SIGTERM', onSignal);
}).then(() => {
return Access.ensureBuiltinGroups();
}).then(() => {
return Access.migrateLegacyGroups();
}).then(() => {
return Access.providersStartupCheck();
}).then(() => {
return LKE.getWebServer().start();
}).then(() => {
return Data.connectSources();
}).then(() => {
return Data.indexSources(true);
}).then(() => {
// start the Alert Manager
return LKE.getAlert().start();
}).catch(WorkerSignal, () => {
Log.info('Layout worker ready.');
}).catch(Errors.LkError, err => {
if (StateMachine) {
StateMachine.set('Linkurious', 'unknown_error');
}
if (err && err.isTechnical() && err.stack) {
Log.error(err.stack);
} else {
Log.error(err.message);
}
if (err && err.key) {
if (err.key === 'invalid_configuration') {
process.exit(2);
} else if (err.key === 'port_restricted' || err.key === 'port_busy') {
process.exit(3);
}
}
}).catch(err => {
if (StateMachine) {
StateMachine.set('Linkurious', 'unknown_error');
}
Log.error(err && err.stack ? err.stack : err.message);
});
}
/**
* Clean up open connections and terminate the process.
*/
function onSignal() {
LKE.getSqlDb().close();
LKE.getData(false).disconnectAll();
process.exit(0);
}
// export the start promise to enable programmatic instantiation
module.exports = startApp();
|
/**
* @class Alloy.Globals
* Classe global, instanciada automáticamente antes de executar a classe controllers.Index.
* Todas as propriedades publicas são acessíveis através de Alloy.Globals, que é uma variável global.
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação
*/
/**
* @property {Number} CustomComponentHeight
* Altura padrão dos controles. Exemplo: Botões
*/
Alloy.Globals.CustomComponentHeight = 40;
/**
* @property {Object} CustomImageSize Tamanho padrão dos icones
* @property {Number} CustomImageSize.height Altura
* @property {Number} CustomImageSize.width Largura
*/
Alloy.Globals.CustomImageSize = {height: 32, width: 32};
/**
* @property {Number} CustomTextSize Tamanho padrão da fonte dos controles.
*/
Alloy.Globals.CustomTextSize = 18;
/**
* @property {Number} CustomTitleFont Tamanho padrao da fonte dos titulos dos controles.
*/
Alloy.Globals.CustomTitleFont = 20;
/**
* @property {String} MainColor Cor padrão no aplicativo. Todo controle que precise ficar em destaque, deve estar nessa cor.
*/
Alloy.Globals.MainColor = "#fd9b33";
/**
* @property {String} MainColorLight Cor que indica quando um controle foi selecionado. Exemplo: clique no botão.
*/
Alloy.Globals.MainColorLight = "#FFA500";
/**
* @property MainDomain
* Endereço do domínio da empresa. Instanciado após o login.
* @type {String}
*/
Alloy.Globals.MainDomain = null;
/**
* @property LocaWebDomain
* Endereço do servidor do LocalWeb.
* @type {String}
*/
Alloy.Globals.LocalWebDomain = "http://177.135.249.37:89/";
/**
* @property {JSONObject} Empresa Informações da empresa que o usuário está logado. Instanciado após o login. Possuí os mesmos atributos do modelo {widgets.Login.models.Empresa}.
*/
Alloy.Globals.Empresa = null;
/**
* @property {JSONObject} Usuario Informações do usuário logado. Instanciado após o login. Possuí os mesmos atributos do modelo {widgets.Login.models.Usuario}.
*/
Alloy.Globals.Usuario = null;
/**
* @property {Array} pilhaWindow Pilha contendo todas as janelas abertas. O topo da pilha representa a janela atual.
*/
Alloy.Globals.pilhaWindow = [];
/**
* @method currentWindow
* Retorna a janela atual.
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
* @returns {Ti.UI.Window}
*/
Alloy.Globals.currentWindow = function(){
return Alloy.Globals.pilhaWindow[Alloy.Globals.pilhaWindow.length - 1];
};
/**
* @property {widgets.Util.Tela} configTela propriedade usada configurar telas.
* @private
*/
var configTela = Alloy.createWidget("Util", "Tela");
/**
* @method configWindow
* Configura a janela para o padrão da arquitetura. Obrigatório o uso no construtor de qualquer janela.
* @param {Ti.UI.Window} janela Janela que se deseja configurar.
* @param {Alloy} seuAlloy Variável $ reservada em todo controller.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.configWindow = function(janela, seuAlloy){
configTela.initConfigWindow(janela, seuAlloy);
};
/**
* @method configPopUp
* Configura a popup para o padrão da arquitetura. Obrigatório o uso no construtor de qualquer popup.
* @param {Controller} controller Controller da popup.
* @param {Function} [showFunction] Função que será executada toda vez que o controller executar a função show.
* @param {Function} [cancelFunction] Função que será executada toda vez que o controller executar a função close.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.configPopUp = function(controller, showFunction, cancelFunction){
configTela.initConfigPopUp(controller, showFunction, cancelFunction);
};
/**
* @property {Boolean} estaOnline Indica se o dispositivo está online.
*/
Alloy.Globals.estaOnline = Ti.Network.online;
/**
* @property {widgets.Util.Format} format Objeto utilizado para formatação de dados. Toda formatação de dados deve ser feita por esse objeto.
*/
Alloy.Globals.format = Alloy.createWidget("Util", "Format");
/**
* @property {widgets.DAL.widget} DAL Objeto utilizado para a camada de persistencia de dados.
*/
Alloy.Globals.DAL = Alloy.createWidget("DAL");
/**
* @property {widgets.Util.Transicao} Transicao Deve ser utilizado sempre que for necessário chamar uma nova janela.
*/
Alloy.Globals.Transicao = Alloy.createWidget("Util", "Transicao");
/**
* @method Alerta
* Exibe um alerta simples com o título e a mensagem.
* @param {String} titulo Título do alerta. Por parão será considerado "Alerta".
* @param {String} mensagem Mensagem a ser exibida no alerta.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.Alerta = function(titulo, mensagem){
var check = Alloy.createWidget("GUI", "Mensagem");
check.init(titulo, mensagem);
check.show();
};
/**
* @property {widgets.Util.Erro} telaErro Controller da tela de erro.
* @private
*/
var telaErro = Alloy.createWidget("Util", "Erro");
/**
* @event onError
* Deve ser invocado em todo caso catch não tratado.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.onError = function(erro, rotina, arquivo){
telaErro.show(erro, rotina, arquivo);
};
/**
* @method logout
* Exibe a mensagem de confirmação de logout.
* @private
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
function logout(){
var check = Alloy.createWidget("GUI", "Mensagem");
check.init("Atenção !", "Gostaria de sair ?", true);
check.show({callback: executeLogout});
}
/**
* @event executeLogout
* Volta a tela de login.
* @param {Object} parans Resposta da mensagem de logout.
* @param {Boolean} parans.value true para o click no ok, false para o click no cancelar
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
function executeLogout(parans){
if(parans.value){
Alloy.createController("index");
Ti.API.info("logout, tamanhao da pilha: " + Alloy.Globals.pilhaWindow.length);
}
}
/**
* @method resetPilhaWindow
* Fecha todas as janelas abertas da aplicação, menos a janela atual.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.resetPilhaWindow = function(){
while(Alloy.Globals.pilhaWindow.length > 1){
Alloy.Globals.pilhaWindow[0].close();
Alloy.Globals.pilhaWindow[0] = null;
Alloy.Globals.pilhaWindow.splice(0, 1);
}
Ti.API.info("janelas removidas, tamanhao da pilha: " + Alloy.Globals.pilhaWindow.length);
return null;
};
/**
* @property {Object} Servicos Tamanho da barra lateral de serviços.
* @property {Number} Servicos.Largura Largura.
*/
Alloy.Globals.Servicos = {Largura: 250};
/**
* @property {widgets.GUI.ListaServicos} ListaServicos Controller da barra lateral de serviços.
*/
Alloy.Globals.ListaServicos = Alloy.createWidget("GUI", "ListaServicos");
/**
* @event callbackServicos
* Quando um novo serviço é selecionado pela barra lateral de serviços, essa rotina é invocada.
* Como usar: Caso o serviço de nome 'novo' seja criado, deve-se criar um case dentro dessa rotina com o mesmo nome.
* Dentro do case deve-se colocar o código de instancia desse novo serviço.
* @param {String} nome Nome do serviço.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
var callbackServicos = function(nome){
try{
Alloy.Globals.ListaServicos.fechar();
switch(nome) {
case "Sair":
logout();
break;
case "Reimpressão de boleto":
Alloy.Globals.iniciarServicos();
var novo = Alloy.createController("Boletos");
Alloy.createWidget("Util", "Transicao").nova(novo, novo.init, {});
break;
case "Tokens cadastrados":
var janelaToken = Alloy.createWidget("Login", "ListaToken");
Alloy.createWidget("Util", "Transicao").proximo(janelaToken, janelaToken.init, {});
break;
default :
alert("Servico não implementado.");
break;
}
}
catch(e){
Alloy.Globals.onError(e.message, "callbackServicos", "app/alloy.js");
}
};
/**
* @method iniciarServicosLogin
* Inicia a lista de serviços com os serviços do login.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.iniciarServicosLogin = function(){
Alloy.Globals.ListaServicos.configCabecalho(false);
Alloy.Globals.ListaServicos.resetar();
Alloy.Globals.ListaServicos.adicionarServico("/images/servicos/token.png", "Tokens cadastrados", callbackServicos);
};
/**
* @method iniciarServicos
* Inicia a lista de serviços com os serviços globais.
* Qualquer novo serviço no aplicativo deve ser adicionado por essa rotina.
* Exemplo: Queremos adicionar o serviço 'novo', basta vir nesta rotina e invocar a rotina adicionarServico da classe widgets.GUI.ListaServicos passando os devidos parâmetros.
* @returns {null}
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Alloy.Globals.iniciarServicos = function(){
Alloy.Globals.ListaServicos.configCabecalho(true);
Alloy.Globals.ListaServicos.resetar();
Alloy.Globals.ListaServicos.adicionarServico("/images/servicos/reBoleto.png", "Reimpressão de boleto", callbackServicos);
Alloy.Globals.ListaServicos.adicionarServico("/images/logout.png", "Sair", callbackServicos);
};
/**
* @event Network_change
* Disparado ao se clicar no ícone de lista. Caso exista uma janela anterior, esta janela será fechada e a anterior será aberta.
* @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos
* Criação.
*/
Ti.Network.addEventListener("change", function(e){
Alloy.Globals.estaOnline = e.online;
});
|
var HomeController = angular.module("HomeController", []);
HomeController.controller('HomeController',
['$scope', '$location', 'WeatherService', 'StockService', 'AuthService', 'CaveWallAPIService', 'CalendarService',
function ($scope, $location, weatherService, stockService, authService, caveWallAPIService, calendarService) {
//'use strict';
if(authService.getUser() == null) {
$location.path('/login');
}
$scope.events = [];
$scope.eventsLoaded = false;
calendarService.getAllFutureEvents(function (data) {
$scope.events = data;
$scope.eventsLoaded = true;
$scope.$apply();
}, function() {
$scope.eventsLoaded = true;
$scope.$apply();
});
$scope.stocks = [];
$scope.stocksLoaded = false;
caveWallAPIService.makeCall('GET', 'stocks/owned', null, null, function (stocks) {
var stockarr = [];
for (var i in stocks) {
if (stocks[i].NumberOfStocks > 0) {
stockarr.push(stocks[i]);
}
}
$scope.stocks = stockarr;
$scope.stocksLoaded = true;
$scope.$apply();
$('.stock').each(function(index){
var child = $(this).find('.change');
if(child.text().includes('-'))
child.addClass('negative');
else if (child.text().includes('+'))
child.addClass('positive');
});
}, function(data) {
$scope.stocksLoaded = true;
$scope.$apply();
});
$scope.loggedIn = false;
authService.doOnLogin('homeControllerLogin', function (user) {
$scope.loggedIn = true;
$scope.facebookUserID = user.id;
authService.getUserFeed(function (userWall) {
$scope.wall = userWall.data;
});
});
authService.doOnLogout('homeControllerLogout', function () {
$scope.loggedIn = false;
$scope.wall = [];
});
$scope.doPost = function () {
if ($scope.message != "") {
authService.postToWall(function (data) {
$scope.message = "";
setTimeout(function () { $scope.$apply(); }, 1);
authService.getUserFeed(function (userWall) {
$scope.wall = userWall.data;
});
}, $scope.message);
}
}
$scope.zipError = false;
$scope.currentZipCode = weatherService.getCurrentZipCode();
$scope.validateZip = function () {
var isnum = /^\d+$/.test($scope.currentZipCode);
if (!isnum || isNaN(parseInt($scope.currentZipCode, 10)) || $scope.currentZipCode.length != 5) {
return false;
}
return true;
}
$scope.weatherUpdate = function () {
if (!$scope.validateZip()) {
$scope.zipError = true;
} else {
$scope.zipError = false;
weatherService.getWeather($scope.currentZipCode, function (weather) {
$scope.weather = weather;
$scope.$apply();
});
}
};
$scope.saveZip = function () {
weatherService.setUserDefaultZipCode($scope.currentZipCode);
};
$scope.weatherUpdate();
}]);
|
const { config } = require('./config');
const init = require('./loaders');
const express = require('express');
const runServer = async () => {
// app init with express
const app = express();
// loaders
await init(app);
app.listen(config.port, error => {
try {
console.log(`server is listening on port ${config.port}`)
} catch (error) {
console.error(error);
return;
}
});
}
// run
runServer(); |
jQuery(document).ready(function($) {
//Zorgt ervoor dat je op een tablerow naar een link kan gaan.
$(".clickable-row").click(function() {
window.location = $(this).data("href");
});
// filter voor de zoek balk
$("#searchbar").on("keyup", function() {
var value = $(this).val().toLowerCase();
$(".table .sfilter").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
//Delete berichten
function deleteStudent() {
return confirm("Weet je zeker dat je deze student wilt verwijderen?")
}
function deleteCompany() {
return confirm("Weet je zeker dat je dit bedrijf wilt verwijderen?")
}
function deleteExperience() {
return confirm("Weet je zeker dat je deze geschreve ervaring wilt verwijderen?")
} |
const Router = require("express-promise-router");
const router = new Router;
const LoginController = require('../controleur/Login');
/**
* @swagger
* /login/:
* post:
* tags:
* - Login
* summary: "genere un jwt token de 24h pour utiliser l'api"
* requestBody:
* $ref: '#/components/requestBodies/login'
* responses:
* 404:
* $ref: '#/components/responses/loginInconnu'
* 201:
* $ref: '#/components/responses/loginOk'
* 500:
* $ref: '#/components/responses/ErreurServ'
*/
router.post('/', LoginController.login);
module.exports = router; |
import React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
margin-bottom: 42px;
font-size: 1.8rem;
`;
const Knowledge = styled.div`
display: flex;
flex-direction: column;
margin-bottom: calc(42px - 1.45rem);
@media (min-width: ${props => props.theme.screen.md}) {
flex-direction: row;
}
`;
const Skills = styled.section`
h2 {
font-size: 1rem;
}
@media (min-width: ${props => props.theme.screen.md}) {
&:not(:last-of-type) {
margin-right: 120px;
}
}
`;
const ExperienceSection = styled.section`
margin-bottom: 42px;
h2,
h3 {
font-size: 1rem;
}
p {
margin-bottom: 0.75rem;
}
`;
const skills = [
'JavaScript',
'CSS3/LESS/CSS Modules',
'CSS-in-JS',
'HTML5',
'Mobile & Responsive Design',
'React.js/Redux/React Router',
'Next.js',
];
const learning = ['TypeScript', 'GraphQL'];
const experience = [
{
position: 'Front-end Developer, Full-time',
period: 'Июль/2018 - настоящее время',
company: 'ООО «Инстамарт Технолоджис»',
responsibilities: ['Разработка/доработка приложений на React/Redux'],
},
{
position: 'Front-end Developer, Freelance',
period: '2014 год - настоящее время',
responsibilities: [
`Разработка/доработка приложений на React.js (Redux, Thunk, React Router),
работа с Google Firebase`,
'Написание Unit тестов (Jest, Enzyme)',
'Адаптивная верстка (Mobile First CSS, Semantic HTML)',
],
},
];
const peviously = [
{
position: 'System Engineer (Virtualization and Storage Systems), Full-time',
period: 'Август/2012 - Июль/2018',
},
];
const renderSkills = (skill, index) => <li key={index}>{skill}</li>;
const Experience = ({
experience: { position, period, company, responsibilities },
}) => (
<div>
<p>
<b>{position}</b> -<i> {period}</i>
{company && (
<React.Fragment>
<br />
{company}
</React.Fragment>
)}
</p>
{responsibilities && responsibilities.length ? (
<ul>
{responsibilities.map((res, index) => (
<li key={index}>{res}</li>
))}
</ul>
) : null}
</div>
);
const About = () => (
<div>
<Title>Обо мне</Title>
<Knowledge>
<Skills>
<h2>Умения/Знания</h2>
<ul>{skills.map(renderSkills)}</ul>
</Skills>
<Skills>
<h2>Изучаю/Пробую</h2>
<ul>{learning.map(renderSkills)}</ul>
</Skills>
</Knowledge>
<ExperienceSection>
<h2>Опыт</h2>
{experience.map((exp, index) => (
<Experience key={index} experience={exp} />
))}
<hr />
<h3>До этого</h3>
{peviously.map((exp, index) => (
<Experience key={index} experience={exp} />
))}
</ExperienceSection>
</div>
);
export default About;
|
////////////////////////////////////////////////////////////////////////////////
// Component: PostEditorContent.js
// Description: post editor content
// Author: Andrew McNaught
// Date Created: 20/10/2016
// Date Modified: 20/10/2016
////////////////////////////////////////////////////////////////////////////////
import React from "react";
export default
class PostEditorContent extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div className="post-editor-content" >
<div className="post-editor-content-inner" >
<div className="post-editor-title-wrapper">
<input type="text" className="post-editor-title-input" />
</div>
<div className="post-editor-text-wrapper">
<textarea className="post-editor-textarea-input" ></textarea>
</div>
<div className="post-editor-button-wrapper">
<input type="button" className="post-editor-button" value="Post"/>
</div>
</div>
</div>
);
}
} |
const expect = require("chai").expect;
const sinon = require("sinon");
const User = require("../models/User");
const { userLogInController } = require("../controllers/auth");
describe("Auth-controller User login", () => {
it("should throw an error at status code 500", function (done) {
sinon.stub(User, "findOne");
User.findOne.throws();
const req = {
body: {
email: "tester@gmail.com",
password: "tester",
},
};
userLogInController(req, {}, () => {}).then((result) => {
console.log(result);
// expect(result).to.be.an("error");
// expect(result).to.have.property("statusCode", 500);
done();
});
User.findOne.restore();
});
});
|
let mainSection = undefined;
let sectionViewSelector = undefined;
function initialize(mainDomElement, viewSelector) {
mainSection = mainDomElement;
sectionViewSelector = viewSelector;
}
async function changeView(viewPromise) {
let view = await viewPromise;
if (view != undefined) {
mainSection.querySelectorAll(sectionViewSelector).forEach(v => v.remove());
mainSection.appendChild(view);
}
}
let viewChanger = {
initialize,
changeView
}
export default viewChanger;
|
const test = require('tape');
const timeTaken = require('./timeTaken.js');
test('Testing timeTaken', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof timeTaken === 'function', 'timeTaken is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(timeTaken(args..), 'Expected');
//t.equal(timeTaken(args..), 'Expected');
//t.false(timeTaken(args..), 'Expected');
//t.throws(timeTaken(args..), 'Expected');
t.end();
});
|
(function (window, document, classie, $) {
'use strict';
function PopupService(args) {
args = args || {};
this._overlay = args.overlay;
this._openClassName = args.openClassName || 'popup-wrap--open';
this._closeClassName = args.closeClassName || 'popup-wrap--close';
this._openOverlayClassName = args.openOverlayClassName || 'popup-overlay--open';
this._isDashboard = args.isDashboard || false;
// responsive
this._body = $('body');
this._sliderWrap = document.querySelector('.slider-wrap');
this._isResponsive = args.isResponsive || false;
this._leftPopupClass = args.leftPopupClass || 'widget-sm-popup--left';
this._rightPopupClass = args.rightPopupClass || 'widget-sm-popup--right';
this._popupPosition = 'right'; // right position is default
this._thumbnailMenu = 'thumbnail-menu';
}
PopupService.prototype.open = function (element) {
var currentElement,
popupPosition,
self = this,
widgetBox,
isSmall,
isThumbnail,
hasThumbnailMenu = classie.has(element, this._thumbnailMenu);
if (!this._isDashboard) {
currentElement = this.currentElement;
if (currentElement === element) {
// thumbnail repsonsive
if (this._isResponsive && hasThumbnailMenu) {
this.close(currentElement);
}
return;
}
if (currentElement) {
this.close(currentElement);
}
this.currentElement = element;
}
if (!this._isDashboard) {
// add overlay if not thumbnail-menu
!hasThumbnailMenu && classie.add(this._overlay, this._openOverlayClassName);
// small responsive
// add a correct class to widget slider-wrap when responsive widget is small or thumbnail - (temporary)
if (this._isResponsive) {
isSmall = classie.has(this._sliderWrap, 'small');
isThumbnail = classie.has(this._sliderWrap, 'thumbnail') && !classie.has(this._sliderWrap, 'normal');
if (isSmall) {
window.iframeMessageSrv && window.iframeMessageSrv.sendPopupMsg($(element).html()); // fixme
widgetBox = this._sliderWrap;
// console.log($(window).width(), widgetBox.getBoundingClientRect().right);
if ($(window).width() - widgetBox.getBoundingClientRect().right >= 296) { // 296 is a value of popup width with margin
this._body.append(element);
classie.add(element, this._rightPopupClass);
setPopupPosition(element, 'right', widgetBox);
this._popupPosition = 'right';
} else {
this._body.append(element);
classie.add(element, this._leftPopupClass);
setPopupPosition(element, 'left', widgetBox);
this._popupPosition = 'left';
}
$(window).on('resize.smallpopup', function() {
if ($(element).is(':visible')) {
setPopupPosition(element, self._popupPosition, widgetBox);
}
});
} else if (isThumbnail && hasThumbnailMenu) {
widgetBox = document.getElementById('thumbnail-image');
this._body.append(element);
setPopupPosition(element, 'right', widgetBox);
$(window).on('resize', function() {
setPopupPosition(element, 'right', widgetBox);
});
}
}
}
classie.remove(element, this._closeClassName);
classie.add(element, this._openClassName);
$(element).show();
// set left or right popup position on small responsive widget
function setPopupPosition(element, pos, widgetBox) {
var widgetRect = widgetBox.getBoundingClientRect();
$(element).css('top', widgetRect.top);
if (pos === 'right') {
$(element).css('left', widgetRect.right + 20); // 20 is a value of popup margin
} else if (pos === 'left') {
$(element).css('left', function () {
var result = widgetRect.left - 296; // 296 is a value of popup width with margin
if (result < 0) { result = 0; }
return result;
});
}
};
};
PopupService.prototype.close = function (element) {
var videoElement,
hasThumbnailMenu = classie.has(element, this._thumbnailMenu);;
this.currentElement = null;
if (!this._isDashboard) {
classie.remove(this._overlay, this._openOverlayClassName);
// small responsive
if (this._isResponsive && (classie.has(element, this._rightPopupClass) || classie.has(element, this._leftPopupClass))) {
$(window).off('resize.smallpopup');
classie.remove(element, this._rightPopupClass);
classie.remove(element, this._leftPopupClass);
console.log(element);
element.removeAttribute("style"); // clean styles
console.log('remove style from small', element);
$(this._sliderWrap).append(element); //return popup back inside sliderWrap
this._popupPosition = 'right';
}
}
classie.remove(element, this._openClassName);
classie.add(element, this._closeClassName);
videoElement = element.querySelector('video');
if (videoElement && videoElement.currentTime > 0) {
videoElement.pause();
videoElement.currentTime = 0;
}
if (this._isResponsive && hasThumbnailMenu) {
$(element).hide();
}
// the code creates a bug 181 after fast clicking on open/close popup
// window.setTimeout(function () {
// // Hide popup after 0.5 s closing animation to free some memory on mobile browsers.
// $(element).hide();
// }, 500);
};
window.PopupService = PopupService;
})(window, window.document, window.classie, window.jQuery);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.