text stringlengths 7 3.69M |
|---|
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../react/App';
import Button from '../react/components/Button';
import DogMedia from '../react/components/DogMedia';
describe('Button component', () => {
const component = renderer.create(<Button onClick={() => {}} />);
it('Button components renders initially', () => {
expect(component.toJSON()).toMatchSnapshot();
});
it('renders with null as an initial state', () => {
const instance = component.getInstance();
// console.log(instance);
expect(instance.state).toBeNull();
});
});
describe('DogMedia component', () => {
it('renders video', () => {
const component = renderer.create(<DogMedia mediaType="video" />);
const instance = component.getInstance();
expect(instance.props.mediaType).toBe('video');
});
});
describe('App component', () => {
it('has a button', () => {
const component = renderer.create(<App />);
const instance = component.getInstance();
expect(instance.props.mediaType).toBe('video');
});
});
// function sum(a, b) {
// return a + b;
// }
// describe('adds 1 + 2 to equal 3', () => {
// expect(sum(1, 2)).toBe(3);
// });
|
// IMPORTS
// react
import React, { useState, useContext } from "react";
// styled components
import styled from "styled-components";
// contexts
import { UserMissionsContext } from "../../../contexts/UserMissionsContext";
// helpers
import { flex } from "../../../styles/global/Mixins";
// components
import MissionCard from "./MissionCard";
import MissionInput from "./MissionInput";
import Congrats from "./CongratsComplete";
import { axiosWithAuth } from "../../../helpers/axiosWithAuth";
import * as ctx from "../../globalFunctions";
// images
import waves from "../../../images/Onboarding/waves.svg"
// DUMMY DATA
// adding some dummy data so that i can work out basic props drilling
// this will probably change a lot after BE figures out all of the data models
// but we can use it for now to move forward on FE -JC
// COMPONENT
const MissionComplete = props => {
// contexts
const userMissions = useContext(UserMissionsContext);
const { missions } = userMissions;
props.debug && console.log("[userMissions]", userMissions);
// console.log("[userMissions]", userMissions.missions.id);
// const missionsComplete
// state hooks
const [drawer, setDrawer] = useState({
status: "closed",
darken: "inactive"
});
const [congratsScreen, setCongratsScreen] = useState({
status: "closed"
});
const [selectedMission, setSelectedMission] = useState(null);
const [missionTracker, setMissionTracker] = useState([]);
// handlers
const handleDrawer = e => {
drawer.status === "closed"
? setDrawer({ ...drawer, status: "open", darken: "active" })
: setDrawer({ ...drawer, status: "closed", darken: "inactive" });
};
const submitMissions = e => {
e.preventDefault();
congratsScreen.status === "closed"
? setCongratsScreen({ ...congratsScreen, status: "open" })
: setCongratsScreen({ ...congratsScreen, status: "closed" });
drawer.darken === "inactive"
? setDrawer({ ...drawer, darken: "active" })
: setDrawer({ ...drawer, darken: "inactive" });
submitMissionTracker();
};
const submitMissionTracker = e => {
axiosWithAuth()
.post(`/answers/${ctx.tzQuery}`, missionTracker)
.then(res => {
const {
mission_subscriptions,
missions_in_progress
} = res.data.user_missions;
userMissions.setUserMissions(
ctx.missionMasher(mission_subscriptions, missions_in_progress)
);
})
.catch(err => {
props.debug && console.log(err);
});
};
props.debug && console.log("[Mission Tracker]", missionTracker);
// render
return (
<MCView>
<Darken className={drawer.darken} onClick={handleDrawer} />
<MCWrapper>
<MCContainer>
<h2 className="mission-message">What mission did you complete?</h2>
<MissionsWrapper>
{missions.map(mission => {
mission.handleDrawer = handleDrawer;
mission.setSelectedMission = setSelectedMission;
return <MissionCard key={mission.mission_id} mission={mission} />;
})}
</MissionsWrapper>
<ContinueButton onClick={submitMissions}>Continue</ContinueButton>
</MCContainer>
<MissionInput
handleDrawer={handleDrawer}
status={drawer.status}
missions={userMissions}
selectedMission={selectedMission}
missionTracker={missionTracker}
setMissionTracker={setMissionTracker}
drawerStatus={drawer.status}
/>
<Congrats
status={congratsScreen.status}
handleClose={submitMissions}
submitMissionTracker={submitMissionTracker}
/>
</MCWrapper>
</MCView>
);
};
// STYLED COMPONENTS
const MCView = styled.div`
width: 100vw;
height: 100vh;
max-height: 100vh;
padding-top: 5rem;
background-color: #4742bc;
background-image: url(${waves});
`;
const MCWrapper = styled.div`
width: 100%;
`;
const MCContainer = styled.div`
width: 90%;
margin: 0 auto;
${flex.flexCol}
.mission-message {
font-size: 3.5rem;
letter-spacing: 0.25rem;
font-weight: bold;
color: #fff;
margin: 3rem 2rem;
}
`;
const MissionsWrapper = styled.div`
width: 100%;
display: flex;
flex-flow: row wrap;
justify-content: space-around;
align-items: top;
`;
const ContinueButton = styled.button`
width: 80%;
height: 5rem;
background-color: #6487ff;
border: none;
border-radius: 3px;
box-shadow: 0px 4px 10px rgba(21, 15, 172, 0.1);
margin: 2rem 0;
font-size: 1.5rem;
color: #fff;
font-weight: normal;
letter-spacing: 0.15rem;
&:hover {
cursor: pointer;
}
`;
const Darken = styled.div`
transition-property: all;
transition: 0.5s;
&.active {
width: 100%;
height: 100vh;
position: fixed;
bottom: 10rem;
background-color: rgba(0, 0, 0, 0.5);
}
&.inactive {
width: 100%;
height: 0vh;
position: fixed;
bottom: 10rem;
background-color: rgba(0, 0, 0, 0);
}
`;
// EXPORT
export default MissionComplete;
|
export default {
// ========================
// diffuse
// ========================
diffuse: {
attributes: [
'a_position',
'a_normal',
'a_uv0'
],
vertexShader: `
precision mediump float;
uniform mat4 model, view, projection;
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_uv0;
varying vec2 v_uv0;
void main() {
v_uv0 = a_uv0;
gl_Position = projection * view * model * vec4(a_position, 1);
}
`,
fragmentShader: `
#extension GL_OES_standard_derivatives : enable
precision mediump float;
uniform sampler2D u_mainTexture;
uniform vec2 u_mainTextureTiling;
uniform vec2 u_mainTextureOffset;
varying vec2 v_uv0;
void main () {
// gl_FragColor = vec4( 1, 1, 1, 1 );
// gl_FragColor = vec4( v_uv0.x, v_uv0.y, 0, 1 );
vec2 uv0 = v_uv0 * u_mainTextureTiling + u_mainTextureOffset;
gl_FragColor = texture2D( u_mainTexture, uv0 );
if (!gl_FrontFacing) {
gl_FragColor *= 0.05;
}
}
`,
},
// ========================
// diffuse_skinning
// ========================
diffuse_skinning: {
attributes: [
'a_position',
'a_normal',
'a_uv0',
'a_joint',
'a_weight'
],
vertexShader: `
precision mediump float;
uniform mat4 model, view, projection;
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_uv0;
attribute vec4 a_weight;
attribute vec4 a_joint;
uniform sampler2D u_bonesTexture;
uniform float u_bonesTextureSize;
varying vec2 v_uv0;
mat4 getBoneMatrix(const in float i) {
float size = u_bonesTextureSize;
float j = i * 4.0;
float x = mod(j, size);
float y = floor(j / size);
float dx = 1.0 / size;
float dy = 1.0 / size;
y = dy * (y + 0.5);
vec4 v1 = texture2D(u_bonesTexture, vec2(dx * (x + 0.5), y));
vec4 v2 = texture2D(u_bonesTexture, vec2(dx * (x + 1.5), y));
vec4 v3 = texture2D(u_bonesTexture, vec2(dx * (x + 2.5), y));
vec4 v4 = texture2D(u_bonesTexture, vec2(dx * (x + 3.5), y));
mat4 bone = mat4(v1, v2, v3, v4);
return bone;
}
void main() {
v_uv0 = a_uv0;
mat4 matSkin =
getBoneMatrix(a_joint.x) * a_weight.x +
getBoneMatrix(a_joint.y) * a_weight.y +
getBoneMatrix(a_joint.z) * a_weight.z +
getBoneMatrix(a_joint.w) * a_weight.w ;
gl_Position = projection * view * model * matSkin * vec4(a_position, 1);
}
`,
fragmentShader: `
#extension GL_OES_standard_derivatives : enable
precision mediump float;
uniform sampler2D u_mainTexture;
varying vec2 v_uv0;
void main () {
// gl_FragColor = vec4( 1, 1, 1, 1 );
// gl_FragColor = vec4( v_uv0.x, v_uv0.y, 0, 1 );
gl_FragColor = texture2D( u_mainTexture, v_uv0 );
if (!gl_FrontFacing) {
gl_FragColor *= 0.05;
}
}
`,
}
}; |
import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import Message from 'element-ui'
var MyAxios = {}
MyAxios.install = function (Vue) {
axios.interceptors.request.use(
config => {
config.headers['Content-Type'] = 'application/json;charset=UTF-8';
let pojo = JSON.parse(sessionStorage.getItem('vuex'))
if (pojo && pojo.user) {
config.headers.token =pojo.user.sessionid;
}
return config;
},
error => {
return Promise.reject(error.response);
});
axios.interceptors.response.use(
response => {
switch (response.data.code) {
case 401:
router.replace('/login')
break
default:
return response
}
},
err => {
switch (err.response.status) {
case 400:
err.message = '请求错误'
break
case 401:
err.message = '未授权,请重新登录'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = '请求出错'
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '服务器错误'
break
case 501:
err.message = '服务未实现'
break
case 502:
err.message = '网络错误'
break
case 503:
err.message = '服务不可用'
break
case 504:
err.message = '连接超时'
break
case 505:
err.message = 'HTTP版本不受支持'
break
default:
err.message = `连接出错(${err.response.status})`
}
Message.error(err.message)
return Promise.reject(err.message)
})
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs
}
export default MyAxios
|
async function aiPrediction(data1, data2, data3, paraDonor, RS)
{
const model = await tf.loadModel('https://ihzaa.com/model.json');
var awaitResult = await model.predict(tf.tensor2d([[data1, data2, data3]])).dataSync();
return awaitResult;
}
//untuk ngebuat CORS request
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
//untuk request CORS
function makeCorsRequest() {
var url = "https://ihzaa.com/model.json";//URL CORS ke AI
var xhr = createCORSRequest('GET', url);
xhr.send();
}
//Untuk integerasi ke database
var firebaseConfig = {
apiKey: "AIzaSyCw3zHbhfPJvkxNvDvuRj1PT3g5ic0hnt8",
authDomain: "test-55af1.firebaseapp.com",
databaseURL: "https://test-55af1.firebaseio.com",
projectId: "test-55af1",
storageBucket: "test-55af1.appspot.com",
messagingSenderId: "131257202002",
appId: "1:131257202002:web:a5a374e6452d60eb30b68b",
measurementId: "G-0S6Y21KB29"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var ref = firebase.database().ref("User/");
ref.once("value", function(snapParent){
snapParent.forEach((snapUser) => {
console.log(snapUser.key);
var nama = snapUser.child("Nama").val();
var goldar = snapUser.child("GolDar").val();
});
});
//Filter berdasarkan golongan darah
function filterFirst(calonDonor, recipient, result)
{
var counter = 0;
var recipientId = recipient.child("ID").val();
calonDonor.forEach((snapChild)=>{
var userId = snapChild.key;
var goldar = snapChild.child("GolDar").val();
var rhesus = snapChild.child("Rhesus").val();
//if eligible result.add snapChild
if(recipient.child("GolDar").val() == goldar && recipientId != userId)
{
if(recipient.child("Rhesus").val() == rhesus || rhesus == "-" )
{
result[counter] = snapChild;
counter++;
}
}
});
calonDonor.forEach((snapChild)=>{
var userId = snapChild.key;
var goldar = snapChild.child("GolDar").val();
var rhesus = snapChild.child("Rhesus").val();
//if eligible result.add snapChild
if(recipient.child("GolDar").val() == "AB" && recipientId != userId)
{
if(goldar == "A" || goldar == "B" || goldar == "O")
{
if(recipient.child("Rhesus").val() == rhesus || rhesus == "-")
{
result[counter] = snapChild;
counter++;
}
}
}
});
calonDonor.forEach((snapChild)=>{
var userId = snapChild.key;
var goldar = snapChild.child("GolDar").val();
var rhesus = snapChild.child("Rhesus").val();
//if eligible result.add snapChild
if(recipient.child("GolDar").val() == "A" || recipient.child("GolDar").val() == "B" && recipientId != userId)
{
if(goldar == "O")
{
if(recipient.child("Rhesus").val() == rhesus || rhesus == "-" )
{
result[counter] = snapChild;
counter++;
}
}
}
});
}
function filterSecond(input, targetRS)
{
var tableCalonDonor = document.getElementById("table-calon-donor");
var row;
var counter = 0;
var i;
var asyncCounter = 0;
var cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8;
input.forEach((snapChild) => {
var userId = snapChild.key;
firebase.database().ref("Koordinat/"+userId).once("value", (koorSnap) => {
var nama = snapChild.child("Nama").val();
var gender = snapChild.child("Gender").val();
var phone = snapChild.child("Phone").val();
var jarak1 = koorSnap.child("RS001").val();
var jarak2 = koorSnap.child("RS002").val();
var jarak3 = koorSnap.child("RS003").val();
aiPrediction(jarak1, jarak2, jarak3, snapChild, targetRS).then(result => {
// console.log(asyncCounter);
result[0] = parseFloat(result[0]);
result[0] = Math.abs(1 - result[0]);
result[1] = parseFloat(result[1]);
result[1] = Math.abs(1 - result[1]);
result[2] = parseFloat(result[2]);
result[2] = Math.abs(1 - result[2]);
console.log(result);
switch(targetRS.child("RS").val()){
case "RS001":
if(result[0]==Math.min.apply(null, result)){
row = tableCalonDonor.insertRow(asyncCounter + 1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
cell8 = row.insertCell(7);
cell1.innerHTML = asyncCounter + 1;
cell2.innerHTML = userId;
cell3.innerHTML = name;
cell4.innerHTML = gender;
cell5.innerHTML = phone;
cell6.innerHTML = "<button onClick = 'calonDonorOnClickAccept(" + asyncCounter + ")'>Accept</button>";
cell7.innerHTML = "<button onClick = 'calonDonorOnClickPending(" + asyncCounter + ")'>Pending</button>";
cell8.innerHTML = "<button onClick = 'calonDonorOnClickDeny(" + asyncCounter + ")'>Deny</button>";
asyncCounter++;
}
break;
case "RS002":
if(result[1]==Math.min.apply(null, result)){
row = tableCalonDonor.insertRow(asyncCounter + 1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
cell8 = row.insertCell(7);
cell1.innerHTML = asyncCounter + 1;
cell2.innerHTML = userId;
cell3.innerHTML = name;
cell4.innerHTML = gender;
cell5.innerHTML = phone;
cell6.innerHTML = "<button onClick = 'calonDonorOnClickAccept(" + asyncCounter + ")'>Accept</button>";
cell7.innerHTML = "<button onClick = 'calonDonorOnClickPending(" + asyncCounter + ")'>Pending</button>";
cell8.innerHTML = "<button onClick = 'calonDonorOnClickDeny(" + asyncCounter + ")'>Deny</button>";
asyncCounter++;
}
break;
case "RS003":
if(result[2]==Math.min.apply(null, result)){
row = tableCalonDonor.insertRow(asyncCounter + 1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
cell8 = row.insertCell(7);
cell1.innerHTML = asyncCounter + 1;
cell2.innerHTML = userId;
cell3.innerHTML = name;
cell4.innerHTML = gender;
cell5.innerHTML = phone;
cell6.innerHTML = "<button onClick = 'calonDonorOnClickAccept(" + asyncCounter + ", " + targetRS +")'>Accept</button>";
cell7.innerHTML = "<button id = 'pendingButton" + asyncCounter + "' onClick = 'calonDonorOnClickPending(" + asyncCounter + ")'>Pending</button>";
cell8.innerHTML = "<button onClick = 'calonDonorOnClickDeny(" + asyncCounter + ")'>Deny</button>";
asyncCounter++;
}
break;
default:
break;
}
});
});
}
);
firebase.database().ref("Request/"+targetRS.key+"/Status").set("3");}
//Mulai filter
function startFilter(snapshotUser, snapshotRequest)
{
var rsId = snapshotRequest.child("RS").val();
localStorage.setItem("rs_id",rsId);
filterFirst(snapshotUser, snapshotRequest, hasilFilter1);
filterSecond(hasilFilter1, snapshotRequest);
}
function calonDonorOnClickAccept(index)
{
var userId = (hasilFilter1[index]).key;
var rsId = localStorage.getItem("rs_id");
firebase.database().ref("User/"+userId+"/Accept").set(rsId);
}
function calonDonorOnClickPending(index)
{
var stringPendingButton = "pendingButton" + index;
console.log(stringPendingButton);
document.getElementById(stringPendingButton).disabled;
}
function calonDonorOnClickDeny(index)
{
alert(index);
}
let hasilFilter1 = [];//list hasil filter pertama
// FUNCTION UNTUK DONOR REQUEST
var requestIdFromPageReq;
function ambilDataRequest() {
firebase.database().ref("Request").on("value", (snap) => {
var counterSnap = 0;
var row;
var cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8, cel9, cel10;
var tableRequest = document.getElementById("table-request");
snap.forEach(snapParent => {
console.log(snapParent.child("Status").val());
if(snapParent.child("Status").val() == 0)
{
counterSnap++;
var requestId = snapParent.key;
var nama = snapParent.child("Nama").val();
var gender = snapParent.child("Gender").val();
var golDar = snapParent.child("GolDar").val();
var rhesus = snapParent.child("Rhesus").val();
var jumlah = snapParent.child("Jumlah").val();
var rs = snapParent.child("RS").val();
row = tableRequest.insertRow(counterSnap);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
cell8 = row.insertCell(7);
cell9 = row.insertCell(8);
cell10 = row.insertCell(9);
cell1.innerHTML = counterSnap;
cell2.innerHTML = requestId;
cell3.innerHTML = nama;
cell4.innerHTML = gender;
cell5.innerHTML = golDar;
cell6.innerHTML = rhesus;
cell7.innerHTML = jumlah;
cell8.innerHTML = rs;
cell9.innerHTML = "<button onClick = 'acceptRequest(" + requestId + ")'>Accept</button>";
cell10.innerHTML = "<button onClick = 'denyRequest(" + requestId + ")'>Deny</button>";
}
else if(counterSnap != 0)
{
tableRequest.deleteRow(counterSnap + 1);
counterSnap--;
}
});
});
}
function denyRequest(requestId) {
firebase.database().ref("Request/"+requestId+"/Status").set("2");
}
function acceptRequest(reqId) {
firebase.database().ref("Request/"+reqId+"/Status").set("1");
localStorage.setItem("req_id",reqId);
window.open('donor.html');
}
// onLoad Donor
function onLoadDonor() {
var req = localStorage.getItem("req_id");
firebase.database().ref("User").on("value", (snapshotUser) => {
firebase.database().ref("Request/"+req).once("value", (snapshotRequest) => {
startFilter(snapshotUser, snapshotRequest);
});
});
}
function onLoadUserValidation() {
var tableUserValidation = document.getElementById("table-user-validation");
var row;
var col1, col2, col3, col4, col5, col6, col7, col8;
var counterSnap = 0;
firebase.database().ref("User").once("value",(snapParent) => {
snapParent.forEach(snapChild =>{
console.log(snapChild.key);
counterSnap++;
row = tableUserValidation.insertRow(counterSnap);
col1 = row.insertCell(0);
col2 = row.insertCell(1);
col3 = row.insertCell(2);
col4 = row.insertCell(3);
col5 = row.insertCell(4);
col6 = row.insertCell(5);
col7 = row.insertCell(6);
col8 = row.insertCell(7);
col1.innerHTML = counterSnap;
col2.innerHTML = snapChild.key;
col3.innerHTML = snapChild.child("Nama").val();
col4.innerHTML = snapChild.child("Gender").val();
col5.innerHTML = snapChild.child("GolDar").val();
col6.innerHTML = snapChild.child("Rhesus").val();
col7.innerHTML = "<button>Validate</button>";
col8.innerHTML = "<button>Detail</button>";
})
})
}
function onLoadBloodDonor()
{
var tableBloodDonor = document.getElementById("table-blood-donor");
var row;
var col1, col2, col3, col4, col5, col6, col7, col8;
var counterSnap = 0;
firebase.database().ref("User").once("value",(snapParent) => {
snapParent.forEach(snapChild =>{
console.log(snapChild.key);
counterSnap++;
row = tableBloodDonor.insertRow(counterSnap);
col1 = row.insertCell(0);
col2 = row.insertCell(1);
col3 = row.insertCell(2);
col4 = row.insertCell(3);
col5 = row.insertCell(4);
col6 = row.insertCell(5);
col1.innerHTML = counterSnap;
col2.innerHTML = snapChild.key;
col3.innerHTML = snapChild.child("Nama").val();
col4.innerHTML = snapChild.child("GolDar").val();
col5.innerHTML = snapChild.child("Rhesus").val();
col6.innerHTML = 600;
})
})
} |
var CallHandler = require('./01_CallHandler').CallHandler;
// basic class: Employee
var Employee = (function() {
var callHanlder = new CallHandler();
function Employee(rank) {
// 0 - fresher
// 1 - techncial lead
// 2 - product manager
this.rank = rank;
this.free = true;
}
Employee.prototype = {
constructor: Employee,
// start the conversation
receiveCall: function(call) {
this.free = false;
},
// the issue is resolved, finish the call
callHandled: function(call) {
call.disconnect();
this.free = true;
callHanlder.getNextCall(this);
},
// the issue is not resolved, escalate the call
cannotHandle: function(call) {
call.rank = this.rank + 1;
callHanlder.dispatchCall(call);
this.free = true;
callHanlder.getNextCall(this);
}
};
return Employee;
})();
exports.Employee = Employee;
|
import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import { login } from '../store/actions/auth';
import StandardForm from '../components/StandardForm';
class LogIn extends React.Component {
constructor(props) {
super(props);
this.onLogIn = this.onLogIn.bind(this);
}
onLogIn(data) {
this.props.onLogIn(data);
}
render() {
return (
<StandardForm
showEmail
showPassword
onSubmit={this.onLogIn}
/>
);
}
}
const mapDispatchToProps = (dispatch) => ({
onLogIn: (data) => dispatch(login(data))
});
const mapStateToProps = (state) => {
return {
user: state.currentUser.user,
isPending: state.currentUser.isPending,
error: state.currentUser.error
};
};
export default connect(mapStateToProps, mapDispatchToProps)(LogIn); |
class TitleSelector extends React.Component{
constructor(){
super();
this.state ={
Title:[]
}
}
componentDidUpdate(propsPrev){
if(propsPrev.titleid!==this.props.titleid)
{
fetch('https://jsonplaceholder.typicode.com/posts/'+this.props.titleid,{
method:'GET',headers:{}
})
.then(res => res.json())
.then(data =>{
console.log(data.title);
this.setState({Title:data.title});
}).catch(err=>console.log(err))
}
}
render(){
return(
<div>
<label>Titulo: {this.state.Title}
</label>
</div>
);
}
}
|
/*
* @Author: dlidala
* @Github: https://github.com/dlidala
* @Date: 2017-03-16 16:27:37
* @Last Modified by: dlidala
* @Last Modified time: 2017-04-21 10:08:02
*/
'use strict'
module.exports = {
...require('./posts')
}
|
const staticUsers = [
{
id: 0,
name: 'John',
surname: 'Doe',
email: 'john.doe@yahoo.com',
phone: '343234234234',
address: 'New York, Madison Ave. 123, ZIP 1213123, US',
level: '4',
description: ''
},
{
id: 1,
name: 'Jane',
surname: 'Doe',
email: 'jane.doe@yahoo.com',
phone: '343234234212',
address: 'New York, Madison Ave. 120, ZIP 1213123, US',
level: '1',
description: 'A beginner in this whole thing'
},
]
export default staticUsers |
const data = [
{
Question: "In inches, how high is a table-tennis net?",
A: "There is no standard",
B: "4 inches",
C: "5 inches",
D: "6 inches",
Answer: "D"
},
{
Question: "Which Italian football team has the nickname I Lupi which translates as The Wolves?",
A: "Fiorentina",
B: "Parma",
C: "Roma",
D: "Genoa",
Answer: "C"
},
{
Question: "Whose ear did Mike Tyson bite in 1997?",
A: "Edward Teech",
B: "Rashad Evans",
C: "Evander Hockle",
D: "Evander Holyfield",
Answer: "D"
},
{
Question: "In a rugby scrum, which player is responsible for controlling the ball with their feet inside the scrum?",
A: "Fullback",
B: "Tighthead Prop",
C: "Hooker",
D: "Rowler",
Answer: "D"
},
{
Question: "How many times has the host nation won the football World Cup?",
A: "3",
B: "4",
C: "5",
D: "6",
Answer: "D"
},
{
Question: "How deep is the atmosphere that surrounds the Earth?",
A: "About 50 miles",
B: "About 100 miles",
C: "About 400 miles",
D: "About 1000 miles",
Answer: "C"
},
{
Question: "The currents of which ocean produce the El Nino effect?",
A: "Indian",
B: "Atlantic",
C: "Pacific",
D: "Arctic",
Answer: "C"
},
{
Question: "What is the highest point in Antarctica?",
A: "Mount Coman",
B: "Mount Erebus",
C: "Mount Jackson",
D: "Mount Mino",
Answer: "C"
},
{
Question: "Which country shares borders with Egypt, Jordan, Lebanon and Syria?",
A: "Iraq",
B: "Israel",
C: "Oman",
D: "Saudi Arabia",
Answer: "B"
},
{
Question: "Which river flows through the Polish capital, Warsaw?",
A: "Neisse",
B: "Oder",
C: "Vistula",
D: "Warta",
Answer: "C"
},
{
Question: "How many chambers does a normal human heart have?",
A: "2",
B: "4",
C: "6",
D: "8",
Answer: "B"
},
{
Question: "In human body, where is the humerus bone?",
A: "Upper leg",
B: "Lower leg",
C: "Upper arm",
D: "Lower arm",
Answer: "C"
},
{
Question: "Which chemist is best known for the process of heating liquids to destroy harmful organisms?",
A: "Michael Faraday",
B: "Primo Levi",
C: "Alfred Nobel",
D: "Louis Pasteur",
Answer: "D"
},
{
Question: "What colour does blue litmus paper turn under acidic conditions?",
A: "Black",
B: "Green",
C: "Red",
D: "Yellow",
Answer: "C"
},
{
Question: "What is created in space upon the collapse of a neutron star?",
A: "Asteroids",
B: "Black Hole",
C: "Galaxy",
D: "Solar System",
Answer: "B"
},
{
Question: "Which director won a special achievement Oscar for his work on the 1995 Pixar film 'Toy Story'",
A: "Brad Bird",
B: "Mike Judge",
C: "John Lasseter",
D: "Trey Parker",
Answer: "C"
},
{
Question: "What is circling the actual golden globe on the Golden Globe statuette?",
A: "A strip of film",
B: "An airplane",
C: "A movie ticket",
D: "A film script",
Answer: "A"
},
{
Question: "The 2008 film The Curious Case of Benjamin Button is based on the short story by which author?",
A: "Isaac Asimov",
B: "Roald Dahl",
C: "Daphne du Maurier",
D: "F Scott Fitzgerald",
Answer: "D"
},
{
Question: "What nationality is Thomas Keneally, whose novel Schindler's Ark became the 1993 film Schindler's List?",
A: "American",
B: "Australian",
C: "Irish",
D: "South African",
Answer: "B"
},
{
Question: "The 1984 film Children of the Corn is based on a short story from which Stephen King collection?",
A: "Blood and Smoke",
B: "Different Seasons",
C: "Night Shift",
D: "Skeleton Crew",
Answer: "C"
},
{
Question: "Which religious leader was assassinated on 4th April 1968?",
A: "Jesse Jackson",
B: "Martin Luther King",
C: "Mother Theresa",
D: "Pope Paul",
Answer: "B"
},
{
Question: "What nationality was the philosopher and mathematician, Pythagoras?",
A: "Greek",
B: "Persian",
C: "Roman",
D: "Trojan",
Answer: "A"
},
{
Question: "Between 1918 and 1939, how did people refer to World War 1?",
A: "The Big War",
B: "The Continental War",
C: "The European War",
D: "The Great War",
Answer: "D"
},
{
Question: "What was the name of the regime in Germany between 1918 and 1933?",
A: "North German Confederation",
B: "Second German Empire",
C: "Third Reich",
D: "Weimar Republic",
Answer: "D"
},
{
Question: "How was the 'Kingdom of Serbs, Croats and Slovenes' re-named in 1929?",
A: "Bulgaria",
B: "Czechoslovakia",
C: "Romania",
D: "Yugoslavia",
Answer: "D"
},
{
Question: "Pablo Picasso was born in 1881 in which Spanish city?",
A: "Madrid",
B: "Malaga",
C: "Marbella",
D: "Murcia",
Answer: "B"
},
{
Question: "The English artist George Stubbs, who died in 1806, is best remembered for his paintings of what?",
A: "Cats",
B: "Deer",
C: "Dogs",
D: "Horses",
Answer: "D"
},
{
Question: "Hans Holbein the Younger was criticized by Henry VIII for painting a flattering portrait of whom?",
A: "Anne Boleyn",
B: "Anne of Cleves",
C: "Catherine Howard",
D: "Jane Seymour",
Answer: "B"
},
{
Question: "Leonardo da Vinci's famous Mona Lisa was painted on what type of wood?",
A: "Elm",
B: "Mahogany",
C: "Poplar",
D: "Walnut",
Answer: "C"
},
{
Question: "How did Vincent van Gogh die?",
A: "He gassed himself",
B: "He poisoned himself",
C: "He shot himself",
D: "He stabbed himself",
Answer: "C"
}
]; |
// localhost: 8080/find or 8080/findName --> 個人查詢
// localhost: 8080/listSchool
// localhost: 8080/listDepart?School=???
// localhost: 8080/listRoll?depcode=????
var http = require("http");
var url = require("url");
var qs = require("querystring");
var fs = require("fs");
var mysql = require('mysql');
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "uac"
});
db.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
// retrieve query string ==> a['school']
if(request.method == 'POST'){
var body = '';
request.on('data', function(data){
body += data;
});
request.on('end', function(){
var query = qs.parse(body);
main(response, pathname, query);
});
}
else{ // console.log('GET...')
var query = qs.parse(url.parse(request.url).query);
main(response, pathname, query);
}
}).listen(8080, '127.0.0.1', function(){
console.log("HTTP listening at http://%s:%s/",
this.address().address,this.address().port);
});
function main(response, pathname, query){
switch(pathname){
case "/find": uacFind(response, query); break;
case "/findName": uacFindName(response, query); break;
case "/listSchool": uacListSchool(response); break;
case "/listDepart": uacListDepart(response, query); break;
case "/listRoll": uacListRoll(response, query); break;
case "/index.html": case '/index.htm': case "default.html":
case "/": toClient(response, ""); break; // uac.html
default: // /favicon.ico, /uac.css, /uac.js
fs.createReadStream('.' + pathname)
.on('error', function(e){
console.log('Caught', e);
response.end(pathname + ' file not found');
})
.on('readable', function(){this.pipe(response)});
break;
}
}
function uacFindName(response, query){
db.query("select eid,name,school,depname from roll,depart where name like '%" + query['name'] + "%' and roll.depcode = depart.depcode", function (err, result) {
var i, out;
out = '<table>';
for(i=0;i<result.length;i++){
for(j=0;j<4;j++){
if(j % 4 == 0) { out += "<tr>"; }
switch(j){
case 0: out += '<td>' + result[i].eid + '</td>'; break;
case 1: out += '<td>' + result[i].name + '</td>'; break;
case 2: out += '<td>' + result[i].school + '</td>'; break;
case 3: out += '<td>' + result[i].depname + '</td>'; break;
default: break;
}
if(j % 4 == 3) { out += '</tr>'; }
}
}
out += '</table>';
toClient(response, out);
});
}
function uacFind(response, query){
db.query("select eid,name,school,depname from roll,depart where eid like '" + query['eid'] + "%' and roll.depcode = depart.depcode", function (err, result) {
var i, out;
out = '<table>';
for(i=0;i<result.length;i++){
for(j=0;j<4;j++){
if(j % 4 == 0) { out += "<tr>"; }
switch(j){
case 0: out += '<td>' + result[i].eid + '</td>'; break;
case 1: out += '<td>' + result[i].name + '</td>'; break;
case 2: out += '<td>' + result[i].school + '</td>'; break;
case 3: out += '<td>' + result[i].depname + '</td>'; break;
default: break;
}
if(j % 4 == 3) { out += '</tr>'; }
}
}
out += '</table>';
toClient(response, out);
});
}
function uacListSchool(response){
// connect DB
// Query
// Generate table html
// Response
db.query("select distinct school,schcode from depart", function (err, result) {
var i, out;
if (err) throw err;
out = "<table>";
for(i=0;i<result.length;i++){
if(i % 4 == 0) { out += "<tr>"; }
out += '<td><a href = "/listDepart?school=' + result[i].schcode + '">' + result[i].school + '<\a>' + '</td>';
if(i % 4 == 3) { out += '</tr>'; }
}
out += "</table>";
toClient(response, out);
});
}
function uacListDepart(response, query){
db.query("select distinct depname,depcode from depart where schcode='" + query['school'] + "'", function (err, result) {
var i, out;
out = '<table>';
for(i=0;i<result.length;i++){
if(i % 4 == 0) { out += "<tr>"; }
out += '<td><a href = "/listRoll?depcode=' + result[i].depcode + '">' + result[i].depname + '<\a>' + '</td>';
if(i % 4 == 3) { out += '</tr>'; }
}
out += '</table>';
toClient(response, out);
});
}
function uacListRoll(response, query){
db.query("select eid,name from roll where depcode='" + query['depcode'] + "'", function (err, result) {
var i, out;
out = '<table>';
for(i=0;i<result.length;i++){
if(i % 4 == 0) { out += "<tr>"; }
out += '<td>' + result[i].eid + ' ' + result[i].name + '</td>';
if(i % 4 == 3) { out += '</tr>'; }
}
out += '</table>';
toClient(response, out);
});
}
function toClient(response, out){
var str = fs.readFileSync('index.view', "utf8")
response.writeHead(200, {
'Content-Type':'text/html; charset=utf-8;'
});
response.end(str.replace('{{variable}}', out))
} |
// require necessary modules and variables
var express = require('express');
var app = express();
var request = require('request');
var mongo = require('mongodb').MongoClient;
var mongoUrl = process.env.IMAGESEARCH_DB;
var key = process.env.BING_IMAGESEARCH_API_KEY;
var timestamp = require('time-stamp');
// Use the Pug templating language and set the view directory to /views
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
// on home page request
app.get('/', function (req, res) {
res.render('index');
});
// if user requests recent search page
app.get('/recentsearch', function (req, res) {
// search database for history
mongo.connect(mongoUrl, function (err, db) {
if (err) throw err;
var collection = db.collection('searchStrings');
collection.find({}, {
_id: 0
}).toArray(function (err, data) {
if (err) throw err;
res.end(JSON.stringify(data, null, 1));
db.close();
});
});
});
// if user enters a search term
app.get('/:search', function (req, res) {
// parse the url for the term to search and offset
var query = req.params.search;
var offset = req.query.offset;
// define url and options for querying image API
var options = {
url: 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + query + '&count=10&offset=' + offset + '&mkt=en-us&safeSearch=Moderate',
headers: {
'Ocp-Apim-Subscription-Key': key
}
};
// define function that queries image API
function callback (error, response, body) {
// if query is successful
if (!error && response.statusCode == 200) {
// create object to be saved in search history
var searchHistoryObject = {
term: query,
date: timestamp('YYYY/MM/DD'),
time: timestamp('HH:mm:ss')
};
// add the result object to the database
mongo.connect(mongoUrl, function (err, db) {
if (err) throw err;
var collection = db.collection('searchStrings');
collection.insert(searchHistoryObject, function (err, data) {
if (err) throw err;
db.close();
});
});
// take the returned information and send the result to the browser
var info = JSON.parse(body);
var array = [];
for (var i = 0, l = info.value.length; i < l; i++) {
var object = {
url: info.value[i].contentUrl,
snippet: info.value[i].name,
thumbnail: info.value[i].thumbnailUrl,
context: info.value[i].hostPageUrl
};
array.push(object);
}
res.end(JSON.stringify(array, null, 1));
}
}
// query image API with options and callback function
request(options, callback);
});
// listen to port for connections
app.listen(process.env.PORT || 8080, function (request, response) {
console.log('Listening for connections...');
});
|
class Servidor{
constructor(){
this.host='http://localhost/www/vectis/api/v1';
}
requisitar(metodo, router, dados, loading, success, failure, sempre){
$.ajax(
{
method: metodo,
url:this.host+router,
data: dados,
beforeSend: loading(),
statusCode: {
200:function (data, textStatus, xhr){
success(data, textStatus, xhr);
},
201:function (data, textStatus, xhr){
success(data, textStatus, xhr);
}
}
})
.fail(function() {
failure();
})
.always(function() {
sempre();
});
}
}
export {Servidor}; |
var NAVTREEINDEX18 =
{
"structmbedtls__pk__info__t.html":[3,39],
"structmbedtls__pk__info__t.html#a06ccb40c98ee73073c6331a5ea1f757a":[3,39,1],
"structmbedtls__pk__info__t.html#a22771d669b2c952f484564b0335d177b":[3,39,3],
"structmbedtls__pk__info__t.html#a261003b2ae6e795d11ddc0551302c49f":[3,39,4],
"structmbedtls__pk__info__t.html#a5b16c13666997a06e088d48fcce5d5db":[3,39,11],
"structmbedtls__pk__info__t.html#a68cd311c24be8bd9263589debed7bf4d":[3,39,2],
"structmbedtls__pk__info__t.html#a7def926ee797ccd5e2fb1768922b02cf":[3,39,10],
"structmbedtls__pk__info__t.html#a83bcfea941e4f1b47e06a3cdd2f17936":[3,39,6],
"structmbedtls__pk__info__t.html#a8cbee6dfeb285f0614c95bb4458a4a45":[3,39,5],
"structmbedtls__pk__info__t.html#a8f8f80d37794cde9472343e4487ba3eb":[3,39,8],
"structmbedtls__pk__info__t.html#ac5fb1e013b8dd33fe7e8af329889641e":[3,39,0],
"structmbedtls__pk__info__t.html#ae54f4425d06a14e890316680e67fcef3":[3,39,7],
"structmbedtls__pk__info__t.html#af92f6ff19b671424b1b9328ec542e765":[3,39,9],
"structmbedtls__ssl__config.html":[3,51],
"structmbedtls__ssl__config.html#a0c497488517185bc2192e13025e0366d":[3,51,39],
"structmbedtls__ssl__config.html#a13a261abae5465d385b3e02a96a6354c":[3,51,46],
"structmbedtls__ssl__config.html#a1b0f754e4dc8091bcc3d0df9101dec8d":[3,51,35],
"structmbedtls__ssl__config.html#a1cd2a5f224d7f87a8a60f495eaa2bb4a":[3,51,33],
"structmbedtls__ssl__config.html#a1fb9c03f836bb312fab6ffcdc415b22f":[3,51,15],
"structmbedtls__ssl__config.html#a248164e33dd01af5d5b09ccbe93f67e9":[3,51,45],
"structmbedtls__ssl__config.html#a3191c7e23749897d9a3684e80601e97c":[3,51,50],
"structmbedtls__ssl__config.html#a33b74a41f2ee04a5ca2efd56eade0d06":[3,51,37],
"structmbedtls__ssl__config.html#a452a2f86c0657b1fabd9c63408a1aa3a":[3,51,59],
"structmbedtls__ssl__config.html#a469952cb1c57f2e343d90b4927551bc4":[3,51,36],
"structmbedtls__ssl__config.html#a479186944896d7f5639942a92d906ec4":[3,51,54],
"structmbedtls__ssl__config.html#a4a73023729b06d5bd891366d88926808":[3,51,21],
"structmbedtls__ssl__config.html#a4dbf356fb4f99cf6fef184822771ca3c":[3,51,6],
"structmbedtls__ssl__config.html#a5042dae63a877a8a73232a75d5f6e0a8":[3,51,1],
"structmbedtls__ssl__config.html#a50e4a03a6a94ee0b28689931aa933859":[3,51,48],
"structmbedtls__ssl__config.html#a545e318b5b6f1f1da19a2c97c08ef9a1":[3,51,14],
"structmbedtls__ssl__config.html#a5691241728b9d162bbff17b4bd2d1480":[3,51,3],
"structmbedtls__ssl__config.html#a5a7203385717a71cc0fcc548e2b0c634":[3,51,17],
"structmbedtls__ssl__config.html#a63e2b2113a08c6f39e09a594c0799143":[3,51,11],
"structmbedtls__ssl__config.html#a66e195aa6434b66eb6ecbc55f0b6bd12":[3,51,27],
"structmbedtls__ssl__config.html#a67fb22c0e6e12438470e5dafadf2ab45":[3,51,8],
"structmbedtls__ssl__config.html#a6d6337df6883392da487f1d367e71878":[3,51,44],
"structmbedtls__ssl__config.html#a73ab22228e8c93cc3acc3c6391860cd5":[3,51,7],
"structmbedtls__ssl__config.html#a764308c6df87c11a9365c61e884aa758":[3,51,56],
"structmbedtls__ssl__config.html#a7753a0b5cebe5fe3602337929ffbda03":[3,51,53],
"structmbedtls__ssl__config.html#a7c73fcd751f80f4da9e23466c6caf859":[3,51,22],
"structmbedtls__ssl__config.html#a7fffc2bfb7c1a08603cfe20f42770496":[3,51,2],
"structmbedtls__ssl__config.html#a8bb7495a1d7a3d6d141134cbb87b5492":[3,51,58],
"structmbedtls__ssl__config.html#a8c8781fa4dc8654cd0528eb99622b82c":[3,51,9],
"structmbedtls__ssl__config.html#a9092ca18b9c74e384edbcfc5dae1f70e":[3,51,47],
"structmbedtls__ssl__config.html#aa1a12bd21d732b49e5193b4368732400":[3,51,60],
"structmbedtls__ssl__config.html#aa570c565121dabd5f8ec889e905f22bf":[3,51,34],
"structmbedtls__ssl__config.html#aabdccfd923300c6d49c02538d13f14f9":[3,51,25],
"structmbedtls__ssl__config.html#aac69a123e5ba5cf9efb2ab44a3d1b560":[3,51,42],
"structmbedtls__ssl__config.html#ab509fc82f2b0526b44c4cefb301b2d72":[3,51,19],
"structmbedtls__ssl__config.html#ab88ccdd73e81bdf8d6872ba5f3bda16c":[3,51,40],
"structmbedtls__ssl__config.html#abb8388c055f9ebb1897b557de4ce6f1f":[3,51,4],
"structmbedtls__ssl__config.html#abf2ef319b36e410c545bbbef6351ac4c":[3,51,38],
"structmbedtls__ssl__config.html#abf4df78ef11e769cad0bc0d47e9b6665":[3,51,43],
"structmbedtls__ssl__config.html#ac2714ab3d34b4abb619dd701546ea4d2":[3,51,49],
"structmbedtls__ssl__config.html#ac52778e4fe113a300866a486f807b9e8":[3,51,18],
"structmbedtls__ssl__config.html#ac5f0b777ed269512e05698cd5d7349c8":[3,51,20],
"structmbedtls__ssl__config.html#aca5e8f03d96555c84d03f0bbdb815957":[3,51,41],
"structmbedtls__ssl__config.html#ad324a74982ba9e885c65dad808bda124":[3,51,5],
"structmbedtls__ssl__config.html#ad56991b0d7ddd6a5e7f83ccbd560890d":[3,51,52],
"structmbedtls__ssl__config.html#ad89d3fdb90bf043eb63d0e7d8131ada1":[3,51,55],
"structmbedtls__ssl__config.html#ad8dc3fde5f2fa7cb11adb2d40ff5afad":[3,51,32],
"structmbedtls__ssl__config.html#adb796c49f3f6e9a6d20e944a0f94c634":[3,51,0],
"structmbedtls__ssl__config.html#ae84775c68bc9e198857d0b21f264fd5f":[3,51,31],
"structmbedtls__ssl__config.html#ae8cc337864c120947ba47ab22c1f04ab":[3,51,29],
"structmbedtls__ssl__config.html#aee330bfee8bc98a35a78234f2333df37":[3,51,30],
"structmbedtls__ssl__config.html#af03c70b95eda47ba1464940666108329":[3,51,12],
"structmbedtls__ssl__config.html#af1b621b4795ddd3c292b8de9b61e7d31":[3,51,13],
"structmbedtls__ssl__config.html#af1c8c4f77902b60c9a1a0c0c2fc8f204":[3,51,10],
"structmbedtls__ssl__config.html#af3d8599c2dd5d5440e2f909ed781338d":[3,51,24],
"structmbedtls__ssl__config.html#af45d566fab67fafbe64367d5f6ff1557":[3,51,28],
"structmbedtls__ssl__config.html#af71a2b01db3b11d2fb26dec452915b1d":[3,51,23],
"structmbedtls__ssl__config.html#af8011592d17318205e0da577d4f5ceb6":[3,51,51],
"structmbedtls__ssl__config.html#af8c60af6c1d9f79ced1b7697fc678cb4":[3,51,16],
"structmbedtls__ssl__config.html#afbdd3e3d4aa269028984b60c0ffcbd86":[3,51,57],
"structmbedtls__ssl__config.html#afec1e321dc7e485061c4fc4c3c6c1909":[3,51,26],
"structmbedtls__ssl__handshake__params.html":[3,55],
"structmbedtls__ssl__handshake__params.html#a06b13bcec5a1f9ab012c05e2ffa9c16c":[3,55,36],
"structmbedtls__ssl__handshake__params.html#a138fefb99eabc43992992afec0ad6103":[3,55,18],
"structmbedtls__ssl__handshake__params.html#a150d102ea5b7a9309f180a6db10fb2dd":[3,55,8],
"structmbedtls__ssl__handshake__params.html#a1b0f754e4dc8091bcc3d0df9101dec8d":[3,55,19],
"structmbedtls__ssl__handshake__params.html#a1bb17a892f54fc9f8a3607002ca7f9f2":[3,55,12],
"structmbedtls__ssl__handshake__params.html#a1bb2f28126ddf5e240d9401eb0a75a95":[3,55,10],
"structmbedtls__ssl__handshake__params.html#a3191c7e23749897d9a3684e80601e97c":[3,55,26],
"structmbedtls__ssl__handshake__params.html#a39963d55545194c9c44237bf460d336a":[3,55,33],
"structmbedtls__ssl__handshake__params.html#a475477f33fa27fe8d7205053877e0260":[3,55,32],
"structmbedtls__ssl__handshake__params.html#a48798379e4834c4d43004ea61aa6a143":[3,55,21],
"structmbedtls__ssl__handshake__params.html#a4b044140d58ca0dacb548c913d24f10e":[3,55,31],
"structmbedtls__ssl__handshake__params.html#a4f4ca6f6b63196ce7adb533bafab8ee1":[3,55,11],
"structmbedtls__ssl__handshake__params.html#a55b7a4217e859d7329e3918c167e454e":[3,55,3],
"structmbedtls__ssl__handshake__params.html#a56e5ff06593a6b2efb09bcf72bba4d66":[3,55,29],
"structmbedtls__ssl__handshake__params.html#a5e9673879028934909edde9ed5120b3e":[3,55,38],
"structmbedtls__ssl__handshake__params.html#a6fcd07a3418fac0c628da9cc5f950ba0":[3,55,34],
"structmbedtls__ssl__handshake__params.html#a7753a0b5cebe5fe3602337929ffbda03":[3,55,27],
"structmbedtls__ssl__handshake__params.html#a7f46db10a3c1da81940f0bca22be0e08":[3,55,24],
"structmbedtls__ssl__handshake__params.html#a811135955dd3fc99ea1ae7acd051fe1d":[3,55,20],
"structmbedtls__ssl__handshake__params.html#a88555b81d17042521cd47e209a4227e9":[3,55,5],
"structmbedtls__ssl__handshake__params.html#a88e3198fe0b700d62d8926dc0232dcb4":[3,55,16],
"structmbedtls__ssl__handshake__params.html#a900208a96df705aea0f433297b55cd88":[3,55,22],
"structmbedtls__ssl__handshake__params.html#aa09ddae8f5840b08cdef576adb657862":[3,55,39],
"structmbedtls__ssl__handshake__params.html#aa19d2729cde127760510b625627de5f2":[3,55,14],
"structmbedtls__ssl__handshake__params.html#aa26b43f41f92ff05e32ada8f2d27f86c":[3,55,23],
"structmbedtls__ssl__handshake__params.html#aa741cb74ff70776142d63a905f3b7584":[3,55,28],
"structmbedtls__ssl__handshake__params.html#aaeec72ace979f52fb6fe2c6e57a679ce":[3,55,2],
"structmbedtls__ssl__handshake__params.html#ab366e5ddb8250622cb5da9c09b4cb41c":[3,55,4],
"structmbedtls__ssl__handshake__params.html#ab53ec1453a9c4a1f324379a9ee7207a6":[3,55,35],
"structmbedtls__ssl__handshake__params.html#ae1d00dd76ab31ce937be7929fcb14a41":[3,55,13],
"structmbedtls__ssl__handshake__params.html#ae5a842180e8758119f629656e8f89983":[3,55,37],
"structmbedtls__ssl__handshake__params.html#ae6caa77d122dc46ea438e749e2d8b008":[3,55,7],
"structmbedtls__ssl__handshake__params.html#ae71d2834ffb25c6ccbce2fc645eadc33":[3,55,30],
"structmbedtls__ssl__handshake__params.html#ae9ae5c1490e5959e942d32fa2ace7522":[3,55,0],
"structmbedtls__ssl__handshake__params.html#aed047ad2e16f4075f0da5ab0e1ca0212":[3,55,6],
"structmbedtls__ssl__handshake__params.html#aed1bab861bddc7d6c228c28de0cf92c1":[3,55,17],
"structmbedtls__ssl__handshake__params.html#af28311c0979b96406e212d8d093c4e06":[3,55,9],
"structmbedtls__ssl__handshake__params.html#af4df1eca33654e0c6f63ac541a417fcd":[3,55,25],
"structmbedtls__ssl__handshake__params.html#af8e2490edc6f03a9e8d9439727072b49":[3,55,1],
"structmbedtls__ssl__handshake__params.html#afa0a1c818dc999923a00e3e98529549b":[3,55,15],
"structmbedtls__ssl__ticket__context.html":[3,60],
"structmbedtls__ssl__ticket__context.html#a13a261abae5465d385b3e02a96a6354c":[3,60,3],
"structmbedtls__ssl__ticket__context.html#a8b27935047c6e270fb9711329943d92f":[3,60,0],
"structmbedtls__ssl__ticket__context.html#ab214c0e70097a959dfcf0337e892089c":[3,60,4],
"structmbedtls__ssl__ticket__context.html#ac028823414417f22d7ad117a0d4a08e6":[3,60,2],
"structmbedtls__ssl__ticket__context.html#afec1e321dc7e485061c4fc4c3c6c1909":[3,60,1],
"threading_8h.html":[6,0,0,0,63],
"threading_8h.html#a51005c51b928706511d3c2ea3390c07f":[6,0,0,0,63,2],
"threading_8h.html#a76cd79a1ed3fd583ed3a4428d6a1e967":[6,0,0,0,63,0],
"threading_8h.html#ad3cbda6bbb5ce837b33ada893d7d5613":[6,0,0,0,63,1],
"timing_8h.html":[6,0,0,0,64],
"timing_8h.html#a07be11c04f52077314018401de1a6833":[3,63,1],
"timing_8h.html#a2e070a66ff65e5471c6cfc3bd656678e":[3,63,2],
"timing_8h.html#a427660928e1e0339d497390c167f895c":[6,0,0,0,64,4],
"timing_8h.html#a7ea7574e836da0dc51b4b16c4033ede3":[6,0,0,0,64,2],
"timing_8h.html#aa832a2e14723215d909150c337199f53":[6,0,0,0,64,6],
"timing_8h.html#aeb3497ab85adabf7db89d81c34e2ef92":[6,0,0,0,64,7],
"timing_8h.html#aed3e49dc460ada48c51a6ce54909bc4d":[3,64,0],
"timing_8h.html#aeec9ae2577ce34ab01f2d213b99d07e1":[6,0,0,0,64,5],
"timing_8h.html#af5df1e20d5197a5af9f5daba5b6ca654":[6,0,0,0,64,8],
"timing_8h.html#afb1705e8c4227b0ec03089aa7fc54d9b":[6,0,0,0,64,3],
"timing_8h.html#afbd3bf54d6faaa5de7b062795b04d069":[3,63,0],
"timing_8h.html#structmbedtls__timing__delay__context":[3,63],
"timing_8h.html#structmbedtls__timing__hr__time":[3,64],
"version_8h.html":[6,0,0,0,65],
"version_8h.html#a1433dae2f973235284ed1b1390e585be":[6,0,0,0,65,4],
"version_8h.html#a3d780043d5104f5e5863255dd55b3951":[6,0,0,0,65,7],
"version_8h.html#a5a7d810a2d7cf4dd3ef85fd9fa3175d5":[6,0,0,0,65,0],
"version_8h.html#a64cf9914ef37c1d591dea65bd99e5f6e":[6,0,0,0,65,1],
"version_8h.html#a779eef1940de834a3d223a2339c2a9bb":[6,0,0,0,65,9],
"version_8h.html#aa3672345ea6deef6e023fcecdee97820":[6,0,0,0,65,5],
"version_8h.html#aa507dab4f28a259909714c4c50cccfc7":[6,0,0,0,65,3],
"version_8h.html#adb4f54ebb33fd1a25e2c4d4480cf4936":[6,0,0,0,65,2],
"version_8h.html#af4fd0e3ea2523313ea177477d6c93bdd":[6,0,0,0,65,8],
"version_8h.html#afe471be7bb2bd441b0c693256ab298ea":[6,0,0,0,65,6],
"x509_8h.html":[6,0,0,0,66],
"x509_8h.html#a02a696da4dcf947d016872f9c51a03a8":[6,0,0,0,66,42],
"x509_8h.html#a061f9945351822e8ccbeb7f3d7fc4fe3":[6,0,0,0,66,99],
"x509_8h.html#a0c0fe57c57131ca34311a993cb39757a":[6,0,0,0,66,43],
"x509_8h.html#a0dc99e9a29593ae1ab51361870b5e555":[6,0,0,0,66,71],
"x509_8h.html#a0de4dd2a5d7fe95fa9b94e19260e29cf":[6,0,0,0,66,100],
"x509_8h.html#a0fbc580797ae0f47e82baddd145eace0":[6,0,0,0,66,55],
"x509_8h.html#a106a78f332b05b10010d01e3c8234ee0":[6,0,0,0,66,98],
"x509_8h.html#a11036f8e61fb3a5433508720360c8bfa":[6,0,0,0,66,70],
"x509_8h.html#a125c85f0064135e1e35179df7d3a76b6":[6,0,0,0,66,102],
"x509_8h.html#a158d0b17cd5ef8fa250f50129c46768b":[6,0,0,0,66,87],
"x509_8h.html#a178dff35633f812860ff7abe7898a8a8":[6,0,0,0,66,72],
"x509_8h.html#a192bfcae14f9e4a8f8ba8ebcb00a24e8":[6,0,0,0,66,57],
"x509_8h.html#a1b6eb7a40a7f4f1b86d15e164543b536":[6,0,0,0,66,86],
"x509_8h.html#a1f04b1b5b387bccc5ae75226a0ddd59c":[6,0,0,0,66,51],
"x509_8h.html#a29722a5dd951872c1b3043bef6896372":[6,0,0,0,66,54],
"x509_8h.html#a2d4212e9f556d819dcf18ada06a22101":[6,0,0,0,66,61],
"x509_8h.html#a31fc57928d31156729c4a18726044bfd":[6,0,0,0,66,60],
"x509_8h.html#a33fbc6a4a09d4503e7d7a7c5f6124a5d":[6,0,0,0,66,95],
"x509_8h.html#a379c1cbfec75822feb6ab8dd470f2f5f":[6,0,0,0,66,75],
"x509_8h.html#a435813d11986e4ffc168e13637b66f26":[6,0,0,0,66,69],
"x509_8h.html#a4787303446416e810ef20d7dcd9b993e":[6,0,0,0,66,101],
"x509_8h.html#a576f34a7432238db229137bdfc3cfde0":[6,0,0,0,66,82],
"x509_8h.html#a632958cb9a2a77af495536a40e1b9fef":[6,0,0,0,66,76],
"x509_8h.html#a6937b6cde9a8a30a3967b6c2288e9d2d":[6,0,0,0,66,64],
"x509_8h.html#a6a66d211cc827839cf46a7dfcb849dc0":[6,0,0,0,66,93],
"x509_8h.html#a6d841aa6a9b81bf0b5d5877ef7a1c11a":[6,0,0,0,66,84],
"x509_8h.html#a77cab17825808958ed405b67a7cad14a":[6,0,0,0,66,46],
"x509_8h.html#a81fb8d771984fe590760da1b7007b61d":[6,0,0,0,66,52],
"x509_8h.html#a831422b2f74283a90bf6f2e88113b5f8":[6,0,0,0,66,74],
"x509_8h.html#a85cc3f91cf3f351fe1b32355da908e50":[6,0,0,0,66,44],
"x509_8h.html#a8c6f90558dfc5ee7d4fedd90bfd8fe6a":[6,0,0,0,66,77],
"x509_8h.html#a8cea7dde1e6f17a99415b67c801ad2e1":[6,0,0,0,66,90],
"x509_8h.html#a93d7df2e17bb972b8910275b94580d46":[6,0,0,0,66,41],
"x509_8h.html#a96a6e579899dff8e0669977605a85178":[6,0,0,0,66,83],
"x509_8h.html#a9a361131f89cd27e19449c991705c0f3":[6,0,0,0,66,58],
"x509_8h.html#aac564b3b46292f598770e5f825460247":[6,0,0,0,66,85],
"x509_8h.html#ab2e4125f34eb6332cca653eccc8a1993":[6,0,0,0,66,66],
"x509_8h.html#ab5b0754499cfd36d9adf0b784f2481fe":[6,0,0,0,66,48],
"x509_8h.html#ab8d3394563832fc0b9e66631b8f188f3":[6,0,0,0,66,53],
"x509_8h.html#aba59e2cdba4bbf669d2515004c438643":[6,0,0,0,66,92],
"x509_8h.html#abce173357d84bc4597b12952a193011c":[6,0,0,0,66,63],
"x509_8h.html#abd29bada76bd07d4357cc15ed0596a4e":[6,0,0,0,66,62],
"x509_8h.html#abdee54b2daa69c504a66354b9e5ba3b8":[6,0,0,0,66,47],
"x509_8h.html#ac5eabb45f2953ac5c82487266614f50e":[6,0,0,0,66,96],
"x509_8h.html#ad0b8a43901d61cb6867a9178e803afa1":[6,0,0,0,66,88],
"x509_8h.html#ad0c7bf2f1f2d64d8285687330c889d78":[6,0,0,0,66,45],
"x509_8h.html#ad1af83d0566030d2c2e61c49044f718a":[6,0,0,0,66,89],
"x509_8h.html#ad323fe050402e90118e2613aaf234691":[6,0,0,0,66,56],
"x509_8h.html#ad3c4beaae071ce4418697df9c0950021":[6,0,0,0,66,59],
"x509_8h.html#ad63ce81102efc0a907a044722f8da888":[6,0,0,0,66,91],
"x509_8h.html#ad7e93b186781f0474f8662fb2a83c370":[6,0,0,0,66,65],
"x509_8h.html#ad8156eef3be25ded825bae1b153650f3":[6,0,0,0,66,40],
"x509_8h.html#add098308e1fa17307e23fbacba7b15d5":[6,0,0,0,66,50],
"x509_8h.html#ae08ff254e779a13bd567f877400de7f9":[6,0,0,0,66,67],
"x509_8h.html#ae492fe84ffb9c79e5529103b89bc653b":[6,0,0,0,66,49],
"x509_8h.html#ae9295ed52a01788c7f8e52c850c251d4":[6,0,0,0,66,73],
"x509_8h.html#af9b151018f1d275c4228c4730cd1c0aa":[6,0,0,0,66,97],
"x509_8h.html#af9ce1b81550ac7290706f99c71150e4d":[6,0,0,0,66,94],
"x509_8h.html#ga022c175386f082b4e056e6268ee68cab":[6,0,0,0,66,14],
"x509_8h.html#ga0e5b1d4c9c1a1a3227238c82042c1d1b":[6,0,0,0,66,29],
"x509_8h.html#ga182a6f1f465e566de7586e6ee8fa7c4e":[6,0,0,0,66,36],
"x509_8h.html#ga185bc7f27a2b1f7742537a2377c52ee3":[6,0,0,0,66,6],
"x509_8h.html#ga1b87b2e1d26077023adf2a5c65a76776":[6,0,0,0,66,33],
"x509_8h.html#ga2272228c7776102328df31623af3168c":[6,0,0,0,66,80],
"x509_8h.html#ga28705c8c3091a013487df25842249c0f":[6,0,0,0,66,27],
"x509_8h.html#ga41b54b526c11bf51cc431ef1a151816d":[6,0,0,0,66,21],
"x509_8h.html#ga45b8366804b7e2cbf3e25011f054802c":[6,0,0,0,66,11],
"x509_8h.html#ga488f8616b42eae6fe3fb9815d43c976f":[6,0,0,0,66,18],
"x509_8h.html#ga4d02c9e8e4e2934555e0d132cd2976dc":[6,0,0,0,66,79],
"x509_8h.html#ga50086f9edc8482b5e6b6e53c647d37ea":[6,0,0,0,66,5],
"x509_8h.html#ga527608dc04b2c831fe5b161ec26aab76":[6,0,0,0,66,15],
"x509_8h.html#ga5f03158dcacc5914872e38c68231b642":[6,0,0,0,66,24],
"x509_8h.html#ga6e71468985ebf243ca7cfce5c3dea881":[6,0,0,0,66,23],
"x509_8h.html#ga76bdd50937a671ef62474b7e38e23e02":[6,0,0,0,66,31],
"x509_8h.html#ga8124a68edabf35ed9323880584128f16":[6,0,0,0,66,13],
"x509_8h.html#ga8bca03e3c2c89460bea17ab142b0b7ab":[6,0,0,0,66,28],
"x509_8h.html#ga8f61c2f303bf065af4f783e03f952ede":[6,0,0,0,66,12],
"x509_8h.html#ga9332fa1e09a373cc56234525b14546c4":[6,0,0,0,66,22],
"x509_8h.html#gaa0788dbf0325aea4ab566717514b4422":[6,0,0,0,66,10],
"x509_8h.html#gaa383ae441177fa7a16fb2313bb48bb10":[6,0,0,0,66,30],
"x509_8h.html#gab4e8e2e41bfe62e969343efaa2784103":[6,0,0,0,66,17],
"x509_8h.html#gab80a4eb806328731def21ec2ebcbc365":[6,0,0,0,66,19],
"x509_8h.html#gab9516fc53ff90c547fd77d35c71feec7":[6,0,0,0,66,2],
"x509_8h.html#gab98caf7dfede54b5c576b5a27a5c6a6a":[6,0,0,0,66,68],
"x509_8h.html#gaba46df0041dcf48fa9d164d28cf3a154":[6,0,0,0,66,4],
"x509_8h.html#gabd52d60a09315854d9ef849d02154f35":[6,0,0,0,66,81],
"x509_8h.html#gac2947ead6fd1035296826110ca74a364":[6,0,0,0,66,34],
"x509_8h.html#gac36bf085ce8f7f57f039bda8828bd824":[6,0,0,0,66,9],
"x509_8h.html#gac3dab3183efdbca7e988916e7fc1a02a":[6,0,0,0,66,25],
"x509_8h.html#gac489ce5e8ba417bcd86012ebbb7f5044":[6,0,0,0,66,16],
"x509_8h.html#gac769acbb18e53198ae2d2e63bd339cfa":[6,0,0,0,66,26],
"x509_8h.html#gacf6d98c6cbb76728260d1dcb1fe3bc7d":[6,0,0,0,66,0],
"x509_8h.html#gad1da8228ca957c2947fd329c32fc7ca4":[6,0,0,0,66,39],
"x509_8h.html#gad3f810fb74f94164185b88b90fffa329":[6,0,0,0,66,35],
"x509_8h.html#gad85d9c7aa5c30b9730297bef3386407c":[6,0,0,0,66,7],
"x509_8h.html#gad93c0f614969729f7d13fb0a3acac68e":[6,0,0,0,66,38],
"x509_8h.html#gaddd96a9eb80fab17bce02d2a147ea504":[6,0,0,0,66,32],
"x509_8h.html#gae16cddbd42e08f6dd093cf4326e59413":[6,0,0,0,66,8]
};
|
const pactum = require('../../src/index');
const request = pactum.request;
describe('Default Recorder', () => {
before(() => {
request.setDefaultRecorders('TraceId', 'req.headers.x-trace-id');
request.setDefaultRecorders('Method', 'req.body.method');
request.setDefaultRecorders('Connection', 'res.headers.connection');
request.setDefaultRecorders('Path', 'res.body.path');
});
it('res header data to recorder', async () => {
await pactum.spec()
.useInteraction('default get')
.get('http://localhost:9393/default/get')
.expectStatus(200);
});
it('req header & res body to recorder', async () => {
await pactum.spec()
.useInteraction('default get')
.get('http://localhost:9393/default/get')
.withHeaders('x-trace-id', 'id')
.expectStatus(200);
});
it('req body data to recorder', async () => {
await pactum.spec()
.useInteraction('default post')
.post('http://localhost:9393/default/post')
.withJson({
method: 'POST',
path: '/default/post'
})
.expectStatus(200);
});
after(() => {
request.getDefaultRecorders().length = 0;
});
});
describe('Recorder', () => {
it('res header data to recorder', async () => {
await pactum.spec()
.useInteraction('default get')
.get('http://localhost:9393/default/get')
.records('Method', 'method')
.records('Path', 'res.body.path')
.expectStatus(200);
});
it('res header data to recorder using capture handler', async () => {
pactum.handler.addCaptureHandler('GetMethod', ({ res }) => res.json.method);
const spec = pactum.spec();
await spec
.useInteraction('default get')
.get('http://localhost:9393/default/get')
.records('Method', '#GetMethod')
.expectStatus(200);
spec.records('Path', 'res.body.path');
});
after(() => {
request.getDefaultRecorders().length = 0;
});
}); |
import React, { Component } from 'react';
import './Zap1.css';
import Web3 from 'web3';
import AavUniZap from '../abis/AavUniZap.json'
import LendingPool from '../abis/LendingPool.json'
import LendingPoolCore from '../abis/LendingPoolCore.json'
class Zap3 extends Component {
/*async componentMount() {
await this.loadWeb3()
await this.loadBlockchainData()
let result2 = await this.state.lendingpool.methods.getUserAccountData("0x48c0d7f837fcad83e48e51e1563856fb1d898d01").call({ from: this.state.account });
console.log(result2)
let result1 = await this.state.lendingpool.methods.getUserReserveData("0xf80A32A835F79D7787E8a8ee5721D0fEaFd78108","0x48c0d7f837fcad83e48e51e1563856fb1d898d01").call({ from: this.state.account })
console.log(result1);
}
*/
async loadBlockchainData() {
const accounts = await this.state.web3.eth.getAccounts()
this.setState({ account: accounts[0] })
console.log(this.state.account);
const ethBalance = await this.state.web3.eth.getBalance(this.state.account)
this.setState({ ethBalance })
console.log(ethBalance);
// Load Aaveunizap
const networkId = await this.state.web3.eth.net.getId();
console.log(networkId);
const aaveunizapdata1 = "0x48c0d7f837fcad83e48e51e1563856fb1d898d01"
const aaveunizapdata2 = "0xb5A0C6C3A0FbE2BD112200209f2111dD62DFf57C"
const aaveunizapdata3 = "0x9E5279e813Bf799D9D00C7a4aa0c46bCe1F6Cf87"
if(aaveunizapdata1) {
const aaveunizap1 = new this.state.web3.eth.Contract(AavUniZap.abi, aaveunizapdata1)
const aaveunizap2 = new this.state.web3.eth.Contract(AavUniZap.abi, aaveunizapdata2)
const aaveunizap3 = new this.state.web3.eth.Contract(AavUniZap.abi, aaveunizapdata3)
console.log(aaveunizap1);
const contractAddress1 = "0xa03105cc79128d7d67f36401c8518695c08c7d0c"
const lendingpool = this.state.web3.eth.Contract(LendingPool, contractAddress1)
console.log(lendingpool);
const contractAddres2 = "0x07Cdaf84340410ca8dB93bDDf77783C61032B75d"
const lendingpoolcore = this.state.web3.eth.Contract(LendingPoolCore, contractAddres2)
console.log(lendingpoolcore);
this.setState({ aaveunizap1 })
this.setState({ aaveunizap2 })
this.setState({ aaveunizap3 })
this.setState({ lendingpool })
this.setState({ lendingpoolcore })
} else {
window.alert('Token contract not deployed to detected network.')
}
}
async loadWeb3() {
if (window.ethereum) {
const web3 = new Web3(window.ethereum)
await window.ethereum.enable()
this.setState({ web3 })
}
else if (window.web3) {
const web3 = new Web3(window.web3.currentProvider)
this.setState({ web3 })
}
else {
window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!')
}
}
buyTokens = async (tokenAmount,etherAmount) => {
let result;
console.log(tokenAmount);
console.log(etherAmount);
result = await this.state.aaveunizap1.methods.zappify("100000000000000000000000000000000000000000000000000000000000").send({ value: etherAmount, from: this.state.account }).on('transactionHash', (hash) => {
})
}
buyTokens1 = async (tokenAmount1,etherAmount1) => {
let result;
console.log(tokenAmount1);
console.log(etherAmount1);
result = await this.state.aaveunizap2.methods.zappify("100000000000000000000000000000000000000000000000000000000000").send({ value: etherAmount1, from: this.state.account }).on('transactionHash', (hash) => {
})
}
buyTokens2 = async (tokenAmount2,etherAmount2) => {
let result;
console.log(tokenAmount2);
console.log(etherAmount2);
result = await this.state.aaveunizap3.methods.zappify("100000000000000000000000000000000000000000000000000000000000").send({ value: etherAmount2, from: this.state.account }).on('transactionHash', (hash) => {
})
}
click = async() => {
try {
await this.loadWeb3()
await this.loadBlockchainData()
let result2 = await this.state.lendingpool.methods.getUserAccountData("0x48c0d7f837fcad83e48e51e1563856fb1d898d01").call({ from: this.state.account });
console.log(result2)
let result1 = await this.state.lendingpool.methods.getUserReserveData("0xf80A32A835F79D7787E8a8ee5721D0fEaFd78108","0x48c0d7f837fcad83e48e51e1563856fb1d898d01").call({ from: this.state.account })
console.log(result1);
this.setState({color: '#0ff279'});
this.setState({buttonText:"Connected"});
} catch(err) {
this.setState({color: '#85f7ff'});
this.setState({buttonText: "Tryagain"});
}
}
constructor(props) {
super(props)
this.state = {
account: '',
lendingpool:{},
lendingpoolcore:{},
output:'',
output1:'',
output2:'',
color: '#85f7ff',
buttonText: "Connect"
}
}
render() {
return (
<div>
<nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
<div
className="navbar-brand col-sm-3 col-md-2 mr-0">
Leveraged Zap
</div>
<button onClick = {this.click} className="button1" style={{backgroundColor: this.state.color }}>{this.state.buttonText}</button>
</nav>
<div className="items">
<form className="mb-3" onSubmit={(event) => {
event.preventDefault()
let etherAmount2, tokenAmount2
etherAmount2 = this.input.value
tokenAmount2 = etherAmount2*20;
etherAmount2 = this.state.web3.utils.toWei(etherAmount2.toString(), 'ether')
tokenAmount2 = this.state.web3.utils.toWei(tokenAmount2.toString(), 'ether')
this.buyTokens2(tokenAmount2,etherAmount2)
}}>
<div>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex text-center">
<div className="content mr-auto ml-auto">
<div id="container3">
<div className="title">aUNI-SETH-ETH Zap</div>
<div className="outer-circle">
<div className="inner-circle">
APY
</div>
</div>
<div className="input-box">
<div className="eth">ETH</div>
<div className="amount">
<input
type="text"
onChange={(event) => {
const etherAmount2 = this.input.value.toString()
this.setState({
output2: etherAmount2
})
console.log(this.state.output2);
}}
ref={(input) => { this.input = input }}
className="form-control form-control-lg"
placeholder="0"
required />
</div>
<div className="zap">
<button type="submit" className="button1">ZAP!</button>
</div>
</div>
</div>
<div className="health-factor">Health factor :Safe</div>
</div>
</main>
</div>
</div>
</div>
</form>
</div>
</div>
);
};
}
export default Zap3;
|
import { connect } from 'react-redux';
import Characteristics from '../components/Characteristics';
import {onChangeCharac} from '../actions';
import {refreshProposals} from '../actions';
import {generateChars} from '../actions';
import {toogleCheaterMode, refreshDetails} from '../actions';
const mapStateToProps = (state) => {
return {
characteristics: state.characteristics,
isCheater : state.isCheater
}
};
const mapDispatchToProps = (dispatch) => {
return {
onChange: (char, event) => {
dispatch(onChangeCharac(char, Number(event.target.value)));
dispatch(refreshProposals());
dispatch(refreshDetails());
},
onGenerateClick: () => {
dispatch(generateChars());
dispatch(refreshProposals());
dispatch(refreshDetails());
},
onCheaterSwitchClick: () => {
dispatch(toogleCheaterMode())
}
}
};
const CharacteristicsContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Characteristics);
export default CharacteristicsContainer; |
var toggle = document.querySelector('.page-header__toggle');
var topNavList = document.querySelector('.page-header__items');
var pageHeader = document.querySelector('.page-header__nav');
var sliderPaginaton = document.querySelectorAll('.slider__pagination');
//burger menu toggle
toggle.addEventListener('click', function () {
this.classList.toggle('page-header__toggle--active');
topNavList.classList.toggle('page-header__items--active');
pageHeader.classList.toggle('page-header__nav--active');
});
//slider
sliderPaginaton.forEach(function (item) {
item.addEventListener('click', function (e) {
var toggle = e.target;
if (toggle.tagName != "LI") return;
var slidesCount = toggle.parentElement.childElementCount;
var toggleIndex = -1;
//find index of selected toggle
for(var i = 0; i < slidesCount; i++) {
if (toggle === toggle.parentElement.children[i]) {
toggleIndex = i;
}
}
if (toggleIndex == -1) return;
var sliderList = toggle.parentElement.parentElement.firstElementChild;
console.log(sliderList);
var slides = toggle.parentElement.parentElement.firstElementChild.children;
var slideWidth = slides[0].clientWidth;
sliderList.style.marginLeft = -slideWidth * toggleIndex + 'px';
});
}); |
// OH SNAP NOT ONLY ARE MY INVADERS COMPONENT-BASED ENTITIES, WITH ONE OF THOSE COMPONENTS BEING
// A FINITE STATE AUTOMATON, BUT THE STATES THEMSELVES ARE COMPONENT-BASED ENTITIES. I HAVE
// COMPLETELY LOST TRACK OF THE NUMBER OF LAYERS OF INDIRECTION I'M EMPLOYING HERE. AT THIS POINT
// I'M BASICALLY GETTING AS FAR AWAY FROM THE ORIGINAL SPACE INVADERS AS FUNCTIONALLY POSSIBLE.
// PUN INTENDED.
// YOU WANT TO KNOW WHAT this REFERS TO? WELL BEST OF LUCK FIGURING IT OUT, BUDDY! NOBODY HAS THE
// THE SLIGHTEST CLUE WHAT this REFERS TO ANYWHERE IN THIS PROGRAM! THANKS A TON, call AND apply!
// MWAHAHAHAHA!
// Seriously though, in this module, "this" refers to an invader object, except in "init" functions,
// where it refers to an invader state.
// COMPONENTS OF INVADER STATES
// Invader state components' enter functions should ideally take a single argument, an
// initialization argument. This way different components can be put in the same state even if they
// take completely different arguments.
var BouncesOnGround = {
init: function (elas, y0) {
this.elasticity = elas || 1
this.groundy = y0 || 0
},
think: function (dt) {
if (this.y < this.state.groundy && this.vy < -1) {
this.y = this.state.groundy
this.vy *= -this.state.elasticity
this.vx *= 1 - 0.01 * (1 - this.state.elasticity)
}
},
}
// Approaches y + A sin(phi t) with rate beta, with a friction term given by alpha
var ApproachAltitude = {
enter: function (obj) {
this.targety = obj.targety
this.approachyalpha = obj.approachyalpha || 2
this.approachybeta = obj.approachybeta || 2
this.approachyA = obj.approachyA || 0
this.approachyphi = obj.approachyphi || 1
this.approachyt = 0
},
think: function (dt) {
this.approachyt += dt
var y = this.targety
if (this.approachyA) y += this.approachyA * Math.sin(this.approachyphi * this.approachyt)
this.ay = -this.approachyalpha * this.vy + this.approachybeta * (y - this.y)
},
}
var ApproachWaveAltitude = {
enter: function (obj) {
this.targety0 = obj.targety0
this.approachyalpha = obj.approachyalpha || 2
this.approachybeta = obj.approachybeta || 2
this.approachyA = obj.approachyA || 0
this.approachyn = obj.approachyn || 1
},
think: function (dt) {
this.approachyt += dt
var y = this.targety0
if (this.approachyA) y += this.approachyA * Math.sin(this.X * this.approachyn)
this.ay = -this.approachyalpha * this.vy + this.approachybeta * (y - this.y)
},
}
var ApproachVelocity = {
enter: function (obj) {
this.targetvx = obj.targetvx
this.approachxalpha = obj.approachxalpha || 2
},
think: function (dt) {
this.ax = -this.approachxalpha * (this.vx - this.targetvx)
}
}
var ScrunchInMotion = {
init: function (scrunchfactor) {
this.scrunchfactor = scrunchfactor || 800
},
draw: function () {
// var adotv = clip((this.lastax * this.vx + this.lastay * this.vy) / 1000, -0.5, 0.5)
var x = this.vx, y = this.vy, f = this.scrunchfactor || this.state.scrunchfactor
if (!x && !y) return
var A = Math.atan2(y, x)
var s = 1 + clip(Math.sqrt(x * x + y * y) / f, 0, 0.3)
UFX.draw("r", A, "z", s, 1/s, "r", -A)
},
}
// Set the clipping region. This is a bit tricky beacuse it gets invoked
// *after* the initial transformation in WorldBound.draw. This solution
// seemed a bit inelegant at first, but actually I don't thnik it's so bad.
var ClipsToPortal = {
draw: function () {
context.restore()
context.save()
this.portal.setclip()
WorldBound.draw.apply(this)
},
}
var ClipsToGround = {
enter: function () {
this.groundy = groundy(this.y)
},
draw: function () {
UFX.draw("[ t 0", -this.y + this.groundy, "m -1000 0 l 1000 0 l 0 1000 ] clip")
},
}
// Load up a later state after a specified time
var AutoNextState = {
// can set default timeout in the state
init: function (t) {
this.autowaittime = t
},
enter: function (obj, nextstate) {
this.autonextstate = nextstate
this.autowaittime = obj.t || this.state.autowaittime
},
think: function (dt) {
if (this.autowaittime < 0) return
this.autowaittime -= dt
if (this.autowaittime < 0) {
this.nextstate = this.autonextstate
}
},
}
var BeInvisible = {
init: function () {
if (!this.draw) this.definemethod("draw")
this.setmethodmode("draw", "any")
},
draw: function () {
return true
},
}
// Follow a Bezier path from current position/velocity to target position/velocity
var TargetBezier = {
enter: function (opts, nstate) {
var vx = opts.targetvx || 0, vy = opts.targetvy || 0
this.path = objbezier(this, opts.targetX, opts.targety, vx, vy)
this.targetnextstate = nstate
},
think: function (dt) {
this.path.t += dt
var pva = this.path.pva()
this.X = pva[0] ; this.y = pva[1]
var xfactor = this.y + gamestate.worldr
this.vx = pva[2] * xfactor ; this.vy = pva[3]
this.lastax = pva[4] * xfactor ; this.lastay = pva[5]
if (this.path.t > this.path.t0) {
this.nextstate = this.targetnextstate
}
},
}
// Effects-related components
var AddAlerter = {
enter: function () {
this.alerter = new Alerter(this)
},
}
var KillAlerter = {
enter: function () {
this.alerter.freezepos()
this.alerter.die()
},
}
// ACTUAL INVADER STATES
// Remain invisible for a specified amount of time before transitioning to next state
var HideState = UFX.Thing()
.addcomp(AutoNextState)
.addcomp(BeInvisible)
HideState.invulnerable = true
// Just keep doing what you're doing
var DriftState = UFX.Thing()
.addcomp(BasicMotion)
.addcomp(ScrunchInMotion)
.addcomp(AutoNextState)
.definemethod("draw")
// Maintain a given altitude and x-velocity
var StationKeepingState = UFX.Thing()
// .addcomp(ApproachAltitude)
.addcomp(ApproachWaveAltitude)
.addcomp(ApproachVelocity)
.addcomp(BasicMotion)
.addcomp(ScrunchInMotion)
.definemethod("draw")
// While coming out of the portal
// Moves in a direction perpendicular to the plane of the portal, obvs
var PortalState = UFX.Thing()
.addcomp({
enter: function (opts) {
opts = opts || {}
this.portalx = -100
this.portalv = opts.portalv || 240
this.X = this.portal.X
this.y = this.portal.y
},
exit: function () {
this.portal.removeentity(this)
},
think: function (dt) {
var S = this.portal.tiltS, C = -this.portal.tiltC
this.portalx += dt * this.portalv
this.vx = this.portalv * S
this.vy = this.portalv * C
this.X = this.portal.X + this.portalx * S / this.portal.xfactor
this.y = this.portal.y + this.portalx * C
this.ax = this.ay = 0
if (this.portalx > 100) {
this.squad.onexitportal(this)
}
},
})
.addcomp(ClipsToPortal)
.addcomp(ScrunchInMotion)
var TargetOmega = UFX.Thing()
.addcomp(ScrunchInMotion)
.addcomp(TargetBezier)
.addcomp(AddAlerter)
.addcomp({
think: function (dt) {
this.whiskerA = Math.max(0, this.whiskerA - 0.5 * dt)
}
})
.definemethod("draw")
var InhaleState = UFX.Thing()
.addcomp(AutoNextState)
.addcomp({
draw: function () {
var s = clip(2 - this.autowaittime * this.autowaittime, 1, 2)
UFX.draw("t 0 -10 z", 1/s, s, "t 0 10")
}
})
var SneezeState = UFX.Thing()
.addcomp(AutoNextState)
.addcomp({
enter: function () {
this.sneeze = new Sneeze(this)
this.whiskerA = 0.5
this.whiskerR = 6
this.shudders = 0
this.shudderA = 0
},
exit: function () {
this.sneeze.die()
},
think: function (dt) {
this.shudders = clip(this.shudders + dt * UFX.random(-30, 30), 0.4)
this.shudderA = clip(this.shudderA + dt * UFX.random(-20, 20), 0.3)
},
draw: function () {
var s = Math.exp(this.shudders)
UFX.draw("t 0 -10 r", this.shudderA, "z", 1/s, s, "t 0 10")
},
})
var DroopState = UFX.Thing()
.addcomp(KillAlerter)
.addcomp({
enter: function () {
this.vy = 100
},
think: function (dt) {
this.ay = -300
if (this.y < -50) this.die()
},
})
.addcomp(BasicMotion)
.addcomp(ClipsToGround)
.addcomp(ScrunchInMotion)
|
import axios from "axios";
function setTokenHeader(token) {
if (token) {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common["Authorization"];
}
}
function apiCall(method, path, data) {
return axios({
method: method,
url: path,
data: data
})
.then(res => {
return (res.data);
})
.catch(err => {
return ("err.response.data.error");
});
}
export { apiCall, setTokenHeader };
|
import {connect} from 'react-redux';
import BrandDialog from './BrandDialog';
import {Action} from '../../../action-reducer/action';
import showPopup from '../../../standard-business/showPopup';
import helper from '../../../common/common';
import {getDictionaryNames, fetchDictionary, setDictionary2} from '../../../common/dictionary';
const action = new Action(['brand'], false);
const URL_ADD = '/api/config/inside_car/addDic';
const getSelfState = (state) => {
return state.brand || {};
};
const buildState = (config) => {
return {
...config,
title: '车辆归属区域',
visible: true,
value: {parentDictionaryCode:{value:'car_area',title:'车辆归属区域'}},
tableItems:[]
};
};
const changeActionCreator = (key, value) => {
return action.assign({[key]: value}, 'value');
};
const okActionCreator = () => async (dispatch, getState) => {
const state = getSelfState(getState());
if (helper.validValue(state.controls, state.value)) {
const body = {
...state.value,
dictionaryLanguage: state.tableItems
};
const json = await helper.fetchJson(URL_ADD, helper.postOption(helper.convert(body), 'post'));
if (json.returnCode) {
helper.showError(json.returnMsg);
} else {
helper.showSuccessMsg(json.returnMsg);
dispatch(action.assign({visible: false, ok: true}));
}
} else {
dispatch(action.assign({valid: true}));
}
};
const cancelActionCreator = () => (dispatch) => {
dispatch(action.assign({visible: false, ok: false}));
};
const addAction = (dispatch, getState) => {
dispatch(action.add({}, 'tableItems', 0))
};
const delAction = (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const newItems = tableItems.filter(items => !items.checked);
dispatch(action.assign({tableItems:newItems}));
};
const clickActionCreators = {
add: addAction,
del: delAction
};
const clickActionCreator = (key) => {
if (clickActionCreators.hasOwnProperty(key)) {
return clickActionCreators[key];
} else {
return {type: 'unknown'};
}
};
const contentChangeActionCreator = (rowIndex, keyName, value) => (dispatch, getState) => {
dispatch(action.update({[keyName]: value}, 'tableItems', rowIndex));
};
const exitValidActionCreator = () => {
return action.assign({valid: false});
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onChange: changeActionCreator,
onClick: clickActionCreator,
onExitValid: exitValidActionCreator,
onContentChange: contentChangeActionCreator,
onOk: okActionCreator,
onCancel: cancelActionCreator
};
const URL_CONFIG = '/api/basic/sysDictionary/config';
export default async () => {
try {
const config = helper.getJsonResult(await helper.fetchJson(URL_CONFIG));
//字典
const names = getDictionaryNames(config.edit.tableCols);
const dictionary = helper.getJsonResult(await fetchDictionary(names));
setDictionary2(dictionary, config.edit.tableCols);
const Container = connect(mapStateToProps, actionCreators)(BrandDialog);
global.store.dispatch(action.create(buildState(config.edit)));
await showPopup(Container, {}, true);
const state = getSelfState(global.store.getState());
global.store.dispatch(action.create({}));
return state.ok;
}catch (e){
helper.showError(e.message)
}
};
|
const fs = require('fs');
const path = require('path');
const CBCPKCS7 = require('@pascalcoin-sbx/crypto').Encryption.AES.CBCPKCS7;
const BC = require('@pascalcoin-sbx/common').BC;
const chai = require('chai');
chai.expect();
const expect = chai.expect;
describe('Crypto.Encryption.AES.CBC-PKCS7', () => {
it('passes aes-cbc vector tests', () => {
const vectors = JSON.parse(fs.readFileSync(path.join(__dirname, '/../../fixtures/aes.json')));
vectors.forEach((v) => {
const input = BC.fromHex(v.input);
const output = BC.fromHex(v.output);
const iv = BC.fromHex(v.iv);
const key = BC.fromHex(v.key);
const enc = CBCPKCS7.encrypt(input, {key, iv});
// TODO: why slicing?
expect(output.toHex()).to.be.equal(enc.slice(0, 16).toHex());
});
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Claim {
constructor(model) {
if (!model)
return;
this.code = model.code;
this.name = model.name;
this.path = model.path;
this.method = model.method;
this.order = model.order;
}
static parseArray(list) {
return list && Array.isArray(list) ? list.map(item => new Claim(item)) : [];
}
}
Object.seal(Claim);
exports.default = Claim;
|
({
onFormSubmit : function(component, event, helper) {
var formData = event.getParam("formData");
console.log("getting the formData " +formData);
//var boatTypeId = formData.boatTypeId;
//alert("getting the boat id " +boatTypeId);
var childCmp = component.find("childCmp");
//console.log("getting the boattypeId " +boatTypeId);
var auraMethodResult = childCmp.search(formData);
console.log("auraMethodResult: " + auraMethodResult);
}
}) |
const Sequelize = require('sequelize');
module.exports = (sequelize) => {
const Order = sequelize.define('order', {
shop_id: {
type: Sequelize.INTEGER,
unique: 'order',
},
cart_total: {
type: Sequelize.FLOAT,
allowNull: false,
},
currency: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: 'USD'
},
order_key: {
type: Sequelize.STRING,
allowNull: false,
unique: 'order',
},
shopify_order_no: {
type: Sequelize.STRING,
},
tracking_numbers: {
type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: []
},
shipping_service: {
type: Sequelize.STRING,
},
shopify_fulfillment_id: {
type: Sequelize.STRING,
},
success: {
type: Sequelize.BOOLEAN,
},
status: {
type: Sequelize.ENUM('InProcess', 'PaymentAccepted', 'SentToFulfillment', 'Shipped', 'Delivered', 'Voided'),
},
compliant: {
type: Sequelize.BOOLEAN,
allowNull: false,
},
override: {
type: Sequelize.ENUM('manual', 'auto'),
},
quarantined: {
type: Sequelize.BOOLEAN,
},
tax_value: {
type: Sequelize.FLOAT
},
location_state: {
type: Sequelize.STRING,
},
location_zip: {
type: Sequelize.STRING,
},
cancelled: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
cancelled_at: {
type: Sequelize.DATE
},
ordered_at: {
type: Sequelize.DATE
},
last_synced_at: {
type: Sequelize.DATE
},
}, {
freezeTableName: true,
paranoid: true,
underscored: true,
indexes: [{
fields: ['shop_id']
}, {
fields: ['shop_id', 'order_key']
}]
});
return Order;
};
|
cc.sys.dump();
cc.game.onStart = function () {
cc.view.adjustViewPort(true);
cc.view.setDesignResolutionSize(320, 480, cc.ResolutionPolicy.SHOW_ALL);
cc.view.resizeWithBrowserSize(true);
cc.LoaderScene.preload(g_res_main_menu, function () {
cc.director.runScene(menu_screen());
}, this);
};
cc.game.run(); |
const { writeFileSync } = require("fs")
const verify = (obj, schema) => {
const defined = {}
for (const key of Object.keys(schema)) defined[key] = null
for (const key of Object.keys(defined)) {
const { required, type } = schema[key]
if (
(required &&
obj[key] === undefined &&
schema[key].default === undefined) ||
obj[key] === null
) {
throw Error(
`The "${key}" value is required, it cannot be undefined or null`
)
}
if (typeof obj[key] !== "object")
defined[key] = obj[key] !== undefined ? type(obj[key]) : type()
else if (obj[key])
defined[key] = Object.entries(obj[key])[0]
? type === Array && Array.isArray(obj[key])
? obj[key]
: type(Object.assign({}, obj[key]))
: type()
if ((schema[key].default && obj[key] === undefined) || obj[key] === null)
defined[key] = schema[key].default
}
return defined
}
const concat = (obj, entries, schema) => {
const defined = { ...obj }
Object.entries(entries).forEach((r) => {
Object.entries(defined).filter((a) => {
if (a[0] === r[0] && r[1] != a[1]) defined[a[0]] = r[1]
else if (r[0]) defined[r[0]] = r[1]
})
})
return verify(defined, schema)
}
const read = (path) => {
return require(path)
}
const save = (path, content) => {
writeFileSync(path, JSON.stringify(content))
}
module.exports = { concat, verify, save, read }
|
//config.js - configuration service
// import lib from node-modules
var readYaml = require('read-yaml');
var configFile = 'application.yml';
var config = readYaml.sync(configFile);
var Config = function () {
};
refresh = function () {
config = readYaml.sync(configFile);
}
Config.prototype.version = function () {
refresh();
return config.application.version;
};
Config.prototype.secretKey = function () {
return process.env.JWT_SECRET_KEY;
};
Config.prototype.secureCookie = function () {
return 'true' == process.env.SECURE_COOKIE;
};
Config.prototype.mongodbUri = function () {
return `mongodb://${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DB}`;
}
Config.prototype.authentication = function () {
var dbAuth = `{
"useMongoClient": false,
"user": "${process.env.MONGODB_USERNAME}",
"pass": "${process.env.MONGODB_PASSWORD}",
"auth":{
"authdb": "${process.env.MONGODB_AUTH_DB}"
}
}`;
return JSON.parse(dbAuth);
}
exports.Config = new Config();
|
import React from "react";
import "./style.css";
const Field = props => (
<div
className={
"field" +
(props.className ? " " + props.className : "") +
(props.name ? " " + props.name : "")
}
>
<label htmlFor={props.name}>{props.label}</label>
<input
type={props.type ? props.type : "text"}
id={props.name}
placeholder={props.placeholder ? props.placeholder : ""}
value={props.value}
onChange={props.valueChanged}
/>
</div>
);
export default Field;
|
//===================================== Sticky navBar ============================================
let navOffsetTop = $('.header').height() + 50;
function navBarFixed(){
if($('.header').length){
$(window).scroll(function(){
let scroll = $(window).scrollTop();
if(scroll>=navOffsetTop){
$('.header .mainMenu').addClass("navbar-fixed");
}else{
$('.header .mainMenu').removeClass("navbar-fixed");
}
})
}
}
navBarFixed();
//=============================================== Enable ToolTips ==================================
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
//============================ Initial Owl Carousel =========================
$('.mainContainer .recomArea .owl-carousel').owlCarousel({
loop: true,
autoplay: true,
dots: true,
responsive:{
0:{
items:1
}
}
});
|
const Skill = require("../models/skill");
module.exports = {
index,
show,
add,
remove,
update,
newSkill,
edit,
};
function newSkill(req, res) {
res.render("skills/new");
}
function index(req, res) {
res.render("skills/index", {
skills: Skill.getAll(),
});
}
function show(req, res) {
const skill = Skill.getOne(req.params.id);
res.render("skills/show", {
skill: skill,
});
}
function add(req, res) {
Skill.addOne(req.body);
res.redirect("skills");
}
function remove(req, res) {
Skill.removeOne(req.params.id);
res.redirect("/skills");
}
function update(req, res) {
Skill.update(req.params.id, req.body);
res.redirect("/skills");
}
function edit(req, res) {
res.render("skills/edit", {
skill: Skill.getOne(req.params.id),
});
}
|
/* Number 오브젝트 */
// 숫자 처리를 위한 오브젝트
// 숫자 처리를 위한 함수와 프로퍼티가 포함! 함수를 호출하여 숫자를 처리
/* Number() */
console.log(Number("123") + 500);
/* "123"은 String 타입이지만 값이 숫자이므로 숫자로 변환 가능
Number타입이 되므로 123+500이 되어 623을 반환 */
console.log(Number("ABC"));
/* "ABC"는 숫자로 변환 불가 - Nat a Number 반환
2가지 관점 1. 변환을 했는데 그 값이 Nat a Number
2. 변환을 할려고 했는데 파라미터 값이 Not a Number
*/
console.log(Number(0x14));
/* 0x는 16진수 16*1+4 */
console.log(Number(true));
/* true = 1 false = 0 */
console.log(Number(null));
/* null = 0 */
console.log(Number(undefined));
/* undefined는 숫자로 변환할 수 없거나 변환했는데 숫자가 아니다 */
/* Number 상수 */
// 값을 변경, 삭제할 수 없음
// MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY
// 상수는 영문 대문자 사용
// Number.MAX_VALUE 형태로 값 사용
/* new 연산자 */
//오브젝트로 인스턴스를 생성하여 반환
var obj = new Number();
console.log(typeof obj);
// 원본을 복사하는 개념
// 복사한 복사본이 인스턴스 -> 생성한 인스턴스를 obj에 할당
// 인스턴스의 생성 목적 : 인스턴스마다 값을 갖기 위한 것
var oneObj = new Number("123");
console.log(oneObj.valueOf());
var twoObj = new Number("456");
console.log(twoObj.valueOf());
/* 원본을 복사해서 나눠준 것을 자신에 복사본에 메모하는것
누구는 123이라 메모하고 누구는 456이라고 메모할 수 있다
값이 다른 경우르 대비해 인스턴스를 만드는 것이다.*/
/* Number 인스턴스 생성 */
//빌트인 Number 오브젝트로 새로운 Number 인스턴스를 생성
var obj = new Number("123");
console.log(obj.valueOf());
// 인스턴스를 만드는 기준으 prototype이다.
// prototype에 연결되어있는 함수들을 복사해서 주는 것
/* 프리미티브 값 */
// 언어에 있어 가장 낮은 단계의 값
// var book = "책"; "책"은 더 이상 분해, 전개 불가
/* 프리미티브 타입
* Number, String, Boolean : 인스턴스 생성 가능
* Null, Undefined : 인스턴스 생성 불가
* Object는 프리미티브 값을 제공하지 않음
*/
/* 프리미티브 값을 갖는 오브젝트 Boolean, Date, Number, String */
var obj = new Number(123);
console.log(obj + 200);
/* valueOf() */
//Number 인스턴스의 프리미티브 값을 반환
var obj = new Number(123);
console.log(obj.valueOf());
/* toString() */
//변환대상을 string타입으로 변환
// 파라미터에 진수작성 가능 작성하지 않으면 10진수로 처리
var value = 20;
console.log(20 === value.toString());
console.log(value.toString(16));
//변환 할 때 주의사항
console.log(20..toString()); /* 20. = 20.0 */
/* 20.toString() 형태로 작성하면 에러
20이 아니라 20.을 변환 대상으로 인식. 점이 없는 valuetoString()형태가 되기때문
20..을 작성*/
/* 자바스크립트는 20을 정수가 아닌 실수로 처리 */
/* toLocalString() */
// 숫자를 브라우저가 지원하는 지역화 문자로 변환
// 지역화는 한국, 중국, 프랑스 등의 지역애서 사용하는 문자
// 지역화 지원 및 형태를 브라우저 개발사에 일임 -> 브라우저마다 조금씩 차이가 날 수 있다.
// 지역화를 지원하지 않으면 toString()으로 변환
var value = 1234.56;
console.log(value.toLocaleString());
console.log(value.toLocaleString('de-DE'));
console.log(value.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
/* toExponential() */
// 숫자를 지수 표기로 변환하여 문자열로 반환
// 파라미터에 소수 이하 자릿수 작성 - 0에서 20까지
var value = 1234;
console.log(value.toExponential());
/* 변환 대상의 첫 자리만 소수점(.) 표시
나머지는 소수점 아래에 표시
지수(e+) 다음에 정수에서 소수로 변환된 자릿수 표시 */
var value = 123456;
console.log(value.toExponential(3));
/* 소수점 아래 3자리로 표시하라 작성
1.234e+5로 표시가 되어야 하는데 1.235e+5인 이유는
2345에서 3자리로 표시할때 반올림하기 때문 */
/* toFixed() */
// 고정 소숫점 표기로 변환하여 문자열로 반환
var value = 1234.567;
console.log(value.toFixed(2)); /* 파라미터에 2를 작성 -> 소수 두 자리까지 표시. 이때 셋째 자리에서 반올림 */
console.log(value.toFixed()); /* 파라미터 값을 작성하지 않으면 0으로 간주 -> 소수 첫째 자리에서 반올림하여 정숫값을 표시 */
//파라미터 값보다 소수 자랏수가 길면 작성한 자리수에 1을 더한 위치에서 반올림
console.log(value.toFixed(5));
//변환 대상 자릿수보다 파라미터 값이 크면 나머지를 0으로 채워 반환 |
import React from 'react'
import { storiesOf } from '@storybook/react'
import Button from '@healthwise-ui/core/Button'
import CallToAction from './index'
const item = {
html: `
<div>
<h3>Call to Action</h3>
<img src="http://via.placeholder.com/48x48">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
`,
}
storiesOf('content|Call to Action', module).add(
'with defaults',
() => <CallToAction item={item} actionButtons={<Button rounded>Action</Button>} />,
{
info: `Demonstrates a default CallToAction`,
}
)
|
const glossary = [
{
name: "Apples",
description: "Apples description"
},
{
name: "Bananas",
description: "Bananas description"
},
{
name: "Cherries",
description: "Cherries description"
},
{
name: "Dragon Fruit",
description: "Dragon Fruit description"
},
{
name: "Elderberry",
description: "Elderberry description"
},
{
name: "Fig",
description: "Fig description"
},
{
name: "Grapefruit",
description: "Grapefruit description"
},
{
name: "Honeydew melon",
description: "Honeydew melon description"
},
{
name: "Indian Prune",
description: "Indian Prune description"
},
{
name: "Jackfruit",
description: "Jackfruit description"
},
{
name: "Kiwi",
description: "Kiwi description"
},
{
name: "Lime",
description: "Lime description"
},
{
name: "Mango",
description: "Mango description"
},
{
name: "Nectarine",
description: "Nectarine description"
},
{
name: "Olive",
description: "Olive description"
},
{
name: "Papaya, Persimmon",
description: "Papaya, Persimmon description"
},
{
name: "Quince",
description: "Quince description"
},
{
name: "Rambutan",
description: "Rambutan description"
},
{
name: "Star Frui",
description: "Star Fruit description"
},
{
name: "Tomato",
description: "Tomato description"
},
{
name: "Ugli Fruit",
description: "Ugli Fruit description"
},
{
name: "Vanilla Bean",
description: "Vanilla Bean, description"
},
{
name: "Watermelon",
description: "Watermelon, description"
},
{
name: "Xigua (Chinese Watermelon)",
description: "Xigua, description"
},
{
name: "Yellow Passion Fruit",
description: "Yellow Passion Fruit, description"
},
{
name: "Zuchinni (a fruit, like tomatoes)",
description: "Zuchinni (a fruit, like tomatoes), description"
}
];
const settings = {
DOMStrings: {
list: ".list",
userInput: ".userInput",
letters: ".glossary-table__letter"
},
highlightClass: "hl",
errorMessage: "No words found, try a new one."
};
const list = document.querySelector(settings.DOMStrings.list);
const userInput = document.querySelector(settings.DOMStrings.userInput);
const letters = document.querySelectorAll(settings.DOMStrings.letters);
// sort data by name alphabetically
function sortArr(arr) {
arr.sort((a, b) => a.name.localeCompare(b.name));
}
function findMatches(wordToMatch, data) {
// sort in alphabetical order
sortArr(data);
return data.filter(item => {
// create regular expression
// so it can be passed into match
// g = global
// i = insenstive - lower or upper
const regex = new RegExp(wordToMatch, "gi");
// array = found items
return item.name.match(regex);
});
}
function displayMatches() {
// check this first letter typed in
checkLetter(this.value[0]);
// pass in type value, and data
let found = findMatches(this.value, glossary);
// return found to 0 once input is empty
if (this.value === "") {
found = [];
}
// pass in typed input
// pass in the array with results
displayItem(this.value, found);
}
function displayItem(a, f) {
const html = f
.map(item => {
// find what is searched for
// replace the found item with a span to highlight
const regex = new RegExp(a, "gi");
const name = item.name.replace(
regex,
`<span class ="${settings.highlightClass}">${a}</span>`
);
return `
<li>
<span>${name}</span>
<p>${item.description}</p>
</li>
`;
})
.join("");
if (f.length > 0) {
list.innerHTML = html;
} else if (this.value === "") {
list.innerHTML = "";
} else {
list.innerHTML = settings.errorMessage;
}
}
let lettersArr = [...letters].map(item => item.innerHTML.toLowerCase()).join();
// check typed letters
function checkLetter(a) {
// if the array includes the typed first letter
if (lettersArr.includes(a)) {
// select the typed in letter and highlight
document.querySelector(`.${a} `).classList.add(settings.highlightClass);
} else if (!lettersArr.includes(a)) {
// remove all hl classes
letters.forEach(item => item.classList.remove(settings.highlightClass));
}
}
// toggle active class on click of letters
function toggleItem(elem, active) {
for (var i = 0; i < elem.length; i++) {
elem[i].addEventListener("click", function(e) {
var current = this;
for (var i = 0; i < elem.length; i++) {
if (current != elem[i]) {
elem[i].classList.remove(active);
} else if (current.classList.contains(active) === true) {
current.classList.remove(active);
} else {
current.classList.add(active);
}
}
e.preventDefault();
});
}
}
toggleItem(letters, settings.highlightClass);
// on user input typed in
userInput.addEventListener("keyup", displayMatches);
// on click of the letters
letters.forEach(item =>
item.addEventListener("click", function(el) {
let clickedLetter = item.innerText.toLowerCase().trim();
let found = findMatches(clickedLetter, glossary);
displayItem(clickedLetter, found);
// clear input
userInput.value = "";
})
);
|
const empelado = require("../Models/Empleados");
function guardarEmpleado(req, res) {
console.log('Endpoint para guardar Empleado Ejecutado');
const newEmpleado = new empelado();
const { codigo, nombre, cedula, pApellido, sApellido, telefono1, telefono2, puesto, nacionalidad, restaurante, foto } = req.body;
newEmpleado.codigo = codigo;
newEmpleado.nombre = nombre;
newEmpleado.cedula = cedula;
newEmpleado.pApellido = pApellido;
newEmpleado.sApellido = sApellido;
newEmpleado.telefono1 = telefono1;
newEmpleado.telefono2 = telefono2;
newEmpleado.puesto = puesto;
newEmpleado.nacionalidad = nacionalidad;
newEmpleado.restaurante = restaurante;
newEmpleado.foto = foto;
if (codigo === '') {
res.status(404).send({ message: "Codigo necesario" })
} else {
if (nombre === '') {
res.status(404).send({ message: "Nombre necesario" })
} else {
if (cedula === '') {
res.status(404).send({ message: "Cedula necesaria" })
} else {
if (pApellido === '') {
res.status(404).send({ message: "Primer apellido necesario" })
} else {
if (sApellido === '') {
res.status(404).send({ message: "Segundo apellido necesario" })
} else {
if (telefono1 === '') {
res.status(404).send({ message: "Telefono 1 necesario" })
} else {
if (telefono2 === '') {
res.status(404).send({ message: "Telefono 2 necesario" })
} else {
if (puesto === '') {
res.status(404).send({ message: "Puesto necesario" })
} else {
if (restaurante === '') {
res.status(404).send({ message: "Restaurante necesario" })
} else {
if (nacionalidad === '') {
res.status(404).send({ message: "Nacionalidad necesaria" })
} else {
newEmpleado.save((err, EmpStored) => {
if (err) {
res.status(500).send({ message: "Error del servidor" })
} else {
if (!EmpStored) {
res.status(404).send({ message: "Error al guardar Empleado" });
} else {
res.status(200).send({ bbH: EmpStored });
console.log('Empleado guardado con exito');
}
}
});
}
}
}
}
}
}
}
}
}
}
}
function getEmpleado(req, res) {
empelado.find().then(empleado => {
if (!empleado) {
res.status(404).send({ message: "No se ha encontrado ningun empleado" });
} else {
res.status(200).send({ empleado });
}
})
}
function updateEmpleado(req, res) {
const especiData = req.body;
const params = req.params;
empelado.findByIdAndUpdate({ _id: params.id }, especiData, (err, espUpdate) => {
if (err) {
res.status(500).send({ code: 500, message: "Error del servidor" });
} else {
if (!espUpdate) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Empleado" });
} else {
res.status(200).send({ code: 200, message: "Empleado actualizado correctamente" });
}
}
})
}
function deleteEmpleado(req, res) {
const { id } = req.params;
empelado.findByIdAndRemove(id, (err, espeDeleted) => {
if (err) {
res.status(500).send({ cod: 500, message: "Error del servidor" });
} else {
if (!espeDeleted) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Empleado" });
} else {
res.status(200).send({ code: 200, message: "Empleado eliminada correctamente" });
}
}
})
}
module.exports = {
guardarEmpleado,
getEmpleado,
updateEmpleado,
deleteEmpleado
}; |
// 1、导入vue'
import Vue from 'vue';
//2、导入app
import App from './App.vue';
//4.导入路由
import vueRouter from 'vue-router'
//4.1把路由绑定到Vue对象上
Vue.use(vueRouter)
//4.1.1导入组件]
import home from './components/home.vue';
import shopcar from './components/shopcar/car.vue';
import newslist from './components/newslist/newslist.vue';
import newsinfo from './components/newslist/newsinfo.vue';
import photolist from './components/photo/photolist.vue';
import photoinfo from './components/photo/photoinfo.vue';
import goodslist from './components/goods/goodslist.vue';
import goodsinfo from './components/goods/goodsinfo.vue';
import goodsdesc from './components/goods/goodsdesc.vue';
import goodscomment from './components/goods/goodscomment.vue';
//4.2定义路由规则
var router=new vueRouter({
linkActiveClass:'mui-active',
routes:[
{path:'/',redirect:'/home'},
{path:'/home',component:home},
{path:'/shopcar',component:shopcar},
{path:'/news/newslist',component:newslist},
{path:'/news/newsinfo/:id',component:newsinfo},
{path:'/photo/photolist',component:photolist},
{path:'/photo/photoinfo/:id',component:photoinfo},
{path:'/goods/goodslist',component:goodslist},
{path:'/goods/goodsinfo/:id',component:goodsinfo},
{path:'/goods/goodsdesc/:id',component:goodsdesc},
{path:'/goods/goodscomment/:id',component:goodscomment},
]
})
//8.导入vue-resource功能
import vueResource from 'vue-resource'
Vue.use(vueResource)
//9.利用moment日期处理类库格式化时间
import moment from 'moment'
Vue.filter('datefmt',function(input,filterstr){
filterstr=filterstr?filterstr:'YYYY-MM-DD HH:mm:ss';
return moment(input).format(filterstr)
})
//10.导入缩略图放大显示的组件
import VuePreview from 'vue-preview'
Vue.use(VuePreview)
//5.导入mint-ui和css
import 'mint-ui/lib/style.min.css';
import mint from 'mint-ui';
//6.导入mui的css
import '../statics/mui/css/mui.css';
//7.导入公共css
import '../statics/css/site.css'
//绑定mint-ui
Vue.use(mint)
//3、实例化vue
new Vue({
el:'#app',
//4.3、导入路由规则
router:router,
render:c=>c(App) //es6语法 等同于reder:function(create){create(App)}
})
|
function createChart() {
var inputBoxElements = getListOfEditableInpuxBoxElements();
var visualizationData = [['Category', 'Expenditure']];
for (var i = 0; i < inputBoxElements.length; i++){
var inputBox = inputBoxElements[i];
visualizationData.push([inputBox.textContent, parseInt(inputBox.value)]);
}
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// var data = google.visualization.arrayToDataTable([
// ['Category', 'Expenditure'],
// ['Work', 11],
// ['Eat', 2],
// ['Commute', 2],
// ['Watch TV', 2],
// ['Sleep', 7]
// ]);
var data = google.visualization.arrayToDataTable(visualizationData);
// console.log(data.jc);
var options = {
title: 'Expenditure Distribution',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
} |
import Head from "next/head";
export default () => (
<Head>
<title>AidenEC</title>
<link rel="stylesheet" href="static/css/main.css"/>
<link rel="icon" href="static/favicon.ico" type="image/x-icon" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<script src="static/js/script.js" />
<script defer src="static/js/fa-brands.min.js" />
<script src="static/js/fontawesome.min.js" />
</Head>
);
|
var cowsay = require("cowsay");
const myInformation = require('./information.js');
myInformation();
console.log(cowsay.say({
text : message,
e : "oO",
T : "U "
}));
console.log(cowsay.think({
text : message,
e : "oO",
T : "U "
})); |
#!/usr/bin/env node
/* eslint-disable import/no-commonjs */
const request = require('request-promise');
const github = require('octonode');
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const ANDROID_APK_LINK = process.env.BITRISE_PUBLIC_INSTALL_PAGE_URL;
const GIT_PROJECT_REPONAME = 'metamask-mobile';
const BITRISEIO_GIT_REPOSITORY_OWNER = process.env.BITRISEIO_GIT_REPOSITORY_OWNER;
const SLACK_TOKEN = process.env.MM_SLACK_TOKEN;
const SLACK_SECRET = process.env.MM_SLACK_SECRET;
const SLACK_ROOM = process.env.MM_SLACK_ROOM;
const BITRISE_GIT_COMMIT = process.env.BITRISE_GIT_COMMIT;
start().catch(console.error);
async function getPRInfo() {
const client = github.client(GITHUB_TOKEN);
const REPO = client.repo(`${BITRISEIO_GIT_REPOSITORY_OWNER}/${GIT_PROJECT_REPONAME}`);
const response = await REPO.prsAsync({ state: 'closed' });
const PR = response[0].find(obj => obj.merge_commit_sha === BITRISE_GIT_COMMIT);
if (PR) {
return { title: PR.title, number: PR.number, url: PR.html_url };
}
}
async function start() {
const PR_INFO = await getPRInfo();
const content = {
text: `NEW BUILDS AVAILABLE! Including <${PR_INFO.url}|#${PR_INFO.number} - ${PR_INFO.title}>`,
attachments: [
{
title_link: 'itms-beta://beta.itunes.apple.com/v1/app/1438144202',
title: 'iOS',
text: 'Install via TestFlight',
thumb_url:
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/202px-Apple_logo_black.svg.png'
},
{
title_link: ANDROID_APK_LINK,
title: 'Android',
text: 'Download APK via Bitrise',
thumb_url:
'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Android_robot.svg/511px-Android_robot.svg.png'
}
]
};
const JSON_PAYLOAD = JSON.stringify(content);
const SLACK_API_URI = `https://hooks.slack.com/services/${SLACK_TOKEN}/${SLACK_SECRET}/${SLACK_ROOM}`;
await request({
method: 'POST',
uri: SLACK_API_URI,
body: JSON_PAYLOAD,
headers: {
'Content-type': 'application/json'
}
});
}
|
/* Sample on how to create A BOARD, AN IDEA and how to USE POPULATE TO RELATE ONE ANOTHER! */
/*create a sample Board: it Works! */
Board.create({
title: 'TestBoard'
}, function(err, board){
if(err){
console.log(err);
}
console.log(board);
});
/*Finds a Board and Creates a new Idea: it Works! */
Board.findOne({title: 'TestBoard'}, function(err, board){
if(err){
console.log(err);
}
console.log('Board before Ideas: ', board);
/*STEP 1: Create a new Idea Works!*/
var item = new Idea({
ideaTitle: 'Last test Before endpoints!!',
voteCount: 15
});
/*STEP 2: Save the Idea Works!*/
item.save(function(err, item){
if(err) {
console.log(err);
}
console.log('new idea', item);
});
/*this works by saving the reference of the Idea Works!*/
/* STEP 3: Push the Idea into the Board.ideas Array section, this will only save the reference */
board.ideas.push(item);
board.save(function(err, boardUpdate){
if(err){
console.log('update error ', err);
}
console.log('board after ideas added: ', boardUpdate);
});
});
/*Step 4: Populate your ideas with the actual objects, rather than just their reference! */
Board.findOne({title: 'TestBoard'}).populate('ideas').exec(function(err, board){
if(err){
console.log('error populate', err);
}
// console.log(JSON.stringify(boards, null, 2));
console.log('Updated Board after populate!!', board);
}); |
import React, { Component } from "react";
import MenuButton from "./MenuButton";
import Menu from "./Menu";
import Home from "./Home";
import Post from "./Post";
import Contact from "./Contact";
import { Route, NavLink, HashRouter } from "react-router-dom";
class MenuContainer extends Component {
state = {
visible: false
};
handleMouseDown = e => {
this.toggleMenu();
console.log("클릭됨");
e.stopPropagation();
};
toggleMenu = () => {
this.setState({
visible: !this.state.visible
});
};
render() {
return (
<div>
<MenuButton handleMouseDown={this.handleMouseDown} />
<Menu
handleMouseDown={this.handleMouseDown}
menuVisibility={this.state.visible}
/>
<HashRouter>
<div>
<h1>Simple SPA</h1>
<ul className="header">
<li>
<NavLink exact to="/">
HOME
</NavLink>
</li>
<li>
<NavLink to="/post">Post</NavLink>
</li>
<li>
<NavLink to="/contact">CONTACT</NavLink>
</li>
</ul>
<div className="content">
<Route exact path="/" component={Home}></Route>
<Route path="/post" component={Post}></Route>
<Route path="/contact" component={Contact}></Route>
</div>
</div>
</HashRouter>
</div>
);
}
}
export default MenuContainer;
|
var Modeler = require("../Modeler.js");
var className = 'Typelocation';
var Typelocation = function(json, parentObj) {
parentObj = parentObj || this;
// Class property definitions here:
Modeler.extend(className, {
ipaddress: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "ipaddress",
"s:annotation": {
"s:documentation": "The IP address that the data relates to"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 15
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
routingtype: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "routingtype",
"s:annotation": {
"s:documentation": "The routing type associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
aolflag: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "aolflag",
"s:annotation": {
"s:documentation": "The aol flag associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 1
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
continent: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "continent",
"s:annotation": {
"s:documentation": "The continent associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
country: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "country",
"s:annotation": {
"s:documentation": "The country associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
state: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "state",
"s:annotation": {
"s:documentation": "The state associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
city: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "city",
"s:annotation": {
"s:documentation": "The city associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
postcodearea: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "postcodearea",
"s:annotation": {
"s:documentation": "The postcode area associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
secondleveldomain: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "secondleveldomain",
"s:annotation": {
"s:documentation": "The second level domain associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
thirdleveldomain: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "thirdleveldomain",
"s:annotation": {
"s:documentation": "The third level domain associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
connectiontype: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "connectiontype",
"s:annotation": {
"s:documentation": "The connection type associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
linespeed: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "linespeed",
"s:annotation": {
"s:documentation": "The linespeed associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
},
carrier: {
type: "string",
wsdlDefinition: {
minOccurs: 0,
maxOccurs: 1,
name: "carrier",
"s:annotation": {
"s:documentation": "The carrier associated with the ipaddress entered"
},
"s:simpleType": {
"s:restriction": {
base: "s:string",
"s:maxLength": {
value: 10
}
}
},
type: "s:string"
},
mask: Modeler.GET | Modeler.SET,
required: false
}
}, parentObj, json);
};
module.exports = Typelocation;
Modeler.register(Typelocation, "Typelocation");
|
const Sequelize = require('sequelize')
const sequelize = require('./sequelizeModel')
const User = require('./userModel')
class Article extends Sequelize.Model{}
Article.init({
id:{
type:Sequelize.INTEGER,
primaryKey:true,
autoIncrement:true
},
title:{
type:Sequelize.STRING,
allowNull:false
},
target:{
type:Sequelize.STRING,
allowNull:true
},
date:{
type:Sequelize.DATE,
allowNull:false
},
clicktime:{
type:Sequelize.INTEGER,
allowNull:false
},
content:{
type:Sequelize.TEXT,
allowNull:false
}
},{
timestamps:false,
sequelize,
modelName:'Article'
})
Article.belongsTo(User,{
foreignKey:'user_id',
allowNull:false
})
Article.sync().then(()=>{
console.log("文章表同步成功!");
})
module.exports=Article;
|
require("dotenv").config();
const express = require("express");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const _ = require("lodash");
const Joi = require("joi");
const { User, validates, validateUser } = require("../Models/user");
const { valid } = require("joi");
const router = express.Router();
router.post("/register", async (req, res) => {
// checking the inputs using JOI
const { error } = validateUser(req.body);
if (error) return res.status(400).send(error.details[0].message);
// finding the user is already registred or not
let user = await User.findOne({ email: req.body.email });
if (user) return res.status(400).send("User already registered");
// create a new user to save
user = new User({
name: req.body.name,
email: req.body.email,
password: await bcrypt.hash(req.body.password, 10),
});
try {
await user.save();
res.status(200).send("User Created !!!");
} catch (err) {
res.status(500).send(err);
}
});
router.post("/login", async (req, res) => {
console.log("in");
const { error } = validates(req.body);
if (error) return res.status(400).send(error.details[0].message);
// if (req.user) return res.send("User already logged in!");
let user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Invalid email or password");
const validpassword = await bcrypt.compare(req.body.password, user.password);
if (!validpassword) return res.status(400).send("Invalid email or password");
console.log("out");
res.send("Success");
});
router.post("/logout", async (req, res) => {});
module.exports = router;
|
'use strict';
var ABSync = require('./libs/ab-sync.js').ABSync;
module.exports = {
new: function() {
return new ABSync.Class();
}
};
|
import React, {useState, useEffect} from 'react'
import getCookie from '../Components/getCookie'
import UserCard from '../Components/userCard'
import axios from 'axios'
function Following(){
const [following, setFollowing] = useState('Loading...')
let showFollowing
useEffect(()=>{
axios({
method:'get',
url: 'http://127.0.0.1:8000/api/user/following',
headers:{
'x-csrftoken': getCookie('csrftoken'),
'content-type': 'application/json'
}
}).then(response=>{
setFollowing(response.data.following)
}).catch(e=>{
console.log(e)
})
},[])
if(following){
showFollowing = following.map(element=>{
return <UserCard content={element}/>
})
}
return (
<div>
{showFollowing}
</div>
)
}
export default Following |
const mongoose = require('mongoose');
var orderBookSchema = mongoose.Schema({
type: {
type: String,
enum: ['stop_loss', 'limit'],
required: true
},
price: {
type: Number
},
quantity: {
type: Number
},
total: {
type: Number
},
date: {
type: String
},
pattern: {
type: String
},
created_at: {
type: Date,
default: Date.now
}
});
const orderBookModel = mongoose.model('order_book', orderBookSchema);
mongoose.set('useFindAndModify', false);
exports.model = orderBookModel;
exports.schema = orderBookSchema; |
import imgSrc from "./assets/artwork.jpg";
import imgSrc2 from "./assets/artwork2.jpg";
import imgSrc3 from "./assets/artwork3.jpg";
import cali from "./assets/cali-wataboi.mp3";
import fifty from "./assets/50-tobylane.mp3";
import iwonder from "./assets/iwonder-dreamheaven.mp3";
// All of these artists are at https://pixabay.com/music/search/mood/laid%20back/
export default [
{
title: "Rising Sun",
artist: "Airshow",
audioSrc:
"https://archive.org/download/AIRSHOW2021-04-09/2021.04.09/03%20Rising%20Sun.mp3",
image:
"https://archive.org/download/AIRSHOW2021-04-09/2021.04.09/IMG_0937.JPG",
color: "#00aeb0"
},
{
title: "50",
artist: "tobylane",
audioSrc: fifty,
image: imgSrc2,
color: "#ffb77a"
},
{
title: "I Wonder",
artist: "DreamHeaven",
audioSrc: iwonder,
image: imgSrc3,
color: "#5f9fff"
}
];
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindCourseClassByModuleController = exports.FindCourseClassController = void 0;
const httpHelpers_1 = require("../../helpers/httpHelpers");
const Controller_1 = require("../../protocols/Controller");
class FindCourseClassController extends Controller_1.Controller {
constructor(findClass, buidClass) {
super();
this.findClass = findClass;
this.buidClass = buidClass;
}
async handler(req) {
const classes = await this.findClass.execute(req.params.id);
const result = await this.buidClass.toClient(classes);
return httpHelpers_1.OK(result);
}
}
exports.FindCourseClassController = FindCourseClassController;
class FindCourseClassByModuleController extends Controller_1.Controller {
constructor(findClassByModule, buidClass) {
super();
this.findClassByModule = findClassByModule;
this.buidClass = buidClass;
}
async handler(req) {
console.log("okok");
const classes = await this.findClassByModule.execute(req.params.module);
const result = await this.buidClass.toClient(classes);
return httpHelpers_1.OK(result);
}
}
exports.FindCourseClassByModuleController = FindCourseClassByModuleController;
|
import React from 'react';
import {shallow} from 'enzyme';
import Visio from '../../views/SVMLoss/Demo/Visio';
describe('Visio', () => {
const component = shallow(<Visio/>);
it('renders correctly', () => {
expect(component).toMatchSnapshot();
});
});
|
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
const webPush = require('web-push');
const { publicKey, privateKey } = webPush.generateVAPIDKeys();
process.env.VAPID_PUBLIC_KEY = publicKey;
process.env.VAPID_PRIVATE_KEY = privateKey;
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
console.log(
'You must set the VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY ' +
'environment variables. You can use the following ones:',
);
console.log(webPush.generateVAPIDKeys());
return;
}
webPush.setVapidDetails(
'http://localhost:1234',
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY,
);
app.get('/vapidPublicKey', function(req, res) {
res.send(process.env.VAPID_PUBLIC_KEY);
});
app.post('/register', function(req, res) {
res.sendStatus(201);
});
app.post('/sendNotification', function(req, res) {
const subscription = req.body.subscription;
const payload = null;
const options = {
TTL: req.body.ttl,
};
setTimeout(function() {
webPush
.sendNotification(subscription, payload, options)
.then(function() {
res.sendStatus(201);
})
.catch(function(error) {
res.sendStatus(500);
console.log(error);
});
}, req.body.delay * 1000);
});
|
/*
* Route: /apps/:appId/devices/:appDeviceId/sessions/:appDeviceSessionId?
*/
const AppDeviceSessionModel = rootRequire('/models/AppDeviceSession');
const appDeviceAuthorize = rootRequire('/middlewares/apps/devices/authorize');
const appUserAuthorizeOptional = rootRequire('/middlewares/apps/users/authorizeOptional');
const router = express.Router({
mergeParams: true,
});
/*
* POST
*/
router.post('/', appDeviceAuthorize);
router.post('/', appUserAuthorizeOptional);
router.post('/', (request, response, next) => {
const { appDevice, appUser } = request;
const { location } = request.body;
let appDeviceSession = null;
return AppDeviceSessionModel.create({
appId: appDevice.appId,
appDeviceId: appDevice.id,
appUserId: appUser.id,
location,
}).then(_appDeviceSession => {
appDeviceSession = _appDeviceSession;
return appDevice.syncToSession(appDeviceSession);
}).then(() => {
response.success(appDeviceSession);
}).catch(next);
});
/*
* PATCH
*/
router.patch('/', appDeviceAuthorize);
router.patch('/', appUserAuthorizeOptional);
router.patch('/', (request, response, next) => {
const { appDevice } = request;
const { appDeviceSessionId } = request.params;
const { location, ended } = request.body;
let appDeviceSession = null;
AppDeviceSessionModel.find({
where: {
id: appDeviceSessionId,
appDeviceId: appDevice.id,
},
}).then(_appDeviceSession => {
appDeviceSession = _appDeviceSession;
if (!appDeviceSession) {
throw new Error('The app device session does not exist.');
}
if (appDeviceSession.endedAt) {
throw new Error('The ended app device session cannot be modified.');
}
appDeviceSession.appUserId = request.appUser.id || null;
appDeviceSession.location = location || appDeviceSession.location;
appDeviceSession.endedAt = (ended) ? new Date() : appDeviceSession.endedAt;
return appDeviceSession.save();
}).then(() => {
return request.appDevice.syncToSession(appDeviceSession);
}).then(() => {
response.success(appDeviceSession);
}).catch(next);
});
/*
* Export
*/
module.exports = router;
|
({
doInit: function(component, event, helper) {
//get the item packed status
var packed = component.get("v.item.Packed__c");
//get the toggle input component instance
//https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_find_by_id.htm
var packedCmps = component.find('packed');
var unpackCmp = component.find('unpack');
if(packed) {
for(var i = 0; i< packedCmps.length; i++) {
packedCmps[i].set("v.disabled", true);
}
unpackCmp.set("v.disabled", false);
} else {
for(var i = 0; i< packedCmps.length; i++) {
packedCmps[i].set("v.disabled", false);
}
unpackCmp.set("v.disabled", true);
}
},
/**
* packItem: function(component, event, helper) {
component.set("v.item.Packed__c",true);
var packedCmps = component.find('packed');
for(var i = 0; i< packedCmps.length; i++) {
console.log("packedCmp is " + packedCmps[i].get("v.disabled"));
packedCmps[i].set("v.disabled", true);
}
},
*/
packItem: function(component, event, helper) {
component.set("v.item.Packed__c",true);
var packedCmps = component.find('packed');
var unpackCmp = component.find('unpack');
for(var i = 0; i < packedCmps.length; i++) {
//console.log("packedCmp is " + packedCmps[i].get("v.disabled"));
packedCmps[i].set("v.disabled", true);
}
unpackCmp.set("v.disabled", false);
var item = component.get("v.item");
var itemUpdateEve = component.getEvent("itemUpdateEve");
itemUpdateEve.setParams({ "item": item });
itemUpdateEve.fire();
},
unpackItem: function(component, event, helper) {
component.set("v.item.Packed__c",false);
var packedCmps = component.find('packed');
var unpackCmp = component.find('unpack');
for(var i = 0; i < packedCmps.length; i++) {
packedCmps[i].set("v.disabled", false);
}
unpackCmp.set("v.disabled", true);
var item = component.get("v.item");
var itemUpdateEve = component.getEvent("itemUpdateEve");
itemUpdateEve.setParams({ "item": item });
itemUpdateEve.fire();
}
}) |
// ============================================================================
// Vector and Neural Network Objects
var DEFAULT_ACT_LIMIT = 1.3;
var DEFAULT_LEARN_RATE = 1;
var DEFAULT_ERR_TOL = 0.2;
//==============================================================================
function Vector(size) {
this.length = size;
this.vector_array = new Array(size);
//----------------------------------------------------------------------------
this.set_zero = function() {
for (var i=0; i<this.length; i++) { this.vector_array[i] = 0; }
};
//----------------------------------------------------------------------------
this.set = function(index, value) {
this.vector_array[index] = value;
};
//----------------------------------------------------------------------------
this.inner_product = function(a, b) {
var i;
var sum = 0.0;
for (i=0; i<a.length;i++) { sum += a[i] * b[i]; }
return sum;
};
//----------------------------------------------------------------------------
this.outer_product = function(a, b, matrix) {
var i,j;
for(i=0;i<a.length;i++) // loop through elements of a to get rows
{
matrix.vector_array[i] = [];
for(j=0;j<b.length;j++) // loop through elements of b to get cols
{
matrix.vector_array[i][j] = a[i] * b[j];
}
}
return matrix;
};
//----------------------------------------------------------------------------
this.sub = function(a, b, dif) {
var i;
for (i=0; i<a.length;i++) { dif.vector_array[i] = a[i] - b[i]; }
return dif;
};
//----------------------------------------------------------------------------
this.scale = function(scalar) {
for(var i=0; i<this.length; i++) { this.vector_array[i] *= scalar; }
};
//----------------------------------------------------------------------------
this.ramp = function( value, limit) {
if ( Math.abs(value) < limit) {
return value;
} else if ( value <= (limit * -1) ) {
return limit * -1;
} else {
return limit;
}
};
//----------------------------------------------------------------------------
this.ramp_all = function(act_limit) {
for (var i=0; i<this.length; i++) {
this.set(i, this.ramp(this.vector_array[i], act_limit));
}
};
//----------------------------------------------------------------------------
this.magnitude = function(a) {
var sum = 0;
for (var i=0; i<a.length; i++) {
sum += (a[i] * a[i]);
}
return Math.sqrt(sum);
};
//----------------------------------------------------------------------------
this.normalized_version = function() {
a_norm = new Vector(this.vector_array.length);
for (var i=0; i<this.length; i++) {
a_norm.vector_array[i] = this.vector_array[i] / this.length;
}
return a_norm;
};
//----------------------------------------------------------------------------
this.normalized_dot_product = function(a,b) {
alert("This method TBD");
return null;
};
}
//==============================================================================
function Network(num_elements, nodes_per_element, weight_min, weight_max) {
//----------------
// private members
var min = weight_min;
var max = weight_max;
var self = this; // self-reference as a private member
//---------------
// public members
this.num_elements = num_elements;
this.nodes_per_element = nodes_per_element;
this.weight_matrix = new Vector(this.num_elements);
this.act_limit = DEFAULT_ACT_LIMIT;
this.learning_rate = DEFAULT_LEARN_RATE;
this.error_tolerance = DEFAULT_ERR_TOL;
//----------------
// private methods
//============================================================================
function private_test(msg) {
alert(msg);
}
//---------------
// public methods
//--------
// SETTERS
this.set_act_limit = function(new_limit) { this.act_limit = new_limit; };
this.set_learning_rate = function(new_rate) { this.learning_rate = new_rate; };
this.set_err_tolerance = function(new_tolerance) { this.error_tolerance = new_tolerance; };
//============================================================================
this.initialize_weights = function() {
for (var i=0; i<this.num_elements; i++) {
this.weight_matrix.vector_array[i] = get_new_random_array(this.nodes_per_element, min, max);
}
};
//============================================================================
this.reset_network = function() {
for (var i=0; i<this.num_elements; i++) {
for (var j=0; j<this.nodes_per_element; j++) {
this.weight_matrix.vector_array[i][j] = generate_random_float(min, max);
}
}
};
//============================================================================
this.stimulate_with = function(input, output) {
var i;
var ip; // inner product
output.set_zero();
for (i=0; i < this.num_elements; i++) {
// Quantize output to binomial values as calculated
ip = input.inner_product(this.weight_matrix.vector_array[i], input.vector_array);
if ( ip >= 0 ) {
output.set(i, 255);
} else {
output.set(i, 0);
}
}
return output;
};
//============================================================================
this.train_with = function(input, output, ref) {
var i,j;
//alert(ref.vector_array);
var errors = new Vector(this.num_elements);
var deltas = new Vector(this.num_elements);
// Compute output of network
for(i=0; i<this.num_elements; i++)
{
output.set(i, input.inner_product(this.weight_matrix.vector_array[i], input.vector_array));
}
output.ramp_all(this.act_limit);
// compute error vector as difference of reference and output
errors = output.sub(ref.vector_array, output.vector_array, errors);
// adjust error vector by learning rate
errors.scale(this.learning_rate);
// calculate delta weights as outer product of errors and input vector
deltas = output.outer_product(errors.vector_array, input.vector_array, deltas);
// adjust weights by adding deltas
for(i=0; i<this.num_elements; i++) // loop through to get rows
{
for(j=0; j<this.num_elements; j++) //loop through to get cols
{
// only change if the delta is > error tolerance
if( Math.abs(deltas.vector_array[i][j]) > this.error_tolerance) {
this.weight_matrix.vector_array[i][j] += deltas.vector_array[i][j];
}
}
}
// recalculate output with new weights
output = this.stimulate_with(input, output);
return output;
};
//============================================================================
this.ratio_of_matching = function(a,b) {
var num_matching = 0;
var num_total = 0;
for (var i = 0; i<a.length; i++ ) {
if (a[i] === b[i]) { num_matching += 1; }
num_total += 1;
}
var ratio = num_matching/num_total;
return Math.round(ratio*100) / 100;
};
//============================================================================
this.test = function(msg) {
private_test(msg + "this is a private message");
};
}
|
var names = ["James", "Jill", "Jane", "Jack"]
function sort() {
console.log("0 ->", names[0]);
console.log("1 ->", names[1]);
console.log("2 ->", names[2]);
console.log("3 ->", names[3]);
}
sort(names)
|
export default {
games:[],
game_prices:[],
game_details:[],
}
|
import React from 'react'
import { Link } from 'react-router'
class Signin extends React.Component {
constructor(props) {
super(props)
this.signinHandler = this.signinHandler.bind(this)
this.signedinHandler = this.signedinHandler.bind(this)
this.enter = this.enter.bind(this)
this.state = {
email: '',
password: ''
}
}
signinHandler() {
fetch('https://nameless-cove-75673.herokuapp.com/log_in', {
body: JSON.stringify({
email: this.state.email,
password: this.state.password
}),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(this.signedinHandler)
}
signedinHandler(response) {
sessionStorage.setItem('chirp_token', response.user.api_token)
window.location.href = path +'/myprofile'
}
enter(e) {
if (e.key === 'Enter') {
this.signinHandler()
}
}
render() {
return <div className="row">
<div className="col-sm-12 text-center">
<h1 className="coolFont">Welcome to Chirp!</h1>
</div>
<div className="col-sm-6 col-sm-offset-3">
<div className="form-group">
<label>Email</label>
<input id="signinEmail" type="email" name="email" onChange={(e) => this.setState({email:e.target.value})} className="form-control" required/>
</div>
<div className="form-group">
<label>Password</label>
<input id="signinPassword" type="password" onChange={(e) => this.setState({password:e.target.value})} className="password" className="form-control" onKeyPress={this.enter} required/>
</div>
<div className="row">
<div className="col-sm-6">
<Link to={path + "/"}>
<button type="button" className="btn btn-primary">Cancel</button>
</Link>
</div>
<div className="col-sm-6 text-right">
<button id="login" type="button" className="btn btn-success" onClick={this.signinHandler}>Login</button>
</div>
</div>
</div>
</div>
}
}
export default Signin
|
var box = null;
var countUnchecked = null;
var countDirectValid = null;
var countRedirectedValid = null;
var countDirectInvalid = null;
var countRedirectedInvalid = null;
var countException = null;
var responses = [];
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
switch (request.cmd) {
case 'makeBox':
makeBox(request.html);
break;
case 'showResult':
showResult(request.url);
break;
default:
break;
}
return true;
}
);
function makeBox(html) {
if (box !== null) {
box.style.visibility = 'visible';
return;
}
var template = document.createElement('template');
template.innerHTML = html.trim();
box = template.content.firstChild;
document.body.appendChild(box);
countUnchecked = document.getElementById('linkit_count_unchecked');
countDirectValid = document.getElementById('linkit_count_direct_valid');
countRedirectedValid = document.getElementById('linkit_count_redirected_valid');
countDirectInvalid = document.getElementById('linkit_count_direct_invalid');
countRedirectedInvalid = document.getElementById('linkit_count_redirected_invalid');
countException = document.getElementById('linkit_count_exception');
document.getElementById('linkit_start').addEventListener('click', start);
document.getElementById('linkit_export').addEventListener('click', export_csv);
document.getElementById('linkit_close').addEventListener('click', function () {
box.style.visibility = 'hidden';
});
box.onmousedown = function (e) {
e = e || window.event;
var x = e.clientX;
var y = e.clientY;
document.onmouseup = function () {
box.style.pointerEvents = 'unset';
document.onmouseup = null;
document.onmousemove = null;
};
document.onmousemove = function (e) {
box.style.pointerEvents = 'none';
e = e || window.event;
box.style.top = (box.offsetTop + e.clientY - y) + "px";
box.style.left = (box.offsetLeft + e.clientX - x) + "px";
box.style.right = 'unset';
x = e.clientX;
y = e.clientY;
};
}
}
function start() {
function changeCount(element, delta) {
var oldCount = parseInt(element.innerHTML);
var newCount = oldCount + delta;
element.innerHTML = String(newCount);
if (oldCount > 0 && newCount <= 0) {
element.parentElement.style.visibility = 'collapse';
}
if (oldCount <= 0 && newCount > 0) {
element.parentElement.style.visibility = 'inherit';
}
return newCount;
}
var noCache = document.getElementById("linkit_no_cache").checked;
var timeout_input = document.getElementById("linkit_timeout");
var timeout = parseFloat(timeout_input.value);
timeout = 0 < timeout ? timeout : 0;
timeout = timeout < 600 ? timeout : 600;
timeout_input.value = timeout;
document.querySelectorAll('a[href]:not(.linkit_checked)').forEach(function (link) {
var url = link.href.split('#')[0];
if (!url.startsWith('http://') && !url.startsWith('https://')) {
return;
}
changeCount(countUnchecked, 1);
link.classList.add('linkit_unchecked');
chrome.runtime.sendMessage({
cmd: 'checkUrl',
url: url,
noCache: noCache,
timeout: timeout
}, function (response) {
responses.push(response);
link.classList.remove('linkit_unchecked');
link.classList.add('linkit_checked');
if (changeCount(countUnchecked, -1) <= 0) {
document.getElementById('linkit_export').style.visibility = 'inherit';
}
if (response.exception === null) {
if (response.redirected) {
link.classList.add('linkit_redirected');
}
if (response.valid) {
link.classList.add('linkit_valid');
changeCount(response.redirected ? countRedirectedValid : countDirectValid, 1);
} else {
link.classList.add('linkit_invalid');
changeCount(response.redirected ? countRedirectedInvalid : countDirectInvalid, 1);
}
} else {
link.classList.add('linkit_exception');
changeCount(countException, 1);
}
});
});
}
function export_csv() {
responses.sort(function (a, b) {
if (a.exception === null && b.exception !== null) {
return 1;
} else if (a.exception !== null && b.exception === null) {
return -1;
} else if (a.exception !== null && b.exception !== null) {
return (a.exception < b.exception) ? -1 : 1;
} else {
if (a.status !== b.status) {
return (a.status < b.status) ? -1 : 1;
} else {
return (a.requestUrl < b.requestUrl) ? -1 : 1;
}
}
});
function escapeCsvString(s) {
return s !== null ? '"' + s.replace('"', '""') + '"' : null;
}
var csv = ['exception,status(code),status(text),redirected,valid,requestUrl,responseUrl'];
responses.forEach(function (r) {
csv.push([
r.exception,
r.status,
r.statusText,
r.redirected,
r.valid,
escapeCsvString(r.requestUrl),
escapeCsvString(r.responseUrl)
].join(','));
});
csv = csv.join('\r\n');
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
element.setAttribute('download', 'linkit.csv');
element.style.display = 'none';
box.appendChild(element);
element.click();
box.removeChild(element);
}
function showResult(url) {
url = url.split('#')[0];
if (!url.startsWith('http://') && !url.startsWith('https://')) {
alert(url + '\n不是一个合理的URL');
return;
}
var results = [];
responses.forEach(function (r) {
// 右键获取的url会自动encode,需要处理
if (r.requestUrl === url || r.requestUrl === decodeURIComponent(url)) {
for (var i = 0; i < results.length; i++) {
if (JSON.stringify(r) === JSON.stringify(results[i])) {
return;
}
}
results.push(r);
}
});
if (results.length === 0) {
alert(url + '\n还未进行检查');
} else {
str = '请求地址:' + url;
results.forEach(function (r) {
str += '\n\n';
if (r.exception === null) {
str += r.redirected ? '(重定向的)' : '';
str += r.valid ? '有效链接' : '无效链接!';
str += r.redirected ? '\n响应地址:' + r.responseUrl : '';
str += '\n响应状态:' + r.status + '(' + r.statusText + ')';
} else {
str += r.exception;
}
});
alert(str);
}
} |
/**
* @author veekergdn.cn
* @file briefs的model
*/
import query from '../utils/query';
import escape from '../utils/escape';
class Briefs {
async getBrief() {
return await query('SELECT * FROM lss_about');
}
async updateBrief(id, content) {
return await query(escape`UPDATE lss_about SET content=${content} WHERE id=${id}`);
}
}
export default new Briefs();
|
'use strict'
const
chai = require('chai'),
chaiHttp = require('chai-http'),
config = require('../../knexfile.js'),
server = require('../../index'),
Faker = require('faker'),
makeFake = require('../helpers/fakers'),
Promise = require('bluebird');
const
should = chai.should(),
expect = chai.expect,
Genre = require('../../models/Genre'),
Artist = require('../../models/Artist'),
knex = require('knex')(config.test),
migrate = knex.migrate;
chai.use(chaiHttp);
const agent = chai.request.agent(server);
describe('artistCtrl', () => {
var testArtist,
testGenre,
testFounder,
testUser,
testAdmin,
session,
testUserPassword,
testAdminPassword;
before((done) => {
migrate.rollback()
.then(() => {
done()
})
.catch((err) => {
console.log(err);
done();
})
});
beforeEach((done) => {
migrate.latest()
.then(() => {
let a = makeFake.Artist(),
g = makeFake.Genre(),
f = makeFake.Artist();
return Promise.all([
Artist.forge(a).save(),
Genre.forge(g).save(),
Artist.forge(f).save()
])
})
.spread((a, g, f) => {
testArtist = a;
testGenre = g;
testFounder = f;
return Promise.all([
g.artists().attach([g.id, f.id]),
g.founders().attach(f),
f.proteges().attach(a),
makeFake.UserAndSave(),
makeFake.UserAndSave()
]);
})
.then(a => {
testUser = a[3].user
testAdmin = a[4].user
testUserPassword = a[3].password
testAdminPassword = a[4].password
done();
})
.catch((err) => {
throw err;
done();
})
})
afterEach((done) => {
migrate.rollback()
.then(() => {
done();
})
.catch((err) => {
console.log(err);
done();
})
})
function login() {
testUser = testUser.toJSON();
testUser.password = testUserPassword;
return agent.post('/login').send(testUser)
}
it.skip('should get a list of all genres', (done) => {
Genre.forge(makeFake.Genre()).save()
.then((artist) => {
return login()
.then(() => {
agent
.get('/api/genre/')
.end((e, r) => {
if (e) console.log(e);
r.should.have.status(200);
r.should.have.property('body');
r.body[0].should.have.property('name');
done();
})
})
})
});
it('should get one genre', (done) => {
login()
.then(() => {
agent
.get('/api/genre/' + testGenre.id)
.end((e, r) => {
if (e) throw e;
r.should.have.status(200)
r.should.have.property('body');
r.body.should.have.property('name');
r.body.name.should.equal(testGenre.get('name'));
r.body.should.have.property('founders');
let f = r.body.founders;
f.should.be.a('array');
expect(f[0]).to.be.ok;
r.body.should.have.property('artists');
let a = r.body.artists;
a.should.be.a('array');
expect(a[0]).to.be.ok;
done();
})
})
});
it('should create a new genre', (done) => {
var genre = makeFake.Genre();
login()
.then(() => {
agent
.post('/api/genre/')
.send(genre)
.end((e, res) => {
if (e) throw e;
res.should.have.status(200)
res.body.should.be.a('object')
res.body.should.have.property('name')
res.body.name.should.equal(genre.name);
done();
})
})
});
it('should update an existing genre', (done) => {
login()
.then(() => {
agent
.put('/api/genre/' + testGenre.id)
.send({name: 'breakfast'})
.end((e, r) => {
if (e) throw e;
r.should.have.status(200);
r.body.should.be.a('object');
r.body.should.have.property('message');
r.body.message.should.equal('Update Successful');
Genre.forge({id: testGenre.id})
.fetch()
.then((genre) => {
expect(genre.get('name')).to.equal('breakfast');
done();
})
})
})
});
it('should delete a genre', (done) => {
login()
.then(() => {
agent
.delete('/api/genre/' + testGenre.id)
.end((e, r) => {
r.should.have.status(200)
r.body.should.have.property('message')
r.body.message.should.equal('Genre deleted')
Genre.forge({id: testGenre.id})
.fetch()
.then((result) => {
expect(result).to.equal(null);
done();
})
})
})
});
it('should add an artist as a founder', (done) => {
let newArtist = makeFake.Artist();
Artist.forge(newArtist).save()
.then((artist) => {
artist = artist.toJSON();
testGenre = testGenre.toJSON()
testGenre.founders = [artist]
return login()
.then(() => {
agent
.put('/api/genre/' + testGenre.id)
.send(testGenre)
.end((e, r) => {
if (e) throw e;
r.should.have.status(200);
r.body.should.be.ok;
Genre.forge({id: testGenre}).fetch({withRelated: ['founders']})
.then((genre) => {
genre = genre.toJSON();
genre.founders.should.be.a('array');
expect(genre.founders[0]).to.be.ok;
done();
})
})
})
})
})
it('should add an artist to a genres artists collection', (done) => {
let genre, artist;
Promise.all([
makeFake.artistAndSave(),
makeFake.genreAndSave(),
])
.spread((_artist, _genre) => {
genre = _genre.toJSON();
artist = _artist.toJSON();
genre.artists = [artist];
return login()
})
.then(() => {
agent
.put('/api/genre/' + genre.id)
.send(genre)
.end((e, r) => {
r.should.have.status(200);
Genre.forge({id: genre.id}).fetch({withRelated: ['artists']})
.then(genre => {
genre = genre.toJSON();
genre.should.have.property('artists');
genre.artists.should.be.a('array');
expect(genre.artists[0]).to.have.property('id');
expect(genre.artists[0].id).to.equal(artist.id);
done();
})
})
})
})
it('should add a founder to a genres founders collection', (done) => {
let genre, artist;
Promise.all([
makeFake.artistAndSave(),
makeFake.genreAndSave()
])
.spread((_artist, _genre) => {
genre = _genre.toJSON()
artist = _artist.toJSON()
genre.founders = [artist];
return login()
})
.then(() => {
agent
.put('/api/genre/' + genre.id)
.send(genre)
.end((e, r) => {
r.should.have.status(200)
Genre.forge({id: genre.id}).fetch({withRelated: ['founders']})
.then(genre => {
genre = genre.toJSON();
genre.should.have.property('founders');
genre.founders.should.be.a('array');
expect(genre.founders[0]).to.have.property('id');
expect(genre.founders[0].id).to.equal(artist.id);
done();
})
})
})
})
it('should add a subgenre', (done) => {
let genre, subgenre;
Promise.all([
makeFake.genreAndSave(),
makeFake.genreAndSave()
])
.spread((_genre, _subgenre) => {
genre = _genre.toJSON();
subgenre = _subgenre.toJSON();
genre.subgenres = [subgenre];
return login()
})
.then(() => {
agent
.put('/api/genre/' + genre.id)
.send(genre)
.end((e, r) => {
r.should.have.status(200)
Genre.forge({id: genre.id}).fetch({withRelated: ['subgenres']})
.then((genre) => {
genre = genre.toJSON();
genre.should.have.property("subgenres")
var s = genre.subgenres;
s.should.be.a('array');
expect(s[0]).to.be.ok;
s[0].should.be.a('object');
s[0].id.should.equal(subgenre.id);
done();
})
})
})
it.only('should add a root', (done) => {
let root, genre;
Promise.all([
makeFake.genreAndSave(),
makeFake.genreAndSave()
])
.spread((_root, _genre) => {
root = _root.toJSON()
genre = _genre.toJSON()
genre.root = root;
return login()
})
.then(() => {
agent
.put('/api/genre/' + genre.id)
.send(genre)
.end((e, r) => {
r.should.have.status(200)
Genre.forge({id: genre.id}).fetch({withRelated: ['root']})
.then(genre => {
genre = genre.toJSON();
expect(genre).to.be.a('object');
expect(genre).to.have.property('root');
expect(genre.root).to.have.property('id');
expect(genre.root.id).to.equal(root.id);
done();
})
})
})
it('should make a new genre and add it as a root', (done) => {
makeFake.genreAndSave()
.then(root => {
root = root.toJSON();
var genre = makeFake.Genre();
genre.root = root;
return login()
})
.then(() => {
agent
.post('/api/genre/')
.send(genre)
.end((e, r) => {
r.should.have.status(200)
r.should.have.property('body');
r.body.should.have.property('id');
genre = r.body;
Genre.forge({id: r.body.id}).fetch({withRelated: ['root']})
.then(genre => {
genre = genre.toJSON();
expect(genre).to.be.ok;
genre.should.have.property('root');
genre.root.should.be.a('object');
genre.root.id.should.equal(root.id);
return Genre.forge({id: root.id}).fetch({withRelated: ['subgenres']})
})
.then(root => {
root = root.toJSON();
expect(root).to.be.ok;
root.should.have.property('subgenres');
root.subgenres.should.be.a('array');
root.subgenres[0].id.should.equal(genre.id);
done();
})
})
})
})
})
})
})
|
var main = angular.module('main');
var mainControllers = {
NavBarController: function ($scope, $http, cookies, $rootScope) {
// VARIABLES
$scope.brand = 'Bookflix';
$scope.currentAction = '';
$scope.search = { query: '' };
$scope.my = { books: false, unreadMessages: 0 };
$scope.location = { isBooks: false };
// get cookies to determine what to show on nav-bar and when
$scope.username = cookies.getCookie('username');
$scope.admin = cookies.getCookie('admin');
// watch changes for books filters, and act accordingly:
$scope.$watch('search.query', function (newVal, from) {
// broadcast an event for new search query by user
$rootScope.$broadcast('searchEvent', newVal);
});
$scope.$watch('my.books', function (newVal, from) {
// update book list to show only my books
$rootScope.myBooks = newVal;
});
// FUNCTIONS
// determines what to ng-include: sign up or login
$scope.action = function () {
return $scope.currentAction;
}
// pops up sign up modal
$scope.displaySignUp = function () {
$scope.currentAction = 'signup.html';
setTimeout(function(){ $('#signup').modal('show');}, 300);
}
// pops up login modal
$scope.displayLogin = function () {
$scope.currentAction = 'login.html';
setTimeout(function(){ $('#login').modal('show'); }, 300);
}
// do logout
$scope.logout = function () {
$http.post("logout").then(function(response){
window.location.hash = "home";
setTimeout(function(){ location.reload(); }, 200);
}, function(response) {
});
}
// get amount of unread messages
$scope.getUnreadMessages = function () {
$http.get("messages/unread").then(function(response){
if (!isNaN(response.data)) {
$scope.my.unreadMessages = response.data;
}
}, function(response) {
});
}
// EVENTS HANDLING
// hide books search-bar depending on location
$(window).on('hashchange', function (){
var currLocation = window.location.hash.split('/')[1];
$scope.location.isBooks = (currLocation === 'books' || currLocation === 'home');
if (currLocation === 'messages') {
$scope.my.unreadMessages = 0;
}
if (currLocation !== 'books') {
$scope.search.query = '';
}
});
// INIT ROUTINE:
if ($scope.username) {
$scope.getUnreadMessages();
}
}
}
main.controller(mainControllers);
main.component('navBar', {
templateUrl: 'navbar.html',
controller: 'NavBarController'
}); |
'use strict';
const express = require('express');
const app = express();
// Application
app.get('/reverse', function (req, res) {
var ans = '';
const inpt = req.query.input;
if (inpt != null) {
for (var i = inpt.length-1; i >= 0; i--)
ans += inpt[i];
}
res.send(ans);
});
const PORT = 8080
app.listen(PORT, function () {
console.log('Webservice up on http://localhost:' + PORT);
});
|
/* ajax functionality for ingesting items in the harvest queue */
$(document).ready(function () {
// NOTE: There is some overlap in ingest/ignore functionality
// below (particularly success/error handling and message
// display), but it is not obvious how to combine them.
// configure ingest buttons to POST pmcid when clicked
$(".content").on("click", ".ingest", function() {
var data = { pmcid: $(this).find(".pmcid").html()};
var entry = $(this).parent();
var msg = entry.find('.message');
var errclass = 'error-msg';
var success_class = 'success-msg';
var csrftoken = $("#csrftoken input").attr("value");
if ( ! entry.hasClass('working') ) {
entry.addClass('working');
$.ajax({
type: 'POST',
data: data,
url: $(this).attr('href'),
headers: {'X-CSRFTOKEN': csrftoken},
success: function(data, status, xhr) {
msg.html(data || 'Success');
msg.removeClass(errclass).addClass(success_class).show().delay(1500).fadeOut();
// change queue item class on success so display can be updated
entry.removeClass('working').addClass('ingested');
var location = xhr.getResponseHeader('Location');
// display view and edit links based on returned location
var view_link = $('<a>view</a>').attr('href', location).addClass('link');
var edit_link = $('<a>review</a>').attr('href', location + 'edit/').addClass('link');
entry.prepend(edit_link).prepend(view_link);
},
error: function(data, status, xhr) {
msg.html('Error: ' + data.responseText);
msg.removeClass(success_class).addClass(errclass).show();
// NOTE: not fading error message out, since it may
// need to be reported
}
});
}
return false;
});
// configure ignore buttons to DELETE specified url when clicked
$(".content").on("click", ".ignore", function() {
var entry = $(this).parent();
var msg = entry.find('.message');
var errclass = 'error-msg';
var success_class = 'success-msg';
var csrftoken = $("#csrftoken input").attr("value");
if ( ! entry.hasClass('working') ) {
entry.addClass('working');
$.ajax({
type: 'DELETE',
url: $(this).attr('href'),
headers: {'X-CSRFTOKEN': csrftoken},
success: function(data, status, xhr) {
msg.html(data || 'Success');
msg.removeClass(errclass).addClass(success_class).show().delay(1500).fadeOut();
// change queue item on success so display can be updated
entry.removeClass('working').addClass('ignored');
},
error: function(data, status, xhr) {
msg.html('Error: ' + data.responseText);
msg.removeClass(success_class).addClass(errclass).show();
}
});
}
return false;
});
});
|
module.exports = {
plugins: ['lodash'],
extends: [
'plugin:prettier/recommended',
],
parser: '@babel/eslint-parser',
rules: {
// No need to convert between OS platforms
'linebreak-style': 'off',
'require-await': 'error',
// Allow dev dependencies to be explicitly required in tools and such
'import/no-extraneous-dependencies': ['error', { 'devDependencies': true }],
// Allow mongo id fields
'no-underscore-dangle': ['error', { 'allow': ['_id'] }],
// Allow functions to be defined anywhere
'no-use-before-define': ['error', { 'functions': false, 'classes': true, 'variables': true }],
'padding-line-between-statements': [
'error',
{
'blankLine': 'always',
'prev': ['block', 'block-like', 'cjs-export', 'class', 'export', 'import'],
'next': '*'
},
{ 'blankLine': 'any', 'prev': ['export', 'import'], 'next': ['export', 'import'] }
],
// Allow not to destructure an object when assigning to an already existing variable
'prefer-destructuring': [
'error',
{
'VariableDeclarator': { 'array': true, 'object': true },
'AssignmentExpression': { 'array': true, 'object': false }
},
{ enforceForRenamedProperties: false, }
],
'lodash/import-scope': ['error', 'method'],
'lodash/prefer-compact': 'error',
'lodash/prefer-immutable-method': 'error',
'lodash/prefer-is-nil': 'error',
'lodash/prefer-lodash-typecheck': 'error',
'lodash/prefer-noop': 'error',
}
} |
var over : boolean = false;
var can_restart: boolean = false;
var fader: fade_in;
private var bg_color : Color = Color(2/255, 20/255, 26/255, 0.05);
function Start () {
GetComponent.<Camera>().backgroundColor = Color.white / 9;
fader.GetComponent(GUITexture).color = Color.black;
fader.Fade();
Application.targetFrameRate = 60;
}
function Update () {
//Exits the application if the player pressed the back button
if (Input.GetButtonDown("Exit"))
Application.Quit();
#if UNITY_EDITOR
if (Input.GetKeyDown("f"))
Cursor.visible = false;
#endif
if (over && !can_restart)
if (Input.touchCount == 0)
can_restart = true;
if (over && can_restart && (Input.touchCount > 0 || Input.GetButtonDown("Fire1"))){
Application.LoadLevel("main");
}
GetComponent.<Camera>().backgroundColor = Color.Lerp(GetComponent.<Camera>().backgroundColor, bg_color, .1);
}
function GameOver () {
if (Input.touchCount == 0)
can_restart = true;
over = true;
}
function ChangeBackgroundColor (color : Color) {
if(color == Color.white)
bg_color = color / 8;
else
bg_color = color / 7;
} |
let canvas;
let ctx;
document.addEventListener('DOMContentLoaded', (event) => {
canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
flag = 0;
canvas.addEventListener('click', (event) =>{
flag = flag^1;
console.log(flag);
if(flag){
canvas.addEventListener('mousemove',fun);
}else{
canvas.removeEventListener('mousemove',fun);
}
})
});
function fun(event){
//console.log(event);
let url = 'http://api.noopschallenge.com/hexbot';
let x = event.clientX;
let y = event.clientY;
axios.get(url).then((response) =>{
let {colors} = response.data;
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2*Math.PI);
ctx.fillStyle = colors[0].value;
ctx.fill();
});
}
|
import { useSelector } from "react-redux";
export const useItemsByCategory = category => {
const [items] = useSelector(({ items }) => [Object.values(items.byId)]);
return items.filter(item => item.category === category);
};
export const useFeaturedItems = () => {
const [items] = useSelector(({ items }) => [Object.values(items.byId)]);
return items.filter(item => item.isFeatured);
};
export const useItem = itemId => {
return useSelector(({ items }) => items.byId[itemId]);
};
|
function getname() {
var gender = document.getElementById("gender").checked;
var day = document.getElementById("birthday").value;
var date = new Date(day).getDay();
if (day && gender !== null) {
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][date];
if (gender == true) {
var names = ["Akosua", "Adwoa", "Abenaa", "Akua", "Yaa", "Afua", "Ama"];
var getname = names[date];
}
else {
var names = ["Kwasi", "Kwadwo", "kwabena", "Kwaku", "Yaw", "Kofi", "Kwame"];
var getname = names[date];
}
alert("Hi, Your Akan Name is " + getname + ". the day you were born is " + days);
}
else {
alert("Enter a date and select gender");
}
} |
import React from 'react';
import ContactForm from './../contact-form/ContactForm';
const APropos = props => {
return <ContactForm />;
};
export default APropos;
|
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Public = lazy(() => import('./pages/Public'));
const Login = lazy(() => import('./pages/Login'));
const Signup = lazy(() => import('./pages/Signup'));
const ForgotPassword = lazy(() => import('./pages/ForgotPassword'));
const Feed = lazy(() => import('./pages/Feed'));
const Post = lazy(() => import('./pages/Post'));
const Profile = lazy(() => import('./pages/Profile'));
const Like = lazy(() => import('./pages/Like'));
const Cart = lazy(() => import('./pages/Cart'));
const Order = lazy(() => import('./pages/Order'));
const Sale = lazy(() => import('./pages/Sale'));
const Settings = lazy(() => import('./pages/Settings'));
const NoMatch = lazy(() => import('./pages/NoMatch'));
const App = () => (
<Router>
<Switch>
<Suspense fallback={<section>Loading...</section>}>
<Route exact path="/" component={Public} />
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
<Route path="/forgotPassword" component={ForgotPassword} />
<Route path="/feed" component={Feed} />
<Route path="/post" component={Post} />
<Route path="/profile" component={Profile} />
<Route path="/like" component={Like} />
<Route path="/cart" component={Cart} />
<Route path="/order" component={Order} />
<Route path="/sale" component={Sale} />
<Route path="/settings" component={Settings} />
</Suspense>
<Route component={NoMatch} />
</Switch>
</Router>
);
export default App;
|
const connection = require('../database/connection')
const Event = require('../models/Event')
module.exports = {
async index (request, response) {
try {
const events = await Event.findAll({ raw: true})
return response.status(200).send(events)
} catch (err) {
return response.status(400).send({ error: 'Error finding events'})
}
},
async show (request, response) {
const id = Number(request.params.id)
try {
const event = await Event.findOne({ where: { id:id } })
if (!event) {
return response.status(404).send({ error: 'Event not found' })
}
return response.status(200).send(event)
} catch (err) {
return response.status(400).send({ error: 'Error finding event' })
}
},
async create (request, response) {
const {
name,
locale,
description,
latitude,
longitude,
image
} = request.body
try {
const event = await Event.create({
name,
locale,
description,
latitude,
longitude,
image
})
return response.status(201).send(event)
} catch (err) {
return response.status(400).send({ error: 'Error creating user' })
}
},
async update (request, response) {
const id = Number(request.params.id)
const {
name,
locale,
description,
latitude,
longitude,
image
} = request.body
try {
const event = await Event.findOne({ where: {id:id} })
if ( !event ) {
return response.status(404).send({ error: 'Event not found' })
}
await Event.update({
name,
locale,
description,
latitude,
longitude,
image
}, {
where: {id:id}
})
return response.status(200).send({ msg: 'Event updated' })
} catch (err) {
return response.status(400).send({ error: 'Error editing event' })
}
},
async delete (request, response) {
const id = Number(request.params.id)
try {
const event = await Event.findOne({ where: { id:id } })
if ( !event ) {
return response.status(404).send({ error: 'Event not found' })
}
await Event.destroy({ where: { id:id } })
return response.status(200).send({ msg: 'Event deleted' })
} catch (err) {
return response.status(400).send({ error: 'Error deleting event' })
}
}
}
|
class BookDao {
constructor(db) {
this._db = db
}
toList() {
return new Promise((resolve, reject) => {
this._db.all(`SELECT * FROM livros`,
(err, results) => {
if (err)
return reject(`It was not possible to list the books.`)
return resolve(results)
}
)
})
}
add(book) {
return new Promise((resolve, reject) => {
this._db.run(`
INSERT INTO livros
(titulo, preco, descricao)
VALUES (?,?,?)`,
[
book.titulo,
book.preco,
book.descricao
]),
(err) => {
if (err) {
console.error(err)
return reject(`It was not possible to add the book.`)
}
resolve()
}
})
}
findById(id) {
return new Promise((resolve, reject) => {
this._db.get(`
SELECT * FROM livros WHERE id = ?
`,
[id]
),
(err, book) => {
if (err)
return reject(`It was not possible find the book.`)
return resolve(book)
}
})
}
update(book) {
return new Promise((resolve, reject) => {
this._db.run(`
UPDATE livros
SET titulo = ?, preco = ?, descricao = ?
WHERE id = ?
`,
[
book.titulo,
book.preco,
book.descricao,
book.id
]),
(err) => {
if (err) {
console.error(err)
return reject(`It was not possible to add the book.`)
}
resolve()
}
})
}
remove(id) {
return new Promise((resolve, reject) => {
this._db.run(`
DELETE FROM livros
WHERE id = ?
`,
[id]
),
(err) => {
if (err) {
console.error(err)
return reject(`It was not possible to delete the books`)
}
resolve()
}
})
}
}
module.exports = BookDao |
export const GET_CHAMPS = "GET_CHAMPS";
export const SEARCH_CHAMPS = "SEARCH_CHAMPS";
export const GET_CHAMP = "GET_CHAMP";
|
const db = require("../models/index");
const Basket = db.sequelize.define(
"Baskets",
{
BasketIP: {
type: db.Sequelize.STRING,
allowNull: false,
primaryKey: true,
},
ProductID: {
type: db.Sequelize.INTEGER,
allowNull: false,
},
Quantity: {
type: db.Sequelize.INTEGER,
allowNull: true,
},
TotalPrice: {
type: db.Sequelize.INTEGER,
allowNull: true,
},
},
{
tableName: "Baskets",
timestamps: false,
}
);
module.exports = Basket;
|
const weather = require('../assets/weather.json');
const superagent = require('superagent');
require('dotenv').config();
const WEATHER_BIT_KEY = process.env.WEATHER_BIT_KEY;
const inMemory = {};
const weatherHandler = (req, res) => {
try {
const weatherBitUrl = `https://api.weatherbit.io/v2.0/forecast/daily?key=${WEATHER_BIT_KEY}&lat=${req.query.lat}&lon=${req.query.lon}`;
superagent.get(weatherBitUrl).then(weatherBitData => {
if (inMemory[`${req.query.lat} ${req.query.lon}`]){
console.log('from APIWeather')
res.send(inMemory[`${req.query.lat} ${req.query.lon}`]);
}else{
const arrOfData = weatherBitData.body.data.map(data => new Weather(data));
console.log('from cacheWeather');
inMemory[`${req.query.lat} ${req.query.lon}`]= arrOfData;
res.send(arrOfData);
// res.send(data.body);
}
}).catch(console.error);
} catch (error) {
const arrOfData = weather.data.map(data => new Weather(data));
res.send(arrOfData);
}
}
class Weather {
constructor(data) {
this.date = data.valid_date;
this.description = data.weather.description;
}
}
module.exports = weatherHandler;
|
import { defineConfig } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue2'
export default defineConfig(({ command, mode, ssrBuild }) => {
return {
plugins: [
vue()
],
resolve: {
alias: {
'vue': 'vue/dist/vue.esm-bundler.js'
},
// .vue 확장자 생략을 위한 설정
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
publicDir: false,
build: {
type: ['es', 'umd'],
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'VueDatamaps',
fileName: 'vue-datamaps'
},
rollupOptions: {
output: {
exports: 'named'
}
}
}
}
})
|
/*
* @Author: HuYanan
* @Date: 2022-08-11 11:12:08
* @LastEditTime: 2022-08-11 14:10:24
* @LastEditors: HuYanan
* @Description:
* @Version: 0.0.1
* @FilePath: /HynScript/src/String/url.js
* @Contributors: [HuYanan, other]
*/
export function updateParams (url='', updateParams) {
let resUrl = url;
if (url && typeof updateParams === 'object') {
let splitUrls = url.split('?');
let search = splitUrls[1];
let params = {};
if (typeof search !== 'undefined') {
search.split('&').forEach((param) => {
if (!param.split('=')[0]) {
return;
}
params[param.split('=')[0]] = param.split('=')[1];
});
}
Object.keys(updateParams).forEach((key) => {
params[key] = updateParams[key];
})
search = Object.keys(params).reduce((prev, key, index) => {
return prev += `${index!==0?'&':''}${key}=${params[key]}`;
}, '')
resUrl = `${splitUrls[0]}${search?'?':''}${search}`;
}
return resUrl;
}
// test
console.log(updateParams()); |
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
boolean: 'p'
})
var execSync = require('child_process').execSync
console.log(argv)
if (argv.h || argv.help || argv._.length === 0) {
var docs = [
'Usage: generate-static name [html]',
'',
'-p Push the container after it has been made.'
]
console.log(docs.join('\n'))
process.exit(0)
}
var run = function (cmd) {
console.log(cmd)
var result = execSync(cmd)
return result.toString()
}
var imagename = argv._.shift()
var html = argv._.shift() || '<h1>Hello Docker</h1>'
console.log('Image:', imagename)
console.log('HTML:', html)
var id = run('docker run -d nginx:latest').replace('\n', '')
console.log('id', id)
var index = 'echo "' + html + '" > /usr/share/nginx/html/index.html'
var done = run('docker exec ' + id + ' /bin/sh -c "' + index.replace(/"/g, '\\"') + '"')
console.log(done)
var container = run('docker commit ' + id + ' ' + imagename)
console.log(container)
var rm = run('docker rm -f ' + id)
console.log(rm)
console.log('\nDocker image is now generated:')
console.log(imagename)
if(argv.p) {
var push = run('docker push ' + imagename)
console.log(push)
}
|
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Link } from "react-router-dom";
import Button from "@material-ui/core/Button";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import EditIcon from "@material-ui/icons/Edit";
import Typography from "@material-ui/core/Typography";
import PropTypes from "prop-types";
const useStyles = makeStyles({
root: {
border: "2px solid #eee",
margin: "10px 0"
}
});
const ClientOrderList = ({ orders, clientId }) => {
const classes = useStyles();
return (
<>
<h2>Список ремонтов</h2>
{orders.map(order => {
const { brand, model, description, imei, repairStart, _id } = order;
return (
<List key={_id} className={classes.root}>
<ListItem>
<Typography variant="subtitle1" gutterBottom>
Бренд:
</Typography>
<Typography variant="subtitle1" gutterBottom>
{brand}
</Typography>
</ListItem>
<ListItem>
<Typography variant="subtitle1" gutterBottom>
Модель:
</Typography>
<Typography variant="subtitle1" gutterBottom>
{model}
</Typography>
</ListItem>
<ListItem>
<Typography variant="subtitle1" gutterBottom>
imei:
</Typography>
<Typography variant="subtitle1" gutterBottom>
{imei}
</Typography>
</ListItem>
<ListItem>
<Typography variant="subtitle1" gutterBottom>
Дата добавления:
</Typography>
<Typography variant="subtitle1" gutterBottom>
{repairStart.slice(0, 10)}
</Typography>
</ListItem>
<ListItem>
<Typography variant="subtitle1" gutterBottom>
Описание:
</Typography>
<Typography variant="subtitle1" gutterBottom>
{description}
</Typography>
</ListItem>
<ListItem>
<Button
variant="contained"
color="primary"
href="#contained-buttons"
component={Link}
to={`/clients/edit-client-order/${clientId}/${_id}`}
>
<EditIcon />
Изменить прогресс ремонта
</Button>
</ListItem>
</List>
);
})}
</>
);
};
ClientOrderList.propTypes = {
ClientOrderList: PropTypes.array,
clientId: PropTypes.string
};
export default ClientOrderList;
|
(function mobileMenu() {
const promoSection = document.querySelector('.promo');
const menuModal = promoSection.firstElementChild;
const menuList = menuModal.firstElementChild;
const menuItems = menuList.querySelectorAll('.nav__item');
const promoBtn = document.querySelector('.promo__btn');
const menuBtn = document.querySelector('.nav-btn');
menuBtn.addEventListener('click', function () {
menuOpenClose();
});
for( let i = 0; i < menuItems.length; i++ ) {
menuItems[i].addEventListener('click', function () {
menuOpenClose();
});
};
function menuOpenClose() {
if (menuModal.classList.contains('active')) {
menuModal.classList.remove('active');
menuBtn.classList.remove('nav-btn-active');
} else {
menuModal.classList.add('active');
menuBtn.classList.add('nav-btn-active');
}
}
}());
|
import BaseLfo from '../../core/BaseLfo';
const commonDefinitions = {
min: {
type: 'float',
default: -1,
metas: { kind: 'dynamic' },
},
max: {
type: 'float',
default: 1,
metas: { kind: 'dynamic' },
},
width: {
type: 'integer',
default: 300,
metas: { kind: 'dynamic' },
},
height: {
type: 'integer',
default: 150,
metas: { kind: 'dynamic' },
},
container: {
type: 'any',
default: null,
constant: true,
},
canvas: {
type: 'any',
default: null,
constant: true,
},
};
const hasDurationDefinitions = {
duration: {
type: 'float',
min: 0,
max: +Infinity,
default: 1,
metas: { kind: 'dynamic' },
},
referenceTime: {
type: 'float',
default: 0,
constant: true,
},
};
/**
* Base class to extend in order to create graphic sinks.
*
* <span class="warning">_This class should be considered abstract and only
* be used to be extended._</span>
*
* @todo - fix float rounding errors (produce decays in sync draws)
*
* @memberof module:client.sink
*
* @param {Object} options - Override default parameters.
* @param {Number} [options.min=-1] - Minimum value represented in the canvas.
* _dynamic parameter_
* @param {Number} [options.max=1] - Maximum value represented in the canvas.
* _dynamic parameter_
* @param {Number} [options.width=300] - Width of the canvas.
* _dynamic parameter_
* @param {Number} [options.height=150] - Height of the canvas.
* _dynamic parameter_
* @param {Element|CSSSelector} [options.container=null] - Container element
* in which to insert the canvas. _constant parameter_
* @param {Element|CSSSelector} [options.canvas=null] - Canvas element
* in which to draw. _constant parameter_
* @param {Number} [options.duration=1] - Duration (in seconds) represented in
* the canvas. This parameter only exists for operators that display several
* consecutive frames on the canvas. _dynamic parameter_
* @param {Number} [options.referenceTime=null] - Optionnal reference time the
* display should considerer as the origin. Is only usefull when synchronizing
* several display using the `DisplaySync` class. This parameter only exists
* for operators that display several consecutive frames on the canvas.
*/
class BaseDisplay extends BaseLfo {
constructor(defs, options = {}, hasDuration = true) {
let commonDefs;
if (hasDuration)
commonDefs = Object.assign({}, commonDefinitions, hasDurationDefinitions);
else
commonDefs = commonDefinitions
const definitions = Object.assign({}, commonDefs, defs);
super(definitions, options);
if (this.params.get('canvas') === null && this.params.get('container') === null)
throw new Error('Invalid parameter: `canvas` or `container` not defined');
const canvasParam = this.params.get('canvas');
const containerParam = this.params.get('container');
// prepare canvas
if (canvasParam) {
if (typeof canvasParam === 'string')
this.canvas = document.querySelector(canvasParam);
else
this.canvas = canvasParam;
} else if (containerParam) {
let container;
if (typeof containerParam === 'string')
container = document.querySelector(containerParam);
else
container = containerParam;
this.canvas = document.createElement('canvas');
container.appendChild(this.canvas);
}
this.ctx = this.canvas.getContext('2d');
this.cachedCanvas = document.createElement('canvas');
this.cachedCtx = this.cachedCanvas.getContext('2d');
this.hasDuration = hasDuration;
this.previousFrame = null;
this.currentTime = hasDuration ? this.params.get('referenceTime') : null;
/**
* Instance of the `DisplaySync` used to synchronize the different displays
* @private
*/
this.displaySync = false;
this._stack = [];
this._rafId = null;
this.renderStack = this.renderStack.bind(this);
this.shiftError = 0;
// initialize canvas size and y scale transfert function
this._resize();
}
/** @private */
_resize() {
const width = this.params.get('width');
const height = this.params.get('height');
const ctx = this.ctx;
const cachedCtx = this.cachedCtx;
const dPR = window.devicePixelRatio || 1;
const bPR = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
this.pixelRatio = dPR / bPR;
const lastWidth = this.canvasWidth;
const lastHeight = this.canvasHeight;
this.canvasWidth = width * this.pixelRatio;
this.canvasHeight = height * this.pixelRatio;
cachedCtx.canvas.width = this.canvasWidth;
cachedCtx.canvas.height = this.canvasHeight;
// copy current image from ctx (resize)
if (lastWidth && lastHeight) {
cachedCtx.drawImage(ctx.canvas,
0, 0, lastWidth, lastHeight,
0, 0, this.canvasWidth, this.canvasHeight
);
}
ctx.canvas.width = this.canvasWidth;
ctx.canvas.height = this.canvasHeight;
ctx.canvas.style.width = `${width}px`;
ctx.canvas.style.height = `${height}px`;
// update scale
this._setYScale();
}
/**
* Create the transfert function used to map values to pixel in the y axis
* @private
*/
_setYScale() {
const min = this.params.get('min');
const max = this.params.get('max');
const height = this.canvasHeight;
const a = (0 - height) / (max - min);
const b = height - (a * min);
this.getYPosition = (x) => a * x + b;
}
/**
* Returns the width in pixel a `vector` frame needs to be drawn.
* @private
*/
getMinimumFrameWidth() {
return 1; // need one pixel to draw the line
}
/**
* Callback function executed when a parameter is updated.
*
* @param {String} name - Parameter name.
* @param {Mixed} value - Parameter value.
* @param {Object} metas - Metadatas of the parameter.
* @private
*/
onParamUpdate(name, value, metas) {
super.onParamUpdate(name, value, metas);
switch (name) {
case 'min':
case 'max':
// @todo - make sure that min and max are different
this._setYScale();
break;
case 'width':
case 'height':
this._resize();
}
}
/** @private */
propagateStreamParams() {
super.propagateStreamParams();
}
/** @private */
resetStream() {
super.resetStream();
const width = this.canvasWidth;
const height = this.canvasHeight;
this.previousFrame = null;
this.currentTime = this.hasDuration ? this.params.get('referenceTime') : null;
this.ctx.clearRect(0, 0, width, height);
this.cachedCtx.clearRect(0, 0, width, height);
}
/** @private */
finalizeStream(endTime) {
this.currentTime = null;
super.finalizeStream(endTime);
this._rafId = null;
// clear the stack if not empty
if (this._stack.length > 0)
this.renderStack();
}
/**
* Add the current frame to the frames to draw. Should not be overriden.
* @private
*/
processFrame(frame) {
const frameSize = this.streamParams.frameSize;
const copy = new Float32Array(frameSize);
const data = frame.data;
// copy values of the input frame as they might be updated
// in reference before being consumed in the draw function
for (let i = 0; i < frameSize; i++)
copy[i] = data[i];
this._stack.push({
time: frame.time,
data: copy,
metadata: frame.metadata,
});
if (this._rafId === null)
this._rafId = window.requestAnimationFrame(this.renderStack);
}
/**
* Render the accumulated frames. Method called in `requestAnimationFrame`.
* @private
*/
renderStack() {
if (this.params.has('duration')) {
// render all frame since last `renderStack` call
for (let i = 0, l = this._stack.length; i < l; i++)
this.scrollModeDraw(this._stack[i]);
} else {
// only render last received frame if any
if (this._stack.length > 0) {
const frame = this._stack[this._stack.length - 1];
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.processFunction(frame);
}
}
this._stack.length = 0; // reinit stack for next call
this._rafId = null;
}
/**
* Draw data from right to left with scrolling
* @private
* @todo - check possibility of maintaining all values from one place to
* minimize float error tracking.
*/
scrollModeDraw(frame) {
const frameType = this.streamParams.frameType;
const frameRate = this.streamParams.frameRate;
const frameSize = this.streamParams.frameSize;
const sourceSampleRate = this.streamParams.sourceSampleRate;
const canvasDuration = this.params.get('duration');
const ctx = this.ctx;
const canvasWidth = this.canvasWidth;
const canvasHeight = this.canvasHeight;
const previousFrame = this.previousFrame;
// current time at the left of the canvas
const currentTime = (this.currentTime !== null) ? this.currentTime : frame.time;
const frameStartTime = frame.time;
const lastFrameTime = previousFrame ? previousFrame.time : 0;
const lastFrameDuration = this.lastFrameDuration ? this.lastFrameDuration : 0;
let frameDuration;
if (frameType === 'scalar' || frameType === 'vector') {
const pixelDuration = canvasDuration / canvasWidth;
frameDuration = this.getMinimumFrameWidth() * pixelDuration;
} else if (this.streamParams.frameType === 'signal') {
frameDuration = frameSize / sourceSampleRate;
}
const frameEndTime = frameStartTime + frameDuration;
// define if we need to shift the canvas
const shiftTime = frameEndTime - currentTime;
// if the canvas is not synced, should never go to `else`
if (shiftTime > 0) {
// shift the canvas of shiftTime in pixels
const fShift = (shiftTime / canvasDuration) * canvasWidth - this.shiftError;
const iShift = Math.floor(fShift + 0.5);
this.shiftError = fShift - iShift;
const currentTime = frameStartTime + frameDuration;
this.shiftCanvas(iShift, currentTime);
// if siblings, share the information
if (this.displaySync)
this.displaySync.shiftSiblings(iShift, currentTime, this);
}
// width of the frame in pixels
const floatFrameWidth = (frameDuration / canvasDuration) * canvasWidth;
const frameWidth = Math.floor(floatFrameWidth + 0.5);
// define position of the head in the canvas
const canvasStartTime = this.currentTime - canvasDuration;
const startTimeRatio = (frameStartTime - canvasStartTime) / canvasDuration;
const startTimePosition = startTimeRatio * canvasWidth;
// number of pixels since last frame
let pixelsSinceLastFrame = this.lastFrameWidth;
if ((frameType === 'scalar' || frameType === 'vector') && previousFrame) {
const frameInterval = frame.time - previousFrame.time;
pixelsSinceLastFrame = (frameInterval / canvasDuration) * canvasWidth;
}
// draw current frame
ctx.save();
ctx.translate(startTimePosition, 0);
this.processFunction(frame, frameWidth, pixelsSinceLastFrame);
ctx.restore();
// save current canvas state into cached canvas
this.cachedCtx.clearRect(0, 0, canvasWidth, canvasHeight);
this.cachedCtx.drawImage(this.canvas, 0, 0, canvasWidth, canvasHeight);
// update lastFrameDuration, lastFrameWidth
this.lastFrameDuration = frameDuration;
this.lastFrameWidth = frameWidth;
this.previousFrame = frame;
}
/**
* Shift canvas, also called from `DisplaySync`
* @private
*/
shiftCanvas(iShift, time) {
const ctx = this.ctx;
const cache = this.cachedCanvas;
const cachedCtx = this.cachedCtx;
const width = this.canvasWidth;
const height = this.canvasHeight;
const croppedWidth = width - iShift;
this.currentTime = time;
ctx.clearRect(0, 0, width, height);
ctx.drawImage(cache, iShift, 0, croppedWidth, height, 0, 0, croppedWidth, height);
// save current canvas state into cached canvas
cachedCtx.clearRect(0, 0, width, height);
cachedCtx.drawImage(this.canvas, 0, 0, width, height);
}
// @todo - Fix trigger mode
// allow to witch easily between the 2 modes
// setTrigger(bool) {
// this.params.trigger = bool;
// // clear canvas and cache
// this.ctx.clearRect(0, 0, this.params.width, this.params.height);
// this.cachedCtx.clearRect(0, 0, this.params.width, this.params.height);
// // reset _currentXPosition
// this._currentXPosition = 0;
// this.lastShiftError = 0;
// }
// /**
// * Alternative drawing mode.
// * Draw from left to right, go back to left when > width
// */
// triggerModeDraw(time, frame) {
// const width = this.params.width;
// const height = this.params.height;
// const duration = this.params.duration;
// const ctx = this.ctx;
// const dt = time - this.previousTime;
// const fShift = (dt / duration) * width - this.lastShiftError; // px
// const iShift = Math.round(fShift);
// this.lastShiftError = iShift - fShift;
// this.currentXPosition += iShift;
// // draw the right part
// ctx.save();
// ctx.translate(this.currentXPosition, 0);
// ctx.clearRect(-iShift, 0, iShift, height);
// this.drawCurve(frame, iShift);
// ctx.restore();
// // go back to the left of the canvas and redraw the same thing
// if (this.currentXPosition > width) {
// // go back to start
// this.currentXPosition -= width;
// ctx.save();
// ctx.translate(this.currentXPosition, 0);
// ctx.clearRect(-iShift, 0, iShift, height);
// this.drawCurve(frame, this.previousFrame, iShift);
// ctx.restore();
// }
// }
}
export default BaseDisplay;
|
import React from 'react';
import { ProjectsWrapper } from './styles'
import { Card } from '../'
import Bounce from 'react-reveal/Bounce';
import Fade from 'react-reveal/Fade';
const cards = [
{
title: "Spectrum",
copy: "Restructured an Angular application with over 30 million users from a large monorepo to a number of micro frontends.",
button: "Go to site",
image: "https://cdn.lfomedia.com/layout_assets/charter/assets/8n_redesign/images/4fa7b97a93a7090550157b8a8ed4da60.devices.png",
link: "https://www.spectrum.net/"
},
{
title: "Charlotte",
copy: "Built features for Charlotte's online destination to discover all that's happening in the QC.",
button: "Go to site",
image: "https://d2j8c2rj2f9b78.cloudfront.net/uploads/banner-images/Romare-Skyline-2200x1500.jpg",
link: "https://www.charlottesgotalot.com/"
},
{
title: "NASCAR",
copy: "Designed and developed animations to bring Nascar Hall of Fame's website to life.",
button: "Go to site",
image: "https://s3.us-east-1.amazonaws.com/nascarhall.com/uploads/images/CRVA-1410-day_2-nascar_museum-0036.jpg?mtime=20200130120535",
link: "https://www.nascarhall.com/"
},
{
title: "Chevrolet",
copy: "Led the development of this microsite for #88 Alex Bowman and Chevy with a two week deadline.",
button: "Go to site",
image: "https://www.motortrend.com/uploads/sites/5/2019/05/2020-Chevrolet-Camaro-LT1-e1557351884715.jpg?fit=around%7C875:492",
link: "https://www.chevygoods.com",
},
{
title: "Discovery Place",
copy: "Refreshed their homepage and built new features for group of muesums that explors the wonders of science, technology and nature.",
button: "Go to site",
image: "https://unionco.imgix.net/uploads/images/dp_slantyscreens3.png?w=1800&fm=jpg&lossless=1",
link: "https://www.discoveryplace.org/",
},
{
title: "Pepsi",
copy: "Working with their initiative Pepsi Cares, developed components for this award winning site.",
button: "Go to site",
image: "https://revenuesandprofits.com/wp-content/uploads/2019/10/pepsi-681x379.jpg",
link: "https://www.pepsicares.com"
}
]
const Projects = () => {
return (
<ProjectsWrapper>
<Fade duration={1000} bottom cascade>
<div className="header">Selected Works</div>
</Fade>
<Bounce duration={1500} bottom cascade>
<div className="Card-container">
{cards.map((card, i) => {
return (
<div key={i}>
<Card
title={card.title}
copy={card.copy}
image={card.image}
link={card.link}
/>
</div>
)
})}
</div>
</Bounce>
</ProjectsWrapper>
)
}
export default Projects;
|
const express = require('express');
const fs = require('fs');
const path = require('path');
const morgan = require('morgan');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const { appConfig } = require('./setup')();
const apiRouter = require('../routes/api');
// Mongoose setup and config.
mongoose.set('useNewUrlParser', true);
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useUnifiedTopology', true);
mongoose.Promise = global.Promise;
// Mongoose connection.
mongoose
.connect(appConfig.dbPath, {})
.then(() => {
console.log(`connected to mongo ${appConfig.dbPath}`);
})
.catch((error) => {
console.error('Error connecting to database', error); //TODO: Use logger
});
// Express app setup and configuration
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
// Setup origin access rules
app.use(function (req, res, next) {
req.accepts('*/*');
req.acceptsEncodings(['gzip', 'deflate', 'sdch', 'br']);
next();
});
// To allow cross origin access.
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
app.use(apiRouter);
// Setup logging
app.use(
morgan('dev', {
skip: (req, res) => res.statusCode < 400,
}),
);
app.use(
morgan('common', {
stream: fs.createWriteStream(path.join(__dirname, 'rest_api.log'), {
flags: 'a',
}),
}),
);
const PORT = process.env.PORT || 5000;
console.log('Environment: ', app.get('env'), '\nPort:', PORT);
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
|
import React from 'react';
import { Container, Column, Row } from './AnimatedTable';
const Xing = (
<a
className="SchedulePage-link"
href="https://www.xing.com/en"
target="_blank"
rel="noopener noreferrer"
>
sponsored by Xing
</a>
);
const Ginetta = (
<a
target="_blank"
rel="noopener noreferrer"
className="SchedulePage-link"
href="https://ginetta.net/"
>
hosted by Ginetta
</a>
);
export default (
<div title="18 & 19 October">
<Container className="SchedulePage-columns">
<Column className="SchedulePage-column">
<Row className="SchedulePage-row">
<h2 className="SchedulePage-title no-topMargin">18</h2>
</Row>
<Row className="SchedulePage-row">
<a
href="https://www.google.pt/maps/place/Altice+Forum+Braga/@41.5414507,-8.4246834,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fc6519e03b3d:0xb47f5e1a7515bd95!8m2!3d41.5414467!4d-8.4224894"
className="SchedulePage-room"
>
Altice Forum Braga <br /> Main Room
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">09:00</p>
<p className="SchedulePage-entryTitle">Check in</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">09:50</p>
<p className="SchedulePage-entryTitle">Opening</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">10:00</p>
<a href="/speakers#jared-spool" className="SchedulePage-entryTitle">
Design is a team sport{' '}
<span className="SchedulePage-entrySpeaker">by Jared Spool</span>
</a>
</Row>
<Row className="SchedulePage-entry xl">
<p className="SchedulePage-entryTime">10:45</p>
<a
href="/speakers#stephanie-troeth"
className="SchedulePage-entryTitle"
>
Behind the Story{' '}
<span className="SchedulePage-entrySpeaker">Stephanie Troeth</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">11:30</p>
<p className="SchedulePage-entryTitle">Coffe Break {Xing}</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">12:15</p>
<a href="/speakers#rails-girls" className="SchedulePage-entryTitle">
Hurdles of Junior Developers and How To Overcome Them{' '}
<span className="SchedulePage-entrySpeaker">
by Sabine van der Eijk & Alina Leuca
</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">13:00</p>
<p className="SchedulePage-entryTitle">Lunch</p>
</Row>
<Row className="SchedulePage-entry l">
<p className="SchedulePage-entryTime">15:00</p>
<a href="/speakers#arne-kittler" className="SchedulePage-entryTitle">
Clarity in Collaboration{' '}
<span className="SchedulePage-entrySpeaker">by Arne Kittler</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">15:30</p>
<p className="SchedulePage-entryTitle">
Talk Shop{' '}
<span className="SchedulePage-entrySpeaker">
with Sabine van der Eijk, Alina Leuca and Arne Kittler
</span>
</p>
</Row>
<Row className="SchedulePage-entry xl">
<p className="SchedulePage-entryTime">15:45</p>
<a
href="/speakers#vivianne-castillo"
className="SchedulePage-entryTitle"
>
Ethics & Power: Understanding the Role of Shame in UX Research{' '}
<span className="SchedulePage-entrySpeaker">Vivianne Castillo</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">16:15</p>
<p className="SchedulePage-entryTitle">Coffe Break {Xing}</p>
</Row>
<Row className="SchedulePage-entry xl">
<p className="SchedulePage-entryTime">18:00</p>
<p className="SchedulePage-entryTitle">
Talk Shop{' '}
<span className="SchedulePage-entrySpeaker">
with Vivianne Castillo, Jared Spool, and Stephanie Troeth
</span>
</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">19:00</p>
<p className="SchedulePage-entryTitle">Closing</p>
</Row>
<Row className="SchedulePage-row">
<a
href="https://www.google.pt/maps/place/Casa+Velha+artbar/@41.5471178,-8.4182091,15.36z/data=!4m8!1m2!2m1!1scasa+velha+near+Parque+Da+Ponte,+N101,+Braga!3m4!1s0x0:0x4d913deb9f7f684f!8m2!3d41.5422586!4d-8.4194005"
className="SchedulePage-room"
>
Casa Velha, Parque da Ponte
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">21:00</p>
<p className="SchedulePage-entryTitle">MirrorConf Party {Ginetta}</p>
</Row>
</Column>
<Column className="SchedulePage-column">
<Row className="SchedulePage-row">
<h2 className="SchedulePage-title">19</h2>
</Row>
<Row className="SchedulePage-row">
<a
href="https://www.google.pt/maps/place/Altice+Forum+Braga/@41.5414507,-8.4246834,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fc6519e03b3d:0xb47f5e1a7515bd95!8m2!3d41.5414467!4d-8.4224894"
className="SchedulePage-room"
>
Altice Forum Braga <br /> Main Room
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">09:00</p>
<p className="SchedulePage-entryTitle">Check in</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">09:50</p>
<p className="SchedulePage-entryTitle">Opening</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">10:00</p>
<a
href="/speakers#vitaly-friedman"
className="SchedulePage-entryTitle"
>
TBA{' '}
<span className="SchedulePage-entrySpeaker">
by Vitaly Friedman
</span>
</a>
</Row>
<Row className="SchedulePage-entry xl">
<p className="SchedulePage-entryTime">10:45</p>
<a href="/speakers#jackie-balzer" className="SchedulePage-entryTitle">
Preprocessors, Components, and CSS in JS or: How I Learned to Stop
Worrying and Love the Website{' '}
<span className="SchedulePage-entrySpeaker">by Jackie Balzer</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">11:30</p>
<p className="SchedulePage-entryTitle">Coffe Break {Xing}</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">12:00</p>
<a href="/speakers#lea-verou" className="SchedulePage-entryTitle">
Even More CSS Secrets{' '}
<span className="SchedulePage-entrySpeaker">by Lea Verou</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">13:00</p>
<p className="SchedulePage-entryTitle">Lunch</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">15:00</p>
<a href="/speakers#amber-case" className="SchedulePage-entryTitle">
Designing Calm Technology{' '}
<span className="SchedulePage-entrySpeaker">by Amber Case</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">15:45</p>
<a href="/speakers#aras-bilgen" className="SchedulePage-entryTitle">
Avoiding Arctic Expeditions: Ways to do research together{' '}
<span className="SchedulePage-entrySpeaker">by Aras Bilgen</span>
</a>
</Row>
<Row className="SchedulePage-entry xl">
<p className="SchedulePage-entryTime">16:30</p>
<a
href="/speakers#jessica-jordan"
className="SchedulePage-entryTitle"
>
Crafting Web Comics with Ember{' '}
<span className="SchedulePage-entrySpeaker">by Jessica Jordan</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">17:00</p>
<p className="SchedulePage-entryTitle">Coffe Break {Xing}</p>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">17:30</p>
<a href="/speakers#mike-monteiro" className="SchedulePage-entryTitle">
How To Build an Atomic Bomb{' '}
<span className="SchedulePage-entrySpeaker">by Mike Monteiro</span>
</a>
</Row>
<Row className="SchedulePage-entry">
<p className="SchedulePage-entryTime">18:30</p>
<p className="SchedulePage-entryTitle">Closing</p>
</Row>
<div className="SchedulePage-fillers" style={{ height: '70px' }} />
<div className="SchedulePage-fillers" style={{ height: '76px' }} />
</Column>
</Container>
</div>
);
|
'use strict'
const sdk = require('../../src/sdk.js')
const mockApi = require('../mock/api.js')
require('should')
describe('Zabo SDK Blockchains Resource', () => {
let blockchains
it('should be instantiated during zabo.init()', async function () {
await sdk.init({
apiKey: 'some-api-key',
secretKey: 'some-secret-key',
env: 'sandbox',
autoConnect: false
}).catch(err => err).should.be.ok()
sdk.api.should.be.ok()
sdk.api.connect.should.be.a.Function()
sdk.api.resources.should.have.property('blockchains')
blockchains = await require('../../src/resources/blockchains')(mockApi)
blockchains.should.have.property('getBlock')
blockchains.should.have.property('getContract')
blockchains.should.have.property('getTokens')
blockchains.should.have.property('getBalances')
blockchains.should.have.property('getTransactions')
blockchains.should.have.property('getTransaction')
blockchains.should.have.property('getTokenTransfers')
blockchains.should.have.property('getTokenTransfer')
})
// blockchains.getBlock()
it('blockchains.getBlock() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getBlock()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getBlock() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getBlock('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getBlock() should return one block', async function () {
const response = await blockchains.getBlock('ethereum', 0)
response.should.be.ok()
response.should.have.properties(['number', 'hash', 'size', 'gas_limit', 'gas_used', 'transaction_count', 'timestamp'])
})
it('blockchains.getBlock() should return latest block if `blockNumber` is missing', async function () {
const response = await blockchains.getBlock('ethereum')
response.should.be.ok()
response.should.have.properties(['number', 'hash', 'size', 'gas_limit', 'gas_used', 'transaction_count', 'timestamp'])
})
// blockchains.getContract()
it('blockchains.getContract() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getContract()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getContract() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getContract('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getContract() should fail if `blockchain` is not supported', async function () {
const response = await blockchains.getContract('bitcoin')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getContract() should fail if `address` is not provided', async function () {
const response = await blockchains.getContract('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('address')
})
it('blockchains.getContract() should return one contract', async function () {
const response = await blockchains.getContract('ethereum', '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f')
response.should.be.ok()
response.should.have.properties(['address', 'bytecode'])
})
// blockchains.getTokens()
it('blockchains.getTokens() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getTokens()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokens() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getTokens('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokens() should fail if `blockchain` is not supported', async function () {
const response = await blockchains.getTokens('bitcoin')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokens() should return the list of tokens', async function () {
const response = await blockchains.getTokens('ethereum')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['contract', 'ticker', 'name', 'decimals', 'total_supply', 'is_erc20'])
})
it('blockchains.getTokens() should return the list of tokens by name', async function () {
const response = await blockchains.getTokens('ethereum', 'Wrapped Ether')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['contract', 'ticker', 'name', 'decimals', 'total_supply', 'is_erc20'])
})
// blockchains.getBalances()
it('blockchains.getBalances() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getBalances()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getBalances() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getBalances('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getBalances() should fail if `address` is not provided', async function () {
const response = await blockchains.getBalances('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('address')
})
it('blockchains.getBalances() should return balances for the given address', async function () {
const response = await blockchains.getBalances('ethereum', '0x62a6ebC0ac598819CCad368788F6d2357FaE0d9e')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['token', 'address', 'balance'])
})
// blockchains.getTransactions()
it('blockchains.getTransactions() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getTransactions()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTransactions() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getTransactions('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTransactions() should fail if `address` is not provided', async function () {
const response = await blockchains.getTransactions('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('address')
})
it('blockchains.getTransactions() should return transactions for the given address', async function () {
const response = await blockchains.getTransactions('ethereum', '0x4ae694344e7e4e5820c62aa9816b7aa61210eaba')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['hash', 'to_address', 'value', 'gas', 'gas_price', 'gas_used', 'input', 'status'])
})
// blockchains.getTransaction()
it('blockchains.getTransaction() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getTransaction()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTransaction() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getTransaction('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTransaction() should fail if `transactionHash` is not provided', async function () {
const response = await blockchains.getTransaction('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('transactionHash')
})
it('blockchains.getTransaction() should return one transaction', async function () {
const response = await blockchains.getTransaction('ethereum', '0x23170b29a16c3ed89a2d7514c2d6d0796e39a29184c52a0bb5aed6b404b78a83')
response.should.be.ok()
response.should.have.properties(['hash', 'block_number', 'from_address', 'to_address', 'value', 'gas', 'gas_price', 'gas_used', 'input', 'status'])
})
// blockchains.getTokenTransfers()
it('blockchains.getTokenTransfers() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getTokenTransfers()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfers() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getTokenTransfers('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfers() should fail if `blockchain` is not supported', async function () {
const response = await blockchains.getTokenTransfers('bitcoin')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfers() should fail if `address` is not provided', async function () {
const response = await blockchains.getTokenTransfers('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('address')
})
it('blockchains.getTokenTransfers() should return token transfers for the given address', async function () {
const response = await blockchains.getTokenTransfers('ethereum', '0x4ae694344e7e4e5820c62aa9816b7aa61210eaba')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['transaction', 'token', 'from_address', 'to_address', 'value'])
})
// blockchains.getTokenTransfer()
it('blockchains.getTokenTransfer() should fail if `blockchain` is not provided', async function () {
const response = await blockchains.getTokenTransfer()
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfer() should fail if `blockchain` is invalid', async function () {
const response = await blockchains.getTokenTransfer('invalidBlockchain')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfer() should fail if `blockchain` is not supported', async function () {
const response = await blockchains.getTokenTransfer('bitcoin')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('blockchain')
})
it('blockchains.getTokenTransfer() should fail if `transactionHash` is not provided', async function () {
const response = await blockchains.getTokenTransfer('ethereum')
.should.be.rejected()
response.should.be.an.Error()
response.error_type.should.be.equal(400)
response.message.should.containEql('transactionHash')
})
it('blockchains.getTokenTransfer() should return the token transfers for the given transaction hash', async function () {
const response = await blockchains.getTokenTransfer('ethereum', '0x23170b29a16c3ed89a2d7514c2d6d0796e39a29184c52a0bb5aed6b404b78a83')
response.should.be.ok()
response.data.should.be.an.Array()
response.data[0].should.have.properties(['transaction', 'token', 'from_address', 'to_address', 'value'])
})
})
|
const MOCK_SERVER = require('../mocks/mock_server');
let mud;
describe('Testing Feature: Hunger and Thirst', () => {
let mockPlayer;
let mockPlayerRoom;
let server;
beforeEach((done) => {
mud = new MOCK_SERVER(() => {
server = mud.server;
mud.createNewEntity((playerModel) => {
mockPlayer = playerModel;
mockPlayer.refId = 'unit-test-player'
mockPlayer.area = 'midgaard';
mockPlayer.originatingArea = mockPlayer.area;
mockPlayer.roomid = '1';
mockPlayer.isPlayer = true;
mockPlayer.level = 1;
mockPlayer.name = 'Bilbo';
mockPlayer.displayName = 'Bilbo';
mockPlayer.combatName = 'Bilbo';
mockPlayer.hp = 100;
mockPlayer.chp = 100;
mockPlayer.hunger = 9;
mockPlayer.thirst = 9;
mockPlayerRoom = server.world.getRoomObject(mockPlayer.area, mockPlayer.roomid);
mockPlayerRoom.playersInRoom.push(mockPlayer);
server.world.players.push(mockPlayer);
done();
});
}, false, false);
});
// hunger ticks upward to an entities maxHunger and then deals damage
// every check afterward
it('should simulate player reaching their max hunger and taking damage', () => {
const charHungerSpy = spyOn(server.world.character, 'hunger').and.callThrough();
const charThirstSpy = spyOn(server.world.character, 'thirst').and.callThrough();
server.world.ticks.hungerThirstLoop(server.world);
expect(charHungerSpy).toHaveBeenCalledTimes(1);
expect(charThirstSpy).toHaveBeenCalledTimes(1);
expect(mockPlayer.hunger).toBe(10);
expect(mockPlayer.thirst).toBe(10);
expect(mockPlayer.chp).toBe(100);
server.world.ticks.hungerThirstLoop(server.world);
expect(charHungerSpy).toHaveBeenCalledTimes(2);
expect(charThirstSpy).toHaveBeenCalledTimes(2);
expect(mockPlayer.hunger).toBe(10);
expect(mockPlayer.thirst).toBe(10);
expect(mockPlayer.chp).toBeLessThan(100);
});
});
|
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const movieSchema = Schema({
name: { type: String, required: true},
rating: { type: Number, required: true},
timestamp: { type: Date, required: true},
directorID: { type: Schema.Types.ObjectId}
});
module.exports = mongoose.model('movie', movieSchema);
|
import React from "react";
function Welcome(props) {
return (
<section className="welcome">
<div className="welcome__inner ds-primary">
<div className="welcome__inner__text">
<div className="text__title">
<span className="icon-note"></span>
<span className="icon-note-double"></span>{" "}
<h2 className="h2 margin-b">
Amazing <span className="primary">Teachers</span>
</h2>
</div>
<p className="text--xxlarge">
You can now learn how to play your favorite instrument!
Enjoy your weekly music lesson in the comfort of your home with an
upbeat, positive and encouraging teacher of your choice. Choose from
dozens of certified music instructors with experience, passion and
outstanding qualifications. Music classes are offered to students of
all ages and all levels in your home and online.
</p>
</div>
<div className="welcome__inner__video">
<iframe
className="radius-l"
width="540"
height="330"
src="https://www.youtube.com/embed/cbFX6TGHtGA?rel=0"
frameBorder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
title="music"
></iframe>
</div>
</div>
</section>
);
}
export default Welcome;
|
class OnsetDetector {
constructor () {
this.prev = 0
this.threeshold = 32
}
detect (arr) {
const old = this.prev
const nrj = this.signalEnergy(arr)
this.prev = nrj
if (nrj >= 2 * old && nrj > 5) {
return true
}
return false
}
signalEnergy (arr) {
let s = 0
for (let i = 0; i < arr.length; ++i) {
s += (arr[i] / 128.0 - 1) ** 2
}
return s
}
}
export default OnsetDetector
|
import React from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { FETCH_POPULAR_ARTICLES } from "../actions";
import { ArticleRowCard, Loader } from "../components";
import { Button } from "antd";
import { Helmet } from "react-helmet";
export class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
displayArticlesCount: 5
};
}
componentDidMount() {
this.props.fetchPopularArticles();
}
loadMoreArticles = () => {
this.setState(prevState => {
return { displayArticlesCount: prevState.displayArticlesCount + 5 };
});
};
openArticle = id => {
this.props.history.push(`/article/${id}`);
};
render() {
const { displayArticlesCount } = this.state;
const { allArticles } = this.props;
if (allArticles.length === 0) {
return <Loader />;
}
return (
<div>
<Helmet>
<title>New York Times Sample Application</title>
</Helmet>
<div className="ArticleList">
{allArticles.slice(0, displayArticlesCount).map(article => (
<ArticleRowCard
key={article.views}
article={article}
openArticle={this.openArticle}
/>
))}
</div>
<div className="LoadMore">
<Button
onClick={() => this.loadMoreArticles()}
disabled={allArticles.length === displayArticlesCount}
size="large"
type="primary"
icon="plus-circle"
>
Load more
</Button>
</div>
</div>
);
}
}
HomePage.defaultProps = {
allArticles: []
};
HomePage.propTypes = {
allArticles: PropTypes.array.isRequired
};
const mapDispatchToProps = dispatch => {
return {
fetchPopularArticles: () => dispatch({ type: FETCH_POPULAR_ARTICLES })
};
};
const mapStateToProps = state => ({
allArticles: state.allArticles
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);
|
import React, { Component } from 'react'
import { Text, View, StyleSheet, Image, Dimensions } from 'react-native'
import Carousel, { Pagination } from 'react-native-snap-carousel';
const { width,height } = Dimensions.get("screen")
import AuthBtn from './AuthBtn';
export default class Corousel extends Component {
constructor(props) {
super(props);
this.state = {
entries: [{ id: '1', description: 'Explore the largest collection of trail maps anywhere curated by millions of outdoor enthusiasts like you', title: 'Discover 100,000+ trails around the world', image: 'https://webneel.com/wallpaper/sites/default/files/images/08-2018/3-nature-wallpaper-mountain.jpg' },
{ id: '12', description: 'Find your perfect hike,bike,ride, or run.Filter by length, rating, and difficulty.Easily find dog and kid-friendly trails', title: "Find a trail that's perfect for you", image: "https://images.pexels.com/photos/2486168/pexels-photo-2486168.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" },
{ id: '3', description: "Browse hand-curated trail maps plus reviews,photos and activities from the AllTrails community", title: 'Hit the trail with confidence', image: 'https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' }],
activeSlide: 0
}
}
_renderItem = ({ item, index }) => {
return (
<View style={styles.snapContainer}>
<Image style={styles.snapImage} source={{ uri: item.image }} />
<Text style={styles.snapTitle}>{item.title}</Text>
<Text style={styles.snapDescription}>{item.description}</Text>
</View>
);
}
get pagination() {
// const { entries, activeSlide } = this.state;
return (
<Pagination
dotsLength={3}
activeDotIndex={this.state.activeSlide}
containerStyle={{ position: "absolute", bottom: 0, margin: 175 }}
dotStyle={{
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: 'green',
// marginHorizontal: 8,
}}
inactiveDotStyle={{
// Define styles for inactive dots here
// backgroundColor: 'rgba(255, 255, 255, 0.92)'
backgroundColor: "grey"
}}
inactiveDotOpacity={0.4}
inactiveDotScale={0.6}
/>
)
}
render() {
return (
<View>
<Text style={[styles.skip,{alignItems:"center"}]}>Skip</Text>
<View style={{ alignSelf: "center", position: "absolute", marginTop: -6,right:175 }}>
<Image style={styles.logo} source={require('../assets/images/adventure.jpg')} />
</View>
<Carousel
layout={'default'}
// pagingEnabled
ref={(c) => { this._carousel = c; }}
data={this.state.entries}
renderItem={this._renderItem}
sliderWidth={width}
itemWidth={415}
onSnapToItem={(index) => this.setState({ activeSlide: index })}
/>
{this.pagination}
<View style={styles.btnStyle}>
<AuthBtn style={styles.login} laebelStyle={{ color: "green" }} mode="outlined" >Log in</AuthBtn>
<AuthBtn style={styles.singup} mode="contained">Sign up</AuthBtn>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
snapImage: {
height: height/1.8,
width: 600
},
snapTitle: {
fontFamily: 'RobotoCondensed-BoldItalic',
fontSize: 26,
marginTop: 20
},
snapContainer: {
padding: 20,
alignItems: "center",
width: width
},
snapDescription: {
marginTop: 5,
fontSize: 16,
color: '#888',
justifyContent:"flex-start",
textAlign:"center"
},
btnStyle: {
flexDirection: 'row',
justifyContent: "space-around",
alignItems: "center"
},
login: {
width: "45%",
color: "green",
borderColor: "green",
borderWidth: 2,
paddingVertical: 6
// elevation:0.3
},
singup: {
width: '45%',
color: "white",
backgroundColor: "green",
paddingVertical: 7
},
logo: {
height: 50,
width: 50
},
skip: {
fontWeight: 'bold',
color: "green",
marginTop: 6,
marginLeft: 5,
paddingHorizontal: 4,
fontSize: 16
}
})
|
/**
* @author YASIN
* @version [React-Native Pactera V01, 2017/9/7]
* @date 17/2/23
* @description ScrollableTabBar
*/
import React, {
Component
} from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
TouchableOpacity,
ScrollView,
Animated,
} from 'react-native';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
export default class ScrollableTabBar extends Component {
// 构造
constructor(props) {
super(props);
this._tabsMeasurements = []
this._containerMeasure = {
width: screenW
}
this._tabContainerMeasure = {
width: 0
}
// 初始状态
this.state = {
_leftTabUnderline: new Animated.Value(0),
_widthTabUnderline: new Animated.Value(0),
};
}
render() {
let { containerWidth, tabs, scrollValue } = this.props;
//给传过来的动画一个插值器
let tabStyle = {
width: this.state._widthTabUnderline,
position: 'absolute',
bottom: 0,
left: this.state._leftTabUnderline
};
return (
<View
style={[styles.container, this.props.style]}
//获取tabbarview的宽度
onLayout={(e) => this._measureContainer(e)}
>
<ScrollView
automaticallyAdjustContentInsets={false}
ref={(scrollView) => {
this._scrollView = scrollView;
}}
horizontal={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
directionalLockEnabled={true}
bounces={false}
scrollsToTop={false}
pagingEnabled={true}
snapToInterval={screenW}
>
<View
style={styles.tabContainer}
//获取tab到底有多宽
onLayout={(e) => this._measureTabContainer(e)}
>
{tabs.map((tab, index) => {
return this._renderTab(tab, index, index === this.props.activeTab);
})}
<Animated.View
style={[styles.tabLineStyle, this.props.tabLineStyle, tabStyle]}
/>
</View>
</ScrollView>
</View>
);
}
/**
* 测量内容view
* @param event
* @private
*/
_measureContainer(event) {
this._containerMeasure = event.nativeEvent.layout;
this._updateView({ value: this.props.scrollValue._value });
}
/**
* 测量tab内容view
* @param event
* @private
*/
_measureTabContainer(event) {
this._tabContainerMeasure = event.nativeEvent.layout;
if (this.state._tabContainerWidth !== this._tabContainerMeasure.width) {
this.setState({
_tabContainerWidth: this._tabContainerMeasure.width,
}, () => {
this._updateView({ value: this.props.scrollValue._value });
});
}
}
componentDidMount() {
this.props.scrollValue.addListener(this._updateView);
}
/**
* 根据scrollview的滑动改变底部线条的宽度跟left
* @param value
* @private
*/
_updateView = ({ value = 0 }) => {
//因为value 的值是[0-1-2-3-4]变换
const position = Math.floor(value);
//取小数部分
const offset = value % 1;
const tabCount = this.props.tabs.length;
const lastTabPosition = tabCount - 1;
//如果没有tab||(有bounce效果)直接return
if (tabCount === 0 || value < 0 || value > lastTabPosition) {
return;
}
if (this._necessarilyMeasurementsCompleted(position, position === tabCount - 1)) {
this._updateTabLine(position, offset);
//控制pannel的移动(也就是tab外部的scrollview的滚动)
this._updateTabPanel(position, offset);
}
}
/**
* 修改tab内容view的scroll在y轴的偏移量
* @private
*/
_updateTabPanel(position, pageOffset) {
//父控件的宽度
const containerWidth = this._containerMeasure.width;// width
//获取当前选中tab的宽度
const tabWidth = this._tabsMeasurements[position].width;
//获取选中tab的下一个tab的测量值
const nextTabMeasurements = this._tabsMeasurements[position + 1];
//获取选中tab的下一个tab的宽度
const nextTabWidth = nextTabMeasurements && nextTabMeasurements.width || 0;
//当前选中tab的x坐标
const tabOffset = this._tabsMeasurements[position].left;
//当前选中tab距离下一个tab的偏移量(也就是底部线条还停留在当前tab的宽度)
const absolutePageOffset = pageOffset * tabWidth;
//所以当前tab实际偏移量=(当前tab的x轴坐标+当前tab的底部线条偏移量)
let newScrollX = tabOffset + absolutePageOffset;
//计算当前tab显示在控件中央位置需要在(当前scrollview偏移量的基础上再偏移多少)
newScrollX -= (containerWidth - (1 - pageOffset) * tabWidth - pageOffset * nextTabWidth) / 2;
//因为tabcontainer里面内容最大宽度=(最大scrollx+控件自身的宽度),
//所以最大scrollx=tabcontainer里面内容最大宽度-控件自身的宽度
const rightBoundScroll = this._tabContainerMeasure.width - (this._containerMeasure.width);
//求出scrollview x轴偏移临界值【0,rightBoundScroll】
newScrollX = newScrollX >= 0 ? (newScrollX > rightBoundScroll ? rightBoundScroll : newScrollX) : 0;
// ios数量小于3个,点击最后一个bug
if (this.props.tabs.length < 4) {
return
}
this._scrollView.scrollTo({ x: newScrollX, y: 0, animated: false, });
}
/**
* 更新底部线view的left跟width
* @param position
* @param offset
* @private
*/
_updateTabLine(position, offset) {
//当前tab的测量值
const currMeasure = this._tabsMeasurements[position];
//position+1的tab的测量值
const nextMeasure = this._tabsMeasurements[position + 1];
let width = currMeasure.width * (1 - offset);
let left = currMeasure.left;
if (nextMeasure) {
width += nextMeasure.width * offset;
left += nextMeasure.width * offset;
}
this.state._leftTabUnderline.setValue(left);
this.state._widthTabUnderline.setValue(width);
}
/**
* 判断是否需要跟新的条件是否初始化
* @param position
* @param isLast 是否是最后一个
* @private
*/
_necessarilyMeasurementsCompleted(position, isLast) {
return (
this._tabsMeasurements[position] &&
(isLast || this._tabsMeasurements[position + 1])
);
}
/**
* 渲染tab
* @param name 名字
* @param page 下标
* @param isTabActive 是否是选中的tab
* @private
*/
_renderTab(name, page, isTabActive) {
let tabTextStyle = null;
//如果被选中的style
if (isTabActive) {
tabTextStyle = this.props.selectedTextStyle;
} else {
tabTextStyle = this.props.unSelectedTextStyle;
}
let self = this;
return (
<TouchableOpacity
key={name + page}
style={[styles.tabStyle]}
onPress={() => this.props.onTabClick(page)}
onLayout={(event) => this._onMeasureTab(page, event)}
>
<Text style={[tabTextStyle, { lineHeight: 20 }]}>{name}</Text>
</TouchableOpacity>
);
}
/**
* 测量tabview
* @param page 页面下标
* @param event 事件
* @private
*/
_onMeasureTab(page, event) {
let { nativeEvent: { layout: { x, width } } } = event;
this._tabsMeasurements[page] = { left: x, right: width + x, width: width };
this._updateView({ value: this.props.scrollValue._value })
}
}
const styles = StyleSheet.create({
container: {
width: screenW,
// height: 41,
// paddingBottom:12
},
tabContainer: {
flexDirection: 'row',
alignItems: 'center',
},
tabLineStyle: {
height: 1,
backgroundColor: 'navy',
},
tabStyle: {
// height: 41,
paddingBottom: 12,
paddingTop: 6,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 20,
},
});
|
for (let i = 0; i < 10; i++) {
console.log(i);
}
console.log('i = ', i); // Apresente erro por i esta em contesto de bloco e não global
|
// pages/advertise/advertise.js
Page({
/**
* 页面的初始数据
*/
data: {
id:null,
imagefile:null,
// advertiseid:0,
// userInfo:"",
// title:"广告",
// time:"2018-10-27 15:18",
// content:"广告,顾名思义,就是广而告之,即向社会广大公众告知某件事物。广告就其含义来说,有广义和狭义之分。广义广告是指不以营利为目的的广告,如政府公告,政党、宗教、教育、文化、市政、社会团体等方面的启事、声明等。狭义广告是指以营利为目的的广告,通常指的是商业广告,或称经济广告,它是工商企业为推销商品或提供服务,以付费方式,通过广告媒体向消费者或用户传播商品或服务信息的手段。商品广告就是这样的经济广告。"
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.getStorage({
key: 'openid',
fail: ()=>{wx.redirectTo({url: '../index/index',})},
})
var that=this
that.setData({
id:options.id
})
console.log("id=="+that.data.id)
wx.showToast({
title: '加载中.....',
icon: 'loading',
duration: 2000
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that=this
that.setData({
imagefile: "https://qczby.oss-cn-shenzhen.aliyuncs.com/forintro/adver" + that.data.id + ".png"
})
console.log(that.data.imagefile)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
import React from 'react';
import {ListGroupItem, ListGroup, Col} from 'react-bootstrap';
import DegreeAreas from './DegreeAreas';
const Courses = (props) => {
return (
<div>
<div class="panel panel-default">
<div class="panel-heading">
<Col md={7}>
<h4 className="centeredText bold">Search for Classes</h4>
</Col>
<Col md={5}>
<DegreeAreas
degreeAreas={props.degreeAreas}
changeDegreeArea={props.changeDegreeArea}
activeDegreeArea={props.activeDegreeArea}
/>
</Col>
</div>
<table class="table table-fixed">
<tbody style={{height:415}}>
{props.currentCourses.map(course => (
!course.taken &&
<tr>
<td class="col-xs-10">
<h4>{course.search_name}</h4>
</td>
<td class="col-xs-2">
<h4><a onClick={(e) => {props.changeClass(course);}} className="changeButton" bsStyle="primary"> +</a></h4>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
export default Courses
|
import Fs from 'fs-extra'
export const coursesJsonPath = process.cwd() + '/courses.json'
export const saveFile = async (fileData, filePath = coursesJsonPath) => {
fileData = JSON.stringify(fileData, null, 4)
await Fs.writeFile(filePath, fileData)
}
|
import {Component} from "react";
import ReactDOM from "react-dom";
import {PageData} from "./util";
//活动组件
class List extends Component{
render(){
let data = this.props.data;
return (
<section>
<a href={data.linkWeixin}>
<img src={data.imgWeixin} />
</a>
<p>{`活动时间 ${data.beginDate} 到 ${data.endDate}`}</p>
</section>
);
}
}
//页面组件
class Page extends Component{
constructor(props){
super(props);
}
render(){
let lists = [],
data = this.props.data;
data.map((list, index) => {
lists.push(
<List data={list} index={index+1} ref={`activity${index + 1}`} key={index} />
);
});
return (
<body>
{lists}
</body>
);
}
}
const init = () => {
PageData.setData("/api/getactivity", data => {
ReactDOM.render(
<Page data={data.data} />,
document.body
);
}).render(init);
};
export {
init
} |
import React, {useEffect} from 'react';
//import {sampleData} from '../../../app/api/sampleData.js';
import {Grid} from 'semantic-ui-react';
import EventList from './EventList';
//import EventForm from '../eventForm/EventForm';
import { useDispatch, useSelector } from 'react-redux';
//import LoadingComponent from '../../../app/layout/LoadingComponent.jsx';
import EventListItemPlaceholder from './EventListItemPlaceholder';
import EventFilters from './EventFilters.jsx';
//import getEventsFromFirestore, { listenToEventsFromFirestore } from '../../../app/firestore/firestoreService.js';
import { listenToEvents } from '../eventActions.js';
//import { asyncActionError, asyncActionFinish, asyncActionStart } from '../../../app/async/asyncReducer.js';
import useFirestoreCollection from '../../../app/hooks/useFirestoreCollection.js';
import {listenToEventsFromFirestore } from '../../../app/firestore/firestoreService.js';
// array functions
const EventDashboard = ({formOpen,setFormOpen, selectEvent, selectedEvent}) => {
//const [events,setEvents] = useState(sampleData);
const dispatch = useDispatch();
const {events} = useSelector(state => state.event);
const {loading} = useSelector(state => state.async);
useFirestoreCollection({
query: () => listenToEventsFromFirestore(),
data: events => dispatch(listenToEvents(events)),
deps: [dispatch],
})
/*useEffect(()=>{
dispatch(asyncActionStart())
const unsubscribe = getEventsFromFirestore({
next: snapshot => {
dispatch(listenToEvents(snapshot.docs.map(docSnapshot => docSnapshot.data())));
dispatch(asyncActionFinish())
},
error: error => dispatch(asyncActionError(error)),
complete: () => console.log('you will never see this message')
})
return unsubscribe
},[dispatch])*/
/*function handleCreateEvent(event) {
setEvents([...events, event])
}*/
/*function handleUpdateEvent(updatedEvent) {
setEvents(events.map(evt => evt.id === updatedEvent.id ? updatedEvent : evt));
selectEvent(null);
setFormOpen(false);
}*/
function handleDeleteEvent(eventId) {
//setEvents(events.filter(evt => evt.id !== eventId));
}
return (
<Grid>
<Grid.Column width={10}>
{loading &&
<>
<EventListItemPlaceholder />
<EventListItemPlaceholder />
</>
}
<EventList events={events} selectEvent={selectEvent} deleteEvent={handleDeleteEvent} />
</Grid.Column>
<Grid.Column width={6}>
<EventFilters />
</Grid.Column>
</Grid>
)
}
export default EventDashboard; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.