text stringlengths 7 3.69M |
|---|
export default class Memory {
public text = '';
public tags = [];
public flags = [];
public link = null;
private _flag = false;
private _done = false;
private _forget = false;
public toggleFlag(toggle = !this._flag) {
this._flag = (toggle);
}
public get isFlagged() {
return this._flagged;
}
public get isDone() {
return this._done;
}
public get isForgotten() {
return this._forget;
}
public parseText() {
}
}
export class Attachment {
url = '';
image;
title;
description;
}
|
// include styling
require("../sass/app.sass");
// other parts of the application
require("./legacy");
require("./bootstrap_vanilla");
require("./font_awesome_light");
require("./font_awesome_solid");
// apps
require('./apps/Feedback/bootstrap');
require('./apps/Result/bootstrap'); |
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import io from 'socket.io-client';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router-dom';
import { API_URL } from '../utils/helpers';
import {
addCreatedNamespace,
fetchNamespacesSuccess,
setSearchedNamespaces,
setSearchLoading
} from '../actions/namespaceActions';
import NamespaceTemplate from '../components/templates/NamespaceTemplate/NamespaceTemplate';
import ServerContentPage from './ServerContentPage';
import { setInformationObject, toggleCreateNamespace } from '../actions/toggleActions';
import CreateNamespace from '../components/compound/CreateNamespace/CreateNamespaceWrapper';
import MainSocketContext from '../providers/MainSocketContext';
import HomePage from './HomePage';
import InformationBox from '../components/molecules/InformationBox/InformationBox';
const StyledWrapper = styled.div`
width: 100%;
height: 100vh;
`;
const ServerPage = ({
fetchNamespaces,
token,
addCreatedNamespace,
toggleCreateNamespace,
setSearchedNamespaces,
setSearchLoading,
setInformationObject
}) => {
const [socket, setSocket] = useState(null);
const [isSocketLoading, setSocketLoading] = useState(true);
useEffect(() => {
setSocket(
io(`${API_URL}`, {
query: {
token
}
})
);
setSocketLoading(false);
}, []);
useEffect(() => {
if (socket) {
socket.on('connect', () => {
socket.emit('user_connected', {
socketID: socket.id
});
socket.on('load_namespaces', namespaces => {
fetchNamespaces(namespaces);
if (namespaces.created.length === 0 && namespaces.joined.length === 0) {
toggleCreateNamespace(true);
}
});
socket.on('namespace_created', namespace => {
addCreatedNamespace(namespace);
});
socket.on('namespace_search_finished', namespace => {
setSearchedNamespaces(namespace);
setSearchLoading(false);
});
/* informationObject -> {type: enum['error', 'success'], message: String} */
socket.on('information', informationObject => {
setInformationObject(informationObject);
});
});
}
}, [socket]);
return (
<>
{!isSocketLoading && (
<MainSocketContext.Provider value={{ socket }}>
<StyledWrapper>
<CreateNamespace />
<NamespaceTemplate>
<Switch>
<Route path={'/server/:id'} component={ServerContentPage} />
<Route path={'/home'} component={HomePage} />
</Switch>
</NamespaceTemplate>
<InformationBox />
</StyledWrapper>
</MainSocketContext.Provider>
)}
</>
);
};
const mapStateToProps = ({ authenticationReducer: { token } }) => {
return { token };
};
const mapDispatchToProps = dispatch => {
return {
fetchNamespaces: namespaces => dispatch(fetchNamespacesSuccess(namespaces)),
toggleCreateNamespace: isOpen => dispatch(toggleCreateNamespace(isOpen)),
addCreatedNamespace: namespace => dispatch(addCreatedNamespace(namespace)),
setSearchedNamespaces: namespaces => dispatch(setSearchedNamespaces(namespaces)),
setSearchLoading: isSearching => dispatch(setSearchLoading(isSearching)),
setInformationObject: message => dispatch(setInformationObject(message))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ServerPage);
|
'use strict';
module.exports = function(sequelize, DataTypes) {
var tuto_video = sequelize.define('tuto_video', {
titre: DataTypes.STRING,
titre_manga: DataTypes.STRING,
video: DataTypes.STRING,
description: DataTypes.STRING,
intro: DataTypes.STRING,
nom_perso: DataTypes.STRING,
date_crea: DataTypes.DATE,
langue: DataTypes.STRING,
img_pres: DataTypes.STRING
},{
timestamps: false
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return tuto_video;
}; |
/*components helper*/
/*convert to blob*/
export async function convertBlob(sourceUrl) {
// first get our hands on the local file
const localFile = await fetch(sourceUrl);
// then create a blob out of it (only works with RN 0.54 and above)
const fileBlob = await localFile.blob();
// yay, let's print the result
console.log(`Server said: ${JSON.stringify(fileBlob)}`);
}
export const generateBlob = (base64URL) => {
console.log(base64URL);
fetch(base64URL)
.then((response) => response.blob())
.then((response) => console.log('Your blob is' + response));
};
|
module.exports = 'Taller básico de ropa interior'
|
var mongo = require('mongodb');
var Step = require('step');
var db = new mongo.Db('test', new mongo.Server('localhost', 27017, {auto_reconnect: true}));
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'test' database");
db.collection('user', {safe:true}, function(err, collection) {
if (err) {
console.log("The 'invitation' collection doesn't exist. Creating it with sample data...");
//populateDB();
}
});
}
});
exports.register=function(req, res){
var collectuser = null;
Step(
function getCollection(){
db.collection('user', this);
},
function findData(err, collection){
if (err) throw err;
collectuser = collection;
var doc = collection.findOne({'username' : req.body.uname}, this);
},
function insertData(err,doc, collection){
if (err) throw err;
if(doc)
return null,null;
var invitation={
'username' : req.body.uname,
'password' : req.body.upwd
};
collectuser.insert(invitation, {safe:true}, this)
},
function generateResponse(err, result){
if (err) throw err;
//res.send(invitation);
if(result){
console.log('yes');
res.json({success : 1, "err" : 0});
}
else {
console.log('no');
res.json({success : 1, "err" : 1});
}
});
}
exports.login=function(req, res){
var collectuser = null;
Step(
function getCollection(){
db.collection('user', this);
},
function findData(err, collection){
if (err) throw err;
collectuser = collection;
var doc = collection.findOne({'username' : req.body.uname}, this);
},
function (err,doc, collection){
if (err) throw err;
if(!doc || doc.password != req.body.upwd){
req.session.user = null;
res.json({success : 1, "err" : 1})
}
else {
req.session.user = doc;
res.json({success : 1, "err" : 0})
global.socketio.emit('sysmsg', {msgType: 1, username: doc.username});
}
});
}
//socket-normal db control
exports.getUserInfo=function(userId, callback){
Step(
function getCollection(){
db.collection('user', this);
},
function findData(err, collection){
if(err) throw err;
collection.findOne({'username' : userId}, this);
},
function (err, doc){
if (err) throw err;
if(doc) {
doc["headicon"] = 'head2.jpg';
callback(doc);
}
else {
console.log("getUserInfo: Not find the user info, ID: " + userId);
callback(doc);
}
}
)
}
exports.getUserInfoList=function(userIdList, callback){
var infoList = [];
for(var i = 0; i < userIdList.length; i++){
infoList.push({"user_id": userIdList[i], "nickname": userIdList[i], "headicon" : "head2.jpg"});
}
callback(infoList);
}
exports.sharedDB=db;
//啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦
|
/* -----------------------------------------
HEADER - /source/js/cagov/header.js
----------------------------------------- */
//------------------------------------------------------------- v5 ----------------------------------------- * need to consolidate .header-single-banner with header-large-banner,
$(document).ready(function () {
var $headerImage = $('.header-single-banner, .header-large-banner, .header-primary-banner');
var $headerLarge = $('.header-large-banner');
var $primaryBanner = $('.header-primary-banner');
var windowHeight = $(window).height();
var $header = $('header');
var $askGroup = $('.ask-group');
var $headSearch = $('#head-search');
// Beta 5 Changes please incorporate into source files
setTimeout(function(){
$askGroup.addClass('in')
$headSearch.addClass('in')
}, 150)
// setting up global variables for header functions
window.headerVars = {
MOBILEWIDTH: 767,
MAXHEIGHT: 1200,
MINHEIGHT: 500,
setHeaderImageHeight: function () {
if ($headerImage.length == 0) {
return
}
var height = windowHeight;
height = Math.max(Math.min(height, headerVars.MAXHEIGHT), headerVars.MINHEIGHT);
var headerTop = $headerImage.offset().top;
$headerImage.css({'height': height - $header.height()});
headerImageHeight = $headerImage.height();
$headerLarge.css({'height': height - headerTop});
headerImageHeight = $headerLarge.height();
$primaryBanner.css({'height': 450 });
// Beta v5 Changes please incorporate into source files
}
};
headerVars.setHeaderImageHeight();
// Take header image and place it on the ask group div for mobile
var bgImage = $headerImage.css('background-image');
var askGroup = $('.ask-group');
askGroup.attr("style", "background-size: cover; background-repeat: no-repeat; background-image:" + bgImage)
});
|
const db_constants = require('../../helpers/db_constants.helper').agentSignup
const AgentDb = require('../../db/agent.db')
const ResponseHelper = require('../../helpers/response.helper')
const stringConstants = require('../../helpers/strings.helpers')
const smsHelper = require('../../helpers/sms/sms_helper.helper')
module.exports = {
signUp: function(req, res, next) {
const params = req.body
// error checking if all parameters have been passed
if(params[db_constants.name] && params[db_constants.phone]){
const agentData = {}
agentData[db_constants.name] = params[db_constants.name]
agentData[db_constants.phone] = params[db_constants.phone]
AgentDb.create(agentData, async function(err, agent){
if(err){
return res.send(ResponseHelper.errorResponse(err))
}else{
try{
const smsResult = await smsHelper.sendSms(agent, 'Account created')
//result of the sms sent
console.log(smsResult)
return res.send(ResponseHelper.successResponse(stringConstants.agent.createAgent.saveSuccess))
}catch(e){
//log the error since the account has been created but the sms wasn't sent, this will be taken care of by the team.
}
}
})
}else{
return res.send(ResponseHelper.errorResponse(stringConstants.generic.paramterError))
}
}
}
|
var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) {
return typeof t;
} : function(t) {
return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t;
};
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/index/_components/_scroll_tabs" ], {
1881: function(t, n, e) {
e.r(n);
var o = e("d0bc"), r = e.n(o);
for (var c in o) [ "default" ].indexOf(c) < 0 && function(t) {
e.d(n, t, function() {
return o[t];
});
}(c);
n.default = r.a;
},
"28c3": function(t, n, e) {
var o = e("afb5");
e.n(o).a;
},
"71c4": function(t, n, e) {
e.d(n, "b", function() {
return o;
}), e.d(n, "c", function() {
return r;
}), e.d(n, "a", function() {});
var o = function() {
var t = this;
t.$createElement;
t._self._c;
}, r = [];
},
a391: function(t, n, e) {
e.r(n);
var o = e("71c4"), r = e("1881");
for (var c in r) [ "default" ].indexOf(c) < 0 && function(t) {
e.d(n, t, function() {
return r[t];
});
}(c);
e("28c3");
var a = e("f0c5"), i = Object(a.a)(r.default, o.b, o.c, !1, null, "aed3b6e8", null, !1, o.a, void 0);
n.default = i.exports;
},
afb5: function(t, n, e) {},
d0bc: function(n, e, o) {
function r(n) {
return (r = "function" == typeof Symbol && "symbol" === t(Symbol.iterator) ? function(n) {
return void 0 === n ? "undefined" : t(n);
} : function(n) {
return n && "function" == typeof Symbol && n.constructor === Symbol && n !== Symbol.prototype ? "symbol" : void 0 === n ? "undefined" : t(n);
})(n);
}
function c() {
if ("function" != typeof WeakMap) return null;
var t = new WeakMap();
return c = function() {
return t;
}, t;
}
Object.defineProperty(e, "__esModule", {
value: !0
}), e.default = void 0;
var a = function(t) {
if (t && t.__esModule) return t;
if (null === t || "object" !== r(t) && "function" != typeof t) return {
default: t
};
var n = c();
if (n && n.has(t)) return n.get(t);
var e = {}, o = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var a in t) if (Object.prototype.hasOwnProperty.call(t, a)) {
var i = o ? Object.getOwnPropertyDescriptor(t, a) : null;
i && (i.get || i.set) ? Object.defineProperty(e, a, i) : e[a] = t[a];
}
return e.default = t, n && n.set(t, e), e;
}(o("9554")), i = wx.getSystemInfoSync().windowWidth / 750, l = 40 * i, u = 750 * i, f = {
data: function() {
return {
marginLeft: 0,
slide_bar_width: 0
};
},
watch: {
scroll_tabs: {
handler: function() {
var t = this;
this.$nextTick(function() {
var n = t.$mp.component.createSelectorQuery();
n.select("#scroll").fields({
size: !0,
scrollOffset: !0
}), n.exec(function(n) {
n.length && (t.slide_bar_width = u / n[0].scrollWidth * l);
});
});
},
immediate: !0
}
},
props: {
scroll_tabs: Array,
scroll_tabs_bg_width: String,
scroll_tabs_bg: String,
scroll_tabs_bg_height: String
},
methods: {
scroll: function(t) {
var n = t.detail, e = n.scrollLeft / n.scrollWidth * l, o = l - this.slide_bar_width;
this.marginLeft = e < 0 ? 0 : e > o ? o : e;
},
goTab: function(t) {
var n = t.currentTarget.dataset, e = n.url, o = n.name;
this.$sendCtmEvtLog("首页金刚区-".concat(o)), (0, a.askAuthNavigator)(t, e);
}
}
};
e.default = f;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/index/_components/_scroll_tabs-create-component", {
"pages/index/_components/_scroll_tabs-create-component": function(t, n, e) {
e("543d").createComponent(e("a391"));
}
}, [ [ "pages/index/_components/_scroll_tabs-create-component" ] ] ]); |
// @flow
import {Dimensions} from 'react-native';
export default function getScreenSize() {
let {height, width} = Dimensions.get('window');
return {height, width};
}
|
import { combineReducers } from 'redux';
import visibilityFilter from './visibilityFilter'
import todo from './todo'
export default combineReducers({todo, visibilityFilter}) |
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const RestauranteSchema = Schema({
codigo: String,
nombre: String,
especialidad: String,
direccion: String,
telefono: String
});
module.exports = mongoose.model("restaurantes", RestauranteSchema); |
const ModelName = {
User: "user",
Team: "team",
Game: "game",
PlayerResult: "playerResult",
Request: "request",
};
module.exports = { ModelName };
|
var macth_mark_point = localStorage.getItem("macth_mark_point"); // console.log(macth_mark_point);
macth_mark_point = JSON.parse(macth_mark_point);
var userInfo = localStorage.getItem("userInfo");
userInfo = JSON.parse(userInfo);
var hiddenMap=null,map=null,ws=null,pop_mark_check=null;
var checkLon=null,checkLat=null;
var infoBox=null,marker=null;
var oldPointName=null;
mui.init({
swipeBack:false
});
function plusReady(){
if(ws){
return;
}
ws = plus.webview.currentWebview();
hiddenMap=new plus.maps.Map("hiddenMap");
hiddenMap.getUserLocation(function(state,pos){
if(0==state){
checkLon = pos.longitude;
checkLat = pos.latitude;
// console.log(checkLon);console.log(checkLat);
}
});
map = new BMap.Map("map");
var poi = new BMap.Point(macth_mark_point.OffSetLon,macth_mark_point.OffSetLat);
if(macth_mark_point.State == 3){ //黄色
marker = new BMap.Marker(poi,{icon:new BMap.Icon("../img/images/point_07.png",new BMap.Size(24,28))});
}else if(macth_mark_point.State == 1){ //红色
marker = new BMap.Marker(poi,{icon:new BMap.Icon("../img/images/point_03.png",new BMap.Size(24,28))});
}else{ //绿色
marker = new BMap.Marker(poi,{icon:new BMap.Icon("../img/images/point_05.png",new BMap.Size(24,28))});
}
map.centerAndZoom(poi, 16);
map.addOverlay(marker);
makeInfo(macth_mark_point);
infoBox.open(marker);
if(macth_mark_point.State == 3){
mui('#pointImg')[0].style.display = 'inline-block';
}
setTimeout(function(){
mui('.navSty')[0].addEventListener('touchend',openSysMap);
},200)
}
if(window.plus){
plusReady();
}else{
document.addEventListener("plusready",plusReady,false);
}
var re_t = false;
function request_timeout(){
re_t = true;
setTimeout(function(){
re_t = false;
},1000);
}
function check_mark_pp(ii){
if(re_t){return};
request_timeout();
// console.log(WebApi + '/api/MarkPoint/CheckMarkPointByID?userID='+userInfo.Data.UserID+'&lon='+macth_mark_point.OffSetLon+'&lat='+macth_mark_point.OffSetLat+'&checkLon='+checkLon+'&checkLat='+checkLat+'&state='+ii+'&pointID='+macth_mark_point.PointID+'&key='+appLoginKey);
if(checkLon&&checkLat){
mui.ajax(WebApi + '/api/MarkPoint/CheckMarkPointByID?userID='+userInfo.Data.UserID+'&lon='+macth_mark_point.OffSetLon+'&lat='+macth_mark_point.OffSetLat+'&checkLon='+checkLon+'&checkLat='+checkLat+'&state='+ii+'&pointID='+macth_mark_point.PointID+'&key='+appLoginKey,{
headers:{'Content-Type':'application/json'},
dataType:"json",
type:"POST",
success:function(data,textStatus,xhr){
// console.log(JSON.stringify(data));
if(data.State == 1){
// console.log('a');
mui.toast('操作成功');
setTimeout(function(){
mui.fire(plus.webview.currentWebview().opener(),'refreshData',{});
mui.back();
},1000);
}else{
// console.log('b')
show_pop_view();
}
},
error:function(xhr,type,errorThrown){
console.log(type);
}
});
}else{
map.getUserLocation(function(state,pos){
if(0==state){
mui.ajax(WebApi + '/api/MarkPoint/CheckMarkPointByID?userID='+userInfo.Data.UserID+'&lon='+macth_mark_point.OffSetLon+'&lat='+macth_mark_point.OffSetLat+'&checkLon='+pos.longitude+'&checkLat='+pos.latitude+'&state='+state+'&pointID='+macth_mark_point.PointID+'&key='+appLoginKey,{
headers:{'Content-Type':'application/json'},
dataType:"json",
type:"POST",
success:function(data,textStatus,xhr){
if(data.State == 1){
mui.toast('操作成功');
setTimeout(function(){
mui.fire(plus.webview.currentWebview().opener(),'refreshData',{});
mui.back();
},1000);
}else{
show_pop_view();
}
},
error:function(xhr,type,errorThrown){
console.log(type);
}
});
}else{
mui.alert("获取定位失败,请重试!");
}
});
}
}
//自定义信息窗口
function makeInfo(obj){
oldPointName = obj.PointName;
var html = '<div class="infoBoxContent">'
+ '<ul>'
+ '<li class="firstLine"><span>标点信息</span><a class="navSty">导航</a></li>'
+ '<li><span>编号:</span><span> '+ obj.PointID +'</span></li>'
+ '<li><span>名称:</span><span id="pointName"> '+ obj.PointName +'</span><img id="pointImg" ontouchend="changeText()" src="../img/images/check_03.png"></li>'
+ '<li><span>状态:</span><span> '+ obj.StateStr +'</span></li>'
+ '<li><span>地址:</span><span> '+ obj.myAdress +'</span></li>'
+ '</ul>';
if(obj.State == 3){
mui('.mui-title')[0].innerText = '标注点审核';
html += '<hr>'
+ '<p class="p1">确认标注点状态</p>'
+ '<p class="p2"><button class="btn" ontouchend="check_mark_pp(1)" alt="1">关注点</button><button class="btn" ontouchend="check_mark_pp(2)" alt="2">正常点</button></p>'
+ '<div id="whiteAngle"></div>'
+ '</div>';
}else{
mui('.mui-title')[0].innerText = '标注点查看';
html += '<div id="whiteAngle"></div>'
+ '</div>';
}
infoBox = new BMapLib.InfoBox(map,html,{
boxStyle:{
background:"transparent",
width: "260px",
borderRadius: '8px'
},
closeIconUrl: ''
,closeIconMargin: "5px"
,enableAutoPan: true
,align: INFOBOX_AT_TOP
});
}
function changeText() {
mui.prompt('','此处输入','修改标注的名称',['确定','取消'],function(val){
// console.log(JSON.stringify(val));
if(val.index == 0){
console.log(WebApi + '/api/MarkPoint/UpdateMarkPointNameByID?userID='+userInfo.Data.UserID+'&PointName='+ val.value +'&pointID='+macth_mark_point.PointID+'&key='+appLoginKey);
mui.ajax(WebApi + '/api/MarkPoint/UpdateMarkPointNameByID?userID='+userInfo.Data.UserID+'&pointID='+macth_mark_point.PointID+'&PointName='+ val.value +'&key='+appLoginKey,{
headers:{'Content-Type':'application/json'},
dataType:"json",
type:"POST",
success:function(data,textStatus,xhr){
if(data.State == 1){
mui('#pointName')[0].innerText = val.value;
mui.fire(plus.webview.currentWebview().opener(),'refreshData',{});
mui.toast('修改成功');
}else{
mui.toast('修改失败');
}
},
error:function(xhr,type,errorThrown){
console.log(type);
mui.toast('网络异常');
}
});
}
},'div');
}
function show_pop_view(){
pop_mark_check = plus.webview.create('pop_mark_check.html','sub',{height:'100%',width:'100%',background:'transparent',position:'absolute',left:'0',top:'0'});
ws.append(pop_mark_check);
}
function hide_pop_view(){
if(!pop_mark_check)return;
ws.remove(pop_mark_check);
pop_mark_check.close();
pop_mark_check = null;
}
function addBottomView(){
var pop_info = plus.webview.create('pop_info.html','sub',{height:'205px',width:'68%',background:'transparent',position:'absolute',left:'16%',bottom:'50%'});
ws.append(pop_info);
}
//调用第三方导航
function openSysMap(){
console.log(111);
var aimTitle = macth_mark_point.PointName;
var url=null,id=null,f=null;
switch ( plus.os.name ) {
case "Android":
// 规范参考官方网站:http://developer.baidu.com/map/index.php?title=uri/api/android
url = "baidumap://map/marker?location="+macth_mark_point.OffSetLat+","+macth_mark_point.OffSetLon+"&title="+aimTitle+"&content="+macth_mark_point.myAdress+"&src=佳裕车联";
f = androidMarket;
id = "com.baidu.BaiduMap";
break;
case "iOS":
// 规范参考官方网站:http://developer.baidu.com/map/index.php?title=uri/api/ios
url = "baidumap://map/marker?location="+macth_mark_point.OffSetLat+","+macth_mark_point.OffSetLon+"&title="+aimTitle+"&content="+macth_mark_point.myAdress+"&src=佳裕车联";
f = iosAppstore;
id = "itunes.apple.com/cn/app/bai-du-de-tu-yu-yin-dao-hang/id452186370?mt=8";
break;
default:
return;
break;
}
url = encodeURI(url);
plus.runtime.openURL( url, function(e) {
plus.nativeUI.confirm( "检查到您未安装\"百度地图\",是否到商城搜索下载?", function(i){
if ( i.index == 0 ) {
f(id);
}
} );
} );
}
function androidMarket( pname ) {
plus.runtime.openURL( "market://details?id="+pname );
}
function iosAppstore( url ) {
plus.runtime.openURL( "itms-apps://"+url );
} |
import Todo from "./Todo";
import Schedule from "./Schedule";
import SiteTop from "./SiteTop";
import Login from "./Login";
import Categories from "./Categories";
import React, {useState, useEffect, useRef} from 'react';
import { Switch, Route } from 'react-router-dom';
import '../components/App.css';
const SLOTS_PER_DAY = 24*2
const HALF_HOUR = 30
const App = () => {
const [tasks, setTasks] = useState([]) // Dictionary of all user tasks, received from DB.
const [tasksID, setTaskID] = useState([]) // List of all tasks ids, needed to put in schedule.
const [categoryTrigger, setCategoryTrigger] = useState(false) // A flag for category change(add/mod/rem).
const [categoryTable, setCategoryTable] = useState([]) // A list of all categories for each table cell.
const [categories, setCategories] = useState([]); // A list of all user's categories (types).
const [rememberMe, setRememberMe] = useState(); // A state for remember me checkbox.
const [pastDue, setPastDue] = useState({})
const [option, setOption] = useState(0) // A chosen color to paint slots (resembles a category).
// A state for weekdays. changes according to screen size.
const [days, setDays] = useState(['Time', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
const [todoMinimized, setTodoMinimized] = useState(false); // State for size of to do list.
const [todoIsLoaded, setTodoIsLoaded] = useState(false); // State for loaded status of to do list.
const [updated_tasks, setUpdatedTasks] = useState({}) // Dictionary of all updated tasks (add/mod/rem).
const updatedRef = useRef(); // Gives updated value of updated tasks.
updatedRef.current = updated_tasks;
const optionRef = useRef(); // Gives updated value of chosen category option.
optionRef.current = option;
const taskRef = useRef(); // Gives updated tasks.
taskRef.current = tasks;
const [scheduleTrigger, setScheduleTrigger] = useState(false) // State for change in schedule (dragging).
const [table1, setTable] = useState([]) //TODO remove
const [scheduleTable, setScheduleTable] = useState([]) // A list of all table elements.
const schedRef = useRef() // Gives updated schedule elements.
schedRef.current = scheduleTable;
const [week, setWeek] = useState(false);
// A list with all category types.
const [categoryTypes, setCategoryTypes] = useState(Array(SLOTS_PER_DAY*7).fill(-1))
const timeRef = useRef(); // Gives updated category types elements.
timeRef.current = categoryTypes;
// A state of all schedule jsx elements (how they appear on screen).
const [scheduleJsx, setScheduleJsx] = useState([])
const [userID, setUserID] = useState() // State of user id (info).
const [categoryChanged, setCategoryChanged] = useState(false); // State for changing categories.
// State for this moment (this week=this moment, next week=sunday, 00:00).
const [scheduleMoment, setScheduleMoment] = useState();
// On main page load, get userID and "remember me" from local storage.
useEffect(() => {
window.addEventListener('click', detectOutsideClicking)
setUserID(localStorage.getItem('userID'))
setRememberMe(localStorage.getItem('rememberMe'))
let date = new Date();
let slot = timeToSlot(date.getDay(), null, date.getHours(), date.getMinutes())
setScheduleMoment(slot);
// In case the element does not contain any text (login phase for exapmle).
if (document.getElementById('schedule_for_next_week_text') === null) return null;
// update relevant time according to local storage.
if (localStorage.getItem('nextWeek') === null || localStorage.getItem('nextWeek').includes('f')) {
let slot = timeToSlot(date.getDay(), null, date.getHours(), date.getMinutes())
setScheduleMoment(slot);
localStorage.setItem('nextWeek', 'f_'+slot)
document.getElementById('schedule_for_next_week_text').innerText = 'This Week'
}
else {
setScheduleMoment(0);
localStorage.setItem('nextWeek', 't_'+slot)
document.getElementById('schedule_for_next_week_text').innerText = 'Next Week'
}
}, [])
// Hides a pinned popup.
const checkClick = (e,i) => {
let current_pinned = document.getElementById('pinned_calendar'+i)
let time = document.getElementById('pinned_choose_time'+i)
if (current_pinned !== null && time!== null && e.target.id !== 'pinned_choose_day'+i && e.target.id !== 'pinned_choose_time'+i && e.target.id !== 'thumbtack'+i ) {
current_pinned.style.visibility = 'hidden'
current_pinned.style.opacity = '0'
}
}
//Detection of clicking outside an element.
const detectOutsideClicking = (e) => {
let i;
// Checking in loaded tasks
for (i of Object.keys(taskRef.current)) {
checkClick(e,i)
}
// Checking in new added tasks.
for (i of Object.keys(updatedRef.current)) {
checkClick(e,i)
}
}
// Task getter function.
const taskGetter = () => {
fetchTasks('gettasks', userID)
}
// Calling trig API, with current day as beginning slot parameter.
const taskIDTrig = () => {
trigTasks(scheduleMoment)
return tasksID
}
// Getter function for receiving schedule.
const taskIDGetter = () => {
if (tasksID.length === 0) {
fetchTaskID('GetSchedule', userID)
}
return tasksID
}
//Graying out an element (css design wise)
const grayIt = (elm) => {
elm.style.pointerEvents = 'none';
elm.style.opacity = '0.3';
}
//Graying out an element (css design wise)
const ungrayIt = (elm) => {
elm.style.pointerEvents = '';
elm.style.opacity = '1';
}
// Graying out elements, depending on place clicked.
const grayOutElements = (edit_cat=false) => {
// If on edit category pane.
if (edit_cat) {
grayIt(document.getElementById('schedule_parent'));
grayIt(document.getElementById('category_send_button'));
grayIt(document.getElementById('category_button'));
grayIt(document.getElementById('add_category_button'));
grayIt(document.getElementById('clear_category_button'));
grayIt(document.getElementById('added_button_0'));
grayIt(document.getElementById('added_button_1'));
grayIt(document.getElementById('added_button_2'));
grayIt(document.getElementById('added_button_3'));
grayIt(document.getElementById('added_button_4'));
grayIt(document.getElementById('added_button_5'));
}
grayIt(document.getElementById('schedule_for_next_week'));
grayIt(document.getElementById('schedule_for_next_week_text'));
grayIt(document.getElementById('site_logo'));
grayIt(document.getElementById('todo_parent'));
}
// Graying out elements, depending on place clicked.
const ungrayOutElements = (icons=false) => {
// Ungraying rest of grayed out areas (exiting category editing mode).
if (icons) {
ungrayIt(document.getElementById('schedule_for_next_week'));
ungrayIt(document.getElementById('schedule_for_next_week_text'));
ungrayIt(document.getElementById('site_logo'));
ungrayIt(document.getElementById('todo_parent'));
}
ungrayIt(document.getElementById('schedule_parent'));
ungrayIt(document.getElementById('add_category_button'));
ungrayIt(document.getElementById('clear_category_button'));
ungrayIt(document.getElementById('category_send_button'));
ungrayIt(document.getElementById('category_button'));
ungrayIt(document.getElementById('added_button_0'));
ungrayIt(document.getElementById('added_button_1'));
ungrayIt(document.getElementById('added_button_2'));
ungrayIt(document.getElementById('added_button_3'));
ungrayIt(document.getElementById('added_button_4'));
ungrayIt(document.getElementById('added_button_5'));
ungrayIt(document.getElementById('add_category_button'));
}
//Converting time to a slot number.
const timeToSlot = (day, time, hours=null, minutes=null) => {
if (hours == null) {
hours = parseInt(time.substr(0, 2));
minutes = parseInt(time.substr(3, 2));
}
// Round minutes down.
if (minutes <= HALF_HOUR && minutes > 0)
minutes = 1
// Round hour up and minutes down (in case minutes > 30).
else if (minutes !== 0) {
hours += 1
minutes = 0
}
return day*48 + hours*2+minutes
}
// Fetching task list of a specific user.
const fetchTasks = (type, userID) => {
fetch("http://localhost:5000/tasks/"+type+"/"+userID)
.then(res => res.json())
.then(
(result) => {
if (result['statusCode'] === 500) throw new Error('Internal server error.');
let temp_tasks = {}
for (let i=0; i<result['tasks'].length; i++){
temp_tasks[result['tasks'][i]['task_id']] = result['tasks'][i]
}
if (Object.keys(temp_tasks).length === 0) {
setTodoIsLoaded(true)
}
setTasks(temp_tasks);
})
.catch((error) => {
console.error('error in get task: ', error)
});
}
// Fetching task id list of a specified user.
const fetchTaskID = (type, userID) => {
fetch("http://localhost:5000/tasks/"+type+"/"+userID)
.then(res => res.json())
.then(
(result) => {
if (result['statusCode'] === 500) throw new Error('Internal server error.');
setTaskID(result)
})
.catch((error) => {
console.error('error in fetch tasks id: ', error)
});
}
// An animation or error in schedule generation.
const showErrorMessage = () => {
let popup = document.getElementById('error_popup')
popup.innerText = 'Could not generate schedule';
popup.animate(errorAnimation[0], errorAnimation[1])
setTimeout(function() {
popup.animate(endErrorAnimation[0], endErrorAnimation[1])
}, 3000)
}
// Remove red marking on all elements and tasks.
const unmarkTasksWithErrors = () => {
for (let id in taskRef.current) {
let recurrences = document.getElementById('recurrings' + id);
let constraints = document.getElementById('constraints' + id);
let categories = document.getElementById('category_id' + id);
let task = document.getElementById('task' + id);
recurrences.classList.remove('thumbtack_error');
constraints.classList.remove('task_error');
categories.classList.remove('task_error');
task.classList.replace('closed_task_error', 'closed_task');
task.classList.replace('expanded_task_daytime_error', 'expanded_task_daytime');
task.classList.replace('expanded_task_error', 'expanded_task');
}
}
// Marking errors in specific properties of specific tasks.
const markTasksWithErrors = (err_tasks) => {
let i;
for (i=0; i<err_tasks.length; i++) {
let task = document.getElementById('task' + err_tasks[i][0]);
// Showing error of a specific task.
task.classList.replace('closed_task', 'closed_task_error');
task.classList.replace('expanded_task', 'expanded_task_error');
task.classList.replace('expanded_task_daytime', 'expanded_task_daytime_error');
let recurrences = document.getElementById('recurrings' + err_tasks[i][0]);
let constraints = document.getElementById('constraints' + err_tasks[i][0]);
let categories = document.getElementById('category_id' + err_tasks[i][0]);
// Showing error in pinning task.
if (err_tasks[i][1] === 1)
recurrences.classList.add('thumbtack_error');
// Showing error in constraints.
if (err_tasks[i][2] === 1)
constraints.classList.add('task_error');
// Showing error in category.
if (err_tasks[i][3] === 1)
categories.classList.add('task_error');
}
}
// Trig API. Receiving calculated schedule.
const trigTasks = (slot) => {
fetch("http://localhost:5000/tasks/trig/"+userID+"/"+slot)
.then(res => res.json())
.then(
(result) => {
if (result['statusCode'] === 500) throw new Error('Internal server error.');
// If it was not possible to generate schedule.
if (result[0] === null) {
console.error('Error in trig: ', result)
showErrorMessage();
markTasksWithErrors(result[1]);
return;
} else {
unmarkTasksWithErrors();
}
setTaskID(result[0])
})
.catch((error) => {
console.error('error in trig: ', error);
});
}
// Task error message animations.
const errorAnimation = [[
{ 'opacity': 0, transform: 'translateY(50px)', zIndex:'0'},
{ 'opacity': 1, transform: 'translateY(-20px)', visibility:'visible', zIndex:'1000100'}
], {duration: 500, fill: 'forwards', easing: 'ease-out'}];
const endErrorAnimation = [[
{ 'opacity': 1, transform: 'translateY(-20px))', zIndex:'1000100'},
{ 'opacity': 0, transform: 'translateY(50px)', visibility:'hidden', zIndex:'0'}
], { duration: 500, fill: 'forwards', easing: 'ease-in'}];
// Actions taken when submitting categories changes.
const handleCategoriesSubmission = () => {
// Removing deleted categories from DB.
removeCategories()
setScheduleJsx(initialSchedule())
setScheduleTrigger(!scheduleTrigger)
}
// Removing category from DB.
const removeCategories = () => {
fetch('http://localhost:5000/tasks/DeleteUserCategories/'+userID, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => {
if (response.status === 200) {
PostCategorySlots()
}
})
.catch((error) => {
console.error("Error while submitting task: " + error.message);
});
}
// Post updated categories.
const PostCategorySlots = () => {
fetch('http://localhost:5000/tasks/PostCategorySlots/'+userID, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(categoryTypes)
})
.then((response) => {
if (response.status === 201) {
console.log("User's tasks hes been sent successfully.");
} else {
console.error("User's tasks hes been sent. HTTP request status code: " + response.status);
}
})
.catch((error) => {
console.error("Error while submitting task: " + error.message);
});
}
// Closing task pane (minimizing).
const closeTaskPane = () => {
let todo_element = document.getElementById('todo_parent')
let schedule_element = document.getElementById('schedule_parent')
let show_hide_todo = document.getElementById('show_hide_todo')
if (!todoMinimized) {
setTodoMinimized(true)
todo_element.className = 'gone'
schedule_element.className = 'col-12_2 col schedule_parent_expanded'
show_hide_todo.className = 'show_hide_todo_reverse'
} else {
setTodoMinimized(false)
todo_element.className = 'col-4'
schedule_element.className = 'col-8'
show_hide_todo.className = 'show_hide_todo'
}
}
// Creating initial table jsx of time in schedule.
const initialSchedule = () => {
let jsx = []
let hour;
let minute = 0;
let content = []
// creating value for each time of day and updating in the relevant slot.
for (let j = 0; j < SLOTS_PER_DAY; j++) {
hour = Math.floor(j / 2);
minute = HALF_HOUR * (j % 2);
if (hour < 10) hour = '0' + hour
if (minute === 0) minute = '00'
content.push(<td className='td1' key={'time' + hour + ':' + minute}>{hour}:{minute}</td>);
}
jsx.push(<tr className='tr1' key={'tr' + 0}><div className={'th_parent'}><th className='th1' key={'th' + 0}>Time</th></div>{content}</tr>);
return jsx
}
// Iterate slots and track all past due tasks.
const updatePastDueTasks = () => {
let todays_slot = scheduleMoment
let i = 0;
while (i < todays_slot) {
if (tasksID[i] !== -1) {
let past_due_task_id = tasksID[i]
setPastDue(data=>({...data,[past_due_task_id]:1}))
}
i += 1
}
}
// Fix representation, according to screen size.
const fixPresentation = (mobile) => {
let sched = document.getElementById('schedule_parent')
let todo = document.getElementById('todo_component')
if (!sched || !todo) return
// Suited for mobile.
if (mobile.matches){
sched.className = 'collapsed_row2'
todo.className = 'sticky-top row tst2'
setDays(['Time', 'Su.', 'Mo.', 'Tu.', 'We.', 'Th.', 'Fr.', 'Sa.'])
} else {
sched.className = 'col col-8_start'
todo.className = 'sticky-top row'
setDays(['Time', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
}
}
// Dynamically resizing screen.
const resizeResponse = () => {
let mobile = window.matchMedia('(max-width: 800px)')
fixPresentation(mobile)
mobile.addEventListener('load',fixPresentation)
}
// Main website page.
const mainPage = () => {
window.onresize = resizeResponse;
return (
<div className="App d-flex flex-column">
<SiteTop ungrayOutElements={ungrayOutElements} grayOutElements={grayOutElements} setWeek={setWeek} week={week} setScheduleJsx={setScheduleJsx} scheduleJsx={scheduleJsx} timeRef={timeRef} setScheduleMoment={setScheduleMoment} timeToSlot={timeToSlot} setCategoryChanged={setCategoryChanged} categories={categories} setCategories={setCategories} optionRef={optionRef} setCategoryTypes={setCategoryTypes} categoryTypes={categoryTypes} userID={userID} setUserID={setUserID} categoryTrigger={categoryTrigger} setCategoryTrigger={setCategoryTrigger} handleCategoriesSubmission={handleCategoriesSubmission} setOption={setOption}/>
<div id='site_body' className='row flex-grow-1'>
{/*<div id='show_hide_todo' className='show_hide_todo' onClick={closeTaskPane}/>*/}
<div id='todo_parent' className='col-4'>
<div id='todo_component' className='sticky-top row'>
<div className='tst col-12'>
<Todo updatePastDueTasks={updatePastDueTasks} pastDue={pastDue} setPastDue={setPastDue} week={week} setWeek={setWeek} setCategoryChanged={setCategoryChanged} scheduleMoment={scheduleMoment} categoryChanged={categoryChanged} categories={categories} setUpdatedTasks={setUpdatedTasks} updated_tasks={updated_tasks} tasksID={tasksID} timeToSlot={timeToSlot} userID={userID} isLoaded={todoIsLoaded} setIsLoaded={setTodoIsLoaded} errorAnimation={errorAnimation} endErrorAnimation={endErrorAnimation} categoryTrigger={categoryTrigger} setCategoryTrigger={setCategoryTrigger} handleCategoriesSubmission={handleCategoriesSubmission} updating_tasks={tasks} trigTasks={taskIDTrig} getTasks={taskGetter} setTasks={setTasks}/>
</div>
</div>
</div>
<div id='schedule_parent' className='col col-8_start'>
<div id='schedule_component'>
<Schedule updatePastDueTasks={updatePastDueTasks} pastDue={pastDue} setPastDue={setPastDue} scheduleMoment={scheduleMoment} days={days} setDays={setDays} categories={categories} setCategories={setCategories} timeToSlot={timeToSlot} userID={userID} categoryTrigger={categoryTrigger} setCategoryTypes={setCategoryTypes} categoryTypes={categoryTypes} schedRef={schedRef} scheduleTable={scheduleTable} setScheduleTable={setScheduleTable} setScheduleJsx={setScheduleJsx} scheduleJsx={scheduleJsx} initialSchedule={initialSchedule} table1={table1} setTable={setTable} getCategoryTable={categoryTable} setCategoryTable={setCategoryTable} tasksID={tasksID} getTasksID={taskIDGetter} trigTasksID={taskIDTrig} updating_tasks={tasks} getTasks={taskGetter} setTasks={setTasks}/>
{/*<Categories userID={userID} setCategoryTrigger={setCategoryTrigger} categoryTrigger={categoryTrigger} setScheduleTrigger={setScheduleTrigger} scheduleTrigger={scheduleTrigger} table1={table1} categoryTable={categoryTable} setTable={setTable} optionRef={optionRef} setCategoryTable={setCategoryTable} setCategoryTypes={setCategoryTypes} categoryTypes={ categoryTypes} initialScedule={initialSchedule} scheduleJsx={scheduleJsx} setScheduleJsx={setScheduleJsx} />*/}
</div>
<div id='category_component'>
<Categories userID={userID} setCategoryTrigger={setCategoryTrigger} categoryTrigger={categoryTrigger} setScheduleTrigger={setScheduleTrigger} scheduleTrigger={scheduleTrigger} table1={table1} categoryTable={categoryTable} setTable={setTable} optionRef={optionRef} setCategoryTable={setCategoryTable} setCategoryTypes={setCategoryTypes} categoryTypes={ categoryTypes} initialScedule={initialSchedule} scheduleJsx={scheduleJsx} setScheduleJsx={setScheduleJsx} />
</div>
</div>
</div>
</div>
);
}
// Routing between login/signup pages to main page.
return (
<div className='app-routes'>
<Switch>
<Route path='/mainPage' render={mainPage}/>
<Route path='/' component={()=><Login setScheduleMoment={setScheduleMoment} timeToSlot={timeToSlot} rememberMe={rememberMe} setRememberMe={setRememberMe} userID={userID} setUserID={setUserID}/>}/>
</Switch>
</div>
);
}
export default App |
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose'); // mongoose for mongodb
var Area = mongoose.model('area', {
name : String,
userID : String,
parentID : String,
});
router.post('/area/:userID', postArea);
router.get('/area/:userID', getAreas);
router.delete('/area/:userID/:_id', deleteArea);
router.put('/areaUpdate/:userID/:_id', updateArea);
module.exports = router;
function getAreas(req, res) {
// use mongoose to get all areas in the database
Area.find({userID : req.params.userID}, function(err, areas)
{
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(areas); // return all areas in JSON format
});
};
// create area and send back all areas after creation
function postArea(req, res) {
// create a area, information comes from AJAX request from Angular
Area.create({
name : req.body.name,
parentID : req.body.parentID,
userID : req.body.userID,
done : false
}, function(err, area) {
if (err)
res.send(err);
// get and return all the areas after you create another
Area.find({userID : req.params.userID}, function(err, areas) {
if (err)
res.send(err)
res.json(areas);
});
});
};
// delete a area
function deleteArea(req, res)
{
Area.remove(
{
_id : req.params._id
},
function(err, area)
{
if (err)
res.send(err);
// get and return all the areas after you create another
Area.find({userID : req.params.userID}, function(err, areas) {
if (err)
res.send(err)
res.json(areas);
});
});
};
//update area and send back data
function updateArea(req, res)
{
Area.findOneAndUpdate({_id : req.params._id}, req.body, function(err, areas)
{
if (err)
res.send(err);
// get and return all the areas after you updated another
Area.find({userID : req.params.userID}, function(err, areas)
{
if (err)
res.send(err)
res.json(areas);
});
});
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { Tab } from 'react-bootstrap';
import cx from 'classnames';
import swal from 'sweetalert';
import { toastr } from 'react-redux-toastr';
import copy from 'copy-to-clipboard';
import { ReactTabulator } from 'react-tabulator';
import { numberFormat, relu } from '../../utils';
// import 'react-tabulator/lib/styles.css'; // default theme
// import 'react-tabulator/css/bootstrap/tabulator_bootstrap.min.css';
import { removeOrder } from '../../actions/order';
import Tabs from '../Tabs';
import themify from '../../themify';
import s from './UserInfo.css';
import config from '../../config';
// import List from '../List/List';
// import ListHash from '../List/ListHash';
/* eslint-disable css-modules/no-undef-class */
const btcTokenId = 2;
const orderStatus = [
{
id: 1,
name: 'Filled',
},
{
id: 2,
name: 'Pending',
},
{
id: 3,
name: 'Cancelled',
},
{
id: 4,
name: 'Rejected',
},
{
id: 5,
name: 'Suspended',
},
{
id: 6,
name: 'Expired',
},
];
const tradeHistoryColumns = currencySymbol => [
// eslint-disable-line
{ title: 'Pair', field: 'pair', align: 'left', minWidth: 100 },
{ title: 'Type', field: 'type', align: 'left', minWidth: 80 },
{ title: 'Side', field: 'side', align: 'left', minWidth: 80 },
{
title: 'Price',
field: 'price',
align: 'right',
minWidth: 100,
// formatter: cell => {
// const value = cell.getValue();
// return `<span>${currencySymbol} ${value}</span>`;
// },
},
{
title: 'Amount',
field: 'amount',
align: 'right',
minWidth: 100,
},
{
title: 'Total',
field: 'total',
align: 'right',
minWidth: 100,
formatter: cell => {
const value = cell.getValue();
return `<span>${numberFormat(Number(value), 12)}</span>`;
},
},
// {
// title: 'Fee',
// field: 'fee',
// align: 'left',
// minWidth: 100,
// formatter: cell => {
// const value = cell.getValue();
// return `<span>${numberFormat(Number(value))}</span>`;
// },
// },
{ title: 'Timestamp', field: 'timestamp', align: 'left', minWidth: 120 },
];
const walletsColumns = currencySymbol => [
{
title: 'Name',
field: 'name',
align: 'left',
formatter: cell => {
const value = cell.getRow().getData();
return `<span>
<img
width="20"
height="20"
src=${`${config.api.serverUrl}/${value.logoUrl}`}
alt="logo"
/> ${value.name}
</span>`;
},
},
{ title: 'Balance', field: 'balance', align: 'left' },
{ title: 'Reserved Balance', field: 'reservedBalance', align: 'left' },
{ title: 'Locked Reward', field: 'lockedReward', align: 'left' },
{
title: 'Value',
field: 'value',
align: 'left',
formatter: cell => {
const value = cell.getValue();
return `<span>${currencySymbol} ${value}</span>`;
},
},
// {
// title: 'P&L',
// field: 'profitNLoss',
// align: 'left',
// formatter: cell => {
// const value = cell.getValue();
// return `<span>${value}%</span>`;
// },
// },
{
title: 'Address',
field: 'address',
align: 'left',
formatter: cell => {
const value = cell.getValue();
return ` <div>
<span style="font-family: monospace; font-size: 11px;">${value.substring(
0,
15,
)}...</span>
<button
style="
height: auto;
background: transparent;
border: 0;
"
>
<span class="fa fa-copy" style="color:#a5bdea;" />
</button>
</div>`;
},
cellClick: (e, cell) => {
copy(cell.getValue());
toastr.info('copied!');
},
},
];
class UserInfo extends Component {
render() {
const orderColumns = currencySymbol => [
// eslint-disable-line
{ title: 'Pair', field: 'pair', align: 'left', minWidth: 100 },
{ title: 'Type', field: 'type', align: 'left', minWidth: 80 },
{ title: 'Side', field: 'side', align: 'left', minWidth: 80 },
{
title: 'Price',
field: 'price',
align: 'right',
minWidth: 100,
// formatter: cell => {
// const value = cell.getValue();
// return `<span>${currencySymbol} ${value}</span>`;
// },
},
{ title: 'Filled', field: 'filled', align: 'right', minWidth: 80 },
{ title: 'Amount', field: 'amount', align: 'right', minWidth: 100 },
{ title: 'Total', field: 'total', align: 'right', minWidth: 100 },
{ title: 'Status', field: 'status', align: 'left', minWidth: 100 },
{ title: 'Timestamp', field: 'timestamp', align: 'left', minWidth: 120 },
{
title: 'Cancel',
align: 'left',
minWidth: 100,
formatter: () =>
`<span class="far fa-times-circle" style="color:#a5bdea;" />`,
cellClick: (e, cell) => {
swal({
title: 'Are you sure?',
text: 'Once you cancel order, you order will be canceled!',
icon: 'warning',
buttons: true,
dangerMode: true,
}).then(willDelete => {
if (willDelete) {
this.props.cancelOpenOrder(cell.getRow().getData().id);
}
});
},
},
];
const baseCurrency = this.props.currencies.find(
item => item.id === this.props.baseCurrencyId,
);
const btcUsdPrice = this.props.tokens.find(item => item.symbol === 'BTC')
.usdPrice;
// A function for calculate profit & loss
const calculateProfitNLossPercentage = (
transactionHistory,
currentTokenValue,
orderHistory,
) => {
const withdrawHistory =
transactionHistory && transactionHistory.withdraw
? transactionHistory.withdraw
: [];
const depositHistory =
transactionHistory && transactionHistory.deposit
? transactionHistory.deposit
: [];
const withdrawAccumulatedValue = withdrawHistory.map(
item => Number(item.usdPriceAtTransactionTime) * Number(item.amount),
);
const depositAccumulatedValue = depositHistory.map(
item => Number(item.usdPriceAtTransactionTime) * Number(item.amount),
);
// TODO: we should change this after adding new non-usd-quote pairs
const buyTradesAccumulatedValue = orderHistory
.filter(item => item.sideId === 1)
.map(item => Number(item.price) * Number(item.filledAmount));
const sellTradesAccumulatedValue = orderHistory
.filter(item => item.sideId === 2)
.map(item => Number(item.price) * Number(item.filledAmount));
return depositAccumulatedValue.reduce((a, b) => a + b, 0) === 0
? 0
: ((withdrawAccumulatedValue.reduce((a, b) => a + b, 0) +
sellTradesAccumulatedValue.reduce((a, b) => a + b, 0) +
currentTokenValue) /
(depositAccumulatedValue.reduce((a, b) => a + b, 0) +
buyTradesAccumulatedValue.reduce((a, b) => a + b, 0)) -
1) *
100;
};
const wallets = this.props.wallets.map(wallet => {
const lastPrice = this.props.pairs.find(
pair =>
pair.baseTokenId === wallet.tokenId &&
pair.quoteTokenId === btcTokenId,
)
? this.props.pairs.find(
pair =>
pair.baseTokenId === wallet.tokenId &&
pair.quoteTokenId === btcTokenId,
).lastPrice
: '1';
return {
logoUrl: this.props.tokens.find(token => token.id === wallet.tokenId)
.logoUrl,
name: this.props.tokens.find(token => token.id === wallet.tokenId)
.symbol,
balance: numberFormat(relu(Number(wallet.balance)), 8),
reservedBalance: numberFormat(relu(Number(wallet.reservedBalance)), 8),
value: (
(relu(Number(wallet.balance)) +
relu(Number(wallet.reservedBalance))) *
Number(lastPrice) *
Number(btcUsdPrice) *
Number(baseCurrency.usdRatio)
).toFixed(2),
profitNLoss: calculateProfitNLossPercentage(
this.props.transactionHistory,
relu(Number(wallet.balance)) * Number(lastPrice),
this.props.openOrders.filter(item => item.statusId === 1),
).toFixed(2),
address: wallet.address,
lockedReward: wallet.lockedReward
? Number(numberFormat(wallet.lockedReward, 8))
: 0,
};
});
return (
<div
className={cx(themify(s, s.customPanel, this.props.theme))}
style={{ height: this.props.height }}
>
<Tabs align="left" theme={this.props.theme}>
<Tab eventKey={0} title="Open Orders">
<ReactTabulator
columns={orderColumns(baseCurrency.symbolNative).filter(
(_, i) =>
i !== orderColumns(baseCurrency.symbolNative).length - 2,
)}
key={this.props.baseCurrencyId}
data={this.props.openOrders
.filter(order => order.statusId === 2)
.map(order => ({
...order,
price:
order.typeId === 1
? 0
: Number(order.price).toFixed(
this.props.pairs.find(
pair => pair.id === order.pairId,
).priceDecimals * 1.5,
),
pair: this.props.pairs.find(pair => pair.id === order.pairId)
.name,
side: order.sideId === 1 ? 'Buy' : 'Sell',
type: order.typeId === 1 ? 'Market' : 'Limit',
amount: Number(order.amount).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.tradeAmountDecimals,
),
filled: Number(order.filledAmount).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.tradeAmountDecimals,
),
total: (order.price * order.amount).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.priceDecimals * 1.5,
),
status:
order.statusId &&
orderStatus.find(item => item.id === order.statusId) &&
orderStatus.find(item => item.id === order.statusId).name,
// ...(!order.status && { status: 'pending' }),
// ...(!order.filled && { filled: 0 }),
}))
.slice()
.reverse()}
options={{
height: 'inherit',
layout: 'fitDataFill',
movableRows: false,
pagination: 'local',
paginationSize: 15,
}}
className={`tabulatorTheme ${this.props.theme} tabulator`}
/>
</Tab>
<Tab eventKey={1} title="Orders History">
<ReactTabulator
columns={orderColumns(baseCurrency.symbolNative).filter(
(_, i) =>
i !== orderColumns(baseCurrency.symbolNative).length - 1,
)}
key={this.props.baseCurrencyId}
data={this.props.orderHistory
.map(order => {
let totalCost = 0;
let avgPrice;
// console.log('hi: ', order, '->', totalCost);
if (order.sideId === 1 && order.buyTrades.length !== 0) {
order.buyTrades.forEach(trade => {
totalCost +=
parseFloat(trade.price) * parseFloat(trade.amount);
});
avgPrice = totalCost / order.amount;
} else if (
order.sideId === 2 &&
order.sellTrades.length !== 0
) {
order.sellTrades.forEach(trade => {
totalCost +=
parseFloat(trade.price) * parseFloat(trade.amount);
});
avgPrice = totalCost / order.amount;
} else if (order.price !== 0) {
avgPrice = order.price;
} else {
avgPrice = '-';
}
return {
...order,
price: Number(avgPrice).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.priceDecimals,
),
pair: this.props.pairs.find(
pair => pair.id === order.pairId,
).name,
side: order.sideId === 1 ? 'Buy' : 'Sell',
type: order.typeId === 1 ? 'Market' : 'Limit',
amount: Number(order.amount).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.tradeAmountDecimals,
),
filled: Number(order.filledAmount).toFixed(
this.props.pairs.find(pair => pair.id === order.pairId)
.tradeAmountDecimals,
),
total:
order.price !== 0
? (avgPrice * order.amount).toFixed(
this.props.pairs.find(
pair => pair.id === order.pairId,
).priceDecimals * 1.5,
)
: '-',
status:
order.statusId &&
orderStatus.find(item => item.id === order.statusId) &&
orderStatus.find(item => item.id === order.statusId).name,
timestamp: order.createdAt,
// ...(!order.status && { status: 'pending' }),
// ...(!order.filled && { filled: 0 }),
};
})
.slice()
.reverse()}
options={{
height: 'inherit',
layout: 'fitDataFill',
movableRows: false,
pagination: 'local',
paginationSize: 15,
}}
className={`tabulatorTheme ${this.props.theme} tabulator`}
/>
</Tab>
<Tab eventKey={2} title="Trades History">
<ReactTabulator
columns={tradeHistoryColumns(baseCurrency.symbolNative)}
data={this.props.tradeHistory.slice().reverse()}
key={this.props.baseCurrencyId}
options={{
height: 'inherit',
layout: 'fitDataFill',
movableRows: false,
pagination: 'local',
paginationSize: 15,
}}
className={`tabulatorTheme ${this.props.theme} tabulator`}
/>
</Tab>
<Tab eventKey={3} title="Wallets">
{/* <List
listType="wallets"
height={220}
theme={this.props.theme}
list={wallets}
columns={['name', 'balance', 'value', 'p&l', 'address']}
columnNames={['Token', 'Balance', 'Value', 'P&L', 'address']}
columnPostfixes={['', '', '']}
colors={[{}, {}, {}]}
rowHeight="40px"
/> */}
<ReactTabulator
columns={walletsColumns(baseCurrency.symbolNative)}
data={wallets}
key={this.props.baseCurrencyId}
options={{
height: 'inherit',
layout: 'fitDataFill',
movableRows: false,
pagination: 'local',
paginationSize: 15,
}}
className={`tabulatorTheme ${this.props.theme} tabulator`}
/>
</Tab>
</Tabs>
</div>
);
}
}
UserInfo.propTypes = {
theme: PropTypes.string,
openOrders: PropTypes.arrayOf(PropTypes.object).isRequired,
orderHistory: PropTypes.arrayOf(PropTypes.object).isRequired,
transactionHistory: PropTypes.arrayOf(PropTypes.object).isRequired,
tradeHistory: PropTypes.arrayOf(PropTypes.object).isRequired,
wallets: PropTypes.arrayOf(PropTypes.object).isRequired,
tokens: PropTypes.arrayOf(PropTypes.object).isRequired,
pairs: PropTypes.arrayOf(PropTypes.object).isRequired,
currencies: PropTypes.arrayOf(PropTypes.object).isRequired,
baseCurrencyId: PropTypes.number.isRequired,
height: PropTypes.string,
cancelOpenOrder: PropTypes.func.isRequired,
};
UserInfo.defaultProps = {
theme: 'dark',
height: '30vh',
};
const mapState = state => ({
openOrders: state.userInfo.openOrders,
orderHistory: state.userInfo.orderHistory,
tradeHistory: state.userInfo.tradeHistory,
transactionHistory: state.userInfo.transactionHistory,
wallets: state.userInfo.wallets,
tokens: state.tokens,
pairs: state.pairs,
currencies: state.currencies,
baseCurrencyId: state.userInfo.profile.baseCurrencyId || 1,
theme: state.theme,
});
const mapDispatch = dispatch => ({
cancelOpenOrder(orderId) {
dispatch(removeOrder(orderId));
},
});
export default connect(
mapState,
mapDispatch,
)(withStyles(s)(UserInfo));
export const WithoutRedux = withStyles(s)(UserInfo);
|
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : '219911925347660',
autoLogAppEvents : true,
xfbml : true,
version : 'v3.1'
});
};
$('.open-messenger').on('click', function(){
FB.CustomerChat.showDialog();
})
// Facebook Payments
$('.lightarian-rays-client-payment').on('click', function(){
FB.ui(
{
method: 'pay',
action: 'purchaseiap',
product_id: 'lightarian_rays_client',
developer_payload: 'think_for_yourself_og_payment_request_lightarian_rays_client'
},
response => (console.log(response)) // Callback function
);
})
$('.lightarian-clearing-client-payment').on('click', function(){
FB.ui(
{
method: 'pay',
action: 'purchaseiap',
product_id: 'lightarian_clearing_client',
developer_payload: 'think_for_yourself_og_payment_request_lightarian_clearing_client'
},
response => (console.log(response)) // Callback function
);
})
|
import React from 'react'
import css from './Footer.module.css';
const Footer = (props) => {
return (
<div className={css.footer_container}>
{(props.isImageLoaded)
? <p className={css.footer_text}>© 2020 Bong Studio. All Rights Reserved.</p>
: <p className={css.footer_loading}>Loading...</p>
}
</div>
)
}
export default Footer
|
$(function(){
init();
/*
* 初始化init
*/
function init(){
$(".img-thumbnail.mashimg").bind("click", function(){
//首先,将评分传到后台,然后再重新替换一组进行评分
mash.winId = $(this).attr("mashId");
console.log(mash);
score(mash);
});
}
/*
* 将评分传到后台
*/
function score(mash){
$.ajax({
type: "post",
url: base + "/mash/saveScore.htm",
data: mash,
cache: false,
beforeSend: function(){
//添加浮层
},
success: function(data){
//重新加载一组数据
nextMash();
},
error:function(){
//取消浮层
}
});
}
/*
* 重新换一组数据进行评价
*/
function nextMash(){
$.ajax({
type: "get",
url: base + "/mash/mashList.htm",
cache: false,
success: function(data){
//重新将数据替换到页面中
$("#mashBox").html(data);
init();
//取消浮层
},
error:function(){
//取消浮层
}
});
}
}); |
(function() {
var toString = Object.prototype.toString;
function isArray(it) {
return toString.call(it) === '[object Array]';
}
function isObject(it) {
return toString.call(it) === '[object Object]';
}
function _merge(a, b) {
for (var key in b) {
if (isArray(b[key])) {
a[key] = b[key].slice();
} else if (isObject(b[key])) {
a[key] = a[key] || {};
_merge(a[key], b[key]);
} else {
a[key] = b[key];
}
}
return a;
}
function merge() {
var res = {};
for (var i = 0; i < arguments.length; ++i) {
_merge(res, arguments[i]);
}
return res;
}
var axisColor = "#707070";
var axisGridlineColor = "#dadada";
var backgroundColor = "#eeeeee";
var background = {
background: {
color: backgroundColor,
border: {
top: {
visible: false
},
bottom: {
visible: false
},
left: {
visible: false
},
right: {
visible: false
}
},
drawingEffect: "glossy"
}
};
var legend = {
legend: {
drawingEffect: "glossy",
title: {
visible: true
}
}
};
var tooltip = {
tooltip: {
drawingEffect: "glossy"
}
};
var plotArea = {
plotArea: {
drawingEffect: "glossy"
}
};
var zAxis = {
zAxis: {
title: {
visible: true
},
color: axisColor
}
};
var axis = {
title: {
visible: true
},
gridline: {
color: axisGridlineColor
},
color: axisColor
};
var showAxisLine = {
axisline: {
visible: true
}
};
var showInfoAxisLine = {
axisLine: {
visible: true
}
};
var hideAxisLine = {
axisline: {
visible: false
}
};
var hideInfoAxisLine = {
axisLine: {
visible: false
}
};
var gridline = {
gridline: {
type: "incised",
color: axisGridlineColor,
showLastLine: true
}
};
var dual = {
title: {
applyAxislineColor: true
}
};
var base = merge(background, legend, tooltip, plotArea);
var horizontalEffect = {
xAxis: merge(axis, hideAxisLine, gridline),
yAxis: axis,
xAxis2: merge(axis, hideAxisLine)
};
var horizontalDualEffect = merge(horizontalEffect, dual);
var verticalEffect = {
yAxis: merge(axis, hideAxisLine, gridline),
xAxis: axis,
yAxis2: merge(axis, hideAxisLine)
};
var verticalDualEffect = merge(verticalEffect, dual);
//--------------------------------------------------------------
var barEffect = merge(base, horizontalEffect);
var bar3dEffect = merge(base, zAxis, horizontalEffect);
var dualbarEffect = merge(base, horizontalDualEffect);
var verticalbarEffect = merge(base, verticalEffect);
var vertical3dbarEffect = merge(base, zAxis, verticalEffect);
var dualverticalbarEffect = merge(base, verticalDualEffect);
var stackedbarEffect = merge(base, horizontalEffect);
var dualstackedbarEffect = merge(base, horizontalDualEffect);
var stackedverticalbarEffect = merge(base, verticalEffect);
var dualstackedverticalbarEffect = merge(base, verticalDualEffect);
var lineEffect = merge(base, verticalEffect);
var duallineEffect = merge(base, verticalDualEffect);
var horizontallineEffect = merge(base, horizontalEffect);
var dualhorizontallineEffect = merge(base, horizontalDualEffect);
var combinationEffect = merge(base, verticalEffect);
var dualcombinationEffect = merge(base, verticalDualEffect);
var horizontalcombinationEffect = merge(base, horizontalEffect);
var dualhorizontalcombinationEffect = merge(base, horizontalDualEffect);
var bulletEffect = {
legend: {
drawingEffect: "normal",
title: {
visible: true
}
},
tooltip: {
drawingEffect: "normal"
},
plotArea: {
drawingEffect: "normal",
gridline:{
visible : true
},
background: {
border: {
top: {
visible: false
},
bottom: {
visible: false
},
left: {
visible: false
},
right: {
visible: false
}
},
drawingEffect: "normal"
}
},
valueAxis : {
title: {
visible: true
},
axisLine: {
visible: false
},
gridline: {
type: "line",
color: "#d8d8d8",
showLastLine: true
},
color: "#333333"
},
categoryAxis : {
title: {
visible: true
},
gridline: {
color: "#d8d8d8"
},
color: "#333333"
}
};
var bubbleEffect = merge(base, {
yAxis: merge(axis, hideAxisLine, gridline),
xAxis: axis
});
var pieEffect = merge(legend, plotArea, {
background: {
visible: false
}
});
var pieWithDepthEffect = merge(pieEffect, tooltip);
var radarEffect = merge(legend, tooltip, plotArea, {
background: {
visible: false
},
plotArea: {
valueAxis: {
title: {
visible: true
},
gridline: {
color: axisGridlineColor
}
}
}
});
var mekkoEffect = merge(base, {
yAxis: merge(axis, hideAxisLine, gridline),
xAxis: merge(axis, showAxisLine),
xAxis2: merge(axis, showAxisLine)
});
var horizontalmekkoEffect = merge(base, {
xAxis: merge(axis, hideAxisLine, gridline),
yAxis: merge(axis, showAxisLine),
yAxis2: merge(axis, showAxisLine)
});
var treemapEffect = {
legend: {
title: {
visible: true
}
}
};
var template = {
id: "flashy",
name: "Flashy",
version: "4.0.0",
properties: {
'viz/bar': barEffect,
'viz/3d_bar': bar3dEffect,
'viz/image_bar': barEffect,
'viz/multi_bar': barEffect,
'viz/dual_bar': dualbarEffect,
'viz/multi_dual_bar': dualbarEffect,
'viz/column': verticalbarEffect,
'viz/3d_column': vertical3dbarEffect,
'viz/multi_column': verticalbarEffect,
'viz/dual_column': dualverticalbarEffect,
'viz/multi_dual_column': dualverticalbarEffect,
'viz/stacked_bar': stackedbarEffect,
'viz/multi_stacked_bar': stackedbarEffect,
'viz/dual_stacked_bar': dualstackedbarEffect,
'viz/multi_dual_stacked_bar': dualstackedbarEffect,
'viz/100_stacked_bar': stackedbarEffect,
'viz/multi_100_stacked_bar': stackedbarEffect,
'viz/100_dual_stacked_bar': dualstackedbarEffect,
'viz/multi_100_dual_stacked_bar': dualstackedbarEffect,
'viz/stacked_column': stackedverticalbarEffect,
'viz/multi_stacked_column': stackedverticalbarEffect,
'viz/dual_stacked_column': dualstackedverticalbarEffect,
'viz/multi_dual_stacked_column': dualstackedverticalbarEffect,
'viz/100_stacked_column': stackedverticalbarEffect,
'viz/multi_100_stacked_column': stackedverticalbarEffect,
'viz/100_dual_stacked_column': dualstackedverticalbarEffect,
'viz/multi_100_dual_stacked_column': dualstackedverticalbarEffect,
'riv/cbar': merge(legend, tooltip, plotArea, {
background: {
drawingEffect: "glossy"
},
yAxis: axis
}),
'viz/combination': combinationEffect,
'viz/horizontal_combination': horizontalcombinationEffect,
'viz/dual_combination': dualcombinationEffect,
'viz/dual_horizontal_combination': dualhorizontalcombinationEffect,
'viz/boxplot': merge(base, {
yAxis: merge(axis, hideAxisLine, gridline),
xAxis: axis
}),
'viz/horizontal_boxplot': merge(base, {
xAxis: merge(axis, hideAxisLine, gridline),
yAxis: axis
}),
'viz/waterfall': merge(base, {
yAxis: merge(axis, hideAxisLine, gridline),
xAxis: {
title: {
visible: true
},
color: axisColor
}
}),
'viz/horizontal_waterfall': merge(base, {
xAxis: merge(axis, hideAxisLine, gridline),
yAxis: {
title: {
visible: true
},
color: axisColor
}
}),
'viz/stacked_waterfall': stackedverticalbarEffect,
'viz/horizontal_stacked_waterfall': stackedbarEffect,
'viz/line': lineEffect,
'viz/multi_line': lineEffect,
'viz/dual_line': duallineEffect,
'viz/multi_dual_line': duallineEffect,
'viz/horizontal_line': horizontallineEffect,
'viz/multi_horizontal_line': horizontallineEffect,
'viz/dual_horizontal_line': dualhorizontallineEffect,
'viz/multi_dual_horizontal_line': dualhorizontallineEffect,
'viz/area': lineEffect,
'viz/multi_area': lineEffect,
'viz/100_area': lineEffect,
'viz/multi_100_area': lineEffect,
'viz/horizontal_area': horizontallineEffect,
'viz/multi_horizontal_area': horizontallineEffect,
'viz/100_horizontal_area': horizontallineEffect,
'viz/multi_100_horizontal_area': horizontallineEffect,
'viz/pie': pieEffect,
'viz/multi_pie': pieEffect,
'viz/donut': pieEffect,
'viz/multi_donut': pieEffect,
'viz/pie_with_depth': pieWithDepthEffect,
'viz/donut_with_depth': pieWithDepthEffect,
'viz/multi_pie_with_depth': pieWithDepthEffect,
'viz/multi_donut_with_depth': pieWithDepthEffect,
'viz/bubble': bubbleEffect,
'viz/multi_bubble': bubbleEffect,
'viz/scatter': bubbleEffect,
'viz/multi_scatter': bubbleEffect,
'viz/scatter_matrix': bubbleEffect,
'viz/radar': radarEffect,
'viz/multi_radar': radarEffect,
'viz/tagcloud': {
legend: {
title: {
visible: true
}
}
},
'viz/heatmap': {
legend: {
title: {
visible: true
}
},
xAxis: {
title: {
visible: true
},
color: axisColor
},
yAxis: {
title: {
visible: true
},
color: axisColor
}
},
'viz/treemap': treemapEffect,
'viz/mekko': mekkoEffect,
'viz/100_mekko': mekkoEffect,
'viz/horizontal_mekko': horizontalmekkoEffect,
'viz/100_horizontal_mekko': horizontalmekkoEffect,
'viz/number': {
plotArea: {
valuePoint: {
label: {
fontColor: '#000000'
}
}
}
},
// info charts
'info/column': info(verticalbarEffect),
'info/bar': info(barEffect),
'info/line': info(lineEffect),
'info/pie': info(pieEffect),
'info/donut': info(pieEffect),
'info/scatter': infoBubble(bubbleEffect),
'info/bubble': infoBubble(bubbleEffect),
'info/stacked_column': info(stackedverticalbarEffect),
'info/stacked_bar': info(stackedbarEffect),
'info/combination': info(combinationEffect),
'info/stacked_combination': info(combinationEffect),
'info/dual_stacked_combination': infoDual(dualcombinationEffect),
'info/dual_column': infoDual(dualverticalbarEffect),
'info/dual_line': infoDual(duallineEffect),
'info/dual_bar': infoDual(dualbarEffect),
'info/bullet' :bulletEffect,
'info/vertical_bullet': bulletEffect,
'info/trellis_bullet': bulletEffect,
'info/trellis_vertical_bullet': bulletEffect,
'info/100_stacked_column': info(stackedverticalbarEffect),
'info/100_stacked_bar': info(stackedbarEffect),
'info/horizontal_line': info(horizontallineEffect),
'info/dual_horizontal_line': infoDual(dualhorizontallineEffect),
'info/horizontal_combination': info(horizontalcombinationEffect),
'info/horizontal_stacked_combination': info(horizontalcombinationEffect),
'info/dual_horizontal_stacked_combination': infoDual(dualhorizontalcombinationEffect),
'info/treemap': infoTreemap(treemapEffect),
'info/trellis_column': info(verticalbarEffect),
'info/trellis_bar': info(barEffect),
'info/trellis_line': info(lineEffect),
'info/trellis_pie': info(pieEffect),
'info/trellis_donut': info(pieEffect),
'info/trellis_scatter': infoBubble(bubbleEffect),
'info/trellis_bubble': infoBubble(bubbleEffect),
'info/trellis_stacked_column': info(stackedverticalbarEffect),
'info/trellis_stacked_bar': info(stackedbarEffect),
'info/trellis_combination': info(combinationEffect),
'info/trellis_dual_column': infoDual(dualverticalbarEffect),
'info/trellis_dual_line': infoDual(duallineEffect),
'info/trellis_dual_bar': infoDual(dualbarEffect),
'info/trellis_100_stacked_column': info(stackedverticalbarEffect),
'info/trellis_100_stacked_bar': info(stackedbarEffect),
'info/trellis_horizontal_line': info(horizontallineEffect),
'info/trellis_dual_horizontal_line': infoDual(dualhorizontallineEffect),
'info/trellis_horizontal_combination': info(horizontalcombinationEffect),
'info/dual_stacked_bar': infoDual(dualstackedbarEffect),
'info/100_dual_stacked_bar': infoDual(dualstackedbarEffect),
'info/dual_stacked_column': infoDual(dualstackedverticalbarEffect),
'info/100_dual_stacked_column': infoDual(dualstackedverticalbarEffect),
'info/time_bubble': infoBubble(bubbleEffect)
},
//v-longtick must be set after v-categoryaxisline
css: "\
.v-m-main .v-background-body{fill:#eeeeee;}\
.v-datapoint .v-boxplotmidline{stroke:#333333}\
.v-longtick{stroke:#b3b3b3;}\
"
};
sap.viz.extapi.env.Template.register(template);
function info(obj) {
var ret = merge(obj, {
valueAxis: merge(hideInfoAxisLine, {
title: {
visible: true
},
color: axisColor
}),
categoryAxis: axis,
plotArea: merge(obj.plotArea, gridline)
});
general(ret);
return ret;
}
function infoDual(obj) {
var ret = merge(obj, {
valueAxis: merge(hideInfoAxisLine, {
title: {
visible: true,
applyAxislineColor: true
}
}),
categoryAxis: axis,
valueAxis2: merge(hideInfoAxisLine, {
title: {
visible: true,
applyAxislineColor: true
},
gridline: {
color: axisGridlineColor
}
}),
plotArea: merge(obj.plotArea, gridline)
});
general(ret);
return ret;
}
function infoBubble(obj) {
var ret = merge(obj, {
valueAxis: merge(showInfoAxisLine, {
title: {
visible: true
},
color: axisColor
}),
valueAxis2: merge(axis, hideInfoAxisLine),
plotArea: merge(obj.plotArea, gridline),
sizeLegend : {
title:{
visible : true
}
}
});
general(ret);
return ret;
}
function general(obj) {
obj.plotArea = obj.plotArea || {};
obj.plotArea.background = obj.background;
delete obj.background;
delete obj.xAxis;
delete obj.xAxis2;
delete obj.yAxis;
delete obj.yAxis2;
}
function infoTreemap(obj) {
obj = merge(background, obj);
return info(obj);
}
})();
|
// cnpm i eslint -D
// 可以直接快速生成一个配置文件 npx eslint --init
// 安装eslint-loader
|
const AMOUNT_OF_GOODS_ON_EACH_PAGE = 6;
const renderPaginationBlock = () => {
const goods = $('.catalog__item').not('.visually-hidden');
const amountOfPages = Math.ceil(goods.length / AMOUNT_OF_GOODS_ON_EACH_PAGE);
const paginationList = $('.pagination__list');
if (amountOfPages === 0) {
paginationList.html(`<div class="pagination__empty">Таких товаров не найдено</div>`);
return;
}
paginationList.html('');
for (let i = 0; i < amountOfPages; i++) {
let className = 'pagination__item';
if (i === 0) {
className += ' pagination__item--current'
}
paginationList.append(`
<li class="${className}" data-info="page-number" data-page-number=${i}>${i + 1}</li>
`);
}
paginationList.prepend(`
<li class="pagination__item pagination__item--disabled" data-info="page-prev">
Предыдущая
</li>
`);
paginationList.append(`
<li class="pagination__item ${amountOfPages === 1 ? 'pagination__item--disabled' : ''}"
data-info="page-next">
Следующая
</li>
`);
};
const performPagination = () => {
const activePageNumber = $('.pagination__item--current').data('page-number');
const indexOfFirstGoodOnPage = activePageNumber * AMOUNT_OF_GOODS_ON_EACH_PAGE;
const indexOfLastGoodOnPage = (activePageNumber + 1) * AMOUNT_OF_GOODS_ON_EACH_PAGE;
const goods = $('.catalog__item').not('.visually-hidden');
goods.each(function(index) {
if (index >= indexOfFirstGoodOnPage && index < indexOfLastGoodOnPage) {
$(this).removeClass('catalog__item--hidden');
} else {
$(this).addClass('catalog__item--hidden');
}
})
}; |
import React, { Component } from 'react';
import firebase from 'firebase';
import _ from 'lodash';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class FirebaseActions extends Component {
constructor(props) {
super(props);
this.users = [];
}
add() {
const firstName = 'User 1';
const lastName = 'User 1';
const id = Math.random()
.toString(36)
.substr(2, 9);
const user = {
firstName,
lastName,
id
};
firebase
.database()
.ref('/users')
.push(user);
}
get() {
firebase
.database()
.ref('/users')
.on('value', snapshot => {
this.users = _.map(snapshot.val(), (val, uid) => {
return { ...val, uid };
});
console.log(this.users);
});
}
delete() {
const user = this.users.pop();
console.log(user);
if (user) {
firebase
.database()
.ref(`/users/${user.uid}`)
.remove();
// .then(() => {
//
// });
}
}
update() {
const user = this.users.pop();
console.log(user);
if (user) {
user.firstName = 'Update user';
firebase
.database()
.ref(`/users/${user.uid}`)
.set(user, a => {
console.log(`OnComplete ${a}`);
})
.then(val => {
console.log(`Promise ${val}`);
});
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.container}>
<Button title="Get" onPress={() => this.get()} />
</View>
<View style={styles.container}>
<Button title="Add" onPress={() => this.add()} />
</View>
<View style={styles.container}>
<Button title="Update" onPress={() => this.update()} />
</View>
<View style={styles.container}>
<Button title="Delete" onPress={() => this.delete()} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
|
$(function () {
$(document).scroll(function () {
var $nav = $(".fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
$(function(){
$(window).scroll(function(){
if($(this).scrollTop()>5){
$(".navbar .navbar-brand img").attr("src","images/logos/yk_png_white.png")
}
else{
$(".navbar .navbar-brand img").attr("src","images/logos/yk_png_white.png")
}
})
})
|
import queryString from 'query-string';
import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
import Col from '../../components/common/Col';
import Header from '../../components/common/Header';
import Row from '../../components/common/Row';
import Table from '../../components/common/Table';
import LaunchCard from '../../components/LaunchCard';
import SelectDate from '../../components/SelectDate';
import SelectLaunchType from '../../components/SelectLaunchType';
import { fetchLaunches, fetchUpcomingLaunches } from '../../redux/launches/actions';
import { getLaunchResults, getLoadingState } from '../../redux/launches/selectors';
import { launchTableColumns } from '../../utils/launchTableColumns';
import PxToRem from '../../utils/PxToRem';
const ContentContainer = styled.div`
width: ${PxToRem(952)};
margin: ${PxToRem(16)} auto;
`;
const HomePage = ({ location }) => {
const getStartQuery = () => {
let startQuery = queryString.parse(location.search).start;
let endQuery = queryString.parse(location.search).end;
let paginationIndex = queryString.parse(location.search).page;
startQuery = startQuery == 'Invalid Date' || startQuery == undefined ? new Date(new Date().getFullYear(), new Date().getMonth()-6, new Date().getDate()) : startQuery;
endQuery = endQuery == 'Invalid Date' || endQuery == undefined ? new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()) : endQuery;
paginationIndex = !paginationIndex ? 0 : Number(paginationIndex);
return {start: startQuery, end: endQuery, page: paginationIndex}
}
const ALL_LAUNCHES = 'All Launches';
const UPCOMING_LAUNCHES = 'Upcoming Launches';
const SUCCESSFUL_LAUNCHES = 'Successful Launches';
const FAILED_LAUNCHES = 'Failed Launches';
const [isOpen, setIsOpen] = useState(false);
const [launchDetails, setLaunchDetails] = useState({});
const [dateQueryParam, setDateQueryParam] = useState(getStartQuery());
const urlToSelectMappers = {
[`/launches?start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`]: ALL_LAUNCHES,
[`/launches/upcoming?start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`]: UPCOMING_LAUNCHES,
[`/launches?launch_success=true&start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`]: SUCCESSFUL_LAUNCHES,
[`/launches?launch_success=false&start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`]: FAILED_LAUNCHES
};
const [selected, setSelected] = useState(urlToSelectMappers[`${location.pathname}${location.search}`]);
const [isLaunchCardOpen, setIsLaunchCardOpen] = useState(false);
const history = useHistory();
const toggling = (e, option) => {
setIsOpen(!isOpen);
setSelected(option);
if (isOpen) {
let params = {...dateQueryParam, page:0};
setDateQueryParam(params);
history.push(selectedToURlMappers[option]);
}
};
const dispatch = useDispatch();
const pending = useSelector(getLoadingState);
const selectedToURlMappers = {
[ALL_LAUNCHES]: `/launches?start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`,
[UPCOMING_LAUNCHES]: `/launches/upcoming?start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`,
[SUCCESSFUL_LAUNCHES]: `/launches?launch_success=true&start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`,
[FAILED_LAUNCHES]: `/launches?launch_success=false&start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`
};
useEffect(() => {
setSelected(urlToSelectMappers[`${location.pathname}${location.search}`]);
}, [location.pathname, location.search]);
useEffect(() => {
let params = {
launch_success: queryString.parse(location.search).launch_success
};
if (dateQueryParam.start != 'Invalid Date' && dateQueryParam.end != 'Invalid Date') {
params = { ...params, ...dateQueryParam };
}
if (location.pathname === '/launches') {
dispatch(fetchLaunches({ ...params }));
} else if (location.pathname === '/launches/upcoming') {
dispatch(fetchUpcomingLaunches({ ...params }));
}
}, [selected, dateQueryParam, location.search, location.pathname]);
useEffect(() => {
if(queryString.parse(location.search).launch_success){
history.push(`${location.pathname}?launch_success=${queryString.parse(location.search).launch_success}&start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`);
}
else{
history.push(`${location.pathname}?start=${dateQueryParam.start}&end=${dateQueryParam.end}&page=${dateQueryParam.page}`);
}
}, [dateQueryParam]);
const closeLaunchModal = () => {
setIsLaunchCardOpen(false);
};
const dropdownOptions = [ALL_LAUNCHES, UPCOMING_LAUNCHES, SUCCESSFUL_LAUNCHES, FAILED_LAUNCHES];
const launches = useSelector(getLaunchResults);
const COLUMNS = useMemo(() => launchTableColumns, []);
const openLaunchCard = launch => {
setLaunchDetails(launch);
setIsLaunchCardOpen(!isLaunchCardOpen);
};
const getQueryParams = (startDate, endDate) => {
let queryParam = { start: startDate, end: endDate, page: dateQueryParam.page };
setDateQueryParam(queryParam);
};
const setPageQuery = (page) => {
let queryParams = {...dateQueryParam, page:page};
setDateQueryParam(queryParams);
}
return (
<>
<Header />
<ContentContainer>
<Col>
<Row margin={`${PxToRem(24)} 0`}>
<SelectDate getQueryParams={getQueryParams} location={location} getStartQuery={getStartQuery}/>
<SelectLaunchType
dropdownOptions={dropdownOptions}
isOpen={isOpen}
selected={selected}
toggling={toggling}
/>
</Row>
<Row>
<Table setPageQuery={setPageQuery} initialTabIndex={dateQueryParam.page} columns={COLUMNS} tableData={launches} openLaunchCard={openLaunchCard} loading={pending} />
</Row>
</Col>
</ContentContainer>
<LaunchCard launchDetails={launchDetails} isOpen={isLaunchCardOpen} closeModal={closeLaunchModal} />
</>
);
};
export default HomePage;
|
import Ember from 'ember';
const { inject } = Ember;
export default Ember.Component.extend({
store: inject.service(),
editingName: false,
editingDesc: false,
actions: {
toggleModal() {
this.sendAction('toggleModal');
},
toggleEditState(element) {
if (element === 'name') {
this.toggleProperty('editingName');
} else if (element === 'description') {
this.toggleProperty('editingDesc');
}
},
editItemName(newItem, id) {
if (newItem.name) {
this.toggleProperty('editingName');
let itemToEdit = this.get('store').findRecord('item', id);
let self = this;
itemToEdit.then(function(item) {
item.set('name', newItem.name);
item.save();
self.set('newItem', {});
});
}
},
editItemDescription(newItem, id) {
if (newItem.description) {
this.toggleProperty('editingDesc');
let itemToEdit = this.get('store').findRecord('item', id);
let self = this;
itemToEdit.then(function(item) {
item.set('description', newItem.description);
item.save();
self.set('newItem', {});
});
}
},
deleteItem(item) {
this.sendAction('toggleModal');
this.sendAction('deleteItem', item);
}
}
});
|
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/app/'));
//tiles mobile
app.get('/', function (req, res) {
res.sendfile('app/index.html')
});
//APISs
app.get('/worksets', function (req, res) {
setTimeout(function () {
res.sendfile('server/json/getApiData.json');
}, 500);
});
//LISTEN
app.listen(3000);
console.log('Listening on port 3000'); |
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
import MenuIcon from '@material-ui/icons/Menu';
import { logout, isAuthenticated } from '../auth/authenticator';
const styles = (theme) => ({
root: {
flexGrow: 1,
marginBottom: "24px"
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
textAlign: 'center'
},
});
export default function restricted(BaseComponent) {
class Restricted extends Component {
constructor () {
super();
this.state = {
}
}
componentDidMount() {
this.checkAuthentication(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this.checkAuthentication(nextProps);
}
}
checkAuthentication(params) {
const { history } = params;
if (!isAuthenticated()) {
history.replace({ pathname: '/login' });
}
}
render () {
const { classes } = this.props;
return (
<div className={classes.root}>
<AppBar position="absolute">
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
JifCast
</Typography>
<Button color="inherit" onClick={() => { logout(); this.props.history.push('/login'); } }>Logout</Button>
</Toolbar>
</AppBar>
<BaseComponent {...this.props} />
</div>
);
}
}
return withRouter(withStyles(styles)(Restricted));
}
|
const str = "${name} is a coder"; // eslint-disable-line no-template-curly-in-string
console.log(str);
|
//index.js
//获取应用实例
const app = getApp();
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
array: ['地区','美国', '中国', '巴西', '日本'],
array1: ['类型', '类型1', '类型2', '类型3', '类型4'],
array2: ['薪资', '薪资1', '薪资2', '薪资3', '薪资4'],
array3: ['排序', '排序1', '排序2', '排序3', '排序4'],
index:0,
index1:0,
index2:0,
index3:0,
},
//事件处理函数
getUserInfo: function (e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
});
wx.navigateTo({
url: '../index/index'
})
},
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
goInfo: function () {
wx.navigateTo({
url: '../info/info'
})
},
goPulish: function(){
wx.redirectTo({
url: '../publish/publish',
})
},
goHome: function () {
wx.redirectTo({
url: '../home/home',
})
},
goUserInfo: function () {
wx.redirectTo({
url: '../userInfo/userInfo',
})
},
bindPickerChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index: e.detail.value
})
},
bindPickerChange1: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index1: e.detail.value
})
},
bindPickerChange2: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index2: e.detail.value
})
},
bindPickerChange3: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index3: e.detail.value
})
},
onLoad: function () {
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
// onPullDownRefresh: function () {
// wx.request({
// url: '',
// data: {},
// method: 'GET',
// success: function (res) { },
// fail: function (res) { },
// complete: function (res) {
// wx.stopPullDownRefresh();
// }
// })
// }
})
|
module.exports = require('./lib/es6kadoo');
|
import express from 'express'
import cors from 'cors'
import mongoose from 'mongoose'
import crypto from 'crypto'
import bcrypt from 'bcrypt'
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/authAPI"
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
mongoose.Promise = Promise
const User = mongoose.model('User', {
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
accessToken: {
type: String,
default: () => crypto.randomBytes(128).toString('hex')
}
});
const port = process.env.PORT || 8080
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Hello world')
});
// or '/users' or '/register'
app.post('/signup', async (req, res) => {
const { username, password } = req.body;
try {
const salt = bcrypt.genSaltSync();
const newUser = await new User({
username,
password: bcrypt.hashSync(password, salt)
}).save();
res.json({
success: true,
userID: newUser._id,
username: newUser.username,
accessToken: newUser.accessToken
});
} catch (error) {
res.status(400).json({ success: false, message: 'Invalid request', error });
}
});
// or '/session' or '/login'
app.post('/signin', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (user && bcrypt.compareSync(password, user.password)) {
res.json({
success: true,
userID: user._id,
username: user.username,
accessToken: user.accessToken
});
} else {
res.status(404).json({ success: false, message: 'User not found' });
}
} catch (error) {
res.status(400).json({ success: false, message: 'Invalid request', error });
}
});
app.listen(port, () => {
// eslint-disable-next-line
console.log(`Server running on http://localhost:${port}`)
});
|
import { StyleSheet } from 'react-native'
import { alignment, colors, verticalScale, scale } from '../../utils'
export default {
flex: {
flex: 1
},
safeAreaStyle: {
backgroundColor: colors.headerbackground
},
mainContainer: {
backgroundColor: colors.themeBackground
},
line: {
width: '100%',
height: StyleSheet.hairlineWidth,
backgroundColor: colors.medHorizontalLine,
...alignment.MTxSmall,
...alignment.MBxSmall
},
backImg: {
marginBottom: '3%',
marginLeft: '5%'
},
cardContainer: {
backgroundColor: colors.backgroudGray,
width: '100%',
justifyContent: 'center',
alignItems: 'center',
...alignment.MBlarge
},
card: {
backgroundColor: colors.whiteColor,
width: '95%',
borderRadius: scale(8),
...alignment.Psmall
},
cardLeftContainer: {
width: '35%',
height: '100%',
borderTopLeftRadius: verticalScale(8),
borderBottomLeftRadius: verticalScale(8)
},
cardRightContainer: {
width: '60%',
height: '100%',
...alignment.MLxSmall
},
imgResponsive: {
flex: 1,
width: undefined,
height: undefined,
borderTopLeftRadius: verticalScale(8),
borderBottomLeftRadius: verticalScale(8)
},
timelineContainer: {
backgroundColor: colors.backgroudGray,
flex: 1,
...alignment.PTlarge,
...alignment.PLsmall,
...alignment.PRsmall
}
}
|
import createVirtualNode from '../createVirtualNode.js';
import { isSameVirtualNodes } from '../updateElement.js';
describe('isSameVirtualNodes()', () => {
it('should return true for same primitives', () => {
expect(isSameVirtualNodes(1, '1')).toBe(true);
expect(isSameVirtualNodes(1, 1)).toBe(true);
expect(isSameVirtualNodes(1, 2)).toBe(false);
expect(isSameVirtualNodes(undefined, null)).toBe(false);
expect(isSameVirtualNodes(false, null)).toBe(false);
expect(isSameVirtualNodes(false, {})).toBe(false);
});
it('should return true for same type virtual nodes', () => {
const div1 = createVirtualNode('div');
const div2 = createVirtualNode('div', null, 'test div 2');
const span = createVirtualNode('span', null, 'test div 2');
expect(isSameVirtualNodes(div1, div1)).toBe(true);
expect(isSameVirtualNodes(span, span)).toBe(true);
expect(isSameVirtualNodes(div1, div2)).toBe(true);
expect(isSameVirtualNodes(div1, span)).toBe(false);
});
});
|
'use strict';
const firstName2 = document.querySelector("#firstName1");
const lastName2 = document.querySelector("#lastName1");
const email2 = document.querySelector("#email1");
const address2 = document.querySelector("#address1");
const postcode2 = document.querySelector("#postcode1");
const password2 = document.querySelector("#password1");
const numberOfTickets = 0;
const totalCost = 0.0;
let submitButton = document.querySelector('#signupSubmit');
const checkPassword = (inputtxt) => {
const passwordReqs = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
if (inputtxt.value.match(passwordReqs)) {
return true;
}
else {
alert('Please follow the instructions to enter a valid password');
return false;
}
}
const checkNames = (inputStuffs) => {
const nameReqs = /^[a-zA-Z].{2,30}$/;
if (inputStuffs.value.match(nameReqs)) {
return true;
}else {
alert('Error - Please enter a valid name.');
return false;
}
}
const checkPostcode = (inputPostcode) => {
const UKpostcode = /^(([a-zA-Z][0-9])|([a-zA-Z][0-9][0-9])|([a-zA-Z][a-zA-Z][0-9])|([a-zA-Z][a-zA-Z][0-9][0-9])) [0-9][a-zA-Z][a-zA-Z]$/;
if (inputPostcode.value.match(UKpostcode)) {
return true;
}else{
alert('Error - please input a valid UK postcode.');
return false;
}
}
const checkEmail = (inputE) => {
const mails = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;
if (inputE.value.match(mails)){
return true;
}else {
alert('Error - Please check that your email matches the required format.');
return false;
}
}
const createEntry = () => {
if (!checkPassword(password2) || !checkNames(firstName2) || !checkNames(lastName2) || !checkPostcode(postcode2) || !checkEmail(email2)) {
location.reload();
return;
}
else {
fetch("http://localhost:8081/passenger/create", {
method: "POST",
body: JSON.stringify({
"address": address2.value,
"email": email2.value,
"first_name": firstName2.value,
"last_name": lastName2.value,
"numberOfTickets": numberOfTickets.value,
"password": password2.value,
"postcode": postcode2.value,
"totalCost": totalCost.value
}),
headers: {
'Content-type': "application/json",
},
}).then((response) => response.json())
.then((json) => console.log(json))
.catch(err => console.error(err));
alert("Congratulations!!\n You have officially registered with QA Coaches.")
window.location.replace("Login.html");
}
}
submitButton.addEventListener('click', createEntry); |
var map = ({
"/laba/": "/laba/phone/",
"/laba": "/laba/phone/",
"/laba/shop": "/laba/products",
"/laba/showCart": "/laba/showCart",
"/laba/search/": "/laba/request/"
});
var App = angular.module("myApp", [], function ($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
App.factory("Service", ["$http", "$q", "$window", function ($http, $q, $window) {
var SERVICE_URI = "/laba/registration/";
var factory = {
createItem: createItem,
fetchUser: fetchUser
};
return factory;
function createItem(user) {
var deferred = $q.defer();
$http.post(SERVICE_URI, user)
.then(
function (response) {
deferred.resolve(response.data);
$window.location.href = "/laba/";
},
function (errResponse) {
deferred.reject(errResponse);
$window.location.href = "/laba/registration?reg-err";
}
);
return deferred.promise;
}
function fetchUser(url) {
var deferred = $q.defer();
$http.get(url)
.then(
function (response) {
deferred.resolve(response.data);
},
function (errResponse) {
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
App.controller("mainController", ["$scope", "Service", "$location", function ($scope, Service, $location) {
var self = this;
self.item = {};
self.items = [];
self.submit = submit;
fetchUser();
function submit() {
Service.createItem(self.item);
}
function fetchUser() {
Service.fetchUser("/laba/user")
.then(
function (d) {
self.item = d;
}
);
}
if ($location.absUrl().indexOf("reg-err") != -1) {
$scope.statusreg = 1;
} else {
$scope.statusreg = 0;
}
}]);
App.controller("loginController", ["$scope", "$location", function ($scope, $location) {
if ($location.absUrl().indexOf("error") != -1) {
$scope.status = 1;
} else {
$scope.status = 0;
}
}]);
App.directive("passwordVerify", function () {
return {
require: "ngModel",
scope: {
passwordVerify: "="
},
link (scope, element, attrs, ctrl) {
scope.$watch(function () {
var combined;
if (scope.passwordVerify || ctrl.$viewValue) {
combined = scope.passwordVerify + "_" + ctrl.$viewValue;
}
return combined;
}, function (value) {
if (value) {
ctrl.$parsers.unshift(function (viewValue) {
var origin = scope.passwordVerify;
if (origin !== viewValue) {
ctrl.$setValidity("passwordVerify", false);
return undefined;
} else {
ctrl.$setValidity("passwordVerify", true);
return viewValue;
}
});
}
});
}
};
}); |
import Taro, { Component } from '@tarojs/taro';
import { View, Text, Image } from '@tarojs/components';
import './timeline.scss';
import smileIcon from '../../images/icons/smile@2x.png';
import peaceIcon from '../../images/icons/peace@2x.png';
import sadIcon from '../../images/icons/sad@2x.png';
import breakIcon from '../../images/icons/icon_breakfast@2x.png';
import coffeeIcon from '../../images/icons/icon_coffee@2x.png';
import salleryIcon from '../../images/icons/icon_salary@2x.png';
/**
* 交易记录
*/
export default class TimeLine extends Component {
render() {
const { comment, type, onItemClick, merchant, money, time } = this.props;
let expression = null;
let commentIcon = null;
const leftIcon =
type == 'food'
? breakIcon
: type == 'coffee'
? coffeeIcon
: salleryIcon;
if (comment) {
commentIcon =
comment === 1
? smileIcon
: comment === 2
? peaceIcon
: sadIcon;
console.log(commentIcon);
expression = <Image className="timeline-right-icon" src={commentIcon} />;
}
return (
<View className="timeline-item" onClick={onItemClick}>
<Image className="timeline-left-icon" src={leftIcon} />
<Text className="timeline-content">{merchant}</Text>
<View className="timeline-right">
<Text className="timeline-right-text">{money}</Text>
{expression}
<Text className="timeline-right-date">{time}</Text>
</View>
</View>
);
}
}
|
import firebase from 'firebase';
export const addTodo = (payload) => {
const { currentUser } = firebase.auth();
return firebase.database().ref(`/users/${currentUser.uid}/todos/`).push(payload)
}
export const removeTodo = (payload) => {
const { currentUser } = firebase.auth();
return firebase.database().ref(`/users/${currentUser.uid}/todos/${payload.uid}`).remove();
}
export const login = (payload) => {
const {email, password} = payload;
return firebase.auth().signInWithEmailAndPassword(email, password);
}
export const register = (payload) => {
const {email, password} = payload;
return firebase.auth().createUserWithEmailAndPassword(email, password);
}
export const logout = () => {
return firebase.auth().signOut();
}
|
var path = require('path')
var webpack = require('webpack')
var merge = require('webpack-merge')
var webpackBaseConfig = require('./webpack.base.config')
var htmlWebpackPlugin = require('html-webpack-plugin')
var OpenBrowserPlugin = require('open-browser-webpack-plugin');
module.exports = merge( webpackBaseConfig , {
plugins : [
new webpack.DefinePlugin({
"process.env.NODE_ENV" : "'dev'"
}),
new webpack.HotModuleReplacementPlugin(), // 热加载
new webpack.NamedModulesPlugin(), // 控制台显示正确的文件名
new webpack.NoEmitOnErrorsPlugin(), // 编译出错的时候 跳过输出阶段,确保输出资源不会包含错误
new htmlWebpackPlugin({
template: 'index.html'
}),
new OpenBrowserPlugin({
url: 'http://localhost:8080'
}),
],
devServer : {
compress : true,
proxy: {
// 凡是 `/api` 开头的 http 请求,都会被代理到 localhost:3000 上,由 koa 提供 mock 数据。
// koa 代码在 ./mock 目录中,启动命令为 npm run mock
'/api': {
target: 'http://localhost:3000',
secure: false
}
},
contentBase: "../dist", //本地服务器所加载的页面所在的目录
historyApiFallback: true, //不跳转
inline: true, //实时刷新
hot: true // 使用热加载插件 HotModuleReplacementPlugin
}
})
|
$(function() {
var key = getCookie('key');
if (!key) {
location.href = WapSiteUrl + '/tmpl/member_system/login.html';
}
var pay_sn = getQueryString('pay_sn');
if (!pay_sn) {
errorTipsShow('参数错误');
} else {
$.ajax({
type: 'post',
url: ApiUrl + '/index.php?act=member_order&op=checkPaysn',
data: { key: key, pay_sn: pay_sn },
dataType: 'json',
success: function(result) {
console.log(result)
checkLogin(result.login);
if (result.datas.error) {
errorTipsShow(result.datas.error);
} else {
$.ajax({
type: 'post',
url: ApiUrl + '/index.php?act=member_payment&op=getPaymentList',
data: { key: key },
dataType: 'json',
success: function(result) {
console.log(result)
var list = result.datas.list;
var html = '';
if (list.length == 0) {
errorTipsShow('暂无支持的支付方式');
location.href = history.back(-1);
return false;
} else {
for (var i = 0; i < list.length; i++) {
html += '<dl class="mt5">';
html += '<dt>';
html += '<a id="pay-item" code="' + list[i].payment_code + '">';
html += '<h3><i class="mcmc-0'+i+'"></i>' + list[i].payment_name + '</h3>';
html += '<h5><i class="arrow-r"></i></h5>';
html += '</a>';
html += '</dt>';
html += '</dl>';
}
$('.payment-list').append(html);
var payment_code = $('#payment_code').val();
if (payment_code != '') {
$("a[code='" + payment_code + "'").parent().parent().addClass('selected');
}
}
}
});
$('.payment-list').on("click", "#pay-item", function() {
var code = $(this).attr('code');
console.log(code)
var payment_code = $('#payment_code').val();
// var payment_code=document.getElementById("payment_code").value;
console.log(payment_code)
errorTipsHide();
if (code === payment_code) {
return;
}
if ($("a[code='" + payment_code + "']").parent().parent().hasClass('selected')) {
$("a[code='" + payment_code + "']").parent().parent().removeClass('selected');
}
$('#payment_code').val(code);
$(this).parent().parent().addClass('selected');
});
$('#submitbtn').click(function() {
var payment_code = $('#payment_code').val();
if (payment_code == '') {
errorTipsShow("请选择支付方式");
return;
} else {
if (payment_code == 'balancepay'|| payment_code == 'goldpay' || payment_code == 'silverpay') {
$.dialog({
titleText: '输入支付密码',
showTitle: true,
type: 'confirm',
contentHtml: '<input type="password" name="pay_passwd" id="pay_passwd" placeholder="请输入支付密码" />',
buttonText: {
ok: '确认支付',
cancel: '取消'
},
onClickOk: function() {
var pay_passwd = $('#pay_passwd').val();
if (pay_passwd == '') {
errorTipsShow('请输入支付密码');
return;
} else {
doPay(key, pay_sn, payment_code, pay_passwd);
}
},
});
} else if(payment_code == 'alipay_wap'){
location.href = ApiUrl + '/index.php?act=member_payment&op=wapPay&key=' + key + '&pay_sn=' + pay_sn + '&payment_code=' + payment_code;
}else{
location.href = ApiUrl + '/index.php?act=member_payment&op=pay_new&key=' + key + '&pay_sn=' + pay_sn + '&payment_code=' + 'wxpay_jsapi';
}
}
});
}
}
});
}
});
function doPay(key, pay_sn, payment_code, pay_passwd) {
$.dialog({
type: 'info',
infoText: '加载中…',
infoIcon: '../images/icon/loading.gif',
autoClose: 2500
});
$.ajax({
type: 'get',
url: ApiUrl + '/index.php?act=member_payment&op=wapPay',
data: {
key: key,
pay_sn: pay_sn,
payment_code: payment_code,
pay_passwd: pay_passwd
},
dataType: 'json',
success: function(result) {
checkLogin(result.login);
if (result.datas.error) {
errorTipsShow(result.datas.error);
return;
}
location.href = WapSiteUrl + '/tmpl/payment_success.html';
}
});
} |
'use strict';
$(document).ready(function(){
checkDocumentVisibility(checkLogin);//check document visibility in order to confirm bank's log in status
//load all banks once the page is ready
//function header: larl_(url)
// larl_();
// laal_();
// ladl_();
load_all();
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//reload the list of loans when fields are changed
$("#reqLoanListSortBy, #reqLoanListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#reqLoan").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all($(this).attr('href'));
return false;
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//handles the addition of new bank details .i.e. when "add bank" button is clicked
$("#addLoanSubmit").click(function(e){
e.preventDefault();
//reset all error msgs in case they are set
changeInnerHTML(['nameErr', 'descriptionErr'],
"");
var name = $("#name").val();
var description = $("#description").val();
//ensure all required fields are filled
if(!name){
!name ? changeInnerHTML('nameErr', "required") : "";
return;
}
//display message telling bank action is being processed
$("#fMsgIcon").attr('class', spinnerClass);
$("#fMsg").text(" Processing...");
//make ajax request if all is well
$.ajax({
method: "POST",
url: appRoot+"loans/add",
data: {name:name, description:description}
}).done(function(returnedData){
$("#fMsgIcon").removeClass();//remove spinner
if(returnedData.status === 1){
$("#fMsg").css('color', 'green').text(returnedData.msg);
//reset the form
document.getElementById("addNewLoanForm").reset();
//close the modal
setTimeout(function(){
$("#fMsg").text("");
$("#addNewLoanModal").modal('hide');
}, 1000);
//reset all error msgs in case they are set
changeInnerHTML(['nameErr', 'descriptionErr'],
"");
//refresh bank list table
load_all();
}
else{
//display error message returned
$("#fMsg").css('color', 'red').html(returnedData.msg);
//display individual error messages if applied
$("#nameErr").text(returnedData.name);
$("#descriptionErr").text(returnedData.description);
}
}).fail(function(){
if(!navigator.onLine){
$("#fMsg").css('color', 'red').text("Network error! Pls check your network connection");
}
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$("#editLoanCancel").click(function(e){
e.preventDefault();
changeInnerHTML(['userEditErr', 'statusNumberEditErr', 'loanUnitEditErr',
'loanAmountEditErr', 'collateralUnitEditErr', 'collateralAmountEditErr','durationEditErr'], "");
});
//handles the updating of loan details
$("#editLoanSubmit").click(function(e){
e.preventDefault();
if(formChanges("editLoanForm")){
//reset all error msgs in case they are set
changeInnerHTML(['userEditErr', 'statusNumberEditErr', 'loanUnitEditErr',
'loanAmountEditErr', 'collateralUnitEditErr', 'collateralAmountEditErr','durationEditErr'], "");
var userId = $("#userEdit").val();
var statusNumber = $("#statusNumberEdit").val();
var loanUnitId = $("#loanUnitEdit").val();
var loanAmount = $("#loanAmountEdit").val();
var collateralUnitId = $("#collateralUnitEdit").val();
var collateralAmount = $("#collateralAmountEdit").val();
var duration = $("#durationEdit").val();
var loanId = $("#loanId").val();
//ensure all required fields are filled
if(!userId || !statusNumber || !loanUnitId || !loanAmount || ! collateralUnitId || !collateralAmount
|| !duration){
!userId ? changeInnerHTML('userEditErr', "required") : "";
!statusNumber ? changeInnerHTML('statusNumberEditErr', "required") : "";
!loanUnitId ? changeInnerHTML('loanUnitEditErr', "required") : "";
!loanAmount ? changeInnerHTML('loanAmountEditErr', "required") : "";
!collateralUnitId ? changeInnerHTML('collateralUnitEditErr', "required") : "";
!collateralAmount ? changeInnerHTML('collateralAmountEditErr', "required") : "";
!duration ? changeInnerHTML('durationEditErr', "required") : "";
return;
}
// if(!statusNumber){
// return;
// }
// if(!loanUnitId){
// return;
// }
// if(!loanAmount){
// return;
// }
// if(!collateralUnitId){
// return;
// }
// if(!collateralAmount){
// return;
// }
// if(!duration){
// return;
// }
if(!loanId){
$("#fMsgEdit").text("An unexpected error occured while trying to update bank's details");
return;
}
//display message telling loan is being processed
$("#fMsgEditIcon").attr('class', spinnerClass);
$("#fMsgEdit").text(" Updating details...");
//make ajax request if all is well
$.ajax({
method: "POST",
url: appRoot+"loans/update",
data: {loanId:loanId, userId:userId, statusNumber:statusNumber,
loanUnitId:loanUnitId, loanAmount:loanAmount,
collateralUnitId:collateralUnitId, collateralAmount:collateralAmount,
duration:duration}
}).done(function(returnedData){
$("#fMsgEditIcon").removeClass();//remove spinner
if(returnedData.status === 1){
$("#fMsgEdit").css('color', 'green').text(returnedData.msg);
//reset the form and close the modal
setTimeout(function(){
$("#fMsgEdit").text("");
$("#editLoanModal").modal('hide');
}, 1000);
//reset all error msgs in case they are set
changeInnerHTML(['nameEditErr', 'descriptionEditErr'], "");
//refresh bank list table
load_all();
}
else{
//display error message returned
$("#fMsgEdit").css('color', 'red').html(returnedData.msg);
//display individual error messages if applied
$("#nameEditErr").html(returnedData.name);
$("#descriptionEditErr").html(returnedData.description);
}
}).fail(function(){
if(!navigator.onLine){
$("#fMsgEdit").css('color', 'red').html("Network error! Pls check your network connection");
}
});
}
else{
$("#fMsgEdit").html("No changes were made");
}
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//handles loan search
$("#reqLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/reqLoanSearch",
data: {v:value},
success: function(returnedData){
$("#reqLoan").html(returnedData.loanTable);
}
});
}
else{
load_all();
}
});
/*
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
*/
//When the trash icon in front of a bank account is clicked on the bank list table (i.e. to delete the account)
$("#reqLoan").on('click', '.deleteLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/delete",
method: "POST",
data: {_uId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData._nv === 1 ? "<a class='pointer'>Undo Delete</a>" : "<i class='fa fa-trash pointer'></i>";
//change the icon
$("#del-"+returnedData._uId).html(newHTML);
}
else{
alert(returnedData.status);
}
});
}
}
});
/*
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
*/
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#reqLoan").on('click', '.approveLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/approve",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Approve</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the deny icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#reqLoan").on('click', '.denyLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/deny",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Deny</a>" : "<i class='fa fa-remove pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//to launch the modal to allow for the editing of bank info
$("#reqLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
});
// ******************************************
// APPROVED LOANS
//reload the list of loans when fields are changed
$("#appLoanListSortBy, #appLoanListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#appLoan").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all($(this).attr('href'));
return false;
});
//handles loan search
$("#appLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/appLoanSearch",
data: {v:value},
success: function(returnedData){
$("#appLoan").html(returnedData.loanTable);
}
});
}
else{
load_all();
}
});
//to launch the modal to allow for the editing of bank info
$("#appLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
//When the deny icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#appLoan").on('click', '.denyLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/deny",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Deny</a>" : "<i class='fa fa-remove pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the revert icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#appLoan").on('click', '.revertLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/revert",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Revert</a>" : "<i class='fa fa-reload pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the grant icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#appLoan").on('click', '.grantLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/grant",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Grant</a>" : "<i class='fa fa-money pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
// ******************************************
// GRANTED LOANS
//reload the list of loans when fields are changed
$("#graLoanListSortBy, #graLoanListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#graLoan").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all($(this).attr('href'));
return false;
});
//handles loan search
$("#graLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/graLoanSearch",
data: {v:value},
success: function(returnedData){
$("#appLoan").html(returnedData.loanTable);
}
});
}
else{
load_all();
}
});
//to launch the modal to allow for the editing of bank info
$("#graLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
//When the revert icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#graLoan").on('click', '.revertLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/revert",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Revert</a>" : "<i class='fa fa-reload pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the clear icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#graLoan").on('click', '.clearLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/clear",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Clear</a>" : "<i class='fa fa-check-circle pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
// ******************************************
// DENIED LOANS
//reload the list of loans when fields are changed
$("#denLoanListSortBy, #denLoanListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#denLoan").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all($(this).attr('href'));
return false;
});
//handles loan search
$("#denLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/denLoanSearch",
data: {v:value},
success: function(returnedData){
$("#denLoan").html(returnedData.loanTable);
}
});
}
else{
load_all();
}
});
//to launch the modal to allow for the editing of bank info
$("#denLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#denLoan").on('click', '.approveLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/approve",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Approve</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#denLoan").on('click', '.revertLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/revert",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Revert</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
// ******************************************
// CLEARED LOANS
//reload the list of loans when fields are changed
$("#cleLoanListSortBy, #cleLoanListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#cleLoan").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
load_all($(this).attr('href'));
return false;
});
//handles loan search
$("#cleLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/cleLoanSearch",
data: {v:value},
success: function(returnedData){
$("#cleLoan").html(returnedData.loanTable);
}
});
}
else{
load_all();
}
});
//to launch the modal to allow for the editing of bank info
$("#cleLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#cleLoan").on('click', '.approveLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/approve",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Approve</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#cleLoan").on('click', '.revertLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/revert",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Revert</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
// CANCELLED LOAN
//When the approve icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#canLoan").on('click', '.approveLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/approve",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Approve</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//When the deny icon in front of a loan is clicked on the bank list table (i.e. to delete the account)
$("#canLoan").on('click', '.denyLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/deny",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Deny</a>" : "<i class='fa fa-remove pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
load_all();
}
else{
alert(returnedData.status);
}
});
}
}
});
//to launch the modal to allow for the editing of bank info
$("#canLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user_id = $(this).siblings(".user_id").html();
var loan_unit_id = $(this).siblings(".loan_unit_id").html();
var loan_amount = parseFloat($(this).siblings(".loan_amount").html());
var collateral_unit_id = $(this).siblings(".collateral_unit_id").html();
var collateral_amount = parseFloat($(this).siblings(".collateral_amount").html());
var duration = parseInt($(this).siblings(".duration").html());
var status_id = $(this).siblings(".status_id").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#loanUnitEdit").val(loan_unit_id);
$("#loanAmountEdit").val(loan_amount);
$("#collateralUnitEdit").val(collateral_unit_id);
$("#collateralAmountEdit").val(collateral_amount);
$("#durationEdit").val(duration);
// prefill dropdowns
$("#status-"+status_id).prop('selected', 'selected');
$("#user-"+user_id).prop('selected', 'selected');
$("#loan_unit-"+loan_unit_id).prop('selected', 'selected');
$("#collateral_unit-"+collateral_unit_id).prop('selected', 'selected');
$("#editLoanModal").modal('show');
});
/*
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
*/
/**
* larl_ = "Load all requested loans"
* @returns {undefined}
*/
function larl_(url){
var orderBy = $("#reqLoanListSortBy").val().split("-")[0];
var orderFormat = $("#reqLoanListSortBy").val().split("-")[1];
var limit = $("#reqLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/larl_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#reqLoan").html(returnedData.loansList);
});
}
/**
* laal_ = "Load all approved loans"
* @returns {undefined}
*/
function laal_(url){
var orderBy = $("#appLoanListSortBy").val().split("-")[0];
var orderFormat = $("#appLoanListSortBy").val().split("-")[1];
var limit = $("#appLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/laal_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#appLoan").html(returnedData.loansList);
});
}
/**
* lagl_ = "Load all approved loans"
* @returns {undefined}
*/
function lagl_(url){
var orderBy = $("#graLoanListSortBy").val().split("-")[0];
var orderFormat = $("#graLoanListSortBy").val().split("-")[1];
var limit = $("#graLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/lagl_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#graLoan").html(returnedData.loansList);
});
}
/**
* ladl_ = "Load all denied loans"
* @returns {undefined}
*/
function ladl_(url){
var orderBy = $("#denLoanListSortBy").val().split("-")[0];
var orderFormat = $("#denLoanListSortBy").val().split("-")[1];
var limit = $("#denLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/ladl_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#denLoan").html(returnedData.loansList);
});
}
/**
* lacl_ = "Load all cleared loans"
* @returns {undefined}
*/
function lacl_(url){
var orderBy = $("#cleLoanListSortBy").val().split("-")[0];
var orderFormat = $("#cleLoanListSortBy").val().split("-")[1];
var limit = $("#cleLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/lacl_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#cleLoan").html(returnedData.loansList);
});
}
/**
* laca_ = "Load all cancelled loans"
* @returns {undefined}
*/
function laca_(url){
var orderBy = $("#canLoanListSortBy").val().split("-")[0];
var orderFormat = $("#canLoanListSortBy").val().split("-")[1];
var limit = $("#canLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/laca_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#canLoan").html(returnedData.loansList);
});
}
function load_all(url) {
larl_();
laal_();
lagl_();
ladl_();
lacl_();
laca_();
} |
import { Link } from "react-router-dom"
import styled from "styled-components/macro"
export const Container = styled.div`
width: 85%;
margin: 50px auto;
background-color: ${(props) => props.theme.blockBg};
box-shadow: 0px 15px 25px rgba(0, 0, 0, 0.35);
border-radius: 5px;
`
export const Inner = styled.div`
display: flex;
flex-direction: column;
padding: 16px 25px;
`
export const Holder = styled.div`
display: flex;
flex-direction: column;
span {
width: 6px;
min-height: 6px;
border-radius: 50%;
background-color: ${(props) => props.theme.title};
align-self: center;
transform: translateY(-1.5px);
}
`
export const InfoHolder = styled.div`
display: flex;
padding-top: 10px;
margin-bottom: 30px;
`
export const Image = styled.img`
max-height: 230px;
object-fit: cover;
`
export const BackHome = styled(Link)`
align-self: flex-start;
text-decoration: none;
font-size: 12px;
line-height: 14px;
opacity: 0.6;
color: ${(props) => props.theme.title};
:hover {
opacity: 1;
text-decoration: underline;
}
`
export const Title = styled.h2`
font-weight: 600;
font-size: 18px;
line-height: 1.3125rem;
margin: 15px 0 0 0;
color: ${(props) => props.theme.title};
`
export const Date = styled.p`
font-size: 0.75rem;
line-height: 14px;
color: ${(props) => props.theme.time};
padding-right: 7.5px;
margin: 0;
`
export const Name = styled.p`
font-size: 0.75rem;
line-height: 14px;
color: ${(props) => props.theme.time};
padding-left: 7.5px;
margin: 0;
`
export const Content = styled.div`
p {
font-size: 0.875rem;
line-height: 21px;
color: ${props => props.theme.title};
}
`
|
import React, { useReducer, useState, useLayoutEffect } from 'react';
import { countReducer, initialState } from './utils/count-reducer';
import styled, { ThemeProvider } from 'styled-components';
import { GlobalStyles } from './utils/global-style';
import { lightTheme, darkTheme } from './utils/themes';
import Row from './components/Row';
import Switch from './components/Switch';
const App = () => {
const [state, dispatch] = useReducer(countReducer, initialState);
const [counts, setCounts] = useState({ rows: 10, cols: 10 });
const [theme, setTheme] = useState(false);
const handleChange = e => {
e.persist();
setCounts(state => ({ ...state, [e.target.name]: Number(e.target.value) }));
};
useLayoutEffect(() => {
dispatch({ type: 'GRID_CHANGE', payload: counts });
}, [counts]);
return (
<ThemeProvider theme={!theme ? lightTheme : darkTheme}>
<>
<GlobalStyles />
<Totals>
<Menu>
<Flexed>
{!state.disabled ? (
<SmallText>{counts.rows} / 20 rows</SmallText>
) : (
<LockedIn>{counts.rows} rows</LockedIn>
)}
<input
disabled={state.disabled}
type="range"
name="rows"
value={counts.rows}
onChange={handleChange}
min="5"
max="20"
/>
</Flexed>
<Flexed>
<SmallText>{!theme ? 'light' : 'dark'}</SmallText>
<Switch isOn={theme} handleToggle={() => setTheme(!theme)} />
</Flexed>
<Flexed>
{!state.disabled ? (
<SmallText>{counts.cols} / 20 cols</SmallText>
) : (
<LockedIn>{counts.cols} cols</LockedIn>
)}
<input
disabled={state.disabled}
type="range"
name="cols"
value={counts.cols}
onChange={handleChange}
min="5"
max="20"
/>
</Flexed>
</Menu>
<Menu>
<h5>
Total Correct: <Correct>{state.correct}</Correct>
</h5>
<h5>Total Guesses: {state.correct + state.incorrect}</h5>
<h5>
Total Wrong: <Incorrect>{state.incorrect}</Incorrect>
</h5>
</Menu>
</Totals>
{state.grid.slice(0, counts.rows).map((row, i) => (
<Row
key={`row-${i}`}
whichRow={i}
colCount={counts.cols}
gameRow={state.gameRow}
tiles={row}
dispatch={dispatch}
/>
))}
</>
</ThemeProvider>
);
};
const Totals = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
border-bottom: 2px solid;
border-color: ${({ theme }) => theme.border};
margin-bottom: 10px;
min-width: 50vw;
`;
const Menu = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
`;
const Flexed = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin-top: 10px;
`;
const SmallText = styled.small`
margin: 0 0 10px 0;
`;
const LockedIn = styled.small`
margin: 0 0 10px 0;
font-weight: 900;
`;
const Correct = styled.span`
color: #2f855a;
`;
const Incorrect = styled.span`
color: #9b2c2c;
`;
export default App;
|
import { trades } from '../fixtures/trades'
import { getTotal, getAvarage, getLowest, getHighest } from '../../calculations/calcR'
test('should return total rMultiple of trades array', () => {
expect(getTotal(trades, 'rMultiple')).toBe(3)
})
test('should return average of rMultiple in trades', () => {
expect(getAvarage(trades, 'rMultiple')).toBe(1)
})
test('should return lowest (-1) of rMultiples in trades object', () => {
expect(getLowest(trades, 'rMultiple')).toBe(-1)
})
test('should return highest rMultiple(2) fof trades array', () => {
expect(getHighest(trades, 'rMultiple')).toBe(2)
}) |
var testCaseList4 = [];
var check;
/**
* find all grammars that have same left hand variable
*
* @param rule
* all grammar rules
* @param key
* Left hand terminal variable
*/
function findSameKey(rule, key) {
var pack = [];
for (var i = 0; i < rule.length; i++) {
if (Object.getOwnPropertyNames(rule[i]) == key) {
pack.push(Object.values(rule[i]));
}
}
return pack;
}
function hasUpperCase(str) {
if (/[A-Z]/.test(str)) {
const regex = /[A-Z]/g;
const found = str.match(regex);
return found[0];
} else {
return '0';
}
}
function insertString(str1, str2, pos) {
let origString = str1;
let stringToAdd = str2;
let indexPosition = pos;
return (newString =
origString.slice(0, indexPosition) +
stringToAdd +
origString.slice(indexPosition));
}
// function falseCases(rule) {
// var res;
// var tempStr;
// do {
// tempStr = stringGenerate();
// res = travGram(rule, tempStr, 0);
// } while (res);
// return tempStr;
// }
// function travGram(rule, tempStr, pos) {
// var keyPackage = findSameKey(rule, key);
// }
function grammarTrav(rule, key) {
var operation = Math.floor(Math.random() * rule.length * 3 + 1);
var keyPackage = findSameKey(rule, key);
var index = Math.floor(Math.random() * keyPackage.length);
var str = keyPackage[index][0];
for (var i = 1; i < operation; i++) {
var letter = hasUpperCase(str);
if (letter != '0') {
keyPackage = findSameKey(rule, letter);
index = Math.floor(Math.random() * keyPackage.length);
str2 = keyPackage[index][0];
str = str.replace(letter, str2);
} else {
break;
}
}
if (hasUpperCase(str) != '0') {
check = false;
// str = falseCases(rule);
} else {
check = true;
}
return str;
}
/**
* random string generator help function
* @return string
*/
function stringGenerate() {
var min = randomStringLength[0];
var max = randomStringLength[1];
var stringLength = Math.round(Math.random() * (max - min)) + min;
for (var a = 0; a < stringLength; a++) {
var pos = Math.round(Math.random() * (containLetters.length - 1));
str += containLetters[pos];
}
return str;
}
function loopkey(testCases, str) {
for (var name in testCases) {
if (Object.keys(testCases[name]) == str) {
return true;
}
}
return false;
}
/**
* add string to testCases
*
* @param testCase
* tastcases
* @param result
* true/false for the current string
* @param str
* string
*/
function gramAdd(testCase, result, str) {
if (testCase.testCases.indexOf(str) == -1) {
if (result) {
if (trueCounter < trueStringLimit && !loopkey(testCaseList4, str)) {
testCaseList4.push(str);
addtoTestCase(str, testCase, 1);
trueCounter++;
}
} else {
if (falseCounter < falseStringLimit && !loopkey(testCaseList4, str)) {
testCaseList4.push(str);
addtoTestCase(str, testCase, 0);
falseCounter++;
}
}
}
}
function addtoTestCase(str, obj, result) {
var current = {};
if (tempFlag != 1) {
var inobj = obj.testCases;
if (result) {
current[str] = true;
inobj[caseCounter] = current;
} else {
current[str] = false;
inobj[caseCounter] = current;
}
} else {
if (result) {
current[str] = true;
obj.testCases[caseCounter] = current;
} else {
current[str] = false;
obj.testCases[caseCounter] = current;
}
}
caseCounter++;
}
/**
* Grammar traverse start funtion.
*
* @param testCase
* object
*/
function graHandler(testCase) {
var rule = testCase.solution;
testCaseList4 = testCase.testCases;
check = false;
var str = grammarTrav(rule, 'S');
gramAdd(testCase, check, str);
return 0;
}
|
//----------------------------------------------------------------------
//
// This source file is part of the Effects project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------
const { effect } = require("../effect");
const { run } = require("../runner");
const Run = effect(
"@builtin:Run",
{
Run: ["effect"]
},
{
Run({ effect }, k, handler) {
run(handler, effect).then(
value => k(null, value),
error => k(error, null)
);
}
}
);
const runner = {
run(effect) {
return Run.Run(effect);
},
runGenerator(gen) {
return Run.Run(function*() {
let { done, value: effect } = gen.next();
while (!done) {
const value = yield effect;
const nextEffect = gen.next(value);
done = nextEffect.done;
effect = nextEffect.value;
}
return effect;
});
}
};
module.exports = {
Run,
runFunction: runner.run,
runEffects: runner.runGenerator
};
|
import React, { Component } from 'react';
import App from '../common/app';
import Constrainer from '../../styles/constrainer';
import Prose from '../../styles/type/prose';
class About extends Component {
render () {
return (
<App pageTitle='About'>
<Constrainer>
<Prose>
<img
src='/assets/graphics/layout/targetting_colored.svg'
alt='Targetting logotype'
width='96'
height='96'
/>
<p>Targetting is an archery scoring application.</p>
<p>Developed by <a href='http://danielfdsilva.com' title="Visit developer's website.">Daniel da Silva</a>. Code is Open Source (MIT license) and available on <a href='https://github.com/danielfdsilva/targetting' title='Visit application github repository'>Github</a>.</p>
</Prose>
</Constrainer>
</App>
);
}
}
export default About;
|
const Discord = require('discord.js');
const data = require('./../data/set1-en_us.json').concat(require('./../data/set2-en_us.json')).concat(require('./../data/set3-en_us.json')).concat(require('./../data/set4-en_us.json'));
module.exports = {
name: 'card',
description: 'Find card image by name',
execute(message, args) {
let cardName = args.join(' ').toLowerCase();
let cards = data.filter(elem => elem.name.toLowerCase() == cardName);
if(cards.length == 0) return message.channel.send("This card does not exist!");
cards.forEach(function(card){
let embed = new Discord.MessageEmbed();
embed.setImage(card.assets[0].gameAbsolutePath);
embed.setTitle(card.name);
embed.setDescription(card.descriptionRaw);
embed.addField("Card Details", createCardString(card));
message.channel.send(embed);
});
}
};
function createCardString(card){
let details = [];
details.push("**Region:** " + card.region);
details.push("**Type:** " + getCardType(card.supertype.toLowerCase(), card.type));
details.push("**Cost:** " + card.cost);
if(card.type == "Unit"){
details.push("**Stats:** " + card.attack + "/" + card.health);
}
if(card.type == "Spell"){
details.push("**Spell speed:** " + card.spellSpeed);
}
if(card.collectible){
details.push("**Crafting cost:** " + getCraftingCost(card.rarity.toLowerCase()));
}
if(card.type == "Unit" && card.keywords.length){
details.push("**Keywords:** " + card.keywords.join(', '));
}
details.push("**Is collectible:** " + (card.collectible ? "Yes" : "No"));
return details.join('\n');
}
function getCraftingCost(rarity){
switch(rarity){
case "common": return 100;
case "rare": return 300;
case "epic": return 1200;
case "champion": return 3000;
}
}
function getCardType(rarity, type){
if(rarity == "champion" && type == "Unit") return "Champion";
return type;
} |
import { all, takeLatest } from 'redux-saga/effects';
import { ToolsTypes } from '../ducks/tools';
import { getToolsRequest, addToolRequest, deleteToolRequest } from './tools';
export default function* rootSaga() {
yield all([
takeLatest(ToolsTypes.GET_TOOLS_REQUEST, getToolsRequest),
takeLatest(ToolsTypes.ADD_TOOL_REQUEST, addToolRequest),
takeLatest(ToolsTypes.DELETE_TOOL_REQUEST, deleteToolRequest),
]);
}
|
import React from "react";
import { shallow, mount } from "enzyme";
import StatusSection from "./status-section";
describe("Renders Status Section", () => {
it("shallow renders Status Section", () => {
const myGuesses = [2];
shallow(<StatusSection guesses={myGuesses} />);
});
it("renders correct number of guesses", () => {
const moreMyGuesses = [9, 6, 50];
const wrapper = shallow(<StatusSection guesses={moreMyGuesses} />);
// console.log("wrapper", wrapper.html());
// specificity in expect and the assertion
expect(wrapper.html()).toContain('<span id="count">3</span>');
});
});
|
export const me = new Map()
.set('#firstName','Brice')
.set( '#lastName','Danvidé')
.set('#adresse','Paris')
.set('#email','brice_danvide@hotmail.fr')
.set ('#tel','0641664106')
.set('#jobTitle1','BusinessDevelopmentManagerSurface')
.set('#jobTitle2','ResponsableSponsoringTECHDAYS2015')
.set('#jobTitle3','ChannelDevelopmentManagerSMS&P/SMB')
.set('#jobTitle4','TechnicalSalesSpecialisteSMS&P/CTMCAM')
.set('#jobTitle5','InsideTerritoryManagerSMS&P/CTMSud-Ouest')
.set('#jobTitle6','CommercialSédentaireSecteurBancaire')
.set('#competence1','Html')
.set('#competence2','Css3')
.set('#competence3','Javascript')
.set('#competence4','React Js')
.set('#competence5','Angular 6')
.set('#competence6','Nodes Js')
.set('#competence7','GitHub')
.set('#competence8','Adobe Creative Suite')
.set('#competence9','Anglais Professionnel')
.set('#formationTitle1','Formation intensive developpeur front-end creation d application web avec Angular/React')
.set('#formationTitle2','Communication visuelle, Design produit, Architecture d intérieur, dessin')
.set('#formationTitle3','Options Action et Communication Commerciale')
;
|
import {generateNumber} from "./NumberGenerator.js";
export function generatePesel(birthDate) {
let pesel = insertBirthDateToPesel(birthDate);
pesel += generateNumber(0, 9, 5).join("");
return pesel;
}
function insertBirthDateToPesel(birthDate) {
let pesel = "";
if(birthDate.day.toString().length>1) {
pesel += birthDate.day;
} else {
pesel += '0' + birthDate.day;
}
if(birthDate.month.toString().length>1) {
pesel += birthDate.month;
} else {
pesel += '0' + birthDate.month;
}
pesel += birthDate.year;
return pesel;
} |
import React from 'react';
import {ReactComponent as IconLogout} from './../images/log-out.svg'
import Boton from './Boton'
import {auth} from './../firebase/firebaseConfig'
import {useHistory} from 'react-router-dom'
const BtnLogout = () => {
const history = useHistory()
const logout = () => {
auth.signOut().then(()=>{
history.push('/login')
})
.catch(err=>{
console.log(err);
})
}
return (
<Boton iconoGrande as="button" onClick={logout}>
<IconLogout/>
</Boton>
);
}
export default BtnLogout; |
'use strict';
const TestDiscovery = require('./helper/test-discovery');
const TestCase = require('./helper/test-case');
const PrismLoader = require('./helper/prism-loader');
const { BFS, BFSPathToPrismTokenPath } = require('./helper/util');
const { assert } = require('chai');
const components = require('../components.json');
const ALL_LANGUAGES = [...Object.keys(components.languages).filter(k => k !== 'meta')];
describe('Pattern test coverage', function () {
/**
* @type {Map<string, PatternData>}
* @typedef PatternData
* @property {RegExp} pattern
* @property {string} language
* @property {Set<string>} from
* @property {RegExpExecArray[]} matches
*/
const patterns = new Map();
/**
* @param {string | string[]} languages
* @returns {import("./helper/prism-loader").Prism}
*/
function createInstance(languages) {
const Prism = PrismLoader.createInstance(languages);
BFS(Prism.languages, (path, object) => {
const { key, value } = path[path.length - 1];
const tokenPath = BFSPathToPrismTokenPath(path);
if (Object.prototype.toString.call(value) == '[object RegExp]') {
const regex = makeGlobal(value);
object[key] = regex;
const patternKey = String(regex);
let data = patterns.get(patternKey);
if (!data) {
data = {
pattern: regex,
language: path[1].key,
from: new Set([tokenPath]),
matches: []
};
patterns.set(patternKey, data);
} else {
data.from.add(tokenPath);
}
regex.exec = string => {
let match = RegExp.prototype.exec.call(regex, string);
if (match) {
data.matches.push(match);
}
return match;
};
}
});
return Prism;
}
describe('Register all patterns', function () {
it('all', function () {
this.slow(10 * 1000);
// This will cause ALL regexes of Prism to be registered in the patterns map.
// (Languages that don't have any tests can't be caught otherwise.)
createInstance(ALL_LANGUAGES);
});
});
describe('Run all language tests', function () {
// define tests for all tests in all languages in the test suite
for (const [languageIdentifier, files] of TestDiscovery.loadAllTests()) {
it(languageIdentifier, function () {
this.timeout(10 * 1000);
for (const filePath of files) {
try {
TestCase.run({
languageIdentifier,
filePath,
updateMode: 'none',
createInstance
});
} catch (error) {
// we don't case about whether the test succeeds,
// we just want to gather usage data
}
}
});
}
});
describe('Coverage', function () {
for (const language of ALL_LANGUAGES) {
describe(language, function () {
it(`- should cover all patterns`, function () {
const untested = getAllOf(language).filter(d => d.matches.length === 0);
if (untested.length === 0) {
return;
}
const problems = untested.map(data => {
return formatProblem(data, [
'This pattern is completely untested. Add test files that match this pattern.'
]);
});
assert.fail([
`${problems.length} pattern(s) are untested:\n`
+ 'You can learn more about writing tests at https://prismjs.com/test-suite.html#writing-tests',
...problems
].join('\n\n'));
});
it(`- should exhaustively cover all keywords in keyword lists`, function () {
const problems = [];
for (const data of getAllOf(language)) {
if (data.matches.length === 0) {
// don't report the same pattern twice
continue;
}
const keywords = getKeywordList(data.pattern);
if (!keywords) {
continue;
}
const keywordCount = keywords.size;
data.matches.forEach(([m]) => {
if (data.pattern.ignoreCase) {
m = m.toUpperCase();
}
keywords.delete(m);
});
if (keywords.size > 0) {
problems.push(formatProblem(data, [
`Add test files to test all keywords. The following keywords (${keywords.size}/${keywordCount}) are untested:`,
...[...keywords].map(k => ` ${k}`)
]));
}
}
if (problems.length === 0) {
return;
}
assert.fail([
`${problems.length} keyword list(s) are not exhaustively tested:\n`
+ 'You can learn more about writing tests at https://prismjs.com/test-suite.html#writing-tests',
...problems
].join('\n\n'));
});
});
}
});
/**
* @param {string} language
* @returns {PatternData[]}
*/
function getAllOf(language) {
return [...patterns.values()].filter(d => d.language === language);
}
/**
* @param {string} string
* @param {number} maxLength
* @returns {string}
*/
function short(string, maxLength) {
if (string.length > maxLength) {
return string.slice(0, maxLength - 1) + '…';
} else {
return string;
}
}
/**
* If the given pattern string describes a keyword list, all keyword will be returned. Otherwise, `null` will be
* returned.
*
* @param {RegExp} pattern
* @returns {Set<string> | null}
*/
function getKeywordList(pattern) {
// Right now, only keyword lists of the form /\b(?:foo|bar)\b/ are supported.
// In the future, we might want to convert these regexes to NFAs and iterate all words to cover more complex
// keyword lists and even operator and punctuation lists.
let source = pattern.source.replace(/^\\b|\\b$/g, '');
if (source.startsWith('(?:') && source.endsWith(')')) {
source = source.slice('(?:'.length, source.length - ')'.length);
}
if (/^\w+(?:\|\w+)*$/.test(source)) {
if (pattern.ignoreCase) {
source = source.toUpperCase();
}
return new Set(source.split(/\|/g));
} else {
return null;
}
}
/**
* @param {Iterable<string>} occurrences
* @returns {{ origin: string; otherOccurrences: string[] }}
*/
function splitOccurrences(occurrences) {
const all = [...occurrences];
return {
origin: all[0],
otherOccurrences: all.slice(1),
};
}
/**
* @param {PatternData} data
* @param {string[]} messageLines
* @returns {string}
*/
function formatProblem(data, messageLines) {
const { origin, otherOccurrences } = splitOccurrences(data.from);
const lines = [
`${origin}:`,
short(String(data.pattern), 100),
'',
...messageLines,
];
if (otherOccurrences.length) {
lines.push(
'',
'Other occurrences of this pattern:',
...otherOccurrences.map(o => `- ${o}`)
);
}
return lines.join('\n ');
}
});
/**
* @param {RegExp} regex
* @returns {RegExp}
*/
function makeGlobal(regex) {
if (regex.global) {
return regex;
} else {
return RegExp(regex.source, regex.flags + 'g');
}
}
|
import React, { useState } from "react";
import styled from "styled-components";
import hat from "../assets/mineur_chapeau.png";
import minor from "../assets/mineur.png";
import Infos from "./molecules/Infos";
import gsap from "gsap";
const Mineur = ({ partData }) => {
const [display, setDisplay] = useState(false);
const minorIshover = () => {
if (display) {
gsap.to(".minorBg", { filter: "brightness(1)" });
} else {
gsap.to(".minorBg", { filter: "brightness(1.6)" });
}
setDisplay(!display);
};
return (
<MineurContainer>
<MineurBody display={display}>
<Minor src={minor} />
<Hat src={hat} />
</MineurBody>
{partData && (
<Infos
setIsAnimated={minorIshover}
title={partData[1]?.cards?.[0].title}
content={partData[1]?.cards?.[0].content}
bottom="8"
left="103"
leftCard="-1500"
bottomCard="-100"
/>
)}
</MineurContainer>
);
};
const MineurContainer = styled.div`
position: absolute;
top: 267px;
left: 1111px;
transform: scale(1.4);
width: 300px;
height: 300px;
`;
const MineurBody = styled.div`
position: relative;
display: ${({ display }) => (display ? "block" : "none")};
`;
const Hat = styled.img`
position: absolute;
top: -153px;
left: 375px;
`;
const Minor = styled.img`
position: absolute;
top: -125px;
left: 277px;
`;
export default Mineur;
|
function dataHandling2(input) {
input.splice(1,2,'Roman Alamsyah Elsharawy','Provinsi Bandar Lampung')
input.splice(4,1,'Pria','SMA Internasional Metro')
console.log(input)
var tanggal = input[3].split('/')
var tanggal2 = tanggal.join('-')
// return tanggal2
// console.log(tanggal2);
// return tanggal[1]
var bulan = tanggal[1]
switch (bulan) {
case '01': {console.log('Januari'); break;}
case '02': {console.log('Februari'); break;}
case '03': {console.log('Maret'); break;}
case '04': {console.log('April'); break;}
case '05': {console.log('Mei'); break;}
case '06': {console.log('Juni'); break;}
case '07': {console.log('Juli'); break;}
case '08': {console.log('Agustus'); break;}
case '09': {console.log('September'); break;}
case '10': {console.log('Oktober'); break;}
case '11': {console.log('November'); break;}
case '12': {console.log('Desember'); break;}
}
// tanggal.parseInt()
tanggal.sort(function(value1, value2) { return Number(value1) < Number(value2) })
console.log(tanggal);
console.log(tanggal2);
return input[1].slice(0,14)
// return input[1]
// return tanggal
}
console.log(dataHandling2(["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"] ));
|
import { ref, value } from '@dws/muster';
import { operation, runScenario } from '@dws/muster/test';
import createGraph from './index';
import loadItems from '../utils/load-items';
jest.mock('../utils/load-items.js', () => jest.fn(() => []));
describe('Testing a list and its operations', () => {
runScenario({
description: 'GIVEN a graph with four completed and three uncompleted todos',
before() {
loadItems.mockReturnValue([
{ id: 1, label: 'Item 1', completed: true },
{ id: 2, label: 'Item 2', completed: true },
{ id: 3, label: 'Item 3', completed: true },
{ id: 4, label: 'Item 4', completed: true },
{ id: 5, label: 'Item 5', completed: false },
{ id: 6, label: 'Item 6', completed: false },
{ id: 7, label: 'Item 7', completed: false },
]);
},
graph: createGraph,
operations: [
operation({
description: 'WHEN getting the itemCount',
input: ref('itemCount'),
expected: value(7),
}),
operation({
description: 'WHEN getting the remainingCount',
input: ref('remainingCount'),
expected: value(3),
}),
],
});
});
|
import Todo from '../models/Todo.model';
export async function postTodo(todo) {
let newTodo;
try {
newTodo = await Todo.query()
.insertWithRelated(todo);
} catch (err) {
return Promise.reject(err);
}
return getTodos();
}
export async function getTodos() {
let todos;
try {
todos = await Todo.query();
} catch (err) {
return Promise.reject(err);
}
if (!todos) return Promise.reject('no todos');
return Promise.resolve(todos);
}
export async function patchTodo(todoId, todoData) {
const todo = await getTodo(todoId);
await todo.$query().update(todoData);
return getTodos();
}
export async function deleteTodo(todoId) {
const todo = await getTodo(todoId);
await todo.$query().delete();
return getTodos();
}
export async function getTodo(todoId) {
const todo = await Todo.query().findById(todoId);
return Promise.resolve(todo);
}
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProjectSchema = new Schema({
language: { type: String, required: true },
title: { type: String, required: true },
link: { type: String, required: true },
image: { type: String, required: true },
// completed: (default to false, true would be completed and data would go into the completed bar in the graph)
});
const Project = mongoose.model("Project", ProjectSchema);
module.exports = Project;
|
#pragma strict
var sceneScript:SceneScript;
var degreeToTurn:float;
var FLIP_SPEED:float;
var totalScaleAmount:float;
var totalEnlargeAmount:float;
var SCALE_SPEED:float;
var SCALE_TARGET_AMOUNT:float;
var MATCH_AMOUNT:float;
var flippingDirection:Vector3;
var CANVAS_CHILD:int;
var TEXT_CHILD:int;
var position:int;
var textChanged:boolean;
var textObject:UnityEngine.UI.Text;
var number:int;
var TIME_UP_SCALE_AMOUNT:float;
var totalScaleAmountForTime:float;
function Start () {
CANVAS_CHILD = 0;
TEXT_CHILD = 0;
sceneScript = Camera.main.GetComponent(SceneScript);
FLIP_SPEED = 200*Time.deltaTime;
SCALE_SPEED = 0.15*Time.deltaTime*3;
SCALE_TARGET_AMOUNT = 0.05;
MATCH_AMOUNT = 0.05*3;
flippingDirection = Vector3(0,1,0);
degreeToTurn = 0;
totalScaleAmount = 0;
totalEnlargeAmount = 0;
textChanged = true;
number = 15;
TIME_UP_SCALE_AMOUNT = 0.3;
totalScaleAmountForTime = 0;
}
function Update () {
// applyCurveValue();
if(!sceneScript.isTilting && !sceneScript.isScaling) flipping();
if(!sceneScript.inUserRotation){
shrink();
enlarge();
}
// shrinkForTime();
}
function flipping(){
if(!sceneScript.inUserRotation && degreeToTurn>0){
if(degreeToTurn<FLIP_SPEED) transform.Rotate(flippingDirection, degreeToTurn,Space.World);
else transform.Rotate(flippingDirection, FLIP_SPEED, Space.World);
degreeToTurn -= FLIP_SPEED;
if(!textChanged && degreeToTurn<=90) {
textChanged = true;
transform.Rotate(flippingDirection, 180 ,Space.World);
updateText();
}
if(degreeToTurn<=0) sceneScript.scoreBoardInRotation = false;
}
}
function flip(){
// sceneScript.inFlip = true;
textChanged = false;
degreeToTurn = 180;
}
function shrink(){
if(totalScaleAmount > 0){
if(totalScaleAmount < SCALE_SPEED) scale(-totalScaleAmount);
else scale(-SCALE_SPEED);
totalScaleAmount -= SCALE_SPEED;
if(totalScaleAmount<=0) totalEnlargeAmount = SCALE_TARGET_AMOUNT;
}
// if(number==0) Debug.Log("tt in shrink: "+totalScaleAmount);
}
function enlarge(){
if(totalEnlargeAmount > 0){
if(totalEnlargeAmount < SCALE_SPEED) scale(totalEnlargeAmount);
else scale(SCALE_SPEED);
totalEnlargeAmount -= SCALE_SPEED;
if(totalEnlargeAmount <= 0) sceneScript.isScaling = false;
}
}
function scale(scaleAmount:float){
transform.localScale += Vector3(scaleAmount,scaleAmount, scaleAmount);
}
function triggerMatchAnimation(){
SCALE_TARGET_AMOUNT = MATCH_AMOUNT;
// sceneScript.isScaling = true;
totalScaleAmount = SCALE_TARGET_AMOUNT;
}
function updateText(){
// var textObject:UnityEngine.UI.Text = transform.GetChild(CANVAS_CHILD).GetChild(TEXT_CHILD).gameObject;
// Debug.Log(textObject);
var newNum = sceneScript.scores;
updateTextWithValue(newNum);
}
function updateTextWithValue(newNum:int){
for(var i:int=0; i<position;i++){
newNum /= 10;
}
newNum = newNum%10;
textObject.text = newNum + "";
}
// function timeUp(){
// totalScaleAmountForTime = TIME_UP_SCALE_AMOUNT;
// }
// function shrinkForTime(){
// if(totalScaleAmountForTime > 0){
// if(totalScaleAmountForTime < SCALE_SPEED) scale(-totalScaleAmountForTime);
// else scale(-SCALE_SPEED);
// totalScaleAmountForTime -= SCALE_SPEED;
// // if(totalScaleAmount<=0) totalEnlargeAmount = SCALE_TARGET_AMOUNT;
// }
// // if(number==0) Debug.Log("tt in shrink: "+totalScaleAmount);
// }
// function applyCurveValue(){
// transform.localScale = new Vector3(ORIGINAL_SCALE-curveValue*SHRINK_AMOUNT, ORIGINAL_SCALE-curveValue*SHRINK_AMOUNT, ORIGINAL_SCALE-curveValue*SHRINK_AMOUNT);
// }
|
P.views.exercises.priv.NoImages = P.views.Item.extend({
templateId: 'exercise.priv.noimages'
}); |
import React from 'react';
import { AlertWrapper, AlertItemBox } from './style';
import { IconView } from '../Button';
export const AlertBox = ({ children, style }) => {
return <AlertWrapper style={style}>{children}</AlertWrapper>;
};
export const AlertItem = ({
children,
style,
nameIcon,
iconSize,
iconStyle,
color,
}) => {
return (
<AlertItemBox style={style}>
<IconView
nameIcon={nameIcon}
size={iconSize}
color={color}
iconStyle={[iconStyle, { alignSelf: 'center', paddingRight: 15 }]}
/>
{children}
</AlertItemBox>
);
};
|
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
AsyncStorage,
StatusBar,
ImageBackground,
Dimensions,
} from 'react-native';
import firebase from 'react-native-firebase';
export default class OptionsScreen extends Component {
static navigationOptions = {
headerShown: false,
}
state = {
uid: ''
}
componentDidMount() {
var firebaseConfig = {
apiKey: "AIzaSyASl8eIzspE9bnPxe8HlaMJdlA3xtz1IS8",
authDomain: "appintmentbooking.firebaseapp.com",
databaseURL: "https://appintmentbooking.firebaseio.com",
projectId: "appintmentbooking",
storageBucket: "appintmentbooking.appspot.com",
messagingSenderId: "512449088784",
appId: "1:512449088784:web:7f533ae4d40e1508bfa995",
measurementId: "G-TY5RFBYT23"
};
// Initialize Firebase
// if (!firebase.apps.length) {
// firebase.initializeApp(firebaseConfig);
// }
// AsyncStorage.getItem('uid', (err, result) => {
// if (result != null) {
// AsyncStorage.getItem('type', (err, result) => {
// if (result != null) {
// if (result=='doctor') {
// this.props.navigation.navigate('DoctorHome')
// }
// else if (result == 'patient') {
// this.props.navigation.navigate('PatientHome');
// }
// else {
// this.props.navigation.navigate('Options screen')
// }
// }
// })
// }
// })
}
render() {
return (
<ImageBackground
imageStyle={{ opacity: 0.4 }}
style={styles.body}
source={require('./images/home.jpg')}>
<View style={{ flex: 1, justifyContent: 'center', marginTop: 250, alignItems: 'center' }}>
<StatusBar backgroundColor='#F9ECAD' barStyle='dark-content' />
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('DoctorOptions')
}}
style={{
backgroundColor: '#F9ECAD',
height: 40,
width: 250,
justifyContent: 'center',
borderRadius: 5
}}>
<Text style={{
color: 'white',
alignSelf: 'center',
fontWeight: 'bold'
}}>Doctor Account</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('PatientOptions')
}}
style={{
// backgroundColor: '#ff6666',
borderColor: '#f9ecad',
borderWidth: 3,
height: 40,
marginTop: 20,
width: 250,
justifyContent: 'center',
borderRadius: 5
}}>
<Text style={{
color: '#f9ecad',
alignSelf: 'center',
fontWeight: 'bold',
fontSize: 15
}}>Patient Account</Text>
</TouchableOpacity>
</View>
</ImageBackground>
)
}
}
const styles = StyleSheet.create({
body: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height - 20,
}
}) |
//Create DB and connection here
const mongoose = require('mongoose');
const mongoUri = 'mongodb://ashcoca:12345a@ds157923.mlab.com:57923/restingdb';
const db = mongoose.connect(mongoUri, { useNewUrlParser: true });
module.exports = db; |
// @flow
import {StyleSheet} from 'react-native';
import {themeTextStyle} from '../../constants/text';
const styles = StyleSheet.create({
root: {
backgroundColor: 'white',
minHeight: '100%',
},
title: themeTextStyle.SCHEDULE_DETAIL_TALK_TITLE,
section: {
paddingHorizontal: 15,
marginVertical: 10,
},
scheduleDetailContainer: {
flex: 1,
},
scheduleDetailSection: {
flexDirection: 'row',
marginBottom: 10,
},
scheduleDetailSectionField: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
},
scheduleDetailIcon: {
marginRight: 10,
},
textStage: {
fontSize: 12,
},
scheduleDetail: {
marginVertical: 0,
paddingHorizontal: 0,
paddingTop: 20,
},
bookmarkContainer: {
position: 'absolute',
opacity: 0,
right: 10,
zIndex: 2,
},
});
export default styles;
|
import axios from 'axios';
import Config from '../config';
import { getItem, getItemStr, removeItem } from '../common/js/util';
import { notification } from 'antd';
const instance = axios.create({
baseURL: Config.baseURL,
timeout: 60000,
headers: {
Sign: getItemStr('uuid'),
},
});
instance.interceptors.request.use(
config => {
/* --- 请求拦截处理 --- */
const { url } = config;
if (url === 'Captcha' || url === 'Login') return config;
const user = getItem('qxkz_info');
const token = user ? user.token : '';
config.headers.Authorization = `Bearer ${token}`;
return config;
},
err => {
return Promise.reject(err);
}
);
instance.interceptors.response.use(
res => {
if (res.status !== 200) {
return Promise.reject(res);
}
/**
* --- 响应拦截器处理 ---
* 1. 判断请求是否成功
* 2. 判断返回数据是否为空
* 3. 判断是否有权限调用该接口,无则重定向
*/
return res;
},
err => {
const res = err.response;
const message = err.message ? err.message : '出错了!';
console.log(err);
if (res && res.status === 401) {
removeItem('qxkz_info');
removeItem('uuid');
removeItem('purchase_info');
/**
* TODO:
* 跳转至登录页
*/
return Promise.reject(err);
}
notification.error({
message: '提示',
description: message,
});
return Promise.reject(err);
}
);
export const createGetAPI = (url, config) => {
config = config || {};
return instance.get(url, {
params: config,
});
};
export const createPostAPI = (url, config) => {
config = config || {};
return instance.post(url, config);
};
/**
* 清除缓存
* @param {Object} config
*/
export const ClearCache = config => {
const url = 'ClearCache';
return createGetAPI(url);
};
/**
* 获取菜单树
* @param {Object} config
*/
export const GetTreelist = config => {
const url = config ? config : 'module/treelist';
return createGetAPI(url);
};
/**
* 获取菜单树
* @param {Object} config
*/
export const GetTreelistNoSource = config => {
const url = 'module/treelist/hideResource';
return createGetAPI(url);
};
export default instance;
|
const logger = require('../logger')(__filename)
const scrapSection = require('../scrapSection')
const SEE_MORE_SELECTOR = 'a[data-control-name=contact_see_more]'
const CLOSE_MODAL_SELECTOR = '.artdeco-modal__dismiss';
const template = {
selector: '.pv-contact-info__contact-type',
fields: {
type: 'header',
values: {
selector: '.pv-contact-info__ci-container',
isMultipleFields: true
},
links: {
selector: 'a',
attribute: 'href',
isMultipleFields: true
}
}
}
const getContactInfo = async(page) => {
await page.waitFor(SEE_MORE_SELECTOR, { timeout: 2000 })
.catch(() => {
logger.warn('contact-info', 'selector not found')
return {}
})
const element = await page.$(SEE_MORE_SELECTOR)
if(element){
await element.click()
const contactInfoIndicatorSelector = '#pv-contact-info'
await page.waitFor(contactInfoIndicatorSelector, { timeout: 5000 })
.catch(() => {
logger.warn('contact info was not found')
})
const contactInfo = await scrapSection(page, template)
const closeButton = await page.$(CLOSE_MODAL_SELECTOR)
if(closeButton)
await closeButton.click()
return contactInfo
}
}
module.exports = getContactInfo
|
Tennisify.Views.Modal = Backbone.View.extend({
template: JST['modal'],
render: function () {
var content = this.template();
this.$el.html(content);
return this;
},
events: {
"hide.bs.modal #modal": "routeBack"
},
routeBack: function () {
routeBack();
},
});
|
import React, { Component } from "react";
import { connect } from "react-redux";
import * as actions from "../actions/auth-action";
import { compose } from "redux"
import { Link } from "react-router-dom";
class Logout extends Component {
handleLogout() {
this.props.logout()
};
render() {
return (
<li class="nav--list--item">
<Link onClick={this.handleLogout.bind(this)} to="/">
Logout
</Link>
</li>
);
}
}
export default connect(null, actions)(Logout);
|
import React, { Component, createRef } from 'react'
import {
View,
Text,
Image,
Linking,
Platform,
Animated,
findNodeHandle,
TouchableHighlight,
} from 'react-native'
import _ from 'lodash'
import { connect } from 'react-redux'
import { get, isEmpty } from 'lodash'
import SafeAreaView from 'react-native-safe-area-view'
import { BlurView } from '@react-native-community/blur'
import MapView, { Marker, Callout } from 'react-native-maps'
import { project } from '@constants'
import { getNavigator } from '@configs/router'
import { IconButton, Button } from '@components'
import { clearGarden, getGardenList } from '@redux/garden'
import styles from './Map.style'
import { Colors } from '@constants'
import { garden } from '@redux'
const BACK_ICON = require('@images/icon/left-arrow.png')
const LEAF_ICON = require('@images/icon/leaf-color.png')
const DEFAULT_GARDEN_IMAGE = require('@images/cards/card-graden.jpg')
const DELTA = 0.009
const initialRegion = {
latitude: 20.045159,
longitude: 99.901946,
latitudeDelta: DELTA,
longitudeDelta: DELTA,
}
class Map extends Component {
static defaultProps = {
gardens: [],
getGardenList() { },
clearGarden() { },
}
constructor(props) {
super(props)
this.mapRef = createRef()
this.blurRef = null
this.state = {
currentRegion: initialRegion,
selectedGarden: {},
isShowed: false,
}
this.animateGardenDescription = new Animated.Value(0)
}
componentDidMount() {
this.props.getGardenList()
this.blurRef = findNodeHandle(this.mapRef.current)
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.gardens !== this.props.gardens && !isEmpty(this.props.gardens)) {
const garden = get(this.props.gardens, '0', initialRegion)
this.onRegionChange({
latitude: _.get(garden, 'location.lat', 0),
longitude: _.get(garden, 'location.long', 0),
latitudeDelta: DELTA,
longitudeDelta: DELTA,
})
}
if (prevState.isShowed !== this.state.isShowed) {
if (this.state.isShowed) {
Animated.spring(this.animateGardenDescription, { toValue: 1 }).start()
} else {
Animated.spring(this.animateGardenDescription, { toValue: 0 }).start()
}
}
}
onPressBack = () => {
this.props.navigator.pop()
}
onPressToGarden = ({ name, _id }) => {
getNavigator().push('SubCategory', { gardenName: name, gardenId: _id }, { animation: 'right' })
}
onPressToDirection = ({ name, lat, lng }) => {
// TODO: Temporary usage
const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
const latLng = `${lat},${lng}`;
const label = name;
const url = Platform.select({
ios: `${scheme}${label}@${latLng}`,
android: `${scheme}${latLng}(${label})`
});
Linking.openURL(url);
}
onPressMarker = (garden) => {
this.setState({
selectedGarden: garden,
isShowed: true,
}, () => {
const latitude = _.get(garden, 'location.lat', 0)
const longitude = _.get(garden, 'location.long', 0)
this.onRegionChange({
latitude,
longitude,
latitudeDelta: DELTA,
longitudeDelta: DELTA
})
})
}
onRegionChange = (region) => {
this.mapRef.current.animateToRegion(region, 350)
}
onPressClose = () => {
this.setState({ isShowed: false })
}
renderGardenMarker = () => this.props.gardens.map((garden, index) => {
const latitude = _.get(garden, 'location.lat', 0)
const longitude = _.get(garden, 'location.long', 0)
return (
<Marker
key={`${index}-marker`}
coordinate={{ latitude, longitude }}>
<TouchableHighlight
style={styles.markerWrapper}
underlayColor={Colors.BLACK_TRANSPARENT_LIGHTNEST}
onPress={() => this.onPressMarker(garden)} >
<Image source={LEAF_ICON} style={styles.marker} />
</TouchableHighlight>
<Callout tooltip>
<View style={styles.tooltipWrapper}>
<View style={styles.tooltip}>
<Text style={styles.tooltipText}>{garden.name}</Text>
</View>
<View style={styles.triangle} />
</View>
</Callout>
</Marker>
)
})
render() {
const GardenMarker = this.renderGardenMarker
const { selectedGarden, currentRegion } = this.state
const displayImageUri = get(selectedGarden, 'images.0', '')
const latitude = _.get(selectedGarden, 'location.lat', 0)
const longitude = _.get(selectedGarden, 'location.long', 0)
const showImage = !isEmpty(displayImageUri) ? { uri: displayImageUri } : DEFAULT_GARDEN_IMAGE
const translateY = this.animateGardenDescription.interpolate({
inputRange: [0, 1],
outputRange: [400, 50]
})
return (
<SafeAreaView
forceInset={{ vertical: 'always', bottom: 'never' }}
style={styles.container}>
<View style={styles.headerWrapper}>
<IconButton
icon={BACK_ICON}
tintColor={Colors.BLACK}
iconSize={20}
onPress={this.onPressBack} />
<Text style={styles.sceneText}>Map</Text>
</View>
<View style={styles.mapContainer}>
<MapView
mapType="satellite"
style={styles.map}
ref={this.mapRef}
initialRegion={currentRegion} >
<GardenMarker />
</MapView>
</View>
<Animated.View style={[
styles.descriptionContainer,
{ transform: [{ translateY }] }]}>
<BlurView
viewRef={this.blurRef}
style={styles.blurComponent}
blurType='light'
blurAmount={20} />
<View style={styles.descriptionHeaderWrapper}>
<View style={styles.descriptionWrapper}>
<Text style={styles.descriptionTitle}>{selectedGarden.name}</Text>
<Text style={styles.descriptionTitleEN}>{selectedGarden.nameEN}</Text>
</View>
<View style={styles.descriptionCloseWrapper}>
<IconButton onPress={this.onPressClose} />
</View>
</View>
<View style={styles.actionContainer}>
<View style={styles.actionWrapper}>
<Button
onPress={() => this.onPressToDirection({ name: selectedGarden.name, lat: latitude, lng: longitude })}
borderColor={Colors.TRANSPARENT}
backgroundColor={Colors.BLACK_TRANSPARENT_LIGHTNESTED}
text="Directions" />
</View>
<View style={styles.actionWrapper}>
<Button
onPress={() => this.onPressToGarden({ name: selectedGarden.name, _id: selectedGarden._id })}
text="Garden" />
</View>
</View>
<View style={styles.gardenImageContainer}>
<Image resizeMode="cover" source={showImage} style={styles.gardenImage} />
</View>
</Animated.View>
</SafeAreaView>
)
}
}
const mapStateToProps = state => ({
gardens: state[project.name].garden.list
})
const mapDispatchToProps = {
clearGarden,
getGardenList,
}
export default connect(mapStateToProps, mapDispatchToProps)(Map) |
$(document).ready();
//These objects are my four factions, all of thes values are placeholders until I work out the game mechanics
var $NCR = $("#NCR");
var $BoS = $("#BoS");
var $Khans = $("#Khans");
var $Legion = $("#Legion");
var NCR = {
HP: 120,
attack: 6,
base_attack: 6,
counter_attack: 15,
name: "New California Republic",
div: $("#NCR")
}
var BoS = {
HP: 100,
attack: 8,
base_attack: 8,
counter_attack: 10,
name: "Brotherhood of Steel",
div: $("#BoS")
}
var Khans = {
HP: 150,
attack: 4,
base_attack: 4,
counter_attack: 20,
name: "The Great Khans",
div: $("#Khans")
}
var Legion = {
HP: 180,
attack: 2,
base_attack: 2,
counter_attack: 25,
name: "Caesar's Legion",
div: $("#Legion")
}
//When the player clicks on the faction, I want to store that faction as "player"
var player = {};
//When we click on the faction we want to attack, I'm going to have that enemy stored as "defender"
var defender = {};
var enemies = [];
var gamestarted = false;
//The game starts on click, when the player chooses a faction
$("#gamemaster").text("Select your faction to begin!")
var choosefaction = function () {
//if (gamestarted = false) {
$NCR.on("click", function () {
player = NCR;
enemies = [BoS, Khans, Legion];
console.log(player.name);
console.log(enemies);
$("#gamemaster").text("Pick a faction to go to war with");
gamestarted = true;
})
$BoS.on("click", function () {
player = BoS;
enemies = [NCR, Khans, Legion];
console.log(player.name);
console.log(enemies);
$("#gamemaster").text("Pick a faction to go to war with");
gamestarted = true;
})
$Khans.on("click", function () {
player = Khans;
enemies = [NCR, BoS, Legion];
console.log(player.name);
console.log(enemies);
$("#gamemaster").text("Pick a faction to go to war with");
gamestarted = true;
})
$Legion.on("click", function () {
player = Legion;
enemies = [NCR, BoS, Khans];
console.log(player.name);
console.log(enemies);
$("#gamemaster").text("Pick a faction to go to war with");
gamestarted = true;
})
}
//else {
player.div.detach().appendTo("#player");
for (var i = 0; i < enemies.length; i++) {
enemies[i].div.detach().appendTo("#enemies");
}
//}
//}
//After choosing your faction, we need to set all other factions as enemies
//maybe add that as an attribute, then set different style rules for said enemies?
choosefaction();
//I need a better way to track damage.
//var attack = function () {
// player.HP - defender.counter_attack;
// defender.HP - player.attack;
// player.attack + base_attack;
//};
//$("#attack").click(attack()); |
var loginForm = document.getElementById("loginForm");
formValidation(loginForm);
var registrationForm = document.getElementById("registrationForm");
formValidation(registrationForm);
function loginFormValidation(){
return formStatus(loginForm);
}
function registrationFormValidation(){
var formVal = formStatus(registrationForm);
var checkPass = checkPassword(registrationForm);
return checkPass && formVal;
}
function formValidation(form){
var inputs = form.getElementsByTagName("input");
for(var i =0;i<inputs.length;i++){
inputs[i].onkeyup=function(){
if (this.value) {
this.style.border='0px';
}else{
this.style.border='2px solid red';
}
};
inputs[i].onblur=function(){
if (this.value) {
this.style.border='0px';
}else{
this.style.border='2px solid red';
}
};
}
}
function formStatus(form){
var inputs = form.getElementsByTagName("input"),
flag=true;
for(var i =0;i<inputs.length;i++){
if(!inputs[i].value){
//window.alert("Please fill all the input fields Correctly");
inputs[i].style.border='2px solid red';
flag = false;
}else{
inputs[i].style.border='0px';
}
}
return flag;
}
function checkPassword(form){
if(form.password.value == ""){
window.alert("Please Enter Password");
return false;
} else if(form.password.value.length < 4){
window.alert("Password should be at least 4 character");
return false;
}
if(form.password_confirm.value == ""){
window.alert("Please Re-Type Password");
return false;
}else if(form.password.value != form.password_confirm.value){
window.alert("The Password and verified password does not match!");
return false;
}
return true;
}
|
import React from 'react'
import styled from 'styled-components'
import Checkbox from './Checkbox'
const StyledBoudlerRoute = styled.div`
list-style-type: none;
display: flex;
padding: 20px;
.Number {
padding: 10px;
}
.Points {
padding: 10px 10px 10px 85px;
}
.CheckboxWrapper {
margin-left: -20px;
margin-right: 50px;
}
`;
function BoulderRoute({ route, toggleBoulders }) {
return (
<StyledBoudlerRoute>
<div className='CheckboxWrapper'>
<Checkbox
id={route.number}
isOn={route.done}
handleToggle={() => toggleBoulders(route.number)}
/>
</div>
<div className='Number'>
{route.number}
</div>
<div className='Points'>
{route.points}
</div>
</StyledBoudlerRoute>
)
}
export default BoulderRoute |
function ingevoerd() {
let Word2VecRes1 = document.getElementById('Word2VecRes1');
let Word2VecRes2 = document.getElementById('Word2VecRes2');
let Word2VecRes3 = document.getElementById('Word2VecRes3');
let Word2VecRes4 = document.getElementById('Word2VecRes4');
let Word2VecRes5 = document.getElementById('Word2VecRes5');
fetch('http://127.0.0.1:5000/ingevoerd', {
method: 'GET',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
}).then((response) => {
return response.json();
})
.then((result) => {
result = result.split(") (");
result1 = result[0];
result2 = result[1];
result3 = result[2];
result4 = result[3];
result5 = result[4];
Word2VecRes1.innerHTML = result1;
Word2VecRes2.innerHTML = result2;
Word2VecRes3.innerHTML = result3;
Word2VecRes4.innerHTML = result4;
Word2VecRes5.innerHTML = result5;
});
}
function report() {
let naam = document.getElementById('fname').value;
let telefoonnummer = document.getElementById('tel').value;
let email_adres = document.getElementById('email').value;
let onderwerp = document.getElementById('subject').value;
let bericht = document.getElementById('message').value;
let jsondata = { 'naam': naam, 'telefoonnummer': telefoonnummer, 'email_adres': email_adres, 'onderwerp': onderwerp, 'bericht': bericht };
fetch('http://127.0.0.1:5000/report', {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(jsondata)
}).then((response) => response.json());
return false;
}
function load_reports() {
fetch('http://127.0.0.1:5000/load_reports')
.then(response => response.json())
.then(result => {
let table_1 = document.getElementById('admintable')
for (var i = 0; i < result.length; ++i) {
item = result[i]
let new_row = table_1.insertRow(-1);
let new_naam = new_row.insertCell(0);
let new_text_naam = document.createTextNode(item.naam);
new_naam.appendChild(new_text_naam);
let new_telefoonnummer = new_row.insertCell(1);
let new_text_telefoonnummer = document.createTextNode(item.telefoonnummer);
new_telefoonnummer.appendChild(new_text_telefoonnummer);
let new_email = new_row.insertCell(2);
let new_text_email = document.createTextNode(item.email_adres);
new_email.appendChild(new_text_email);
let new_onderwerp = new_row.insertCell(3);
let new_text_onderwerp = document.createTextNode(item.onderwerp);
new_onderwerp.appendChild(new_text_onderwerp)
let new_bericht = new_row.insertCell(4);
let new_text_bericht = document.createTextNode(item.bericht);
new_bericht.appendChild(new_text_bericht)
}
})
.catch(console.error);
}
// Grafieken maken
resultarray_frontend = []
function load_chars_frontend() {
fetch('http://127.0.0.1:5000/load_chars_frontend')
.then(response => response.json())
.then(result =>{
resultarray_frontend = result
})
}
resultarray_backend = []
function load_chars_backend() {
fetch('http://127.0.0.1:5000/load_chars_backend')
.then(response => response.json())
.then(result =>{
resultarray_backend = result
})
}
resultarray_productowner = []
function load_chars_productowner() {
fetch('http://127.0.0.1:5000/load_chars_productowner')
.then(response => response.json())
.then(result =>{
resultarray_productowner = result
})
}
resultarray_cloud_security = []
function load_chars_cloud_security() {
fetch('http://127.0.0.1:5000/load_chars_cloud_security')
.then(response => response.json())
.then(result =>{
resultarray_cloud_security = result
})
} |
import React, { Component } from 'react';
import { Link } from 'react-router';
import ForecastsService from './services/ForecastsService';
import DateHelper from './helpers/DateHelper';
import ForecastArrayHelper from './helpers/ForecastArrayHelper';
import HeaderAppComponent from './components/HeaderAppComponent';
import SearchComponent from './components/SearchComponent';
import TableComponent from './components/TableComponent';
import LoadingComponent from './components/LoadingComponent';
import config from './config';
/**
* @class
* @classdesc WeatherApp é responsável pelo gerenciamento do app.
*/
class WeatherApp extends Component {
constructor(props) {
super(props);
this.state = {
cities: config.CITIES,
forecasts: [],
serviceError: ''
}
this.filterCities = this.filterCities.bind(this);
this.resetFilter = this.resetFilter.bind(this);
this.getForecasts = this.getForecasts.bind(this);;
}
componentDidMount() {
this.getForecasts();
}
getForecasts() {
const forecasts = ForecastsService.get(this.state.cities);
forecasts.then((forecast) => {
const nCities = forecast.length;
let data = [];
let allForecasts = [];
for (let i = 0; i < nCities; i++) {
let nextForecasts = ForecastArrayHelper.extract(forecast[i].data.list);
nextForecasts.forEach((obj) => {
if (obj) {
data.push({ date: obj.dt_txt, temp: Math.round(obj.main.temp) });
}
else {
data.push({ date: '', temp: '' });
}
});
allForecasts.push({
city: forecast[i].data.city.name,
cityId: forecast[i].data.city.id,
data: data
});
data = [];
}
this.setState({ forecasts: allForecasts });
});
forecasts.catch((error) => {
console.log('Server error:', error);
this.setState({ serviceError: 'Ops, não foi possível obter os dados do servidor.' });
});
}
filterCities(city) {
this.setState({ cities: [city] });
}
resetFilter() {
this.setState({ cities: config.CITIES });
}
render() {
return (
<div>
<HeaderAppComponent />
<SearchComponent filterCities={this.filterCities} resetFilter={this.resetFilter} cities={config.CITIES} />
{ React.cloneElement(this.props.children, this.state) }
<LoadingComponent hasData={this.state.forecasts} hasError={this.state.serviceError} />
</div>
);
}
}
export default WeatherApp;
|
const element = document.querySelector("#head");
const btn = document.querySelector('#btn-click');
const navLink = document.querySelectorAll('.dropdown');
const clearFile = document.querySelector('#clear-file');
const saveFile = document.querySelector('#save-file');
const navTabs = document.querySelector('#tabs');
const tabContent = document.querySelector('#myTabContent');
const runTime = document.querySelector('#runtime');
const btnShowHide = document.getElementById('btn-show-hide');
const main = document.getElementById('home');
var mEditor;
const syntaxHighlighting = {
keywords: [
'print','if', 'var','class'
],
operators : [
'-', '+' ,'='
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\/\^%]+/,
// update to own escape strings
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
tokenizer : {
root:[
[/[a-z_$][\w$]*/, {cases: {'@keywords' : 'keyword','@default': 'identifier'}}
],
[/[A-Z][\w\$]*/,'type.identifier'],
{include: '@whitespace'},
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],//not implemented?
[/@symbols/, { cases: { '@operators': 'operator',
'@default' : '' } } ],
// numbers
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F]+/, 'number.hex'],
[/\d+/, 'number'],
//strings
[/[;,.]/, "delimiter"],
[/"([^"\\]|\\.)*$/, 'string.invalid' ], // non-teminated string
[/"/, { token: 'string.quote', bracket: '@open', next: '@string' } ],
],
comment: [
[/[^\/*]+/, 'comment' ],
[/\/\*/, 'comment', '@push' ], // nested comment
["\\*/", 'comment', '@pop' ],
[/[\/*]/, 'comment' ]
],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, { token: 'string.quote', bracket: '@close', next: '@pop' } ]
],
whitespace: [
[/[ \t\r\n]+/, 'white'],
[/\/\*/, 'comment', '@comment' ],
[/\/\/.*$/, 'comment'],
],
}
};
window.onload = () => {
monaco.languages.register({ id: 'roto' });
monaco.languages.setMonarchTokensProvider('roto', syntaxHighlighting);
mEditor = monaco.editor.create(home, {
value: 'print("Hello world!!")',
language: "roto"
});
}
navLink.forEach(function (element) {
element.addEventListener('mouseover', function () {
element.setAttribute('style', 'background-color: lightgrey;');
});
element.addEventListener('mouseout', function () {
element.removeAttribute('style');
});
});
clearFile.addEventListener('click', function () {
mEditor.setValue('')
});
btnShowHide.addEventListener('click', () => {
if(/btn-warning/.test(btnShowHide.className)){
btnShowHide.className = 'btn btn-sm btn-success';
btnShowHide.textContent = 'Show';
runTime.className = 'hide';
document.getElementById('runTimeContent').removeAttribute('style');
main.style.height = '390px';
}
else{
btnShowHide.className = 'btn btn-sm btn-warning';
btnShowHide.textContent = 'Hide';
runTime.className = '';
document.getElementById('runTimeContent').setAttribute('style','border: 1px solid lightgray;');
main.style.height = '300px';
}
});
saveFile.addEventListener('click', () => {
let link = document.createElement('a');
//TODO: capture txt
link.download = 'script.rt';
let blob = new Blob([mEditor.getValue()], {type: 'text/plain'});
link.href = URL.createObjectURL(blob);
link.click()
URL.revokeObjectURL(link.href);
});
|
var config = {
token: 'josie',
appid: 'wxf7b28b05a78d409b',
encodingAESKey: 'VMZlfbsrHbx9dURyvoosnKPXttq5tbtLZ607DOvJnA6'
}
module.exports=config; |
Vue.component("counter", {
template: "#counter-template",
props:["subject"],
data: function(){
return{count:0}
}
});
var data = {
count: 0,
};
new Vue({
el:"#app",
});
|
window.testSuite.load(new TestingClass('Error', 'errorTests.js')
.setup({
run: function () {
try {
testDocument1.model.beginCompoundOperation();
testDocument1.model.beginCompoundOperation('', false);
testDocument1.model.endCompoundOperation();
testDocument1.model.endCompoundOperation();
} catch (e) {
this.error = e;
} finally {
testDocument1.model.endCompoundOperation();
}
},
assert: function () {
return !!this.error;
}
})
.test({
description: 'isFatal',
run: function () {},
assert: function () {
// TODO (sethhoward) Use the bottom return when we fix this
return true;
return typeof this.error.isFatal === 'boolean';
}
})
.test({
description: 'message',
run: function () {},
assert: function () {
return typeof this.error.message === 'string';
}
})
.test({
description: 'type',
run: function () {},
assert: function () {
return true; // TODO (sethhoward) Use the bottom return when we fix this
return !!this.error.type;
}
})
.teardown({
run: function () {
// Return the document back to it's original settings for subsequent tests
testDocument1.string.setText('');
testDocument1.list.clear();
testDocument1.map.set('key1', 1);
testDocument1.map.set('key2', 2);
testDocument3 = null;
},
assert: function () {
return testDocument1.string.getText() == '' &&
testDocument1.list.asArray().length == 0 &&
testDocument1.map.get('key1') == 1 &&
testDocument1.map.get('key2') == 2 &&
testDocument2.string.getText() == '' &&
testDocument2.list.asArray().length == 0 &&
testDocument2.map.get('key1') == 1 &&
testDocument2.map.get('key2') == 2;
}
})); |
class Cell {
constructor() {
this.contents = [];
}
add(thing) {
this.contents.push(thing);
}
remove(thing) {
this.contents = this.contents.filter(x => x !== thing);
}
clear() {
for (let thing of this.contents) {
if (thing.constructor.name === 'Drone') {
thing.destroy();
}
}
this.contents = [];
}
get(type) {
return this.contents.find(x => x.constructor.name === type);
}
getAll(type) {
return this.contents.filter(x => x.constructor.name === type);
}
isEmpty() {
return this.contents.length == 0;
}
}
|
const cp = require('child_process')
console.log('Checking dependencies...')
cp.spawnSync('npm', ['install'], {stdio: 'inherit'})
cp.spawnSync('npm', ['start'], {stdio: 'inherit'})
|
const Operation = require("src/app/Operation");
class GetMedia extends Operation {
constructor({ mediaRepository }) {
super();
this.mediaRepository = mediaRepository;
}
async execute(id) {
const { SUCCESS, NOT_FOUND } = this.outputs;
try {
const data = await this.mediaRepository.getById(id);
this.emit(SUCCESS, data);
} catch (error) {
this.emit(NOT_FOUND, {
type: error.message,
details: error.details
});
}
}
}
GetMedia.setOutputs(["SUCCESS", "ERROR", "NOT_FOUND"]);
module.exports = GetMedia;
|
const hightMark = 1.69;
const massMark = 78;
const hightJohn = 1.95;
const massJohn = 92;
const BMIMark = massMark / hightMark ** 2;
const BMIJohn = massJohn / (hightJohn * hightJohn);
if (BMIMark > BMIJohn) {
console.log(`Mark BMI ${BMIMark} is higher then John ${BMIJohn}`);
} else {
console.log(`John BMI ${BMIJohn} is higher then Mark ${BMIMark}`);
}
//console.log("Mark BMI is greater", maxBMI);
console.log(BMIMark, BMIJohn);
|
const fs = require('fs');
const port = 33080;
var util = require('util');
const listener = (req, res) => {
const path = req.url.replace(/\?.*$/, '');
var param = { };
const query_string = req.url.match(/^.+\?(.*)$/);
if(query_string) {
query_string[1].split(/&/).forEach(kv => {
((k, v) => { param[k] = decodeURIComponent(v); }).apply(null, kv.split(/=/))
});
}
if(path.indexOf('/otameshi/redis_put') == 0 && req.method === 'POST') {
console.log('redis put POST');
const querystring = require('querystring');
var data = '';
req.on('readable', function(chunk) {
var chunk = req.read();
if(chunk != null) {
data += chunk;
}
});
req.on('end', function() {
const param = querystring.parse(data);
console.log(data);
const Redis = require('ioredis');
const {promisify} = require('util');
const redis = require("ioredis");
const client = redis.createClient();
client.set(param['redis_key'], new Buffer(param['redis_value']));
});
fs.readFile('./htdocs/otameshi/index.html', 'utf-8', function (error, data) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
return;
}
if(path.indexOf('/otameshi/redis_del') == 0 && req.method === 'POST') {
console.log('redis del POST');
const querystring = require('querystring');
var data = '';
req.on('readable', function(chunk) {
var chunk = req.read();
if(chunk != null) {
data += chunk;
}
});
req.on('end', function() {
const param = querystring.parse(data);
console.log(data);
const Redis = require('ioredis');
const {promisify} = require('util');
const redis = require("ioredis");
const client = redis.createClient();
client.del(param['redis_key']);
});
fs.readFile('./htdocs/otameshi/index.html', 'utf-8', function (error, data) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
return;
}
if(path.indexOf('/otameshi/redis_get') == 0 && req.method === 'POST') {
console.log('redis get POST');
const querystring = require('querystring');
var data = '';
req.on('readable', function(chunk) {
// POSTデータ作成開始
var chunk = req.read();
if(chunk != null) {
data += chunk;
}
});
req.on('end', function() {
// POSTデータ作成終了
const param = querystring.parse(data);
console.log("param = %s", data);
const Redis = require('ioredis');
const {promisify} = require('util');
const redis = require("ioredis");
const client = redis.createClient();
const getAsync = promisify(client.get).bind(client);
(async () => {
// Redisからデータ取得
const res = await getAsync(param['redis_key']);
console.log('key %s = %s', param['redis_key'], res);
})();
});
fs.readFile('./htdocs/otameshi/index.html', 'utf-8', function (error, data) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
return;
}
if(path.indexOf('/otameshi/') == 0 && req.method === 'GET') {
console.log('GET');
console.log('param = %s', param['otameshitext']);
fs.readFile('./htdocs/otameshi/index.html', 'utf-8', function (error, data) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.write(data);
res.end();
});
return;
}
console.log("-> Not Found");
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.write('Not Found!');
res.end();
return;
}
console.log('Listening on :'+port);
require('http').createServer(listener)
.listen(port, '0.0.0.0');
|
#target "illustrator-19";
if ( app.documents.length > 0) {
doc = app.activeDocument;
var activeAB = doc.artboards[doc.artboards.getActiveArtboardIndex()];
var voorzet = activeAB.name;
var Newname = prompt("Rename Artboard", voorzet);
if (Newname){
activeAB.name = Newname;
}
}
|
const ResponseError = require('../../../Enterprise_business_rules/Manage_error/ResponseError');
const { TYPES_ERROR } = require('../../../Enterprise_business_rules/Manage_error/codeError');
const { ROLES } = require('../../../Enterprise_business_rules/constant');
module.exports = async (dataExam, repositories) => {
const { idAdmin, id, subject, group, date, teacher, space, state } = dataExam;
const { userRepositoryMySQL, examRepositoryMySQL, reservationRepositoryMySQL } = repositories;
// Se comprueban que se han recibido el id del administrador de sistemas y el id del examen
if (!idAdmin || !id) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los IDs son necesarios para realizar la actualización', 'id_empty');
}
// Se comprueba que los ids sean números
if (Number.isNaN(Number(idAdmin)) || Number.isNaN(Number(id))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los ids deben ser números', 'id_format_error');
}
// Se comprueba que el usuario con idAdmin existe
const existAdmin = await userRepositoryMySQL.getUser(idAdmin);
if (!existAdmin) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El administrador no existe', 'user_not_exist');
}
// Se comprueba que el idAdmin tiene rol de adminsitrador de exámenes
const isRoleAdmin = await userRepositoryMySQL.getRole({ userRoleData: { UserId: idAdmin, role: ROLES.ADMIN_EXAM } });
if (!isRoleAdmin) {
throw new ResponseError(TYPES_ERROR.ERROR, 'El usuario actual necesita rol de Administrador de exámenes para actualizar un examen', 'role_not_assigned');
}
// Se comprueba que exista un examen a modificar
const existExam = await examRepositoryMySQL.getExam(id);
if (!existExam) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El examen no existe', 'exam_not_exist');
}
// Se comprueba que al menos se ha recibido un parámetro para modificar
if (!subject && !group && !date && !teacher && !space && !state) {
throw new ResponseError(TYPES_ERROR.ERROR, 'Es necesario al menos un parámetro para actualizar', 'incomplete_data');
}
// Se comprueba si se va a actualizar un aula, y si es así, se actualiza la reserva o se reserva
if (space) {
const reservationData = {
ExamId: id,
SpaceId: space,
date: existExam.date,
};
await reservationRepositoryMySQL.addReservation(reservationData);
}
return examRepositoryMySQL.updateExam({ examData: { idAdmin, ...dataExam } });
};
|
'use strict'
/**
* Module dependencies.
* @private
*/
var http = require('http')
/**
* Module exports.
* @private
*/
module.exports = getCurrentNodeMethods() || getBasicNodeMethods()
/*
* Get current node.js methods.
* @private
*/
function getCurrentNodeMethods() {
return http.METHODS && http.METHODS.map(function lowerCaseMethod (method) {
return method.toLowerCase();
});
}
|
// Controller: EVENTO
//
// * Metodos: identificarTipo() por ejemplo movimiento, gas, apertura o nulo {esto va en el controller y no en el model}
//En este modelo en lugar de declarar metodo identificarTipo(), debo poner los metodos CRUD de los eventos.
/**
* Esta funcion analiza una trama y determina si los pines digital input del nodo router
* recibieron alguna señal HIGH proveniente de un sensor.
*
*/
function analizarTrama(frame) {
if (JSON.stringify(trama.digitalSamples) === '{"DIO0":1}') {
return 'movimiento';
//return 'gas'; // si {"DIO1":1}
//return 'apertura'; // si {"DIO2":1}
//return 'todoEnOrden'; //cuando ningun sensor disparo un evento
}
} |
import store from '@/vuex/store'
import { DEVICE_TYPE } from '@/utils/common'
export default {
computed: {
},
beforeMount () {
if (typeof window !== 'undefined') {
window.removeEventListener('resize', this.onResize, { passive: true })
}
},
mounted () {
this.onResize()
window.addEventListener('resize', this.onResize, { passive: true })
},
methods: {
onResize () {
if (!document.hidden) {
const isMobile = window.innerWidth < 768
const isTablet = !isMobile && window.innerWidth < 1020
const device = isMobile ? DEVICE_TYPE.MOBILE : isTablet ? DEVICE_TYPE.TABLET : DEVICE_TYPE.PC
device !== store.getters.device && store.dispatch('app/setDevice', device)
}
}
}
}
|
/*
* Return true if you did this operation
*/
var wallHits = 4000000;
var depositRepair = {
deposit: function(creep) {
if(creep.memory.wallHits) {
wallHits = creep.memory.wallHits;
}
if(!creep.memory.repairTargetTypes){
console.log("Creep " + creep.name + " not configured to repair any types, but is using depositRepair behavior!");
return ERR_INVALID_TARGET;
}
if(creep.memory.depositRoom && creep.memory.depositRoom != creep.pos.roomName) {
creep.tryToRepairRoads();
creep.moveTo(new RoomPosition(25,25, creep.memory.depositRoom));
creep.say("I don't belong here");
return true;
}
var targetTypes = creep.memory.repairTargetTypes.split(",");
var index = 0;
var targets = [];
while(targets.length == 0 && index < targetTypes.length) {
// console.log(index);
targets = creep.room.find(FIND_STRUCTURES, {filter: function(structure) {
return targetTypes[index]==structure.structureType &&
((structure.structureType == 'constructedWall' && structure.hits < wallHits) ||
(structure.structureType == 'rampart' && structure.hits < wallHits) ||
(structure.structureType == 'road' && structure.hits < structure.hitsMax) ||
(structure.structureType == 'container' && structure.hits < structure.hitsMax));
//TODO this sort is busted
}}).sort((a, b) => creep.getDistanceTo(a) - creep.getDistanceTo(b) /*(Math.round(a.hits/5000)*5000/Math.min(a.hitsMax,wallHits)*100.0) - (Math.round(b.hits/5000)*5000/Math.min(a.hitsMax,wallHits)*100.0)*/);
// console.log(targetTypes[index] + targets.length);
index = index + 1;
}
// console.log(creep.name + " should repair " + targets.length + "things");
if(targets.length > 0) {
result = creep.repair(targets[0]);
if(result == OK) {
creep.report("repaired", creep.getActiveBodyparts(WORK));
}
if(result == ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
creep.say(targets[0].structureType);
}
}
// console.log(targets.length > 0)
return targets.length > 0;
},
name: "depositRepair"
}
module.exports = depositRepair; |
import { initAjaxWorkerEvent } from "organism-react-ajax";
import { getDefault } from "get-object-value";
import { win as getWin } from "win-doc";
import windowOnLoad from "window-onload";
import { KEYS } from "reshow-constant";
const importWorker = (win, serviceWorkerURL) => {
import("worker-loader!organism-react-ajax/build/es/src/worker").then(
(workerObject) => {
workerObject = getDefault(workerObject);
if (workerObject) {
const objWorker = new workerObject();
initAjaxWorkerEvent(objWorker);
}
}
);
const navigator = win.navigator;
if ("serviceWorker" in navigator) {
if (process.env.ENABLE_SW) {
if (serviceWorkerURL) {
const [load] = windowOnLoad({ domReady: true, domReadyDelay: 0 });
load(() => {
navigator.serviceWorker
.register(serviceWorkerURL)
.then((registration) => {})
.catch((registrationError) => {
console.log("SW registration failed: ", registrationError);
});
});
}
} else {
navigator.serviceWorker.getRegistrations().then((registrations) => {
KEYS(registrations).forEach((key) => registrations[key].unregister());
});
}
}
};
const initWorker = ({
win = getWin(),
cb = importWorker,
serviceWorkerURL = "/service-worker.js",
}) => {
if (win.Worker) {
cb(win, serviceWorkerURL);
}
};
export default initWorker;
|
/*
* ログイン後の画面表示
*
**/
$(window).load(function() {
});
$(function() {
prevLoginVal();
});
/* 前回のログイン情報取得
*
@param -
@return -
*/
function prevLoginVal() {
var result = ajaxPrevLoginVal();
result.done(function(response) {
console.debug(response);
if(response['ERROR'] == 'NO SESSION') {
forNoSession();
}
//console.debug(response['VALLIST']);
var branchName = response['BRANCHNAME'];
var logoutDT = response['LOGOUTDT' ];
var loginDT = response['LOGINDT' ];
$("#branchName" ).html(branchName);
$("#prevLogoutDT").html(logoutDT);
$("#currLoginDT" ).html(loginDT);
setWidthAdjust();
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxPrevLoginVal:" + result.status + ' ' + textStatus);
});
result.always(function() {
//console.debug(ret['VALLIST']);
});
}
/* ログイン情報取得(ajax)
*
@param -
@return -
*/
function ajaxPrevLoginVal() {
var jqXHR;
jqXHR = $.ajax({
type : "get" ,
url : "../cgi/ajax/mtn/getPrevLogin.php" ,
cache : false ,
dataType : 'json'
});
return jqXHR;
}
/* 表示幅の調整
*
@param -
@return -
*/
function setWidthAdjust() {
var a1 = $("table#loginDT").css("width");
$("div#vals").css('width' ,a1);
}
|
import React from 'react'
import LazyLoad from 'react-lazyload'
import Logo from '../illustration.svg'
export default function({ elem }) {
const { title, genre, music, id } = elem
return (
<div className="cp-movie-card">
<div className="cp-movie-card-overlay">
<h2>{title}</h2>
<p className="genre">{genre}</p>
<p className="music">{music}</p>
</div>
<LazyLoad once placeholder={<img src={Logo} alt="React brand logo" />}>
<img
className="cp-movie-card-thumb"
src={`${elem.image_src}?random=${id}`}
alt={elem.title}
/>
</LazyLoad>
</div>
)
}
|
//Brands Start
function productDiscountOffersCtrl($scope, $uibModal, productService) {
$scope.suppliers = {};
$scope.discountTypes = {};
$scope.discountOffer = {
offerName: '',
offerDisplayText: '',
discountOfferDateRange: '',
discountType : ''
};
init();
function init() {
getAllMasterDataForCreateOrEditDiscountOffer();
}
/* Product Suppliers Start*/
$scope.supplier = {};
$scope.saveSupplier = function () {
var options = { successMessage: "Supplier saved successfully.", errorMessage: "Error occurred in saving Supplier" };
if ($scope.dataSupplierForm.$valid) {
// Submit as normal
productService.postSupplier($scope.supplier, options)
.then(function (data) {
var successData = data;
getAllSuppliers();
}, function (error) {
//
});
} else {
$scope.dataSupplierForm.submitted = true;
}
}
$scope.onDiscountTypeChange = function () {
if ($scope.discountOffer.discountType.discountTypeId == 1) {
$scope.discountTypeText = 'product';
}
else if ($scope.discountOffer.discountType.discountTypeId == 2) {
$scope.discountTypeText = 'product category';
}
else if ($scope.discountOffer.discountType.discountTypeId == 3) {
$scope.discountTypeText = 'brand';
}
else if ($scope.discountOffer.discountType.discountTypeId == 4) {
$scope.discountTypeText = 'tag';
}
else if ($scope.discountOffer.discountType.discountTypeId == 5) {
$scope.discountTypeText = 'order';
}
}
$scope.$watch('discountOffer.discountOfferType', function (newVal, oldVal) {
if (newVal === oldVal) return;
if (newVal == percentDiscount) {
var test = percentDiscount;
}
});
function getAllMasterDataForCreateOrEditDiscountOffer() {
productService.getAllMasterDataForCreateOrEditDiscountOffer().then(
function (data) {
if (data) {
$scope.discountTypes = data.discountTypes;
}
});
};
/* Product Suppliers End*/
};
|
const random = x => Math.random()*x|0;
const uniqueKey = (l, x, y) => `${l}${x}${y}`;
const squareStyle = (arr, lost) => {
const result = {fill: `rgb(${arr[0]}, ${arr[1]}, ${arr[2]})`};
return (lost)
? Object.assign(result, {stroke: 'rgb(0,0,0)', strokeWidth: '2'})
: result
};
const generateColours = level => {
const idx = random(3);
const stdFill = [random(255),random(255),random(255)];
stdFill[idx] = 255;
const winFill = stdFill.slice();
winFill[idx] -= (50 - level);
return {stdFill, winFill}
};
export {random, uniqueKey, squareStyle, generateColours};
|
import React, {useReducer} from 'react'
import authContext from './authContext'
import authReducer from './authReducer'
import {
REGISTER_SUCCESS,REGISTER_FAIL,USER_LOADED,
AUTH_ERROR,LOGIN_SUCCESS,LOGIN_FAIL,LOGOUT
} from '../types'
const AuthState = props => {
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user:null,
error: null
}
const [state, dispatch] = useReducer(authReducer, initialState)
//TODO refactor
const createRequest = (url,method, data, token) => {
console.log(token)
let customHeader = new Headers({'Content-Type': 'application/json'})
if (token) {
customHeader.append('x-auth-token', token)
} else {
customHeader.delete('x-auth-token')
}
const myInit = {
method: method,
body: data ? JSON.stringify(data): null,
headers: customHeader
}
return fetch(url,myInit)
}
const register = async (userData) => {
try {
const response = await createRequest('api/users','POST',userData)
const data = await response.json()
console.log(response)
console.log(data)
if (!response.ok) {
throw new Error(data.msg);
}
dispatch({
type: REGISTER_SUCCESS,
payload: data
})
loadUser(localStorage.getItem('token'))
} catch (err) {
console.error(err)
dispatch({
type: REGISTER_FAIL,
payload: err.response
})
}
}
const login = async (userData) => {
try {
const response = await createRequest('api/auth','POST',userData)
const data = await response.json()
console.log(response)
console.log(data)
if (!response.ok) {
throw new Error(data.msg);
}
dispatch({
type: LOGIN_SUCCESS,
payload: data
})
loadUser(localStorage.getItem('token'))
} catch (err) {
console.error(err)
dispatch({
type: LOGIN_FAIL,
payload: err.response
})
}
}
const loadUser = async (token) => {
try {
const response = await createRequest('api/auth','GET',null,token)
const data = await response.json()
if (!response.ok) {
throw new Error(data.msg);
}
console.log(response)
console.log(data)
dispatch({
type: USER_LOADED,
payload: data
})
} catch (err) {
console.error(err)
dispatch({
type: AUTH_ERROR
})
}
}
const logout = async () => {dispatch({type: LOGOUT})}
return (
<authContext.Provider
value={{
token: state.token,
isAuthenticated: state.isAuthenticated,
user: state.user,
loading: state.loading,
error: state.error,
register,
loadUser,
login,
logout
}}>
{props.children}
</authContext.Provider>
)
}
export default AuthState; |
const express = require('express')
const mysql = require('mysql')
const app = express()
const port = 3000
const config = {
host: 'db',
user: 'root',
password: 'root',
database: 'coursesdb'
}
app.get('/', (req, res) => {
const connection = mysql.createConnection(config)
let nomes = [];
connection.query("SELECT * FROM module", function(error, result, fields){
if(error)
{
console.log('deu erro')
console.log(error)
return error;
}
result.forEach(element => {
nomes.push(element.name + '<br>');
});
res.send('<h1>Módulos: </h1><br>' + nomes)
})
})
app.listen(port, () => {
console.log('Rodando na porta ' + port)
}) |
import React, { Component, Fragment } from "react";
import {
Grid,
Card
} from "@material-ui/core";
import DoughnutChart from "../charts/echarts/Doughnut";
import TableCard from "./shared/DepressionCard";
import StatCards2 from "./shared/StatCards2";
import { withStyles } from "@material-ui/styles";
import './shared/modal.css'
class Dashboard1 extends Component {
state = {};
render() {
let { theme } = this.props;
return (
<Fragment>
<div className="pb-86 pt-30 px-30 bg-primary"></div>
<div className="analytics m-sm-30 mt--72">
<Grid container spacing={3}>
<Grid item lg={8} md={8} sm={12} xs={12}>
<StatCards2 />
<TableCard />
</Grid>
<Grid item lg={4} md={4} sm={12} xs={12}>
<Card className="px-24 py-30 mb-16">
<div className="card-title ModalTitle">
General Prediction Results
</div>
<div className="card-subtitle">All Time</div>
<DoughnutChart
height="400px"
color={[
"#036916",
// theme.palette.primary.main,
"#f5c000",
"#f56200",
"#f53900",
"#f50039",
"#ed2d2d",
"#b80000",
]}
/>
</Card>
</Grid>
</Grid>
</div>
</Fragment>
);
}
}
export default withStyles({}, { withTheme: true })(Dashboard1);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.